from fastapi import APIRouter, UploadFile, File, Form, HTTPException from fastapi import APIRouter, Depends from infra.token.token_manager import TokenManager from starlette.status import HTTP_401_UNAUTHORIZED from fastapi.encoders import jsonable_encoder from fastapi.responses import JSONResponse from app.central_storage.backend.application.document_hub import DocumentHub router = APIRouter() token_manager = TokenManager() @router.post( "/upload-document", summary="upload a document for a given object.", description="upload a document. If success, returning the document id", ) async def attach_document_for_request( object_id: str = Form(...), file: UploadFile = File(None), current_user: dict = Depends(token_manager.get_current_user), ): print("current user", current_user) user_id = current_user.get("id") print("current user id", user_id) if not user_id: raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Could not validate credentials" ) document_hub = DocumentHub(user_id) # File processing try: file_data = await file.read() # You can use async chunking for larger files document_id = await document_hub.upload_document_for_object( object_id, file.filename, file_data ) if document_id: result = {"document_id": str(document_id), "file_name": file.filename} return JSONResponse(content=jsonable_encoder(result)) else: return JSONResponse( status_code=500, content={"error": "File upload failed"} ) except Exception as e: print("this is exception", e) return JSONResponse(status_code=500, content={"error": "Internal server error"})