🔀 合并回收站与取件码升级到生产分支
Deploy VitePress site to Pages / build (push) Has been cancelled
Deploy VitePress site to Pages / Deploy (push) Has been cancelled
Create release / release-please (push) Has been cancelled
Build and push Docker image / buildx (push) Has been cancelled

This commit is contained in:
Orion committed 2026-08-07 11:02:00 +08:00
commit a9c280fde8
18 files changed
+638 -126

No files matched your search

+5 -1
View File
@@ -15,7 +15,8 @@ WORKDIR /build
# 克隆并构建 2024 主题 # 克隆并构建 2024 主题
ARG FRONTEND_2024_REPO=https://git.orionc.me/orion/FileCodeBoxFronted.git ARG FRONTEND_2024_REPO=https://git.orionc.me/orion/FileCodeBoxFronted.git
ARG FRONTEND_2024_BRANCH=main ARG FRONTEND_2024_BRANCH=main
ARG FRONTEND_CACHE_BUST=1 # 每次更新 2026 前端后,同步为测试分支已验证的提交,避免 Docker 复用过期的远端前端构建层。
ARG FRONTEND_CACHE_BUST=2bf610ac224202caa4278b9ec8699bc4514da842
RUN echo "$FRONTEND_CACHE_BUST" >/tmp/frontend-cache-bust && \ RUN echo "$FRONTEND_CACHE_BUST" >/tmp/frontend-cache-bust && \
git clone --filter=blob:none --no-checkout "$FRONTEND_2024_REPO" /build/fronted-2024 && \ git clone --filter=blob:none --no-checkout "$FRONTEND_2024_REPO" /build/fronted-2024 && \
cd /build/fronted-2024 && \ cd /build/fronted-2024 && \
@@ -73,6 +74,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-2026/dist ./themes/2026
COPY --from=frontend-builder /build/fronted-2023/dist ./themes/2023 COPY --from=frontend-builder /build/fronted-2023/dist ./themes/2023
# 应用管理后台详情页取件记录展开/收起、复制回退与悬停边框补丁
RUN python scripts/patch_admin_timeline_ui.py
# 安装系统安全更新 + Python 依赖 # 安装系统安全更新 + Python 依赖
RUN apt-get update \ RUN apt-get update \
&& apt-get upgrade -y --no-install-recommends \ && apt-get upgrade -y --no-install-recommends \
+5
View File
@@ -57,6 +57,11 @@ class BatchFilePolicyActionData(BaseModel):
download_limit: Optional[int] = None download_limit: Optional[int] = None
class TrashRetentionData(BaseModel):
id: int
retentionDays: int
class FileMetadataData(BaseModel): class FileMetadataData(BaseModel):
id: int id: int
note: Optional[str] = None note: Optional[str] = None
+183 -34
View File
@@ -17,9 +17,9 @@ from core.settings import (
) )
from core.config import refresh_settings from core.config import refresh_settings
from core.security import INTERNAL_CONFIG_KEYS, generate_jwt_secret from core.security import INTERNAL_CONFIG_KEYS, generate_jwt_secret
from apps.base.models import FileCodes, KeyValue, TransferStats, file_codes_pydantic from apps.base.models import FileCodes, KeyValue, ShareCodeReservations, 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 apps.base.quota import release_storage, reserve_storage
from fastapi import HTTPException from fastapi import HTTPException
from core.settings import data_root from core.settings import data_root
@@ -36,7 +36,7 @@ class FileService:
MAX_VIEW_PRESETS = 24 MAX_VIEW_PRESETS = 24
MAX_VIEW_PRESET_NAME_LENGTH = 32 MAX_VIEW_PRESET_NAME_LENGTH = 32
MAX_VIEW_PRESET_KEYWORD_LENGTH = 80 MAX_VIEW_PRESET_KEYWORD_LENGTH = 80
MAX_ADMIN_ACTIVITIES = 80 MAX_ADMIN_ACTIVITIES = 5000
MAX_ADMIN_ACTIVITY_TEXT_LENGTH = 120 MAX_ADMIN_ACTIVITY_TEXT_LENGTH = 120
POLICY_ACTIONS = { POLICY_ACTIONS = {
@@ -80,6 +80,9 @@ class FileService:
"code", "code",
} }
TRASH_DEFAULT_RETENTION_DAYS = 7
TRASH_MAX_RETENTION_DAYS = 365
def __init__(self): def __init__(self):
self._file_storage: Optional[FileStorageInterface] = None self._file_storage: Optional[FileStorageInterface] = None
@@ -105,38 +108,174 @@ class FileService:
return deduped return deduped
async def _delete_file_code(self, file_code: FileCodes): async def _delete_file_code(self, file_code: FileCodes):
try: await self.move_to_trash(file_code, reason="manual")
name = (
f"{file_code.prefix or ''}{file_code.suffix or ''}" @staticmethod
or file_code.uuid_file_name def _trash_path(file_code: FileCodes) -> str:
or file_code.code 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.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( await TransferStats.create(
action="delete", action="trash",
file_code_id=file_code.id, file_code_id=file_code.id,
code=file_code.code, code=file_code.code,
name=name, name=f"{file_code.prefix or ''}{file_code.suffix or ''}" or file_code.code,
size=int(file_code.size or 0), size=int(file_code.size or 0),
ip="admin-delete", 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
original_code = file_code.code
await ShareCodeReservations.get_or_create(
code=original_code,
defaults={"file_code_id": file_code.id, "reason": "restored"},
)
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 "", file_path=file_code.file_path or "",
expired_at=file_code.expired_at, expired_at=file_code.expired_at,
deleted_at=datetime.now(), meta=json.dumps({"new_code": file_code.code}, ensure_ascii=False),
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: await self.record_admin_activity(
pass 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: if file_code.text is None:
await self.file_storage.delete_file(file_code) trash_path = self._trash_path(file_code)
await KeyValue.filter(key=self._file_metadata_key(file_code.id)).delete() await self.file_storage.delete_file(
await file_code.delete() 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): async def delete_file(self, file_id: int):
file_code = await FileCodes.get(id=file_id) file_code = await FileCodes.get(id=file_id)
@@ -504,7 +643,7 @@ class FileService:
sort_by = self._normalize_sort_by(sort_by) sort_by = self._normalize_sort_by(sort_by)
reverse = sort_order.strip().lower() != "asc" reverse = sort_order.strip().lower() != "asc"
all_files = await FileCodes.all() all_files = await FileCodes.filter(is_trashed=False).all()
now = await get_now() now = await get_now()
enriched_files = [] enriched_files = []
summary = { summary = {
@@ -800,16 +939,24 @@ class FileService:
async def list_admin_activities( async def list_admin_activities(
self, self,
limit: int = 8, page: int = 1,
size: int = 20,
limit: Optional[int] = None,
action: Optional[str] = None, action: Optional[str] = None,
target_type: Optional[str] = None, target_type: Optional[str] = None,
keyword: Optional[str] = None, keyword: Optional[str] = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
if limit is not None:
size = limit
try: try:
normalized_limit = int(limit or 8) page = max(int(page or 1), 1)
except (TypeError, ValueError): except (TypeError, ValueError):
normalized_limit = 8 page = 1
limit = min(max(normalized_limit, 1), self.MAX_ADMIN_ACTIVITIES) try:
size = int(size or 20)
except (TypeError, ValueError):
size = 20
size = min(max(size, 1), 100)
activities = await self._get_admin_activities() activities = await self._get_admin_activities()
normalized_action = self._normalize_admin_activity_text(action).lower() normalized_action = self._normalize_admin_activity_text(action).lower()
normalized_target_type = self._normalize_admin_activity_text(target_type).lower() normalized_target_type = self._normalize_admin_activity_text(target_type).lower()
@@ -820,16 +967,18 @@ class FileService:
target_type=normalized_target_type, target_type=normalized_target_type,
keyword=normalized_keyword, 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") action_options = self._build_admin_activity_options(activities, "action")
target_type_options = self._build_admin_activity_options(activities, "targetType") target_type_options = self._build_admin_activity_options(activities, "targetType")
return { return {
"activities": visible_activities, "activities": visible_activities,
"items": visible_activities, "items": visible_activities,
"page": page,
"size": size,
"total": len(filtered_activities), "total": len(filtered_activities),
"storedTotal": len(activities), "storedTotal": len(activities),
"stored_total": len(activities), "stored_total": len(activities),
"limit": limit,
"filters": { "filters": {
"action": normalized_action, "action": normalized_action,
"targetType": normalized_target_type, "targetType": normalized_target_type,
+58 -6
View File
@@ -21,6 +21,7 @@ from apps.admin.schemas import (
BatchUpdateFileData, BatchUpdateFileData,
BatchFilePolicyActionData, BatchFilePolicyActionData,
FilePolicyActionData, FilePolicyActionData,
TrashRetentionData,
FileMetadataData, FileMetadataData,
FileViewPresetData, FileViewPresetData,
FileViewPresetDeleteData, FileViewPresetDeleteData,
@@ -30,7 +31,7 @@ from apps.admin.schemas import (
UpdateFileData, UpdateFileData,
) )
from core.response import APIResponse from core.response import APIResponse
from apps.base.models import FileCodes, KeyValue, TransferStats from apps.base.models import FileCodes, KeyValue, ShareCodeReservations, TransferStats
from apps.admin.dependencies import ( from apps.admin.dependencies import (
create_token, create_token,
get_admin_session_expire_seconds, get_admin_session_expire_seconds,
@@ -104,7 +105,7 @@ async def build_dashboard_recent_file(file_code: FileCodes) -> dict:
@admin_api.get("/dashboard") @admin_api.get("/dashboard")
async def dashboard(file_service: FileService = Depends(get_file_service)): 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]) all_size = sum([code.size for code in all_codes])
sys_start = await KeyValue.filter(key="sys_start").first() sys_start = await KeyValue.filter(key="sys_start").first()
now = await get_now() now = await get_now()
@@ -176,7 +177,9 @@ async def dashboard(file_service: FileService = Depends(get_file_service)):
@admin_api.get("/activities") @admin_api.get("/activities")
async def admin_activities( async def admin_activities(
limit: int = 20, page: int = 1,
size: int = 20,
limit: Optional[int] = None,
action: Optional[str] = None, action: Optional[str] = None,
targetType: Optional[str] = None, targetType: Optional[str] = None,
target_type: Optional[str] = None, target_type: Optional[str] = None,
@@ -184,6 +187,8 @@ async def admin_activities(
file_service: FileService = Depends(get_file_service), file_service: FileService = Depends(get_file_service),
): ):
result = await file_service.list_admin_activities( result = await file_service.list_admin_activities(
page=page,
size=size,
limit=limit, limit=limit,
action=action, action=action,
target_type=_pick_query_text(targetType, target_type), 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) 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( async def batch_update_files(
data: BatchUpdateFileData, data: BatchUpdateFileData,
file_service: FileService, file_service: FileService,
@@ -812,12 +856,15 @@ async def update_file(
if not file_code: if not file_code:
raise HTTPException(status_code=404, detail="文件不存在") raise HTTPException(status_code=404, detail="文件不存在")
target_name = file_service._build_file_activity_name(file_code) target_name = file_service._build_file_activity_name(file_code)
previous_code = file_code.code
update_data = {} update_data = {}
if data.code is not None and data.code != file_code.code: if data.code is not None and data.code != file_code.code:
# 判断code是否存在 # 当前记录和全部退役取件码都不可重复使用。
if await FileCodes.filter(code=data.code).first(): if await FileCodes.filter(code=data.code).first() or await ShareCodeReservations.filter(
raise HTTPException(status_code=400, detail="code已存在") code=data.code
).first():
raise HTTPException(status_code=400, detail="取件码已被占用")
update_data["code"] = data.code update_data["code"] = data.code
if data.prefix is not None and data.prefix != file_code.prefix: if data.prefix is not None and data.prefix != file_code.prefix:
update_data["prefix"] = data.prefix update_data["prefix"] = data.prefix
@@ -833,6 +880,11 @@ async def update_file(
update_data["expired_count"] = data.expired_count update_data["expired_count"] = data.expired_count
await file_code.update_from_dict(update_data).save() await file_code.update_from_dict(update_data).save()
if "code" in update_data:
await ShareCodeReservations.get_or_create(
code=previous_code,
defaults={"file_code_id": file_code.id, "reason": "manual_update"},
)
if update_data: if update_data:
await file_service.record_admin_activity( await file_service.record_admin_activity(
action="file.update", action="file.update",
@@ -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);
"""
)
@@ -0,0 +1,20 @@
from tortoise import connections
async def migrate():
conn = connections.get("default")
await conn.execute_script(
"""
CREATE TABLE IF NOT EXISTS share_code_reservations (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
code VARCHAR(255) NOT NULL UNIQUE,
file_code_id INT NULL,
reason VARCHAR(32) NOT NULL DEFAULT 'retired',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_share_code_reservations_code
ON share_code_reservations(code);
CREATE INDEX IF NOT EXISTS idx_share_code_reservations_file_code_id
ON share_code_reservations(file_code_id);
"""
)
@@ -0,0 +1,14 @@
from tortoise import connections
async def migrate():
"""把既有审计日志中的取件码也登记为永久占用。"""
conn = connections.get("default")
await conn.execute_query(
"""
INSERT OR IGNORE INTO share_code_reservations (code, file_code_id, reason)
SELECT DISTINCT TRIM(code), file_code_id, 'historical_audit'
FROM transfer_stats
WHERE code IS NOT NULL AND TRIM(code) <> ''
"""
)
+19
View File
@@ -28,6 +28,12 @@ class FileCodes(models.Model):
file_hash = fields.CharField(max_length=64, null=True) file_hash = fields.CharField(max_length=64, null=True)
is_chunked = fields.BooleanField(default=False) is_chunked = fields.BooleanField(default=False)
upload_id = fields.CharField(max_length=36, null=True) 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): async def is_expired(self):
if self.expired_at is None: if self.expired_at is None:
@@ -40,6 +46,19 @@ class FileCodes(models.Model):
return f"{self.file_path}/{self.uuid_file_name}" return f"{self.file_path}/{self.uuid_file_name}"
class ShareCodeReservations(models.Model):
"""已退役取件码的永久封存登记,防止恢复文件后旧码被重新分配。"""
id = fields.IntField(pk=True)
code = fields.CharField(max_length=255, unique=True, index=True)
file_code_id = fields.IntField(null=True, index=True)
reason = fields.CharField(max_length=32, default="retired")
created_at = fields.DatetimeField(auto_now_add=True)
class Meta:
table = "share_code_reservations"
class UploadChunk(models.Model): class UploadChunk(models.Model):
id = fields.IntField(pk=True) id = fields.IntField(pk=True)
upload_id = fields.CharField(max_length=36, index=True) upload_id = fields.CharField(max_length=36, index=True)
+14 -5
View File
@@ -8,7 +8,7 @@ from fastapi import UploadFile, HTTPException
from typing import Optional, Tuple from typing import Optional, Tuple
from apps.base.dependencies import IPRateLimit from apps.base.dependencies import IPRateLimit
from apps.base.models import FileCodes from apps.base.models import FileCodes, ShareCodeReservations
from core.settings import settings from core.settings import settings
from core.utils import ( from core.utils import (
get_random_num, get_random_num,
@@ -96,6 +96,11 @@ async def get_expire_info(
return expired_at, expired_count, used_count, code return expired_at, expired_count, used_count, code
CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
CODE_LENGTH = 8
CODE_MAX_ATTEMPTS = 50
def get_code_generate_type() -> str: def get_code_generate_type() -> str:
code_generate_type = getattr(settings, "code_generate_type", "secret") code_generate_type = getattr(settings, "code_generate_type", "secret")
if code_generate_type in {"secret", "string"}: if code_generate_type in {"secret", "string"}:
@@ -104,20 +109,24 @@ def get_code_generate_type() -> str:
async def get_random_code(style: str | None = None) -> str: async def get_random_code(style: str | None = None) -> str:
"""生成新的 8 位取件码,并避开所有仍保留的历史审计记录。"""
code_style = style or get_code_generate_type() code_style = style or get_code_generate_type()
if code_style == "num": if code_style == "num":
code_style = "number" code_style = "number"
if code_style == "string": if code_style == "string":
code_style = "secret" code_style = "secret"
while True: for _ in range(CODE_MAX_ATTEMPTS):
code = ( code = (
await get_random_num() await get_random_num(CODE_LENGTH)
if code_style == "number" if code_style == "number"
else await get_random_string() else await get_random_string(CODE_LENGTH)
) )
if not await FileCodes.filter(code=code).exists(): if not await FileCodes.filter(code=code).exists() and not await ShareCodeReservations.filter(
code=code
).exists():
return str(code) return str(code)
raise HTTPException(status_code=503, detail="取件码生成暂时繁忙,请重试")
async def calculate_file_hash(file: UploadFile, chunk_size=1024 * 1024) -> str: async def calculate_file_hash(file: UploadFile, chunk_size=1024 * 1024) -> str:
+1 -1
View File
@@ -238,7 +238,7 @@ async def get_code_file_by_code(
normalized_code = normalize_share_code(code) normalized_code = normalize_share_code(code)
if not normalized_code: if not normalized_code:
return False, "文件不存在" 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: if not file_code:
return False, "文件不存在" return False, "文件不存在"
if await file_code.is_expired() and check: if await file_code.is_expired() and check:
+29
View File
@@ -42,6 +42,10 @@ class FileStorageInterface:
""" """
raise NotImplementedError 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): async def get_file_url(self, file_code: FileCodes):
""" """
获取文件分享的url 获取文件分享的url
@@ -147,6 +151,14 @@ class SystemFileStorage(FileStorageInterface):
if save_path.exists(): if save_path.exists():
save_path.unlink() 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): async def get_file_url(self, file_code: FileCodes):
return await get_file_url(file_code.code) return await get_file_url(file_code.code)
@@ -1164,6 +1176,23 @@ class WebDAVFileStorage(FileStorageInterface):
raise HTTPException( raise HTTPException(
status_code=503, detail=f"WebDAV连接异常: {str(e)}") 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): async def get_file_url(self, file_code: FileCodes):
return await get_file_url(file_code.code) return await get_file_url(file_code.code)
+14 -6
View File
@@ -15,6 +15,7 @@ from apps.base.models import (
StorageReservation, StorageReservation,
UploadChunk, UploadChunk,
) )
from apps.admin.services import FileService
from apps.base.utils import ip_limit, get_chunk_file_path_name from apps.base.utils import ip_limit, get_chunk_file_path_name
from core.config import refresh_settings from core.config import refresh_settings
from core.settings import settings, data_root 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["metadata"].remove_expired_ip()
await ip_limit["upload"].remove_expired_ip() await ip_limit["upload"].remove_expired_ip()
await StorageReservation.filter(expires_at__lte=await get_now()).delete() await StorageReservation.filter(expires_at__lte=await get_now()).delete()
file_service = FileService()
expire_data = await FileCodes.filter( expire_data = await FileCodes.filter(
Q(expired_at__lt=await get_now()) | Q(expired_count=0) is_trashed=False,
).all() ).filter(Q(expired_at__lt=await get_now()) | Q(expired_count=0)).all()
for exp in expire_data: for exp in expire_data:
try: try:
await file_storage.delete_file(exp) await file_service.move_to_trash(exp, reason="expired")
except Exception as e: 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: try:
await exp.delete() await file_service.purge_trashed_file(item)
except Exception as e: except Exception as e:
logging.error(f"删除记录失败 code={exp.code}: {e}") logging.error(f"彻底清理回收站文件失败 id={item.id}: {e}")
except Exception as e: except Exception as e:
logging.error(e) logging.error(e)
finally: finally:
+11 -14
View File
@@ -8,29 +8,26 @@ import hmac
import os import os
import re import re
import secrets import secrets
import string
import time import time
from core.settings import settings from core.settings import settings
async def get_random_num(): async def get_random_num(length: int = 8):
""" """返回指定长度的纯数字取件码。"""
获取随机数 normalized_length = max(1, int(length or 8))
:return: lower = 10 ** (normalized_length - 1)
""" return str(secrets.randbelow(9 * lower) + lower)
return secrets.randbelow(90000) + 10000
r_s = string.ascii_uppercase + string.digits # 排除 0/O、1/I/L,避免人工输入取件码时混淆。
r_s = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
async def get_random_string(): async def get_random_string(length: int = 8):
""" """返回指定长度、无易混淆字符的取件码。"""
获取随机字符串 normalized_length = max(1, int(length or 8))
:return: return "".join(secrets.choice(r_s) for _ in range(normalized_length))
"""
return "".join(secrets.choice(r_s) for _ in range(5))
async def get_now(): async def get_now():
+61 -59
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from pathlib import Path from pathlib import Path
import gzip import gzip
import re
ASSETS_ROOT = Path('/app') ASSETS_ROOT = Path('/app')
@@ -39,28 +40,27 @@ def patch_file_manage(path: Path) -> bool:
def patch_clipboard(path: Path) -> bool: def patch_clipboard(path: Path) -> bool:
text = path.read_text(encoding='utf-8') text = path.read_text(encoding='utf-8')
old = text old = text
marker = 'const y=async(a,e={})=>{' pattern = re.compile(
if marker not in text or 'fcbx-copy-fallback' in text: 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 return False
start = text.index(marker) name = match.group('name')
end_marker = '},T=async(a,e={})=>{' 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}}}}'''
end = text.index(end_marker, start) + 1 text = text[:match.start()] + replacement + text[match.end():]
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:]
if text != old: if text != old:
rewrite(path, text) rewrite(path, text)
return True return True
return False return False
def write_detail_collapse_script(theme_dir: Path) -> bool: def build_lifecycle_script() -> str:
assets = theme_dir / 'assets' return r'''(() => {
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'''(() => {
const LIFE_RE = /(生命周期|Lifecycle)/i; const LIFE_RE = /(生命周期|Lifecycle)/i;
const RETRIEVAL_RE = /^(第\s*\d+\s*次取件|retrieval\s*#?\d+)/i;
const STATE = new WeakMap(); const STATE = new WeakMap();
const getSection = section => { const getSection = section => {
const title = section.querySelector('h1,h2,h3,h4,h5'); 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 getRows = section => {
const ctx = getSection(section); const ctx = getSection(section);
if (!ctx) return []; if (!ctx) return [];
return [...ctx.box.children].filter(el => el instanceof HTMLElement); return [...ctx.box.querySelectorAll(':scope > .fcb-expand-content')];
}; };
const apply = section => { const apply = section => {
const ctx = getSection(section); const ctx = getSection(section);
if (!ctx) return; if (!ctx) return;
const rows = [...ctx.box.children].filter(el => el instanceof HTMLElement); const rows = getRows(section);
if (rows.length <= 3) return; const events = rows.filter(row => RETRIEVAL_RE.test((row.querySelector('p')?.textContent || '').trim()));
if (events.length <= 3) return;
const expanded = STATE.get(section) === true; const expanded = STATE.get(section) === true;
section.classList.toggle('fcbx-life-expanded', expanded); events.forEach((row, idx) => {
rows.forEach((row, idx) => { row.classList.add('fcbx-retrieval-event');
const shouldHide = idx >= 3 && !expanded; row.style.display = expanded || idx < 3 ? '' : 'none';
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');
}
}); });
const btn = section.querySelector(':scope > .fcbx-life-toggle') || section.querySelector('.fcbx-life-toggle'); let button = section.querySelector(':scope > .fcbx-retrieval-toggle');
if (btn) { if (!button) {
btn.textContent = expanded ? '收起生命周期记录' : `展开全部生命周期记录(共 ${rows.length} 条)`; button = document.createElement('button');
btn.setAttribute('aria-expanded', expanded ? 'true' : 'false'); 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;';
const ensureSection = section => { button.onclick = event => {
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 => {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
STATE.set(section, STATE.get(section) !== true); STATE.set(section, STATE.get(section) !== true);
apply(section); 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 markRows = root => {
const scope = root?.querySelectorAll ? root : document; 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; let raf = 0;
const schedule = root => { cancelAnimationFrame(raf); raf = requestAnimationFrame(() => markRows(root)); }; const schedule = root => { cancelAnimationFrame(raf); raf = requestAnimationFrame(() => markRows(root)); };
window.addEventListener('hashchange', () => schedule(document)); window.addEventListener('hashchange', () => schedule(document));
document.addEventListener('DOMContentLoaded', () => schedule(document)); document.addEventListener('DOMContentLoaded', () => schedule(document));
new MutationObserver(records => { new MutationObserver(() => schedule(document)).observe(document.body || document.documentElement, { childList: true, subtree: true });
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 });
schedule(document); 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) rewrite(js_path, js)
html = index.read_text(encoding='utf-8') html = index.read_text(encoding='utf-8')
# Remove old detail-collapse injection so browsers cannot keep loading the stale “取件记录” script. # Remove old detail-collapse injection so browsers cannot keep loading the stale “取件记录” script.
@@ -156,11 +160,9 @@ def write_detail_collapse_script(theme_dir: Path) -> bool:
def main() -> None: def main() -> None:
changed = [] changed = []
theme = ASSETS_ROOT / 'themes/2026' for theme in (ASSETS_ROOT / 'themes/2024', ASSETS_ROOT / 'themes/2026'):
assets = theme / 'assets' assets = theme / 'assets'
if assets.exists(): if assets.exists():
# 只用独立 DOM 脚本处理生命周期收起,避免再改编译后的 FileManageView,
# 否则 Vue 内部状态和外部补丁会互相抢状态,导致展开/收起需要点多次。
for path in assets.glob('clipboard-*.js'): for path in assets.glob('clipboard-*.js'):
if patch_clipboard(path): if patch_clipboard(path):
changed.append(str(path.relative_to(ASSETS_ROOT))) changed.append(str(path.relative_to(ASSETS_ROOT)))
+43
View File
@@ -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()
+16
View File
@@ -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()
+74
View File
@@ -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, ShareCodeReservations
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 ShareCodeReservations.create(code="RETIRE02", file_code_id=item.id)
with patch("apps.base.utils.get_random_string", AsyncMock(side_effect=["RETIRE02", "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()
+47
View File
@@ -0,0 +1,47 @@
import asyncio
import unittest
from unittest.mock import AsyncMock, patch
from tortoise import Tortoise
from apps.admin.services import FileService
from apps.base.models import FileCodes, ShareCodeReservations
class ShareCodeReservationTests(unittest.TestCase):
def test_restore_reserves_old_code_before_assigning_new_code(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_CODE", is_trashed=True, text="text")
service = FileService()
with patch("apps.admin.services.get_random_code", AsyncMock(return_value="NEWCODE8")):
restored = await service.restore_from_trash(item.id)
self.assertEqual(restored.code, "NEWCODE8")
reservation = await ShareCodeReservations.get(code="OLD_CODE")
self.assertEqual(reservation.file_code_id, item.id)
self.assertEqual(reservation.reason, "restored")
# 模拟管理员手工改码:被替换的旧码也必须永久封存。
await ShareCodeReservations.get_or_create(
code="MANUALOLD",
defaults={"file_code_id": item.id, "reason": "manual_update"},
)
self.assertTrue(await ShareCodeReservations.filter(code="MANUALOLD").exists())
finally:
await Tortoise.close_connections()
if __name__ == "__main__":
unittest.main()