files.py 6.5 KB

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