147 lines
5.4 KiB
Python
147 lines
5.4 KiB
Python
"""把任意存储后端的内容变成浏览器能下载的响应。
|
||
|
||
本地磁盘走 ``FileResponse``(sendfile + 断点续传都白送);MinIO 走
|
||
``StreamingResponse`` 分块转发,顺手实现了 ``Range``,这样浏览器"另存为"
|
||
支持暂停继续,大文件也不会把后端内存吃穿。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from urllib.parse import quote
|
||
|
||
from fastapi.responses import FileResponse, Response, StreamingResponse
|
||
|
||
from ..envelope import ApiError, bad_request, forbidden, not_found
|
||
from .base import FileStore, StorageError, StorageUnreadableError, StorageValidationError, guess_type
|
||
from .local import LocalStore
|
||
|
||
_CHUNK = 256 * 1024
|
||
_RANGE = re.compile(r"bytes=(\d*)-(\d*)")
|
||
|
||
|
||
def content_disposition(filename: str, *, inline: bool = False) -> dict[str, str]:
|
||
"""RFC 6266 pair: an ASCII fallback for old clients plus ``filename*``.
|
||
|
||
The fallback matters more than it looks -- stripping a fully CJK name down to
|
||
``.pdf`` makes some browsers offer a dotfile, so anything left without a stem
|
||
falls back to ``download<extension>``.
|
||
"""
|
||
quoted = quote(filename or "file", safe="")
|
||
stripped = (filename or "").encode("ascii", "ignore").decode().strip()
|
||
stem, dot, tail = stripped.rpartition(".")
|
||
if not stem:
|
||
stripped = f"download{dot}{tail}" if dot else "download"
|
||
kind = "inline" if inline else "attachment"
|
||
return {"content-disposition": f"{kind}; filename=\"{stripped}\"; filename*=UTF-8''{quoted}"}
|
||
|
||
|
||
def _stream(store: FileStore, uri: str, start: int = 0, end: int | None = None):
|
||
def generate():
|
||
handle = store.open_stream(uri)
|
||
try:
|
||
if start:
|
||
handle.seek(start)
|
||
remaining = None if end is None else end - start + 1
|
||
while True:
|
||
size = _CHUNK if remaining is None else min(_CHUNK, int(remaining))
|
||
if size <= 0:
|
||
break
|
||
chunk = handle.read(size)
|
||
if not chunk:
|
||
break
|
||
if remaining is not None:
|
||
remaining -= len(chunk)
|
||
yield chunk
|
||
finally:
|
||
handle.close()
|
||
|
||
return generate()
|
||
|
||
|
||
def _parse_range(header: str | None, total: int) -> tuple[int, int] | None:
|
||
if not header or total <= 0:
|
||
return None
|
||
match = _RANGE.match(header.strip())
|
||
if not match:
|
||
return None
|
||
raw_start, raw_end = match.groups()
|
||
if not raw_start and not raw_end:
|
||
return None
|
||
if not raw_start: # bytes=-500 -> last 500 bytes
|
||
length = min(int(raw_end), total)
|
||
return (total - length, total - 1)
|
||
start = int(raw_start)
|
||
end = min(int(raw_end), total - 1) if raw_end else total - 1
|
||
if start > end or start >= total:
|
||
return None
|
||
return (start, end)
|
||
|
||
|
||
def download_response(
|
||
store: FileStore,
|
||
uri: str,
|
||
filename: str,
|
||
content_type: str = "",
|
||
*,
|
||
inline: bool = False,
|
||
range_header: str | None = None,
|
||
) -> Response:
|
||
"""Stream ``uri`` as a download, whatever backend owns it."""
|
||
media = content_type or guess_type(filename)
|
||
|
||
if isinstance(store, LocalStore):
|
||
path = store.resolve(uri)
|
||
if path.is_file():
|
||
return FileResponse(
|
||
path=str(path),
|
||
filename=None if inline else filename,
|
||
media_type=media,
|
||
content_disposition_type="inline" if inline else "attachment",
|
||
)
|
||
|
||
total = store.size(uri)
|
||
if total <= 0 and not store.exists(uri):
|
||
raise StorageError("文件已丢失")
|
||
|
||
span = _parse_range(range_header, total)
|
||
headers = {**content_disposition(filename, inline=inline), "accept-ranges": "bytes"}
|
||
if span:
|
||
start, end = span
|
||
headers["content-range"] = f"bytes {start}-{end}/{total}"
|
||
headers["content-length"] = str(end - start + 1)
|
||
return StreamingResponse(
|
||
_stream(store, uri, start, end), status_code=206, headers=headers, media_type=media
|
||
)
|
||
headers["content-length"] = str(total)
|
||
return StreamingResponse(_stream(store, uri), headers=headers, media_type=media)
|
||
|
||
|
||
_MISSING = ("不存在", "找不到", "已丢失", "为空")
|
||
_DENIED = ("没有权限", "未开放", "只读")
|
||
|
||
|
||
def storage_error(exc: StorageError, label: str = "文件") -> ApiError:
|
||
"""Turn a storage failure into the right HTTP shape for the front end.
|
||
|
||
an invalid upload (too big, extension not whitelisted) is a 400, "no such
|
||
file" is a 404, a permission rule is a 403, and anything that means MinIO is
|
||
unreachable is a 502 carrying the config hint -- an operator reading the
|
||
toast should know whether to fix the file or open the config file.
|
||
"""
|
||
message = str(exc) or f"{label}存储异常"
|
||
if isinstance(exc, StorageValidationError):
|
||
# 文件超限 / 类型不在白名单:是传上来的文件不对,不是存储坏了
|
||
return bad_request(message, reason="STORAGE_INVALID_FILE")
|
||
if isinstance(exc, StorageUnreadableError):
|
||
# 文件损坏 / 加了密 / 没有正文:同样是文件不对,服务端好得很
|
||
return bad_request(message, reason="STORAGE_UNREADABLE")
|
||
if any(word in message for word in _MISSING):
|
||
return not_found(message)
|
||
if any(word in message for word in _DENIED):
|
||
return forbidden(message)
|
||
return ApiError(message, 502, "STORAGE_UNAVAILABLE", http_status=502)
|
||
|
||
|
||
__all__ = ["content_disposition", "download_response", "storage_error"]
|