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

This commit is contained in:
orion committed 2026-09-11 16:49:50 +08:00
1 parent 5e71cde60e
commit 6bc1c30797
17 files changed
+6309

No files matched your search

+98
View File
@@ -0,0 +1,98 @@
# 第一阶段:构建前端主题
# 前端产物与 CPU 架构无关,使用原生构建平台避免在 QEMU 中运行 Node/pnpm。
FROM --platform=$BUILDPLATFORM node:20-alpine AS frontend-builder
ARG FRONTEND_2024_REF=main
ARG FRONTEND_2023_REF=main
RUN apk add --no-cache git python3 make g++
RUN corepack enable && \
corepack prepare pnpm@9.15.9 --activate
WORKDIR /build
# 克隆并构建 2024 主题
ARG FRONTEND_2024_REPO=https://git.orionc.me/orion/FileCodeBoxFronted.git
ARG FRONTEND_2024_BRANCH=main
ARG FRONTEND_CACHE_BUST=1
RUN echo "$FRONTEND_CACHE_BUST" >/tmp/frontend-cache-bust && \
git clone --filter=blob:none --no-checkout "$FRONTEND_2024_REPO" /build/fronted-2024 && \
cd /build/fronted-2024 && \
git fetch --depth 1 origin "${FRONTEND_2024_REF}" && \
git checkout --detach FETCH_HEAD && \
pnpm install --frozen-lockfile --prod=false && \
VITE_GIT_COMMIT="$(git rev-parse HEAD)" pnpm run build
# 克隆并构建定制 2026 主题
ARG FRONTEND_2026_REPO=https://git.orionc.me/orion/FileCodeBoxFronted2026.git
ARG FRONTEND_2026_BRANCH=test/custom-admin-ui
RUN echo "$FRONTEND_CACHE_BUST" >/tmp/frontend-2026-cache-bust && \
git clone --depth 1 --branch "$FRONTEND_2026_BRANCH" "$FRONTEND_2026_REPO" /build/fronted-2026 && \
cd /build/fronted-2026 && \
pnpm install --frozen-lockfile --prod=false && \
VITE_GIT_COMMIT="$(git rev-parse HEAD)" pnpm run build
# 克隆并构建 2023 主题
ARG FRONTEND_2023_REPO=https://git.orionc.me/orion/FileCodeBoxFronted2023.git
ARG FRONTEND_2023_BRANCH=main
RUN git clone --filter=blob:none --no-checkout "$FRONTEND_2023_REPO" /build/fronted-2023 && \
cd /build/fronted-2023 && \
git fetch --depth 1 origin "${FRONTEND_2023_REF}" && \
git checkout --detach FETCH_HEAD && \
npm install --legacy-peer-deps && \
npm run build
# 第二阶段:构建最终镜像
FROM python:3.12-slim-bookworm
ARG APP_VERSION
ARG VCS_REF=unknown
ARG FRONTEND_2024_REF=main
ARG FRONTEND_2023_REF=main
LABEL author="Lan"
LABEL email="xzu@live.com"
LABEL org.opencontainers.image.version="${APP_VERSION}"
LABEL org.opencontainers.image.revision="${VCS_REF}"
LABEL org.opencontainers.image.filecodebox.frontend-2024-revision="${FRONTEND_2024_REF}"
LABEL org.opencontainers.image.filecodebox.frontend-2023-revision="${FRONTEND_2023_REF}"
WORKDIR /app
# 复制项目文件(通过 .dockerignore 排除不必要的文件)
COPY . .
# 分支镜像使用带提交号的开发版本;正式镜像使用 VERSION 中的版本。
ENV APP_VERSION="${APP_VERSION}"
# 设置时区
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
echo 'Asia/Shanghai' > /etc/timezone
# 从构建阶段复制编译好的前端主题
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 \
&& rm -rf /var/lib/apt/lists/* \
&& pip install --no-cache-dir -r requirements.txt \
&& pip cache purge || true
# 环境变量配置
ENV HOST="0.0.0.0" \
PORT=12345 \
WORKERS=1 \
LOG_LEVEL="info" \
FORWARDED_ALLOW_IPS=""
EXPOSE 12345
# 生产环境启动命令
# FORWARDED_ALLOW_IPS 由部署环境显式指定,避免任意客户端伪造 X-Forwarded-*。
CMD ["sh", "-c", "exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-}\""]
+79
View File
@@ -0,0 +1,79 @@
import datetime
from typing import Any, Optional, Union
from pydantic import BaseModel
class IDData(BaseModel):
id: int
class IDsData(BaseModel):
ids: list[int]
class ShareItem(BaseModel):
expire_value: int
expire_style: str = "day"
filename: str
class DeleteItem(BaseModel):
filename: str
class LoginData(BaseModel):
password: str
class UpdateFileData(BaseModel):
id: int
code: Optional[str] = None
prefix: Optional[str] = None
suffix: Optional[str] = None
expired_at: Optional[Union[datetime.datetime, str]] = None
expired_count: Optional[int] = None
class BatchUpdateFileData(BaseModel):
ids: list[int]
expired_at: Optional[Union[datetime.datetime, str]] = None
expired_count: Optional[int] = None
clearExpiredAt: Optional[bool] = None
clear_expired_at: Optional[bool] = None
class FilePolicyActionData(BaseModel):
id: int
action: str
downloadLimit: Optional[int] = None
download_limit: Optional[int] = None
class BatchFilePolicyActionData(BaseModel):
ids: list[int]
action: str
downloadLimit: Optional[int] = None
download_limit: Optional[int] = None
class TrashRetentionData(BaseModel):
id: int
retentionDays: int
class FileMetadataData(BaseModel):
id: int
note: Optional[str] = None
tags: Optional[list[str]] = None
class FileViewPresetData(BaseModel):
id: Optional[str] = None
name: str
filters: Optional[dict[str, Any]] = None
params: Optional[dict[str, Any]] = None
class FileViewPresetDeleteData(BaseModel):
id: str
File diff suppressed because it is too large. Load diff
+889
View File
@@ -0,0 +1,889 @@
# @Time : 2023/8/14 14:38
# @Author : Lan
# @File : views.py
# @Software: PyCharm
import datetime
from collections import Counter
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException
from apps.admin.services import FileService, ConfigService, LocalFileService
from apps.admin.dependencies import (
admin_required,
get_admin_session,
get_file_service,
get_config_service,
get_local_file_service,
)
from apps.admin.schemas import (
IDData,
IDsData,
BatchUpdateFileData,
BatchFilePolicyActionData,
FilePolicyActionData,
TrashRetentionData,
FileMetadataData,
FileViewPresetData,
FileViewPresetDeleteData,
ShareItem,
DeleteItem,
LoginData,
UpdateFileData,
)
from core.response import APIResponse
from apps.base.models import FileCodes, KeyValue, TransferStats
from apps.admin.dependencies import (
create_token,
get_admin_session_expire_seconds,
verify_token,
)
from core.settings import settings
from core.utils import get_now, verify_password
from apps.base.utils import ip_limit
admin_api = APIRouter(
prefix="/admin", tags=["管理"], dependencies=[Depends(admin_required)]
)
def _pick_query_text(*values: Optional[str]) -> Optional[str]:
for value in values:
normalized_value = str(value or "").strip()
if normalized_value:
return normalized_value
return None
@admin_api.post("/login")
async def login(data: LoginData, ip: str = Depends(ip_limit["login"])):
# 登录失败计入 IP 频率限制,超过 loginCount/loginMinute 后暂时锁定
if not verify_password(data.password, settings.admin_token):
ip_limit["login"].add_ip(ip)
raise HTTPException(status_code=401, detail="密码错误")
expires_in = get_admin_session_expire_seconds()
token = create_token({"is_admin": True}, expires_in=expires_in)
return APIResponse(
detail={
"id": "admin",
"username": "admin",
"token": token,
"token_type": "Bearer",
"expires_at": verify_token(token)["exp"],
"expires_in": expires_in,
}
)
@admin_api.get("/verify")
async def verify_admin(session: dict = Depends(get_admin_session)):
return APIResponse(detail=session)
@admin_api.post("/logout")
async def logout_admin():
return APIResponse(detail={"ok": True})
async def build_dashboard_recent_file(file_code: FileCodes) -> dict:
is_expired = await file_code.is_expired()
return {
"id": file_code.id,
"code": file_code.code,
"name": file_code.prefix + file_code.suffix,
"suffix": file_code.suffix,
"size": file_code.size,
"text": file_code.text is not None,
"expiredAt": file_code.expired_at,
"expiredCount": file_code.expired_count,
"usedCount": file_code.used_count,
"createdAt": file_code.created_at,
"isExpired": is_expired,
}
@admin_api.get("/dashboard")
async def dashboard(file_service: FileService = Depends(get_file_service)):
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()
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
yesterday_start = today_start - datetime.timedelta(days=1)
yesterday_end = today_start - datetime.timedelta(microseconds=1)
yesterday_codes = FileCodes.filter(
created_at__gte=yesterday_start, created_at__lte=yesterday_end
)
today_codes = FileCodes.filter(created_at__gte=today_start)
yesterday_file_codes = await yesterday_codes
today_file_codes = await today_codes
expired_count = 0
for file_code in all_codes:
if await file_code.is_expired():
expired_count += 1
health_summary = await file_service.build_file_health_summary(all_codes, now=now)
text_count = sum(1 for file_code in all_codes if file_code.text is not None)
chunked_count = sum(1 for file_code in all_codes if file_code.is_chunked)
used_count = sum([file_code.used_count for file_code in all_codes])
suffix_counter = Counter(
"Text" if file_code.text is not None else (file_code.suffix or "file")
for file_code in all_codes
)
recent_file_codes = sorted(
all_codes,
key=lambda file_code: file_code.created_at.timestamp()
if file_code.created_at
else 0,
reverse=True,
)[:8]
recent_activities = await file_service.list_admin_activities(limit=8)
return APIResponse(
detail={
"totalFiles": len(all_codes),
"storageUsed": str(all_size),
"sysUptime": sys_start.value if sys_start else None,
"yesterdayCount": len(yesterday_file_codes),
"yesterdaySize": str(sum([code.size for code in yesterday_file_codes])),
"todayCount": len(today_file_codes),
"todaySize": str(sum([code.size for code in today_file_codes])),
"activeCount": len(all_codes) - expired_count,
"expiredCount": expired_count,
"textCount": text_count,
"fileCount": len(all_codes) - text_count,
"chunkedCount": chunked_count,
"usedCount": used_count,
"storageBackend": settings.file_storage,
"uploadSizeLimit": settings.uploadSize,
"openUpload": settings.openUpload,
"enableChunk": settings.enableChunk,
"maxSaveSeconds": settings.max_save_seconds,
**health_summary,
"healthSummary": health_summary,
"topSuffixes": [
{"suffix": suffix, "count": count}
for suffix, count in suffix_counter.most_common(8)
],
"recentFiles": [
await build_dashboard_recent_file(file_code)
for file_code in recent_file_codes
],
"recentActivities": recent_activities["activities"],
"recent_activities": recent_activities["activities"],
}
)
@admin_api.get("/activities")
async def admin_activities(
page: int = 1,
size: int = 20,
limit: Optional[int] = None,
action: Optional[str] = None,
targetType: Optional[str] = None,
target_type: Optional[str] = None,
keyword: Optional[str] = None,
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),
keyword=keyword,
)
return APIResponse(detail=result)
@admin_api.get("/analytics")
async def analytics(start: str = "", end: str = ""):
now = await get_now()
def parse_day(value: str, fallback: datetime.datetime) -> datetime.datetime:
if not value:
return fallback
try:
return datetime.datetime.strptime(value[:10], "%Y-%m-%d")
except Exception:
return fallback
end_day = parse_day(end, now.replace(hour=0, minute=0, second=0, microsecond=0))
start_day = parse_day(start, end_day - datetime.timedelta(days=29))
end_exclusive = end_day + datetime.timedelta(days=1)
raw_stats = await TransferStats.filter(
created_at__gte=start_day,
created_at__lt=end_exclusive,
).order_by("created_at", "id")
stats = []
recent_downloads = {}
for item in raw_stats:
if item.action == "download":
dedupe_key = (
item.file_code_id or item.code or "",
item.ip or "",
int(item.size or 0),
)
previous = recent_downloads.get(dedupe_key)
if previous and (item.created_at - previous).total_seconds() <= 5:
continue
recent_downloads[dedupe_key] = item.created_at
stats.append(item)
files = await FileCodes.all()
file_map = {item.code: item for item in files}
day_map = {}
cursor = start_day
while cursor < end_exclusive:
key = cursor.strftime("%Y-%m-%d")
day_map[key] = {
"date": key,
"downloads": 0,
"uploads": 0,
"downloadTraffic": 0,
"uploadTraffic": 0,
}
cursor += datetime.timedelta(days=1)
file_stats = {}
for item in stats:
key = item.created_at.strftime("%Y-%m-%d")
row = day_map.get(key)
if row and item.action == "download":
row["downloads"] += 1
row["downloadTraffic"] += item.size or 0
elif row and item.action == "upload":
row["uploads"] += 1
row["uploadTraffic"] += item.size or 0
if not item.code:
continue
bucket = file_stats.setdefault(
item.code,
{
"downloads": 0,
"downloadTraffic": 0,
"uploads": 0,
"uploadTraffic": 0,
"name": item.name or item.code,
"size": int(item.size or 0),
"uploaded_at": None,
"expired_at": item.expired_at,
"deleted_at": None,
"deleted": False,
},
)
bucket["name"] = bucket["name"] or item.name or item.code
bucket["size"] = bucket["size"] or int(item.size or 0)
bucket["expired_at"] = bucket["expired_at"] or item.expired_at
if item.action == "upload":
bucket["uploads"] += 1
bucket["uploadTraffic"] += item.size or 0
bucket["uploaded_at"] = bucket["uploaded_at"] or item.created_at
elif item.action == "download":
bucket["downloads"] += 1
bucket["downloadTraffic"] += item.size or 0
elif item.action == "delete":
bucket["deleted"] = True
bucket["deleted_at"] = item.deleted_at or item.created_at
for file_item in files:
current_name = (
f"{file_item.prefix or ''}{file_item.suffix or ''}"
or file_item.uuid_file_name
or file_item.code
)
bucket = file_stats.setdefault(
file_item.code,
{
"downloads": 0,
"downloadTraffic": 0,
"uploads": 0,
"uploadTraffic": 0,
"name": current_name,
"size": int(file_item.size or 0),
"uploaded_at": file_item.created_at,
"expired_at": file_item.expired_at,
"deleted_at": None,
"deleted": False,
},
)
bucket["name"] = current_name
bucket["size"] = int(file_item.size or 0)
bucket["uploaded_at"] = file_item.created_at or bucket["uploaded_at"]
bucket["expired_at"] = file_item.expired_at
bucket["deleted"] = False
bucket["deleted_at"] = None
created_key = (
file_item.created_at.strftime("%Y-%m-%d") if file_item.created_at else ""
)
created_row = day_map.get(created_key)
if bucket["uploads"] <= 0:
bucket["uploads"] = 1
bucket["uploadTraffic"] = int(file_item.size or 0)
if created_row:
created_row["uploads"] += 1
created_row["uploadTraffic"] += int(file_item.size or 0)
missing_downloads = max(0, int(file_item.used_count or 0) - bucket["downloads"])
if missing_downloads:
traffic = missing_downloads * int(file_item.size or 0)
bucket["downloads"] += missing_downloads
bucket["downloadTraffic"] += traffic
if created_row:
created_row["downloads"] += missing_downloads
created_row["downloadTraffic"] += traffic
def iso(value):
return value.isoformat() if value else ""
def current_file_expired(file_item) -> bool:
if not file_item:
return False
if file_item.expired_at and file_item.expired_at < now:
return True
return file_item.expired_count == 0
def history_row(code: str, data: dict) -> dict:
file_item = file_map.get(code)
current_name = ""
if file_item:
current_name = (
f"{file_item.prefix or ''}{file_item.suffix or ''}"
or file_item.uuid_file_name
or file_item.code
)
uploaded_at = file_item.created_at if file_item else data.get("uploaded_at")
expired_at = file_item.expired_at if file_item else data.get("expired_at")
size = int(file_item.size or 0) if file_item else data.get("size") or 0
return {
"code": code,
"name": current_name or data.get("name") or code,
"size": str(size),
"download_count": data.get("downloads") or 0,
"download_traffic": str(data.get("downloadTraffic") or 0),
"upload_count": data.get("uploads") or 0,
"upload_traffic": str(data.get("uploadTraffic") or 0),
"current": bool(file_item),
"expired": current_file_expired(file_item),
"deleted": bool(data.get("deleted")) and not bool(file_item),
"created_at": iso(uploaded_at),
"uploaded_at": iso(uploaded_at),
"expired_at": iso(expired_at),
"deleted_at": iso(data.get("deleted_at")),
}
def sort_time(value) -> float:
return value.timestamp() if value else 0
history = sorted(
file_stats.items(),
key=lambda kv: (
sort_time(kv[1].get("deleted_at") or kv[1].get("uploaded_at")),
kv[1].get("downloads") or 0,
kv[1].get("downloadTraffic") or 0,
),
reverse=True,
)
top_files = sorted(
[item for item in history if (item[1].get("downloads") or 0) > 0],
key=lambda kv: (kv[1].get("downloads") or 0, kv[1].get("downloadTraffic") or 0),
reverse=True,
)[:5]
daily_rows = list(day_map.values())
return APIResponse(
detail={
"range": {
"start": start_day.strftime("%Y-%m-%d"),
"end": end_day.strftime("%Y-%m-%d"),
},
"totals": {
"totalDownloads": sum(row["downloads"] for row in daily_rows),
"downloadedFiles": len(
[item for item in file_stats.values() if (item.get("downloads") or 0) > 0]
),
"downloadTraffic": str(
sum(row["downloadTraffic"] for row in daily_rows)
),
"historicalFiles": len(file_stats),
"currentFiles": len(files),
"totalUploads": sum(row["uploads"] for row in daily_rows),
"uploadTraffic": str(
sum(row["uploadTraffic"] for row in daily_rows)
),
},
"daily": daily_rows,
"topFiles": [history_row(code, data) for code, data in top_files],
"historyFiles": [history_row(code, data) for code, data in history],
}
)
@admin_api.delete("/file/delete")
async def file_delete(
data: IDData,
file_service: FileService = Depends(get_file_service),
):
await file_service.delete_file(data.id)
return APIResponse()
async def batch_delete_files(
data: IDsData,
file_service: FileService,
):
if not data.ids:
raise HTTPException(status_code=400, detail="请选择要删除的文件")
result = await file_service.delete_files(data.ids)
return APIResponse(detail=result)
@admin_api.delete("/file/batch-delete")
async def file_batch_delete(
data: IDsData,
file_service: FileService = Depends(get_file_service),
):
return await batch_delete_files(data, file_service)
@admin_api.post("/file/batch-delete")
async def file_batch_delete_post(
data: IDsData,
file_service: FileService = Depends(get_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(
data: BatchUpdateFileData,
file_service: FileService,
):
if not data.ids:
raise HTTPException(status_code=400, detail="请选择要更新的文件")
update_data = {}
fields_set = data.model_fields_set
should_clear_expired_at = bool(data.clearExpiredAt or data.clear_expired_at)
if should_clear_expired_at:
update_data["expired_at"] = None
update_data["expired_count"] = -1
elif "expired_at" in fields_set and data.expired_at != "":
update_data["expired_at"] = data.expired_at
if (
not should_clear_expired_at
and "expired_count" in fields_set
and data.expired_count is not None
):
update_data["expired_count"] = data.expired_count
if not update_data:
raise HTTPException(status_code=400, detail="请选择要更新的字段")
result = await file_service.update_files(data.ids, update_data)
return APIResponse(detail=result)
@admin_api.patch("/file/batch-update")
async def file_batch_update(
data: BatchUpdateFileData,
file_service: FileService = Depends(get_file_service),
):
return await batch_update_files(data, file_service)
@admin_api.post("/file/batch-update")
async def file_batch_update_post(
data: BatchUpdateFileData,
file_service: FileService = Depends(get_file_service),
):
return await batch_update_files(data, file_service)
async def apply_file_policy_action(
data: FilePolicyActionData,
file_service: FileService,
):
download_limit = data.downloadLimit
if download_limit is None:
download_limit = data.download_limit
detail = await file_service.apply_file_policy_action(
file_id=data.id,
action=data.action,
download_limit=download_limit,
)
return APIResponse(detail=detail)
@admin_api.patch("/file/policy-action")
async def file_policy_action(
data: FilePolicyActionData,
file_service: FileService = Depends(get_file_service),
):
return await apply_file_policy_action(data, file_service)
@admin_api.post("/file/policy-action")
async def file_policy_action_post(
data: FilePolicyActionData,
file_service: FileService = Depends(get_file_service),
):
return await apply_file_policy_action(data, file_service)
async def apply_batch_file_policy_action(
data: BatchFilePolicyActionData,
file_service: FileService,
):
if not data.ids:
raise HTTPException(status_code=400, detail="请选择要更新的文件")
download_limit = data.downloadLimit
if download_limit is None:
download_limit = data.download_limit
result = await file_service.apply_files_policy_action(
file_ids=data.ids,
action=data.action,
download_limit=download_limit,
)
return APIResponse(detail=result)
@admin_api.patch("/file/batch-policy-action")
async def file_batch_policy_action(
data: BatchFilePolicyActionData,
file_service: FileService = Depends(get_file_service),
):
return await apply_batch_file_policy_action(data, file_service)
@admin_api.post("/file/batch-policy-action")
async def file_batch_policy_action_post(
data: BatchFilePolicyActionData,
file_service: FileService = Depends(get_file_service),
):
return await apply_batch_file_policy_action(data, file_service)
@admin_api.get("/file/list")
async def file_list(
page: int = 1,
size: int = 10,
keyword: str = "",
status: str = "",
type: str = "",
health: str = "",
sortBy: str = "created_at",
sortOrder: str = "desc",
file_service: FileService = Depends(get_file_service),
):
page = max(page, 1)
size = min(max(size, 1), 100)
files, total, summary = await file_service.list_files(
page,
size,
keyword,
status=status,
file_type=type,
health=health,
sort_by=sortBy,
sort_order=sortOrder,
)
return APIResponse(
detail={
"page": page,
"size": size,
"data": files,
"total": total,
"summary": summary,
}
)
@admin_api.get("/file/detail")
async def file_detail(
id: int,
file_service: FileService = Depends(get_file_service),
):
detail = await file_service.get_file_detail(id)
return APIResponse(detail=detail)
@admin_api.post("/file/detail")
async def file_detail_post(
data: IDData,
file_service: FileService = Depends(get_file_service),
):
detail = await file_service.get_file_detail(data.id)
return APIResponse(detail=detail)
async def update_file_metadata(
data: FileMetadataData,
file_service: FileService,
):
fields_set = data.model_fields_set
update_note = "note" in fields_set
update_tags = "tags" in fields_set
if not update_note and not update_tags:
raise HTTPException(status_code=400, detail="请选择要更新的元数据")
detail = await file_service.update_file_metadata(
file_id=data.id,
note=data.note,
tags=data.tags,
update_note=update_note,
update_tags=update_tags,
)
return APIResponse(detail=detail)
@admin_api.patch("/file/metadata")
async def file_metadata(
data: FileMetadataData,
file_service: FileService = Depends(get_file_service),
):
return await update_file_metadata(data, file_service)
@admin_api.post("/file/metadata")
async def file_metadata_post(
data: FileMetadataData,
file_service: FileService = Depends(get_file_service),
):
return await update_file_metadata(data, file_service)
@admin_api.get("/file/view-presets")
async def file_view_presets(
file_service: FileService = Depends(get_file_service),
):
result = await file_service.list_file_view_presets()
return APIResponse(detail=result)
async def save_file_view_preset(
data: FileViewPresetData,
file_service: FileService,
):
filters = data.filters if data.filters is not None else data.params
preset = await file_service.save_file_view_preset(
preset_id=data.id,
name=data.name,
filters=filters or {},
)
return APIResponse(detail=preset)
@admin_api.post("/file/view-presets")
async def file_view_presets_save(
data: FileViewPresetData,
file_service: FileService = Depends(get_file_service),
):
return await save_file_view_preset(data, file_service)
@admin_api.patch("/file/view-presets")
async def file_view_presets_patch(
data: FileViewPresetData,
file_service: FileService = Depends(get_file_service),
):
return await save_file_view_preset(data, file_service)
async def delete_file_view_preset(
data: FileViewPresetDeleteData,
file_service: FileService,
):
result = await file_service.delete_file_view_preset(data.id)
return APIResponse(detail=result)
@admin_api.delete("/file/view-presets")
async def file_view_presets_delete(
data: FileViewPresetDeleteData,
file_service: FileService = Depends(get_file_service),
):
return await delete_file_view_preset(data, file_service)
@admin_api.post("/file/view-presets/delete")
async def file_view_presets_delete_post(
data: FileViewPresetDeleteData,
file_service: FileService = Depends(get_file_service),
):
return await delete_file_view_preset(data, file_service)
@admin_api.get("/config/get")
async def get_config(
config_service: ConfigService = Depends(get_config_service),
):
return APIResponse(detail=config_service.get_config())
@admin_api.patch("/config/update")
async def update_config(
data: dict,
config_service: ConfigService = Depends(get_config_service),
file_service: FileService = Depends(get_file_service),
):
data.pop("themesChoices", None)
await config_service.update_config(data)
await file_service.record_admin_activity(
action="config.update",
target_type="config",
target_name="system",
count=1,
meta={"fields": sorted(data.keys())},
)
return APIResponse()
@admin_api.get("/file/download")
async def file_download(
id: int,
file_service: FileService = Depends(get_file_service),
):
file_content = await file_service.download_file(id)
return file_content
@admin_api.get("/file/preview")
async def file_preview(
id: int,
maxChars: int = 4000,
file_service: FileService = Depends(get_file_service),
):
preview = await file_service.preview_file(id, maxChars)
return APIResponse(detail=preview)
@admin_api.get("/local/lists")
async def get_local_lists(
local_file_service: LocalFileService = Depends(get_local_file_service),
):
files = await local_file_service.list_files()
return APIResponse(detail=files)
@admin_api.delete("/local/delete")
async def delete_local_file(
item: DeleteItem,
local_file_service: LocalFileService = Depends(get_local_file_service),
file_service: FileService = Depends(get_file_service),
):
result = await local_file_service.delete_file(item.filename)
await file_service.record_admin_activity(
action="local_file.delete",
target_type="local_file",
target_name=item.filename,
count=1,
meta={"success": bool(result)},
)
return APIResponse(detail=result)
@admin_api.post("/local/share")
async def share_local_file(
item: ShareItem,
file_service: FileService = Depends(get_file_service),
):
share_info = await file_service.share_local_file(item)
await file_service.record_admin_activity(
action="local_file.share",
target_type="file",
target_id=share_info.get("id") if isinstance(share_info, dict) else None,
target_name=item.filename,
count=1,
meta={
"expireValue": item.expire_value,
"expireStyle": item.expire_style,
},
)
return APIResponse(detail=share_info)
@admin_api.patch("/file/update")
async def update_file(
data: UpdateFileData,
file_service: FileService = Depends(get_file_service),
):
file_code = await FileCodes.filter(id=data.id).first()
if not file_code:
raise HTTPException(status_code=404, detail="文件不存在")
target_name = file_service._build_file_activity_name(file_code)
update_data = {}
if data.code is not None and data.code != file_code.code:
# 判断code是否存在
if await FileCodes.filter(code=data.code).first():
raise HTTPException(status_code=400, detail="code已存在")
update_data["code"] = data.code
if data.prefix is not None and data.prefix != file_code.prefix:
update_data["prefix"] = data.prefix
if data.suffix is not None and data.suffix != file_code.suffix:
update_data["suffix"] = data.suffix
if (
data.expired_at is not None
and data.expired_at != ""
and data.expired_at != file_code.expired_at
):
update_data["expired_at"] = data.expired_at
if data.expired_count is not None and data.expired_count != file_code.expired_count:
update_data["expired_count"] = data.expired_count
await file_code.update_from_dict(update_data).save()
if update_data:
await file_service.record_admin_activity(
action="file.update",
target_type="file",
target_id=data.id,
target_name=target_name,
count=1,
meta={"fields": sorted(update_data.keys())},
)
return APIResponse(detail="更新成功")
@@ -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);
"""
)
+125
View File
@@ -0,0 +1,125 @@
# @Time : 2023/8/13 20:43
# @Author : Lan
# @File : models.py
# @Software: PyCharm
from typing import Optional
from tortoise.models import Model
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise import fields, models
from datetime import datetime
from core.utils import get_now
class FileCodes(models.Model):
id = fields.IntField(pk=True)
code = fields.CharField(max_length=255, unique=True, index=True)
prefix = fields.CharField(max_length=255, default="")
suffix = fields.CharField(max_length=255, default="")
uuid_file_name = fields.CharField(max_length=255, null=True)
file_path = fields.CharField(max_length=255, null=True)
size = fields.BigIntField(default=0)
text = fields.TextField(null=True)
expired_at = fields.DatetimeField(null=True)
expired_count = fields.IntField(default=0)
used_count = fields.IntField(default=0)
created_at = fields.DatetimeField(auto_now_add=True)
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:
return False
if self.expired_at and self.expired_count < 0:
return self.expired_at < await get_now()
return self.expired_count <= 0
async def get_file_path(self):
return f"{self.file_path}/{self.uuid_file_name}"
class UploadChunk(models.Model):
id = fields.IntField(pk=True)
upload_id = fields.CharField(max_length=36, index=True)
chunk_index = fields.IntField()
chunk_hash = fields.CharField(max_length=64)
total_chunks = fields.IntField()
file_size = fields.BigIntField()
chunk_size = fields.IntField()
file_name = fields.CharField(max_length=255)
save_path = fields.CharField(max_length=512, null=True)
created_at = fields.DatetimeField(auto_now_add=True)
completed = fields.BooleanField(default=False)
class TransferStats(models.Model):
id = fields.IntField(pk=True)
action = fields.CharField(max_length=16, index=True)
file_code_id = fields.IntField(null=True, index=True)
code = fields.CharField(max_length=255, null=True, index=True)
name = fields.CharField(max_length=512, default="")
size = fields.BigIntField(default=0)
ip = fields.CharField(max_length=64, default="")
file_path = fields.CharField(max_length=1024, default="")
expired_at = fields.DatetimeField(null=True)
deleted_at = fields.DatetimeField(null=True, index=True)
meta = fields.TextField(null=True)
created_at = fields.DatetimeField(auto_now_add=True, index=True)
class Meta:
table = "transfer_stats"
class KeyValue(Model):
id: Optional[int] = fields.IntField(pk=True)
key: Optional[str] = fields.CharField(
max_length=255, description="键", index=True, unique=True
)
value: Optional[str] = fields.JSONField(description="值", null=True)
created_at: Optional[datetime] = fields.DatetimeField(
auto_now_add=True, description="创建时间"
)
class PresignUploadSession(models.Model):
"""预签名上传会话模型"""
id = fields.IntField(pk=True)
upload_id = fields.CharField(max_length=36, unique=True, index=True)
file_name = fields.CharField(max_length=255)
file_size = fields.BigIntField()
save_path = fields.CharField(max_length=512)
mode = fields.CharField(max_length=10) # "direct" 或 "proxy"
expire_value = fields.IntField(default=1)
expire_style = fields.CharField(max_length=20, default="day")
created_at = fields.DatetimeField(auto_now_add=True)
expires_at = fields.DatetimeField() # 会话过期时间
async def is_expired(self):
"""检查会话是否已过期"""
return self.expires_at < await get_now()
class StorageReservation(models.Model):
"""尚未写入 FileCodes 的上传容量预留。"""
id = fields.IntField(pk=True)
token = fields.CharField(max_length=64, unique=True, index=True)
size = fields.BigIntField()
expires_at = fields.DatetimeField(index=True)
file_codes_pydantic = pydantic_model_creator(FileCodes, name="FileCodes")
upload_chunk_pydantic = pydantic_model_creator(UploadChunk, name="UploadChunk")
key_value_pydantic = pydantic_model_creator(KeyValue, name="KeyValue")
presign_upload_session_pydantic = pydantic_model_creator(
PresignUploadSession, name="PresignUploadSession"
)
+147
View File
@@ -0,0 +1,147 @@
import datetime
import hashlib
import os
import uuid
from urllib.parse import unquote
from fastapi import UploadFile, HTTPException
from typing import Optional, Tuple
from apps.base.dependencies import IPRateLimit
from apps.base.models import FileCodes
from core.settings import settings
from core.utils import (
get_random_num,
get_random_string,
max_save_times_desc,
sanitize_filename,
get_now,
)
def validate_expire_style(expire_style: str) -> str:
"""校验过期方式是否在管理员配置的白名单内。"""
if expire_style not in settings.expireStyle:
raise HTTPException(status_code=400, detail="过期时间类型错误")
return expire_style
async def get_file_path_name(file: UploadFile) -> Tuple[str, str, str, str, str]:
today = await get_now()
storage_path = settings.storage_path.strip("/")
file_uuid = uuid.uuid4().hex
filename = await sanitize_filename(unquote(file.filename or ""))
base_path = f"share/data/{today.strftime('%Y/%m/%d')}/{file_uuid}"
path = f"{storage_path}/{base_path}" if storage_path else base_path
prefix, suffix = os.path.splitext(filename)
save_path = f"{path}/{filename}"
return path, suffix, prefix, filename, save_path
async def get_chunk_file_path_name(
file_name: str, upload_id: str
) -> Tuple[str, str, str, str, str]:
today = await get_now()
storage_path = settings.storage_path.strip("/")
base_path = f"share/data/{today.strftime('%Y/%m/%d')}/{upload_id}"
path = f"{storage_path}/{base_path}" if storage_path else base_path
prefix, suffix = os.path.splitext(file_name)
save_path = f"{path}/{prefix}{suffix}"
return path, suffix, prefix, file_name, save_path
async def get_expire_info(
expire_value: int, expire_style: str
) -> Tuple[Optional[datetime.datetime], int, int, str]:
expired_count, used_count = -1, 0
now = await get_now()
code = None
max_timedelta = (
datetime.timedelta(seconds=settings.max_save_seconds)
if settings.max_save_seconds > 0
else datetime.timedelta(days=7)
)
detail = (
await max_save_times_desc(settings.max_save_seconds)
if settings.max_save_seconds > 0
else "7天"
)
detail = f"限制最长时间为 {detail[0]},可换用其他方式"
expire_styles = {
"day": lambda: now + datetime.timedelta(days=expire_value),
"hour": lambda: now + datetime.timedelta(hours=expire_value),
"minute": lambda: now + datetime.timedelta(minutes=expire_value),
"count": lambda: (now + datetime.timedelta(days=1), expire_value),
"forever": lambda: (None, None),
}
if expire_style in expire_styles:
result = expire_styles[expire_style]()
if isinstance(result, tuple):
expired_at, extra = result
if expire_style == "count":
expired_count = extra
else:
expired_at = result
if expired_at and expired_at - now > max_timedelta:
raise HTTPException(status_code=403, detail=detail)
else:
expired_at = now + datetime.timedelta(days=1)
if not code:
code = await get_random_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:
code_generate_type = getattr(settings, "code_generate_type", "secret")
if code_generate_type in {"secret", "string"}:
return "secret"
return "number"
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"
for _ in range(CODE_MAX_ATTEMPTS):
code = (
await get_random_num(CODE_LENGTH)
if code_style == "number"
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:
sha = hashlib.sha256()
await file.seek(0)
while True:
chunk = await file.read(chunk_size)
if not chunk:
break
sha.update(chunk)
await file.seek(0)
return sha.hexdigest()
ip_limit = {
"error": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
"metadata": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
"upload": IPRateLimit(count=settings.uploadCount, minutes=settings.uploadMinute),
"login": IPRateLimit(count=settings.loginCount, minutes=settings.loginMinute),
}
+1004
View File
File diff suppressed because it is too large. Load diff
+1393
View File
File diff suppressed because it is too large. Load diff
+138
View File
@@ -0,0 +1,138 @@
# @Time : 2023/8/15 22:00
# @Author : Lan
# @File : tasks.py
# @Software: PyCharm
import asyncio
import datetime
import logging
import os
from tortoise.expressions import Q
from apps.base.models import (
FileCodes,
PresignUploadSession,
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
from core.storage import FileStorageInterface, storages
from core.utils import get_now
async def delete_expire_files():
while True:
try:
await refresh_settings()
file_storage: FileStorageInterface = storages[settings.file_storage]()
# 遍历 share目录下的所有文件夹,删除空的文件夹,并判断父目录是否为空,如果为空也删除
if settings.file_storage == "local":
for root, dirs, files in os.walk(f"{data_root}/share/data"):
if not dirs and not files:
os.rmdir(root)
await ip_limit["error"].remove_expired_ip()
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(
is_trashed=False,
).filter(Q(expired_at__lt=await get_now()) | Q(expired_count=0)).all()
for exp in expire_data:
try:
await file_service.move_to_trash(exp, reason="expired")
except Exception as 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 file_service.purge_trashed_file(item)
except Exception as e:
logging.error(f"彻底清理回收站文件失败 id={item.id}: {e}")
except Exception as e:
logging.error(e)
finally:
await asyncio.sleep(600)
async def clean_incomplete_uploads():
while True:
try:
await refresh_settings()
file_storage: FileStorageInterface = storages[settings.file_storage]()
expire_hours = getattr(settings, "chunk_expire_hours", 24)
now = await get_now()
expire_time = now - datetime.timedelta(hours=expire_hours)
expired_sessions = await UploadChunk.filter(
chunk_index=-1, created_at__lt=expire_time
).all()
for session in expired_sessions:
try:
save_path = session.save_path
if not save_path:
_, _, _, _, save_path = await get_chunk_file_path_name(
session.file_name, session.upload_id
)
await file_storage.clean_chunks(session.upload_id, save_path)
except Exception as e:
logging.error(
f"清理分片文件失败 upload_id={session.upload_id}: {e}"
)
try:
await UploadChunk.filter(upload_id=session.upload_id).delete()
await StorageReservation.filter(
token=f"chunk:{session.upload_id}"
).delete()
logging.info(f"已清理过期上传会话 upload_id={session.upload_id}")
except Exception as e:
logging.error(
f"删除分片记录失败 upload_id={session.upload_id}: {e}"
)
except Exception as e:
logging.error(f"清理未完成上传任务异常: {e}")
finally:
await asyncio.sleep(3600)
async def clean_expired_presign_sessions():
while True:
try:
await refresh_settings()
storage: FileStorageInterface = storages[settings.file_storage]()
now = await get_now()
expired_sessions = await PresignUploadSession.filter(
expires_at__lt=now
).all()
for session in expired_sessions:
if session.mode == "direct":
try:
if await storage.file_exists(session.save_path):
await storage.delete_file(
FileCodes(
file_path=os.path.dirname(session.save_path),
uuid_file_name=os.path.basename(session.save_path),
)
)
except Exception as e:
logging.error(
"清理过期直传文件失败 "
f"upload_id={session.upload_id}: {e}"
)
await StorageReservation.filter(
token=f"presign:{session.upload_id}"
).delete()
await session.delete()
except Exception as e:
logging.error(f"清理过期预签名会话异常: {e}")
finally:
await asyncio.sleep(900)
+164
View File
@@ -0,0 +1,164 @@
# @Time : 2023/8/13 19:54
# @Author : Lan
# @File : utils.py
# @Software: PyCharm
import datetime
import hashlib
import hmac
import os
import re
import secrets
import time
from core.settings import settings
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)
# 排除 0/O、1/I/L,避免人工输入取件码时混淆。
r_s = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
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():
"""
获取当前时间
:return:
"""
return datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8)))
async def get_select_token(code: str, offset: int = 0):
"""
获取下载token
:param code: 取件码
:param offset: 时间窗口偏移(0=当前窗口,1=上一个窗口)。
用于兼容窗口边界竞态:用户在某窗口末尾获取的 token,
请求到达服务器时可能已进入下一窗口。
:return:
"""
token = getattr(settings, "jwt_secret", "")
if not token:
raise RuntimeError("应用签名密钥未初始化")
# 每个窗口约 1000 秒;offset 允许校验上一窗口,避免边界竞态
time_factor = int(time.time() / 1000) - max(0, int(offset))
return hashlib.sha256(
f"{code}{time_factor}000{token}".encode()
).hexdigest()
async def get_file_url(code: str):
"""
对于需要通过服务器中转下载的服务,获取文件下载地址
:param code:
:return:
"""
return f"/share/download?key={await get_select_token(code)}&code={code}"
async def max_save_times_desc(max_save_seconds: int):
"""
获取最大保存时间的描述
:param max_save_seconds:
:return:
"""
def gen_desc_zh(value: int, desc: str):
if value > 0:
return f"{value}{desc}"
else:
return ""
def gen_desc_en(value: int, desc: str):
if value > 0:
ret = f"{value} {desc}"
if value > 1:
ret += "s"
ret += " "
return ret
else:
return ""
max_timedelta = datetime.timedelta(seconds=max_save_seconds)
desc_zh, desc_en = "最长保存时间:", "Max save time: "
desc_zh += gen_desc_zh(max_timedelta.days, "天")
desc_en += gen_desc_en(max_timedelta.days, "day")
desc_zh += gen_desc_zh(max_timedelta.seconds // 3600, "小时")
desc_en += gen_desc_en(max_timedelta.seconds // 3600, "hour")
desc_zh += gen_desc_zh(max_timedelta.seconds % 3600 // 60, "分钟")
desc_en += gen_desc_en(max_timedelta.seconds % 3600 // 60, "minute")
desc_zh += gen_desc_zh(max_timedelta.seconds % 60, "秒")
desc_en += gen_desc_en(max_timedelta.seconds % 60, "second")
return desc_zh, desc_en
def hash_password(password: str) -> str:
"""
使用 SHA256 + salt 哈希密码
返回格式: sha256$<salt>$<hash>
"""
salt = os.urandom(16).hex()
password_hash = hashlib.sha256(f"{salt}{password}".encode()).hexdigest()
return f"sha256${salt}${password_hash}"
def verify_password(password: str, hashed: str) -> bool:
"""
验证密码是否匹配
支持新格式 (sha256$salt$hash) 和旧格式 (明文)
"""
if not hashed:
return False
# 新格式: sha256$salt$hash
if hashed.startswith("sha256$"):
parts = hashed.split("$")
if len(parts) != 3:
return False
_, salt, stored_hash = parts
password_hash = hashlib.sha256(f"{salt}{password}".encode()).hexdigest()
return hmac.compare_digest(password_hash, stored_hash)
# 旧格式: 明文比较 (兼容迁移前的数据)
return hmac.compare_digest(str(password), str(hashed))
def is_password_hashed(password: str) -> bool:
"""
检查密码是否已经是哈希格式
"""
return password.startswith("sha256$") and len(password.split("$")) == 3
async def sanitize_filename(filename: str) -> str:
"""
安全处理文件名:
1. 剥离路径只保留文件名
2. 替换非法字符
3. 处理空文件名情况
"""
filename = os.path.basename(filename)
illegal_chars = r'[\\/*?:"<>|\x00-\x1F]' # 包含控制字符
# 替换非法字符为下划线
cleaned = re.sub(illegal_chars, "_", filename)
# 处理空格(可选替换为_)
cleaned = cleaned.replace(" ", "_")
# 处理连续下划线
cleaned = re.sub(r"_+", "_", cleaned)
# 处理首尾特殊字符
cleaned = cleaned.strip("._")
# 处理空文件名情况
if not cleaned:
cleaned = "unnamed_file"
# 长度限制(按需调整)
return cleaned[:255]
+177
View File
@@ -0,0 +1,177 @@
#!/usr/bin/env python3
from pathlib import Path
import gzip
import re
ASSETS_ROOT = Path('/app')
def rewrite(path: Path, text: str) -> None:
path.write_text(text, encoding='utf-8')
gz_path = path.with_suffix(path.suffix + '.gz')
if gz_path.exists():
with gzip.open(gz_path, 'wb', compresslevel=9) as gz:
gz.write(text.encode('utf-8'))
def patch_file_manage(path: Path) -> bool:
text = path.read_text(encoding='utf-8')
old = text
if 'detailTimeline:It(s.timeline||[])' in text and 'fcbxTimelineCollapsed' not in text:
text = text.replace(
'detailTimeline:It(s.timeline||[])}},nt=t=>',
'detailTimeline:It(s.timeline||[]),fcbxTimelineCollapsed:!0}},nt=t=>',
1,
)
render_old = 'N(e(b).detailTimeline,(n,K)=>(p(),f("div",{key:`${n.key}-${K}`,class:"grid grid-cols-[auto_minmax(0,1fr)] gap-3"}'
render_new = 'N((e(b).fcbxTimelineCollapsed&&e(b).detailTimeline.filter(ga=>ga.key==="retrieved_event").length>3)?e(b).detailTimeline.filter((ga,Qa)=>ga.key!=="retrieved_event"||e(b).detailTimeline.filter(Ja=>Ja.key==="retrieved_event").indexOf(ga)<3):e(b).detailTimeline,(n,K)=>(p(),f("div",{key:`${n.key}-${K}`,class:"grid grid-cols-[auto_minmax(0,1fr)] gap-3"}'
if render_old in text and 'ga.key==="retrieved_event"' not in text:
text = text.replace(render_old, render_new, 1)
close_old = ']))),128))],2)])):j("",!0),l("section",kn,'
close_new = ']))),128)),e(b).detailTimeline.filter(n=>n.key==="retrieved_event").length>3?(p(),f("button",{key:0,type:"button",class:o(["mt-3 rounded-lg border px-3 py-2 text-sm font-medium transition",[e(u)?"border-gray-600 text-gray-200 hover:bg-gray-700":"border-gray-200 text-gray-700 hover:bg-gray-50"]]),onClick:m[99]||(m[99]=n=>e(b).fcbxTimelineCollapsed=!e(b).fcbxTimelineCollapsed)},r(e(b).fcbxTimelineCollapsed?`展开全部取件记录(共 ${e(b).detailTimeline.filter(n=>n.key==="retrieved_event").length} 次)":"收起取件记录"),3)):j("",!0)],2)])):j("",!0),l("section",kn,'
if close_old in text and '展开全部取件记录' not in text:
text = text.replace(close_old, close_new, 1)
if text != old:
rewrite(path, text)
return True
return False
def patch_clipboard(path: Path) -> bool:
text = path.read_text(encoding='utf-8')
old = 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
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 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');
if (!title || !LIFE_RE.test(title.textContent || '')) return null;
const box = title.nextElementSibling;
if (!box) return null;
return { title, box };
};
const getRows = section => {
const ctx = getSection(section);
if (!ctx) return [];
return [...ctx.box.querySelectorAll(':scope > .fcb-expand-content')];
};
const apply = section => {
const ctx = getSection(section);
if (!ctx) 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;
events.forEach((row, idx) => {
row.classList.add('fcbx-retrieval-event');
row.style.display = expanded || idx < 3 ? '' : 'none';
});
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);
};
ctx.box.parentNode.insertBefore(button, ctx.box);
}
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(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(() => 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.
html = html.replace('<script src="assets/fcb-detail-collapse.js?v=20260709"></script>\n', '')
html = html.replace('<script src="assets/fcb-detail-collapse.js?v=20260709"></script>', '')
html = html.replace('<script src="assets/fcb-lifecycle-collapse.js?v=20260709-2"></script>\n', '')
html = html.replace('<script src="assets/fcb-lifecycle-collapse.js?v=20260709-2"></script>', '')
tag = '<script src="assets/fcb-lifecycle-collapse-v3.js"></script>'
if 'fcb-lifecycle-collapse-v3.js' not in html:
html = html.replace('</body>', tag + '\n</body>') if '</body>' in html else html + '\n' + tag + '\n'
index.write_text(html, encoding='utf-8')
gz = index.with_suffix(index.suffix + '.gz')
if gz.exists():
with gzip.open(gz, 'wb', compresslevel=9) as fh:
fh.write(html.encode('utf-8'))
return True
def main() -> None:
changed = []
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))
if __name__ == '__main__':
main()
+24
View File
@@ -0,0 +1,24 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import ts from 'typescript'
const root = new URL('../', import.meta.url)
test('entry must not truncate new codes or submit before typing is complete', () => {
const form = readFileSync(new URL('src/components/common/RetrieveForm.vue', root), 'utf8')
const view = readFileSync(new URL('src/views/RetrievewFileView.vue', root), 'utf8')
assert.ok(!form.includes('maxlength="5"'), '8-character code is truncated')
assert.ok(!view.includes('watch(code,'), 'typing a legacy prefix must not consume a retrieval')
})
test('legacy/new codes and URL extraction preserve literal code', async () => {
const source = readFileSync(new URL('src/utils/retrieval-code.ts', root), 'utf8')
const js = ts.transpile(source, {module:ts.ModuleKind.ESNext,target:ts.ScriptTarget.ES2022})
const {parseRetrievalCode, isValidRetrievalCode} = await import('data:text/javascript;base64,'+Buffer.from(js).toString('base64'))
for (const code of ['01234','aB12C','00123456','Ab12Cd34']) {
assert.equal(parseRetrievalCode(' '+code+' '),code)
assert.equal(parseRetrievalCode('https://files.example/#/?code='+code),code)
assert.equal(parseRetrievalCode('https://files.example/?code='+code),code)
assert.equal(isValidRetrievalCode(code),true)
}
for (const code of ['1234','123456','1234567','123456789','12 34','../../foo']) assert.equal(isValidRetrievalCode(code),false)
assert.equal(parseRetrievalCode('https://files.example/?code=bad#/?code=01234'),'')
})
+27
View File
@@ -0,0 +1,27 @@
import assert from 'node:assert/strict'
import test from 'node:test'
const body = { style: { overflow: 'scroll' } }
globalThis.document = { body }
const { lockBodyScroll, unlockBodyScroll } = await import('../src/components/common/scrollLock.ts')
test('restores overflow only after the owning lock is released', () => {
const first = lockBodyScroll()
const second = lockBodyScroll()
unlockBodyScroll(Symbol('unrelated'))
assert.equal(body.style.overflow, 'hidden')
unlockBodyScroll(first)
assert.equal(body.style.overflow, 'hidden')
unlockBodyScroll(second)
assert.equal(body.style.overflow, 'scroll')
})
test('releasing an owner twice cannot unlock another owner', () => {
const first = lockBodyScroll()
const second = lockBodyScroll()
unlockBodyScroll(first)
unlockBodyScroll(first)
assert.equal(body.style.overflow, 'hidden')
unlockBodyScroll(second)
assert.equal(body.style.overflow, 'scroll')
})
+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
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()