files.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. import os, shutil, logging, re
  30. from config import SRC_LOG_LEVELS, UPLOAD_DIR
  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. # Delete All Files
  90. ############################
  91. @router.delete("/all")
  92. async def delete_all_files(user=Depends(get_admin_user)):
  93. result = Files.delete_all_files()
  94. if result:
  95. folder = f"{UPLOAD_DIR}"
  96. try:
  97. # Check if the directory exists
  98. if os.path.exists(folder):
  99. # Iterate over all the files and directories in the specified directory
  100. for filename in os.listdir(folder):
  101. file_path = os.path.join(folder, filename)
  102. try:
  103. if os.path.isfile(file_path) or os.path.islink(file_path):
  104. os.unlink(file_path) # Remove the file or link
  105. elif os.path.isdir(file_path):
  106. shutil.rmtree(file_path) # Remove the directory
  107. except Exception as e:
  108. print(f"Failed to delete {file_path}. Reason: {e}")
  109. else:
  110. print(f"The directory {folder} does not exist")
  111. except Exception as e:
  112. print(f"Failed to process the directory {folder}. Reason: {e}")
  113. return {"message": "All files deleted successfully"}
  114. else:
  115. raise HTTPException(
  116. status_code=status.HTTP_400_BAD_REQUEST,
  117. detail=ERROR_MESSAGES.DEFAULT("Error deleting files"),
  118. )
  119. ############################
  120. # Get File By Id
  121. ############################
  122. @router.get("/{id}", response_model=Optional[FileModel])
  123. async def get_file_by_id(id: str, user=Depends(get_verified_user)):
  124. file = Files.get_file_by_id(id)
  125. if file:
  126. return file
  127. else:
  128. raise HTTPException(
  129. status_code=status.HTTP_404_NOT_FOUND,
  130. detail=ERROR_MESSAGES.NOT_FOUND,
  131. )
  132. ############################
  133. # Get File Content By Id
  134. ############################
  135. @router.get("/{id}/content", response_model=Optional[FileModel])
  136. async def get_file_content_by_id(id: str, user=Depends(get_verified_user)):
  137. file = Files.get_file_by_id(id)
  138. if file:
  139. file_path = Path(file.meta["path"])
  140. # Check if the file already exists in the cache
  141. if file_path.is_file():
  142. print(f"file_path: {file_path}")
  143. return FileResponse(file_path)
  144. else:
  145. raise HTTPException(
  146. status_code=status.HTTP_404_NOT_FOUND,
  147. detail=ERROR_MESSAGES.NOT_FOUND,
  148. )
  149. else:
  150. raise HTTPException(
  151. status_code=status.HTTP_404_NOT_FOUND,
  152. detail=ERROR_MESSAGES.NOT_FOUND,
  153. )
  154. @router.get("/{id}/content/{file_name}", response_model=Optional[FileModel])
  155. async def get_file_content_by_id(id: str, user=Depends(get_verified_user)):
  156. file = Files.get_file_by_id(id)
  157. if file:
  158. file_path = Path(file.meta["path"])
  159. # Check if the file already exists in the cache
  160. if file_path.is_file():
  161. print(f"file_path: {file_path}")
  162. return FileResponse(file_path)
  163. else:
  164. raise HTTPException(
  165. status_code=status.HTTP_404_NOT_FOUND,
  166. detail=ERROR_MESSAGES.NOT_FOUND,
  167. )
  168. else:
  169. raise HTTPException(
  170. status_code=status.HTTP_404_NOT_FOUND,
  171. detail=ERROR_MESSAGES.NOT_FOUND,
  172. )
  173. ############################
  174. # Delete File By Id
  175. ############################
  176. @router.delete("/{id}")
  177. async def delete_file_by_id(id: str, user=Depends(get_verified_user)):
  178. file = Files.get_file_by_id(id)
  179. if file:
  180. result = Files.delete_file_by_id(id)
  181. if result:
  182. return {"message": "File deleted successfully"}
  183. else:
  184. raise HTTPException(
  185. status_code=status.HTTP_400_BAD_REQUEST,
  186. detail=ERROR_MESSAGES.DEFAULT("Error deleting file"),
  187. )
  188. else:
  189. raise HTTPException(
  190. status_code=status.HTTP_404_NOT_FOUND,
  191. detail=ERROR_MESSAGES.NOT_FOUND,
  192. )