Files
upload-gltf/app/api/upload/route.ts
T
2026-04-05 12:32:38 +02:00

176 lines
5.6 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { writeFileSync, mkdirSync, existsSync, rmSync } from 'fs'
import { join, extname, basename } from 'path'
import { execSync } from 'child_process'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
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 ASSETS_DIR = join(process.cwd(), 'public', 'assets')
function sanitizeFilename(name: string): string {
return basename(name)
.replace(/[^a-zA-Z0-9._-]/g, '_')
.replace(/_{2,}/g, '_')
.toLowerCase()
}
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 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')
}
const originalSafe = sanitizeFilename(file.name)
const ext = extname(originalSafe).toLowerCase()
if (!ALL_ALLOWED_EXTENSIONS.has(ext)) {
throw new Error(`Extension non autorisée: "${ext}"`)
}
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 })
const savedPath = join(destDir, filename)
const buffer = Buffer.from(await file.arrayBuffer())
writeFileSync(savedPath, buffer)
const relPath = join('public', 'assets', safeFolderName, filename)
return { filename, savedPath, relPath, folderName: safeFolderName }
}
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: 120_000,
env: {
...process.env,
GIT_SSH_COMMAND: 'ssh -i /root/.ssh/id_rsa -o StrictHostKeyChecking=no -o UserKnownHostsFile=/root/.ssh/known_hosts',
GIT_AUTHOR_NAME: 'Asset Bridge 3D',
GIT_AUTHOR_EMAIL: 'deploy@assetbridge.local',
GIT_COMMITTER_NAME: 'Asset Bridge 3D',
GIT_COMMITTER_EMAIL: 'deploy@assetbridge.local',
},
}
try {
execSync('git rev-parse --git-dir', { cwd: process.cwd(), stdio: 'ignore' })
} catch {
execSync('git init && git lfs install', { ...execOpts, stdio: 'pipe' })
if (repoUrl) {
execSync(`git remote add origin "${repoUrl}"`, { ...execOpts, stdio: 'pipe' })
}
try {
execSync(`git fetch origin ${branch}`, { ...execOpts, stdio: 'pipe', timeout: 30_000 })
execSync(`git checkout -b ${branch} --track origin/${branch}`, { ...execOpts, stdio: 'pipe' })
} catch {
execSync(`git checkout -b ${branch}`, { ...execOpts, stdio: 'pipe' })
}
}
if (repoUrl) {
execSync(`git remote set-url origin "${repoUrl}"`, { ...execOpts, stdio: 'pipe' })
}
const timestamp = new Date().toISOString()
let output = ''
output += execSync(`git fetch origin ${branch}`, execOpts)
output += execSync(`git reset --hard origin/${branch}`, execOpts)
const folderPath = join('public', 'assets', folderName)
if (existsSync(folderPath)) {
output += execSync(`git add "${folderPath}"`, execOpts)
}
try {
output += execSync(`git commit -m "Design Update: ${folderName} [${timestamp}]"`, execOpts)
} catch (err) {
const msg = [
err instanceof Error ? err.message : '',
(err as NodeJS.ErrnoException & { stdout?: string })?.stdout ?? '',
(err as NodeJS.ErrnoException & { stderr?: string })?.stderr ?? '',
].join(' ')
if (!msg.includes('nothing to commit') && !msg.includes('nothing added to commit')) {
throw err
}
output += '[rien à committer]\n'
}
output += execSync(`git push origin ${branch}`, execOpts)
return { output }
}
export async function POST(req: NextRequest) {
const secret = req.headers.get('x-upload-secret')
const expectedSecret = process.env.UPLOAD_SECRET_KEY
if (!expectedSecret) {
return NextResponse.json(
{ success: false, error: 'Configuration serveur incomplète' },
{ status: 500 }
)
}
if (!secret || secret !== expectedSecret) {
return NextResponse.json(
{ success: false, error: 'Clé d\'authentification invalide' },
{ status: 401 }
)
}
let filename: string
let savedPath: string
let relPath: string
let folderName: string
try {
;({ filename, savedPath, relPath, folderName } = await parseUpload(req))
} catch (err) {
const message = err instanceof Error ? err.message : 'Erreur inconnue'
return NextResponse.json({ success: false, error: message }, { status: 400 })
}
try {
const { output } = runGitPush(folderName)
return NextResponse.json({
success: true,
filename,
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 ?? ''
return NextResponse.json(
{ success: false, error: `Fichier sauvegardé mais git push a échoué: ${message}`, gitError: stderr },
{ status: 500 }
)
}
}