files.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. import logging
  2. import os
  3. import uuid
  4. from fnmatch import fnmatch
  5. from pathlib import Path
  6. from typing import Optional
  7. from urllib.parse import quote
  8. from fastapi import (
  9. APIRouter,
  10. Depends,
  11. File,
  12. HTTPException,
  13. Request,
  14. UploadFile,
  15. status,
  16. Query,
  17. )
  18. from fastapi.responses import FileResponse, StreamingResponse
  19. from open_webui.constants import ERROR_MESSAGES
  20. from open_webui.env import SRC_LOG_LEVELS
  21. from open_webui.models.files import (
  22. FileForm,
  23. FileModel,
  24. FileModelResponse,
  25. Files,
  26. )
  27. from open_webui.models.knowledge import Knowledges
  28. from open_webui.routers.knowledge import get_knowledge, get_knowledge_list
  29. from open_webui.routers.retrieval import ProcessFileForm, process_file
  30. from open_webui.routers.audio import transcribe
  31. from open_webui.storage.provider import Storage
  32. from open_webui.utils.auth import get_admin_user, get_verified_user
  33. from pydantic import BaseModel
  34. log = logging.getLogger(__name__)
  35. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  36. router = APIRouter()
  37. ############################
  38. # Check if the current user has access to a file through any knowledge bases the user may be in.
  39. ############################
  40. def has_access_to_file(
  41. file_id: Optional[str], access_type: str, user=Depends(get_verified_user)
  42. ) -> bool:
  43. file = Files.get_file_by_id(file_id)
  44. log.debug(f"Checking if user has {access_type} access to file")
  45. if not file:
  46. raise HTTPException(
  47. status_code=status.HTTP_404_NOT_FOUND,
  48. detail=ERROR_MESSAGES.NOT_FOUND,
  49. )
  50. has_access = False
  51. knowledge_base_id = file.meta.get("collection_name") if file.meta else None
  52. if knowledge_base_id:
  53. knowledge_bases = Knowledges.get_knowledge_bases_by_user_id(
  54. user.id, access_type
  55. )
  56. for knowledge_base in knowledge_bases:
  57. if knowledge_base.id == knowledge_base_id:
  58. has_access = True
  59. break
  60. return has_access
  61. ############################
  62. # Upload File
  63. ############################
  64. @router.post("/", response_model=FileModelResponse)
  65. def upload_file(
  66. request: Request,
  67. file: UploadFile = File(...),
  68. user=Depends(get_verified_user),
  69. file_metadata: dict = None,
  70. process: bool = Query(True),
  71. ):
  72. log.info(f"file.content_type: {file.content_type}")
  73. file_metadata = file_metadata if file_metadata else {}
  74. try:
  75. unsanitized_filename = file.filename
  76. filename = os.path.basename(unsanitized_filename)
  77. # replace filename with uuid
  78. id = str(uuid.uuid4())
  79. name = filename
  80. filename = f"{id}_{filename}"
  81. tags = {
  82. "OpenWebUI-User-Email": user.email,
  83. "OpenWebUI-User-Id": user.id,
  84. "OpenWebUI-User-Name": user.name,
  85. "OpenWebUI-File-Id": id,
  86. }
  87. contents, file_path = Storage.upload_file(file.file, filename, tags)
  88. file_item = Files.insert_new_file(
  89. user.id,
  90. FileForm(
  91. **{
  92. "id": id,
  93. "filename": name,
  94. "path": file_path,
  95. "meta": {
  96. "name": name,
  97. "content_type": file.content_type,
  98. "size": len(contents),
  99. "data": file_metadata,
  100. },
  101. }
  102. ),
  103. )
  104. if process:
  105. try:
  106. if file.content_type in [
  107. "audio/mpeg",
  108. "audio/wav",
  109. "audio/ogg",
  110. "audio/x-m4a",
  111. ]:
  112. file_path = Storage.get_file(file_path)
  113. result = transcribe(request, file_path)
  114. process_file(
  115. request,
  116. ProcessFileForm(file_id=id, content=result.get("text", "")),
  117. user=user,
  118. )
  119. elif file.content_type not in [
  120. "image/png",
  121. "image/jpeg",
  122. "image/gif",
  123. "video/mp4",
  124. "video/ogg",
  125. "video/quicktime",
  126. "video/webm",
  127. ]:
  128. process_file(request, ProcessFileForm(file_id=id), user=user)
  129. file_item = Files.get_file_by_id(id=id)
  130. except Exception as e:
  131. log.exception(e)
  132. log.error(f"Error processing file: {file_item.id}")
  133. file_item = FileModelResponse(
  134. **{
  135. **file_item.model_dump(),
  136. "error": str(e.detail) if hasattr(e, "detail") else str(e),
  137. }
  138. )
  139. if file_item:
  140. return file_item
  141. else:
  142. raise HTTPException(
  143. status_code=status.HTTP_400_BAD_REQUEST,
  144. detail=ERROR_MESSAGES.DEFAULT("Error uploading file"),
  145. )
  146. except Exception as e:
  147. log.exception(e)
  148. raise HTTPException(
  149. status_code=status.HTTP_400_BAD_REQUEST,
  150. detail=ERROR_MESSAGES.DEFAULT(e),
  151. )
  152. ############################
  153. # List Files
  154. ############################
  155. @router.get("/", response_model=list[FileModelResponse])
  156. async def list_files(user=Depends(get_verified_user), content: bool = Query(True)):
  157. if user.role == "admin":
  158. files = Files.get_files()
  159. else:
  160. files = Files.get_files_by_user_id(user.id)
  161. if not content:
  162. for file in files:
  163. if "content" in file.data:
  164. del file.data["content"]
  165. return files
  166. ############################
  167. # Search Files
  168. ############################
  169. @router.get("/search", response_model=list[FileModelResponse])
  170. async def search_files(
  171. filename: str = Query(
  172. ...,
  173. description="Filename pattern to search for. Supports wildcards such as '*.txt'",
  174. ),
  175. content: bool = Query(True),
  176. user=Depends(get_verified_user),
  177. ):
  178. """
  179. Search for files by filename with support for wildcard patterns.
  180. """
  181. # Get files according to user role
  182. if user.role == "admin":
  183. files = Files.get_files()
  184. else:
  185. files = Files.get_files_by_user_id(user.id)
  186. # Get matching files
  187. matching_files = [
  188. file for file in files if fnmatch(file.filename.lower(), filename.lower())
  189. ]
  190. if not matching_files:
  191. raise HTTPException(
  192. status_code=status.HTTP_404_NOT_FOUND,
  193. detail="No files found matching the pattern.",
  194. )
  195. if not content:
  196. for file in matching_files:
  197. if "content" in file.data:
  198. del file.data["content"]
  199. return matching_files
  200. ############################
  201. # Delete All Files
  202. ############################
  203. @router.delete("/all")
  204. async def delete_all_files(user=Depends(get_admin_user)):
  205. result = Files.delete_all_files()
  206. if result:
  207. try:
  208. Storage.delete_all_files()
  209. except Exception as e:
  210. log.exception(e)
  211. log.error("Error deleting files")
  212. raise HTTPException(
  213. status_code=status.HTTP_400_BAD_REQUEST,
  214. detail=ERROR_MESSAGES.DEFAULT("Error deleting files"),
  215. )
  216. return {"message": "All files deleted successfully"}
  217. else:
  218. raise HTTPException(
  219. status_code=status.HTTP_400_BAD_REQUEST,
  220. detail=ERROR_MESSAGES.DEFAULT("Error deleting files"),
  221. )
  222. ############################
  223. # Get File By Id
  224. ############################
  225. @router.get("/{id}", response_model=Optional[FileModel])
  226. async def get_file_by_id(id: str, user=Depends(get_verified_user)):
  227. file = Files.get_file_by_id(id)
  228. if not file:
  229. raise HTTPException(
  230. status_code=status.HTTP_404_NOT_FOUND,
  231. detail=ERROR_MESSAGES.NOT_FOUND,
  232. )
  233. if (
  234. file.user_id == user.id
  235. or user.role == "admin"
  236. or has_access_to_file(id, "read", user)
  237. ):
  238. return file
  239. else:
  240. raise HTTPException(
  241. status_code=status.HTTP_404_NOT_FOUND,
  242. detail=ERROR_MESSAGES.NOT_FOUND,
  243. )
  244. ############################
  245. # Get File Data Content By Id
  246. ############################
  247. @router.get("/{id}/data/content")
  248. async def get_file_data_content_by_id(id: str, user=Depends(get_verified_user)):
  249. file = Files.get_file_by_id(id)
  250. if not file:
  251. raise HTTPException(
  252. status_code=status.HTTP_404_NOT_FOUND,
  253. detail=ERROR_MESSAGES.NOT_FOUND,
  254. )
  255. if (
  256. file.user_id == user.id
  257. or user.role == "admin"
  258. or has_access_to_file(id, "read", user)
  259. ):
  260. return {"content": file.data.get("content", "")}
  261. else:
  262. raise HTTPException(
  263. status_code=status.HTTP_404_NOT_FOUND,
  264. detail=ERROR_MESSAGES.NOT_FOUND,
  265. )
  266. ############################
  267. # Update File Data Content By Id
  268. ############################
  269. class ContentForm(BaseModel):
  270. content: str
  271. @router.post("/{id}/data/content/update")
  272. async def update_file_data_content_by_id(
  273. request: Request, id: str, form_data: ContentForm, user=Depends(get_verified_user)
  274. ):
  275. file = Files.get_file_by_id(id)
  276. if not file:
  277. raise HTTPException(
  278. status_code=status.HTTP_404_NOT_FOUND,
  279. detail=ERROR_MESSAGES.NOT_FOUND,
  280. )
  281. if (
  282. file.user_id == user.id
  283. or user.role == "admin"
  284. or has_access_to_file(id, "write", user)
  285. ):
  286. try:
  287. process_file(
  288. request,
  289. ProcessFileForm(file_id=id, content=form_data.content),
  290. user=user,
  291. )
  292. file = Files.get_file_by_id(id=id)
  293. except Exception as e:
  294. log.exception(e)
  295. log.error(f"Error processing file: {file.id}")
  296. return {"content": file.data.get("content", "")}
  297. else:
  298. raise HTTPException(
  299. status_code=status.HTTP_404_NOT_FOUND,
  300. detail=ERROR_MESSAGES.NOT_FOUND,
  301. )
  302. ############################
  303. # Get File Content By Id
  304. ############################
  305. @router.get("/{id}/content")
  306. async def get_file_content_by_id(
  307. id: str, user=Depends(get_verified_user), attachment: bool = Query(False)
  308. ):
  309. file = Files.get_file_by_id(id)
  310. if not file:
  311. raise HTTPException(
  312. status_code=status.HTTP_404_NOT_FOUND,
  313. detail=ERROR_MESSAGES.NOT_FOUND,
  314. )
  315. if (
  316. file.user_id == user.id
  317. or user.role == "admin"
  318. or has_access_to_file(id, "read", user)
  319. ):
  320. try:
  321. file_path = Storage.get_file(file.path)
  322. file_path = Path(file_path)
  323. # Check if the file already exists in the cache
  324. if file_path.is_file():
  325. # Handle Unicode filenames
  326. filename = file.meta.get("name", file.filename)
  327. encoded_filename = quote(filename) # RFC5987 encoding
  328. content_type = file.meta.get("content_type")
  329. filename = file.meta.get("name", file.filename)
  330. encoded_filename = quote(filename)
  331. headers = {}
  332. if attachment:
  333. headers["Content-Disposition"] = (
  334. f"attachment; filename*=UTF-8''{encoded_filename}"
  335. )
  336. else:
  337. if content_type == "application/pdf" or filename.lower().endswith(
  338. ".pdf"
  339. ):
  340. headers["Content-Disposition"] = (
  341. f"inline; filename*=UTF-8''{encoded_filename}"
  342. )
  343. content_type = "application/pdf"
  344. elif content_type != "text/plain":
  345. headers["Content-Disposition"] = (
  346. f"attachment; filename*=UTF-8''{encoded_filename}"
  347. )
  348. return FileResponse(file_path, headers=headers, media_type=content_type)
  349. else:
  350. raise HTTPException(
  351. status_code=status.HTTP_404_NOT_FOUND,
  352. detail=ERROR_MESSAGES.NOT_FOUND,
  353. )
  354. except Exception as e:
  355. log.exception(e)
  356. log.error("Error getting file content")
  357. raise HTTPException(
  358. status_code=status.HTTP_400_BAD_REQUEST,
  359. detail=ERROR_MESSAGES.DEFAULT("Error getting file content"),
  360. )
  361. else:
  362. raise HTTPException(
  363. status_code=status.HTTP_404_NOT_FOUND,
  364. detail=ERROR_MESSAGES.NOT_FOUND,
  365. )
  366. @router.get("/{id}/content/html")
  367. async def get_html_file_content_by_id(id: str, user=Depends(get_verified_user)):
  368. file = Files.get_file_by_id(id)
  369. if not file:
  370. raise HTTPException(
  371. status_code=status.HTTP_404_NOT_FOUND,
  372. detail=ERROR_MESSAGES.NOT_FOUND,
  373. )
  374. if (
  375. file.user_id == user.id
  376. or user.role == "admin"
  377. or has_access_to_file(id, "read", user)
  378. ):
  379. try:
  380. file_path = Storage.get_file(file.path)
  381. file_path = Path(file_path)
  382. # Check if the file already exists in the cache
  383. if file_path.is_file():
  384. log.info(f"file_path: {file_path}")
  385. return FileResponse(file_path)
  386. else:
  387. raise HTTPException(
  388. status_code=status.HTTP_404_NOT_FOUND,
  389. detail=ERROR_MESSAGES.NOT_FOUND,
  390. )
  391. except Exception as e:
  392. log.exception(e)
  393. log.error("Error getting file content")
  394. raise HTTPException(
  395. status_code=status.HTTP_400_BAD_REQUEST,
  396. detail=ERROR_MESSAGES.DEFAULT("Error getting file content"),
  397. )
  398. else:
  399. raise HTTPException(
  400. status_code=status.HTTP_404_NOT_FOUND,
  401. detail=ERROR_MESSAGES.NOT_FOUND,
  402. )
  403. @router.get("/{id}/content/{file_name}")
  404. async def get_file_content_by_id(id: str, user=Depends(get_verified_user)):
  405. file = Files.get_file_by_id(id)
  406. if not file:
  407. raise HTTPException(
  408. status_code=status.HTTP_404_NOT_FOUND,
  409. detail=ERROR_MESSAGES.NOT_FOUND,
  410. )
  411. if (
  412. file.user_id == user.id
  413. or user.role == "admin"
  414. or has_access_to_file(id, "read", user)
  415. ):
  416. file_path = file.path
  417. # Handle Unicode filenames
  418. filename = file.meta.get("name", file.filename)
  419. encoded_filename = quote(filename) # RFC5987 encoding
  420. headers = {
  421. "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
  422. }
  423. if file_path:
  424. file_path = Storage.get_file(file_path)
  425. file_path = Path(file_path)
  426. # Check if the file already exists in the cache
  427. if file_path.is_file():
  428. return FileResponse(file_path, headers=headers)
  429. else:
  430. raise HTTPException(
  431. status_code=status.HTTP_404_NOT_FOUND,
  432. detail=ERROR_MESSAGES.NOT_FOUND,
  433. )
  434. else:
  435. # File path doesn’t exist, return the content as .txt if possible
  436. file_content = file.content.get("content", "")
  437. file_name = file.filename
  438. # Create a generator that encodes the file content
  439. def generator():
  440. yield file_content.encode("utf-8")
  441. return StreamingResponse(
  442. generator(),
  443. media_type="text/plain",
  444. headers=headers,
  445. )
  446. else:
  447. raise HTTPException(
  448. status_code=status.HTTP_404_NOT_FOUND,
  449. detail=ERROR_MESSAGES.NOT_FOUND,
  450. )
  451. ############################
  452. # Delete File By Id
  453. ############################
  454. @router.delete("/{id}")
  455. async def delete_file_by_id(id: str, user=Depends(get_verified_user)):
  456. file = Files.get_file_by_id(id)
  457. if not file:
  458. raise HTTPException(
  459. status_code=status.HTTP_404_NOT_FOUND,
  460. detail=ERROR_MESSAGES.NOT_FOUND,
  461. )
  462. if (
  463. file.user_id == user.id
  464. or user.role == "admin"
  465. or has_access_to_file(id, "write", user)
  466. ):
  467. # We should add Chroma cleanup here
  468. result = Files.delete_file_by_id(id)
  469. if result:
  470. try:
  471. Storage.delete_file(file.path)
  472. except Exception as e:
  473. log.exception(e)
  474. log.error("Error deleting files")
  475. raise HTTPException(
  476. status_code=status.HTTP_400_BAD_REQUEST,
  477. detail=ERROR_MESSAGES.DEFAULT("Error deleting files"),
  478. )
  479. return {"message": "File deleted successfully"}
  480. else:
  481. raise HTTPException(
  482. status_code=status.HTTP_400_BAD_REQUEST,
  483. detail=ERROR_MESSAGES.DEFAULT("Error deleting file"),
  484. )
  485. else:
  486. raise HTTPException(
  487. status_code=status.HTTP_404_NOT_FOUND,
  488. detail=ERROR_MESSAGES.NOT_FOUND,
  489. )