You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

173 regels
5.7 KiB

  1. import { NextResponse } from 'next/server';
  2. import { writeFile, mkdir, rename, unlink } from 'fs/promises';
  3. import path from 'path';
  4. import { fromBuffer as fileTypeFromBuffer } from 'file-type';
  5. import { enqueueTranscode, needsTranscode, probeCodecs, isFfmpegAvailable } from '@/lib/transcode';
  6. import { UPLOAD_LIMITS } from '@/lib/config';
  7. export const dynamic = 'force-dynamic';
  8. export const maxDuration = 300;
  9. // Allowed extensions and their families (size + handling differ per family).
  10. type Family = 'image' | 'video' | 'pdf';
  11. const EXT_FAMILY: Record<string, Family> = {
  12. png: 'image', jpg: 'image', jpeg: 'image', gif: 'image', webp: 'image',
  13. mp4: 'video', m4v: 'video', webm: 'video', mov: 'video', ogv: 'video', ogg: 'video',
  14. pdf: 'pdf',
  15. };
  16. // Strict per family, permissive within a family (mov ↔ mp4 are both ISO BMFF).
  17. const ALLOWED_MIMES: Record<string, string[]> = {
  18. png: ['image/png'],
  19. jpg: ['image/jpeg'],
  20. jpeg: ['image/jpeg'],
  21. gif: ['image/gif'],
  22. webp: ['image/webp'],
  23. mp4: ['video/mp4', 'video/x-m4v', 'video/quicktime'],
  24. m4v: ['video/mp4', 'video/x-m4v'],
  25. webm: ['video/webm'],
  26. mov: ['video/quicktime', 'video/mp4'],
  27. ogv: ['video/ogg', 'application/ogg'],
  28. ogg: ['video/ogg', 'application/ogg', 'audio/ogg'],
  29. pdf: ['application/pdf'],
  30. };
  31. const MAX_BYTES: Record<Family, number> = UPLOAD_LIMITS;
  32. const UPLOAD_DIR = path.join(process.cwd(), 'data', 'uploads');
  33. const TMP_DIR = path.join(UPLOAD_DIR, '.tmp');
  34. function extractExt(name: string): string {
  35. const lastDot = name.lastIndexOf('.');
  36. if (lastDot < 0 || lastDot === name.length - 1) return '';
  37. return name.slice(lastDot + 1).toLowerCase();
  38. }
  39. export function normalizeFilename(originalName: string): string {
  40. const ext = extractExt(originalName);
  41. const safeExt = /^[a-z0-9]{1,5}$/.test(ext) ? ext : 'bin';
  42. const base = ext ? originalName.slice(0, originalName.length - ext.length - 1) : originalName;
  43. const slug = base
  44. .normalize('NFKD')
  45. .replace(/\p{Mn}/gu, '')
  46. .toLowerCase()
  47. .replace(/[\s/\\]+/g, '-')
  48. .replace(/[^a-z0-9_-]/g, '')
  49. .replace(/-+/g, '-')
  50. .replace(/^[-_]+|[-_]+$/g, '')
  51. .slice(0, 40) || 'file';
  52. const ts = Date.now().toString(36);
  53. const rand = Math.random().toString(36).slice(2, 8);
  54. return `${ts}-${rand}-${slug}.${safeExt}`;
  55. }
  56. export async function POST(request: Request) {
  57. let tmpPath: string | null = null;
  58. try {
  59. const formData = await request.formData();
  60. const file = formData.get('file') as File | null;
  61. if (!file) {
  62. return NextResponse.json({ error: 'No file received.' }, { status: 400 });
  63. }
  64. const ext = extractExt(file.name);
  65. const family = EXT_FAMILY[ext];
  66. if (!family) {
  67. return NextResponse.json(
  68. { error: `Estensione non permessa: .${ext || '(nessuna)'}` },
  69. { status: 400 }
  70. );
  71. }
  72. if (file.size > MAX_BYTES[family]) {
  73. const mb = (MAX_BYTES[family] / (1024 * 1024)).toFixed(0);
  74. return NextResponse.json(
  75. { error: `File troppo grande (max ${mb} MB per ${family}).` },
  76. { status: 413 }
  77. );
  78. }
  79. const buffer = Buffer.from(await file.arrayBuffer());
  80. // Magic-bytes sniffing: reject if the file content doesn't match its claimed extension.
  81. const detected = await fileTypeFromBuffer(buffer);
  82. if (!detected) {
  83. return NextResponse.json(
  84. { error: 'Tipo del file non riconoscibile dal contenuto.' },
  85. { status: 400 }
  86. );
  87. }
  88. const allowedMimes = ALLOWED_MIMES[ext] ?? [];
  89. if (!allowedMimes.includes(detected.mime)) {
  90. return NextResponse.json(
  91. { error: `Contenuto del file non corrisponde all'estensione (.${ext} dichiarato, rilevato ${detected.mime}).` },
  92. { status: 400 }
  93. );
  94. }
  95. const storedName = normalizeFilename(file.name);
  96. await mkdir(TMP_DIR, { recursive: true });
  97. tmpPath = path.join(TMP_DIR, storedName);
  98. await writeFile(tmpPath, buffer);
  99. // Image / PDF: rename atomically into the uploads dir and we're done.
  100. if (family !== 'video') {
  101. const finalPath = path.join(UPLOAD_DIR, storedName);
  102. await rename(tmpPath, finalPath);
  103. tmpPath = null;
  104. return NextResponse.json(
  105. { url: `/api/files?name=${encodeURIComponent(storedName)}` },
  106. { status: 201 }
  107. );
  108. }
  109. // Video: probe codecs. If already h264+aac/mp3 → fast path (rename).
  110. const codecs = await probeCodecs(tmpPath);
  111. if (!needsTranscode(codecs)) {
  112. const finalPath = path.join(UPLOAD_DIR, storedName);
  113. await rename(tmpPath, finalPath);
  114. tmpPath = null;
  115. return NextResponse.json(
  116. { url: `/api/files?name=${encodeURIComponent(storedName)}` },
  117. { status: 201 }
  118. );
  119. }
  120. // Needs transcoding: bail out early if ffmpeg is unavailable.
  121. if (!(await isFfmpegAvailable())) {
  122. return NextResponse.json(
  123. { error: 'Video richiede ricodifica ma ffmpeg non è disponibile sul server.' },
  124. { status: 503 }
  125. );
  126. }
  127. // The final file is always an .mp4 once transcoded — replace the extension.
  128. const finalMp4Name = storedName.replace(/\.[^.]+$/, '.mp4');
  129. const job = await enqueueTranscode({
  130. inputPath: tmpPath,
  131. outputName: finalMp4Name,
  132. originalUploadName: file.name,
  133. });
  134. // The input is now owned by the transcode worker; don't unlink in our catch.
  135. tmpPath = null;
  136. return NextResponse.json(
  137. {
  138. url: `/api/files?name=${encodeURIComponent(finalMp4Name)}`,
  139. transcoding: { jobId: job.id, status: job.status },
  140. },
  141. { status: 201 }
  142. );
  143. } catch (error) {
  144. console.error('Upload Error:', error);
  145. if (tmpPath) {
  146. try { await unlink(tmpPath); } catch {}
  147. }
  148. return NextResponse.json({ error: 'Failed to upload file.' }, { status: 500 });
  149. }
  150. }