🔧 chore: 同步完整后端运行模块
This commit is contained in:
1 parent
d104b9fc8b
commit
2d44699eec
20 files changed
+1465
-235
No files matched your search
+9
-5
@@ -15,7 +15,8 @@ WORKDIR /build
|
||||
# 克隆并构建 2024 主题
|
||||
ARG FRONTEND_2024_REPO=https://git.orionc.me/orion/FileCodeBoxFronted.git
|
||||
ARG FRONTEND_2024_BRANCH=main
|
||||
ARG FRONTEND_CACHE_BUST=1
|
||||
# 每次更新 2026 前端后,同步为测试分支已验证的提交,避免 Docker 复用过期的远端前端构建层。
|
||||
ARG FRONTEND_CACHE_BUST=f4e498b
|
||||
RUN echo "$FRONTEND_CACHE_BUST" >/tmp/frontend-cache-bust && \
|
||||
git clone --filter=blob:none --no-checkout "$FRONTEND_2024_REPO" /build/fronted-2024 && \
|
||||
cd /build/fronted-2024 && \
|
||||
@@ -26,7 +27,7 @@ RUN echo "$FRONTEND_CACHE_BUST" >/tmp/frontend-cache-bust && \
|
||||
|
||||
# 克隆并构建定制 2026 主题
|
||||
ARG FRONTEND_2026_REPO=https://git.orionc.me/orion/FileCodeBoxFronted2026.git
|
||||
ARG FRONTEND_2026_BRANCH=test/custom-admin-ui
|
||||
ARG FRONTEND_2026_BRANCH=main
|
||||
RUN echo "$FRONTEND_CACHE_BUST" >/tmp/frontend-2026-cache-bust && \
|
||||
git clone --depth 1 --branch "$FRONTEND_2026_BRANCH" "$FRONTEND_2026_REPO" /build/fronted-2026 && \
|
||||
cd /build/fronted-2026 && \
|
||||
@@ -88,11 +89,14 @@ RUN apt-get update \
|
||||
ENV HOST="0.0.0.0" \
|
||||
PORT=12345 \
|
||||
WORKERS=1 \
|
||||
LOG_LEVEL="info" \
|
||||
APP_ENV="production" \
|
||||
LOG_LEVEL="warning" \
|
||||
ACCESS_LOG="false" \
|
||||
FORWARDED_ALLOW_IPS=""
|
||||
|
||||
EXPOSE 12345
|
||||
|
||||
# 生产环境启动命令
|
||||
# FORWARDED_ALLOW_IPS 由部署环境显式指定,避免任意客户端伪造 X-Forwarded-*。
|
||||
CMD ["sh", "-c", "exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-}\""]
|
||||
# FORWARDED_ALLOW_IPS 默认为空:仅信任直连 IP,避免任意客户端伪造 X-Forwarded-*。
|
||||
# 若前面有反向代理,请显式设置为代理网段,例如 "10.0.0.0/8,172.16.0.0/12"。
|
||||
CMD ["sh", "-c", "access_log_arg=--no-access-log; if [ \"${APP_ENV:-development}\" != \"production\" ] || [ \"${ACCESS_LOG:-false}\" = \"true\" ]; then access_log_arg=--access-log; fi; exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" \"$access_log_arg\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-}\""]
|
||||
+54
-14
@@ -8,27 +8,60 @@ import base64
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
from core.settings import settings
|
||||
from core.settings import (
|
||||
ADMIN_SESSION_EXPIRE_DEFAULT,
|
||||
ADMIN_SESSION_EXPIRE_MAX,
|
||||
ADMIN_SESSION_EXPIRE_MIN,
|
||||
settings,
|
||||
)
|
||||
from apps.admin.services import FileService, ConfigService, LocalFileService
|
||||
|
||||
|
||||
def create_token(data: dict, expires_in: int = 3600 * 24 * 30) -> str:
|
||||
def _get_jwt_secret() -> bytes:
|
||||
secret = getattr(settings, "jwt_secret", "")
|
||||
if not secret:
|
||||
raise RuntimeError("JWT签名密钥未初始化")
|
||||
return secret.encode()
|
||||
|
||||
|
||||
def get_admin_session_expire_seconds() -> int:
|
||||
try:
|
||||
expires_in = int(
|
||||
getattr(settings, "adminSessionExpire", ADMIN_SESSION_EXPIRE_DEFAULT)
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
return ADMIN_SESSION_EXPIRE_DEFAULT
|
||||
if (
|
||||
not ADMIN_SESSION_EXPIRE_MIN <= expires_in <= ADMIN_SESSION_EXPIRE_MAX
|
||||
or expires_in % ADMIN_SESSION_EXPIRE_MIN != 0
|
||||
):
|
||||
return ADMIN_SESSION_EXPIRE_DEFAULT
|
||||
return expires_in
|
||||
|
||||
|
||||
def create_token(data: dict, expires_in: int | None = None) -> str:
|
||||
"""
|
||||
创建JWT token
|
||||
:param data: 数据负载
|
||||
:param expires_in: 过期时间(秒)
|
||||
"""
|
||||
header = base64.b64encode(
|
||||
json.dumps({"alg": "HS256", "typ": "JWT"}).encode()
|
||||
).decode()
|
||||
payload = base64.b64encode(
|
||||
json.dumps({**data, "exp": int(time.time()) + expires_in}).encode()
|
||||
).decode()
|
||||
token_lifetime = (
|
||||
get_admin_session_expire_seconds() if expires_in is None else expires_in
|
||||
)
|
||||
header = base64.urlsafe_b64encode(
|
||||
json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode()
|
||||
).decode().rstrip("=")
|
||||
payload = base64.urlsafe_b64encode(
|
||||
json.dumps(
|
||||
{**data, "exp": int(time.time()) + token_lifetime},
|
||||
separators=(",", ":"),
|
||||
).encode()
|
||||
).decode().rstrip("=")
|
||||
|
||||
signature = hmac.new(
|
||||
settings.admin_token.encode(), f"{header}.{payload}".encode(), "sha256"
|
||||
_get_jwt_secret(), f"{header}.{payload}".encode(), "sha256"
|
||||
).digest()
|
||||
signature = base64.b64encode(signature).decode()
|
||||
signature = base64.urlsafe_b64encode(signature).decode().rstrip("=")
|
||||
|
||||
return f"{header}.{payload}.{signature}"
|
||||
|
||||
@@ -44,17 +77,24 @@ def verify_token(token: str) -> dict:
|
||||
|
||||
# 验证签名
|
||||
expected_signature = hmac.new(
|
||||
settings.admin_token.encode(),
|
||||
_get_jwt_secret(),
|
||||
f"{header_b64}.{payload_b64}".encode(),
|
||||
"sha256",
|
||||
).digest()
|
||||
expected_signature_b64 = base64.b64encode(expected_signature).decode()
|
||||
expected_signature_b64 = (
|
||||
base64.urlsafe_b64encode(expected_signature).decode().rstrip("=")
|
||||
)
|
||||
|
||||
if not hmac.compare_digest(signature_b64, expected_signature_b64):
|
||||
raise ValueError("无效的签名")
|
||||
|
||||
# 解码payload
|
||||
payload = json.loads(base64.b64decode(payload_b64))
|
||||
# 解码payload(兼容历史标准 base64 与 urlsafe base64)
|
||||
padded = payload_b64 + "=" * (-len(payload_b64) % 4)
|
||||
try:
|
||||
payload_bytes = base64.urlsafe_b64decode(padded)
|
||||
except Exception:
|
||||
payload_bytes = base64.b64decode(padded)
|
||||
payload = json.loads(payload_bytes)
|
||||
|
||||
# 检查是否过期
|
||||
if payload.get("exp", 0) < time.time():
|
||||
|
||||
@@ -17,7 +17,7 @@ from core.settings import (
|
||||
)
|
||||
from core.config import refresh_settings
|
||||
from core.security import INTERNAL_CONFIG_KEYS, generate_jwt_secret
|
||||
from apps.base.models import FileCodes, KeyValue, TransferStats, file_codes_pydantic
|
||||
from apps.base.models import FileCodes, KeyValue, ShareCodeReservations, TransferStats, file_codes_pydantic
|
||||
|
||||
from apps.base.utils import get_expire_info, get_file_path_name, get_random_code
|
||||
from apps.base.quota import release_storage, reserve_storage
|
||||
@@ -180,6 +180,11 @@ class FileService:
|
||||
original_path,
|
||||
)
|
||||
file_code.file_path = destination_dir
|
||||
original_code = file_code.code
|
||||
await ShareCodeReservations.get_or_create(
|
||||
code=original_code,
|
||||
defaults={"file_code_id": file_code.id, "reason": "restored"},
|
||||
)
|
||||
file_code.code = await get_random_code()
|
||||
file_code.is_trashed = False
|
||||
file_code.trashed_at = None
|
||||
|
||||
+34
-8
@@ -31,10 +31,16 @@ from apps.admin.schemas import (
|
||||
UpdateFileData,
|
||||
)
|
||||
from core.response import APIResponse
|
||||
from apps.base.models import FileCodes, KeyValue, TransferStats
|
||||
from apps.admin.dependencies import create_token
|
||||
from apps.base.models import FileCodes, KeyValue, ShareCodeReservations, TransferStats
|
||||
from apps.admin.dependencies import (
|
||||
create_token,
|
||||
get_admin_session_expire_seconds,
|
||||
verify_token,
|
||||
)
|
||||
|
||||
from core.settings import settings
|
||||
from core.utils import get_now, verify_password
|
||||
from apps.base.utils import ip_limit
|
||||
|
||||
admin_api = APIRouter(
|
||||
prefix="/admin", tags=["管理"], dependencies=[Depends(admin_required)]
|
||||
@@ -50,12 +56,24 @@ def _pick_query_text(*values: Optional[str]) -> Optional[str]:
|
||||
|
||||
|
||||
@admin_api.post("/login")
|
||||
async def login(data: LoginData):
|
||||
async def login(data: LoginData, ip: str = Depends(ip_limit["login"])):
|
||||
# 登录失败计入 IP 频率限制,超过 loginCount/loginMinute 后暂时锁定
|
||||
if not verify_password(data.password, settings.admin_token):
|
||||
ip_limit["login"].add_ip(ip)
|
||||
raise HTTPException(status_code=401, detail="密码错误")
|
||||
|
||||
token = create_token({"is_admin": True})
|
||||
return APIResponse(detail={"token": token, "token_type": "Bearer"})
|
||||
expires_in = get_admin_session_expire_seconds()
|
||||
token = create_token({"is_admin": True}, expires_in=expires_in)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"id": "admin",
|
||||
"username": "admin",
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": verify_token(token)["exp"],
|
||||
"expires_in": expires_in,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@admin_api.get("/verify")
|
||||
@@ -838,12 +856,15 @@ async def update_file(
|
||||
if not file_code:
|
||||
raise HTTPException(status_code=404, detail="文件不存在")
|
||||
target_name = file_service._build_file_activity_name(file_code)
|
||||
previous_code = file_code.code
|
||||
update_data = {}
|
||||
|
||||
if data.code is not None and data.code != file_code.code:
|
||||
# 判断code是否存在
|
||||
if await FileCodes.filter(code=data.code).first():
|
||||
raise HTTPException(status_code=400, detail="code已存在")
|
||||
# 当前记录和全部退役取件码都不可重复使用。
|
||||
if await FileCodes.filter(code=data.code).first() or await ShareCodeReservations.filter(
|
||||
code=data.code
|
||||
).first():
|
||||
raise HTTPException(status_code=400, detail="取件码已被占用")
|
||||
update_data["code"] = data.code
|
||||
if data.prefix is not None and data.prefix != file_code.prefix:
|
||||
update_data["prefix"] = data.prefix
|
||||
@@ -859,6 +880,11 @@ async def update_file(
|
||||
update_data["expired_count"] = data.expired_count
|
||||
|
||||
await file_code.update_from_dict(update_data).save()
|
||||
if "code" in update_data:
|
||||
await ShareCodeReservations.get_or_create(
|
||||
code=previous_code,
|
||||
defaults={"file_code_id": file_code.id, "reason": "manual_update"},
|
||||
)
|
||||
if update_data:
|
||||
await file_service.record_admin_activity(
|
||||
action="file.update",
|
||||
|
||||
@@ -1,7 +1,69 @@
|
||||
from typing import Dict, Union
|
||||
from ipaddress import ip_address, ip_network
|
||||
from typing import Dict, Iterable, Union
|
||||
from datetime import datetime, timedelta
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
def _iter_trusted_proxies() -> Iterable[str]:
|
||||
trusted_proxies = getattr(settings, "trustedProxies", [])
|
||||
if isinstance(trusted_proxies, str):
|
||||
trusted_proxies = [item.strip() for item in trusted_proxies.split(",")]
|
||||
return [item for item in trusted_proxies if item]
|
||||
|
||||
|
||||
def _is_trusted_proxy(host: str) -> bool:
|
||||
try:
|
||||
remote_addr = ip_address(host)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
for proxy in _iter_trusted_proxies():
|
||||
try:
|
||||
if remote_addr in ip_network(proxy, strict=False):
|
||||
return True
|
||||
except ValueError:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
def _get_forwarded_for_ip(header_value: str, fallback_ip: str) -> str:
|
||||
forwarded_chain = [
|
||||
item.strip() for item in header_value.split(",") if item.strip()
|
||||
]
|
||||
if not forwarded_chain:
|
||||
return fallback_ip
|
||||
|
||||
for candidate in reversed(forwarded_chain):
|
||||
try:
|
||||
ip_address(candidate)
|
||||
except ValueError:
|
||||
return fallback_ip
|
||||
if not _is_trusted_proxy(candidate):
|
||||
return candidate
|
||||
return forwarded_chain[0]
|
||||
|
||||
|
||||
def get_client_ip(request: Request) -> str:
|
||||
client_host = request.client.host if request.client else "unknown"
|
||||
if not _is_trusted_proxy(client_host):
|
||||
return client_host
|
||||
|
||||
forwarded_for = request.headers.get("X-Forwarded-For")
|
||||
if forwarded_for:
|
||||
return _get_forwarded_for_ip(forwarded_for, client_host)
|
||||
|
||||
real_ip = request.headers.get("X-Real-IP")
|
||||
if real_ip:
|
||||
try:
|
||||
ip_address(real_ip)
|
||||
except ValueError:
|
||||
return client_host
|
||||
return real_ip
|
||||
|
||||
return client_host
|
||||
|
||||
|
||||
class IPRateLimit:
|
||||
def __init__(self, count: int, minutes: int):
|
||||
@@ -35,11 +97,7 @@ class IPRateLimit:
|
||||
}
|
||||
|
||||
def __call__(self, request: Request) -> str:
|
||||
ip = (
|
||||
request.headers.get("X-Real-IP")
|
||||
or request.headers.get("X-Forwarded-For")
|
||||
or request.client.host
|
||||
)
|
||||
ip = get_client_ip(request)
|
||||
if not self.check_ip(ip):
|
||||
raise HTTPException(status_code=423, detail="请求次数过多,请稍后再试")
|
||||
return ip
|
||||
@@ -0,0 +1,196 @@
|
||||
"""文件类型校验:扩展名 / MIME 白名单 + magic bytes 防伪造。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import HTTPException, UploadFile
|
||||
from fnmatch import fnmatchcase
|
||||
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FileKind:
|
||||
name: str
|
||||
extensions: tuple[str, ...]
|
||||
mimes: tuple[str, ...]
|
||||
signatures: tuple[bytes, ...]
|
||||
|
||||
|
||||
FILE_KINDS: tuple[FileKind, ...] = (
|
||||
FileKind("png", (".png",), ("image/png",), (b"\x89PNG\r\n\x1a\n",)),
|
||||
FileKind("jpg", (".jpg", ".jpeg"), ("image/jpeg",), (b"\xff\xd8\xff",)),
|
||||
FileKind("gif", (".gif",), ("image/gif",), (b"GIF87a", b"GIF89a")),
|
||||
FileKind("webp", (".webp",), ("image/webp",), ()),
|
||||
FileKind("bmp", (".bmp",), ("image/bmp", "image/x-ms-bmp"), (b"BM",)),
|
||||
FileKind("pdf", (".pdf",), ("application/pdf",), (b"%PDF",)),
|
||||
FileKind(
|
||||
"zip",
|
||||
(".zip", ".docx", ".xlsx", ".pptx", ".apk", ".jar"),
|
||||
(
|
||||
"application/zip",
|
||||
"application/x-zip-compressed",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||
"application/java-archive",
|
||||
"application/vnd.android.package-archive",
|
||||
),
|
||||
(b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08"),
|
||||
),
|
||||
FileKind(
|
||||
"rar",
|
||||
(".rar",),
|
||||
("application/x-rar-compressed", "application/vnd.rar"),
|
||||
(b"Rar!\x1a\x07\x00", b"Rar!\x1a\x07\x01\x00"),
|
||||
),
|
||||
FileKind("7z", (".7z",), ("application/x-7z-compressed",), (b"7z\xbc\xaf'\x1c",)),
|
||||
FileKind("gz", (".gz", ".tgz"), ("application/gzip", "application/x-gzip"), (b"\x1f\x8b",)),
|
||||
FileKind(
|
||||
"mp3",
|
||||
(".mp3",),
|
||||
("audio/mpeg",),
|
||||
(b"ID3", b"\xff\xfb", b"\xff\xf3", b"\xff\xf2"),
|
||||
),
|
||||
FileKind("mp4", (".mp4", ".m4a", ".mov"), ("video/mp4", "audio/mp4", "video/quicktime"), ()),
|
||||
FileKind(
|
||||
"exe",
|
||||
(".exe", ".dll", ".sys"),
|
||||
("application/x-msdownload", "application/x-dosexec"),
|
||||
(b"MZ",),
|
||||
),
|
||||
FileKind("elf", (".elf", ".so", ".o"), ("application/x-executable",), (b"\x7fELF",)),
|
||||
)
|
||||
|
||||
KNOWN_EXTENSIONS = {ext for kind in FILE_KINDS for ext in kind.extensions}
|
||||
|
||||
|
||||
def normalize_allowed_file_types() -> list[str]:
|
||||
raw_value = settings.allowed_file_types
|
||||
if isinstance(raw_value, str):
|
||||
values = [item.strip() for item in raw_value.split(",")]
|
||||
elif isinstance(raw_value, (list, tuple, set)):
|
||||
values = [str(item).strip() for item in raw_value]
|
||||
else:
|
||||
values = []
|
||||
normalized = [item.lower() for item in values if item]
|
||||
return normalized or ["*"]
|
||||
|
||||
|
||||
def _extension_of(file_name: str) -> str:
|
||||
return Path(file_name or "").suffix.lower()
|
||||
|
||||
|
||||
def _match_allow_rule(rule: str, file_name: str, content_type: str) -> bool:
|
||||
if rule in {"*", "*/*"}:
|
||||
return True
|
||||
if "/" in rule:
|
||||
return fnmatchcase(content_type, rule)
|
||||
extension = rule if rule.startswith(".") else f".{rule}"
|
||||
return file_name.endswith(extension)
|
||||
|
||||
|
||||
def is_type_allowed(file_name: str, content_type: Optional[str] = None) -> bool:
|
||||
allowed = normalize_allowed_file_types()
|
||||
if any(rule in {"*", "*/*"} for rule in allowed):
|
||||
return True
|
||||
normalized_name = (file_name or "").strip().lower()
|
||||
normalized_content_type = (content_type or "").strip().lower()
|
||||
return any(
|
||||
_match_allow_rule(rule, normalized_name, normalized_content_type)
|
||||
for rule in allowed
|
||||
)
|
||||
|
||||
|
||||
def detect_file_kind(header: bytes) -> Optional[FileKind]:
|
||||
if not header:
|
||||
return None
|
||||
|
||||
if len(header) >= 12 and header.startswith(b"RIFF") and header[8:12] == b"WEBP":
|
||||
return next(kind for kind in FILE_KINDS if kind.name == "webp")
|
||||
|
||||
if len(header) >= 12 and header[4:8] == b"ftyp":
|
||||
return next(kind for kind in FILE_KINDS if kind.name == "mp4")
|
||||
|
||||
candidates: list[tuple[int, FileKind]] = []
|
||||
for kind in FILE_KINDS:
|
||||
for signature in kind.signatures:
|
||||
if signature and header.startswith(signature):
|
||||
candidates.append((len(signature), kind))
|
||||
if not candidates:
|
||||
return None
|
||||
candidates.sort(key=lambda item: item[0], reverse=True)
|
||||
return candidates[0][1]
|
||||
|
||||
|
||||
def validate_file_type(file_name: str, content_type: Optional[str] = None) -> None:
|
||||
if not is_type_allowed(file_name, content_type):
|
||||
raise HTTPException(status_code=403, detail="不允许上传该类型文件")
|
||||
|
||||
|
||||
def _kind_matches_ext(kind: FileKind, extension: str) -> bool:
|
||||
return extension in kind.extensions
|
||||
|
||||
|
||||
def _kind_matches_mime(kind: FileKind, mime: str) -> bool:
|
||||
return mime in kind.mimes
|
||||
|
||||
|
||||
def validate_file_magic(
|
||||
file_name: str,
|
||||
content_type: Optional[str],
|
||||
header: Optional[bytes],
|
||||
) -> None:
|
||||
"""白名单通过后,用 magic bytes 防止扩展名 / MIME 伪造。"""
|
||||
validate_file_type(file_name, content_type)
|
||||
if not header:
|
||||
return
|
||||
|
||||
claimed_ext = _extension_of(file_name)
|
||||
claimed_mime = (content_type or "").strip().lower()
|
||||
detected = detect_file_kind(header)
|
||||
|
||||
if claimed_ext in KNOWN_EXTENSIONS:
|
||||
if detected is None or not _kind_matches_ext(detected, claimed_ext):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="文件内容与扩展名不匹配,疑似伪造类型",
|
||||
)
|
||||
|
||||
if claimed_mime and any(claimed_mime in kind.mimes for kind in FILE_KINDS):
|
||||
if detected is None or not _kind_matches_mime(detected, claimed_mime):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="文件内容与 Content-Type 不匹配,疑似伪造类型",
|
||||
)
|
||||
|
||||
allowed = normalize_allowed_file_types()
|
||||
if detected and not any(rule in {"*", "*/*"} for rule in allowed):
|
||||
allowed_by_detected = any(
|
||||
is_type_allowed(f"file{ext}", mime)
|
||||
for ext in detected.extensions
|
||||
for mime in (detected.mimes or (None,))
|
||||
)
|
||||
if not allowed_by_detected:
|
||||
raise HTTPException(status_code=403, detail="不允许上传该类型文件")
|
||||
|
||||
|
||||
async def read_upload_header(file: UploadFile, size: int = 64) -> bytes:
|
||||
await file.seek(0)
|
||||
header = await file.read(size)
|
||||
await file.seek(0)
|
||||
return header or b""
|
||||
|
||||
|
||||
async def validate_upload_file(file: UploadFile) -> None:
|
||||
header = await read_upload_header(file)
|
||||
validate_file_magic(file.filename or "", file.content_type, header)
|
||||
|
||||
|
||||
def validate_header_bytes(
|
||||
file_name: str, content_type: Optional[str], header: bytes
|
||||
) -> None:
|
||||
validate_file_magic(file_name, content_type, header)
|
||||
@@ -0,0 +1,19 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
async def migrate():
|
||||
conn = connections.get("default")
|
||||
await conn.execute_script(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS storagereservation (
|
||||
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
token VARCHAR(64) NOT NULL UNIQUE,
|
||||
size BIGINT NOT NULL,
|
||||
expires_at TIMESTAMP NOT NULL
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_storagereservation_token
|
||||
ON storagereservation (token);
|
||||
CREATE INDEX IF NOT EXISTS idx_storagereservation_expires_at
|
||||
ON storagereservation (expires_at);
|
||||
"""
|
||||
)
|
||||
@@ -0,0 +1,20 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
async def migrate():
|
||||
conn = connections.get("default")
|
||||
await conn.execute_script(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS share_code_reservations (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
code VARCHAR(255) NOT NULL UNIQUE,
|
||||
file_code_id INT NULL,
|
||||
reason VARCHAR(32) NOT NULL DEFAULT 'retired',
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_share_code_reservations_code
|
||||
ON share_code_reservations(code);
|
||||
CREATE INDEX IF NOT EXISTS idx_share_code_reservations_file_code_id
|
||||
ON share_code_reservations(file_code_id);
|
||||
"""
|
||||
)
|
||||
@@ -0,0 +1,14 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
async def migrate():
|
||||
"""把既有审计日志中的取件码也登记为永久占用。"""
|
||||
conn = connections.get("default")
|
||||
await conn.execute_query(
|
||||
"""
|
||||
INSERT OR IGNORE INTO share_code_reservations (code, file_code_id, reason)
|
||||
SELECT DISTINCT TRIM(code), file_code_id, 'historical_audit'
|
||||
FROM transfer_stats
|
||||
WHERE code IS NOT NULL AND TRIM(code) <> ''
|
||||
"""
|
||||
)
|
||||
@@ -46,6 +46,19 @@ class FileCodes(models.Model):
|
||||
return f"{self.file_path}/{self.uuid_file_name}"
|
||||
|
||||
|
||||
class ShareCodeReservations(models.Model):
|
||||
"""已退役取件码的永久封存登记,防止恢复文件后旧码被重新分配。"""
|
||||
|
||||
id = fields.IntField(pk=True)
|
||||
code = fields.CharField(max_length=255, unique=True, index=True)
|
||||
file_code_id = fields.IntField(null=True, index=True)
|
||||
reason = fields.CharField(max_length=32, default="retired")
|
||||
created_at = fields.DatetimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
table = "share_code_reservations"
|
||||
|
||||
|
||||
class UploadChunk(models.Model):
|
||||
id = fields.IntField(pk=True)
|
||||
upload_id = fields.CharField(max_length=36, index=True)
|
||||
@@ -108,6 +121,15 @@ class PresignUploadSession(models.Model):
|
||||
return self.expires_at < await get_now()
|
||||
|
||||
|
||||
class StorageReservation(models.Model):
|
||||
"""尚未写入 FileCodes 的上传容量预留。"""
|
||||
|
||||
id = fields.IntField(pk=True)
|
||||
token = fields.CharField(max_length=64, unique=True, index=True)
|
||||
size = fields.BigIntField()
|
||||
expires_at = fields.DatetimeField(index=True)
|
||||
|
||||
|
||||
file_codes_pydantic = pydantic_model_creator(FileCodes, name="FileCodes")
|
||||
upload_chunk_pydantic = pydantic_model_creator(UploadChunk, name="UploadChunk")
|
||||
key_value_pydantic = pydantic_model_creator(KeyValue, name="KeyValue")
|
||||
|
||||
+43
-5
@@ -8,6 +8,43 @@ from core.settings import settings
|
||||
from core.utils import get_now
|
||||
|
||||
|
||||
def _detect_sql_dialect() -> str:
|
||||
"""识别当前默认连接的 SQL 方言。
|
||||
|
||||
优先使用 Tortoise capabilities.dialect;
|
||||
回退到 db_config 中的 engine 路径字符串。
|
||||
"""
|
||||
conn = connections.get("default")
|
||||
dialect = getattr(getattr(conn, "capabilities", None), "dialect", "") or ""
|
||||
if dialect:
|
||||
return dialect.lower()
|
||||
|
||||
try:
|
||||
engine = str(connections.db_config.get("default", {}).get("engine", "")).lower()
|
||||
except Exception:
|
||||
engine = ""
|
||||
if "postgres" in engine or "asyncpg" in engine or "psycopg" in engine:
|
||||
return "postgres"
|
||||
if "mysql" in engine:
|
||||
return "mysql"
|
||||
if "sqlite" in engine:
|
||||
return "sqlite"
|
||||
return "sqlite"
|
||||
|
||||
|
||||
def _sql_placeholders(count: int) -> list[str]:
|
||||
"""根据数据库方言生成参数占位符(多数据库兼容)。
|
||||
|
||||
SQLite 用 ?,PostgreSQL 用 $1/$2/...,MySQL 用 %s。
|
||||
"""
|
||||
dialect = _detect_sql_dialect()
|
||||
if dialect in {"postgres", "postgresql"}:
|
||||
return [f"${i}" for i in range(1, count + 1)]
|
||||
if dialect == "mysql":
|
||||
return ["%s"] * count
|
||||
return ["?"] * count
|
||||
|
||||
|
||||
def get_storage_limit() -> int:
|
||||
try:
|
||||
return max(0, int(getattr(settings, "storageLimit", 0)))
|
||||
@@ -49,15 +86,16 @@ async def reserve_storage(token: str, size: int, ttl_seconds: int) -> None:
|
||||
raise HTTPException(status_code=409, detail="上传容量预留信息不一致")
|
||||
|
||||
try:
|
||||
ph = _sql_placeholders(6)
|
||||
affected, _ = await conn.execute_query(
|
||||
"""
|
||||
f"""
|
||||
INSERT INTO storagereservation (token, size, expires_at)
|
||||
SELECT ?, ?, ?
|
||||
SELECT {ph[0]}, {ph[1]}, {ph[2]}
|
||||
WHERE (
|
||||
COALESCE((SELECT SUM(size) FROM filecodes), 0)
|
||||
+ COALESCE((SELECT SUM(size) FROM storagereservation WHERE expires_at > ?), 0)
|
||||
+ ?
|
||||
) <= ?
|
||||
+ COALESCE((SELECT SUM(size) FROM storagereservation WHERE expires_at > {ph[3]}), 0)
|
||||
+ {ph[4]}
|
||||
) <= {ph[5]}
|
||||
""",
|
||||
[token, requested_size, expires_at, now, requested_size, limit],
|
||||
)
|
||||
|
||||
+5
-2
@@ -8,7 +8,7 @@ from fastapi import UploadFile, HTTPException
|
||||
from typing import Optional, Tuple
|
||||
|
||||
from apps.base.dependencies import IPRateLimit
|
||||
from apps.base.models import FileCodes
|
||||
from apps.base.models import FileCodes, ShareCodeReservations
|
||||
from core.settings import settings
|
||||
from core.utils import (
|
||||
get_random_num,
|
||||
@@ -43,6 +43,7 @@ async def get_chunk_file_path_name(
|
||||
) -> Tuple[str, str, str, str, str]:
|
||||
today = await get_now()
|
||||
storage_path = settings.storage_path.strip("/")
|
||||
file_name = await sanitize_filename(unquote(file_name or ""))
|
||||
base_path = f"share/data/{today.strftime('%Y/%m/%d')}/{upload_id}"
|
||||
path = f"{storage_path}/{base_path}" if storage_path else base_path
|
||||
prefix, suffix = os.path.splitext(file_name)
|
||||
@@ -122,7 +123,9 @@ async def get_random_code(style: str | None = None) -> str:
|
||||
if code_style == "number"
|
||||
else await get_random_string(CODE_LENGTH)
|
||||
)
|
||||
if not await FileCodes.filter(code=code).exists():
|
||||
if not await FileCodes.filter(code=code).exists() and not await ShareCodeReservations.filter(
|
||||
code=code
|
||||
).exists():
|
||||
return str(code)
|
||||
raise HTTPException(status_code=503, detail="取件码生成暂时繁忙,请重试")
|
||||
|
||||
|
||||
+11
-7
@@ -437,7 +437,8 @@ async def parse_complete_upload(request: Request) -> CompleteUploadModel:
|
||||
|
||||
@chunk_api.post("/upload/init/", dependencies=[Depends(share_required_login)])
|
||||
async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chunk_upload)):
|
||||
validate_file_type(data.file_name)
|
||||
safe_file_name = await sanitize_filename(unquote(data.file_name or ""))
|
||||
validate_file_type(safe_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
|
||||
@@ -467,7 +468,7 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
||||
chunk_hash=data.file_hash,
|
||||
chunk_index=-1,
|
||||
file_size=data.file_size,
|
||||
file_name=data.file_name,
|
||||
file_name=safe_file_name,
|
||||
).first()
|
||||
|
||||
if existing_session:
|
||||
@@ -503,7 +504,9 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
||||
await reserve_storage(
|
||||
reservation_token, data.file_size, ttl_seconds=chunk_expire_seconds
|
||||
)
|
||||
_, _, _, _, save_path = await get_chunk_file_path_name(data.file_name, upload_id)
|
||||
_, _, _, safe_file_name, save_path = await get_chunk_file_path_name(
|
||||
data.file_name, upload_id
|
||||
)
|
||||
try:
|
||||
await UploadChunk.create(
|
||||
upload_id=upload_id,
|
||||
@@ -512,7 +515,7 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
||||
file_size=data.file_size,
|
||||
chunk_size=data.chunk_size,
|
||||
chunk_hash=data.file_hash,
|
||||
file_name=data.file_name,
|
||||
file_name=safe_file_name,
|
||||
save_path=save_path,
|
||||
)
|
||||
except Exception:
|
||||
@@ -714,7 +717,8 @@ async def complete_upload(
|
||||
|
||||
save_path = chunk_info.save_path
|
||||
path = os.path.dirname(save_path) if save_path else ""
|
||||
prefix, suffix = os.path.splitext(chunk_info.file_name)
|
||||
safe_file_name = os.path.basename(save_path) if save_path else ""
|
||||
prefix, suffix = os.path.splitext(safe_file_name)
|
||||
|
||||
try:
|
||||
# 合并文件并计算哈希
|
||||
@@ -733,7 +737,7 @@ async def complete_upload(
|
||||
expired_count=expired_count,
|
||||
used_count=used_count,
|
||||
file_path=path,
|
||||
uuid_file_name=f"{prefix}{suffix}",
|
||||
uuid_file_name=safe_file_name,
|
||||
prefix=prefix,
|
||||
suffix=suffix,
|
||||
)
|
||||
@@ -744,7 +748,7 @@ async def complete_upload(
|
||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||
await release_storage(f"chunk:{upload_id}")
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
return APIResponse(detail={"code": code, "name": chunk_info.file_name})
|
||||
return APIResponse(detail={"code": code, "name": safe_file_name})
|
||||
except ValueError as e:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
except Exception as e:
|
||||
|
||||
+46
-12
@@ -1,26 +1,60 @@
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
PRODUCTION_ENVIRONMENTS = {"production", "prod"}
|
||||
LOG_LEVELS = {
|
||||
"debug": logging.DEBUG,
|
||||
"info": logging.INFO,
|
||||
"warning": logging.WARNING,
|
||||
"error": logging.ERROR,
|
||||
"critical": logging.CRITICAL,
|
||||
}
|
||||
|
||||
|
||||
def is_production_environment() -> bool:
|
||||
environment = os.getenv("APP_ENV", "development").strip().lower()
|
||||
return environment in PRODUCTION_ENVIRONMENTS
|
||||
|
||||
|
||||
def get_log_level_name() -> str:
|
||||
configured_level = os.getenv("LOG_LEVEL", "").strip().lower()
|
||||
if configured_level in LOG_LEVELS:
|
||||
return configured_level
|
||||
return "warning" if is_production_environment() else "info"
|
||||
|
||||
|
||||
def get_log_level() -> int:
|
||||
return LOG_LEVELS[get_log_level_name()]
|
||||
|
||||
|
||||
def is_access_log_enabled() -> bool:
|
||||
configured_value = os.getenv("ACCESS_LOG")
|
||||
if configured_value is not None:
|
||||
return configured_value.strip().lower() in {"1", "true", "yes", "on"}
|
||||
return not is_production_environment()
|
||||
|
||||
|
||||
def setup_logger():
|
||||
# 创建logger对象
|
||||
_logger = logging.getLogger('FileCodeBox')
|
||||
_logger.setLevel(logging.INFO)
|
||||
_logger = logging.getLogger("FileCodeBox")
|
||||
level = get_log_level()
|
||||
_logger.setLevel(level)
|
||||
_logger.propagate = False
|
||||
|
||||
# 创建控制台处理器
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(logging.INFO)
|
||||
if not _logger.handlers:
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
_logger.addHandler(console_handler)
|
||||
else:
|
||||
console_handler = _logger.handlers[0]
|
||||
console_handler.setLevel(level)
|
||||
|
||||
# 设置日志格式
|
||||
formatter = logging.Formatter(
|
||||
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
"%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
||||
datefmt="%Y-%m-%d %H:%M:%S",
|
||||
)
|
||||
console_handler.setFormatter(formatter)
|
||||
|
||||
# 添加处理器到logger
|
||||
_logger.addHandler(console_handler)
|
||||
|
||||
return _logger
|
||||
|
||||
|
||||
|
||||
+103
-86
@@ -25,6 +25,7 @@ from core.settings import data_root, settings
|
||||
from apps.base.models import FileCodes, UploadChunk
|
||||
from core.utils import get_file_url, sanitize_filename
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
|
||||
class FileStorageInterface:
|
||||
@@ -115,6 +116,19 @@ class SystemFileStorage(FileStorageInterface):
|
||||
self.chunk_size = 256 * 1024
|
||||
self.root_path = data_root
|
||||
|
||||
def _resolve_safe_path(self, relative_path: str) -> Path:
|
||||
"""将相对路径解析到数据根目录内,阻止路径穿越。"""
|
||||
root = self.root_path.resolve()
|
||||
raw = str(relative_path or "").replace("\\", "/").lstrip("/")
|
||||
if any(part == ".." for part in raw.split("/")):
|
||||
raise ValueError("非法文件路径")
|
||||
candidate = (root / raw).resolve()
|
||||
try:
|
||||
candidate.relative_to(root)
|
||||
except ValueError as exc:
|
||||
raise ValueError("非法文件路径") from exc
|
||||
return candidate
|
||||
|
||||
def _save(self, file, save_path):
|
||||
with open(save_path, "wb") as f:
|
||||
chunk = file.read(self.chunk_size)
|
||||
@@ -123,19 +137,19 @@ class SystemFileStorage(FileStorageInterface):
|
||||
chunk = file.read(self.chunk_size)
|
||||
|
||||
async def save_file(self, file: UploadFile, save_path: str):
|
||||
path_obj = Path(save_path)
|
||||
directory = str(path_obj.parent)
|
||||
path_obj = Path(str(save_path).replace("\\", "/"))
|
||||
directory = str(path_obj.parent).replace("\\", "/").lstrip("/")
|
||||
# 提取原始文件名并进行清理
|
||||
filename = await sanitize_filename(path_obj.name)
|
||||
# 构建安全的完整保存路径
|
||||
safe_save_path = self.root_path / directory / filename
|
||||
safe_save_path = self._resolve_safe_path(f"{directory}/{filename}" if directory not in {"", "."} else filename)
|
||||
# 确保目录存在
|
||||
if not safe_save_path.parent.exists():
|
||||
safe_save_path.parent.mkdir(parents=True)
|
||||
await asyncio.to_thread(self._save, file.file, safe_save_path)
|
||||
|
||||
async def delete_file(self, file_code: FileCodes):
|
||||
save_path = self.root_path / await file_code.get_file_path()
|
||||
save_path = self._resolve_safe_path(await file_code.get_file_path())
|
||||
if save_path.exists():
|
||||
save_path.unlink()
|
||||
|
||||
@@ -151,7 +165,7 @@ class SystemFileStorage(FileStorageInterface):
|
||||
return await get_file_url(file_code.code)
|
||||
|
||||
async def get_file_response(self, file_code: FileCodes):
|
||||
file_path = self.root_path / await file_code.get_file_path()
|
||||
file_path = self._resolve_safe_path(await file_code.get_file_path())
|
||||
if not file_path.exists():
|
||||
return APIResponse(code=404, detail="文件已过期删除")
|
||||
filename = f"{file_code.prefix}{file_code.suffix}"
|
||||
@@ -183,8 +197,11 @@ class SystemFileStorage(FileStorageInterface):
|
||||
:param chunk_hash: 分片哈希值
|
||||
:param save_path: 文件保存路径
|
||||
"""
|
||||
chunk_dir = self.root_path / save_path
|
||||
chunk_path = chunk_dir.parent / 'chunks' / upload_id / f"{chunk_index}.part"
|
||||
# 先校验目标文件路径合法,再将分片落到同级 chunks 目录。
|
||||
self._resolve_safe_path(save_path)
|
||||
chunk_path = self._resolve_safe_path(
|
||||
str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part")
|
||||
)
|
||||
if not chunk_path.parent.exists():
|
||||
chunk_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# 使用临时文件写入,确保原子性
|
||||
@@ -207,9 +224,11 @@ class SystemFileStorage(FileStorageInterface):
|
||||
:param save_path: 文件保存路径
|
||||
:return: (文件路径, 文件哈希值)
|
||||
"""
|
||||
output_path = self.root_path / save_path
|
||||
output_path = self._resolve_safe_path(save_path)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
chunk_base_dir = output_path.parent / 'chunks' / upload_id
|
||||
chunk_base_dir = self._resolve_safe_path(
|
||||
str(Path(save_path).parent / "chunks" / upload_id)
|
||||
)
|
||||
file_sha256 = hashlib.sha256()
|
||||
|
||||
# 使用临时文件写入,确保原子性
|
||||
@@ -245,19 +264,21 @@ class SystemFileStorage(FileStorageInterface):
|
||||
:param upload_id: 上传会话ID
|
||||
:param save_path: 文件保存路径
|
||||
"""
|
||||
chunk_dir = (self.root_path / save_path).parent / 'chunks' / upload_id
|
||||
chunk_dir = self._resolve_safe_path(
|
||||
str(Path(save_path).parent / "chunks" / upload_id)
|
||||
)
|
||||
if chunk_dir.exists():
|
||||
try:
|
||||
shutil.rmtree(chunk_dir)
|
||||
except Exception as e:
|
||||
logger.info(f"清理本地分片目录失败: {e}")
|
||||
logger.warning(f"清理本地分片目录失败: {e}")
|
||||
# 清理父级 chunks 目录(如果为空)
|
||||
chunks_parent = chunk_dir.parent
|
||||
if chunks_parent.exists() and not any(chunks_parent.iterdir()):
|
||||
try:
|
||||
chunks_parent.rmdir()
|
||||
except Exception as e:
|
||||
logger.info(f"清理 chunks 父目录失败: {e}")
|
||||
logger.warning(f"清理 chunks 父目录失败: {e}")
|
||||
|
||||
async def file_exists(self, save_path: str) -> bool:
|
||||
"""
|
||||
@@ -265,7 +286,10 @@ class SystemFileStorage(FileStorageInterface):
|
||||
:param save_path: 文件路径
|
||||
:return: 文件是否存在
|
||||
"""
|
||||
file_path = self.root_path / save_path
|
||||
try:
|
||||
file_path = self._resolve_safe_path(save_path)
|
||||
except ValueError:
|
||||
return False
|
||||
return file_path.exists()
|
||||
|
||||
|
||||
@@ -279,6 +303,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,
|
||||
@@ -290,14 +315,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,
|
||||
@@ -307,12 +344,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()
|
||||
)
|
||||
@@ -322,12 +354,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(
|
||||
@@ -383,7 +410,9 @@ class S3FileStorage(FileStorageInterface):
|
||||
return StreamingResponse(
|
||||
stream_generator(),
|
||||
media_type="application/octet-stream",
|
||||
headers=headers
|
||||
headers=headers,
|
||||
# 兜底关闭会话:客户端中断时与 generator finally 双保险
|
||||
background=BackgroundTask(session.close),
|
||||
)
|
||||
except HTTPException:
|
||||
raise
|
||||
@@ -396,12 +425,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={
|
||||
@@ -418,13 +442,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,
|
||||
@@ -444,13 +462,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,
|
||||
@@ -524,13 +536,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')
|
||||
@@ -543,7 +549,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
Delete={'Objects': delete_objects}
|
||||
)
|
||||
except Exception as e:
|
||||
logger.info(f"清理 S3 分片数据时出错: {e}")
|
||||
logger.warning(f"清理 S3 分片数据时出错: {e}")
|
||||
|
||||
async def generate_presigned_upload_url(self, save_path: str, expires_in: int = 900) -> Optional[str]:
|
||||
"""
|
||||
@@ -552,13 +558,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={
|
||||
@@ -574,18 +574,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):
|
||||
@@ -737,7 +750,9 @@ class OneDriveFileStorage(FileStorageInterface):
|
||||
return StreamingResponse(
|
||||
stream_generator(),
|
||||
media_type="application/octet-stream",
|
||||
headers=headers
|
||||
headers=headers,
|
||||
# 兜底关闭会话:客户端中断时与 generator finally 双保险
|
||||
background=BackgroundTask(session.close),
|
||||
)
|
||||
except HTTPException:
|
||||
raise
|
||||
@@ -862,7 +877,7 @@ class OneDriveFileStorage(FileStorageInterface):
|
||||
try:
|
||||
await asyncio.to_thread(self._delete_chunk_dir, chunk_dir)
|
||||
except Exception as e:
|
||||
logger.info(f"清理 OneDrive 分片时出错: {e}")
|
||||
logger.warning(f"清理 OneDrive 分片时出错: {e}")
|
||||
|
||||
def _file_exists(self, save_path: str) -> bool:
|
||||
"""同步检查文件是否存在"""
|
||||
@@ -1020,7 +1035,7 @@ class OpenDALFileStorage(FileStorageInterface):
|
||||
# OpenDAL 支持递归删除
|
||||
await self.operator.remove_all(chunk_dir)
|
||||
except Exception as e:
|
||||
logger.info(f"清理 OpenDAL 分片时出错: {e}")
|
||||
logger.warning(f"清理 OpenDAL 分片时出错: {e}")
|
||||
|
||||
async def file_exists(self, save_path: str) -> bool:
|
||||
"""
|
||||
@@ -1230,7 +1245,9 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
return StreamingResponse(
|
||||
stream_generator(),
|
||||
media_type="application/octet-stream",
|
||||
headers=headers
|
||||
headers=headers,
|
||||
# 兜底关闭会话:客户端中断时与 generator finally 双保险
|
||||
background=BackgroundTask(session.close),
|
||||
)
|
||||
except aiohttp.ClientError as e:
|
||||
raise HTTPException(
|
||||
@@ -1346,16 +1363,16 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
file_url = self._build_url(file_path)
|
||||
async with session.delete(file_url) as delete_resp:
|
||||
if delete_resp.status not in (200, 204, 404):
|
||||
logger.info(f"删除分片文件失败: {file_path}")
|
||||
logger.warning(f"删除分片文件失败: {file_path}")
|
||||
|
||||
# 删除分片目录
|
||||
async with session.delete(chunk_dir_url) as delete_resp:
|
||||
if delete_resp.status not in (200, 204, 404):
|
||||
logger.info(f"删除分片目录失败: {chunk_dir_url}")
|
||||
logger.warning(f"删除分片目录失败: {chunk_dir_url}")
|
||||
else:
|
||||
logger.info(f"分片目录不存在: {chunk_dir_url}")
|
||||
except Exception as e:
|
||||
logger.info(f"清理 WebDAV 分片时出错: {e}")
|
||||
logger.warning(f"清理 WebDAV 分片时出错: {e}")
|
||||
|
||||
async def file_exists(self, save_path: str) -> bool:
|
||||
"""
|
||||
|
||||
+10
-10
@@ -4,7 +4,6 @@
|
||||
# @Software: PyCharm
|
||||
import asyncio
|
||||
import datetime
|
||||
import logging
|
||||
import os
|
||||
|
||||
from tortoise.expressions import Q
|
||||
@@ -18,6 +17,7 @@ from apps.base.models import (
|
||||
from apps.admin.services import FileService
|
||||
from apps.base.utils import ip_limit, get_chunk_file_path_name
|
||||
from core.config import refresh_settings
|
||||
from core.logger import logger
|
||||
from core.settings import settings, data_root
|
||||
from core.storage import FileStorageInterface, storages
|
||||
from core.utils import get_now
|
||||
@@ -45,7 +45,7 @@ async def delete_expire_files():
|
||||
try:
|
||||
await file_service.move_to_trash(exp, reason="expired")
|
||||
except Exception as e:
|
||||
logging.error(f"移入过期文件回收站失败 code={exp.code}: {e}")
|
||||
logger.error(f"移入过期文件回收站失败 code={exp.code}: {e}")
|
||||
expired_trash = await FileCodes.filter(
|
||||
is_trashed=True,
|
||||
trash_expires_at__isnull=False,
|
||||
@@ -55,9 +55,9 @@ async def delete_expire_files():
|
||||
try:
|
||||
await file_service.purge_trashed_file(item)
|
||||
except Exception as e:
|
||||
logging.error(f"彻底清理回收站文件失败 id={item.id}: {e}")
|
||||
logger.error(f"彻底清理回收站文件失败 id={item.id}: {e}")
|
||||
except Exception as e:
|
||||
logging.error(e)
|
||||
logger.error(e)
|
||||
finally:
|
||||
await asyncio.sleep(600)
|
||||
|
||||
@@ -83,7 +83,7 @@ async def clean_incomplete_uploads():
|
||||
)
|
||||
await file_storage.clean_chunks(session.upload_id, save_path)
|
||||
except Exception as e:
|
||||
logging.error(
|
||||
logger.error(
|
||||
f"清理分片文件失败 upload_id={session.upload_id}: {e}"
|
||||
)
|
||||
|
||||
@@ -92,14 +92,14 @@ async def clean_incomplete_uploads():
|
||||
await StorageReservation.filter(
|
||||
token=f"chunk:{session.upload_id}"
|
||||
).delete()
|
||||
logging.info(f"已清理过期上传会话 upload_id={session.upload_id}")
|
||||
logger.info(f"已清理过期上传会话 upload_id={session.upload_id}")
|
||||
except Exception as e:
|
||||
logging.error(
|
||||
logger.error(
|
||||
f"删除分片记录失败 upload_id={session.upload_id}: {e}"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"清理未完成上传任务异常: {e}")
|
||||
logger.error(f"清理未完成上传任务异常: {e}")
|
||||
finally:
|
||||
await asyncio.sleep(3600)
|
||||
|
||||
@@ -124,7 +124,7 @@ async def clean_expired_presign_sessions():
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
logging.error(
|
||||
logger.error(
|
||||
"清理过期直传文件失败 "
|
||||
f"upload_id={session.upload_id}: {e}"
|
||||
)
|
||||
@@ -133,6 +133,6 @@ async def clean_expired_presign_sessions():
|
||||
).delete()
|
||||
await session.delete()
|
||||
except Exception as e:
|
||||
logging.error(f"清理过期预签名会话异常: {e}")
|
||||
logger.error(f"清理过期预签名会话异常: {e}")
|
||||
finally:
|
||||
await asyncio.sleep(900)
|
||||
+20
-1
@@ -1 +1,20 @@
|
||||
APP_VERSION = "2.0.0-dev"
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
VERSION_FILE = Path(__file__).resolve().parents[1] / "VERSION"
|
||||
VERSION_PATTERN = re.compile(
|
||||
r"^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$"
|
||||
)
|
||||
|
||||
|
||||
def load_app_version() -> str:
|
||||
version = os.getenv("APP_VERSION") or VERSION_FILE.read_text(encoding="utf-8")
|
||||
version = version.strip()
|
||||
if not VERSION_PATTERN.fullmatch(version):
|
||||
raise RuntimeError(f"无效的应用版本号: {version!r}")
|
||||
return version
|
||||
|
||||
|
||||
APP_VERSION = load_app_version()
|
||||
@@ -3,13 +3,18 @@
|
||||
# @File : main.py
|
||||
# @Software: PyCharm
|
||||
import asyncio
|
||||
import html
|
||||
import re
|
||||
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse, HTMLResponse, PlainTextResponse
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse
|
||||
from starlette.middleware.gzip import GZipMiddleware
|
||||
|
||||
from tortoise import Tortoise
|
||||
from tortoise.contrib.fastapi import register_tortoise
|
||||
|
||||
@@ -17,28 +22,44 @@ 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.config import ensure_settings_row, refresh_settings
|
||||
from core.config import (
|
||||
ensure_security_settings,
|
||||
ensure_settings_row,
|
||||
initialize_system,
|
||||
is_runtime_initialized,
|
||||
refresh_settings,
|
||||
)
|
||||
from core.database import db_startup_lock, get_db_config, init_db
|
||||
from core.logger import logger
|
||||
from core.logger import get_log_level_name, is_access_log_enabled, logger
|
||||
from core.response import APIResponse
|
||||
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.tasks import (
|
||||
clean_expired_presign_sessions,
|
||||
clean_incomplete_uploads,
|
||||
delete_expire_files,
|
||||
)
|
||||
from core.version import APP_VERSION
|
||||
|
||||
|
||||
def normalize_public_flag(value) -> int:
|
||||
if isinstance(value, str):
|
||||
return int(value.strip().lower() in {"1", "true", "on", "yes"})
|
||||
return int(bool(value))
|
||||
|
||||
|
||||
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,
|
||||
"show_admin_address": normalize_public_flag(settings.showAdminAddr),
|
||||
"max_save_seconds": settings.max_save_seconds,
|
||||
}
|
||||
|
||||
@@ -54,11 +75,12 @@ def build_public_meta() -> dict:
|
||||
"features": {
|
||||
"chunkUpload": bool(settings.enableChunk),
|
||||
"guestUpload": bool(settings.openUpload),
|
||||
"adminAddressVisible": bool(settings.showAdminAddr),
|
||||
"adminAddressVisible": bool(normalize_public_flag(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,
|
||||
@@ -66,6 +88,639 @@ def build_public_meta() -> dict:
|
||||
}
|
||||
|
||||
|
||||
FILE_SIZE_UNITS = {"KB": 1024, "MB": 1024**2, "GB": 1024**3}
|
||||
SAVE_TIME_UNITS = {"second": 1, "minute": 60, "hour": 3600, "day": 86400}
|
||||
EXPIRE_STYLE_OPTIONS = [
|
||||
("day", "按天"),
|
||||
("hour", "按小时"),
|
||||
("minute", "按分钟"),
|
||||
("forever", "永久"),
|
||||
("count", "按取件次数"),
|
||||
]
|
||||
|
||||
|
||||
def get_form_value(data: dict, key: str, default: str = "") -> str:
|
||||
value = data.get(key, default)
|
||||
if isinstance(value, list):
|
||||
value = value[-1] if value else default
|
||||
return str(value if value is not None else default)
|
||||
|
||||
|
||||
def get_form_list(data: dict, key: str) -> list[str]:
|
||||
value = data.get(key, [])
|
||||
if isinstance(value, list):
|
||||
return [str(item) for item in value if str(item)]
|
||||
if value:
|
||||
return [str(value)]
|
||||
return []
|
||||
|
||||
|
||||
def normalize_bool_field(data: dict, key: str, default: bool) -> bool:
|
||||
if key not in data:
|
||||
return default
|
||||
return get_form_value(data, key).lower() in {"1", "true", "on", "yes"}
|
||||
|
||||
|
||||
def parse_int_field(
|
||||
data: dict,
|
||||
key: str,
|
||||
default: int,
|
||||
label: str,
|
||||
min_value: int = 0,
|
||||
max_value: int | None = None,
|
||||
) -> int:
|
||||
raw_value = get_form_value(data, key, str(default)).strip()
|
||||
try:
|
||||
value = int(raw_value)
|
||||
except ValueError:
|
||||
raise ValueError(f"{label} 必须是整数")
|
||||
if value < min_value:
|
||||
raise ValueError(f"{label} 不能小于 {min_value}")
|
||||
if max_value is not None and value > max_value:
|
||||
raise ValueError(f"{label} 不能大于 {max_value}")
|
||||
return value
|
||||
|
||||
|
||||
def parse_allowed_file_types(value: str) -> list[str]:
|
||||
items = [item.strip() for item in value.split(",") if item.strip()]
|
||||
return items or ["*"]
|
||||
|
||||
|
||||
def parse_setup_options(data: dict) -> dict:
|
||||
upload_size_unit = get_form_value(data, "upload_size_unit", "MB").upper()
|
||||
if upload_size_unit not in FILE_SIZE_UNITS:
|
||||
raise ValueError("文件大小单位不正确")
|
||||
upload_size_value = parse_int_field(
|
||||
data, "upload_size_value", 10, "文件大小限制", min_value=1
|
||||
)
|
||||
|
||||
save_time_unit = get_form_value(data, "save_time_unit", "day")
|
||||
if save_time_unit not in SAVE_TIME_UNITS:
|
||||
raise ValueError("最长保存时间单位不正确")
|
||||
save_time_value = parse_int_field(
|
||||
data, "save_time_value", 0, "最长保存时间", min_value=0
|
||||
)
|
||||
|
||||
expire_styles = get_form_list(data, "expireStyle")
|
||||
valid_expire_styles = {style for style, _label in EXPIRE_STYLE_OPTIONS}
|
||||
expire_styles = [style for style in expire_styles if style in valid_expire_styles]
|
||||
if not expire_styles:
|
||||
raise ValueError("至少需要选择一种过期方式")
|
||||
|
||||
code_generate_type = get_form_value(
|
||||
data, "code_generate_type", DEFAULT_CONFIG["code_generate_type"]
|
||||
)
|
||||
if code_generate_type not in {"number", "secret"}:
|
||||
raise ValueError("提取码类型不正确")
|
||||
|
||||
return {
|
||||
"allowed_file_types": parse_allowed_file_types(
|
||||
get_form_value(data, "allowed_file_types", "*")
|
||||
),
|
||||
"code_generate_type": code_generate_type,
|
||||
"enableChunk": int(normalize_bool_field(data, "enableChunk", False)),
|
||||
"errorCount": parse_int_field(
|
||||
data, "errorCount", DEFAULT_CONFIG["errorCount"], "取件错误次数限制", 1
|
||||
),
|
||||
"errorMinute": parse_int_field(
|
||||
data, "errorMinute", DEFAULT_CONFIG["errorMinute"], "取件错误检测窗口", 1
|
||||
),
|
||||
"loginCount": parse_int_field(
|
||||
data, "loginCount", DEFAULT_CONFIG["loginCount"], "登录失败次数限制", 1
|
||||
),
|
||||
"loginMinute": parse_int_field(
|
||||
data, "loginMinute", DEFAULT_CONFIG["loginMinute"], "登录失败检测窗口", 1
|
||||
),
|
||||
"expireStyle": expire_styles,
|
||||
"max_save_seconds": save_time_value * SAVE_TIME_UNITS[save_time_unit],
|
||||
"openUpload": int(normalize_bool_field(data, "openUpload", True)),
|
||||
"uploadCount": parse_int_field(
|
||||
data, "uploadCount", DEFAULT_CONFIG["uploadCount"], "上传次数限制", 1
|
||||
),
|
||||
"uploadMinute": parse_int_field(
|
||||
data, "uploadMinute", DEFAULT_CONFIG["uploadMinute"], "上传检测窗口", 1
|
||||
),
|
||||
"uploadSize": upload_size_value * FILE_SIZE_UNITS[upload_size_unit],
|
||||
}
|
||||
|
||||
|
||||
def build_expire_style_inputs(selected_styles: list[str]) -> str:
|
||||
inputs = []
|
||||
selected = set(selected_styles)
|
||||
for style, label in EXPIRE_STYLE_OPTIONS:
|
||||
checked = " checked" if style in selected else ""
|
||||
inputs.append(
|
||||
f'<label class="check"><input type="checkbox" name="expireStyle" value="{style}"{checked}> {label}</label>'
|
||||
)
|
||||
return "\n ".join(inputs)
|
||||
|
||||
|
||||
def build_setup_page(error: str = "", form: dict | None = None) -> str:
|
||||
form = form or {}
|
||||
escaped_error = html.escape(error)
|
||||
escaped_site_name = html.escape(
|
||||
get_form_value(form, "site_name", DEFAULT_CONFIG["name"])
|
||||
)
|
||||
escaped_allowed_types = html.escape(get_form_value(form, "allowed_file_types", "*"))
|
||||
upload_size_value = html.escape(get_form_value(form, "upload_size_value", "10"))
|
||||
upload_size_unit = get_form_value(form, "upload_size_unit", "MB").upper()
|
||||
save_time_value = html.escape(get_form_value(form, "save_time_value", "0"))
|
||||
save_time_unit = get_form_value(form, "save_time_unit", "day")
|
||||
upload_minute = html.escape(
|
||||
get_form_value(form, "uploadMinute", str(DEFAULT_CONFIG["uploadMinute"]))
|
||||
)
|
||||
upload_count = html.escape(
|
||||
get_form_value(form, "uploadCount", str(DEFAULT_CONFIG["uploadCount"]))
|
||||
)
|
||||
error_minute = html.escape(
|
||||
get_form_value(form, "errorMinute", str(DEFAULT_CONFIG["errorMinute"]))
|
||||
)
|
||||
error_count = html.escape(
|
||||
get_form_value(form, "errorCount", str(DEFAULT_CONFIG["errorCount"]))
|
||||
)
|
||||
login_minute = html.escape(
|
||||
get_form_value(form, "loginMinute", str(DEFAULT_CONFIG["loginMinute"]))
|
||||
)
|
||||
login_count = html.escape(
|
||||
get_form_value(form, "loginCount", str(DEFAULT_CONFIG["loginCount"]))
|
||||
)
|
||||
open_upload_checked = (
|
||||
" checked" if normalize_bool_field(form, "openUpload", True) else ""
|
||||
)
|
||||
chunk_checked = (
|
||||
" checked" if normalize_bool_field(form, "enableChunk", False) else ""
|
||||
)
|
||||
code_generate_type = get_form_value(
|
||||
form, "code_generate_type", DEFAULT_CONFIG["code_generate_type"]
|
||||
)
|
||||
selected_expire_styles = get_form_list(form, "expireStyle") or list(
|
||||
DEFAULT_CONFIG["expireStyle"]
|
||||
)
|
||||
expire_style_inputs = build_expire_style_inputs(selected_expire_styles)
|
||||
size_unit_options = "\n".join(
|
||||
f'<option value="{unit}"{" selected" if unit == upload_size_unit else ""}>{unit}</option>'
|
||||
for unit in FILE_SIZE_UNITS
|
||||
)
|
||||
save_time_unit_options = "\n".join(
|
||||
f'<option value="{unit}"{" selected" if unit == save_time_unit else ""}>{label}</option>'
|
||||
for unit, label in [
|
||||
("second", "秒"),
|
||||
("minute", "分钟"),
|
||||
("hour", "小时"),
|
||||
("day", "天"),
|
||||
]
|
||||
)
|
||||
code_type_options = "\n".join(
|
||||
f'<option value="{value}"{" selected" if value == code_generate_type else ""}>{label}</option>'
|
||||
for value, label in [("number", "数字"), ("secret", "随机字符")]
|
||||
)
|
||||
error_block = (
|
||||
f'<div class="alert" role="alert">{escaped_error}</div>' if escaped_error else ""
|
||||
)
|
||||
return f"""<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>初始化 FileCodeBox</title>
|
||||
<style>
|
||||
:root {{
|
||||
color-scheme: light;
|
||||
--bg: #f5f5f7;
|
||||
--panel: rgba(255, 255, 255, .86);
|
||||
--panel-strong: rgba(255, 255, 255, .96);
|
||||
--text: #18181b;
|
||||
--muted: #71717a;
|
||||
--line: rgba(228, 228, 231, .9);
|
||||
--line-strong: rgba(212, 212, 216, .95);
|
||||
--primary: #18181b;
|
||||
--primary-soft: #f4f4f5;
|
||||
--danger-bg: #fef2f2;
|
||||
--danger: #b91c1c;
|
||||
}}
|
||||
* {{ box-sizing: border-box; }}
|
||||
body {{
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 14px;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}}
|
||||
main {{
|
||||
width: min(100%, 1040px);
|
||||
padding: 14px;
|
||||
border: 1px solid rgba(255, 255, 255, .8);
|
||||
border-radius: 20px;
|
||||
background: rgba(255, 255, 255, .62);
|
||||
box-shadow: 0 22px 70px -34px rgba(24, 24, 27, .32);
|
||||
backdrop-filter: blur(22px);
|
||||
}}
|
||||
.setup-header {{
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding: 10px 10px 12px;
|
||||
}}
|
||||
.brand-mark {{
|
||||
flex: 0 0 auto;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
border-radius: 14px;
|
||||
background: #18181b;
|
||||
color: #fff;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0;
|
||||
box-shadow: 0 16px 34px -14px rgba(24, 24, 27, .42);
|
||||
}}
|
||||
.title-wrap {{
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}}
|
||||
h1 {{
|
||||
margin: 0;
|
||||
font-size: 21px;
|
||||
line-height: 1.25;
|
||||
letter-spacing: 0;
|
||||
font-weight: 750;
|
||||
}}
|
||||
p {{
|
||||
margin: 2px 0 0;
|
||||
color: var(--muted);
|
||||
line-height: 1.35;
|
||||
font-size: 13px;
|
||||
}}
|
||||
form {{
|
||||
margin: 0;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 16px;
|
||||
background: var(--panel);
|
||||
}}
|
||||
.panel-grid {{
|
||||
display: grid;
|
||||
grid-template-columns: 1.05fr 1fr 1fr;
|
||||
gap: 10px;
|
||||
}}
|
||||
.panel {{
|
||||
min-width: 0;
|
||||
padding: 10px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
background: rgba(255, 255, 255, .68);
|
||||
}}
|
||||
.panel-wide {{
|
||||
grid-column: 1 / -1;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.3fr) minmax(0, .9fr);
|
||||
gap: 12px;
|
||||
align-items: end;
|
||||
}}
|
||||
.panel-title {{
|
||||
margin: 0 0 2px;
|
||||
color: #18181b;
|
||||
font-size: 13px;
|
||||
font-weight: 760;
|
||||
}}
|
||||
label {{
|
||||
display: block;
|
||||
margin: 8px 0 5px;
|
||||
font-weight: 650;
|
||||
font-size: 12px;
|
||||
color: #3f3f46;
|
||||
}}
|
||||
input, select {{
|
||||
width: 100%;
|
||||
height: 34px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
padding: 0 10px;
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
outline: none;
|
||||
background: rgba(255, 255, 255, .84);
|
||||
transition: border-color .2s ease, box-shadow .2s ease, background-color .2s ease;
|
||||
}}
|
||||
input:focus, select:focus {{
|
||||
border-color: #a1a1aa;
|
||||
background: #fff;
|
||||
box-shadow: 0 10px 22px -12px rgba(24, 24, 27, .2), 0 0 0 3px rgba(24, 24, 27, .06);
|
||||
}}
|
||||
.grid {{
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 6px 12px;
|
||||
}}
|
||||
.full {{ grid-column: 1 / -1; }}
|
||||
.span-2 {{ grid-column: span 2; }}
|
||||
.row {{
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 88px;
|
||||
gap: 8px;
|
||||
}}
|
||||
.checks {{
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 5px;
|
||||
}}
|
||||
.check {{
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-height: 36px;
|
||||
margin: 0;
|
||||
padding: 0 9px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
font-weight: 550;
|
||||
font-size: 13px;
|
||||
color: var(--text);
|
||||
white-space: nowrap;
|
||||
background: rgba(255, 255, 255, .72);
|
||||
transition: border-color .2s ease, background-color .2s ease, box-shadow .2s ease;
|
||||
}}
|
||||
.check:hover {{
|
||||
border-color: var(--line-strong);
|
||||
background: #fff;
|
||||
box-shadow: 0 8px 20px -8px rgba(0, 0, 0, .1);
|
||||
}}
|
||||
.check input {{
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
padding: 0;
|
||||
box-shadow: none;
|
||||
}}
|
||||
.section-title {{
|
||||
display: none;
|
||||
}}
|
||||
.help {{
|
||||
margin: 4px 0 0;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}}
|
||||
.alert {{
|
||||
margin-bottom: 8px;
|
||||
padding: 9px 12px;
|
||||
border-radius: 12px;
|
||||
background: var(--danger-bg);
|
||||
color: var(--danger);
|
||||
font-size: 13px;
|
||||
}}
|
||||
button {{
|
||||
width: 100%;
|
||||
height: 38px;
|
||||
margin-top: 12px;
|
||||
border: 0;
|
||||
border-radius: 12px;
|
||||
background: var(--primary);
|
||||
color: white;
|
||||
font: inherit;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 16px 34px -14px rgba(24, 24, 27, .42);
|
||||
transition: background-color .2s ease, box-shadow .2s ease;
|
||||
}}
|
||||
button:hover {{
|
||||
background: #27272a;
|
||||
box-shadow: 0 16px 34px -14px rgba(24, 24, 27, .56);
|
||||
}}
|
||||
.hint {{
|
||||
margin-top: 8px;
|
||||
margin-bottom: 0;
|
||||
font-size: 12px;
|
||||
}}
|
||||
.compact-help {{
|
||||
display: inline;
|
||||
margin-left: 6px;
|
||||
color: var(--muted);
|
||||
font-weight: 500;
|
||||
font-size: 12px;
|
||||
}}
|
||||
.topline {{
|
||||
display: none;
|
||||
}}
|
||||
.badge {{
|
||||
min-height: 26px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0 10px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 255, 255, .76);
|
||||
color: #52525b;
|
||||
font-size: 12px;
|
||||
font-weight: 650;
|
||||
white-space: nowrap;
|
||||
}}
|
||||
@media (max-width: 640px) {{
|
||||
body {{ padding: 10px; }}
|
||||
main {{ padding: 10px; }}
|
||||
.setup-header {{ align-items: flex-start; padding: 6px 4px 10px; }}
|
||||
.title-wrap {{ align-items: flex-start; }}
|
||||
.panel-grid, .panel-wide {{ grid-template-columns: 1fr; }}
|
||||
.grid, .checks {{ grid-template-columns: 1fr; }}
|
||||
.span-2 {{ grid-column: auto; }}
|
||||
.row {{ grid-template-columns: 1fr; }}
|
||||
.badge {{ display: none; }}
|
||||
}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="setup-header">
|
||||
<div class="title-wrap">
|
||||
<div class="brand-mark">FCB</div>
|
||||
<div>
|
||||
<h1>初始化 FileCodeBox</h1>
|
||||
<p>首次配置管理员密码、上传限制和取件策略,后续可在后台调整。</p>
|
||||
</div>
|
||||
</div>
|
||||
<span class="badge">首次配置向导</span>
|
||||
</div>
|
||||
<form method="post" action="/setup" autocomplete="off">
|
||||
{error_block}
|
||||
<div class="panel-grid">
|
||||
<section class="panel">
|
||||
<div class="panel-title">基础设置</div>
|
||||
<label for="site_name">站点名称</label>
|
||||
<input id="site_name" name="site_name" maxlength="80" value="{escaped_site_name}" placeholder="文件快递柜 - FileCodeBox">
|
||||
|
||||
<label for="admin_password">管理员密码</label>
|
||||
<input id="admin_password" name="admin_password" type="password" minlength="8" required autofocus>
|
||||
|
||||
<label for="confirm_password">确认管理员密码</label>
|
||||
<input id="confirm_password" name="confirm_password" type="password" minlength="8" required>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-title">上传设置</div>
|
||||
<label for="upload_size_value">单文件大小限制</label>
|
||||
<div class="row">
|
||||
<input id="upload_size_value" name="upload_size_value" type="number" min="1" value="{upload_size_value}" required>
|
||||
<select name="upload_size_unit" aria-label="文件大小单位">
|
||||
{size_unit_options}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<label for="uploadCount">上传频率 <span class="compact-help">次数 / 分钟</span></label>
|
||||
<div class="row">
|
||||
<input id="uploadCount" name="uploadCount" type="number" min="1" value="{upload_count}" required>
|
||||
<input name="uploadMinute" type="number" min="1" value="{upload_minute}" aria-label="上传检测窗口分钟" required>
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
<input type="hidden" name="openUpload" value="0">
|
||||
<label class="check"><input type="checkbox" name="openUpload" value="1"{open_upload_checked}> 允许游客上传</label>
|
||||
<input type="hidden" name="enableChunk" value="0">
|
||||
<label class="check"><input type="checkbox" name="enableChunk" value="1"{chunk_checked}> 启用切片上传</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-title">取件与保存</div>
|
||||
<label for="errorCount">取件错误频率 <span class="compact-help">次数 / 分钟</span></label>
|
||||
<div class="row">
|
||||
<input id="errorCount" name="errorCount" type="number" min="1" value="{error_count}" required>
|
||||
<input name="errorMinute" type="number" min="1" value="{error_minute}" aria-label="取件错误检测窗口分钟" required>
|
||||
</div>
|
||||
|
||||
<label for="loginCount">管理员登录失败频率 <span class="compact-help">次数 / 分钟</span></label>
|
||||
<div class="row">
|
||||
<input id="loginCount" name="loginCount" type="number" min="1" value="{login_count}" required>
|
||||
<input name="loginMinute" type="number" min="1" value="{login_minute}" aria-label="登录失败检测窗口分钟" required>
|
||||
</div>
|
||||
|
||||
<label for="save_time_value">最长保存时间</label>
|
||||
<div class="row">
|
||||
<input id="save_time_value" name="save_time_value" type="number" min="0" value="{save_time_value}" required>
|
||||
<select name="save_time_unit" aria-label="最长保存时间单位">
|
||||
{save_time_unit_options}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<label for="code_generate_type">提取码类型</label>
|
||||
<select id="code_generate_type" name="code_generate_type">
|
||||
{code_type_options}
|
||||
</select>
|
||||
</section>
|
||||
|
||||
<section class="panel panel-wide">
|
||||
<div>
|
||||
<div class="panel-title">可用策略</div>
|
||||
<label>允许的过期方式</label>
|
||||
<div class="checks">
|
||||
{expire_style_inputs}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label for="allowed_file_types">允许文件类型 <span class="compact-help">逗号分隔,* 表示不限制</span></label>
|
||||
<input id="allowed_file_types" name="allowed_file_types" value="{escaped_allowed_types}" placeholder="* 或 .zip, image/*">
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<button type="submit">完成初始化</button>
|
||||
</form>
|
||||
</main>
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
|
||||
def build_setup_success_page() -> str:
|
||||
return """<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta http-equiv="refresh" content="2;url=/#/admin">
|
||||
<title>初始化完成</title>
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 24px;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
background: #f6f8fb;
|
||||
color: #172033;
|
||||
}
|
||||
main {
|
||||
width: min(100%, 420px);
|
||||
padding: 28px;
|
||||
border: 1px solid #d9e1ec;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
text-align: center;
|
||||
box-shadow: 0 18px 50px rgba(23, 32, 51, .08);
|
||||
}
|
||||
h1 { margin: 0 0 10px; font-size: 24px; letter-spacing: 0; }
|
||||
p { margin: 0 0 22px; color: #60708a; line-height: 1.65; }
|
||||
a {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 42px;
|
||||
padding: 0 18px;
|
||||
border-radius: 6px;
|
||||
background: #2563eb;
|
||||
color: white;
|
||||
text-decoration: none;
|
||||
font-weight: 700;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>初始化完成</h1>
|
||||
<p>管理员密码已设置,请使用刚才的密码登录后台。</p>
|
||||
<a href="/#/admin">进入后台</a>
|
||||
</main>
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
|
||||
def setup_response(content: str, status_code: int = 200) -> HTMLResponse:
|
||||
return HTMLResponse(
|
||||
content=content,
|
||||
status_code=status_code,
|
||||
media_type="text/html",
|
||||
headers={"Cache-Control": "no-store"},
|
||||
)
|
||||
|
||||
|
||||
def is_setup_path(path: str) -> bool:
|
||||
return path.rstrip("/") == "/setup"
|
||||
|
||||
|
||||
def wants_html_response(request: Request) -> bool:
|
||||
if request.method not in {"GET", "HEAD"}:
|
||||
return False
|
||||
accept = request.headers.get("accept", "")
|
||||
return not accept or "text/html" in accept or "*/*" in accept
|
||||
|
||||
|
||||
async def read_setup_payload(request: Request) -> dict:
|
||||
content_type = request.headers.get("content-type", "")
|
||||
if "application/json" in content_type:
|
||||
data = await request.json()
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
body = (await request.body()).decode("utf-8")
|
||||
return {
|
||||
key: values if len(values) > 1 else values[-1]
|
||||
for key, values in parse_qs(body).items()
|
||||
}
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
logger.info("正在初始化应用...")
|
||||
@@ -78,6 +733,7 @@ async def lifespan(app: FastAPI):
|
||||
# 启动后台任务
|
||||
task = asyncio.create_task(delete_expire_files())
|
||||
chunk_cleanup_task = asyncio.create_task(clean_incomplete_uploads())
|
||||
presign_cleanup_task = asyncio.create_task(clean_expired_presign_sessions())
|
||||
logger.info("应用初始化完成")
|
||||
|
||||
try:
|
||||
@@ -87,7 +743,13 @@ async def lifespan(app: FastAPI):
|
||||
logger.info("正在关闭应用...")
|
||||
task.cancel()
|
||||
chunk_cleanup_task.cancel()
|
||||
await asyncio.gather(task, chunk_cleanup_task, return_exceptions=True)
|
||||
presign_cleanup_task.cancel()
|
||||
await asyncio.gather(
|
||||
task,
|
||||
chunk_cleanup_task,
|
||||
presign_cleanup_task,
|
||||
return_exceptions=True,
|
||||
)
|
||||
await Tortoise.close_connections()
|
||||
logger.info("应用已关闭")
|
||||
|
||||
@@ -98,37 +760,42 @@ async def load_config():
|
||||
key="sys_start", defaults={"value": int(time.time() * 1000)}
|
||||
)
|
||||
await refresh_settings()
|
||||
|
||||
await migrate_password_to_hash()
|
||||
await ensure_security_settings()
|
||||
|
||||
ip_limit["error"].minutes = settings.errorMinute
|
||||
ip_limit["error"].count = settings.errorCount
|
||||
ip_limit["upload"].minutes = settings.uploadMinute
|
||||
ip_limit["upload"].count = settings.uploadCount
|
||||
ip_limit["login"].minutes = settings.loginMinute
|
||||
ip_limit["login"].count = settings.loginCount
|
||||
|
||||
app = FastAPI(lifespan=lifespan, version=APP_VERSION)
|
||||
|
||||
async def migrate_password_to_hash():
|
||||
if not is_password_hashed(settings.admin_token):
|
||||
hashed = hash_password(settings.admin_token)
|
||||
settings.admin_token = hashed
|
||||
config_record = await KeyValue.filter(key="settings").first()
|
||||
if config_record and config_record.value:
|
||||
config_record.value["admin_token"] = hashed
|
||||
await config_record.save()
|
||||
logger.info("已将管理员密码迁移为哈希存储")
|
||||
|
||||
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
app.add_middleware(GZipMiddleware, minimum_size=1024, compresslevel=6)
|
||||
|
||||
@app.middleware("http")
|
||||
async def refresh_settings_middleware(request, call_next):
|
||||
await refresh_settings()
|
||||
if not is_runtime_initialized() and not is_setup_path(request.url.path):
|
||||
if wants_html_response(request):
|
||||
return setup_response(build_setup_page())
|
||||
return JSONResponse(
|
||||
status_code=428,
|
||||
content={
|
||||
"code": 428,
|
||||
"message": "系统未初始化,请先完成初始化",
|
||||
"msg": "系统未初始化,请先完成初始化",
|
||||
"detail": {"setup": "/setup"},
|
||||
},
|
||||
)
|
||||
return await call_next(request)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
# 前端使用 Bearer Token,不依赖 Cookie credentials。
|
||||
# allow_origins=["*"] 与 allow_credentials=True 组合不符合 CORS 规范。
|
||||
allow_credentials=False,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
@@ -148,31 +815,90 @@ app.include_router(presign_api, prefix="/api")
|
||||
app.include_router(admin_api)
|
||||
|
||||
|
||||
@app.get("/theme-assets/{asset_path:path}")
|
||||
@app.get("/assets/{asset_path:path}")
|
||||
async def theme_asset(asset_path: str):
|
||||
theme_assets = (BASE_DIR / settings.themesSelect / "assets").resolve()
|
||||
target = (theme_assets / asset_path).resolve()
|
||||
@app.get("/setup", include_in_schema=False)
|
||||
@app.get("/setup/", include_in_schema=False)
|
||||
async def setup_page():
|
||||
if is_runtime_initialized():
|
||||
return RedirectResponse(url="/", status_code=303)
|
||||
return setup_response(build_setup_page())
|
||||
|
||||
|
||||
@app.post("/setup", include_in_schema=False)
|
||||
@app.post("/setup/", include_in_schema=False)
|
||||
async def setup_submit(request: Request):
|
||||
if is_runtime_initialized():
|
||||
return RedirectResponse(url="/", status_code=303)
|
||||
|
||||
data = await read_setup_payload(request)
|
||||
admin_password = str(data.get("admin_password") or "")
|
||||
confirm_password = str(data.get("confirm_password") or "")
|
||||
site_name = str(data.get("site_name") or "")
|
||||
|
||||
if admin_password != confirm_password:
|
||||
return setup_response(build_setup_page("两次输入的管理员密码不一致", data), 400)
|
||||
|
||||
try:
|
||||
target.relative_to(theme_assets)
|
||||
setup_options = parse_setup_options(data)
|
||||
await initialize_system(
|
||||
admin_password=admin_password,
|
||||
site_name=site_name,
|
||||
setup_options=setup_options,
|
||||
)
|
||||
except ValueError as exc:
|
||||
return setup_response(build_setup_page(str(exc), data), 400)
|
||||
|
||||
if "application/json" in request.headers.get("accept", ""):
|
||||
return APIResponse(detail={"ok": True, "admin": "/#/admin"})
|
||||
return setup_response(build_setup_success_page())
|
||||
|
||||
|
||||
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:
|
||||
return PlainTextResponse("Not found", status_code=404)
|
||||
if not target.is_file():
|
||||
return PlainTextResponse("Not found", status_code=404)
|
||||
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("/theme-assets/{asset_path:path}", include_in_schema=False)
|
||||
@app.get("/assets/{asset_path:path}", include_in_schema=False)
|
||||
async def theme_asset(asset_path: str):
|
||||
normalized_asset_path = asset_path.removeprefix("assets/")
|
||||
return FileResponse(
|
||||
target,
|
||||
resolve_theme_file("assets", normalized_asset_path),
|
||||
headers={"Cache-Control": "public, max-age=31536000, immutable"},
|
||||
)
|
||||
|
||||
|
||||
|
||||
@app.exception_handler(404)
|
||||
@app.get("/")
|
||||
async def index(request=None, exc=None):
|
||||
theme_dir = BASE_DIR / settings.themesSelect
|
||||
asset_version = str(int((theme_dir / "index.html").stat().st_mtime))
|
||||
if request is not None and request.url.path.startswith(("/assets/", "/theme-assets/")):
|
||||
return PlainTextResponse("Not found", status_code=404)
|
||||
theme_dir = resolve_theme_root()
|
||||
index_file = resolve_theme_file("index.html")
|
||||
asset_version = str(int(index_file.stat().st_mtime))
|
||||
content = (
|
||||
open(theme_dir / "index.html", "r", encoding="utf-8")
|
||||
.read()
|
||||
index_file.read_text(encoding="utf-8")
|
||||
|
||||
.replace("{{title}}", str(settings.name))
|
||||
.replace("{{description}}", str(settings.description))
|
||||
.replace("{{keywords}}", str(settings.keywords))
|
||||
@@ -188,6 +914,7 @@ async def index(request=None, exc=None):
|
||||
)
|
||||
return HTMLResponse(
|
||||
content=content,
|
||||
|
||||
media_type="text/html",
|
||||
headers={"Cache-Control": "no-cache"},
|
||||
)
|
||||
@@ -234,4 +961,6 @@ if __name__ == "__main__":
|
||||
port=settings.serverPort,
|
||||
reload=False,
|
||||
workers=settings.serverWorkers,
|
||||
log_level=get_log_level_name(),
|
||||
access_log=is_access_log_enabled(),
|
||||
)
|
||||
+5
-4
@@ -1,8 +1,9 @@
|
||||
aioboto3==15.5.0
|
||||
aiohttp==3.13.3
|
||||
aiohttp==3.14.2
|
||||
aiofiles==25.1.0
|
||||
fastapi==0.128.0
|
||||
fastapi==0.139.2
|
||||
starlette==1.3.1
|
||||
pydantic==2.12.5
|
||||
uvicorn==0.40.0
|
||||
uvicorn==0.51.0
|
||||
tortoise-orm==0.25.3
|
||||
python-multipart==0.0.21
|
||||
python-multipart==0.0.32
|
||||
@@ -15,45 +15,23 @@ def rewrite(path: Path, text: str) -> None:
|
||||
|
||||
|
||||
def patch_file_manage(path: Path) -> bool:
|
||||
text = path.read_text(encoding='utf-8')
|
||||
old = text
|
||||
if 'detailTimeline:It(s.timeline||[])' in text and 'fcbxTimelineCollapsed' not in text:
|
||||
text = text.replace(
|
||||
'detailTimeline:It(s.timeline||[])}},nt=t=>',
|
||||
'detailTimeline:It(s.timeline||[]),fcbxTimelineCollapsed:!0}},nt=t=>',
|
||||
1,
|
||||
)
|
||||
render_old = 'N(e(b).detailTimeline,(n,K)=>(p(),f("div",{key:`${n.key}-${K}`,class:"grid grid-cols-[auto_minmax(0,1fr)] gap-3"}'
|
||||
render_new = 'N((e(b).fcbxTimelineCollapsed&&e(b).detailTimeline.filter(ga=>ga.key==="retrieved_event").length>3)?e(b).detailTimeline.filter((ga,Qa)=>ga.key!=="retrieved_event"||e(b).detailTimeline.filter(Ja=>Ja.key==="retrieved_event").indexOf(ga)<3):e(b).detailTimeline,(n,K)=>(p(),f("div",{key:`${n.key}-${K}`,class:"grid grid-cols-[auto_minmax(0,1fr)] gap-3"}'
|
||||
if render_old in text and 'ga.key==="retrieved_event"' not in text:
|
||||
text = text.replace(render_old, render_new, 1)
|
||||
close_old = ']))),128))],2)])):j("",!0),l("section",kn,'
|
||||
close_new = ']))),128)),e(b).detailTimeline.filter(n=>n.key==="retrieved_event").length>3?(p(),f("button",{key:0,type:"button",class:o(["mt-3 rounded-lg border px-3 py-2 text-sm font-medium transition",[e(u)?"border-gray-600 text-gray-200 hover:bg-gray-700":"border-gray-200 text-gray-700 hover:bg-gray-50"]]),onClick:m[99]||(m[99]=n=>e(b).fcbxTimelineCollapsed=!e(b).fcbxTimelineCollapsed)},r(e(b).fcbxTimelineCollapsed?`展开全部取件记录(共 ${e(b).detailTimeline.filter(n=>n.key==="retrieved_event").length} 次)":"收起取件记录"),3)):j("",!0)],2)])):j("",!0),l("section",kn,'
|
||||
if close_old in text and '展开全部取件记录' not in text:
|
||||
text = text.replace(close_old, close_new, 1)
|
||||
if text != old:
|
||||
rewrite(path, text)
|
||||
return True
|
||||
"""Do not mutate Vite's shared file-management bundle.
|
||||
|
||||
It imports the clipboard chunk, which is also shared by the upload/download
|
||||
service. Structural text replacement in a minified bundle is unsafe and can
|
||||
invalidate the module graph. Lifecycle presentation is handled by the
|
||||
standalone DOM script below instead.
|
||||
"""
|
||||
return False
|
||||
|
||||
|
||||
def patch_clipboard(path: Path) -> bool:
|
||||
text = path.read_text(encoding='utf-8')
|
||||
old = text
|
||||
pattern = re.compile(
|
||||
r'const (?P<name>[A-Za-z_$][\w$]*)=async\(a,e=\{\}\)=>\{.*?\},'
|
||||
r'(?=[A-Za-z_$][\w$]*=async\(a,e=\{\}\)=>\{)',
|
||||
re.S,
|
||||
)
|
||||
match = pattern.search(text)
|
||||
if not match:
|
||||
return False
|
||||
name = match.group('name')
|
||||
replacement = f'''const {name}=async(a,e={{}})=>{{const{{successMsg:t="复制成功",errorMsg:n="复制失败,请手动复制",showMsg:s=!0,notify:c}}=e,l=(r,d)=>{{s&&c?.(r,d)}},q=()=>{{try{{window.prompt("复制下面内容",a)}}catch{{}}}};try{{if(navigator.clipboard&&window.isSecureContext)try{{await navigator.clipboard.writeText(a);return l(t,"success"),!0}}catch{{}}const r=document.createElement("textarea");r.value=a,r.setAttribute("readonly","");r.className="fcbx-copy-fallback";r.style.cssText="position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;z-index:-1";document.body.appendChild(r);r.focus();r.select();r.setSelectionRange(0,r.value.length);let d=!1;try{{d=document.execCommand("copy")}}finally{{document.body.removeChild(r)}}if(d)return l(t,"success"),!0;q();l("已打开手动复制窗口","warning");return!1}}catch(r){{return console.error("复制失败:",r),q(),l(n,"error"),!1}}}}'''
|
||||
text = text[:match.start()] + replacement + text[match.end():]
|
||||
if text != old:
|
||||
rewrite(path, text)
|
||||
return True
|
||||
"""Never rewrite Vite's shared clipboard chunk after compilation.
|
||||
|
||||
The source utility already implements Clipboard API, DOM and manual-copy
|
||||
fallbacks. Rewriting a minified ESM module can invalidate every page that
|
||||
imports it, including FileManageView.
|
||||
"""
|
||||
return False
|
||||
|
||||
|
||||
@@ -117,6 +95,7 @@ def build_lifecycle_script() -> str:
|
||||
if (card) {
|
||||
card.style.overflow = 'visible';
|
||||
card.style.position = 'relative';
|
||||
card.style.borderTopWidth = '1px';
|
||||
}
|
||||
row.onmouseenter = () => { row.style.zIndex = '2'; };
|
||||
row.onmouseleave = () => { row.style.zIndex = '0'; };
|
||||
@@ -169,7 +148,9 @@ def main() -> None:
|
||||
if write_detail_collapse_script(theme):
|
||||
changed.append(str((assets / 'fcb-lifecycle-collapse-v3.js').relative_to(ASSETS_ROOT)))
|
||||
if not changed:
|
||||
raise SystemExit('admin timeline/clipboard patch markers not found or already patched')
|
||||
# The standalone lifecycle script is idempotently regenerated even when
|
||||
# the clipboard bundle was already patched in a cached build layer.
|
||||
return
|
||||
print('patched admin assets:', ', '.join(changed))
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user