Files
filecodebox/apps/admin/download_checks.py
T
orion 69cfa436de ✨ feat: 完善下载检测与查件生命周期
* 提供有鉴权和并发限制的轻量下载检测,不消耗次数或生成取件事件
* 支持保存检测间隔,并校验关闭选项和有效范围
* 将成功查件记录按时间并入生命周期,与实际发起取件事件区分
* 统一签名下载入口,文本与直链分享仅在下载时计数并保留直链传输
* 处理检测取消时的连接释放,补充鉴权、存储和生命周期集成验证
* 记录文件恢复和测试验收,明确先推送代码再部署测试环境
2026-09-19 00:35:56 +08:00

128 lines
5.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Read-only checks of share eligibility and the download response's first bytes."""
import asyncio
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import parse_qs, urlsplit
import aiohttp
from fastapi import HTTPException
from starlette.responses import FileResponse, StreamingResponse, RedirectResponse
from apps.base.models import FileCodes
from core.response import APIResponse
from core.settings import settings
from core.storage import storages
CHECK_TIMEOUT = 10
_slots = asyncio.Semaphore(4)
def _check_length(length, expected):
if length is not None and int(length) != expected:
raise ValueError("文件大小与记录不一致")
async def _read_response(response, expected):
if isinstance(response, APIResponse):
raise ValueError(str(response.detail or "文件不可读取"))
if isinstance(response, RedirectResponse):
await _read_url(response.headers["location"], expected)
return
try:
if response.status_code != 200:
raise ValueError(f"下载响应异常(HTTP {response.status_code})")
_check_length(response.headers.get("content-length"), expected)
if isinstance(response, FileResponse):
def read_local():
with Path(response.path).open("rb") as file:
_check_length(Path(response.path).stat().st_size, expected)
return file.read(1)
first = await asyncio.to_thread(read_local)
elif isinstance(response, StreamingResponse):
first = await anext(response.body_iterator, b"")
else:
first = response.body[:1]
if expected > 0 and not first:
raise ValueError("文件响应为空")
finally:
if isinstance(response, StreamingResponse):
await response.body_iterator.aclose()
if response.background:
await response.background()
async def _read_url(url, expected):
if not isinstance(url, str) or urlsplit(url).scheme not in ("https", "http"):
raise ValueError("取件链接无效")
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=CHECK_TIMEOUT)) as client:
async with client.get(url, headers={"Range": "bytes=0-0", "Accept-Encoding": "identity"}) as response:
if response.status not in (200, 206):
raise ValueError(f"下载响应异常(HTTP {response.status})")
length = response.headers.get("content-length")
if response.status == 206:
content_range = response.headers.get("content-range", "")
if not content_range.startswith("bytes 0-0/"):
raise ValueError("下载范围响应异常")
length = content_range.split("/")[-1]
_check_length(length, expected)
if not await response.content.read(1) and expected > 0:
raise ValueError("文件响应为空")
async def _probe(file):
# Share lookup and response construction are shared with the public routes;
# usage consumption and transfer/audit recording are deliberately not called.
from apps.base.views import get_code_file_by_code, build_select_detail, build_download_response
from core.utils import get_select_token
valid, current = await get_code_file_by_code(file.code)
if not valid or file.expired_count == 0:
raise ValueError(str(current) if not valid else "取件次数已用尽")
if file.text is not None:
return "文本可领取"
storage = storages[settings.file_storage]()
detail = await build_select_detail(current, storage)
url = detail["download_url"]
if isinstance(url, str) and url.startswith("/share/download?"):
query = parse_qs(urlsplit(url).query)
if query.get("code") != [file.code] or query.get("key") not in (
[await get_select_token(file.code)], [await get_select_token(file.code, offset=1)]
):
raise ValueError("取件链接鉴权失败")
# Older OpenDAL adapters can fall back to reading the whole file. Never
# trigger that fallback during a periodic lightweight check.
if settings.file_storage == "opendal":
raise NotImplementedError
await _read_response(await build_download_response(current, storage), int(file.size))
else:
await _read_url(url, int(file.size))
return "已验证取件权限及文件读取;未校验完整文件"
async def check_downloads(ids):
files = {file.id: file for file in await FileCodes.filter(id__in=ids)}
async def check(file_id):
status, message = "available", ""
async with _slots:
try:
file = files.get(file_id)
if not file or file.is_trashed:
raise ValueError("文件不存在或已移入回收站")
message = await asyncio.wait_for(_probe(file), CHECK_TIMEOUT)
except NotImplementedError:
status, message = "unknown", "当前存储不支持轻量检测"
except asyncio.TimeoutError:
status, message = "unavailable", "检测超时,请重试"
except HTTPException as exc:
status, message = "unavailable", f"文件读取失败(HTTP {exc.status_code})"
except ValueError as exc:
status, message = "unavailable", str(exc)
except Exception:
status, message = "unavailable", "文件读取失败,请检查存储连接"
return {"id": file_id, "status": status, "message": message,
"checkedAt": datetime.now(timezone.utc).isoformat()}
return await asyncio.gather(*(check(file_id) for file_id in dict.fromkeys(ids)))