files.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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. stt_supported_content_types = (
  134. request.app.state.config.STT_SUPPORTED_CONTENT_TYPES
  135. or [
  136. "audio/*",
  137. "video/webm",
  138. ]
  139. )
  140. if any(
  141. fnmatch(file.content_type, content_type)
  142. for content_type in stt_supported_content_types
  143. ):
  144. file_path = Storage.get_file(file_path)
  145. result = transcribe(request, file_path, file_metadata)
  146. process_file(
  147. request,
  148. ProcessFileForm(file_id=id, content=result.get("text", "")),
  149. user=user,
  150. )
  151. elif (not file.content_type.startswith(("image/", "video/"))) or (
  152. request.app.state.config.CONTENT_EXTRACTION_ENGINE == "external"
  153. ):
  154. process_file(request, ProcessFileForm(file_id=id), user=user)
  155. else:
  156. log.info(
  157. f"File type {file.content_type} is not provided, but trying to process anyway"
  158. )
  159. process_file(request, ProcessFileForm(file_id=id), user=user)
  160. file_item = Files.get_file_by_id(id=id)
  161. except Exception as e:
  162. log.exception(e)
  163. log.error(f"Error processing file: {file_item.id}")
  164. file_item = FileModelResponse(
  165. **{
  166. **file_item.model_dump(),
  167. "error": str(e.detail) if hasattr(e, "detail") else str(e),
  168. }
  169. )
  170. if file_item:
  171. return file_item
  172. else:
  173. raise HTTPException(
  174. status_code=status.HTTP_400_BAD_REQUEST,
  175. detail=ERROR_MESSAGES.DEFAULT("Error uploading file"),
  176. )
  177. except Exception as e:
  178. log.exception(e)
  179. raise HTTPException(
  180. status_code=status.HTTP_400_BAD_REQUEST,
  181. detail=ERROR_MESSAGES.DEFAULT("Error uploading file"),
  182. )
  183. ############################
  184. # List Files
  185. ############################
  186. @router.get("/", response_model=list[FileModelResponse])
  187. async def list_files(user=Depends(get_verified_user), content: bool = Query(True)):
  188. if user.role == "admin":
  189. files = Files.get_files()
  190. else:
  191. files = Files.get_files_by_user_id(user.id)
  192. if not content:
  193. for file in files:
  194. if "content" in file.data:
  195. del file.data["content"]
  196. return files
  197. ############################
  198. # Search Files
  199. ############################
  200. @router.get("/search", response_model=list[FileModelResponse])
  201. async def search_files(
  202. filename: str = Query(
  203. ...,
  204. description="Filename pattern to search for. Supports wildcards such as '*.txt'",
  205. ),
  206. content: bool = Query(True),
  207. user=Depends(get_verified_user),
  208. ):
  209. """
  210. Search for files by filename with support for wildcard patterns.
  211. """
  212. # Get files according to user role
  213. if user.role == "admin":
  214. files = Files.get_files()
  215. else:
  216. files = Files.get_files_by_user_id(user.id)
  217. # Get matching files
  218. matching_files = [
  219. file for file in files if fnmatch(file.filename.lower(), filename.lower())
  220. ]
  221. if not matching_files:
  222. raise HTTPException(
  223. status_code=status.HTTP_404_NOT_FOUND,
  224. detail="No files found matching the pattern.",
  225. )
  226. if not content:
  227. for file in matching_files:
  228. if "content" in file.data:
  229. del file.data["content"]
  230. return matching_files
  231. ############################
  232. # Delete All Files
  233. ############################
  234. @router.delete("/all")
  235. async def delete_all_files(user=Depends(get_admin_user)):
  236. result = Files.delete_all_files()
  237. if result:
  238. try:
  239. Storage.delete_all_files()
  240. except Exception as e:
  241. log.exception(e)
  242. log.error("Error deleting files")
  243. raise HTTPException(
  244. status_code=status.HTTP_400_BAD_REQUEST,
  245. detail=ERROR_MESSAGES.DEFAULT("Error deleting files"),
  246. )
  247. return {"message": "All files deleted successfully"}
  248. else:
  249. raise HTTPException(
  250. status_code=status.HTTP_400_BAD_REQUEST,
  251. detail=ERROR_MESSAGES.DEFAULT("Error deleting files"),
  252. )
  253. ############################
  254. # Get File By Id
  255. ############################
  256. @router.get("/{id}", response_model=Optional[FileModel])
  257. async def get_file_by_id(id: str, user=Depends(get_verified_user)):
  258. file = Files.get_file_by_id(id)
  259. if not file:
  260. raise HTTPException(
  261. status_code=status.HTTP_404_NOT_FOUND,
  262. detail=ERROR_MESSAGES.NOT_FOUND,
  263. )
  264. if (
  265. file.user_id == user.id
  266. or user.role == "admin"
  267. or has_access_to_file(id, "read", user)
  268. ):
  269. return file
  270. else:
  271. raise HTTPException(
  272. status_code=status.HTTP_404_NOT_FOUND,
  273. detail=ERROR_MESSAGES.NOT_FOUND,
  274. )
  275. ############################
  276. # Get File Data Content By Id
  277. ############################
  278. @router.get("/{id}/data/content")
  279. async def get_file_data_content_by_id(id: str, user=Depends(get_verified_user)):
  280. file = Files.get_file_by_id(id)
  281. if not file:
  282. raise HTTPException(
  283. status_code=status.HTTP_404_NOT_FOUND,
  284. detail=ERROR_MESSAGES.NOT_FOUND,
  285. )
  286. if (
  287. file.user_id == user.id
  288. or user.role == "admin"
  289. or has_access_to_file(id, "read", user)
  290. ):
  291. return {"content": file.data.get("content", "")}
  292. else:
  293. raise HTTPException(
  294. status_code=status.HTTP_404_NOT_FOUND,
  295. detail=ERROR_MESSAGES.NOT_FOUND,
  296. )
  297. ############################
  298. # Update File Data Content By Id
  299. ############################
  300. class ContentForm(BaseModel):
  301. content: str
  302. @router.post("/{id}/data/content/update")
  303. async def update_file_data_content_by_id(
  304. request: Request, id: str, form_data: ContentForm, user=Depends(get_verified_user)
  305. ):
  306. file = Files.get_file_by_id(id)
  307. if not file:
  308. raise HTTPException(
  309. status_code=status.HTTP_404_NOT_FOUND,
  310. detail=ERROR_MESSAGES.NOT_FOUND,
  311. )
  312. if (
  313. file.user_id == user.id
  314. or user.role == "admin"
  315. or has_access_to_file(id, "write", user)
  316. ):
  317. try:
  318. process_file(
  319. request,
  320. ProcessFileForm(file_id=id, content=form_data.content),
  321. user=user,
  322. )
  323. file = Files.get_file_by_id(id=id)
  324. except Exception as e:
  325. log.exception(e)
  326. log.error(f"Error processing file: {file.id}")
  327. return {"content": file.data.get("content", "")}
  328. else:
  329. raise HTTPException(
  330. status_code=status.HTTP_404_NOT_FOUND,
  331. detail=ERROR_MESSAGES.NOT_FOUND,
  332. )
  333. ############################
  334. # Get File Content By Id
  335. ############################
  336. @router.get("/{id}/content")
  337. async def get_file_content_by_id(
  338. id: str, user=Depends(get_verified_user), attachment: bool = Query(False)
  339. ):
  340. file = Files.get_file_by_id(id)
  341. if not file:
  342. raise HTTPException(
  343. status_code=status.HTTP_404_NOT_FOUND,
  344. detail=ERROR_MESSAGES.NOT_FOUND,
  345. )
  346. if (
  347. file.user_id == user.id
  348. or user.role == "admin"
  349. or has_access_to_file(id, "read", user)
  350. ):
  351. try:
  352. file_path = Storage.get_file(file.path)
  353. file_path = Path(file_path)
  354. # Check if the file already exists in the cache
  355. if file_path.is_file():
  356. # Handle Unicode filenames
  357. filename = file.meta.get("name", file.filename)
  358. encoded_filename = quote(filename) # RFC5987 encoding
  359. content_type = file.meta.get("content_type")
  360. filename = file.meta.get("name", file.filename)
  361. encoded_filename = quote(filename)
  362. headers = {}
  363. if attachment:
  364. headers["Content-Disposition"] = (
  365. f"attachment; filename*=UTF-8''{encoded_filename}"
  366. )
  367. else:
  368. if content_type == "application/pdf" or filename.lower().endswith(
  369. ".pdf"
  370. ):
  371. headers["Content-Disposition"] = (
  372. f"inline; filename*=UTF-8''{encoded_filename}"
  373. )
  374. content_type = "application/pdf"
  375. elif content_type != "text/plain":
  376. headers["Content-Disposition"] = (
  377. f"attachment; filename*=UTF-8''{encoded_filename}"
  378. )
  379. return FileResponse(file_path, headers=headers, media_type=content_type)
  380. else:
  381. raise HTTPException(
  382. status_code=status.HTTP_404_NOT_FOUND,
  383. detail=ERROR_MESSAGES.NOT_FOUND,
  384. )
  385. except Exception as e:
  386. log.exception(e)
  387. log.error("Error getting file content")
  388. raise HTTPException(
  389. status_code=status.HTTP_400_BAD_REQUEST,
  390. detail=ERROR_MESSAGES.DEFAULT("Error getting file content"),
  391. )
  392. else:
  393. raise HTTPException(
  394. status_code=status.HTTP_404_NOT_FOUND,
  395. detail=ERROR_MESSAGES.NOT_FOUND,
  396. )
  397. @router.get("/{id}/content/html")
  398. async def get_html_file_content_by_id(id: str, user=Depends(get_verified_user)):
  399. file = Files.get_file_by_id(id)
  400. if not file:
  401. raise HTTPException(
  402. status_code=status.HTTP_404_NOT_FOUND,
  403. detail=ERROR_MESSAGES.NOT_FOUND,
  404. )
  405. file_user = Users.get_user_by_id(file.user_id)
  406. if not file_user.role == "admin":
  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. try:
  417. file_path = Storage.get_file(file.path)
  418. file_path = Path(file_path)
  419. # Check if the file already exists in the cache
  420. if file_path.is_file():
  421. log.info(f"file_path: {file_path}")
  422. return FileResponse(file_path)
  423. else:
  424. raise HTTPException(
  425. status_code=status.HTTP_404_NOT_FOUND,
  426. detail=ERROR_MESSAGES.NOT_FOUND,
  427. )
  428. except Exception as e:
  429. log.exception(e)
  430. log.error("Error getting file content")
  431. raise HTTPException(
  432. status_code=status.HTTP_400_BAD_REQUEST,
  433. detail=ERROR_MESSAGES.DEFAULT("Error getting file content"),
  434. )
  435. else:
  436. raise HTTPException(
  437. status_code=status.HTTP_404_NOT_FOUND,
  438. detail=ERROR_MESSAGES.NOT_FOUND,
  439. )
  440. @router.get("/{id}/content/{file_name}")
  441. async def get_file_content_by_id(id: str, user=Depends(get_verified_user)):
  442. file = Files.get_file_by_id(id)
  443. if not file:
  444. raise HTTPException(
  445. status_code=status.HTTP_404_NOT_FOUND,
  446. detail=ERROR_MESSAGES.NOT_FOUND,
  447. )
  448. if (
  449. file.user_id == user.id
  450. or user.role == "admin"
  451. or has_access_to_file(id, "read", user)
  452. ):
  453. file_path = file.path
  454. # Handle Unicode filenames
  455. filename = file.meta.get("name", file.filename)
  456. encoded_filename = quote(filename) # RFC5987 encoding
  457. headers = {
  458. "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
  459. }
  460. if file_path:
  461. file_path = Storage.get_file(file_path)
  462. file_path = Path(file_path)
  463. # Check if the file already exists in the cache
  464. if file_path.is_file():
  465. return FileResponse(file_path, headers=headers)
  466. else:
  467. raise HTTPException(
  468. status_code=status.HTTP_404_NOT_FOUND,
  469. detail=ERROR_MESSAGES.NOT_FOUND,
  470. )
  471. else:
  472. # File path doesn’t exist, return the content as .txt if possible
  473. file_content = file.content.get("content", "")
  474. file_name = file.filename
  475. # Create a generator that encodes the file content
  476. def generator():
  477. yield file_content.encode("utf-8")
  478. return StreamingResponse(
  479. generator(),
  480. media_type="text/plain",
  481. headers=headers,
  482. )
  483. else:
  484. raise HTTPException(
  485. status_code=status.HTTP_404_NOT_FOUND,
  486. detail=ERROR_MESSAGES.NOT_FOUND,
  487. )
  488. ############################
  489. # Delete File By Id
  490. ############################
  491. @router.delete("/{id}")
  492. async def delete_file_by_id(id: str, user=Depends(get_verified_user)):
  493. file = Files.get_file_by_id(id)
  494. if not file:
  495. raise HTTPException(
  496. status_code=status.HTTP_404_NOT_FOUND,
  497. detail=ERROR_MESSAGES.NOT_FOUND,
  498. )
  499. if (
  500. file.user_id == user.id
  501. or user.role == "admin"
  502. or has_access_to_file(id, "write", user)
  503. ):
  504. # We should add Chroma cleanup here
  505. result = Files.delete_file_by_id(id)
  506. if result:
  507. try:
  508. Storage.delete_file(file.path)
  509. except Exception as e:
  510. log.exception(e)
  511. log.error("Error deleting files")
  512. raise HTTPException(
  513. status_code=status.HTTP_400_BAD_REQUEST,
  514. detail=ERROR_MESSAGES.DEFAULT("Error deleting files"),
  515. )
  516. return {"message": "File deleted successfully"}
  517. else:
  518. raise HTTPException(
  519. status_code=status.HTTP_400_BAD_REQUEST,
  520. detail=ERROR_MESSAGES.DEFAULT("Error deleting file"),
  521. )
  522. else:
  523. raise HTTPException(
  524. status_code=status.HTTP_404_NOT_FOUND,
  525. detail=ERROR_MESSAGES.NOT_FOUND,
  526. )