✨ 新增回收站审计与八位取件码

This commit is contained in:
orion committed 2026-08-07 10:28:22 +08:00
1 parent c25c495657
commit 4ee06e2d29
15 files changed
+534 -132

No files matched your search

+29
View File
@@ -42,6 +42,10 @@ class FileStorageInterface:
"""
raise NotImplementedError
async def move_file(self, file_code: FileCodes, target_path: str) -> None:
"""将现有文件移动到目标路径,供回收站使用。"""
raise NotImplementedError
async def get_file_url(self, file_code: FileCodes):
"""
获取文件分享的url
@@ -147,6 +151,14 @@ class SystemFileStorage(FileStorageInterface):
if save_path.exists():
save_path.unlink()
async def move_file(self, file_code: FileCodes, target_path: str) -> None:
source_path = self._resolve_safe_path(await file_code.get_file_path())
destination_path = self._resolve_safe_path(target_path)
destination_path.parent.mkdir(parents=True, exist_ok=True)
if not source_path.exists():
raise FileNotFoundError("回收站源文件不存在")
await asyncio.to_thread(source_path.replace, destination_path)
async def get_file_url(self, file_code: FileCodes):
return await get_file_url(file_code.code)
@@ -1164,6 +1176,23 @@ class WebDAVFileStorage(FileStorageInterface):
raise HTTPException(
status_code=503, detail=f"WebDAV连接异常: {str(e)}")
async def move_file(self, file_code: FileCodes, target_path: str) -> None:
source_path = await file_code.get_file_path()
source_url = self._build_url(source_path)
target_url = self._build_url(target_path)
await self._mkdir_p(str(Path(target_path).parent))
try:
async with aiohttp.ClientSession(auth=self.auth) as session:
async with session.request("MOVE", source_url, headers={"Destination": target_url, "Overwrite": "F"}) as response:
if response.status not in (201, 204):
content = await response.text()
raise HTTPException(
status_code=response.status,
detail=f"WebDAV移动到回收站失败: {content[:200]}",
)
except aiohttp.ClientError as e:
raise HTTPException(status_code=503, detail=f"WebDAV连接异常: {str(e)}")
async def get_file_url(self, file_code: FileCodes):
return await get_file_url(file_code.code)
+14 -6
View File
@@ -15,6 +15,7 @@ from apps.base.models import (
StorageReservation,
UploadChunk,
)
from apps.admin.services import FileService
from apps.base.utils import ip_limit, get_chunk_file_path_name
from core.config import refresh_settings
from core.settings import settings, data_root
@@ -36,18 +37,25 @@ async def delete_expire_files():
await ip_limit["metadata"].remove_expired_ip()
await ip_limit["upload"].remove_expired_ip()
await StorageReservation.filter(expires_at__lte=await get_now()).delete()
file_service = FileService()
expire_data = await FileCodes.filter(
Q(expired_at__lt=await get_now()) | Q(expired_count=0)
).all()
is_trashed=False,
).filter(Q(expired_at__lt=await get_now()) | Q(expired_count=0)).all()
for exp in expire_data:
try:
await file_storage.delete_file(exp)
await file_service.move_to_trash(exp, reason="expired")
except Exception as e:
logging.error(f"删除过期文件失败 code={exp.code}: {e}")
logging.error(f"移入过期文件回收站失败 code={exp.code}: {e}")
expired_trash = await FileCodes.filter(
is_trashed=True,
trash_expires_at__isnull=False,
trash_expires_at__lte=await get_now(),
).all()
for item in expired_trash:
try:
await exp.delete()
await file_service.purge_trashed_file(item)
except Exception as e:
logging.error(f"删除记录失败 code={exp.code}: {e}")
logging.error(f"彻底清理回收站文件失败 id={item.id}: {e}")
except Exception as e:
logging.error(e)
finally:
+11 -14
View File
@@ -8,29 +8,26 @@ import hmac
import os
import re
import secrets
import string
import time
from core.settings import settings
async def get_random_num():
"""
获取随机数
:return:
"""
return secrets.randbelow(90000) + 10000
async def get_random_num(length: int = 8):
"""返回指定长度的纯数字取件码。"""
normalized_length = max(1, int(length or 8))
lower = 10 ** (normalized_length - 1)
return str(secrets.randbelow(9 * lower) + lower)
r_s = string.ascii_uppercase + string.digits
# 排除 0/O、1/I/L,避免人工输入取件码时混淆。
r_s = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
async def get_random_string():
"""
获取随机字符串
:return:
"""
return "".join(secrets.choice(r_s) for _ in range(5))
async def get_random_string(length: int = 8):
"""返回指定长度、无易混淆字符的取件码。"""
normalized_length = max(1, int(length or 8))
return "".join(secrets.choice(r_s) for _ in range(normalized_length))
async def get_now():