upatde: add docker for coolify
This commit is contained in:
+126
-27
@@ -1,6 +1,12 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { Octokit } from '@octokit/rest'
|
||||
import { extname, basename } from 'path'
|
||||
import { extname, basename, join } from 'path'
|
||||
import { mkdir, writeFile, readFile, unlink, rm } from 'fs/promises'
|
||||
import { existsSync } from 'fs'
|
||||
import { execFile } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
export const dynamic = 'force-dynamic'
|
||||
@@ -9,6 +15,8 @@ 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 TMP_DIR = join('/tmp', 'assets')
|
||||
|
||||
function sanitizeFilename(name: string): string {
|
||||
return basename(name)
|
||||
.replace(/[^a-zA-Z0-9._-]/g, '_')
|
||||
@@ -18,15 +26,14 @@ function sanitizeFilename(name: string): string {
|
||||
|
||||
function getOctokit(): Octokit {
|
||||
const token = process.env.GITHUB_TOKEN
|
||||
if (!token) throw new Error('GITHUB_TOKEN non configuré')
|
||||
if (!token) throw new Error('GITHUB_TOKEN non configure')
|
||||
return new Octokit({ auth: token })
|
||||
}
|
||||
|
||||
function parseRepoUrl(): { owner: string; repo: string } {
|
||||
const url = process.env.GIT_REPO_URL
|
||||
if (!url) throw new Error('GIT_REPO_URL non configuré')
|
||||
if (!url) throw new Error('GIT_REPO_URL non configure')
|
||||
|
||||
// Support formats: https://github.com/owner/repo.git, owner/repo, git@github.com:owner/repo.git
|
||||
const httpsMatch = url.match(/github\.com\/([^/]+)\/([^/.]+)/)
|
||||
const sshMatch = url.match(/github\.com:([^/]+)\/([^/.]+)/)
|
||||
const shortMatch = url.match(/^([^/]+)\/([^/]+)$/)
|
||||
@@ -37,6 +44,48 @@ function parseRepoUrl(): { owner: string; repo: string } {
|
||||
return { owner: match[1], repo: match[2] }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Blender Draco compression
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function compressWithBlender(
|
||||
inputPath: string,
|
||||
outputPath: string
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
const blenderPath = process.env.BLENDER_PATH || 'blender'
|
||||
const scriptPath = join(process.cwd(), 'scripts', 'compress.py')
|
||||
|
||||
if (!existsSync(scriptPath)) {
|
||||
return { success: false, error: 'scripts/compress.py introuvable' }
|
||||
}
|
||||
|
||||
try {
|
||||
await execFileAsync(blenderPath, [
|
||||
'--background',
|
||||
'--python', scriptPath,
|
||||
'--',
|
||||
'-i', inputPath,
|
||||
'-o', outputPath,
|
||||
'--draco-level', '7',
|
||||
'--texture-size', '512',
|
||||
'-q',
|
||||
], { timeout: 120_000 })
|
||||
|
||||
if (!existsSync(outputPath)) {
|
||||
return { success: false, error: 'Blender n\'a pas produit de fichier compresse' }
|
||||
}
|
||||
|
||||
return { success: true }
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
return { success: false, error: `Compression Blender echouee: ${message}` }
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Parse uploaded file from FormData
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function parseUpload(req: NextRequest) {
|
||||
const formData = await req.formData()
|
||||
const file = formData.get('file') as File | null
|
||||
@@ -45,14 +94,14 @@ async function parseUpload(req: NextRequest) {
|
||||
const textureName = formData.get('textureName') as string | null
|
||||
|
||||
if (!file || file.size === 0) {
|
||||
throw new Error('Aucun fichier reçu')
|
||||
throw new Error('Aucun fichier recu')
|
||||
}
|
||||
|
||||
const originalSafe = sanitizeFilename(file.name)
|
||||
const ext = extname(originalSafe).toLowerCase()
|
||||
|
||||
if (!ALL_ALLOWED_EXTENSIONS.has(ext)) {
|
||||
throw new Error(`Extension non autorisée: "${ext}"`)
|
||||
throw new Error(`Extension non autorisee: "${ext}"`)
|
||||
}
|
||||
|
||||
const safeFolderName = sanitizeFilename(folderName).replace(/[^a-zA-Z0-9-_]/g, '-')
|
||||
@@ -64,23 +113,26 @@ async function parseUpload(req: NextRequest) {
|
||||
filename = originalSafe
|
||||
}
|
||||
|
||||
const isModel = MODEL_EXTENSIONS.has(ext)
|
||||
const buffer = Buffer.from(await file.arrayBuffer())
|
||||
const content = buffer.toString('base64')
|
||||
const path = `public/assets/${safeFolderName}/${filename}`
|
||||
|
||||
return { filename, content, path, folderName: safeFolderName }
|
||||
return { filename, buffer, safeFolderName, isModel }
|
||||
}
|
||||
|
||||
async function pushToGitHub(
|
||||
// ---------------------------------------------------------------------------
|
||||
// Push a single file to GitHub via the API
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function pushFileToGitHub(
|
||||
filePath: string,
|
||||
content: string,
|
||||
contentBase64: string,
|
||||
folderName: string
|
||||
): Promise<{ commitUrl: string }> {
|
||||
const octokit = getOctokit()
|
||||
const { owner, repo } = parseRepoUrl()
|
||||
const branch = process.env.GIT_BRANCH ?? 'main'
|
||||
|
||||
// 1. Get the current commit SHA on the branch
|
||||
// 1. Get latest commit on branch
|
||||
const { data: ref } = await octokit.git.getRef({
|
||||
owner,
|
||||
repo,
|
||||
@@ -88,22 +140,22 @@ async function pushToGitHub(
|
||||
})
|
||||
const latestCommitSha = ref.object.sha
|
||||
|
||||
// 2. Get the tree of the latest commit
|
||||
// 2. Get that commit's tree
|
||||
const { data: commit } = await octokit.git.getCommit({
|
||||
owner,
|
||||
repo,
|
||||
commit_sha: latestCommitSha,
|
||||
})
|
||||
|
||||
// 3. Create a blob for the file
|
||||
// 3. Create blob
|
||||
const { data: blob } = await octokit.git.createBlob({
|
||||
owner,
|
||||
repo,
|
||||
content,
|
||||
content: contentBase64,
|
||||
encoding: 'base64',
|
||||
})
|
||||
|
||||
// 4. Create a new tree with the file added
|
||||
// 4. Create tree
|
||||
const { data: newTree } = await octokit.git.createTree({
|
||||
owner,
|
||||
repo,
|
||||
@@ -118,7 +170,7 @@ async function pushToGitHub(
|
||||
],
|
||||
})
|
||||
|
||||
// 5. Create a new commit
|
||||
// 5. Create commit
|
||||
const timestamp = new Date().toISOString()
|
||||
const { data: newCommit } = await octokit.git.createCommit({
|
||||
owner,
|
||||
@@ -128,7 +180,7 @@ async function pushToGitHub(
|
||||
parents: [latestCommitSha],
|
||||
})
|
||||
|
||||
// 6. Update the branch reference
|
||||
// 6. Update branch ref
|
||||
await octokit.git.updateRef({
|
||||
owner,
|
||||
repo,
|
||||
@@ -139,49 +191,96 @@ async function pushToGitHub(
|
||||
return { commitUrl: newCommit.html_url }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// POST handler
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
// --- Auth ---
|
||||
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 (UPLOAD_SECRET_KEY manquant)' },
|
||||
{ success: false, error: 'Configuration serveur incomplete (UPLOAD_SECRET_KEY manquant)' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
if (!secret || secret !== expectedSecret) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Clé d'authentification invalide" },
|
||||
{ success: false, error: "Cle d'authentification invalide" },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
// --- Parse upload ---
|
||||
let filename: string
|
||||
let content: string
|
||||
let path: string
|
||||
let folderName: string
|
||||
let buffer: Buffer
|
||||
let safeFolderName: string
|
||||
let isModel: boolean
|
||||
|
||||
try {
|
||||
;({ filename, content, path, folderName } = await parseUpload(req))
|
||||
;({ filename, buffer, safeFolderName, isModel } = await parseUpload(req))
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Erreur inconnue'
|
||||
return NextResponse.json({ success: false, error: message }, { status: 400 })
|
||||
}
|
||||
|
||||
// --- Write to /tmp ---
|
||||
const tmpFolder = join(TMP_DIR, safeFolderName)
|
||||
await mkdir(tmpFolder, { recursive: true })
|
||||
const tmpFilePath = join(tmpFolder, filename)
|
||||
await writeFile(tmpFilePath, buffer)
|
||||
|
||||
let contentToUpload: Buffer = buffer
|
||||
let compressed = false
|
||||
let compressionError: string | undefined
|
||||
|
||||
// --- Compress model with Blender (if available) ---
|
||||
if (isModel) {
|
||||
const stem = filename.replace(/\.[^.]+$/, '')
|
||||
const compressedPath = join(tmpFolder, `${stem}_compressed.glb`)
|
||||
|
||||
const result = await compressWithBlender(tmpFilePath, compressedPath)
|
||||
|
||||
if (result.success && existsSync(compressedPath)) {
|
||||
contentToUpload = await readFile(compressedPath)
|
||||
compressed = true
|
||||
// Clean up compressed temp file
|
||||
await unlink(compressedPath).catch(() => {})
|
||||
} else {
|
||||
// Blender not available or failed — push original
|
||||
compressionError = result.error
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up original temp file
|
||||
await unlink(tmpFilePath).catch(() => {})
|
||||
// Clean up folder if empty
|
||||
await rm(tmpFolder, { recursive: true, force: true }).catch(() => {})
|
||||
|
||||
// --- Push to GitHub ---
|
||||
const gitPath = `public/assets/${safeFolderName}/${filename}`
|
||||
const contentBase64 = contentToUpload.toString('base64')
|
||||
|
||||
try {
|
||||
const { commitUrl } = await pushToGitHub(path, content, folderName)
|
||||
const { commitUrl } = await pushFileToGitHub(gitPath, contentBase64, safeFolderName)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
filename,
|
||||
message: `"${filename}" ajouté au dossier "${folderName}" et poussé sur GitHub.`,
|
||||
compressed,
|
||||
compressionError: compressionError || undefined,
|
||||
message: compressed
|
||||
? `"${filename}" compresse avec Draco et pousse sur GitHub.`
|
||||
: `"${filename}" pousse sur GitHub${compressionError ? ' (sans compression: ' + compressionError + ')' : ''}.`,
|
||||
commitUrl,
|
||||
})
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Erreur GitHub inconnue'
|
||||
return NextResponse.json(
|
||||
{ success: false, error: `Push GitHub échoué: ${message}` },
|
||||
{ success: false, error: `Push GitHub echoue: ${message}` },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user