diff --git a/app/api/upload/route.ts b/app/api/upload/route.ts index a0b2b02..beb18ec 100644 --- a/app/api/upload/route.ts +++ b/app/api/upload/route.ts @@ -1,23 +1,17 @@ import { NextRequest, NextResponse } from 'next/server' -import { writeFileSync, mkdirSync } from 'fs' +import { writeFileSync, mkdirSync, existsSync, rmSync } from 'fs' import { join, extname, basename } from 'path' import { execSync } from 'child_process' -// Forcer le runtime Node.js (nécessaire pour fs, child_process) export const runtime = 'nodejs' export const dynamic = 'force-dynamic' -// Formats autorisés par type -const MODEL_EXTENSIONS = new Set(['.glb', '.gltf', '.fbx']) -const TEXTURE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.ktx2']) +const MODEL_EXTENSIONS = new Set(['.glb', '.gltf']) +const TEXTURE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp']) const ALL_ALLOWED_EXTENSIONS = new Set([...MODEL_EXTENSIONS, ...TEXTURE_EXTENSIONS]) -const MODELS_DIR = join(process.cwd(), 'public', 'models') -const TEXTURES_DIR = join(process.cwd(), 'public', 'textures') +const ASSETS_DIR = join(process.cwd(), 'public', 'assets') -// ───────────────────────────────────────────── -// Utilitaire : sanitiser le nom de fichier -// ───────────────────────────────────────────── function sanitizeFilename(name: string): string { return basename(name) .replace(/[^a-zA-Z0-9._-]/g, '_') @@ -25,35 +19,33 @@ function sanitizeFilename(name: string): string { .toLowerCase() } -// ───────────────────────────────────────────── -// Utilitaire : parser le multipart via req.formData() -// Retourne { filename, savedPath } ou throw -// ───────────────────────────────────────────── -async function parseUpload(req: NextRequest): Promise<{ filename: string; savedPath: string; relPath: string }> { +async function parseUpload(req: NextRequest): Promise<{ filename: string; savedPath: string; relPath: string; folderName: string }> { const formData = await req.formData() const file = formData.get('file') as File | null - const assetName = (formData.get('assetName') as string | null)?.trim() + const folderName = (formData.get('folderName') as string | null)?.trim() || 'assets' + const fileType = formData.get('fileType') as string | null + const textureName = formData.get('textureName') as string | null if (!file || file.size === 0) { - throw new Error('Aucun fichier reçu dans la requête') + throw new Error('Aucun fichier reçu') } const originalSafe = sanitizeFilename(file.name) const ext = extname(originalSafe).toLowerCase() if (!ALL_ALLOWED_EXTENSIONS.has(ext)) { - throw new Error(`Extension non autorisée : "${ext}". Formats acceptés : .glb, .gltf, .fbx, .png, .jpg, .jpeg, .webp, .ktx2`) + throw new Error(`Extension non autorisée: "${ext}"`) } - // Renommer avec le nom fourni par le designer si disponible - const baseName = assetName - ? sanitizeFilename(assetName).replace(/\.[^.]+$/, '') // retirer extension si présente - : originalSafe.replace(/\.[^.]+$/, '') - const filename = `${baseName}${ext}` - - const isTexture = TEXTURE_EXTENSIONS.has(ext) - const destDir = isTexture ? TEXTURES_DIR : MODELS_DIR - const relPath = join('public', isTexture ? 'textures' : 'models', filename) + const safeFolderName = sanitizeFilename(folderName).replace(/[^a-zA-Z0-9-_]/g, '-') + const destDir = join(ASSETS_DIR, safeFolderName) + + let filename: string + if (fileType === 'texture' && textureName) { + filename = sanitizeFilename(textureName) + } else { + filename = originalSafe + } mkdirSync(destDir, { recursive: true }) @@ -61,20 +53,19 @@ async function parseUpload(req: NextRequest): Promise<{ filename: string; savedP const buffer = Buffer.from(await file.arrayBuffer()) writeFileSync(savedPath, buffer) - return { filename, savedPath, relPath } + const relPath = join('public', 'assets', safeFolderName, filename) + + return { filename, savedPath, relPath, folderName: safeFolderName } } -// ───────────────────────────────────────────── -// Utilitaire : exécuter la séquence git -// ───────────────────────────────────────────── -function runGitPush(filename: string, relPath: string): { output: string } { +function runGitPush(folderName: string): { output: string } { const branch = process.env.GIT_BRANCH ?? 'main' const repoUrl = process.env.GIT_REPO_URL const execOpts = { cwd: process.cwd(), encoding: 'utf-8' as const, - timeout: 60_000, + timeout: 120_000, env: { ...process.env, GIT_SSH_COMMAND: 'ssh -i /root/.ssh/id_rsa -o StrictHostKeyChecking=no -o UserKnownHostsFile=/root/.ssh/known_hosts', @@ -85,18 +76,13 @@ function runGitPush(filename: string, relPath: string): { output: string } { }, } - // S'assurer que le repo est initialisé et que le remote est configuré try { execSync('git rev-parse --git-dir', { cwd: process.cwd(), stdio: 'ignore' }) } catch { - // Pas encore de repo git — initialiser execSync('git init && git lfs install', { ...execOpts, stdio: 'pipe' }) - if (repoUrl) { execSync(`git remote add origin "${repoUrl}"`, { ...execOpts, stdio: 'pipe' }) } - - // Récupérer l'historique distant si possible try { execSync(`git fetch origin ${branch}`, { ...execOpts, stdio: 'pipe', timeout: 30_000 }) execSync(`git checkout -b ${branch} --track origin/${branch}`, { ...execOpts, stdio: 'pipe' }) @@ -105,25 +91,23 @@ function runGitPush(filename: string, relPath: string): { output: string } { } } - // Mettre à jour l'URL du remote avec le token (au cas où elle aurait changé) if (repoUrl) { execSync(`git remote set-url origin "${repoUrl}"`, { ...execOpts, stdio: 'pipe' }) } const timestamp = new Date().toISOString() - let output = '' - // Sync avec le remote avant de committer output += execSync(`git fetch origin ${branch}`, execOpts) output += execSync(`git reset --hard origin/${branch}`, execOpts) - // git add - output += execSync(`git add "${relPath}"`, execOpts) + const folderPath = join('public', 'assets', folderName) + if (existsSync(folderPath)) { + output += execSync(`git add "${folderPath}"`, execOpts) + } - // git commit — ignoré si rien à committer (fichier identique) try { - output += execSync(`git commit -m "Design Update: ${filename} [${timestamp}]"`, execOpts) + output += execSync(`git commit -m "Design Update: ${folderName} [${timestamp}]"`, execOpts) } catch (err) { const msg = [ err instanceof Error ? err.message : '', @@ -133,25 +117,19 @@ function runGitPush(filename: string, relPath: string): { output: string } { if (!msg.includes('nothing to commit') && !msg.includes('nothing added to commit')) { throw err } - output += '[rien à committer — fichier identique]\n' + output += '[rien à committer]\n' } - // git push output += execSync(`git push origin ${branch}`, execOpts) return { output } } -// ───────────────────────────────────────────── -// POST /api/upload -// ───────────────────────────────────────────── export async function POST(req: NextRequest) { - // 1. Authentification const secret = req.headers.get('x-upload-secret') const expectedSecret = process.env.UPLOAD_SECRET_KEY if (!expectedSecret) { - console.error('[upload] UPLOAD_SECRET_KEY non configurée côté serveur') return NextResponse.json( { success: false, error: 'Configuration serveur incomplète' }, { status: 500 } @@ -165,47 +143,34 @@ export async function POST(req: NextRequest) { ) } - // 2. Parse & écriture disque let filename: string let savedPath: string let relPath: string + let folderName: string try { - ;({ filename, savedPath, relPath } = await parseUpload(req)) - console.log(`[upload] Fichier reçu et sauvegardé : ${savedPath}`) + ;({ filename, savedPath, relPath, folderName } = await parseUpload(req)) } catch (err) { - const message = err instanceof Error ? err.message : 'Erreur inconnue lors de l\'upload' - console.error('[upload] Erreur parsing :', message) - return NextResponse.json( - { success: false, error: message }, - { status: 400 } - ) + const message = err instanceof Error ? err.message : 'Erreur inconnue' + return NextResponse.json({ success: false, error: message }, { status: 400 }) } - // 3. Séquence git push try { - const { output } = runGitPush(filename, relPath) - console.log(`[upload] Git push réussi pour ${filename}`) + const { output } = runGitPush(folderName) return NextResponse.json({ success: true, filename, - message: `"${filename}" sauvegardé et poussé sur Git avec succès.`, + message: `"${filename}" ajouté au dossier "${folderName}" et poussé sur Git.`, gitOutput: output, }) } catch (err) { const message = err instanceof Error ? err.message : 'Erreur git inconnue' const stderr = (err as NodeJS.ErrnoException & { stderr?: string })?.stderr ?? '' - console.error('[upload] Erreur git push :', message, stderr) return NextResponse.json( - { - success: false, - filename, - error: `Fichier sauvegardé mais git push a échoué : ${message}`, - gitError: stderr, - }, + { success: false, error: `Fichier sauvegardé mais git push a échoué: ${message}`, gitError: stderr }, { status: 500 } ) } -} +} \ No newline at end of file diff --git a/components/UploadZone.tsx b/components/UploadZone.tsx index 285449f..22cab82 100644 --- a/components/UploadZone.tsx +++ b/components/UploadZone.tsx @@ -1,111 +1,174 @@ 'use client' import { useCallback, useRef, useState } from 'react' -import { useDropzone, FileRejection } from 'react-dropzone' import dynamic from 'next/dynamic' const ModelViewer = dynamic(() => import('./ModelViewer'), { ssr: false }) type FileStatus = 'pending' | 'uploading' | 'success' | 'error' -interface FileEntry { +interface TextureFile { + name: string file: File +} + +interface FolderEntry { + folderName: string + modelFile: File + textures: TextureFile[] status: FileStatus progress: number error?: string filename?: string - previewUrl?: string + modelUrl?: string viewerOpen?: boolean + warnings: string[] } -interface UploadResult { - success: boolean - filename?: string - message?: string - error?: string - gitOutput?: string - gitError?: string -} - -const ACCEPTED_FORMATS = { - 'model/gltf-binary': ['.glb'], - 'model/gltf+json': ['.gltf'], - 'image/png': ['.png'], - 'image/jpeg': ['.jpg', '.jpeg'], - 'image/webp': ['.webp'], -} - -const MODEL_EXTENSIONS = ['.glb', '.gltf'] +const REQUIRED_TEXTURES = ['roughness', 'normal', 'metalness', 'color', 'displace'] const TEXTURE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp'] -const ALL_EXTENSIONS = [...MODEL_EXTENSIONS, ...TEXTURE_EXTENSIONS] function formatBytes(bytes: number): string { if (bytes === 0) return '0 B' const k = 1024 const sizes = ['B', 'KB', 'MB', 'GB'] const i = Math.floor(Math.log(bytes) / Math.log(k)) - return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}` + return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i] } -function getFileType(filename: string): 'model' | 'texture' | null { - const ext = filename.slice(filename.lastIndexOf('.')).toLowerCase() - if (MODEL_EXTENSIONS.includes(ext)) return 'model' - if (TEXTURE_EXTENSIONS.includes(ext)) return 'texture' +function getTextureType(filename: string): string | null { + const name = filename.toLowerCase().replace(/\.[^.]+$/, '') + if (REQUIRED_TEXTURES.includes(name)) return name return null } -function uploadSingleFile( - file: File, +function validateFolder(files: File[]): { model?: File; textures: TextureFile[]; errors: string[]; warnings: string[] } { + const result: { model?: File; textures: TextureFile[]; errors: string[]; warnings: string[] } = { + textures: [], + errors: [], + warnings: [] + } + + const modelFiles = files.filter(f => { + const name = f.name.toLowerCase() + return name === 'model.glb' || name === 'model.gltf' + }) + + if (modelFiles.length === 0) { + result.errors.push('model.glb ou model.gltf manquant (obligatoire)') + } else { + result.model = modelFiles[0] + } + + const textureFiles = files.filter(f => { + const ext = f.name.slice(f.name.lastIndexOf('.')).toLowerCase() + return TEXTURE_EXTENSIONS.includes(ext) && getTextureType(f.name) !== null + }) + + for (const tf of textureFiles) { + result.textures.push({ name: tf.name, file: tf }) + } + + const foundTextures = new Set(result.textures.map(t => t.name.toLowerCase().replace(/\.[^.]+$/, ''))) + for (const req of REQUIRED_TEXTURES) { + if (!foundTextures.has(req)) { + result.warnings.push(`${req}.webp/png/jpg manquant`) + } + } + + return result +} + +function uploadFolder( + folder: FolderEntry, secret: string, - assetName: string, onProgress: (pct: number) => void, xhrRef: { current: XMLHttpRequest | null } -): Promise { +): Promise<{ success: boolean; filename?: string; error?: string }> { return new Promise((resolve) => { - const formData = new FormData() - formData.append('file', file) - if (assetName.trim()) formData.append('assetName', assetName.trim()) - - const xhr = new XMLHttpRequest() - xhrRef.current = xhr - - xhr.upload.onprogress = (e) => { - if (e.lengthComputable) onProgress(Math.round((e.loaded / e.total) * 100)) - } - - xhr.onload = () => { - try { - resolve(JSON.parse(xhr.responseText)) - } catch { - resolve({ success: false, error: `Unexpected response (HTTP ${xhr.status})` }) + const totalFiles = 1 + folder.textures.length + let completed = 0 + + const checkDone = () => { + completed++ + onProgress(Math.round((completed / totalFiles) * 100)) + if (completed >= totalFiles) { + resolve({ success: true, filename: folder.folderName }) } } - - xhr.onerror = () => resolve({ success: false, error: 'Network error.' }) - xhr.onabort = () => resolve({ success: false, error: 'Cancelled.' }) - - xhr.open('POST', '/api/upload') - xhr.setRequestHeader('x-upload-secret', secret.trim()) - xhr.send(formData) + + const formData = new FormData() + formData.append('folderName', folder.folderName) + formData.append('file', folder.modelFile) + formData.append('fileType', 'model') + + for (const tex of folder.textures) { + const texForm = new FormData() + texForm.append('folderName', folder.folderName) + texForm.append('file', tex.file) + texForm.append('fileType', 'texture') + texForm.append('textureName', tex.name) + + const xhr = new XMLHttpRequest() + xhrRef.current = xhr + + xhr.onload = () => { + try { + const res = JSON.parse(xhr.responseText) + if (!res.success) { + resolve({ success: false, error: `Texture ${tex.name} : ${res.error}` }) + } else { + checkDone() + } + } catch { + checkDone() + } + } + xhr.onerror = () => resolve({ success: false, error: `Erreur réseau: ${tex.name}` }) + + xhr.open('POST', '/api/upload') + xhr.setRequestHeader('x-upload-secret', secret.trim()) + xhr.send(texForm) + } + + const modelXhr = new XMLHttpRequest() + xhrRef.current = modelXhr + + modelXhr.onload = () => { + try { + const res = JSON.parse(modelXhr.responseText) + if (!res.success) { + resolve({ success: false, error: res.error }) + } else { + checkDone() + } + } catch { + checkDone() + } + } + modelXhr.onerror = () => resolve({ success: false, error: 'Erreur réseau: model' }) + + modelXhr.open('POST', '/api/upload') + modelXhr.setRequestHeader('x-upload-secret', secret.trim()) + modelXhr.send(formData) }) } export default function UploadZone() { - const [files, setFiles] = useState([]) + const [files, setFiles] = useState([]) const [isUploading, setIsUploading] = useState(false) const [secret, setSecret] = useState('') const [secretVisible, setSecretVisible] = useState(false) - const [assetName, setAssetName] = useState('') const [globalError, setGlobalError] = useState(null) const xhrRef = useRef(null) - const updateFile = (index: number, patch: Partial) => { + const updateFile = (index: number, patch: Partial) => { setFiles((prev) => prev.map((f, i) => i === index ? { ...f, ...patch } : f)) } const handleUpload = useCallback(async () => { if (!secret.trim()) { - setGlobalError('Please enter the access key before uploading.') + setGlobalError('Veuillez entrer la clé d\'accès avant d\'uploader.') return } if (files.length === 0) return @@ -118,10 +181,9 @@ export default function UploadZone() { updateFile(i, { status: 'uploading', progress: 0, error: undefined }) - const result = await uploadSingleFile( - files[i].file, + const result = await uploadFolder( + files[i], secret, - assetName, (pct) => updateFile(i, { progress: pct }), xhrRef ) @@ -135,65 +197,25 @@ export default function UploadZone() { } setIsUploading(false) - }, [files, secret, assetName]) + }, [files, secret]) const handleCancel = () => { xhrRef.current?.abort() } const removeFile = (index: number) => { const file = files[index] - if (file.previewUrl) { - URL.revokeObjectURL(file.previewUrl) - } + if (file.modelUrl) URL.revokeObjectURL(file.modelUrl) setFiles((prev) => prev.filter((_, i) => i !== index)) } const handleReset = () => { files.forEach((f) => { - if (f.previewUrl) URL.revokeObjectURL(f.previewUrl) + if (f.modelUrl) URL.revokeObjectURL(f.modelUrl) }) setFiles([]) setGlobalError(null) setIsUploading(false) } - const onDrop = useCallback((acceptedFiles: File[], rejectedFiles: FileRejection[]) => { - if (rejectedFiles.length > 0) { - const codes = rejectedFiles[0].errors.map((e) => e.code).join(', ') - setGlobalError( - codes.includes('file-invalid-type') - ? `Unsupported format. Use: ${ALL_EXTENSIONS.join(', ')}` - : codes.includes('file-too-large') - ? 'File too large (max 2 GB)' - : `File rejected: ${codes}` - ) - return - } - - setGlobalError(null) - setFiles((prev) => { - const existingNames = new Set(prev.map((f) => f.file.name)) - const newEntries: FileEntry[] = acceptedFiles - .filter((f) => !existingNames.has(f.name)) - .map((file) => { - const entry: FileEntry = { file, status: 'pending', progress: 0, viewerOpen: true } - const type = getFileType(file.name) - if (type === 'model') { - entry.previewUrl = URL.createObjectURL(file) - } - return entry - }) - return [...prev, ...newEntries] - }) - }, []) - - const { getRootProps, getInputProps, isDragActive, isDragReject } = useDropzone({ - onDrop, - accept: ACCEPTED_FORMATS, - maxSize: 2 * 1024 * 1024 * 1024, - disabled: isUploading, - multiple: false, - }) - const allDone = files.length > 0 && files.every((f) => f.status === 'success') const hasErrors = files.some((f) => f.status === 'error') @@ -233,62 +255,65 @@ export default function UploadZone() { -
- - setAssetName(e.target.value)} - placeholder="e.g., tower, stone_floor, brick_wall..." - disabled={isUploading} -className="w-full bg-black-800 border border-white/30 rounded-xl px-4 py-2.5 - text-gray-100 placeholder-gray-500 text-sm font-mono - focus:outline-none focus:ring-2 focus:ring-white/50 focus:border-white/50 - disabled:opacity-50 disabled:cursor-not-allowed transition" - /> -
+ )} + multiple + className="hidden" + onChange={(e) => { + const files = e.target.files + if (files && files.length > 0) { + const fileArray = Array.from(files) + const folderName = fileArray[0].webkitRelativePath?.split('/')[0] || 'folder' + const validation = validateFolder(fileArray) + + if (validation.errors.length > 0) { + setGlobalError(validation.errors.join(' | ')) + return + } + + setGlobalError(null) + const entry: FolderEntry = { + folderName, + modelFile: validation.model!, + textures: validation.textures, + status: 'pending', + progress: 0, + warnings: validation.warnings, + modelUrl: URL.createObjectURL(validation.model!), + viewerOpen: true, + } + setFiles([entry]) + } + }} + /> {files.length === 0 && (
document.getElementById('folder-input')?.click()} className={` relative border-2 border-dashed rounded-2xl p-8 text-center cursor-pointer transition-all duration-200 bg-black-800 ${isUploading ? 'cursor-not-allowed opacity-60 border-white/20' : ''} - ${isDragReject ? 'border-red-500 bg-red-900/20' : ''} - ${isDragActive && !isDragReject ? 'border-white/50 bg-black-700 scale-[1.01]' : ''} - ${!isDragActive && !isDragReject && !isUploading - ? 'border-white/30 hover:border-white/50 hover:bg-black-700' - : ''} + ${!isUploading ? 'border-white/30 hover:border-white/50 hover:bg-black-700' : ''} `} > -
-
- + + d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
- {isDragReject ? ( -

Unsupported format

- ) : isDragActive ? ( -

Release to add

- ) : ( - <> -

- Drag files here - or click to browse -

-

- Models: .glb, .gltf · Textures: .png, .jpg, .webp -

- - )} +

+ Drop ton dossier ici + ou click pour parcourir +

+

+ Contient: model.glb/gltf + textures (roughness, normal, metalness, color, displace) +

)} @@ -298,12 +323,9 @@ className="w-full bg-black-800 border border-white/30 rounded-xl px-4 py-2.5 {files.length > 0 && (
- {files.map((entry, i) => { - const type = getFileType(entry.file.name) - return ( -
-
- + {files.map((entry, i) => ( +
+
{entry.status === 'success' ? (
@@ -326,15 +348,9 @@ className="w-full bg-black-800 border border-white/30 rounded-xl px-4 py-2.5
) : (
- ); - })} + ))}
)} @@ -416,9 +437,7 @@ className="w-full bg-black-800 border border-white/30 rounded-xl px-4 py-2.5 hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-white/50 border border-white/20" style={{ color: '#000000' }} > - Upload {files.filter(f => f.status !== 'success').length > 1 - ? `${files.filter(f => f.status !== 'success').length} files` - : 'file'} & Push to Git + Upload & Push to Git )}