fix: issue on viewer
This commit is contained in:
+36
-71
@@ -1,23 +1,17 @@
|
|||||||
import { NextRequest, NextResponse } from 'next/server'
|
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 { join, extname, basename } from 'path'
|
||||||
import { execSync } from 'child_process'
|
import { execSync } from 'child_process'
|
||||||
|
|
||||||
// Forcer le runtime Node.js (nécessaire pour fs, child_process)
|
|
||||||
export const runtime = 'nodejs'
|
export const runtime = 'nodejs'
|
||||||
export const dynamic = 'force-dynamic'
|
export const dynamic = 'force-dynamic'
|
||||||
|
|
||||||
// Formats autorisés par type
|
const MODEL_EXTENSIONS = new Set(['.glb', '.gltf'])
|
||||||
const MODEL_EXTENSIONS = new Set(['.glb', '.gltf', '.fbx'])
|
const TEXTURE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp'])
|
||||||
const TEXTURE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.ktx2'])
|
|
||||||
const ALL_ALLOWED_EXTENSIONS = new Set([...MODEL_EXTENSIONS, ...TEXTURE_EXTENSIONS])
|
const ALL_ALLOWED_EXTENSIONS = new Set([...MODEL_EXTENSIONS, ...TEXTURE_EXTENSIONS])
|
||||||
|
|
||||||
const MODELS_DIR = join(process.cwd(), 'public', 'models')
|
const ASSETS_DIR = join(process.cwd(), 'public', 'assets')
|
||||||
const TEXTURES_DIR = join(process.cwd(), 'public', 'textures')
|
|
||||||
|
|
||||||
// ─────────────────────────────────────────────
|
|
||||||
// Utilitaire : sanitiser le nom de fichier
|
|
||||||
// ─────────────────────────────────────────────
|
|
||||||
function sanitizeFilename(name: string): string {
|
function sanitizeFilename(name: string): string {
|
||||||
return basename(name)
|
return basename(name)
|
||||||
.replace(/[^a-zA-Z0-9._-]/g, '_')
|
.replace(/[^a-zA-Z0-9._-]/g, '_')
|
||||||
@@ -25,35 +19,33 @@ function sanitizeFilename(name: string): string {
|
|||||||
.toLowerCase()
|
.toLowerCase()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─────────────────────────────────────────────
|
async function parseUpload(req: NextRequest): Promise<{ filename: string; savedPath: string; relPath: string; folderName: string }> {
|
||||||
// Utilitaire : parser le multipart via req.formData()
|
|
||||||
// Retourne { filename, savedPath } ou throw
|
|
||||||
// ─────────────────────────────────────────────
|
|
||||||
async function parseUpload(req: NextRequest): Promise<{ filename: string; savedPath: string; relPath: string }> {
|
|
||||||
const formData = await req.formData()
|
const formData = await req.formData()
|
||||||
const file = formData.get('file') as File | null
|
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) {
|
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 originalSafe = sanitizeFilename(file.name)
|
||||||
const ext = extname(originalSafe).toLowerCase()
|
const ext = extname(originalSafe).toLowerCase()
|
||||||
|
|
||||||
if (!ALL_ALLOWED_EXTENSIONS.has(ext)) {
|
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 safeFolderName = sanitizeFilename(folderName).replace(/[^a-zA-Z0-9-_]/g, '-')
|
||||||
const baseName = assetName
|
const destDir = join(ASSETS_DIR, safeFolderName)
|
||||||
? sanitizeFilename(assetName).replace(/\.[^.]+$/, '') // retirer extension si présente
|
|
||||||
: originalSafe.replace(/\.[^.]+$/, '')
|
|
||||||
const filename = `${baseName}${ext}`
|
|
||||||
|
|
||||||
const isTexture = TEXTURE_EXTENSIONS.has(ext)
|
let filename: string
|
||||||
const destDir = isTexture ? TEXTURES_DIR : MODELS_DIR
|
if (fileType === 'texture' && textureName) {
|
||||||
const relPath = join('public', isTexture ? 'textures' : 'models', filename)
|
filename = sanitizeFilename(textureName)
|
||||||
|
} else {
|
||||||
|
filename = originalSafe
|
||||||
|
}
|
||||||
|
|
||||||
mkdirSync(destDir, { recursive: true })
|
mkdirSync(destDir, { recursive: true })
|
||||||
|
|
||||||
@@ -61,20 +53,19 @@ async function parseUpload(req: NextRequest): Promise<{ filename: string; savedP
|
|||||||
const buffer = Buffer.from(await file.arrayBuffer())
|
const buffer = Buffer.from(await file.arrayBuffer())
|
||||||
writeFileSync(savedPath, buffer)
|
writeFileSync(savedPath, buffer)
|
||||||
|
|
||||||
return { filename, savedPath, relPath }
|
const relPath = join('public', 'assets', safeFolderName, filename)
|
||||||
|
|
||||||
|
return { filename, savedPath, relPath, folderName: safeFolderName }
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─────────────────────────────────────────────
|
function runGitPush(folderName: string): { output: string } {
|
||||||
// Utilitaire : exécuter la séquence git
|
|
||||||
// ─────────────────────────────────────────────
|
|
||||||
function runGitPush(filename: string, relPath: string): { output: string } {
|
|
||||||
const branch = process.env.GIT_BRANCH ?? 'main'
|
const branch = process.env.GIT_BRANCH ?? 'main'
|
||||||
const repoUrl = process.env.GIT_REPO_URL
|
const repoUrl = process.env.GIT_REPO_URL
|
||||||
|
|
||||||
const execOpts = {
|
const execOpts = {
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
encoding: 'utf-8' as const,
|
encoding: 'utf-8' as const,
|
||||||
timeout: 60_000,
|
timeout: 120_000,
|
||||||
env: {
|
env: {
|
||||||
...process.env,
|
...process.env,
|
||||||
GIT_SSH_COMMAND: 'ssh -i /root/.ssh/id_rsa -o StrictHostKeyChecking=no -o UserKnownHostsFile=/root/.ssh/known_hosts',
|
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 {
|
try {
|
||||||
execSync('git rev-parse --git-dir', { cwd: process.cwd(), stdio: 'ignore' })
|
execSync('git rev-parse --git-dir', { cwd: process.cwd(), stdio: 'ignore' })
|
||||||
} catch {
|
} catch {
|
||||||
// Pas encore de repo git — initialiser
|
|
||||||
execSync('git init && git lfs install', { ...execOpts, stdio: 'pipe' })
|
execSync('git init && git lfs install', { ...execOpts, stdio: 'pipe' })
|
||||||
|
|
||||||
if (repoUrl) {
|
if (repoUrl) {
|
||||||
execSync(`git remote add origin "${repoUrl}"`, { ...execOpts, stdio: 'pipe' })
|
execSync(`git remote add origin "${repoUrl}"`, { ...execOpts, stdio: 'pipe' })
|
||||||
}
|
}
|
||||||
|
|
||||||
// Récupérer l'historique distant si possible
|
|
||||||
try {
|
try {
|
||||||
execSync(`git fetch origin ${branch}`, { ...execOpts, stdio: 'pipe', timeout: 30_000 })
|
execSync(`git fetch origin ${branch}`, { ...execOpts, stdio: 'pipe', timeout: 30_000 })
|
||||||
execSync(`git checkout -b ${branch} --track origin/${branch}`, { ...execOpts, stdio: 'pipe' })
|
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) {
|
if (repoUrl) {
|
||||||
execSync(`git remote set-url origin "${repoUrl}"`, { ...execOpts, stdio: 'pipe' })
|
execSync(`git remote set-url origin "${repoUrl}"`, { ...execOpts, stdio: 'pipe' })
|
||||||
}
|
}
|
||||||
|
|
||||||
const timestamp = new Date().toISOString()
|
const timestamp = new Date().toISOString()
|
||||||
|
|
||||||
let output = ''
|
let output = ''
|
||||||
|
|
||||||
// Sync avec le remote avant de committer
|
|
||||||
output += execSync(`git fetch origin ${branch}`, execOpts)
|
output += execSync(`git fetch origin ${branch}`, execOpts)
|
||||||
output += execSync(`git reset --hard origin/${branch}`, execOpts)
|
output += execSync(`git reset --hard origin/${branch}`, execOpts)
|
||||||
|
|
||||||
// git add
|
const folderPath = join('public', 'assets', folderName)
|
||||||
output += execSync(`git add "${relPath}"`, execOpts)
|
if (existsSync(folderPath)) {
|
||||||
|
output += execSync(`git add "${folderPath}"`, execOpts)
|
||||||
|
}
|
||||||
|
|
||||||
// git commit — ignoré si rien à committer (fichier identique)
|
|
||||||
try {
|
try {
|
||||||
output += execSync(`git commit -m "Design Update: ${filename} [${timestamp}]"`, execOpts)
|
output += execSync(`git commit -m "Design Update: ${folderName} [${timestamp}]"`, execOpts)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const msg = [
|
const msg = [
|
||||||
err instanceof Error ? err.message : '',
|
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')) {
|
if (!msg.includes('nothing to commit') && !msg.includes('nothing added to commit')) {
|
||||||
throw err
|
throw err
|
||||||
}
|
}
|
||||||
output += '[rien à committer — fichier identique]\n'
|
output += '[rien à committer]\n'
|
||||||
}
|
}
|
||||||
|
|
||||||
// git push
|
|
||||||
output += execSync(`git push origin ${branch}`, execOpts)
|
output += execSync(`git push origin ${branch}`, execOpts)
|
||||||
|
|
||||||
return { output }
|
return { output }
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─────────────────────────────────────────────
|
|
||||||
// POST /api/upload
|
|
||||||
// ─────────────────────────────────────────────
|
|
||||||
export async function POST(req: NextRequest) {
|
export async function POST(req: NextRequest) {
|
||||||
// 1. Authentification
|
|
||||||
const secret = req.headers.get('x-upload-secret')
|
const secret = req.headers.get('x-upload-secret')
|
||||||
const expectedSecret = process.env.UPLOAD_SECRET_KEY
|
const expectedSecret = process.env.UPLOAD_SECRET_KEY
|
||||||
|
|
||||||
if (!expectedSecret) {
|
if (!expectedSecret) {
|
||||||
console.error('[upload] UPLOAD_SECRET_KEY non configurée côté serveur')
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ success: false, error: 'Configuration serveur incomplète' },
|
{ success: false, error: 'Configuration serveur incomplète' },
|
||||||
{ status: 500 }
|
{ status: 500 }
|
||||||
@@ -165,46 +143,33 @@ export async function POST(req: NextRequest) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Parse & écriture disque
|
|
||||||
let filename: string
|
let filename: string
|
||||||
let savedPath: string
|
let savedPath: string
|
||||||
let relPath: string
|
let relPath: string
|
||||||
|
let folderName: string
|
||||||
|
|
||||||
try {
|
try {
|
||||||
;({ filename, savedPath, relPath } = await parseUpload(req))
|
;({ filename, savedPath, relPath, folderName } = await parseUpload(req))
|
||||||
console.log(`[upload] Fichier reçu et sauvegardé : ${savedPath}`)
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const message = err instanceof Error ? err.message : 'Erreur inconnue lors de l\'upload'
|
const message = err instanceof Error ? err.message : 'Erreur inconnue'
|
||||||
console.error('[upload] Erreur parsing :', message)
|
return NextResponse.json({ success: false, error: message }, { status: 400 })
|
||||||
return NextResponse.json(
|
|
||||||
{ success: false, error: message },
|
|
||||||
{ status: 400 }
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Séquence git push
|
|
||||||
try {
|
try {
|
||||||
const { output } = runGitPush(filename, relPath)
|
const { output } = runGitPush(folderName)
|
||||||
console.log(`[upload] Git push réussi pour ${filename}`)
|
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
success: true,
|
success: true,
|
||||||
filename,
|
filename,
|
||||||
message: `"${filename}" sauvegardé et poussé sur Git avec succès.`,
|
message: `"${filename}" ajouté au dossier "${folderName}" et poussé sur Git.`,
|
||||||
gitOutput: output,
|
gitOutput: output,
|
||||||
})
|
})
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const message = err instanceof Error ? err.message : 'Erreur git inconnue'
|
const message = err instanceof Error ? err.message : 'Erreur git inconnue'
|
||||||
const stderr = (err as NodeJS.ErrnoException & { stderr?: string })?.stderr ?? ''
|
const stderr = (err as NodeJS.ErrnoException & { stderr?: string })?.stderr ?? ''
|
||||||
console.error('[upload] Erreur git push :', message, stderr)
|
|
||||||
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{
|
{ success: false, error: `Fichier sauvegardé mais git push a échoué: ${message}`, gitError: stderr },
|
||||||
success: false,
|
|
||||||
filename,
|
|
||||||
error: `Fichier sauvegardé mais git push a échoué : ${message}`,
|
|
||||||
gitError: stderr,
|
|
||||||
},
|
|
||||||
{ status: 500 }
|
{ status: 500 }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
+193
-174
@@ -1,111 +1,174 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useCallback, useRef, useState } from 'react'
|
import { useCallback, useRef, useState } from 'react'
|
||||||
import { useDropzone, FileRejection } from 'react-dropzone'
|
|
||||||
import dynamic from 'next/dynamic'
|
import dynamic from 'next/dynamic'
|
||||||
|
|
||||||
const ModelViewer = dynamic(() => import('./ModelViewer'), { ssr: false })
|
const ModelViewer = dynamic(() => import('./ModelViewer'), { ssr: false })
|
||||||
|
|
||||||
type FileStatus = 'pending' | 'uploading' | 'success' | 'error'
|
type FileStatus = 'pending' | 'uploading' | 'success' | 'error'
|
||||||
|
|
||||||
interface FileEntry {
|
interface TextureFile {
|
||||||
|
name: string
|
||||||
file: File
|
file: File
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FolderEntry {
|
||||||
|
folderName: string
|
||||||
|
modelFile: File
|
||||||
|
textures: TextureFile[]
|
||||||
status: FileStatus
|
status: FileStatus
|
||||||
progress: number
|
progress: number
|
||||||
error?: string
|
error?: string
|
||||||
filename?: string
|
filename?: string
|
||||||
previewUrl?: string
|
modelUrl?: string
|
||||||
viewerOpen?: boolean
|
viewerOpen?: boolean
|
||||||
|
warnings: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
interface UploadResult {
|
const REQUIRED_TEXTURES = ['roughness', 'normal', 'metalness', 'color', 'displace']
|
||||||
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 TEXTURE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp']
|
const TEXTURE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp']
|
||||||
const ALL_EXTENSIONS = [...MODEL_EXTENSIONS, ...TEXTURE_EXTENSIONS]
|
|
||||||
|
|
||||||
function formatBytes(bytes: number): string {
|
function formatBytes(bytes: number): string {
|
||||||
if (bytes === 0) return '0 B'
|
if (bytes === 0) return '0 B'
|
||||||
const k = 1024
|
const k = 1024
|
||||||
const sizes = ['B', 'KB', 'MB', 'GB']
|
const sizes = ['B', 'KB', 'MB', 'GB']
|
||||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
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 {
|
function getTextureType(filename: string): string | null {
|
||||||
const ext = filename.slice(filename.lastIndexOf('.')).toLowerCase()
|
const name = filename.toLowerCase().replace(/\.[^.]+$/, '')
|
||||||
if (MODEL_EXTENSIONS.includes(ext)) return 'model'
|
if (REQUIRED_TEXTURES.includes(name)) return name
|
||||||
if (TEXTURE_EXTENSIONS.includes(ext)) return 'texture'
|
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
function uploadSingleFile(
|
function validateFolder(files: File[]): { model?: File; textures: TextureFile[]; errors: string[]; warnings: string[] } {
|
||||||
file: File,
|
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,
|
secret: string,
|
||||||
assetName: string,
|
|
||||||
onProgress: (pct: number) => void,
|
onProgress: (pct: number) => void,
|
||||||
xhrRef: { current: XMLHttpRequest | null }
|
xhrRef: { current: XMLHttpRequest | null }
|
||||||
): Promise<UploadResult> {
|
): Promise<{ success: boolean; filename?: string; error?: string }> {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
const formData = new FormData()
|
const totalFiles = 1 + folder.textures.length
|
||||||
formData.append('file', file)
|
let completed = 0
|
||||||
if (assetName.trim()) formData.append('assetName', assetName.trim())
|
|
||||||
|
|
||||||
const xhr = new XMLHttpRequest()
|
const checkDone = () => {
|
||||||
xhrRef.current = xhr
|
completed++
|
||||||
|
onProgress(Math.round((completed / totalFiles) * 100))
|
||||||
xhr.upload.onprogress = (e) => {
|
if (completed >= totalFiles) {
|
||||||
if (e.lengthComputable) onProgress(Math.round((e.loaded / e.total) * 100))
|
resolve({ success: true, filename: folder.folderName })
|
||||||
}
|
|
||||||
|
|
||||||
xhr.onload = () => {
|
|
||||||
try {
|
|
||||||
resolve(JSON.parse(xhr.responseText))
|
|
||||||
} catch {
|
|
||||||
resolve({ success: false, error: `Unexpected response (HTTP ${xhr.status})` })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
xhr.onerror = () => resolve({ success: false, error: 'Network error.' })
|
const formData = new FormData()
|
||||||
xhr.onabort = () => resolve({ success: false, error: 'Cancelled.' })
|
formData.append('folderName', folder.folderName)
|
||||||
|
formData.append('file', folder.modelFile)
|
||||||
|
formData.append('fileType', 'model')
|
||||||
|
|
||||||
xhr.open('POST', '/api/upload')
|
for (const tex of folder.textures) {
|
||||||
xhr.setRequestHeader('x-upload-secret', secret.trim())
|
const texForm = new FormData()
|
||||||
xhr.send(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() {
|
export default function UploadZone() {
|
||||||
const [files, setFiles] = useState<FileEntry[]>([])
|
const [files, setFiles] = useState<FolderEntry[]>([])
|
||||||
const [isUploading, setIsUploading] = useState(false)
|
const [isUploading, setIsUploading] = useState(false)
|
||||||
const [secret, setSecret] = useState('')
|
const [secret, setSecret] = useState('')
|
||||||
const [secretVisible, setSecretVisible] = useState(false)
|
const [secretVisible, setSecretVisible] = useState(false)
|
||||||
const [assetName, setAssetName] = useState('')
|
|
||||||
const [globalError, setGlobalError] = useState<string | null>(null)
|
const [globalError, setGlobalError] = useState<string | null>(null)
|
||||||
const xhrRef = useRef<XMLHttpRequest | null>(null)
|
const xhrRef = useRef<XMLHttpRequest | null>(null)
|
||||||
|
|
||||||
const updateFile = (index: number, patch: Partial<FileEntry>) => {
|
const updateFile = (index: number, patch: Partial<FolderEntry>) => {
|
||||||
setFiles((prev) => prev.map((f, i) => i === index ? { ...f, ...patch } : f))
|
setFiles((prev) => prev.map((f, i) => i === index ? { ...f, ...patch } : f))
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleUpload = useCallback(async () => {
|
const handleUpload = useCallback(async () => {
|
||||||
if (!secret.trim()) {
|
if (!secret.trim()) {
|
||||||
setGlobalError('Please enter the access key before uploading.')
|
setGlobalError('Veuillez entrer la clé d\'accès avant d\'uploader.')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (files.length === 0) return
|
if (files.length === 0) return
|
||||||
@@ -118,10 +181,9 @@ export default function UploadZone() {
|
|||||||
|
|
||||||
updateFile(i, { status: 'uploading', progress: 0, error: undefined })
|
updateFile(i, { status: 'uploading', progress: 0, error: undefined })
|
||||||
|
|
||||||
const result = await uploadSingleFile(
|
const result = await uploadFolder(
|
||||||
files[i].file,
|
files[i],
|
||||||
secret,
|
secret,
|
||||||
assetName,
|
|
||||||
(pct) => updateFile(i, { progress: pct }),
|
(pct) => updateFile(i, { progress: pct }),
|
||||||
xhrRef
|
xhrRef
|
||||||
)
|
)
|
||||||
@@ -135,65 +197,25 @@ export default function UploadZone() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setIsUploading(false)
|
setIsUploading(false)
|
||||||
}, [files, secret, assetName])
|
}, [files, secret])
|
||||||
|
|
||||||
const handleCancel = () => { xhrRef.current?.abort() }
|
const handleCancel = () => { xhrRef.current?.abort() }
|
||||||
|
|
||||||
const removeFile = (index: number) => {
|
const removeFile = (index: number) => {
|
||||||
const file = files[index]
|
const file = files[index]
|
||||||
if (file.previewUrl) {
|
if (file.modelUrl) URL.revokeObjectURL(file.modelUrl)
|
||||||
URL.revokeObjectURL(file.previewUrl)
|
|
||||||
}
|
|
||||||
setFiles((prev) => prev.filter((_, i) => i !== index))
|
setFiles((prev) => prev.filter((_, i) => i !== index))
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleReset = () => {
|
const handleReset = () => {
|
||||||
files.forEach((f) => {
|
files.forEach((f) => {
|
||||||
if (f.previewUrl) URL.revokeObjectURL(f.previewUrl)
|
if (f.modelUrl) URL.revokeObjectURL(f.modelUrl)
|
||||||
})
|
})
|
||||||
setFiles([])
|
setFiles([])
|
||||||
setGlobalError(null)
|
setGlobalError(null)
|
||||||
setIsUploading(false)
|
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 allDone = files.length > 0 && files.every((f) => f.status === 'success')
|
||||||
const hasErrors = files.some((f) => f.status === 'error')
|
const hasErrors = files.some((f) => f.status === 'error')
|
||||||
|
|
||||||
@@ -233,62 +255,65 @@ export default function UploadZone() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-1.5">
|
<input
|
||||||
<label className="block text-sm font-medium text-gray-300">
|
type="file"
|
||||||
Asset Name
|
id="folder-input"
|
||||||
<span className="text-gray-500 font-normal ml-2">— common name for model and texture</span>
|
{...({ webkitdirectory: '', directory: '' } as React.InputHTMLAttributes<HTMLInputElement>)}
|
||||||
</label>
|
multiple
|
||||||
<input
|
className="hidden"
|
||||||
type="text"
|
onChange={(e) => {
|
||||||
value={assetName}
|
const files = e.target.files
|
||||||
onChange={(e) => setAssetName(e.target.value)}
|
if (files && files.length > 0) {
|
||||||
placeholder="e.g., tower, stone_floor, brick_wall..."
|
const fileArray = Array.from(files)
|
||||||
disabled={isUploading}
|
const folderName = fileArray[0].webkitRelativePath?.split('/')[0] || 'folder'
|
||||||
className="w-full bg-black-800 border border-white/30 rounded-xl px-4 py-2.5
|
const validation = validateFolder(fileArray)
|
||||||
text-gray-100 placeholder-gray-500 text-sm font-mono
|
|
||||||
focus:outline-none focus:ring-2 focus:ring-white/50 focus:border-white/50
|
if (validation.errors.length > 0) {
|
||||||
disabled:opacity-50 disabled:cursor-not-allowed transition"
|
setGlobalError(validation.errors.join(' | '))
|
||||||
/>
|
return
|
||||||
</div>
|
}
|
||||||
|
|
||||||
|
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 && (
|
{files.length === 0 && (
|
||||||
<div
|
<div
|
||||||
{...getRootProps()}
|
onClick={() => document.getElementById('folder-input')?.click()}
|
||||||
className={`
|
className={`
|
||||||
relative border-2 border-dashed rounded-2xl p-8 text-center cursor-pointer transition-all duration-200 bg-black-800
|
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' : ''}
|
${isUploading ? 'cursor-not-allowed opacity-60 border-white/20' : ''}
|
||||||
${isDragReject ? 'border-red-500 bg-red-900/20' : ''}
|
${!isUploading ? 'border-white/30 hover:border-white/50 hover:bg-black-700' : ''}
|
||||||
${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'
|
|
||||||
: ''}
|
|
||||||
`}
|
`}
|
||||||
>
|
>
|
||||||
<input {...getInputProps()} />
|
|
||||||
<div className="flex justify-center mb-3">
|
<div className="flex justify-center mb-3">
|
||||||
<div className={`w-12 h-12 rounded-full flex items-center justify-center transition ${isDragActive ? 'bg-gray-700' : 'bg-black-700'}`}>
|
<div className="w-12 h-12 rounded-full flex items-center justify-center bg-black-700">
|
||||||
<svg className={`w-6 h-6 transition ${isDragActive ? 'text-white' : 'text-gray-400'}`}
|
<svg className="w-6 h-6 text-gray-400"
|
||||||
fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
|
fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
|
||||||
<path strokeLinecap="round" strokeLinejoin="round"
|
<path strokeLinecap="round" strokeLinejoin="round"
|
||||||
d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
|
d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
|
||||||
</svg>
|
</svg>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{isDragReject ? (
|
<p className="text-sm font-medium text-gray-300">
|
||||||
<p className="text-sm font-medium text-red-400">Unsupported format</p>
|
Drop ton dossier ici
|
||||||
) : isDragActive ? (
|
<span className="text-gray-500 font-normal"> ou click pour parcourir</span>
|
||||||
<p className="text-sm font-medium text-gray-200">Release to add</p>
|
</p>
|
||||||
) : (
|
<p className="text-xs text-gray-500 mt-1">
|
||||||
<>
|
Contient: model.glb/gltf + textures (roughness, normal, metalness, color, displace)
|
||||||
<p className="text-sm font-medium text-gray-300">
|
</p>
|
||||||
Drag files here
|
|
||||||
<span className="text-gray-500 font-normal"> or click to browse</span>
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-gray-500 mt-1">
|
|
||||||
Models: .glb, .gltf · Textures: .png, .jpg, .webp
|
|
||||||
</p>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -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.length > 0 && (
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
{files.map((entry, i) => {
|
{files.map((entry, i) => (
|
||||||
const type = getFileType(entry.file.name)
|
<div key={i}>
|
||||||
return (
|
<div className="flex items-center gap-3 bg-black-800 border border-white/20 rounded-xl px-4 py-3">
|
||||||
<div key={`${entry.file.name}-${i}`}>
|
|
||||||
<div className="flex items-center gap-3 bg-black-800 border border-white/20 rounded-xl px-4 py-3">
|
|
||||||
|
|
||||||
<div className="shrink-0">
|
<div className="shrink-0">
|
||||||
{entry.status === 'success' ? (
|
{entry.status === 'success' ? (
|
||||||
<div className="w-8 h-8 rounded-full bg-green-900/30 flex items-center justify-center">
|
<div className="w-8 h-8 rounded-full bg-green-900/30 flex items-center justify-center">
|
||||||
@@ -326,15 +348,9 @@ className="w-full bg-black-800 border border-white/30 rounded-xl px-4 py-2.5
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<button
|
<button
|
||||||
onClick={() => {
|
onClick={() => entry.modelUrl ? updateFile(i, { viewerOpen: !entry.viewerOpen }) : null}
|
||||||
if (entry.previewUrl && type === 'model') {
|
|
||||||
updateFile(i, { viewerOpen: !entry.viewerOpen })
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
className={`shrink-0 w-8 h-8 rounded-full flex items-center justify-center transition ${
|
className={`shrink-0 w-8 h-8 rounded-full flex items-center justify-center transition ${
|
||||||
entry.previewUrl && type === 'model'
|
entry.modelUrl ? 'bg-black-700 hover:bg-gray-700 cursor-pointer' : 'bg-black-700 cursor-default'
|
||||||
? 'bg-black-700 hover:bg-gray-700 cursor-pointer'
|
|
||||||
: 'bg-black-700 cursor-default'
|
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<svg
|
<svg
|
||||||
@@ -349,16 +365,11 @@ className="w-full bg-black-800 border border-white/30 rounded-xl px-4 py-2.5
|
|||||||
|
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<span className="text-sm text-gray-200 font-mono truncate">{entry.file.name}</span>
|
<span className="text-sm text-gray-200 font-mono truncate">{entry.folderName}/</span>
|
||||||
{type && (
|
<span className="shrink-0 text-xs px-1.5 py-0.5 rounded-full bg-gray-700 text-gray-300">Folder</span>
|
||||||
<span className={`shrink-0 text-xs px-1.5 py-0.5 rounded-full
|
|
||||||
${type === 'model' ? 'bg-gray-700 text-gray-300' : 'bg-gray-700 text-gray-300'}`}>
|
|
||||||
{type === 'model' ? '3D' : 'Texture'}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2 mt-0.5">
|
<div className="flex items-center gap-2 mt-0.5">
|
||||||
<span className="text-xs text-gray-500">{formatBytes(entry.file.size)}</span>
|
<span className="text-xs text-gray-500">model: {entry.modelFile.name}</span>
|
||||||
{entry.status === 'error' && entry.error && (
|
{entry.status === 'error' && entry.error && (
|
||||||
<span className="text-xs text-red-400 truncate">{entry.error}</span>
|
<span className="text-xs text-red-400 truncate">{entry.error}</span>
|
||||||
)}
|
)}
|
||||||
@@ -388,22 +399,32 @@ className="w-full bg-black-800 border border-white/30 rounded-xl px-4 py-2.5
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{entry.previewUrl && type === 'model' && entry.status !== 'success' && (
|
{entry.warnings.length > 0 && entry.status !== 'success' && (
|
||||||
|
<div className="mt-2 px-3 py-2 bg-yellow-900/20 border border-yellow-700/30 rounded-lg">
|
||||||
|
<div className="flex items-center gap-2 text-xs text-yellow-400">
|
||||||
|
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
|
||||||
|
</svg>
|
||||||
|
<span>Textures manquantes: {entry.warnings.join(', ')}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{entry.modelUrl && entry.status !== 'success' && (
|
||||||
<div
|
<div
|
||||||
className={`transition-all duration-300 ease-in-out ${
|
className={`transition-all duration-300 ease-in-out ${
|
||||||
entry.viewerOpen ? 'max-h-[500px] opacity-100 mt-2' : 'max-h-0 opacity-0'
|
entry.viewerOpen ? 'max-h-[500px] opacity-100 mt-2' : 'max-h-0 opacity-0'
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<ModelViewer
|
<ModelViewer
|
||||||
url={entry.previewUrl}
|
url={entry.modelUrl}
|
||||||
filename={entry.file.name}
|
filename={entry.modelFile.name}
|
||||||
size={formatBytes(entry.file.size)}
|
size={formatBytes(entry.modelFile.size)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
))}
|
||||||
})}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -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"
|
hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-white/50 border border-white/20"
|
||||||
style={{ color: '#000000' }}
|
style={{ color: '#000000' }}
|
||||||
>
|
>
|
||||||
Upload {files.filter(f => f.status !== 'success').length > 1
|
Upload & Push to Git
|
||||||
? `${files.filter(f => f.status !== 'success').length} files`
|
|
||||||
: 'file'} & Push to Git
|
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user