files.py 12 KB

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