✨ feat: 合并手动下载检测、查件生命周期与可靠上传
* 默认关闭自动检测,提供管理员全量枚举与不消耗次数的下载验证 * 查件写入独立事件,实际下载才计取件,统一签名下载入口 * 完善 WebDAV 分片流式合并、取消清理与分片大小配置 * 修正回收及历史状态,保护已发布文件免受会话清理影响 * 固定前端 main 正式提交,记录测试站验证和正式构建发布流程
This commit is contained in:
commit
6fc56a27d4
21 files changed
+1258
-160
No files matched your search
@@ -1 +1 @@
|
|||||||
da54bf40c9f3f7bb18ac5890b4e89e2a01724bd2
|
519aee1d12e6619767df83839538cbfa100064f5
|
||||||
+150
@@ -110,3 +110,153 @@ WebDAV 保持 legacy 路径。新模式仍支持重试、续传、取消、配
|
|||||||
|
|
||||||
部署按新前端+后端同镜像进行。回滚旧镜像前应完成或取消新模式会话,旧代码
|
部署按新前端+后端同镜像进行。回滚旧镜像前应完成或取消新模式会话,旧代码
|
||||||
不认识偏移暂存对象;不得在活动新会话存在时直接恢复旧数据库。
|
不认识偏移暂存对象;不得在活动新会话存在时直接恢复旧数据库。
|
||||||
|
|
||||||
|
## 测试版:中断上传、100MB 与历史状态
|
||||||
|
|
||||||
|
后续修复只推 `test/custom-admin-ui` 并部署测试容器;用户验收后才能更新正式分支和生产。
|
||||||
|
发送页新增中断上传:终止客户端传输/轮询,清理远端临时会话并释放配额;请求晚于
|
||||||
|
文件发布时返回原取件码而不误删已发布文件。清理失败保留会话供重试。S3 直传取消
|
||||||
|
保留取消记录至签名到期,后台清理可能迟到的 PUT,期间禁止确认发布。
|
||||||
|
|
||||||
|
分片最大为 100 MiB (`104857600` 字节),实际最后一片可小于此值;新增原始请求体
|
||||||
|
`/chunk/upload/raw/{upload_id}/{chunk_index}`,兼容旧 multipart 端点。测试站反代上限
|
||||||
|
128m;CloudDrive `/dav/` 取消请求大小上限并关闭请求缓冲,因为流式合并的 PUT
|
||||||
|
是完整文件大小。生产 FileCodeBox 配置保持不变。测试站的 Cloudflare 边缘限制
|
||||||
|
通过实际 100 MiB 请求验证,Nginx 调高不代表 CDN 限制自动改变。
|
||||||
|
|
||||||
|
历史文件状态以数据库当前回收站字段为准,不再把审计保留记录计为“现存”。可恢复
|
||||||
|
记录使用回收站相同原因标签;已清理显示“已清理”;有恢复事件的现存文件显示
|
||||||
|
“现存,已从回收站恢复”;从未回收的文件显示“现存”。恢复后再次回收以当前原因
|
||||||
|
为准,旧永久删除记录保留“已删除”。恢复事件查询独立于分析日期范围。
|
||||||
|
|
||||||
|
## 分片大小设置
|
||||||
|
|
||||||
|
后台“系统设置 → 上传限制 → 上传分片大小”可配置 `chunkSizeMB`,范围 1–100 整数,
|
||||||
|
默认 90。单位 MB 在本程序中按 MiB(1024×1024 字节)换算。
|
||||||
|
保存后公共配置接口同步下发,前端用于新上传,后端对新会话再次限幅;客户端缓存
|
||||||
|
尚未刷新时,服务端返回的协商大小仍为准。已有上传沿用原大小,调整设置不改变
|
||||||
|
续传偏移。最后一片按实际剩余字节检查,上传上限不按分片补齐后的大小计算。
|
||||||
|
|
||||||
|
此值控制分片,不保证代理/CDN支持整文件 PUT;WebDAV流式合并仍以完整文件大小
|
||||||
|
发起最终PUT,代理限制需要独立验证。当前测试环境继续使用公网 cd2 地址;
|
||||||
|
90 MiB 分片及90 MiB+3字节整文件已实测上传、合并、下载SHA-256一致并清理。
|
||||||
|
|
||||||
|
### 分片配置测试验收(2026-09-18)
|
||||||
|
|
||||||
|
- 测试镜像后端 `5c1e1ef36811d588b58927e8f82308126f65abed`,前端
|
||||||
|
`272741ee49671327964e82c3cb0dec0a81e8261d`;生产版本不变。
|
||||||
|
- 镜像内后端单元/接口集成 157 项通过,覆盖率 60%;前端 57 项通过,
|
||||||
|
类型检查、架构检查和生产构建通过。
|
||||||
|
- 在测试站真实后台把分片大小从 90 MB 改为 2 MB,刷新设置页确认持久化;
|
||||||
|
上传 3 MiB+17 字节文件,初始化请求使用 2 MiB、实际分两片完成,下载 SHA-256 一致。
|
||||||
|
- 同一验证文件的历史状态依次为现存、批量删除、现存且已恢复、已清理;
|
||||||
|
测试文件已清理。结束后恢复 chunkSizeMB=90。
|
||||||
|
- 测试 WebDAV 仍为 `https://cd2.orionc.me/dav`,保持独立测试用户和目录。
|
||||||
|
本轮未修改生产代码或生产 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。
|
||||||
|
- 部署流程:必须先提交并推送前后端代码,再由已推送提交打包构建测试镜像;
|
||||||
|
不再使用未提交的工作区部署。生产升级仍需用户验收后明确授权。
|
||||||
|
- 本轮前端构建固定为已推送的 `4fefcd0f0a82a5f1c0d293e9935f6b1e23a38658`,
|
||||||
|
`FRONTEND_2026_REVISION` 与测试镜像的来源清单保持一致。
|
||||||
|
|
||||||
|
## 测试版:仪表盘刷新按钮(2026-09-19)
|
||||||
|
|
||||||
|
- 生产部署暂停,先修复刷新按钮误用纯图标样式导致的留白与间距缺失。
|
||||||
|
- 前端固定到已推送提交 `fe6d81285744937e201d0452d6324533b58cc422`;后端运行逻辑保持不变。
|
||||||
|
- 前端 72 项单元/集成及覆盖率检查通过,类型、架构与构建通过;浏览器验证
|
||||||
|
深浅主题和 1440/640/390px 下的按钮留白、加载居中与实际刷新请求。
|
||||||
|
|
||||||
|
## 手动检测下载状态与正式分支发布(2026-09-19)
|
||||||
|
|
||||||
|
- 默认 downloadCheckInterval=0;生产配置已关闭定时检测。取消页面加载、翻页、
|
||||||
|
搜索和列表刷新触发文件读取,只有显式检测按钮才开始任务。
|
||||||
|
- 提供单文件、选中多个及全量检测;全量 ID 通过管理员接口快照枚举所有未回收文件,
|
||||||
|
不受当前列表筛选或分页限制。前端逐个请求,显示进度,取消停止后续请求。
|
||||||
|
- 本地后端 172 项通过、2 项旧主题测试待镜像内验证,覆盖率 62%;前端 75 项通过。
|
||||||
|
浏览器以 25 文件受控响应验证跨页全量、单个、勾选、取消和默认零检测请求。
|
||||||
|
- 发布顺序:测试分支提交推送 → 构建并部署测试 → 验证 → 合并前端 main、后端 master
|
||||||
|
→ 推送正式分支 → 从正式提交重新构建生产镜像 → 备份、部署及生产回归。
|
||||||
|
正式构建使用 Dockerfile.release,固定前端提交;不再把测试镜像改标签作为生产发布。
|
||||||
|
|
||||||
|
## 正式分支合并与发布验证(2026-09-19)
|
||||||
|
|
||||||
|
- 后端测试提交 `8af45a7`、前端测试提交 `3d70f67` 先推送,再构建并部署测试站。
|
||||||
|
- 测试镜像内后端 174 项全部通过,覆盖率 62%;前端 75 项及覆盖率、类型、架构、构建检查通过。
|
||||||
|
后端验证挂载同一提交的测试及构建元数据,不挂载实际环境数据。
|
||||||
|
- 测试站真实接口验证管理员鉴权、全量 ID、单个文件读取,检测不改变取件次数或生命周期。
|
||||||
|
临时文本分享验证查件后次数为 0,点击下载后为 1,事件顺序正确,验收分享已清理。
|
||||||
|
- 部署后浏览器以受控 25 文件响应验证跨页全量、单个、选中、串行和取消,以及页面加载、
|
||||||
|
刷新、翻页、模拟等待一小时均不触发检测。真实测试文件的全量按钮另行验证通过。
|
||||||
|
- 三处表格拖拽、键盘调整、窄屏通过;筛选收起末段帧间变化 0.31px,快速反转与减少动画通过。
|
||||||
|
- 前端正式 main 合并提交为 `519aee1d12e6619767df83839538cbfa100064f5`,构建固定至该提交;
|
||||||
|
后端合入 master 后推送并重新构建生产镜像。测试、生产配置均保持 downloadCheckInterval=0。
|
||||||
|
- 测试升级备份:`/root/backups/filecodebox-test-formal-20260919-013158`。
|
||||||
|
生产部署仍须先备份数据库及编排配置,并核对镜像标签与正式提交一致。
|
||||||
@@ -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)
|
||||||
+34
-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(
|
||||||
@@ -1709,6 +1723,8 @@ class ConfigService:
|
|||||||
"adminSessionExpire",
|
"adminSessionExpire",
|
||||||
"trashRetentionDays",
|
"trashRetentionDays",
|
||||||
"enableChunk",
|
"enableChunk",
|
||||||
|
"chunkSizeMB",
|
||||||
|
"downloadCheckInterval",
|
||||||
"errorCount",
|
"errorCount",
|
||||||
"errorMinute",
|
"errorMinute",
|
||||||
"loginCount",
|
"loginCount",
|
||||||
@@ -1747,6 +1763,23 @@ 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:
|
||||||
|
raw_size = update_data["chunkSizeMB"]
|
||||||
|
if isinstance(raw_size, bool) or not (
|
||||||
|
isinstance(raw_size, int) or
|
||||||
|
isinstance(raw_size, str) and raw_size.strip().isdigit()
|
||||||
|
):
|
||||||
|
raise HTTPException(400, "分片大小必须是 1–100 MB 的整数")
|
||||||
|
if not 1 <= int(raw_size) <= 100:
|
||||||
|
raise HTTPException(400, "分片大小必须是 1–100 MB 的整数")
|
||||||
|
|
||||||
admin_token = update_data.get("admin_token")
|
admin_token = update_data.get("admin_token")
|
||||||
admin_password_changed = False
|
admin_password_changed = False
|
||||||
if admin_token is None or admin_token == "":
|
if admin_token is None or admin_token == "":
|
||||||
|
|||||||
+36
-6
@@ -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,
|
||||||
@@ -248,6 +249,7 @@ async def analytics(start: str = "", end: str = ""):
|
|||||||
|
|
||||||
files = await FileCodes.all()
|
files = await FileCodes.all()
|
||||||
file_map = {item.code: item for item in files}
|
file_map = {item.code: item for item in files}
|
||||||
|
restored_ids = set(await TransferStats.filter(action="restore",file_code_id__isnull=False).values_list("file_code_id",flat=True))
|
||||||
|
|
||||||
day_map = {}
|
day_map = {}
|
||||||
cursor = start_day
|
cursor = start_day
|
||||||
@@ -371,6 +373,15 @@ async def analytics(start: str = "", end: str = ""):
|
|||||||
uploaded_at = file_item.created_at if file_item else data.get("uploaded_at")
|
uploaded_at = file_item.created_at if file_item else data.get("uploaded_at")
|
||||||
expired_at = file_item.expired_at if file_item else data.get("expired_at")
|
expired_at = file_item.expired_at if file_item else data.get("expired_at")
|
||||||
size = int(file_item.size or 0) if file_item else data.get("size") or 0
|
size = int(file_item.size or 0) if file_item else data.get("size") or 0
|
||||||
|
trashed = bool(file_item and file_item.is_trashed)
|
||||||
|
purged = bool(file_item and file_item.trash_purged_at is not None)
|
||||||
|
expired = current_file_expired(file_item)
|
||||||
|
current = bool(file_item) and not trashed and not purged
|
||||||
|
state = (
|
||||||
|
"purged" if purged else "trashed" if trashed else
|
||||||
|
"expired" if current and expired else "active" if current else
|
||||||
|
"deleted" if data.get("deleted") else "history"
|
||||||
|
)
|
||||||
return {
|
return {
|
||||||
"code": code,
|
"code": code,
|
||||||
"name": current_name or data.get("name") or code,
|
"name": current_name or data.get("name") or code,
|
||||||
@@ -379,13 +390,21 @@ async def analytics(start: str = "", end: str = ""):
|
|||||||
"download_traffic": str(data.get("downloadTraffic") or 0),
|
"download_traffic": str(data.get("downloadTraffic") or 0),
|
||||||
"upload_count": data.get("uploads") or 0,
|
"upload_count": data.get("uploads") or 0,
|
||||||
"upload_traffic": str(data.get("uploadTraffic") or 0),
|
"upload_traffic": str(data.get("uploadTraffic") or 0),
|
||||||
"current": bool(file_item),
|
"current": current,
|
||||||
"expired": current_file_expired(file_item),
|
"expired": expired,
|
||||||
"deleted": bool(data.get("deleted")) and not bool(file_item),
|
"deleted": purged or (bool(data.get("deleted")) and not bool(file_item)),
|
||||||
|
"status": state,
|
||||||
|
"is_trashed": trashed,
|
||||||
|
"trash_reason": file_item.trash_reason if file_item else None,
|
||||||
|
"was_restored": bool(file_item and file_item.id in restored_ids),
|
||||||
|
"is_purged": purged,
|
||||||
|
"can_download": current and not expired,
|
||||||
|
"trashed_at": iso(file_item.trashed_at) if file_item else "",
|
||||||
|
"purged_at": iso(file_item.trash_purged_at) if file_item else "",
|
||||||
"created_at": iso(uploaded_at),
|
"created_at": iso(uploaded_at),
|
||||||
"uploaded_at": iso(uploaded_at),
|
"uploaded_at": iso(uploaded_at),
|
||||||
"expired_at": iso(expired_at),
|
"expired_at": iso(expired_at),
|
||||||
"deleted_at": iso(data.get("deleted_at")),
|
"deleted_at": iso(file_item.trash_purged_at or file_item.trashed_at) if trashed or purged else iso(data.get("deleted_at")),
|
||||||
}
|
}
|
||||||
|
|
||||||
def sort_time(value) -> float:
|
def sort_time(value) -> float:
|
||||||
@@ -422,7 +441,7 @@ async def analytics(start: str = "", end: str = ""):
|
|||||||
sum(row["downloadTraffic"] for row in daily_rows)
|
sum(row["downloadTraffic"] for row in daily_rows)
|
||||||
),
|
),
|
||||||
"historicalFiles": len(file_stats),
|
"historicalFiles": len(file_stats),
|
||||||
"currentFiles": len(files),
|
"currentFiles": sum(not item.is_trashed and item.trash_purged_at is None for item in files),
|
||||||
"totalUploads": sum(row["uploads"] for row in daily_rows),
|
"totalUploads": sum(row["uploads"] for row in daily_rows),
|
||||||
"uploadTraffic": str(
|
"uploadTraffic": str(
|
||||||
sum(row["uploadTraffic"] for row in daily_rows)
|
sum(row["uploadTraffic"] for row in daily_rows)
|
||||||
@@ -926,4 +945,15 @@ 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))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.get("/file/download-check-ids")
|
||||||
|
async def file_download_check_ids():
|
||||||
|
ids = await FileCodes.filter(is_trashed=False).order_by("id").values_list("id", flat=True)
|
||||||
|
return APIResponse(detail=ids)
|
||||||
+122
-72
@@ -1,5 +1,6 @@
|
|||||||
import datetime
|
import datetime
|
||||||
import hashlib
|
import hashlib
|
||||||
|
from io import BytesIO
|
||||||
import os
|
import os
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
@@ -10,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
|
||||||
@@ -243,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
|
||||||
|
|
||||||
@@ -289,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,
|
||||||
@@ -347,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/")
|
||||||
@@ -372,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)
|
||||||
|
|
||||||
|
|
||||||
@@ -405,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=["切片"])
|
||||||
@@ -441,7 +431,11 @@ async def parse_complete_upload(request: Request) -> CompleteUploadModel:
|
|||||||
async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chunk_upload)):
|
async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chunk_upload)):
|
||||||
safe_file_name = await sanitize_filename(unquote(data.file_name or ""))
|
safe_file_name = await sanitize_filename(unquote(data.file_name or ""))
|
||||||
validate_file_type(safe_file_name)
|
validate_file_type(safe_file_name)
|
||||||
# 服务端校验:根据 total_chunks * chunk_size 计算理论最大上传量
|
# New sessions negotiate the smaller client/server size. Existing sessions
|
||||||
|
# below retain their original offsets when an administrator changes this.
|
||||||
|
configured_mb = max(1, min(100, int(settings.chunkSizeMB)))
|
||||||
|
data.chunk_size = min(data.chunk_size, configured_mb * 1024 * 1024, data.file_size)
|
||||||
|
# File limits concern actual bytes, not a rounded-up final chunk.
|
||||||
total_chunks = (data.file_size + data.chunk_size - 1) // data.chunk_size
|
total_chunks = (data.file_size + data.chunk_size - 1) // data.chunk_size
|
||||||
max_possible_size = data.file_size
|
max_possible_size = data.file_size
|
||||||
if max_possible_size > settings.uploadSize:
|
if max_possible_size > settings.uploadSize:
|
||||||
@@ -465,6 +459,9 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
|||||||
# "name": f'{existing.prefix}{existing.suffix}'
|
# "name": f'{existing.prefix}{existing.suffix}'
|
||||||
# })
|
# })
|
||||||
|
|
||||||
|
preferred_mode = "legacy"
|
||||||
|
if settings.file_storage == "webdav":
|
||||||
|
preferred_mode = await storages["webdav"]().chunk_upload_mode()
|
||||||
# 断点续传:检查是否存在相同文件的未完成上传会话
|
# 断点续传:检查是否存在相同文件的未完成上传会话
|
||||||
existing_session = await UploadChunk.filter(
|
existing_session = await UploadChunk.filter(
|
||||||
chunk_hash=data.file_hash,
|
chunk_hash=data.file_hash,
|
||||||
@@ -473,6 +470,10 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
|||||||
file_name=safe_file_name,
|
file_name=safe_file_name,
|
||||||
).first()
|
).first()
|
||||||
|
|
||||||
|
if existing_session and existing_session.storage_mode == "webdav-offset" and preferred_mode == "webdav-stream":
|
||||||
|
# Restart the failed mutable-object protocol instead of extending it again.
|
||||||
|
await cancel_upload(existing_session.upload_id)
|
||||||
|
existing_session = None
|
||||||
if existing_session:
|
if existing_session:
|
||||||
task = completion_task(existing_session.upload_id)
|
task = completion_task(existing_session.upload_id)
|
||||||
if task is not None and not task.done():
|
if task is not None and not task.done():
|
||||||
@@ -521,11 +522,7 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
|||||||
data.file_name, upload_id
|
data.file_name, upload_id
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
storage_mode = "legacy"
|
storage_mode = preferred_mode
|
||||||
if settings.file_storage == "webdav":
|
|
||||||
storage_mode = await storages["webdav"]().chunk_upload_mode()
|
|
||||||
if storage_mode == "legacy" and total_chunks * data.chunk_size > settings.uploadSize:
|
|
||||||
raise HTTPException(403, "文件分片大小超过上传限制")
|
|
||||||
await UploadChunk.create(
|
await UploadChunk.create(
|
||||||
upload_id=upload_id,
|
upload_id=upload_id,
|
||||||
storage_mode=storage_mode,
|
storage_mode=storage_mode,
|
||||||
@@ -579,7 +576,7 @@ async def upload_chunk(
|
|||||||
existing_chunk = await UploadChunk.filter(
|
existing_chunk = await UploadChunk.filter(
|
||||||
upload_id=upload_id, chunk_index=chunk_index, completed=True
|
upload_id=upload_id, chunk_index=chunk_index, completed=True
|
||||||
).first()
|
).first()
|
||||||
if existing_chunk and chunk_info.storage_mode != "webdav-offset":
|
if existing_chunk and chunk_info.storage_mode not in {"webdav-offset", "webdav-stream"}:
|
||||||
return APIResponse(
|
return APIResponse(
|
||||||
detail={"chunk_hash": existing_chunk.chunk_hash, "skipped": True}
|
detail={"chunk_hash": existing_chunk.chunk_hash, "skipped": True}
|
||||||
)
|
)
|
||||||
@@ -602,7 +599,7 @@ async def upload_chunk(
|
|||||||
upload_id=upload_id, completed=True
|
upload_id=upload_id, completed=True
|
||||||
).count()
|
).count()
|
||||||
# 已上传分片的最大可能大小 + 当前分片
|
# 已上传分片的最大可能大小 + 当前分片
|
||||||
max_uploaded_size = chunk_info.file_size if chunk_info.storage_mode == "webdav-offset" else uploaded_count * chunk_info.chunk_size + chunk_size
|
max_uploaded_size = chunk_info.file_size
|
||||||
if max_uploaded_size > settings.uploadSize:
|
if max_uploaded_size > settings.uploadSize:
|
||||||
max_size_mb = settings.uploadSize / (1024 * 1024)
|
max_size_mb = settings.uploadSize / (1024 * 1024)
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
@@ -610,10 +607,10 @@ async def upload_chunk(
|
|||||||
)
|
)
|
||||||
|
|
||||||
chunk_hash = hashlib.sha256(chunk_data).hexdigest()
|
chunk_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||||
if chunk_info.storage_mode == "webdav-offset":
|
expected_size = min(chunk_info.chunk_size, chunk_info.file_size-chunk_index*chunk_info.chunk_size)
|
||||||
expected_size = min(chunk_info.chunk_size, chunk_info.file_size-chunk_index*chunk_info.chunk_size)
|
if chunk_size != expected_size:
|
||||||
if chunk_size != expected_size:
|
raise HTTPException(400, "分片大小与声明值不一致")
|
||||||
raise HTTPException(400, "分片大小与声明值不一致")
|
if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"}:
|
||||||
if existing_chunk:
|
if existing_chunk:
|
||||||
if existing_chunk.chunk_hash != chunk_hash:
|
if existing_chunk.chunk_hash != chunk_hash:
|
||||||
raise HTTPException(409, "重传分片内容不一致")
|
raise HTTPException(409, "重传分片内容不一致")
|
||||||
@@ -653,6 +650,31 @@ async def upload_chunk(
|
|||||||
return APIResponse(detail={"chunk_hash": chunk_hash})
|
return APIResponse(detail={"chunk_hash": chunk_hash})
|
||||||
|
|
||||||
|
|
||||||
|
@chunk_api.post("/upload/raw/{upload_id}/{chunk_index}", dependencies=[Depends(share_required_login)])
|
||||||
|
async def upload_raw_chunk(upload_id: str, chunk_index: int, request: Request):
|
||||||
|
info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||||
|
if info is None:
|
||||||
|
raise HTTPException(404, "上传会话不存在")
|
||||||
|
if not 0 <= chunk_index < info.total_chunks:
|
||||||
|
raise HTTPException(400, "无效的分片索引")
|
||||||
|
maximum = min(info.chunk_size, info.file_size - chunk_index * info.chunk_size, 100 * 1024 * 1024)
|
||||||
|
content_length = request.headers.get("content-length")
|
||||||
|
if content_length:
|
||||||
|
try:
|
||||||
|
if int(content_length) > maximum: raise HTTPException(413, "分片超过声明大小")
|
||||||
|
except ValueError: raise HTTPException(400, "无效的请求大小")
|
||||||
|
buffer = BytesIO()
|
||||||
|
try:
|
||||||
|
async for block in request.stream():
|
||||||
|
if buffer.tell() + len(block) > maximum:
|
||||||
|
raise HTTPException(413, "分片超过声明大小")
|
||||||
|
buffer.write(block)
|
||||||
|
buffer.seek(0)
|
||||||
|
return await upload_chunk(upload_id, chunk_index, UploadFile(file=buffer, filename=info.file_name))
|
||||||
|
finally:
|
||||||
|
buffer.close()
|
||||||
|
|
||||||
|
|
||||||
@chunk_api.delete("/upload/{upload_id}", dependencies=[Depends(share_required_login)])
|
@chunk_api.delete("/upload/{upload_id}", dependencies=[Depends(share_required_login)])
|
||||||
async def cancel_upload(upload_id: str):
|
async def cancel_upload(upload_id: str):
|
||||||
if is_cancelling(upload_id):
|
if is_cancelling(upload_id):
|
||||||
@@ -668,9 +690,16 @@ async def cancel_upload(upload_id: str):
|
|||||||
@serialize_upload
|
@serialize_upload
|
||||||
async def _cancel_upload(upload_id):
|
async def _cancel_upload(upload_id):
|
||||||
"""取消上传并清理临时文件"""
|
"""取消上传并清理临时文件"""
|
||||||
|
published = await FileCodes.filter(upload_id=upload_id).first()
|
||||||
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||||
|
if published:
|
||||||
|
if chunk_info and chunk_info.save_path:
|
||||||
|
await storages[settings.file_storage]().clean_chunks(upload_id, chunk_info.save_path)
|
||||||
|
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||||
|
await release_storage(f"chunk:{upload_id}")
|
||||||
|
return APIResponse(detail={"completed":True, "code":published.code, "name":published.prefix+published.suffix})
|
||||||
if not chunk_info:
|
if not chunk_info:
|
||||||
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在")
|
return APIResponse(detail={"cancelled":True, "message":"上传会话已结束"})
|
||||||
|
|
||||||
save_path = chunk_info.save_path
|
save_path = chunk_info.save_path
|
||||||
|
|
||||||
@@ -680,7 +709,7 @@ async def _cancel_upload(upload_id):
|
|||||||
try:
|
try:
|
||||||
await storage.clean_chunks(upload_id, save_path)
|
await storage.clean_chunks(upload_id, save_path)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if chunk_info.storage_mode == "webdav-offset":
|
if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"}:
|
||||||
raise
|
raise
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -688,7 +717,7 @@ async def _cancel_upload(upload_id):
|
|||||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||||
await release_storage(f"chunk:{upload_id}")
|
await release_storage(f"chunk:{upload_id}")
|
||||||
|
|
||||||
return APIResponse(detail={"message": "上传已取消"})
|
return APIResponse(detail={"cancelled":True,"message": "上传已取消"})
|
||||||
|
|
||||||
|
|
||||||
@chunk_api.get(
|
@chunk_api.get(
|
||||||
@@ -733,7 +762,7 @@ async def complete_upload(
|
|||||||
info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||||
if is_cancelling(upload_id):
|
if is_cancelling(upload_id):
|
||||||
raise HTTPException(409, "上传正在取消")
|
raise HTTPException(409, "上传正在取消")
|
||||||
if info is None or info.storage_mode != "webdav-offset":
|
if info is None or info.storage_mode not in {"webdav-offset", "webdav-stream"}:
|
||||||
return await _complete_upload(upload_id, data, ip)
|
return await _complete_upload(upload_id, data, ip)
|
||||||
task = completion_task(upload_id)
|
task = completion_task(upload_id)
|
||||||
if task is None:
|
if task is None:
|
||||||
@@ -771,15 +800,15 @@ async def _complete_upload(upload_id, data, ip):
|
|||||||
if len(completed_chunks_list) != chunk_info.total_chunks:
|
if len(completed_chunks_list) != chunk_info.total_chunks:
|
||||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="分片不完整")
|
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="分片不完整")
|
||||||
|
|
||||||
# 用分片数 * chunk_size 校验最大可能大小
|
# Each newly uploaded chunk has an exact-length check, including the last.
|
||||||
max_total_size = chunk_info.file_size if chunk_info.storage_mode == "webdav-offset" else len(completed_chunks_list) * chunk_info.chunk_size
|
max_total_size = chunk_info.file_size
|
||||||
if max_total_size > settings.uploadSize:
|
if max_total_size > settings.uploadSize:
|
||||||
save_path = chunk_info.save_path
|
save_path = chunk_info.save_path
|
||||||
if save_path:
|
if save_path:
|
||||||
try:
|
try:
|
||||||
await storage.clean_chunks(upload_id, save_path)
|
await storage.clean_chunks(upload_id, save_path)
|
||||||
except Exception:
|
except Exception:
|
||||||
if chunk_info.storage_mode == "webdav-offset":
|
if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"}:
|
||||||
raise
|
raise
|
||||||
pass
|
pass
|
||||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||||
@@ -828,7 +857,7 @@ async def _complete_upload(upload_id, data, ip):
|
|||||||
except HTTPException:
|
except HTTPException:
|
||||||
raise
|
raise
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if chunk_info.storage_mode == "webdav-offset":
|
if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"}:
|
||||||
raise HTTPException(500, "上传完成状态保存失败,请重试完成上传") from e
|
raise HTTPException(500, "上传完成状态保存失败,请重试完成上传") from e
|
||||||
# 合并失败时清理临时文件
|
# 合并失败时清理临时文件
|
||||||
try:
|
try:
|
||||||
@@ -861,6 +890,8 @@ async def _get_valid_session(
|
|||||||
session = await PresignUploadSession.filter(upload_id=upload_id).first()
|
session = await PresignUploadSession.filter(upload_id=upload_id).first()
|
||||||
if not session:
|
if not session:
|
||||||
raise HTTPException(404, "上传会话不存在")
|
raise HTTPException(404, "上传会话不存在")
|
||||||
|
if session.mode == "cancelled":
|
||||||
|
raise HTTPException(409, "上传已取消,等待后台清理")
|
||||||
if await session.is_expired():
|
if await session.is_expired():
|
||||||
await session.delete()
|
await session.delete()
|
||||||
await release_storage(f"presign:{upload_id}")
|
await release_storage(f"presign:{upload_id}")
|
||||||
@@ -931,6 +962,7 @@ async def presign_upload_init(
|
|||||||
@presign_api.put(
|
@presign_api.put(
|
||||||
"/upload/proxy/{upload_id}", dependencies=[Depends(share_required_login)]
|
"/upload/proxy/{upload_id}", dependencies=[Depends(share_required_login)]
|
||||||
)
|
)
|
||||||
|
@serialize_upload
|
||||||
async def presign_upload_proxy(
|
async def presign_upload_proxy(
|
||||||
upload_id: str, file: UploadFile = File(...), ip: str = Depends(ip_limit["upload"])
|
upload_id: str, file: UploadFile = File(...), ip: str = Depends(ip_limit["upload"])
|
||||||
):
|
):
|
||||||
@@ -953,6 +985,8 @@ async def presign_upload_proxy(
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise HTTPException(500, f"文件保存失败: {str(e)}")
|
raise HTTPException(500, f"文件保存失败: {str(e)}")
|
||||||
|
|
||||||
|
if is_cancelling(upload_id):
|
||||||
|
raise HTTPException(409, "上传正在取消")
|
||||||
try:
|
try:
|
||||||
code = await FileUploadService.create_file_record(
|
code = await FileUploadService.create_file_record(
|
||||||
session.file_name,
|
session.file_name,
|
||||||
@@ -961,6 +995,7 @@ async def presign_upload_proxy(
|
|||||||
session.expire_value,
|
session.expire_value,
|
||||||
session.expire_style,
|
session.expire_style,
|
||||||
ip=ip,
|
ip=ip,
|
||||||
|
upload_id=upload_id,
|
||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
try:
|
try:
|
||||||
@@ -984,6 +1019,7 @@ async def presign_upload_proxy(
|
|||||||
@presign_api.post(
|
@presign_api.post(
|
||||||
"/upload/confirm/{upload_id}", dependencies=[Depends(share_required_login)]
|
"/upload/confirm/{upload_id}", dependencies=[Depends(share_required_login)]
|
||||||
)
|
)
|
||||||
|
@serialize_upload
|
||||||
async def presign_upload_confirm(upload_id: str, ip: str = Depends(ip_limit["upload"])):
|
async def presign_upload_confirm(upload_id: str, ip: str = Depends(ip_limit["upload"])):
|
||||||
"""直传确认,客户端完成S3直传后调用获取分享码"""
|
"""直传确认,客户端完成S3直传后调用获取分享码"""
|
||||||
session = await _get_valid_session(upload_id, expected_mode="direct")
|
session = await _get_valid_session(upload_id, expected_mode="direct")
|
||||||
@@ -1012,6 +1048,8 @@ async def presign_upload_confirm(upload_id: str, ip: str = Depends(ip_limit["upl
|
|||||||
if not await storage.file_exists(session.save_path):
|
if not await storage.file_exists(session.save_path):
|
||||||
raise HTTPException(404, "文件未上传或上传失败")
|
raise HTTPException(404, "文件未上传或上传失败")
|
||||||
|
|
||||||
|
if is_cancelling(upload_id):
|
||||||
|
raise HTTPException(409, "上传正在取消")
|
||||||
try:
|
try:
|
||||||
code = await FileUploadService.create_file_record(
|
code = await FileUploadService.create_file_record(
|
||||||
session.file_name,
|
session.file_name,
|
||||||
@@ -1020,6 +1058,7 @@ async def presign_upload_confirm(upload_id: str, ip: str = Depends(ip_limit["upl
|
|||||||
session.expire_value,
|
session.expire_value,
|
||||||
session.expire_style,
|
session.expire_style,
|
||||||
ip=ip,
|
ip=ip,
|
||||||
|
upload_id=upload_id,
|
||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
try:
|
try:
|
||||||
@@ -1064,23 +1103,34 @@ async def presign_upload_status(upload_id: str):
|
|||||||
|
|
||||||
@presign_api.delete("/upload/{upload_id}", dependencies=[Depends(share_required_login)])
|
@presign_api.delete("/upload/{upload_id}", dependencies=[Depends(share_required_login)])
|
||||||
async def presign_upload_cancel(upload_id: str):
|
async def presign_upload_cancel(upload_id: str):
|
||||||
"""取消上传会话"""
|
if is_cancelling(upload_id):
|
||||||
|
raise HTTPException(409, "上传正在取消,请稍后重试")
|
||||||
|
begin_cancel(upload_id)
|
||||||
|
try:
|
||||||
|
return await _presign_upload_cancel(upload_id)
|
||||||
|
finally:
|
||||||
|
end_cancel(upload_id)
|
||||||
|
|
||||||
|
|
||||||
|
@serialize_upload
|
||||||
|
async def _presign_upload_cancel(upload_id):
|
||||||
session = await PresignUploadSession.filter(upload_id=upload_id).first()
|
session = await PresignUploadSession.filter(upload_id=upload_id).first()
|
||||||
|
published = await FileCodes.filter(upload_id=upload_id).first()
|
||||||
|
if published:
|
||||||
|
if session: await session.delete()
|
||||||
|
await release_storage(f"presign:{upload_id}")
|
||||||
|
return APIResponse(detail={"completed":True,"code":published.code,"name":published.prefix+published.suffix})
|
||||||
if not session:
|
if not session:
|
||||||
raise HTTPException(404, "上传会话不存在")
|
return APIResponse(detail={"cancelled":True})
|
||||||
|
storage = storages[settings.file_storage]()
|
||||||
if session.mode == "direct":
|
if session.mode in {"direct", "cancelled"}:
|
||||||
storage: FileStorageInterface = storages[settings.file_storage]()
|
# Browser abort cannot revoke a pre-signed PUT already committing remotely.
|
||||||
try:
|
# Keep a durable tombstone and quota until the signed URL expires.
|
||||||
if await storage.file_exists(session.save_path):
|
session.mode = "cancelled"
|
||||||
temp_file_code = FileCodes(
|
await session.save(update_fields=["mode"])
|
||||||
file_path=os.path.dirname(session.save_path),
|
return APIResponse(detail={"cancelled":True,"cleanup_pending":True,"message":"传输已中断,临时文件将在上传授权到期后自动清理"})
|
||||||
uuid_file_name=os.path.basename(session.save_path),
|
if await storage.file_exists(session.save_path):
|
||||||
)
|
await storage.delete_file(FileCodes(file_path=os.path.dirname(session.save_path),uuid_file_name=os.path.basename(session.save_path)))
|
||||||
await storage.delete_file(temp_file_code)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
await session.delete()
|
await session.delete()
|
||||||
await release_storage(f"presign:{upload_id}")
|
await release_storage(f"presign:{upload_id}")
|
||||||
return APIResponse(detail={"message": "上传会话已取消"})
|
return APIResponse(detail={"cancelled":True,"message":"上传已取消"})
|
||||||
@@ -54,6 +54,8 @@ DEFAULT_CONFIG = {
|
|||||||
"code_generate_type": "secret",
|
"code_generate_type": "secret",
|
||||||
"uploadMinute": 1,
|
"uploadMinute": 1,
|
||||||
"enableChunk": 0,
|
"enableChunk": 0,
|
||||||
|
"chunkSizeMB": 90,
|
||||||
|
"downloadCheckInterval": 0,
|
||||||
"webdav_url": "",
|
"webdav_url": "",
|
||||||
"webdav_password": "",
|
"webdav_password": "",
|
||||||
"webdav_username": "",
|
"webdav_username": "",
|
||||||
|
|||||||
+50
-52
@@ -85,6 +85,12 @@ class FileStorageInterface:
|
|||||||
"""
|
"""
|
||||||
raise NotImplementedError
|
raise NotImplementedError
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def validate_stored_chunk_size(chunk_info: UploadChunk, index: int, data: bytes):
|
||||||
|
expected = min(chunk_info.chunk_size, chunk_info.file_size - index * chunk_info.chunk_size)
|
||||||
|
if len(data) != expected:
|
||||||
|
raise ValueError(f"分片{index}大小与上传声明不一致,请重新上传")
|
||||||
|
|
||||||
async def generate_presigned_upload_url(self, save_path: str, expires_in: int = 900) -> Optional[str]:
|
async def generate_presigned_upload_url(self, save_path: str, expires_in: int = 900) -> Optional[str]:
|
||||||
"""
|
"""
|
||||||
生成预签名上传URL
|
生成预签名上传URL
|
||||||
@@ -245,6 +251,7 @@ class SystemFileStorage(FileStorageInterface):
|
|||||||
raise ValueError(f"分片{i}文件不存在")
|
raise ValueError(f"分片{i}文件不存在")
|
||||||
async with aiofiles.open(chunk_path, "rb") as in_file:
|
async with aiofiles.open(chunk_path, "rb") as in_file:
|
||||||
chunk_data = await in_file.read()
|
chunk_data = await in_file.read()
|
||||||
|
self.validate_stored_chunk_size(chunk_info, i, chunk_data)
|
||||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||||
if current_hash != chunk_record.chunk_hash:
|
if current_hash != chunk_record.chunk_hash:
|
||||||
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
||||||
@@ -489,6 +496,7 @@ class S3FileStorage(FileStorageInterface):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise ValueError(f"分片{i}文件不存在: {e}")
|
raise ValueError(f"分片{i}文件不存在: {e}")
|
||||||
|
|
||||||
|
self.validate_stored_chunk_size(chunk_info, i, chunk_data)
|
||||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||||
if current_hash != chunk_record.chunk_hash:
|
if current_hash != chunk_record.chunk_hash:
|
||||||
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
||||||
@@ -843,6 +851,7 @@ class OneDriveFileStorage(FileStorageInterface):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise ValueError(f"分片{i}文件不存在: {e}")
|
raise ValueError(f"分片{i}文件不存在: {e}")
|
||||||
|
|
||||||
|
self.validate_stored_chunk_size(chunk_info, i, chunk_data)
|
||||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||||
if current_hash != chunk_record.chunk_hash:
|
if current_hash != chunk_record.chunk_hash:
|
||||||
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
||||||
@@ -1009,6 +1018,7 @@ class OpenDALFileStorage(FileStorageInterface):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise ValueError(f"分片{i}文件不存在: {e}")
|
raise ValueError(f"分片{i}文件不存在: {e}")
|
||||||
|
|
||||||
|
self.validate_stored_chunk_size(chunk_info, i, chunk_data)
|
||||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||||
if current_hash != chunk_record.chunk_hash:
|
if current_hash != chunk_record.chunk_hash:
|
||||||
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
||||||
@@ -1051,9 +1061,10 @@ class OpenDALFileStorage(FileStorageInterface):
|
|||||||
|
|
||||||
|
|
||||||
from core.webdav_chunks import WebDAVOffsetMixin
|
from core.webdav_chunks import WebDAVOffsetMixin
|
||||||
|
from core.webdav_stream import WebDAVStreamMixin
|
||||||
|
|
||||||
|
|
||||||
class WebDAVFileStorage(WebDAVOffsetMixin, FileStorageInterface):
|
class WebDAVFileStorage(WebDAVStreamMixin, WebDAVOffsetMixin, FileStorageInterface):
|
||||||
_instance: Optional["WebDAVFileStorage"] = None
|
_instance: Optional["WebDAVFileStorage"] = None
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
@@ -1202,62 +1213,44 @@ class WebDAVFileStorage(WebDAVOffsetMixin, FileStorageInterface):
|
|||||||
return await get_file_url(file_code.code)
|
return await get_file_url(file_code.code)
|
||||||
|
|
||||||
async def get_file_response(self, file_code: FileCodes):
|
async def get_file_response(self, file_code: FileCodes):
|
||||||
"""获取文件响应(代理模式)"""
|
"""Validate the upstream response before starting the downstream stream."""
|
||||||
|
filename = file_code.prefix + file_code.suffix
|
||||||
|
url = self._build_url(await file_code.get_file_path())
|
||||||
|
session = aiohttp.ClientSession(auth=self.auth, timeout=aiohttp.ClientTimeout(total=None, connect=30, sock_read=120))
|
||||||
try:
|
try:
|
||||||
filename = file_code.prefix + file_code.suffix
|
upstream = await session.get(url)
|
||||||
url = self._build_url(await file_code.get_file_path())
|
if upstream.status == 404:
|
||||||
content_length = None # 初始化为 None,表示未知大小
|
await session.close()
|
||||||
|
raise HTTPException(404, "文件在 WebDAV 中不存在或已被移动")
|
||||||
# 创建ClientSession并复用(包含认证头)
|
if upstream.status != 200:
|
||||||
session = aiohttp.ClientSession(headers={
|
status_code = upstream.status
|
||||||
"Authorization": f"Basic {base64.b64encode(f'{settings.webdav_username}:{settings.webdav_password}'.encode()).decode()}"
|
await session.close()
|
||||||
})
|
raise HTTPException(502, f"WebDAV 文件读取失败(上游 {status_code}),请稍后重试")
|
||||||
|
except (aiohttp.ClientError, asyncio.TimeoutError) as exc:
|
||||||
# 尝试发送HEAD请求获取Content-Length
|
await session.close()
|
||||||
|
raise HTTPException(503, "WebDAV 连接失败,请稍后重试") from exc
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
await session.close()
|
||||||
|
raise
|
||||||
|
|
||||||
|
async def stream_generator():
|
||||||
try:
|
try:
|
||||||
async with session.head(url) as resp:
|
async for chunk in upstream.content.iter_chunked(65536):
|
||||||
if resp.status == 200 and 'Content-Length' in resp.headers:
|
yield chunk
|
||||||
content_length = int(resp.headers['Content-Length'])
|
finally:
|
||||||
except Exception:
|
upstream.release()
|
||||||
# 如果HEAD请求失败,则不提供 Content-Length
|
await session.close()
|
||||||
pass
|
|
||||||
|
headers = {"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename, safe='')}"}
|
||||||
async def stream_generator():
|
if upstream.content_length is not None:
|
||||||
try:
|
headers["Content-Length"] = str(upstream.content_length)
|
||||||
async with session.get(url) as resp:
|
return StreamingResponse(stream_generator(), media_type="application/octet-stream", headers=headers, background=BackgroundTask(session.close))
|
||||||
if resp.status != 200:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=resp.status,
|
|
||||||
detail=f"文件获取失败{resp.status}: {await resp.text()}",
|
|
||||||
)
|
|
||||||
chunk_size = 65536
|
|
||||||
while True:
|
|
||||||
chunk = await resp.content.read(chunk_size)
|
|
||||||
if not chunk:
|
|
||||||
break
|
|
||||||
yield chunk
|
|
||||||
finally:
|
|
||||||
await session.close()
|
|
||||||
|
|
||||||
encoded_filename = quote(filename, safe='')
|
|
||||||
headers = {
|
|
||||||
"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
|
|
||||||
}
|
|
||||||
if content_length is not None:
|
|
||||||
headers["Content-Length"] = str(content_length)
|
|
||||||
return StreamingResponse(
|
|
||||||
stream_generator(),
|
|
||||||
media_type="application/octet-stream",
|
|
||||||
headers=headers,
|
|
||||||
# 兜底关闭会话:客户端中断时与 generator finally 双保险
|
|
||||||
background=BackgroundTask(session.close),
|
|
||||||
)
|
|
||||||
except aiohttp.ClientError as e:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=503, detail=f"WebDAV连接异常: {str(e)}")
|
|
||||||
|
|
||||||
async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str):
|
async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str):
|
||||||
"""保存分片到 WebDAV"""
|
"""保存分片到 WebDAV"""
|
||||||
|
stream = await self._stream_session(upload_id)
|
||||||
|
if stream is not None:
|
||||||
|
return await self.save_stream_chunk(stream, chunk_index, chunk_data, chunk_hash)
|
||||||
info = await self._offset_session(upload_id)
|
info = await self._offset_session(upload_id)
|
||||||
if info is not None:
|
if info is not None:
|
||||||
return await self.save_offset_chunk(info, chunk_index, chunk_data)
|
return await self.save_offset_chunk(info, chunk_index, chunk_data)
|
||||||
@@ -1282,6 +1275,8 @@ class WebDAVFileStorage(WebDAVOffsetMixin, FileStorageInterface):
|
|||||||
合并 WebDAV 上的分片文件
|
合并 WebDAV 上的分片文件
|
||||||
使用临时文件避免内存问题
|
使用临时文件避免内存问题
|
||||||
"""
|
"""
|
||||||
|
if chunk_info.storage_mode == "webdav-stream":
|
||||||
|
return await self.finish_stream_upload(chunk_info, save_path)
|
||||||
if chunk_info.storage_mode == "webdav-offset":
|
if chunk_info.storage_mode == "webdav-offset":
|
||||||
return await self.finish_offset_upload(chunk_info, save_path)
|
return await self.finish_offset_upload(chunk_info, save_path)
|
||||||
file_sha256 = hashlib.sha256()
|
file_sha256 = hashlib.sha256()
|
||||||
@@ -1311,6 +1306,7 @@ class WebDAVFileStorage(WebDAVOffsetMixin, FileStorageInterface):
|
|||||||
chunk_data = await resp.read()
|
chunk_data = await resp.read()
|
||||||
|
|
||||||
# 验证哈希
|
# 验证哈希
|
||||||
|
self.validate_stored_chunk_size(chunk_info, i, chunk_data)
|
||||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||||
if current_hash != chunk_record.chunk_hash:
|
if current_hash != chunk_record.chunk_hash:
|
||||||
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
||||||
@@ -1354,6 +1350,8 @@ class WebDAVFileStorage(WebDAVOffsetMixin, FileStorageInterface):
|
|||||||
:param upload_id: 上传会话ID
|
:param upload_id: 上传会话ID
|
||||||
:param save_path: 文件保存路径
|
:param save_path: 文件保存路径
|
||||||
"""
|
"""
|
||||||
|
if await self._stream_session(upload_id) is not None:
|
||||||
|
return await self.clean_stream_upload(upload_id, save_path)
|
||||||
if await self._offset_session(upload_id) is not None:
|
if await self._offset_session(upload_id) is not None:
|
||||||
return await self.clean_offset_upload(upload_id, save_path)
|
return await self.clean_offset_upload(upload_id, save_path)
|
||||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||||
|
|||||||
+19
-22
@@ -103,34 +103,31 @@ async def clean_incomplete_uploads():
|
|||||||
await asyncio.sleep(3600)
|
await asyncio.sleep(3600)
|
||||||
|
|
||||||
|
|
||||||
|
async def clean_expired_presign_session(upload_id, now):
|
||||||
|
async with upload_lock(upload_id):
|
||||||
|
session = await PresignUploadSession.filter(upload_id=upload_id, expires_at__lt=now).first()
|
||||||
|
if session is None:
|
||||||
|
return
|
||||||
|
published = await FileCodes.filter(upload_id=upload_id).exists()
|
||||||
|
if not published:
|
||||||
|
storage = storages[settings.file_storage]()
|
||||||
|
if await storage.file_exists(session.save_path):
|
||||||
|
await storage.delete_file(FileCodes(file_path=os.path.dirname(session.save_path),uuid_file_name=os.path.basename(session.save_path)))
|
||||||
|
await StorageReservation.filter(token=f"presign:{upload_id}").delete()
|
||||||
|
await session.delete()
|
||||||
|
|
||||||
|
|
||||||
async def clean_expired_presign_sessions():
|
async def clean_expired_presign_sessions():
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
await refresh_settings()
|
await refresh_settings()
|
||||||
storage: FileStorageInterface = storages[settings.file_storage]()
|
|
||||||
now = await get_now()
|
now = await get_now()
|
||||||
expired_sessions = await PresignUploadSession.filter(
|
expired_sessions = await PresignUploadSession.filter(expires_at__lt=now).all()
|
||||||
expires_at__lt=now
|
|
||||||
).all()
|
|
||||||
for session in expired_sessions:
|
for session in expired_sessions:
|
||||||
if session.mode == "direct":
|
try:
|
||||||
try:
|
await clean_expired_presign_session(session.upload_id, now)
|
||||||
if await storage.file_exists(session.save_path):
|
except Exception as e:
|
||||||
await storage.delete_file(
|
logger.error(f"清理上传失败,保留会话等待重试 upload_id={session.upload_id}: {e}")
|
||||||
FileCodes(
|
|
||||||
file_path=os.path.dirname(session.save_path),
|
|
||||||
uuid_file_name=os.path.basename(session.save_path),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(
|
|
||||||
"清理过期直传文件失败 "
|
|
||||||
f"upload_id={session.upload_id}: {e}"
|
|
||||||
)
|
|
||||||
await StorageReservation.filter(
|
|
||||||
token=f"presign:{session.upload_id}"
|
|
||||||
).delete()
|
|
||||||
await session.delete()
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"清理过期预签名会话异常: {e}")
|
logger.error(f"清理过期预签名会话异常: {e}")
|
||||||
finally:
|
finally:
|
||||||
|
|||||||
@@ -18,6 +18,9 @@ class WebDAVOffsetMixin:
|
|||||||
return str(PurePosixPath(save_path).parent / 'chunks' / upload_id / 'upload.bin')
|
return str(PurePosixPath(save_path).parent / 'chunks' / upload_id / 'upload.bin')
|
||||||
|
|
||||||
async def chunk_upload_mode(self):
|
async def chunk_upload_mode(self):
|
||||||
|
return "webdav-stream"
|
||||||
|
|
||||||
|
async def offset_upload_mode(self):
|
||||||
async with aiohttp.ClientSession(auth=self.auth, timeout=OFFSET_TIMEOUT) as client:
|
async with aiohttp.ClientSession(auth=self.auth, timeout=OFFSET_TIMEOUT) as client:
|
||||||
async with client.options(self.base_url) as response:
|
async with client.options(self.base_url) as response:
|
||||||
if response.status not in (200,204):
|
if response.status not in (200,204):
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
"""Immutable remote parts and streamed assembly for cloud-backed WebDAV."""
|
||||||
|
import asyncio
|
||||||
|
import hashlib
|
||||||
|
from pathlib import PurePosixPath
|
||||||
|
|
||||||
|
import aiohttp
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
from apps.base.models import UploadChunk
|
||||||
|
from core.webdav_chunks import OFFSET_TIMEOUT
|
||||||
|
|
||||||
|
STREAM_MODE = 'webdav-stream'
|
||||||
|
|
||||||
|
|
||||||
|
class WebDAVStreamMixin:
|
||||||
|
async def _stream_session(self, upload_id):
|
||||||
|
return await UploadChunk.filter(upload_id=upload_id, chunk_index=-1, storage_mode=STREAM_MODE).first()
|
||||||
|
|
||||||
|
def _stream_part_path(self, info, index):
|
||||||
|
return str(PurePosixPath(info.save_path).parent / 'chunks' / info.upload_id / f'{index}.part')
|
||||||
|
|
||||||
|
async def save_stream_chunk(self, info, index, data, expected_hash):
|
||||||
|
expected = min(info.chunk_size, info.file_size-index*info.chunk_size)
|
||||||
|
if len(data) != expected:
|
||||||
|
raise HTTPException(400, '分片大小与声明值不一致')
|
||||||
|
path = self._stream_part_path(info,index)
|
||||||
|
await self._mkdir_p(str(PurePosixPath(path).parent))
|
||||||
|
async with aiohttp.ClientSession(auth=self.auth,timeout=OFFSET_TIMEOUT) as client:
|
||||||
|
url=self._build_url(path)
|
||||||
|
# Never PATCH an object already synchronizing to the cloud.
|
||||||
|
async with client.put(url,data=data,headers={'If-None-Match':'*'}) as response:
|
||||||
|
if response.status in (200,201,204): return
|
||||||
|
if response.status != 412:
|
||||||
|
raise HTTPException(503,f'WebDAV 分片上传失败(上游 {response.status}),请重试')
|
||||||
|
digest=hashlib.sha256();length=0
|
||||||
|
async with client.get(url) as response:
|
||||||
|
if response.status != 200:
|
||||||
|
raise HTTPException(503,'WebDAV 分片状态暂时无法确认,请重试')
|
||||||
|
async for block in response.content.iter_chunked(65536):
|
||||||
|
digest.update(block);length+=len(block)
|
||||||
|
if length==len(data) and digest.hexdigest()==expected_hash:return
|
||||||
|
# A failed first PUT can leave a partial object; delete before replacing.
|
||||||
|
async with client.delete(url) as response:
|
||||||
|
if response.status not in (200,204,404):raise HTTPException(503,'WebDAV 分片重试清理失败')
|
||||||
|
async with client.put(url,data=data,headers={'If-None-Match':'*'}) as response:
|
||||||
|
if response.status not in (200,201,204):raise HTTPException(503,'WebDAV 分片重传失败,请重试')
|
||||||
|
|
||||||
|
async def finish_stream_upload(self, info, save_path):
|
||||||
|
records=await UploadChunk.filter(upload_id=info.upload_id,completed=True).order_by('chunk_index')
|
||||||
|
if [r.chunk_index for r in records]!=list(range(info.total_chunks)):raise ValueError('分片不完整')
|
||||||
|
directory=str(PurePosixPath(self._stream_part_path(info,0)).parent)
|
||||||
|
staging=directory+'/assembled.bin'
|
||||||
|
async with aiohttp.ClientSession(auth=self.auth,timeout=OFFSET_TIMEOUT) as client:
|
||||||
|
# Recover a completed MOVE whose response/database acknowledgement was lost.
|
||||||
|
digest=await self._verify_offset_file(client,save_path,info,records)
|
||||||
|
if digest is not None:return save_path,digest
|
||||||
|
async with client.delete(self._build_url(staging)) as response:
|
||||||
|
if response.status not in (200,204,404):raise HTTPException(503,'WebDAV 合并临时文件清理失败')
|
||||||
|
verified=0
|
||||||
|
async def stream_parts():
|
||||||
|
nonlocal verified
|
||||||
|
for index,record in enumerate(records):
|
||||||
|
digest=hashlib.sha256();length=0
|
||||||
|
expected=min(info.chunk_size,info.file_size-index*info.chunk_size)
|
||||||
|
async with client.get(self._build_url(self._stream_part_path(info,index))) as response:
|
||||||
|
if response.status!=200:raise ValueError('远端分片缺失,请重新上传')
|
||||||
|
async for block in response.content.iter_chunked(65536):
|
||||||
|
length+=len(block)
|
||||||
|
if length>expected:raise ValueError('远端分片大小异常')
|
||||||
|
digest.update(block);yield block
|
||||||
|
if length!=expected or digest.hexdigest()!=record.chunk_hash:raise ValueError('远端分片校验失败,请重新上传')
|
||||||
|
verified+=1
|
||||||
|
async def assemble():
|
||||||
|
try:
|
||||||
|
async with client.put(self._build_url(staging),data=stream_parts(),headers={'Content-Length':str(info.file_size),'If-None-Match':'*'}) as response:
|
||||||
|
if response.status not in (200,201,204):raise HTTPException(503,f'WebDAV 流式合并失败(上游 {response.status})')
|
||||||
|
except aiohttp.ClientError as exc:
|
||||||
|
raise HTTPException(503,'WebDAV 流式合并中断,请重试完成上传') from exc
|
||||||
|
task=asyncio.create_task(assemble())
|
||||||
|
try:await asyncio.shield(task)
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
await task
|
||||||
|
raise
|
||||||
|
if verified!=len(records):raise ValueError('分片校验未完成,请重新上传')
|
||||||
|
digest=await self._verify_offset_file(client,staging,info,records)
|
||||||
|
if digest is None:raise ValueError('合并后的文件不存在')
|
||||||
|
move=asyncio.create_task(self._publish_offset(client,staging,save_path))
|
||||||
|
try:await asyncio.shield(move)
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
await move
|
||||||
|
raise
|
||||||
|
return save_path,digest
|
||||||
|
|
||||||
|
async def clean_stream_upload(self, upload_id, save_path):
|
||||||
|
await self.clean_offset_upload(upload_id, save_path)
|
||||||
@@ -57,6 +57,7 @@ def build_public_config() -> dict:
|
|||||||
"allowedFileTypes": settings.allowed_file_types,
|
"allowedFileTypes": settings.allowed_file_types,
|
||||||
"expireStyle": settings.expireStyle,
|
"expireStyle": settings.expireStyle,
|
||||||
"enableChunk": settings.enableChunk,
|
"enableChunk": settings.enableChunk,
|
||||||
|
"chunkSizeMB": settings.chunkSizeMB,
|
||||||
"openUpload": settings.openUpload,
|
"openUpload": settings.openUpload,
|
||||||
"notify_title": settings.notify_title,
|
"notify_title": settings.notify_title,
|
||||||
"notify_content": settings.notify_content,
|
"notify_content": settings.notify_content,
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import unittest
|
||||||
|
import httpx
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from apps.admin.views import admin_api
|
||||||
|
from apps.admin.dependencies import admin_required
|
||||||
|
from apps.base.views import chunk_api
|
||||||
|
from apps.base.models import KeyValue,UploadChunk
|
||||||
|
from core.settings import settings
|
||||||
|
from core.config import refresh_settings
|
||||||
|
from main import get_public_config
|
||||||
|
from tests.helpers import init_memory_db,close_db
|
||||||
|
|
||||||
|
MIB=1024*1024
|
||||||
|
class ChunkSizeConfigTests(unittest.IsolatedAsyncioTestCase):
|
||||||
|
async def asyncSetUp(self):
|
||||||
|
self.old=dict(settings.user_config)
|
||||||
|
await init_memory_db()
|
||||||
|
from apps.base.utils import ip_limit
|
||||||
|
for limiter in ip_limit.values():limiter.ips.clear()
|
||||||
|
await KeyValue.create(key='settings',value={'file_storage':'webdav','uploadSize':200*MIB,'openUpload':1})
|
||||||
|
await refresh_settings(force=True)
|
||||||
|
app=FastAPI();app.include_router(admin_api);app.include_router(chunk_api)
|
||||||
|
app.add_api_route('/api/v1/config',get_public_config,methods=['GET'])
|
||||||
|
app.dependency_overrides[admin_required]=lambda:None
|
||||||
|
self.client=httpx.AsyncClient(transport=httpx.ASGITransport(app=app),base_url='http://test')
|
||||||
|
async def asyncTearDown(self):
|
||||||
|
await self.client.aclose();settings.user_config=self.old;await close_db()
|
||||||
|
async def update(self,value):
|
||||||
|
return await self.client.patch('/admin/config/update',json={'chunkSizeMB':value})
|
||||||
|
async def init_upload(self,name='file.bin'):
|
||||||
|
response=await self.client.post('/chunk/upload/init/',json={'file_name':name,'file_size':120*MIB,'chunk_size':100*MIB,'file_hash':'a'*64})
|
||||||
|
self.assertEqual(response.status_code,200,response.text)
|
||||||
|
return response.json()['detail']
|
||||||
|
async def test_saved_setting_is_public_and_controls_new_sessions(self):
|
||||||
|
self.assertEqual((await self.client.get('/api/v1/config')).json()['detail']['config']['chunkSizeMB'],90)
|
||||||
|
r=await self.update(32);self.assertEqual(r.status_code,200,r.text)
|
||||||
|
self.assertEqual((await KeyValue.get(key='settings')).value['chunkSizeMB'],32)
|
||||||
|
self.assertEqual((await self.client.get('/api/v1/config')).json()['detail']['config']['chunkSizeMB'],32)
|
||||||
|
detail=await self.init_upload();self.assertEqual(detail['chunk_size'],32*MIB);self.assertEqual(detail['total_chunks'],4)
|
||||||
|
async def test_invalid_values_do_not_persist_or_change_runtime(self):
|
||||||
|
await self.update(90)
|
||||||
|
for value in [0,-1,101,1.5,True,None,'','abc','1.5']:
|
||||||
|
with self.subTest(value=value):
|
||||||
|
r=await self.update(value);self.assertEqual(r.status_code,400,r.text)
|
||||||
|
self.assertEqual((await KeyValue.get(key='settings')).value['chunkSizeMB'],90)
|
||||||
|
for value in [1,100,'25']:
|
||||||
|
r=await self.update(value);self.assertEqual(r.status_code,200,r.text)
|
||||||
|
async def test_changed_setting_does_not_change_existing_session_offsets(self):
|
||||||
|
await self.update(90);original=await self.init_upload()
|
||||||
|
await self.update(10);resumed=await self.init_upload()
|
||||||
|
self.assertEqual(resumed['upload_id'],original['upload_id']);self.assertEqual(resumed['chunk_size'],90*MIB)
|
||||||
|
fresh=await self.init_upload('other.bin');self.assertEqual(fresh['chunk_size'],10*MIB)
|
||||||
|
async def test_config_write_requires_admin(self):
|
||||||
|
from apps.admin.dependencies import admin_required
|
||||||
|
self.client._transport.app.dependency_overrides.pop(admin_required)
|
||||||
|
self.assertIn((await self.update(10)).status_code,[401,403])
|
||||||
|
async def test_local_full_size_file_works_with_non_divisible_chunk_config(self):
|
||||||
|
from pathlib import Path
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
from unittest.mock import patch
|
||||||
|
import hashlib
|
||||||
|
payload=b'a'*(10*MIB)
|
||||||
|
await self.client.patch('/admin/config/update',json={'chunkSizeMB':3,'file_storage':'local','uploadSize':len(payload)})
|
||||||
|
with TemporaryDirectory() as tmp,patch('core.storage.data_root',Path(tmp)):
|
||||||
|
response=await self.client.post('/chunk/upload/init/',json={'file_name':'limit.txt','file_size':len(payload),'chunk_size':100*MIB,'file_hash':hashlib.sha256(payload).hexdigest()})
|
||||||
|
self.assertEqual(response.status_code,200,response.text)
|
||||||
|
details=response.json()['detail'];self.assertEqual(details['chunk_size'],3*MIB)
|
||||||
|
for i in range(4):
|
||||||
|
r=await self.client.post(f"/chunk/upload/raw/{details['upload_id']}/{i}",content=payload[i*3*MIB:(i+1)*3*MIB])
|
||||||
|
self.assertEqual(r.status_code,200,r.text)
|
||||||
|
r=await self.client.post(f"/chunk/upload/complete/{details['upload_id']}",json={'expire_value':1,'expire_style':'day'})
|
||||||
|
self.assertEqual(r.status_code,200,r.text)
|
||||||
|
from apps.base.models import FileCodes
|
||||||
|
saved=await FileCodes.get(code=r.json()['detail']['code'])
|
||||||
|
self.assertEqual((Path(tmp)/await saved.get_file_path()).read_bytes(),payload)
|
||||||
|
async def test_old_legacy_oversized_tail_cannot_publish_beyond_declared_size(self):
|
||||||
|
from pathlib import Path
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
from unittest.mock import patch
|
||||||
|
from core.storage import SystemFileStorage
|
||||||
|
from apps.base.models import FileCodes
|
||||||
|
import hashlib
|
||||||
|
await self.client.patch('/admin/config/update',json={'file_storage':'local','uploadSize':10})
|
||||||
|
with TemporaryDirectory() as tmp,patch('core.storage.data_root',Path(tmp)):
|
||||||
|
uid='legacy-tail';path='share/legacy/file.txt'
|
||||||
|
await UploadChunk.create(upload_id=uid,chunk_index=-1,file_name='file.txt',file_size=10,chunk_size=3,total_chunks=4,chunk_hash='a'*64,save_path=path)
|
||||||
|
storage=SystemFileStorage()
|
||||||
|
for i in range(4):
|
||||||
|
data=b'abc';digest=hashlib.sha256(data).hexdigest()
|
||||||
|
await storage.save_chunk(uid,i,data,digest,path)
|
||||||
|
await UploadChunk.create(upload_id=uid,chunk_index=i,file_name='file.txt',file_size=10,chunk_size=3,total_chunks=4,chunk_hash=digest,save_path=path,completed=True)
|
||||||
|
response=await self.client.post(f'/chunk/upload/complete/{uid}',json={'expire_value':1,'expire_style':'day'})
|
||||||
|
self.assertEqual(response.status_code,400,response.text)
|
||||||
|
self.assertFalse(await FileCodes.filter(upload_id=uid).exists())
|
||||||
|
self.assertFalse((Path(tmp)/path).exists())
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
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')
|
||||||
|
|
||||||
|
async def test_full_check_ids_include_other_pages_without_reading_storage(self):
|
||||||
|
from core.settings import DEFAULT_CONFIG
|
||||||
|
self.assertEqual(DEFAULT_CONFIG['downloadCheckInterval'], 0)
|
||||||
|
expired = await FileCodes.create(code='EXPIRED1', expired_count=0)
|
||||||
|
await FileCodes.create(code='TRASHED1', is_trashed=True)
|
||||||
|
response = await self.client.get('/admin/file/download-check-ids')
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertEqual(response.json()['detail'], [self.file.id, expired.id])
|
||||||
|
self.assertEqual(self.requests, 0)
|
||||||
|
self.assertEqual(await TransferStats.all().count(), 0)
|
||||||
|
self.app.dependency_overrides.clear()
|
||||||
|
response = await self.client.get('/admin/file/download-check-ids')
|
||||||
|
self.assertEqual(response.status_code, 401)
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import datetime
|
||||||
|
import unittest
|
||||||
|
import httpx
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from apps.admin.views import admin_api
|
||||||
|
from apps.admin.dependencies import admin_required
|
||||||
|
from apps.admin.services import FileService
|
||||||
|
from apps.base.models import FileCodes,TransferStats
|
||||||
|
from core.utils import get_now
|
||||||
|
from tests.helpers import init_memory_db,close_db
|
||||||
|
|
||||||
|
class HistoryStatusTests(unittest.IsolatedAsyncioTestCase):
|
||||||
|
async def asyncSetUp(self):
|
||||||
|
await init_memory_db()
|
||||||
|
app=FastAPI();app.include_router(admin_api)
|
||||||
|
app.dependency_overrides[admin_required]=lambda:None
|
||||||
|
self.client=httpx.AsyncClient(transport=httpx.ASGITransport(app=app),base_url='http://test')
|
||||||
|
self.service=FileService()
|
||||||
|
self.item=await FileCodes.create(code='HISTORY1',prefix='test',suffix='.txt',text='history',expired_count=-1)
|
||||||
|
async def asyncTearDown(self):
|
||||||
|
await self.client.aclose();await close_db()
|
||||||
|
async def row(self,**params):
|
||||||
|
response=await self.client.get('/admin/analytics',params=params);self.assertEqual(response.status_code,200,response.text)
|
||||||
|
data=response.json()['detail'];return next(x for x in data['historyFiles'] if x['code']=='HISTORY1'),data['totals']
|
||||||
|
async def test_live_trash_restore_purge_state_and_counts(self):
|
||||||
|
row,totals=await self.row();self.assertEqual(row['status'],'active');self.assertTrue(row['can_download']);self.assertEqual(totals['currentFiles'],1)
|
||||||
|
await self.service.move_to_trash(self.item,reason='manual')
|
||||||
|
row,totals=await self.row();self.assertEqual(row['status'],'trashed');self.assertFalse(row['current']);self.assertFalse(row['can_download']);self.assertIsNotNone(row['trashed_at']);self.assertEqual(totals['currentFiles'],0)
|
||||||
|
self.item=await self.service.restore_from_trash(self.item.id)
|
||||||
|
row,totals=await self.row();self.assertEqual(row['status'],'active');self.assertTrue(row['was_restored']);self.assertTrue(row['current']);self.assertFalse(row['deleted']);self.assertEqual(totals['currentFiles'],1)
|
||||||
|
await self.service.move_to_trash(self.item,reason='manual');await self.service.purge_trashed_file(self.item)
|
||||||
|
row,totals=await self.row();self.assertEqual(row['status'],'purged');self.assertTrue(row['deleted']);self.assertFalse(row['can_download']);self.assertEqual(totals['currentFiles'],0)
|
||||||
|
async def test_current_state_is_not_lost_outside_selected_activity_date_range(self):
|
||||||
|
await self.service.move_to_trash(self.item,reason='expired_time')
|
||||||
|
row,_=await self.row(start='2020-01-01',end='2020-01-02');self.assertEqual(row['status'],'trashed');self.assertEqual(row['trash_reason'],'expired_time')
|
||||||
|
async def test_expired_restored_item_stays_expired_until_policy_changes(self):
|
||||||
|
self.item.expired_at=await get_now()-datetime.timedelta(days=1);await self.item.save()
|
||||||
|
await self.service.move_to_trash(self.item,reason='expired_time');await self.service.restore_from_trash(self.item.id)
|
||||||
|
row,_=await self.row();self.assertEqual(row['status'],'expired');self.assertFalse(row['can_download'])
|
||||||
|
async def test_hard_deleted_historical_record_keeps_deleted_status(self):
|
||||||
|
await TransferStats.create(action='delete',code=self.item.code,file_code_id=self.item.id,name='test.txt',deleted_at=await get_now())
|
||||||
|
await self.item.delete();row,totals=await self.row();self.assertEqual(row['status'],'deleted');self.assertFalse(row['can_download']);self.assertEqual(totals['currentFiles'],0)
|
||||||
@@ -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()
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import unittest
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from aiohttp import web
|
||||||
|
from fastapi import FastAPI
|
||||||
|
import httpx
|
||||||
|
from core.settings import settings
|
||||||
|
from core.storage import WebDAVFileStorage
|
||||||
|
|
||||||
|
|
||||||
|
class WebDAVDownloadTests(unittest.IsolatedAsyncioTestCase):
|
||||||
|
async def asyncSetUp(self):
|
||||||
|
self.original=dict(settings.user_config);self.status=200;self.data=b'old file bytes'
|
||||||
|
upstream=web.Application();upstream.router.add_route('*','/dav/{path:.*}',self.handle)
|
||||||
|
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={'webdav_url':f'http://127.0.0.1:{port}/dav','webdav_username':'test','webdav_password':'test'}
|
||||||
|
app=FastAPI()
|
||||||
|
@app.get('/download')
|
||||||
|
async def download():
|
||||||
|
async def path():return 'share/data/2026/05/18/old-id/old.apk'
|
||||||
|
return await WebDAVFileStorage().get_file_response(SimpleNamespace(prefix='历史文件',suffix='.apk',get_file_path=path))
|
||||||
|
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();settings.user_config=self.original
|
||||||
|
|
||||||
|
async def handle(self,request):
|
||||||
|
# Some DAV servers answer HEAD but cannot fetch the backing cloud object.
|
||||||
|
if request.method=='HEAD':return web.Response(headers={'Content-Length':str(len(self.data))})
|
||||||
|
return web.Response(status=self.status,body=self.data if self.status==200 else b'upstream-error')
|
||||||
|
|
||||||
|
async def test_missing_upstream_is_404_before_stream_headers_start(self):
|
||||||
|
self.status=404;r=await self.client.get('/download')
|
||||||
|
self.assertEqual(r.status_code,404,r.text);self.assertIn('文件',r.json()['detail'])
|
||||||
|
|
||||||
|
async def test_upstream_range_error_is_readable_gateway_error(self):
|
||||||
|
self.status=416;r=await self.client.get('/download')
|
||||||
|
self.assertEqual(r.status_code,502,r.text);self.assertIn('WebDAV',r.json()['detail'])
|
||||||
|
|
||||||
|
async def test_existing_legacy_file_streams_bytes_and_filename(self):
|
||||||
|
r=await self.client.get('/download');self.assertEqual(r.status_code,200)
|
||||||
|
self.assertEqual(r.content,self.data);self.assertEqual(r.headers['content-length'],str(len(self.data)))
|
||||||
|
self.assertIn("filename*=UTF-8''",r.headers['content-disposition'])
|
||||||
@@ -15,10 +15,12 @@ from core.settings import settings
|
|||||||
from tests.helpers import init_memory_db, close_db
|
from tests.helpers import init_memory_db, close_db
|
||||||
|
|
||||||
|
|
||||||
class WebDAVOffsetTests(unittest.IsolatedAsyncioTestCase):
|
class WebDAVFixture(unittest.IsolatedAsyncioTestCase):
|
||||||
async def asyncSetUp(self):
|
async def asyncSetUp(self):
|
||||||
self.original = dict(settings.user_config)
|
self.original = dict(settings.user_config)
|
||||||
await init_memory_db()
|
await init_memory_db()
|
||||||
|
from apps.base.utils import ip_limit
|
||||||
|
for limiter in ip_limit.values(): limiter.ips.clear()
|
||||||
self.files = {}; self.calls = []; self.fail_patch = False; self.bad_offset = False; self.fail_delete = False; self.fail_move_reply = False
|
self.files = {}; self.calls = []; self.fail_patch = False; self.bad_offset = False; self.fail_delete = False; self.fail_move_reply = False
|
||||||
self.supported = True
|
self.supported = True
|
||||||
self.block_get = None
|
self.block_get = None
|
||||||
@@ -96,6 +98,17 @@ class WebDAVOffsetTests(unittest.IsolatedAsyncioTestCase):
|
|||||||
for i in range(3):self.assertEqual((await self.chunk(uid,i)).status_code,200)
|
for i in range(3):self.assertEqual((await self.chunk(uid,i)).status_code,200)
|
||||||
return uid
|
return uid
|
||||||
|
|
||||||
|
class WebDAVOffsetTests(WebDAVFixture):
|
||||||
|
async def asyncSetUp(self):
|
||||||
|
await super().asyncSetUp()
|
||||||
|
from core.storage import WebDAVFileStorage
|
||||||
|
self.mode_patch = patch.object(WebDAVFileStorage, 'chunk_upload_mode', WebDAVFileStorage.offset_upload_mode)
|
||||||
|
self.mode_patch.start()
|
||||||
|
|
||||||
|
async def asyncTearDown(self):
|
||||||
|
self.mode_patch.stop()
|
||||||
|
await super().asyncTearDown()
|
||||||
|
|
||||||
async def test_offset_upload_resume_retry_and_no_local_merge(self):
|
async def test_offset_upload_resume_retry_and_no_local_merge(self):
|
||||||
uid=await self.init()
|
uid=await self.init()
|
||||||
self.assertEqual((await UploadChunk.get(upload_id=uid,chunk_index=-1)).storage_mode,'webdav-offset')
|
self.assertEqual((await UploadChunk.get(upload_id=uid,chunk_index=-1)).storage_mode,'webdav-offset')
|
||||||
@@ -241,12 +254,12 @@ class WebDAVOffsetTests(unittest.IsolatedAsyncioTestCase):
|
|||||||
self.assertFalse(any(c[0]=='PATCH' for c in self.calls))
|
self.assertFalse(any(c[0]=='PATCH' for c in self.calls))
|
||||||
self.assertTrue(any(c[1].endswith('1.part') for c in self.calls))
|
self.assertTrue(any(c[1].endswith('1.part') for c in self.calls))
|
||||||
|
|
||||||
async def test_legacy_limit_is_rejected_before_transferring_any_content(self):
|
async def test_legacy_limit_accepts_actual_size_without_rounding_last_chunk(self):
|
||||||
self.supported=False;settings.uploadSize=len(self.payload)
|
self.supported=False;settings.uploadSize=len(self.payload)
|
||||||
response=await self.client.post('/chunk/upload/init/',json={'file_name':'sample.txt','file_size':len(self.payload),'chunk_size':8,'file_hash':hashlib.md5(self.payload).hexdigest()})
|
response=await self.client.post('/chunk/upload/init/',json={'file_name':'sample.txt','file_size':len(self.payload),'chunk_size':8,'file_hash':hashlib.md5(self.payload).hexdigest()})
|
||||||
self.assertEqual(response.status_code,403)
|
self.assertEqual(response.status_code,200,response.text)
|
||||||
self.assertEqual(await StorageReservation.all().count(),0)
|
self.assertEqual(await StorageReservation.all().count(),1)
|
||||||
self.assertEqual(await UploadChunk.all().count(),0)
|
self.assertEqual(await UploadChunk.all().count(),1)
|
||||||
self.assertFalse(self.files)
|
self.assertFalse(self.files)
|
||||||
|
|
||||||
async def test_init_waiting_for_cancel_returns_a_new_live_session(self):
|
async def test_init_waiting_for_cancel_returns_a_new_live_session(self):
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"""Independent immutable DAV parts; one streaming assembly, never PATCH/tempfile."""
|
||||||
|
import hashlib
|
||||||
|
from unittest.mock import patch
|
||||||
|
from tests.test_webdav_offset_upload import WebDAVFixture
|
||||||
|
|
||||||
|
|
||||||
|
class WebDAVStreamTests(WebDAVFixture):
|
||||||
|
async def asyncSetUp(self):
|
||||||
|
await super().asyncSetUp()
|
||||||
|
from core.storage import WebDAVFileStorage
|
||||||
|
self.mode_patch = patch.object(WebDAVFileStorage, 'chunk_upload_mode', return_value='webdav-stream')
|
||||||
|
self.mode_patch.start()
|
||||||
|
|
||||||
|
async def asyncTearDown(self):
|
||||||
|
self.mode_patch.stop()
|
||||||
|
await super().asyncTearDown()
|
||||||
|
|
||||||
|
async def test_stream_upload_has_only_immutable_parts_and_one_final_put(self):
|
||||||
|
uid=await self.upload_all()
|
||||||
|
before=len(self.calls)
|
||||||
|
with patch('core.storage.tempfile.NamedTemporaryFile',side_effect=AssertionError('no local whole-file temporary')):
|
||||||
|
done=await self.complete(uid)
|
||||||
|
self.assertEqual(done.status_code,200,done.text)
|
||||||
|
self.assertEqual(list(self.files.values()),[self.payload])
|
||||||
|
self.assertFalse(any(c[0]=='PATCH' for c in self.calls))
|
||||||
|
puts=[c for c in self.calls[before:] if c[0]=='PUT']
|
||||||
|
self.assertEqual(len(puts),1);self.assertEqual(puts[0][3],len(self.payload))
|
||||||
|
|
||||||
|
async def test_bad_remote_part_is_not_published(self):
|
||||||
|
uid=await self.upload_all()
|
||||||
|
part=next(k for k in self.files if k.endswith('/1.part'))
|
||||||
|
self.files[part]=b'XXXXXXXX'
|
||||||
|
done=await self.complete(uid);self.assertIn(done.status_code,(400,503))
|
||||||
|
from apps.base.models import FileCodes
|
||||||
|
self.assertEqual(await FileCodes.all().count(),0)
|
||||||
|
await self.client.delete(f'/chunk/upload/{uid}');self.assertFalse(self.files)
|
||||||
|
|
||||||
|
async def test_failed_part_put_retries_without_mutating_existing_cloud_object(self):
|
||||||
|
uid=await self.init();await self.chunk(uid,0)
|
||||||
|
from apps.base.models import UploadChunk
|
||||||
|
await UploadChunk.filter(upload_id=uid,chunk_index=0).delete()
|
||||||
|
self.assertEqual((await self.chunk(uid,0)).status_code,200)
|
||||||
|
self.assertFalse(any(c[0]=='PATCH' for c in self.calls))
|
||||||
|
|
||||||
|
async def test_cancel_after_lost_move_reply_cleans_unpublished_destination(self):
|
||||||
|
uid=await self.upload_all();self.fail_move_reply=True
|
||||||
|
response=await self.complete(uid);self.assertEqual(response.status_code,503)
|
||||||
|
self.assertIn(self.payload,self.files.values())
|
||||||
|
cancel=await self.client.delete(f'/chunk/upload/{uid}')
|
||||||
|
self.assertEqual(cancel.status_code,200);self.assertFalse(self.files)
|
||||||
|
|
||||||
|
async def test_raw_chunk_upload_has_no_form_overhead_and_rejects_oversize(self):
|
||||||
|
uid=await self.init()
|
||||||
|
good=await self.client.post(f'/chunk/upload/raw/{uid}/0',content=self.payload[:8],headers={'Content-Type':'application/octet-stream'})
|
||||||
|
self.assertEqual(good.status_code,200,good.text)
|
||||||
|
bad=await self.client.post(f'/chunk/upload/raw/{uid}/1',content=b'x'*9,headers={'Content-Type':'application/octet-stream'})
|
||||||
|
self.assertEqual(bad.status_code,413,bad.text)
|
||||||
|
|
||||||
|
async def test_cancel_is_idempotent_and_preserves_already_completed_file(self):
|
||||||
|
uid=await self.init();await self.chunk(uid,0)
|
||||||
|
first=await self.client.delete(f'/chunk/upload/{uid}');self.assertEqual(first.status_code,200)
|
||||||
|
again=await self.client.delete(f'/chunk/upload/{uid}');self.assertEqual(again.status_code,200)
|
||||||
|
uid=await self.upload_all();done=await self.complete(uid);code=done.json()['detail']['code']
|
||||||
|
late=await self.client.delete(f'/chunk/upload/{uid}')
|
||||||
|
self.assertEqual(late.status_code,200,late.text);self.assertEqual(late.json()['detail']['code'],code)
|
||||||
|
self.assertTrue(late.json()['detail']['completed']);self.assertIn(self.payload,self.files.values())
|
||||||
|
|
||||||
|
async def test_cancel_preserves_completed_file_even_with_residual_session(self):
|
||||||
|
from apps.base.models import FileCodes
|
||||||
|
uid=await self.upload_all()
|
||||||
|
info=await __import__('apps.base.models',fromlist=['UploadChunk']).UploadChunk.get(upload_id=uid,chunk_index=-1)
|
||||||
|
from core.storage import WebDAVFileStorage
|
||||||
|
await WebDAVFileStorage().finish_stream_upload(info,info.save_path)
|
||||||
|
await FileCodes.create(code='DONE0001',upload_id=uid,prefix='sample',suffix='.txt',file_path=info.save_path.rsplit('/',1)[0],uuid_file_name='sample.txt',expired_count=-1)
|
||||||
|
cancel=await self.client.delete(f'/chunk/upload/{uid}')
|
||||||
|
self.assertTrue(cancel.json()['detail']['completed']);self.assertEqual(cancel.json()['detail']['code'],'DONE0001')
|
||||||
|
self.assertEqual(list(self.files.values()),[self.payload])
|
||||||
|
|
||||||
|
async def test_presign_cancel_preserves_published_file_and_deferred_direct_cleanup(self):
|
||||||
|
from apps.base.models import FileCodes,PresignUploadSession,StorageReservation
|
||||||
|
from apps.base.views import presign_upload_cancel,_get_valid_session
|
||||||
|
from core.utils import get_now
|
||||||
|
from fastapi import HTTPException
|
||||||
|
import datetime
|
||||||
|
deadline=await get_now()+datetime.timedelta(minutes=15)
|
||||||
|
await PresignUploadSession.create(upload_id='published',file_name='old.txt',file_size=4,save_path='old.txt',mode='proxy',expire_value=1,expire_style='day',expires_at=deadline)
|
||||||
|
await FileCodes.create(code='PRESIGN1',upload_id='published',prefix='old',suffix='.txt',file_path='',uuid_file_name='old.txt',expired_count=-1)
|
||||||
|
self.files['/dav/old.txt']=b'keep'
|
||||||
|
result=await presign_upload_cancel('published');self.assertTrue(result.detail['completed']);self.assertEqual(self.files['/dav/old.txt'],b'keep')
|
||||||
|
await PresignUploadSession.create(upload_id='direct',file_name='new.txt',file_size=4,save_path='new.txt',mode='direct',expire_value=1,expire_style='day',expires_at=deadline)
|
||||||
|
await StorageReservation.create(token='presign:direct',size=4,expires_at=deadline)
|
||||||
|
result=await presign_upload_cancel('direct');self.assertTrue(result.detail['cleanup_pending'])
|
||||||
|
self.assertEqual((await PresignUploadSession.get(upload_id='direct')).mode,'cancelled')
|
||||||
|
self.assertTrue(await StorageReservation.filter(token='presign:direct').exists())
|
||||||
|
with self.assertRaises(HTTPException):await _get_valid_session('direct')
|
||||||
|
|
||||||
|
async def test_expired_presign_cleanup_preserves_published_file_with_residual_session(self):
|
||||||
|
from apps.base.models import FileCodes,PresignUploadSession
|
||||||
|
from core.tasks import clean_expired_presign_session
|
||||||
|
from core.utils import get_now
|
||||||
|
import datetime
|
||||||
|
now=await get_now()
|
||||||
|
await PresignUploadSession.create(upload_id='published-stale',file_name='old.txt',file_size=4,save_path='old.txt',mode='direct',expire_value=1,expire_style='day',expires_at=now-datetime.timedelta(minutes=1))
|
||||||
|
await FileCodes.create(code='OLDKEEP1',upload_id='published-stale',prefix='old',suffix='.txt',file_path='',uuid_file_name='old.txt',expired_count=-1)
|
||||||
|
self.files['/dav/old.txt']=b'keep'
|
||||||
|
await clean_expired_presign_session('published-stale',now)
|
||||||
|
self.assertEqual(self.files['/dav/old.txt'],b'keep')
|
||||||
|
self.assertFalse(await PresignUploadSession.filter(upload_id='published-stale').exists())
|
||||||
Reference in new issue
Block a user