cmvr-visual/backend/app/api/responses.py

65 lines
2.2 KiB
Python
Raw Permalink Normal View History

import os, re
from urllib.parse import quote
from fastapi import Response
from fastapi.responses import StreamingResponse
from starlette.background import BackgroundTask
from app.adapters.storage import safe_file
from app.core.errors import fail
def file_response(settings, asset, key, range_header, download):
try:
handle = safe_file(settings.asset_root, key)
except (ValueError, OSError):
fail(404, "file_unavailable", "素材文件不可用")
size = os.fstat(handle.fileno()).st_size
start, end, code = 0, size - 1, 200
if range_header:
match = re.fullmatch(r"bytes=(\d*)-(\d*)", range_header.strip())
try:
if not match or not any(match.groups()):
raise ValueError
a, b = match.groups()
if a:
start, end = int(a), min(int(b), size - 1) if b else size - 1
else:
start, end = max(0, size - int(b)), size - 1
if start > end or start >= size or start < 0:
raise ValueError
code = 206
except ValueError:
handle.close()
return Response(status_code=416, headers={"Content-Range": f"bytes */{size}"})
handle.seek(start)
def chunks():
remaining = end - start + 1
try:
while remaining > 0:
data = handle.read(min(1024 * 1024, remaining))
if not data:
break
remaining -= len(data)
yield data
finally:
handle.close()
headers = {
"Accept-Ranges": "bytes",
"Content-Length": str(max(0, end - start + 1)),
"X-Content-Type-Options": "nosniff",
"Cache-Control": "private, no-store",
"Content-Disposition": ("attachment" if download else "inline")
+ "; filename*=UTF-8''"
+ quote(asset.name, safe=""),
}
if code == 206:
headers["Content-Range"] = f"bytes {start}-{end}/{size}"
return StreamingResponse(
chunks(),
status_code=code,
media_type="image/jpeg" if key != asset.storage_key else asset.mime_type,
headers=headers,
background=BackgroundTask(handle.close),
)