✨ feat: 完善下载检测与查件生命周期
* 提供有鉴权和并发限制的轻量下载检测,不消耗次数或生成取件事件 * 支持保存检测间隔,并校验关闭选项和有效范围 * 将成功查件记录按时间并入生命周期,与实际发起取件事件区分 * 统一签名下载入口,文本与直链分享仅在下载时计数并保留直链传输 * 处理检测取消时的连接释放,补充鉴权、存储和生命周期集成验证 * 记录文件恢复和测试验收,明确先推送代码再部署测试环境
This commit is contained in:
1 parent
32b31ac271
commit
69cfa436de
11 files changed
+555
-39
No files matched your search
@@ -0,0 +1,127 @@
|
||||
"""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)))
|
||||
@@ -98,3 +98,7 @@ class FileViewPresetData(BaseModel):
|
||||
|
||||
class FileViewPresetDeleteData(BaseModel):
|
||||
id: str
|
||||
|
||||
|
||||
class DownloadCheckData(BaseModel):
|
||||
ids: list[Annotated[int, Field(strict=True, gt=0)]] = Field(min_length=1, max_length=20)
|
||||
+23
-1
@@ -1479,8 +1479,21 @@ class FileService(TrashManagementMixin):
|
||||
"event_count": download_event_count,
|
||||
}
|
||||
)
|
||||
lookup_stats = await TransferStats.filter(
|
||||
action="lookup", file_code_id=file_code.id
|
||||
).order_by("created_at", "id")
|
||||
events = []
|
||||
for index, stat in enumerate(lookup_stats, start=1):
|
||||
events.append({
|
||||
"key": "queried_event",
|
||||
"status": "done",
|
||||
"severity": "info",
|
||||
"timestamp": stat.created_at,
|
||||
"value": index,
|
||||
"detail": stat.ip or "",
|
||||
})
|
||||
for index, stat in enumerate(download_stats, start=1):
|
||||
timeline.append(
|
||||
events.append(
|
||||
{
|
||||
"key": "retrieved_event",
|
||||
"status": "done",
|
||||
@@ -1490,6 +1503,7 @@ class FileService(TrashManagementMixin):
|
||||
"detail": stat.ip or "",
|
||||
}
|
||||
)
|
||||
timeline.extend(sorted(events, key=lambda event: event["timestamp"]))
|
||||
return timeline
|
||||
|
||||
def _seconds_between(
|
||||
@@ -1710,6 +1724,7 @@ class ConfigService:
|
||||
"trashRetentionDays",
|
||||
"enableChunk",
|
||||
"chunkSizeMB",
|
||||
"downloadCheckInterval",
|
||||
"errorCount",
|
||||
"errorMinute",
|
||||
"loginCount",
|
||||
@@ -1748,6 +1763,13 @@ class ConfigService:
|
||||
if key in settings.default_config and key not in INTERNAL_CONFIG_KEYS
|
||||
}
|
||||
|
||||
if "downloadCheckInterval" in update_data:
|
||||
interval = update_data["downloadCheckInterval"]
|
||||
if isinstance(interval, bool) or not isinstance(interval, int) or (
|
||||
interval != 0 and not 30 <= interval <= 86400
|
||||
):
|
||||
raise HTTPException(400, "检测间隔必须是 0(关闭)或 30–86400 秒的整数")
|
||||
|
||||
if "chunkSizeMB" in update_data:
|
||||
raw_size = update_data["chunkSizeMB"]
|
||||
if isinstance(raw_size, bool) or not (
|
||||
|
||||
+7
-1
@@ -18,6 +18,7 @@ from apps.admin.dependencies import (
|
||||
)
|
||||
from apps.admin.schemas import (
|
||||
IDData,
|
||||
DownloadCheckData,
|
||||
IDsData,
|
||||
BatchUpdateFileData,
|
||||
BatchFilePolicyActionData,
|
||||
@@ -944,4 +945,9 @@ async def update_file(
|
||||
count=1,
|
||||
meta={"fields": sorted(update_data.keys())},
|
||||
)
|
||||
return APIResponse(detail="更新成功")
|
||||
return APIResponse(detail="更新成功")
|
||||
|
||||
@admin_api.post("/file/download-check")
|
||||
async def file_download_check(data: DownloadCheckData):
|
||||
from apps.admin.download_checks import check_downloads
|
||||
return APIResponse(detail=await check_downloads(data.ids))
|
||||
+25
-36
@@ -11,7 +11,7 @@ from typing import Optional, Tuple, Union
|
||||
from fastapi import APIRouter, Form, Request, UploadFile, File, Depends, HTTPException
|
||||
from pydantic import BaseModel, ValidationError
|
||||
from starlette import status
|
||||
from starlette.responses import Response
|
||||
from starlette.responses import Response, RedirectResponse
|
||||
from tortoise.expressions import Case, F, Q, When
|
||||
|
||||
from apps.admin.dependencies import share_required_login
|
||||
@@ -244,7 +244,7 @@ async def get_code_file_by_code(
|
||||
file_code = await FileCodes.filter(code=normalized_code, is_trashed=False).first()
|
||||
if not file_code:
|
||||
return False, "文件不存在"
|
||||
if await file_code.is_expired() and check:
|
||||
if check and (file_code.expired_count == 0 or await file_code.is_expired()):
|
||||
return False, "文件已过期"
|
||||
return True, file_code
|
||||
|
||||
@@ -290,17 +290,30 @@ def build_file_metadata(file_code: FileCodes) -> dict:
|
||||
}
|
||||
|
||||
|
||||
async def build_download_response(file_code: FileCodes, file_storage: FileStorageInterface):
|
||||
if file_code.text is not None:
|
||||
filename = f"{file_code.prefix or 'Text'}{file_code.suffix or '.txt'}"
|
||||
return Response(
|
||||
content=file_code.text,
|
||||
media_type="text/plain",
|
||||
headers={"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename, safe='')}"},
|
||||
)
|
||||
if is_local_ref(file_code):
|
||||
return build_local_ref_download(file_code)
|
||||
if file_code.expired_count < 0:
|
||||
url = await file_storage.get_file_url(file_code)
|
||||
if isinstance(url, str) and url.startswith(("https://", "http://")):
|
||||
return RedirectResponse(url)
|
||||
return await file_storage.get_file_response(file_code)
|
||||
|
||||
|
||||
async def build_select_detail(
|
||||
file_code: FileCodes, file_storage: FileStorageInterface
|
||||
) -> dict:
|
||||
metadata = build_file_metadata(file_code)
|
||||
if file_code.text is not None:
|
||||
download_url = None
|
||||
elif file_code.expired_count >= 0 or is_local_ref(file_code):
|
||||
# 有次数限制的文件必须经过下载接口,第三方直链无法阻止重复使用。
|
||||
download_url = await get_proxy_file_url(file_code.code)
|
||||
else:
|
||||
download_url = await file_storage.get_file_url(file_code)
|
||||
# Lookup never counts as retrieval; all downloads first pass this signed entry.
|
||||
# Unlimited direct storage links still redirect at download time.
|
||||
download_url = await get_proxy_file_url(file_code.code)
|
||||
content = file_code.text if file_code.text is not None else None
|
||||
return {
|
||||
**metadata,
|
||||
@@ -348,19 +361,7 @@ async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])):
|
||||
if not await consume_file_usage(file_code):
|
||||
return APIResponse(code=404, detail="文件已过期")
|
||||
await record_transfer_stat("download", file_code, file_code.size, ip)
|
||||
if file_code.text is not None:
|
||||
filename = f"{file_code.prefix or 'Text'}{file_code.suffix or '.txt'}"
|
||||
return Response(
|
||||
content=file_code.text,
|
||||
media_type="text/plain",
|
||||
headers={
|
||||
"Content-Disposition": (
|
||||
f"attachment; filename*=UTF-8''{quote(filename, safe='')}"
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
return (build_local_ref_download(file_code) if is_local_ref(file_code) else await file_storage.get_file_response(file_code))
|
||||
return await build_download_response(file_code, file_storage)
|
||||
|
||||
|
||||
@share_api.post("/select/")
|
||||
@@ -373,15 +374,7 @@ async def select_file(data: SelectFileModel, ip: str = Depends(ip_limit["error"]
|
||||
|
||||
assert isinstance(file_code, FileCodes)
|
||||
detail = await build_select_detail(file_code, file_storage)
|
||||
download_url = detail.get("download_url")
|
||||
consumes_on_download = isinstance(download_url, str) and download_url.startswith(
|
||||
"/share/download?"
|
||||
)
|
||||
if not consumes_on_download:
|
||||
if not await consume_file_usage(file_code):
|
||||
return APIResponse(code=404, detail="文件已过期")
|
||||
await record_transfer_stat("download", file_code, file_code.size, ip)
|
||||
detail.update(build_file_metadata(file_code))
|
||||
await record_transfer_stat("lookup", file_code, 0, ip)
|
||||
return APIResponse(detail=detail)
|
||||
|
||||
|
||||
@@ -406,11 +399,7 @@ async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"]
|
||||
return APIResponse(code=404, detail="文件已过期")
|
||||
await record_transfer_stat("download", file_code, file_code.size, ip)
|
||||
|
||||
return (
|
||||
APIResponse(detail=file_code.text)
|
||||
if file_code.text
|
||||
else (build_local_ref_download(file_code) if is_local_ref(file_code) else await file_storage.get_file_response(file_code))
|
||||
)
|
||||
return await build_download_response(file_code, file_storage)
|
||||
|
||||
|
||||
chunk_api = APIRouter(prefix="/chunk", tags=["切片"])
|
||||
|
||||
Reference in new issue
Block a user