Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. import pathlib
  2. import re
  3. import flask
  4. from flask import request
  5. from api.db.services.document_service import DocumentService
  6. from api.db.services.file2document_service import File2DocumentService
  7. from api.utils.api_utils import server_error_response, token_required
  8. from api.utils import get_uuid
  9. from api.db import FileType
  10. from api.db.services import duplicate_name
  11. from api.db.services.file_service import FileService
  12. from api.utils.api_utils import get_json_result
  13. from api.utils.file_utils import filename_type
  14. from rag.utils.storage_factory import STORAGE_IMPL
  15. @manager.route('/file/upload', methods=['POST']) # noqa: F821
  16. @token_required
  17. def upload(tenant_id):
  18. """
  19. Upload a file to the system.
  20. ---
  21. tags:
  22. - File Management
  23. security:
  24. - ApiKeyAuth: []
  25. parameters:
  26. - in: formData
  27. name: file
  28. type: file
  29. required: true
  30. description: The file to upload
  31. - in: formData
  32. name: parent_id
  33. type: string
  34. description: Parent folder ID where the file will be uploaded. Optional.
  35. responses:
  36. 200:
  37. description: Successfully uploaded the file.
  38. schema:
  39. type: object
  40. properties:
  41. data:
  42. type: array
  43. items:
  44. type: object
  45. properties:
  46. id:
  47. type: string
  48. description: File ID
  49. name:
  50. type: string
  51. description: File name
  52. size:
  53. type: integer
  54. description: File size in bytes
  55. type:
  56. type: string
  57. description: File type (e.g., document, folder)
  58. """
  59. pf_id = request.form.get("parent_id")
  60. if not pf_id:
  61. root_folder = FileService.get_root_folder(tenant_id)
  62. pf_id = root_folder["id"]
  63. if 'file' not in request.files:
  64. return get_json_result(data=False, message='No file part!', code=400)
  65. file_objs = request.files.getlist('file')
  66. for file_obj in file_objs:
  67. if file_obj.filename == '':
  68. return get_json_result(data=False, message='No selected file!', code=400)
  69. file_res = []
  70. try:
  71. e, pf_folder = FileService.get_by_id(pf_id)
  72. if not e:
  73. return get_json_result(data=False, message="Can't find this folder!", code=404)
  74. for file_obj in file_objs:
  75. # 文件路径处理
  76. full_path = '/' + file_obj.filename
  77. file_obj_names = full_path.split('/')
  78. file_len = len(file_obj_names)
  79. # 获取文件夹路径ID
  80. file_id_list = FileService.get_id_list_by_id(pf_id, file_obj_names, 1, [pf_id])
  81. len_id_list = len(file_id_list)
  82. # 创建文件夹结构
  83. if file_len != len_id_list:
  84. e, file = FileService.get_by_id(file_id_list[len_id_list - 1])
  85. if not e:
  86. return get_json_result(data=False, message="Folder not found!", code=404)
  87. last_folder = FileService.create_folder(file, file_id_list[len_id_list - 1], file_obj_names, len_id_list)
  88. else:
  89. e, file = FileService.get_by_id(file_id_list[len_id_list - 2])
  90. if not e:
  91. return get_json_result(data=False, message="Folder not found!", code=404)
  92. last_folder = FileService.create_folder(file, file_id_list[len_id_list - 2], file_obj_names, len_id_list)
  93. filetype = filename_type(file_obj_names[file_len - 1])
  94. location = file_obj_names[file_len - 1]
  95. while STORAGE_IMPL.obj_exist(last_folder.id, location):
  96. location += "_"
  97. blob = file_obj.read()
  98. filename = duplicate_name(FileService.query, name=file_obj_names[file_len - 1], parent_id=last_folder.id)
  99. file = {
  100. "id": get_uuid(),
  101. "parent_id": last_folder.id,
  102. "tenant_id": tenant_id,
  103. "created_by": tenant_id,
  104. "type": filetype,
  105. "name": filename,
  106. "location": location,
  107. "size": len(blob),
  108. }
  109. file = FileService.insert(file)
  110. STORAGE_IMPL.put(last_folder.id, location, blob)
  111. file_res.append(file.to_json())
  112. return get_json_result(data=file_res)
  113. except Exception as e:
  114. return server_error_response(e)
  115. @manager.route('/file/create', methods=['POST']) # noqa: F821
  116. @token_required
  117. def create(tenant_id):
  118. """
  119. Create a new file or folder.
  120. ---
  121. tags:
  122. - File Management
  123. security:
  124. - ApiKeyAuth: []
  125. parameters:
  126. - in: body
  127. name: body
  128. description: File creation parameters
  129. required: true
  130. schema:
  131. type: object
  132. properties:
  133. name:
  134. type: string
  135. description: Name of the file/folder
  136. parent_id:
  137. type: string
  138. description: Parent folder ID. Optional.
  139. type:
  140. type: string
  141. enum: ["FOLDER", "VIRTUAL"]
  142. description: Type of the file
  143. responses:
  144. 200:
  145. description: File created successfully.
  146. schema:
  147. type: object
  148. properties:
  149. data:
  150. type: object
  151. properties:
  152. id:
  153. type: string
  154. name:
  155. type: string
  156. type:
  157. type: string
  158. """
  159. req = request.json
  160. pf_id = request.json.get("parent_id")
  161. input_file_type = request.json.get("type")
  162. if not pf_id:
  163. root_folder = FileService.get_root_folder(tenant_id)
  164. pf_id = root_folder["id"]
  165. try:
  166. if not FileService.is_parent_folder_exist(pf_id):
  167. return get_json_result(data=False, message="Parent Folder Doesn't Exist!", code=400)
  168. if FileService.query(name=req["name"], parent_id=pf_id):
  169. return get_json_result(data=False, message="Duplicated folder name in the same folder.", code=409)
  170. if input_file_type == FileType.FOLDER.value:
  171. file_type = FileType.FOLDER.value
  172. else:
  173. file_type = FileType.VIRTUAL.value
  174. file = FileService.insert({
  175. "id": get_uuid(),
  176. "parent_id": pf_id,
  177. "tenant_id": tenant_id,
  178. "created_by": tenant_id,
  179. "name": req["name"],
  180. "location": "",
  181. "size": 0,
  182. "type": file_type
  183. })
  184. return get_json_result(data=file.to_json())
  185. except Exception as e:
  186. return server_error_response(e)
  187. @manager.route('/file/list', methods=['GET']) # noqa: F821
  188. @token_required
  189. def list_files(tenant_id):
  190. """
  191. List files under a specific folder.
  192. ---
  193. tags:
  194. - File Management
  195. security:
  196. - ApiKeyAuth: []
  197. parameters:
  198. - in: query
  199. name: parent_id
  200. type: string
  201. description: Folder ID to list files from
  202. - in: query
  203. name: keywords
  204. type: string
  205. description: Search keyword filter
  206. - in: query
  207. name: page
  208. type: integer
  209. default: 1
  210. description: Page number
  211. - in: query
  212. name: page_size
  213. type: integer
  214. default: 15
  215. description: Number of results per page
  216. - in: query
  217. name: orderby
  218. type: string
  219. default: "create_time"
  220. description: Sort by field
  221. - in: query
  222. name: desc
  223. type: boolean
  224. default: true
  225. description: Descending order
  226. responses:
  227. 200:
  228. description: Successfully retrieved file list.
  229. schema:
  230. type: object
  231. properties:
  232. total:
  233. type: integer
  234. files:
  235. type: array
  236. items:
  237. type: object
  238. properties:
  239. id:
  240. type: string
  241. name:
  242. type: string
  243. type:
  244. type: string
  245. size:
  246. type: integer
  247. create_time:
  248. type: string
  249. format: date-time
  250. """
  251. pf_id = request.args.get("parent_id")
  252. keywords = request.args.get("keywords", "")
  253. page_number = int(request.args.get("page", 1))
  254. items_per_page = int(request.args.get("page_size", 15))
  255. orderby = request.args.get("orderby", "create_time")
  256. desc = request.args.get("desc", True)
  257. if not pf_id:
  258. root_folder = FileService.get_root_folder(tenant_id)
  259. pf_id = root_folder["id"]
  260. FileService.init_knowledgebase_docs(pf_id, tenant_id)
  261. try:
  262. e, file = FileService.get_by_id(pf_id)
  263. if not e:
  264. return get_json_result(message="Folder not found!", code=404)
  265. files, total = FileService.get_by_pf_id(tenant_id, pf_id, page_number, items_per_page, orderby, desc, keywords)
  266. parent_folder = FileService.get_parent_folder(pf_id)
  267. if not parent_folder:
  268. return get_json_result(message="File not found!", code=404)
  269. return get_json_result(data={"total": total, "files": files, "parent_folder": parent_folder.to_json()})
  270. except Exception as e:
  271. return server_error_response(e)
  272. @manager.route('/file/root_folder', methods=['GET']) # noqa: F821
  273. @token_required
  274. def get_root_folder(tenant_id):
  275. """
  276. Get user's root folder.
  277. ---
  278. tags:
  279. - File Management
  280. security:
  281. - ApiKeyAuth: []
  282. responses:
  283. 200:
  284. description: Root folder information
  285. schema:
  286. type: object
  287. properties:
  288. data:
  289. type: object
  290. properties:
  291. root_folder:
  292. type: object
  293. properties:
  294. id:
  295. type: string
  296. name:
  297. type: string
  298. type:
  299. type: string
  300. """
  301. try:
  302. root_folder = FileService.get_root_folder(tenant_id)
  303. return get_json_result(data={"root_folder": root_folder})
  304. except Exception as e:
  305. return server_error_response(e)
  306. @manager.route('/file/parent_folder', methods=['GET']) # noqa: F821
  307. @token_required
  308. def get_parent_folder():
  309. """
  310. Get parent folder info of a file.
  311. ---
  312. tags:
  313. - File Management
  314. security:
  315. - ApiKeyAuth: []
  316. parameters:
  317. - in: query
  318. name: file_id
  319. type: string
  320. required: true
  321. description: Target file ID
  322. responses:
  323. 200:
  324. description: Parent folder information
  325. schema:
  326. type: object
  327. properties:
  328. data:
  329. type: object
  330. properties:
  331. parent_folder:
  332. type: object
  333. properties:
  334. id:
  335. type: string
  336. name:
  337. type: string
  338. """
  339. file_id = request.args.get("file_id")
  340. try:
  341. e, file = FileService.get_by_id(file_id)
  342. if not e:
  343. return get_json_result(message="Folder not found!", code=404)
  344. parent_folder = FileService.get_parent_folder(file_id)
  345. return get_json_result(data={"parent_folder": parent_folder.to_json()})
  346. except Exception as e:
  347. return server_error_response(e)
  348. @manager.route('/file/all_parent_folder', methods=['GET']) # noqa: F821
  349. @token_required
  350. def get_all_parent_folders(tenant_id):
  351. """
  352. Get all parent folders of a file.
  353. ---
  354. tags:
  355. - File Management
  356. security:
  357. - ApiKeyAuth: []
  358. parameters:
  359. - in: query
  360. name: file_id
  361. type: string
  362. required: true
  363. description: Target file ID
  364. responses:
  365. 200:
  366. description: All parent folders of the file
  367. schema:
  368. type: object
  369. properties:
  370. data:
  371. type: object
  372. properties:
  373. parent_folders:
  374. type: array
  375. items:
  376. type: object
  377. properties:
  378. id:
  379. type: string
  380. name:
  381. type: string
  382. """
  383. file_id = request.args.get("file_id")
  384. try:
  385. e, file = FileService.get_by_id(file_id)
  386. if not e:
  387. return get_json_result(message="Folder not found!", code=404)
  388. parent_folders = FileService.get_all_parent_folders(file_id)
  389. parent_folders_res = [folder.to_json() for folder in parent_folders]
  390. return get_json_result(data={"parent_folders": parent_folders_res})
  391. except Exception as e:
  392. return server_error_response(e)
  393. @manager.route('/file/rm', methods=['POST']) # noqa: F821
  394. @token_required
  395. def rm(tenant_id):
  396. """
  397. Delete one or multiple files/folders.
  398. ---
  399. tags:
  400. - File Management
  401. security:
  402. - ApiKeyAuth: []
  403. parameters:
  404. - in: body
  405. name: body
  406. description: Files to delete
  407. required: true
  408. schema:
  409. type: object
  410. properties:
  411. file_ids:
  412. type: array
  413. items:
  414. type: string
  415. description: List of file IDs to delete
  416. responses:
  417. 200:
  418. description: Successfully deleted files
  419. schema:
  420. type: object
  421. properties:
  422. data:
  423. type: boolean
  424. example: true
  425. """
  426. req = request.json
  427. file_ids = req["file_ids"]
  428. try:
  429. for file_id in file_ids:
  430. e, file = FileService.get_by_id(file_id)
  431. if not e:
  432. return get_json_result(message="File or Folder not found!", code=404)
  433. if not file.tenant_id:
  434. return get_json_result(message="Tenant not found!", code=404)
  435. if file.type == FileType.FOLDER.value:
  436. file_id_list = FileService.get_all_innermost_file_ids(file_id, [])
  437. for inner_file_id in file_id_list:
  438. e, file = FileService.get_by_id(inner_file_id)
  439. if not e:
  440. return get_json_result(message="File not found!", code=404)
  441. STORAGE_IMPL.rm(file.parent_id, file.location)
  442. FileService.delete_folder_by_pf_id(tenant_id, file_id)
  443. else:
  444. STORAGE_IMPL.rm(file.parent_id, file.location)
  445. if not FileService.delete(file):
  446. return get_json_result(message="Database error (File removal)!", code=500)
  447. informs = File2DocumentService.get_by_file_id(file_id)
  448. for inform in informs:
  449. doc_id = inform.document_id
  450. e, doc = DocumentService.get_by_id(doc_id)
  451. if not e:
  452. return get_json_result(message="Document not found!", code=404)
  453. tenant_id = DocumentService.get_tenant_id(doc_id)
  454. if not tenant_id:
  455. return get_json_result(message="Tenant not found!", code=404)
  456. if not DocumentService.remove_document(doc, tenant_id):
  457. return get_json_result(message="Database error (Document removal)!", code=500)
  458. File2DocumentService.delete_by_file_id(file_id)
  459. return get_json_result(data=True)
  460. except Exception as e:
  461. return server_error_response(e)
  462. @manager.route('/file/rename', methods=['POST']) # noqa: F821
  463. @token_required
  464. def rename(tenant_id):
  465. """
  466. Rename a file.
  467. ---
  468. tags:
  469. - File Management
  470. security:
  471. - ApiKeyAuth: []
  472. parameters:
  473. - in: body
  474. name: body
  475. description: Rename file
  476. required: true
  477. schema:
  478. type: object
  479. properties:
  480. file_id:
  481. type: string
  482. description: Target file ID
  483. name:
  484. type: string
  485. description: New name for the file
  486. responses:
  487. 200:
  488. description: File renamed successfully
  489. schema:
  490. type: object
  491. properties:
  492. data:
  493. type: boolean
  494. example: true
  495. """
  496. req = request.json
  497. try:
  498. e, file = FileService.get_by_id(req["file_id"])
  499. if not e:
  500. return get_json_result(message="File not found!", code=404)
  501. if file.type != FileType.FOLDER.value and pathlib.Path(req["name"].lower()).suffix != pathlib.Path(file.name.lower()).suffix:
  502. return get_json_result(data=False, message="The extension of file can't be changed", code=400)
  503. for existing_file in FileService.query(name=req["name"], pf_id=file.parent_id):
  504. if existing_file.name == req["name"]:
  505. return get_json_result(data=False, message="Duplicated file name in the same folder.", code=409)
  506. if not FileService.update_by_id(req["file_id"], {"name": req["name"]}):
  507. return get_json_result(message="Database error (File rename)!", code=500)
  508. informs = File2DocumentService.get_by_file_id(req["file_id"])
  509. if informs:
  510. if not DocumentService.update_by_id(informs[0].document_id, {"name": req["name"]}):
  511. return get_json_result(message="Database error (Document rename)!", code=500)
  512. return get_json_result(data=True)
  513. except Exception as e:
  514. return server_error_response(e)
  515. @manager.route('/file/get/<file_id>', methods=['GET']) # noqa: F821
  516. @token_required
  517. def get(tenant_id,file_id):
  518. """
  519. Download a file.
  520. ---
  521. tags:
  522. - File Management
  523. security:
  524. - ApiKeyAuth: []
  525. produces:
  526. - application/octet-stream
  527. parameters:
  528. - in: path
  529. name: file_id
  530. type: string
  531. required: true
  532. description: File ID to download
  533. responses:
  534. 200:
  535. description: File stream
  536. schema:
  537. type: file
  538. 404:
  539. description: File not found
  540. """
  541. try:
  542. e, file = FileService.get_by_id(file_id)
  543. if not e:
  544. return get_json_result(message="Document not found!", code=404)
  545. blob = STORAGE_IMPL.get(file.parent_id, file.location)
  546. if not blob:
  547. b, n = File2DocumentService.get_storage_address(file_id=file_id)
  548. blob = STORAGE_IMPL.get(b, n)
  549. response = flask.make_response(blob)
  550. ext = re.search(r"\.([^.]+)$", file.name)
  551. if ext:
  552. if file.type == FileType.VISUAL.value:
  553. response.headers.set('Content-Type', 'image/%s' % ext.group(1))
  554. else:
  555. response.headers.set('Content-Type', 'application/%s' % ext.group(1))
  556. return response
  557. except Exception as e:
  558. return server_error_response(e)
  559. @manager.route('/file/mv', methods=['POST']) # noqa: F821
  560. @token_required
  561. def move(tenant_id):
  562. """
  563. Move one or multiple files to another folder.
  564. ---
  565. tags:
  566. - File Management
  567. security:
  568. - ApiKeyAuth: []
  569. parameters:
  570. - in: body
  571. name: body
  572. description: Move operation
  573. required: true
  574. schema:
  575. type: object
  576. properties:
  577. src_file_ids:
  578. type: array
  579. items:
  580. type: string
  581. description: Source file IDs
  582. dest_file_id:
  583. type: string
  584. description: Destination folder ID
  585. responses:
  586. 200:
  587. description: Files moved successfully
  588. schema:
  589. type: object
  590. properties:
  591. data:
  592. type: boolean
  593. example: true
  594. """
  595. req = request.json
  596. try:
  597. file_ids = req["src_file_ids"]
  598. parent_id = req["dest_file_id"]
  599. files = FileService.get_by_ids(file_ids)
  600. files_dict = {f.id: f for f in files}
  601. for file_id in file_ids:
  602. file = files_dict[file_id]
  603. if not file:
  604. return get_json_result(message="File or Folder not found!", code=404)
  605. if not file.tenant_id:
  606. return get_json_result(message="Tenant not found!", code=404)
  607. fe, _ = FileService.get_by_id(parent_id)
  608. if not fe:
  609. return get_json_result(message="Parent Folder not found!", code=404)
  610. FileService.move_file(file_ids, parent_id)
  611. return get_json_result(data=True)
  612. except Exception as e:
  613. return server_error_response(e)