🐛 修复后端回收站部署内容
This commit is contained in:
1 parent
8badb80600
commit
dddca40df8
22 files changed
+986
-124
No files matched your search
+78
-93
@@ -25,7 +25,6 @@ from core.settings import data_root, settings
|
||||
from apps.base.models import FileCodes, UploadChunk
|
||||
from core.utils import get_file_url, sanitize_filename
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
|
||||
class FileStorageInterface:
|
||||
@@ -116,17 +115,6 @@ class SystemFileStorage(FileStorageInterface):
|
||||
self.chunk_size = 256 * 1024
|
||||
self.root_path = data_root
|
||||
|
||||
def _resolve_safe_path(self, relative_path: str) -> Path:
|
||||
"""将相对路径解析到数据根目录内,阻止路径穿越。"""
|
||||
root = self.root_path.resolve()
|
||||
raw = str(relative_path or "").replace("\\", "/").lstrip("/")
|
||||
candidate = (root / raw).resolve()
|
||||
try:
|
||||
candidate.relative_to(root)
|
||||
except ValueError as exc:
|
||||
raise ValueError("非法文件路径") from exc
|
||||
return candidate
|
||||
|
||||
def _save(self, file, save_path):
|
||||
with open(save_path, "wb") as f:
|
||||
chunk = file.read(self.chunk_size)
|
||||
@@ -135,19 +123,19 @@ class SystemFileStorage(FileStorageInterface):
|
||||
chunk = file.read(self.chunk_size)
|
||||
|
||||
async def save_file(self, file: UploadFile, save_path: str):
|
||||
path_obj = Path(str(save_path).replace("\\", "/"))
|
||||
directory = str(path_obj.parent).replace("\\", "/").lstrip("/")
|
||||
path_obj = Path(save_path)
|
||||
directory = str(path_obj.parent)
|
||||
# 提取原始文件名并进行清理
|
||||
filename = await sanitize_filename(path_obj.name)
|
||||
# 构建安全的完整保存路径
|
||||
safe_save_path = self._resolve_safe_path(f"{directory}/{filename}" if directory not in {"", "."} else filename)
|
||||
safe_save_path = self.root_path / directory / filename
|
||||
# 确保目录存在
|
||||
if not safe_save_path.parent.exists():
|
||||
safe_save_path.parent.mkdir(parents=True)
|
||||
await asyncio.to_thread(self._save, file.file, safe_save_path)
|
||||
|
||||
async def delete_file(self, file_code: FileCodes):
|
||||
save_path = self._resolve_safe_path(await file_code.get_file_path())
|
||||
save_path = self.root_path / await file_code.get_file_path()
|
||||
if save_path.exists():
|
||||
save_path.unlink()
|
||||
|
||||
@@ -163,7 +151,7 @@ class SystemFileStorage(FileStorageInterface):
|
||||
return await get_file_url(file_code.code)
|
||||
|
||||
async def get_file_response(self, file_code: FileCodes):
|
||||
file_path = self._resolve_safe_path(await file_code.get_file_path())
|
||||
file_path = self.root_path / await file_code.get_file_path()
|
||||
if not file_path.exists():
|
||||
return APIResponse(code=404, detail="文件已过期删除")
|
||||
filename = f"{file_code.prefix}{file_code.suffix}"
|
||||
@@ -195,11 +183,8 @@ class SystemFileStorage(FileStorageInterface):
|
||||
:param chunk_hash: 分片哈希值
|
||||
:param save_path: 文件保存路径
|
||||
"""
|
||||
# 先校验目标文件路径合法,再将分片落到同级 chunks 目录。
|
||||
self._resolve_safe_path(save_path)
|
||||
chunk_path = self._resolve_safe_path(
|
||||
str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part")
|
||||
)
|
||||
chunk_dir = self.root_path / save_path
|
||||
chunk_path = chunk_dir.parent / 'chunks' / upload_id / f"{chunk_index}.part"
|
||||
if not chunk_path.parent.exists():
|
||||
chunk_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# 使用临时文件写入,确保原子性
|
||||
@@ -222,11 +207,9 @@ class SystemFileStorage(FileStorageInterface):
|
||||
:param save_path: 文件保存路径
|
||||
:return: (文件路径, 文件哈希值)
|
||||
"""
|
||||
output_path = self._resolve_safe_path(save_path)
|
||||
output_path = self.root_path / save_path
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
chunk_base_dir = self._resolve_safe_path(
|
||||
str(Path(save_path).parent / "chunks" / upload_id)
|
||||
)
|
||||
chunk_base_dir = output_path.parent / 'chunks' / upload_id
|
||||
file_sha256 = hashlib.sha256()
|
||||
|
||||
# 使用临时文件写入,确保原子性
|
||||
@@ -262,9 +245,7 @@ class SystemFileStorage(FileStorageInterface):
|
||||
:param upload_id: 上传会话ID
|
||||
:param save_path: 文件保存路径
|
||||
"""
|
||||
chunk_dir = self._resolve_safe_path(
|
||||
str(Path(save_path).parent / "chunks" / upload_id)
|
||||
)
|
||||
chunk_dir = (self.root_path / save_path).parent / 'chunks' / upload_id
|
||||
if chunk_dir.exists():
|
||||
try:
|
||||
shutil.rmtree(chunk_dir)
|
||||
@@ -284,10 +265,7 @@ class SystemFileStorage(FileStorageInterface):
|
||||
:param save_path: 文件路径
|
||||
:return: 文件是否存在
|
||||
"""
|
||||
try:
|
||||
file_path = self._resolve_safe_path(save_path)
|
||||
except ValueError:
|
||||
return False
|
||||
file_path = self.root_path / save_path
|
||||
return file_path.exists()
|
||||
|
||||
|
||||
@@ -301,7 +279,6 @@ class S3FileStorage(FileStorageInterface):
|
||||
self.signature_version = settings.s3_signature_version
|
||||
self.endpoint_url = settings.s3_endpoint_url or f"https://{self.s3_hostname}"
|
||||
self.aws_session_token = settings.aws_session_token
|
||||
self.addressing_style = str(settings.s3_addressing_style or "auto").lower()
|
||||
self.proxy = settings.s3_proxy
|
||||
self.session = aioboto3.Session(
|
||||
aws_access_key_id=self.access_key_id,
|
||||
@@ -313,26 +290,14 @@ class S3FileStorage(FileStorageInterface):
|
||||
# 如果提供了 s3_endpoint_url,则优先使用它
|
||||
self.endpoint_url = settings.s3_endpoint_url
|
||||
|
||||
def _client_config(self) -> Config:
|
||||
config = {"signature_version": self.signature_version}
|
||||
s3_config = {}
|
||||
if self.addressing_style in {"path", "virtual", "auto"}:
|
||||
s3_config["addressing_style"] = self.addressing_style
|
||||
if s3_config:
|
||||
config["s3"] = s3_config
|
||||
return Config(**config)
|
||||
|
||||
def _client(self):
|
||||
return self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=self._client_config(),
|
||||
)
|
||||
|
||||
async def save_file(self, file: UploadFile, save_path: str):
|
||||
async with self._client() as s3:
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
# 使用 upload_fileobj 流式上传,避免将整个文件加载到内存
|
||||
await s3.upload_fileobj(
|
||||
file.file,
|
||||
@@ -342,7 +307,12 @@ class S3FileStorage(FileStorageInterface):
|
||||
)
|
||||
|
||||
async def delete_file(self, file_code: FileCodes):
|
||||
async with self._client() as s3:
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
await s3.delete_object(
|
||||
Bucket=self.bucket_name, Key=await file_code.get_file_path()
|
||||
)
|
||||
@@ -352,7 +322,12 @@ class S3FileStorage(FileStorageInterface):
|
||||
filename = file_code.prefix + file_code.suffix
|
||||
content_length = None # 初始化为 None,表示未知大小
|
||||
|
||||
async with self._client() as s3:
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
# 尝试获取文件大小(HEAD请求)
|
||||
try:
|
||||
head_response = await s3.head_object(
|
||||
@@ -408,9 +383,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
return StreamingResponse(
|
||||
stream_generator(),
|
||||
media_type="application/octet-stream",
|
||||
headers=headers,
|
||||
# 兜底关闭会话:客户端中断时与 generator finally 双保险
|
||||
background=BackgroundTask(session.close),
|
||||
headers=headers
|
||||
)
|
||||
except HTTPException:
|
||||
raise
|
||||
@@ -423,7 +396,12 @@ class S3FileStorage(FileStorageInterface):
|
||||
if self.proxy:
|
||||
return await get_file_url(file_code.code)
|
||||
else:
|
||||
async with self._client() as s3:
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
result = await s3.generate_presigned_url(
|
||||
"get_object",
|
||||
Params={
|
||||
@@ -440,7 +418,13 @@ class S3FileStorage(FileStorageInterface):
|
||||
注意:这里不使用 S3 原生的 multipart upload,而是将每个分片作为独立对象存储
|
||||
"""
|
||||
chunk_key = str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part")
|
||||
async with self._client() as s3:
|
||||
async with self.session.client(
|
||||
's3',
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
# 将分片作为独立对象上传
|
||||
await s3.put_object(
|
||||
Bucket=self.bucket_name,
|
||||
@@ -460,7 +444,13 @@ class S3FileStorage(FileStorageInterface):
|
||||
file_sha256 = hashlib.sha256()
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
|
||||
async with self._client() as s3:
|
||||
async with self.session.client(
|
||||
's3',
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
# 创建 multipart upload
|
||||
mpu = await s3.create_multipart_upload(
|
||||
Bucket=self.bucket_name,
|
||||
@@ -534,7 +524,13 @@ class S3FileStorage(FileStorageInterface):
|
||||
:param save_path: 文件保存路径
|
||||
"""
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
async with self._client() as s3:
|
||||
async with self.session.client(
|
||||
's3',
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
try:
|
||||
# 列出并删除所有分片对象
|
||||
paginator = s3.get_paginator('list_objects_v2')
|
||||
@@ -556,7 +552,13 @@ class S3FileStorage(FileStorageInterface):
|
||||
:param expires_in: URL过期时间(秒),默认15分钟
|
||||
:return: 预签名PUT URL
|
||||
"""
|
||||
async with self._client() as s3:
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
return await s3.generate_presigned_url(
|
||||
"put_object",
|
||||
Params={
|
||||
@@ -572,31 +574,18 @@ class S3FileStorage(FileStorageInterface):
|
||||
:param save_path: 文件路径
|
||||
:return: 文件是否存在
|
||||
"""
|
||||
async with self._client() as s3:
|
||||
last_error = None
|
||||
for attempt in range(3):
|
||||
try:
|
||||
await s3.head_object(Bucket=self.bucket_name, Key=save_path)
|
||||
return True
|
||||
except Exception as e:
|
||||
last_error = e
|
||||
if attempt < 2:
|
||||
await asyncio.sleep(0.2 * (attempt + 1))
|
||||
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
try:
|
||||
result = await s3.list_objects_v2(
|
||||
Bucket=self.bucket_name,
|
||||
Prefix=save_path,
|
||||
MaxKeys=1,
|
||||
)
|
||||
for item in result.get("Contents", []):
|
||||
if item.get("Key") == save_path:
|
||||
return True
|
||||
except Exception as e:
|
||||
last_error = e
|
||||
|
||||
logger.warning(f"S3文件确认失败 key={save_path}: {last_error}")
|
||||
return False
|
||||
await s3.head_object(Bucket=self.bucket_name, Key=save_path)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
class OneDriveFileStorage(FileStorageInterface):
|
||||
@@ -748,9 +737,7 @@ class OneDriveFileStorage(FileStorageInterface):
|
||||
return StreamingResponse(
|
||||
stream_generator(),
|
||||
media_type="application/octet-stream",
|
||||
headers=headers,
|
||||
# 兜底关闭会话:客户端中断时与 generator finally 双保险
|
||||
background=BackgroundTask(session.close),
|
||||
headers=headers
|
||||
)
|
||||
except HTTPException:
|
||||
raise
|
||||
@@ -1243,9 +1230,7 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
return StreamingResponse(
|
||||
stream_generator(),
|
||||
media_type="application/octet-stream",
|
||||
headers=headers,
|
||||
# 兜底关闭会话:客户端中断时与 generator finally 双保险
|
||||
background=BackgroundTask(session.close),
|
||||
headers=headers
|
||||
)
|
||||
except aiohttp.ClientError as e:
|
||||
raise HTTPException(
|
||||
|
||||
Reference in new issue
Block a user