|
| 1 | +import { createLogger } from '@sim/logger' |
| 2 | +import { toError } from '@sim/utils/errors' |
| 3 | +import JSZip from 'jszip' |
| 4 | +import type { NextRequest } from 'next/server' |
| 5 | +import { NextResponse } from 'next/server' |
| 6 | +import { fileExportContract } from '@/lib/api/contracts/storage-transfer' |
| 7 | +import { parseRequest } from '@/lib/api/server' |
| 8 | +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' |
| 9 | +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' |
| 10 | +import { USE_BLOB_STORAGE } from '@/lib/uploads/config' |
| 11 | +import { downloadFile } from '@/lib/uploads/core/storage-service' |
| 12 | +import { getFileMetadataById } from '@/lib/uploads/server/metadata' |
| 13 | +import { verifyFileAccess } from '@/app/api/files/authorization' |
| 14 | + |
| 15 | +const logger = createLogger('FilesExportAPI') |
| 16 | + |
| 17 | +const MARKDOWN_MIME_TYPES = new Set(['text/markdown', 'text/x-markdown']) |
| 18 | +const MARKDOWN_EXTENSIONS = new Set(['md', 'markdown']) |
| 19 | +const VIEW_URL_RE = |
| 20 | + /\/api\/files\/view\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/gi |
| 21 | + |
| 22 | +function isMarkdown(originalName: string, contentType: string): boolean { |
| 23 | + if (MARKDOWN_MIME_TYPES.has(contentType)) return true |
| 24 | + const ext = originalName.split('.').pop()?.toLowerCase() ?? '' |
| 25 | + return MARKDOWN_EXTENSIONS.has(ext) |
| 26 | +} |
| 27 | + |
| 28 | +export const GET = withRouteHandler( |
| 29 | + async (request: NextRequest, context: { params: Promise<{ id: string }> }) => { |
| 30 | + const parsed = await parseRequest(fileExportContract, request, context) |
| 31 | + if (!parsed.success) return parsed.response |
| 32 | + |
| 33 | + const { id } = parsed.data.params |
| 34 | + |
| 35 | + const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) |
| 36 | + if (!authResult.success || !authResult.userId) { |
| 37 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 38 | + } |
| 39 | + |
| 40 | + const record = await getFileMetadataById(id) |
| 41 | + if (!record) { |
| 42 | + logger.warn('File not found by ID', { id }) |
| 43 | + return NextResponse.json({ error: 'Not found' }, { status: 404 }) |
| 44 | + } |
| 45 | + |
| 46 | + const hasAccess = await verifyFileAccess(record.key, authResult.userId) |
| 47 | + if (!hasAccess) { |
| 48 | + logger.warn('Unauthorized file export attempt', { id, userId: authResult.userId }) |
| 49 | + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) |
| 50 | + } |
| 51 | + |
| 52 | + if (!isMarkdown(record.originalName, record.contentType)) { |
| 53 | + const storagePrefix = USE_BLOB_STORAGE ? 'blob' : 's3' |
| 54 | + const servePath = `/api/files/serve/${storagePrefix}/${encodeURIComponent(record.key)}` |
| 55 | + return NextResponse.redirect(new URL(servePath, request.url), { status: 302 }) |
| 56 | + } |
| 57 | + |
| 58 | + const mdBuffer = await downloadFile({ key: record.key, context: record.context as 'workspace' }) |
| 59 | + let mdContent = mdBuffer.toString('utf-8') |
| 60 | + |
| 61 | + const imageIds = [...new Set([...mdContent.matchAll(VIEW_URL_RE)].map((m) => m[1]))] |
| 62 | + logger.info('Exporting markdown with embedded images', { id, imageCount: imageIds.length }) |
| 63 | + |
| 64 | + const assetMap = new Map<string, { filename: string; buffer: Buffer }>() |
| 65 | + |
| 66 | + await Promise.allSettled( |
| 67 | + imageIds.map(async (imageId) => { |
| 68 | + try { |
| 69 | + const imgRecord = await getFileMetadataById(imageId) |
| 70 | + if (!imgRecord) return |
| 71 | + const imgHasAccess = await verifyFileAccess(imgRecord.key, authResult.userId) |
| 72 | + if (!imgHasAccess) return |
| 73 | + const imgBuffer = await downloadFile({ |
| 74 | + key: imgRecord.key, |
| 75 | + context: imgRecord.context as 'workspace', |
| 76 | + }) |
| 77 | + assetMap.set(imageId, { filename: imgRecord.originalName, buffer: imgBuffer }) |
| 78 | + } catch (err) { |
| 79 | + logger.warn('Failed to fetch asset for export', { imageId, error: toError(err).message }) |
| 80 | + } |
| 81 | + }) |
| 82 | + ) |
| 83 | + |
| 84 | + for (const [imageId, asset] of assetMap) { |
| 85 | + const escapedId = imageId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') |
| 86 | + mdContent = mdContent.replace( |
| 87 | + new RegExp(`/api/files/view/${escapedId}`, 'g'), |
| 88 | + `./assets/${asset.filename}` |
| 89 | + ) |
| 90 | + } |
| 91 | + |
| 92 | + const zip = new JSZip() |
| 93 | + zip.file(record.originalName, mdContent) |
| 94 | + const assets = zip.folder('assets')! |
| 95 | + for (const { filename, buffer } of assetMap.values()) { |
| 96 | + assets.file(filename, buffer) |
| 97 | + } |
| 98 | + |
| 99 | + const zipBuffer = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' }) |
| 100 | + const zipName = `${record.originalName.replace(/\.[^.]+$/, '')}.zip` |
| 101 | + |
| 102 | + return new NextResponse(zipBuffer, { |
| 103 | + status: 200, |
| 104 | + headers: { |
| 105 | + 'Content-Type': 'application/zip', |
| 106 | + 'Content-Disposition': `attachment; filename="${zipName}"`, |
| 107 | + 'Content-Length': String(zipBuffer.length), |
| 108 | + }, |
| 109 | + }) |
| 110 | + } |
| 111 | +) |
0 commit comments