Files
upload-gltf/app/api/upload/git/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

142 lines
4.6 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { join } from 'path'
import { mkdir, writeFile, readFile, unlink, rm } from 'fs/promises'
import { existsSync } from 'fs'
import { validateUploadSecret } from '@/lib/auth'
import { parseMultiUpload } from '@/lib/parse-upload'
import { compressWithBlender } from '@/lib/blender'
import { getRemoteFolder, pushAllToGitHub } from '@/lib/github'
import { buildCommitMessage } from '@/lib/commit-message'
import { classifyFileChanges } from '@/lib/diff-files'
import { TMP_DIR } from '@/lib/constants'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
/**
* POST /api/upload/git
* Upload files, compress with Blender, and push to GitHub via Octokit.
*/
export async function POST(req: NextRequest) {
// --- Auth ---
const authError = validateUploadSecret(req)
if (authError) return authError
// --- Parse all files ---
let folderName: string
let destination: string
let parsedFiles: Awaited<ReturnType<typeof parseMultiUpload>>['files']
try {
const parsed = await parseMultiUpload(req)
folderName = parsed.folderName
destination = parsed.destination
parsedFiles = parsed.files
} catch (err) {
const message = err instanceof Error ? err.message : 'Erreur inconnue'
return NextResponse.json({ success: false, error: message }, { status: 400 })
}
// --- Process files (compress model if possible) ---
const filesToPush: { path: string; contentBase64: string }[] = []
let modelFilename = ''
let compressed = false
let compressionError: string | undefined
const textureNames: string[] = []
for (const pf of parsedFiles) {
let content = pf.buffer
if (pf.isModel) {
modelFilename = pf.filename
// Write to /tmp for Blender compression
const tmpFolder = join(TMP_DIR, folderName)
await mkdir(tmpFolder, { recursive: true })
const tmpFilePath = join(tmpFolder, pf.filename)
await writeFile(tmpFilePath, pf.buffer)
const stem = pf.filename.replace(/\.[^.]+$/, '')
const compressedPath = join(tmpFolder, `${stem}_compressed.glb`)
try {
const result = await compressWithBlender(tmpFilePath, compressedPath)
if (result.success && existsSync(compressedPath)) {
content = await readFile(compressedPath)
compressed = true
await unlink(compressedPath).catch(() => {})
} else {
compressionError = result.error
}
} finally {
// Always cleanup temp files
await unlink(tmpFilePath).catch(() => {})
await rm(tmpFolder, { recursive: true, force: true }).catch(() => {})
}
} else {
textureNames.push(pf.filename)
}
filesToPush.push({
path: `public/models/${destination}/${folderName}/${pf.filename}`,
contentBase64: content.toString('base64'),
})
}
// --- Detect existing files and classify changes ---
const folderPath = `public/models/${destination}/${folderName}`
let remoteFileMap: Map<string, number>
try {
const remote = await getRemoteFolder(folderPath)
remoteFileMap = new Map(remote.files.map((f) => [f.name.toLowerCase(), f.size]))
} catch {
remoteFileMap = new Map()
}
const isReplace = remoteFileMap.size > 0
const { fileChanges, changedFilesToPush, deletedFileNames, deletePaths } =
classifyFileChanges(filesToPush, remoteFileMap, folderPath)
// If nothing changed, don't create an empty commit
if (changedFilesToPush.length === 0 && deletePaths.length === 0) {
return NextResponse.json({
success: true,
folderName,
filesCount: 0,
compressed,
compressionError: compressionError || undefined,
message: 'Aucun fichier modifie — rien a envoyer.',
})
}
// --- Build commit message ---
const commitMessage = buildCommitMessage(
folderName, destination, modelFilename, textureNames,
compressed, isReplace, fileChanges, deletedFileNames,
)
// --- Push all in one commit ---
try {
const { commitUrl } = await pushAllToGitHub(changedFilesToPush, deletePaths, commitMessage)
return NextResponse.json({
success: true,
folderName,
filesCount: changedFilesToPush.length,
compressed,
compressionError: compressionError || undefined,
message: `${changedFilesToPush.length} fichier(s) modifie(s) envoye(s) sur GitHub en un seul commit.`,
commitUrl,
})
} catch (err) {
const message = err instanceof Error ? err.message : 'Erreur GitHub inconnue'
return NextResponse.json(
{ success: false, error: `Push GitHub echoue: ${message}` },
{ status: 500 },
)
}
}