mirror of
https://github.com/vastsa/FileCodeBox.git
synced 2026-11-20 13:29:56 +08:00
Compare commits
45
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1ec397af0c | ||
|
|
eb6fc627ae | ||
|
|
c1fb802223 | ||
|
|
1d03337e2f | ||
|
|
8d6eaacb70 | ||
|
|
3fe136536e | ||
|
|
aa6904a12c | ||
|
|
135dfdda9d | ||
|
|
e3ea7825bf | ||
|
|
6759539078 | ||
|
|
530f52aa1e | ||
|
|
b859ec211e | ||
|
|
8ac367d0b8 | ||
|
|
63cf725802 | ||
|
|
ccbc710d74 | ||
|
|
2d18b02005 | ||
|
|
e75fe596d0 | ||
|
|
be7ce2b30e | ||
|
|
0dbb594f4a | ||
|
|
b6aa28c345 | ||
|
|
fc6046a663 | ||
|
|
3467e973ac | ||
|
|
a1de598277 | ||
|
|
1ba0d2a044 | ||
|
|
1f0b0b791c | ||
|
|
4ae53fc4a5 | ||
|
|
35e069ccc3 | ||
|
|
2fa1faebe0 | ||
|
|
0ced9b1f38 | ||
|
|
1eb69e4cc5 | ||
|
|
71fc1ad8ea | ||
|
|
64ebc59a84 | ||
|
|
78b1dbe81f | ||
|
|
6805206efd | ||
|
|
6fe68be2dd | ||
|
|
0d71b914e4 | ||
|
|
20fcf0c3df | ||
|
|
75d345e5d0 | ||
|
|
a0c453b014 | ||
|
|
1cc901d2b9 | ||
|
|
e7b5792602 | ||
|
|
843a237fad | ||
|
|
4a9bf3a3a0 | ||
|
|
c380778336 | ||
|
|
f1c09b0b20 |
No files matched your search
+6
-9
@@ -3,13 +3,16 @@ FROM node:20-alpine AS frontend-builder
|
||||
|
||||
RUN apk add --no-cache git python3 make g++
|
||||
|
||||
RUN corepack enable && \
|
||||
corepack prepare pnpm@9.15.9 --activate
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
# 克隆并构建 2024 主题
|
||||
RUN git clone --depth 1 https://github.com/vastsa/FileCodeBoxFronted.git /build/fronted-2024 && \
|
||||
cd /build/fronted-2024 && \
|
||||
npm install && \
|
||||
npm run build
|
||||
pnpm install --frozen-lockfile --prod=false && \
|
||||
pnpm run build
|
||||
|
||||
# 克隆并构建 2023 主题
|
||||
RUN git clone --depth 1 https://github.com/vastsa/FileCodeBoxFronted2023.git /build/fronted-2023 && \
|
||||
@@ -47,10 +50,4 @@ ENV HOST="0.0.0.0" \
|
||||
EXPOSE 12345
|
||||
|
||||
# 生产环境启动命令
|
||||
CMD uvicorn main:app \
|
||||
--host $HOST \
|
||||
--port $PORT \
|
||||
--workers $WORKERS \
|
||||
--log-level $LOG_LEVEL \
|
||||
--proxy-headers \
|
||||
--forwarded-allow-ips "*"
|
||||
CMD ["sh", "-c", "exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" --proxy-headers --forwarded-allow-ips '*'"]
|
||||
@@ -85,6 +85,18 @@ def _require_admin_payload(authorization: str) -> dict:
|
||||
return payload
|
||||
|
||||
|
||||
def get_admin_session(authorization: str = Header(default=None)) -> dict:
|
||||
token = _extract_bearer_token(authorization)
|
||||
payload = _require_admin_payload(authorization)
|
||||
return {
|
||||
"id": "admin",
|
||||
"username": "admin",
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": payload.get("exp"),
|
||||
}
|
||||
|
||||
|
||||
ADMIN_PUBLIC_ENDPOINTS = {("POST", "/admin/login")}
|
||||
|
||||
|
||||
|
||||
+44
-1
@@ -1,5 +1,5 @@
|
||||
import datetime
|
||||
from typing import Optional, Union
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
@@ -8,6 +8,10 @@ class IDData(BaseModel):
|
||||
id: int
|
||||
|
||||
|
||||
class IDsData(BaseModel):
|
||||
ids: list[int]
|
||||
|
||||
|
||||
class ShareItem(BaseModel):
|
||||
expire_value: int
|
||||
expire_style: str = "day"
|
||||
@@ -29,3 +33,42 @@ class UpdateFileData(BaseModel):
|
||||
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 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
|
||||
+1479
-41
File diff suppressed because it is too large.
Load diff
+446
-11
@@ -3,16 +3,32 @@
|
||||
# @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, ShareItem, DeleteItem, LoginData, UpdateFileData
|
||||
from apps.admin.schemas import (
|
||||
IDData,
|
||||
IDsData,
|
||||
BatchUpdateFileData,
|
||||
BatchFilePolicyActionData,
|
||||
FilePolicyActionData,
|
||||
FileMetadataData,
|
||||
FileViewPresetData,
|
||||
FileViewPresetDeleteData,
|
||||
ShareItem,
|
||||
DeleteItem,
|
||||
LoginData,
|
||||
UpdateFileData,
|
||||
)
|
||||
from core.response import APIResponse
|
||||
from apps.base.models import FileCodes, KeyValue
|
||||
from apps.admin.dependencies import create_token
|
||||
@@ -24,6 +40,14 @@ admin_api = APIRouter(
|
||||
)
|
||||
|
||||
|
||||
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):
|
||||
if not verify_password(data.password, settings.admin_token):
|
||||
@@ -33,10 +57,37 @@ async def login(data: LoginData):
|
||||
return APIResponse(detail={"token": token, "token_type": "Bearer"})
|
||||
|
||||
|
||||
@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():
|
||||
async def dashboard(file_service: FileService = Depends(get_file_service)):
|
||||
all_codes = await FileCodes.all()
|
||||
all_size = str(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()
|
||||
now = await get_now()
|
||||
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
@@ -46,19 +97,83 @@ async def dashboard():
|
||||
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": all_size,
|
||||
"sysUptime": sys_start.value,
|
||||
"yesterdayCount": await yesterday_codes.count(),
|
||||
"yesterdaySize": str(sum([code.size for code in await yesterday_codes])),
|
||||
"todayCount": await today_codes.count(),
|
||||
"todaySize": str(sum([code.size for code in await today_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(
|
||||
limit: int = 20,
|
||||
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(
|
||||
limit=limit,
|
||||
action=action,
|
||||
target_type=_pick_query_text(targetType, target_type),
|
||||
keyword=keyword,
|
||||
)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.delete("/file/delete")
|
||||
async def file_delete(
|
||||
data: IDData,
|
||||
@@ -68,24 +183,296 @@ async def file_delete(
|
||||
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)
|
||||
|
||||
|
||||
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),
|
||||
):
|
||||
files, total = await file_service.list_files(page, size, keyword)
|
||||
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),
|
||||
@@ -97,9 +484,17 @@ async def get_config(
|
||||
async def update_config(
|
||||
data: dict,
|
||||
config_service: ConfigService = Depends(get_config_service),
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
data.pop("themesChoices")
|
||||
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()
|
||||
|
||||
|
||||
@@ -112,6 +507,16 @@ async def file_download(
|
||||
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),
|
||||
@@ -124,8 +529,16 @@ async def get_local_lists(
|
||||
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)
|
||||
|
||||
|
||||
@@ -135,16 +548,29 @@ async def share_local_file(
|
||||
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:
|
||||
@@ -166,4 +592,13 @@ async def update_file(
|
||||
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,72 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
def _need_upgrade(columns: list[tuple]) -> bool:
|
||||
for column in columns:
|
||||
# PRAGMA table_info 返回 (cid, name, type, notnull, dflt_value, pk)
|
||||
if column[1] == "size":
|
||||
column_type = (column[2] or "").upper()
|
||||
return "BIGINT" not in column_type
|
||||
return False
|
||||
|
||||
|
||||
async def migrate():
|
||||
conn = connections.get("default")
|
||||
result = await conn.execute_query("PRAGMA table_info(filecodes)")
|
||||
columns = result[1] if result and len(result) > 1 else []
|
||||
|
||||
if not columns or not _need_upgrade(columns):
|
||||
return
|
||||
|
||||
await conn.execute_script(
|
||||
"""
|
||||
BEGIN;
|
||||
CREATE TABLE IF NOT EXISTS filecodes_new
|
||||
(
|
||||
id INTEGER not null
|
||||
primary key autoincrement,
|
||||
code VARCHAR(255) not null
|
||||
unique,
|
||||
prefix VARCHAR(255) default '' not null,
|
||||
suffix VARCHAR(255) default '' not null,
|
||||
uuid_file_name VARCHAR(255),
|
||||
file_path VARCHAR(255),
|
||||
size BIGINT default 0 not null,
|
||||
text TEXT,
|
||||
expired_at TIMESTAMP,
|
||||
expired_count INT default 0 not null,
|
||||
used_count INT default 0 not null,
|
||||
created_at TIMESTAMP default CURRENT_TIMESTAMP not null,
|
||||
file_hash VARCHAR(128),
|
||||
is_chunked BOOL default False not null,
|
||||
upload_id VARCHAR(128)
|
||||
);
|
||||
|
||||
INSERT INTO filecodes_new (id, code, prefix, suffix, uuid_file_name, file_path, size, text,
|
||||
expired_at, expired_count, used_count, created_at, file_hash,
|
||||
is_chunked, upload_id)
|
||||
SELECT id,
|
||||
code,
|
||||
prefix,
|
||||
suffix,
|
||||
uuid_file_name,
|
||||
file_path,
|
||||
size,
|
||||
text,
|
||||
expired_at,
|
||||
expired_count,
|
||||
used_count,
|
||||
created_at,
|
||||
file_hash,
|
||||
is_chunked,
|
||||
upload_id
|
||||
FROM filecodes;
|
||||
|
||||
DROP TABLE filecodes;
|
||||
ALTER TABLE filecodes_new
|
||||
RENAME TO filecodes;
|
||||
CREATE INDEX IF NOT EXISTS idx_filecodes_code_1c7ee7
|
||||
on filecodes (code);
|
||||
COMMIT;
|
||||
"""
|
||||
)
|
||||
+1
-1
@@ -19,7 +19,7 @@ class FileCodes(models.Model):
|
||||
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.IntField(default=0)
|
||||
size = fields.BigIntField(default=0)
|
||||
text = fields.TextField(null=True)
|
||||
expired_at = fields.DatetimeField(null=True)
|
||||
expired_count = fields.IntField(default=0)
|
||||
|
||||
+154
-25
@@ -1,4 +1,5 @@
|
||||
import datetime
|
||||
from fnmatch import fnmatchcase
|
||||
import hashlib
|
||||
import os
|
||||
import uuid
|
||||
@@ -7,7 +8,8 @@ from urllib.parse import unquote
|
||||
|
||||
from typing import Optional, Tuple, Union
|
||||
|
||||
from fastapi import APIRouter, Form, UploadFile, File, Depends, HTTPException
|
||||
from fastapi import APIRouter, Form, Request, UploadFile, File, Depends, HTTPException
|
||||
from pydantic import BaseModel, ValidationError
|
||||
from starlette import status
|
||||
|
||||
from apps.admin.dependencies import share_required_login
|
||||
@@ -95,10 +97,46 @@ async def validate_file_size(file: UploadFile, max_size: int) -> int:
|
||||
return size
|
||||
|
||||
|
||||
def normalize_allowed_file_types() -> list[str]:
|
||||
raw_value = settings.allowed_file_types
|
||||
if isinstance(raw_value, str):
|
||||
values = raw_value.replace(";", ",").split(",")
|
||||
elif isinstance(raw_value, (list, tuple, set)):
|
||||
values = raw_value
|
||||
else:
|
||||
values = []
|
||||
|
||||
allowed = [str(item).strip().lower() for item in values if str(item).strip()]
|
||||
return allowed or ["*"]
|
||||
|
||||
|
||||
def validate_file_type(file_name: str, content_type: Optional[str] = None) -> None:
|
||||
allowed = normalize_allowed_file_types()
|
||||
if "*" in allowed or "*/*" in allowed:
|
||||
return
|
||||
|
||||
normalized_name = file_name.strip().lower()
|
||||
normalized_content_type = (content_type or "").strip().lower()
|
||||
|
||||
for rule in allowed:
|
||||
if "/" in rule and fnmatchcase(normalized_content_type, rule):
|
||||
return
|
||||
|
||||
extension = rule if rule.startswith(".") else f".{rule}"
|
||||
if normalized_name.endswith(extension):
|
||||
return
|
||||
|
||||
raise HTTPException(status_code=403, detail="不允许上传该类型文件")
|
||||
|
||||
|
||||
async def create_file_code(code, **kwargs):
|
||||
return await FileCodes.create(code=code, **kwargs)
|
||||
|
||||
|
||||
def normalize_share_code(code: str) -> str:
|
||||
return str(code or "").strip()
|
||||
|
||||
|
||||
@share_api.post("/text/", dependencies=[Depends(share_required_login)])
|
||||
async def share_text(
|
||||
text: str = Form(...),
|
||||
@@ -135,6 +173,7 @@ async def share_file(
|
||||
ip: str = Depends(ip_limit["upload"]),
|
||||
):
|
||||
file_size = await validate_file_size(file, settings.uploadSize)
|
||||
validate_file_type(file.filename or "", file.content_type)
|
||||
if expire_style not in settings.expireStyle:
|
||||
raise HTTPException(status_code=400, detail="过期时间类型错误")
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(
|
||||
@@ -161,7 +200,10 @@ async def share_file(
|
||||
async def get_code_file_by_code(
|
||||
code: str, check: bool = True
|
||||
) -> Tuple[bool, Union[FileCodes, str]]:
|
||||
file_code = await FileCodes.filter(code=code).first()
|
||||
normalized_code = normalize_share_code(code)
|
||||
if not normalized_code:
|
||||
return False, "文件不存在"
|
||||
file_code = await FileCodes.filter(code=normalized_code).first()
|
||||
if not file_code:
|
||||
return False, "文件不存在"
|
||||
if await file_code.is_expired() and check:
|
||||
@@ -176,6 +218,64 @@ async def update_file_usage(file_code: FileCodes) -> None:
|
||||
await file_code.save()
|
||||
|
||||
|
||||
def build_file_metadata(file_code: FileCodes) -> dict:
|
||||
is_text = file_code.text is not None
|
||||
remaining_downloads = (
|
||||
file_code.expired_count if file_code.expired_count > 0 else None
|
||||
)
|
||||
return {
|
||||
"code": file_code.code,
|
||||
"name": file_code.prefix + file_code.suffix,
|
||||
"size": file_code.size,
|
||||
"type": "text" if is_text else "file",
|
||||
"is_text": is_text,
|
||||
"created_at": file_code.created_at,
|
||||
"expired_at": file_code.expired_at,
|
||||
"expires_at": file_code.expired_at,
|
||||
"expired_count": file_code.expired_count,
|
||||
"used_count": file_code.used_count,
|
||||
"remaining_downloads": remaining_downloads,
|
||||
}
|
||||
|
||||
|
||||
async def build_select_detail(
|
||||
file_code: FileCodes, file_storage: FileStorageInterface
|
||||
) -> dict:
|
||||
metadata = build_file_metadata(file_code)
|
||||
download_url = (
|
||||
None if file_code.text is not None else await file_storage.get_file_url(file_code)
|
||||
)
|
||||
content = file_code.text if file_code.text is not None else None
|
||||
return {
|
||||
**metadata,
|
||||
"text": content if content is not None else download_url,
|
||||
"content": content,
|
||||
"download_url": download_url,
|
||||
}
|
||||
|
||||
|
||||
@share_api.get("/metadata/")
|
||||
async def get_file_metadata(code: str, ip: str = Depends(ip_limit["error"])):
|
||||
has, file_code = await get_code_file_by_code(code)
|
||||
if not has:
|
||||
ip_limit["error"].add_ip(ip)
|
||||
return APIResponse(code=404, detail=file_code)
|
||||
|
||||
assert isinstance(file_code, FileCodes)
|
||||
return APIResponse(detail=build_file_metadata(file_code))
|
||||
|
||||
|
||||
@share_api.post("/metadata/")
|
||||
async def post_file_metadata(data: SelectFileModel, ip: str = Depends(ip_limit["error"])):
|
||||
has, file_code = await get_code_file_by_code(data.code)
|
||||
if not has:
|
||||
ip_limit["error"].add_ip(ip)
|
||||
return APIResponse(code=404, detail=file_code)
|
||||
|
||||
assert isinstance(file_code, FileCodes)
|
||||
return APIResponse(detail=build_file_metadata(file_code))
|
||||
|
||||
|
||||
@share_api.get("/select/")
|
||||
async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])):
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
@@ -199,27 +299,17 @@ async def select_file(data: SelectFileModel, ip: str = Depends(ip_limit["error"]
|
||||
|
||||
assert isinstance(file_code, FileCodes)
|
||||
await update_file_usage(file_code)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"code": file_code.code,
|
||||
"name": file_code.prefix + file_code.suffix,
|
||||
"size": file_code.size,
|
||||
"text": (
|
||||
file_code.text
|
||||
if file_code.text is not None
|
||||
else await file_storage.get_file_url(file_code)
|
||||
),
|
||||
}
|
||||
)
|
||||
return APIResponse(detail=await build_select_detail(file_code, file_storage))
|
||||
|
||||
|
||||
@share_api.get("/download")
|
||||
async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"])):
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
if await get_select_token(code) != key:
|
||||
normalized_code = normalize_share_code(code)
|
||||
if await get_select_token(normalized_code) != key:
|
||||
ip_limit["error"].add_ip(ip)
|
||||
raise HTTPException(status_code=403, detail="下载鉴权失败")
|
||||
has, file_code = await get_code_file_by_code(code, False)
|
||||
has, file_code = await get_code_file_by_code(normalized_code, False)
|
||||
if not has:
|
||||
return APIResponse(code=404, detail="文件不存在")
|
||||
assert isinstance(file_code, FileCodes)
|
||||
@@ -233,8 +323,31 @@ async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"]
|
||||
chunk_api = APIRouter(prefix="/chunk", tags=["切片"])
|
||||
|
||||
|
||||
async def parse_body_model(request: Request, model_class: type[BaseModel]):
|
||||
content_type = request.headers.get("content-type", "").lower()
|
||||
try:
|
||||
if "application/x-www-form-urlencoded" in content_type or "multipart/form-data" in content_type:
|
||||
payload = dict(await request.form())
|
||||
else:
|
||||
payload = await request.json()
|
||||
return model_class.model_validate(payload)
|
||||
except ValidationError as e:
|
||||
raise HTTPException(status_code=422, detail=e.errors())
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="请求体格式错误")
|
||||
|
||||
|
||||
async def parse_init_chunk_upload(request: Request) -> InitChunkUploadModel:
|
||||
return await parse_body_model(request, InitChunkUploadModel)
|
||||
|
||||
|
||||
async def parse_complete_upload(request: Request) -> CompleteUploadModel:
|
||||
return await parse_body_model(request, CompleteUploadModel)
|
||||
|
||||
|
||||
@chunk_api.post("/upload/init/", dependencies=[Depends(share_required_login)])
|
||||
async def init_chunk_upload(data: InitChunkUploadModel):
|
||||
async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chunk_upload)):
|
||||
validate_file_type(data.file_name)
|
||||
# 服务端校验:根据 total_chunks * chunk_size 计算理论最大上传量
|
||||
total_chunks = (data.file_size + data.chunk_size - 1) // data.chunk_size
|
||||
max_possible_size = total_chunks * data.chunk_size
|
||||
@@ -444,7 +557,9 @@ async def get_upload_status(upload_id: str):
|
||||
"/upload/complete/{upload_id}", dependencies=[Depends(share_required_login)]
|
||||
)
|
||||
async def complete_upload(
|
||||
upload_id: str, data: CompleteUploadModel, ip: str = Depends(ip_limit["upload"])
|
||||
upload_id: str,
|
||||
data: CompleteUploadModel = Depends(parse_complete_upload),
|
||||
ip: str = Depends(ip_limit["upload"]),
|
||||
):
|
||||
# 获取上传基本信息
|
||||
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||
@@ -524,6 +639,14 @@ presign_api = APIRouter(prefix="/presign", tags=["预签名上传"])
|
||||
PRESIGN_SESSION_EXPIRES = 900 # 15分钟
|
||||
|
||||
|
||||
def build_proxy_upload_urls(upload_id: str) -> dict:
|
||||
proxy_upload_url = f"/presign/upload/proxy/{upload_id}"
|
||||
return {
|
||||
"proxy_upload_url": proxy_upload_url,
|
||||
"legacy_proxy_upload_url": f"/api{proxy_upload_url}",
|
||||
}
|
||||
|
||||
|
||||
async def _get_valid_session(
|
||||
upload_id: str, expected_mode: Optional[str] = None
|
||||
) -> PresignUploadSession:
|
||||
@@ -544,6 +667,7 @@ async def presign_upload_init(
|
||||
data: PresignUploadInitRequest, ip: str = Depends(ip_limit["upload"])
|
||||
):
|
||||
"""初始化预签名上传,S3返回直传URL,其他存储返回代理URL"""
|
||||
validate_file_type(data.file_name)
|
||||
if data.file_size > settings.uploadSize:
|
||||
raise HTTPException(
|
||||
403,
|
||||
@@ -563,7 +687,8 @@ async def presign_upload_init(
|
||||
)
|
||||
|
||||
mode = "direct" if presigned_url else "proxy"
|
||||
upload_url = presigned_url or f"/api/presign/upload/proxy/{upload_id}"
|
||||
proxy_urls = build_proxy_upload_urls(upload_id)
|
||||
upload_url = presigned_url or proxy_urls["proxy_upload_url"]
|
||||
|
||||
await PresignUploadSession.create(
|
||||
upload_id=upload_id,
|
||||
@@ -577,13 +702,17 @@ async def presign_upload_init(
|
||||
)
|
||||
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
detail = {
|
||||
"upload_id": upload_id,
|
||||
"upload_url": upload_url,
|
||||
"mode": mode,
|
||||
"expires_in": PRESIGN_SESSION_EXPIRES,
|
||||
}
|
||||
if mode == "proxy":
|
||||
detail.update(proxy_urls)
|
||||
|
||||
return APIResponse(
|
||||
detail={
|
||||
"upload_id": upload_id,
|
||||
"upload_url": upload_url,
|
||||
"mode": mode,
|
||||
"expires_in": PRESIGN_SESSION_EXPIRES,
|
||||
}
|
||||
detail=detail
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
from apps.base.models import KeyValue
|
||||
from apps.base.utils import ip_limit
|
||||
from core.settings import DEFAULT_CONFIG, settings
|
||||
|
||||
|
||||
async def ensure_settings_row() -> None:
|
||||
await KeyValue.get_or_create(key="settings", defaults={"value": DEFAULT_CONFIG})
|
||||
|
||||
|
||||
def _sync_ip_limits() -> None:
|
||||
ip_limit["error"].minutes = settings.errorMinute
|
||||
ip_limit["error"].count = settings.errorCount
|
||||
ip_limit["upload"].minutes = settings.uploadMinute
|
||||
ip_limit["upload"].count = settings.uploadCount
|
||||
|
||||
|
||||
async def refresh_settings() -> None:
|
||||
"""从数据库读取最新配置并应用到运行时。"""
|
||||
config_record = await KeyValue.filter(key="settings").first()
|
||||
settings.user_config = config_record.value if config_record and config_record.value else {}
|
||||
_sync_ip_limits()
|
||||
+83
-18
@@ -1,6 +1,9 @@
|
||||
import asyncio
|
||||
import glob
|
||||
import importlib
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import IO
|
||||
|
||||
from tortoise import Tortoise
|
||||
|
||||
@@ -8,29 +11,91 @@ from core.logger import logger
|
||||
from core.settings import data_root
|
||||
|
||||
|
||||
_DB_FILE = os.path.join(data_root, "filecodebox.db")
|
||||
_STARTUP_LOCK_FILE = os.path.join(data_root, "filecodebox.startup.lock")
|
||||
|
||||
|
||||
def get_db_config() -> dict:
|
||||
return {
|
||||
"connections": {
|
||||
"default": {
|
||||
"engine": "tortoise.backends.sqlite",
|
||||
"credentials": {
|
||||
"file_path": _DB_FILE,
|
||||
"journal_mode": "WAL",
|
||||
"busy_timeout": 10000,
|
||||
"foreign_keys": "ON",
|
||||
},
|
||||
}
|
||||
},
|
||||
"apps": {
|
||||
"models": {
|
||||
"models": ["apps.base.models"],
|
||||
"default_connection": "default",
|
||||
}
|
||||
},
|
||||
"use_tz": False,
|
||||
"timezone": "Asia/Shanghai",
|
||||
}
|
||||
|
||||
|
||||
def _lock_file(file_obj: IO[str]) -> None:
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
# Windows 需要锁定至少 1 字节
|
||||
if os.fstat(file_obj.fileno()).st_size == 0:
|
||||
file_obj.write("0")
|
||||
file_obj.flush()
|
||||
msvcrt.locking(file_obj.fileno(), msvcrt.LK_LOCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(file_obj.fileno(), fcntl.LOCK_EX)
|
||||
|
||||
|
||||
def _unlock_file(file_obj: IO[str]) -> None:
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
msvcrt.locking(file_obj.fileno(), msvcrt.LK_UNLCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(file_obj.fileno(), fcntl.LOCK_UN)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def db_startup_lock():
|
||||
os.makedirs(data_root, exist_ok=True)
|
||||
lock_file = open(_STARTUP_LOCK_FILE, "a+", encoding="utf-8")
|
||||
try:
|
||||
await asyncio.to_thread(_lock_file, lock_file)
|
||||
yield
|
||||
finally:
|
||||
await asyncio.to_thread(_unlock_file, lock_file)
|
||||
lock_file.close()
|
||||
|
||||
|
||||
async def init_db():
|
||||
try:
|
||||
# 使用正确的Tortoise初始化配置格式
|
||||
db_config = {
|
||||
"db_url": f"sqlite://{data_root}/filecodebox.db",
|
||||
"modules": {"models": ["apps.base.models"]},
|
||||
"use_tz": False,
|
||||
"timezone": "Asia/Shanghai"
|
||||
}
|
||||
db_config = get_db_config()
|
||||
|
||||
await Tortoise.init(**db_config)
|
||||
if not Tortoise._inited:
|
||||
await Tortoise.init(config=db_config)
|
||||
|
||||
# 创建migrations表
|
||||
await Tortoise.get_connection("default").execute_script("""
|
||||
CREATE TABLE IF NOT EXISTS migrates (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
migration_file VARCHAR(255) NOT NULL UNIQUE,
|
||||
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
""")
|
||||
async with db_startup_lock():
|
||||
# 创建migrations表
|
||||
await Tortoise.get_connection("default").execute_script("""
|
||||
CREATE TABLE IF NOT EXISTS migrates (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
migration_file VARCHAR(255) NOT NULL UNIQUE,
|
||||
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
""")
|
||||
|
||||
# 执行迁移
|
||||
await execute_migrations()
|
||||
# 执行迁移
|
||||
await execute_migrations()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"数据库初始化失败: {str(e)}")
|
||||
|
||||
@@ -12,4 +12,9 @@ T = TypeVar("T")
|
||||
class APIResponse(BaseModel, Generic[T]):
|
||||
code: int = 200
|
||||
message: str = "ok"
|
||||
msg: Optional[str] = None
|
||||
detail: Optional[T] = None
|
||||
|
||||
def model_post_init(self, __context) -> None:
|
||||
if self.msg is None:
|
||||
self.msg = self.message
|
||||
+3
-1
@@ -26,6 +26,7 @@ DEFAULT_CONFIG = {
|
||||
"s3_region_name": "auto",
|
||||
"s3_signature_version": "s3v2",
|
||||
"s3_hostname": "",
|
||||
"s3_addressing_style": "auto",
|
||||
"s3_proxy": 0,
|
||||
"max_save_seconds": 0,
|
||||
"aws_session_token": "",
|
||||
@@ -40,6 +41,7 @@ DEFAULT_CONFIG = {
|
||||
"admin_token": "FileCodeBox2023",
|
||||
"openUpload": 1,
|
||||
"uploadSize": 1024 * 1024 * 10,
|
||||
"allowed_file_types": ["*"],
|
||||
"expireStyle": ["day", "hour", "minute", "forever", "count"],
|
||||
"uploadMinute": 1,
|
||||
"enableChunk": 0,
|
||||
@@ -65,7 +67,7 @@ DEFAULT_CONFIG = {
|
||||
],
|
||||
"themesSelect": "themes/2024",
|
||||
"errorMinute": 1,
|
||||
"errorCount": 1,
|
||||
"errorCount": 10,
|
||||
"serverWorkers": 1,
|
||||
"serverHost": "0.0.0.0",
|
||||
"serverPort": 12345,
|
||||
|
||||
+51
-64
@@ -267,6 +267,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
self.signature_version = settings.s3_signature_version
|
||||
self.endpoint_url = settings.s3_endpoint_url or f"https://{self.s3_hostname}"
|
||||
self.aws_session_token = settings.aws_session_token
|
||||
self.addressing_style = str(settings.s3_addressing_style or "auto").lower()
|
||||
self.proxy = settings.s3_proxy
|
||||
self.session = aioboto3.Session(
|
||||
aws_access_key_id=self.access_key_id,
|
||||
@@ -278,14 +279,26 @@ class S3FileStorage(FileStorageInterface):
|
||||
# 如果提供了 s3_endpoint_url,则优先使用它
|
||||
self.endpoint_url = settings.s3_endpoint_url
|
||||
|
||||
def _client_config(self) -> Config:
|
||||
config = {"signature_version": self.signature_version}
|
||||
s3_config = {}
|
||||
if self.addressing_style in {"path", "virtual", "auto"}:
|
||||
s3_config["addressing_style"] = self.addressing_style
|
||||
if s3_config:
|
||||
config["s3"] = s3_config
|
||||
return Config(**config)
|
||||
|
||||
def _client(self):
|
||||
return self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=self._client_config(),
|
||||
)
|
||||
|
||||
async def save_file(self, file: UploadFile, save_path: str):
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
async with self._client() as s3:
|
||||
# 使用 upload_fileobj 流式上传,避免将整个文件加载到内存
|
||||
await s3.upload_fileobj(
|
||||
file.file,
|
||||
@@ -295,12 +308,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
)
|
||||
|
||||
async def delete_file(self, file_code: FileCodes):
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
async with self._client() as s3:
|
||||
await s3.delete_object(
|
||||
Bucket=self.bucket_name, Key=await file_code.get_file_path()
|
||||
)
|
||||
@@ -310,12 +318,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
filename = file_code.prefix + file_code.suffix
|
||||
content_length = None # 初始化为 None,表示未知大小
|
||||
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
async with self._client() as s3:
|
||||
# 尝试获取文件大小(HEAD请求)
|
||||
try:
|
||||
head_response = await s3.head_object(
|
||||
@@ -384,12 +387,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
if self.proxy:
|
||||
return await get_file_url(file_code.code)
|
||||
else:
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
async with self._client() as s3:
|
||||
result = await s3.generate_presigned_url(
|
||||
"get_object",
|
||||
Params={
|
||||
@@ -406,13 +404,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
注意:这里不使用 S3 原生的 multipart upload,而是将每个分片作为独立对象存储
|
||||
"""
|
||||
chunk_key = str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part")
|
||||
async with self.session.client(
|
||||
's3',
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
async with self._client() as s3:
|
||||
# 将分片作为独立对象上传
|
||||
await s3.put_object(
|
||||
Bucket=self.bucket_name,
|
||||
@@ -432,13 +424,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
file_sha256 = hashlib.sha256()
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
|
||||
async with self.session.client(
|
||||
's3',
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
async with self._client() as s3:
|
||||
# 创建 multipart upload
|
||||
mpu = await s3.create_multipart_upload(
|
||||
Bucket=self.bucket_name,
|
||||
@@ -512,13 +498,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
:param save_path: 文件保存路径
|
||||
"""
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
async with self.session.client(
|
||||
's3',
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
async with self._client() as s3:
|
||||
try:
|
||||
# 列出并删除所有分片对象
|
||||
paginator = s3.get_paginator('list_objects_v2')
|
||||
@@ -540,13 +520,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
:param expires_in: URL过期时间(秒),默认15分钟
|
||||
:return: 预签名PUT URL
|
||||
"""
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
async with self._client() as s3:
|
||||
return await s3.generate_presigned_url(
|
||||
"put_object",
|
||||
Params={
|
||||
@@ -562,18 +536,31 @@ class S3FileStorage(FileStorageInterface):
|
||||
:param save_path: 文件路径
|
||||
:return: 文件是否存在
|
||||
"""
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
async with self._client() as s3:
|
||||
last_error = None
|
||||
for attempt in range(3):
|
||||
try:
|
||||
await s3.head_object(Bucket=self.bucket_name, Key=save_path)
|
||||
return True
|
||||
except Exception as e:
|
||||
last_error = e
|
||||
if attempt < 2:
|
||||
await asyncio.sleep(0.2 * (attempt + 1))
|
||||
|
||||
try:
|
||||
await s3.head_object(Bucket=self.bucket_name, Key=save_path)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
result = await s3.list_objects_v2(
|
||||
Bucket=self.bucket_name,
|
||||
Prefix=save_path,
|
||||
MaxKeys=1,
|
||||
)
|
||||
for item in result.get("Contents", []):
|
||||
if item.get("Key") == save_path:
|
||||
return True
|
||||
except Exception as e:
|
||||
last_error = e
|
||||
|
||||
logger.warning(f"S3文件确认失败 key={save_path}: {last_error}")
|
||||
return False
|
||||
|
||||
|
||||
class OneDriveFileStorage(FileStorageInterface):
|
||||
|
||||
+6
-3
@@ -11,15 +11,17 @@ from tortoise.expressions import Q
|
||||
|
||||
from apps.base.models import FileCodes, UploadChunk
|
||||
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():
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
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"):
|
||||
@@ -46,10 +48,11 @@ async def delete_expire_files():
|
||||
|
||||
|
||||
async def clean_incomplete_uploads():
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
expire_hours = getattr(settings, "chunk_expire_hours", 24)
|
||||
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(
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
APP_VERSION = "2.0.0-dev"
|
||||
@@ -0,0 +1,196 @@
|
||||
# 本轮开发交付报告
|
||||
|
||||
生成日期:2026-06-06
|
||||
|
||||
本文档记录 `feature/development-plan` 分支本轮开发完成情况、验证结果和后续处理建议。
|
||||
|
||||
## 分支状态
|
||||
|
||||
当前工作区包含两个独立 Git 仓库,均已切换到本轮开发分支:
|
||||
|
||||
- 后端仓库:`FileCodeBox`
|
||||
- 前端仓库:`FileCodeBoxFronted`
|
||||
- 当前分支:`feature/development-plan`
|
||||
|
||||
本轮变更尚未提交。
|
||||
|
||||
## 开发目标
|
||||
|
||||
本轮目标是根据 `docs/development-plan.md` 完成下一阶段的优先开发项:
|
||||
|
||||
1. 补齐取件文件预览链路。
|
||||
2. 建立前端最小测试体系。
|
||||
3. 加固后端预签名上传回归测试。
|
||||
4. 区分前端检查脚本和自动修复脚本。
|
||||
5. 拆分管理文件模块的部分纯函数、状态逻辑和批量操作 UI。
|
||||
|
||||
## 完成范围
|
||||
|
||||
### P0:取件文件预览链路
|
||||
|
||||
已在取件页完成文件预览接线:
|
||||
|
||||
- `RetrievewFileView.vue` 绑定文件详情弹窗的 `preview-file` 事件。
|
||||
- 取件页渲染并控制 `MediaPreviewModal`。
|
||||
- 取件详情中的可预览文件现在可以打开媒体预览弹窗。
|
||||
|
||||
### P0:前端最小测试体系
|
||||
|
||||
已建立 Vitest 测试基础:
|
||||
|
||||
- 新增 `vitest.config.ts`。
|
||||
- 新增 `package.json` 的 `test` 脚本。
|
||||
- 引入 `vitest`、`@vue/test-utils`、`jsdom` 等测试依赖。
|
||||
- 更新 `pnpm-lock.yaml`。
|
||||
|
||||
首批测试覆盖:
|
||||
|
||||
- 文件类型规则。
|
||||
- 下载动作解析。
|
||||
- 内容预览处理。
|
||||
- 发送记录工具逻辑。
|
||||
- 预签名上传相关流程。
|
||||
- 上传策略分支。
|
||||
- 管理文件摘要、视图预设和批量选择逻辑。
|
||||
|
||||
### P1:后端上传回归加固
|
||||
|
||||
已补充后端预签名上传流程测试:
|
||||
|
||||
- 新增 `tests/conftest.py`,固定测试导入路径。
|
||||
- 新增 `tests/test_presign_upload_flow.py`。
|
||||
|
||||
覆盖场景包括:
|
||||
|
||||
- `init` 直传模式。
|
||||
- `init` 代理上传模式。
|
||||
- `confirm` 成功创建文件记录。
|
||||
- `confirm` 拒绝缺失的直传文件。
|
||||
- `proxy` 上传大小不一致校验。
|
||||
- `cancel` 取消并清理已上传对象。
|
||||
- 过期上传会话自动删除并拒绝继续操作。
|
||||
|
||||
### P1:质量脚本调整
|
||||
|
||||
已区分自动修复和只检查命令:
|
||||
|
||||
```json
|
||||
{
|
||||
"lint": "eslint . --fix",
|
||||
"lint:check": "eslint ."
|
||||
}
|
||||
```
|
||||
|
||||
同时,架构检查脚本已忽略测试文件,避免测试代码影响前端分层规则检查。
|
||||
|
||||
### P2:管理文件模块拆分
|
||||
|
||||
已完成第一轮低风险拆分:
|
||||
|
||||
- 新增 `admin-file-view-preset.ts`,承载管理文件视图预设规则。
|
||||
- 新增 `admin-file-summary.ts`,承载管理文件摘要计算逻辑。
|
||||
- 新增 `useAdminFileSelection.ts`,承载批量选择状态逻辑。
|
||||
- 新增 `AdminBatchActionBar.vue`,承载管理页批量操作栏 UI。
|
||||
- `FileManageView.vue` 已接入新的批量操作栏组件。
|
||||
|
||||
本轮拆分优先处理纯函数和单一职责状态逻辑,避免一次性重构整个管理页。
|
||||
|
||||
## 关键设计决策
|
||||
|
||||
1. 优先补用户可见断点,再推进模块拆分。
|
||||
2. 先给工具函数和 composable 补测试,再扩大重构范围。
|
||||
3. `lint` 保留自动修复语义,新增 `lint:check` 用于 CI 和人工验证。
|
||||
4. 管理文件页拆分采用渐进方式,每次只抽离职责清晰、影响边界可控的模块。
|
||||
5. 后端上传测试使用替身对象和临时状态,避免依赖真实网络、真实 S3 或污染运行数据目录。
|
||||
|
||||
## 验证记录
|
||||
|
||||
本轮已完成以下验证:
|
||||
|
||||
```bash
|
||||
cd FileCodeBoxFronted
|
||||
pnpm test
|
||||
pnpm check:architecture
|
||||
pnpm type-check
|
||||
pnpm lint:check
|
||||
pnpm build
|
||||
|
||||
cd ../FileCodeBox
|
||||
pytest
|
||||
|
||||
git diff --check
|
||||
```
|
||||
|
||||
验证结果:
|
||||
|
||||
- 前端 `pnpm test`:9 files / 27 tests passed。
|
||||
- 前端 `pnpm check:architecture`:通过。
|
||||
- 前端 `pnpm type-check`:通过。
|
||||
- 前端 `pnpm lint:check`:通过。
|
||||
- 前端 `pnpm build`:通过。
|
||||
- 后端 `pytest`:21 passed,仅存在 Tortoise ORM deprecation warnings。
|
||||
- 前后端 `git diff --check`:通过。
|
||||
|
||||
## 当前未提交文件
|
||||
|
||||
### 后端仓库
|
||||
|
||||
新增文件:
|
||||
|
||||
- `docs/development-plan.md`
|
||||
- `docs/development-delivery-report.md`
|
||||
- `tests/conftest.py`
|
||||
- `tests/test_presign_upload_flow.py`
|
||||
|
||||
### 前端仓库
|
||||
|
||||
修改文件:
|
||||
|
||||
- `package.json`
|
||||
- `pnpm-lock.yaml`
|
||||
- `scripts/check-architecture.mjs`
|
||||
- `src/composables/useAdminFiles.ts`
|
||||
- `src/composables/useSendFlow.ts`
|
||||
- `src/utils/download-action.ts`
|
||||
- `src/views/RetrievewFileView.vue`
|
||||
- `src/views/manage/FileManageView.vue`
|
||||
- `tsconfig.app.json`
|
||||
|
||||
新增文件:
|
||||
|
||||
- `src/components/common/AdminBatchActionBar.vue`
|
||||
- `src/composables/useAdminFileSelection.ts`
|
||||
- `src/composables/useAdminFileSelection.test.ts`
|
||||
- `src/composables/usePresignedUpload.test.ts`
|
||||
- `src/services/upload-strategy.test.ts`
|
||||
- `src/utils/admin-file-summary.ts`
|
||||
- `src/utils/admin-file-summary.test.ts`
|
||||
- `src/utils/admin-file-view-preset.ts`
|
||||
- `src/utils/admin-file-view-preset.test.ts`
|
||||
- `src/utils/content-preview.test.ts`
|
||||
- `src/utils/download-action.test.ts`
|
||||
- `src/utils/file-type.ts`
|
||||
- `src/utils/file-type.test.ts`
|
||||
- `src/utils/send-record.test.ts`
|
||||
- `vitest.config.ts`
|
||||
|
||||
## 后续建议
|
||||
|
||||
1. 提交前再次执行前后端验证命令,确保工作区未被其他改动影响。
|
||||
2. 分别在两个仓库创建提交,避免跨仓库状态混淆。
|
||||
3. 下一轮继续拆分管理文件模块时,优先处理筛选栏、详情侧栏和元数据编辑逻辑。
|
||||
4. 后端可继续补充 `allowed_file_types`、S3 `file_exists` 降级、主题资源路径穿越保护等测试。
|
||||
|
||||
## 推荐提交信息
|
||||
|
||||
后端仓库:
|
||||
|
||||
```bash
|
||||
git commit -m "test: add presign upload flow coverage"
|
||||
```
|
||||
|
||||
前端仓库:
|
||||
|
||||
```bash
|
||||
git commit -m "feat: add retrieve preview and frontend tests"
|
||||
```
|
||||
@@ -0,0 +1,211 @@
|
||||
# 下一步开发计划
|
||||
|
||||
本文档记录 FileCodeBox 下一阶段开发优先级、并行拆分方式、验收标准和质量门禁。
|
||||
|
||||
## 背景
|
||||
|
||||
当前工作区包含两个独立仓库:
|
||||
|
||||
- `FileCodeBox`:FastAPI 后端,包含接口、存储、管理后台 API、文档和后端测试。
|
||||
- `FileCodeBoxFronted`:Vue 3 + Vite 前端,包含公开取件/发件页和管理后台界面。
|
||||
|
||||
近期提交主要集中在 S3 存储、取件码归一化、文件类型限制、主题资源加载、前端管理页和上传下载体验。
|
||||
|
||||
下一阶段应优先处理用户可见断点和自动化回归保护,再推进大模块拆分。
|
||||
|
||||
## 优先级总览
|
||||
|
||||
### P0:补齐取件文件预览链路
|
||||
|
||||
目标:打通前端已存在但尚未完整接线的文件预览能力。
|
||||
|
||||
涉及模块:
|
||||
|
||||
- `RetrievewFileView.vue`
|
||||
- `FileDetailModal.vue`
|
||||
- `MediaPreviewModal.vue`
|
||||
- `useRetrieveFlow.ts`
|
||||
|
||||
主要工作:
|
||||
|
||||
1. 在取件详情弹窗中绑定文件预览事件。
|
||||
2. 在取件页渲染媒体预览弹窗。
|
||||
3. 确认图片、视频、音频、PDF 等可预览文件能正常打开。
|
||||
4. 保持关闭、下载、错误提示等状态行为一致。
|
||||
|
||||
验收标准:
|
||||
|
||||
```bash
|
||||
pnpm check:architecture
|
||||
pnpm build
|
||||
```
|
||||
|
||||
手工验收:
|
||||
|
||||
1. 上传非文本文件并获取取件码。
|
||||
2. 取件后打开详情弹窗。
|
||||
3. 点击预览,确认弹窗可打开。
|
||||
4. 确认关闭和下载动作正常。
|
||||
|
||||
### P0:建立最小前端测试体系
|
||||
|
||||
目标:为核心前端流程建立可持续的自动化回归保护。
|
||||
|
||||
现状:
|
||||
|
||||
- 前端暂无测试目录。
|
||||
- `package.json` 中暂无 `test` 脚本。
|
||||
- 最近改动涉及上传、下载、Markdown 预览、配置表单等高风险路径。
|
||||
|
||||
建议引入:
|
||||
|
||||
```bash
|
||||
vitest
|
||||
@vue/test-utils
|
||||
jsdom
|
||||
```
|
||||
|
||||
首批测试范围:
|
||||
|
||||
- 文件类型限制规则。
|
||||
- 过期时间限制校验。
|
||||
- Markdown 渲染和 HTML 清洗。
|
||||
- 下载动作解析。
|
||||
- 预签名上传与分片上传提交分支。
|
||||
|
||||
验收标准:
|
||||
|
||||
```bash
|
||||
pnpm test
|
||||
```
|
||||
|
||||
要求:
|
||||
|
||||
- 测试能在 60 秒内完成。
|
||||
- 核心工具函数至少具备首批单元测试。
|
||||
- 测试脚本不修改源码文件。
|
||||
|
||||
### P1:后端上传与存储回归加固
|
||||
|
||||
目标:把近期修复沉淀为后端测试,降低存储和上传链路回归风险。
|
||||
|
||||
涉及模块:
|
||||
|
||||
- `apps/base/views.py`
|
||||
- `core/storage.py`
|
||||
- `main.py`
|
||||
- `tests/`
|
||||
|
||||
优先测试场景:
|
||||
|
||||
1. 预签名上传 `init` / `confirm` / `cancel`。
|
||||
2. 代理上传文件大小校验。
|
||||
3. `allowed_file_types` 的扩展名、MIME、通配规则。
|
||||
4. S3 `file_exists` 的 `head_object` 失败降级逻辑。
|
||||
5. 主题资源路径穿越保护。
|
||||
|
||||
验收标准:
|
||||
|
||||
```bash
|
||||
pytest
|
||||
```
|
||||
|
||||
要求:
|
||||
|
||||
- 测试使用临时目录和替身对象,避免污染 `data/`。
|
||||
- 外部存储相关测试不依赖真实网络或真实 S3。
|
||||
- 异常路径和边界值必须覆盖。
|
||||
|
||||
### P1:调整质量脚本
|
||||
|
||||
目标:区分“检查”和“自动修复”,避免 CI 或验证命令改写源码。
|
||||
|
||||
当前问题:
|
||||
|
||||
```json
|
||||
"lint": "eslint . --fix"
|
||||
```
|
||||
|
||||
建议调整:
|
||||
|
||||
```json
|
||||
{
|
||||
"lint": "eslint . --fix",
|
||||
"lint:check": "eslint ."
|
||||
}
|
||||
```
|
||||
|
||||
推荐前端验证顺序:
|
||||
|
||||
```bash
|
||||
pnpm check:architecture
|
||||
pnpm type-check
|
||||
pnpm lint:check
|
||||
pnpm test
|
||||
pnpm build
|
||||
```
|
||||
|
||||
### P2:拆分管理文件模块
|
||||
|
||||
目标:降低管理文件页面和业务 composable 的维护复杂度。
|
||||
|
||||
现状:
|
||||
|
||||
- `FileManageView.vue` 体量较大。
|
||||
- `useAdminFiles.ts` 同时承载列表、筛选、视图预设、批量操作、详情、元数据、下载和预览等职责。
|
||||
|
||||
拆分顺序:
|
||||
|
||||
1. 抽纯函数:筛选参数归一化、视图预设归一化、摘要计算、详情视图模型转换。
|
||||
2. 抽 composable:批量操作、详情弹窗、元数据编辑、视图预设。
|
||||
3. 抽 UI 子组件:批量工具栏、筛选栏、详情侧栏、预设选择器。
|
||||
|
||||
约束:
|
||||
|
||||
- 每次只拆一块。
|
||||
- 拆分前后行为保持一致。
|
||||
- 先给纯函数补测试,再推进 UI 拆分。
|
||||
|
||||
## 并行开发安排
|
||||
|
||||
第一轮可并行拆分为四个互不冲突的任务:
|
||||
|
||||
1. 前端 A:接线取件文件预览。
|
||||
2. 前端 B:搭建 Vitest 与首批工具函数测试。
|
||||
3. 后端 C:补充上传和存储回归测试。
|
||||
4. 工程 D:新增 `lint:check` 并整理验证命令。
|
||||
|
||||
合并前统一验证:
|
||||
|
||||
```bash
|
||||
cd FileCodeBoxFronted
|
||||
pnpm check:architecture
|
||||
pnpm type-check
|
||||
pnpm lint:check
|
||||
pnpm test
|
||||
pnpm build
|
||||
|
||||
cd ../FileCodeBox
|
||||
pytest
|
||||
```
|
||||
|
||||
## 质量门禁
|
||||
|
||||
每个开发任务完成时必须记录:
|
||||
|
||||
- 改动范围。
|
||||
- 关键设计决策。
|
||||
- 执行过的验证命令。
|
||||
- 未覆盖风险和后续事项。
|
||||
|
||||
涉及上传、删除、存储、认证、配置等功能时,必须补充异常路径测试。
|
||||
|
||||
## 推荐执行顺序
|
||||
|
||||
1. 先完成 P0 的取件预览接线。
|
||||
2. 同步建立前端最小测试体系。
|
||||
3. 补齐后端上传和存储回归测试。
|
||||
4. 调整前端质量脚本。
|
||||
5. 等测试保护到位后,再拆分管理文件模块。
|
||||
|
||||
结论:下一阶段以“取件预览接线 + 测试体系建设”为主线,先修用户可见断点,再提升长期维护质量。
|
||||
@@ -0,0 +1,843 @@
|
||||
# 功能与用户体验提升规划
|
||||
|
||||
生成日期:2026-06-06
|
||||
|
||||
本文档承接 `development-plan.md` 和 `development-delivery-report.md`,用于规划下一轮“功能增强 + 用户体验提升”开发。重点不是重做界面,而是让发送、取件和管理流程更清楚、更可恢复、更适合反复使用。
|
||||
|
||||
## 当前基线
|
||||
|
||||
当前工作区包含两个独立仓库:
|
||||
|
||||
- `FileCodeBox`:FastAPI 后端,提供分享、取件、分片上传、预签名上传、管理后台、配置和本地文件管理接口。
|
||||
- `FileCodeBoxFronted`:Vue 3 + Vite 前端,提供公开取件页、发件页、登录页、管理仪表盘、文件管理和系统设置。
|
||||
|
||||
本轮已完成的基础能力:
|
||||
|
||||
- 取件文件预览链路已接通。
|
||||
- 前端 Vitest 测试体系已建立。
|
||||
- 后端预签名上传流程已有回归测试。
|
||||
- 管理文件页已抽出部分纯函数、批量选择逻辑和批量操作栏。
|
||||
|
||||
下一轮应把重点从“能用”推进到“好用、稳定、可解释”。
|
||||
|
||||
## 体验目标
|
||||
|
||||
1. 发送流程要让用户明确知道当前文件是否可发、发到哪一步、失败后如何继续。
|
||||
2. 取件流程要避免误消耗取件次数,先展示文件摘要,再由用户确认下载或预览。
|
||||
3. 管理后台要提高高频操作效率,减少大页面内工具堆叠和重复确认成本。
|
||||
4. 所有危险操作要有清晰影响范围,避免误删、误批量修改和不可逆操作。
|
||||
5. 错误提示要从“发生错误”升级为“原因 + 可执行下一步”。
|
||||
|
||||
## 规划依据
|
||||
|
||||
本轮规划基于前后端只读审阅结果:
|
||||
|
||||
- 前端主流程已完整,但取件前确认、上传取消/重试、发送成功结果区和后台强确认仍不足。
|
||||
- 后端接口能力较全,但取件扣次数、下载票据、预签名直传确认、错误响应和审计追踪仍需要加固。
|
||||
- 下一轮应优先处理“安全边界 + 关键路径体验”,再扩展管理效率和长期产品能力。
|
||||
|
||||
## P0:取件扣次数与下载票据一致性
|
||||
|
||||
目标:确保取件次数只在真实授权动作中消耗,并且旧下载地址不能绕过过期或次数限制。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- `/share/select/` 当前会调用 `update_file_usage()`,取件前缺少确认时容易误消耗次数。
|
||||
- `/share/download` 使用 `check=False` 获取文件记录,已生成的下载地址存在被继续复用的窗口。
|
||||
- 下载票据由 `get_select_token()` 生成,缺少明确的短期过期语义和服务端状态绑定。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 将“查看元数据”和“确认取件授权”严格分离。
|
||||
2. 为确认取件生成短期下载票据:
|
||||
- 票据绑定取件码。
|
||||
- 票据包含过期时间。
|
||||
- 票据校验时重新检查文件是否过期、次数是否耗尽。
|
||||
3. 并发场景下保证 `expired_count=1` 只能成功一次。
|
||||
4. 下载接口拒绝已过期、次数耗尽或票据失效的请求。
|
||||
5. 响应中明确返回剩余次数和下一步动作。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `apps/base/views.py`
|
||||
- `core/utils.py`
|
||||
- `apps/base/models.py`
|
||||
- `tests/`
|
||||
|
||||
### 数据模型影响
|
||||
|
||||
第一阶段可先使用签名票据,不强制新增表。
|
||||
|
||||
如果要做更完整审计,后续新增:
|
||||
|
||||
- `DownloadTicket`
|
||||
- `FileAccessLog`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 元数据查询不消耗下载次数。
|
||||
2. 确认取件后才消耗次数并返回下载票据。
|
||||
3. `expired_count=1` 并发取件时只能成功一次。
|
||||
4. 旧下载地址在文件过期或次数耗尽后不可继续下载。
|
||||
5. 后端测试覆盖票据过期、次数耗尽和并发边界。
|
||||
|
||||
## P0:公开取件体验升级
|
||||
|
||||
目标:取件码输入后先确认内容,再执行会消耗次数的取件动作。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- `RetrievewFileView.vue` 在取件码长度达到 5 位时直接调用 `handleSubmit()`。
|
||||
- `handleSubmit()` 调用 `/share/select/`,会执行 `update_file_usage()`,可能消耗下载次数。
|
||||
- `useRetrieveFlow.ts` 已有 `inspectCode()` 和 `inspectedFile`,但页面当前未形成完整的“预检查确认”体验。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 输入 5 位取件码后调用 `inspectCode()`,请求 `/share/metadata/`。
|
||||
2. 页面展示文件摘要卡片:
|
||||
- 文件名或文本类型。
|
||||
- 文件大小。
|
||||
- 过期时间。
|
||||
- 剩余下载次数。
|
||||
- 是否可预览。
|
||||
3. 用户点击“取件”后再调用 `handleSubmit()`。
|
||||
4. 如果文件已过期或次数耗尽,直接展示不可取原因,不再进入下载动作。
|
||||
5. 查询参数 `?code=xxxxx` 进入页面时,也走同样的预检查流程。
|
||||
6. 与服务端下载票据机制配合,确认取件后再获得可下载地址。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `RetrievewFileView.vue`
|
||||
- `RetrieveForm.vue`
|
||||
- `useRetrieveFlow.ts`
|
||||
- `FileDetailModal.vue`
|
||||
- `download-action.ts`
|
||||
- `src/i18n/locales/zh-CN.ts`
|
||||
- `src/i18n/locales/en-US.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
```bash
|
||||
cd FileCodeBoxFronted
|
||||
pnpm test
|
||||
pnpm check:architecture
|
||||
pnpm type-check
|
||||
pnpm lint:check
|
||||
pnpm build
|
||||
```
|
||||
|
||||
手工验收:
|
||||
|
||||
1. 输入有效取件码,只展示摘要,不立即消耗下载次数。
|
||||
2. 点击确认取件后,才新增取件记录并打开详情或预览。
|
||||
3. 输入过期取件码时展示明确原因。
|
||||
4. 从 `?code=xxxxx` 访问时能自动展示摘要。
|
||||
|
||||
## P0:发送结果页增强
|
||||
|
||||
目标:发送成功后让用户更快完成复制、分享、复查和再次发送。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- `useSendFlow.ts` 发送成功后会自动复制链接并打开记录详情。
|
||||
- 用户能看到结果,但结果区域更像历史详情,不像一次明确的“发送完成”状态。
|
||||
- 多文件、文本、单文件的结果反馈可以更聚焦。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 新增发送成功结果面板,替代只依赖记录详情弹窗:
|
||||
- 取件码大号展示。
|
||||
- 一键复制取件码。
|
||||
- 一键复制链接。
|
||||
- 二维码展示入口。
|
||||
- 重新发送按钮。
|
||||
2. 明确自动复制结果:
|
||||
- 复制成功展示“链接已复制”。
|
||||
- 复制失败展示“请手动复制”。
|
||||
3. 多文件上传成功后展示文件数量和压缩包/批量记录说明。
|
||||
4. 文本发送成功后提供“预览文本”和“复制原文”。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `SendFileView.vue`
|
||||
- `SentRecordDetailModal.vue`
|
||||
- `SentRecordList.vue`
|
||||
- `useSendFlow.ts`
|
||||
- `sent-record-actions.ts`
|
||||
- `send-record.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 单文件、文本、多文件发送成功后都有明确完成态。
|
||||
2. 复制取件码、复制链接、二维码入口可用。
|
||||
3. 发送成功后再次选择文件或文本不会残留上一次进度。
|
||||
4. 自动复制失败时有人工复制路径。
|
||||
|
||||
## P0:上传失败恢复与取消
|
||||
|
||||
目标:上传过程可中断、可重试、可解释。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- 前端已有上传进度、速度和预签名上传封装。
|
||||
- 用户在上传中无法主动取消。
|
||||
- 失败后缺少保留文件并重试的明确路径。
|
||||
- 预签名上传会话存在后端取消接口,但前端体验还可以更完整。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 上传中展示取消按钮。
|
||||
2. 取消时调用对应取消逻辑:
|
||||
- 预签名上传:`DELETE /presign/upload/{upload_id}`。
|
||||
- 分片上传:`DELETE /chunk/upload/{upload_id}`。
|
||||
3. 失败后保留已选择文件,提供“重试”按钮。
|
||||
4. 错误提示按类型分层:
|
||||
- 文件过大。
|
||||
- 文件类型不允许。
|
||||
- 网络中断。
|
||||
- 服务端拒绝。
|
||||
- 上传会话过期。
|
||||
5. 上传过程中离开页面时提示用户确认。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `FileUploadArea.vue`
|
||||
- `SendFileView.vue`
|
||||
- `useSendFlow.ts`
|
||||
- `useSendSubmit.ts`
|
||||
- `usePresignedUpload.ts`
|
||||
- `upload-strategy.ts`
|
||||
- `FileService`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 上传中可以取消,后端临时会话或分片状态被清理。
|
||||
2. 网络失败后可以直接重试,不需要重新选择文件。
|
||||
3. 取消上传后进度归零,按钮状态恢复。
|
||||
4. 页面跳转或关闭前有上传中提示。
|
||||
|
||||
## P0:预签名直传确认加固
|
||||
|
||||
目标:直传文件确认不只检查“对象存在”,还要确认大小、状态和失败原因。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- `presign_upload_confirm()` 当前主要依赖 `file_exists()`。
|
||||
- 直传对象大小不符、上传中断、对象异常时,服务端难以给出准确原因。
|
||||
- `PresignUploadSession` 当前缺少状态字段,前端只能通过接口错误推断上传阶段。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 存储接口增加对象元信息读取能力:
|
||||
- `stat_file(save_path)`
|
||||
- 返回是否存在、实际大小、更新时间和存储后端错误。
|
||||
2. `presign_upload_confirm()` 校验实际大小与声明大小一致。
|
||||
3. 上传会话状态响应补充原因:
|
||||
- `pending`
|
||||
- `uploading`
|
||||
- `uploaded`
|
||||
- `confirmed`
|
||||
- `expired`
|
||||
- `cancelled`
|
||||
- `failed`
|
||||
4. 失败时返回明确错误码和可展示文案。
|
||||
5. 取消或失败后清理可清理的临时对象。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `apps/base/views.py`
|
||||
- `apps/base/models.py`
|
||||
- `core/storage.py`
|
||||
- `src/composables/usePresignedUpload.ts`
|
||||
- `src/services/presign-upload.ts`
|
||||
- `tests/test_presign_upload_flow.py`
|
||||
|
||||
### 数据模型影响
|
||||
|
||||
建议为 `PresignUploadSession` 增加:
|
||||
|
||||
- `status`
|
||||
- `actual_size`
|
||||
- `error_message`
|
||||
|
||||
第一阶段如果不做迁移,也可以先在状态接口中计算并返回原因。
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 直传对象不存在时返回明确错误。
|
||||
2. 直传对象大小不符时拒绝创建分享记录。
|
||||
3. 会话过期、取消、确认成功均有稳定状态。
|
||||
4. 前端能展示初始化、上传中、确认中、失败、成功状态。
|
||||
5. 后端测试覆盖对象不存在、大小不符、取消清理和会话过期。
|
||||
|
||||
## P0:统一错误响应与请求追踪
|
||||
|
||||
目标:让前端能稳定识别业务错误、网络错误和权限错误,并展示可执行下一步。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- 部分接口抛出 `HTTPException`,部分接口返回 `APIResponse(code=404)`。
|
||||
- 客户端难以稳定区分上传超限、类型不允许、取件码不存在、会话过期等业务失败。
|
||||
- 缺少请求 ID,线上排查问题时难以关联日志和用户反馈。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 统一错误响应结构:
|
||||
- `code`
|
||||
- `message`
|
||||
- `error_code`
|
||||
- `request_id`
|
||||
- `detail`
|
||||
2. 增加全局异常处理中间件或异常处理器。
|
||||
3. 上传、取件、登录、配置保存等关键接口返回稳定错误码。
|
||||
4. 前端错误提示按 `error_code` 映射文案和建议动作。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `core/response.py`
|
||||
- `main.py`
|
||||
- `apps/base/views.py`
|
||||
- `apps/admin/views.py`
|
||||
- `src/utils/common.ts`
|
||||
- `src/services/client.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 上传超限、类型不允许、取件码不存在、登录失败返回统一结构。
|
||||
2. 前端提示包含原因和下一步动作。
|
||||
3. 日志中可按 `request_id` 定位请求。
|
||||
4. 后端测试覆盖全局错误响应格式。
|
||||
|
||||
## P0:管理高风险操作确认升级
|
||||
|
||||
目标:删除、批量修改、批量策略等不可逆操作必须让管理员清楚知道影响范围。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- `useAdminFiles.ts` 中多处仍使用 `window.confirm()`。
|
||||
- 批量删除、批量更新和批量策略操作缺少文件样例、影响数量和不可逆提示。
|
||||
- 视图预设删除、单文件删除和批量删除的确认体验不统一。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 替换 `window.confirm()` 为统一确认弹窗。
|
||||
2. 确认弹窗展示:
|
||||
- 操作类型。
|
||||
- 影响文件数量。
|
||||
- 文件样例。
|
||||
- 是否不可逆。
|
||||
- 操作执行后可能的结果。
|
||||
3. 操作执行中禁用确认按钮和相关批量按钮。
|
||||
4. 操作完成后展示成功数量、失败数量和失败原因。
|
||||
5. 删除本地浏览器记录时明确提示“不删除服务器文件”。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `FileManageView.vue`
|
||||
- `AdminBatchActionBar.vue`
|
||||
- `BaseModal.vue`
|
||||
- `useAdminFiles.ts`
|
||||
- `SentRecordList.vue`
|
||||
- `FileRecordList.vue`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 单文件删除、批量删除、批量更新、批量策略动作均使用统一确认弹窗。
|
||||
2. 批量删除前可看到选中数量和至少 3 个文件样例。
|
||||
3. 操作中按钮禁用,避免重复提交。
|
||||
4. 取消操作不会改变选中状态。
|
||||
5. 操作结果能区分全部成功、部分成功和全部失败。
|
||||
|
||||
## P0:配置保存强校验
|
||||
|
||||
目标:把配置错误拦在保存阶段,而不是等用户上传或下载时才暴露。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- 配置存储在 `KeyValue` 中,更新入口需要更强字段校验。
|
||||
- 存储后端切换、上传限制、过期策略、文件类型规则等配置一旦错误,会直接影响公开流程。
|
||||
- 前端设置页有未保存状态,但配置变更风险没有形成统一摘要。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 后端保存配置前做字段级校验:
|
||||
- `file_storage` 必须是支持的存储后端。
|
||||
- 上传大小、限流和保存时长不能为负数。
|
||||
- `expireStyle` 必须属于允许枚举。
|
||||
- S3、WebDAV、OpenDAL、OneDrive 的必填项按存储类型校验。
|
||||
2. 前端保存前展示变更摘要:
|
||||
- 已变更字段。
|
||||
- 是否影响现有上传。
|
||||
- 是否需要管理员复查。
|
||||
3. 高风险配置显示明确提示:
|
||||
- 公开上传。
|
||||
- 允许全部文件类型。
|
||||
- 永久保存。
|
||||
- 默认管理员口令。
|
||||
4. 设置页离开、刷新、切换后台页面时提示保存或放弃。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
前端:
|
||||
|
||||
- `SystemSettingsView.vue`
|
||||
- `useSystemConfig.ts`
|
||||
- `router/index.ts`
|
||||
- `config-storage.ts`
|
||||
|
||||
后端:
|
||||
|
||||
- `apps/admin/services.py`
|
||||
- `apps/admin/views.py`
|
||||
- `core/settings.py`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 非法配置会被后端拒绝,并返回具体字段原因。
|
||||
2. 前端保存前展示变更摘要。
|
||||
3. 未保存配置离开页面会触发确认。
|
||||
4. 默认管理员口令、公开上传、允许所有文件类型会有高风险提示。
|
||||
|
||||
## P1:管理文件页信息架构优化
|
||||
|
||||
目标:把管理页从“功能堆在一个表格上”调整为更适合高频扫描和批量处理的工作台。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- `FileManageView.vue` 仍承担较多职责。
|
||||
- 筛选、预设、批量操作、表格、详情、编辑弹窗集中在同一个页面。
|
||||
- 单行操作按钮较多,在窄屏或大量数据时容易拥挤。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 拆分筛选区组件:
|
||||
- `AdminFileFilterBar.vue`
|
||||
- 负责关键词、状态、健康度、类型、排序和预设入口。
|
||||
2. 拆分详情侧栏:
|
||||
- `AdminFileDetailDrawer.vue`
|
||||
- 替代过重弹窗,保留复制、下载、编辑、预览入口。
|
||||
3. 表格行操作收敛为主操作 + 更多菜单:
|
||||
- 详情作为主操作。
|
||||
- 下载、编辑、删除进入更多菜单。
|
||||
4. 增加快捷筛选:
|
||||
- 即将过期。
|
||||
- 从未取件。
|
||||
- 已耗尽次数。
|
||||
- 存储异常。
|
||||
5. 表格空状态提供可执行动作:
|
||||
- 清空筛选。
|
||||
- 创建视图预设。
|
||||
- 返回全部文件。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `FileManageView.vue`
|
||||
- `AdminBatchActionBar.vue`
|
||||
- `useAdminFiles.ts`
|
||||
- `admin-file-summary.ts`
|
||||
- `admin-file-view-preset.ts`
|
||||
- `src/i18n/locales/zh-CN.ts`
|
||||
- `src/i18n/locales/en-US.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 筛选区、批量操作区、表格区职责清晰。
|
||||
2. 窄屏下表格行操作不溢出。
|
||||
3. 快捷筛选能正确改变请求参数并刷新数据。
|
||||
4. 已有批量选择、批量删除、批量策略动作不回归。
|
||||
|
||||
## P1:管理后台操作反馈增强
|
||||
|
||||
目标:让管理员明确知道批量操作影响了哪些文件、哪些成功、哪些失败。
|
||||
|
||||
### 现状能力
|
||||
|
||||
- 后端已有批量删除、批量更新、策略动作和活动记录。
|
||||
- 前端已有批量操作栏。
|
||||
- 后端 `FileService` 已具备管理活动记录能力。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 批量操作执行前展示影响摘要:
|
||||
- 选中文件数。
|
||||
- 即将修改的字段。
|
||||
- 不可逆风险。
|
||||
2. 批量操作完成后展示结果摘要:
|
||||
- 成功数量。
|
||||
- 失败数量。
|
||||
- 跳过原因。
|
||||
3. 活动记录支持从文件详情进入:
|
||||
- 展示该文件最近操作。
|
||||
- 展示操作者、动作和时间。
|
||||
4. 危险操作确认文案包含文件名或数量,而不是只问“是否删除”。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
前端:
|
||||
|
||||
- `AdminBatchActionBar.vue`
|
||||
- `FileManageView.vue`
|
||||
- `useAdminFiles.ts`
|
||||
- `DashboardView.vue`
|
||||
|
||||
后端:
|
||||
|
||||
- `apps/admin/views.py`
|
||||
- `apps/admin/services.py`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 批量删除和批量更新前有明确影响摘要。
|
||||
2. 批量操作结果能展示部分失败,不只显示统一成功或失败。
|
||||
3. 操作记录能按文件或关键词过滤。
|
||||
4. 后端测试覆盖活动记录过滤和批量操作结果结构。
|
||||
|
||||
## P1:下载与预览体验统一
|
||||
|
||||
目标:用户在公开页和管理页面对“文本、图片、视频、音频、PDF、未知文件”时,操作路径一致。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 抽统一文件能力判断工具:
|
||||
- 是否可文本预览。
|
||||
- 是否可媒体预览。
|
||||
- 是否建议下载。
|
||||
- 是否可复制内容。
|
||||
2. 统一公开取件和管理页的预览入口文案。
|
||||
3. PDF、图片、音视频预览失败时提供下载兜底。
|
||||
4. 文本预览支持复制、下载为 `.txt`、查看原始内容。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `MediaPreviewModal.vue`
|
||||
- `ContentPreviewModal.vue`
|
||||
- `FileDetailModal.vue`
|
||||
- `FileManageView.vue`
|
||||
- `content-preview.ts`
|
||||
- `download-action.ts`
|
||||
- `file-type.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 同一文件类型在公开页和管理页展示一致。
|
||||
2. 预览失败时始终能回退到下载。
|
||||
3. 文本内容复制和导出行为一致。
|
||||
4. 文件类型判断工具具备单元测试。
|
||||
|
||||
## P1:上传前文件清单与限制提示
|
||||
|
||||
目标:多文件或大文件上传前,让用户提前知道会发生什么,减少上传中途失败。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- 多文件上传会先打包为 zip,但用户只看到“正在打包文件”。
|
||||
- 文件清单、总大小、超限原因和打包后行为没有在提交前集中展示。
|
||||
- `FileUploadArea.vue` 已支持更多上传状态,但页面当前只传入 `uploading` 和 `idle`。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 多文件选择后展示文件清单:
|
||||
- 文件数量。
|
||||
- 总大小。
|
||||
- 最大文件。
|
||||
- 不允许类型或超限文件。
|
||||
2. 明确提示多文件将被打包为 zip。
|
||||
3. 打包阶段展示独立状态,避免和上传阶段混淆。
|
||||
4. 提交前对所有文件逐项校验,并返回具体失败原因。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `FileUploadArea.vue`
|
||||
- `SendFileView.vue`
|
||||
- `useSendFlow.ts`
|
||||
- `useSendSubmit.ts`
|
||||
- `ExpirationSelector.vue`
|
||||
- `file-type.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 多文件选择后可看到数量、总大小和打包提示。
|
||||
2. 超限文件能逐项展示原因。
|
||||
3. 打包中、上传中、确认中三个阶段状态不同。
|
||||
4. 文件清单在取消或重新选择后正确重置。
|
||||
|
||||
## P1:服务端状态字段与可操作能力
|
||||
|
||||
目标:为前端展示更清楚的状态和主操作提供稳定数据,减少前端重复推断。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 分享记录增加明确状态字段:
|
||||
- `active`
|
||||
- `expired`
|
||||
- `download_limit_exhausted`
|
||||
- `storage_missing`
|
||||
2. 公开元数据接口补充可操作能力:
|
||||
- `canPreview`
|
||||
- `canDownload`
|
||||
- `canCopy`
|
||||
- `primaryAction`
|
||||
3. 管理列表支持快捷筛选参数:
|
||||
- `expiringSoon`
|
||||
- `neverUsed`
|
||||
- `exhausted`
|
||||
- `storageIssue`
|
||||
4. 后端响应保留必要的 snake_case 和 camelCase 兼容。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `apps/base/views.py`
|
||||
- `apps/base/schemas.py`
|
||||
- `apps/admin/views.py`
|
||||
- `apps/admin/services.py`
|
||||
- `src/types/file.ts`
|
||||
- `src/services/file.ts`
|
||||
- `tests/`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 元数据接口能直接告诉前端主操作是什么。
|
||||
2. 管理文件列表能按快捷状态筛选。
|
||||
3. 状态字段有后端测试覆盖。
|
||||
4. 前端不再依赖 `filename === 'Text'` 这类脆弱判断。
|
||||
|
||||
## P1:审计日志表化
|
||||
|
||||
目标:让上传、下载、删除、配置变更等关键动作可追踪、可过滤、可定位。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- 管理活动当前主要保存在 `KeyValue` 中,容量和查询能力有限。
|
||||
- 活动记录缺少 IP、User-Agent、请求 ID、结果状态等排障信息。
|
||||
- 批量操作失败时,缺少逐项结果追踪。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 新增审计日志模型,记录:
|
||||
- 动作类型。
|
||||
- 操作者。
|
||||
- IP。
|
||||
- User-Agent。
|
||||
- 请求 ID。
|
||||
- 目标类型和目标 ID。
|
||||
- 执行结果。
|
||||
- 元数据。
|
||||
- 创建时间。
|
||||
2. `/admin/activities` 支持分页和筛选:
|
||||
- 动作。
|
||||
- 对象类型。
|
||||
- 关键词。
|
||||
- 时间范围。
|
||||
- 结果状态。
|
||||
3. 文件详情中展示该文件最近操作。
|
||||
4. 配置变更记录变更摘要,不记录密钥明文。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `apps/admin/services.py`
|
||||
- `apps/admin/views.py`
|
||||
- `apps/base/models.py`
|
||||
- `tests/`
|
||||
|
||||
### 数据模型影响
|
||||
|
||||
建议新增:
|
||||
|
||||
- `AuditLog`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 删除、批量更新、配置变更会写入审计日志。
|
||||
2. 审计列表支持分页和筛选。
|
||||
3. 日志不泄露 Token、密码、密钥。
|
||||
4. 后端测试覆盖写入、过滤和敏感字段脱敏。
|
||||
|
||||
## P1:管理查询性能优化
|
||||
|
||||
目标:让后台在千级、万级文件记录下仍能稳定分页、筛选和统计。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- 文件列表和仪表盘部分统计、过滤、排序在 Python 内存中完成。
|
||||
- 数据量增加后,后台打开、筛选和统计会逐渐变慢。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 文件列表筛选和排序尽量下推到数据库。
|
||||
2. 仪表盘统计改为聚合查询。
|
||||
3. 为高频字段补索引:
|
||||
- `created_at`
|
||||
- `expired_at`
|
||||
- `suffix`
|
||||
- `is_chunked`
|
||||
- `used_count`
|
||||
- `file_hash`
|
||||
4. 大量记录下避免一次性加载所有文件再过滤。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `apps/admin/views.py`
|
||||
- `apps/admin/services.py`
|
||||
- `apps/base/models.py`
|
||||
- `tests/`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 千级和万级记录下分页耗时稳定。
|
||||
2. 仪表盘统计结果与现有结果一致。
|
||||
3. 筛选、排序、分页返回结构保持兼容。
|
||||
4. 后端测试覆盖主要过滤组合。
|
||||
|
||||
## P2:取件与发送记录体验增强
|
||||
|
||||
目标:让浏览器本地记录更适合长期使用。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 记录支持搜索:
|
||||
- 取件码。
|
||||
- 文件名。
|
||||
- 类型。
|
||||
2. 记录支持分组:
|
||||
- 今天。
|
||||
- 最近 7 天。
|
||||
- 更早。
|
||||
3. 记录详情展示来源:
|
||||
- 手动输入。
|
||||
- 链接打开。
|
||||
- 历史记录。
|
||||
4. 支持清空记录前二次确认,并说明只清理本地记录,不删除服务器文件。
|
||||
5. 支持导出发送记录为 JSON。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `SideDrawer.vue`
|
||||
- `SentRecordList.vue`
|
||||
- `FileRecordList.vue`
|
||||
- `fileData` store
|
||||
- `send-record.ts`
|
||||
- `download-action.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 本地记录超过 20 条时仍易于查找。
|
||||
2. 清空记录不会误导用户以为删除了服务器文件。
|
||||
3. 导出的记录可重新导入或至少可人工读取。
|
||||
|
||||
## P2:系统设置体验增强
|
||||
|
||||
目标:在强校验之外,给管理员提供配置自检、连接测试和修复建议。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 设置页增加配置自检:
|
||||
- 当前存储后端是否可用。
|
||||
- 上传大小限制是否合理。
|
||||
- 允许文件类型是否能被正确解析。
|
||||
- 管理地址是否公开。
|
||||
2. 存储配置增加测试连接按钮:
|
||||
- S3。
|
||||
- WebDAV。
|
||||
- OpenDAL。
|
||||
- OneDrive。
|
||||
3. 自检结果返回修复建议:
|
||||
- 缺少必填项。
|
||||
- 存储连接失败。
|
||||
- 上传限制过宽。
|
||||
- 管理地址暴露。
|
||||
4. 支持导出当前非敏感配置快照,便于排障。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
前端:
|
||||
|
||||
- `SystemSettingsView.vue`
|
||||
- `config-storage.ts`
|
||||
- `config` types
|
||||
|
||||
后端:
|
||||
|
||||
- `apps/admin/views.py`
|
||||
- `apps/admin/services.py`
|
||||
- `core/storage.py`
|
||||
- `core/settings.py`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 保存设置前能看到变更摘要。
|
||||
2. 错误配置不会只在上传时暴露。
|
||||
3. 存储连接失败能返回可理解原因。
|
||||
4. 配置自检接口有后端测试覆盖。
|
||||
|
||||
## 并行开发拆分
|
||||
|
||||
第一轮建议拆成四个互不冲突任务,先处理会影响安全边界和关键体验的事项:
|
||||
|
||||
1. 后端 A:取件扣次数与下载票据一致性。
|
||||
2. 前端 B:取件前确认卡片和查询参数自动预检查。
|
||||
3. 后端 C:统一错误响应和请求追踪。
|
||||
4. 前端 D:发送成功结果面板和复制反馈。
|
||||
|
||||
第二轮在第一轮稳定后推进:
|
||||
|
||||
1. 后端 E:预签名直传确认加固和上传会话状态原因。
|
||||
2. 前端 F:上传取消、失败重试和离页确认。
|
||||
3. 前端 G:管理高风险操作确认弹窗。
|
||||
4. 后端 H:配置保存强校验。
|
||||
|
||||
第三轮推进管理效率和长期维护:
|
||||
|
||||
1. 前端 I:管理文件筛选区、详情侧栏和行操作收敛。
|
||||
2. 后端 J:服务端状态字段、快捷筛选和管理查询性能优化。
|
||||
3. 后端 K:审计日志表化。
|
||||
4. 前端 L:记录搜索、分组、导出和国际化补齐。
|
||||
|
||||
## 推荐执行顺序
|
||||
|
||||
1. 先做 P0 取件票据和扣次数一致性,修正服务端安全边界。
|
||||
2. 接着做 P0 取件前确认卡片,避免用户误消耗次数。
|
||||
3. 同步推进统一错误响应,让前端能展示稳定错误文案。
|
||||
4. 再做发送成功结果区,提升公开用户最常见路径。
|
||||
5. 然后做上传取消/重试和预签名直传确认加固。
|
||||
6. 管理页按强确认、筛选拆分、详情侧栏的顺序渐进推进。
|
||||
|
||||
## 质量门禁
|
||||
|
||||
前端每轮合并前执行:
|
||||
|
||||
```bash
|
||||
cd FileCodeBoxFronted
|
||||
pnpm test
|
||||
pnpm check:architecture
|
||||
pnpm type-check
|
||||
pnpm lint:check
|
||||
pnpm build
|
||||
```
|
||||
|
||||
后端每轮合并前执行:
|
||||
|
||||
```bash
|
||||
cd FileCodeBox
|
||||
pytest
|
||||
```
|
||||
|
||||
涉及上传、删除、配置、权限和批量操作时,必须补充异常路径测试。
|
||||
|
||||
## 风险与注意事项
|
||||
|
||||
1. 取件预检查不能调用会消耗次数的接口。
|
||||
2. 上传取消需要确认不同上传策略的清理路径一致。
|
||||
3. 管理页组件拆分必须保持现有批量操作行为不变。
|
||||
4. 配置自检不能泄露密钥、Token 或内部路径。
|
||||
5. 本地记录增强只影响浏览器存储,不应让用户误解为服务端记录。
|
||||
|
||||
## 下一步建议
|
||||
|
||||
下一轮优先实现:
|
||||
|
||||
1. `P0:取件扣次数与下载票据一致性`
|
||||
2. `P0:公开取件体验升级`
|
||||
3. `P0:统一错误响应与请求追踪`
|
||||
4. `P0:发送结果页增强`
|
||||
|
||||
这四项组合能同时修正服务端边界和公开用户体验,为后续上传恢复、管理工作台优化打基础。
|
||||
@@ -6,10 +6,9 @@ import asyncio
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.responses import FileResponse, HTMLResponse
|
||||
from tortoise import Tortoise
|
||||
from tortoise.contrib.fastapi import register_tortoise
|
||||
|
||||
@@ -17,12 +16,55 @@ from apps.admin.views import admin_api
|
||||
from apps.base.models import KeyValue
|
||||
from apps.base.utils import ip_limit
|
||||
from apps.base.views import share_api, chunk_api, presign_api
|
||||
from core.database import init_db
|
||||
from core.config import ensure_settings_row, refresh_settings
|
||||
from core.database import db_startup_lock, get_db_config, init_db
|
||||
from core.logger import logger
|
||||
from core.response import APIResponse
|
||||
from core.settings import data_root, settings, BASE_DIR, DEFAULT_CONFIG
|
||||
from core.settings import settings, BASE_DIR, DEFAULT_CONFIG
|
||||
from core.tasks import delete_expire_files, clean_incomplete_uploads
|
||||
from core.utils import hash_password, is_password_hashed
|
||||
from core.version import APP_VERSION
|
||||
|
||||
|
||||
def build_public_config() -> dict:
|
||||
return {
|
||||
"name": settings.name,
|
||||
"description": settings.description,
|
||||
"explain": settings.page_explain,
|
||||
"uploadSize": settings.uploadSize,
|
||||
"allowedFileTypes": settings.allowed_file_types,
|
||||
"expireStyle": settings.expireStyle,
|
||||
"enableChunk": settings.enableChunk,
|
||||
"openUpload": settings.openUpload,
|
||||
"notify_title": settings.notify_title,
|
||||
"notify_content": settings.notify_content,
|
||||
"show_admin_address": settings.showAdminAddr,
|
||||
"max_save_seconds": settings.max_save_seconds,
|
||||
}
|
||||
|
||||
|
||||
def build_public_meta() -> dict:
|
||||
return {
|
||||
"version": APP_VERSION,
|
||||
"api": {
|
||||
"legacyConfig": "/",
|
||||
"publicConfig": "/api/v1/config",
|
||||
"health": "/health",
|
||||
},
|
||||
"features": {
|
||||
"chunkUpload": bool(settings.enableChunk),
|
||||
"guestUpload": bool(settings.openUpload),
|
||||
"adminAddressVisible": bool(settings.showAdminAddr),
|
||||
"expirationModes": settings.expireStyle,
|
||||
},
|
||||
"limits": {
|
||||
"uploadSize": settings.uploadSize,
|
||||
"allowedFileTypes": settings.allowed_file_types,
|
||||
"maxSaveSeconds": settings.max_save_seconds,
|
||||
"uploadWindowMinutes": settings.uploadMinute,
|
||||
"uploadWindowCount": settings.uploadCount,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -31,14 +73,9 @@ async def lifespan(app: FastAPI):
|
||||
# 初始化数据库
|
||||
await init_db()
|
||||
|
||||
# 加载配置
|
||||
await load_config()
|
||||
app.mount(
|
||||
"/assets",
|
||||
StaticFiles(directory=f"./{settings.themesSelect}/assets"),
|
||||
name="assets",
|
||||
)
|
||||
|
||||
# 加载配置(多进程下串行化启动写操作)
|
||||
async with db_startup_lock():
|
||||
await load_config()
|
||||
# 启动后台任务
|
||||
task = asyncio.create_task(delete_expire_files())
|
||||
chunk_cleanup_task = asyncio.create_task(clean_incomplete_uploads())
|
||||
@@ -57,13 +94,11 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
|
||||
async def load_config():
|
||||
user_config, _ = await KeyValue.get_or_create(
|
||||
key="settings", defaults={"value": DEFAULT_CONFIG}
|
||||
)
|
||||
await ensure_settings_row()
|
||||
await KeyValue.update_or_create(
|
||||
key="sys_start", defaults={"value": int(time.time() * 1000)}
|
||||
)
|
||||
settings.user_config = user_config.value
|
||||
await refresh_settings()
|
||||
|
||||
await migrate_password_to_hash()
|
||||
|
||||
@@ -86,6 +121,11 @@ async def migrate_password_to_hash():
|
||||
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
|
||||
@app.middleware("http")
|
||||
async def refresh_settings_middleware(request, call_next):
|
||||
await refresh_settings()
|
||||
return await call_next(request)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
@@ -97,15 +137,7 @@ app.add_middleware(
|
||||
# 使用 register_tortoise 来添加异常处理器
|
||||
register_tortoise(
|
||||
app,
|
||||
config={
|
||||
"connections": {"default": f"sqlite://{data_root}/filecodebox.db"},
|
||||
"apps": {
|
||||
"models": {
|
||||
"models": ["apps.base.models"],
|
||||
"default_connection": "default",
|
||||
},
|
||||
},
|
||||
},
|
||||
config=get_db_config(),
|
||||
generate_schemas=False,
|
||||
add_exception_handlers=True,
|
||||
)
|
||||
@@ -113,22 +145,50 @@ register_tortoise(
|
||||
app.include_router(share_api)
|
||||
app.include_router(chunk_api)
|
||||
app.include_router(presign_api)
|
||||
app.include_router(presign_api, prefix="/api")
|
||||
app.include_router(admin_api)
|
||||
|
||||
|
||||
def resolve_theme_root():
|
||||
themes_root = (BASE_DIR / "themes").resolve()
|
||||
theme_root = (BASE_DIR / str(settings.themesSelect)).resolve()
|
||||
try:
|
||||
theme_root.relative_to(themes_root)
|
||||
except ValueError:
|
||||
theme_root = (BASE_DIR / DEFAULT_CONFIG["themesSelect"]).resolve()
|
||||
if not theme_root.exists():
|
||||
theme_root = (BASE_DIR / DEFAULT_CONFIG["themesSelect"]).resolve()
|
||||
return theme_root
|
||||
|
||||
|
||||
def resolve_theme_file(*parts: str):
|
||||
theme_root = resolve_theme_root()
|
||||
file_path = theme_root.joinpath(*parts).resolve()
|
||||
# 防止通过 /assets/../ 读取主题目录外的文件。
|
||||
try:
|
||||
file_path.relative_to(theme_root)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=404, detail="资源不存在")
|
||||
if not file_path.is_file():
|
||||
raise HTTPException(status_code=404, detail="资源不存在")
|
||||
return file_path
|
||||
|
||||
|
||||
@app.get("/assets/{asset_path:path}", include_in_schema=False)
|
||||
async def theme_asset(asset_path: str):
|
||||
return FileResponse(resolve_theme_file("assets", asset_path))
|
||||
|
||||
|
||||
@app.exception_handler(404)
|
||||
@app.get("/")
|
||||
async def index(request=None, exc=None):
|
||||
return HTMLResponse(
|
||||
content=open(
|
||||
BASE_DIR / f"{settings.themesSelect}/index.html", "r", encoding="utf-8"
|
||||
)
|
||||
.read()
|
||||
content=resolve_theme_file("index.html")
|
||||
.read_text(encoding="utf-8")
|
||||
.replace("{{title}}", str(settings.name))
|
||||
.replace("{{description}}", str(settings.description))
|
||||
.replace("{{keywords}}", str(settings.keywords))
|
||||
.replace("{{opacity}}", str(settings.opacity))
|
||||
.replace('"/assets/', '"assets/')
|
||||
.replace("{{background}}", str(settings.background)),
|
||||
media_type="text/html",
|
||||
headers={"Cache-Control": "no-cache"},
|
||||
@@ -142,19 +202,27 @@ async def robots():
|
||||
|
||||
@app.post("/")
|
||||
async def get_config():
|
||||
return APIResponse(detail=build_public_config())
|
||||
|
||||
|
||||
@app.get("/api/v1/config")
|
||||
async def get_public_config():
|
||||
return APIResponse(
|
||||
detail={
|
||||
"name": settings.name,
|
||||
"description": settings.description,
|
||||
"explain": settings.page_explain,
|
||||
"uploadSize": settings.uploadSize,
|
||||
"expireStyle": settings.expireStyle,
|
||||
"enableChunk": settings.enableChunk,
|
||||
"openUpload": settings.openUpload,
|
||||
"notify_title": settings.notify_title,
|
||||
"notify_content": settings.notify_content,
|
||||
"show_admin_address": settings.showAdminAddr,
|
||||
"max_save_seconds": settings.max_save_seconds,
|
||||
"config": build_public_config(),
|
||||
"meta": build_public_meta(),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
return APIResponse(
|
||||
detail={
|
||||
"status": "ok",
|
||||
"version": APP_VERSION,
|
||||
"storage": settings.file_storage,
|
||||
"theme": settings.themesSelect,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -468,4 +468,5 @@ git push origin feature/your-feature
|
||||
|
||||
Made with ❤️ by [vastsa](https://github.com/vastsa)
|
||||
|
||||
|
||||
</div>
|
||||
@@ -0,0 +1,6 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(PROJECT_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
@@ -0,0 +1,33 @@
|
||||
import unittest
|
||||
|
||||
from core.settings import settings
|
||||
from core.storage import S3FileStorage
|
||||
|
||||
|
||||
class SettingsOverrideMixin:
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
|
||||
def tearDown(self):
|
||||
settings.user_config = self._original_user_config
|
||||
|
||||
|
||||
class S3StorageConfigTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def test_client_config_uses_path_style_when_configured(self):
|
||||
storage = S3FileStorage.__new__(S3FileStorage)
|
||||
storage.signature_version = "s3v4"
|
||||
storage.addressing_style = "path"
|
||||
|
||||
config = storage._client_config()
|
||||
|
||||
self.assertEqual(config.signature_version, "s3v4")
|
||||
self.assertEqual(config.s3["addressing_style"], "path")
|
||||
|
||||
def test_client_config_ignores_invalid_addressing_style(self):
|
||||
storage = S3FileStorage.__new__(S3FileStorage)
|
||||
storage.signature_version = "s3v4"
|
||||
storage.addressing_style = "invalid"
|
||||
|
||||
config = storage._client_config()
|
||||
|
||||
self.assertIsNone(config.s3)
|
||||
@@ -0,0 +1,65 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from apps.admin.services import FileService
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
class SettingsOverrideMixin:
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
|
||||
def tearDown(self):
|
||||
settings.user_config = self._original_user_config
|
||||
|
||||
|
||||
class FakeFileCode:
|
||||
def __init__(self):
|
||||
self.id = 1
|
||||
self.code = "ABC123"
|
||||
self.prefix = "report"
|
||||
self.suffix = ".txt"
|
||||
self.uuid_file_name = "report.txt"
|
||||
self.file_path = "share/data/2026/01/01/abc"
|
||||
self.size = 12
|
||||
self.text = None
|
||||
self.expired_at = datetime(2026, 1, 2, 12, 0, 0)
|
||||
self.expired_count = 3
|
||||
self.used_count = 0
|
||||
self.created_at = datetime(2026, 1, 1, 12, 0, 0)
|
||||
self.file_hash = "a" * 64
|
||||
self.is_chunked = False
|
||||
self.upload_id = None
|
||||
|
||||
async def is_expired(self):
|
||||
return False
|
||||
|
||||
|
||||
class AdminFileItemTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def test_build_admin_file_item_serializes_required_fields(self):
|
||||
settings.file_storage = "local"
|
||||
service = FileService()
|
||||
now = datetime(2026, 1, 1, 13, 0, 0)
|
||||
|
||||
item = asyncio.run(service._build_admin_file_item(FakeFileCode(), now=now))
|
||||
|
||||
self.assertEqual(item["id"], 1)
|
||||
self.assertEqual(item["name"], "report.txt")
|
||||
self.assertEqual(item["type"], "file")
|
||||
self.assertFalse(item["isExpired"])
|
||||
self.assertEqual(item["remainingDownloads"], 3)
|
||||
self.assertEqual(item["file_path"], "share/data/2026/01/01/abc")
|
||||
self.assertIn("never_retrieved", item["statusInsights"]["reasons"])
|
||||
self.assertEqual(item["statusInsights"]["metrics"]["ageSeconds"], 3600)
|
||||
|
||||
def test_build_admin_file_item_marks_expiring_soon(self):
|
||||
settings.file_storage = "local"
|
||||
service = FileService()
|
||||
file_code = FakeFileCode()
|
||||
now = file_code.expired_at - timedelta(hours=2)
|
||||
|
||||
item = asyncio.run(service._build_admin_file_item(file_code, now=now))
|
||||
|
||||
self.assertEqual(item["statusInsights"]["severity"], "warning")
|
||||
self.assertIn("expires_soon", item["statusInsights"]["reasons"])
|
||||
@@ -0,0 +1,31 @@
|
||||
import unittest
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from apps.base.views import validate_file_type
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
class SettingsOverrideMixin:
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
|
||||
def tearDown(self):
|
||||
settings.user_config = self._original_user_config
|
||||
|
||||
|
||||
class FileTypeValidationTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def test_allows_extensions_and_mime_patterns(self):
|
||||
settings.allowed_file_types = ["rar", ".zip", "image/*"]
|
||||
|
||||
validate_file_type("backup.RAR")
|
||||
validate_file_type("archive.zip")
|
||||
validate_file_type("avatar.bin", "image/png")
|
||||
|
||||
def test_rejects_disallowed_file_type(self):
|
||||
settings.allowed_file_types = ["rar"]
|
||||
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
validate_file_type("payload.exe", "application/octet-stream")
|
||||
|
||||
self.assertEqual(error.exception.status_code, 403)
|
||||
@@ -0,0 +1,34 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
|
||||
import apps.base.views as views
|
||||
from apps.base.views import normalize_share_code
|
||||
|
||||
|
||||
class FakeFileCodes:
|
||||
seen_code = None
|
||||
|
||||
@classmethod
|
||||
def filter(cls, **kwargs):
|
||||
cls.seen_code = kwargs.get("code")
|
||||
return cls()
|
||||
|
||||
async def first(self):
|
||||
return None
|
||||
|
||||
|
||||
class RetrieveCodeTests(unittest.TestCase):
|
||||
def test_normalize_share_code_strips_surrounding_whitespace(self):
|
||||
self.assertEqual(normalize_share_code(" 12345\n"), "12345")
|
||||
|
||||
def test_get_code_file_by_code_queries_normalized_code(self):
|
||||
original_file_codes = views.FileCodes
|
||||
views.FileCodes = FakeFileCodes
|
||||
try:
|
||||
has_file, message = asyncio.run(views.get_code_file_by_code(" 12345\n"))
|
||||
finally:
|
||||
views.FileCodes = original_file_codes
|
||||
|
||||
self.assertFalse(has_file)
|
||||
self.assertEqual(message, "文件不存在")
|
||||
self.assertEqual(FakeFileCodes.seen_code, "12345")
|
||||
@@ -0,0 +1,44 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from core.settings import settings
|
||||
from main import index, resolve_theme_file
|
||||
|
||||
|
||||
class SettingsOverrideMixin:
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
|
||||
def tearDown(self):
|
||||
settings.user_config = self._original_user_config
|
||||
|
||||
|
||||
class ThemeAssetTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def test_resolves_assets_from_current_theme(self):
|
||||
settings.themesSelect = "themes/2023"
|
||||
theme_2023_asset = resolve_theme_file("assets", "index-CxMsK_Ni.js")
|
||||
|
||||
settings.themesSelect = "themes/2024"
|
||||
theme_2024_asset = resolve_theme_file("assets", "index-DjzJA_Oj.js")
|
||||
|
||||
self.assertIn("themes/2023/assets", str(theme_2023_asset))
|
||||
self.assertIn("themes/2024/assets", str(theme_2024_asset))
|
||||
|
||||
def test_rejects_theme_asset_path_traversal(self):
|
||||
settings.themesSelect = "themes/2024"
|
||||
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
resolve_theme_file("assets", "..", "..", "core", "settings.py")
|
||||
|
||||
self.assertEqual(error.exception.status_code, 404)
|
||||
|
||||
def test_index_keeps_absolute_asset_urls(self):
|
||||
settings.themesSelect = "themes/2023"
|
||||
|
||||
response = asyncio.run(index())
|
||||
html = response.body.decode("utf-8")
|
||||
|
||||
self.assertIn('src="/assets/', html)
|
||||
self.assertIn('href="/assets/', html)
|
||||
@@ -0,0 +1,46 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
|
||||
from core.storage import S3FileStorage
|
||||
|
||||
|
||||
class FakeS3Client:
|
||||
def __init__(self, list_response):
|
||||
self.list_response = list_response
|
||||
self.head_calls = 0
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc, traceback):
|
||||
return False
|
||||
|
||||
async def head_object(self, **kwargs):
|
||||
self.head_calls += 1
|
||||
raise RuntimeError("head not supported")
|
||||
|
||||
async def list_objects_v2(self, **kwargs):
|
||||
return self.list_response
|
||||
|
||||
|
||||
class S3FileExistsTests(unittest.TestCase):
|
||||
def test_file_exists_falls_back_to_list_objects(self):
|
||||
client = FakeS3Client({"Contents": [{"Key": "share/data/file.txt"}]})
|
||||
storage = S3FileStorage.__new__(S3FileStorage)
|
||||
storage.bucket_name = "bucket"
|
||||
storage._client = lambda: client
|
||||
|
||||
exists = asyncio.run(storage.file_exists("share/data/file.txt"))
|
||||
|
||||
self.assertTrue(exists)
|
||||
self.assertEqual(client.head_calls, 3)
|
||||
|
||||
def test_file_exists_returns_false_when_missing(self):
|
||||
client = FakeS3Client({"Contents": [{"Key": "share/data/other.txt"}]})
|
||||
storage = S3FileStorage.__new__(S3FileStorage)
|
||||
storage.bucket_name = "bucket"
|
||||
storage._client = lambda: client
|
||||
|
||||
exists = asyncio.run(storage.file_exists("share/data/file.txt"))
|
||||
|
||||
self.assertFalse(exists)
|
||||
@@ -0,0 +1,271 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
from datetime import timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
import apps.base.views as views
|
||||
from apps.base.schemas import PresignUploadInitRequest
|
||||
from core.settings import settings
|
||||
from core.utils import get_now
|
||||
|
||||
|
||||
class SettingsOverrideMixin:
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
|
||||
def tearDown(self):
|
||||
settings.user_config = self._original_user_config
|
||||
|
||||
|
||||
class FakeUploadLimiter:
|
||||
def __init__(self):
|
||||
self.added_ips = []
|
||||
|
||||
def add_ip(self, ip):
|
||||
self.added_ips.append(ip)
|
||||
|
||||
|
||||
class FakeUploadFile:
|
||||
def __init__(self, size):
|
||||
self.size = size
|
||||
self.filename = "upload.txt"
|
||||
self.content_type = "text/plain"
|
||||
|
||||
|
||||
class FakeStorage:
|
||||
def __init__(self, presigned_url=None, exists=True):
|
||||
self.presigned_url = presigned_url
|
||||
self.exists = exists
|
||||
self.saved = []
|
||||
self.deleted = []
|
||||
|
||||
async def generate_presigned_upload_url(self, save_path, expires_in):
|
||||
self.last_presign_request = (save_path, expires_in)
|
||||
return self.presigned_url
|
||||
|
||||
async def save_file(self, file, save_path):
|
||||
self.saved.append((file, save_path))
|
||||
|
||||
async def file_exists(self, save_path):
|
||||
self.last_exists_path = save_path
|
||||
return self.exists
|
||||
|
||||
async def delete_file(self, file_code):
|
||||
self.deleted.append(file_code)
|
||||
|
||||
|
||||
class FakeSession:
|
||||
def __init__(self, mode="direct", file_size=12, expired=False):
|
||||
self.upload_id = "upload-1"
|
||||
self.file_name = "upload.txt"
|
||||
self.file_size = file_size
|
||||
self.save_path = "share/data/2026/06/06/upload-1/upload.txt"
|
||||
self.mode = mode
|
||||
self.expire_value = 2
|
||||
self.expire_style = "day"
|
||||
self.created_at = None
|
||||
self.expires_at = None
|
||||
self.expired = expired
|
||||
self.deleted = False
|
||||
|
||||
async def is_expired(self):
|
||||
return self.expired
|
||||
|
||||
async def delete(self):
|
||||
self.deleted = True
|
||||
|
||||
|
||||
class FakeSessionQuery:
|
||||
def __init__(self, session):
|
||||
self.session = session
|
||||
|
||||
async def first(self):
|
||||
return self.session
|
||||
|
||||
|
||||
class FakePresignUploadSession:
|
||||
created_payload = None
|
||||
session = None
|
||||
|
||||
@classmethod
|
||||
async def create(cls, **kwargs):
|
||||
cls.created_payload = kwargs
|
||||
return SimpleNamespace(**kwargs)
|
||||
|
||||
@classmethod
|
||||
def filter(cls, **kwargs):
|
||||
cls.filter_kwargs = kwargs
|
||||
return FakeSessionQuery(cls.session)
|
||||
|
||||
|
||||
class FakeFileUploadService:
|
||||
created_records = []
|
||||
|
||||
@staticmethod
|
||||
async def generate_file_path(file_name, upload_id=None):
|
||||
filename = file_name.strip()
|
||||
return (
|
||||
f"share/data/2026/06/06/{upload_id}",
|
||||
".txt",
|
||||
"upload",
|
||||
filename,
|
||||
f"share/data/2026/06/06/{upload_id}/{filename}",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
async def create_file_record(
|
||||
cls, file_name, file_size, file_path, expire_value, expire_style, **extra_fields
|
||||
):
|
||||
cls.created_records.append(
|
||||
{
|
||||
"file_name": file_name,
|
||||
"file_size": file_size,
|
||||
"file_path": file_path,
|
||||
"expire_value": expire_value,
|
||||
"expire_style": expire_style,
|
||||
**extra_fields,
|
||||
}
|
||||
)
|
||||
return "12345"
|
||||
|
||||
|
||||
class PresignUploadFlowTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self._original_storages = dict(views.storages)
|
||||
self._original_session_model = views.PresignUploadSession
|
||||
self._original_file_upload_service = views.FileUploadService
|
||||
self._original_upload_limiter = views.ip_limit["upload"]
|
||||
self.storage = FakeStorage()
|
||||
views.storages = {"local": lambda: self.storage}
|
||||
views.PresignUploadSession = FakePresignUploadSession
|
||||
views.FileUploadService = FakeFileUploadService
|
||||
views.ip_limit["upload"] = FakeUploadLimiter()
|
||||
FakePresignUploadSession.created_payload = None
|
||||
FakePresignUploadSession.session = None
|
||||
FakeFileUploadService.created_records = []
|
||||
settings.file_storage = "local"
|
||||
settings.uploadSize = 1024
|
||||
settings.allowed_file_types = ["*"]
|
||||
settings.expireStyle = ["day", "hour", "minute", "forever", "count"]
|
||||
|
||||
def tearDown(self):
|
||||
views.storages = self._original_storages
|
||||
views.PresignUploadSession = self._original_session_model
|
||||
views.FileUploadService = self._original_file_upload_service
|
||||
views.ip_limit["upload"] = self._original_upload_limiter
|
||||
super().tearDown()
|
||||
|
||||
def test_init_returns_proxy_urls_when_storage_has_no_presigned_url(self):
|
||||
response = asyncio.run(
|
||||
views.presign_upload_init(
|
||||
PresignUploadInitRequest(
|
||||
file_name="upload.txt",
|
||||
file_size=12,
|
||||
expire_value=2,
|
||||
expire_style="day",
|
||||
),
|
||||
ip="127.0.0.1",
|
||||
)
|
||||
)
|
||||
|
||||
detail = response.detail
|
||||
self.assertEqual(detail["mode"], "proxy")
|
||||
self.assertEqual(detail["upload_url"], detail["proxy_upload_url"])
|
||||
self.assertEqual(detail["legacy_proxy_upload_url"], f"/api{detail['proxy_upload_url']}")
|
||||
self.assertEqual(FakePresignUploadSession.created_payload["file_name"], "upload.txt")
|
||||
self.assertEqual(FakePresignUploadSession.created_payload["file_size"], 12)
|
||||
self.assertEqual(views.ip_limit["upload"].added_ips, ["127.0.0.1"])
|
||||
|
||||
def test_init_returns_direct_url_when_storage_supports_presigned_upload(self):
|
||||
self.storage.presigned_url = "https://storage.example/upload"
|
||||
|
||||
response = asyncio.run(
|
||||
views.presign_upload_init(
|
||||
PresignUploadInitRequest(file_name="upload.txt", file_size=12),
|
||||
ip="127.0.0.1",
|
||||
)
|
||||
)
|
||||
|
||||
self.assertEqual(response.detail["mode"], "direct")
|
||||
self.assertEqual(response.detail["upload_url"], "https://storage.example/upload")
|
||||
self.assertNotIn("proxy_upload_url", response.detail)
|
||||
|
||||
def test_init_rejects_disallowed_expiration_style(self):
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
asyncio.run(
|
||||
views.presign_upload_init(
|
||||
PresignUploadInitRequest(
|
||||
file_name="upload.txt",
|
||||
file_size=12,
|
||||
expire_style="week",
|
||||
),
|
||||
ip="127.0.0.1",
|
||||
)
|
||||
)
|
||||
|
||||
self.assertEqual(error.exception.status_code, 400)
|
||||
|
||||
def test_confirm_requires_uploaded_direct_file_before_creating_record(self):
|
||||
FakePresignUploadSession.session = FakeSession(mode="direct")
|
||||
self.storage.exists = True
|
||||
|
||||
response = asyncio.run(views.presign_upload_confirm("upload-1", ip="127.0.0.1"))
|
||||
|
||||
self.assertEqual(response.detail, {"code": "12345", "name": "upload.txt"})
|
||||
self.assertTrue(FakePresignUploadSession.session.deleted)
|
||||
self.assertEqual(FakeFileUploadService.created_records[0]["file_size"], 12)
|
||||
self.assertEqual(
|
||||
FakeFileUploadService.created_records[0]["file_path"],
|
||||
"share/data/2026/06/06/upload-1",
|
||||
)
|
||||
|
||||
def test_confirm_rejects_missing_uploaded_direct_file(self):
|
||||
FakePresignUploadSession.session = FakeSession(mode="direct")
|
||||
self.storage.exists = False
|
||||
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
asyncio.run(views.presign_upload_confirm("upload-1", ip="127.0.0.1"))
|
||||
|
||||
self.assertEqual(error.exception.status_code, 404)
|
||||
self.assertFalse(FakePresignUploadSession.session.deleted)
|
||||
self.assertEqual(FakeFileUploadService.created_records, [])
|
||||
|
||||
def test_proxy_upload_rejects_size_mismatch_before_saving_file(self):
|
||||
FakePresignUploadSession.session = FakeSession(mode="proxy", file_size=10)
|
||||
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
asyncio.run(
|
||||
views.presign_upload_proxy(
|
||||
"upload-1",
|
||||
file=FakeUploadFile(size=2048),
|
||||
ip="127.0.0.1",
|
||||
)
|
||||
)
|
||||
|
||||
self.assertEqual(error.exception.status_code, 403)
|
||||
self.assertEqual(self.storage.saved, [])
|
||||
|
||||
def test_cancel_direct_session_removes_uploaded_object_when_present(self):
|
||||
FakePresignUploadSession.session = FakeSession(mode="direct")
|
||||
self.storage.exists = True
|
||||
|
||||
response = asyncio.run(views.presign_upload_cancel("upload-1"))
|
||||
|
||||
self.assertEqual(response.detail, {"message": "上传会话已取消"})
|
||||
self.assertTrue(FakePresignUploadSession.session.deleted)
|
||||
self.assertEqual(len(self.storage.deleted), 1)
|
||||
self.assertEqual(self.storage.deleted[0].file_path, "share/data/2026/06/06/upload-1")
|
||||
self.assertEqual(self.storage.deleted[0].uuid_file_name, "upload.txt")
|
||||
|
||||
def test_expired_session_is_deleted_and_rejected(self):
|
||||
FakePresignUploadSession.session = FakeSession(mode="direct", expired=True)
|
||||
FakePresignUploadSession.session.expires_at = asyncio.run(get_now()) - timedelta(seconds=1)
|
||||
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
asyncio.run(views.presign_upload_confirm("upload-1", ip="127.0.0.1"))
|
||||
|
||||
self.assertEqual(error.exception.status_code, 404)
|
||||
self.assertTrue(FakePresignUploadSession.session.deleted)
|
||||
Reference in new issue
Block a user