✨ feat(backend): 完善上传取消与历史文件生命周期状态
This commit is contained in:
1 parent
dd905c5c90
commit
dfb392545a
7 files changed
+203
-25
No files matched your search
+23
-5
@@ -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)
|
||||
|
||||
+72
-18
@@ -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":"上传已取消"})
|
||||
Reference in new issue
Block a user