files.py 19 KB

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