✨ feat: 完善下载检测与查件生命周期
* 提供有鉴权和并发限制的轻量下载检测,不消耗次数或生成取件事件 * 支持保存检测间隔,并校验关闭选项和有效范围 * 将成功查件记录按时间并入生命周期,与实际发起取件事件区分 * 统一签名下载入口,文本与直链分享仅在下载时计数并保留直链传输 * 处理检测取消时的连接释放,补充鉴权、存储和生命周期集成验证 * 记录文件恢复和测试验收,明确先推送代码再部署测试环境
This commit is contained in:
1 parent
32b31ac271
commit
69cfa436de
11 files changed
+555
-39
No files matched your search
+71
@@ -153,3 +153,74 @@ WebDAV 保持 legacy 路径。新模式仍支持重试、续传、取消、配
|
|||||||
测试文件已清理。结束后恢复 chunkSizeMB=90。
|
测试文件已清理。结束后恢复 chunkSizeMB=90。
|
||||||
- 测试 WebDAV 仍为 `https://cd2.orionc.me/dav`,保持独立测试用户和目录。
|
- 测试 WebDAV 仍为 `https://cd2.orionc.me/dav`,保持独立测试用户和目录。
|
||||||
本轮未修改生产代码或生产 FileCodeBox 配置。
|
本轮未修改生产代码或生产 FileCodeBox 配置。
|
||||||
|
|
||||||
|
|
||||||
|
## 测试版:可下载状态检测(2026-09-18)
|
||||||
|
|
||||||
|
文件管理的桌面列表和移动端卡片显示可下载、不可下载、检测中、未检测,
|
||||||
|
附带原因和检测时间。进入列表、翻页、筛选、刷新列表均检测当前页。
|
||||||
|
默认每 300 秒自动刷新;可选关闭、30 秒、1/5/10/30 分钟。间隔保存在
|
||||||
|
管理员配置 `downloadCheckInterval`;页面关闭后停止,隐藏时暂停定时检测。
|
||||||
|
|
||||||
|
管理员接口 `POST /admin/file/download-check` 每批最多 20 个 ID,最多并发 4 个读取,
|
||||||
|
单项超时 10 秒。复用取件码校验、下载链接签名和文件响应构造;流式文件只读取
|
||||||
|
首个小块,直链请求首字节,本地文件读取首字节。不扣取件次数,不增加下载统计,
|
||||||
|
不自动回收或删除文件。检测证明当时能开始读取,不替代完整下载和哈希校验;
|
||||||
|
不支持轻量读取的 OpenDAL 返回未检测,不退回整文件读取。
|
||||||
|
|
||||||
|
此功能先部署测试环境。生产仅恢复 BNApp64 和 godownload 的原路径:
|
||||||
|
两份回收站副本先按数据库大小及 SHA-256 完整校验;保留副本,隔离 godownload
|
||||||
|
原路径上的异常对象,再复制恢复。两项均通过实际取件接口完整下载与哈希验证,
|
||||||
|
生产代码及镜像保持不变。
|
||||||
|
|
||||||
|
### 本轮验证与部署
|
||||||
|
|
||||||
|
- 测试镜像:`local/filecodebox:2.7.0-test-download-check-07a78986f4a5`。
|
||||||
|
由后端 `32b31ac`、前端 `272741e` 加本地工作区改动打包;改动尚未提交。
|
||||||
|
`/app/download-check-build.json` 记录部署内容清单和 SHA-256。
|
||||||
|
- 本地后端 167 项通过、2 项主题测试跳过;镜像内补齐后 169 项全部通过,
|
||||||
|
总覆盖率 61%,新增检测模块 88%。前端 62 项通过,类型检查及构建通过。
|
||||||
|
Node 覆盖率报告未统计 Vite 动态载入的 composable,不能据此声称该模块 100%。
|
||||||
|
- 测试站真实 WebDAV 上传后可检测,取件次数保持不变;浏览器完成间隔保存、
|
||||||
|
刷新持久化、30 秒自动检测、手动刷新及桌面/移动端显示验收。
|
||||||
|
验收文件已清理,自动检测间隔恢复 300 秒。
|
||||||
|
- 生产 J84UF(BNApp64)和 W2ZVQ(godownload)通过完整取件下载哈希校验,
|
||||||
|
公网域名另验证下载响应 200 和 APK 首字节。真实下载验证按现有逻辑计入取件次数。
|
||||||
|
- 生产恢复数据库备份:`/root/backups/filecodebox-recover-20260918-233014`。
|
||||||
|
异常 godownload 对象保留在生产 WebDAV `recovery/20260918-233424/godownload.apk`。
|
||||||
|
测试升级备份:`/root/backups/filecodebox-download-check-20260918-234930`。
|
||||||
|
生产镜像 ID 与升级前一致。
|
||||||
|
|
||||||
|
## 测试版:查件与取件时间、表头换行(2026-09-19)
|
||||||
|
|
||||||
|
- 查件成功写入 queriedAt;旧 date 仅按查件时间兼容。点击弹窗或记录列表下载后
|
||||||
|
写入 retrievedAt,再次下载更新此值;重新查件保留已知取件时间。
|
||||||
|
未点击下载显示“尚未取件”,时间仅代表下载点击,不代表下载完成。
|
||||||
|
沿用浏览器当前会话记录,不追溯历史下载,也不新增跨设备记录能力。
|
||||||
|
- 共用表格的短表头不换行,宽度不足时在表格内部横向滚动。
|
||||||
|
- 测试镜像 `local/filecodebox:2.7.0-test-retrieve-times-42313b729baa`;
|
||||||
|
后端沿用前一测试镜像,前端由当前未提交工作区构建。
|
||||||
|
`/app/retrieve-times-build.json` 记录前端源码和构建文件 SHA-256。
|
||||||
|
- 前端单元/集成 68 项通过,新增时间工具覆盖率 100%,类型和架构检查、构建通过。
|
||||||
|
后端回归 167 项通过、2 项主题测试跳过,总覆盖率 61%;后端本轮未改动,
|
||||||
|
前次测试镜像含主题的 169 项验证已通过。
|
||||||
|
- 真实测试站创建独立次数限制文件,验证查件次数为 0,弹窗下载后为 1,
|
||||||
|
再查件保持 1,历史记录下载后为 2;两种时间显示符合定义。验收文件已清理。
|
||||||
|
- 测试升级备份:`/root/backups/filecodebox-retrieve-times-20260919-000906`。
|
||||||
|
生产镜像保持不变。
|
||||||
|
|
||||||
|
## 测试版:表格列宽与查件生命周期(2026-09-19)
|
||||||
|
|
||||||
|
- 所有文件、历史文件和下载排行的表头居中且不换行;可拖动表头右侧调整列宽,
|
||||||
|
保留表头最小宽度,超出容器时横向滚动。下载状态只显示标签和检测时间。
|
||||||
|
- 查码成功记录 lookup 事件(零传输流量),与 download 事件按时间排列在已有
|
||||||
|
取件记录中,共用展开/收起。失败查码、元数据预览和定时检测不增加查件事件。
|
||||||
|
历史没有查件事件的记录不推算补填,原下载统计保持兼容。
|
||||||
|
- 文本及不限次数的直链分享也先返回签名下载入口,查件不再消耗次数或计入下载。
|
||||||
|
文本点击下载返回文本附件;第三方直链在实际下载入口记录后跳转,保留直连传输。
|
||||||
|
- 筛选面板的顶部间距移入动画容器内部,避免收起结束时外边距突然消失。
|
||||||
|
- 前端 72 项单元/集成通过;列宽工具覆盖率 100%,Vite SSR 模块不纳入 Node 原生覆盖率。
|
||||||
|
后端 171 项通过、2 项旧主题构建测试本地跳过,总覆盖率 62%。
|
||||||
|
浏览器三处表格拖拽、窄屏、快速展开收起通过;筛选收起末段最大帧间变化 0.31px。
|
||||||
|
- 部署流程:必须先提交并推送前后端代码,再由已推送提交打包构建测试镜像;
|
||||||
|
不再使用未提交的工作区部署。生产升级仍需用户验收后明确授权。
|
||||||
@@ -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):
|
class FileViewPresetDeleteData(BaseModel):
|
||||||
id: str
|
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,
|
"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):
|
for index, stat in enumerate(download_stats, start=1):
|
||||||
timeline.append(
|
events.append(
|
||||||
{
|
{
|
||||||
"key": "retrieved_event",
|
"key": "retrieved_event",
|
||||||
"status": "done",
|
"status": "done",
|
||||||
@@ -1490,6 +1503,7 @@ class FileService(TrashManagementMixin):
|
|||||||
"detail": stat.ip or "",
|
"detail": stat.ip or "",
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
timeline.extend(sorted(events, key=lambda event: event["timestamp"]))
|
||||||
return timeline
|
return timeline
|
||||||
|
|
||||||
def _seconds_between(
|
def _seconds_between(
|
||||||
@@ -1710,6 +1724,7 @@ class ConfigService:
|
|||||||
"trashRetentionDays",
|
"trashRetentionDays",
|
||||||
"enableChunk",
|
"enableChunk",
|
||||||
"chunkSizeMB",
|
"chunkSizeMB",
|
||||||
|
"downloadCheckInterval",
|
||||||
"errorCount",
|
"errorCount",
|
||||||
"errorMinute",
|
"errorMinute",
|
||||||
"loginCount",
|
"loginCount",
|
||||||
@@ -1748,6 +1763,13 @@ class ConfigService:
|
|||||||
if key in settings.default_config and key not in INTERNAL_CONFIG_KEYS
|
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:
|
if "chunkSizeMB" in update_data:
|
||||||
raw_size = update_data["chunkSizeMB"]
|
raw_size = update_data["chunkSizeMB"]
|
||||||
if isinstance(raw_size, bool) or not (
|
if isinstance(raw_size, bool) or not (
|
||||||
|
|||||||
+7
-1
@@ -18,6 +18,7 @@ from apps.admin.dependencies import (
|
|||||||
)
|
)
|
||||||
from apps.admin.schemas import (
|
from apps.admin.schemas import (
|
||||||
IDData,
|
IDData,
|
||||||
|
DownloadCheckData,
|
||||||
IDsData,
|
IDsData,
|
||||||
BatchUpdateFileData,
|
BatchUpdateFileData,
|
||||||
BatchFilePolicyActionData,
|
BatchFilePolicyActionData,
|
||||||
@@ -944,4 +945,9 @@ async def update_file(
|
|||||||
count=1,
|
count=1,
|
||||||
meta={"fields": sorted(update_data.keys())},
|
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 fastapi import APIRouter, Form, Request, UploadFile, File, Depends, HTTPException
|
||||||
from pydantic import BaseModel, ValidationError
|
from pydantic import BaseModel, ValidationError
|
||||||
from starlette import status
|
from starlette import status
|
||||||
from starlette.responses import Response
|
from starlette.responses import Response, RedirectResponse
|
||||||
from tortoise.expressions import Case, F, Q, When
|
from tortoise.expressions import Case, F, Q, When
|
||||||
|
|
||||||
from apps.admin.dependencies import share_required_login
|
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()
|
file_code = await FileCodes.filter(code=normalized_code, is_trashed=False).first()
|
||||||
if not file_code:
|
if not file_code:
|
||||||
return False, "文件不存在"
|
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 False, "文件已过期"
|
||||||
return True, file_code
|
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(
|
async def build_select_detail(
|
||||||
file_code: FileCodes, file_storage: FileStorageInterface
|
file_code: FileCodes, file_storage: FileStorageInterface
|
||||||
) -> dict:
|
) -> dict:
|
||||||
metadata = build_file_metadata(file_code)
|
metadata = build_file_metadata(file_code)
|
||||||
if file_code.text is not None:
|
# Lookup never counts as retrieval; all downloads first pass this signed entry.
|
||||||
download_url = None
|
# Unlimited direct storage links still redirect at download time.
|
||||||
elif file_code.expired_count >= 0 or is_local_ref(file_code):
|
download_url = await get_proxy_file_url(file_code.code)
|
||||||
# 有次数限制的文件必须经过下载接口,第三方直链无法阻止重复使用。
|
|
||||||
download_url = await get_proxy_file_url(file_code.code)
|
|
||||||
else:
|
|
||||||
download_url = await file_storage.get_file_url(file_code)
|
|
||||||
content = file_code.text if file_code.text is not None else None
|
content = file_code.text if file_code.text is not None else None
|
||||||
return {
|
return {
|
||||||
**metadata,
|
**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):
|
if not await consume_file_usage(file_code):
|
||||||
return APIResponse(code=404, detail="文件已过期")
|
return APIResponse(code=404, detail="文件已过期")
|
||||||
await record_transfer_stat("download", file_code, file_code.size, ip)
|
await record_transfer_stat("download", file_code, file_code.size, ip)
|
||||||
if file_code.text is not None:
|
return await build_download_response(file_code, file_storage)
|
||||||
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))
|
|
||||||
|
|
||||||
|
|
||||||
@share_api.post("/select/")
|
@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)
|
assert isinstance(file_code, FileCodes)
|
||||||
detail = await build_select_detail(file_code, file_storage)
|
detail = await build_select_detail(file_code, file_storage)
|
||||||
download_url = detail.get("download_url")
|
await record_transfer_stat("lookup", file_code, 0, ip)
|
||||||
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))
|
|
||||||
return APIResponse(detail=detail)
|
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="文件已过期")
|
return APIResponse(code=404, detail="文件已过期")
|
||||||
await record_transfer_stat("download", file_code, file_code.size, ip)
|
await record_transfer_stat("download", file_code, file_code.size, ip)
|
||||||
|
|
||||||
return (
|
return await build_download_response(file_code, file_storage)
|
||||||
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))
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
chunk_api = APIRouter(prefix="/chunk", tags=["切片"])
|
chunk_api = APIRouter(prefix="/chunk", tags=["切片"])
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ DEFAULT_CONFIG = {
|
|||||||
"uploadMinute": 1,
|
"uploadMinute": 1,
|
||||||
"enableChunk": 0,
|
"enableChunk": 0,
|
||||||
"chunkSizeMB": 90,
|
"chunkSizeMB": 90,
|
||||||
|
"downloadCheckInterval": 300,
|
||||||
"webdav_url": "",
|
"webdav_url": "",
|
||||||
"webdav_password": "",
|
"webdav_password": "",
|
||||||
"webdav_username": "",
|
"webdav_username": "",
|
||||||
|
|||||||
@@ -1229,6 +1229,9 @@ class WebDAVFileStorage(WebDAVStreamMixin, WebDAVOffsetMixin, FileStorageInterfa
|
|||||||
except (aiohttp.ClientError, asyncio.TimeoutError) as exc:
|
except (aiohttp.ClientError, asyncio.TimeoutError) as exc:
|
||||||
await session.close()
|
await session.close()
|
||||||
raise HTTPException(503, "WebDAV 连接失败,请稍后重试") from exc
|
raise HTTPException(503, "WebDAV 连接失败,请稍后重试") from exc
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
await session.close()
|
||||||
|
raise
|
||||||
|
|
||||||
async def stream_generator():
|
async def stream_generator():
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -0,0 +1,190 @@
|
|||||||
|
import asyncio
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from aiohttp import web
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from starlette.responses import StreamingResponse
|
||||||
|
from apps.admin.views import admin_api
|
||||||
|
from apps.admin.dependencies import admin_required
|
||||||
|
from apps.admin.download_checks import _read_response
|
||||||
|
from apps.base.models import FileCodes, KeyValue, TransferStats
|
||||||
|
from core.settings import settings
|
||||||
|
from tests.helpers import init_memory_db, close_db
|
||||||
|
|
||||||
|
|
||||||
|
class DownloadCheckTests(unittest.IsolatedAsyncioTestCase):
|
||||||
|
async def asyncSetUp(self):
|
||||||
|
self.original = dict(settings.user_config)
|
||||||
|
await init_memory_db()
|
||||||
|
self.status = 200
|
||||||
|
self.data = b'file content'
|
||||||
|
self.requests = 0
|
||||||
|
upstream = web.Application()
|
||||||
|
upstream.router.add_get('/dav/{path:.*}', self.upstream)
|
||||||
|
self.runner = web.AppRunner(upstream)
|
||||||
|
await self.runner.setup()
|
||||||
|
site = web.TCPSite(self.runner, '127.0.0.1', 0)
|
||||||
|
await site.start()
|
||||||
|
port = site._server.sockets[0].getsockname()[1]
|
||||||
|
settings.user_config = {'file_storage': 'webdav', 'jwt_secret': 'test-secret',
|
||||||
|
'webdav_url': f'http://127.0.0.1:{port}/dav',
|
||||||
|
'webdav_username': 'test', 'webdav_password': 'test'}
|
||||||
|
await KeyValue.create(key='settings', value=dict(settings.user_config))
|
||||||
|
self.file = await FileCodes.create(code='CHECK123', prefix='a', suffix='.txt',
|
||||||
|
file_path='share/test', uuid_file_name='a.txt', size=len(self.data), expired_count=2)
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(admin_api)
|
||||||
|
app.dependency_overrides[admin_required] = lambda: True
|
||||||
|
self.app = app
|
||||||
|
self.client = httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test')
|
||||||
|
|
||||||
|
async def asyncTearDown(self):
|
||||||
|
await self.client.aclose()
|
||||||
|
await self.runner.cleanup()
|
||||||
|
await close_db()
|
||||||
|
settings.user_config = self.original
|
||||||
|
|
||||||
|
async def upstream(self, request):
|
||||||
|
self.requests += 1
|
||||||
|
return web.Response(status=self.status, body=self.data if self.status == 200 else b'failure')
|
||||||
|
|
||||||
|
async def check(self, ids=None):
|
||||||
|
response = await self.client.post('/admin/file/download-check', json={'ids': ids or [self.file.id]})
|
||||||
|
self.assertEqual(response.status_code, 200, response.text)
|
||||||
|
return response.json()['detail']
|
||||||
|
|
||||||
|
async def test_real_webdav_read_without_usage_or_audit_side_effects(self):
|
||||||
|
rows = await self.check([self.file.id, self.file.id])
|
||||||
|
self.assertEqual(len(rows), 1)
|
||||||
|
self.assertEqual(rows[0]['status'], 'available', rows)
|
||||||
|
self.assertIsNotNone(rows[0]['checkedAt'])
|
||||||
|
self.assertEqual(self.requests, 1)
|
||||||
|
await self.file.refresh_from_db()
|
||||||
|
self.assertEqual(self.file.expired_count, 2)
|
||||||
|
self.assertEqual(self.file.used_count, 0)
|
||||||
|
self.assertEqual(await TransferStats.all().count(), 0)
|
||||||
|
|
||||||
|
async def test_404_416_and_size_mismatch_are_unavailable(self):
|
||||||
|
for status in [404, 416, 401]:
|
||||||
|
self.status = status
|
||||||
|
self.assertEqual((await self.check())[0]['status'], 'unavailable')
|
||||||
|
self.status = 200
|
||||||
|
self.data = b'wrong size'
|
||||||
|
self.assertEqual((await self.check())[0]['status'], 'unavailable')
|
||||||
|
|
||||||
|
async def test_expired_trashed_missing_and_text_batch(self):
|
||||||
|
self.file.expired_count = 0
|
||||||
|
await self.file.save()
|
||||||
|
text = await FileCodes.create(code='TEXT1234', text='', size=0)
|
||||||
|
trash = await FileCodes.create(code='TRASH123', is_trashed=True)
|
||||||
|
rows = await self.check([self.file.id, text.id, trash.id, 999])
|
||||||
|
self.assertEqual([row['status'] for row in rows], ['unavailable', 'available', 'unavailable', 'unavailable'])
|
||||||
|
self.assertEqual(self.requests, 0)
|
||||||
|
|
||||||
|
async def test_timeout_is_reported_without_failing_the_batch(self):
|
||||||
|
async def slow(_):
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
with patch('apps.admin.download_checks.CHECK_TIMEOUT', 0.01), patch('apps.admin.download_checks._probe', slow):
|
||||||
|
rows = await self.check()
|
||||||
|
self.assertEqual(rows[0]['message'], '检测超时,请重试')
|
||||||
|
|
||||||
|
async def test_local_file_reads_and_missing_are_detected(self):
|
||||||
|
settings.file_storage = 'local'
|
||||||
|
with tempfile.TemporaryDirectory() as directory, patch('core.storage.data_root', Path(directory)):
|
||||||
|
path = Path(directory) / 'share/test/a.txt'
|
||||||
|
path.parent.mkdir(parents=True)
|
||||||
|
path.write_bytes(self.data)
|
||||||
|
self.assertEqual((await self.check())[0]['status'], 'available')
|
||||||
|
path.unlink()
|
||||||
|
self.assertEqual((await self.check())[0]['status'], 'unavailable')
|
||||||
|
|
||||||
|
async def test_direct_link_is_read_not_just_head(self):
|
||||||
|
from core.storage import WebDAVFileStorage
|
||||||
|
with patch.object(WebDAVFileStorage, 'get_file_url', return_value=settings.webdav_url + '/direct'):
|
||||||
|
self.file.expired_count = -1
|
||||||
|
await self.file.save()
|
||||||
|
self.assertEqual((await self.check())[0]['status'], 'available')
|
||||||
|
self.status = 404
|
||||||
|
self.assertEqual((await self.check())[0]['status'], 'unavailable')
|
||||||
|
|
||||||
|
async def test_admin_auth_and_batch_validation(self):
|
||||||
|
for ids in [[], [0], ['1'], list(range(1, 22))]:
|
||||||
|
result = await self.client.post('/admin/file/download-check', json={'ids': ids})
|
||||||
|
self.assertEqual(result.status_code, 422)
|
||||||
|
self.app.dependency_overrides.clear()
|
||||||
|
result = await self.client.post('/admin/file/download-check', json={'ids': [1]})
|
||||||
|
self.assertEqual(result.status_code, 401)
|
||||||
|
|
||||||
|
async def test_interval_persistence_and_invalid_config(self):
|
||||||
|
for interval in [0, 30, 300, 86400]:
|
||||||
|
result = await self.client.patch('/admin/config/update', json={'downloadCheckInterval': interval})
|
||||||
|
self.assertEqual(result.status_code, 200, result.text)
|
||||||
|
result = await self.client.get('/admin/config/get')
|
||||||
|
self.assertEqual(result.json()['detail']['downloadCheckInterval'], interval)
|
||||||
|
for interval in [-1, 1, 29, 86401, True, '30', 30.5]:
|
||||||
|
result = await self.client.patch('/admin/config/update', json={'downloadCheckInterval': interval})
|
||||||
|
self.assertEqual(result.status_code, 400)
|
||||||
|
|
||||||
|
async def test_probe_stops_stream_and_closes_on_read_failure(self):
|
||||||
|
closed = []
|
||||||
|
async def stream():
|
||||||
|
try:
|
||||||
|
yield b'x'
|
||||||
|
raise AssertionError('must not read the entire file')
|
||||||
|
finally:
|
||||||
|
closed.append(True)
|
||||||
|
await _read_response(StreamingResponse(stream()), 100)
|
||||||
|
self.assertEqual(closed, [True])
|
||||||
|
async def broken():
|
||||||
|
try:
|
||||||
|
raise OSError('connection lost')
|
||||||
|
yield b''
|
||||||
|
finally:
|
||||||
|
closed.append(True)
|
||||||
|
with self.assertRaises(OSError):
|
||||||
|
await _read_response(StreamingResponse(broken()), 100)
|
||||||
|
self.assertEqual(len(closed), 2)
|
||||||
|
|
||||||
|
async def test_local_reference_uses_nas_file_even_with_webdav_selected(self):
|
||||||
|
self.file.file_path = 'local-ref'
|
||||||
|
self.file.uuid_file_name = 'a.txt'
|
||||||
|
await self.file.save()
|
||||||
|
with tempfile.TemporaryDirectory() as directory, patch('core.settings.data_root', Path(directory)):
|
||||||
|
path = Path(directory) / 'local/a.txt'
|
||||||
|
path.parent.mkdir()
|
||||||
|
path.write_bytes(self.data)
|
||||||
|
self.assertEqual((await self.check())[0]['status'], 'available')
|
||||||
|
path.unlink()
|
||||||
|
self.assertEqual((await self.check())[0]['status'], 'unavailable')
|
||||||
|
self.assertEqual(self.requests, 0)
|
||||||
|
|
||||||
|
async def test_empty_local_file_and_expired_share(self):
|
||||||
|
import datetime
|
||||||
|
from core.utils import get_now
|
||||||
|
settings.file_storage = 'local'
|
||||||
|
self.file.size = 0
|
||||||
|
await self.file.save()
|
||||||
|
with tempfile.TemporaryDirectory() as directory, patch('core.storage.data_root', Path(directory)):
|
||||||
|
path = Path(directory) / 'share/test/a.txt'
|
||||||
|
path.parent.mkdir(parents=True)
|
||||||
|
path.write_bytes(b'')
|
||||||
|
self.assertEqual((await self.check())[0]['status'], 'available')
|
||||||
|
self.file.expired_at = await get_now() - datetime.timedelta(seconds=1)
|
||||||
|
self.file.expired_count = -1
|
||||||
|
await self.file.save()
|
||||||
|
self.assertEqual((await self.check())[0]['status'], 'unavailable')
|
||||||
|
|
||||||
|
async def test_network_failure_and_empty_body_are_unavailable(self):
|
||||||
|
from unittest.mock import AsyncMock
|
||||||
|
from core.storage import WebDAVFileStorage
|
||||||
|
with patch.object(WebDAVFileStorage, 'get_file_response', side_effect=OSError('connection lost')):
|
||||||
|
self.assertEqual((await self.check())[0]['status'], 'unavailable')
|
||||||
|
async def empty():
|
||||||
|
if False:
|
||||||
|
yield b''
|
||||||
|
with patch.object(WebDAVFileStorage, 'get_file_response', new=AsyncMock(return_value=StreamingResponse(empty()))):
|
||||||
|
self.assertEqual((await self.check())[0]['status'], 'unavailable')
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from starlette.responses import Response
|
||||||
|
from apps.admin.dependencies import admin_required
|
||||||
|
from apps.admin.views import admin_api
|
||||||
|
from apps.base.models import FileCodes, TransferStats
|
||||||
|
from apps.base.views import share_api, storages
|
||||||
|
from core.settings import settings
|
||||||
|
from tests.helpers import init_memory_db, close_db
|
||||||
|
|
||||||
|
|
||||||
|
class Storage:
|
||||||
|
async def get_file_url(self, file):
|
||||||
|
return 'https://storage.example/file'
|
||||||
|
|
||||||
|
async def get_file_response(self, file):
|
||||||
|
return Response(b'abc')
|
||||||
|
|
||||||
|
|
||||||
|
class LookupLifecycleTests(unittest.IsolatedAsyncioTestCase):
|
||||||
|
async def asyncSetUp(self):
|
||||||
|
self.original = dict(settings.user_config)
|
||||||
|
settings.user_config = {'file_storage': 'local', 'jwt_secret': 'lookup-test-secret'}
|
||||||
|
await init_memory_db()
|
||||||
|
self.file = await FileCodes.create(code='LOOK2345', prefix='sample', suffix='.txt', size=3, expired_count=3)
|
||||||
|
self.patch = patch.dict(storages, {'local': Storage})
|
||||||
|
self.patch.start()
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(share_api)
|
||||||
|
app.include_router(admin_api)
|
||||||
|
app.dependency_overrides[admin_required] = lambda: True
|
||||||
|
self.client = httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test')
|
||||||
|
|
||||||
|
async def asyncTearDown(self):
|
||||||
|
await self.client.aclose()
|
||||||
|
self.patch.stop()
|
||||||
|
await close_db()
|
||||||
|
settings.user_config = self.original
|
||||||
|
|
||||||
|
async def lookup(self):
|
||||||
|
result = await self.client.post('/share/select/', json={'code': self.file.code})
|
||||||
|
self.assertEqual(result.status_code, 200)
|
||||||
|
self.assertEqual(result.json()['code'], 200)
|
||||||
|
return result.json()['detail']
|
||||||
|
|
||||||
|
async def test_lookup_and_download_are_distinct_chronological_events(self):
|
||||||
|
first = await self.lookup()
|
||||||
|
await self.file.refresh_from_db()
|
||||||
|
self.assertEqual(self.file.used_count, 0)
|
||||||
|
self.assertEqual(self.file.expired_count, 3)
|
||||||
|
self.assertEqual((await TransferStats.get(action='lookup')).size, 0)
|
||||||
|
self.assertEqual(await TransferStats.filter(action='download').count(), 0)
|
||||||
|
download = await self.client.get(first['download_url'])
|
||||||
|
self.assertEqual(download.content, b'abc')
|
||||||
|
await self.lookup()
|
||||||
|
await self.file.refresh_from_db()
|
||||||
|
self.assertEqual(self.file.used_count, 1)
|
||||||
|
self.assertEqual(self.file.expired_count, 2)
|
||||||
|
detail = await self.client.get('/admin/file/detail', params={'id': self.file.id})
|
||||||
|
self.assertEqual(detail.status_code, 200, detail.text)
|
||||||
|
timeline = detail.json()['detail']['timeline']
|
||||||
|
events = [item for item in timeline if item['key'] in ('queried_event', 'retrieved_event')]
|
||||||
|
self.assertEqual([item['key'] for item in events], ['queried_event', 'retrieved_event', 'queried_event'])
|
||||||
|
self.assertEqual([item['value'] for item in events], [1, 1, 2])
|
||||||
|
self.assertTrue(all(item['detail'] == '127.0.0.1' and item['timestamp'] for item in events))
|
||||||
|
summary = next(item for item in timeline if item['key'] == 'retrieved')
|
||||||
|
self.assertEqual(summary['value'], 1)
|
||||||
|
|
||||||
|
async def test_metadata_failed_and_expired_lookups_do_not_create_events(self):
|
||||||
|
await self.client.get('/share/metadata/', params={'code': self.file.code})
|
||||||
|
await self.client.post('/share/select/', json={'code': 'NONEXIST'})
|
||||||
|
self.file.expired_count = 0
|
||||||
|
await self.file.save()
|
||||||
|
await self.client.post('/share/select/', json={'code': self.file.code})
|
||||||
|
self.assertEqual(await TransferStats.all().count(), 0)
|
||||||
|
|
||||||
|
async def test_text_lookup_preserves_usage_and_signed_click_downloads_empty_text(self):
|
||||||
|
self.file.text = ''
|
||||||
|
self.file.size = 0
|
||||||
|
await self.file.save()
|
||||||
|
detail = await self.lookup()
|
||||||
|
self.assertEqual(detail['content'], '')
|
||||||
|
self.assertEqual(detail['used_count'], 0)
|
||||||
|
download = await self.client.get(detail['download_url'])
|
||||||
|
self.assertEqual(download.status_code, 200)
|
||||||
|
self.assertEqual(download.content, b'')
|
||||||
|
self.assertIn('attachment;', download.headers['content-disposition'])
|
||||||
|
self.assertEqual(await TransferStats.filter(action='download').count(), 1)
|
||||||
|
|
||||||
|
async def test_unlimited_direct_link_is_redirected_only_after_download_click(self):
|
||||||
|
self.file.expired_count = -1
|
||||||
|
await self.file.save()
|
||||||
|
detail = await self.lookup()
|
||||||
|
self.assertTrue(detail['download_url'].startswith('/share/download?'))
|
||||||
|
self.assertEqual(await TransferStats.filter(action='download').count(), 0)
|
||||||
|
download = await self.client.get(detail['download_url'])
|
||||||
|
self.assertEqual(download.status_code, 307)
|
||||||
|
self.assertEqual(download.headers['location'], 'https://storage.example/file')
|
||||||
|
self.assertEqual(await TransferStats.filter(action='download').count(), 1)
|
||||||
@@ -131,7 +131,8 @@ class SecurityPatchTests(unittest.TestCase):
|
|||||||
result = await views.download_file(
|
result = await views.download_file(
|
||||||
key=current, code=code, ip="127.0.0.1"
|
key=current, code=code, ip="127.0.0.1"
|
||||||
)
|
)
|
||||||
self.assertEqual(result, {"downloaded": code})
|
self.assertEqual(result.status_code, 307)
|
||||||
|
self.assertEqual(result.headers["location"], f"https://example.invalid/{code}")
|
||||||
finally:
|
finally:
|
||||||
settings.user_config = original
|
settings.user_config = original
|
||||||
await Tortoise.close_connections()
|
await Tortoise.close_connections()
|
||||||
|
|||||||
Reference in new issue
Block a user