upadte: clean code + add next cloud

This commit is contained in:
Tom Boullay
2026-04-14 16:21:37 +02:00
parent 3adcf9d30e
commit 3a7a5e2eea
20 changed files with 663 additions and 131 deletions
+183 -24
View File
@@ -1,8 +1,7 @@
'use client'
import { useState, useRef } from 'react'
import { useState, useRef, useCallback } from 'react'
import type { Destination } from '@/lib/constants'
import { DESTINATIONS } from '@/lib/constants'
import type { FolderEntry } from '@/lib/client-types'
import type { FileDiff } from '@/lib/types'
import { useSecret } from '@/hooks/useSecret'
@@ -14,11 +13,11 @@ import FolderCard from './upload/FolderCard'
import ActionButtons from './upload/ActionButtons'
import OverwriteConfirmModal from './upload/OverwriteConfirmModal'
import NoChangesModal from './upload/NoChangesModal'
import DriveErrorModal from './upload/DriveErrorModal'
// ---------------------------------------------------------------------------
// API helpers
// ---------------------------------------------------------------------------
interface CheckResult {
exists: boolean
diffs: FileDiff[]
@@ -48,15 +47,13 @@ async function checkFolderDiffs(
const localNames = new Set<string>()
// Model: skip size comparison (compression changes the size).
// We only check if it exists on remote or not.
const modelKey = folder.modelFile.name.toLowerCase()
localNames.add(modelKey)
if (!remoteMap.has(modelKey)) {
diffs.push({ name: folder.modelFile.name, status: 'new' })
}
// If model exists on remote → don't add to diffs (we can't know if it changed)
// Textures: compare by size (not compressed, so size is reliable)
// Textures: compare by size
for (const tex of folder.textures) {
const key = tex.name.toLowerCase()
localNames.add(key)
@@ -68,7 +65,7 @@ async function checkFolderDiffs(
}
}
// Files on remote but not in local → deleted
// Deleted
for (const [name] of remoteMap) {
if (!localNames.has(name)) {
diffs.push({ name, status: 'deleted' })
@@ -81,7 +78,49 @@ async function checkFolderDiffs(
}
}
async function uploadFolder(
/** Upload original files to Nextcloud Drive (no Blender compression). */
async function uploadDrive(
folder: FolderEntry,
secret: string,
destination: string,
action: 'new' | 'replace',
signal?: AbortSignal,
): Promise<{ success: boolean; error?: string }> {
const formData = new FormData()
formData.append('folderName', folder.folderName)
formData.append('destination', destination)
formData.append('action', action)
formData.append('files', folder.modelFile)
formData.append('fileTypes', 'model')
formData.append('textureNames', '')
for (const tex of folder.textures) {
formData.append('files', tex.file)
formData.append('fileTypes', 'texture')
formData.append('textureNames', tex.name)
}
try {
const res = await fetch('/api/upload/drive', {
method: 'POST',
headers: { 'x-upload-secret': secret.trim() },
body: formData,
signal,
})
const data = await res.json()
if (!data.success) return { success: false, error: data.error }
return { success: true }
} catch (err) {
if (err instanceof DOMException && err.name === 'AbortError') {
return { success: false, error: 'Upload annule' }
}
return { success: false, error: 'Erreur reseau (Drive)' }
}
}
/** Upload files to GitHub (with Blender compression). */
async function uploadGit(
folder: FolderEntry,
secret: string,
destination: string,
@@ -132,7 +171,6 @@ async function uploadFolder(
// ---------------------------------------------------------------------------
// UploadZone — orchestrator
// ---------------------------------------------------------------------------
export default function UploadZone() {
const {
secret,
@@ -156,14 +194,24 @@ export default function UploadZone() {
const [isUploading, setIsUploading] = useState(false)
const [globalError, setGlobalError] = useState<string | null>(null)
const [destination, setDestination] = useState<Destination>(DESTINATIONS[0].value)
const [destination, setDestination] = useState<Destination | null>(null)
const [overwriteConfirm, setOverwriteConfirm] = useState<{
folderName: string
diffs: FileDiff[]
} | null>(null)
const [noChangesFolder, setNoChangesFolder] = useState<string | null>(null)
// Drive error modal state
const [driveError, setDriveError] = useState<{
error: string
folderIndex: number
} | null>(null)
const abortRef = useRef<AbortController | null>(null)
// Tracks the check result so we know if it's "new" or "replace" for the Drive
const checkResultRef = useRef<CheckResult>({ exists: false, diffs: [] })
// -- Handlers --
const handleFolderSelected = (entry: FolderEntry) => {
@@ -183,13 +231,19 @@ export default function UploadZone() {
setSecretError("La cle d'acces est requise")
return
}
if (!destination) {
setGlobalError('Veuillez choisir une destination')
return
}
if (entries.length === 0) return
setSecretError(null)
setGlobalError(null)
const folder = entries[0]
const check = await checkFolderDiffs(folder, destination, secret, abortRef.current?.signal)
const check = await checkFolderDiffs(folder, destination!, secret, abortRef.current?.signal)
checkResultRef.current = check
if (check.exists) {
if (check.diffs.length === 0) {
setNoChangesFolder(folder.folderName)
@@ -202,6 +256,10 @@ export default function UploadZone() {
await proceedUpload()
}
/**
* Main upload flow: Drive first, then Git.
* If Drive fails, show DriveErrorModal so user can decide.
*/
const proceedUpload = async () => {
setOverwriteConfirm(null)
setIsUploading(true)
@@ -214,28 +272,118 @@ export default function UploadZone() {
if (entries[i].status === 'success') continue
if (controller.signal.aborted) break
updateEntry(i, { status: 'uploading', progress: 0, error: undefined })
const folderEntry = entries[i]
const driveAction = checkResultRef.current.exists ? 'replace' : 'new'
const result = await uploadFolder(
entries[i],
// ---- Step 1: Drive upload ----
updateEntry(i, {
status: 'uploading',
progress: 0,
error: undefined,
driveStatus: 'uploading',
driveError: undefined,
})
const driveResult = await uploadDrive(
folderEntry,
secret,
destination,
(pct) => updateEntry(i, { progress: pct }),
destination!,
driveAction as 'new' | 'replace',
controller.signal,
)
updateEntry(i, {
status: result.success ? 'success' : 'error',
progress: result.success ? 100 : 0,
error: result.success ? undefined : result.error,
filename: result.filename,
})
if (!driveResult.success) {
// Drive failed — pause and ask user
updateEntry(i, { driveStatus: 'error', driveError: driveResult.error })
setDriveError({ error: driveResult.error || 'Erreur inconnue', folderIndex: i })
// Stop here — the DriveErrorModal callbacks will resume or cancel
return
}
updateEntry(i, { driveStatus: 'success' })
// ---- Step 2: Git upload ----
await pushGit(i, controller.signal)
}
abortRef.current = null
setIsUploading(false)
}
/** Push a single folder to Git. Called after Drive succeeds or user skips Drive. */
const pushGit = async (index: number, signal?: AbortSignal) => {
const folderEntry = entries[index]
updateEntry(index, { progress: 5 })
const gitResult = await uploadGit(
folderEntry,
secret,
destination!,
(pct) => updateEntry(index, { progress: pct }),
signal,
)
updateEntry(index, {
status: gitResult.success ? 'success' : 'error',
progress: gitResult.success ? 100 : 0,
error: gitResult.success ? undefined : gitResult.error,
filename: gitResult.filename,
})
}
/** User chose "Continue without Drive" in DriveErrorModal. */
const handleDriveContinue = useCallback(async () => {
if (!driveError) return
const idx = driveError.folderIndex
setDriveError(null)
updateEntry(idx, { driveStatus: 'skipped' })
// Continue with Git
const signal = abortRef.current?.signal
await pushGit(idx, signal)
// Continue with remaining entries
for (let i = idx + 1; i < entries.length; i++) {
if (entries[i].status === 'success') continue
if (abortRef.current?.signal.aborted) break
// For subsequent entries after a Drive skip, also skip Drive
updateEntry(i, {
status: 'uploading',
progress: 0,
error: undefined,
driveStatus: 'skipped',
})
await pushGit(i, abortRef.current?.signal)
}
abortRef.current = null
setIsUploading(false)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [driveError, entries, secret, destination])
/** User chose "Cancel" in DriveErrorModal. */
const handleDriveCancel = useCallback(() => {
if (!driveError) return
const idx = driveError.folderIndex
setDriveError(null)
updateEntry(idx, {
status: 'error',
progress: 0,
error: 'Upload annule (Drive echoue)',
driveStatus: 'error',
})
abortRef.current?.abort()
abortRef.current = null
setIsUploading(false)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [driveError])
const handleCancel = () => {
abortRef.current?.abort()
abortRef.current = null
@@ -246,6 +394,8 @@ export default function UploadZone() {
resetEntries()
setGlobalError(null)
setIsUploading(false)
setDriveError(null)
checkResultRef.current = { exists: false, diffs: [] }
}
const hasPendingOrErrors = entries.some((f) => f.status === 'pending' || f.status === 'error')
@@ -298,6 +448,7 @@ export default function UploadZone() {
<ActionButtons
isUploading={isUploading}
isSecretEmpty={isSecretEmpty}
noDestination={!destination}
hasPendingOrErrors={hasPendingOrErrors}
allDone={allDone}
hasErrors={hasErrors}
@@ -308,7 +459,7 @@ export default function UploadZone() {
{overwriteConfirm && (
<OverwriteConfirmModal
destination={destination}
destination={destination!}
folderName={overwriteConfirm.folderName}
diffs={overwriteConfirm.diffs}
onCancel={() => setOverwriteConfirm(null)}
@@ -318,7 +469,7 @@ export default function UploadZone() {
{noChangesFolder && (
<NoChangesModal
destination={destination}
destination={destination!}
folderName={noChangesFolder}
onCancel={() => {
setNoChangesFolder(null)
@@ -327,6 +478,14 @@ export default function UploadZone() {
onModify={() => setNoChangesFolder(null)}
/>
)}
{driveError && (
<DriveErrorModal
error={driveError.error}
onCancel={handleDriveCancel}
onContinue={handleDriveContinue}
/>
)}
</div>
)
}