files.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. from fastapi import (
  2. Depends,
  3. FastAPI,
  4. HTTPException,
  5. status,
  6. Request,
  7. UploadFile,
  8. File,
  9. Form,
  10. )
  11. from datetime import datetime, timedelta
  12. from typing import List, Union, Optional
  13. from pathlib import Path
  14. from fastapi import APIRouter
  15. from fastapi.responses import StreamingResponse, JSONResponse, FileResponse
  16. from pydantic import BaseModel
  17. import json
  18. from apps.webui.models.files import (
  19. Files,
  20. FileForm,
  21. FileModel,
  22. FileModelResponse,
  23. )
  24. from utils.utils import get_verified_user, get_admin_user
  25. from constants import ERROR_MESSAGES
  26. from importlib import util
  27. import os
  28. import uuid
  29. from config import SRC_LOG_LEVELS, UPLOAD_DIR
  30. import logging
  31. log = logging.getLogger(__name__)
  32. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  33. router = APIRouter()
  34. ############################
  35. # Upload File
  36. ############################
  37. @router.post("/")
  38. def upload_file(
  39. file: UploadFile = File(...),
  40. user=Depends(get_verified_user),
  41. ):
  42. log.info(f"file.content_type: {file.content_type}")
  43. try:
  44. unsanitized_filename = file.filename
  45. filename = os.path.basename(unsanitized_filename)
  46. # replace filename with uuid
  47. id = str(uuid.uuid4())
  48. filename = f"{id}_{filename}"
  49. file_path = f"{UPLOAD_DIR}/{filename}"
  50. contents = file.file.read()
  51. with open(file_path, "wb") as f:
  52. f.write(contents)
  53. f.close()
  54. file = Files.insert_new_file(
  55. user.id,
  56. FileForm(
  57. **{
  58. "id": id,
  59. "filename": filename,
  60. "meta": {
  61. "content_type": file.content_type,
  62. "size": len(contents),
  63. "path": file_path,
  64. },
  65. }
  66. ),
  67. )
  68. if file:
  69. return file
  70. else:
  71. raise HTTPException(
  72. status_code=status.HTTP_400_BAD_REQUEST,
  73. detail=ERROR_MESSAGES.DEFAULT("Error uploading file"),
  74. )
  75. except Exception as e:
  76. log.exception(e)
  77. raise HTTPException(
  78. status_code=status.HTTP_400_BAD_REQUEST,
  79. detail=ERROR_MESSAGES.DEFAULT(e),
  80. )
  81. ############################
  82. # List Files
  83. ############################
  84. @router.get("/", response_model=List[FileModel])
  85. async def list_files(user=Depends(get_verified_user)):
  86. files = Files.get_files()
  87. return files
  88. ############################
  89. # Get File By Id
  90. ############################
  91. @router.get("/{id}", response_model=Optional[FileModel])
  92. async def get_file_by_id(id: str, user=Depends(get_verified_user)):
  93. file = Files.get_file_by_id(id)
  94. if file:
  95. return file
  96. else:
  97. raise HTTPException(
  98. status_code=status.HTTP_401_UNAUTHORIZED,
  99. detail=ERROR_MESSAGES.NOT_FOUND,
  100. )
  101. ############################
  102. # Get File Content By Id
  103. ############################
  104. @router.get("/{id}/content", response_model=Optional[FileModel])
  105. async def get_file_content_by_id(id: str, user=Depends(get_verified_user)):
  106. file = Files.get_file_by_id(id)
  107. if file:
  108. file_path = Path(file.meta["path"])
  109. # Check if the file already exists in the cache
  110. if file_path.is_file():
  111. print(f"file_path: {file_path}")
  112. return FileResponse(file_path)
  113. else:
  114. raise HTTPException(
  115. status_code=status.HTTP_401_UNAUTHORIZED,
  116. detail=ERROR_MESSAGES.NOT_FOUND,
  117. )
  118. else:
  119. raise HTTPException(
  120. status_code=status.HTTP_401_UNAUTHORIZED,
  121. detail=ERROR_MESSAGES.NOT_FOUND,
  122. )
  123. ############################
  124. # Delete File By Id
  125. ############################
  126. @router.delete("/{id}")
  127. async def delete_file_by_id(id: str, user=Depends(get_verified_user)):
  128. file = Files.get_file_by_id(id)
  129. if file:
  130. result = Files.delete_file_by_id(id)
  131. if result:
  132. return {"message": "File deleted successfully"}
  133. else:
  134. raise HTTPException(
  135. status_code=status.HTTP_400_BAD_REQUEST,
  136. detail=ERROR_MESSAGES.DEFAULT("Error deleting file"),
  137. )
  138. else:
  139. raise HTTPException(
  140. status_code=status.HTTP_401_UNAUTHORIZED,
  141. detail=ERROR_MESSAGES.NOT_FOUND,
  142. )
  143. ############################
  144. # Delete All Files
  145. ############################
  146. @router.delete("/all")
  147. async def delete_all_files(user=Depends(get_admin_user)):
  148. result = Files.delete_all_files()
  149. if result:
  150. return {"message": "All files deleted successfully"}
  151. else:
  152. raise HTTPException(
  153. status_code=status.HTTP_400_BAD_REQUEST,
  154. detail=ERROR_MESSAGES.DEFAULT("Error deleting files"),
  155. )