import { open } from 'fs/promises' import { Readable } from 'stream' import type { Session } from 'next-auth' import { authorizePerformanceSurveyAttachment, PerformanceSurveyApiError } from './performance-survey-service' import { performanceAttachmentPath } from './performance-survey-attachment-storage' import { serializePerformanceCaseAttachments } from './performance-survey-attachment-contract' import { prisma } from './prisma' export function parsePerformanceAttachmentRange(range: string, size: number): { start: number; end: number } | null { const match = /^bytes=(\d*)-(\d*)$/.exec(range) if (!match || (!match[1] && !match[2])) return null const start = match[1] ? Number(match[1]) : Math.max(0, size - Number(match[2])) let end = match[1] && match[2] ? Number(match[2]) : size - 1 if (!match[1] && Number(match[2]) === 0) return null end = Math.min(end, size - 1) return Number.isSafeInteger(start) && Number.isSafeInteger(end) && start >= 0 && start <= end && start < size ? { start, end } : null } export async function performanceAttachmentMetadata(session: Session | null, id: string) { return serializePerformanceCaseAttachments([await authorizePerformanceSurveyAttachment(session, id)])[0] } export async function retryPerformanceAttachment(session: Session | null, id: string) { const attachment = await authorizePerformanceSurveyAttachment(session, id) if (attachment.status === 'failed') { await prisma.performanceSurveyAttachment.updateMany({ where: { id, status: 'failed' }, data: { status: 'queued', error: null, attempts: 0, leaseToken: null, leaseExpiresAt: null } }) const { ensurePerformanceAttachmentWorkerStarted } = await import('./performance-survey-attachment-worker') ensurePerformanceAttachmentWorkerStarted() } return performanceAttachmentMetadata(session, id) } export async function performanceAttachmentFile(session: Session | null, id: string, request: Request) { const attachment = await authorizePerformanceSurveyAttachment(session, id) const url = new URL(request.url) const variant = url.searchParams.get('variant') || 'original' let relative: string let mime: string if (variant === 'original') { relative = `original.${attachment.extension}` mime = attachment.mimeType } else { if (attachment.status !== 'ready' || !attachment.previewKey || !/^attempt-[0-9a-f-]{36}$/.test(attachment.previewKey)) throw new PerformanceSurveyApiError('预览尚未就绪', 409) if (variant === 'video' && attachment.kind === 'video') { relative = `${attachment.previewKey}/playback.mp4` mime = 'video/mp4' } else if (variant === 'page' && attachment.kind === 'document') { const page = Number(url.searchParams.get('page')) if (!Number.isSafeInteger(page) || page < 1 || page > (attachment.previewPageCount || 0)) throw new PerformanceSurveyApiError('预览页码无效', 400) relative = `${attachment.previewKey}/${page}.jpg` mime = 'image/jpeg' } else throw new PerformanceSurveyApiError('预览类型无效', 400) } const file = await performanceAttachmentPath(id, relative) let handle try { handle = await open(file, 'r') } catch { throw new PerformanceSurveyApiError('附件文件暂不可用,请稍后重试', 503) } const { size } = await handle.stat() const headers = new Headers({ 'Content-Type': mime, 'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff', 'Accept-Ranges': 'bytes', 'Vary': 'Cookie, Authorization', 'Cross-Origin-Resource-Policy': 'same-origin' }) if (variant === 'original') headers.set('Content-Disposition', `attachment; filename="case.${attachment.extension}"; filename*=UTF-8''${encodeURIComponent(attachment.originalName).replace(/['()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`)}`) const rangeHeader = request.headers.get('range') const range = rangeHeader ? parsePerformanceAttachmentRange(rangeHeader, size) : { start: 0, end: size - 1 } if (!range) { await handle.close() headers.set('Content-Range', `bytes */${size}`) return new Response(null, { status: 416, headers }) } headers.set('Content-Length', String(range.end - range.start + 1)) if (rangeHeader) headers.set('Content-Range', `bytes ${range.start}-${range.end}/${size}`) if (request.method === 'HEAD') { await handle.close() return new Response(null, { headers, status: rangeHeader ? 206 : 200 }) } const stream = handle.createReadStream({ start: range.start, end: range.end }) const cancel = () => stream.destroy() request.signal.addEventListener('abort', cancel, { once: true }) stream.once('close', () => request.signal.removeEventListener('abort', cancel)) return new Response(Readable.toWeb(stream) as ReadableStream, { headers, status: rangeHeader ? 206 : 200 }) }