files.py 19 KB

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