files.py 6.4 KB

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