init du repo

This commit is contained in:
Tom Boullay
2026-04-03 10:22:24 +02:00
parent 929b1075d4
commit a730946ad2
14 changed files with 3224 additions and 0 deletions
+89
View File
@@ -0,0 +1,89 @@
# =============================================================================
# Asset Bridge 3D — Dockerfile optimisé pour Coolify
# Node 20 Alpine · Git LFS · SSH · Multi-stage build
# =============================================================================
# ─── Stage 1 : Dépendances ───────────────────────────────────────────────────
FROM node:20-alpine AS deps
# Outils système nécessaires : git, git-lfs, openssh (pour push SSH)
RUN apk add --no-cache \
git \
git-lfs \
openssh-client \
ca-certificates
# Initialiser Git LFS globalement
RUN git lfs install --system
WORKDIR /app
# Copier uniquement les fichiers de dépendances pour profiter du cache Docker
COPY package.json package-lock.json* ./
RUN npm ci --ignore-scripts
# ─── Stage 2 : Build ─────────────────────────────────────────────────────────
FROM node:20-alpine AS builder
RUN apk add --no-cache git git-lfs openssh-client ca-certificates
RUN git lfs install --system
WORKDIR /app
# Récupérer node_modules depuis le stage deps
COPY --from=deps /app/node_modules ./node_modules
COPY . .
# Build Next.js en mode production
ENV NEXT_TELEMETRY_DISABLED=1
ENV NODE_ENV=production
RUN npm run build
# ─── Stage 3 : Production ────────────────────────────────────────────────────
FROM node:20-alpine AS runner
LABEL maintainer="Asset Bridge 3D"
LABEL description="Interface d'upload 3D sécurisée avec Git LFS"
# Outils runtime : git, git-lfs, openssh (pour le git push au runtime)
RUN apk add --no-cache \
git \
git-lfs \
openssh-client \
ca-certificates \
tini
# Initialiser Git LFS au niveau système
RUN git lfs install --system
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
# Créer un utilisateur non-root pour la sécurité
# Note : on garde root pour les opérations git/SSH en contexte Coolify
# Si vous souhaitez un user non-root, adaptez les permissions SSH en conséquence
# Copier les artefacts de build
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public
COPY --from=builder /app/.gitattributes ./.gitattributes
# S'assurer que le dossier models existe (sera écrasé par le volume Coolify)
RUN mkdir -p ./public/models
# Copier le script d'entrée
COPY docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
EXPOSE 3000
# Utiliser tini comme PID 1 pour une gestion correcte des signaux
ENTRYPOINT ["/sbin/tini", "--", "/docker-entrypoint.sh"]
CMD ["node", "server.js"]
+211
View File
@@ -0,0 +1,211 @@
import { NextRequest, NextResponse } from 'next/server'
import { writeFileSync, mkdirSync } from 'fs'
import { join, extname, basename } from 'path'
import { execSync } from 'child_process'
// Forcer le runtime Node.js (nécessaire pour fs, child_process)
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
// Formats autorisés par type
const MODEL_EXTENSIONS = new Set(['.glb', '.gltf', '.fbx'])
const TEXTURE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.ktx2'])
const ALL_ALLOWED_EXTENSIONS = new Set([...MODEL_EXTENSIONS, ...TEXTURE_EXTENSIONS])
const MODELS_DIR = join(process.cwd(), 'public', 'models')
const TEXTURES_DIR = join(process.cwd(), 'public', 'textures')
// ─────────────────────────────────────────────
// Utilitaire : sanitiser le nom de fichier
// ─────────────────────────────────────────────
function sanitizeFilename(name: string): string {
return basename(name)
.replace(/[^a-zA-Z0-9._-]/g, '_')
.replace(/_{2,}/g, '_')
.toLowerCase()
}
// ─────────────────────────────────────────────
// 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 file = formData.get('file') as File | null
const assetName = (formData.get('assetName') as string | null)?.trim()
if (!file || file.size === 0) {
throw new Error('Aucun fichier reçu dans la requête')
}
const originalSafe = sanitizeFilename(file.name)
const ext = extname(originalSafe).toLowerCase()
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`)
}
// Renommer avec le nom fourni par le designer si disponible
const baseName = assetName
? sanitizeFilename(assetName).replace(/\.[^.]+$/, '') // retirer extension si présente
: originalSafe.replace(/\.[^.]+$/, '')
const filename = `${baseName}${ext}`
const isTexture = TEXTURE_EXTENSIONS.has(ext)
const destDir = isTexture ? TEXTURES_DIR : MODELS_DIR
const relPath = join('public', isTexture ? 'textures' : 'models', filename)
mkdirSync(destDir, { recursive: true })
const savedPath = join(destDir, filename)
const buffer = Buffer.from(await file.arrayBuffer())
writeFileSync(savedPath, buffer)
return { filename, savedPath, relPath }
}
// ─────────────────────────────────────────────
// Utilitaire : exécuter la séquence git
// ─────────────────────────────────────────────
function runGitPush(filename: string, relPath: 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: 60_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',
},
}
// S'assurer que le repo est initialisé et que le remote est configuré
try {
execSync('git rev-parse --git-dir', { cwd: process.cwd(), stdio: 'ignore' })
} catch {
// Pas encore de repo git — initialiser
execSync('git init && git lfs install', { ...execOpts, stdio: 'pipe' })
if (repoUrl) {
execSync(`git remote add origin "${repoUrl}"`, { ...execOpts, stdio: 'pipe' })
}
// Récupérer l'historique distant si possible
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' })
}
}
// Mettre à jour l'URL du remote avec le token (au cas où elle aurait changé)
if (repoUrl) {
execSync(`git remote set-url origin "${repoUrl}"`, { ...execOpts, stdio: 'pipe' })
}
const timestamp = new Date().toISOString()
let output = ''
// Sync avec le remote avant de committer
output += execSync(`git fetch origin ${branch}`, execOpts)
output += execSync(`git reset --hard origin/${branch}`, execOpts)
// git add
output += execSync(`git add "${relPath}"`, execOpts)
// git commit — ignoré si rien à committer (fichier identique)
try {
output += execSync(`git commit -m "Design Update: ${filename} [${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 — fichier identique]\n'
}
// git push
output += execSync(`git push origin ${branch}`, execOpts)
return { output }
}
// ─────────────────────────────────────────────
// POST /api/upload
// ─────────────────────────────────────────────
export async function POST(req: NextRequest) {
// 1. Authentification
const secret = req.headers.get('x-upload-secret')
const expectedSecret = process.env.UPLOAD_SECRET_KEY
if (!expectedSecret) {
console.error('[upload] UPLOAD_SECRET_KEY non configurée côté serveur')
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 }
)
}
// 2. Parse & écriture disque
let filename: string
let savedPath: string
let relPath: string
try {
;({ filename, savedPath, relPath } = await parseUpload(req))
console.log(`[upload] Fichier reçu et sauvegardé : ${savedPath}`)
} catch (err) {
const message = err instanceof Error ? err.message : 'Erreur inconnue lors de l\'upload'
console.error('[upload] Erreur parsing :', message)
return NextResponse.json(
{ success: false, error: message },
{ status: 400 }
)
}
// 3. Séquence git push
try {
const { output } = runGitPush(filename, relPath)
console.log(`[upload] Git push réussi pour ${filename}`)
return NextResponse.json({
success: true,
filename,
message: `"${filename}" sauvegardé et poussé sur Git avec succès.`,
gitOutput: output,
})
} catch (err) {
const message = err instanceof Error ? err.message : 'Erreur git inconnue'
const stderr = (err as NodeJS.ErrnoException & { stderr?: string })?.stderr ?? ''
console.error('[upload] Erreur git push :', message, stderr)
return NextResponse.json(
{
success: false,
filename,
error: `Fichier sauvegardé mais git push a échoué : ${message}`,
gitError: stderr,
},
{ status: 500 }
)
}
}
+25
View File
@@ -0,0 +1,25 @@
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
html {
font-family: 'Inter', system-ui, sans-serif;
}
body {
@apply bg-surface-soft text-gray-800 antialiased;
}
}
@layer utilities {
.text-gradient {
@apply bg-gradient-to-r from-brand-500 to-rose-400 bg-clip-text text-transparent;
}
.bg-gradient-brand {
@apply bg-gradient-to-r from-brand-500 to-rose-400;
}
}
+19
View File
@@ -0,0 +1,19 @@
import type { Metadata } from 'next'
import './globals.css'
export const metadata: Metadata = {
title: 'Asset Bridge 3D',
description: 'Interface de dépôt sécurisé pour fichiers 3D (.glb, .gltf, .fbx)',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="fr">
<body>{children}</body>
</html>
)
}
+34
View File
@@ -0,0 +1,34 @@
import UploadZone from '@/components/UploadZone'
export default function Home() {
return (
<main className="min-h-screen bg-surface-soft flex flex-col items-center justify-center p-6">
{/* Header */}
<div className="w-full max-w-2xl mb-10 text-center">
<div className="inline-flex items-center gap-2 mb-4 px-3 py-1 rounded-full bg-brand-100 border border-brand-200 text-brand-600 text-xs font-medium uppercase tracking-widest">
<span className="w-1.5 h-1.5 rounded-full bg-brand-500 animate-pulse" />
Git LFS · Déploiement continu
</div>
<h1 className="text-4xl font-bold tracking-tight mb-3">
<span className="text-gradient">Asset Bridge 3D</span>
</h1>
<p className="text-gray-500 text-base leading-relaxed">
Déposez vos fichiers 3D ils seront automatiquement versionnés
<br />et poussés sur le dépôt GitHub via Git LFS.
</p>
</div>
{/* Upload Zone */}
<UploadZone />
{/* Footer */}
<footer className="mt-10 text-gray-400 text-xs text-center">
Modèles : <span className="font-mono text-gray-500">.glb · .gltf · .fbx</span>
<span className="mx-2">·</span>
Textures : <span className="font-mono text-gray-500">.png · .jpg · .webp · .ktx2</span>
<span className="mx-2">·</span>
Taille max : <span className="font-mono text-gray-500">2 GB</span>
</footer>
</main>
)
}
+428
View File
@@ -0,0 +1,428 @@
'use client'
import { useCallback, useRef, useState } from 'react'
import { useDropzone, FileRejection } from 'react-dropzone'
// ─────────────────────────────────────────────
// Types
// ─────────────────────────────────────────────
type FileStatus = 'pending' | 'uploading' | 'success' | 'error'
interface FileEntry {
file: File
status: FileStatus
progress: number
error?: string
filename?: string
}
interface UploadResult {
success: boolean
filename?: string
message?: string
error?: string
gitOutput?: string
gitError?: string
}
// ─────────────────────────────────────────────
// Formats acceptés
// ─────────────────────────────────────────────
const ACCEPTED_FORMATS = {
'model/gltf-binary': ['.glb'],
'model/gltf+json': ['.gltf'],
'application/octet-stream': ['.fbx'],
'image/png': ['.png'],
'image/jpeg': ['.jpg', '.jpeg'],
'image/webp': ['.webp'],
'image/ktx2': ['.ktx2'],
}
const MODEL_EXTENSIONS = ['.glb', '.gltf', '.fbx']
const TEXTURE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp', '.ktx2']
const ALL_EXTENSIONS = [...MODEL_EXTENSIONS, ...TEXTURE_EXTENSIONS]
function formatBytes(bytes: number): string {
if (bytes === 0) return '0 B'
const k = 1024
const sizes = ['B', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`
}
function getFileType(filename: string): 'model' | 'texture' | null {
const ext = filename.slice(filename.lastIndexOf('.')).toLowerCase()
if (MODEL_EXTENSIONS.includes(ext)) return 'model'
if (TEXTURE_EXTENSIONS.includes(ext)) return 'texture'
return null
}
function uploadSingleFile(
file: File,
secret: string,
assetName: string,
onProgress: (pct: number) => void,
xhrRef: { current: XMLHttpRequest | null }
): Promise<UploadResult> {
return new Promise((resolve) => {
const formData = new FormData()
formData.append('file', file)
if (assetName.trim()) formData.append('assetName', assetName.trim())
const xhr = new XMLHttpRequest()
xhrRef.current = xhr
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) onProgress(Math.round((e.loaded / e.total) * 100))
}
xhr.onload = () => {
try {
resolve(JSON.parse(xhr.responseText))
} catch {
resolve({ success: false, error: `Réponse inattendue (HTTP ${xhr.status})` })
}
}
xhr.onerror = () => resolve({ success: false, error: 'Erreur réseau.' })
xhr.onabort = () => resolve({ success: false, error: 'Annulé.' })
xhr.open('POST', '/api/upload')
xhr.setRequestHeader('x-upload-secret', secret.trim())
xhr.send(formData)
})
}
// ─────────────────────────────────────────────
// Composant principal
// ─────────────────────────────────────────────
export default function UploadZone() {
const [files, setFiles] = useState<FileEntry[]>([])
const [isUploading, setIsUploading] = useState(false)
const [secret, setSecret] = useState('')
const [secretVisible, setSecretVisible] = useState(false)
const [assetName, setAssetName] = useState('')
const [globalError, setGlobalError] = useState<string | null>(null)
const xhrRef = useRef<XMLHttpRequest | null>(null)
const updateFile = (index: number, patch: Partial<FileEntry>) => {
setFiles((prev) => prev.map((f, i) => i === index ? { ...f, ...patch } : f))
}
// ── Upload séquentiel de tous les fichiers ──
const handleUpload = useCallback(async () => {
if (!secret.trim()) {
setGlobalError('Veuillez saisir la clé d\'accès avant d\'uploader.')
return
}
if (files.length === 0) return
setIsUploading(true)
setGlobalError(null)
for (let i = 0; i < files.length; i++) {
if (files[i].status === 'success') continue
updateFile(i, { status: 'uploading', progress: 0, error: undefined })
const result = await uploadSingleFile(
files[i].file,
secret,
assetName,
(pct) => updateFile(i, { progress: pct }),
xhrRef
)
updateFile(i, {
status: result.success ? 'success' : 'error',
progress: result.success ? 100 : 0,
error: result.success ? undefined : result.error,
filename: result.filename,
})
}
setIsUploading(false)
}, [files, secret, assetName])
// ── Annuler le fichier en cours ──
const handleCancel = () => { xhrRef.current?.abort() }
// ── Supprimer un fichier de la liste ──
const removeFile = (index: number) => {
setFiles((prev) => prev.filter((_, i) => i !== index))
}
// ── Reset total ──
const handleReset = () => {
setFiles([])
setGlobalError(null)
setIsUploading(false)
}
// ── react-dropzone ──
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')
? `Format non supporté. Utilisez : ${ALL_EXTENSIONS.join(', ')}`
: codes.includes('file-too-large')
? 'Fichier trop volumineux (max 2 GB)'
: `Fichier rejeté : ${codes}`
)
return
}
setGlobalError(null)
setFiles((prev) => {
// Dédoublonner par nom
const existingNames = new Set(prev.map((f) => f.file.name))
const newEntries: FileEntry[] = acceptedFiles
.filter((f) => !existingNames.has(f.name))
.map((file) => ({ file, status: 'pending', progress: 0 }))
return [...prev, ...newEntries]
})
}, [])
const { getRootProps, getInputProps, isDragActive, isDragReject } = useDropzone({
onDrop,
accept: ACCEPTED_FORMATS,
maxSize: 2 * 1024 * 1024 * 1024,
disabled: isUploading,
multiple: true,
})
const allDone = files.length > 0 && files.every((f) => f.status === 'success')
const hasErrors = files.some((f) => f.status === 'error')
// ─────────────────────────────────────────────
// Render
// ─────────────────────────────────────────────
return (
<div className="w-full max-w-2xl space-y-4">
{/* Clé d'accès */}
<div className="space-y-1.5">
<label className="block text-sm font-medium text-gray-700">Clé d&apos;accès</label>
<div className="relative">
<input
type={secretVisible ? 'text' : 'password'}
value={secret}
onChange={(e) => setSecret(e.target.value)}
placeholder="Saisir la clé secrète…"
disabled={isUploading}
className="w-full bg-white border border-surface-border rounded-xl px-4 py-2.5 pr-12
text-gray-800 placeholder-gray-300 text-sm shadow-soft
focus:outline-none focus:ring-2 focus:ring-brand-300 focus:border-brand-400
disabled:opacity-50 disabled:cursor-not-allowed transition"
/>
<button
type="button"
onClick={() => setSecretVisible((v) => !v)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-brand-500 transition"
tabIndex={-1}
>
{secretVisible ? (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
</svg>
) : (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
</svg>
)}
</button>
</div>
</div>
{/* Nom de l'asset */}
<div className="space-y-1.5">
<label className="block text-sm font-medium text-gray-700">
Nom de l&apos;asset
<span className="text-gray-400 font-normal ml-2"> nom commun pour le modèle et la texture</span>
</label>
<input
type="text"
value={assetName}
onChange={(e) => setAssetName(e.target.value)}
placeholder="ex : clocher, sol_pierre, mur_brique…"
disabled={isUploading}
className="w-full bg-white border border-surface-border rounded-xl px-4 py-2.5
text-gray-800 placeholder-gray-300 text-sm font-mono shadow-soft
focus:outline-none focus:ring-2 focus:ring-brand-300 focus:border-brand-400
disabled:opacity-50 disabled:cursor-not-allowed transition"
/>
</div>
{/* Dropzone */}
<div
{...getRootProps()}
className={`
relative border-2 border-dashed rounded-2xl p-8 text-center cursor-pointer transition-all duration-200 bg-white shadow-soft
${isUploading ? 'cursor-not-allowed opacity-60 border-surface-border' : ''}
${isDragReject ? 'border-red-400 bg-red-50' : ''}
${isDragActive && !isDragReject ? 'border-brand-400 bg-brand-50 scale-[1.01]' : ''}
${!isDragActive && !isDragReject && !isUploading
? 'border-surface-border hover:border-brand-300 hover:bg-brand-50/40'
: ''}
`}
>
<input {...getInputProps()} />
<div className="flex justify-center mb-3">
<div className={`w-12 h-12 rounded-full flex items-center justify-center transition
${isDragActive ? 'bg-brand-200' : 'bg-brand-100'}`}>
<svg className={`w-6 h-6 transition ${isDragActive ? 'text-brand-600' : 'text-brand-500'}`}
fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
<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" />
</svg>
</div>
</div>
{isDragReject ? (
<p className="text-sm font-medium text-red-500">Format non supporté</p>
) : isDragActive ? (
<p className="text-sm font-medium text-brand-600">Relâchez pour ajouter</p>
) : (
<>
<p className="text-sm font-medium text-gray-600">
Glissez vos fichiers ici
<span className="text-gray-400 font-normal"> ou cliquez pour parcourir</span>
</p>
<p className="text-xs text-gray-400 mt-1">
Modèles : .glb, .gltf, .fbx · Textures : .png, .jpg, .webp, .ktx2
</p>
</>
)}
</div>
{/* Erreur globale */}
{globalError && (
<p className="text-xs text-red-500 text-center">{globalError}</p>
)}
{/* Liste des fichiers */}
{files.length > 0 && (
<div className="space-y-2">
{files.map((entry, i) => {
const type = getFileType(entry.file.name)
return (
<div key={`${entry.file.name}-${i}`}
className="flex items-center gap-3 bg-white border border-surface-border rounded-xl px-4 py-3 shadow-soft">
{/* Icône statut */}
<div className="shrink-0">
{entry.status === 'success' ? (
<div className="w-8 h-8 rounded-full bg-green-100 flex items-center justify-center">
<svg className="w-4 h-4 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
</svg>
</div>
) : entry.status === 'error' ? (
<div className="w-8 h-8 rounded-full bg-red-100 flex items-center justify-center">
<svg className="w-4 h-4 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</div>
) : entry.status === 'uploading' ? (
<div className="w-8 h-8 rounded-full bg-brand-100 flex items-center justify-center">
<svg className="w-4 h-4 text-brand-500 animate-spin" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
</svg>
</div>
) : (
<div className="w-8 h-8 rounded-full bg-surface-muted flex items-center justify-center">
<svg className="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
</svg>
</div>
)}
</div>
{/* Infos fichier */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-sm text-gray-700 font-mono truncate">{entry.file.name}</span>
{type && (
<span className={`shrink-0 text-xs px-1.5 py-0.5 rounded-full
${type === 'model' ? 'bg-brand-100 text-brand-600' : 'bg-rose-100 text-rose-500'}`}>
{type === 'model' ? '3D' : 'Texture'}
</span>
)}
</div>
<div className="flex items-center gap-2 mt-0.5">
<span className="text-xs text-gray-400">{formatBytes(entry.file.size)}</span>
{entry.status === 'error' && entry.error && (
<span className="text-xs text-red-400 truncate">{entry.error}</span>
)}
{entry.status === 'success' && entry.filename && (
<span className="text-xs text-green-500 font-mono">{entry.filename}</span>
)}
</div>
{/* Barre de progression individuelle */}
{entry.status === 'uploading' && (
<div className="mt-1.5 w-full h-1 bg-brand-100 rounded-full overflow-hidden">
<div
className="h-full bg-gradient-brand rounded-full transition-all duration-200"
style={{ width: `${entry.progress}%` }}
/>
</div>
)}
</div>
{/* Supprimer */}
{entry.status !== 'uploading' && (
<button
onClick={() => removeFile(i)}
className="shrink-0 text-gray-300 hover:text-red-400 transition"
>
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
</div>
)
})}
</div>
)}
{/* Boutons d'action */}
<div className="flex gap-3">
{!isUploading && files.some((f) => f.status === 'pending' || f.status === 'error') && (
<button
onClick={handleUpload}
className="flex-1 bg-gradient-brand hover:opacity-90 text-white font-medium text-sm
py-2.5 px-6 rounded-xl shadow-soft transition-opacity duration-150
focus:outline-none focus:ring-2 focus:ring-brand-300"
>
Uploader {files.filter(f => f.status !== 'success').length > 1
? `${files.filter(f => f.status !== 'success').length} fichiers`
: 'le fichier'} &amp; Pousser sur Git
</button>
)}
{isUploading && (
<button
onClick={handleCancel}
className="flex-1 bg-surface-muted hover:bg-brand-100 text-gray-600 font-medium text-sm
py-2.5 px-6 rounded-xl border border-surface-border transition-colors duration-150"
>
Annuler le fichier en cours
</button>
)}
{(allDone || hasErrors) && !isUploading && (
<button
onClick={handleReset}
className="flex-1 bg-surface-muted hover:bg-brand-100 text-gray-600 font-medium text-sm
py-2.5 px-6 rounded-xl border border-surface-border transition-colors duration-150"
>
{allDone ? 'Tout effacer' : 'Réessayer'}
</button>
)}
</div>
</div>
)
}
+95
View File
@@ -0,0 +1,95 @@
#!/bin/sh
# =============================================================================
# Asset Bridge 3D — Entrypoint Docker
# Configure Git, SSH et LFS au démarrage du container
# =============================================================================
set -e
echo "[entrypoint] Démarrage d'Asset Bridge 3D..."
# ─── 1. Configurer l'identité Git ────────────────────────────────────────────
git config --global user.email "${GIT_USER_EMAIL:-deploy@asset-bridge.local}"
git config --global user.name "${GIT_USER_NAME:-Asset Bridge Bot}"
git config --global init.defaultBranch "${GIT_BRANCH:-main}"
# Autoriser le dossier /app comme safe.directory (requis depuis Git 2.35.2)
git config --global --add safe.directory /app
echo "[entrypoint] Identité Git configurée."
# ─── 2. Injecter la clé SSH privée ───────────────────────────────────────────
if [ -n "$SSH_PRIVATE_KEY" ]; then
mkdir -p /root/.ssh
chmod 700 /root/.ssh
# Écrire la clé — Coolify préserve les vrais sauts de ligne en multiline
# On strip les \r éventuels (Windows CRLF) pour éviter "error in libcrypto"
printf '%s\n' "$SSH_PRIVATE_KEY" | tr -d '\r' > /root/.ssh/id_rsa
chmod 600 /root/.ssh/id_rsa
# Ajouter github.com aux known_hosts pour éviter l'invite interactive
ssh-keyscan -t rsa,ecdsa,ed25519 github.com >> /root/.ssh/known_hosts 2>/dev/null
chmod 644 /root/.ssh/known_hosts
echo "[entrypoint] Clé SSH configurée et github.com ajouté aux known_hosts."
else
echo "[entrypoint] AVERTISSEMENT : SSH_PRIVATE_KEY non définie — git push SSH ne fonctionnera pas."
fi
# ─── 3. Initialiser Git LFS dans le dossier de travail ───────────────────────
cd /app
git lfs install --local 2>/dev/null || true
# ─── 4. Initialiser le repo Git si nécessaire ────────────────────────────────
# Le volume persistant Coolify monte /app/public/models
# Si le repo n'est pas initialisé, on le fait ici
if [ ! -d ".git" ]; then
echo "[entrypoint] Initialisation du dépôt Git local..."
git init
git lfs install
# Copier .gitattributes si pas déjà présent
if [ -f ".gitattributes" ]; then
echo "[entrypoint] .gitattributes détecté."
fi
if [ -n "$GIT_REPO_URL" ]; then
git remote add origin "$GIT_REPO_URL"
echo "[entrypoint] Remote origin configuré : $GIT_REPO_URL"
BRANCH="${GIT_BRANCH:-main}"
# Tenter de récupérer l'historique distant
if git fetch origin "$BRANCH" 2>/dev/null; then
git checkout -b "$BRANCH" --track "origin/$BRANCH" 2>/dev/null || \
git checkout "$BRANCH" 2>/dev/null || true
echo "[entrypoint] Branch '$BRANCH' récupérée depuis origin."
else
git checkout -b "$BRANCH" 2>/dev/null || true
echo "[entrypoint] Branch locale '$BRANCH' créée."
fi
else
echo "[entrypoint] AVERTISSEMENT : GIT_REPO_URL non définie — les pushes Git échoueront."
git checkout -b "${GIT_BRANCH:-main}" 2>/dev/null || true
fi
echo "[entrypoint] Dépôt Git initialisé."
else
echo "[entrypoint] Dépôt Git existant détecté."
# Vérifier que le remote origin est configuré
if [ -n "$GIT_REPO_URL" ]; then
if ! git remote get-url origin >/dev/null 2>&1; then
git remote add origin "$GIT_REPO_URL"
echo "[entrypoint] Remote origin ajouté : $GIT_REPO_URL"
fi
fi
fi
echo "[entrypoint] Configuration terminée. Lancement de l'application..."
# ─── 5. Lancer la commande principale ────────────────────────────────────────
exec "$@"
+16
View File
@@ -0,0 +1,16 @@
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
// Output standalone pour Docker (inclut uniquement les fichiers nécessaires)
output: 'standalone',
// Augmenter la taille max des réponses pour les gros fichiers
// Note : la limite d'upload est gérée par le proxy Nginx (client_max_body_size 500M dans Coolify)
experimental: {
serverActions: {
bodySizeLimit: '2gb',
},
},
}
export default nextConfig
+2184
View File
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
{
"name": "asset-bridge-3d",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "^16.1.7",
"react": "^18.3.0",
"react-dom": "^18.3.0",
"react-dropzone": "^14.2.3"
},
"devDependencies": {
"@types/busboy": "^1.5.4",
"@types/node": "^20.14.0",
"@types/react": "^18.3.0",
"@types/react-dom": "^18.3.0",
"autoprefixer": "^10.4.19",
"postcss": "^8.4.38",
"tailwindcss": "^3.4.4",
"typescript": "^5.4.5"
}
}
+6
View File
@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
View File
+49
View File
@@ -0,0 +1,49 @@
import type { Config } from 'tailwindcss'
const config: Config = {
content: [
'./pages/**/*.{js,ts,jsx,tsx,mdx}',
'./components/**/*.{js,ts,jsx,tsx,mdx}',
'./app/**/*.{js,ts,jsx,tsx,mdx}',
],
theme: {
extend: {
colors: {
brand: {
50: '#FAF5FF',
100: '#EDE9FE',
200: '#DDD6FE',
300: '#C4B5FD',
400: '#A78BFA',
500: '#7C5CFC', // violet principal (image)
600: '#6D28D9',
700: '#5B21B6',
900: '#2E1065',
},
// Rose/magenta (dégradé image)
rose: {
300: '#FDA4C4',
400: '#F472B6',
500: '#EC4899',
},
surface: {
DEFAULT: '#FFFFFF',
soft: '#F9F5FF', // fond global lavande très clair
muted: '#F3EEFF', // fond carte/panel
border: '#E5D9FD', // bordure douce
},
},
fontFamily: {
sans: ['Inter', 'system-ui', 'sans-serif'],
mono: ['JetBrains Mono', 'Fira Code', 'monospace'],
},
boxShadow: {
soft: '0 2px 16px 0 rgba(124, 92, 252, 0.08)',
card: '0 4px 24px 0 rgba(124, 92, 252, 0.10)',
},
},
},
plugins: [],
}
export default config
+41
View File
@@ -0,0 +1,41 @@
{
"compilerOptions": {
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": [
"./*"
]
},
"target": "ES2017"
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}