⚡ fix(webdav): 改用独立分片流式合并并隔离测试协议
This commit is contained in:
1 parent
9a489297f4
commit
90089f793e
7 files changed
+255
-64
No files matched your search
+36
-52
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user