file_router.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. import sys,os,io
  2. current_path = os.getcwd()
  3. sys.path.append(current_path)
  4. from config.site import SiteConfig
  5. from fastapi import APIRouter, Depends, Query, UploadFile, File
  6. from fastapi.responses import FileResponse
  7. from db.database import get_db
  8. from sqlalchemy.orm import Session
  9. from agent.models.web.response import StandardResponse,FAILED,SUCCESS
  10. from agent.models.web.request import BasicRequest
  11. from agent.libs.agent import AgentBusiness
  12. from typing import Optional
  13. import logging
  14. import base64
  15. import chardet
  16. router = APIRouter(prefix="/file", tags=["agent job interface"])
  17. logger = logging.getLogger(__name__)
  18. config = SiteConfig()
  19. @router.post("/upload/{file_type}/{job_id}", response_model=StandardResponse)
  20. async def upload_file(file_type:str, job_id:int, file: UploadFile = File(...)):
  21. #if not file.filename.endswith(file_type):
  22. # return StandardResponse(code=FAILED, message="Invalid file type")
  23. logger.info(f"upload file: {file.filename} {file_type}")
  24. data = { "file_type":file_type, "file_name":file.filename}
  25. try:
  26. file_content = await file.read()
  27. os.makedirs(config.get_config('JOB_PATH')+f"/{job_id}/upload", exist_ok=True)
  28. with open(config.get_config('JOB_PATH')+f"/{job_id}/upload/{file.filename}", "wb") as f:
  29. f.write(file_content)
  30. except Exception as e:
  31. logger.error(f"upload file error: {e}")
  32. return StandardResponse(code=FAILED, message="File upload failed")
  33. return StandardResponse(code=SUCCESS, message="File uploaded successfully", records=[data])
  34. @router.post("/browse", response_model=StandardResponse)
  35. async def browser_file(request:BasicRequest):
  36. job_id = request.get_param("job_id", 0)
  37. param_path = request.get_param("path", "")
  38. if job_id == 0:
  39. return StandardResponse(code=FAILED, message="Job id is required")
  40. job_path = os.path.join(config.get_config('JOB_PATH'),f"{job_id}")
  41. path = os.path.join(job_path, param_path.replace("..", ""))
  42. if not os.path.exists(path):
  43. return StandardResponse(code=FAILED, message="File not found")
  44. if os.path.isdir(path):
  45. files = os.listdir(path)
  46. data = []
  47. for file in files:
  48. param_path = os.path.join(path, file)
  49. encoded_param_path = base64.b64encode(param_path.encode("utf-8")).decode('utf-8')
  50. file_type = "file"
  51. if os.path.isdir(param_path):
  52. file_type = "dir"
  53. data.append({ "name":file, "path":encoded_param_path, "type":file_type})
  54. return StandardResponse(code=SUCCESS, message="File list", records=data)
  55. else:
  56. return StandardResponse(code=SUCCESS, message="nothing found", records=[])
  57. @router.get("/download/{job_id}")
  58. async def download_file(job_id:int, path:str=Query("path")):
  59. logger.info(f"GET download file: {job_id} {path}")
  60. if job_id == 0:
  61. return StandardResponse(code=FAILED, message="Job id is required")
  62. job_path = os.path.join(config.get_config('JOB_PATH'),f"{job_id}")
  63. param_path = base64.b64decode(path.encode("utf-8")).decode('utf-8')
  64. param_path = param_path.replace("..", "")
  65. path = os.path.join(job_path, param_path)
  66. filename = os.path.basename(path)
  67. logger.info(f"path: {path} filename: {filename}")
  68. if not os.path.exists(path):
  69. return StandardResponse(code=FAILED, message="File not found")
  70. if os.path.isdir(path):
  71. return StandardResponse(code=FAILED, message="Can not download directory")
  72. else:
  73. return FileResponse(path, media_type='application/octet-stream', filename=filename)
  74. @router.get("/view/{job_id}", response_model=StandardResponse)
  75. def view_file(job_id:int, path:str=Query("path")):
  76. logger.info(f"view file: {job_id} {path}")
  77. if job_id == 0:
  78. return StandardResponse(code=FAILED, message="Job id is required")
  79. job_path = os.path.join(config.get_config('JOB_PATH'),f"{job_id}")
  80. param_path = base64.b64decode(path.encode("utf-8")).decode('utf-8')
  81. param_path = param_path.replace("..", "")
  82. path = os.path.join(job_path, param_path)
  83. filename = os.path.basename(path)
  84. logger.info(f"path: {path} filename: {filename}")
  85. logger.info(f"view file: {path}")
  86. if not os.path.exists(path):
  87. logger.info(f"file not exists: {path}")
  88. return StandardResponse(code=FAILED, message="File not found")
  89. if os.path.isdir(path):
  90. logger.info(f"is dir: {path}")
  91. return StandardResponse(code=FAILED, message="Can not download directory")
  92. else:
  93. logger.info("open file")
  94. with open(path, "rb") as f:
  95. raw_content = f.read()
  96. result = chardet.detect(raw_content)
  97. content = raw_content.decode(result['encoding'], errors='ignore')
  98. return StandardResponse(code=SUCCESS, message="File content", records=[{"content":content}])
  99. return StandardResponse(code=FAILED, message="File not found")
  100. file_router = router