files.py 11 KB

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