Files
crawler-plugin/frontend-vue/src/shared/bridges/web-fallback.ts
T
huangzd1997 0390788f2b perf(代码审查落地): 后端 A1-A8 与前端 C1-C8 加固,retention 清理补索引(V141)
A 组(backend-java):
- A1 载荷引用计数不再无条件回落全表 COUNT
- A2 结果行读取由 LIMIT 1 改整页
- A3 ziniao 索引缓存过期判断下推 SQL
- A4 循环子任务认领改 CAS,失败一律抛
- A5 建单事务里不碰外部 IO
- A6 连接池补网络层超时(connectTimeout/socketTimeout,env 可覆盖)
- A7 日志留现场 + 异步落盘
- A8 其余:货源图片预取、结果工作簿装配等
- V141:三条 retention DELETE 的可用索引,其中 biz_price_track_loop_run
  用 STORED 生成列承载 COALESCE 时间线(该表实测 881 行/17MB,COPY 秒级)

C 组(frontend-vue):URL 取值走 safe-url、行号取值走 row-id、
交付视频任务状态抽成 delivery-video-task-state.ts,各补用例。
2026-10-03 12:24:16 +08:00

277 lines
11 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.
/**
* Web 浏览器降级桥
*
* 桌面客户端(pywebview)环境下 window.pywebview.api 提供文件对话框、任务队列、本地存档等能力;
* 前端 Web 独立部署后页面运行在纯浏览器中,没有该桥。
* 本模块用浏览器原生能力模拟其中"可全链路完成"的方法(文件选择 → 上传 Java / 模板下载 / 配置存取),
* 其余方法保持 undefined,让页面代码走既有的"请在本地客户端中打开"降级分支。
*/
import type { DesktopConfig, DesktopConfigUpdate, PywebviewApi } from './pywebview'
import { extractErrorMessage, http } from '@/shared/api/http'
/**
* 虚拟路径 → 浏览器 File 对象(虚拟路径仅存活于当前页面会话,刷新即失效)
*
* 桌面 WebView 常驻不刷新,整份 Excel File(数 MB)会一直被 Map 持有,所以这里做双重有界化:
* 1. 上传成功即 delete(文件已进服务端,页面后续只用返回的 fileKey,不再需要本地 File);
* 2. 只选不传(用户放弃提交)的条目按 FIFO 淘汰,容量上限见 MAX_TRACKED_WEB_FILES。
*/
const webFileMap = new Map<string, File>()
let webFileSeq = 0
const MAX_TRACKED_WEB_FILES = 8
/** 放入新的 File 前先按 FIFO 淘汰最旧条目,保证 Map 不会随选文件次数无界增长。 */
function rememberWebFile(id: string, file: File) {
while (webFileMap.size >= MAX_TRACKED_WEB_FILES) {
const oldest = webFileMap.keys().next()
if (oldest.done) break
webFileMap.delete(oldest.value)
}
webFileMap.set(id, file)
}
const CONFIG_STORAGE_KEY = 'web_desktop_config'
/**
* 敏感配置字段(口令/密钥类)判定:沿用 bridges/pywebview.ts 中 DesktopConfig /
* DesktopConfigUpdate 已声明的字段命名(aliprice_pwd 这类 *_pwd 口令后缀),
* 再覆盖同族写法 passwd/password 与密钥/令牌(secret/token/api_key)。
*
* 不含用户名(aliprice_usename)与代理地址(proxy_url):页面要用它们做回填与展示,
* 收紧这两类字段会改变既有可见行为。
*/
const SENSITIVE_CONFIG_KEY_RE = /(?:^|[_-])(?:pwd|passwd|password|secret|token|api[_-]?key)$/i
function isSensitiveConfigKey(key: string) {
return SENSITIVE_CONFIG_KEY_RE.test(key)
}
/**
* 敏感字段在本会话内的内存副本:浏览器形态不落 localStorage(同页 XSS / 共用机器读不到明文),
* 但 read_config 仍能取回刚保存的值,页面「保存 → 回显 → 提交」链路行为不变。
* 桌面形态(pywebview)走原生桥的 app.json,代码根本不经过本文件。
*/
const webMemoryConfig: Record<string, unknown> = {}
/** 读磁盘原始副本(不含内存值) */
function readDiskConfig(): DesktopConfig {
try {
const raw = window.localStorage.getItem(CONFIG_STORAGE_KEY) || ''
if (!raw) return {}
const parsed = JSON.parse(raw) as DesktopConfig
// 历史版本把口令明文写进过 localStorage:读到时一并丢弃
const out: Record<string, unknown> = {}
for (const [key, value] of Object.entries(parsed || {})) {
if (isSensitiveConfigKey(key)) continue
out[key] = value
}
return out as DesktopConfig
} catch {
return {}
}
}
let storedSensitivePurged = false
/** 首次读写时把磁盘上已有的敏感字段抹掉一次(之后写入路径不再产生敏感字段) */
function purgeStoredSensitiveOnce() {
if (storedSensitivePurged || typeof window === 'undefined') return
storedSensitivePurged = true
try {
const raw = window.localStorage.getItem(CONFIG_STORAGE_KEY) || ''
if (!raw) return
const parsed = JSON.parse(raw) as Record<string, unknown>
if (!Object.keys(parsed || {}).some(isSensitiveConfigKey)) return
const cleaned: Record<string, unknown> = {}
for (const [key, value] of Object.entries(parsed)) {
if (isSensitiveConfigKey(key)) continue
cleaned[key] = value
}
window.localStorage.setItem(CONFIG_STORAGE_KEY, JSON.stringify(cleaned))
} catch {
/* 清理失败不阻断主流程:读取侧同样会丢弃敏感字段 */
}
}
function readStoredConfig(): DesktopConfig {
purgeStoredSensitiveOnce()
return { ...readDiskConfig(), ...webMemoryConfig } as DesktopConfig
}
function writeStoredConfig(data: DesktopConfigUpdate): DesktopConfig {
purgeStoredSensitiveOnce()
const persistable: Record<string, unknown> = {}
for (const [key, value] of Object.entries(data || {})) {
if (isSensitiveConfigKey(key)) {
// 口令/密钥类:只进内存,绝不落盘
webMemoryConfig[key] = value
continue
}
persistable[key] = value
}
const persisted: DesktopConfig = { ...readDiskConfig(), ...persistable } as DesktopConfig
try {
window.localStorage.setItem(CONFIG_STORAGE_KEY, JSON.stringify(persisted))
} catch {
/* 本地存储异常时忽略:配置读取仍是空对象 */
}
// 返回结构与桌面桥一致(含本次保存的敏感字段),页面按原样使用
return { ...persisted, ...webMemoryConfig } as DesktopConfig
}
/** 文件选择框挂起兜底超时:旧内核取消时不触发 cancel 事件,Promise 会永远挂起 */
const FILE_PICK_TIMEOUT_MS = 10 * 60 * 1000
/** 打开浏览器文件选择框;用户取消/超时都返回空数组(不阻塞后续选择) */
function pickBrowserFiles(accept = '', multiple = false): Promise<File[]> {
return new Promise((resolve) => {
const input = document.createElement('input')
input.type = 'file'
input.accept = accept
input.multiple = multiple
input.style.display = 'none'
document.body.appendChild(input)
let settled = false
// 统一 cleanup:无论 change / cancel / 超时,都摘掉临时 DOM 节点并清掉计时器
// (此前取消路径只 remove 一次,挂起路径上 DOM 节点永不摘除)
const cleanup = () => {
if (settled) return
settled = true
window.clearTimeout(guardTimer)
input.remove()
}
const guardTimer = window.setTimeout(() => {
cleanup()
resolve([])
}, FILE_PICK_TIMEOUT_MS)
input.addEventListener('cancel', () => {
// 现代浏览器支持 file input 的 cancel 事件;旧浏览器取消时不触发,由上面的超时兜底
cleanup()
resolve([])
})
input.onchange = () => {
const files = Array.from(input.files || [])
cleanup()
resolve(files)
}
input.click()
})
}
/**
* 把浏览器 File 注册为虚拟路径(形如 web-file:<序号>/<文件名>)。
* 虚拟路径满足页面既有的文件名规整逻辑(baseName 按 / 切分、.xlsx 后缀校验)。
*/
function registerWebFiles(files: File[]): string[] {
return files.map((file) => {
const id = `web-file:${++webFileSeq}/${file.name}`
rememberWebFile(id, file)
return id
})
}
/** 扩展名过滤('xlsx,xls,csv')转 input accept('.xlsx,.xls,.csv') */
function buildAccept(extensions?: string): string {
return (extensions || '')
.split(',')
.map((item) => item.trim())
.filter(Boolean)
.map((ext) => (ext.startsWith('.') ? ext : `.${ext}`))
.join(',')
}
/** 触发浏览器下载(a[download]) */
function triggerAnchorDownload(url: string, filename: string) {
const link = document.createElement('a')
link.href = url
link.download = filename
link.style.display = 'none'
document.body.appendChild(link)
link.click()
link.remove()
}
/** 模板文件下载:先 HEAD 预检(含 content-type 防 SPA/vite 回退 HTML),文件不存在时返回失败而非静默 404 */
async function downloadTemplateFile(path: string, filename: string) {
try {
const resp = await window.fetch(path, { method: 'HEAD' })
const contentType = resp.headers.get('content-type') || ''
if (!resp.ok || contentType.includes('text/html')) {
return { success: false, error: `模板文件不存在(HTTP ${resp.status})` }
}
} catch {
return { success: false, error: '模板文件不可访问' }
}
triggerAnchorDownload(path, filename)
return { success: true, path: filename }
}
/** 浏览器环境下的桥降级实现:只提供浏览器可全链路完成的方法 */
export const webFallbackApi: PywebviewApi = {
/** 选择文件(Excel/CSV 等),返回虚拟路径列表 */
async select_files(options) {
const accept = buildAccept(options?.filters?.[0]?.extensions)
const files = await pickBrowserFiles(accept, options?.multiple !== false)
if (!files.length) return null
return { paths: registerWebFiles(files) }
},
/** 选择品牌 xlsx 文件(多选) */
async select_brand_xlsx_files() {
const files = await pickBrowserFiles('.xlsx', true)
return registerWebFiles(files)
},
/** 虚拟路径 → 浏览器 File → 上传 Java;uploadOss=true 时同时上传公开 OSS(品牌检测等服务端化工具用) */
async upload_file_to_java(filePath, relativePath, uploadOss) {
const file = typeof filePath === 'string' ? webFileMap.get(filePath) : undefined
if (!file) {
return { success: false, error: '文件不存在,请重新选择' }
}
const form = new FormData()
form.append('file', file, file.name)
if (relativePath) {
form.append('relativePath', relativePath)
}
if (uploadOss) {
form.append('uploadToOss', 'true')
form.append('moduleType', 'BRAND')
}
try {
// http 实例对 /newApi 前缀自动附带 Bearer;FormData 的 Content-Type 交由浏览器自动生成(含 boundary)
const response = await http.post('/newApi/api/files/upload', form, { timeout: 120000 })
// 消费完即释放:文件已落到服务端,页面后续只用返回的 fileKey/url,不再需要这份本地 File。
// 失败分支保留条目,让用户能在不重新选文件的情况下重试(超量时由 rememberWebFile 的 FIFO 淘汰兜底)。
if (response.data?.success) {
webFileMap.delete(filePath)
}
return response.data
} catch (error) {
return { success: false, error: extractErrorMessage(error) }
}
},
/** 品牌文档模板(xlsx)直接浏览器下载 */
async save_template_xlsx() {
const name = '品牌文档格式_模板.xlsx'
return downloadTemplateFile(`/static/${encodeURIComponent(name)}`, name)
},
/** 文件夹方式上传模板(zip)直接浏览器下载 */
async save_template_zip() {
const name = '模板2-以文件夹方式上传.zip'
return downloadTemplateFile(`/static/${encodeURIComponent(name)}`, name)
},
/** 代理等桌面配置降级:非敏感字段落 localStorage,口令/密钥类只存内存(见 writeStoredConfig) */
async read_config() {
return readStoredConfig()
},
/** 浏览器形态的桌面配置写入:敏感字段拒绝持久化,仅保留在会话内存中 */
async save_config(data) {
return writeStoredConfig(data)
},
}