Implement normalize_upload_paths function: Add a utility to standardize upload paths, ensuring correct directory and destination paths when the provided path may include the filename. Update upload controllers to utilize this new function for improved path handling.
Some checks failed
Docker Build / build (push) Has been cancelled

This commit is contained in:
jletienne 2025-10-22 20:14:14 +02:00
parent e19a43fcd5
commit b0e8d8edb5
3 changed files with 48 additions and 20 deletions

View File

@ -2,7 +2,7 @@
from fastapi import APIRouter, HTTPException, UploadFile, File, Form from fastapi import APIRouter, HTTPException, UploadFile, File, Form
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from nc_py_api import NextcloudException from nc_py_api import NextcloudException
from utils import get_nextcloud_client, create_directory_recursive from utils import get_nextcloud_client, create_directory_recursive, normalize_upload_paths
from typing import Optional from typing import Optional
router = APIRouter() router = APIRouter()
@ -32,15 +32,8 @@ async def upload_file(
# Déterminer le nom du fichier # Déterminer le nom du fichier
final_filename = filename if filename else file.filename final_filename = filename if filename else file.filename
# Normaliser le chemin de destination # Normaliser les chemins (gère le cas où path contient déjà le nom du fichier)
if path == "/" or path == "": directory_path, destination_path = normalize_upload_paths(path, final_filename)
destination_path = f"/{final_filename}"
directory_path = "/"
else:
# Enlever les slashes de début/fin et ajouter le nom du fichier
clean_path = path.strip("/")
destination_path = f"/{clean_path}/{final_filename}"
directory_path = f"/{clean_path}"
# Créer le dossier de destination récursivement s'il n'existe pas # Créer le dossier de destination récursivement s'il n'existe pas
if directory_path != "/": if directory_path != "/":

View File

@ -2,7 +2,7 @@
from fastapi import APIRouter, HTTPException, Form from fastapi import APIRouter, HTTPException, Form
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from nc_py_api import NextcloudException from nc_py_api import NextcloudException
from utils import get_nextcloud_client, create_directory_recursive from utils import get_nextcloud_client, create_directory_recursive, normalize_upload_paths
from typing import Optional from typing import Optional
import base64 import base64
@ -32,15 +32,8 @@ async def upload_file_base64(
# Créer le client Nextcloud # Créer le client Nextcloud
nc = get_nextcloud_client() nc = get_nextcloud_client()
# Normaliser le chemin de destination # Normaliser les chemins (gère le cas où path contient déjà le nom du fichier)
if path == "/" or path == "": directory_path, destination_path = normalize_upload_paths(path, filename)
destination_path = f"/{filename}"
directory_path = "/"
else:
# Enlever les slashes de début/fin et ajouter le nom du fichier
clean_path = path.strip("/")
destination_path = f"/{clean_path}/{filename}"
directory_path = f"/{clean_path}"
# Créer le dossier de destination récursivement s'il n'existe pas # Créer le dossier de destination récursivement s'il n'existe pas
if directory_path != "/": if directory_path != "/":

View File

@ -21,6 +21,48 @@ def get_nextcloud_client() -> Nextcloud:
) )
def normalize_upload_paths(path: str, filename: str) -> tuple[str, str]:
"""
Normalise les chemins d'upload pour gérer les cas où le path contient déjà le nom du fichier
Args:
path: Chemin fourni par l'utilisateur (peut contenir ou non le nom du fichier)
filename: Nom du fichier
Returns:
tuple: (directory_path, destination_path)
"""
if path == "/" or path == "":
return "/", f"/{filename}"
# Nettoyer le chemin
clean_path = path.strip("/")
# Si le path se termine par le même nom que le filename, on l'enlève
# Ex: /GED/Mouvements/symbol.svg avec filename=symbol.svg -> /GED/Mouvements
path_parts = clean_path.split("/")
last_part = path_parts[-1]
# Vérifier si la dernière partie du path est le même que le filename
# ou si elle a une extension de fichier (contient un point dans les 5 derniers caractères)
if last_part == filename or (len(last_part) > 4 and "." in last_part[-5:]):
# Enlever la dernière partie qui est probablement un nom de fichier
if len(path_parts) > 1:
directory_path = "/" + "/".join(path_parts[:-1])
else:
directory_path = "/"
else:
directory_path = "/" + clean_path
# Construire le chemin de destination final
if directory_path == "/":
destination_path = f"/{filename}"
else:
destination_path = f"{directory_path}/{filename}"
return directory_path, destination_path
def create_directory_recursive(nc: Nextcloud, directory_path: str) -> None: def create_directory_recursive(nc: Nextcloud, directory_path: str) -> None:
""" """
Crée un dossier et tous ses parents récursivement si nécessaire Crée un dossier et tous ses parents récursivement si nécessaire