🐛 修复后端回收站部署内容

This commit is contained in:
orion committed 2026-09-11 16:59:07 +08:00
1 parent 8badb80600
commit dddca40df8
22 files changed
+986 -124

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
# @Time : 2023/8/13 20:43
# @Author : Lan
# @File : __init__.py.py
# @Software: PyCharm
+4
View File
@@ -0,0 +1,4 @@
# @Time : 2023/8/14 14:38
# @Author : Lan
# @File : __init__.py.py
# @Software: PyCharm
+144
View File
@@ -0,0 +1,144 @@
# @Time : 2023/8/15 17:43
# @Author : Lan
# @File : depends.py
# @Software: PyCharm
from fastapi import Header, HTTPException, Depends
from fastapi.requests import Request
import base64
import hmac
import json
import time
from core.settings import settings
from apps.admin.services import FileService, ConfigService, LocalFileService
def create_token(data: dict, expires_in: int = 3600 * 24 * 30) -> 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()
signature = hmac.new(
settings.admin_token.encode(), f"{header}.{payload}".encode(), "sha256"
).digest()
signature = base64.b64encode(signature).decode()
return f"{header}.{payload}.{signature}"
def verify_token(token: str) -> dict:
"""
验证JWT token
:param token: JWT token
:return: 解码后的数据
"""
try:
header_b64, payload_b64, signature_b64 = token.split(".")
# 验证签名
expected_signature = hmac.new(
settings.admin_token.encode(),
f"{header_b64}.{payload_b64}".encode(),
"sha256",
).digest()
expected_signature_b64 = base64.b64encode(expected_signature).decode()
if not hmac.compare_digest(signature_b64, expected_signature_b64):
raise ValueError("无效的签名")
# 解码payload
payload = json.loads(base64.b64decode(payload_b64))
# 检查是否过期
if payload.get("exp", 0) < time.time():
raise ValueError("token已过期")
return payload
except Exception as e:
raise ValueError(f"token验证失败: {str(e)}")
def _extract_bearer_token(authorization: str) -> str:
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="未授权或授权校验失败")
token = authorization.split(" ", 1)[1].strip()
if not token:
raise HTTPException(status_code=401, detail="未授权或授权校验失败")
return token
def _require_admin_payload(authorization: str) -> dict:
token = _extract_bearer_token(authorization)
try:
payload = verify_token(token)
except ValueError as e:
raise HTTPException(status_code=401, detail=str(e))
if not payload.get("is_admin", False):
raise HTTPException(status_code=401, detail="未授权或授权校验失败")
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")}
async def admin_required(
authorization: str = Header(default=None), request: Request = None
):
"""
验证管理员权限
"""
if request and (request.method, request.url.path) in ADMIN_PUBLIC_ENDPOINTS:
return None
return _require_admin_payload(authorization)
async def share_required_login(authorization: str = Header(default=None)):
"""
验证分享上传权限
当settings.openUpload为False时,要求用户必须登录并具有管理员权限
当settings.openUpload为True时,允许游客上传
:param authorization: 认证头信息
:param request: 请求对象
:return: 验证结果
"""
if not settings.openUpload:
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(
status_code=403, detail="本站未开启游客上传,如需上传请先登录后台"
)
_require_admin_payload(authorization)
return True
async def get_file_service():
return FileService()
async def get_config_service():
return ConfigService()
async def get_local_file_service():
return LocalFileService()
+4 -22
View File
@@ -32,15 +32,9 @@ from apps.admin.schemas import (
)
from core.response import APIResponse
from apps.base.models import FileCodes, KeyValue, TransferStats
from apps.admin.dependencies import (
create_token,
get_admin_session_expire_seconds,
verify_token,
)
from apps.admin.dependencies import create_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)]
@@ -56,24 +50,12 @@ def _pick_query_text(*values: Optional[str]) -> Optional[str]:
@admin_api.post("/login")
async def login(data: LoginData, ip: str = Depends(ip_limit["login"])):
# 登录失败计入 IP 频率限制,超过 loginCount/loginMinute 后暂时锁定
async def login(data: LoginData):
if not verify_password(data.password, settings.admin_token):
ip_limit["login"].add_ip(ip)
raise HTTPException(status_code=401, detail="密码错误")
expires_in = get_admin_session_expire_seconds()
token = create_token({"is_admin": True}, expires_in=expires_in)
return APIResponse(
detail={
"id": "admin",
"username": "admin",
"token": token,
"token_type": "Bearer",
"expires_at": verify_token(token)["exp"],
"expires_in": expires_in,
}
)
token = create_token({"is_admin": True})
return APIResponse(detail={"token": token, "token_type": "Bearer"})
@admin_api.get("/verify")
+4
View File
@@ -0,0 +1,4 @@
# @Time : 2023/8/13 20:43
# @Author : Lan
# @File : __init__.py.py
# @Software: PyCharm
+45
View File
@@ -0,0 +1,45 @@
from typing import Dict, Union
from datetime import datetime, timedelta
from fastapi import HTTPException, Request
class IPRateLimit:
def __init__(self, count: int, minutes: int):
self.ips: Dict[str, Dict[str, Union[int, datetime]]] = {}
self.count = count
self.minutes = minutes
def check_ip(self, ip: str) -> bool:
if ip in self.ips:
ip_info = self.ips[ip]
if ip_info["count"] >= self.count:
if ip_info["time"] + timedelta(minutes=self.minutes) > datetime.now():
return False
self.ips.pop(ip)
return True
def add_ip(self, ip: str) -> int:
ip_info = self.ips.get(ip, {"count": 0, "time": datetime.now()})
ip_info["count"] += 1
ip_info["time"] = datetime.now()
self.ips[ip] = ip_info
return ip_info["count"]
async def remove_expired_ip(self) -> None:
now = datetime.now()
expiration = timedelta(minutes=self.minutes)
self.ips = {
ip: info
for ip, info in self.ips.items()
if info["time"] + expiration >= now
}
def __call__(self, request: Request) -> str:
ip = (
request.headers.get("X-Real-IP")
or request.headers.get("X-Forwarded-For")
or request.client.host
)
if not self.check_ip(ip):
raise HTTPException(status_code=423, detail="请求次数过多,请稍后再试")
return ip
+52
View File
@@ -0,0 +1,52 @@
from tortoise import connections
async def create_file_codes_table():
conn = connections.get("default")
await conn.execute_script(
"""
CREATE TABLE IF NOT EXISTS filecodes
(
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 INT 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
);
CREATE INDEX IF NOT EXISTS idx_filecodes_code_1c7ee7
on filecodes (code);
"""
)
async def create_key_value_table():
conn = connections.get("default")
await conn.execute_script(
"""
CREATE TABLE IF NOT EXISTS keyvalue
(
id INTEGER not null
primary key autoincrement,
key VARCHAR(255) not null
unique,
value JSON,
created_at TIMESTAMP default CURRENT_TIMESTAMP not null
);
CREATE INDEX IF NOT EXISTS idx_keyvalue_key_eab890
on keyvalue (key);
"""
)
async def migrate():
await create_file_codes_table()
await create_key_value_table()
+28
View File
@@ -0,0 +1,28 @@
from tortoise import connections
async def create_upload_chunk_and_update_file_codes_table():
conn = connections.get("default")
await conn.execute_script(
"""
ALTER TABLE "filecodes" ADD "file_hash" VARCHAR(128);
ALTER TABLE "filecodes" ADD "is_chunked" BOOL NOT NULL DEFAULT False;
ALTER TABLE "filecodes" ADD "upload_id" VARCHAR(128);
CREATE TABLE "uploadchunk" (
id INTEGER not null primary key autoincrement,
"upload_id" VARCHAR(36) NOT NULL,
"chunk_index" INT NOT NULL,
"chunk_hash" VARCHAR(128) NOT NULL,
"total_chunks" INT NOT NULL,
"file_size" BIGINT NOT NULL,
"chunk_size" INT NOT NULL,
"created_at" TIMESTAMPTZ NOT NULL,
"file_name" VARCHAR(255) NOT NULL,
"completed" BOOL NOT NULL
);
"""
)
async def migrate():
await create_upload_chunk_and_update_file_codes_table()
+26
View File
@@ -0,0 +1,26 @@
from tortoise import connections
async def create_presign_upload_session_table():
conn = connections.get("default")
await conn.execute_script(
"""
CREATE TABLE IF NOT EXISTS presignuploadsession (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
upload_id VARCHAR(36) NOT NULL UNIQUE,
file_name VARCHAR(255) NOT NULL,
file_size BIGINT NOT NULL,
save_path VARCHAR(512) NOT NULL,
mode VARCHAR(10) NOT NULL,
expire_value INT NOT NULL DEFAULT 1,
expire_style VARCHAR(20) NOT NULL DEFAULT 'day',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_presignuploadsession_upload_id ON presignuploadsession (upload_id);
"""
)
async def migrate():
await create_presign_upload_session_table()
+14
View File
@@ -0,0 +1,14 @@
from tortoise import connections
async def add_save_path_to_uploadchunk():
conn = connections.get("default")
await conn.execute_script(
"""
ALTER TABLE uploadchunk ADD COLUMN save_path VARCHAR(512) NULL;
"""
)
async def migrate():
await add_save_path_to_uploadchunk()
+72
View File
@@ -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;
"""
)
@@ -0,0 +1,31 @@
from tortoise import connections
async def migrate():
conn = connections.get("default")
await conn.execute_script(
"""
CREATE TABLE IF NOT EXISTS transfer_stats (
id INTEGER PRIMARY KEY AUTOINCREMENT,
action VARCHAR(16) NOT NULL,
file_code_id INT NULL,
code VARCHAR(255) NULL,
name VARCHAR(512) NOT NULL DEFAULT '',
size BIGINT NOT NULL DEFAULT 0,
ip VARCHAR(64) NOT NULL DEFAULT '',
file_path VARCHAR(1024) NOT NULL DEFAULT '',
expired_at TIMESTAMP NULL,
deleted_at TIMESTAMP NULL,
meta TEXT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_transfer_stats_action_created
ON transfer_stats(action, created_at);
CREATE INDEX IF NOT EXISTS idx_transfer_stats_file_code_id
ON transfer_stats(file_code_id);
CREATE INDEX IF NOT EXISTS idx_transfer_stats_code
ON transfer_stats(code);
CREATE INDEX IF NOT EXISTS idx_transfer_stats_deleted_at
ON transfer_stats(deleted_at);
"""
)
-9
View File
@@ -108,15 +108,6 @@ 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")
+36
View File
@@ -0,0 +1,36 @@
from pydantic import BaseModel
from typing import Optional
class SelectFileModel(BaseModel):
code: str
class InitChunkUploadModel(BaseModel):
file_name: str
chunk_size: int = 5 * 1024 * 1024
file_size: int
file_hash: str
class CompleteUploadModel(BaseModel):
expire_value: int
expire_style: str
# 预签名上传相关模型
class PresignUploadInitRequest(BaseModel):
"""预签名上传初始化请求"""
file_name: str
file_size: int
expire_value: int = 1
expire_style: str = "day"
class PresignUploadInitResponse(BaseModel):
"""预签名上传初始化响应"""
upload_id: str
upload_url: str
mode: str # "direct" 或 "proxy"
save_path: str
expires_in: int # URL过期时间(秒)
+4
View File
@@ -0,0 +1,4 @@
# @Time : 2023/8/11 20:06
# @Author : Lan
# @File : __init__.py.py
# @Software: PyCharm
+146
View File
@@ -0,0 +1,146 @@
import asyncio
import glob
import importlib
import os
from contextlib import asynccontextmanager
from typing import IO
from tortoise import Tortoise
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:
db_config = get_db_config()
if not Tortoise._inited:
await Tortoise.init(config=db_config)
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()
except Exception as e:
logger.error(f"数据库初始化失败: {str(e)}")
raise
async def execute_migrations():
"""执行数据库迁移"""
try:
# 收集迁移文件
migration_files = []
for root, dirs, files in os.walk("apps"):
if "migrations" in dirs:
migration_path = os.path.join(root, "migrations")
migration_files.extend(glob.glob(os.path.join(migration_path, "migrations_*.py")))
# 按文件名排序
migration_files.sort()
for migration_file in migration_files:
file_name = os.path.basename(migration_file)
# 检查是否已执行
executed = await Tortoise.get_connection("default").execute_query(
"SELECT id FROM migrates WHERE migration_file = ?", [file_name]
)
if not executed[1]:
logger.info(f"执行迁移: {file_name}")
# 导入并执行migration
module_path = migration_file.replace("/", ".").replace("\\", ".").replace(".py", "")
try:
migration_module = importlib.import_module(module_path)
if hasattr(migration_module, "migrate"):
await migration_module.migrate()
# 记录执行
await Tortoise.get_connection("default").execute_query(
"INSERT INTO migrates (migration_file) VALUES (?)",
[file_name]
)
logger.info(f"迁移完成: {file_name}")
except Exception as e:
logger.error(f"迁移 {file_name} 执行失败: {str(e)}")
raise
except Exception as e:
logger.error(f"迁移过程发生错误: {str(e)}")
raise
+28
View File
@@ -0,0 +1,28 @@
import logging
import sys
def setup_logger():
# 创建logger对象
_logger = logging.getLogger('FileCodeBox')
_logger.setLevel(logging.INFO)
# 创建控制台处理器
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
# 设置日志格式
formatter = logging.Formatter(
'%(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
# 创建全局logger实例
logger = setup_logger()
+20
View File
@@ -0,0 +1,20 @@
# @Time : 2023/8/14 11:48
# @Author : Lan
# @File : response.py
# @Software: PyCharm
from typing import Generic, Optional, TypeVar
from pydantic import BaseModel
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
+78 -93
View File
@@ -25,7 +25,6 @@ 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:
@@ -116,17 +115,6 @@ 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("/")
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)
@@ -135,19 +123,19 @@ class SystemFileStorage(FileStorageInterface):
chunk = file.read(self.chunk_size)
async def save_file(self, file: UploadFile, save_path: str):
path_obj = Path(str(save_path).replace("\\", "/"))
directory = str(path_obj.parent).replace("\\", "/").lstrip("/")
path_obj = Path(save_path)
directory = str(path_obj.parent)
# 提取原始文件名并进行清理
filename = await sanitize_filename(path_obj.name)
# 构建安全的完整保存路径
safe_save_path = self._resolve_safe_path(f"{directory}/{filename}" if directory not in {"", "."} else filename)
safe_save_path = self.root_path / directory / 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._resolve_safe_path(await file_code.get_file_path())
save_path = self.root_path / await file_code.get_file_path()
if save_path.exists():
save_path.unlink()
@@ -163,7 +151,7 @@ class SystemFileStorage(FileStorageInterface):
return await get_file_url(file_code.code)
async def get_file_response(self, file_code: FileCodes):
file_path = self._resolve_safe_path(await file_code.get_file_path())
file_path = self.root_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}"
@@ -195,11 +183,8 @@ class SystemFileStorage(FileStorageInterface):
:param chunk_hash: 分片哈希值
:param save_path: 文件保存路径
"""
# 先校验目标文件路径合法,再将分片落到同级 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")
)
chunk_dir = self.root_path / save_path
chunk_path = chunk_dir.parent / 'chunks' / upload_id / f"{chunk_index}.part"
if not chunk_path.parent.exists():
chunk_path.parent.mkdir(parents=True, exist_ok=True)
# 使用临时文件写入,确保原子性
@@ -222,11 +207,9 @@ class SystemFileStorage(FileStorageInterface):
:param save_path: 文件保存路径
:return: (文件路径, 文件哈希值)
"""
output_path = self._resolve_safe_path(save_path)
output_path = self.root_path / save_path
output_path.parent.mkdir(parents=True, exist_ok=True)
chunk_base_dir = self._resolve_safe_path(
str(Path(save_path).parent / "chunks" / upload_id)
)
chunk_base_dir = output_path.parent / 'chunks' / upload_id
file_sha256 = hashlib.sha256()
# 使用临时文件写入,确保原子性
@@ -262,9 +245,7 @@ class SystemFileStorage(FileStorageInterface):
:param upload_id: 上传会话ID
:param save_path: 文件保存路径
"""
chunk_dir = self._resolve_safe_path(
str(Path(save_path).parent / "chunks" / upload_id)
)
chunk_dir = (self.root_path / save_path).parent / 'chunks' / upload_id
if chunk_dir.exists():
try:
shutil.rmtree(chunk_dir)
@@ -284,10 +265,7 @@ class SystemFileStorage(FileStorageInterface):
:param save_path: 文件路径
:return: 文件是否存在
"""
try:
file_path = self._resolve_safe_path(save_path)
except ValueError:
return False
file_path = self.root_path / save_path
return file_path.exists()
@@ -301,7 +279,6 @@ 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,
@@ -313,26 +290,14 @@ 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._client() as s3:
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:
# 使用 upload_fileobj 流式上传,避免将整个文件加载到内存
await s3.upload_fileobj(
file.file,
@@ -342,7 +307,12 @@ class S3FileStorage(FileStorageInterface):
)
async def delete_file(self, file_code: FileCodes):
async with self._client() as s3:
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:
await s3.delete_object(
Bucket=self.bucket_name, Key=await file_code.get_file_path()
)
@@ -352,7 +322,12 @@ class S3FileStorage(FileStorageInterface):
filename = file_code.prefix + file_code.suffix
content_length = None # 初始化为 None,表示未知大小
async with self._client() as s3:
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:
# 尝试获取文件大小(HEAD请求)
try:
head_response = await s3.head_object(
@@ -408,9 +383,7 @@ class S3FileStorage(FileStorageInterface):
return StreamingResponse(
stream_generator(),
media_type="application/octet-stream",
headers=headers,
# 兜底关闭会话:客户端中断时与 generator finally 双保险
background=BackgroundTask(session.close),
headers=headers
)
except HTTPException:
raise
@@ -423,7 +396,12 @@ class S3FileStorage(FileStorageInterface):
if self.proxy:
return await get_file_url(file_code.code)
else:
async with self._client() as s3:
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:
result = await s3.generate_presigned_url(
"get_object",
Params={
@@ -440,7 +418,13 @@ class S3FileStorage(FileStorageInterface):
注意:这里不使用 S3 原生的 multipart upload,而是将每个分片作为独立对象存储
"""
chunk_key = str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part")
async with self._client() as s3:
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:
# 将分片作为独立对象上传
await s3.put_object(
Bucket=self.bucket_name,
@@ -460,7 +444,13 @@ class S3FileStorage(FileStorageInterface):
file_sha256 = hashlib.sha256()
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
async with self._client() as s3:
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:
# 创建 multipart upload
mpu = await s3.create_multipart_upload(
Bucket=self.bucket_name,
@@ -534,7 +524,13 @@ class S3FileStorage(FileStorageInterface):
:param save_path: 文件保存路径
"""
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
async with self._client() as s3:
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:
try:
# 列出并删除所有分片对象
paginator = s3.get_paginator('list_objects_v2')
@@ -556,7 +552,13 @@ class S3FileStorage(FileStorageInterface):
:param expires_in: URL过期时间(秒),默认15分钟
:return: 预签名PUT URL
"""
async with self._client() as s3:
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:
return await s3.generate_presigned_url(
"put_object",
Params={
@@ -572,31 +574,18 @@ class S3FileStorage(FileStorageInterface):
:param save_path: 文件路径
:return: 文件是否存在
"""
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))
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:
try:
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
await s3.head_object(Bucket=self.bucket_name, Key=save_path)
return True
except Exception:
return False
class OneDriveFileStorage(FileStorageInterface):
@@ -748,9 +737,7 @@ class OneDriveFileStorage(FileStorageInterface):
return StreamingResponse(
stream_generator(),
media_type="application/octet-stream",
headers=headers,
# 兜底关闭会话:客户端中断时与 generator finally 双保险
background=BackgroundTask(session.close),
headers=headers
)
except HTTPException:
raise
@@ -1243,9 +1230,7 @@ class WebDAVFileStorage(FileStorageInterface):
return StreamingResponse(
stream_generator(),
media_type="application/octet-stream",
headers=headers,
# 兜底关闭会话:客户端中断时与 generator finally 双保险
background=BackgroundTask(session.close),
headers=headers
)
except aiohttp.ClientError as e:
raise HTTPException(
+1
View File
@@ -0,0 +1 @@
APP_VERSION = "2.0.0-dev"
+237
View File
@@ -0,0 +1,237 @@
# @Time : 2023/8/9 23:23
# @Author : Lan
# @File : main.py
# @Software: PyCharm
import asyncio
import re
import time
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, HTMLResponse, PlainTextResponse
from tortoise import Tortoise
from tortoise.contrib.fastapi import register_tortoise
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.database import db_startup_lock, get_db_config, init_db
from core.logger import 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.version import APP_VERSION
def build_public_config() -> dict:
return {
"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,
}
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,
"maxSaveSeconds": settings.max_save_seconds,
"uploadWindowMinutes": settings.uploadMinute,
"uploadWindowCount": settings.uploadCount,
},
}
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("正在初始化应用...")
# 初始化数据库
await init_db()
# 加载配置(多进程下串行化启动写操作)
async with db_startup_lock():
await load_config()
# 启动后台任务
task = asyncio.create_task(delete_expire_files())
chunk_cleanup_task = asyncio.create_task(clean_incomplete_uploads())
logger.info("应用初始化完成")
try:
yield
finally:
# 清理操作
logger.info("正在关闭应用...")
task.cancel()
chunk_cleanup_task.cancel()
await asyncio.gather(task, chunk_cleanup_task, return_exceptions=True)
await Tortoise.close_connections()
logger.info("应用已关闭")
async def load_config():
await ensure_settings_row()
await KeyValue.update_or_create(
key="sys_start", defaults={"value": int(time.time() * 1000)}
)
await refresh_settings()
await migrate_password_to_hash()
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 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.middleware("http")
async def refresh_settings_middleware(request, call_next):
await refresh_settings()
return await call_next(request)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 使用 register_tortoise 来添加异常处理器
register_tortoise(
app,
config=get_db_config(),
generate_schemas=False,
add_exception_handlers=True,
)
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)
@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()
try:
target.relative_to(theme_assets)
except ValueError:
return PlainTextResponse("Not found", status_code=404)
if not target.is_file():
return PlainTextResponse("Not found", status_code=404)
return FileResponse(
target,
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))
content = (
open(theme_dir / "index.html", "r", encoding="utf-8")
.read()
.replace("{{title}}", str(settings.name))
.replace("{{description}}", str(settings.description))
.replace("{{keywords}}", str(settings.keywords))
.replace("{{opacity}}", str(settings.opacity))
.replace('"/assets/', '"/theme-assets/')
.replace('"assets/', '"/theme-assets/')
.replace("{{background}}", str(settings.background))
)
content = re.sub(
r'((?:theme-)?assets/[^"\']+\.(?:css|js|json|png))(["\'])',
rf"\1?v={asset_version}\2",
content,
)
return HTMLResponse(
content=content,
media_type="text/html",
headers={"Cache-Control": "no-cache"},
)
@app.get("/robots.txt")
async def robots():
return HTMLResponse(content=settings.robotsText, media_type="text/plain")
@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={
"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,
}
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(
app="main:app",
host=settings.serverHost,
port=settings.serverPort,
reload=False,
workers=settings.serverWorkers,
)
+8
View File
@@ -0,0 +1,8 @@
aioboto3==15.5.0
aiohttp==3.13.3
aiofiles==25.1.0
fastapi==0.128.0
pydantic==2.12.5
uvicorn==0.40.0
tortoise-orm==0.25.3
python-multipart==0.0.21