From 90089f793ef751a461adeb5edddfde161e0c6b8d Mon Sep 17 00:00:00 2001 From: Orion Date: Fri, 18 Sep 2026 15:38:45 +0800 Subject: [PATCH 01/12] =?UTF-8?q?=E2=9A=A1=20fix(webdav):=20=E6=94=B9?= =?UTF-8?q?=E7=94=A8=E7=8B=AC=E7=AB=8B=E5=88=86=E7=89=87=E6=B5=81=E5=BC=8F?= =?UTF-8?q?=E5=90=88=E5=B9=B6=E5=B9=B6=E9=9A=94=E7=A6=BB=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E5=8D=8F=E8=AE=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/base/views.py | 27 ++++---- core/storage.py | 88 ++++++++++--------------- core/webdav_chunks.py | 3 + core/webdav_stream.py | 102 +++++++++++++++++++++++++++++ tests/test_webdav_download.py | 43 ++++++++++++ tests/test_webdav_offset_upload.py | 13 +++- tests/test_webdav_stream_upload.py | 43 ++++++++++++ 7 files changed, 255 insertions(+), 64 deletions(-) create mode 100644 core/webdav_stream.py create mode 100644 tests/test_webdav_download.py create mode 100644 tests/test_webdav_stream_upload.py diff --git a/apps/base/views.py b/apps/base/views.py index 751c419..dcefda0 100644 --- a/apps/base/views.py +++ b/apps/base/views.py @@ -465,6 +465,9 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun # "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( chunk_hash=data.file_hash, @@ -473,6 +476,10 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun file_name=safe_file_name, ).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: task = completion_task(existing_session.upload_id) if task is not None and not task.done(): @@ -521,9 +528,7 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun data.file_name, upload_id ) try: - storage_mode = "legacy" - if settings.file_storage == "webdav": - storage_mode = await storages["webdav"]().chunk_upload_mode() + storage_mode = preferred_mode if storage_mode == "legacy" and total_chunks * data.chunk_size > settings.uploadSize: raise HTTPException(403, "文件分片大小超过上传限制") await UploadChunk.create( @@ -579,7 +584,7 @@ async def upload_chunk( existing_chunk = await UploadChunk.filter( upload_id=upload_id, chunk_index=chunk_index, completed=True ).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( detail={"chunk_hash": existing_chunk.chunk_hash, "skipped": True} ) @@ -602,7 +607,7 @@ async def upload_chunk( upload_id=upload_id, completed=True ).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 chunk_info.storage_mode in {"webdav-offset", "webdav-stream"} else uploaded_count * chunk_info.chunk_size + chunk_size if max_uploaded_size > settings.uploadSize: max_size_mb = settings.uploadSize / (1024 * 1024) raise HTTPException( @@ -610,7 +615,7 @@ async def upload_chunk( ) chunk_hash = hashlib.sha256(chunk_data).hexdigest() - if chunk_info.storage_mode == "webdav-offset": + if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"}: expected_size = min(chunk_info.chunk_size, chunk_info.file_size-chunk_index*chunk_info.chunk_size) if chunk_size != expected_size: raise HTTPException(400, "分片大小与声明值不一致") @@ -680,7 +685,7 @@ async def _cancel_upload(upload_id): try: await storage.clean_chunks(upload_id, save_path) except Exception as e: - if chunk_info.storage_mode == "webdav-offset": + if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"}: raise pass @@ -733,7 +738,7 @@ async def complete_upload( info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first() if is_cancelling(upload_id): 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) task = completion_task(upload_id) if task is None: @@ -772,14 +777,14 @@ async def _complete_upload(upload_id, data, ip): raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="分片不完整") # 用分片数 * chunk_size 校验最大可能大小 - 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 chunk_info.storage_mode in {"webdav-offset", "webdav-stream"} else len(completed_chunks_list) * chunk_info.chunk_size if max_total_size > settings.uploadSize: save_path = chunk_info.save_path if save_path: try: await storage.clean_chunks(upload_id, save_path) except Exception: - if chunk_info.storage_mode == "webdav-offset": + if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"}: raise pass await UploadChunk.filter(upload_id=upload_id).delete() @@ -828,7 +833,7 @@ async def _complete_upload(upload_id, data, ip): except HTTPException: raise 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 # 合并失败时清理临时文件 try: diff --git a/core/storage.py b/core/storage.py index c80a882..a4d877b 100644 --- a/core/storage.py +++ b/core/storage.py @@ -1051,9 +1051,10 @@ class OpenDALFileStorage(FileStorageInterface): 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 def __init__(self): @@ -1202,62 +1203,41 @@ class WebDAVFileStorage(WebDAVOffsetMixin, FileStorageInterface): return await get_file_url(file_code.code) 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: - filename = file_code.prefix + file_code.suffix - url = self._build_url(await file_code.get_file_path()) - content_length = None # 初始化为 None,表示未知大小 - - # 创建ClientSession并复用(包含认证头) - session = aiohttp.ClientSession(headers={ - "Authorization": f"Basic {base64.b64encode(f'{settings.webdav_username}:{settings.webdav_password}'.encode()).decode()}" - }) - - # 尝试发送HEAD请求获取Content-Length + upstream = await session.get(url) + if upstream.status == 404: + await session.close() + raise HTTPException(404, "文件在 WebDAV 中不存在或已被移动") + if upstream.status != 200: + status_code = upstream.status + await session.close() + raise HTTPException(502, f"WebDAV 文件读取失败(上游 {status_code}),请稍后重试") + except (aiohttp.ClientError, asyncio.TimeoutError) as exc: + await session.close() + raise HTTPException(503, "WebDAV 连接失败,请稍后重试") from exc + + async def stream_generator(): try: - async with session.head(url) as resp: - if resp.status == 200 and 'Content-Length' in resp.headers: - content_length = int(resp.headers['Content-Length']) - except Exception: - # 如果HEAD请求失败,则不提供 Content-Length - pass - - async def stream_generator(): - try: - async with session.get(url) as resp: - 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 for chunk in upstream.content.iter_chunked(65536): + yield chunk + finally: + upstream.release() + await session.close() + + headers = {"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename, safe='')}"} + if upstream.content_length is not None: + headers["Content-Length"] = str(upstream.content_length) + return StreamingResponse(stream_generator(), media_type="application/octet-stream", headers=headers, background=BackgroundTask(session.close)) async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str): """保存分片到 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) if info is not None: return await self.save_offset_chunk(info, chunk_index, chunk_data) @@ -1282,6 +1262,8 @@ class WebDAVFileStorage(WebDAVOffsetMixin, FileStorageInterface): 合并 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": return await self.finish_offset_upload(chunk_info, save_path) file_sha256 = hashlib.sha256() @@ -1354,6 +1336,8 @@ class WebDAVFileStorage(WebDAVOffsetMixin, FileStorageInterface): :param upload_id: 上传会话ID :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: return await self.clean_offset_upload(upload_id, save_path) chunk_dir = str(Path(save_path).parent / "chunks" / upload_id) diff --git a/core/webdav_chunks.py b/core/webdav_chunks.py index 582c86d..9e44781 100644 --- a/core/webdav_chunks.py +++ b/core/webdav_chunks.py @@ -18,6 +18,9 @@ class WebDAVOffsetMixin: return str(PurePosixPath(save_path).parent / 'chunks' / upload_id / 'upload.bin') 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 client.options(self.base_url) as response: if response.status not in (200,204): diff --git a/core/webdav_stream.py b/core/webdav_stream.py new file mode 100644 index 0000000..355793c --- /dev/null +++ b/core/webdav_stream.py @@ -0,0 +1,102 @@ +"""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): + info = await self._stream_session(upload_id) + if info is None: + return + directory = str(PurePosixPath(self._stream_part_path(info, 0)).parent) + async with aiohttp.ClientSession(auth=self.auth, timeout=OFFSET_TIMEOUT) as client: + async with client.delete(self._build_url(directory)) as response: + if response.status not in (200, 204, 404): + raise HTTPException(503, 'WebDAV 分片清理失败,请重试') diff --git a/tests/test_webdav_download.py b/tests/test_webdav_download.py new file mode 100644 index 0000000..30ba60c --- /dev/null +++ b/tests/test_webdav_download.py @@ -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']) diff --git a/tests/test_webdav_offset_upload.py b/tests/test_webdav_offset_upload.py index ea36b6d..91019c7 100644 --- a/tests/test_webdav_offset_upload.py +++ b/tests/test_webdav_offset_upload.py @@ -15,7 +15,7 @@ from core.settings import settings from tests.helpers import init_memory_db, close_db -class WebDAVOffsetTests(unittest.IsolatedAsyncioTestCase): +class WebDAVFixture(unittest.IsolatedAsyncioTestCase): async def asyncSetUp(self): self.original = dict(settings.user_config) await init_memory_db() @@ -96,6 +96,17 @@ class WebDAVOffsetTests(unittest.IsolatedAsyncioTestCase): for i in range(3):self.assertEqual((await self.chunk(uid,i)).status_code,200) 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): uid=await self.init() self.assertEqual((await UploadChunk.get(upload_id=uid,chunk_index=-1)).storage_mode,'webdav-offset') diff --git a/tests/test_webdav_stream_upload.py b/tests/test_webdav_stream_upload.py new file mode 100644 index 0000000..c8e4bb3 --- /dev/null +++ b/tests/test_webdav_stream_upload.py @@ -0,0 +1,43 @@ +"""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)) From 8a3147ef0d6881ca6cfc0e88781c4202a3dc743c Mon Sep 17 00:00:00 2001 From: Orion Date: Fri, 18 Sep 2026 16:17:58 +0800 Subject: [PATCH 02/12] =?UTF-8?q?=F0=9F=94=A7=20chore(test):=20=E5=9B=BA?= =?UTF-8?q?=E5=AE=9A=E5=8F=96=E4=BB=B6=E7=A0=81=E4=BF=AE=E5=A4=8D=E5=89=8D?= =?UTF-8?q?=E7=AB=AF=E5=B9=B6=E9=9A=94=E7=A6=BB=E6=B5=8B=E8=AF=95=E9=99=90?= =?UTF-8?q?=E6=B5=81=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- FRONTEND_2026_REVISION | 2 +- tests/test_webdav_offset_upload.py | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/FRONTEND_2026_REVISION b/FRONTEND_2026_REVISION index 5327244..2f79ff6 100644 --- a/FRONTEND_2026_REVISION +++ b/FRONTEND_2026_REVISION @@ -1 +1 @@ -da54bf40c9f3f7bb18ac5890b4e89e2a01724bd2 +f2461378ef9a103e72d3f8ed6ea4ef6fdaecb32c diff --git a/tests/test_webdav_offset_upload.py b/tests/test_webdav_offset_upload.py index 91019c7..f0bcb67 100644 --- a/tests/test_webdav_offset_upload.py +++ b/tests/test_webdav_offset_upload.py @@ -19,6 +19,8 @@ class WebDAVFixture(unittest.IsolatedAsyncioTestCase): async def asyncSetUp(self): self.original = dict(settings.user_config) 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.supported = True self.block_get = None From dd905c5c90f06f28c151b1557bf3e3df050e7921 Mon Sep 17 00:00:00 2001 From: Orion Date: Fri, 18 Sep 2026 16:22:22 +0800 Subject: [PATCH 03/12] =?UTF-8?q?=F0=9F=90=9B=20fix(webdav):=20=E4=BF=9D?= =?UTF-8?q?=E8=AF=81=E6=B5=81=E5=BC=8F=E4=B8=8A=E4=BC=A0=E5=8F=96=E6=B6=88?= =?UTF-8?q?=E5=90=8E=E6=B8=85=E7=90=86=E6=9C=AA=E5=8F=91=E5=B8=83=E6=96=87?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- FRONTEND_2026_REVISION | 2 +- core/webdav_stream.py | 9 +-------- tests/test_webdav_stream_upload.py | 7 +++++++ 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/FRONTEND_2026_REVISION b/FRONTEND_2026_REVISION index 2f79ff6..6560902 100644 --- a/FRONTEND_2026_REVISION +++ b/FRONTEND_2026_REVISION @@ -1 +1 @@ -f2461378ef9a103e72d3f8ed6ea4ef6fdaecb32c +a962f7aec7c222b1545ecb3774e95d534b1219e9 diff --git a/core/webdav_stream.py b/core/webdav_stream.py index 355793c..52aa955 100644 --- a/core/webdav_stream.py +++ b/core/webdav_stream.py @@ -92,11 +92,4 @@ class WebDAVStreamMixin: return save_path,digest async def clean_stream_upload(self, upload_id, save_path): - info = await self._stream_session(upload_id) - if info is None: - return - directory = str(PurePosixPath(self._stream_part_path(info, 0)).parent) - async with aiohttp.ClientSession(auth=self.auth, timeout=OFFSET_TIMEOUT) as client: - async with client.delete(self._build_url(directory)) as response: - if response.status not in (200, 204, 404): - raise HTTPException(503, 'WebDAV 分片清理失败,请重试') + await self.clean_offset_upload(upload_id, save_path) diff --git a/tests/test_webdav_stream_upload.py b/tests/test_webdav_stream_upload.py index c8e4bb3..779ada0 100644 --- a/tests/test_webdav_stream_upload.py +++ b/tests/test_webdav_stream_upload.py @@ -41,3 +41,10 @@ class WebDAVStreamTests(WebDAVFixture): 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) From dfb392545a0e1b77ae72fb6254b65aac6adbeaa3 Mon Sep 17 00:00:00 2001 From: Orion Date: Fri, 18 Sep 2026 16:54:58 +0800 Subject: [PATCH 04/12] =?UTF-8?q?=E2=9C=A8=20feat(backend):=20=E5=AE=8C?= =?UTF-8?q?=E5=96=84=E4=B8=8A=E4=BC=A0=E5=8F=96=E6=B6=88=E4=B8=8E=E5=8E=86?= =?UTF-8?q?=E5=8F=B2=E6=96=87=E4=BB=B6=E7=94=9F=E5=91=BD=E5=91=A8=E6=9C=9F?= =?UTF-8?q?=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- FRONTEND_2026_REVISION | 2 +- UPGRADE.md | 18 ++++++ apps/admin/views.py | 28 ++++++++-- apps/base/views.py | 90 ++++++++++++++++++++++++------ core/tasks.py | 3 +- tests/test_history_trash_status.py | 42 ++++++++++++++ tests/test_webdav_stream_upload.py | 45 +++++++++++++++ 7 files changed, 203 insertions(+), 25 deletions(-) create mode 100644 tests/test_history_trash_status.py diff --git a/FRONTEND_2026_REVISION b/FRONTEND_2026_REVISION index 6560902..29f894b 100644 --- a/FRONTEND_2026_REVISION +++ b/FRONTEND_2026_REVISION @@ -1 +1 @@ -a962f7aec7c222b1545ecb3774e95d534b1219e9 +e7918e9317ee56d0460e5d93c113594d054da0f9 diff --git a/UPGRADE.md b/UPGRADE.md index 8c11836..9ebfd99 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -110,3 +110,21 @@ 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 限制自动改变。 + +历史文件状态以数据库当前回收站字段为准,不再把审计保留记录计为“现存”。可恢复 +记录使用回收站相同原因标签;已清理显示“已清理”;有恢复事件的现存文件显示 +“现存,已从回收站恢复”;从未回收的文件显示“现存”。恢复后再次回收以当前原因 +为准,旧永久删除记录保留“已删除”。恢复事件查询独立于分析日期范围。 diff --git a/apps/admin/views.py b/apps/admin/views.py index 08ab2ab..d8a48b4 100644 --- a/apps/admin/views.py +++ b/apps/admin/views.py @@ -248,6 +248,7 @@ async def analytics(start: str = "", end: str = ""): files = await FileCodes.all() 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 = {} cursor = start_day @@ -371,6 +372,15 @@ async def analytics(start: str = "", end: str = ""): 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") 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 { "code": code, "name": current_name or data.get("name") or code, @@ -379,13 +389,21 @@ async def analytics(start: str = "", end: str = ""): "download_traffic": str(data.get("downloadTraffic") or 0), "upload_count": data.get("uploads") or 0, "upload_traffic": str(data.get("uploadTraffic") or 0), - "current": bool(file_item), - "expired": current_file_expired(file_item), - "deleted": bool(data.get("deleted")) and not bool(file_item), + "current": current, + "expired": expired, + "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), "uploaded_at": iso(uploaded_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: @@ -422,7 +440,7 @@ async def analytics(start: str = "", end: str = ""): sum(row["downloadTraffic"] for row in daily_rows) ), "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), "uploadTraffic": str( sum(row["uploadTraffic"] for row in daily_rows) diff --git a/apps/base/views.py b/apps/base/views.py index dcefda0..c561959 100644 --- a/apps/base/views.py +++ b/apps/base/views.py @@ -1,5 +1,6 @@ import datetime import hashlib +from io import BytesIO import os import uuid from datetime import timedelta @@ -658,6 +659,31 @@ async def upload_chunk( 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)]) async def cancel_upload(upload_id: str): if is_cancelling(upload_id): @@ -673,9 +699,16 @@ async def cancel_upload(upload_id: str): @serialize_upload 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() + 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: - raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在") + return APIResponse(detail={"cancelled":True, "message":"上传会话已结束"}) save_path = chunk_info.save_path @@ -693,7 +726,7 @@ async def _cancel_upload(upload_id): await UploadChunk.filter(upload_id=upload_id).delete() await release_storage(f"chunk:{upload_id}") - return APIResponse(detail={"message": "上传已取消"}) + return APIResponse(detail={"cancelled":True,"message": "上传已取消"}) @chunk_api.get( @@ -866,6 +899,8 @@ async def _get_valid_session( session = await PresignUploadSession.filter(upload_id=upload_id).first() if not session: raise HTTPException(404, "上传会话不存在") + if session.mode == "cancelled": + raise HTTPException(409, "上传已取消,等待后台清理") if await session.is_expired(): await session.delete() await release_storage(f"presign:{upload_id}") @@ -936,6 +971,7 @@ async def presign_upload_init( @presign_api.put( "/upload/proxy/{upload_id}", dependencies=[Depends(share_required_login)] ) +@serialize_upload async def presign_upload_proxy( upload_id: str, file: UploadFile = File(...), ip: str = Depends(ip_limit["upload"]) ): @@ -958,6 +994,8 @@ async def presign_upload_proxy( except Exception as e: raise HTTPException(500, f"文件保存失败: {str(e)}") + if is_cancelling(upload_id): + raise HTTPException(409, "上传正在取消") try: code = await FileUploadService.create_file_record( session.file_name, @@ -966,6 +1004,7 @@ async def presign_upload_proxy( session.expire_value, session.expire_style, ip=ip, + upload_id=upload_id, ) except Exception: try: @@ -989,6 +1028,7 @@ async def presign_upload_proxy( @presign_api.post( "/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"])): """直传确认,客户端完成S3直传后调用获取分享码""" session = await _get_valid_session(upload_id, expected_mode="direct") @@ -1017,6 +1057,8 @@ async def presign_upload_confirm(upload_id: str, ip: str = Depends(ip_limit["upl if not await storage.file_exists(session.save_path): raise HTTPException(404, "文件未上传或上传失败") + if is_cancelling(upload_id): + raise HTTPException(409, "上传正在取消") try: code = await FileUploadService.create_file_record( session.file_name, @@ -1025,6 +1067,7 @@ async def presign_upload_confirm(upload_id: str, ip: str = Depends(ip_limit["upl session.expire_value, session.expire_style, ip=ip, + upload_id=upload_id, ) except Exception: try: @@ -1069,23 +1112,34 @@ async def presign_upload_status(upload_id: str): @presign_api.delete("/upload/{upload_id}", dependencies=[Depends(share_required_login)]) 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() + 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: - raise HTTPException(404, "上传会话不存在") - - if session.mode == "direct": - storage: FileStorageInterface = storages[settings.file_storage]() - try: - if await storage.file_exists(session.save_path): - temp_file_code = 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 - + return APIResponse(detail={"cancelled":True}) + storage = storages[settings.file_storage]() + if session.mode in {"direct", "cancelled"}: + # Browser abort cannot revoke a pre-signed PUT already committing remotely. + # Keep a durable tombstone and quota until the signed URL expires. + session.mode = "cancelled" + await session.save(update_fields=["mode"]) + return APIResponse(detail={"cancelled":True,"cleanup_pending":True,"message":"传输已中断,临时文件将在上传授权到期后自动清理"}) + 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 session.delete() await release_storage(f"presign:{upload_id}") - return APIResponse(detail={"message": "上传会话已取消"}) + return APIResponse(detail={"cancelled":True,"message":"上传已取消"}) diff --git a/core/tasks.py b/core/tasks.py index 2e32d58..add243f 100644 --- a/core/tasks.py +++ b/core/tasks.py @@ -113,7 +113,7 @@ async def clean_expired_presign_sessions(): expires_at__lt=now ).all() for session in expired_sessions: - if session.mode == "direct": + if session.mode in {"direct", "cancelled"}: try: if await storage.file_exists(session.save_path): await storage.delete_file( @@ -127,6 +127,7 @@ async def clean_expired_presign_sessions(): "清理过期直传文件失败 " f"upload_id={session.upload_id}: {e}" ) + continue await StorageReservation.filter( token=f"presign:{session.upload_id}" ).delete() diff --git a/tests/test_history_trash_status.py b/tests/test_history_trash_status.py new file mode 100644 index 0000000..25503fd --- /dev/null +++ b/tests/test_history_trash_status.py @@ -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) diff --git a/tests/test_webdav_stream_upload.py b/tests/test_webdav_stream_upload.py index 779ada0..844e995 100644 --- a/tests/test_webdav_stream_upload.py +++ b/tests/test_webdav_stream_upload.py @@ -48,3 +48,48 @@ class WebDAVStreamTests(WebDAVFixture): 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') From 1023292e7113c5532e60adb0656ec9db139828f8 Mon Sep 17 00:00:00 2001 From: Orion Date: Fri, 18 Sep 2026 16:57:59 +0800 Subject: [PATCH 05/12] =?UTF-8?q?=F0=9F=90=9B=20fix(upload):=20=E5=AE=9A?= =?UTF-8?q?=E6=97=B6=E6=B8=85=E7=90=86=E4=BF=9D=E6=8A=A4=E5=B7=B2=E5=8F=91?= =?UTF-8?q?=E5=B8=83=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/tasks.py | 42 ++++++++++++++---------------- tests/test_webdav_stream_upload.py | 13 +++++++++ 2 files changed, 32 insertions(+), 23 deletions(-) diff --git a/core/tasks.py b/core/tasks.py index add243f..3ae15b3 100644 --- a/core/tasks.py +++ b/core/tasks.py @@ -103,35 +103,31 @@ async def clean_incomplete_uploads(): 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(): while True: try: await refresh_settings() - storage: FileStorageInterface = storages[settings.file_storage]() now = await get_now() - expired_sessions = await PresignUploadSession.filter( - expires_at__lt=now - ).all() + expired_sessions = await PresignUploadSession.filter(expires_at__lt=now).all() for session in expired_sessions: - if session.mode in {"direct", "cancelled"}: - try: - 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), - ) - ) - except Exception as e: - logger.error( - "清理过期直传文件失败 " - f"upload_id={session.upload_id}: {e}" - ) - continue - await StorageReservation.filter( - token=f"presign:{session.upload_id}" - ).delete() - await session.delete() + try: + await clean_expired_presign_session(session.upload_id, now) + except Exception as e: + logger.error(f"清理上传失败,保留会话等待重试 upload_id={session.upload_id}: {e}") except Exception as e: logger.error(f"清理过期预签名会话异常: {e}") finally: diff --git a/tests/test_webdav_stream_upload.py b/tests/test_webdav_stream_upload.py index 844e995..6152eab 100644 --- a/tests/test_webdav_stream_upload.py +++ b/tests/test_webdav_stream_upload.py @@ -93,3 +93,16 @@ class WebDAVStreamTests(WebDAVFixture): 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()) From c2d743ba51d67b33e14d5a6ab0c966f951c0af87 Mon Sep 17 00:00:00 2001 From: Orion Date: Fri, 18 Sep 2026 17:51:42 +0800 Subject: [PATCH 06/12] =?UTF-8?q?=E2=9C=A8=20feat(config):=20=E7=BB=9F?= =?UTF-8?q?=E4=B8=80=E5=88=86=E7=89=87=E5=A4=A7=E5=B0=8F=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E4=B8=8E=E7=BB=AD=E4=BC=A0=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- FRONTEND_2026_REVISION | 2 +- UPGRADE.md | 12 +++++ apps/admin/services.py | 11 +++++ apps/base/views.py | 20 ++++---- core/settings.py | 1 + main.py | 1 + tests/test_chunk_size_config.py | 75 ++++++++++++++++++++++++++++++ tests/test_webdav_offset_upload.py | 8 ++-- 8 files changed, 116 insertions(+), 14 deletions(-) create mode 100644 tests/test_chunk_size_config.py diff --git a/FRONTEND_2026_REVISION b/FRONTEND_2026_REVISION index 29f894b..e038fc4 100644 --- a/FRONTEND_2026_REVISION +++ b/FRONTEND_2026_REVISION @@ -1 +1 @@ -e7918e9317ee56d0460e5d93c113594d054da0f9 +272741ee49671327964e82c3cb0dec0a81e8261d diff --git a/UPGRADE.md b/UPGRADE.md index 9ebfd99..908d464 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -128,3 +128,15 @@ WebDAV 保持 legacy 路径。新模式仍支持重试、续传、取消、配 记录使用回收站相同原因标签;已清理显示“已清理”;有恢复事件的现存文件显示 “现存,已从回收站恢复”;从未回收的文件显示“现存”。恢复后再次回收以当前原因 为准,旧永久删除记录保留“已删除”。恢复事件查询独立于分析日期范围。 + +## 分片大小设置 + +后台“系统设置 → 上传限制 → 上传分片大小”可配置 `chunkSizeMB`,范围 1–100 整数, +默认 90。单位 MB 在本程序中按 MiB(1024×1024 字节)换算。 +保存后公共配置接口同步下发,前端用于新上传,后端对新会话再次限幅;客户端缓存 +尚未刷新时,服务端返回的协商大小仍为准。已有上传沿用原大小,调整设置不改变 +续传偏移。最后一片按实际剩余字节检查,上传上限不按分片补齐后的大小计算。 + +此值控制分片,不保证代理/CDN支持整文件 PUT;WebDAV流式合并仍以完整文件大小 +发起最终PUT,代理限制需要独立验证。当前测试环境继续使用公网 cd2 地址; +90 MiB 分片及90 MiB+3字节整文件已实测上传、合并、下载SHA-256一致并清理。 diff --git a/apps/admin/services.py b/apps/admin/services.py index 315bd49..54832ed 100644 --- a/apps/admin/services.py +++ b/apps/admin/services.py @@ -1709,6 +1709,7 @@ class ConfigService: "adminSessionExpire", "trashRetentionDays", "enableChunk", + "chunkSizeMB", "errorCount", "errorMinute", "loginCount", @@ -1747,6 +1748,16 @@ class ConfigService: if key in settings.default_config and key not in INTERNAL_CONFIG_KEYS } + 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_password_changed = False if admin_token is None or admin_token == "": diff --git a/apps/base/views.py b/apps/base/views.py index c561959..ab02b93 100644 --- a/apps/base/views.py +++ b/apps/base/views.py @@ -442,7 +442,11 @@ async def parse_complete_upload(request: Request) -> CompleteUploadModel: async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chunk_upload)): safe_file_name = await sanitize_filename(unquote(data.file_name or "")) 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 max_possible_size = data.file_size if max_possible_size > settings.uploadSize: @@ -530,8 +534,6 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun ) try: storage_mode = preferred_mode - if storage_mode == "legacy" and total_chunks * data.chunk_size > settings.uploadSize: - raise HTTPException(403, "文件分片大小超过上传限制") await UploadChunk.create( upload_id=upload_id, storage_mode=storage_mode, @@ -608,7 +610,7 @@ async def upload_chunk( upload_id=upload_id, completed=True ).count() # 已上传分片的最大可能大小 + 当前分片 - max_uploaded_size = chunk_info.file_size if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"} else uploaded_count * chunk_info.chunk_size + chunk_size + max_uploaded_size = chunk_info.file_size if max_uploaded_size > settings.uploadSize: max_size_mb = settings.uploadSize / (1024 * 1024) raise HTTPException( @@ -616,10 +618,10 @@ async def upload_chunk( ) chunk_hash = hashlib.sha256(chunk_data).hexdigest() + expected_size = min(chunk_info.chunk_size, chunk_info.file_size-chunk_index*chunk_info.chunk_size) + if chunk_size != expected_size: + raise HTTPException(400, "分片大小与声明值不一致") if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"}: - expected_size = min(chunk_info.chunk_size, chunk_info.file_size-chunk_index*chunk_info.chunk_size) - if chunk_size != expected_size: - raise HTTPException(400, "分片大小与声明值不一致") if existing_chunk: if existing_chunk.chunk_hash != chunk_hash: raise HTTPException(409, "重传分片内容不一致") @@ -809,8 +811,8 @@ async def _complete_upload(upload_id, data, ip): if len(completed_chunks_list) != chunk_info.total_chunks: raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="分片不完整") - # 用分片数 * chunk_size 校验最大可能大小 - max_total_size = chunk_info.file_size if chunk_info.storage_mode in {"webdav-offset", "webdav-stream"} else len(completed_chunks_list) * chunk_info.chunk_size + # Each newly uploaded chunk has an exact-length check, including the last. + max_total_size = chunk_info.file_size if max_total_size > settings.uploadSize: save_path = chunk_info.save_path if save_path: diff --git a/core/settings.py b/core/settings.py index f7f7480..77ce1c6 100644 --- a/core/settings.py +++ b/core/settings.py @@ -54,6 +54,7 @@ DEFAULT_CONFIG = { "code_generate_type": "secret", "uploadMinute": 1, "enableChunk": 0, + "chunkSizeMB": 90, "webdav_url": "", "webdav_password": "", "webdav_username": "", diff --git a/main.py b/main.py index 8aeaba1..a291f4f 100644 --- a/main.py +++ b/main.py @@ -57,6 +57,7 @@ def build_public_config() -> dict: "allowedFileTypes": settings.allowed_file_types, "expireStyle": settings.expireStyle, "enableChunk": settings.enableChunk, + "chunkSizeMB": settings.chunkSizeMB, "openUpload": settings.openUpload, "notify_title": settings.notify_title, "notify_content": settings.notify_content, diff --git a/tests/test_chunk_size_config.py b/tests/test_chunk_size_config.py new file mode 100644 index 0000000..8912610 --- /dev/null +++ b/tests/test_chunk_size_config.py @@ -0,0 +1,75 @@ +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) diff --git a/tests/test_webdav_offset_upload.py b/tests/test_webdav_offset_upload.py index f0bcb67..4856898 100644 --- a/tests/test_webdav_offset_upload.py +++ b/tests/test_webdav_offset_upload.py @@ -254,12 +254,12 @@ class WebDAVOffsetTests(WebDAVFixture): self.assertFalse(any(c[0]=='PATCH' 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) 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(await StorageReservation.all().count(),0) - self.assertEqual(await UploadChunk.all().count(),0) + self.assertEqual(response.status_code,200,response.text) + self.assertEqual(await StorageReservation.all().count(),1) + self.assertEqual(await UploadChunk.all().count(),1) self.assertFalse(self.files) async def test_init_waiting_for_cancel_returns_a_new_live_session(self): From 5c1e1ef36811d588b58927e8f82308126f65abed Mon Sep 17 00:00:00 2001 From: Orion Date: Fri, 18 Sep 2026 17:54:13 +0800 Subject: [PATCH 07/12] =?UTF-8?q?=F0=9F=90=9B=20fix(upload):=20=E6=A0=A1?= =?UTF-8?q?=E9=AA=8C=E6=97=A7=E4=BC=9A=E8=AF=9D=E6=9C=AB=E7=89=87=E5=AE=9E?= =?UTF-8?q?=E9=99=85=E5=A4=A7=E5=B0=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/storage.py | 11 +++++++++++ tests/test_chunk_size_config.py | 20 ++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/core/storage.py b/core/storage.py index a4d877b..5768764 100644 --- a/core/storage.py +++ b/core/storage.py @@ -85,6 +85,12 @@ class FileStorageInterface: """ 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]: """ 生成预签名上传URL @@ -245,6 +251,7 @@ class SystemFileStorage(FileStorageInterface): raise ValueError(f"分片{i}文件不存在") async with aiofiles.open(chunk_path, "rb") as in_file: chunk_data = await in_file.read() + self.validate_stored_chunk_size(chunk_info, i, chunk_data) current_hash = hashlib.sha256(chunk_data).hexdigest() if current_hash != chunk_record.chunk_hash: raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}") @@ -489,6 +496,7 @@ class S3FileStorage(FileStorageInterface): except Exception as e: raise ValueError(f"分片{i}文件不存在: {e}") + self.validate_stored_chunk_size(chunk_info, i, chunk_data) current_hash = hashlib.sha256(chunk_data).hexdigest() if current_hash != chunk_record.chunk_hash: raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}") @@ -843,6 +851,7 @@ class OneDriveFileStorage(FileStorageInterface): except Exception as e: raise ValueError(f"分片{i}文件不存在: {e}") + self.validate_stored_chunk_size(chunk_info, i, chunk_data) current_hash = hashlib.sha256(chunk_data).hexdigest() if current_hash != chunk_record.chunk_hash: raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}") @@ -1009,6 +1018,7 @@ class OpenDALFileStorage(FileStorageInterface): except Exception as e: raise ValueError(f"分片{i}文件不存在: {e}") + self.validate_stored_chunk_size(chunk_info, i, chunk_data) current_hash = hashlib.sha256(chunk_data).hexdigest() if current_hash != chunk_record.chunk_hash: raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}") @@ -1293,6 +1303,7 @@ class WebDAVFileStorage(WebDAVStreamMixin, WebDAVOffsetMixin, FileStorageInterfa chunk_data = await resp.read() # 验证哈希 + self.validate_stored_chunk_size(chunk_info, i, chunk_data) current_hash = hashlib.sha256(chunk_data).hexdigest() if current_hash != chunk_record.chunk_hash: raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}") diff --git a/tests/test_chunk_size_config.py b/tests/test_chunk_size_config.py index 8912610..96b750c 100644 --- a/tests/test_chunk_size_config.py +++ b/tests/test_chunk_size_config.py @@ -73,3 +73,23 @@ class ChunkSizeConfigTests(unittest.IsolatedAsyncioTestCase): 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()) From 32b31ac27120a7240d858918ae56dcb528adef02 Mon Sep 17 00:00:00 2001 From: Orion Date: Fri, 18 Sep 2026 18:03:02 +0800 Subject: [PATCH 08/12] =?UTF-8?q?=F0=9F=93=9D=20docs:=20=E8=AE=B0=E5=BD=95?= =?UTF-8?q?=E5=8F=AF=E9=85=8D=E7=BD=AE=E5=88=86=E7=89=87=E5=A4=A7=E5=B0=8F?= =?UTF-8?q?=E7=9A=84=E6=B5=8B=E8=AF=95=E7=8E=AF=E5=A2=83=E9=AA=8C=E6=94=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 记录默认 90MB、可配置 1–100MB 的设置入口与版本来源 - 确认设置保存和刷新后生效,新上传按配置值进行分片 - 验证实际上传下载哈希一致,以及回收、恢复、清理后的历史状态 - 记录单元测试、接口集成、覆盖率和前端构建结果 - 明确测试文件清理、默认值恢复及生产环境保持不变 --- UPGRADE.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/UPGRADE.md b/UPGRADE.md index 908d464..d32d76e 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -140,3 +140,16 @@ WebDAV 保持 legacy 路径。新模式仍支持重试、续传、取消、配 此值控制分片,不保证代理/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 配置。 From 69cfa436dea720628a05a367386a008c3cdff957 Mon Sep 17 00:00:00 2001 From: Orion Date: Sat, 19 Sep 2026 00:35:56 +0800 Subject: [PATCH 09/12] =?UTF-8?q?=E2=9C=A8=20feat:=20=E5=AE=8C=E5=96=84?= =?UTF-8?q?=E4=B8=8B=E8=BD=BD=E6=A3=80=E6=B5=8B=E4=B8=8E=E6=9F=A5=E4=BB=B6?= =?UTF-8?q?=E7=94=9F=E5=91=BD=E5=91=A8=E6=9C=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 提供有鉴权和并发限制的轻量下载检测,不消耗次数或生成取件事件 * 支持保存检测间隔,并校验关闭选项和有效范围 * 将成功查件记录按时间并入生命周期,与实际发起取件事件区分 * 统一签名下载入口,文本与直链分享仅在下载时计数并保留直链传输 * 处理检测取消时的连接释放,补充鉴权、存储和生命周期集成验证 * 记录文件恢复和测试验收,明确先推送代码再部署测试环境 --- UPGRADE.md | 71 ++++++++++ apps/admin/download_checks.py | 127 ++++++++++++++++++ apps/admin/schemas.py | 4 + apps/admin/services.py | 24 +++- apps/admin/views.py | 8 +- apps/base/views.py | 61 ++++----- core/settings.py | 1 + core/storage.py | 3 + tests/test_download_checks.py | 190 +++++++++++++++++++++++++++ tests/test_lookup_lifecycle.py | 102 ++++++++++++++ tests/test_pr494_security_patches.py | 3 +- 11 files changed, 555 insertions(+), 39 deletions(-) create mode 100644 apps/admin/download_checks.py create mode 100644 tests/test_download_checks.py create mode 100644 tests/test_lookup_lifecycle.py diff --git a/UPGRADE.md b/UPGRADE.md index d32d76e..2f89f99 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -153,3 +153,74 @@ WebDAV 保持 legacy 路径。新模式仍支持重试、续传、取消、配 测试文件已清理。结束后恢复 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。 +- 部署流程:必须先提交并推送前后端代码,再由已推送提交打包构建测试镜像; + 不再使用未提交的工作区部署。生产升级仍需用户验收后明确授权。 diff --git a/apps/admin/download_checks.py b/apps/admin/download_checks.py new file mode 100644 index 0000000..4a556cf --- /dev/null +++ b/apps/admin/download_checks.py @@ -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))) diff --git a/apps/admin/schemas.py b/apps/admin/schemas.py index 851e340..31633cc 100644 --- a/apps/admin/schemas.py +++ b/apps/admin/schemas.py @@ -98,3 +98,7 @@ class FileViewPresetData(BaseModel): class FileViewPresetDeleteData(BaseModel): id: str + + +class DownloadCheckData(BaseModel): + ids: list[Annotated[int, Field(strict=True, gt=0)]] = Field(min_length=1, max_length=20) diff --git a/apps/admin/services.py b/apps/admin/services.py index 54832ed..62af3fe 100644 --- a/apps/admin/services.py +++ b/apps/admin/services.py @@ -1479,8 +1479,21 @@ class FileService(TrashManagementMixin): "event_count": download_event_count, } ) + lookup_stats = await TransferStats.filter( + action="lookup", file_code_id=file_code.id + ).order_by("created_at", "id") + events = [] + for index, stat in enumerate(lookup_stats, start=1): + events.append({ + "key": "queried_event", + "status": "done", + "severity": "info", + "timestamp": stat.created_at, + "value": index, + "detail": stat.ip or "", + }) for index, stat in enumerate(download_stats, start=1): - timeline.append( + events.append( { "key": "retrieved_event", "status": "done", @@ -1490,6 +1503,7 @@ class FileService(TrashManagementMixin): "detail": stat.ip or "", } ) + timeline.extend(sorted(events, key=lambda event: event["timestamp"])) return timeline def _seconds_between( @@ -1710,6 +1724,7 @@ class ConfigService: "trashRetentionDays", "enableChunk", "chunkSizeMB", + "downloadCheckInterval", "errorCount", "errorMinute", "loginCount", @@ -1748,6 +1763,13 @@ class ConfigService: if key in settings.default_config and key not in INTERNAL_CONFIG_KEYS } + if "downloadCheckInterval" in update_data: + interval = update_data["downloadCheckInterval"] + if isinstance(interval, bool) or not isinstance(interval, int) or ( + interval != 0 and not 30 <= interval <= 86400 + ): + raise HTTPException(400, "检测间隔必须是 0(关闭)或 30–86400 秒的整数") + if "chunkSizeMB" in update_data: raw_size = update_data["chunkSizeMB"] if isinstance(raw_size, bool) or not ( diff --git a/apps/admin/views.py b/apps/admin/views.py index d8a48b4..0e28b85 100644 --- a/apps/admin/views.py +++ b/apps/admin/views.py @@ -18,6 +18,7 @@ from apps.admin.dependencies import ( ) from apps.admin.schemas import ( IDData, + DownloadCheckData, IDsData, BatchUpdateFileData, BatchFilePolicyActionData, @@ -944,4 +945,9 @@ async def update_file( count=1, meta={"fields": sorted(update_data.keys())}, ) - return APIResponse(detail="更新成功") \ No newline at end of file + 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)) diff --git a/apps/base/views.py b/apps/base/views.py index ab02b93..72b6db8 100644 --- a/apps/base/views.py +++ b/apps/base/views.py @@ -11,7 +11,7 @@ from typing import Optional, Tuple, Union from fastapi import APIRouter, Form, Request, UploadFile, File, Depends, HTTPException from pydantic import BaseModel, ValidationError from starlette import status -from starlette.responses import Response +from starlette.responses import Response, RedirectResponse from tortoise.expressions import Case, F, Q, When from apps.admin.dependencies import share_required_login @@ -244,7 +244,7 @@ async def get_code_file_by_code( file_code = await FileCodes.filter(code=normalized_code, is_trashed=False).first() if not file_code: return False, "文件不存在" - if await file_code.is_expired() and check: + if check and (file_code.expired_count == 0 or await file_code.is_expired()): return False, "文件已过期" return True, file_code @@ -290,17 +290,30 @@ def build_file_metadata(file_code: FileCodes) -> dict: } +async def build_download_response(file_code: FileCodes, file_storage: FileStorageInterface): + if file_code.text is not None: + filename = f"{file_code.prefix or 'Text'}{file_code.suffix or '.txt'}" + return Response( + content=file_code.text, + media_type="text/plain", + headers={"Content-Disposition": f"attachment; filename*=UTF-8''{quote(filename, safe='')}"}, + ) + if is_local_ref(file_code): + return build_local_ref_download(file_code) + if file_code.expired_count < 0: + url = await file_storage.get_file_url(file_code) + if isinstance(url, str) and url.startswith(("https://", "http://")): + return RedirectResponse(url) + return await file_storage.get_file_response(file_code) + + async def build_select_detail( file_code: FileCodes, file_storage: FileStorageInterface ) -> dict: metadata = build_file_metadata(file_code) - if file_code.text is not None: - download_url = None - elif file_code.expired_count >= 0 or is_local_ref(file_code): - # 有次数限制的文件必须经过下载接口,第三方直链无法阻止重复使用。 - download_url = await get_proxy_file_url(file_code.code) - else: - download_url = await file_storage.get_file_url(file_code) + # Lookup never counts as retrieval; all downloads first pass this signed entry. + # Unlimited direct storage links still redirect at download time. + download_url = await get_proxy_file_url(file_code.code) content = file_code.text if file_code.text is not None else None return { **metadata, @@ -348,19 +361,7 @@ async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])): if not await consume_file_usage(file_code): return APIResponse(code=404, detail="文件已过期") await record_transfer_stat("download", file_code, file_code.size, ip) - if file_code.text is not None: - filename = f"{file_code.prefix or 'Text'}{file_code.suffix or '.txt'}" - return Response( - content=file_code.text, - media_type="text/plain", - headers={ - "Content-Disposition": ( - f"attachment; filename*=UTF-8''{quote(filename, safe='')}" - ) - }, - ) - - return (build_local_ref_download(file_code) if is_local_ref(file_code) else await file_storage.get_file_response(file_code)) + return await build_download_response(file_code, file_storage) @share_api.post("/select/") @@ -373,15 +374,7 @@ async def select_file(data: SelectFileModel, ip: str = Depends(ip_limit["error"] assert isinstance(file_code, FileCodes) detail = await build_select_detail(file_code, file_storage) - download_url = detail.get("download_url") - consumes_on_download = isinstance(download_url, str) and download_url.startswith( - "/share/download?" - ) - if not consumes_on_download: - if not await consume_file_usage(file_code): - return APIResponse(code=404, detail="文件已过期") - await record_transfer_stat("download", file_code, file_code.size, ip) - detail.update(build_file_metadata(file_code)) + await record_transfer_stat("lookup", file_code, 0, ip) return APIResponse(detail=detail) @@ -406,11 +399,7 @@ async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"] return APIResponse(code=404, detail="文件已过期") await record_transfer_stat("download", file_code, file_code.size, ip) - return ( - APIResponse(detail=file_code.text) - if file_code.text - else (build_local_ref_download(file_code) if is_local_ref(file_code) else await file_storage.get_file_response(file_code)) - ) + return await build_download_response(file_code, file_storage) chunk_api = APIRouter(prefix="/chunk", tags=["切片"]) diff --git a/core/settings.py b/core/settings.py index 77ce1c6..156d77e 100644 --- a/core/settings.py +++ b/core/settings.py @@ -55,6 +55,7 @@ DEFAULT_CONFIG = { "uploadMinute": 1, "enableChunk": 0, "chunkSizeMB": 90, + "downloadCheckInterval": 300, "webdav_url": "", "webdav_password": "", "webdav_username": "", diff --git a/core/storage.py b/core/storage.py index 5768764..257e236 100644 --- a/core/storage.py +++ b/core/storage.py @@ -1229,6 +1229,9 @@ class WebDAVFileStorage(WebDAVStreamMixin, WebDAVOffsetMixin, FileStorageInterfa except (aiohttp.ClientError, asyncio.TimeoutError) as exc: await session.close() raise HTTPException(503, "WebDAV 连接失败,请稍后重试") from exc + except asyncio.CancelledError: + await session.close() + raise async def stream_generator(): try: diff --git a/tests/test_download_checks.py b/tests/test_download_checks.py new file mode 100644 index 0000000..4f0d17f --- /dev/null +++ b/tests/test_download_checks.py @@ -0,0 +1,190 @@ +import asyncio +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import httpx +from aiohttp import web +from fastapi import FastAPI +from starlette.responses import StreamingResponse +from apps.admin.views import admin_api +from apps.admin.dependencies import admin_required +from apps.admin.download_checks import _read_response +from apps.base.models import FileCodes, KeyValue, TransferStats +from core.settings import settings +from tests.helpers import init_memory_db, close_db + + +class DownloadCheckTests(unittest.IsolatedAsyncioTestCase): + async def asyncSetUp(self): + self.original = dict(settings.user_config) + await init_memory_db() + self.status = 200 + self.data = b'file content' + self.requests = 0 + upstream = web.Application() + upstream.router.add_get('/dav/{path:.*}', self.upstream) + self.runner = web.AppRunner(upstream) + await self.runner.setup() + site = web.TCPSite(self.runner, '127.0.0.1', 0) + await site.start() + port = site._server.sockets[0].getsockname()[1] + settings.user_config = {'file_storage': 'webdav', 'jwt_secret': 'test-secret', + 'webdav_url': f'http://127.0.0.1:{port}/dav', + 'webdav_username': 'test', 'webdav_password': 'test'} + await KeyValue.create(key='settings', value=dict(settings.user_config)) + self.file = await FileCodes.create(code='CHECK123', prefix='a', suffix='.txt', + file_path='share/test', uuid_file_name='a.txt', size=len(self.data), expired_count=2) + app = FastAPI() + app.include_router(admin_api) + app.dependency_overrides[admin_required] = lambda: True + self.app = app + self.client = httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test') + + async def asyncTearDown(self): + await self.client.aclose() + await self.runner.cleanup() + await close_db() + settings.user_config = self.original + + async def upstream(self, request): + self.requests += 1 + return web.Response(status=self.status, body=self.data if self.status == 200 else b'failure') + + async def check(self, ids=None): + response = await self.client.post('/admin/file/download-check', json={'ids': ids or [self.file.id]}) + self.assertEqual(response.status_code, 200, response.text) + return response.json()['detail'] + + async def test_real_webdav_read_without_usage_or_audit_side_effects(self): + rows = await self.check([self.file.id, self.file.id]) + self.assertEqual(len(rows), 1) + self.assertEqual(rows[0]['status'], 'available', rows) + self.assertIsNotNone(rows[0]['checkedAt']) + self.assertEqual(self.requests, 1) + await self.file.refresh_from_db() + self.assertEqual(self.file.expired_count, 2) + self.assertEqual(self.file.used_count, 0) + self.assertEqual(await TransferStats.all().count(), 0) + + async def test_404_416_and_size_mismatch_are_unavailable(self): + for status in [404, 416, 401]: + self.status = status + self.assertEqual((await self.check())[0]['status'], 'unavailable') + self.status = 200 + self.data = b'wrong size' + self.assertEqual((await self.check())[0]['status'], 'unavailable') + + async def test_expired_trashed_missing_and_text_batch(self): + self.file.expired_count = 0 + await self.file.save() + text = await FileCodes.create(code='TEXT1234', text='', size=0) + trash = await FileCodes.create(code='TRASH123', is_trashed=True) + rows = await self.check([self.file.id, text.id, trash.id, 999]) + self.assertEqual([row['status'] for row in rows], ['unavailable', 'available', 'unavailable', 'unavailable']) + self.assertEqual(self.requests, 0) + + async def test_timeout_is_reported_without_failing_the_batch(self): + async def slow(_): + await asyncio.sleep(1) + with patch('apps.admin.download_checks.CHECK_TIMEOUT', 0.01), patch('apps.admin.download_checks._probe', slow): + rows = await self.check() + self.assertEqual(rows[0]['message'], '检测超时,请重试') + + async def test_local_file_reads_and_missing_are_detected(self): + settings.file_storage = 'local' + with tempfile.TemporaryDirectory() as directory, patch('core.storage.data_root', Path(directory)): + path = Path(directory) / 'share/test/a.txt' + path.parent.mkdir(parents=True) + path.write_bytes(self.data) + self.assertEqual((await self.check())[0]['status'], 'available') + path.unlink() + self.assertEqual((await self.check())[0]['status'], 'unavailable') + + async def test_direct_link_is_read_not_just_head(self): + from core.storage import WebDAVFileStorage + with patch.object(WebDAVFileStorage, 'get_file_url', return_value=settings.webdav_url + '/direct'): + self.file.expired_count = -1 + await self.file.save() + self.assertEqual((await self.check())[0]['status'], 'available') + self.status = 404 + self.assertEqual((await self.check())[0]['status'], 'unavailable') + + async def test_admin_auth_and_batch_validation(self): + for ids in [[], [0], ['1'], list(range(1, 22))]: + result = await self.client.post('/admin/file/download-check', json={'ids': ids}) + self.assertEqual(result.status_code, 422) + self.app.dependency_overrides.clear() + result = await self.client.post('/admin/file/download-check', json={'ids': [1]}) + self.assertEqual(result.status_code, 401) + + async def test_interval_persistence_and_invalid_config(self): + for interval in [0, 30, 300, 86400]: + result = await self.client.patch('/admin/config/update', json={'downloadCheckInterval': interval}) + self.assertEqual(result.status_code, 200, result.text) + result = await self.client.get('/admin/config/get') + self.assertEqual(result.json()['detail']['downloadCheckInterval'], interval) + for interval in [-1, 1, 29, 86401, True, '30', 30.5]: + result = await self.client.patch('/admin/config/update', json={'downloadCheckInterval': interval}) + self.assertEqual(result.status_code, 400) + + async def test_probe_stops_stream_and_closes_on_read_failure(self): + closed = [] + async def stream(): + try: + yield b'x' + raise AssertionError('must not read the entire file') + finally: + closed.append(True) + await _read_response(StreamingResponse(stream()), 100) + self.assertEqual(closed, [True]) + async def broken(): + try: + raise OSError('connection lost') + yield b'' + finally: + closed.append(True) + with self.assertRaises(OSError): + await _read_response(StreamingResponse(broken()), 100) + self.assertEqual(len(closed), 2) + + async def test_local_reference_uses_nas_file_even_with_webdav_selected(self): + self.file.file_path = 'local-ref' + self.file.uuid_file_name = 'a.txt' + await self.file.save() + with tempfile.TemporaryDirectory() as directory, patch('core.settings.data_root', Path(directory)): + path = Path(directory) / 'local/a.txt' + path.parent.mkdir() + path.write_bytes(self.data) + self.assertEqual((await self.check())[0]['status'], 'available') + path.unlink() + self.assertEqual((await self.check())[0]['status'], 'unavailable') + self.assertEqual(self.requests, 0) + + async def test_empty_local_file_and_expired_share(self): + import datetime + from core.utils import get_now + settings.file_storage = 'local' + self.file.size = 0 + await self.file.save() + with tempfile.TemporaryDirectory() as directory, patch('core.storage.data_root', Path(directory)): + path = Path(directory) / 'share/test/a.txt' + path.parent.mkdir(parents=True) + path.write_bytes(b'') + self.assertEqual((await self.check())[0]['status'], 'available') + self.file.expired_at = await get_now() - datetime.timedelta(seconds=1) + self.file.expired_count = -1 + await self.file.save() + self.assertEqual((await self.check())[0]['status'], 'unavailable') + + async def test_network_failure_and_empty_body_are_unavailable(self): + from unittest.mock import AsyncMock + from core.storage import WebDAVFileStorage + with patch.object(WebDAVFileStorage, 'get_file_response', side_effect=OSError('connection lost')): + self.assertEqual((await self.check())[0]['status'], 'unavailable') + async def empty(): + if False: + yield b'' + with patch.object(WebDAVFileStorage, 'get_file_response', new=AsyncMock(return_value=StreamingResponse(empty()))): + self.assertEqual((await self.check())[0]['status'], 'unavailable') diff --git a/tests/test_lookup_lifecycle.py b/tests/test_lookup_lifecycle.py new file mode 100644 index 0000000..355893e --- /dev/null +++ b/tests/test_lookup_lifecycle.py @@ -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) diff --git a/tests/test_pr494_security_patches.py b/tests/test_pr494_security_patches.py index 986a5ba..e93700d 100644 --- a/tests/test_pr494_security_patches.py +++ b/tests/test_pr494_security_patches.py @@ -131,7 +131,8 @@ class SecurityPatchTests(unittest.TestCase): result = await views.download_file( 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: settings.user_config = original await Tortoise.close_connections() From 87d2e3da23f6a8d302c3b3c84e304117b8a3b48c Mon Sep 17 00:00:00 2001 From: Orion Date: Sat, 19 Sep 2026 00:38:18 +0800 Subject: [PATCH 10/12] =?UTF-8?q?=F0=9F=94=A7=20chore:=20=E5=9B=BA?= =?UTF-8?q?=E5=AE=9A=E6=B5=8B=E8=AF=95=E7=8E=AF=E5=A2=83=E5=89=8D=E7=AB=AF?= =?UTF-8?q?=E6=9E=84=E5=BB=BA=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 将测试前端固定到已推送的表格交互与查件记录提交 * 记录构建来源,保持版本文件与测试镜像一致 --- FRONTEND_2026_REVISION | 2 +- UPGRADE.md | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/FRONTEND_2026_REVISION b/FRONTEND_2026_REVISION index e038fc4..399a223 100644 --- a/FRONTEND_2026_REVISION +++ b/FRONTEND_2026_REVISION @@ -1 +1 @@ -272741ee49671327964e82c3cb0dec0a81e8261d +4fefcd0f0a82a5f1c0d293e9935f6b1e23a38658 diff --git a/UPGRADE.md b/UPGRADE.md index 2f89f99..1f828ee 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -224,3 +224,5 @@ WebDAV 保持 legacy 路径。新模式仍支持重试、续传、取消、配 浏览器三处表格拖拽、窄屏、快速展开收起通过;筛选收起末段最大帧间变化 0.31px。 - 部署流程:必须先提交并推送前后端代码,再由已推送提交打包构建测试镜像; 不再使用未提交的工作区部署。生产升级仍需用户验收后明确授权。 +- 本轮前端构建固定为已推送的 `4fefcd0f0a82a5f1c0d293e9935f6b1e23a38658`, + `FRONTEND_2026_REVISION` 与测试镜像的来源清单保持一致。 From 9d2ef0c34b1d18e53df322afe2f1e10296e7f047 Mon Sep 17 00:00:00 2001 From: Orion Date: Sat, 19 Sep 2026 00:54:26 +0800 Subject: [PATCH 11/12] =?UTF-8?q?=F0=9F=94=A7=20chore:=20=E5=9B=BA?= =?UTF-8?q?=E5=AE=9A=E5=88=B7=E6=96=B0=E6=8C=89=E9=92=AE=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E7=9A=84=E6=B5=8B=E8=AF=95=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 固定已推送的仪表盘刷新按钮修复提交 * 记录样式及刷新验证结果,并保持生产部署暂停 --- FRONTEND_2026_REVISION | 2 +- UPGRADE.md | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/FRONTEND_2026_REVISION b/FRONTEND_2026_REVISION index 399a223..de42a22 100644 --- a/FRONTEND_2026_REVISION +++ b/FRONTEND_2026_REVISION @@ -1 +1 @@ -4fefcd0f0a82a5f1c0d293e9935f6b1e23a38658 +fe6d81285744937e201d0452d6324533b58cc422 diff --git a/UPGRADE.md b/UPGRADE.md index 1f828ee..0d8ee81 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -226,3 +226,10 @@ WebDAV 保持 legacy 路径。新模式仍支持重试、续传、取消、配 不再使用未提交的工作区部署。生产升级仍需用户验收后明确授权。 - 本轮前端构建固定为已推送的 `4fefcd0f0a82a5f1c0d293e9935f6b1e23a38658`, `FRONTEND_2026_REVISION` 与测试镜像的来源清单保持一致。 + +## 测试版:仪表盘刷新按钮(2026-09-19) + +- 生产部署暂停,先修复刷新按钮误用纯图标样式导致的留白与间距缺失。 +- 前端固定到已推送提交 `fe6d81285744937e201d0452d6324533b58cc422`;后端运行逻辑保持不变。 +- 前端 72 项单元/集成及覆盖率检查通过,类型、架构与构建通过;浏览器验证 + 深浅主题和 1440/640/390px 下的按钮留白、加载居中与实际刷新请求。 From 8af45a70f61e1e7ed7da2bf7a5914fca7b64d32c Mon Sep 17 00:00:00 2001 From: Orion Date: Sat, 19 Sep 2026 01:24:17 +0800 Subject: [PATCH 12/12] =?UTF-8?q?=E2=9C=A8=20feat:=20=E9=BB=98=E8=AE=A4?= =?UTF-8?q?=E5=85=B3=E9=97=AD=E8=87=AA=E5=8A=A8=E6=A3=80=E6=B5=8B=E5=B9=B6?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=85=A8=E9=87=8F=E6=96=87=E4=BB=B6=E6=9E=9A?= =?UTF-8?q?=E4=B8=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 默认仅手动检测下载状态,减少非主动的网盘读取请求 * 提供管理员全量文件 ID 快照,排除回收文件且不读取存储 * 验证枚举鉴权、跨分页范围及检测不产生取件副作用 * 明确先验证测试分支,再合并正式分支构建生产版本 --- UPGRADE.md | 12 ++++++++++++ apps/admin/views.py | 6 ++++++ core/settings.py | 2 +- tests/test_download_checks.py | 14 ++++++++++++++ 4 files changed, 33 insertions(+), 1 deletion(-) diff --git a/UPGRADE.md b/UPGRADE.md index 0d8ee81..9170fe6 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -233,3 +233,15 @@ WebDAV 保持 legacy 路径。新模式仍支持重试、续传、取消、配 - 前端固定到已推送提交 `fe6d81285744937e201d0452d6324533b58cc422`;后端运行逻辑保持不变。 - 前端 72 项单元/集成及覆盖率检查通过,类型、架构与构建通过;浏览器验证 深浅主题和 1440/640/390px 下的按钮留白、加载居中与实际刷新请求。 + +## 手动检测下载状态与正式分支发布(2026-09-19) + +- 默认 downloadCheckInterval=0;生产配置已关闭定时检测。取消页面加载、翻页、 + 搜索和列表刷新触发文件读取,只有显式检测按钮才开始任务。 +- 提供单文件、选中多个及全量检测;全量 ID 通过管理员接口快照枚举所有未回收文件, + 不受当前列表筛选或分页限制。前端逐个请求,显示进度,取消停止后续请求。 +- 本地后端 172 项通过、2 项旧主题测试待镜像内验证,覆盖率 62%;前端 75 项通过。 + 浏览器以 25 文件受控响应验证跨页全量、单个、勾选、取消和默认零检测请求。 +- 发布顺序:测试分支提交推送 → 构建并部署测试 → 验证 → 合并前端 main、后端 master + → 推送正式分支 → 从正式提交重新构建生产镜像 → 备份、部署及生产回归。 + 正式构建使用 Dockerfile.release,固定前端提交;不再把测试镜像改标签作为生产发布。 diff --git a/apps/admin/views.py b/apps/admin/views.py index 0e28b85..0eda804 100644 --- a/apps/admin/views.py +++ b/apps/admin/views.py @@ -951,3 +951,9 @@ async def update_file( 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) diff --git a/core/settings.py b/core/settings.py index 156d77e..9248121 100644 --- a/core/settings.py +++ b/core/settings.py @@ -55,7 +55,7 @@ DEFAULT_CONFIG = { "uploadMinute": 1, "enableChunk": 0, "chunkSizeMB": 90, - "downloadCheckInterval": 300, + "downloadCheckInterval": 0, "webdav_url": "", "webdav_password": "", "webdav_username": "", diff --git a/tests/test_download_checks.py b/tests/test_download_checks.py index 4f0d17f..66d680c 100644 --- a/tests/test_download_checks.py +++ b/tests/test_download_checks.py @@ -188,3 +188,17 @@ class DownloadCheckTests(unittest.IsolatedAsyncioTestCase): 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)