|
| 1 | +/** |
| 2 | + * 课堂关键帧图片持久化 IPC + keyframe:// 自定义协议 |
| 3 | + * Classroom keyframe image persistence IPC handlers and custom |
| 4 | + * keyframe:// protocol for renderer-side image loading. |
| 5 | + * |
| 6 | + * @ai-context: 关键帧 JPEG 本地落盘到 {userData}/captures/{sessionId}/{keyframeId}.jpg, |
| 7 | + * 遵守本地优先原则(图片不上传)。渲染进程通过自定义 keyframe:// 协议加载: |
| 8 | + * 开发页面源为 http://localhost、生产为 file://,file:// 子资源会被 |
| 9 | + * webSecurity/CSP 拦截,故注册 standard+secure 专用协议(CSP img-src 已放行 keyframe:)。 |
| 10 | + * (Custom protocol is used because file:// subresources are blocked by |
| 11 | + * webSecurity/CSP under both dev http origin and prod file origin.) |
| 12 | + * @ai-context: sessionId/keyframeId 仅允许 UUID/安全字符(防路径穿越); |
| 13 | + * keyframe_cleanup 删除整个会话目录,由笔记删除路径调用(失败静默)。 |
| 14 | + */ |
| 15 | +import { app, net, protocol } from 'electron'; |
| 16 | +import * as path from 'path'; |
| 17 | +import { mkdir, rm, writeFile } from 'fs/promises'; |
| 18 | +import { pathToFileURL } from 'url'; |
| 19 | +import { safeHandle } from '../ipcUtils.js'; |
| 20 | +import { logger } from '../logger.js'; |
| 21 | + |
| 22 | +/** 自定义协议名与固定 host(keyframe://capture/{sessionId}/{keyframeId}.jpg) */ |
| 23 | +const KEYFRAME_SCHEME = 'keyframe'; |
| 24 | +const KEYFRAME_HOST = 'capture'; |
| 25 | + |
| 26 | +/** 安全 ID 校验:仅允许 UUID/字母数字/下划线/连字符,最长 64(防路径穿越) */ |
| 27 | +const SAFE_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; |
| 28 | + |
| 29 | +function isSafeId(id: unknown): id is string { |
| 30 | + return typeof id === 'string' && SAFE_ID_RE.test(id); |
| 31 | +} |
| 32 | + |
| 33 | +/** 关键帧图片根目录:{userData}/captures */ |
| 34 | +function capturesRoot(): string { |
| 35 | + return path.join(app.getPath('userData'), 'captures'); |
| 36 | +} |
| 37 | + |
| 38 | +/** |
| 39 | + * 注册 keyframe:// 为特权 scheme。 |
| 40 | + * 必须在 app ready 之前调用(main.ts 模块顶层)。 |
| 41 | + * (Must be called before app ready.) |
| 42 | + */ |
| 43 | +export function registerKeyframeScheme(): void { |
| 44 | + protocol.registerSchemesAsPrivileged([ |
| 45 | + { |
| 46 | + scheme: KEYFRAME_SCHEME, |
| 47 | + privileges: { standard: true, secure: true, supportFetchAPI: true, stream: true }, |
| 48 | + }, |
| 49 | + ]); |
| 50 | +} |
| 51 | + |
| 52 | +/** |
| 53 | + * 注册 keyframe:// 协议 handler 与 keyframe_save / keyframe_cleanup IPC。 |
| 54 | + * app ready 后调用一次(main.ts whenReady 中)。 |
| 55 | + */ |
| 56 | +export function registerKeyframeIpcHandlers(): void { |
| 57 | + // ---- keyframe:// 协议:映射到本地 captures 目录(只读) ---- |
| 58 | + if (protocol.isProtocolHandled(KEYFRAME_SCHEME)) { |
| 59 | + protocol.unhandle(KEYFRAME_SCHEME); |
| 60 | + } |
| 61 | + protocol.handle(KEYFRAME_SCHEME, async (request) => { |
| 62 | + try { |
| 63 | + const url = new URL(request.url); |
| 64 | + const [sessionId, fileName] = url.pathname.replace(/^\//, '').split('/'); |
| 65 | + const keyframeId = fileName?.endsWith('.jpg') ? fileName.slice(0, -4) : undefined; |
| 66 | + if (url.hostname !== KEYFRAME_HOST || !isSafeId(sessionId) || !isSafeId(keyframeId)) { |
| 67 | + return new Response('Bad Request', { status: 400 }); |
| 68 | + } |
| 69 | + const filePath = path.join(capturesRoot(), sessionId, `${keyframeId}.jpg`); |
| 70 | + return await net.fetch(pathToFileURL(filePath).toString()); |
| 71 | + } catch (err) { |
| 72 | + logger.warn(`[Keyframe] Protocol request failed: ${String(err)}`); |
| 73 | + return new Response('Not Found', { status: 404 }); |
| 74 | + } |
| 75 | + }); |
| 76 | + |
| 77 | + // ---- 保存关键帧 JPEG(返回可渲染 URL)---- |
| 78 | + safeHandle( |
| 79 | + 'keyframe_save', |
| 80 | + async (_event, args: { sessionId: string; keyframeId: string; imageBase64: string }) => { |
| 81 | + const { sessionId, keyframeId, imageBase64 } = args ?? {}; |
| 82 | + if (!isSafeId(sessionId) || !isSafeId(keyframeId)) { |
| 83 | + throw new Error('非法的 sessionId/keyframeId'); |
| 84 | + } |
| 85 | + if (typeof imageBase64 !== 'string' || imageBase64.length === 0) { |
| 86 | + throw new Error('imageBase64 不能为空'); |
| 87 | + } |
| 88 | + // 容忍 data URL 前缀(tolerate optional data URL prefix) |
| 89 | + const commaIdx = imageBase64.indexOf(','); |
| 90 | + const rawBase64 = imageBase64.startsWith('data:') && commaIdx >= 0 |
| 91 | + ? imageBase64.slice(commaIdx + 1) |
| 92 | + : imageBase64; |
| 93 | + |
| 94 | + const dir = path.join(capturesRoot(), sessionId); |
| 95 | + await mkdir(dir, { recursive: true }); |
| 96 | + await writeFile(path.join(dir, `${keyframeId}.jpg`), Buffer.from(rawBase64, 'base64')); |
| 97 | + return { |
| 98 | + success: true, |
| 99 | + url: `${KEYFRAME_SCHEME}://${KEYFRAME_HOST}/${sessionId}/${keyframeId}.jpg`, |
| 100 | + }; |
| 101 | + }, |
| 102 | + ); |
| 103 | + |
| 104 | + // ---- 清理会话目录(笔记删除时调用,失败由调用方静默处理)---- |
| 105 | + safeHandle('keyframe_cleanup', async (_event, args: { sessionId: string }) => { |
| 106 | + const sessionId = args?.sessionId; |
| 107 | + if (!isSafeId(sessionId)) { |
| 108 | + throw new Error('非法的 sessionId'); |
| 109 | + } |
| 110 | + await rm(path.join(capturesRoot(), sessionId), { recursive: true, force: true }); |
| 111 | + return { success: true }; |
| 112 | + }); |
| 113 | +} |
0 commit comments