Files
upload-gltf/app/api/upload/drive/route.ts
T

90 lines
2.7 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { validateUploadSecret } from '@/lib/auth'
import { readStagedOriginalFiles } from '@/lib/upload-staging'
import {
mkdirRecursive,
moveFolder,
uploadFile,
findNextVersion,
} from '@/lib/nextcloud'
import { acquireUploadLock, releaseUploadLock } from '@/lib/upload-lock'
import { parseDriveRequestBody } from '@/lib/upload-request'
import { getErrorMessage } from '@/lib/guards'
import type { DriveAction } from '@/lib/types'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
export async function POST(req: NextRequest) {
const authError = validateUploadSecret(req)
if (authError) return authError
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 },
)
}
let folderName: string
let parsedFiles: Awaited<ReturnType<typeof readStagedOriginalFiles>>['files']
let action: DriveAction
try {
const body: unknown = await req.json()
const parsedBody = parseDriveRequestBody(body)
action = parsedBody.action
const stagingId = parsedBody.stagingId
const staged = await readStagedOriginalFiles(stagingId)
folderName = staged.folderName
parsedFiles = staged.files
} catch (err) {
const message = getErrorMessage(err)
return NextResponse.json({ success: false, error: message }, { status: 400 })
}
if (!acquireUploadLock(folderName)) {
return NextResponse.json(
{ success: false, error: 'Un upload est deja en cours pour ce dossier. Patientez quelques secondes.' },
{ status: 409 },
)
}
const basePath = process.env.NEXTCLOUD_BASE_PATH || 'Models'
const vfFolderPath = `${basePath}/VF/${folderName}`
try {
if (action === 'replace') {
const nextVersion = await findNextVersion(basePath, folderName)
await mkdirRecursive(`${basePath}/${nextVersion}`)
await moveFolder(vfFolderPath, `${basePath}/${nextVersion}/${folderName}`)
await mkdirRecursive(vfFolderPath)
} else {
await mkdirRecursive(vfFolderPath)
}
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 = getErrorMessage(err, 'Erreur Nextcloud inconnue')
return NextResponse.json(
{ success: false, error: `Drive echoue: ${message}` },
{ status: 500 },
)
} finally {
releaseUploadLock(folderName)
}
}