files.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. import logging
  2. import os
  3. import uuid
  4. from pathlib import Path
  5. from typing import Optional
  6. from pydantic import BaseModel
  7. import mimetypes
  8. from open_webui.storage.provider import Storage
  9. from open_webui.models.files import (
  10. FileForm,
  11. FileModel,
  12. FileModelResponse,
  13. Files,
  14. )
  15. from open_webui.routers.retrieval import process_file, ProcessFileForm
  16. from open_webui.config import UPLOAD_DIR
  17. from open_webui.env import SRC_LOG_LEVELS
  18. from open_webui.constants import ERROR_MESSAGES
  19. from fastapi import APIRouter, Depends, File, HTTPException, UploadFile, status, Request
  20. from fastapi.responses import FileResponse, StreamingResponse
  21. from open_webui.utils.auth import get_admin_user, get_verified_user
  22. log = logging.getLogger(__name__)
  23. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  24. router = APIRouter()
  25. ############################
  26. # Upload File
  27. ############################
  28. @router.post("/", response_model=FileModelResponse)
  29. def upload_file(
  30. request: Request, file: UploadFile = File(...), user=Depends(get_verified_user)
  31. ):
  32. log.info(f"file.content_type: {file.content_type}")
  33. try:
  34. unsanitized_filename = file.filename
  35. filename = os.path.basename(unsanitized_filename)
  36. # replace filename with uuid
  37. id = str(uuid.uuid4())
  38. name = filename
  39. filename = f"{id}_{filename}"
  40. contents, file_path = Storage.upload_file(file.file, filename)
  41. file_item = Files.insert_new_file(
  42. user.id,
  43. FileForm(
  44. **{
  45. "id": id,
  46. "filename": name,
  47. "path": file_path,
  48. "meta": {
  49. "name": name,
  50. "content_type": file.content_type,
  51. "size": len(contents),
  52. },
  53. }
  54. ),
  55. )
  56. try:
  57. process_file(request, ProcessFileForm(file_id=id))
  58. file_item = Files.get_file_by_id(id=id)
  59. except Exception as e:
  60. log.exception(e)
  61. log.error(f"Error processing file: {file_item.id}")
  62. file_item = FileModelResponse(
  63. **{
  64. **file_item.model_dump(),
  65. "error": str(e.detail) if hasattr(e, "detail") else str(e),
  66. }
  67. )
  68. if file_item:
  69. return file_item
  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[FileModelResponse])
  85. async def list_files(user=Depends(get_verified_user)):
  86. if user.role == "admin":
  87. files = Files.get_files()
  88. else:
  89. files = Files.get_files_by_user_id(user.id)
  90. return files
  91. ############################
  92. # Delete All Files
  93. ############################
  94. @router.delete("/all")
  95. async def delete_all_files(user=Depends(get_admin_user)):
  96. result = Files.delete_all_files()
  97. if result:
  98. try:
  99. Storage.delete_all_files()
  100. except Exception as e:
  101. log.exception(e)
  102. log.error(f"Error deleting files")
  103. raise HTTPException(
  104. status_code=status.HTTP_400_BAD_REQUEST,
  105. detail=ERROR_MESSAGES.DEFAULT("Error deleting files"),
  106. )
  107. return {"message": "All files deleted successfully"}
  108. else:
  109. raise HTTPException(
  110. status_code=status.HTTP_400_BAD_REQUEST,
  111. detail=ERROR_MESSAGES.DEFAULT("Error deleting files"),
  112. )
  113. ############################
  114. # Get File By Id
  115. ############################
  116. @router.get("/{id}", response_model=Optional[FileModel])
  117. async def get_file_by_id(id: str, user=Depends(get_verified_user)):
  118. file = Files.get_file_by_id(id)
  119. if file and (file.user_id == user.id or user.role == "admin"):
  120. return file
  121. else:
  122. raise HTTPException(
  123. status_code=status.HTTP_404_NOT_FOUND,
  124. detail=ERROR_MESSAGES.NOT_FOUND,
  125. )
  126. ############################
  127. # Get File Data Content By Id
  128. ############################
  129. @router.get("/{id}/data/content")
  130. async def get_file_data_content_by_id(id: str, user=Depends(get_verified_user)):
  131. file = Files.get_file_by_id(id)
  132. if file and (file.user_id == user.id or user.role == "admin"):
  133. return {"content": file.data.get("content", "")}
  134. else:
  135. raise HTTPException(
  136. status_code=status.HTTP_404_NOT_FOUND,
  137. detail=ERROR_MESSAGES.NOT_FOUND,
  138. )
  139. ############################
  140. # Update File Data Content By Id
  141. ############################
  142. class ContentForm(BaseModel):
  143. content: str
  144. @router.post("/{id}/data/content/update")
  145. async def update_file_data_content_by_id(
  146. request: Request, id: str, form_data: ContentForm, user=Depends(get_verified_user)
  147. ):
  148. file = Files.get_file_by_id(id)
  149. if file and (file.user_id == user.id or user.role == "admin"):
  150. try:
  151. process_file(
  152. request, ProcessFileForm(file_id=id, content=form_data.content)
  153. )
  154. file = Files.get_file_by_id(id=id)
  155. except Exception as e:
  156. log.exception(e)
  157. log.error(f"Error processing file: {file.id}")
  158. return {"content": file.data.get("content", "")}
  159. else:
  160. raise HTTPException(
  161. status_code=status.HTTP_404_NOT_FOUND,
  162. detail=ERROR_MESSAGES.NOT_FOUND,
  163. )
  164. ############################
  165. # Get File Content By Id
  166. ############################
  167. @router.get("/{id}/content")
  168. async def get_file_content_by_id(id: str, user=Depends(get_verified_user)):
  169. file = Files.get_file_by_id(id)
  170. if file and (file.user_id == user.id or user.role == "admin"):
  171. try:
  172. file_path = Storage.get_file(file.path)
  173. file_path = Path(file_path)
  174. # Check if the file already exists in the cache
  175. if file_path.is_file():
  176. print(f"file_path: {file_path}")
  177. headers = {
  178. "Content-Disposition": f'attachment; filename="{file.meta.get("name", file.filename)}"'
  179. }
  180. return FileResponse(file_path, headers=headers)
  181. else:
  182. raise HTTPException(
  183. status_code=status.HTTP_404_NOT_FOUND,
  184. detail=ERROR_MESSAGES.NOT_FOUND,
  185. )
  186. except Exception as e:
  187. log.exception(e)
  188. log.error(f"Error getting file content")
  189. raise HTTPException(
  190. status_code=status.HTTP_400_BAD_REQUEST,
  191. detail=ERROR_MESSAGES.DEFAULT("Error getting file content"),
  192. )
  193. else:
  194. raise HTTPException(
  195. status_code=status.HTTP_404_NOT_FOUND,
  196. detail=ERROR_MESSAGES.NOT_FOUND,
  197. )
  198. @router.get("/{id}/content/html")
  199. async def get_html_file_content_by_id(id: str, user=Depends(get_verified_user)):
  200. file = Files.get_file_by_id(id)
  201. if file and (file.user_id == user.id or user.role == "admin"):
  202. try:
  203. file_path = Storage.get_file(file.path)
  204. file_path = Path(file_path)
  205. # Check if the file already exists in the cache
  206. if file_path.is_file():
  207. print(f"file_path: {file_path}")
  208. return FileResponse(file_path)
  209. else:
  210. raise HTTPException(
  211. status_code=status.HTTP_404_NOT_FOUND,
  212. detail=ERROR_MESSAGES.NOT_FOUND,
  213. )
  214. except Exception as e:
  215. log.exception(e)
  216. log.error(f"Error getting file content")
  217. raise HTTPException(
  218. status_code=status.HTTP_400_BAD_REQUEST,
  219. detail=ERROR_MESSAGES.DEFAULT("Error getting file content"),
  220. )
  221. else:
  222. raise HTTPException(
  223. status_code=status.HTTP_404_NOT_FOUND,
  224. detail=ERROR_MESSAGES.NOT_FOUND,
  225. )
  226. @router.get("/{id}/content/{file_name}")
  227. async def get_file_content_by_id(id: str, user=Depends(get_verified_user)):
  228. file = Files.get_file_by_id(id)
  229. if file and (file.user_id == user.id or user.role == "admin"):
  230. file_path = file.path
  231. if file_path:
  232. file_path = Storage.get_file(file_path)
  233. file_path = Path(file_path)
  234. # Check if the file already exists in the cache
  235. if file_path.is_file():
  236. print(f"file_path: {file_path}")
  237. headers = {
  238. "Content-Disposition": f'attachment; filename="{file.meta.get("name", file.filename)}"'
  239. }
  240. return FileResponse(file_path, headers=headers)
  241. else:
  242. raise HTTPException(
  243. status_code=status.HTTP_404_NOT_FOUND,
  244. detail=ERROR_MESSAGES.NOT_FOUND,
  245. )
  246. else:
  247. # File path doesn’t exist, return the content as .txt if possible
  248. file_content = file.content.get("content", "")
  249. file_name = file.filename
  250. # Create a generator that encodes the file content
  251. def generator():
  252. yield file_content.encode("utf-8")
  253. return StreamingResponse(
  254. generator(),
  255. media_type="text/plain",
  256. headers={"Content-Disposition": f"attachment; filename={file_name}"},
  257. )
  258. else:
  259. raise HTTPException(
  260. status_code=status.HTTP_404_NOT_FOUND,
  261. detail=ERROR_MESSAGES.NOT_FOUND,
  262. )
  263. ############################
  264. # Delete File By Id
  265. ############################
  266. @router.delete("/{id}")
  267. async def delete_file_by_id(id: str, user=Depends(get_verified_user)):
  268. file = Files.get_file_by_id(id)
  269. if file and (file.user_id == user.id or user.role == "admin"):
  270. result = Files.delete_file_by_id(id)
  271. if result:
  272. try:
  273. Storage.delete_file(file.filename)
  274. except Exception as e:
  275. log.exception(e)
  276. log.error(f"Error deleting files")
  277. raise HTTPException(
  278. status_code=status.HTTP_400_BAD_REQUEST,
  279. detail=ERROR_MESSAGES.DEFAULT("Error deleting files"),
  280. )
  281. return {"message": "File deleted successfully"}
  282. else:
  283. raise HTTPException(
  284. status_code=status.HTTP_400_BAD_REQUEST,
  285. detail=ERROR_MESSAGES.DEFAULT("Error deleting file"),
  286. )
  287. else:
  288. raise HTTPException(
  289. status_code=status.HTTP_404_NOT_FOUND,
  290. detail=ERROR_MESSAGES.NOT_FOUND,
  291. )