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

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

+184 -40
View File
@@ -19,7 +19,7 @@ from core.config import refresh_settings
from core.security import INTERNAL_CONFIG_KEYS, generate_jwt_secret
from apps.base.models import FileCodes, KeyValue, TransferStats, file_codes_pydantic
from apps.base.utils import get_expire_info, get_file_path_name
from apps.base.utils import get_expire_info, get_file_path_name, get_random_code
from apps.base.quota import release_storage, reserve_storage
from fastapi import HTTPException
from core.settings import data_root
@@ -36,7 +36,7 @@ class FileService:
MAX_VIEW_PRESETS = 24
MAX_VIEW_PRESET_NAME_LENGTH = 32
MAX_VIEW_PRESET_KEYWORD_LENGTH = 80
MAX_ADMIN_ACTIVITIES = 80
MAX_ADMIN_ACTIVITIES = 5000
MAX_ADMIN_ACTIVITY_TEXT_LENGTH = 120
POLICY_ACTIONS = {
@@ -80,6 +80,9 @@ class FileService:
"code",
}
TRASH_DEFAULT_RETENTION_DAYS = 7
TRASH_MAX_RETENTION_DAYS = 365
def __init__(self):
self._file_storage: Optional[FileStorageInterface] = None
@@ -105,38 +108,169 @@ class FileService:
return deduped
async def _delete_file_code(self, file_code: FileCodes):
try:
name = (
f"{file_code.prefix or ''}{file_code.suffix or ''}"
or file_code.uuid_file_name
or file_code.code
)
await TransferStats.create(
action="delete",
file_code_id=file_code.id,
code=file_code.code,
name=name,
size=int(file_code.size or 0),
ip="admin-delete",
file_path=file_code.file_path or "",
expired_at=file_code.expired_at,
deleted_at=datetime.now(),
meta=json.dumps(
{
"prefix": file_code.prefix or "",
"suffix": file_code.suffix or "",
"uuid_file_name": file_code.uuid_file_name or "",
"created_at": str(file_code.created_at),
},
ensure_ascii=False,
),
)
except Exception:
pass
await self.move_to_trash(file_code, reason="manual")
@staticmethod
def _trash_path(file_code: FileCodes) -> str:
filename = file_code.uuid_file_name or f"{file_code.prefix}{file_code.suffix}"
return f"trash/{file_code.id}/{filename}"
@classmethod
def _trash_expiry(cls, now: datetime, retention_days: Optional[int]):
if retention_days is None:
retention_days = cls.TRASH_DEFAULT_RETENTION_DAYS
if retention_days == 0:
return None
if not 1 <= retention_days <= cls.TRASH_MAX_RETENTION_DAYS:
raise HTTPException(status_code=400, detail="回收站保留期限必须为 1 到 365 天,或设为永久")
return now + timedelta(days=retention_days)
async def move_to_trash(
self,
file_code: FileCodes,
reason: str,
retention_days: Optional[int] = None,
) -> FileCodes:
if file_code.is_trashed:
return file_code
now = await get_now()
original_path = await file_code.get_file_path() if file_code.text is None else ""
if file_code.text is None:
await self.file_storage.delete_file(file_code)
await KeyValue.filter(key=self._file_metadata_key(file_code.id)).delete()
await file_code.delete()
await self.file_storage.move_file(file_code, self._trash_path(file_code))
await file_code.update_from_dict(
{
"is_trashed": True,
"trashed_at": now,
"trash_expires_at": self._trash_expiry(now, retention_days),
"trash_reason": reason,
"trash_original_path": original_path,
}
).save()
await TransferStats.create(
action="trash",
file_code_id=file_code.id,
code=file_code.code,
name=f"{file_code.prefix or ''}{file_code.suffix or ''}" or file_code.code,
size=int(file_code.size or 0),
ip=f"system-{reason}",
file_path=original_path,
expired_at=file_code.expired_at,
deleted_at=now,
meta=json.dumps({"reason": reason, "trash_path": self._trash_path(file_code)}, ensure_ascii=False),
)
return file_code
async def restore_from_trash(self, file_id: int) -> FileCodes:
file_code = await FileCodes.filter(id=file_id, is_trashed=True).first()
if not file_code:
raise HTTPException(status_code=404, detail="回收站文件不存在")
if file_code.trash_purged_at is not None:
raise HTTPException(status_code=409, detail="文件本体已永久清理,仅保留审计记录")
original_path = file_code.trash_original_path or ""
if file_code.text is None:
if not original_path:
raise HTTPException(status_code=409, detail="缺少原始文件路径,无法恢复")
destination_dir, filename = os.path.split(original_path)
if filename != (file_code.uuid_file_name or filename):
raise HTTPException(status_code=409, detail="回收站文件名不一致,无法恢复")
await self.file_storage.move_file(
FileCodes(file_path=os.path.dirname(self._trash_path(file_code)), uuid_file_name=os.path.basename(self._trash_path(file_code))),
original_path,
)
file_code.file_path = destination_dir
file_code.code = await get_random_code()
file_code.is_trashed = False
file_code.trashed_at = None
file_code.trash_expires_at = None
file_code.trash_reason = None
file_code.trash_original_path = None
file_code.trash_purged_at = None
await file_code.save()
await TransferStats.create(
action="restore",
file_code_id=file_code.id,
code=file_code.code,
name=f"{file_code.prefix or ''}{file_code.suffix or ''}" or file_code.code,
size=int(file_code.size or 0),
ip="admin-restore",
file_path=file_code.file_path or "",
expired_at=file_code.expired_at,
meta=json.dumps({"new_code": file_code.code}, ensure_ascii=False),
)
await self.record_admin_activity(
action="trash.restore",
target_type="file",
target_id=file_code.id,
target_name=self._build_file_activity_name(file_code),
meta={"newCode": file_code.code},
)
return file_code
async def purge_trashed_file(self, file_code: FileCodes) -> None:
if file_code.trash_purged_at is not None:
return
if file_code.text is None:
trash_path = self._trash_path(file_code)
await self.file_storage.delete_file(
FileCodes(
file_path=os.path.dirname(trash_path),
uuid_file_name=os.path.basename(trash_path),
)
)
purged_at = await get_now()
file_code.trash_purged_at = purged_at
file_code.trash_expires_at = None
await file_code.save(update_fields=["trash_purged_at", "trash_expires_at"])
await TransferStats.create(
action="purge",
file_code_id=file_code.id,
code=file_code.code,
name=f"{file_code.prefix or ''}{file_code.suffix or ''}" or file_code.code,
size=int(file_code.size or 0),
ip="system-purge",
file_path=file_code.trash_original_path or "",
expired_at=file_code.expired_at,
deleted_at=purged_at,
meta=json.dumps({"reason": "trash_purge"}, ensure_ascii=False),
)
await self.record_admin_activity(
action="trash.purge",
target_type="file",
target_id=file_code.id,
target_name=self._build_file_activity_name(file_code),
meta={"auditOnly": True},
)
async def list_trash(self, page: int, size: int) -> dict[str, Any]:
page = max(page, 1)
size = min(max(size, 1), 100)
query = FileCodes.filter(is_trashed=True).order_by("-trashed_at", "-id")
total = await query.count()
files = await query.offset((page - 1) * size).limit(size)
now = await get_now()
items = []
for file_code in files:
item = await self._build_admin_file_item(file_code, now=now)
item.update(
{
"trashedAt": file_code.trashed_at,
"trashExpiresAt": file_code.trash_expires_at,
"trashReason": file_code.trash_reason,
"trashPurgedAt": file_code.trash_purged_at,
"isTrashPermanent": file_code.trash_expires_at is None and file_code.trash_purged_at is None,
"isTrashPurged": file_code.trash_purged_at is not None,
}
)
items.append(item)
return {"page": page, "size": size, "total": total, "data": items}
async def set_trash_retention(self, file_id: int, retention_days: int) -> FileCodes:
file_code = await FileCodes.filter(id=file_id, is_trashed=True).first()
if not file_code:
raise HTTPException(status_code=404, detail="回收站文件不存在")
file_code.trash_expires_at = self._trash_expiry(await get_now(), retention_days)
await file_code.save(update_fields=["trash_expires_at"])
return file_code
async def delete_file(self, file_id: int):
file_code = await FileCodes.get(id=file_id)
@@ -504,7 +638,7 @@ class FileService:
sort_by = self._normalize_sort_by(sort_by)
reverse = sort_order.strip().lower() != "asc"
all_files = await FileCodes.all()
all_files = await FileCodes.filter(is_trashed=False).all()
now = await get_now()
enriched_files = []
summary = {
@@ -800,16 +934,24 @@ class FileService:
async def list_admin_activities(
self,
limit: int = 8,
page: int = 1,
size: int = 20,
limit: Optional[int] = None,
action: Optional[str] = None,
target_type: Optional[str] = None,
keyword: Optional[str] = None,
) -> dict[str, Any]:
if limit is not None:
size = limit
try:
normalized_limit = int(limit or 8)
page = max(int(page or 1), 1)
except (TypeError, ValueError):
normalized_limit = 8
limit = min(max(normalized_limit, 1), self.MAX_ADMIN_ACTIVITIES)
page = 1
try:
size = int(size or 20)
except (TypeError, ValueError):
size = 20
size = min(max(size, 1), 100)
activities = await self._get_admin_activities()
normalized_action = self._normalize_admin_activity_text(action).lower()
normalized_target_type = self._normalize_admin_activity_text(target_type).lower()
@@ -820,16 +962,18 @@ class FileService:
target_type=normalized_target_type,
keyword=normalized_keyword,
)
visible_activities = filtered_activities[:limit]
offset = (page - 1) * size
visible_activities = filtered_activities[offset : offset + size]
action_options = self._build_admin_activity_options(activities, "action")
target_type_options = self._build_admin_activity_options(activities, "targetType")
return {
"activities": visible_activities,
"items": visible_activities,
"page": page,
"size": size,
"total": len(filtered_activities),
"storedTotal": len(activities),
"stored_total": len(activities),
"limit": limit,
"filters": {
"action": normalized_action,
"targetType": normalized_target_type,