132 lines
No EOL
4.4 KiB
Python
132 lines
No EOL
4.4 KiB
Python
from fastapi import APIRouter, HTTPException, Depends, File, UploadFile, Path
|
|
from typing import List, Dict, Any
|
|
from fastapi import status
|
|
import uuid
|
|
import os
|
|
import logging
|
|
|
|
# Import auth module
|
|
from auth import get_current_active_user, get_user_context
|
|
|
|
# Import interfaces
|
|
from modules.lucydom_interface import get_lucydom_interface
|
|
from modules.agentservice_interface import get_agentservice_interface
|
|
|
|
# Logger konfigurieren
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Router für Datei-Endpunkte erstellen
|
|
router = APIRouter(
|
|
prefix="/api/files",
|
|
tags=["Files"],
|
|
responses={404: {"description": "Not found"}}
|
|
)
|
|
|
|
@router.get("", response_model=List[Dict[str, Any]])
|
|
async def get_files(current_user: Dict[str, Any] = Depends(get_current_active_user)):
|
|
"""Alle verfügbaren Dateien abrufen"""
|
|
mandate_id, user_id = await get_user_context(current_user)
|
|
|
|
# LucyDOM-Interface mit Benutzerkontext initialisieren
|
|
lucy_interface = get_lucydom_interface(mandate_id, user_id)
|
|
|
|
return lucy_interface.get_all_files()
|
|
|
|
|
|
@router.post("/upload")
|
|
async def upload_file(
|
|
file: UploadFile = File(...),
|
|
current_user: Dict[str, Any] = Depends(get_current_active_user)
|
|
):
|
|
"""Eine Datei hochladen"""
|
|
mandate_id, user_id = await get_user_context(current_user)
|
|
|
|
# LucyDOM-Interface mit Benutzerkontext initialisieren
|
|
lucy_interface = get_lucydom_interface(mandate_id, user_id)
|
|
|
|
try:
|
|
# Generiere eine eindeutige ID für die Datei
|
|
file_id = str(uuid.uuid4())
|
|
file_ext = os.path.splitext(file.filename)[1]
|
|
file_path = os.path.join(get_agentservice_interface(mandate_id, user_id).upload_dir, f"{file_id}{file_ext}")
|
|
|
|
# Datei speichern
|
|
with open(file_path, "wb") as f:
|
|
content = await file.read()
|
|
f.write(content)
|
|
|
|
# Dateityp bestimmen
|
|
file_type = "image" if file.content_type and "image" in file.content_type else "document"
|
|
|
|
# In Datenbank speichern
|
|
new_file = lucy_interface.create_file(
|
|
name=file.filename,
|
|
file_type=file_type,
|
|
content_type=file.content_type,
|
|
size=os.path.getsize(file_path),
|
|
path=file_path
|
|
)
|
|
|
|
return {
|
|
"id": new_file["id"],
|
|
"name": new_file["name"],
|
|
"type": new_file["type"],
|
|
"size": f"{new_file['size'] / (1024 * 1024):.1f} MB",
|
|
"upload_date": new_file.get("upload_date")
|
|
}
|
|
|
|
except Exception as e:
|
|
logger.error(f"Fehler beim Hochladen der Datei: {e}")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail=f"Fehler beim Hochladen der Datei: {str(e)}"
|
|
)
|
|
|
|
|
|
@router.delete("/{file_id}")
|
|
async def delete_file(
|
|
file_id: int,
|
|
current_user: Dict[str, Any] = Depends(get_current_active_user)
|
|
):
|
|
"""Löscht eine Datei"""
|
|
mandate_id, user_id = await get_user_context(current_user)
|
|
|
|
# LucyDOM-Interface mit Benutzerkontext initialisieren
|
|
lucy_interface = get_lucydom_interface(mandate_id, user_id)
|
|
|
|
try:
|
|
# Hole die Datei aus der Datenbank
|
|
file = lucy_interface.get_file(file_id)
|
|
if not file:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Datei mit ID {file_id} nicht gefunden"
|
|
)
|
|
|
|
# Prüfe, ob die physische Datei existiert
|
|
if "path" in file and os.path.exists(file["path"]):
|
|
try:
|
|
# Versuche, die physische Datei zu löschen
|
|
os.remove(file["path"])
|
|
except Exception as e:
|
|
logger.warning(f"Konnte physische Datei nicht löschen: {e}")
|
|
|
|
# Lösche die Datei aus der Datenbank
|
|
success = lucy_interface.delete_file(file_id)
|
|
|
|
if not success:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail="Fehler beim Löschen der Datei aus der Datenbank"
|
|
)
|
|
|
|
return {"success": True, "message": f"Datei '{file.get('name', 'unbekannt')}' wurde gelöscht"}
|
|
|
|
except HTTPException:
|
|
raise
|
|
except Exception as e:
|
|
logger.error(f"Fehler beim Löschen der Datei: {e}")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail=f"Fehler beim Löschen der Datei: {str(e)}"
|
|
) |