Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

remote_files.py 5.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. import urllib.parse
  2. import httpx
  3. from flask_restx import marshal_with, reqparse
  4. import services
  5. from controllers.common import helpers
  6. from controllers.common.errors import (
  7. FileTooLargeError,
  8. RemoteFileUploadError,
  9. UnsupportedFileTypeError,
  10. )
  11. from controllers.web import web_ns
  12. from controllers.web.wraps import WebApiResource
  13. from core.file import helpers as file_helpers
  14. from core.helper import ssrf_proxy
  15. from fields.file_fields import build_file_with_signed_url_model, build_remote_file_info_model
  16. from services.file_service import FileService
  17. @web_ns.route("/remote-files/<path:url>")
  18. class RemoteFileInfoApi(WebApiResource):
  19. @web_ns.doc("get_remote_file_info")
  20. @web_ns.doc(description="Get information about a remote file")
  21. @web_ns.doc(
  22. responses={
  23. 200: "Remote file information retrieved successfully",
  24. 400: "Bad request - invalid URL",
  25. 404: "Remote file not found",
  26. 500: "Failed to fetch remote file",
  27. }
  28. )
  29. @marshal_with(build_remote_file_info_model(web_ns))
  30. def get(self, app_model, end_user, url):
  31. """Get information about a remote file.
  32. Retrieves basic information about a file located at a remote URL,
  33. including content type and content length.
  34. Args:
  35. app_model: The associated application model
  36. end_user: The end user making the request
  37. url: URL-encoded path to the remote file
  38. Returns:
  39. dict: Remote file information including type and length
  40. Raises:
  41. HTTPException: If the remote file cannot be accessed
  42. """
  43. decoded_url = urllib.parse.unquote(url)
  44. resp = ssrf_proxy.head(decoded_url)
  45. if resp.status_code != httpx.codes.OK:
  46. # failed back to get method
  47. resp = ssrf_proxy.get(decoded_url, timeout=3)
  48. resp.raise_for_status()
  49. return {
  50. "file_type": resp.headers.get("Content-Type", "application/octet-stream"),
  51. "file_length": int(resp.headers.get("Content-Length", -1)),
  52. }
  53. @web_ns.route("/remote-files/upload")
  54. class RemoteFileUploadApi(WebApiResource):
  55. @web_ns.doc("upload_remote_file")
  56. @web_ns.doc(description="Upload a file from a remote URL")
  57. @web_ns.doc(
  58. responses={
  59. 201: "Remote file uploaded successfully",
  60. 400: "Bad request - invalid URL or parameters",
  61. 413: "File too large",
  62. 415: "Unsupported file type",
  63. 500: "Failed to fetch remote file",
  64. }
  65. )
  66. @marshal_with(build_file_with_signed_url_model(web_ns))
  67. def post(self, app_model, end_user):
  68. """Upload a file from a remote URL.
  69. Downloads a file from the provided remote URL and uploads it
  70. to the platform storage for use in web applications.
  71. Args:
  72. app_model: The associated application model
  73. end_user: The end user making the request
  74. JSON Parameters:
  75. url: The remote URL to download the file from (required)
  76. Returns:
  77. dict: File information including ID, signed URL, and metadata
  78. int: HTTP status code 201 for success
  79. Raises:
  80. RemoteFileUploadError: Failed to fetch file from remote URL
  81. FileTooLargeError: File exceeds size limit
  82. UnsupportedFileTypeError: File type not supported
  83. """
  84. parser = reqparse.RequestParser()
  85. parser.add_argument("url", type=str, required=True, help="URL is required")
  86. args = parser.parse_args()
  87. url = args["url"]
  88. try:
  89. resp = ssrf_proxy.head(url=url)
  90. if resp.status_code != httpx.codes.OK:
  91. resp = ssrf_proxy.get(url=url, timeout=3, follow_redirects=True)
  92. if resp.status_code != httpx.codes.OK:
  93. raise RemoteFileUploadError(f"Failed to fetch file from {url}: {resp.text}")
  94. except httpx.RequestError as e:
  95. raise RemoteFileUploadError(f"Failed to fetch file from {url}: {str(e)}")
  96. file_info = helpers.guess_file_info_from_response(resp)
  97. if not FileService.is_file_size_within_limit(extension=file_info.extension, file_size=file_info.size):
  98. raise FileTooLargeError
  99. content = resp.content if resp.request.method == "GET" else ssrf_proxy.get(url).content
  100. try:
  101. upload_file = FileService.upload_file(
  102. filename=file_info.filename,
  103. content=content,
  104. mimetype=file_info.mimetype,
  105. user=end_user,
  106. source_url=url,
  107. )
  108. except services.errors.file.FileTooLargeError as file_too_large_error:
  109. raise FileTooLargeError(file_too_large_error.description)
  110. except services.errors.file.UnsupportedFileTypeError:
  111. raise UnsupportedFileTypeError
  112. return {
  113. "id": upload_file.id,
  114. "name": upload_file.name,
  115. "size": upload_file.size,
  116. "extension": upload_file.extension,
  117. "url": file_helpers.get_signed_file_url(upload_file_id=upload_file.id),
  118. "mime_type": upload_file.mime_type,
  119. "created_by": upload_file.created_by,
  120. "created_at": upload_file.created_at,
  121. }, 201