✨ 新增回收站审计与八位取件码
This commit is contained in:
1 parent
c25c495657
commit
4ee06e2d29
15 files changed
+534
-132
No files matched your search
@@ -73,6 +73,9 @@ COPY --from=frontend-builder /build/fronted-2024/dist ./themes/2024
|
||||
COPY --from=frontend-builder /build/fronted-2026/dist ./themes/2026
|
||||
COPY --from=frontend-builder /build/fronted-2023/dist ./themes/2023
|
||||
|
||||
# 应用管理后台详情页取件记录展开/收起、复制回退与悬停边框补丁
|
||||
RUN python scripts/patch_admin_timeline_ui.py
|
||||
|
||||
# 安装系统安全更新 + Python 依赖
|
||||
RUN apt-get update \
|
||||
&& apt-get upgrade -y --no-install-recommends \
|
||||
|
||||
@@ -57,6 +57,11 @@ class BatchFilePolicyActionData(BaseModel):
|
||||
download_limit: Optional[int] = None
|
||||
|
||||
|
||||
class TrashRetentionData(BaseModel):
|
||||
id: int
|
||||
retentionDays: int
|
||||
|
||||
|
||||
class FileMetadataData(BaseModel):
|
||||
id: int
|
||||
note: Optional[str] = None
|
||||
|
||||
+184
-40
@@ -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,
|
||||
|
||||
+46
-2
@@ -21,6 +21,7 @@ from apps.admin.schemas import (
|
||||
BatchUpdateFileData,
|
||||
BatchFilePolicyActionData,
|
||||
FilePolicyActionData,
|
||||
TrashRetentionData,
|
||||
FileMetadataData,
|
||||
FileViewPresetData,
|
||||
FileViewPresetDeleteData,
|
||||
@@ -104,7 +105,7 @@ async def build_dashboard_recent_file(file_code: FileCodes) -> dict:
|
||||
|
||||
@admin_api.get("/dashboard")
|
||||
async def dashboard(file_service: FileService = Depends(get_file_service)):
|
||||
all_codes = await FileCodes.all()
|
||||
all_codes = await FileCodes.filter(is_trashed=False).all()
|
||||
all_size = sum([code.size for code in all_codes])
|
||||
sys_start = await KeyValue.filter(key="sys_start").first()
|
||||
now = await get_now()
|
||||
@@ -176,7 +177,9 @@ async def dashboard(file_service: FileService = Depends(get_file_service)):
|
||||
|
||||
@admin_api.get("/activities")
|
||||
async def admin_activities(
|
||||
limit: int = 20,
|
||||
page: int = 1,
|
||||
size: int = 20,
|
||||
limit: Optional[int] = None,
|
||||
action: Optional[str] = None,
|
||||
targetType: Optional[str] = None,
|
||||
target_type: Optional[str] = None,
|
||||
@@ -184,6 +187,8 @@ async def admin_activities(
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
result = await file_service.list_admin_activities(
|
||||
page=page,
|
||||
size=size,
|
||||
limit=limit,
|
||||
action=action,
|
||||
target_type=_pick_query_text(targetType, target_type),
|
||||
@@ -450,6 +455,45 @@ async def file_batch_delete_post(
|
||||
return await batch_delete_files(data, file_service)
|
||||
|
||||
|
||||
@admin_api.get("/trash/list")
|
||||
async def trash_list(
|
||||
page: int = 1,
|
||||
size: int = 20,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return APIResponse(detail=await file_service.list_trash(page, size))
|
||||
|
||||
|
||||
@admin_api.post("/trash/restore")
|
||||
async def trash_restore(
|
||||
data: IDData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
file_code = await file_service.restore_from_trash(data.id)
|
||||
return APIResponse(detail=await file_service.get_file_detail(file_code.id))
|
||||
|
||||
|
||||
@admin_api.post("/trash/retention")
|
||||
async def trash_retention(
|
||||
data: TrashRetentionData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
file_code = await file_service.set_trash_retention(data.id, data.retentionDays)
|
||||
return APIResponse(detail={"id": file_code.id, "trashExpiresAt": file_code.trash_expires_at})
|
||||
|
||||
|
||||
@admin_api.delete("/trash/purge")
|
||||
async def trash_purge(
|
||||
data: IDData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
file_code = await FileCodes.filter(id=data.id, is_trashed=True).first()
|
||||
if not file_code:
|
||||
raise HTTPException(status_code=404, detail="回收站文件不存在")
|
||||
await file_service.purge_trashed_file(file_code)
|
||||
return APIResponse()
|
||||
|
||||
|
||||
async def batch_update_files(
|
||||
data: BatchUpdateFileData,
|
||||
file_service: FileService,
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
async def migrate():
|
||||
conn = connections.get("default")
|
||||
result = await conn.execute_query("PRAGMA table_info(filecodes)")
|
||||
columns = {row[1] for row in (result[1] if result and len(result) > 1 else [])}
|
||||
additions = [
|
||||
("is_trashed", "BOOLEAN NOT NULL DEFAULT 0"),
|
||||
("trashed_at", "TIMESTAMP NULL"),
|
||||
("trash_expires_at", "TIMESTAMP NULL"),
|
||||
("trash_reason", "VARCHAR(32) NULL"),
|
||||
("trash_original_path", "VARCHAR(1024) NULL"),
|
||||
("trash_purged_at", "TIMESTAMP NULL"),
|
||||
]
|
||||
for name, definition in additions:
|
||||
if name not in columns:
|
||||
await conn.execute_query(f"ALTER TABLE filecodes ADD COLUMN {name} {definition}")
|
||||
await conn.execute_script(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_filecodes_is_trashed ON filecodes(is_trashed);
|
||||
CREATE INDEX IF NOT EXISTS idx_filecodes_trash_expires_at ON filecodes(trash_expires_at);
|
||||
"""
|
||||
)
|
||||
@@ -28,6 +28,12 @@ class FileCodes(models.Model):
|
||||
file_hash = fields.CharField(max_length=64, null=True)
|
||||
is_chunked = fields.BooleanField(default=False)
|
||||
upload_id = fields.CharField(max_length=36, null=True)
|
||||
is_trashed = fields.BooleanField(default=False, index=True)
|
||||
trashed_at = fields.DatetimeField(null=True, index=True)
|
||||
trash_expires_at = fields.DatetimeField(null=True, index=True)
|
||||
trash_reason = fields.CharField(max_length=32, null=True)
|
||||
trash_original_path = fields.CharField(max_length=1024, null=True)
|
||||
trash_purged_at = fields.DatetimeField(null=True, index=True)
|
||||
|
||||
async def is_expired(self):
|
||||
if self.expired_at is None:
|
||||
|
||||
+10
-3
@@ -96,6 +96,11 @@ async def get_expire_info(
|
||||
return expired_at, expired_count, used_count, code
|
||||
|
||||
|
||||
CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
|
||||
CODE_LENGTH = 8
|
||||
CODE_MAX_ATTEMPTS = 50
|
||||
|
||||
|
||||
def get_code_generate_type() -> str:
|
||||
code_generate_type = getattr(settings, "code_generate_type", "secret")
|
||||
if code_generate_type in {"secret", "string"}:
|
||||
@@ -104,20 +109,22 @@ def get_code_generate_type() -> str:
|
||||
|
||||
|
||||
async def get_random_code(style: str | None = None) -> str:
|
||||
"""生成新的 8 位取件码,并避开所有仍保留的历史审计记录。"""
|
||||
code_style = style or get_code_generate_type()
|
||||
if code_style == "num":
|
||||
code_style = "number"
|
||||
if code_style == "string":
|
||||
code_style = "secret"
|
||||
|
||||
while True:
|
||||
for _ in range(CODE_MAX_ATTEMPTS):
|
||||
code = (
|
||||
await get_random_num()
|
||||
await get_random_num(CODE_LENGTH)
|
||||
if code_style == "number"
|
||||
else await get_random_string()
|
||||
else await get_random_string(CODE_LENGTH)
|
||||
)
|
||||
if not await FileCodes.filter(code=code).exists():
|
||||
return str(code)
|
||||
raise HTTPException(status_code=503, detail="取件码生成暂时繁忙,请重试")
|
||||
|
||||
|
||||
async def calculate_file_hash(file: UploadFile, chunk_size=1024 * 1024) -> str:
|
||||
|
||||
+1
-1
@@ -238,7 +238,7 @@ async def get_code_file_by_code(
|
||||
normalized_code = normalize_share_code(code)
|
||||
if not normalized_code:
|
||||
return False, "文件不存在"
|
||||
file_code = await FileCodes.filter(code=normalized_code).first()
|
||||
file_code = await FileCodes.filter(code=normalized_code, is_trashed=False).first()
|
||||
if not file_code:
|
||||
return False, "文件不存在"
|
||||
if await file_code.is_expired() and check:
|
||||
|
||||
@@ -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
@@ -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
@@ -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():
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
from pathlib import Path
|
||||
import gzip
|
||||
import re
|
||||
|
||||
ASSETS_ROOT = Path('/app')
|
||||
|
||||
@@ -39,28 +40,27 @@ def patch_file_manage(path: Path) -> bool:
|
||||
def patch_clipboard(path: Path) -> bool:
|
||||
text = path.read_text(encoding='utf-8')
|
||||
old = text
|
||||
marker = 'const y=async(a,e={})=>{'
|
||||
if marker not in text or 'fcbx-copy-fallback' in text:
|
||||
pattern = re.compile(
|
||||
r'const (?P<name>[A-Za-z_$][\w$]*)=async\(a,e=\{\}\)=>\{.*?\},'
|
||||
r'(?=[A-Za-z_$][\w$]*=async\(a,e=\{\}\)=>\{)',
|
||||
re.S,
|
||||
)
|
||||
match = pattern.search(text)
|
||||
if not match:
|
||||
return False
|
||||
start = text.index(marker)
|
||||
end_marker = '},T=async(a,e={})=>{'
|
||||
end = text.index(end_marker, start) + 1
|
||||
replacement = '''const y=async(a,e={})=>{const{successMsg:t="复制成功",errorMsg:n="复制失败,请手动复制",showMsg:s=!0,notify:c}=e,l=(r,d)=>{s&&c?.(r,d)},q=()=>{try{window.prompt("复制下面内容",a)}catch{}};try{if(navigator.clipboard&&window.isSecureContext)try{await navigator.clipboard.writeText(a);return l(t,"success"),!0}catch{}const r=document.createElement("textarea");r.value=a,r.setAttribute("readonly","");r.className="fcbx-copy-fallback";r.style.cssText="position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;z-index:-1";document.body.appendChild(r);r.focus();r.select();r.setSelectionRange(0,r.value.length);let d=!1;try{d=document.execCommand("copy")}finally{document.body.removeChild(r)}if(d)return l(t,"success"),!0;q();l("已打开手动复制窗口","warning");return!1}catch(r){return console.error("复制失败:",r),q(),l(n,"error"),!1}}'''
|
||||
text = text[:start] + replacement + text[end:]
|
||||
name = match.group('name')
|
||||
replacement = f'''const {name}=async(a,e={{}})=>{{const{{successMsg:t="复制成功",errorMsg:n="复制失败,请手动复制",showMsg:s=!0,notify:c}}=e,l=(r,d)=>{{s&&c?.(r,d)}},q=()=>{{try{{window.prompt("复制下面内容",a)}}catch{{}}}};try{{if(navigator.clipboard&&window.isSecureContext)try{{await navigator.clipboard.writeText(a);return l(t,"success"),!0}}catch{{}}const r=document.createElement("textarea");r.value=a,r.setAttribute("readonly","");r.className="fcbx-copy-fallback";r.style.cssText="position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;z-index:-1";document.body.appendChild(r);r.focus();r.select();r.setSelectionRange(0,r.value.length);let d=!1;try{{d=document.execCommand("copy")}}finally{{document.body.removeChild(r)}}if(d)return l(t,"success"),!0;q();l("已打开手动复制窗口","warning");return!1}}catch(r){{return console.error("复制失败:",r),q(),l(n,"error"),!1}}}}'''
|
||||
text = text[:match.start()] + replacement + text[match.end():]
|
||||
if text != old:
|
||||
rewrite(path, text)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def write_detail_collapse_script(theme_dir: Path) -> bool:
|
||||
assets = theme_dir / 'assets'
|
||||
index = theme_dir / 'index.html'
|
||||
if not assets.exists() or not index.exists():
|
||||
return False
|
||||
js_path = assets / 'fcb-lifecycle-collapse-v3.js'
|
||||
js = r'''(() => {
|
||||
def build_lifecycle_script() -> str:
|
||||
return r'''(() => {
|
||||
const LIFE_RE = /(生命周期|Lifecycle)/i;
|
||||
const RETRIEVAL_RE = /^(第\s*\d+\s*次取件|retrieval\s*#?\d+)/i;
|
||||
const STATE = new WeakMap();
|
||||
const getSection = section => {
|
||||
const title = section.querySelector('h1,h2,h3,h4,h5');
|
||||
@@ -72,70 +72,74 @@ def write_detail_collapse_script(theme_dir: Path) -> bool:
|
||||
const getRows = section => {
|
||||
const ctx = getSection(section);
|
||||
if (!ctx) return [];
|
||||
return [...ctx.box.children].filter(el => el instanceof HTMLElement);
|
||||
return [...ctx.box.querySelectorAll(':scope > .fcb-expand-content')];
|
||||
};
|
||||
const apply = section => {
|
||||
const ctx = getSection(section);
|
||||
if (!ctx) return;
|
||||
const rows = [...ctx.box.children].filter(el => el instanceof HTMLElement);
|
||||
if (rows.length <= 3) return;
|
||||
const rows = getRows(section);
|
||||
const events = rows.filter(row => RETRIEVAL_RE.test((row.querySelector('p')?.textContent || '').trim()));
|
||||
if (events.length <= 3) return;
|
||||
const expanded = STATE.get(section) === true;
|
||||
section.classList.toggle('fcbx-life-expanded', expanded);
|
||||
rows.forEach((row, idx) => {
|
||||
const shouldHide = idx >= 3 && !expanded;
|
||||
row.classList.toggle('fcbx-life-row-extra', idx >= 3);
|
||||
if (shouldHide) {
|
||||
if (row.style.display !== 'none') row.style.setProperty('display', 'none', 'important');
|
||||
} else if (row.style.display) {
|
||||
row.style.removeProperty('display');
|
||||
}
|
||||
events.forEach((row, idx) => {
|
||||
row.classList.add('fcbx-retrieval-event');
|
||||
row.style.display = expanded || idx < 3 ? '' : 'none';
|
||||
});
|
||||
const btn = section.querySelector(':scope > .fcbx-life-toggle') || section.querySelector('.fcbx-life-toggle');
|
||||
if (btn) {
|
||||
btn.textContent = expanded ? '收起生命周期记录' : `展开全部生命周期记录(共 ${rows.length} 条)`;
|
||||
btn.setAttribute('aria-expanded', expanded ? 'true' : 'false');
|
||||
}
|
||||
};
|
||||
const ensureSection = section => {
|
||||
const ctx = getSection(section);
|
||||
if (!ctx) return;
|
||||
const rows = [...ctx.box.children].filter(el => el instanceof HTMLElement);
|
||||
if (rows.length <= 3) return;
|
||||
if (!STATE.has(section)) STATE.set(section, false);
|
||||
let btn = section.querySelector(':scope > .fcbx-life-toggle');
|
||||
if (!btn) {
|
||||
btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'fcbx-life-toggle mt-3 rounded-lg border px-3 py-2 text-sm font-medium transition';
|
||||
btn.style.cssText = 'border-color:rgba(148,163,184,.55);display:inline-flex;align-items:center;gap:.35rem;touch-action:manipulation;user-select:none;cursor:pointer;';
|
||||
btn.onclick = event => {
|
||||
let button = section.querySelector(':scope > .fcbx-retrieval-toggle');
|
||||
if (!button) {
|
||||
button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'fcbx-retrieval-toggle';
|
||||
button.style.cssText = 'display:inline-flex;align-items:center;margin:0 0 12px 44px;padding:8px 12px;border:1px solid rgba(148,163,184,.55);border-radius:10px;background:transparent;cursor:pointer;touch-action:manipulation;';
|
||||
button.onclick = event => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
STATE.set(section, STATE.get(section) !== true);
|
||||
apply(section);
|
||||
};
|
||||
section.appendChild(btn);
|
||||
ctx.box.parentNode.insertBefore(button, ctx.box);
|
||||
}
|
||||
apply(section);
|
||||
button.textContent = expanded ? '收起取件记录' : `展开全部取件记录(共 ${events.length} 次)`;
|
||||
button.setAttribute('aria-expanded', expanded ? 'true' : 'false');
|
||||
};
|
||||
const markRows = root => {
|
||||
const scope = root?.querySelectorAll ? root : document;
|
||||
scope.querySelectorAll('section').forEach(ensureSection);
|
||||
scope.querySelectorAll('section').forEach(section => {
|
||||
const ctx = getSection(section);
|
||||
if (!ctx) return;
|
||||
ctx.box.style.overflow = 'visible';
|
||||
if (ctx.box.parentElement) ctx.box.parentElement.style.overflow = 'visible';
|
||||
getRows(section).forEach(row => {
|
||||
row.style.overflow = 'visible';
|
||||
row.style.position = 'relative';
|
||||
row.style.zIndex = '0';
|
||||
const card = row.lastElementChild;
|
||||
if (card) {
|
||||
card.style.overflow = 'visible';
|
||||
card.style.position = 'relative';
|
||||
}
|
||||
row.onmouseenter = () => { row.style.zIndex = '2'; };
|
||||
row.onmouseleave = () => { row.style.zIndex = '0'; };
|
||||
});
|
||||
apply(section);
|
||||
});
|
||||
};
|
||||
let raf = 0;
|
||||
const schedule = root => { cancelAnimationFrame(raf); raf = requestAnimationFrame(() => markRows(root)); };
|
||||
window.addEventListener('hashchange', () => schedule(document));
|
||||
document.addEventListener('DOMContentLoaded', () => schedule(document));
|
||||
new MutationObserver(records => {
|
||||
for (const rec of records) {
|
||||
if ([...rec.addedNodes].some(n => n.nodeType === 1 && ((n.matches?.('section')) || n.querySelector?.('section')))) {
|
||||
schedule(document);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}).observe(document.body || document.documentElement, { childList: true, subtree: true });
|
||||
new MutationObserver(() => schedule(document)).observe(document.body || document.documentElement, { childList: true, subtree: true });
|
||||
schedule(document);
|
||||
})();'''
|
||||
|
||||
|
||||
def write_detail_collapse_script(theme_dir: Path) -> bool:
|
||||
assets = theme_dir / 'assets'
|
||||
index = theme_dir / 'index.html'
|
||||
if not assets.exists() or not index.exists():
|
||||
return False
|
||||
js_path = assets / 'fcb-lifecycle-collapse-v3.js'
|
||||
js = build_lifecycle_script()
|
||||
rewrite(js_path, js)
|
||||
html = index.read_text(encoding='utf-8')
|
||||
# Remove old detail-collapse injection so browsers cannot keep loading the stale “取件记录” script.
|
||||
@@ -156,16 +160,14 @@ def write_detail_collapse_script(theme_dir: Path) -> bool:
|
||||
|
||||
def main() -> None:
|
||||
changed = []
|
||||
theme = ASSETS_ROOT / 'themes/2026'
|
||||
assets = theme / 'assets'
|
||||
if assets.exists():
|
||||
# 只用独立 DOM 脚本处理生命周期收起,避免再改编译后的 FileManageView,
|
||||
# 否则 Vue 内部状态和外部补丁会互相抢状态,导致展开/收起需要点多次。
|
||||
for path in assets.glob('clipboard-*.js'):
|
||||
if patch_clipboard(path):
|
||||
changed.append(str(path.relative_to(ASSETS_ROOT)))
|
||||
if write_detail_collapse_script(theme):
|
||||
changed.append(str((assets / 'fcb-lifecycle-collapse-v3.js').relative_to(ASSETS_ROOT)))
|
||||
for theme in (ASSETS_ROOT / 'themes/2024', ASSETS_ROOT / 'themes/2026'):
|
||||
assets = theme / 'assets'
|
||||
if assets.exists():
|
||||
for path in assets.glob('clipboard-*.js'):
|
||||
if patch_clipboard(path):
|
||||
changed.append(str(path.relative_to(ASSETS_ROOT)))
|
||||
if write_detail_collapse_script(theme):
|
||||
changed.append(str((assets / 'fcb-lifecycle-collapse-v3.js').relative_to(ASSETS_ROOT)))
|
||||
if not changed:
|
||||
raise SystemExit('admin timeline/clipboard patch markers not found or already patched')
|
||||
print('patched admin assets:', ', '.join(changed))
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
|
||||
from tortoise import Tortoise
|
||||
|
||||
from apps.admin.services import FileService
|
||||
|
||||
|
||||
class AdminActivityPaginationTests(unittest.TestCase):
|
||||
def test_activity_log_filters_and_paginates(self):
|
||||
asyncio.run(self.scenario())
|
||||
|
||||
async def scenario(self):
|
||||
await Tortoise.init(
|
||||
config={
|
||||
"connections": {"default": {"engine": "tortoise.backends.sqlite", "credentials": {"file_path": ":memory:"}}},
|
||||
"apps": {"models": {"models": ["apps.base.models"], "default_connection": "default"}},
|
||||
"use_tz": False,
|
||||
"timezone": "Asia/Shanghai",
|
||||
}
|
||||
)
|
||||
await Tortoise.generate_schemas()
|
||||
try:
|
||||
service = FileService()
|
||||
await service.record_admin_activity("file.update", "file", 1, "a.txt")
|
||||
await service.record_admin_activity("trash.purge", "file", 2, "b.txt")
|
||||
await service.record_admin_activity("config.update", "config", None, "system")
|
||||
|
||||
first = await service.list_admin_activities(page=1, size=2)
|
||||
self.assertEqual(first["page"], 1)
|
||||
self.assertEqual(first["size"], 2)
|
||||
self.assertEqual(first["total"], 3)
|
||||
self.assertEqual(len(first["items"]), 2)
|
||||
|
||||
filtered = await service.list_admin_activities(page=1, size=20, action="trash.purge")
|
||||
self.assertEqual(filtered["total"], 1)
|
||||
self.assertEqual(filtered["items"][0]["targetName"], "b.txt")
|
||||
finally:
|
||||
await Tortoise.close_connections()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,16 @@
|
||||
import unittest
|
||||
|
||||
from scripts.patch_admin_timeline_ui import build_lifecycle_script
|
||||
|
||||
|
||||
class AdminTimelinePatchTests(unittest.TestCase):
|
||||
def test_lifecycle_script_collapses_retrieval_events_and_preserves_hover_borders(self):
|
||||
script = build_lifecycle_script()
|
||||
|
||||
self.assertIn("fcbx-retrieval-event", script)
|
||||
self.assertIn("展开全部取件记录", script)
|
||||
self.assertIn("row.style.overflow = 'visible'", script)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,74 @@
|
||||
import asyncio
|
||||
import datetime
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from tortoise import Tortoise
|
||||
|
||||
from apps.base.models import FileCodes
|
||||
from apps.base.utils import CODE_LENGTH, get_random_code
|
||||
from apps.admin.services import FileService
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
class FakeStorage:
|
||||
moved = []
|
||||
deleted = []
|
||||
|
||||
async def move_file(self, file_code, target_path):
|
||||
self.moved.append((file_code.id, target_path))
|
||||
|
||||
async def delete_file(self, file_code):
|
||||
self.deleted.append((file_code.file_path, file_code.uuid_file_name))
|
||||
|
||||
|
||||
class RecycleBinTests(unittest.TestCase):
|
||||
def test_trash_restore_and_expiry_policy(self):
|
||||
asyncio.run(self.scenario())
|
||||
|
||||
async def scenario(self):
|
||||
await Tortoise.init(
|
||||
config={
|
||||
"connections": {"default": {"engine": "tortoise.backends.sqlite", "credentials": {"file_path": ":memory:"}}},
|
||||
"apps": {"models": {"models": ["apps.base.models"], "default_connection": "default"}},
|
||||
"use_tz": False,
|
||||
"timezone": "Asia/Shanghai",
|
||||
}
|
||||
)
|
||||
await Tortoise.generate_schemas()
|
||||
try:
|
||||
item = await FileCodes.create(code="old", prefix="demo", suffix=".txt", file_path="share/data/demo", uuid_file_name="demo.txt", expired_count=-1)
|
||||
service = FileService()
|
||||
service._file_storage = FakeStorage()
|
||||
trashed = await service.move_to_trash(item, reason="manual", retention_days=7)
|
||||
self.assertTrue(trashed.is_trashed)
|
||||
self.assertEqual(trashed.trash_reason, "manual")
|
||||
self.assertIsNotNone(trashed.trash_expires_at)
|
||||
self.assertTrue(FakeStorage.moved)
|
||||
|
||||
await service.purge_trashed_file(trashed)
|
||||
audit_record = await FileCodes.get(id=item.id)
|
||||
self.assertTrue(audit_record.is_trashed)
|
||||
self.assertIsNotNone(audit_record.trash_purged_at)
|
||||
self.assertTrue(FakeStorage.deleted)
|
||||
|
||||
with self.assertRaises(Exception):
|
||||
await service.restore_from_trash(item.id)
|
||||
|
||||
await FileCodes.create(code="RETIRED1", is_trashed=True, trash_purged_at=datetime.datetime.now())
|
||||
with patch("apps.base.utils.get_random_string", AsyncMock(side_effect=["RETIRED1", "FRESH002"])):
|
||||
self.assertEqual(await get_random_code(), "FRESH002")
|
||||
|
||||
generated_code = await get_random_code()
|
||||
self.assertEqual(len(generated_code), CODE_LENGTH)
|
||||
self.assertRegex(generated_code, rf"^[ABCDEFGHJKMNPQRSTUVWXYZ23456789]{{{CODE_LENGTH}}}$")
|
||||
|
||||
numeric_code = await get_random_code(style="number")
|
||||
self.assertEqual(len(numeric_code), 8)
|
||||
self.assertRegex(numeric_code, r"^[1-9][0-9]{7}$")
|
||||
finally:
|
||||
await Tortoise.close_connections()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user