files.py 17 KB

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