1
0

files.py 21 KB

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