import { link, mkdir, mkdtemp, rm, unlink } from 'node:fs/promises' import { extname, join } from 'node:path' import { createError } from 'h3' import { buildDefaultUploadSizeLimits, formatUploadSizeLimit, getMaxUploadBytesForKind, getUploadKind, getUploadKindLabel, normalizeUploadMaxFileCount, normalizeUploadMaxTotalSize } from '../../../../lib/upload-size-limit.js' import { requireAdminSession } from '../../../utils/admin-auth' import { getRuntimeEnvNumber } from '../../../utils/runtime-env.js' import { upsertMediaMetadataCategory } from '../../../utils/media-library' import { deleteMediaCatalogEntries } from '../../../repositories/media-catalog-repository' import { saveMultipartFilesToDisk } from '../../../utils/multipart-file-upload' import { getConfiguredUploadRoot } from '../../../utils/upload-root' import { getSiteSettings } from '../../../repositories/content-repository' const allowedUploadTypes = new Map([ ['image/jpeg', '.jpg'], ['image/png', '.png'], ['image/webp', '.webp'], ['image/gif', '.gif'], ['video/mp4', '.mp4'], ['video/webm', '.webm'], ['video/quicktime', '.mov'], ['audio/mpeg', '.mp3'], ['audio/wav', '.wav'], ['audio/ogg', '.ogg'], ['audio/mp4', '.m4a'], ['application/pdf', '.pdf'], ['application/zip', '.zip'], ['text/plain', '.txt'], ['text/csv', '.csv'], ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', '.docx'], ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '.xlsx'], ['application/vnd.openxmlformats-officedocument.presentationml.presentation', '.pptx'] ]) const allowedUploadExtensions = new Set([ '.jpg', '.jpeg', '.png', '.webp', '.gif', '.mp4', '.webm', '.mov', '.mp3', '.wav', '.ogg', '.m4a', '.pdf', '.zip', '.txt', '.csv', '.docx', '.xlsx', '.pptx' ]) /** * 업로드 경로 조각을 URL 안전 문자열로 정리 * @param {string} value - 원본 경로 조각 * @returns {string} 정리된 경로 조각 */ const sanitizePathPart = (value) => String(value || '') .normalize('NFC') .replace(/[^\p{L}\p{N}._-]+/gu, '-') .replace(/-+/g, '-') .replace(/^\.+|\.+$/g, '') .replace(/^-|-$/g, '') /** * 파일 확장자 조회 * @param {{ filename: string, type: string }} file - multipart 파일 정보 * @returns {string} 확장자 */ const getUploadExtension = (file) => { const extension = extname(file.filename || '').toLowerCase() if (allowedUploadTypes.has(file.type)) { return allowedUploadTypes.get(file.type) } return extension } /** * 업로드 허용 파일인지 확인한다. * @param {{ filename: string, type: string }} file - multipart 파일 정보 * @returns {boolean} 허용 여부 */ const isAllowedUploadFile = (file) => allowedUploadTypes.has(file.type) || allowedUploadExtensions.has(extname(file.filename || '').toLowerCase()) /** * 임시 파일을 충돌하지 않는 최종 파일명으로 원자적으로 이동한다. * @param {string} directoryPath - 저장 디렉터리 절대 경로 * @param {string} stem - 확장자 제외 파일명 * @param {string} extension - 확장자(점 포함, 예: `.png`) * @param {string} sourcePath - 임시 파일 절대 경로 * @returns {Promise<{ fileName: string, filePath: string }>} 선택된 파일명과 절대 경로 */ const moveToUniqueDiskFileName = async (directoryPath, stem, extension, sourcePath) => { let suffix = 1 while (suffix < 10000) { const fileName = suffix === 1 ? `${stem}${extension}` : `${stem}-${suffix}${extension}` const filePath = join(directoryPath, fileName) try { await link(sourcePath, filePath) await unlink(sourcePath) return { fileName, filePath } } catch (error) { if (error?.code !== 'EEXIST') { throw error } suffix += 1 } } throw createError({ statusCode: 500, message: '저장할 고유 파일명을 만들 수 없습니다.' }) } /** * 관리자 미디어 업로드 API * @param {import('h3').H3Event} event - 요청 이벤트 * @returns {Promise<{ files: Array<{ url: string, name: string, size: number }> }>} 업로드 결과 */ export default defineEventHandler(async (event) => { requireAdminSession(event) const config = useRuntimeConfig() const uploadSizeLimits = buildDefaultUploadSizeLimits({ image: getRuntimeEnvNumber('MAX_FILE_SIZE', 'maxFileSize', 10485760), video: getRuntimeEnvNumber('MAX_VIDEO_FILE_SIZE', 'maxVideoFileSize', 209715200), audio: getRuntimeEnvNumber('MAX_AUDIO_FILE_SIZE', 'maxAudioFileSize', 52428800), document: getRuntimeEnvNumber('MAX_DOCUMENT_FILE_SIZE', 'maxDocumentFileSize', 52428800) }) const settings = await getSiteSettings() const uploadMaxFileCount = normalizeUploadMaxFileCount(settings.uploadMaxFileCount) const uploadMaxTotalSize = normalizeUploadMaxTotalSize(settings.uploadMaxTotalSize) const now = new Date() const year = String(now.getFullYear()) const month = String(now.getMonth() + 1).padStart(2, '0') const uploadBaseUrl = String(config.uploadDir || '/uploads').replace(/\/+$/g, '') || '/uploads' const publicBasePath = uploadBaseUrl.replace(/^\/+/, '') const directoryPath = join(getConfiguredUploadRoot(publicBasePath), 'posts', year, month) await mkdir(directoryPath, { recursive: true }) const tempDirectoryPath = await mkdtemp(join(directoryPath, '.upload-')) const movedFilePaths = [] const catalogRecordedUrls = [] try { const streamedFiles = await saveMultipartFilesToDisk(event, { fieldName: 'files', maxFiles: uploadMaxFileCount, maxTotalBytes: uploadMaxTotalSize, createFileTarget: async (file, index) => { const uploadFile = { filename: file.filename, type: file.mimeType } if (!isAllowedUploadFile(uploadFile)) { throw createError({ statusCode: 400, message: '지원하지 않는 파일 형식입니다.' }) } const uploadKind = getUploadKind(uploadFile.type, uploadFile.filename) const maxFileSize = getMaxUploadBytesForKind(uploadKind, uploadSizeLimits) const originalStem = sanitizePathPart(uploadFile.filename.replace(/\.[^.]+$/g, '')) || 'file' const extension = getUploadExtension(uploadFile) return { filePath: join(tempDirectoryPath, `${index}${extension}`), maxBytes: maxFileSize, metadata: { originalStem, extension, uploadKind } } } }) const uploadedFiles = [] for (const file of streamedFiles) { const { fileName, filePath } = await moveToUniqueDiskFileName( directoryPath, file.metadata.originalStem, file.metadata.extension, file.filePath ) movedFilePaths.push(filePath) const publicUrl = `${uploadBaseUrl}/posts/${year}/${month}/${fileName}` await upsertMediaMetadataCategory(publicUrl, '미분류') catalogRecordedUrls.push(publicUrl) uploadedFiles.push({ url: publicUrl, name: fileName, size: file.size }) } return { files: uploadedFiles } } catch (error) { await Promise.all(movedFilePaths.map((filePath) => unlink(filePath).catch(() => {}))) await deleteMediaCatalogEntries(catalogRecordedUrls).catch(() => { console.warn('[media-catalog] 업로드 실패 정리 중 카탈로그 갱신 실패') }) if (error?.statusCode) { throw error } if (error?.code === 'MULTIPART_TOO_MANY_FILES') { throw createError({ statusCode: 413, message: `한 번에 업로드할 수 있는 파일은 최대 ${uploadMaxFileCount}개입니다.` }) } if (error?.code === 'MULTIPART_TOTAL_SIZE_TOO_LARGE') { throw createError({ statusCode: 413, message: `한 번에 업로드 가능한 전체 용량을 초과했습니다. (최대 ${formatUploadSizeLimit(uploadMaxTotalSize)})` }) } if (error?.code === 'MULTIPART_FILE_TOO_LARGE') { throw createError({ statusCode: 413, message: `${getUploadKindLabel(error.metadata?.uploadKind)} 업로드 가능 크기를 초과했습니다. (최대 ${formatUploadSizeLimit(error.maxBytes)})` }) } if (['MULTIPART_FILE_NOT_FOUND', 'INVALID_MULTIPART_REQUEST', 'MULTIPART_TOO_MANY_PARTS'].includes(error?.code)) { throw createError({ statusCode: 400, message: '업로드할 파일이 없거나 요청 형식이 올바르지 않습니다.' }) } throw createError({ statusCode: 500, message: '파일을 업로드하지 못했습니다.' }) } finally { await rm(tempDirectoryPath, { recursive: true, force: true }) } })