files.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 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(file: UploadFile = File(...), user=Depends(get_verified_user)):
  39. log.info(f"file.content_type: {file.content_type}")
  40. try:
  41. unsanitized_filename = file.filename
  42. filename = os.path.basename(unsanitized_filename)
  43. # replace filename with uuid
  44. id = str(uuid.uuid4())
  45. name = filename
  46. filename = f"{id}_{filename}"
  47. file_path = f"{UPLOAD_DIR}/{filename}"
  48. contents = file.file.read()
  49. with open(file_path, "wb") as f:
  50. f.write(contents)
  51. f.close()
  52. file = Files.insert_new_file(
  53. user.id,
  54. FileForm(
  55. **{
  56. "id": id,
  57. "filename": filename,
  58. "meta": {
  59. "name": name,
  60. "content_type": file.content_type,
  61. "size": len(contents),
  62. "path": file_path,
  63. },
  64. }
  65. ),
  66. )
  67. if file:
  68. return file
  69. else:
  70. raise HTTPException(
  71. status_code=status.HTTP_400_BAD_REQUEST,
  72. detail=ERROR_MESSAGES.DEFAULT("Error uploading file"),
  73. )
  74. except Exception as e:
  75. log.exception(e)
  76. raise HTTPException(
  77. status_code=status.HTTP_400_BAD_REQUEST,
  78. detail=ERROR_MESSAGES.DEFAULT(e),
  79. )
  80. ############################
  81. # List Files
  82. ############################
  83. @router.get("/", response_model=list[FileModel])
  84. async def list_files(user=Depends(get_verified_user)):
  85. if user.role == "admin":
  86. files = Files.get_files()
  87. else:
  88. files = Files.get_files_by_user_id(user.id)
  89. return files
  90. ############################
  91. # Delete All Files
  92. ############################
  93. @router.delete("/all")
  94. async def delete_all_files(user=Depends(get_admin_user)):
  95. result = Files.delete_all_files()
  96. if result:
  97. folder = f"{UPLOAD_DIR}"
  98. try:
  99. # Check if the directory exists
  100. if os.path.exists(folder):
  101. # Iterate over all the files and directories in the specified directory
  102. for filename in os.listdir(folder):
  103. file_path = os.path.join(folder, filename)
  104. try:
  105. if os.path.isfile(file_path) or os.path.islink(file_path):
  106. os.unlink(file_path) # Remove the file or link
  107. elif os.path.isdir(file_path):
  108. shutil.rmtree(file_path) # Remove the directory
  109. except Exception as e:
  110. print(f"Failed to delete {file_path}. Reason: {e}")
  111. else:
  112. print(f"The directory {folder} does not exist")
  113. except Exception as e:
  114. print(f"Failed to process the directory {folder}. Reason: {e}")
  115. return {"message": "All files deleted successfully"}
  116. else:
  117. raise HTTPException(
  118. status_code=status.HTTP_400_BAD_REQUEST,
  119. detail=ERROR_MESSAGES.DEFAULT("Error deleting files"),
  120. )
  121. ############################
  122. # Get File By Id
  123. ############################
  124. @router.get("/{id}", response_model=Optional[FileModel])
  125. async def get_file_by_id(id: str, user=Depends(get_verified_user)):
  126. file = Files.get_file_by_id(id)
  127. if file and (file.user_id == user.id or user.role == "admin"):
  128. return file
  129. else:
  130. raise HTTPException(
  131. status_code=status.HTTP_404_NOT_FOUND,
  132. detail=ERROR_MESSAGES.NOT_FOUND,
  133. )
  134. ############################
  135. # Get File Content By Id
  136. ############################
  137. @router.get("/{id}/content", response_model=Optional[FileModel])
  138. async def get_file_content_by_id(id: str, user=Depends(get_verified_user)):
  139. file = Files.get_file_by_id(id)
  140. if file and (file.user_id == user.id or user.role == "admin"):
  141. file_path = Path(file.meta["path"])
  142. # Check if the file already exists in the cache
  143. if file_path.is_file():
  144. print(f"file_path: {file_path}")
  145. return FileResponse(file_path)
  146. else:
  147. raise HTTPException(
  148. status_code=status.HTTP_404_NOT_FOUND,
  149. detail=ERROR_MESSAGES.NOT_FOUND,
  150. )
  151. else:
  152. raise HTTPException(
  153. status_code=status.HTTP_404_NOT_FOUND,
  154. detail=ERROR_MESSAGES.NOT_FOUND,
  155. )
  156. @router.get("/{id}/content/{file_name}", response_model=Optional[FileModel])
  157. async def get_file_content_by_id(id: str, user=Depends(get_verified_user)):
  158. file = Files.get_file_by_id(id)
  159. if file and (file.user_id == user.id or user.role == "admin"):
  160. file_path = Path(file.meta["path"])
  161. # Check if the file already exists in the cache
  162. if file_path.is_file():
  163. print(f"file_path: {file_path}")
  164. return FileResponse(file_path)
  165. else:
  166. raise HTTPException(
  167. status_code=status.HTTP_404_NOT_FOUND,
  168. detail=ERROR_MESSAGES.NOT_FOUND,
  169. )
  170. else:
  171. raise HTTPException(
  172. status_code=status.HTTP_404_NOT_FOUND,
  173. detail=ERROR_MESSAGES.NOT_FOUND,
  174. )
  175. ############################
  176. # Delete File By Id
  177. ############################
  178. @router.delete("/{id}")
  179. async def delete_file_by_id(id: str, user=Depends(get_verified_user)):
  180. file = Files.get_file_by_id(id)
  181. if file and (file.user_id == user.id or user.role == "admin"):
  182. result = Files.delete_file_by_id(id)
  183. if result:
  184. return {"message": "File deleted successfully"}
  185. else:
  186. raise HTTPException(
  187. status_code=status.HTTP_400_BAD_REQUEST,
  188. detail=ERROR_MESSAGES.DEFAULT("Error deleting file"),
  189. )
  190. else:
  191. raise HTTPException(
  192. status_code=status.HTTP_404_NOT_FOUND,
  193. detail=ERROR_MESSAGES.NOT_FOUND,
  194. )