tool_files.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from flask import Response
  2. from flask_restful import Resource, reqparse # type: ignore
  3. from werkzeug.exceptions import Forbidden, NotFound
  4. from controllers.files import api
  5. from controllers.files.error import UnsupportedFileTypeError
  6. from core.tools.tool_file_manager import ToolFileManager
  7. class ToolFilePreviewApi(Resource):
  8. def get(self, file_id, extension):
  9. file_id = str(file_id)
  10. parser = reqparse.RequestParser()
  11. parser.add_argument("timestamp", type=str, required=True, location="args")
  12. parser.add_argument("nonce", type=str, required=True, location="args")
  13. parser.add_argument("sign", type=str, required=True, location="args")
  14. parser.add_argument("as_attachment", type=bool, required=False, default=False, location="args")
  15. args = parser.parse_args()
  16. if not ToolFileManager.verify_file(
  17. file_id=file_id,
  18. timestamp=args["timestamp"],
  19. nonce=args["nonce"],
  20. sign=args["sign"],
  21. ):
  22. raise Forbidden("Invalid request.")
  23. try:
  24. stream, tool_file = ToolFileManager.get_file_generator_by_tool_file_id(
  25. file_id,
  26. )
  27. if not stream or not tool_file:
  28. raise NotFound("file is not found")
  29. except Exception:
  30. raise UnsupportedFileTypeError()
  31. response = Response(
  32. stream,
  33. mimetype=tool_file.mimetype,
  34. direct_passthrough=True,
  35. headers={},
  36. )
  37. if tool_file.size > 0:
  38. response.headers["Content-Length"] = str(tool_file.size)
  39. if args["as_attachment"]:
  40. response.headers["Content-Disposition"] = f"attachment; filename={tool_file.name}"
  41. return response
  42. api.add_resource(ToolFilePreviewApi, "/files/tools/<uuid:file_id>.<string:extension>")