Files
upload-gltf/app/api/upload/drive/route.ts
T
Tom Boullay 78f4aa83e0 refactor: full codebase audit — extract modules, fix type safety, clean dead code
- Extract API helpers from UploadZone into lib/upload-api.ts (FormData builder, checkFolderDiffs, uploadDrive, uploadGit)
- Extract upload orchestration into hooks/useUploadOrchestrator.ts (UploadZone: 489 → 162 lines)
- Extract file diff classification into lib/diff-files.ts (from git route)
- Extract shared SVG icons into components/ui/icons.tsx (7 icons, 0 duplication)
- Extract shared modal wrapper into components/ui/Modal.tsx + ModalActions
- Extract DriveStatusLine sub-component from FolderCard
- Fix checkFolderDiffs silently swallowing auth/network errors (now throws)
- Fix type safety: remove as never casts, add isHttpError type guard, use discriminated union for validateFolder
- Fix nextcloud: cache getConfig, add max bound to findNextVersion, optimize mkdirRecursive (skip PROPFIND)
- Fix drive route: remove req.clone(), extend parseMultiUpload to return extra fields
- Fix commit message: model shown as unchanged with ↔️ on updates (not falsely marked as modified)
- Clean dead code: unused folderExists import, FileStatus/DriveStatus exports, ParsedFile.textureName, getConfig basePath
- Add security headers in next.config.ts (HSTS, X-Content-Type-Options, X-Frame-Options, etc.)
- Update README with new project structure
2026-04-14 17:19:10 +02:00

100 lines
3.2 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { validateUploadSecret } from '@/lib/auth'
import { parseMultiUpload } from '@/lib/parse-upload'
import {
mkdirRecursive,
moveFolder,
uploadFile,
findNextVersion,
} from '@/lib/nextcloud'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
// ---------------------------------------------------------------------------
// POST /api/upload/drive
//
// Upload **original** files (no Blender compression) to Nextcloud Drive.
//
// FormData fields:
// - folderName, destination, files[], fileTypes[], textureNames[] (same as /api/upload/git)
// - action: "new" | "replace"
//
// Versioning logic:
// VF/{folderName} <- latest version
// V1/{folderName} <- first archive, V2/ second, etc.
//
// action="new" -> just mkdir + upload into VF/
// action="replace" -> archive VF -> Vx, then re-upload all files into VF/
// ---------------------------------------------------------------------------
export async function POST(req: NextRequest) {
// --- Auth ---
const authError = validateUploadSecret(req)
if (authError) return authError
// --- Check Nextcloud config ---
if (!process.env.NEXTCLOUD_URL || !process.env.NEXTCLOUD_SHARE_TOKEN) {
return NextResponse.json(
{ success: false, error: 'Nextcloud non configure sur le serveur (NEXTCLOUD_URL, NEXTCLOUD_SHARE_TOKEN)' },
{ status: 500 },
)
}
// --- Parse files (includes extra fields like "action") ---
let folderName: string
let parsedFiles: Awaited<ReturnType<typeof parseMultiUpload>>['files']
let action: string
try {
const parsed = await parseMultiUpload(req)
folderName = parsed.folderName
parsedFiles = parsed.files
action = parsed.extra.action?.trim() || 'new'
} catch (err) {
const message = err instanceof Error ? err.message : 'Erreur inconnue'
return NextResponse.json({ success: false, error: message }, { status: 400 })
}
const basePath = process.env.NEXTCLOUD_BASE_PATH || 'Models'
const vfFolderPath = `${basePath}/VF/${folderName}`
try {
if (action === 'replace') {
// 1. Find the next available Vx
const nextVersion = await findNextVersion(basePath, folderName)
// 2. Ensure Vx/ exists
await mkdirRecursive(`${basePath}/${nextVersion}`)
// 3. Move VF/{folderName} -> Vx/{folderName}
await moveFolder(vfFolderPath, `${basePath}/${nextVersion}/${folderName}`)
// 4. Re-create VF/{folderName}
await mkdirRecursive(vfFolderPath)
} else {
// action === 'new': just ensure VF/{folderName} exists
await mkdirRecursive(vfFolderPath)
}
// --- Upload all original files ---
for (const pf of parsedFiles) {
const remotePath = `${vfFolderPath}/${pf.filename}`
await uploadFile(remotePath, pf.buffer)
}
return NextResponse.json({
success: true,
folderName,
filesCount: parsedFiles.length,
message: `${parsedFiles.length} fichier(s) envoye(s) sur le Drive.`,
})
} catch (err) {
const message = err instanceof Error ? err.message : 'Erreur Nextcloud inconnue'
return NextResponse.json(
{ success: false, error: `Drive echoue: ${message}` },
{ status: 500 },
)
}
}