mirror of
https://github.com/vastsa/FileCodeBox.git
synced 2026-11-20 13:29:56 +08:00
Compare commits
73
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1ec397af0c | ||
|
|
eb6fc627ae | ||
|
|
c1fb802223 | ||
|
|
1d03337e2f | ||
|
|
8d6eaacb70 | ||
|
|
3fe136536e | ||
|
|
aa6904a12c | ||
|
|
135dfdda9d | ||
|
|
e3ea7825bf | ||
|
|
6759539078 | ||
|
|
530f52aa1e | ||
|
|
b859ec211e | ||
|
|
8ac367d0b8 | ||
|
|
63cf725802 | ||
|
|
ccbc710d74 | ||
|
|
2d18b02005 | ||
|
|
e75fe596d0 | ||
|
|
be7ce2b30e | ||
|
|
0dbb594f4a | ||
|
|
b6aa28c345 | ||
|
|
fc6046a663 | ||
|
|
3467e973ac | ||
|
|
a1de598277 | ||
|
|
1ba0d2a044 | ||
|
|
1f0b0b791c | ||
|
|
4ae53fc4a5 | ||
|
|
35e069ccc3 | ||
|
|
2fa1faebe0 | ||
|
|
0ced9b1f38 | ||
|
|
1eb69e4cc5 | ||
|
|
71fc1ad8ea | ||
|
|
64ebc59a84 | ||
|
|
78b1dbe81f | ||
|
|
6805206efd | ||
|
|
6fe68be2dd | ||
|
|
0d71b914e4 | ||
|
|
20fcf0c3df | ||
|
|
75d345e5d0 | ||
|
|
a0c453b014 | ||
|
|
1cc901d2b9 | ||
|
|
e7b5792602 | ||
|
|
843a237fad | ||
|
|
4a9bf3a3a0 | ||
|
|
0504e6e4dc | ||
|
|
24d49e1c9a | ||
|
|
c380778336 | ||
|
|
f1c09b0b20 | ||
|
|
a3f599fe51 | ||
|
|
2e5dc532a0 | ||
|
|
7f46c58898 | ||
|
|
5a889bab47 | ||
|
|
5fee1c7b86 | ||
|
|
73017935e9 | ||
|
|
a35b3c8262 | ||
|
|
da5dc378a7 | ||
|
|
d170ca8005 | ||
|
|
0fe01c98db | ||
|
|
d5b0327f90 | ||
|
|
9120486449 | ||
|
|
f5a5e03269 | ||
|
|
ade5799db4 | ||
|
|
6b728abbeb | ||
|
|
ff1943d60c | ||
|
|
442ef5b0e0 | ||
|
|
34e36944bd | ||
|
|
ba8802ad75 | ||
|
|
bf43727531 | ||
|
|
d49a61d06e | ||
|
|
3074d9ba2e | ||
|
|
81ee640353 | ||
|
|
e87bcfcce5 | ||
|
|
e80be564a5 | ||
|
|
69972e28b3 |
No files matched your search
+49
-2
@@ -1,3 +1,50 @@
|
||||
*.md
|
||||
.idea
|
||||
# Git
|
||||
.git
|
||||
.gitignore
|
||||
.gitattributes
|
||||
|
||||
# IDE
|
||||
.idea
|
||||
.vscode
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# Documentation
|
||||
*.md
|
||||
docs/
|
||||
LICENSE
|
||||
|
||||
# Development
|
||||
.venv
|
||||
__pycache__
|
||||
*.pyc
|
||||
*.pyo
|
||||
.pytest_cache
|
||||
.coverage
|
||||
htmlcov/
|
||||
|
||||
# macOS
|
||||
.DS_Store
|
||||
._*
|
||||
|
||||
# Frontend source (will be built from GitHub)
|
||||
fcb-fronted/
|
||||
themes/
|
||||
|
||||
# Test files
|
||||
test_*.py
|
||||
tests/
|
||||
|
||||
# Data (should be mounted as volume)
|
||||
data/
|
||||
|
||||
# GitHub
|
||||
.github/
|
||||
|
||||
# Docker
|
||||
Dockerfile
|
||||
docker-compose.yml
|
||||
.dockerignore
|
||||
|
||||
# Claude
|
||||
.claude/
|
||||
@@ -5,6 +5,7 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- dev
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
@@ -31,6 +32,7 @@ jobs:
|
||||
type=ref,event=pr
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=raw,value=dev,enable=${{ github.ref == 'refs/heads/dev' }}
|
||||
type=raw,value=beta,enable={{is_default_branch}}
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
|
||||
|
||||
+3
-2
@@ -158,7 +158,8 @@ data/.env
|
||||
# Ignore node_modules
|
||||
node_modules/
|
||||
|
||||
|
||||
AGENTS.md
|
||||
|
||||
dist/
|
||||
dist/
|
||||
# Frontend themes (built from GitHub during Docker build)
|
||||
themes/
|
||||
+44
-15
@@ -1,24 +1,53 @@
|
||||
FROM python:3.9.5-slim-buster
|
||||
# 第一阶段:构建前端主题
|
||||
FROM node:20-alpine AS frontend-builder
|
||||
|
||||
RUN apk add --no-cache git python3 make g++
|
||||
|
||||
RUN corepack enable && \
|
||||
corepack prepare pnpm@9.15.9 --activate
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
# 克隆并构建 2024 主题
|
||||
RUN git clone --depth 1 https://github.com/vastsa/FileCodeBoxFronted.git /build/fronted-2024 && \
|
||||
cd /build/fronted-2024 && \
|
||||
pnpm install --frozen-lockfile --prod=false && \
|
||||
pnpm run build
|
||||
|
||||
# 克隆并构建 2023 主题
|
||||
RUN git clone --depth 1 https://github.com/vastsa/FileCodeBoxFronted2023.git /build/fronted-2023 && \
|
||||
cd /build/fronted-2023 && \
|
||||
npm install --legacy-peer-deps && \
|
||||
npm run build
|
||||
|
||||
# 第二阶段:构建最终镜像
|
||||
FROM python:3.12-slim-bookworm
|
||||
LABEL author="Lan"
|
||||
LABEL email="xzu@live.com"
|
||||
|
||||
# 将当前目录下的文件复制到容器的 /app 目录
|
||||
COPY . /app
|
||||
|
||||
# 设置时区为亚洲/上海
|
||||
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone
|
||||
|
||||
# 设置工作目录
|
||||
WORKDIR /app
|
||||
|
||||
# 删除不必要的目录,减少镜像体积
|
||||
RUN rm -rf docs fcb-fronted
|
||||
# 复制项目文件(通过 .dockerignore 排除不必要的文件)
|
||||
COPY . .
|
||||
|
||||
# 安装依赖
|
||||
RUN pip install -r requirements.txt
|
||||
# 设置时区
|
||||
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
|
||||
echo 'Asia/Shanghai' > /etc/timezone
|
||||
|
||||
# 从构建阶段复制编译好的前端主题
|
||||
COPY --from=frontend-builder /build/fronted-2024/dist ./themes/2024
|
||||
COPY --from=frontend-builder /build/fronted-2023/dist ./themes/2023
|
||||
|
||||
# 安装 Python 依赖
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# 环境变量配置
|
||||
ENV HOST="0.0.0.0" \
|
||||
PORT=12345 \
|
||||
WORKERS=1 \
|
||||
LOG_LEVEL="info"
|
||||
|
||||
# 暴露端口
|
||||
EXPOSE 12345
|
||||
|
||||
# 启动应用
|
||||
CMD ["python", "main.py"]
|
||||
# 生产环境启动命令
|
||||
CMD ["sh", "-c", "exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" --proxy-headers --forwarded-allow-ips '*'"]
|
||||
+45
-41
@@ -50,7 +50,7 @@ def verify_token(token: str) -> dict:
|
||||
).digest()
|
||||
expected_signature_b64 = base64.b64encode(expected_signature).decode()
|
||||
|
||||
if signature_b64 != expected_signature_b64:
|
||||
if not hmac.compare_digest(signature_b64, expected_signature_b64):
|
||||
raise ValueError("无效的签名")
|
||||
|
||||
# 解码payload
|
||||
@@ -65,39 +65,53 @@ def verify_token(token: str) -> dict:
|
||||
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
|
||||
):
|
||||
"""
|
||||
验证管理员权限
|
||||
"""
|
||||
try:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
is_admin = False
|
||||
else:
|
||||
try:
|
||||
token = authorization.split(" ")[1]
|
||||
payload = verify_token(token)
|
||||
is_admin = payload.get("is_admin", False)
|
||||
except ValueError as e:
|
||||
is_admin = False
|
||||
|
||||
if request.url.path.startswith("/share/"):
|
||||
if not settings.openUpload and not is_admin:
|
||||
raise HTTPException(
|
||||
status_code=403, detail="本站未开启游客上传,如需上传请先登录后台"
|
||||
)
|
||||
else:
|
||||
if not is_admin:
|
||||
raise HTTPException(status_code=401, detail="未授权或授权校验失败")
|
||||
return is_admin
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=401, detail=str(e))
|
||||
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), request: Request = None
|
||||
):
|
||||
async def share_required_login(authorization: str = Header(default=None)):
|
||||
"""
|
||||
验证分享上传权限
|
||||
|
||||
@@ -109,21 +123,11 @@ async def share_required_login(
|
||||
:return: 验证结果
|
||||
"""
|
||||
if not settings.openUpload:
|
||||
try:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise HTTPException(
|
||||
status_code=403, detail="本站未开启游客上传,如需上传请先登录后台"
|
||||
)
|
||||
|
||||
token = authorization.split(" ")[1]
|
||||
try:
|
||||
payload = verify_token(token)
|
||||
if not payload.get("is_admin", False):
|
||||
raise HTTPException(status_code=401, detail="未授权或授权校验失败")
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=401, detail=str(e))
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=401, detail="认证失败:" + str(e))
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise HTTPException(
|
||||
status_code=403, detail="本站未开启游客上传,如需上传请先登录后台"
|
||||
)
|
||||
_require_admin_payload(authorization)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
+44
-1
@@ -1,5 +1,5 @@
|
||||
import datetime
|
||||
from typing import Optional, Union
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
@@ -8,6 +8,10 @@ class IDData(BaseModel):
|
||||
id: int
|
||||
|
||||
|
||||
class IDsData(BaseModel):
|
||||
ids: list[int]
|
||||
|
||||
|
||||
class ShareItem(BaseModel):
|
||||
expire_value: int
|
||||
expire_style: str = "day"
|
||||
@@ -29,3 +33,42 @@ class UpdateFileData(BaseModel):
|
||||
suffix: Optional[str] = None
|
||||
expired_at: Optional[Union[datetime.datetime, str]] = None
|
||||
expired_count: Optional[int] = None
|
||||
|
||||
|
||||
class BatchUpdateFileData(BaseModel):
|
||||
ids: list[int]
|
||||
expired_at: Optional[Union[datetime.datetime, str]] = None
|
||||
expired_count: Optional[int] = None
|
||||
clearExpiredAt: Optional[bool] = None
|
||||
clear_expired_at: Optional[bool] = None
|
||||
|
||||
|
||||
class FilePolicyActionData(BaseModel):
|
||||
id: int
|
||||
action: str
|
||||
downloadLimit: Optional[int] = None
|
||||
download_limit: Optional[int] = None
|
||||
|
||||
|
||||
class BatchFilePolicyActionData(BaseModel):
|
||||
ids: list[int]
|
||||
action: str
|
||||
downloadLimit: Optional[int] = None
|
||||
download_limit: Optional[int] = None
|
||||
|
||||
|
||||
class FileMetadataData(BaseModel):
|
||||
id: int
|
||||
note: Optional[str] = None
|
||||
tags: Optional[list[str]] = None
|
||||
|
||||
|
||||
class FileViewPresetData(BaseModel):
|
||||
id: Optional[str] = None
|
||||
name: str
|
||||
filters: Optional[dict[str, Any]] = None
|
||||
params: Optional[dict[str, Any]] = None
|
||||
|
||||
|
||||
class FileViewPresetDeleteData(BaseModel):
|
||||
id: str
|
||||
+1486
-36
File diff suppressed because it is too large.
Load diff
+474
-46
@@ -3,126 +3,523 @@
|
||||
# @File : views.py
|
||||
# @Software: PyCharm
|
||||
import datetime
|
||||
from collections import Counter
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from apps.admin.services import FileService, ConfigService, LocalFileService
|
||||
from apps.admin.dependencies import (
|
||||
admin_required,
|
||||
get_admin_session,
|
||||
get_file_service,
|
||||
get_config_service,
|
||||
get_local_file_service,
|
||||
)
|
||||
from apps.admin.schemas import IDData, ShareItem, DeleteItem, LoginData, UpdateFileData
|
||||
from apps.admin.schemas import (
|
||||
IDData,
|
||||
IDsData,
|
||||
BatchUpdateFileData,
|
||||
BatchFilePolicyActionData,
|
||||
FilePolicyActionData,
|
||||
FileMetadataData,
|
||||
FileViewPresetData,
|
||||
FileViewPresetDeleteData,
|
||||
ShareItem,
|
||||
DeleteItem,
|
||||
LoginData,
|
||||
UpdateFileData,
|
||||
)
|
||||
from core.response import APIResponse
|
||||
from apps.base.models import FileCodes, KeyValue
|
||||
from apps.admin.dependencies import create_token
|
||||
from core.settings import settings
|
||||
from core.utils import get_now, verify_password
|
||||
|
||||
admin_api = APIRouter(prefix="/admin", tags=["管理"])
|
||||
admin_api = APIRouter(
|
||||
prefix="/admin", tags=["管理"], dependencies=[Depends(admin_required)]
|
||||
)
|
||||
|
||||
|
||||
def _pick_query_text(*values: Optional[str]) -> Optional[str]:
|
||||
for value in values:
|
||||
normalized_value = str(value or "").strip()
|
||||
if normalized_value:
|
||||
return normalized_value
|
||||
return None
|
||||
|
||||
|
||||
@admin_api.post("/login")
|
||||
async def login(data: LoginData):
|
||||
# 验证管理员密码
|
||||
if data.password != settings.admin_token:
|
||||
if not verify_password(data.password, settings.admin_token):
|
||||
raise HTTPException(status_code=401, detail="密码错误")
|
||||
|
||||
# 生成包含管理员身份的token
|
||||
token = create_token({"is_admin": True})
|
||||
return APIResponse(detail={"token": token, "token_type": "Bearer"})
|
||||
|
||||
|
||||
@admin_api.get("/verify")
|
||||
async def verify_admin(session: dict = Depends(get_admin_session)):
|
||||
return APIResponse(detail=session)
|
||||
|
||||
|
||||
@admin_api.post("/logout")
|
||||
async def logout_admin():
|
||||
return APIResponse(detail={"ok": True})
|
||||
|
||||
|
||||
async def build_dashboard_recent_file(file_code: FileCodes) -> dict:
|
||||
is_expired = await file_code.is_expired()
|
||||
return {
|
||||
"id": file_code.id,
|
||||
"code": file_code.code,
|
||||
"name": file_code.prefix + file_code.suffix,
|
||||
"suffix": file_code.suffix,
|
||||
"size": file_code.size,
|
||||
"text": file_code.text is not None,
|
||||
"expiredAt": file_code.expired_at,
|
||||
"expiredCount": file_code.expired_count,
|
||||
"usedCount": file_code.used_count,
|
||||
"createdAt": file_code.created_at,
|
||||
"isExpired": is_expired,
|
||||
}
|
||||
|
||||
|
||||
@admin_api.get("/dashboard")
|
||||
async def dashboard(admin: bool = Depends(admin_required)):
|
||||
async def dashboard(file_service: FileService = Depends(get_file_service)):
|
||||
all_codes = await FileCodes.all()
|
||||
all_size = str(sum([code.size for code in all_codes]))
|
||||
all_size = sum([code.size for code in all_codes])
|
||||
sys_start = await KeyValue.filter(key="sys_start").first()
|
||||
# 获取当前日期时间
|
||||
now = datetime.datetime.now()
|
||||
now = await get_now()
|
||||
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
yesterday_start = today_start - datetime.timedelta(days=1)
|
||||
yesterday_end = today_start - datetime.timedelta(microseconds=1)
|
||||
# 统计昨天一整天的记录数(从昨天0点到23:59:59)
|
||||
yesterday_codes = FileCodes.filter(
|
||||
created_at__gte=yesterday_start, created_at__lte=yesterday_end
|
||||
)
|
||||
# 统计今天到现在的记录数(从今天0点到现在)
|
||||
today_codes = FileCodes.filter(created_at__gte=today_start)
|
||||
yesterday_file_codes = await yesterday_codes
|
||||
today_file_codes = await today_codes
|
||||
expired_count = 0
|
||||
for file_code in all_codes:
|
||||
if await file_code.is_expired():
|
||||
expired_count += 1
|
||||
health_summary = await file_service.build_file_health_summary(all_codes, now=now)
|
||||
|
||||
text_count = sum(1 for file_code in all_codes if file_code.text is not None)
|
||||
chunked_count = sum(1 for file_code in all_codes if file_code.is_chunked)
|
||||
used_count = sum([file_code.used_count for file_code in all_codes])
|
||||
suffix_counter = Counter(
|
||||
"Text" if file_code.text is not None else (file_code.suffix or "file")
|
||||
for file_code in all_codes
|
||||
)
|
||||
recent_file_codes = sorted(
|
||||
all_codes,
|
||||
key=lambda file_code: file_code.created_at.timestamp()
|
||||
if file_code.created_at
|
||||
else 0,
|
||||
reverse=True,
|
||||
)[:8]
|
||||
recent_activities = await file_service.list_admin_activities(limit=8)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"totalFiles": len(all_codes),
|
||||
"storageUsed": all_size,
|
||||
"sysUptime": sys_start.value,
|
||||
"yesterdayCount": await yesterday_codes.count(),
|
||||
"yesterdaySize": str(sum([code.size for code in await yesterday_codes])),
|
||||
"todayCount": await today_codes.count(),
|
||||
"todaySize": str(sum([code.size for code in await today_codes])),
|
||||
"storageUsed": str(all_size),
|
||||
"sysUptime": sys_start.value if sys_start else None,
|
||||
"yesterdayCount": len(yesterday_file_codes),
|
||||
"yesterdaySize": str(sum([code.size for code in yesterday_file_codes])),
|
||||
"todayCount": len(today_file_codes),
|
||||
"todaySize": str(sum([code.size for code in today_file_codes])),
|
||||
"activeCount": len(all_codes) - expired_count,
|
||||
"expiredCount": expired_count,
|
||||
"textCount": text_count,
|
||||
"fileCount": len(all_codes) - text_count,
|
||||
"chunkedCount": chunked_count,
|
||||
"usedCount": used_count,
|
||||
"storageBackend": settings.file_storage,
|
||||
"uploadSizeLimit": settings.uploadSize,
|
||||
"openUpload": settings.openUpload,
|
||||
"enableChunk": settings.enableChunk,
|
||||
"maxSaveSeconds": settings.max_save_seconds,
|
||||
**health_summary,
|
||||
"healthSummary": health_summary,
|
||||
"topSuffixes": [
|
||||
{"suffix": suffix, "count": count}
|
||||
for suffix, count in suffix_counter.most_common(8)
|
||||
],
|
||||
"recentFiles": [
|
||||
await build_dashboard_recent_file(file_code)
|
||||
for file_code in recent_file_codes
|
||||
],
|
||||
"recentActivities": recent_activities["activities"],
|
||||
"recent_activities": recent_activities["activities"],
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@admin_api.get("/activities")
|
||||
async def admin_activities(
|
||||
limit: int = 20,
|
||||
action: Optional[str] = None,
|
||||
targetType: Optional[str] = None,
|
||||
target_type: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
result = await file_service.list_admin_activities(
|
||||
limit=limit,
|
||||
action=action,
|
||||
target_type=_pick_query_text(targetType, target_type),
|
||||
keyword=keyword,
|
||||
)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.delete("/file/delete")
|
||||
async def file_delete(
|
||||
data: IDData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
data: IDData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
await file_service.delete_file(data.id)
|
||||
return APIResponse()
|
||||
|
||||
|
||||
async def batch_delete_files(
|
||||
data: IDsData,
|
||||
file_service: FileService,
|
||||
):
|
||||
if not data.ids:
|
||||
raise HTTPException(status_code=400, detail="请选择要删除的文件")
|
||||
result = await file_service.delete_files(data.ids)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.delete("/file/batch-delete")
|
||||
async def file_batch_delete(
|
||||
data: IDsData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await batch_delete_files(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/batch-delete")
|
||||
async def file_batch_delete_post(
|
||||
data: IDsData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await batch_delete_files(data, file_service)
|
||||
|
||||
|
||||
async def batch_update_files(
|
||||
data: BatchUpdateFileData,
|
||||
file_service: FileService,
|
||||
):
|
||||
if not data.ids:
|
||||
raise HTTPException(status_code=400, detail="请选择要更新的文件")
|
||||
|
||||
update_data = {}
|
||||
fields_set = data.model_fields_set
|
||||
should_clear_expired_at = bool(data.clearExpiredAt or data.clear_expired_at)
|
||||
|
||||
if should_clear_expired_at:
|
||||
update_data["expired_at"] = None
|
||||
update_data["expired_count"] = -1
|
||||
elif "expired_at" in fields_set and data.expired_at != "":
|
||||
update_data["expired_at"] = data.expired_at
|
||||
|
||||
if (
|
||||
not should_clear_expired_at
|
||||
and "expired_count" in fields_set
|
||||
and data.expired_count is not None
|
||||
):
|
||||
update_data["expired_count"] = data.expired_count
|
||||
|
||||
if not update_data:
|
||||
raise HTTPException(status_code=400, detail="请选择要更新的字段")
|
||||
|
||||
result = await file_service.update_files(data.ids, update_data)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.patch("/file/batch-update")
|
||||
async def file_batch_update(
|
||||
data: BatchUpdateFileData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await batch_update_files(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/batch-update")
|
||||
async def file_batch_update_post(
|
||||
data: BatchUpdateFileData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await batch_update_files(data, file_service)
|
||||
|
||||
|
||||
async def apply_file_policy_action(
|
||||
data: FilePolicyActionData,
|
||||
file_service: FileService,
|
||||
):
|
||||
download_limit = data.downloadLimit
|
||||
if download_limit is None:
|
||||
download_limit = data.download_limit
|
||||
|
||||
detail = await file_service.apply_file_policy_action(
|
||||
file_id=data.id,
|
||||
action=data.action,
|
||||
download_limit=download_limit,
|
||||
)
|
||||
return APIResponse(detail=detail)
|
||||
|
||||
|
||||
@admin_api.patch("/file/policy-action")
|
||||
async def file_policy_action(
|
||||
data: FilePolicyActionData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await apply_file_policy_action(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/policy-action")
|
||||
async def file_policy_action_post(
|
||||
data: FilePolicyActionData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await apply_file_policy_action(data, file_service)
|
||||
|
||||
|
||||
async def apply_batch_file_policy_action(
|
||||
data: BatchFilePolicyActionData,
|
||||
file_service: FileService,
|
||||
):
|
||||
if not data.ids:
|
||||
raise HTTPException(status_code=400, detail="请选择要更新的文件")
|
||||
|
||||
download_limit = data.downloadLimit
|
||||
if download_limit is None:
|
||||
download_limit = data.download_limit
|
||||
|
||||
result = await file_service.apply_files_policy_action(
|
||||
file_ids=data.ids,
|
||||
action=data.action,
|
||||
download_limit=download_limit,
|
||||
)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.patch("/file/batch-policy-action")
|
||||
async def file_batch_policy_action(
|
||||
data: BatchFilePolicyActionData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await apply_batch_file_policy_action(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/batch-policy-action")
|
||||
async def file_batch_policy_action_post(
|
||||
data: BatchFilePolicyActionData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await apply_batch_file_policy_action(data, file_service)
|
||||
|
||||
|
||||
@admin_api.get("/file/list")
|
||||
async def file_list(
|
||||
page: int = 1,
|
||||
size: int = 10,
|
||||
keyword: str = "",
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
page: int = 1,
|
||||
size: int = 10,
|
||||
keyword: str = "",
|
||||
status: str = "",
|
||||
type: str = "",
|
||||
health: str = "",
|
||||
sortBy: str = "created_at",
|
||||
sortOrder: str = "desc",
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
files, total = await file_service.list_files(page, size, keyword)
|
||||
page = max(page, 1)
|
||||
size = min(max(size, 1), 100)
|
||||
files, total, summary = await file_service.list_files(
|
||||
page,
|
||||
size,
|
||||
keyword,
|
||||
status=status,
|
||||
file_type=type,
|
||||
health=health,
|
||||
sort_by=sortBy,
|
||||
sort_order=sortOrder,
|
||||
)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"page": page,
|
||||
"size": size,
|
||||
"data": files,
|
||||
"total": total,
|
||||
"summary": summary,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@admin_api.get("/file/detail")
|
||||
async def file_detail(
|
||||
id: int,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
detail = await file_service.get_file_detail(id)
|
||||
return APIResponse(detail=detail)
|
||||
|
||||
|
||||
@admin_api.post("/file/detail")
|
||||
async def file_detail_post(
|
||||
data: IDData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
detail = await file_service.get_file_detail(data.id)
|
||||
return APIResponse(detail=detail)
|
||||
|
||||
|
||||
async def update_file_metadata(
|
||||
data: FileMetadataData,
|
||||
file_service: FileService,
|
||||
):
|
||||
fields_set = data.model_fields_set
|
||||
update_note = "note" in fields_set
|
||||
update_tags = "tags" in fields_set
|
||||
if not update_note and not update_tags:
|
||||
raise HTTPException(status_code=400, detail="请选择要更新的元数据")
|
||||
|
||||
detail = await file_service.update_file_metadata(
|
||||
file_id=data.id,
|
||||
note=data.note,
|
||||
tags=data.tags,
|
||||
update_note=update_note,
|
||||
update_tags=update_tags,
|
||||
)
|
||||
return APIResponse(detail=detail)
|
||||
|
||||
|
||||
@admin_api.patch("/file/metadata")
|
||||
async def file_metadata(
|
||||
data: FileMetadataData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await update_file_metadata(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/metadata")
|
||||
async def file_metadata_post(
|
||||
data: FileMetadataData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await update_file_metadata(data, file_service)
|
||||
|
||||
|
||||
@admin_api.get("/file/view-presets")
|
||||
async def file_view_presets(
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
result = await file_service.list_file_view_presets()
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
async def save_file_view_preset(
|
||||
data: FileViewPresetData,
|
||||
file_service: FileService,
|
||||
):
|
||||
filters = data.filters if data.filters is not None else data.params
|
||||
preset = await file_service.save_file_view_preset(
|
||||
preset_id=data.id,
|
||||
name=data.name,
|
||||
filters=filters or {},
|
||||
)
|
||||
return APIResponse(detail=preset)
|
||||
|
||||
|
||||
@admin_api.post("/file/view-presets")
|
||||
async def file_view_presets_save(
|
||||
data: FileViewPresetData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await save_file_view_preset(data, file_service)
|
||||
|
||||
|
||||
@admin_api.patch("/file/view-presets")
|
||||
async def file_view_presets_patch(
|
||||
data: FileViewPresetData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await save_file_view_preset(data, file_service)
|
||||
|
||||
|
||||
async def delete_file_view_preset(
|
||||
data: FileViewPresetDeleteData,
|
||||
file_service: FileService,
|
||||
):
|
||||
result = await file_service.delete_file_view_preset(data.id)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.delete("/file/view-presets")
|
||||
async def file_view_presets_delete(
|
||||
data: FileViewPresetDeleteData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await delete_file_view_preset(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/view-presets/delete")
|
||||
async def file_view_presets_delete_post(
|
||||
data: FileViewPresetDeleteData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await delete_file_view_preset(data, file_service)
|
||||
|
||||
|
||||
@admin_api.get("/config/get")
|
||||
async def get_config(
|
||||
config_service: ConfigService = Depends(get_config_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
config_service: ConfigService = Depends(get_config_service),
|
||||
):
|
||||
return APIResponse(detail=config_service.get_config())
|
||||
|
||||
|
||||
@admin_api.patch("/config/update")
|
||||
async def update_config(
|
||||
data: dict,
|
||||
config_service: ConfigService = Depends(get_config_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
data: dict,
|
||||
config_service: ConfigService = Depends(get_config_service),
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
data.pop("themesChoices")
|
||||
data.pop("themesChoices", None)
|
||||
await config_service.update_config(data)
|
||||
await file_service.record_admin_activity(
|
||||
action="config.update",
|
||||
target_type="config",
|
||||
target_name="system",
|
||||
count=1,
|
||||
meta={"fields": sorted(data.keys())},
|
||||
)
|
||||
return APIResponse()
|
||||
|
||||
|
||||
@admin_api.get("/file/download")
|
||||
async def file_download(
|
||||
id: int,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
id: int,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
file_content = await file_service.download_file(id)
|
||||
return file_content
|
||||
|
||||
|
||||
@admin_api.get("/file/preview")
|
||||
async def file_preview(
|
||||
id: int,
|
||||
maxChars: int = 4000,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
preview = await file_service.preview_file(id, maxChars)
|
||||
return APIResponse(detail=preview)
|
||||
|
||||
|
||||
@admin_api.get("/local/lists")
|
||||
async def get_local_lists(
|
||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||
):
|
||||
files = await local_file_service.list_files()
|
||||
return APIResponse(detail=files)
|
||||
@@ -130,32 +527,50 @@ async def get_local_lists(
|
||||
|
||||
@admin_api.delete("/local/delete")
|
||||
async def delete_local_file(
|
||||
item: DeleteItem,
|
||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
item: DeleteItem,
|
||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
result = await local_file_service.delete_file(item.filename)
|
||||
await file_service.record_admin_activity(
|
||||
action="local_file.delete",
|
||||
target_type="local_file",
|
||||
target_name=item.filename,
|
||||
count=1,
|
||||
meta={"success": bool(result)},
|
||||
)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.post("/local/share")
|
||||
async def share_local_file(
|
||||
item: ShareItem,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
item: ShareItem,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
share_info = await file_service.share_local_file(item)
|
||||
await file_service.record_admin_activity(
|
||||
action="local_file.share",
|
||||
target_type="file",
|
||||
target_id=share_info.get("id") if isinstance(share_info, dict) else None,
|
||||
target_name=item.filename,
|
||||
count=1,
|
||||
meta={
|
||||
"expireValue": item.expire_value,
|
||||
"expireStyle": item.expire_style,
|
||||
},
|
||||
)
|
||||
return APIResponse(detail=share_info)
|
||||
|
||||
|
||||
@admin_api.patch("/file/update")
|
||||
async def update_file(
|
||||
data: UpdateFileData,
|
||||
admin: bool = Depends(admin_required),
|
||||
data: UpdateFileData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
file_code = await FileCodes.filter(id=data.id).first()
|
||||
if not file_code:
|
||||
raise HTTPException(status_code=404, detail="文件不存在")
|
||||
target_name = file_service._build_file_activity_name(file_code)
|
||||
update_data = {}
|
||||
|
||||
if data.code is not None and data.code != file_code.code:
|
||||
@@ -167,10 +582,23 @@ async def update_file(
|
||||
update_data["prefix"] = data.prefix
|
||||
if data.suffix is not None and data.suffix != file_code.suffix:
|
||||
update_data["suffix"] = data.suffix
|
||||
if data.expired_at is not None and data.expired_at != "" and data.expired_at != file_code.expired_at:
|
||||
if (
|
||||
data.expired_at is not None
|
||||
and data.expired_at != ""
|
||||
and data.expired_at != file_code.expired_at
|
||||
):
|
||||
update_data["expired_at"] = data.expired_at
|
||||
if data.expired_count is not None and data.expired_count != file_code.expired_count:
|
||||
update_data["expired_count"] = data.expired_count
|
||||
|
||||
await file_code.update_from_dict(update_data).save()
|
||||
if update_data:
|
||||
await file_service.record_admin_activity(
|
||||
action="file.update",
|
||||
target_type="file",
|
||||
target_id=data.id,
|
||||
target_name=target_name,
|
||||
count=1,
|
||||
meta={"fields": sorted(update_data.keys())},
|
||||
)
|
||||
return APIResponse(detail="更新成功")
|
||||
@@ -0,0 +1,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()
|
||||
@@ -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;
|
||||
"""
|
||||
)
|
||||
+6
-2
@@ -19,7 +19,7 @@ class FileCodes(models.Model):
|
||||
suffix = fields.CharField(max_length=255, default="")
|
||||
uuid_file_name = fields.CharField(max_length=255, null=True)
|
||||
file_path = fields.CharField(max_length=255, null=True)
|
||||
size = fields.IntField(default=0)
|
||||
size = fields.BigIntField(default=0)
|
||||
text = fields.TextField(null=True)
|
||||
expired_at = fields.DatetimeField(null=True)
|
||||
expired_count = fields.IntField(default=0)
|
||||
@@ -49,6 +49,7 @@ class UploadChunk(models.Model):
|
||||
file_size = fields.BigIntField()
|
||||
chunk_size = fields.IntField()
|
||||
file_name = fields.CharField(max_length=255)
|
||||
save_path = fields.CharField(max_length=512, null=True)
|
||||
created_at = fields.DatetimeField(auto_now_add=True)
|
||||
completed = fields.BooleanField(default=False)
|
||||
|
||||
@@ -66,6 +67,7 @@ class KeyValue(Model):
|
||||
|
||||
class PresignUploadSession(models.Model):
|
||||
"""预签名上传会话模型"""
|
||||
|
||||
id = fields.IntField(pk=True)
|
||||
upload_id = fields.CharField(max_length=36, unique=True, index=True)
|
||||
file_name = fields.CharField(max_length=255)
|
||||
@@ -85,4 +87,6 @@ class PresignUploadSession(models.Model):
|
||||
file_codes_pydantic = pydantic_model_creator(FileCodes, name="FileCodes")
|
||||
upload_chunk_pydantic = pydantic_model_creator(UploadChunk, name="UploadChunk")
|
||||
key_value_pydantic = pydantic_model_creator(KeyValue, name="KeyValue")
|
||||
presign_upload_session_pydantic = pydantic_model_creator(PresignUploadSession, name="PresignUploadSession")
|
||||
presign_upload_session_pydantic = pydantic_model_creator(
|
||||
PresignUploadSession, name="PresignUploadSession"
|
||||
)
|
||||
+23
-21
@@ -10,30 +10,32 @@ from typing import Optional, Tuple
|
||||
from apps.base.dependencies import IPRateLimit
|
||||
from apps.base.models import FileCodes
|
||||
from core.settings import settings
|
||||
from core.utils import get_random_num, get_random_string, max_save_times_desc, sanitize_filename
|
||||
from core.utils import (
|
||||
get_random_num,
|
||||
get_random_string,
|
||||
max_save_times_desc,
|
||||
sanitize_filename,
|
||||
get_now,
|
||||
)
|
||||
|
||||
|
||||
async def get_file_path_name(file: UploadFile) -> Tuple[str, str, str, str, str]:
|
||||
"""获取文件路径和文件名"""
|
||||
today = datetime.datetime.now()
|
||||
storage_path = settings.storage_path.strip("/") # 移除开头和结尾的斜杠
|
||||
today = await get_now()
|
||||
storage_path = settings.storage_path.strip("/")
|
||||
file_uuid = uuid.uuid4().hex
|
||||
# 一些客户端对非ASCII字符会进行编码,需要解码
|
||||
filename = await sanitize_filename(unquote(file.filename))
|
||||
# 使用 UUID 作为子目录名
|
||||
filename = await sanitize_filename(unquote(file.filename or ""))
|
||||
base_path = f"share/data/{today.strftime('%Y/%m/%d')}/{file_uuid}"
|
||||
# 如果设置了存储路径,将其添加到基础路径中
|
||||
path = f"{storage_path}/{base_path}" if storage_path else base_path
|
||||
prefix, suffix = os.path.splitext(filename)
|
||||
# 保持原始文件名
|
||||
save_path = f"{path}/{filename}"
|
||||
return path, suffix, prefix, filename, save_path
|
||||
|
||||
|
||||
async def get_chunk_file_path_name(file_name: str, upload_id: str) -> Tuple[str, str, str, str, str]:
|
||||
"""获取切片文件的路径和文件名"""
|
||||
today = datetime.datetime.now()
|
||||
storage_path = settings.storage_path.strip("/") # 移除开头和结尾的斜杠
|
||||
async def get_chunk_file_path_name(
|
||||
file_name: str, upload_id: str
|
||||
) -> Tuple[str, str, str, str, str]:
|
||||
today = await get_now()
|
||||
storage_path = settings.storage_path.strip("/")
|
||||
base_path = f"share/data/{today.strftime('%Y/%m/%d')}/{upload_id}"
|
||||
path = f"{storage_path}/{base_path}" if storage_path else base_path
|
||||
prefix, suffix = os.path.splitext(file_name)
|
||||
@@ -41,10 +43,11 @@ async def get_chunk_file_path_name(file_name: str, upload_id: str) -> Tuple[str,
|
||||
return path, suffix, prefix, file_name, save_path
|
||||
|
||||
|
||||
async def get_expire_info(expire_value: int, expire_style: str) -> Tuple[Optional[datetime.datetime], int, int, str]:
|
||||
"""获取过期信息"""
|
||||
async def get_expire_info(
|
||||
expire_value: int, expire_style: str
|
||||
) -> Tuple[Optional[datetime.datetime], int, int, str]:
|
||||
expired_count, used_count = -1, 0
|
||||
now = datetime.datetime.now()
|
||||
now = await get_now()
|
||||
code = None
|
||||
|
||||
max_timedelta = (
|
||||
@@ -64,7 +67,7 @@ async def get_expire_info(expire_value: int, expire_style: str) -> Tuple[Optiona
|
||||
"hour": lambda: now + datetime.timedelta(hours=expire_value),
|
||||
"minute": lambda: now + datetime.timedelta(minutes=expire_value),
|
||||
"count": lambda: (now + datetime.timedelta(days=1), expire_value),
|
||||
"forever": lambda: (None, None), # 修改这里
|
||||
"forever": lambda: (None, None),
|
||||
}
|
||||
|
||||
if expire_style in expire_styles:
|
||||
@@ -74,7 +77,7 @@ async def get_expire_info(expire_value: int, expire_style: str) -> Tuple[Optiona
|
||||
if expire_style == "count":
|
||||
expired_count = extra
|
||||
elif expire_style == "forever":
|
||||
code = await get_random_code(style="string") # 移动到这里
|
||||
code = await get_random_code(style="string")
|
||||
else:
|
||||
expired_at = result
|
||||
if expired_at and expired_at - now > max_timedelta:
|
||||
@@ -88,12 +91,11 @@ async def get_expire_info(expire_value: int, expire_style: str) -> Tuple[Optiona
|
||||
return expired_at, expired_count, used_count, code
|
||||
|
||||
|
||||
async def get_random_code(style="num") -> str:
|
||||
"""获取随机字符串"""
|
||||
async def get_random_code(style: str = "num") -> str:
|
||||
while True:
|
||||
code = await get_random_num() if style == "num" else await get_random_string()
|
||||
if not await FileCodes.filter(code=code).exists():
|
||||
return code
|
||||
return str(code)
|
||||
|
||||
|
||||
async def calculate_file_hash(file: UploadFile, chunk_size=1024 * 1024) -> str:
|
||||
|
||||
+353
-153
@@ -1,17 +1,31 @@
|
||||
import datetime
|
||||
from fnmatch import fnmatchcase
|
||||
import hashlib
|
||||
import os
|
||||
import uuid
|
||||
from datetime import timedelta
|
||||
from urllib.parse import unquote
|
||||
|
||||
from fastapi import APIRouter, Form, UploadFile, File, Depends, HTTPException
|
||||
from typing import Optional, Tuple, Union
|
||||
|
||||
from fastapi import APIRouter, Form, Request, UploadFile, File, Depends, HTTPException
|
||||
from pydantic import BaseModel, ValidationError
|
||||
from starlette import status
|
||||
|
||||
from apps.admin.dependencies import share_required_login
|
||||
from apps.base.models import FileCodes, UploadChunk, PresignUploadSession
|
||||
from apps.base.schemas import SelectFileModel, InitChunkUploadModel, CompleteUploadModel, PresignUploadInitRequest
|
||||
from apps.base.utils import get_expire_info, get_file_path_name, ip_limit, get_chunk_file_path_name
|
||||
from apps.base.schemas import (
|
||||
SelectFileModel,
|
||||
InitChunkUploadModel,
|
||||
CompleteUploadModel,
|
||||
PresignUploadInitRequest,
|
||||
)
|
||||
from apps.base.utils import (
|
||||
get_expire_info,
|
||||
get_file_path_name,
|
||||
ip_limit,
|
||||
get_chunk_file_path_name,
|
||||
)
|
||||
from core.response import APIResponse
|
||||
from core.settings import settings
|
||||
from core.storage import storages, FileStorageInterface
|
||||
@@ -25,7 +39,9 @@ class FileUploadService:
|
||||
"""统一的文件上传服务"""
|
||||
|
||||
@staticmethod
|
||||
async def generate_file_path(file_name: str, upload_id: str = None) -> tuple[str, str, str, str, str]:
|
||||
async def generate_file_path(
|
||||
file_name: str, upload_id: Optional[str] = None
|
||||
) -> tuple[str, str, str, str, str]:
|
||||
"""统一的路径生成"""
|
||||
today = datetime.datetime.now()
|
||||
storage_path = settings.storage_path.strip("/")
|
||||
@@ -44,10 +60,12 @@ class FileUploadService:
|
||||
file_path: str,
|
||||
expire_value: int,
|
||||
expire_style: str,
|
||||
**extra_fields
|
||||
**extra_fields,
|
||||
) -> str:
|
||||
"""统一创建FileCodes记录,返回code"""
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(expire_value, expire_style)
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(
|
||||
expire_value, expire_style
|
||||
)
|
||||
prefix, suffix = os.path.splitext(file_name)
|
||||
|
||||
await FileCodes.create(
|
||||
@@ -60,7 +78,7 @@ class FileUploadService:
|
||||
expired_at=expired_at,
|
||||
expired_count=expired_count,
|
||||
used_count=used_count,
|
||||
**extra_fields
|
||||
**extra_fields,
|
||||
)
|
||||
return code
|
||||
|
||||
@@ -68,8 +86,7 @@ class FileUploadService:
|
||||
async def validate_file_size(file: UploadFile, max_size: int) -> int:
|
||||
size = file.size
|
||||
if size is None:
|
||||
# 读取流计算大小,保持指针复位
|
||||
await file.seek(0, 2)
|
||||
await file.seek(0, 2) # type: ignore[arg-type]
|
||||
size = file.file.tell()
|
||||
await file.seek(0)
|
||||
if size > max_size:
|
||||
@@ -80,16 +97,52 @@ async def validate_file_size(file: UploadFile, max_size: int) -> int:
|
||||
return size
|
||||
|
||||
|
||||
def normalize_allowed_file_types() -> list[str]:
|
||||
raw_value = settings.allowed_file_types
|
||||
if isinstance(raw_value, str):
|
||||
values = raw_value.replace(";", ",").split(",")
|
||||
elif isinstance(raw_value, (list, tuple, set)):
|
||||
values = raw_value
|
||||
else:
|
||||
values = []
|
||||
|
||||
allowed = [str(item).strip().lower() for item in values if str(item).strip()]
|
||||
return allowed or ["*"]
|
||||
|
||||
|
||||
def validate_file_type(file_name: str, content_type: Optional[str] = None) -> None:
|
||||
allowed = normalize_allowed_file_types()
|
||||
if "*" in allowed or "*/*" in allowed:
|
||||
return
|
||||
|
||||
normalized_name = file_name.strip().lower()
|
||||
normalized_content_type = (content_type or "").strip().lower()
|
||||
|
||||
for rule in allowed:
|
||||
if "/" in rule and fnmatchcase(normalized_content_type, rule):
|
||||
return
|
||||
|
||||
extension = rule if rule.startswith(".") else f".{rule}"
|
||||
if normalized_name.endswith(extension):
|
||||
return
|
||||
|
||||
raise HTTPException(status_code=403, detail="不允许上传该类型文件")
|
||||
|
||||
|
||||
async def create_file_code(code, **kwargs):
|
||||
return await FileCodes.create(code=code, **kwargs)
|
||||
|
||||
|
||||
def normalize_share_code(code: str) -> str:
|
||||
return str(code or "").strip()
|
||||
|
||||
|
||||
@share_api.post("/text/", dependencies=[Depends(share_required_login)])
|
||||
async def share_text(
|
||||
text: str = Form(...),
|
||||
expire_value: int = Form(default=1, gt=0),
|
||||
expire_style: str = Form(default="day"),
|
||||
ip: str = Depends(ip_limit["upload"]),
|
||||
text: str = Form(...),
|
||||
expire_value: int = Form(default=1, gt=0),
|
||||
expire_style: str = Form(default="day"),
|
||||
ip: str = Depends(ip_limit["upload"]),
|
||||
):
|
||||
text_size = len(text.encode("utf-8"))
|
||||
max_txt_size = 222 * 1024
|
||||
@@ -114,15 +167,18 @@ async def share_text(
|
||||
|
||||
@share_api.post("/file/", dependencies=[Depends(share_required_login)])
|
||||
async def share_file(
|
||||
expire_value: int = Form(default=1, gt=0),
|
||||
expire_style: str = Form(default="day"),
|
||||
file: UploadFile = File(...),
|
||||
ip: str = Depends(ip_limit["upload"]),
|
||||
expire_value: int = Form(default=1, gt=0),
|
||||
expire_style: str = Form(default="day"),
|
||||
file: UploadFile = File(...),
|
||||
ip: str = Depends(ip_limit["upload"]),
|
||||
):
|
||||
file_size = await validate_file_size(file, settings.uploadSize)
|
||||
validate_file_type(file.filename or "", file.content_type)
|
||||
if expire_style not in settings.expireStyle:
|
||||
raise HTTPException(status_code=400, detail="过期时间类型错误")
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(expire_value, expire_style)
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(
|
||||
expire_value, expire_style
|
||||
)
|
||||
path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name(file)
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
await file_storage.save_file(file, save_path)
|
||||
@@ -141,8 +197,13 @@ async def share_file(
|
||||
return APIResponse(detail={"code": code, "name": file.filename})
|
||||
|
||||
|
||||
async def get_code_file_by_code(code, check=True):
|
||||
file_code = await FileCodes.filter(code=code).first()
|
||||
async def get_code_file_by_code(
|
||||
code: str, check: bool = True
|
||||
) -> Tuple[bool, Union[FileCodes, str]]:
|
||||
normalized_code = normalize_share_code(code)
|
||||
if not normalized_code:
|
||||
return False, "文件不存在"
|
||||
file_code = await FileCodes.filter(code=normalized_code).first()
|
||||
if not file_code:
|
||||
return False, "文件不存在"
|
||||
if await file_code.is_expired() and check:
|
||||
@@ -150,13 +211,71 @@ async def get_code_file_by_code(code, check=True):
|
||||
return True, file_code
|
||||
|
||||
|
||||
async def update_file_usage(file_code):
|
||||
async def update_file_usage(file_code: FileCodes) -> None:
|
||||
file_code.used_count += 1
|
||||
if file_code.expired_count > 0:
|
||||
file_code.expired_count -= 1
|
||||
await file_code.save()
|
||||
|
||||
|
||||
def build_file_metadata(file_code: FileCodes) -> dict:
|
||||
is_text = file_code.text is not None
|
||||
remaining_downloads = (
|
||||
file_code.expired_count if file_code.expired_count > 0 else None
|
||||
)
|
||||
return {
|
||||
"code": file_code.code,
|
||||
"name": file_code.prefix + file_code.suffix,
|
||||
"size": file_code.size,
|
||||
"type": "text" if is_text else "file",
|
||||
"is_text": is_text,
|
||||
"created_at": file_code.created_at,
|
||||
"expired_at": file_code.expired_at,
|
||||
"expires_at": file_code.expired_at,
|
||||
"expired_count": file_code.expired_count,
|
||||
"used_count": file_code.used_count,
|
||||
"remaining_downloads": remaining_downloads,
|
||||
}
|
||||
|
||||
|
||||
async def build_select_detail(
|
||||
file_code: FileCodes, file_storage: FileStorageInterface
|
||||
) -> dict:
|
||||
metadata = build_file_metadata(file_code)
|
||||
download_url = (
|
||||
None if file_code.text is not None else await file_storage.get_file_url(file_code)
|
||||
)
|
||||
content = file_code.text if file_code.text is not None else None
|
||||
return {
|
||||
**metadata,
|
||||
"text": content if content is not None else download_url,
|
||||
"content": content,
|
||||
"download_url": download_url,
|
||||
}
|
||||
|
||||
|
||||
@share_api.get("/metadata/")
|
||||
async def get_file_metadata(code: str, ip: str = Depends(ip_limit["error"])):
|
||||
has, file_code = await get_code_file_by_code(code)
|
||||
if not has:
|
||||
ip_limit["error"].add_ip(ip)
|
||||
return APIResponse(code=404, detail=file_code)
|
||||
|
||||
assert isinstance(file_code, FileCodes)
|
||||
return APIResponse(detail=build_file_metadata(file_code))
|
||||
|
||||
|
||||
@share_api.post("/metadata/")
|
||||
async def post_file_metadata(data: SelectFileModel, ip: str = Depends(ip_limit["error"])):
|
||||
has, file_code = await get_code_file_by_code(data.code)
|
||||
if not has:
|
||||
ip_limit["error"].add_ip(ip)
|
||||
return APIResponse(code=404, detail=file_code)
|
||||
|
||||
assert isinstance(file_code, FileCodes)
|
||||
return APIResponse(detail=build_file_metadata(file_code))
|
||||
|
||||
|
||||
@share_api.get("/select/")
|
||||
async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])):
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
@@ -165,6 +284,7 @@ async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])):
|
||||
ip_limit["error"].add_ip(ip)
|
||||
return APIResponse(code=404, detail=file_code)
|
||||
|
||||
assert isinstance(file_code, FileCodes)
|
||||
await update_file_usage(file_code)
|
||||
return await file_storage.get_file_response(file_code)
|
||||
|
||||
@@ -177,30 +297,22 @@ async def select_file(data: SelectFileModel, ip: str = Depends(ip_limit["error"]
|
||||
ip_limit["error"].add_ip(ip)
|
||||
return APIResponse(code=404, detail=file_code)
|
||||
|
||||
assert isinstance(file_code, FileCodes)
|
||||
await update_file_usage(file_code)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"code": file_code.code,
|
||||
"name": file_code.prefix + file_code.suffix,
|
||||
"size": file_code.size,
|
||||
"text": (
|
||||
file_code.text
|
||||
if file_code.text is not None
|
||||
else await file_storage.get_file_url(file_code)
|
||||
),
|
||||
}
|
||||
)
|
||||
return APIResponse(detail=await build_select_detail(file_code, file_storage))
|
||||
|
||||
|
||||
@share_api.get("/download")
|
||||
async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"])):
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
if await get_select_token(code) != key:
|
||||
normalized_code = normalize_share_code(code)
|
||||
if await get_select_token(normalized_code) != key:
|
||||
ip_limit["error"].add_ip(ip)
|
||||
raise HTTPException(status_code=403, detail="下载鉴权失败")
|
||||
has, file_code = await get_code_file_by_code(code, False)
|
||||
has, file_code = await get_code_file_by_code(normalized_code, False)
|
||||
if not has:
|
||||
return APIResponse(code=404, detail="文件不存在")
|
||||
assert isinstance(file_code, FileCodes)
|
||||
return (
|
||||
APIResponse(detail=file_code.text)
|
||||
if file_code.text
|
||||
@@ -211,16 +323,38 @@ async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"]
|
||||
chunk_api = APIRouter(prefix="/chunk", tags=["切片"])
|
||||
|
||||
|
||||
async def parse_body_model(request: Request, model_class: type[BaseModel]):
|
||||
content_type = request.headers.get("content-type", "").lower()
|
||||
try:
|
||||
if "application/x-www-form-urlencoded" in content_type or "multipart/form-data" in content_type:
|
||||
payload = dict(await request.form())
|
||||
else:
|
||||
payload = await request.json()
|
||||
return model_class.model_validate(payload)
|
||||
except ValidationError as e:
|
||||
raise HTTPException(status_code=422, detail=e.errors())
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="请求体格式错误")
|
||||
|
||||
|
||||
async def parse_init_chunk_upload(request: Request) -> InitChunkUploadModel:
|
||||
return await parse_body_model(request, InitChunkUploadModel)
|
||||
|
||||
|
||||
async def parse_complete_upload(request: Request) -> CompleteUploadModel:
|
||||
return await parse_body_model(request, CompleteUploadModel)
|
||||
|
||||
|
||||
@chunk_api.post("/upload/init/", dependencies=[Depends(share_required_login)])
|
||||
async def init_chunk_upload(data: InitChunkUploadModel):
|
||||
async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chunk_upload)):
|
||||
validate_file_type(data.file_name)
|
||||
# 服务端校验:根据 total_chunks * chunk_size 计算理论最大上传量
|
||||
total_chunks = (data.file_size + data.chunk_size - 1) // data.chunk_size
|
||||
max_possible_size = total_chunks * data.chunk_size
|
||||
if max_possible_size > settings.uploadSize:
|
||||
max_size_mb = settings.uploadSize / (1024 * 1024)
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail=f"文件大小超过限制,最大为 {max_size_mb:.2f} MB"
|
||||
status_code=403, detail=f"文件大小超过限制,最大为 {max_size_mb:.2f} MB"
|
||||
)
|
||||
|
||||
# # 秒传检查
|
||||
@@ -247,21 +381,25 @@ async def init_chunk_upload(data: InitChunkUploadModel):
|
||||
).first()
|
||||
|
||||
if existing_session:
|
||||
# 复用已有会话,获取已上传的分片列表
|
||||
uploaded_chunks = await UploadChunk.filter(
|
||||
upload_id=existing_session.upload_id,
|
||||
completed=True
|
||||
).values_list('chunk_index', flat=True)
|
||||
return APIResponse(detail={
|
||||
"existed": False,
|
||||
"upload_id": existing_session.upload_id,
|
||||
"chunk_size": existing_session.chunk_size,
|
||||
"total_chunks": existing_session.total_chunks,
|
||||
"uploaded_chunks": list(uploaded_chunks)
|
||||
})
|
||||
if not existing_session.save_path:
|
||||
await UploadChunk.filter(upload_id=existing_session.upload_id).delete()
|
||||
else:
|
||||
uploaded_chunks = await UploadChunk.filter(
|
||||
upload_id=existing_session.upload_id, completed=True
|
||||
).values_list("chunk_index", flat=True)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"existed": False,
|
||||
"upload_id": existing_session.upload_id,
|
||||
"chunk_size": existing_session.chunk_size,
|
||||
"total_chunks": existing_session.total_chunks,
|
||||
"uploaded_chunks": list(uploaded_chunks),
|
||||
}
|
||||
)
|
||||
|
||||
# 创建新的上传会话
|
||||
upload_id = uuid.uuid4().hex
|
||||
_, _, _, _, save_path = await get_chunk_file_path_name(data.file_name, upload_id)
|
||||
await UploadChunk.create(
|
||||
upload_id=upload_id,
|
||||
chunk_index=-1,
|
||||
@@ -270,21 +408,27 @@ async def init_chunk_upload(data: InitChunkUploadModel):
|
||||
chunk_size=data.chunk_size,
|
||||
chunk_hash=data.file_hash,
|
||||
file_name=data.file_name,
|
||||
save_path=save_path,
|
||||
)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"existed": False,
|
||||
"upload_id": upload_id,
|
||||
"chunk_size": data.chunk_size,
|
||||
"total_chunks": total_chunks,
|
||||
"uploaded_chunks": [],
|
||||
}
|
||||
)
|
||||
return APIResponse(detail={
|
||||
"existed": False,
|
||||
"upload_id": upload_id,
|
||||
"chunk_size": data.chunk_size,
|
||||
"total_chunks": total_chunks,
|
||||
"uploaded_chunks": []
|
||||
})
|
||||
|
||||
|
||||
@chunk_api.post("/upload/chunk/{upload_id}/{chunk_index}", dependencies=[Depends(share_required_login)])
|
||||
@chunk_api.post(
|
||||
"/upload/chunk/{upload_id}/{chunk_index}",
|
||||
dependencies=[Depends(share_required_login)],
|
||||
)
|
||||
async def upload_chunk(
|
||||
upload_id: str,
|
||||
chunk_index: int,
|
||||
chunk: UploadFile = File(...),
|
||||
upload_id: str,
|
||||
chunk_index: int,
|
||||
chunk: UploadFile = File(...),
|
||||
):
|
||||
# 获取上传会话信息
|
||||
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||
@@ -297,12 +441,12 @@ async def upload_chunk(
|
||||
|
||||
# 检查是否已上传(支持断点续传)
|
||||
existing_chunk = await UploadChunk.filter(
|
||||
upload_id=upload_id,
|
||||
chunk_index=chunk_index,
|
||||
completed=True
|
||||
upload_id=upload_id, chunk_index=chunk_index, completed=True
|
||||
).first()
|
||||
if existing_chunk:
|
||||
return APIResponse(detail={"chunk_hash": existing_chunk.chunk_hash, "skipped": True})
|
||||
return APIResponse(
|
||||
detail={"chunk_hash": existing_chunk.chunk_hash, "skipped": True}
|
||||
)
|
||||
|
||||
# 读取分片数据并计算哈希
|
||||
chunk_data = await chunk.read()
|
||||
@@ -312,47 +456,49 @@ async def upload_chunk(
|
||||
if chunk_size > chunk_info.chunk_size:
|
||||
raise HTTPException(
|
||||
status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"分片大小超过声明值: 最大 {chunk_info.chunk_size}, 实际 {chunk_size}"
|
||||
detail=f"分片大小超过声明值: 最大 {chunk_info.chunk_size}, 实际 {chunk_size}",
|
||||
)
|
||||
|
||||
# 计算已上传分片数,校验累计大小不超限(用分片数 * chunk_size 估算)
|
||||
uploaded_count = await UploadChunk.filter(
|
||||
upload_id=upload_id,
|
||||
completed=True
|
||||
upload_id=upload_id, completed=True
|
||||
).count()
|
||||
# 已上传分片的最大可能大小 + 当前分片
|
||||
max_uploaded_size = uploaded_count * chunk_info.chunk_size + chunk_size
|
||||
if max_uploaded_size > settings.uploadSize:
|
||||
max_size_mb = settings.uploadSize / (1024 * 1024)
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail=f"累计上传大小超过限制,最大为 {max_size_mb:.2f} MB"
|
||||
status_code=403, detail=f"累计上传大小超过限制,最大为 {max_size_mb:.2f} MB"
|
||||
)
|
||||
|
||||
|
||||
chunk_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||
|
||||
# 获取文件路径
|
||||
_, _, _, _, save_path = await get_chunk_file_path_name(chunk_info.file_name, upload_id)
|
||||
|
||||
save_path = chunk_info.save_path
|
||||
|
||||
# 保存分片到存储
|
||||
storage = storages[settings.file_storage]()
|
||||
try:
|
||||
await storage.save_chunk(upload_id, chunk_index, chunk_data, chunk_hash, save_path)
|
||||
await storage.save_chunk(
|
||||
upload_id, chunk_index, chunk_data, chunk_hash, save_path
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"分片保存失败: {str(e)}")
|
||||
|
||||
raise HTTPException(
|
||||
status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"分片保存失败: {str(e)}"
|
||||
)
|
||||
|
||||
# 更新或创建分片记录(保存成功后再记录)
|
||||
await UploadChunk.update_or_create(
|
||||
upload_id=upload_id,
|
||||
chunk_index=chunk_index,
|
||||
defaults={
|
||||
'chunk_hash': chunk_hash,
|
||||
'completed': True,
|
||||
'file_size': chunk_info.file_size,
|
||||
'total_chunks': chunk_info.total_chunks,
|
||||
'chunk_size': chunk_info.chunk_size,
|
||||
'file_name': chunk_info.file_name
|
||||
}
|
||||
"chunk_hash": chunk_hash,
|
||||
"completed": True,
|
||||
"file_size": chunk_info.file_size,
|
||||
"total_chunks": chunk_info.total_chunks,
|
||||
"chunk_size": chunk_info.chunk_size,
|
||||
"file_name": chunk_info.file_name,
|
||||
"save_path": chunk_info.save_path,
|
||||
},
|
||||
)
|
||||
return APIResponse(detail={"chunk_hash": chunk_hash})
|
||||
|
||||
@@ -363,50 +509,58 @@ async def cancel_upload(upload_id: str):
|
||||
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||
if not chunk_info:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在")
|
||||
|
||||
# 获取文件路径
|
||||
_, _, _, _, save_path = await get_chunk_file_path_name(chunk_info.file_name, upload_id)
|
||||
|
||||
|
||||
save_path = chunk_info.save_path
|
||||
|
||||
# 清理存储中的临时文件
|
||||
storage = storages[settings.file_storage]()
|
||||
try:
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
except Exception as e:
|
||||
# 记录错误但不阻止删除数据库记录
|
||||
pass
|
||||
|
||||
if save_path:
|
||||
try:
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
# 清理数据库记录
|
||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||
|
||||
|
||||
return APIResponse(detail={"message": "上传已取消"})
|
||||
|
||||
|
||||
@chunk_api.get("/upload/status/{upload_id}", dependencies=[Depends(share_required_login)])
|
||||
@chunk_api.get(
|
||||
"/upload/status/{upload_id}", dependencies=[Depends(share_required_login)]
|
||||
)
|
||||
async def get_upload_status(upload_id: str):
|
||||
"""获取上传状态"""
|
||||
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||
if not chunk_info:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在")
|
||||
|
||||
|
||||
# 获取已上传的分片列表
|
||||
uploaded_chunks = await UploadChunk.filter(
|
||||
upload_id=upload_id,
|
||||
completed=True
|
||||
).values_list('chunk_index', flat=True)
|
||||
|
||||
return APIResponse(detail={
|
||||
"upload_id": upload_id,
|
||||
"file_name": chunk_info.file_name,
|
||||
"file_size": chunk_info.file_size,
|
||||
"chunk_size": chunk_info.chunk_size,
|
||||
"total_chunks": chunk_info.total_chunks,
|
||||
"uploaded_chunks": list(uploaded_chunks),
|
||||
"progress": len(uploaded_chunks) / chunk_info.total_chunks * 100
|
||||
})
|
||||
upload_id=upload_id, completed=True
|
||||
).values_list("chunk_index", flat=True)
|
||||
|
||||
return APIResponse(
|
||||
detail={
|
||||
"upload_id": upload_id,
|
||||
"file_name": chunk_info.file_name,
|
||||
"file_size": chunk_info.file_size,
|
||||
"chunk_size": chunk_info.chunk_size,
|
||||
"total_chunks": chunk_info.total_chunks,
|
||||
"uploaded_chunks": list(uploaded_chunks),
|
||||
"progress": len(uploaded_chunks) / chunk_info.total_chunks * 100,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@chunk_api.post("/upload/complete/{upload_id}", dependencies=[Depends(share_required_login)])
|
||||
async def complete_upload(upload_id: str, data: CompleteUploadModel, ip: str = Depends(ip_limit["upload"])):
|
||||
@chunk_api.post(
|
||||
"/upload/complete/{upload_id}", dependencies=[Depends(share_required_login)]
|
||||
)
|
||||
async def complete_upload(
|
||||
upload_id: str,
|
||||
data: CompleteUploadModel = Depends(parse_complete_upload),
|
||||
ip: str = Depends(ip_limit["upload"]),
|
||||
):
|
||||
# 获取上传基本信息
|
||||
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||
if not chunk_info:
|
||||
@@ -415,8 +569,7 @@ async def complete_upload(upload_id: str, data: CompleteUploadModel, ip: str = D
|
||||
storage = storages[settings.file_storage]()
|
||||
# 验证所有分片
|
||||
completed_chunks_list = await UploadChunk.filter(
|
||||
upload_id=upload_id,
|
||||
completed=True
|
||||
upload_id=upload_id, completed=True
|
||||
).all()
|
||||
if len(completed_chunks_list) != chunk_info.total_chunks:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="分片不完整")
|
||||
@@ -424,27 +577,29 @@ async def complete_upload(upload_id: str, data: CompleteUploadModel, ip: str = D
|
||||
# 用分片数 * chunk_size 校验最大可能大小
|
||||
max_total_size = len(completed_chunks_list) * chunk_info.chunk_size
|
||||
if max_total_size > settings.uploadSize:
|
||||
# 清理已上传的分片
|
||||
_, _, _, _, save_path = await get_chunk_file_path_name(chunk_info.file_name, upload_id)
|
||||
try:
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
except Exception:
|
||||
pass
|
||||
save_path = chunk_info.save_path
|
||||
if save_path:
|
||||
try:
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
except Exception:
|
||||
pass
|
||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||
max_size_mb = settings.uploadSize / (1024 * 1024)
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail=f"实际上传大小超过限制,最大为 {max_size_mb:.2f} MB"
|
||||
status_code=403, detail=f"实际上传大小超过限制,最大为 {max_size_mb:.2f} MB"
|
||||
)
|
||||
|
||||
# 获取文件路径
|
||||
path, suffix, prefix, _, save_path = await get_chunk_file_path_name(chunk_info.file_name, upload_id)
|
||||
|
||||
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)
|
||||
|
||||
try:
|
||||
# 合并文件并计算哈希
|
||||
_, file_hash = await storage.merge_chunks(upload_id, chunk_info, save_path)
|
||||
# 创建文件记录
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(data.expire_value, data.expire_style)
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(
|
||||
data.expire_value, data.expire_style
|
||||
)
|
||||
await FileCodes.create(
|
||||
code=code,
|
||||
file_hash=file_hash, # 使用合并后计算的哈希
|
||||
@@ -457,7 +612,7 @@ async def complete_upload(upload_id: str, data: CompleteUploadModel, ip: str = D
|
||||
file_path=path,
|
||||
uuid_file_name=f"{prefix}{suffix}",
|
||||
prefix=prefix,
|
||||
suffix=suffix
|
||||
suffix=suffix,
|
||||
)
|
||||
# 清理临时文件
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
@@ -473,7 +628,9 @@ async def complete_upload(upload_id: str, data: CompleteUploadModel, ip: str = D
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
except Exception:
|
||||
pass
|
||||
raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"文件合并失败: {str(e)}")
|
||||
raise HTTPException(
|
||||
status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"文件合并失败: {str(e)}"
|
||||
)
|
||||
|
||||
|
||||
# ============ 预签名上传API ============
|
||||
@@ -482,7 +639,17 @@ presign_api = APIRouter(prefix="/presign", tags=["预签名上传"])
|
||||
PRESIGN_SESSION_EXPIRES = 900 # 15分钟
|
||||
|
||||
|
||||
async def _get_valid_session(upload_id: str, expected_mode: str = None) -> PresignUploadSession:
|
||||
def build_proxy_upload_urls(upload_id: str) -> dict:
|
||||
proxy_upload_url = f"/presign/upload/proxy/{upload_id}"
|
||||
return {
|
||||
"proxy_upload_url": proxy_upload_url,
|
||||
"legacy_proxy_upload_url": f"/api{proxy_upload_url}",
|
||||
}
|
||||
|
||||
|
||||
async def _get_valid_session(
|
||||
upload_id: str, expected_mode: Optional[str] = None
|
||||
) -> PresignUploadSession:
|
||||
"""获取并验证会话"""
|
||||
session = await PresignUploadSession.filter(upload_id=upload_id).first()
|
||||
if not session:
|
||||
@@ -496,21 +663,32 @@ async def _get_valid_session(upload_id: str, expected_mode: str = None) -> Presi
|
||||
|
||||
|
||||
@presign_api.post("/upload/init", dependencies=[Depends(share_required_login)])
|
||||
async def presign_upload_init(data: PresignUploadInitRequest, ip: str = Depends(ip_limit["upload"])):
|
||||
async def presign_upload_init(
|
||||
data: PresignUploadInitRequest, ip: str = Depends(ip_limit["upload"])
|
||||
):
|
||||
"""初始化预签名上传,S3返回直传URL,其他存储返回代理URL"""
|
||||
validate_file_type(data.file_name)
|
||||
if data.file_size > settings.uploadSize:
|
||||
raise HTTPException(403, f"文件大小超过限制,最大为 {settings.uploadSize / (1024*1024):.2f} MB")
|
||||
raise HTTPException(
|
||||
403,
|
||||
f"文件大小超过限制,最大为 {settings.uploadSize / (1024 * 1024):.2f} MB",
|
||||
)
|
||||
if data.expire_style not in settings.expireStyle:
|
||||
raise HTTPException(400, "过期时间类型错误")
|
||||
|
||||
upload_id = uuid.uuid4().hex
|
||||
path, _, _, filename, save_path = await FileUploadService.generate_file_path(data.file_name, upload_id)
|
||||
path, _, _, filename, save_path = await FileUploadService.generate_file_path(
|
||||
data.file_name, upload_id
|
||||
)
|
||||
|
||||
storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
presigned_url = await storage.generate_presigned_upload_url(save_path, PRESIGN_SESSION_EXPIRES)
|
||||
presigned_url = await storage.generate_presigned_upload_url(
|
||||
save_path, PRESIGN_SESSION_EXPIRES
|
||||
)
|
||||
|
||||
mode = "direct" if presigned_url else "proxy"
|
||||
upload_url = presigned_url or f"/api/presign/upload/proxy/{upload_id}"
|
||||
proxy_urls = build_proxy_upload_urls(upload_id)
|
||||
upload_url = presigned_url or proxy_urls["proxy_upload_url"]
|
||||
|
||||
await PresignUploadSession.create(
|
||||
upload_id=upload_id,
|
||||
@@ -524,16 +702,26 @@ async def presign_upload_init(data: PresignUploadInitRequest, ip: str = Depends(
|
||||
)
|
||||
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
return APIResponse(detail={
|
||||
detail = {
|
||||
"upload_id": upload_id,
|
||||
"upload_url": upload_url,
|
||||
"mode": mode,
|
||||
"expires_in": PRESIGN_SESSION_EXPIRES,
|
||||
})
|
||||
}
|
||||
if mode == "proxy":
|
||||
detail.update(proxy_urls)
|
||||
|
||||
return APIResponse(
|
||||
detail=detail
|
||||
)
|
||||
|
||||
|
||||
@presign_api.put("/upload/proxy/{upload_id}", dependencies=[Depends(share_required_login)])
|
||||
async def presign_upload_proxy(upload_id: str, file: UploadFile = File(...), ip: str = Depends(ip_limit["upload"])):
|
||||
@presign_api.put(
|
||||
"/upload/proxy/{upload_id}", dependencies=[Depends(share_required_login)]
|
||||
)
|
||||
async def presign_upload_proxy(
|
||||
upload_id: str, file: UploadFile = File(...), ip: str = Depends(ip_limit["upload"])
|
||||
):
|
||||
"""代理模式上传,服务器转存到存储后端"""
|
||||
session = await _get_valid_session(upload_id, expected_mode="proxy")
|
||||
|
||||
@@ -548,8 +736,11 @@ async def presign_upload_proxy(upload_id: str, file: UploadFile = File(...), ip:
|
||||
raise HTTPException(500, f"文件保存失败: {str(e)}")
|
||||
|
||||
code = await FileUploadService.create_file_record(
|
||||
session.file_name, file_size, os.path.dirname(session.save_path),
|
||||
session.expire_value, session.expire_style
|
||||
session.file_name,
|
||||
file_size,
|
||||
os.path.dirname(session.save_path),
|
||||
session.expire_value,
|
||||
session.expire_style,
|
||||
)
|
||||
|
||||
await session.delete()
|
||||
@@ -557,7 +748,9 @@ async def presign_upload_proxy(upload_id: str, file: UploadFile = File(...), ip:
|
||||
return APIResponse(detail={"code": code, "name": session.file_name})
|
||||
|
||||
|
||||
@presign_api.post("/upload/confirm/{upload_id}", dependencies=[Depends(share_required_login)])
|
||||
@presign_api.post(
|
||||
"/upload/confirm/{upload_id}", dependencies=[Depends(share_required_login)]
|
||||
)
|
||||
async def presign_upload_confirm(upload_id: str, ip: str = Depends(ip_limit["upload"])):
|
||||
"""直传确认,客户端完成S3直传后调用获取分享码"""
|
||||
session = await _get_valid_session(upload_id, expected_mode="direct")
|
||||
@@ -567,8 +760,11 @@ async def presign_upload_confirm(upload_id: str, ip: str = Depends(ip_limit["upl
|
||||
raise HTTPException(404, "文件未上传或上传失败")
|
||||
|
||||
code = await FileUploadService.create_file_record(
|
||||
session.file_name, session.file_size, os.path.dirname(session.save_path),
|
||||
session.expire_value, session.expire_style
|
||||
session.file_name,
|
||||
session.file_size,
|
||||
os.path.dirname(session.save_path),
|
||||
session.expire_value,
|
||||
session.expire_style,
|
||||
)
|
||||
|
||||
await session.delete()
|
||||
@@ -576,22 +772,26 @@ async def presign_upload_confirm(upload_id: str, ip: str = Depends(ip_limit["upl
|
||||
return APIResponse(detail={"code": code, "name": session.file_name})
|
||||
|
||||
|
||||
@presign_api.get("/upload/status/{upload_id}", dependencies=[Depends(share_required_login)])
|
||||
@presign_api.get(
|
||||
"/upload/status/{upload_id}", dependencies=[Depends(share_required_login)]
|
||||
)
|
||||
async def presign_upload_status(upload_id: str):
|
||||
"""查询上传会话状态"""
|
||||
session = await PresignUploadSession.filter(upload_id=upload_id).first()
|
||||
if not session:
|
||||
raise HTTPException(404, "上传会话不存在")
|
||||
|
||||
return APIResponse(detail={
|
||||
"upload_id": session.upload_id,
|
||||
"file_name": session.file_name,
|
||||
"file_size": session.file_size,
|
||||
"mode": session.mode,
|
||||
"created_at": session.created_at.isoformat(),
|
||||
"expires_at": session.expires_at.isoformat(),
|
||||
"is_expired": await session.is_expired(),
|
||||
})
|
||||
return APIResponse(
|
||||
detail={
|
||||
"upload_id": session.upload_id,
|
||||
"file_name": session.file_name,
|
||||
"file_size": session.file_size,
|
||||
"mode": session.mode,
|
||||
"created_at": session.created_at.isoformat(),
|
||||
"expires_at": session.expires_at.isoformat(),
|
||||
"is_expired": await session.is_expired(),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@presign_api.delete("/upload/{upload_id}", dependencies=[Depends(share_required_login)])
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
from apps.base.models import KeyValue
|
||||
from apps.base.utils import ip_limit
|
||||
from core.settings import DEFAULT_CONFIG, settings
|
||||
|
||||
|
||||
async def ensure_settings_row() -> None:
|
||||
await KeyValue.get_or_create(key="settings", defaults={"value": DEFAULT_CONFIG})
|
||||
|
||||
|
||||
def _sync_ip_limits() -> None:
|
||||
ip_limit["error"].minutes = settings.errorMinute
|
||||
ip_limit["error"].count = settings.errorCount
|
||||
ip_limit["upload"].minutes = settings.uploadMinute
|
||||
ip_limit["upload"].count = settings.uploadCount
|
||||
|
||||
|
||||
async def refresh_settings() -> None:
|
||||
"""从数据库读取最新配置并应用到运行时。"""
|
||||
config_record = await KeyValue.filter(key="settings").first()
|
||||
settings.user_config = config_record.value if config_record and config_record.value else {}
|
||||
_sync_ip_limits()
|
||||
+83
-18
@@ -1,6 +1,9 @@
|
||||
import asyncio
|
||||
import glob
|
||||
import importlib
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import IO
|
||||
|
||||
from tortoise import Tortoise
|
||||
|
||||
@@ -8,29 +11,91 @@ from core.logger import logger
|
||||
from core.settings import data_root
|
||||
|
||||
|
||||
_DB_FILE = os.path.join(data_root, "filecodebox.db")
|
||||
_STARTUP_LOCK_FILE = os.path.join(data_root, "filecodebox.startup.lock")
|
||||
|
||||
|
||||
def get_db_config() -> dict:
|
||||
return {
|
||||
"connections": {
|
||||
"default": {
|
||||
"engine": "tortoise.backends.sqlite",
|
||||
"credentials": {
|
||||
"file_path": _DB_FILE,
|
||||
"journal_mode": "WAL",
|
||||
"busy_timeout": 10000,
|
||||
"foreign_keys": "ON",
|
||||
},
|
||||
}
|
||||
},
|
||||
"apps": {
|
||||
"models": {
|
||||
"models": ["apps.base.models"],
|
||||
"default_connection": "default",
|
||||
}
|
||||
},
|
||||
"use_tz": False,
|
||||
"timezone": "Asia/Shanghai",
|
||||
}
|
||||
|
||||
|
||||
def _lock_file(file_obj: IO[str]) -> None:
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
# Windows 需要锁定至少 1 字节
|
||||
if os.fstat(file_obj.fileno()).st_size == 0:
|
||||
file_obj.write("0")
|
||||
file_obj.flush()
|
||||
msvcrt.locking(file_obj.fileno(), msvcrt.LK_LOCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(file_obj.fileno(), fcntl.LOCK_EX)
|
||||
|
||||
|
||||
def _unlock_file(file_obj: IO[str]) -> None:
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
msvcrt.locking(file_obj.fileno(), msvcrt.LK_UNLCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(file_obj.fileno(), fcntl.LOCK_UN)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def db_startup_lock():
|
||||
os.makedirs(data_root, exist_ok=True)
|
||||
lock_file = open(_STARTUP_LOCK_FILE, "a+", encoding="utf-8")
|
||||
try:
|
||||
await asyncio.to_thread(_lock_file, lock_file)
|
||||
yield
|
||||
finally:
|
||||
await asyncio.to_thread(_unlock_file, lock_file)
|
||||
lock_file.close()
|
||||
|
||||
|
||||
async def init_db():
|
||||
try:
|
||||
# 使用正确的Tortoise初始化配置格式
|
||||
db_config = {
|
||||
"db_url": f"sqlite://{data_root}/filecodebox.db",
|
||||
"modules": {"models": ["apps.base.models"]},
|
||||
"use_tz": False,
|
||||
"timezone": "Asia/Shanghai"
|
||||
}
|
||||
db_config = get_db_config()
|
||||
|
||||
await Tortoise.init(**db_config)
|
||||
if not Tortoise._inited:
|
||||
await Tortoise.init(config=db_config)
|
||||
|
||||
# 创建migrations表
|
||||
await Tortoise.get_connection("default").execute_script("""
|
||||
CREATE TABLE IF NOT EXISTS migrates (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
migration_file VARCHAR(255) NOT NULL UNIQUE,
|
||||
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
""")
|
||||
async with db_startup_lock():
|
||||
# 创建migrations表
|
||||
await Tortoise.get_connection("default").execute_script("""
|
||||
CREATE TABLE IF NOT EXISTS migrates (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
migration_file VARCHAR(255) NOT NULL UNIQUE,
|
||||
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
""")
|
||||
|
||||
# 执行迁移
|
||||
await execute_migrations()
|
||||
# 执行迁移
|
||||
await execute_migrations()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"数据库初始化失败: {str(e)}")
|
||||
|
||||
+9
-4
@@ -2,14 +2,19 @@
|
||||
# @Author : Lan
|
||||
# @File : response.py
|
||||
# @Software: PyCharm
|
||||
from typing import Generic, TypeVar
|
||||
from typing import Generic, Optional, TypeVar
|
||||
|
||||
from pydantic.v1.generics import GenericModel
|
||||
from pydantic import BaseModel
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class APIResponse(GenericModel, Generic[T]):
|
||||
class APIResponse(BaseModel, Generic[T]):
|
||||
code: int = 200
|
||||
message: str = "ok"
|
||||
detail: T
|
||||
msg: Optional[str] = None
|
||||
detail: Optional[T] = None
|
||||
|
||||
def model_post_init(self, __context) -> None:
|
||||
if self.msg is None:
|
||||
self.msg = self.message
|
||||
+3
-1
@@ -26,6 +26,7 @@ DEFAULT_CONFIG = {
|
||||
"s3_region_name": "auto",
|
||||
"s3_signature_version": "s3v2",
|
||||
"s3_hostname": "",
|
||||
"s3_addressing_style": "auto",
|
||||
"s3_proxy": 0,
|
||||
"max_save_seconds": 0,
|
||||
"aws_session_token": "",
|
||||
@@ -40,6 +41,7 @@ DEFAULT_CONFIG = {
|
||||
"admin_token": "FileCodeBox2023",
|
||||
"openUpload": 1,
|
||||
"uploadSize": 1024 * 1024 * 10,
|
||||
"allowed_file_types": ["*"],
|
||||
"expireStyle": ["day", "hour", "minute", "forever", "count"],
|
||||
"uploadMinute": 1,
|
||||
"enableChunk": 0,
|
||||
@@ -65,7 +67,7 @@ DEFAULT_CONFIG = {
|
||||
],
|
||||
"themesSelect": "themes/2024",
|
||||
"errorMinute": 1,
|
||||
"errorCount": 1,
|
||||
"errorCount": 10,
|
||||
"serverWorkers": 1,
|
||||
"serverHost": "0.0.0.0",
|
||||
"serverPort": 12345,
|
||||
|
||||
+467
-248
@@ -4,6 +4,8 @@
|
||||
# @Software: PyCharm
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
import tempfile
|
||||
from core.logger import logger
|
||||
import shutil
|
||||
from typing import Optional
|
||||
@@ -14,7 +16,6 @@ import aiohttp
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
import datetime
|
||||
import io
|
||||
import re
|
||||
import aioboto3
|
||||
from botocore.config import Config
|
||||
@@ -23,7 +24,7 @@ from core.response import APIResponse
|
||||
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
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
|
||||
|
||||
class FileStorageInterface:
|
||||
@@ -144,10 +145,20 @@ class SystemFileStorage(FileStorageInterface):
|
||||
filename = f"{file_code.prefix}{file_code.suffix}"
|
||||
encoded_filename = quote(filename, safe='')
|
||||
content_disposition = f"attachment; filename*=UTF-8''{encoded_filename}"
|
||||
|
||||
# 尝试获取文件系统大小,如果成功则设置 Content-Length
|
||||
headers = {"Content-Disposition": content_disposition}
|
||||
try:
|
||||
content_length = file_path.stat().st_size
|
||||
headers["Content-Length"] = str(content_length)
|
||||
except Exception:
|
||||
# 如果获取文件大小失败,则不提供 Content-Length
|
||||
pass
|
||||
|
||||
return FileResponse(
|
||||
file_path,
|
||||
media_type="application/octet-stream",
|
||||
headers={"Content-Disposition": content_disposition},
|
||||
headers=headers,
|
||||
filename=filename # 保留原始文件名以备某些场景使用
|
||||
)
|
||||
|
||||
@@ -256,6 +267,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
self.signature_version = settings.s3_signature_version
|
||||
self.endpoint_url = settings.s3_endpoint_url or f"https://{self.s3_hostname}"
|
||||
self.aws_session_token = settings.aws_session_token
|
||||
self.addressing_style = str(settings.s3_addressing_style or "auto").lower()
|
||||
self.proxy = settings.s3_proxy
|
||||
self.session = aioboto3.Session(
|
||||
aws_access_key_id=self.access_key_id,
|
||||
@@ -267,28 +279,36 @@ 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:
|
||||
await s3.put_object(
|
||||
Bucket=self.bucket_name,
|
||||
Key=save_path,
|
||||
Body=await file.read(),
|
||||
ContentType=file.content_type,
|
||||
async with self._client() as s3:
|
||||
# 使用 upload_fileobj 流式上传,避免将整个文件加载到内存
|
||||
await s3.upload_fileobj(
|
||||
file.file,
|
||||
self.bucket_name,
|
||||
save_path,
|
||||
ExtraArgs={"ContentType": file.content_type or "application/octet-stream"},
|
||||
)
|
||||
|
||||
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()
|
||||
)
|
||||
@@ -296,12 +316,24 @@ class S3FileStorage(FileStorageInterface):
|
||||
async def get_file_response(self, file_code: FileCodes):
|
||||
try:
|
||||
filename = file_code.prefix + file_code.suffix
|
||||
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:
|
||||
content_length = None # 初始化为 None,表示未知大小
|
||||
|
||||
async with self._client() as s3:
|
||||
# 尝试获取文件大小(HEAD请求)
|
||||
try:
|
||||
head_response = await s3.head_object(
|
||||
Bucket=self.bucket_name,
|
||||
Key=await file_code.get_file_path()
|
||||
)
|
||||
# 从HEAD响应中获取Content-Length
|
||||
if 'ContentLength' in head_response:
|
||||
content_length = head_response['ContentLength']
|
||||
elif 'Content-Length' in head_response['ResponseMetadata']['HTTPHeaders']:
|
||||
content_length = int(head_response['ResponseMetadata']['HTTPHeaders']['Content-Length'])
|
||||
except Exception:
|
||||
# 如果HEAD请求失败,则不提供 Content-Length
|
||||
pass
|
||||
|
||||
link = await s3.generate_presigned_url(
|
||||
"get_object",
|
||||
Params={
|
||||
@@ -310,20 +342,42 @@ class S3FileStorage(FileStorageInterface):
|
||||
},
|
||||
ExpiresIn=3600,
|
||||
)
|
||||
tmp = io.BytesIO()
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(link) as resp:
|
||||
tmp.write(await resp.read())
|
||||
tmp.seek(0)
|
||||
content = tmp.read()
|
||||
tmp.close()
|
||||
return Response(
|
||||
content,
|
||||
|
||||
# 创建ClientSession并传递给生成器复用
|
||||
session = aiohttp.ClientSession()
|
||||
|
||||
async def stream_generator():
|
||||
try:
|
||||
async with session.get(link) as resp:
|
||||
if resp.status != 200:
|
||||
raise HTTPException(
|
||||
status_code=resp.status,
|
||||
detail=f"从S3获取文件失败: {resp.status}"
|
||||
)
|
||||
# 设置块大小(例如64KB)
|
||||
chunk_size = 65536
|
||||
while True:
|
||||
chunk = await resp.content.read(chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
from fastapi.responses import StreamingResponse
|
||||
encoded_filename = quote(filename, safe='')
|
||||
headers = {
|
||||
"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
|
||||
}
|
||||
if content_length is not None:
|
||||
headers["Content-Length"] = str(content_length)
|
||||
return StreamingResponse(
|
||||
stream_generator(),
|
||||
media_type="application/octet-stream",
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="{filename.encode("utf-8").decode("latin-1")}"'
|
||||
},
|
||||
headers=headers
|
||||
)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
raise HTTPException(status_code=503, detail="服务代理下载异常,请稍后再试")
|
||||
|
||||
@@ -333,12 +387,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
if self.proxy:
|
||||
return await get_file_url(file_code.code)
|
||||
else:
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
async with self._client() as s3:
|
||||
result = await s3.generate_presigned_url(
|
||||
"get_object",
|
||||
Params={
|
||||
@@ -355,13 +404,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
注意:这里不使用 S3 原生的 multipart upload,而是将每个分片作为独立对象存储
|
||||
"""
|
||||
chunk_key = str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part")
|
||||
async with self.session.client(
|
||||
's3',
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
async with self._client() as s3:
|
||||
# 将分片作为独立对象上传
|
||||
await s3.put_object(
|
||||
Bucket=self.bucket_name,
|
||||
@@ -376,51 +419,76 @@ class S3FileStorage(FileStorageInterface):
|
||||
async def merge_chunks(self, upload_id: str, chunk_info: UploadChunk, save_path: str) -> tuple[str, str]:
|
||||
"""
|
||||
合并 S3 上的分片文件
|
||||
由于分片是独立对象存储的,需要下载后合并再上传
|
||||
使用 S3 的 multipart upload API 实现流式合并,避免内存问题
|
||||
"""
|
||||
file_sha256 = hashlib.sha256()
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
merged_data = io.BytesIO()
|
||||
|
||||
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:
|
||||
# 按顺序读取并验证每个分片
|
||||
for i in range(chunk_info.total_chunks):
|
||||
chunk_key = f"{chunk_dir}/{i}.part"
|
||||
chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first()
|
||||
if not chunk_record:
|
||||
raise ValueError(f"分片{i}记录不存在")
|
||||
|
||||
try:
|
||||
response = await s3.get_object(
|
||||
Bucket=self.bucket_name,
|
||||
Key=chunk_key
|
||||
)
|
||||
chunk_data = await response['Body'].read()
|
||||
except Exception as e:
|
||||
raise ValueError(f"分片{i}文件不存在: {e}")
|
||||
|
||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||
if current_hash != chunk_record.chunk_hash:
|
||||
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
||||
|
||||
file_sha256.update(chunk_data)
|
||||
merged_data.write(chunk_data)
|
||||
|
||||
# 上传合并后的文件
|
||||
merged_data.seek(0)
|
||||
await s3.put_object(
|
||||
|
||||
async with self._client() as s3:
|
||||
# 创建 multipart upload
|
||||
mpu = await s3.create_multipart_upload(
|
||||
Bucket=self.bucket_name,
|
||||
Key=save_path,
|
||||
Body=merged_data.getvalue(),
|
||||
ContentType='application/octet-stream'
|
||||
)
|
||||
|
||||
mpu_id = mpu['UploadId']
|
||||
parts = []
|
||||
|
||||
try:
|
||||
# 按顺序读取、验证并上传每个分片
|
||||
for i in range(chunk_info.total_chunks):
|
||||
chunk_key = f"{chunk_dir}/{i}.part"
|
||||
chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first()
|
||||
if not chunk_record:
|
||||
raise ValueError(f"分片{i}记录不存在")
|
||||
|
||||
try:
|
||||
response = await s3.get_object(
|
||||
Bucket=self.bucket_name,
|
||||
Key=chunk_key
|
||||
)
|
||||
chunk_data = await response['Body'].read()
|
||||
except Exception as e:
|
||||
raise ValueError(f"分片{i}文件不存在: {e}")
|
||||
|
||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||
if current_hash != chunk_record.chunk_hash:
|
||||
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
||||
|
||||
file_sha256.update(chunk_data)
|
||||
|
||||
# 上传分片到 multipart upload
|
||||
part_response = await s3.upload_part(
|
||||
Bucket=self.bucket_name,
|
||||
Key=save_path,
|
||||
UploadId=mpu_id,
|
||||
PartNumber=i + 1, # S3 part numbers start at 1
|
||||
Body=chunk_data
|
||||
)
|
||||
parts.append({
|
||||
'PartNumber': i + 1,
|
||||
'ETag': part_response['ETag']
|
||||
})
|
||||
|
||||
# 释放内存
|
||||
del chunk_data
|
||||
|
||||
# 完成 multipart upload
|
||||
await s3.complete_multipart_upload(
|
||||
Bucket=self.bucket_name,
|
||||
Key=save_path,
|
||||
UploadId=mpu_id,
|
||||
MultipartUpload={'Parts': parts}
|
||||
)
|
||||
except Exception as e:
|
||||
# 出错时取消 multipart upload
|
||||
await s3.abort_multipart_upload(
|
||||
Bucket=self.bucket_name,
|
||||
Key=save_path,
|
||||
UploadId=mpu_id
|
||||
)
|
||||
raise e
|
||||
|
||||
return save_path, file_sha256.hexdigest()
|
||||
|
||||
async def clean_chunks(self, upload_id: str, save_path: str):
|
||||
@@ -430,13 +498,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
:param save_path: 文件保存路径
|
||||
"""
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
async with self.session.client(
|
||||
's3',
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
async with self._client() as s3:
|
||||
try:
|
||||
# 列出并删除所有分片对象
|
||||
paginator = s3.get_paginator('list_objects_v2')
|
||||
@@ -458,13 +520,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
:param expires_in: URL过期时间(秒),默认15分钟
|
||||
:return: 预签名PUT URL
|
||||
"""
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
async with self._client() as s3:
|
||||
return await s3.generate_presigned_url(
|
||||
"put_object",
|
||||
Params={
|
||||
@@ -480,18 +536,31 @@ class S3FileStorage(FileStorageInterface):
|
||||
:param save_path: 文件路径
|
||||
:return: 文件是否存在
|
||||
"""
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
async with self._client() as s3:
|
||||
last_error = None
|
||||
for attempt in range(3):
|
||||
try:
|
||||
await s3.head_object(Bucket=self.bucket_name, Key=save_path)
|
||||
return True
|
||||
except Exception as e:
|
||||
last_error = e
|
||||
if attempt < 2:
|
||||
await asyncio.sleep(0.2 * (attempt + 1))
|
||||
|
||||
try:
|
||||
await s3.head_object(Bucket=self.bucket_name, Key=save_path)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
result = await s3.list_objects_v2(
|
||||
Bucket=self.bucket_name,
|
||||
Prefix=save_path,
|
||||
MaxKeys=1,
|
||||
)
|
||||
for item in result.get("Contents", []):
|
||||
if item.get("Key") == save_path:
|
||||
return True
|
||||
except Exception as e:
|
||||
last_error = e
|
||||
|
||||
logger.warning(f"S3文件确认失败 key={save_path}: {last_error}")
|
||||
return False
|
||||
|
||||
|
||||
class OneDriveFileStorage(FileStorageInterface):
|
||||
@@ -602,20 +671,51 @@ class OneDriveFileStorage(FileStorageInterface):
|
||||
link = await asyncio.to_thread(
|
||||
self._get_file_url, await file_code.get_file_path(), filename
|
||||
)
|
||||
tmp = io.BytesIO()
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(link) as resp:
|
||||
tmp.write(await resp.read())
|
||||
tmp.seek(0)
|
||||
content = tmp.read()
|
||||
tmp.close()
|
||||
return Response(
|
||||
content,
|
||||
|
||||
content_length = None # 初始化为 None,表示未知大小
|
||||
|
||||
# 创建ClientSession并复用
|
||||
session = aiohttp.ClientSession()
|
||||
|
||||
# 尝试发送HEAD请求获取Content-Length
|
||||
try:
|
||||
async with session.head(link) as resp:
|
||||
if resp.status == 200 and 'Content-Length' in resp.headers:
|
||||
content_length = int(resp.headers['Content-Length'])
|
||||
except Exception:
|
||||
# 如果HEAD请求失败,则不提供 Content-Length
|
||||
pass
|
||||
|
||||
async def stream_generator():
|
||||
try:
|
||||
async with session.get(link) as resp:
|
||||
if resp.status != 200:
|
||||
raise HTTPException(
|
||||
status_code=resp.status,
|
||||
detail=f"从OneDrive获取文件失败: {resp.status}"
|
||||
)
|
||||
chunk_size = 65536
|
||||
while True:
|
||||
chunk = await resp.content.read(chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
encoded_filename = quote(filename, safe='')
|
||||
headers = {
|
||||
"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
|
||||
}
|
||||
if content_length is not None:
|
||||
headers["Content-Length"] = str(content_length)
|
||||
return StreamingResponse(
|
||||
stream_generator(),
|
||||
media_type="application/octet-stream",
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="{filename.encode("utf-8").decode("latin-1")}"'
|
||||
},
|
||||
headers=headers
|
||||
)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
raise HTTPException(status_code=503, detail="服务代理下载异常,请稍后再试")
|
||||
|
||||
@@ -682,33 +782,44 @@ class OneDriveFileStorage(FileStorageInterface):
|
||||
current_folder.upload(filename, data).execute_query()
|
||||
|
||||
async def merge_chunks(self, upload_id: str, chunk_info: UploadChunk, save_path: str) -> tuple[str, str]:
|
||||
"""合并 OneDrive 上的分片文件"""
|
||||
"""合并 OneDrive 上的分片文件,使用临时文件避免内存问题"""
|
||||
file_sha256 = hashlib.sha256()
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
merged_data = io.BytesIO()
|
||||
|
||||
for i in range(chunk_info.total_chunks):
|
||||
chunk_path = f"{chunk_dir}/{i}.part"
|
||||
chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first()
|
||||
if not chunk_record:
|
||||
raise ValueError(f"分片{i}记录不存在")
|
||||
|
||||
try:
|
||||
chunk_data = await asyncio.to_thread(self._read_chunk, chunk_path)
|
||||
except Exception as e:
|
||||
raise ValueError(f"分片{i}文件不存在: {e}")
|
||||
|
||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||
if current_hash != chunk_record.chunk_hash:
|
||||
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
||||
|
||||
file_sha256.update(chunk_data)
|
||||
merged_data.write(chunk_data)
|
||||
|
||||
# 上传合并后的文件
|
||||
merged_data.seek(0)
|
||||
await asyncio.to_thread(self._upload_merged, save_path, merged_data.getvalue())
|
||||
|
||||
|
||||
# 使用临时文件存储合并数据
|
||||
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
||||
temp_path = temp_file.name
|
||||
|
||||
try:
|
||||
async with aiofiles.open(temp_path, 'wb') as out_file:
|
||||
for i in range(chunk_info.total_chunks):
|
||||
chunk_path = f"{chunk_dir}/{i}.part"
|
||||
chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first()
|
||||
if not chunk_record:
|
||||
raise ValueError(f"分片{i}记录不存在")
|
||||
|
||||
try:
|
||||
chunk_data = await asyncio.to_thread(self._read_chunk, chunk_path)
|
||||
except Exception as e:
|
||||
raise ValueError(f"分片{i}文件不存在: {e}")
|
||||
|
||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||
if current_hash != chunk_record.chunk_hash:
|
||||
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
||||
|
||||
file_sha256.update(chunk_data)
|
||||
await out_file.write(chunk_data)
|
||||
del chunk_data # 释放内存
|
||||
|
||||
# 读取临时文件并上传
|
||||
async with aiofiles.open(temp_path, 'rb') as f:
|
||||
merged_content = await f.read()
|
||||
await asyncio.to_thread(self._upload_merged, save_path, merged_content)
|
||||
finally:
|
||||
# 清理临时文件
|
||||
if os.path.exists(temp_path):
|
||||
os.unlink(temp_path)
|
||||
|
||||
return save_path, file_sha256.hexdigest()
|
||||
|
||||
def _delete_chunk_dir(self, chunk_dir: str):
|
||||
@@ -765,7 +876,9 @@ class OpenDALFileStorage(FileStorageInterface):
|
||||
)
|
||||
|
||||
async def save_file(self, file: UploadFile, save_path: str):
|
||||
await self.operator.write(save_path, file.file.read())
|
||||
# 使用 asyncio.to_thread 避免阻塞事件循环
|
||||
content = await asyncio.to_thread(file.file.read)
|
||||
await self.operator.write(save_path, content)
|
||||
|
||||
async def delete_file(self, file_code: FileCodes):
|
||||
await self.operator.delete(await file_code.get_file_path())
|
||||
@@ -776,11 +889,54 @@ class OpenDALFileStorage(FileStorageInterface):
|
||||
async def get_file_response(self, file_code: FileCodes):
|
||||
try:
|
||||
filename = file_code.prefix + file_code.suffix
|
||||
content = await self.operator.read(await file_code.get_file_path())
|
||||
content_length = None # 初始化为 None,表示未知大小
|
||||
|
||||
# 尝试获取文件大小
|
||||
try:
|
||||
stat_result = await self.operator.stat(await file_code.get_file_path())
|
||||
if hasattr(stat_result, 'content_length') and stat_result.content_length:
|
||||
content_length = stat_result.content_length
|
||||
elif hasattr(stat_result, 'size') and stat_result.size:
|
||||
content_length = stat_result.size
|
||||
except Exception:
|
||||
# 如果获取大小失败,则不提供 Content-Length
|
||||
pass
|
||||
|
||||
# 尝试使用流式读取器
|
||||
try:
|
||||
# OpenDAL 可能提供 reader 方法返回一个异步读取器
|
||||
reader = await self.operator.reader(await file_code.get_file_path())
|
||||
except AttributeError:
|
||||
# 如果 reader 方法不存在,回退到全量读取(兼容旧版本)
|
||||
content = await self.operator.read(await file_code.get_file_path())
|
||||
encoded_filename = quote(filename, safe='')
|
||||
headers = {
|
||||
"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
|
||||
}
|
||||
if content_length is not None:
|
||||
headers["Content-Length"] = str(content_length)
|
||||
return Response(
|
||||
content, headers=headers, media_type="application/octet-stream"
|
||||
)
|
||||
|
||||
async def stream_generator():
|
||||
chunk_size = 65536
|
||||
while True:
|
||||
chunk = await reader.read(chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
|
||||
encoded_filename = quote(filename, safe='')
|
||||
headers = {
|
||||
"Content-Disposition": f'attachment; filename="{filename}"'}
|
||||
return Response(
|
||||
content, headers=headers, media_type="application/octet-stream"
|
||||
"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
|
||||
}
|
||||
if content_length is not None:
|
||||
headers["Content-Length"] = str(content_length)
|
||||
return StreamingResponse(
|
||||
stream_generator(),
|
||||
media_type="application/octet-stream",
|
||||
headers=headers
|
||||
)
|
||||
except Exception as e:
|
||||
logger.info(e)
|
||||
@@ -792,32 +948,43 @@ class OpenDALFileStorage(FileStorageInterface):
|
||||
await self.operator.write(chunk_path, chunk_data)
|
||||
|
||||
async def merge_chunks(self, upload_id: str, chunk_info: UploadChunk, save_path: str) -> tuple[str, str]:
|
||||
"""合并 OpenDAL 存储上的分片文件"""
|
||||
"""合并 OpenDAL 存储上的分片文件,使用临时文件避免内存问题"""
|
||||
file_sha256 = hashlib.sha256()
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
merged_data = io.BytesIO()
|
||||
|
||||
for i in range(chunk_info.total_chunks):
|
||||
chunk_path = f"{chunk_dir}/{i}.part"
|
||||
chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first()
|
||||
if not chunk_record:
|
||||
raise ValueError(f"分片{i}记录不存在")
|
||||
|
||||
try:
|
||||
chunk_data = await self.operator.read(chunk_path)
|
||||
except Exception as e:
|
||||
raise ValueError(f"分片{i}文件不存在: {e}")
|
||||
|
||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||
if current_hash != chunk_record.chunk_hash:
|
||||
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
||||
|
||||
file_sha256.update(chunk_data)
|
||||
merged_data.write(chunk_data)
|
||||
|
||||
# 写入合并后的文件
|
||||
merged_data.seek(0)
|
||||
await self.operator.write(save_path, merged_data.getvalue())
|
||||
|
||||
# 使用临时文件存储合并数据
|
||||
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
||||
temp_path = temp_file.name
|
||||
|
||||
try:
|
||||
async with aiofiles.open(temp_path, 'wb') as out_file:
|
||||
for i in range(chunk_info.total_chunks):
|
||||
chunk_path = f"{chunk_dir}/{i}.part"
|
||||
chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first()
|
||||
if not chunk_record:
|
||||
raise ValueError(f"分片{i}记录不存在")
|
||||
|
||||
try:
|
||||
chunk_data = await self.operator.read(chunk_path)
|
||||
except Exception as e:
|
||||
raise ValueError(f"分片{i}文件不存在: {e}")
|
||||
|
||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||
if current_hash != chunk_record.chunk_hash:
|
||||
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
||||
|
||||
file_sha256.update(chunk_data)
|
||||
await out_file.write(chunk_data)
|
||||
del chunk_data # 释放内存
|
||||
|
||||
# 读取临时文件并写入存储
|
||||
async with aiofiles.open(temp_path, 'rb') as f:
|
||||
merged_content = await f.read()
|
||||
await self.operator.write(save_path, merged_content)
|
||||
finally:
|
||||
# 清理临时文件
|
||||
if os.path.exists(temp_path):
|
||||
os.unlink(temp_path)
|
||||
|
||||
return save_path, file_sha256.hexdigest()
|
||||
|
||||
@@ -910,7 +1077,7 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
current_path = current_path.parent
|
||||
|
||||
async def save_file(self, file: UploadFile, save_path: str):
|
||||
"""保存文件(自动创建目录)"""
|
||||
"""保存文件(自动创建目录,流式上传)"""
|
||||
path_obj = Path(save_path)
|
||||
directory_path = str(path_obj.parent)
|
||||
# 提取原始文件名并进行清理
|
||||
@@ -921,13 +1088,23 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
try:
|
||||
# 先创建目录结构
|
||||
await self._mkdir_p(directory_path)
|
||||
# 上传文件
|
||||
# 上传文件(流式)
|
||||
url = self._build_url(safe_save_path)
|
||||
|
||||
async def file_sender():
|
||||
"""流式读取文件内容"""
|
||||
chunk_size = 256 * 1024 # 256KB chunks
|
||||
while True:
|
||||
chunk = await asyncio.to_thread(file.file.read, chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
|
||||
async with aiohttp.ClientSession(auth=self.auth) as session:
|
||||
content = await file.read()
|
||||
async with session.put(
|
||||
url, data=content, headers={
|
||||
"Content-Type": file.content_type}
|
||||
url,
|
||||
data=file_sender(),
|
||||
headers={"Content-Type": file.content_type or "application/octet-stream"}
|
||||
) as resp:
|
||||
if resp.status not in (200, 201, 204):
|
||||
content = await resp.text()
|
||||
@@ -969,26 +1146,50 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
try:
|
||||
filename = file_code.prefix + file_code.suffix
|
||||
url = self._build_url(await file_code.get_file_path())
|
||||
async with aiohttp.ClientSession(headers={
|
||||
content_length = None # 初始化为 None,表示未知大小
|
||||
|
||||
# 创建ClientSession并复用(包含认证头)
|
||||
session = aiohttp.ClientSession(headers={
|
||||
"Authorization": f"Basic {base64.b64encode(f'{settings.webdav_username}:{settings.webdav_password}'.encode()).decode()}"
|
||||
}) as session:
|
||||
async with session.get(url) as resp:
|
||||
if resp.status != 200:
|
||||
raise HTTPException(
|
||||
status_code=resp.status,
|
||||
detail=f"文件获取失败{resp.status}: {await resp.text()}",
|
||||
)
|
||||
# 读取内容到内存
|
||||
content = await resp.read()
|
||||
return Response(
|
||||
content=content,
|
||||
media_type=resp.headers.get(
|
||||
"Content-Type", "application/octet-stream"
|
||||
),
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="{filename.encode("utf-8").decode()}"'
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
# 尝试发送HEAD请求获取Content-Length
|
||||
try:
|
||||
async with session.head(url) as resp:
|
||||
if resp.status == 200 and 'Content-Length' in resp.headers:
|
||||
content_length = int(resp.headers['Content-Length'])
|
||||
except Exception:
|
||||
# 如果HEAD请求失败,则不提供 Content-Length
|
||||
pass
|
||||
|
||||
async def stream_generator():
|
||||
try:
|
||||
async with session.get(url) as resp:
|
||||
if resp.status != 200:
|
||||
raise HTTPException(
|
||||
status_code=resp.status,
|
||||
detail=f"文件获取失败{resp.status}: {await resp.text()}",
|
||||
)
|
||||
chunk_size = 65536
|
||||
while True:
|
||||
chunk = await resp.content.read(chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
encoded_filename = quote(filename, safe='')
|
||||
headers = {
|
||||
"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
|
||||
}
|
||||
if content_length is not None:
|
||||
headers["Content-Length"] = str(content_length)
|
||||
return StreamingResponse(
|
||||
stream_generator(),
|
||||
media_type="application/octet-stream",
|
||||
headers=headers
|
||||
)
|
||||
except aiohttp.ClientError as e:
|
||||
raise HTTPException(
|
||||
status_code=503, detail=f"WebDAV连接异常: {str(e)}")
|
||||
@@ -1014,52 +1215,70 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
async def merge_chunks(self, upload_id: str, chunk_info: UploadChunk, save_path: str) -> tuple[str, str]:
|
||||
"""
|
||||
合并 WebDAV 上的分片文件
|
||||
由于大多数 WebDAV 服务器不支持 PATCH 追加,这里下载所有分片后合并上传
|
||||
使用临时文件避免内存问题
|
||||
"""
|
||||
file_sha256 = hashlib.sha256()
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
merged_data = io.BytesIO()
|
||||
|
||||
async with aiohttp.ClientSession(auth=self.auth) as session:
|
||||
# 按顺序读取并验证每个分片
|
||||
for i in range(chunk_info.total_chunks):
|
||||
chunk_path = f"{chunk_dir}/{i}.part"
|
||||
chunk_url = self._build_url(chunk_path)
|
||||
|
||||
# 获取分片记录
|
||||
chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first()
|
||||
if not chunk_record:
|
||||
raise ValueError(f"分片{i}记录不存在")
|
||||
|
||||
# 下载分片数据
|
||||
async with session.get(chunk_url) as resp:
|
||||
if resp.status != 200:
|
||||
raise ValueError(f"分片{i}文件不存在或无法访问")
|
||||
chunk_data = await resp.read()
|
||||
|
||||
# 验证哈希
|
||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||
if current_hash != chunk_record.chunk_hash:
|
||||
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
||||
|
||||
file_sha256.update(chunk_data)
|
||||
merged_data.write(chunk_data)
|
||||
|
||||
# 确保目标目录存在
|
||||
output_dir = str(Path(save_path).parent)
|
||||
await self._mkdir_p(output_dir)
|
||||
|
||||
# 上传合并后的文件
|
||||
output_url = self._build_url(save_path)
|
||||
merged_data.seek(0)
|
||||
async with session.put(output_url, data=merged_data.getvalue()) as resp:
|
||||
if resp.status not in (200, 201, 204):
|
||||
content = await resp.text()
|
||||
raise HTTPException(
|
||||
status_code=resp.status,
|
||||
detail=f"合并文件上传失败: {content[:200]}"
|
||||
)
|
||||
|
||||
|
||||
# 使用临时文件存储合并数据,避免内存问题
|
||||
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
||||
temp_path = temp_file.name
|
||||
|
||||
try:
|
||||
async with aiohttp.ClientSession(auth=self.auth) as session:
|
||||
# 按顺序读取并验证每个分片,写入临时文件
|
||||
async with aiofiles.open(temp_path, 'wb') as out_file:
|
||||
for i in range(chunk_info.total_chunks):
|
||||
chunk_path = f"{chunk_dir}/{i}.part"
|
||||
chunk_url = self._build_url(chunk_path)
|
||||
|
||||
# 获取分片记录
|
||||
chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first()
|
||||
if not chunk_record:
|
||||
raise ValueError(f"分片{i}记录不存在")
|
||||
|
||||
# 下载分片数据
|
||||
async with session.get(chunk_url) as resp:
|
||||
if resp.status != 200:
|
||||
raise ValueError(f"分片{i}文件不存在或无法访问")
|
||||
chunk_data = await resp.read()
|
||||
|
||||
# 验证哈希
|
||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||
if current_hash != chunk_record.chunk_hash:
|
||||
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
||||
|
||||
file_sha256.update(chunk_data)
|
||||
await out_file.write(chunk_data)
|
||||
del chunk_data # 释放内存
|
||||
|
||||
# 确保目标目录存在
|
||||
output_dir = str(Path(save_path).parent)
|
||||
await self._mkdir_p(output_dir)
|
||||
|
||||
# 流式上传合并后的文件
|
||||
output_url = self._build_url(save_path)
|
||||
|
||||
async def file_sender():
|
||||
async with aiofiles.open(temp_path, 'rb') as f:
|
||||
while True:
|
||||
chunk = await f.read(256 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
|
||||
async with session.put(output_url, data=file_sender()) as resp:
|
||||
if resp.status not in (200, 201, 204):
|
||||
content = await resp.text()
|
||||
raise HTTPException(
|
||||
status_code=resp.status,
|
||||
detail=f"合并文件上传失败: {content[:200]}"
|
||||
)
|
||||
finally:
|
||||
# 清理临时文件
|
||||
if os.path.exists(temp_path):
|
||||
os.unlink(temp_path)
|
||||
|
||||
return save_path, file_sha256.hexdigest()
|
||||
|
||||
async def clean_chunks(self, upload_id: str, save_path: str):
|
||||
|
||||
+21
-18
@@ -11,15 +11,17 @@ from tortoise.expressions import Q
|
||||
|
||||
from apps.base.models import FileCodes, UploadChunk
|
||||
from apps.base.utils import ip_limit, get_chunk_file_path_name
|
||||
from core.config import refresh_settings
|
||||
from core.settings import settings, data_root
|
||||
from core.storage import FileStorageInterface, storages
|
||||
from core.utils import get_now
|
||||
|
||||
|
||||
async def delete_expire_files():
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
while True:
|
||||
try:
|
||||
await refresh_settings()
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
# 遍历 share目录下的所有文件夹,删除空的文件夹,并判断父目录是否为空,如果为空也删除
|
||||
if settings.file_storage == "local":
|
||||
for root, dirs, files in os.walk(f"{data_root}/share/data"):
|
||||
@@ -46,38 +48,39 @@ async def delete_expire_files():
|
||||
|
||||
|
||||
async def clean_incomplete_uploads():
|
||||
"""清理超时未完成的分片上传"""
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
# 默认 24 小时未完成的上传视为过期
|
||||
expire_hours = getattr(settings, 'chunk_expire_hours', 24)
|
||||
while True:
|
||||
try:
|
||||
expire_time = datetime.datetime.now() - datetime.timedelta(hours=expire_hours)
|
||||
# 查找所有过期的上传会话(chunk_index=-1 的记录)
|
||||
await refresh_settings()
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
expire_hours = getattr(settings, "chunk_expire_hours", 24)
|
||||
now = await get_now()
|
||||
expire_time = now - datetime.timedelta(hours=expire_hours)
|
||||
expired_sessions = await UploadChunk.filter(
|
||||
chunk_index=-1,
|
||||
created_at__lt=expire_time
|
||||
chunk_index=-1, created_at__lt=expire_time
|
||||
).all()
|
||||
|
||||
for session in expired_sessions:
|
||||
try:
|
||||
# 获取分片存储路径
|
||||
_, _, _, _, save_path = await get_chunk_file_path_name(
|
||||
session.file_name, session.upload_id
|
||||
)
|
||||
# 清理存储中的临时文件
|
||||
save_path = session.save_path
|
||||
if not save_path:
|
||||
_, _, _, _, save_path = await get_chunk_file_path_name(
|
||||
session.file_name, session.upload_id
|
||||
)
|
||||
await file_storage.clean_chunks(session.upload_id, save_path)
|
||||
except Exception as e:
|
||||
logging.error(f"清理分片文件失败 upload_id={session.upload_id}: {e}")
|
||||
logging.error(
|
||||
f"清理分片文件失败 upload_id={session.upload_id}: {e}"
|
||||
)
|
||||
|
||||
try:
|
||||
# 删除该会话的所有数据库记录
|
||||
await UploadChunk.filter(upload_id=session.upload_id).delete()
|
||||
logging.info(f"已清理过期上传会话 upload_id={session.upload_id}")
|
||||
except Exception as e:
|
||||
logging.error(f"删除分片记录失败 upload_id={session.upload_id}: {e}")
|
||||
logging.error(
|
||||
f"删除分片记录失败 upload_id={session.upload_id}: {e}"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"清理未完成上传任务异常: {e}")
|
||||
finally:
|
||||
await asyncio.sleep(3600) # 每小时执行一次
|
||||
await asyncio.sleep(3600)
|
||||
+46
-6
@@ -47,7 +47,9 @@ async def get_select_token(code: str):
|
||||
:return:
|
||||
"""
|
||||
token = settings.admin_token
|
||||
return hashlib.sha256(f"{code}{int(time.time() / 1000)}000{token}".encode()).hexdigest()
|
||||
return hashlib.sha256(
|
||||
f"{code}{int(time.time() / 1000)}000{token}".encode()
|
||||
).hexdigest()
|
||||
|
||||
|
||||
async def get_file_url(code: str):
|
||||
@@ -95,6 +97,44 @@ async def max_save_times_desc(max_save_seconds: int):
|
||||
return desc_zh, desc_en
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""
|
||||
使用 SHA256 + salt 哈希密码
|
||||
返回格式: sha256$<salt>$<hash>
|
||||
"""
|
||||
salt = os.urandom(16).hex()
|
||||
password_hash = hashlib.sha256(f"{salt}{password}".encode()).hexdigest()
|
||||
return f"sha256${salt}${password_hash}"
|
||||
|
||||
|
||||
def verify_password(password: str, hashed: str) -> bool:
|
||||
"""
|
||||
验证密码是否匹配
|
||||
支持新格式 (sha256$salt$hash) 和旧格式 (明文)
|
||||
"""
|
||||
if not hashed:
|
||||
return False
|
||||
|
||||
# 新格式: sha256$salt$hash
|
||||
if hashed.startswith("sha256$"):
|
||||
parts = hashed.split("$")
|
||||
if len(parts) != 3:
|
||||
return False
|
||||
_, salt, stored_hash = parts
|
||||
password_hash = hashlib.sha256(f"{salt}{password}".encode()).hexdigest()
|
||||
return password_hash == stored_hash
|
||||
|
||||
# 旧格式: 明文比较 (兼容迁移前的数据)
|
||||
return password == hashed
|
||||
|
||||
|
||||
def is_password_hashed(password: str) -> bool:
|
||||
"""
|
||||
检查密码是否已经是哈希格式
|
||||
"""
|
||||
return password.startswith("sha256$") and len(password.split("$")) == 3
|
||||
|
||||
|
||||
async def sanitize_filename(filename: str) -> str:
|
||||
"""
|
||||
安全处理文件名:
|
||||
@@ -105,15 +145,15 @@ async def sanitize_filename(filename: str) -> str:
|
||||
filename = os.path.basename(filename)
|
||||
illegal_chars = r'[\\/*?:"<>|\x00-\x1F]' # 包含控制字符
|
||||
# 替换非法字符为下划线
|
||||
cleaned = re.sub(illegal_chars, '_', filename)
|
||||
cleaned = re.sub(illegal_chars, "_", filename)
|
||||
# 处理空格(可选替换为_)
|
||||
cleaned = cleaned.replace(' ', '_')
|
||||
cleaned = cleaned.replace(" ", "_")
|
||||
# 处理连续下划线
|
||||
cleaned = re.sub(r'_+', '_', cleaned)
|
||||
cleaned = re.sub(r"_+", "_", cleaned)
|
||||
# 处理首尾特殊字符
|
||||
cleaned = cleaned.strip('._')
|
||||
cleaned = cleaned.strip("._")
|
||||
# 处理空文件名情况
|
||||
if not cleaned:
|
||||
cleaned = 'unnamed_file'
|
||||
cleaned = "unnamed_file"
|
||||
# 长度限制(按需调整)
|
||||
return cleaned[:255]
|
||||
@@ -0,0 +1 @@
|
||||
APP_VERSION = "2.0.0-dev"
|
||||
+74
-5
@@ -15,6 +15,29 @@
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
### 获取 Token
|
||||
|
||||
当管理面板关闭了游客上传(`openUpload=0`)时,需要先登录获取 token:
|
||||
|
||||
```bash
|
||||
curl -X POST "http://localhost:12345/admin/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"password": "FileCodeBox2023"}'
|
||||
```
|
||||
|
||||
**响应示例:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"token": "xxx.xxx.xxx",
|
||||
"token_type": "Bearer"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 分享接口
|
||||
|
||||
### 分享文本
|
||||
@@ -29,7 +52,22 @@ Authorization: Bearer <token>
|
||||
|-------|------|------|--------|------|
|
||||
| text | string | 是 | - | 要分享的文本内容 |
|
||||
| expire_value | integer | 否 | 1 | 过期时间值 |
|
||||
| expire_style | string | 否 | "day" | 过期时间单位(day/hour/minute) |
|
||||
| expire_style | string | 否 | "day" | 过期时间单位(day/hour/minute/count/forever) |
|
||||
|
||||
**cURL 示例:**
|
||||
|
||||
```bash
|
||||
# 游客上传(openUpload=1 时)
|
||||
curl -X POST "http://localhost:12345/share/text/" \
|
||||
-F "text=这是要分享的文本内容" \
|
||||
-F "expire_value=1" \
|
||||
-F "expire_style=day"
|
||||
|
||||
# 需要认证时(openUpload=0 时)
|
||||
curl -X POST "http://localhost:12345/share/text/" \
|
||||
-H "Authorization: Bearer xxx.xxx.xxx" \
|
||||
-F "text=这是要分享的文本内容"
|
||||
```
|
||||
|
||||
**响应示例:**
|
||||
|
||||
@@ -38,8 +76,7 @@ Authorization: Bearer <token>
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "text.txt"
|
||||
"code": "abc123"
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -56,7 +93,32 @@ Authorization: Bearer <token>
|
||||
|-------|------|------|--------|------|
|
||||
| file | file | 是 | - | 要上传的文件 |
|
||||
| expire_value | integer | 否 | 1 | 过期时间值 |
|
||||
| expire_style | string | 否 | "day" | 过期时间单位(day/hour/minute) |
|
||||
| expire_style | string | 否 | "day" | 过期时间单位(day/hour/minute/count/forever) |
|
||||
|
||||
**cURL 示例:**
|
||||
|
||||
```bash
|
||||
# 上传文件(默认1天有效期)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.txt"
|
||||
|
||||
# 上传文件(7天有效期)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.txt" \
|
||||
-F "expire_value=7" \
|
||||
-F "expire_style=day"
|
||||
|
||||
# 上传文件(可下载10次)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.txt" \
|
||||
-F "expire_value=10" \
|
||||
-F "expire_style=count"
|
||||
|
||||
# 需要认证时
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-H "Authorization: Bearer xxx.xxx.xxx" \
|
||||
-F "file=@/path/to/file.txt"
|
||||
```
|
||||
|
||||
**响应示例:**
|
||||
|
||||
@@ -75,7 +137,7 @@ Authorization: Bearer <token>
|
||||
|
||||
**GET** `/share/select/`
|
||||
|
||||
通过分享码获取文件信息。
|
||||
通过分享码获取文件信息(直接下载文件)。
|
||||
|
||||
**请求参数:**
|
||||
|
||||
@@ -83,6 +145,13 @@ Authorization: Bearer <token>
|
||||
|-------|------|------|------|
|
||||
| code | string | 是 | 文件分享码 |
|
||||
|
||||
**cURL 示例:**
|
||||
|
||||
```bash
|
||||
# 通过取件码下载文件
|
||||
curl -L "http://localhost:12345/share/select/?code=abc123" -o downloaded_file
|
||||
```
|
||||
|
||||
**响应示例:**
|
||||
|
||||
```json
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
# 本轮开发交付报告
|
||||
|
||||
生成日期:2026-06-06
|
||||
|
||||
本文档记录 `feature/development-plan` 分支本轮开发完成情况、验证结果和后续处理建议。
|
||||
|
||||
## 分支状态
|
||||
|
||||
当前工作区包含两个独立 Git 仓库,均已切换到本轮开发分支:
|
||||
|
||||
- 后端仓库:`FileCodeBox`
|
||||
- 前端仓库:`FileCodeBoxFronted`
|
||||
- 当前分支:`feature/development-plan`
|
||||
|
||||
本轮变更尚未提交。
|
||||
|
||||
## 开发目标
|
||||
|
||||
本轮目标是根据 `docs/development-plan.md` 完成下一阶段的优先开发项:
|
||||
|
||||
1. 补齐取件文件预览链路。
|
||||
2. 建立前端最小测试体系。
|
||||
3. 加固后端预签名上传回归测试。
|
||||
4. 区分前端检查脚本和自动修复脚本。
|
||||
5. 拆分管理文件模块的部分纯函数、状态逻辑和批量操作 UI。
|
||||
|
||||
## 完成范围
|
||||
|
||||
### P0:取件文件预览链路
|
||||
|
||||
已在取件页完成文件预览接线:
|
||||
|
||||
- `RetrievewFileView.vue` 绑定文件详情弹窗的 `preview-file` 事件。
|
||||
- 取件页渲染并控制 `MediaPreviewModal`。
|
||||
- 取件详情中的可预览文件现在可以打开媒体预览弹窗。
|
||||
|
||||
### P0:前端最小测试体系
|
||||
|
||||
已建立 Vitest 测试基础:
|
||||
|
||||
- 新增 `vitest.config.ts`。
|
||||
- 新增 `package.json` 的 `test` 脚本。
|
||||
- 引入 `vitest`、`@vue/test-utils`、`jsdom` 等测试依赖。
|
||||
- 更新 `pnpm-lock.yaml`。
|
||||
|
||||
首批测试覆盖:
|
||||
|
||||
- 文件类型规则。
|
||||
- 下载动作解析。
|
||||
- 内容预览处理。
|
||||
- 发送记录工具逻辑。
|
||||
- 预签名上传相关流程。
|
||||
- 上传策略分支。
|
||||
- 管理文件摘要、视图预设和批量选择逻辑。
|
||||
|
||||
### P1:后端上传回归加固
|
||||
|
||||
已补充后端预签名上传流程测试:
|
||||
|
||||
- 新增 `tests/conftest.py`,固定测试导入路径。
|
||||
- 新增 `tests/test_presign_upload_flow.py`。
|
||||
|
||||
覆盖场景包括:
|
||||
|
||||
- `init` 直传模式。
|
||||
- `init` 代理上传模式。
|
||||
- `confirm` 成功创建文件记录。
|
||||
- `confirm` 拒绝缺失的直传文件。
|
||||
- `proxy` 上传大小不一致校验。
|
||||
- `cancel` 取消并清理已上传对象。
|
||||
- 过期上传会话自动删除并拒绝继续操作。
|
||||
|
||||
### P1:质量脚本调整
|
||||
|
||||
已区分自动修复和只检查命令:
|
||||
|
||||
```json
|
||||
{
|
||||
"lint": "eslint . --fix",
|
||||
"lint:check": "eslint ."
|
||||
}
|
||||
```
|
||||
|
||||
同时,架构检查脚本已忽略测试文件,避免测试代码影响前端分层规则检查。
|
||||
|
||||
### P2:管理文件模块拆分
|
||||
|
||||
已完成第一轮低风险拆分:
|
||||
|
||||
- 新增 `admin-file-view-preset.ts`,承载管理文件视图预设规则。
|
||||
- 新增 `admin-file-summary.ts`,承载管理文件摘要计算逻辑。
|
||||
- 新增 `useAdminFileSelection.ts`,承载批量选择状态逻辑。
|
||||
- 新增 `AdminBatchActionBar.vue`,承载管理页批量操作栏 UI。
|
||||
- `FileManageView.vue` 已接入新的批量操作栏组件。
|
||||
|
||||
本轮拆分优先处理纯函数和单一职责状态逻辑,避免一次性重构整个管理页。
|
||||
|
||||
## 关键设计决策
|
||||
|
||||
1. 优先补用户可见断点,再推进模块拆分。
|
||||
2. 先给工具函数和 composable 补测试,再扩大重构范围。
|
||||
3. `lint` 保留自动修复语义,新增 `lint:check` 用于 CI 和人工验证。
|
||||
4. 管理文件页拆分采用渐进方式,每次只抽离职责清晰、影响边界可控的模块。
|
||||
5. 后端上传测试使用替身对象和临时状态,避免依赖真实网络、真实 S3 或污染运行数据目录。
|
||||
|
||||
## 验证记录
|
||||
|
||||
本轮已完成以下验证:
|
||||
|
||||
```bash
|
||||
cd FileCodeBoxFronted
|
||||
pnpm test
|
||||
pnpm check:architecture
|
||||
pnpm type-check
|
||||
pnpm lint:check
|
||||
pnpm build
|
||||
|
||||
cd ../FileCodeBox
|
||||
pytest
|
||||
|
||||
git diff --check
|
||||
```
|
||||
|
||||
验证结果:
|
||||
|
||||
- 前端 `pnpm test`:9 files / 27 tests passed。
|
||||
- 前端 `pnpm check:architecture`:通过。
|
||||
- 前端 `pnpm type-check`:通过。
|
||||
- 前端 `pnpm lint:check`:通过。
|
||||
- 前端 `pnpm build`:通过。
|
||||
- 后端 `pytest`:21 passed,仅存在 Tortoise ORM deprecation warnings。
|
||||
- 前后端 `git diff --check`:通过。
|
||||
|
||||
## 当前未提交文件
|
||||
|
||||
### 后端仓库
|
||||
|
||||
新增文件:
|
||||
|
||||
- `docs/development-plan.md`
|
||||
- `docs/development-delivery-report.md`
|
||||
- `tests/conftest.py`
|
||||
- `tests/test_presign_upload_flow.py`
|
||||
|
||||
### 前端仓库
|
||||
|
||||
修改文件:
|
||||
|
||||
- `package.json`
|
||||
- `pnpm-lock.yaml`
|
||||
- `scripts/check-architecture.mjs`
|
||||
- `src/composables/useAdminFiles.ts`
|
||||
- `src/composables/useSendFlow.ts`
|
||||
- `src/utils/download-action.ts`
|
||||
- `src/views/RetrievewFileView.vue`
|
||||
- `src/views/manage/FileManageView.vue`
|
||||
- `tsconfig.app.json`
|
||||
|
||||
新增文件:
|
||||
|
||||
- `src/components/common/AdminBatchActionBar.vue`
|
||||
- `src/composables/useAdminFileSelection.ts`
|
||||
- `src/composables/useAdminFileSelection.test.ts`
|
||||
- `src/composables/usePresignedUpload.test.ts`
|
||||
- `src/services/upload-strategy.test.ts`
|
||||
- `src/utils/admin-file-summary.ts`
|
||||
- `src/utils/admin-file-summary.test.ts`
|
||||
- `src/utils/admin-file-view-preset.ts`
|
||||
- `src/utils/admin-file-view-preset.test.ts`
|
||||
- `src/utils/content-preview.test.ts`
|
||||
- `src/utils/download-action.test.ts`
|
||||
- `src/utils/file-type.ts`
|
||||
- `src/utils/file-type.test.ts`
|
||||
- `src/utils/send-record.test.ts`
|
||||
- `vitest.config.ts`
|
||||
|
||||
## 后续建议
|
||||
|
||||
1. 提交前再次执行前后端验证命令,确保工作区未被其他改动影响。
|
||||
2. 分别在两个仓库创建提交,避免跨仓库状态混淆。
|
||||
3. 下一轮继续拆分管理文件模块时,优先处理筛选栏、详情侧栏和元数据编辑逻辑。
|
||||
4. 后端可继续补充 `allowed_file_types`、S3 `file_exists` 降级、主题资源路径穿越保护等测试。
|
||||
|
||||
## 推荐提交信息
|
||||
|
||||
后端仓库:
|
||||
|
||||
```bash
|
||||
git commit -m "test: add presign upload flow coverage"
|
||||
```
|
||||
|
||||
前端仓库:
|
||||
|
||||
```bash
|
||||
git commit -m "feat: add retrieve preview and frontend tests"
|
||||
```
|
||||
@@ -0,0 +1,211 @@
|
||||
# 下一步开发计划
|
||||
|
||||
本文档记录 FileCodeBox 下一阶段开发优先级、并行拆分方式、验收标准和质量门禁。
|
||||
|
||||
## 背景
|
||||
|
||||
当前工作区包含两个独立仓库:
|
||||
|
||||
- `FileCodeBox`:FastAPI 后端,包含接口、存储、管理后台 API、文档和后端测试。
|
||||
- `FileCodeBoxFronted`:Vue 3 + Vite 前端,包含公开取件/发件页和管理后台界面。
|
||||
|
||||
近期提交主要集中在 S3 存储、取件码归一化、文件类型限制、主题资源加载、前端管理页和上传下载体验。
|
||||
|
||||
下一阶段应优先处理用户可见断点和自动化回归保护,再推进大模块拆分。
|
||||
|
||||
## 优先级总览
|
||||
|
||||
### P0:补齐取件文件预览链路
|
||||
|
||||
目标:打通前端已存在但尚未完整接线的文件预览能力。
|
||||
|
||||
涉及模块:
|
||||
|
||||
- `RetrievewFileView.vue`
|
||||
- `FileDetailModal.vue`
|
||||
- `MediaPreviewModal.vue`
|
||||
- `useRetrieveFlow.ts`
|
||||
|
||||
主要工作:
|
||||
|
||||
1. 在取件详情弹窗中绑定文件预览事件。
|
||||
2. 在取件页渲染媒体预览弹窗。
|
||||
3. 确认图片、视频、音频、PDF 等可预览文件能正常打开。
|
||||
4. 保持关闭、下载、错误提示等状态行为一致。
|
||||
|
||||
验收标准:
|
||||
|
||||
```bash
|
||||
pnpm check:architecture
|
||||
pnpm build
|
||||
```
|
||||
|
||||
手工验收:
|
||||
|
||||
1. 上传非文本文件并获取取件码。
|
||||
2. 取件后打开详情弹窗。
|
||||
3. 点击预览,确认弹窗可打开。
|
||||
4. 确认关闭和下载动作正常。
|
||||
|
||||
### P0:建立最小前端测试体系
|
||||
|
||||
目标:为核心前端流程建立可持续的自动化回归保护。
|
||||
|
||||
现状:
|
||||
|
||||
- 前端暂无测试目录。
|
||||
- `package.json` 中暂无 `test` 脚本。
|
||||
- 最近改动涉及上传、下载、Markdown 预览、配置表单等高风险路径。
|
||||
|
||||
建议引入:
|
||||
|
||||
```bash
|
||||
vitest
|
||||
@vue/test-utils
|
||||
jsdom
|
||||
```
|
||||
|
||||
首批测试范围:
|
||||
|
||||
- 文件类型限制规则。
|
||||
- 过期时间限制校验。
|
||||
- Markdown 渲染和 HTML 清洗。
|
||||
- 下载动作解析。
|
||||
- 预签名上传与分片上传提交分支。
|
||||
|
||||
验收标准:
|
||||
|
||||
```bash
|
||||
pnpm test
|
||||
```
|
||||
|
||||
要求:
|
||||
|
||||
- 测试能在 60 秒内完成。
|
||||
- 核心工具函数至少具备首批单元测试。
|
||||
- 测试脚本不修改源码文件。
|
||||
|
||||
### P1:后端上传与存储回归加固
|
||||
|
||||
目标:把近期修复沉淀为后端测试,降低存储和上传链路回归风险。
|
||||
|
||||
涉及模块:
|
||||
|
||||
- `apps/base/views.py`
|
||||
- `core/storage.py`
|
||||
- `main.py`
|
||||
- `tests/`
|
||||
|
||||
优先测试场景:
|
||||
|
||||
1. 预签名上传 `init` / `confirm` / `cancel`。
|
||||
2. 代理上传文件大小校验。
|
||||
3. `allowed_file_types` 的扩展名、MIME、通配规则。
|
||||
4. S3 `file_exists` 的 `head_object` 失败降级逻辑。
|
||||
5. 主题资源路径穿越保护。
|
||||
|
||||
验收标准:
|
||||
|
||||
```bash
|
||||
pytest
|
||||
```
|
||||
|
||||
要求:
|
||||
|
||||
- 测试使用临时目录和替身对象,避免污染 `data/`。
|
||||
- 外部存储相关测试不依赖真实网络或真实 S3。
|
||||
- 异常路径和边界值必须覆盖。
|
||||
|
||||
### P1:调整质量脚本
|
||||
|
||||
目标:区分“检查”和“自动修复”,避免 CI 或验证命令改写源码。
|
||||
|
||||
当前问题:
|
||||
|
||||
```json
|
||||
"lint": "eslint . --fix"
|
||||
```
|
||||
|
||||
建议调整:
|
||||
|
||||
```json
|
||||
{
|
||||
"lint": "eslint . --fix",
|
||||
"lint:check": "eslint ."
|
||||
}
|
||||
```
|
||||
|
||||
推荐前端验证顺序:
|
||||
|
||||
```bash
|
||||
pnpm check:architecture
|
||||
pnpm type-check
|
||||
pnpm lint:check
|
||||
pnpm test
|
||||
pnpm build
|
||||
```
|
||||
|
||||
### P2:拆分管理文件模块
|
||||
|
||||
目标:降低管理文件页面和业务 composable 的维护复杂度。
|
||||
|
||||
现状:
|
||||
|
||||
- `FileManageView.vue` 体量较大。
|
||||
- `useAdminFiles.ts` 同时承载列表、筛选、视图预设、批量操作、详情、元数据、下载和预览等职责。
|
||||
|
||||
拆分顺序:
|
||||
|
||||
1. 抽纯函数:筛选参数归一化、视图预设归一化、摘要计算、详情视图模型转换。
|
||||
2. 抽 composable:批量操作、详情弹窗、元数据编辑、视图预设。
|
||||
3. 抽 UI 子组件:批量工具栏、筛选栏、详情侧栏、预设选择器。
|
||||
|
||||
约束:
|
||||
|
||||
- 每次只拆一块。
|
||||
- 拆分前后行为保持一致。
|
||||
- 先给纯函数补测试,再推进 UI 拆分。
|
||||
|
||||
## 并行开发安排
|
||||
|
||||
第一轮可并行拆分为四个互不冲突的任务:
|
||||
|
||||
1. 前端 A:接线取件文件预览。
|
||||
2. 前端 B:搭建 Vitest 与首批工具函数测试。
|
||||
3. 后端 C:补充上传和存储回归测试。
|
||||
4. 工程 D:新增 `lint:check` 并整理验证命令。
|
||||
|
||||
合并前统一验证:
|
||||
|
||||
```bash
|
||||
cd FileCodeBoxFronted
|
||||
pnpm check:architecture
|
||||
pnpm type-check
|
||||
pnpm lint:check
|
||||
pnpm test
|
||||
pnpm build
|
||||
|
||||
cd ../FileCodeBox
|
||||
pytest
|
||||
```
|
||||
|
||||
## 质量门禁
|
||||
|
||||
每个开发任务完成时必须记录:
|
||||
|
||||
- 改动范围。
|
||||
- 关键设计决策。
|
||||
- 执行过的验证命令。
|
||||
- 未覆盖风险和后续事项。
|
||||
|
||||
涉及上传、删除、存储、认证、配置等功能时,必须补充异常路径测试。
|
||||
|
||||
## 推荐执行顺序
|
||||
|
||||
1. 先完成 P0 的取件预览接线。
|
||||
2. 同步建立前端最小测试体系。
|
||||
3. 补齐后端上传和存储回归测试。
|
||||
4. 调整前端质量脚本。
|
||||
5. 等测试保护到位后,再拆分管理文件模块。
|
||||
|
||||
结论:下一阶段以“取件预览接线 + 测试体系建设”为主线,先修用户可见断点,再提升长期维护质量。
|
||||
+74
-5
@@ -15,6 +15,29 @@ Some APIs require `Authorization` header for authentication:
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
### Get Token
|
||||
|
||||
When guest upload is disabled in admin panel (`openUpload=0`), you need to login first:
|
||||
|
||||
```bash
|
||||
curl -X POST "http://localhost:12345/admin/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"password": "FileCodeBox2023"}'
|
||||
```
|
||||
|
||||
**Response Example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"token": "xxx.xxx.xxx",
|
||||
"token_type": "Bearer"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Share API
|
||||
|
||||
### Share Text
|
||||
@@ -29,7 +52,22 @@ Share text content and get a share code.
|
||||
|-----------|------|----------|---------|-------------|
|
||||
| text | string | Yes | - | Text content to share |
|
||||
| expire_value | integer | No | 1 | Expiration time value |
|
||||
| expire_style | string | No | "day" | Expiration time unit(day/hour/minute) |
|
||||
| expire_style | string | No | "day" | Expiration time unit(day/hour/minute/count/forever) |
|
||||
|
||||
**cURL Example:**
|
||||
|
||||
```bash
|
||||
# Guest upload (when openUpload=1)
|
||||
curl -X POST "http://localhost:12345/share/text/" \
|
||||
-F "text=This is the text content to share" \
|
||||
-F "expire_value=1" \
|
||||
-F "expire_style=day"
|
||||
|
||||
# When authentication required (openUpload=0)
|
||||
curl -X POST "http://localhost:12345/share/text/" \
|
||||
-H "Authorization: Bearer xxx.xxx.xxx" \
|
||||
-F "text=This is the text content to share"
|
||||
```
|
||||
|
||||
**Response Example:**
|
||||
|
||||
@@ -38,8 +76,7 @@ Share text content and get a share code.
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "text.txt"
|
||||
"code": "abc123"
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -56,7 +93,32 @@ Upload and share a file, get a share code.
|
||||
|-----------|------|----------|---------|-------------|
|
||||
| file | file | Yes | - | File to upload |
|
||||
| expire_value | integer | No | 1 | Expiration time value |
|
||||
| expire_style | string | No | "day" | Expiration time unit(day/hour/minute) |
|
||||
| expire_style | string | No | "day" | Expiration time unit(day/hour/minute/count/forever) |
|
||||
|
||||
**cURL Example:**
|
||||
|
||||
```bash
|
||||
# Upload file (default 1 day expiration)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.txt"
|
||||
|
||||
# Upload file (7 days expiration)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.txt" \
|
||||
-F "expire_value=7" \
|
||||
-F "expire_style=day"
|
||||
|
||||
# Upload file (10 downloads limit)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.txt" \
|
||||
-F "expire_value=10" \
|
||||
-F "expire_style=count"
|
||||
|
||||
# When authentication required
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-H "Authorization: Bearer xxx.xxx.xxx" \
|
||||
-F "file=@/path/to/file.txt"
|
||||
```
|
||||
|
||||
**Response Example:**
|
||||
|
||||
@@ -75,7 +137,7 @@ Upload and share a file, get a share code.
|
||||
|
||||
**GET** `/share/select/`
|
||||
|
||||
Get file information by share code.
|
||||
Get file information by share code (direct file download).
|
||||
|
||||
**Parameters:**
|
||||
|
||||
@@ -83,6 +145,13 @@ Get file information by share code.
|
||||
|-----------|------|----------|-------------|
|
||||
| code | string | Yes | File share code |
|
||||
|
||||
**cURL Example:**
|
||||
|
||||
```bash
|
||||
# Download file by extraction code
|
||||
curl -L "http://localhost:12345/share/select/?code=abc123" -o downloaded_file
|
||||
```
|
||||
|
||||
**Response Example:**
|
||||
|
||||
```json
|
||||
|
||||
@@ -118,12 +118,53 @@ Content-Type: `multipart/form-data`
|
||||
**cURL example:**
|
||||
|
||||
```bash
|
||||
# Upload file (default 1 day expiration)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.pdf"
|
||||
|
||||
# Upload file with 7 days expiration
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.pdf" \
|
||||
-F "expire_value=7" \
|
||||
-F "expire_style=day"
|
||||
|
||||
# Upload file with 10 downloads limit
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.pdf" \
|
||||
-F "expire_value=10" \
|
||||
-F "expire_style=count"
|
||||
|
||||
# Share text
|
||||
curl -X POST "http://localhost:12345/share/text/" \
|
||||
-F "text=This is the text content to share"
|
||||
|
||||
# Download file by extraction code
|
||||
curl -L "http://localhost:12345/share/select/?code=YOUR_CODE" -o downloaded_file
|
||||
```
|
||||
|
||||
::: tip When Authentication Required
|
||||
If guest upload is disabled in admin panel (`openUpload=0`), you need to login first:
|
||||
|
||||
```bash
|
||||
# 1. Login to get token
|
||||
curl -X POST "http://localhost:12345/admin/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"password": "FileCodeBox2023"}'
|
||||
|
||||
# Returns: {"code":200,"msg":"success","detail":{"token":"xxx.xxx.xxx","token_type":"Bearer"}}
|
||||
|
||||
# 2. Upload file with token
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-H "Authorization: Bearer xxx.xxx.xxx" \
|
||||
-F "file=@/path/to/file.pdf"
|
||||
|
||||
# 3. Share text with token
|
||||
curl -X POST "http://localhost:12345/share/text/" \
|
||||
-H "Authorization: Bearer xxx.xxx.xxx" \
|
||||
-F "text=This is the text content to share"
|
||||
```
|
||||
:::
|
||||
|
||||
|
||||
## Chunked Upload API
|
||||
|
||||
|
||||
@@ -17,8 +17,61 @@ FileCodeBox 是一个简单高效的文件分享工具,支持文件临时中
|
||||
|
||||
### Docker 部署(推荐)
|
||||
|
||||
#### 快速启动
|
||||
|
||||
```bash
|
||||
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:beta
|
||||
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:latest
|
||||
```
|
||||
|
||||
#### Docker Compose
|
||||
|
||||
```yml
|
||||
version: "3"
|
||||
services:
|
||||
file-code-box:
|
||||
image: lanol/filecodebox:latest
|
||||
volumes:
|
||||
- fcb-data:/app/data:rw
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "12345:12345"
|
||||
environment:
|
||||
- WORKERS=4
|
||||
- LOG_LEVEL=info
|
||||
volumes:
|
||||
fcb-data:
|
||||
external: false
|
||||
```
|
||||
|
||||
#### 环境变量
|
||||
|
||||
| 变量 | 默认值 | 说明 |
|
||||
|------|--------|------|
|
||||
| `HOST` | `::` | 监听地址,支持 IPv4/IPv6 双栈 |
|
||||
| `PORT` | `12345` | 服务端口 |
|
||||
| `WORKERS` | `4` | 工作进程数,建议设置为 CPU 核心数 |
|
||||
| `LOG_LEVEL` | `info` | 日志级别:debug/info/warning/error |
|
||||
|
||||
#### 自定义配置示例
|
||||
|
||||
```bash
|
||||
docker run -d --restart=always \
|
||||
-p 12345:12345 \
|
||||
-v /opt/FileCodeBox/:/app/data \
|
||||
-e WORKERS=8 \
|
||||
-e LOG_LEVEL=warning \
|
||||
--name filecodebox \
|
||||
lanol/filecodebox:latest
|
||||
```
|
||||
|
||||
### 配置反向代理(Nginx)
|
||||
|
||||
```nginx
|
||||
location / {
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_pass http://localhost:12345;
|
||||
}
|
||||
```
|
||||
|
||||
### 手动部署
|
||||
|
||||
File renamed without changes.
File renamed without changes.
@@ -118,12 +118,53 @@ Content-Type: `multipart/form-data`
|
||||
**cURL 示例:**
|
||||
|
||||
```bash
|
||||
# 上传文件(默认1天有效期)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.pdf"
|
||||
|
||||
# 上传文件并指定有效期(7天)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.pdf" \
|
||||
-F "expire_value=7" \
|
||||
-F "expire_style=day"
|
||||
|
||||
# 上传文件并指定有效期(可下载10次)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.pdf" \
|
||||
-F "expire_value=10" \
|
||||
-F "expire_style=count"
|
||||
|
||||
# 分享文本
|
||||
curl -X POST "http://localhost:12345/share/text/" \
|
||||
-F "text=这是要分享的文本内容"
|
||||
|
||||
# 通过取件码下载文件
|
||||
curl -L "http://localhost:12345/share/select/?code=取件码" -o downloaded_file
|
||||
```
|
||||
|
||||
::: tip 需要认证时
|
||||
如果管理面板关闭了游客上传(`openUpload=0`),需要先登录获取 token:
|
||||
|
||||
```bash
|
||||
# 1. 登录获取 token
|
||||
curl -X POST "http://localhost:12345/admin/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"password": "FileCodeBox2023"}'
|
||||
|
||||
# 返回: {"code":200,"msg":"success","detail":{"token":"xxx.xxx.xxx","token_type":"Bearer"}}
|
||||
|
||||
# 2. 使用 token 上传文件
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-H "Authorization: Bearer xxx.xxx.xxx" \
|
||||
-F "file=@/path/to/file.pdf"
|
||||
|
||||
# 3. 使用 token 分享文本
|
||||
curl -X POST "http://localhost:12345/share/text/" \
|
||||
-H "Authorization: Bearer xxx.xxx.xxx" \
|
||||
-F "text=这是要分享的文本内容"
|
||||
```
|
||||
:::
|
||||
|
||||
## 分片上传 API
|
||||
|
||||
对于大文件,FileCodeBox 支持分片上传功能。分片上传将大文件分割成多个小块分别上传,支持断点续传。
|
||||
|
||||
@@ -0,0 +1,843 @@
|
||||
# 功能与用户体验提升规划
|
||||
|
||||
生成日期:2026-06-06
|
||||
|
||||
本文档承接 `development-plan.md` 和 `development-delivery-report.md`,用于规划下一轮“功能增强 + 用户体验提升”开发。重点不是重做界面,而是让发送、取件和管理流程更清楚、更可恢复、更适合反复使用。
|
||||
|
||||
## 当前基线
|
||||
|
||||
当前工作区包含两个独立仓库:
|
||||
|
||||
- `FileCodeBox`:FastAPI 后端,提供分享、取件、分片上传、预签名上传、管理后台、配置和本地文件管理接口。
|
||||
- `FileCodeBoxFronted`:Vue 3 + Vite 前端,提供公开取件页、发件页、登录页、管理仪表盘、文件管理和系统设置。
|
||||
|
||||
本轮已完成的基础能力:
|
||||
|
||||
- 取件文件预览链路已接通。
|
||||
- 前端 Vitest 测试体系已建立。
|
||||
- 后端预签名上传流程已有回归测试。
|
||||
- 管理文件页已抽出部分纯函数、批量选择逻辑和批量操作栏。
|
||||
|
||||
下一轮应把重点从“能用”推进到“好用、稳定、可解释”。
|
||||
|
||||
## 体验目标
|
||||
|
||||
1. 发送流程要让用户明确知道当前文件是否可发、发到哪一步、失败后如何继续。
|
||||
2. 取件流程要避免误消耗取件次数,先展示文件摘要,再由用户确认下载或预览。
|
||||
3. 管理后台要提高高频操作效率,减少大页面内工具堆叠和重复确认成本。
|
||||
4. 所有危险操作要有清晰影响范围,避免误删、误批量修改和不可逆操作。
|
||||
5. 错误提示要从“发生错误”升级为“原因 + 可执行下一步”。
|
||||
|
||||
## 规划依据
|
||||
|
||||
本轮规划基于前后端只读审阅结果:
|
||||
|
||||
- 前端主流程已完整,但取件前确认、上传取消/重试、发送成功结果区和后台强确认仍不足。
|
||||
- 后端接口能力较全,但取件扣次数、下载票据、预签名直传确认、错误响应和审计追踪仍需要加固。
|
||||
- 下一轮应优先处理“安全边界 + 关键路径体验”,再扩展管理效率和长期产品能力。
|
||||
|
||||
## P0:取件扣次数与下载票据一致性
|
||||
|
||||
目标:确保取件次数只在真实授权动作中消耗,并且旧下载地址不能绕过过期或次数限制。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- `/share/select/` 当前会调用 `update_file_usage()`,取件前缺少确认时容易误消耗次数。
|
||||
- `/share/download` 使用 `check=False` 获取文件记录,已生成的下载地址存在被继续复用的窗口。
|
||||
- 下载票据由 `get_select_token()` 生成,缺少明确的短期过期语义和服务端状态绑定。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 将“查看元数据”和“确认取件授权”严格分离。
|
||||
2. 为确认取件生成短期下载票据:
|
||||
- 票据绑定取件码。
|
||||
- 票据包含过期时间。
|
||||
- 票据校验时重新检查文件是否过期、次数是否耗尽。
|
||||
3. 并发场景下保证 `expired_count=1` 只能成功一次。
|
||||
4. 下载接口拒绝已过期、次数耗尽或票据失效的请求。
|
||||
5. 响应中明确返回剩余次数和下一步动作。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `apps/base/views.py`
|
||||
- `core/utils.py`
|
||||
- `apps/base/models.py`
|
||||
- `tests/`
|
||||
|
||||
### 数据模型影响
|
||||
|
||||
第一阶段可先使用签名票据,不强制新增表。
|
||||
|
||||
如果要做更完整审计,后续新增:
|
||||
|
||||
- `DownloadTicket`
|
||||
- `FileAccessLog`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 元数据查询不消耗下载次数。
|
||||
2. 确认取件后才消耗次数并返回下载票据。
|
||||
3. `expired_count=1` 并发取件时只能成功一次。
|
||||
4. 旧下载地址在文件过期或次数耗尽后不可继续下载。
|
||||
5. 后端测试覆盖票据过期、次数耗尽和并发边界。
|
||||
|
||||
## P0:公开取件体验升级
|
||||
|
||||
目标:取件码输入后先确认内容,再执行会消耗次数的取件动作。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- `RetrievewFileView.vue` 在取件码长度达到 5 位时直接调用 `handleSubmit()`。
|
||||
- `handleSubmit()` 调用 `/share/select/`,会执行 `update_file_usage()`,可能消耗下载次数。
|
||||
- `useRetrieveFlow.ts` 已有 `inspectCode()` 和 `inspectedFile`,但页面当前未形成完整的“预检查确认”体验。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 输入 5 位取件码后调用 `inspectCode()`,请求 `/share/metadata/`。
|
||||
2. 页面展示文件摘要卡片:
|
||||
- 文件名或文本类型。
|
||||
- 文件大小。
|
||||
- 过期时间。
|
||||
- 剩余下载次数。
|
||||
- 是否可预览。
|
||||
3. 用户点击“取件”后再调用 `handleSubmit()`。
|
||||
4. 如果文件已过期或次数耗尽,直接展示不可取原因,不再进入下载动作。
|
||||
5. 查询参数 `?code=xxxxx` 进入页面时,也走同样的预检查流程。
|
||||
6. 与服务端下载票据机制配合,确认取件后再获得可下载地址。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `RetrievewFileView.vue`
|
||||
- `RetrieveForm.vue`
|
||||
- `useRetrieveFlow.ts`
|
||||
- `FileDetailModal.vue`
|
||||
- `download-action.ts`
|
||||
- `src/i18n/locales/zh-CN.ts`
|
||||
- `src/i18n/locales/en-US.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
```bash
|
||||
cd FileCodeBoxFronted
|
||||
pnpm test
|
||||
pnpm check:architecture
|
||||
pnpm type-check
|
||||
pnpm lint:check
|
||||
pnpm build
|
||||
```
|
||||
|
||||
手工验收:
|
||||
|
||||
1. 输入有效取件码,只展示摘要,不立即消耗下载次数。
|
||||
2. 点击确认取件后,才新增取件记录并打开详情或预览。
|
||||
3. 输入过期取件码时展示明确原因。
|
||||
4. 从 `?code=xxxxx` 访问时能自动展示摘要。
|
||||
|
||||
## P0:发送结果页增强
|
||||
|
||||
目标:发送成功后让用户更快完成复制、分享、复查和再次发送。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- `useSendFlow.ts` 发送成功后会自动复制链接并打开记录详情。
|
||||
- 用户能看到结果,但结果区域更像历史详情,不像一次明确的“发送完成”状态。
|
||||
- 多文件、文本、单文件的结果反馈可以更聚焦。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 新增发送成功结果面板,替代只依赖记录详情弹窗:
|
||||
- 取件码大号展示。
|
||||
- 一键复制取件码。
|
||||
- 一键复制链接。
|
||||
- 二维码展示入口。
|
||||
- 重新发送按钮。
|
||||
2. 明确自动复制结果:
|
||||
- 复制成功展示“链接已复制”。
|
||||
- 复制失败展示“请手动复制”。
|
||||
3. 多文件上传成功后展示文件数量和压缩包/批量记录说明。
|
||||
4. 文本发送成功后提供“预览文本”和“复制原文”。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `SendFileView.vue`
|
||||
- `SentRecordDetailModal.vue`
|
||||
- `SentRecordList.vue`
|
||||
- `useSendFlow.ts`
|
||||
- `sent-record-actions.ts`
|
||||
- `send-record.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 单文件、文本、多文件发送成功后都有明确完成态。
|
||||
2. 复制取件码、复制链接、二维码入口可用。
|
||||
3. 发送成功后再次选择文件或文本不会残留上一次进度。
|
||||
4. 自动复制失败时有人工复制路径。
|
||||
|
||||
## P0:上传失败恢复与取消
|
||||
|
||||
目标:上传过程可中断、可重试、可解释。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- 前端已有上传进度、速度和预签名上传封装。
|
||||
- 用户在上传中无法主动取消。
|
||||
- 失败后缺少保留文件并重试的明确路径。
|
||||
- 预签名上传会话存在后端取消接口,但前端体验还可以更完整。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 上传中展示取消按钮。
|
||||
2. 取消时调用对应取消逻辑:
|
||||
- 预签名上传:`DELETE /presign/upload/{upload_id}`。
|
||||
- 分片上传:`DELETE /chunk/upload/{upload_id}`。
|
||||
3. 失败后保留已选择文件,提供“重试”按钮。
|
||||
4. 错误提示按类型分层:
|
||||
- 文件过大。
|
||||
- 文件类型不允许。
|
||||
- 网络中断。
|
||||
- 服务端拒绝。
|
||||
- 上传会话过期。
|
||||
5. 上传过程中离开页面时提示用户确认。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `FileUploadArea.vue`
|
||||
- `SendFileView.vue`
|
||||
- `useSendFlow.ts`
|
||||
- `useSendSubmit.ts`
|
||||
- `usePresignedUpload.ts`
|
||||
- `upload-strategy.ts`
|
||||
- `FileService`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 上传中可以取消,后端临时会话或分片状态被清理。
|
||||
2. 网络失败后可以直接重试,不需要重新选择文件。
|
||||
3. 取消上传后进度归零,按钮状态恢复。
|
||||
4. 页面跳转或关闭前有上传中提示。
|
||||
|
||||
## P0:预签名直传确认加固
|
||||
|
||||
目标:直传文件确认不只检查“对象存在”,还要确认大小、状态和失败原因。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- `presign_upload_confirm()` 当前主要依赖 `file_exists()`。
|
||||
- 直传对象大小不符、上传中断、对象异常时,服务端难以给出准确原因。
|
||||
- `PresignUploadSession` 当前缺少状态字段,前端只能通过接口错误推断上传阶段。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 存储接口增加对象元信息读取能力:
|
||||
- `stat_file(save_path)`
|
||||
- 返回是否存在、实际大小、更新时间和存储后端错误。
|
||||
2. `presign_upload_confirm()` 校验实际大小与声明大小一致。
|
||||
3. 上传会话状态响应补充原因:
|
||||
- `pending`
|
||||
- `uploading`
|
||||
- `uploaded`
|
||||
- `confirmed`
|
||||
- `expired`
|
||||
- `cancelled`
|
||||
- `failed`
|
||||
4. 失败时返回明确错误码和可展示文案。
|
||||
5. 取消或失败后清理可清理的临时对象。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `apps/base/views.py`
|
||||
- `apps/base/models.py`
|
||||
- `core/storage.py`
|
||||
- `src/composables/usePresignedUpload.ts`
|
||||
- `src/services/presign-upload.ts`
|
||||
- `tests/test_presign_upload_flow.py`
|
||||
|
||||
### 数据模型影响
|
||||
|
||||
建议为 `PresignUploadSession` 增加:
|
||||
|
||||
- `status`
|
||||
- `actual_size`
|
||||
- `error_message`
|
||||
|
||||
第一阶段如果不做迁移,也可以先在状态接口中计算并返回原因。
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 直传对象不存在时返回明确错误。
|
||||
2. 直传对象大小不符时拒绝创建分享记录。
|
||||
3. 会话过期、取消、确认成功均有稳定状态。
|
||||
4. 前端能展示初始化、上传中、确认中、失败、成功状态。
|
||||
5. 后端测试覆盖对象不存在、大小不符、取消清理和会话过期。
|
||||
|
||||
## P0:统一错误响应与请求追踪
|
||||
|
||||
目标:让前端能稳定识别业务错误、网络错误和权限错误,并展示可执行下一步。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- 部分接口抛出 `HTTPException`,部分接口返回 `APIResponse(code=404)`。
|
||||
- 客户端难以稳定区分上传超限、类型不允许、取件码不存在、会话过期等业务失败。
|
||||
- 缺少请求 ID,线上排查问题时难以关联日志和用户反馈。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 统一错误响应结构:
|
||||
- `code`
|
||||
- `message`
|
||||
- `error_code`
|
||||
- `request_id`
|
||||
- `detail`
|
||||
2. 增加全局异常处理中间件或异常处理器。
|
||||
3. 上传、取件、登录、配置保存等关键接口返回稳定错误码。
|
||||
4. 前端错误提示按 `error_code` 映射文案和建议动作。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `core/response.py`
|
||||
- `main.py`
|
||||
- `apps/base/views.py`
|
||||
- `apps/admin/views.py`
|
||||
- `src/utils/common.ts`
|
||||
- `src/services/client.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 上传超限、类型不允许、取件码不存在、登录失败返回统一结构。
|
||||
2. 前端提示包含原因和下一步动作。
|
||||
3. 日志中可按 `request_id` 定位请求。
|
||||
4. 后端测试覆盖全局错误响应格式。
|
||||
|
||||
## P0:管理高风险操作确认升级
|
||||
|
||||
目标:删除、批量修改、批量策略等不可逆操作必须让管理员清楚知道影响范围。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- `useAdminFiles.ts` 中多处仍使用 `window.confirm()`。
|
||||
- 批量删除、批量更新和批量策略操作缺少文件样例、影响数量和不可逆提示。
|
||||
- 视图预设删除、单文件删除和批量删除的确认体验不统一。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 替换 `window.confirm()` 为统一确认弹窗。
|
||||
2. 确认弹窗展示:
|
||||
- 操作类型。
|
||||
- 影响文件数量。
|
||||
- 文件样例。
|
||||
- 是否不可逆。
|
||||
- 操作执行后可能的结果。
|
||||
3. 操作执行中禁用确认按钮和相关批量按钮。
|
||||
4. 操作完成后展示成功数量、失败数量和失败原因。
|
||||
5. 删除本地浏览器记录时明确提示“不删除服务器文件”。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `FileManageView.vue`
|
||||
- `AdminBatchActionBar.vue`
|
||||
- `BaseModal.vue`
|
||||
- `useAdminFiles.ts`
|
||||
- `SentRecordList.vue`
|
||||
- `FileRecordList.vue`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 单文件删除、批量删除、批量更新、批量策略动作均使用统一确认弹窗。
|
||||
2. 批量删除前可看到选中数量和至少 3 个文件样例。
|
||||
3. 操作中按钮禁用,避免重复提交。
|
||||
4. 取消操作不会改变选中状态。
|
||||
5. 操作结果能区分全部成功、部分成功和全部失败。
|
||||
|
||||
## P0:配置保存强校验
|
||||
|
||||
目标:把配置错误拦在保存阶段,而不是等用户上传或下载时才暴露。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- 配置存储在 `KeyValue` 中,更新入口需要更强字段校验。
|
||||
- 存储后端切换、上传限制、过期策略、文件类型规则等配置一旦错误,会直接影响公开流程。
|
||||
- 前端设置页有未保存状态,但配置变更风险没有形成统一摘要。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 后端保存配置前做字段级校验:
|
||||
- `file_storage` 必须是支持的存储后端。
|
||||
- 上传大小、限流和保存时长不能为负数。
|
||||
- `expireStyle` 必须属于允许枚举。
|
||||
- S3、WebDAV、OpenDAL、OneDrive 的必填项按存储类型校验。
|
||||
2. 前端保存前展示变更摘要:
|
||||
- 已变更字段。
|
||||
- 是否影响现有上传。
|
||||
- 是否需要管理员复查。
|
||||
3. 高风险配置显示明确提示:
|
||||
- 公开上传。
|
||||
- 允许全部文件类型。
|
||||
- 永久保存。
|
||||
- 默认管理员口令。
|
||||
4. 设置页离开、刷新、切换后台页面时提示保存或放弃。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
前端:
|
||||
|
||||
- `SystemSettingsView.vue`
|
||||
- `useSystemConfig.ts`
|
||||
- `router/index.ts`
|
||||
- `config-storage.ts`
|
||||
|
||||
后端:
|
||||
|
||||
- `apps/admin/services.py`
|
||||
- `apps/admin/views.py`
|
||||
- `core/settings.py`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 非法配置会被后端拒绝,并返回具体字段原因。
|
||||
2. 前端保存前展示变更摘要。
|
||||
3. 未保存配置离开页面会触发确认。
|
||||
4. 默认管理员口令、公开上传、允许所有文件类型会有高风险提示。
|
||||
|
||||
## P1:管理文件页信息架构优化
|
||||
|
||||
目标:把管理页从“功能堆在一个表格上”调整为更适合高频扫描和批量处理的工作台。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- `FileManageView.vue` 仍承担较多职责。
|
||||
- 筛选、预设、批量操作、表格、详情、编辑弹窗集中在同一个页面。
|
||||
- 单行操作按钮较多,在窄屏或大量数据时容易拥挤。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 拆分筛选区组件:
|
||||
- `AdminFileFilterBar.vue`
|
||||
- 负责关键词、状态、健康度、类型、排序和预设入口。
|
||||
2. 拆分详情侧栏:
|
||||
- `AdminFileDetailDrawer.vue`
|
||||
- 替代过重弹窗,保留复制、下载、编辑、预览入口。
|
||||
3. 表格行操作收敛为主操作 + 更多菜单:
|
||||
- 详情作为主操作。
|
||||
- 下载、编辑、删除进入更多菜单。
|
||||
4. 增加快捷筛选:
|
||||
- 即将过期。
|
||||
- 从未取件。
|
||||
- 已耗尽次数。
|
||||
- 存储异常。
|
||||
5. 表格空状态提供可执行动作:
|
||||
- 清空筛选。
|
||||
- 创建视图预设。
|
||||
- 返回全部文件。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `FileManageView.vue`
|
||||
- `AdminBatchActionBar.vue`
|
||||
- `useAdminFiles.ts`
|
||||
- `admin-file-summary.ts`
|
||||
- `admin-file-view-preset.ts`
|
||||
- `src/i18n/locales/zh-CN.ts`
|
||||
- `src/i18n/locales/en-US.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 筛选区、批量操作区、表格区职责清晰。
|
||||
2. 窄屏下表格行操作不溢出。
|
||||
3. 快捷筛选能正确改变请求参数并刷新数据。
|
||||
4. 已有批量选择、批量删除、批量策略动作不回归。
|
||||
|
||||
## P1:管理后台操作反馈增强
|
||||
|
||||
目标:让管理员明确知道批量操作影响了哪些文件、哪些成功、哪些失败。
|
||||
|
||||
### 现状能力
|
||||
|
||||
- 后端已有批量删除、批量更新、策略动作和活动记录。
|
||||
- 前端已有批量操作栏。
|
||||
- 后端 `FileService` 已具备管理活动记录能力。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 批量操作执行前展示影响摘要:
|
||||
- 选中文件数。
|
||||
- 即将修改的字段。
|
||||
- 不可逆风险。
|
||||
2. 批量操作完成后展示结果摘要:
|
||||
- 成功数量。
|
||||
- 失败数量。
|
||||
- 跳过原因。
|
||||
3. 活动记录支持从文件详情进入:
|
||||
- 展示该文件最近操作。
|
||||
- 展示操作者、动作和时间。
|
||||
4. 危险操作确认文案包含文件名或数量,而不是只问“是否删除”。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
前端:
|
||||
|
||||
- `AdminBatchActionBar.vue`
|
||||
- `FileManageView.vue`
|
||||
- `useAdminFiles.ts`
|
||||
- `DashboardView.vue`
|
||||
|
||||
后端:
|
||||
|
||||
- `apps/admin/views.py`
|
||||
- `apps/admin/services.py`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 批量删除和批量更新前有明确影响摘要。
|
||||
2. 批量操作结果能展示部分失败,不只显示统一成功或失败。
|
||||
3. 操作记录能按文件或关键词过滤。
|
||||
4. 后端测试覆盖活动记录过滤和批量操作结果结构。
|
||||
|
||||
## P1:下载与预览体验统一
|
||||
|
||||
目标:用户在公开页和管理页面对“文本、图片、视频、音频、PDF、未知文件”时,操作路径一致。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 抽统一文件能力判断工具:
|
||||
- 是否可文本预览。
|
||||
- 是否可媒体预览。
|
||||
- 是否建议下载。
|
||||
- 是否可复制内容。
|
||||
2. 统一公开取件和管理页的预览入口文案。
|
||||
3. PDF、图片、音视频预览失败时提供下载兜底。
|
||||
4. 文本预览支持复制、下载为 `.txt`、查看原始内容。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `MediaPreviewModal.vue`
|
||||
- `ContentPreviewModal.vue`
|
||||
- `FileDetailModal.vue`
|
||||
- `FileManageView.vue`
|
||||
- `content-preview.ts`
|
||||
- `download-action.ts`
|
||||
- `file-type.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 同一文件类型在公开页和管理页展示一致。
|
||||
2. 预览失败时始终能回退到下载。
|
||||
3. 文本内容复制和导出行为一致。
|
||||
4. 文件类型判断工具具备单元测试。
|
||||
|
||||
## P1:上传前文件清单与限制提示
|
||||
|
||||
目标:多文件或大文件上传前,让用户提前知道会发生什么,减少上传中途失败。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- 多文件上传会先打包为 zip,但用户只看到“正在打包文件”。
|
||||
- 文件清单、总大小、超限原因和打包后行为没有在提交前集中展示。
|
||||
- `FileUploadArea.vue` 已支持更多上传状态,但页面当前只传入 `uploading` 和 `idle`。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 多文件选择后展示文件清单:
|
||||
- 文件数量。
|
||||
- 总大小。
|
||||
- 最大文件。
|
||||
- 不允许类型或超限文件。
|
||||
2. 明确提示多文件将被打包为 zip。
|
||||
3. 打包阶段展示独立状态,避免和上传阶段混淆。
|
||||
4. 提交前对所有文件逐项校验,并返回具体失败原因。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `FileUploadArea.vue`
|
||||
- `SendFileView.vue`
|
||||
- `useSendFlow.ts`
|
||||
- `useSendSubmit.ts`
|
||||
- `ExpirationSelector.vue`
|
||||
- `file-type.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 多文件选择后可看到数量、总大小和打包提示。
|
||||
2. 超限文件能逐项展示原因。
|
||||
3. 打包中、上传中、确认中三个阶段状态不同。
|
||||
4. 文件清单在取消或重新选择后正确重置。
|
||||
|
||||
## P1:服务端状态字段与可操作能力
|
||||
|
||||
目标:为前端展示更清楚的状态和主操作提供稳定数据,减少前端重复推断。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 分享记录增加明确状态字段:
|
||||
- `active`
|
||||
- `expired`
|
||||
- `download_limit_exhausted`
|
||||
- `storage_missing`
|
||||
2. 公开元数据接口补充可操作能力:
|
||||
- `canPreview`
|
||||
- `canDownload`
|
||||
- `canCopy`
|
||||
- `primaryAction`
|
||||
3. 管理列表支持快捷筛选参数:
|
||||
- `expiringSoon`
|
||||
- `neverUsed`
|
||||
- `exhausted`
|
||||
- `storageIssue`
|
||||
4. 后端响应保留必要的 snake_case 和 camelCase 兼容。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `apps/base/views.py`
|
||||
- `apps/base/schemas.py`
|
||||
- `apps/admin/views.py`
|
||||
- `apps/admin/services.py`
|
||||
- `src/types/file.ts`
|
||||
- `src/services/file.ts`
|
||||
- `tests/`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 元数据接口能直接告诉前端主操作是什么。
|
||||
2. 管理文件列表能按快捷状态筛选。
|
||||
3. 状态字段有后端测试覆盖。
|
||||
4. 前端不再依赖 `filename === 'Text'` 这类脆弱判断。
|
||||
|
||||
## P1:审计日志表化
|
||||
|
||||
目标:让上传、下载、删除、配置变更等关键动作可追踪、可过滤、可定位。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- 管理活动当前主要保存在 `KeyValue` 中,容量和查询能力有限。
|
||||
- 活动记录缺少 IP、User-Agent、请求 ID、结果状态等排障信息。
|
||||
- 批量操作失败时,缺少逐项结果追踪。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 新增审计日志模型,记录:
|
||||
- 动作类型。
|
||||
- 操作者。
|
||||
- IP。
|
||||
- User-Agent。
|
||||
- 请求 ID。
|
||||
- 目标类型和目标 ID。
|
||||
- 执行结果。
|
||||
- 元数据。
|
||||
- 创建时间。
|
||||
2. `/admin/activities` 支持分页和筛选:
|
||||
- 动作。
|
||||
- 对象类型。
|
||||
- 关键词。
|
||||
- 时间范围。
|
||||
- 结果状态。
|
||||
3. 文件详情中展示该文件最近操作。
|
||||
4. 配置变更记录变更摘要,不记录密钥明文。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `apps/admin/services.py`
|
||||
- `apps/admin/views.py`
|
||||
- `apps/base/models.py`
|
||||
- `tests/`
|
||||
|
||||
### 数据模型影响
|
||||
|
||||
建议新增:
|
||||
|
||||
- `AuditLog`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 删除、批量更新、配置变更会写入审计日志。
|
||||
2. 审计列表支持分页和筛选。
|
||||
3. 日志不泄露 Token、密码、密钥。
|
||||
4. 后端测试覆盖写入、过滤和敏感字段脱敏。
|
||||
|
||||
## P1:管理查询性能优化
|
||||
|
||||
目标:让后台在千级、万级文件记录下仍能稳定分页、筛选和统计。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- 文件列表和仪表盘部分统计、过滤、排序在 Python 内存中完成。
|
||||
- 数据量增加后,后台打开、筛选和统计会逐渐变慢。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 文件列表筛选和排序尽量下推到数据库。
|
||||
2. 仪表盘统计改为聚合查询。
|
||||
3. 为高频字段补索引:
|
||||
- `created_at`
|
||||
- `expired_at`
|
||||
- `suffix`
|
||||
- `is_chunked`
|
||||
- `used_count`
|
||||
- `file_hash`
|
||||
4. 大量记录下避免一次性加载所有文件再过滤。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `apps/admin/views.py`
|
||||
- `apps/admin/services.py`
|
||||
- `apps/base/models.py`
|
||||
- `tests/`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 千级和万级记录下分页耗时稳定。
|
||||
2. 仪表盘统计结果与现有结果一致。
|
||||
3. 筛选、排序、分页返回结构保持兼容。
|
||||
4. 后端测试覆盖主要过滤组合。
|
||||
|
||||
## P2:取件与发送记录体验增强
|
||||
|
||||
目标:让浏览器本地记录更适合长期使用。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 记录支持搜索:
|
||||
- 取件码。
|
||||
- 文件名。
|
||||
- 类型。
|
||||
2. 记录支持分组:
|
||||
- 今天。
|
||||
- 最近 7 天。
|
||||
- 更早。
|
||||
3. 记录详情展示来源:
|
||||
- 手动输入。
|
||||
- 链接打开。
|
||||
- 历史记录。
|
||||
4. 支持清空记录前二次确认,并说明只清理本地记录,不删除服务器文件。
|
||||
5. 支持导出发送记录为 JSON。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `SideDrawer.vue`
|
||||
- `SentRecordList.vue`
|
||||
- `FileRecordList.vue`
|
||||
- `fileData` store
|
||||
- `send-record.ts`
|
||||
- `download-action.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 本地记录超过 20 条时仍易于查找。
|
||||
2. 清空记录不会误导用户以为删除了服务器文件。
|
||||
3. 导出的记录可重新导入或至少可人工读取。
|
||||
|
||||
## P2:系统设置体验增强
|
||||
|
||||
目标:在强校验之外,给管理员提供配置自检、连接测试和修复建议。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 设置页增加配置自检:
|
||||
- 当前存储后端是否可用。
|
||||
- 上传大小限制是否合理。
|
||||
- 允许文件类型是否能被正确解析。
|
||||
- 管理地址是否公开。
|
||||
2. 存储配置增加测试连接按钮:
|
||||
- S3。
|
||||
- WebDAV。
|
||||
- OpenDAL。
|
||||
- OneDrive。
|
||||
3. 自检结果返回修复建议:
|
||||
- 缺少必填项。
|
||||
- 存储连接失败。
|
||||
- 上传限制过宽。
|
||||
- 管理地址暴露。
|
||||
4. 支持导出当前非敏感配置快照,便于排障。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
前端:
|
||||
|
||||
- `SystemSettingsView.vue`
|
||||
- `config-storage.ts`
|
||||
- `config` types
|
||||
|
||||
后端:
|
||||
|
||||
- `apps/admin/views.py`
|
||||
- `apps/admin/services.py`
|
||||
- `core/storage.py`
|
||||
- `core/settings.py`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 保存设置前能看到变更摘要。
|
||||
2. 错误配置不会只在上传时暴露。
|
||||
3. 存储连接失败能返回可理解原因。
|
||||
4. 配置自检接口有后端测试覆盖。
|
||||
|
||||
## 并行开发拆分
|
||||
|
||||
第一轮建议拆成四个互不冲突任务,先处理会影响安全边界和关键体验的事项:
|
||||
|
||||
1. 后端 A:取件扣次数与下载票据一致性。
|
||||
2. 前端 B:取件前确认卡片和查询参数自动预检查。
|
||||
3. 后端 C:统一错误响应和请求追踪。
|
||||
4. 前端 D:发送成功结果面板和复制反馈。
|
||||
|
||||
第二轮在第一轮稳定后推进:
|
||||
|
||||
1. 后端 E:预签名直传确认加固和上传会话状态原因。
|
||||
2. 前端 F:上传取消、失败重试和离页确认。
|
||||
3. 前端 G:管理高风险操作确认弹窗。
|
||||
4. 后端 H:配置保存强校验。
|
||||
|
||||
第三轮推进管理效率和长期维护:
|
||||
|
||||
1. 前端 I:管理文件筛选区、详情侧栏和行操作收敛。
|
||||
2. 后端 J:服务端状态字段、快捷筛选和管理查询性能优化。
|
||||
3. 后端 K:审计日志表化。
|
||||
4. 前端 L:记录搜索、分组、导出和国际化补齐。
|
||||
|
||||
## 推荐执行顺序
|
||||
|
||||
1. 先做 P0 取件票据和扣次数一致性,修正服务端安全边界。
|
||||
2. 接着做 P0 取件前确认卡片,避免用户误消耗次数。
|
||||
3. 同步推进统一错误响应,让前端能展示稳定错误文案。
|
||||
4. 再做发送成功结果区,提升公开用户最常见路径。
|
||||
5. 然后做上传取消/重试和预签名直传确认加固。
|
||||
6. 管理页按强确认、筛选拆分、详情侧栏的顺序渐进推进。
|
||||
|
||||
## 质量门禁
|
||||
|
||||
前端每轮合并前执行:
|
||||
|
||||
```bash
|
||||
cd FileCodeBoxFronted
|
||||
pnpm test
|
||||
pnpm check:architecture
|
||||
pnpm type-check
|
||||
pnpm lint:check
|
||||
pnpm build
|
||||
```
|
||||
|
||||
后端每轮合并前执行:
|
||||
|
||||
```bash
|
||||
cd FileCodeBox
|
||||
pytest
|
||||
```
|
||||
|
||||
涉及上传、删除、配置、权限和批量操作时,必须补充异常路径测试。
|
||||
|
||||
## 风险与注意事项
|
||||
|
||||
1. 取件预检查不能调用会消耗次数的接口。
|
||||
2. 上传取消需要确认不同上传策略的清理路径一致。
|
||||
3. 管理页组件拆分必须保持现有批量操作行为不变。
|
||||
4. 配置自检不能泄露密钥、Token 或内部路径。
|
||||
5. 本地记录增强只影响浏览器存储,不应让用户误解为服务端记录。
|
||||
|
||||
## 下一步建议
|
||||
|
||||
下一轮优先实现:
|
||||
|
||||
1. `P0:取件扣次数与下载票据一致性`
|
||||
2. `P0:公开取件体验升级`
|
||||
3. `P0:统一错误响应与请求追踪`
|
||||
4. `P0:发送结果页增强`
|
||||
|
||||
这四项组合能同时修正服务端边界和公开用户体验,为后续上传恢复、管理工作台优化打基础。
|
||||
@@ -6,10 +6,9 @@ import asyncio
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.responses import FileResponse, HTMLResponse
|
||||
from tortoise import Tortoise
|
||||
from tortoise.contrib.fastapi import register_tortoise
|
||||
|
||||
@@ -17,11 +16,55 @@ from apps.admin.views import admin_api
|
||||
from apps.base.models import KeyValue
|
||||
from apps.base.utils import ip_limit
|
||||
from apps.base.views import share_api, chunk_api, presign_api
|
||||
from core.database import init_db
|
||||
from core.config import ensure_settings_row, refresh_settings
|
||||
from core.database import db_startup_lock, get_db_config, init_db
|
||||
from core.logger import logger
|
||||
from core.response import APIResponse
|
||||
from core.settings import data_root, settings, BASE_DIR, DEFAULT_CONFIG
|
||||
from core.settings import settings, BASE_DIR, DEFAULT_CONFIG
|
||||
from core.tasks import delete_expire_files, clean_incomplete_uploads
|
||||
from core.utils import hash_password, is_password_hashed
|
||||
from core.version import APP_VERSION
|
||||
|
||||
|
||||
def build_public_config() -> dict:
|
||||
return {
|
||||
"name": settings.name,
|
||||
"description": settings.description,
|
||||
"explain": settings.page_explain,
|
||||
"uploadSize": settings.uploadSize,
|
||||
"allowedFileTypes": settings.allowed_file_types,
|
||||
"expireStyle": settings.expireStyle,
|
||||
"enableChunk": settings.enableChunk,
|
||||
"openUpload": settings.openUpload,
|
||||
"notify_title": settings.notify_title,
|
||||
"notify_content": settings.notify_content,
|
||||
"show_admin_address": settings.showAdminAddr,
|
||||
"max_save_seconds": settings.max_save_seconds,
|
||||
}
|
||||
|
||||
|
||||
def build_public_meta() -> dict:
|
||||
return {
|
||||
"version": APP_VERSION,
|
||||
"api": {
|
||||
"legacyConfig": "/",
|
||||
"publicConfig": "/api/v1/config",
|
||||
"health": "/health",
|
||||
},
|
||||
"features": {
|
||||
"chunkUpload": bool(settings.enableChunk),
|
||||
"guestUpload": bool(settings.openUpload),
|
||||
"adminAddressVisible": bool(settings.showAdminAddr),
|
||||
"expirationModes": settings.expireStyle,
|
||||
},
|
||||
"limits": {
|
||||
"uploadSize": settings.uploadSize,
|
||||
"allowedFileTypes": settings.allowed_file_types,
|
||||
"maxSaveSeconds": settings.max_save_seconds,
|
||||
"uploadWindowMinutes": settings.uploadMinute,
|
||||
"uploadWindowCount": settings.uploadCount,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -30,14 +73,9 @@ async def lifespan(app: FastAPI):
|
||||
# 初始化数据库
|
||||
await init_db()
|
||||
|
||||
# 加载配置
|
||||
await load_config()
|
||||
app.mount(
|
||||
"/assets",
|
||||
StaticFiles(directory=f"./{settings.themesSelect}/assets"),
|
||||
name="assets",
|
||||
)
|
||||
|
||||
# 加载配置(多进程下串行化启动写操作)
|
||||
async with db_startup_lock():
|
||||
await load_config()
|
||||
# 启动后台任务
|
||||
task = asyncio.create_task(delete_expire_files())
|
||||
chunk_cleanup_task = asyncio.create_task(clean_incomplete_uploads())
|
||||
@@ -56,22 +94,38 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
|
||||
async def load_config():
|
||||
user_config, _ = await KeyValue.get_or_create(
|
||||
key="settings", defaults={"value": DEFAULT_CONFIG}
|
||||
)
|
||||
await ensure_settings_row()
|
||||
await KeyValue.update_or_create(
|
||||
key="sys_start", defaults={"value": int(time.time() * 1000)}
|
||||
)
|
||||
settings.user_config = user_config.value
|
||||
# 更新 ip_limit 配置
|
||||
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=["*"],
|
||||
@@ -83,15 +137,7 @@ app.add_middleware(
|
||||
# 使用 register_tortoise 来添加异常处理器
|
||||
register_tortoise(
|
||||
app,
|
||||
config={
|
||||
"connections": {"default": f"sqlite://{data_root}/filecodebox.db"},
|
||||
"apps": {
|
||||
"models": {
|
||||
"models": ["apps.base.models"],
|
||||
"default_connection": "default",
|
||||
},
|
||||
},
|
||||
},
|
||||
config=get_db_config(),
|
||||
generate_schemas=False,
|
||||
add_exception_handlers=True,
|
||||
)
|
||||
@@ -99,22 +145,50 @@ register_tortoise(
|
||||
app.include_router(share_api)
|
||||
app.include_router(chunk_api)
|
||||
app.include_router(presign_api)
|
||||
app.include_router(presign_api, prefix="/api")
|
||||
app.include_router(admin_api)
|
||||
|
||||
|
||||
def resolve_theme_root():
|
||||
themes_root = (BASE_DIR / "themes").resolve()
|
||||
theme_root = (BASE_DIR / str(settings.themesSelect)).resolve()
|
||||
try:
|
||||
theme_root.relative_to(themes_root)
|
||||
except ValueError:
|
||||
theme_root = (BASE_DIR / DEFAULT_CONFIG["themesSelect"]).resolve()
|
||||
if not theme_root.exists():
|
||||
theme_root = (BASE_DIR / DEFAULT_CONFIG["themesSelect"]).resolve()
|
||||
return theme_root
|
||||
|
||||
|
||||
def resolve_theme_file(*parts: str):
|
||||
theme_root = resolve_theme_root()
|
||||
file_path = theme_root.joinpath(*parts).resolve()
|
||||
# 防止通过 /assets/../ 读取主题目录外的文件。
|
||||
try:
|
||||
file_path.relative_to(theme_root)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=404, detail="资源不存在")
|
||||
if not file_path.is_file():
|
||||
raise HTTPException(status_code=404, detail="资源不存在")
|
||||
return file_path
|
||||
|
||||
|
||||
@app.get("/assets/{asset_path:path}", include_in_schema=False)
|
||||
async def theme_asset(asset_path: str):
|
||||
return FileResponse(resolve_theme_file("assets", asset_path))
|
||||
|
||||
|
||||
@app.exception_handler(404)
|
||||
@app.get("/")
|
||||
async def index(request=None, exc=None):
|
||||
return HTMLResponse(
|
||||
content=open(
|
||||
BASE_DIR / f"{settings.themesSelect}/index.html", "r", encoding="utf-8"
|
||||
)
|
||||
.read()
|
||||
content=resolve_theme_file("index.html")
|
||||
.read_text(encoding="utf-8")
|
||||
.replace("{{title}}", str(settings.name))
|
||||
.replace("{{description}}", str(settings.description))
|
||||
.replace("{{keywords}}", str(settings.keywords))
|
||||
.replace("{{opacity}}", str(settings.opacity))
|
||||
.replace('"/assets/', '"assets/')
|
||||
.replace("{{background}}", str(settings.background)),
|
||||
media_type="text/html",
|
||||
headers={"Cache-Control": "no-cache"},
|
||||
@@ -128,19 +202,27 @@ async def robots():
|
||||
|
||||
@app.post("/")
|
||||
async def get_config():
|
||||
return APIResponse(detail=build_public_config())
|
||||
|
||||
|
||||
@app.get("/api/v1/config")
|
||||
async def get_public_config():
|
||||
return APIResponse(
|
||||
detail={
|
||||
"name": settings.name,
|
||||
"description": settings.description,
|
||||
"explain": settings.page_explain,
|
||||
"uploadSize": settings.uploadSize,
|
||||
"expireStyle": settings.expireStyle,
|
||||
"enableChunk": settings.enableChunk,
|
||||
"openUpload": settings.openUpload,
|
||||
"notify_title": settings.notify_title,
|
||||
"notify_content": settings.notify_content,
|
||||
"show_admin_address": settings.showAdminAddr,
|
||||
"max_save_seconds": settings.max_save_seconds,
|
||||
"config": build_public_config(),
|
||||
"meta": build_public_meta(),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
return APIResponse(
|
||||
detail={
|
||||
"status": "ok",
|
||||
"version": APP_VERSION,
|
||||
"storage": settings.file_storage,
|
||||
"theme": settings.themesSelect,
|
||||
}
|
||||
)
|
||||
|
||||
@@ -149,5 +231,9 @@ if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run(
|
||||
app="main:app", host=settings.serverHost, port=settings.serverPort, reload=False, workers=settings.serverWorkers
|
||||
app="main:app",
|
||||
host=settings.serverHost,
|
||||
port=settings.serverPort,
|
||||
reload=False,
|
||||
workers=settings.serverWorkers,
|
||||
)
|
||||
@@ -1,271 +1,339 @@
|
||||
# FileCodeBox - 文件快递柜
|
||||
|
||||
<div align="center">
|
||||
|
||||
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/static/banners/img_1.png" alt="FileCodeBox Logo">
|
||||
# FileCodeBox
|
||||
|
||||
<p><em>匿名口令分享文本和文件,像拿快递一样取文件</em></p>
|
||||
### 文件快递柜 - 匿名口令分享文本和文件
|
||||
|
||||
[](https://github.com/vastsa/FileCodeBox/stargazers)
|
||||
[](https://github.com/vastsa/FileCodeBox/network)
|
||||
[](https://github.com/vastsa/FileCodeBox/issues)
|
||||
[](https://github.com/vastsa/FileCodeBox/blob/master/LICENSE)
|
||||
[](https://qm.qq.com/q/PemPzhdEIM)
|
||||
[](https://www.python.org)
|
||||
[](https://fastapi.tiangolo.com)
|
||||
[](https://v3.vuejs.org)
|
||||
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/static/banners/img_1.png" alt="FileCodeBox Logo" width="400">
|
||||
|
||||
[English](./readme_en.md) | [部署教程](https://github.com/vastsa/FileCodeBox/wiki/部署教程) | [常见问题](https://github.com/vastsa/FileCodeBox/wiki/常见问题)
|
||||
像拿快递一样取文件,无需注册,输入口令即可获取
|
||||
|
||||
[](https://github.com/vastsa/FileCodeBox/stargazers)
|
||||
[](https://github.com/vastsa/FileCodeBox/network)
|
||||
[](https://github.com/vastsa/FileCodeBox/issues)
|
||||
[](https://github.com/vastsa/FileCodeBox/blob/master/LICENSE)
|
||||
[](https://hub.docker.com/r/lanol/filecodebox)
|
||||
|
||||
[](https://www.python.org)
|
||||
[](https://fastapi.tiangolo.com)
|
||||
[](https://vuejs.org)
|
||||
|
||||
[English](./readme_en.md) | [在线演示](https://share.lanol.cn) | [部署教程](https://github.com/vastsa/FileCodeBox/wiki/部署教程) | [常见问题](https://github.com/vastsa/FileCodeBox/wiki/常见问题) | [QQ群: 739673698](https://qm.qq.com/q/PemPzhdEIM)
|
||||
|
||||
```bash
|
||||
# 🚀 一键部署
|
||||
docker run -d -p 12345:12345 -v /opt/FileCodeBox:/app/data --name filecodebox lanol/filecodebox:latest
|
||||
# 国内镜像(如果上面拉取缓慢): docker.cnb.cool/aixk/filecodebox
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## 🚀 更新计划
|
||||
---
|
||||
|
||||
- [ ] 2025年皮肤
|
||||
- [ ] 文件收集功能
|
||||
## 目录
|
||||
|
||||
- [项目简介](#-项目简介)
|
||||
- [功能特性](#-功能特性)
|
||||
- [界面预览](#-界面预览)
|
||||
- [快速开始](#-快速开始)
|
||||
- [使用指南](#-使用指南)
|
||||
- [开发指南](#-开发指南)
|
||||
- [常见问题](#-常见问题)
|
||||
- [贡献指南](#-贡献指南)
|
||||
- [项目统计](#-项目统计)
|
||||
- [免责声明](#-免责声明)
|
||||
|
||||
---
|
||||
|
||||
## 📝 项目简介
|
||||
|
||||
FileCodeBox 是一个基于 FastAPI + Vue3 开发的轻量级文件分享工具。它允许用户通过简单的方式分享文本和文件,接收者只需要一个提取码就可以取得文件,就像从快递柜取出快递一样简单。
|
||||
FileCodeBox 是一个轻量级的文件分享工具,基于 **FastAPI + Vue3** 开发。用户可以通过简单的方式匿名分享文本和文件,接收者只需输入提取码即可获取内容——就像从快递柜取出快递一样简单。
|
||||
|
||||
## 🖼️ 功能预览
|
||||
### 应用场景
|
||||
|
||||
别问前端源码怎么是js了,麻烦仔细看下面的内容
|
||||
<div align="center">
|
||||
<h3>
|
||||
<a href="https://github.com/vastsa/FileCodeBoxFronted" target="_blank">
|
||||
<img src="https://img.shields.io/badge/Frontend-主题2024仓库-blue?style=for-the-badge&logo=github" alt="前端仓库2024">
|
||||
</a>
|
||||
<a href="https://github.com/vastsa/FileCodeBoxFronted2023" target="_blank">
|
||||
<img src="https://img.shields.io/badge/Frontend-主题2023仓库-blue?style=for-the-badge&logo=github" alt="前端仓库2023">
|
||||
</a>
|
||||
|
||||
<a href="https://share.lanol.cn" target="_blank">
|
||||
<img src="https://img.shields.io/badge/Demo-share.lanol.cn-green?style=for-the-badge&logo=internet-explorer" alt="演示站点">
|
||||
</a>
|
||||
</h3>
|
||||
</div>
|
||||
| 场景 | 描述 |
|
||||
|------|------|
|
||||
| 📁 **临时文件分享** | 快速分享文件,无需注册登录 |
|
||||
| 📝 **代码片段分享** | 分享代码、配置文件等文本内容 |
|
||||
| 🕶️ **匿名文件传输** | 保护隐私的点对点传输 |
|
||||
| 🔄 **跨设备传输** | 在不同设备间快速同步文件 |
|
||||
| 💾 **临时存储** | 支持自定义过期时间的云存储 |
|
||||
| 🌐 **私有服务** | 搭建企业或个人专属分享服务 |
|
||||
|
||||
### 新版界面
|
||||
---
|
||||
|
||||
## ✨ 功能特性
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="33%" valign="top">
|
||||
|
||||
### 🚀 轻量高效
|
||||
- FastAPI + SQLite3 后端
|
||||
- Vue3 + Element Plus 前端
|
||||
- Docker 一键部署
|
||||
- 资源占用极低
|
||||
|
||||
</td>
|
||||
<td width="33%" valign="top">
|
||||
|
||||
### 🔒 安全可靠
|
||||
- IP 上传频率限制
|
||||
- 提取码错误次数限制
|
||||
- 文件自动过期清理
|
||||
- 支持管理员认证
|
||||
|
||||
</td>
|
||||
<td width="33%" valign="top">
|
||||
|
||||
### 📤 便捷上传
|
||||
- 拖拽上传
|
||||
- 复制粘贴上传
|
||||
- 命令行 curl 上传
|
||||
- 批量文件上传
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="33%" valign="top">
|
||||
|
||||
### 🎫 灵活分享
|
||||
- 随机/自定义提取码
|
||||
- 可设置有效期(时间/次数)
|
||||
- 支持永久有效
|
||||
- 文本和文件统一管理
|
||||
|
||||
</td>
|
||||
<td width="33%" valign="top">
|
||||
|
||||
### 💾 多存储支持
|
||||
- 本地文件系统
|
||||
- S3 兼容存储
|
||||
- [OneDrive](./docs/guide/storage-onedrive.md)
|
||||
- [OpenDAL](./docs/guide/storage-opendal.md)
|
||||
|
||||
</td>
|
||||
<td width="33%" valign="top">
|
||||
|
||||
### 🌍 国际化
|
||||
- 简体中文
|
||||
- 繁体中文
|
||||
- English
|
||||
- 响应式设计 / 深色模式
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
---
|
||||
|
||||
## 🖼️ 界面预览
|
||||
|
||||
> 前端源码仓库:[2024主题](https://github.com/vastsa/FileCodeBoxFronted) | [2023主题](https://github.com/vastsa/FileCodeBoxFronted2023)
|
||||
|
||||
<details open>
|
||||
<summary><b>🎨 新版界面 (2024)</b></summary>
|
||||
<br>
|
||||
<div align="center">
|
||||
<table>
|
||||
<tr>
|
||||
<td><img src="./.github/images/img_7.png" alt="文件上传" title="文件上传界面"></td>
|
||||
<td><img src="./.github/images/img_8.png" alt="文本分享" title="文本分享界面"></td>
|
||||
<td><img src="./.github/images/img_7.png" alt="文件上传"></td>
|
||||
<td><img src="./.github/images/img_8.png" alt="文本分享"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="./.github/images/img_10.png" alt="文件管理" title="文件管理界面"></td>
|
||||
<td><img src="./.github/images/img_9.png" alt="系统设置" title="系统设置界面"></td>
|
||||
<td><img src="./.github/images/img_10.png" alt="文件管理"></td>
|
||||
<td><img src="./.github/images/img_9.png" alt="系统设置"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="./.github/images/img_11.png" alt="移动端" title="移动端界面"></td>
|
||||
<td><img src="./.github/images/img_12.png" alt="深色模式" title="深色模式界面"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="./.github/images/img_13.png" alt="国际化" title="国际化支持"></td>
|
||||
<td><img src="./.github/images/img_14.png" alt="响应式" title="响应式设计"></td>
|
||||
<td><img src="./.github/images/img_11.png" alt="移动端"></td>
|
||||
<td><img src="./.github/images/img_12.png" alt="深色模式"></td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
### 经典界面
|
||||
|
||||
<details>
|
||||
<summary><b>📦 经典界面 (2023)</b></summary>
|
||||
<br>
|
||||
<div align="center">
|
||||
<table>
|
||||
<tr>
|
||||
<td><img src="./.github/images/img.png" alt="首页" title="首页界面"></td>
|
||||
<td><img src="./.github/images/img_1.png" alt="上传" title="上传界面"></td>
|
||||
<td><img src="./.github/images/img.png" alt="首页"></td>
|
||||
<td><img src="./.github/images/img_1.png" alt="上传"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="./.github/images/img_2.png" alt="管理" title="管理界面"></td>
|
||||
<td><img src="./.github/images/img_3.png" alt="设置" title="设置界面"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="./.github/images/img_4.png" alt="分享" title="分享界面"></td>
|
||||
<td><img src="./.github/images/img_5.png" alt="下载" title="下载界面"></td>
|
||||
<td><img src="./.github/images/img_2.png" alt="管理"></td>
|
||||
<td><img src="./.github/images/img_3.png" alt="设置"></td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
## 🎯 应用场景
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>📁 临时文件分享</h4>
|
||||
快速分享单个文件,无需注册登录
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>📝 文本快速分享</h4>
|
||||
分享代码片段、文本内容等
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🕶️ 匿名文件传输</h4>
|
||||
保护隐私的文件传输方式
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>💾 临时文件存储</h4>
|
||||
支持设置过期时间的文件存储
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🔄 跨平台传输</h4>
|
||||
在不同设备间快速传输文件
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🌐 小型分享服务</h4>
|
||||
搭建私有的文件分享服务
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## ✨ 核心特性
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>🚀 轻量简洁</h4>
|
||||
基于 FastAPI + SQLite3 + Vue3 + ElementUI,部署简单,性能出色
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>📤 便捷上传</h4>
|
||||
支持复制粘贴、拖拽上传,操作简单直观
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>📦 多种类型</h4>
|
||||
支持文本和各类文件的分享
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>🔒 安全机制</h4>
|
||||
|
||||
- IP 限制上传次数
|
||||
- 错误次数限制
|
||||
- 文件过期机制
|
||||
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🎫 提取码分享</h4>
|
||||
随机提取码,可自定义次数及有效期
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🌍 多语言支持</h4>
|
||||
支持中文简体、繁体及英文
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>🎭 匿名分享</h4>
|
||||
无需注册登录,保护隐私
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🛠 管理面板</h4>
|
||||
文件管理和系统配置
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🐳 容器部署</h4>
|
||||
支持 Docker 一键部署
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>💾 存储扩展</h4>
|
||||
支持本地存储、S3 协议、OneDrive 等
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>📱 响应式设计</h4>
|
||||
支持移动端访问
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>💻 终端支持</h4>
|
||||
支持命令行下载
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
---
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### Docker 部署
|
||||
### Docker 部署(推荐)
|
||||
|
||||
#### Docker CLI
|
||||
**方式一:Docker CLI**
|
||||
|
||||
```bash
|
||||
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:beta
|
||||
# Docker Hub(推荐)
|
||||
docker run -d --restart always -p 12345:12345 -v /opt/FileCodeBox:/app/data --name filecodebox lanol/filecodebox:latest
|
||||
|
||||
# 国内镜像(如果 Docker Hub 拉取缓慢)
|
||||
docker run -d --restart always -p 12345:12345 -v /opt/FileCodeBox:/app/data --name filecodebox docker.cnb.cool/aixk/filecodebox
|
||||
```
|
||||
|
||||
#### Docker Compose
|
||||
**方式二:Docker Compose**
|
||||
|
||||
```yml
|
||||
version: "3"
|
||||
```yaml
|
||||
services:
|
||||
file-code-box:
|
||||
filecodebox:
|
||||
image: lanol/filecodebox:latest
|
||||
volumes:
|
||||
- fcb-data:/app/data:rw
|
||||
container_name: filecodebox
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "12345:12345"
|
||||
volumes:
|
||||
fcb-data:
|
||||
external: false
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
environment:
|
||||
- WORKERS=4
|
||||
- LOG_LEVEL=info
|
||||
```
|
||||
|
||||
### 配置反向代理(Nginx示例)
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
请注意,必须添加以下配置来确保正确处理客户端IP和代理请求:
|
||||
**环境变量说明**
|
||||
|
||||
| 变量 | 默认值 | 说明 |
|
||||
|------|--------|------|
|
||||
| `HOST` | `::` | 监听地址(支持 IPv4/IPv6 双栈) |
|
||||
| `PORT` | `12345` | 服务端口 |
|
||||
| `WORKERS` | `4` | 工作进程数(建议设为 CPU 核心数) |
|
||||
| `LOG_LEVEL` | `info` | 日志级别:`debug` / `info` / `warning` / `error` |
|
||||
|
||||
### 反向代理配置
|
||||
|
||||
使用 Nginx 时,请添加以下配置以正确获取客户端 IP:
|
||||
|
||||
```nginx
|
||||
location / {
|
||||
proxy_set_header X-Real-IP $remote_addr; # 设置真实客户端IP
|
||||
proxy_pass http://127.0.0.1:12345;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_pass http://localhost:12345;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 100m; # 根据需要调整上传大小限制
|
||||
}
|
||||
```
|
||||
|
||||
### 手动部署
|
||||
|
||||
1. 克隆项目
|
||||
|
||||
```bash
|
||||
# 1. 克隆项目
|
||||
git clone https://github.com/vastsa/FileCodeBox.git
|
||||
```
|
||||
|
||||
2. 安装依赖
|
||||
|
||||
```bash
|
||||
cd FileCodeBox
|
||||
|
||||
# 2. 安装依赖
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. 启动服务
|
||||
|
||||
```bash
|
||||
# 3. 启动服务
|
||||
python main.py
|
||||
```
|
||||
|
||||
## 📖 使用说明
|
||||
---
|
||||
|
||||
### 分享文件
|
||||
## 📖 使用指南
|
||||
|
||||
1. 打开网页,点击"分享文件"
|
||||
2. 选择或拖拽文件
|
||||
3. 设置过期时间和次数
|
||||
4. 获取提取码
|
||||
### 基础操作
|
||||
|
||||
### 获取文件
|
||||
| 操作 | 步骤 |
|
||||
|------|------|
|
||||
| **分享文件** | 打开网页 → 选择/拖拽文件 → 设置有效期 → 获取提取码 |
|
||||
| **获取文件** | 打开网页 → 输入提取码 → 下载文件或查看文本 |
|
||||
| **管理后台** | 访问 `/#/admin` → 输入密码 `FileCodeBox2023` |
|
||||
|
||||
1. 打开网页,输入提取码
|
||||
2. 点击获取
|
||||
3. 下载文件或查看文本
|
||||
### 命令行使用(curl)
|
||||
|
||||
### 管理面板
|
||||
<details>
|
||||
<summary><b>点击展开 curl 使用示例</b></summary>
|
||||
|
||||
1. 访问 `/#/admin`
|
||||
2. 输入管理员密码 `FileCodeBox2023`
|
||||
3. 管理文件和配置
|
||||
**上传文件**
|
||||
|
||||
```bash
|
||||
# 基础上传(默认 1 天有效期)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.txt"
|
||||
|
||||
# 指定 1 小时有效期
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.txt" \
|
||||
-F "expire_value=1" \
|
||||
-F "expire_style=hour"
|
||||
|
||||
# 指定下载 10 次后过期
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.txt" \
|
||||
-F "expire_value=10" \
|
||||
-F "expire_style=count"
|
||||
```
|
||||
|
||||
**分享文本**
|
||||
|
||||
```bash
|
||||
curl -X POST "http://localhost:12345/share/text/" \
|
||||
-F "text=要分享的文本内容"
|
||||
```
|
||||
|
||||
**下载文件**
|
||||
|
||||
```bash
|
||||
curl -L "http://localhost:12345/share/select/?code=提取码" -o filename
|
||||
```
|
||||
|
||||
**有效期参数**
|
||||
|
||||
| `expire_style` | 说明 |
|
||||
|----------------|------|
|
||||
| `day` | 天数 |
|
||||
| `hour` | 小时 |
|
||||
| `minute` | 分钟 |
|
||||
| `count` | 下载次数 |
|
||||
| `forever` | 永久有效 |
|
||||
|
||||
**返回示例**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abcd1234",
|
||||
"name": "file.txt"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**需要认证时**(管理员关闭游客上传后)
|
||||
|
||||
```bash
|
||||
# 1. 获取 token
|
||||
curl -X POST "http://localhost:12345/admin/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"password": "FileCodeBox2023"}'
|
||||
|
||||
# 2. 携带 token 上传
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-H "Authorization: Bearer <token>" \
|
||||
-F "file=@/path/to/file.txt"
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## 🛠 开发指南
|
||||
|
||||
@@ -273,71 +341,132 @@ python main.py
|
||||
|
||||
```
|
||||
FileCodeBox/
|
||||
├── apps/ # 应用代码
|
||||
│ ├── admin/ # 管理后台
|
||||
│ └── base/ # 基础功能
|
||||
├── core/ # 核心功能
|
||||
├── data/ # 数据目录
|
||||
└── fcb-fronted/ # 前端代码
|
||||
├── apps/ # 应用模块
|
||||
│ ├── admin/ # 管理后台
|
||||
│ └── base/ # 基础功能
|
||||
├── core/ # 核心模块
|
||||
├── data/ # 数据目录(运行时生成)
|
||||
├── docs/ # 文档
|
||||
└── main.py # 入口文件
|
||||
```
|
||||
|
||||
### 开发环境
|
||||
|
||||
- Python 3.8+
|
||||
- Node.js 14+
|
||||
- Vue 3
|
||||
- FastAPI
|
||||
|
||||
### 本地开发
|
||||
|
||||
1. 后端开发
|
||||
**后端**
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
python main.py
|
||||
```
|
||||
|
||||
2. 前端开发
|
||||
**前端**
|
||||
|
||||
```bash
|
||||
# 前端仓库: https://github.com/vastsa/FileCodeBoxFronted
|
||||
cd fcb-fronted
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## 🤝 贡献指南
|
||||
### 技术栈
|
||||
|
||||
1. Fork 本项目
|
||||
2. 创建新分支 `git checkout -b feature/xxx`
|
||||
3. 提交更改 `git commit -m 'Add xxx'`
|
||||
4. 推送到分支 `git push origin feature/xxx`
|
||||
5. 提交 Pull Request
|
||||
| 类别 | 技术 |
|
||||
|------|------|
|
||||
| **后端框架** | FastAPI 0.128+ / Uvicorn |
|
||||
| **数据库** | SQLite + Tortoise ORM |
|
||||
| **数据验证** | Pydantic 2.x |
|
||||
| **异步支持** | aiofiles / aiohttp / aioboto3 |
|
||||
| **对象存储** | S3 协议 / OneDrive / OpenDAL |
|
||||
| **前端框架** | Vue 3 + Element Plus + Vite |
|
||||
| **运行环境** | Python 3.8+ / Node.js 18+ |
|
||||
| **容器化** | Docker / Docker Compose |
|
||||
|
||||
---
|
||||
|
||||
## ❓ 常见问题
|
||||
|
||||
### Q: 如何修改上传大小限制?
|
||||
<details>
|
||||
<summary><b>如何修改上传大小限制?</b></summary>
|
||||
|
||||
A: 在管理面板中修改配置项 `uploadSize`
|
||||
在管理面板中修改 `uploadSize` 配置项。如果使用 Nginx 反向代理,还需修改 `client_max_body_size`。
|
||||
</details>
|
||||
|
||||
### Q: 如何配置存储引擎?
|
||||
<details>
|
||||
<summary><b>如何配置存储引擎?</b></summary>
|
||||
|
||||
A: 在管理面板中选择存储引擎并配置相应参数
|
||||
在管理面板中选择存储引擎类型并配置相应参数。支持本地存储、S3、OneDrive、OpenDAL 等。
|
||||
</details>
|
||||
|
||||
### Q: 如何备份数据?
|
||||
<details>
|
||||
<summary><b>如何备份数据?</b></summary>
|
||||
|
||||
A: 备份 `data` 目录即可
|
||||
备份 `data` 目录即可,包含数据库和上传的文件。
|
||||
</details>
|
||||
|
||||
更多问题请访问 [Wiki](https://github.com/vastsa/FileCodeBox/wiki/常见问题)
|
||||
<details>
|
||||
<summary><b>如何修改管理员密码?</b></summary>
|
||||
|
||||
登录管理面板后,在系统设置中修改 `adminPassword` 配置项。
|
||||
</details>
|
||||
|
||||
更多问题请访问 [Wiki](https://github.com/vastsa/FileCodeBox/wiki/常见问题) 或加入 [QQ群: 739673698](https://qm.qq.com/q/PemPzhdEIM)
|
||||
|
||||
---
|
||||
|
||||
## 🤝 贡献指南
|
||||
|
||||
欢迎提交 Issue 和 Pull Request!
|
||||
|
||||
```bash
|
||||
# 1. Fork 并克隆
|
||||
git clone https://github.com/your-username/FileCodeBox.git
|
||||
|
||||
# 2. 创建分支
|
||||
git checkout -b feature/your-feature
|
||||
|
||||
# 3. 提交更改
|
||||
git commit -m "feat: add your feature"
|
||||
|
||||
# 4. 推送并创建 PR
|
||||
git push origin feature/your-feature
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 项目统计
|
||||
|
||||
<div align="center">
|
||||
<a href="https://hellogithub.com/repository/75ad7ffedd404a6485b4d621ec5b47e6" target="_blank"><img src="https://api.hellogithub.com/v1/widgets/recommend.svg?rid=75ad7ffedd404a6485b4d621ec5b47e6&claim_uid=beSz6INEkCM4mDH" alt="Featured|HelloGitHub" style="width: 200px; height: 45px;" width="200" height="45" /></a>
|
||||
|
||||
<a href="https://hellogithub.com/repository/75ad7ffedd404a6485b4d621ec5b47e6" target="_blank">
|
||||
<img src="https://api.hellogithub.com/v1/widgets/recommend.svg?rid=75ad7ffedd404a6485b4d621ec5b47e6&claim_uid=beSz6INEkCM4mDH" alt="HelloGitHub" width="200">
|
||||
</a>
|
||||
|
||||

|
||||
|
||||
[](https://star-history.com/#vastsa/FileCodeBox&Date)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## 🗓 更新计划
|
||||
|
||||
- [ ] 2025 年新皮肤
|
||||
- [ ] 文件收集功能
|
||||
|
||||
---
|
||||
|
||||
## 📜 免责声明
|
||||
|
||||
本项目开源仅供学习使用,不得用于任何违法用途,否则后果自负,与作者无关。使用时请保留项目地址和版权信息。
|
||||
本项目开源仅供学习交流使用,不得用于任何违法用途,否则后果自负,与作者无关。使用本项目时请保留项目地址和版权信息。
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
**如果觉得项目不错,欢迎 ⭐ Star 支持!**
|
||||
|
||||
Made with ❤️ by [vastsa](https://github.com/vastsa)
|
||||
|
||||
|
||||
</div>
|
||||
+355
-224
@@ -1,340 +1,471 @@
|
||||
# FileCodeBox
|
||||
|
||||
<div align="center">
|
||||
|
||||
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/static/banners/img_1.png" alt="FileCodeBox Logo">
|
||||
# FileCodeBox
|
||||
|
||||
<p><em>Share text and files anonymously with a passcode, like picking up a package</em></p>
|
||||
### Anonymous File & Text Sharing with Passcode
|
||||
|
||||
[](https://github.com/vastsa/FileCodeBox/stargazers)
|
||||
[](https://github.com/vastsa/FileCodeBox/network)
|
||||
[](https://github.com/vastsa/FileCodeBox/issues)
|
||||
[](https://github.com/vastsa/FileCodeBox/blob/master/LICENSE)
|
||||
[](https://qm.qq.com/q/PemPzhdEIM)
|
||||
[](https://www.python.org)
|
||||
[](https://fastapi.tiangolo.com)
|
||||
[](https://v3.vuejs.org)
|
||||
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/static/banners/img_1.png" alt="FileCodeBox Logo" width="400">
|
||||
|
||||
[简体中文](./readme.md) | [Deployment Guide](https://github.com/vastsa/FileCodeBox/wiki/Deployment-Guide) | [FAQ](https://github.com/vastsa/FileCodeBox/wiki/FAQ)
|
||||
Share files like picking up a package — no registration required, just enter the passcode
|
||||
|
||||
[](https://github.com/vastsa/FileCodeBox/stargazers)
|
||||
[](https://github.com/vastsa/FileCodeBox/network)
|
||||
[](https://github.com/vastsa/FileCodeBox/issues)
|
||||
[](https://github.com/vastsa/FileCodeBox/blob/master/LICENSE)
|
||||
[](https://hub.docker.com/r/lanol/filecodebox)
|
||||
|
||||
[](https://www.python.org)
|
||||
[](https://fastapi.tiangolo.com)
|
||||
[](https://vuejs.org)
|
||||
|
||||
[简体中文](./README.md) | [Live Demo](https://share.lanol.cn) | [Documentation](https://github.com/vastsa/FileCodeBox/wiki/Deployment-Guide) | [FAQ](https://github.com/vastsa/FileCodeBox/wiki/FAQ)
|
||||
|
||||
```bash
|
||||
# 🚀 Quick Deploy
|
||||
docker run -d -p 12345:12345 -v /opt/FileCodeBox:/app/data --name filecodebox lanol/filecodebox:latest
|
||||
# China Mirror (if slow): docker.cnb.cool/aixk/filecodebox
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Introduction](#-introduction)
|
||||
- [Features](#-features)
|
||||
- [Screenshots](#-screenshots)
|
||||
- [Quick Start](#-quick-start)
|
||||
- [Usage Guide](#-usage-guide)
|
||||
- [Development](#-development)
|
||||
- [FAQ](#-faq)
|
||||
- [Contributing](#-contributing)
|
||||
- [Statistics](#-statistics)
|
||||
- [Disclaimer](#-disclaimer)
|
||||
|
||||
---
|
||||
|
||||
## 📝 Introduction
|
||||
|
||||
FileCodeBox is a lightweight file sharing tool developed with FastAPI + Vue3. It allows users to share text and files
|
||||
easily, where recipients only need a passcode to retrieve the files, just like picking up a package from a delivery
|
||||
locker.
|
||||
FileCodeBox is a lightweight file sharing tool built with **FastAPI + Vue3**. Users can anonymously share text and files, and recipients only need to enter a passcode to retrieve the content — just like picking up a package from a locker.
|
||||
|
||||
## 🖼️ Preview
|
||||
### Use Cases
|
||||
|
||||
<div align="center">
|
||||
<h3>
|
||||
<a href="https://github.com/vastsa/FileCodeBoxFronted" target="_blank">
|
||||
<img src="https://img.shields.io/badge/Frontend-FileCodeBoxFronted2024-blue?style=for-the-badge&logo=github" alt="前端仓库2024">
|
||||
</a>
|
||||
<a href="https://github.com/vastsa/FileCodeBoxFronted2023" target="_blank">
|
||||
<img src="https://img.shields.io/badge/Frontend-FileCodeBoxFronted2023-blue?style=for-the-badge&logo=github" alt="前端仓库2023">
|
||||
</a>
|
||||
|
||||
<a href="https://share.lanol.cn" target="_blank">
|
||||
<img src="https://img.shields.io/badge/Demo-share.lanol.cn-green?style=for-the-badge&logo=internet-explorer" alt="演示站点">
|
||||
</a>
|
||||
</h3>
|
||||
</div>
|
||||
| Scenario | Description |
|
||||
|----------|-------------|
|
||||
| 📁 **Temporary File Sharing** | Quick file sharing without registration |
|
||||
| 📝 **Code Snippet Sharing** | Share code, config files, and text content |
|
||||
| 🕶️ **Anonymous Transfer** | Privacy-protected peer-to-peer transfer |
|
||||
| 🔄 **Cross-Device Transfer** | Quickly sync files between devices |
|
||||
| 💾 **Temporary Storage** | Cloud storage with custom expiration |
|
||||
| 🌐 **Private Service** | Build your own enterprise or personal sharing service |
|
||||
|
||||
### New Interface
|
||||
---
|
||||
|
||||
## ✨ Features
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="33%" valign="top">
|
||||
|
||||
### 🚀 Lightweight & Fast
|
||||
- FastAPI + SQLite3 backend
|
||||
- Vue3 + Element Plus frontend
|
||||
- One-click Docker deployment
|
||||
- Minimal resource usage
|
||||
|
||||
</td>
|
||||
<td width="33%" valign="top">
|
||||
|
||||
### 🔒 Secure & Reliable
|
||||
- IP upload rate limiting
|
||||
- Passcode attempt limiting
|
||||
- Auto file expiration cleanup
|
||||
- Admin authentication support
|
||||
|
||||
</td>
|
||||
<td width="33%" valign="top">
|
||||
|
||||
### 📤 Easy Upload
|
||||
- Drag & drop upload
|
||||
- Copy & paste upload
|
||||
- Command line curl upload
|
||||
- Batch file upload
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="33%" valign="top">
|
||||
|
||||
### 🎫 Flexible Sharing
|
||||
- Random / custom passcodes
|
||||
- Set expiration (time/count)
|
||||
- Permanent validity support
|
||||
- Unified text & file management
|
||||
|
||||
</td>
|
||||
<td width="33%" valign="top">
|
||||
|
||||
### 💾 Multiple Storage
|
||||
- Local file system
|
||||
- S3-compatible storage
|
||||
- [OneDrive](./docs/guide/storage-onedrive.md)
|
||||
- [OpenDAL](./docs/guide/storage-opendal.md)
|
||||
|
||||
</td>
|
||||
<td width="33%" valign="top">
|
||||
|
||||
### 🌍 Internationalization
|
||||
- Simplified Chinese
|
||||
- Traditional Chinese
|
||||
- English
|
||||
- Responsive design / Dark mode
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
---
|
||||
|
||||
## 🖼️ Screenshots
|
||||
|
||||
> Frontend repositories: [2024 Theme](https://github.com/vastsa/FileCodeBoxFronted) | [2023 Theme](https://github.com/vastsa/FileCodeBoxFronted2023)
|
||||
|
||||
<details open>
|
||||
<summary><b>🎨 New Interface (2024)</b></summary>
|
||||
<br>
|
||||
<div align="center">
|
||||
<table>
|
||||
<tr>
|
||||
<td><img src="./.github/images/img_7.png" alt="File Upload" title="File Upload Interface"></td>
|
||||
<td><img src="./.github/images/img_8.png" alt="Text Share" title="Text Share Interface"></td>
|
||||
<td><img src="./.github/images/img_7.png" alt="File Upload"></td>
|
||||
<td><img src="./.github/images/img_8.png" alt="Text Share"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="./.github/images/img_10.png" alt="File Management" title="File Management Interface"></td>
|
||||
<td><img src="./.github/images/img_9.png" alt="System Settings" title="System Settings Interface"></td>
|
||||
<td><img src="./.github/images/img_10.png" alt="File Management"></td>
|
||||
<td><img src="./.github/images/img_9.png" alt="System Settings"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="./.github/images/img_11.png" alt="Mobile View" title="Mobile Interface"></td>
|
||||
<td><img src="./.github/images/img_12.png" alt="Dark Mode" title="Dark Mode Interface"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="./.github/images/img_13.png" alt="Internationalization" title="Language Support"></td>
|
||||
<td><img src="./.github/images/img_14.png" alt="Responsive" title="Responsive Design"></td>
|
||||
<td><img src="./.github/images/img_11.png" alt="Mobile View"></td>
|
||||
<td><img src="./.github/images/img_12.png" alt="Dark Mode"></td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
### Classic Interface
|
||||
|
||||
<details>
|
||||
<summary><b>📦 Classic Interface (2023)</b></summary>
|
||||
<br>
|
||||
<div align="center">
|
||||
<table>
|
||||
<tr>
|
||||
<td><img src="./.github/images/img.png" alt="Home" title="Home Page"></td>
|
||||
<td><img src="./.github/images/img_1.png" alt="Upload" title="Upload Interface"></td>
|
||||
<td><img src="./.github/images/img.png" alt="Home"></td>
|
||||
<td><img src="./.github/images/img_1.png" alt="Upload"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="./.github/images/img_2.png" alt="Management" title="Management Interface"></td>
|
||||
<td><img src="./.github/images/img_3.png" alt="Settings" title="Settings Interface"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="./.github/images/img_4.png" alt="Share" title="Share Interface"></td>
|
||||
<td><img src="./.github/images/img_5.png" alt="Download" title="Download Interface"></td>
|
||||
<td><img src="./.github/images/img_2.png" alt="Management"></td>
|
||||
<td><img src="./.github/images/img_3.png" alt="Settings"></td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
## 🎯 Use Cases
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>📁 Temporary File Sharing</h4>
|
||||
Quick file sharing without registration
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>📝 Quick Text Sharing</h4>
|
||||
Share code snippets and text content
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🕶️ Anonymous Transfer</h4>
|
||||
Privacy-protected file transfer
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>💾 Temporary Storage</h4>
|
||||
File storage with expiration time
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🔄 Cross-platform Transfer</h4>
|
||||
Quick file transfer between devices
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🌐 Private Share Service</h4>
|
||||
Build your own file sharing service
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## ✨ Core Features
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>🚀 Lightweight</h4>
|
||||
Based on FastAPI + SQLite3 + Vue3 + ElementUI
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>📤 Easy Upload</h4>
|
||||
Support copy-paste and drag-drop
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>📦 Multiple Types</h4>
|
||||
Support text and various file types
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>🔒 Security</h4>
|
||||
|
||||
- IP upload limits
|
||||
- Error attempt limits
|
||||
- File expiration
|
||||
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🎫 Passcode Sharing</h4>
|
||||
Random codes with customizable limits
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🌍 Multi-language</h4>
|
||||
Support for Simplified Chinese, Traditional Chinese, and English
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>🎭 Anonymous</h4>
|
||||
No registration required
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🛠 Admin Panel</h4>
|
||||
File and system management
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🐳 Docker</h4>
|
||||
One-click deployment
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>💾 Storage Options</h4>
|
||||
Local, S3, OneDrive support
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>📱 Responsive</h4>
|
||||
Mobile-friendly design
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>💻 CLI Support</h4>
|
||||
Command-line download
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
---
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### Docker Deployment
|
||||
### Docker Deployment (Recommended)
|
||||
|
||||
#### Docker CLI
|
||||
**Option 1: Docker CLI**
|
||||
|
||||
```bash
|
||||
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:beta
|
||||
# Docker Hub (Recommended)
|
||||
docker run -d --restart always -p 12345:12345 -v /opt/FileCodeBox:/app/data --name filecodebox lanol/filecodebox:latest
|
||||
|
||||
# China Mirror (if Docker Hub is slow)
|
||||
docker run -d --restart always -p 12345:12345 -v /opt/FileCodeBox:/app/data --name filecodebox docker.cnb.cool/aixk/filecodebox
|
||||
```
|
||||
|
||||
#### Docker Compose
|
||||
**Option 2: Docker Compose**
|
||||
|
||||
```ymlfix
|
||||
version: "3"
|
||||
services:s
|
||||
file-code-box:
|
||||
```yaml
|
||||
services:
|
||||
filecodebox:
|
||||
image: lanol/filecodebox:latest
|
||||
volumes:
|
||||
- fcb-data:/app/data:rw
|
||||
container_name: filecodebox
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "12345:12345"
|
||||
volumes:
|
||||
fcb-data:
|
||||
external: false
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
environment:
|
||||
- WORKERS=4
|
||||
- LOG_LEVEL=info
|
||||
```
|
||||
|
||||
### Configure reverse proxy (Nginx example)
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Please note that the following configurations must be added to ensure proper handling of client IP and proxy requests:
|
||||
**Environment Variables**
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `HOST` | `::` | Listen address (supports IPv4/IPv6 dual-stack) |
|
||||
| `PORT` | `12345` | Service port |
|
||||
| `WORKERS` | `4` | Worker processes (recommended: CPU cores) |
|
||||
| `LOG_LEVEL` | `info` | Log level: `debug` / `info` / `warning` / `error` |
|
||||
|
||||
### Reverse Proxy Configuration
|
||||
|
||||
When using Nginx, add the following configuration to properly obtain client IP:
|
||||
|
||||
```nginx
|
||||
location / {
|
||||
proxy_set_header X-Real-IP $remote_addr; #Set real client IP
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_pass http://localhost:12345 ;
|
||||
proxy_pass http://127.0.0.1:12345;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 100m; # Adjust upload size limit as needed
|
||||
}
|
||||
```
|
||||
|
||||
### Manual Deployment
|
||||
|
||||
1. Clone the repository
|
||||
|
||||
```bash
|
||||
# 1. Clone the repository
|
||||
git clone https://github.com/vastsa/FileCodeBox.git
|
||||
```
|
||||
|
||||
2. Install dependencies
|
||||
|
||||
```bash
|
||||
cd FileCodeBox
|
||||
|
||||
# 2. Install dependencies
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. Start the service
|
||||
|
||||
```bash
|
||||
# 3. Start the service
|
||||
python main.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📖 Usage Guide
|
||||
|
||||
### Share Files
|
||||
### Basic Operations
|
||||
|
||||
1. Open the website, click "Share File"
|
||||
2. Select or drag files
|
||||
3. Set expiration time and count
|
||||
4. Get the passcode
|
||||
| Operation | Steps |
|
||||
|-----------|-------|
|
||||
| **Share File** | Open website → Select/drag files → Set expiration → Get passcode |
|
||||
| **Retrieve File** | Open website → Enter passcode → Download file or view text |
|
||||
| **Admin Panel** | Visit `/#/admin` → Enter password `FileCodeBox2023` |
|
||||
|
||||
### Retrieve Files
|
||||
### Command Line Usage (curl)
|
||||
|
||||
1. Open the website, enter passcode
|
||||
2. Click retrieve
|
||||
3. Download file or view text
|
||||
<details>
|
||||
<summary><b>Click to expand curl examples</b></summary>
|
||||
|
||||
### Admin Panel
|
||||
**Upload File**
|
||||
|
||||
1. Visit `/admin`
|
||||
2. Enter admin password
|
||||
3. Manage files and settings
|
||||
```bash
|
||||
# Basic upload (default 1 day expiration)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.txt"
|
||||
|
||||
## 🛠 Development Guide
|
||||
# Set 1 hour expiration
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.txt" \
|
||||
-F "expire_value=1" \
|
||||
-F "expire_style=hour"
|
||||
|
||||
# Set expiration after 10 downloads
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.txt" \
|
||||
-F "expire_value=10" \
|
||||
-F "expire_style=count"
|
||||
```
|
||||
|
||||
**Share Text**
|
||||
|
||||
```bash
|
||||
curl -X POST "http://localhost:12345/share/text/" \
|
||||
-F "text=Text content to share"
|
||||
```
|
||||
|
||||
**Download File**
|
||||
|
||||
```bash
|
||||
curl -L "http://localhost:12345/share/select/?code=PASSCODE" -o filename
|
||||
```
|
||||
|
||||
**Expiration Parameters**
|
||||
|
||||
| `expire_style` | Description |
|
||||
|----------------|-------------|
|
||||
| `day` | Days |
|
||||
| `hour` | Hours |
|
||||
| `minute` | Minutes |
|
||||
| `count` | Download count |
|
||||
| `forever` | Never expire |
|
||||
|
||||
**Response Example**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abcd1234",
|
||||
"name": "file.txt"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**When Authentication Required** (after admin disables guest upload)
|
||||
|
||||
```bash
|
||||
# 1. Get token
|
||||
curl -X POST "http://localhost:12345/admin/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"password": "FileCodeBox2023"}'
|
||||
|
||||
# 2. Upload with token
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-H "Authorization: Bearer <token>" \
|
||||
-F "file=@/path/to/file.txt"
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## 🛠 Development
|
||||
|
||||
### Project Structure
|
||||
|
||||
```
|
||||
FileCodeBox/
|
||||
├── apps/ # Application code
|
||||
│ ├── admin/ # Admin backend
|
||||
│ └── base/ # Base functions
|
||||
├── core/ # Core functions
|
||||
├── data/ # Data directory
|
||||
└── fcb-fronted/ # Frontend code
|
||||
├── apps/ # Application modules
|
||||
│ ├── admin/ # Admin backend
|
||||
│ └── base/ # Base functionality
|
||||
├── core/ # Core modules
|
||||
├── data/ # Data directory (generated at runtime)
|
||||
├── docs/ # Documentation
|
||||
└── main.py # Entry point
|
||||
```
|
||||
|
||||
### Development Environment
|
||||
|
||||
- Python 3.8+
|
||||
- Node.js 14+
|
||||
- Vue 3
|
||||
- FastAPI
|
||||
|
||||
### Local Development
|
||||
|
||||
1. Backend development
|
||||
**Backend**
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
python main.py
|
||||
```
|
||||
|
||||
2. Frontend development
|
||||
**Frontend**
|
||||
|
||||
```bash
|
||||
# Frontend repo: https://github.com/vastsa/FileCodeBoxFronted
|
||||
cd fcb-fronted
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## 🤝 Contributing
|
||||
### Tech Stack
|
||||
|
||||
1. Fork the project
|
||||
2. Create your feature branch `git checkout -b feature/xxx`
|
||||
3. Commit your changes `git commit -m 'Add xxx'`
|
||||
4. Push to the branch `git push origin feature/xxx`
|
||||
5. Open a Pull Request
|
||||
| Category | Technology |
|
||||
|----------|------------|
|
||||
| **Backend Framework** | FastAPI 0.128+ / Uvicorn |
|
||||
| **Database** | SQLite + Tortoise ORM |
|
||||
| **Data Validation** | Pydantic 2.x |
|
||||
| **Async Support** | aiofiles / aiohttp / aioboto3 |
|
||||
| **Object Storage** | S3 Protocol / OneDrive / OpenDAL |
|
||||
| **Frontend Framework** | Vue 3 + Element Plus + Vite |
|
||||
| **Runtime** | Python 3.8+ / Node.js 18+ |
|
||||
| **Containerization** | Docker / Docker Compose |
|
||||
|
||||
---
|
||||
|
||||
## ❓ FAQ
|
||||
|
||||
### Q: How to modify upload size limit?
|
||||
<details>
|
||||
<summary><b>How to modify upload size limit?</b></summary>
|
||||
|
||||
A: Change `uploadSize` in admin panel
|
||||
Modify the `uploadSize` configuration in the admin panel. If using Nginx reverse proxy, also modify `client_max_body_size`.
|
||||
</details>
|
||||
|
||||
### Q: How to configure storage engine?
|
||||
<details>
|
||||
<summary><b>How to configure storage engine?</b></summary>
|
||||
|
||||
A: Select storage engine and configure parameters in admin panel
|
||||
Select the storage engine type and configure parameters in the admin panel. Supports local storage, S3, OneDrive, OpenDAL, etc.
|
||||
</details>
|
||||
|
||||
### Q: How to backup data?
|
||||
<details>
|
||||
<summary><b>How to backup data?</b></summary>
|
||||
|
||||
A: Backup the `data` directory
|
||||
Backup the `data` directory, which contains the database and uploaded files.
|
||||
</details>
|
||||
|
||||
For more questions, visit [Wiki](https://github.com/vastsa/FileCodeBox/wiki/常见问题)
|
||||
<details>
|
||||
<summary><b>How to change admin password?</b></summary>
|
||||
|
||||
## �� Project Statistics and Analytics
|
||||
After logging into the admin panel, modify the `adminPassword` configuration in system settings.
|
||||
</details>
|
||||
|
||||
For more questions, visit [Wiki](https://github.com/vastsa/FileCodeBox/wiki/FAQ)
|
||||
|
||||
---
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
Issues and Pull Requests are welcome!
|
||||
|
||||
```bash
|
||||
# 1. Fork and clone
|
||||
git clone https://github.com/your-username/FileCodeBox.git
|
||||
|
||||
# 2. Create branch
|
||||
git checkout -b feature/your-feature
|
||||
|
||||
# 3. Commit changes
|
||||
git commit -m "feat: add your feature"
|
||||
|
||||
# 4. Push and create PR
|
||||
git push origin feature/your-feature
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 Statistics
|
||||
|
||||
<div align="center">
|
||||
<a href="https://hellogithub.com/repository/75ad7ffedd404a6485b4d621ec5b47e6" target="_blank"><img src="https://api.hellogithub.com/v1/widgets/recommend.svg?rid=75ad7ffedd404a6485b4d621ec5b47e6&claim_uid=beSz6INEkCM4mDH" alt="Featured|HelloGitHub" style="width: 200px; height: 45px;" width="200" height="45" /></a>
|
||||
|
||||
<a href="https://hellogithub.com/repository/75ad7ffedd404a6485b4d621ec5b47e6" target="_blank">
|
||||
<img src="https://api.hellogithub.com/v1/widgets/recommend.svg?rid=75ad7ffedd404a6485b4d621ec5b47e6&claim_uid=beSz6INEkCM4mDH" alt="HelloGitHub" width="200">
|
||||
</a>
|
||||
|
||||

|
||||
|
||||
[](https://star-history.com/#vastsa/FileCodeBox&Date)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## 🗓 Roadmap
|
||||
|
||||
- [ ] 2025 New Theme
|
||||
- [ ] File Collection Feature
|
||||
|
||||
---
|
||||
|
||||
## 📜 Disclaimer
|
||||
|
||||
This project is open-source for learning purposes only. It should not be used for any illegal purposes. The author is
|
||||
not responsible for any consequences. Please retain the project address and copyright information when using it.
|
||||
This project is open-source for learning and communication purposes only. It should not be used for any illegal purposes. The author is not responsible for any consequences. Please retain the project address and copyright information when using it.
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
**If you find this project helpful, please give it a ⭐ Star!**
|
||||
|
||||
Made with ❤️ by [vastsa](https://github.com/vastsa)
|
||||
|
||||
</div>
|
||||
+8
-9
@@ -1,9 +1,8 @@
|
||||
aioboto3==11.2.0
|
||||
aiohttp==3.10.11
|
||||
aiofiles==24.1.0
|
||||
botocore==1.29.76
|
||||
fastapi==0.115.0
|
||||
pydantic==2.4.0
|
||||
uvicorn==0.23.2
|
||||
tortoise-orm==0.20.0
|
||||
python-multipart==0.0.20
|
||||
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
|
||||
@@ -0,0 +1,6 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(PROJECT_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
@@ -0,0 +1,33 @@
|
||||
import unittest
|
||||
|
||||
from core.settings import settings
|
||||
from core.storage import S3FileStorage
|
||||
|
||||
|
||||
class SettingsOverrideMixin:
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
|
||||
def tearDown(self):
|
||||
settings.user_config = self._original_user_config
|
||||
|
||||
|
||||
class S3StorageConfigTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def test_client_config_uses_path_style_when_configured(self):
|
||||
storage = S3FileStorage.__new__(S3FileStorage)
|
||||
storage.signature_version = "s3v4"
|
||||
storage.addressing_style = "path"
|
||||
|
||||
config = storage._client_config()
|
||||
|
||||
self.assertEqual(config.signature_version, "s3v4")
|
||||
self.assertEqual(config.s3["addressing_style"], "path")
|
||||
|
||||
def test_client_config_ignores_invalid_addressing_style(self):
|
||||
storage = S3FileStorage.__new__(S3FileStorage)
|
||||
storage.signature_version = "s3v4"
|
||||
storage.addressing_style = "invalid"
|
||||
|
||||
config = storage._client_config()
|
||||
|
||||
self.assertIsNone(config.s3)
|
||||
@@ -0,0 +1,65 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from apps.admin.services import FileService
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
class SettingsOverrideMixin:
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
|
||||
def tearDown(self):
|
||||
settings.user_config = self._original_user_config
|
||||
|
||||
|
||||
class FakeFileCode:
|
||||
def __init__(self):
|
||||
self.id = 1
|
||||
self.code = "ABC123"
|
||||
self.prefix = "report"
|
||||
self.suffix = ".txt"
|
||||
self.uuid_file_name = "report.txt"
|
||||
self.file_path = "share/data/2026/01/01/abc"
|
||||
self.size = 12
|
||||
self.text = None
|
||||
self.expired_at = datetime(2026, 1, 2, 12, 0, 0)
|
||||
self.expired_count = 3
|
||||
self.used_count = 0
|
||||
self.created_at = datetime(2026, 1, 1, 12, 0, 0)
|
||||
self.file_hash = "a" * 64
|
||||
self.is_chunked = False
|
||||
self.upload_id = None
|
||||
|
||||
async def is_expired(self):
|
||||
return False
|
||||
|
||||
|
||||
class AdminFileItemTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def test_build_admin_file_item_serializes_required_fields(self):
|
||||
settings.file_storage = "local"
|
||||
service = FileService()
|
||||
now = datetime(2026, 1, 1, 13, 0, 0)
|
||||
|
||||
item = asyncio.run(service._build_admin_file_item(FakeFileCode(), now=now))
|
||||
|
||||
self.assertEqual(item["id"], 1)
|
||||
self.assertEqual(item["name"], "report.txt")
|
||||
self.assertEqual(item["type"], "file")
|
||||
self.assertFalse(item["isExpired"])
|
||||
self.assertEqual(item["remainingDownloads"], 3)
|
||||
self.assertEqual(item["file_path"], "share/data/2026/01/01/abc")
|
||||
self.assertIn("never_retrieved", item["statusInsights"]["reasons"])
|
||||
self.assertEqual(item["statusInsights"]["metrics"]["ageSeconds"], 3600)
|
||||
|
||||
def test_build_admin_file_item_marks_expiring_soon(self):
|
||||
settings.file_storage = "local"
|
||||
service = FileService()
|
||||
file_code = FakeFileCode()
|
||||
now = file_code.expired_at - timedelta(hours=2)
|
||||
|
||||
item = asyncio.run(service._build_admin_file_item(file_code, now=now))
|
||||
|
||||
self.assertEqual(item["statusInsights"]["severity"], "warning")
|
||||
self.assertIn("expires_soon", item["statusInsights"]["reasons"])
|
||||
@@ -0,0 +1,31 @@
|
||||
import unittest
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from apps.base.views import validate_file_type
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
class SettingsOverrideMixin:
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
|
||||
def tearDown(self):
|
||||
settings.user_config = self._original_user_config
|
||||
|
||||
|
||||
class FileTypeValidationTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def test_allows_extensions_and_mime_patterns(self):
|
||||
settings.allowed_file_types = ["rar", ".zip", "image/*"]
|
||||
|
||||
validate_file_type("backup.RAR")
|
||||
validate_file_type("archive.zip")
|
||||
validate_file_type("avatar.bin", "image/png")
|
||||
|
||||
def test_rejects_disallowed_file_type(self):
|
||||
settings.allowed_file_types = ["rar"]
|
||||
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
validate_file_type("payload.exe", "application/octet-stream")
|
||||
|
||||
self.assertEqual(error.exception.status_code, 403)
|
||||
@@ -0,0 +1,34 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
|
||||
import apps.base.views as views
|
||||
from apps.base.views import normalize_share_code
|
||||
|
||||
|
||||
class FakeFileCodes:
|
||||
seen_code = None
|
||||
|
||||
@classmethod
|
||||
def filter(cls, **kwargs):
|
||||
cls.seen_code = kwargs.get("code")
|
||||
return cls()
|
||||
|
||||
async def first(self):
|
||||
return None
|
||||
|
||||
|
||||
class RetrieveCodeTests(unittest.TestCase):
|
||||
def test_normalize_share_code_strips_surrounding_whitespace(self):
|
||||
self.assertEqual(normalize_share_code(" 12345\n"), "12345")
|
||||
|
||||
def test_get_code_file_by_code_queries_normalized_code(self):
|
||||
original_file_codes = views.FileCodes
|
||||
views.FileCodes = FakeFileCodes
|
||||
try:
|
||||
has_file, message = asyncio.run(views.get_code_file_by_code(" 12345\n"))
|
||||
finally:
|
||||
views.FileCodes = original_file_codes
|
||||
|
||||
self.assertFalse(has_file)
|
||||
self.assertEqual(message, "文件不存在")
|
||||
self.assertEqual(FakeFileCodes.seen_code, "12345")
|
||||
@@ -0,0 +1,44 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from core.settings import settings
|
||||
from main import index, resolve_theme_file
|
||||
|
||||
|
||||
class SettingsOverrideMixin:
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
|
||||
def tearDown(self):
|
||||
settings.user_config = self._original_user_config
|
||||
|
||||
|
||||
class ThemeAssetTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def test_resolves_assets_from_current_theme(self):
|
||||
settings.themesSelect = "themes/2023"
|
||||
theme_2023_asset = resolve_theme_file("assets", "index-CxMsK_Ni.js")
|
||||
|
||||
settings.themesSelect = "themes/2024"
|
||||
theme_2024_asset = resolve_theme_file("assets", "index-DjzJA_Oj.js")
|
||||
|
||||
self.assertIn("themes/2023/assets", str(theme_2023_asset))
|
||||
self.assertIn("themes/2024/assets", str(theme_2024_asset))
|
||||
|
||||
def test_rejects_theme_asset_path_traversal(self):
|
||||
settings.themesSelect = "themes/2024"
|
||||
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
resolve_theme_file("assets", "..", "..", "core", "settings.py")
|
||||
|
||||
self.assertEqual(error.exception.status_code, 404)
|
||||
|
||||
def test_index_keeps_absolute_asset_urls(self):
|
||||
settings.themesSelect = "themes/2023"
|
||||
|
||||
response = asyncio.run(index())
|
||||
html = response.body.decode("utf-8")
|
||||
|
||||
self.assertIn('src="/assets/', html)
|
||||
self.assertIn('href="/assets/', html)
|
||||
@@ -0,0 +1,46 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
|
||||
from core.storage import S3FileStorage
|
||||
|
||||
|
||||
class FakeS3Client:
|
||||
def __init__(self, list_response):
|
||||
self.list_response = list_response
|
||||
self.head_calls = 0
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc, traceback):
|
||||
return False
|
||||
|
||||
async def head_object(self, **kwargs):
|
||||
self.head_calls += 1
|
||||
raise RuntimeError("head not supported")
|
||||
|
||||
async def list_objects_v2(self, **kwargs):
|
||||
return self.list_response
|
||||
|
||||
|
||||
class S3FileExistsTests(unittest.TestCase):
|
||||
def test_file_exists_falls_back_to_list_objects(self):
|
||||
client = FakeS3Client({"Contents": [{"Key": "share/data/file.txt"}]})
|
||||
storage = S3FileStorage.__new__(S3FileStorage)
|
||||
storage.bucket_name = "bucket"
|
||||
storage._client = lambda: client
|
||||
|
||||
exists = asyncio.run(storage.file_exists("share/data/file.txt"))
|
||||
|
||||
self.assertTrue(exists)
|
||||
self.assertEqual(client.head_calls, 3)
|
||||
|
||||
def test_file_exists_returns_false_when_missing(self):
|
||||
client = FakeS3Client({"Contents": [{"Key": "share/data/other.txt"}]})
|
||||
storage = S3FileStorage.__new__(S3FileStorage)
|
||||
storage.bucket_name = "bucket"
|
||||
storage._client = lambda: client
|
||||
|
||||
exists = asyncio.run(storage.file_exists("share/data/file.txt"))
|
||||
|
||||
self.assertFalse(exists)
|
||||
@@ -0,0 +1,271 @@
|
||||
import asyncio
|
||||
import unittest
|
||||
from datetime import timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
import apps.base.views as views
|
||||
from apps.base.schemas import PresignUploadInitRequest
|
||||
from core.settings import settings
|
||||
from core.utils import get_now
|
||||
|
||||
|
||||
class SettingsOverrideMixin:
|
||||
def setUp(self):
|
||||
self._original_user_config = dict(settings.user_config)
|
||||
|
||||
def tearDown(self):
|
||||
settings.user_config = self._original_user_config
|
||||
|
||||
|
||||
class FakeUploadLimiter:
|
||||
def __init__(self):
|
||||
self.added_ips = []
|
||||
|
||||
def add_ip(self, ip):
|
||||
self.added_ips.append(ip)
|
||||
|
||||
|
||||
class FakeUploadFile:
|
||||
def __init__(self, size):
|
||||
self.size = size
|
||||
self.filename = "upload.txt"
|
||||
self.content_type = "text/plain"
|
||||
|
||||
|
||||
class FakeStorage:
|
||||
def __init__(self, presigned_url=None, exists=True):
|
||||
self.presigned_url = presigned_url
|
||||
self.exists = exists
|
||||
self.saved = []
|
||||
self.deleted = []
|
||||
|
||||
async def generate_presigned_upload_url(self, save_path, expires_in):
|
||||
self.last_presign_request = (save_path, expires_in)
|
||||
return self.presigned_url
|
||||
|
||||
async def save_file(self, file, save_path):
|
||||
self.saved.append((file, save_path))
|
||||
|
||||
async def file_exists(self, save_path):
|
||||
self.last_exists_path = save_path
|
||||
return self.exists
|
||||
|
||||
async def delete_file(self, file_code):
|
||||
self.deleted.append(file_code)
|
||||
|
||||
|
||||
class FakeSession:
|
||||
def __init__(self, mode="direct", file_size=12, expired=False):
|
||||
self.upload_id = "upload-1"
|
||||
self.file_name = "upload.txt"
|
||||
self.file_size = file_size
|
||||
self.save_path = "share/data/2026/06/06/upload-1/upload.txt"
|
||||
self.mode = mode
|
||||
self.expire_value = 2
|
||||
self.expire_style = "day"
|
||||
self.created_at = None
|
||||
self.expires_at = None
|
||||
self.expired = expired
|
||||
self.deleted = False
|
||||
|
||||
async def is_expired(self):
|
||||
return self.expired
|
||||
|
||||
async def delete(self):
|
||||
self.deleted = True
|
||||
|
||||
|
||||
class FakeSessionQuery:
|
||||
def __init__(self, session):
|
||||
self.session = session
|
||||
|
||||
async def first(self):
|
||||
return self.session
|
||||
|
||||
|
||||
class FakePresignUploadSession:
|
||||
created_payload = None
|
||||
session = None
|
||||
|
||||
@classmethod
|
||||
async def create(cls, **kwargs):
|
||||
cls.created_payload = kwargs
|
||||
return SimpleNamespace(**kwargs)
|
||||
|
||||
@classmethod
|
||||
def filter(cls, **kwargs):
|
||||
cls.filter_kwargs = kwargs
|
||||
return FakeSessionQuery(cls.session)
|
||||
|
||||
|
||||
class FakeFileUploadService:
|
||||
created_records = []
|
||||
|
||||
@staticmethod
|
||||
async def generate_file_path(file_name, upload_id=None):
|
||||
filename = file_name.strip()
|
||||
return (
|
||||
f"share/data/2026/06/06/{upload_id}",
|
||||
".txt",
|
||||
"upload",
|
||||
filename,
|
||||
f"share/data/2026/06/06/{upload_id}/{filename}",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
async def create_file_record(
|
||||
cls, file_name, file_size, file_path, expire_value, expire_style, **extra_fields
|
||||
):
|
||||
cls.created_records.append(
|
||||
{
|
||||
"file_name": file_name,
|
||||
"file_size": file_size,
|
||||
"file_path": file_path,
|
||||
"expire_value": expire_value,
|
||||
"expire_style": expire_style,
|
||||
**extra_fields,
|
||||
}
|
||||
)
|
||||
return "12345"
|
||||
|
||||
|
||||
class PresignUploadFlowTests(SettingsOverrideMixin, unittest.TestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self._original_storages = dict(views.storages)
|
||||
self._original_session_model = views.PresignUploadSession
|
||||
self._original_file_upload_service = views.FileUploadService
|
||||
self._original_upload_limiter = views.ip_limit["upload"]
|
||||
self.storage = FakeStorage()
|
||||
views.storages = {"local": lambda: self.storage}
|
||||
views.PresignUploadSession = FakePresignUploadSession
|
||||
views.FileUploadService = FakeFileUploadService
|
||||
views.ip_limit["upload"] = FakeUploadLimiter()
|
||||
FakePresignUploadSession.created_payload = None
|
||||
FakePresignUploadSession.session = None
|
||||
FakeFileUploadService.created_records = []
|
||||
settings.file_storage = "local"
|
||||
settings.uploadSize = 1024
|
||||
settings.allowed_file_types = ["*"]
|
||||
settings.expireStyle = ["day", "hour", "minute", "forever", "count"]
|
||||
|
||||
def tearDown(self):
|
||||
views.storages = self._original_storages
|
||||
views.PresignUploadSession = self._original_session_model
|
||||
views.FileUploadService = self._original_file_upload_service
|
||||
views.ip_limit["upload"] = self._original_upload_limiter
|
||||
super().tearDown()
|
||||
|
||||
def test_init_returns_proxy_urls_when_storage_has_no_presigned_url(self):
|
||||
response = asyncio.run(
|
||||
views.presign_upload_init(
|
||||
PresignUploadInitRequest(
|
||||
file_name="upload.txt",
|
||||
file_size=12,
|
||||
expire_value=2,
|
||||
expire_style="day",
|
||||
),
|
||||
ip="127.0.0.1",
|
||||
)
|
||||
)
|
||||
|
||||
detail = response.detail
|
||||
self.assertEqual(detail["mode"], "proxy")
|
||||
self.assertEqual(detail["upload_url"], detail["proxy_upload_url"])
|
||||
self.assertEqual(detail["legacy_proxy_upload_url"], f"/api{detail['proxy_upload_url']}")
|
||||
self.assertEqual(FakePresignUploadSession.created_payload["file_name"], "upload.txt")
|
||||
self.assertEqual(FakePresignUploadSession.created_payload["file_size"], 12)
|
||||
self.assertEqual(views.ip_limit["upload"].added_ips, ["127.0.0.1"])
|
||||
|
||||
def test_init_returns_direct_url_when_storage_supports_presigned_upload(self):
|
||||
self.storage.presigned_url = "https://storage.example/upload"
|
||||
|
||||
response = asyncio.run(
|
||||
views.presign_upload_init(
|
||||
PresignUploadInitRequest(file_name="upload.txt", file_size=12),
|
||||
ip="127.0.0.1",
|
||||
)
|
||||
)
|
||||
|
||||
self.assertEqual(response.detail["mode"], "direct")
|
||||
self.assertEqual(response.detail["upload_url"], "https://storage.example/upload")
|
||||
self.assertNotIn("proxy_upload_url", response.detail)
|
||||
|
||||
def test_init_rejects_disallowed_expiration_style(self):
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
asyncio.run(
|
||||
views.presign_upload_init(
|
||||
PresignUploadInitRequest(
|
||||
file_name="upload.txt",
|
||||
file_size=12,
|
||||
expire_style="week",
|
||||
),
|
||||
ip="127.0.0.1",
|
||||
)
|
||||
)
|
||||
|
||||
self.assertEqual(error.exception.status_code, 400)
|
||||
|
||||
def test_confirm_requires_uploaded_direct_file_before_creating_record(self):
|
||||
FakePresignUploadSession.session = FakeSession(mode="direct")
|
||||
self.storage.exists = True
|
||||
|
||||
response = asyncio.run(views.presign_upload_confirm("upload-1", ip="127.0.0.1"))
|
||||
|
||||
self.assertEqual(response.detail, {"code": "12345", "name": "upload.txt"})
|
||||
self.assertTrue(FakePresignUploadSession.session.deleted)
|
||||
self.assertEqual(FakeFileUploadService.created_records[0]["file_size"], 12)
|
||||
self.assertEqual(
|
||||
FakeFileUploadService.created_records[0]["file_path"],
|
||||
"share/data/2026/06/06/upload-1",
|
||||
)
|
||||
|
||||
def test_confirm_rejects_missing_uploaded_direct_file(self):
|
||||
FakePresignUploadSession.session = FakeSession(mode="direct")
|
||||
self.storage.exists = False
|
||||
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
asyncio.run(views.presign_upload_confirm("upload-1", ip="127.0.0.1"))
|
||||
|
||||
self.assertEqual(error.exception.status_code, 404)
|
||||
self.assertFalse(FakePresignUploadSession.session.deleted)
|
||||
self.assertEqual(FakeFileUploadService.created_records, [])
|
||||
|
||||
def test_proxy_upload_rejects_size_mismatch_before_saving_file(self):
|
||||
FakePresignUploadSession.session = FakeSession(mode="proxy", file_size=10)
|
||||
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
asyncio.run(
|
||||
views.presign_upload_proxy(
|
||||
"upload-1",
|
||||
file=FakeUploadFile(size=2048),
|
||||
ip="127.0.0.1",
|
||||
)
|
||||
)
|
||||
|
||||
self.assertEqual(error.exception.status_code, 403)
|
||||
self.assertEqual(self.storage.saved, [])
|
||||
|
||||
def test_cancel_direct_session_removes_uploaded_object_when_present(self):
|
||||
FakePresignUploadSession.session = FakeSession(mode="direct")
|
||||
self.storage.exists = True
|
||||
|
||||
response = asyncio.run(views.presign_upload_cancel("upload-1"))
|
||||
|
||||
self.assertEqual(response.detail, {"message": "上传会话已取消"})
|
||||
self.assertTrue(FakePresignUploadSession.session.deleted)
|
||||
self.assertEqual(len(self.storage.deleted), 1)
|
||||
self.assertEqual(self.storage.deleted[0].file_path, "share/data/2026/06/06/upload-1")
|
||||
self.assertEqual(self.storage.deleted[0].uuid_file_name, "upload.txt")
|
||||
|
||||
def test_expired_session_is_deleted_and_rejected(self):
|
||||
FakePresignUploadSession.session = FakeSession(mode="direct", expired=True)
|
||||
FakePresignUploadSession.session.expires_at = asyncio.run(get_now()) - timedelta(seconds=1)
|
||||
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
asyncio.run(views.presign_upload_confirm("upload-1", ip="127.0.0.1"))
|
||||
|
||||
self.assertEqual(error.exception.status_code, 404)
|
||||
self.assertTrue(FakePresignUploadSession.session.deleted)
|
||||
@@ -1 +0,0 @@
|
||||
import{a as s,a8 as n,P as c,N as e,U as r,R as a,j as o,o as i}from"./index-CxMsK_Ni.js";const l={style:{"text-align":"center"}},u={style:{color:"#333"},href:"https://github.com/vastsa/FileCodeBox"},f=s({__name:"AboutView",setup(_){const{t}=n();return(m,p)=>(i(),c("main",l,[e("span",null,[r(a(o(t)("admin.about.source1"))+" ",1),e("em",null,[e("a",u,a(o(t)("admin.about.source2")),1)])])]))}});export{f as default};
|
||||
@@ -1 +0,0 @@
|
||||
.el-container{box-sizing:border-box;display:flex;flex:1;flex-basis:auto;flex-direction:row;min-width:0}.el-container.is-vertical{flex-direction:column}.el-aside{box-sizing:border-box;flex-shrink:0;overflow:auto;width:var(--el-aside-width,300px)}.el-footer{--el-footer-padding:0 20px;--el-footer-height:60px;box-sizing:border-box;flex-shrink:0;height:var(--el-footer-height);padding:var(--el-footer-padding)}.el-header{--el-header-padding:0 20px;--el-header-height:60px;box-sizing:border-box;flex-shrink:0;height:var(--el-header-height);padding:var(--el-header-padding)}.el-main{--el-main-padding:20px;box-sizing:border-box;display:block;flex:1;flex-basis:auto;overflow:auto;padding:var(--el-main-padding)}.fade-in-linear-enter-active,.fade-in-linear-leave-active{transition:var(--el-transition-fade-linear)}.fade-in-linear-enter-from,.fade-in-linear-leave-to{opacity:0}.el-fade-in-linear-enter-active,.el-fade-in-linear-leave-active{transition:var(--el-transition-fade-linear)}.el-fade-in-linear-enter-from,.el-fade-in-linear-leave-to{opacity:0}.el-fade-in-enter-active,.el-fade-in-leave-active{transition:all var(--el-transition-duration) cubic-bezier(.55,0,.1,1)}.el-fade-in-enter-from,.el-fade-in-leave-active{opacity:0}.el-zoom-in-center-enter-active,.el-zoom-in-center-leave-active{transition:all var(--el-transition-duration) cubic-bezier(.55,0,.1,1)}.el-zoom-in-center-enter-from,.el-zoom-in-center-leave-active{opacity:0;transform:scaleX(0)}.el-zoom-in-top-enter-active,.el-zoom-in-top-leave-active{opacity:1;transform:scaleY(1);transform-origin:center top;transition:var(--el-transition-md-fade)}.el-zoom-in-top-enter-active[data-popper-placement^=top],.el-zoom-in-top-leave-active[data-popper-placement^=top]{transform-origin:center bottom}.el-zoom-in-top-enter-from,.el-zoom-in-top-leave-active{opacity:0;transform:scaleY(0)}.el-zoom-in-bottom-enter-active,.el-zoom-in-bottom-leave-active{opacity:1;transform:scaleY(1);transform-origin:center bottom;transition:var(--el-transition-md-fade)}.el-zoom-in-bottom-enter-from,.el-zoom-in-bottom-leave-active{opacity:0;transform:scaleY(0)}.el-zoom-in-left-enter-active,.el-zoom-in-left-leave-active{opacity:1;transform:scale(1);transform-origin:top left;transition:var(--el-transition-md-fade)}.el-zoom-in-left-enter-from,.el-zoom-in-left-leave-active{opacity:0;transform:scale(.45)}.collapse-transition{transition:var(--el-transition-duration) height ease-in-out,var(--el-transition-duration) padding-top ease-in-out,var(--el-transition-duration) padding-bottom ease-in-out}.el-collapse-transition-enter-active,.el-collapse-transition-leave-active{transition:var(--el-transition-duration) max-height ease-in-out,var(--el-transition-duration) padding-top ease-in-out,var(--el-transition-duration) padding-bottom ease-in-out}.horizontal-collapse-transition{transition:var(--el-transition-duration) width ease-in-out,var(--el-transition-duration) padding-left ease-in-out,var(--el-transition-duration) padding-right ease-in-out}.el-list-enter-active,.el-list-leave-active{transition:all 1s}.el-list-enter-from,.el-list-leave-to{opacity:0;transform:translateY(-30px)}.el-list-leave-active{position:absolute!important}.el-opacity-transition{transition:opacity var(--el-transition-duration) cubic-bezier(.55,0,.1,1)}:root{--el-menu-active-color:var(--el-color-primary);--el-menu-text-color:var(--el-text-color-primary);--el-menu-hover-text-color:var(--el-color-primary);--el-menu-bg-color:var(--el-fill-color-blank);--el-menu-hover-bg-color:var(--el-color-primary-light-9);--el-menu-item-height:56px;--el-menu-sub-item-height:calc(var(--el-menu-item-height) - 6px);--el-menu-horizontal-height:60px;--el-menu-horizontal-sub-item-height:36px;--el-menu-item-font-size:var(--el-font-size-base);--el-menu-item-hover-fill:var(--el-color-primary-light-9);--el-menu-border-color:var(--el-border-color);--el-menu-base-level-padding:20px;--el-menu-level-padding:20px;--el-menu-icon-width:24px}.el-menu{background-color:var(--el-menu-bg-color);border-right:1px solid var(--el-menu-border-color);box-sizing:border-box;list-style:none;margin:0;padding-left:0;position:relative}.el-menu--vertical:not(.el-menu--collapse):not(.el-menu--popup-container) .el-menu-item,.el-menu--vertical:not(.el-menu--collapse):not(.el-menu--popup-container) .el-menu-item-group__title,.el-menu--vertical:not(.el-menu--collapse):not(.el-menu--popup-container) .el-sub-menu__title{padding-left:calc(var(--el-menu-base-level-padding) + var(--el-menu-level)*var(--el-menu-level-padding));white-space:nowrap}.el-menu:not(.el-menu--collapse) .el-sub-menu__title{padding-right:calc(var(--el-menu-base-level-padding) + var(--el-menu-icon-width))}.el-menu--horizontal{border-right:none;display:flex;flex-wrap:nowrap;height:var(--el-menu-horizontal-height)}.el-menu--horizontal.el-menu--popup-container{height:unset}.el-menu--horizontal.el-menu{border-bottom:1px solid var(--el-menu-border-color)}.el-menu--horizontal>.el-menu-item{align-items:center;border-bottom:2px solid transparent;colorLine truncated
|
||||
@@ -1 +0,0 @@
|
||||
import{k as ie,T as Ke,t as ce,E as Qe,b as Xe}from"./el-input-CNNwOXGP.js";import{E as Ye,a as Ze}from"./el-form-item-llYGp2SQ.js";import"./el-tooltip-l0sNRNKZ.js";import{E as Pe,C as Je}from"./el-popper-C96qJ_vz.js";import{u as et,a as tt}from"./index-CBpXPsVN.js";import{_ as V,a as y,u as $,g as X,o as S,w,r as k,aC as Oe,aP as nt,j as h,T as Ne,l as ye,aG as at,c as f,P as A,h as D,n as Ie,ak as q,L as P,I as ue,aQ as ot,D as ve,b as Ce,i as de,s as x,aR as st,aS as lt,t as Ee,$ as re,p as _e,aT as Se,a0 as we,a1 as Be,z as I,W as Ae,G as Y,A as ze,C as ut,ab as pe,aU as $e,aV as ne,al as He,f as it,aW as rt,am as ke,d as me,aX as ct,m as dt,F as mt,aY as pt,M as Le,N as Me,aA as ft,U as ae,R as oe,aK as vt,a8 as ht,B as L,a9 as gt,ac as bt,af as _t,aF as Te}from"./index-CxMsK_Ni.js";import{f as Mt}from"./vnode-Cc0RQjVK.js";import"./_baseClone-DD6IrDYX.js";const yt=y({name:"ElCollapseTransition"}),It=y({...yt,setup(e){const a=$("collapse-transition"),n=t=>{t.style.maxHeight="",t.style.overflow=t.dataset.oldOverflow,t.style.paddingTop=t.dataset.oldPaddingTop,t.style.paddingBottom=t.dataset.oldPaddingBottom},o={beforeEnter(t){t.dataset||(t.dataset={}),t.dataset.oldPaddingTop=t.style.paddingTop,t.dataset.oldPaddingBottom=t.style.paddingBottom,t.style.height&&(t.dataset.elExistsHeight=t.style.height),t.style.maxHeight=0,t.style.paddingTop=0,t.style.paddingBottom=0},enter(t){requestAnimationFrame(()=>{t.dataset.oldOverflow=t.style.overflow,t.dataset.elExistsHeight?t.style.maxHeight=t.dataset.elExistsHeight:t.scrollHeight!==0?t.style.maxHeight=`${t.scrollHeight}px`:t.style.maxHeight=0,t.style.paddingTop=t.dataset.oldPaddingTop,t.style.paddingBottom=t.dataset.oldPaddingBottom,t.style.overflow="hidden"})},afterEnter(t){t.style.maxHeight="",t.style.overflow=t.dataset.oldOverflow},enterCancelled(t){n(t)},beforeLeave(t){t.dataset||(t.dataset={}),t.dataset.oldPaddingTop=t.style.paddingTop,t.dataset.oldPaddingBottom=t.style.paddingBottom,t.dataset.oldOverflow=t.style.overflow,t.style.maxHeight=`${t.scrollHeight}px`,t.style.overflow="hidden"},leave(t){t.scrollHeight!==0&&(t.style.maxHeight=0,t.style.paddingTop=0,t.style.paddingBottom=0)},afterLeave(t){n(t)},leaveCancelled(t){n(t)}};return(t,v)=>(S(),X(Ne,Oe({name:h(a).b()},nt(o)),{default:w(()=>[k(t.$slots,"default")]),_:3},16,["name"]))}});var Ct=V(It,[["__file","collapse-transition.vue"]]);const Et=ye(Ct),St=y({name:"ElContainer"}),wt=y({...St,props:{direction:{type:String}},setup(e){const a=e,n=at(),o=$("container"),t=f(()=>a.direction==="vertical"?!0:a.direction==="horizontal"?!1:n&&n.default?n.default().some(d=>{const g=d.type.name;return g==="ElHeader"||g==="ElFooter"}):!1);return(v,d)=>(S(),A("section",{class:D([h(o).b(),h(o).is("vertical",h(t))])},[k(v.$slots,"default")],2))}});var xt=V(wt,[["__file","container.vue"]]);const $t=y({name:"ElAside"}),kt=y({...$t,props:{width:{type:String,default:null}},setup(e){const a=e,n=$("aside"),o=f(()=>a.width?n.cssVarBlock({width:a.width}):{});return(t,v)=>(S(),A("aside",{class:D(h(n).b()),style:Ie(h(o))},[k(t.$slots,"default")],6))}});var De=V(kt,[["__file","aside.vue"]]);const Tt=y({name:"ElFooter"}),Pt=y({...Tt,props:{height:{type:String,default:null}},setup(e){const a=e,n=$("footer"),o=f(()=>a.height?n.cssVarBlock({height:a.height}):{});return(t,v)=>(S(),A("footer",{class:D(h(n).b()),style:Ie(h(o))},[k(t.$slots,"default")],6))}});var Ve=V(Pt,[["__file","footer.vue"]]);const Ot=y({name:"ElHeader"}),Nt=y({...Ot,props:{height:{type:String,default:null}},setup(e){const a=e,n=$("header"),o=f(()=>a.height?n.cssVarBlock({height:a.height}):{});return(t,v)=>(S(),A("header",{class:D(h(n).b()),style:Ie(h(o))},[k(t.$slots,"default")],6))}});var Fe=V(Nt,[["__file","header.vue"]]);const Bt=y({name:"ElMain"}),At=y({...Bt,setup(e){const a=$("main");return(n,o)=>(S(),A("main",{class:D(h(a).b())},[k(n.$slots,"default")],2))}});var Re=V(At,[["__file","main.vue"]]);const zt=ye(xt,{Aside:De,Footer:Ve,Header:Fe,Main:Re});q(De);q(Ve);const Ht=q(Fe),Lt=q(Re);let Dt=class{constructor(a,n){this.parent=a,this.domNode=n,this.subIndex=0,this.subIndex=0,this.init()}init(){this.subMenuItems=this.domNode.querySelectorAll("li"),this.addListeners()}gotoSubIndex(a){a===this.subMenuItems.length?a=0:a<0&&(a=this.subMenuItems.length-1),this.subMenuItems[a].focus(),this.subIndex=a}addListeners(){const a=this.parent.domNode;Array.prototype.forEach.call(this.subMenuItems,n=>{n.addEventListener("keydown",o=>{let t=!1;switch(o.code){case P.down:{this.gotoSubIndex(this.subIndex+1),t=!0;break}case P.up:{this.gotoSubIndex(this.subIndex-1),t=!0;break}case P.tab:{ie(a,"mouseleave");break}case P.enter:case P.numpadEnter:case P.space:{t=!0,o.currentTarget.click();break}}return t&&(o.preventDefault(),o.stopPropagation()),!1})})}},Vt=class{constructor(a,n){this.domNode=a,this.submenu=null,this.submenu=null,this.init(n)}init(a){this.domNode.setAttribute("tabindex","0");const n=this.domNode.querySelector(`.${a}-menu`);n&&(this.submenu=new Dt(this,n)),this.addListeners()Line truncated
|
||||
@@ -1 +0,0 @@
|
||||
.el-drawer{--el-drawer-bg-color:var(--el-dialog-bg-color,var(--el-bg-color));--el-drawer-padding-primary:var(--el-dialog-padding-primary,20px);background-color:var(--el-drawer-bg-color);box-shadow:var(--el-box-shadow-dark);box-sizing:border-box;display:flex;flex-direction:column;overflow:hidden;position:absolute;transition:all var(--el-transition-duration)}.el-drawer .btt,.el-drawer .ltr,.el-drawer .rtl,.el-drawer .ttb{transform:translate(0)}.el-drawer__sr-focus:focus{outline:none!important}.el-drawer__header{align-items:center;color:#72767b;display:flex;margin-bottom:32px;padding:var(--el-drawer-padding-primary);padding-bottom:0}.el-drawer__header>:first-child{flex:1}.el-drawer__title{flex:1;font-size:16px;line-height:inherit;margin:0}.el-drawer__footer{padding:var(--el-drawer-padding-primary);padding-top:10px;text-align:right}.el-drawer__close-btn{background-color:transparent;border:none;color:inherit;cursor:pointer;display:inline-flex;font-size:var(--el-font-size-extra-large);outline:none}.el-drawer__close-btn:focus i,.el-drawer__close-btn:hover i{color:var(--el-color-primary)}.el-drawer__body{flex:1;overflow:auto;padding:var(--el-drawer-padding-primary)}.el-drawer__body>*{box-sizing:border-box}.el-drawer.ltr,.el-drawer.rtl{bottom:0;height:100%;top:0}.el-drawer.btt,.el-drawer.ttb{left:0;right:0;width:100%}.el-drawer.ltr{left:0}.el-drawer.rtl{right:0}.el-drawer.ttb{top:0}.el-drawer.btt{bottom:0}.el-drawer-fade-enter-active,.el-drawer-fade-leave-active{transition:all var(--el-transition-duration)}.el-drawer-fade-enter-active,.el-drawer-fade-enter-from,.el-drawer-fade-enter-to,.el-drawer-fade-leave-active,.el-drawer-fade-leave-from,.el-drawer-fade-leave-to{overflow:hidden!important}.el-drawer-fade-enter-from,.el-drawer-fade-leave-to{background-color:transparent!important}.el-drawer-fade-enter-from .rtl,.el-drawer-fade-leave-to .rtl{transform:translate(100%)}.el-drawer-fade-enter-from .ltr,.el-drawer-fade-leave-to .ltr{transform:translate(-100%)}.el-drawer-fade-enter-from .ttb,.el-drawer-fade-leave-to .ttb{transform:translateY(-100%)}.el-drawer-fade-enter-from .btt,.el-drawer-fade-leave-to .btt{transform:translateY(100%)}.el-progress{align-items:center;display:flex;line-height:1;position:relative}.el-progress__text{color:var(--el-text-color-regular);font-size:14px;line-height:1;margin-left:5px;min-width:50px}.el-progress__text i{display:block;vertical-align:middle}.el-progress--circle,.el-progress--dashboard{display:inline-block}.el-progress--circle .el-progress__text,.el-progress--dashboard .el-progress__text{left:0;margin:0;position:absolute;text-align:center;top:50%;transform:translateY(-50%);width:100%}.el-progress--circle .el-progress__text i,.el-progress--dashboard .el-progress__text i{display:inline-block;vertical-align:middle}.el-progress--without-text .el-progress__text{display:none}.el-progress--without-text .el-progress-bar{display:block;margin-right:0;padding-right:0}.el-progress--text-inside .el-progress-bar{margin-right:0;padding-right:0}.el-progress.is-success .el-progress-bar__inner{background-color:var(--el-color-success)}.el-progress.is-success .el-progress__text{color:var(--el-color-success)}.el-progress.is-warning .el-progress-bar__inner{background-color:var(--el-color-warning)}.el-progress.is-warning .el-progress__text{color:var(--el-color-warning)}.el-progress.is-exception .el-progress-bar__inner{background-color:var(--el-color-danger)}.el-progress.is-exception .el-progress__text{color:var(--el-color-danger)}.el-progress-bar{box-sizing:border-box;flex-grow:1}.el-progress-bar__outer{background-color:var(--el-border-color-lighter);border-radius:100px;height:6px;overflow:hidden;position:relative;vertical-align:middle}.el-progress-bar__inner{background-color:var(--el-color-primary);border-radius:100px;height:100%;left:0;line-height:1;position:absolute;text-align:right;top:0;transition:width .6s ease;white-space:nowrap}.el-progress-bar__inner:after{content:"";display:inline-block;height:100%;vertical-align:middle}.el-progress-bar__inner--indeterminate{animation:indeterminate 3s infinite;transform:translateZ(0)}.el-progress-bar__inner--striped{background-image:linear-gradient(45deg,rgba(0,0,0,.1) 25%,transparent 0,transparent 50%,rgba(0,0,0,.1) 0,rgba(0,0,0,.1) 75%,transparent 0,transparent);background-size:1.25em 1.25em}.el-progress-bar__inner--striped.el-progress-bar__inner--striped-flow{animation:striped-flow 3s linear infinite}.el-progress-bar__innerText{color:#fff;display:inline-block;font-size:12px;margin:0 5px;vertical-align:middle}@keyframes progress{0%{background-position:0 0}to{background-position:32px 0}}@keyframes indeterminate{0%{left:-100%}to{left:100%}}@keyframes striped-flow{0%{background-position:-100%}to{background-position:100%}}@font-face{font-family:KaTeX_AMS;font-style:normal;font-weight:400;src:url(/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2) format("woff2"),url(/assets/KaTeX_AMS-Regular-DMm9YOAa.woff) format("woff"),url(/assets/KaTeX_AMS-Regular-DRggAlZN.ttf) format("truLine truncated
|
||||
@@ -1,297 +0,0 @@
|
||||
import{e as lg,a as cg,j as ug,b as dg}from"./el-input-CNNwOXGP.js";import{u as _g,a as mg}from"./index-CBpXPsVN.js";import{b as bm,_ as hm,a as gn,aG as pg,c as St,s as pn,u as Tm,ao as gg,aH as Eg,g as Dt,o as Ne,w as ze,B as ot,T as fg,j as X,A as Sg,N as it,aC as bg,O as hg,P as rt,Q as Tn,h as bt,r as Yn,R as pt,W as Ol,as as Cm,C as Tg,l as Rm,d as ka,aI as Cg,aq as Rg,aJ as Ng,ar as yg,a2 as Og,G as _u,n as Bn,k as Ag,aK as Nm,t as mu,z as Ft,aL as ym,a0 as vg,ab as Cl,a8 as Ig,a9 as Om,U as mn,ac as pu,aF as Dg,aa as xg,aM as Mg,ad as wg,aN as Lg,aO as kg,ae as Pg}from"./index-CxMsK_Ni.js";import{e as Fg,f as Bg,g as Ug,E as Gg,h as Yg,d as qg}from"./config-CZWWa62X.js";import{E as zg}from"./el-tag-5pOVEKUY.js";var Hg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Al(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}const Vg=bm({...Bg,direction:{type:String,default:"rtl",values:["ltr","rtl","ttb","btt"]},size:{type:[String,Number],default:"30%"},withHeader:{type:Boolean,default:!0},modalFade:{type:Boolean,default:!0},headerAriaLevel:{type:String,default:"2"}}),Wg=Fg,$g=gn({name:"ElDrawer",inheritAttrs:!1}),Kg=gn({...$g,props:Vg,emits:Wg,setup(t,{expose:e}){const a=t,o=pg();lg({scope:"el-drawer",from:"the title slot",replacement:"the header slot",version:"3.0.0",ref:"https://element-plus.org/en-US/component/drawer.html#slots"},St(()=>!!o.title));const c=pn(),s=pn(),d=Tm("drawer"),{t:u}=gg(),{afterEnter:_,afterLeave:p,beforeLeave:S,visible:h,rendered:y,titleId:O,bodyId:N,zIndex:w,onModalClick:L,onOpenAutoFocus:D,onCloseAutoFocus:U,onFocusoutPrevented:x,onCloseRequested:G,handleClose:F}=Ug(a,c),z=St(()=>a.direction==="rtl"||a.direction==="ltr"),$=St(()=>Eg(a.size));return e({handleClose:F,afterEnter:_,afterLeave:p}),(V,ee)=>(Ne(),Dt(X(ug),{to:V.appendTo,disabled:V.appendTo!=="body"?!1:!V.appendToBody},{default:ze(()=>[ot(fg,{name:X(d).b("fade"),onAfterEnter:X(_),onAfterLeave:X(p),onBeforeLeave:X(S),persisted:""},{default:ze(()=>[Sg(ot(X(Gg),{mask:V.modal,"overlay-class":V.modalClass,"z-index":X(w),onClick:X(L)},{default:ze(()=>[ot(X(cg),{loop:"",trapped:X(h),"focus-trap-el":c.value,"focus-start-el":s.value,onFocusAfterTrapped:X(D),onFocusAfterReleased:X(U),onFocusoutPrevented:X(x),onReleaseRequested:X(G)},{default:ze(()=>[it("div",bg({ref_key:"drawerRef",ref:c,"aria-modal":"true","aria-label":V.title||void 0,"aria-labelledby":V.title?void 0:X(O),"aria-describedby":X(N)},V.$attrs,{class:[X(d).b(),V.direction,X(h)&&"open"],style:X(z)?"width: "+X($):"height: "+X($),role:"dialog",onClick:hg(()=>{},["stop"])}),[it("span",{ref_key:"focusStartRef",ref:s,class:bt(X(d).e("sr-focus")),tabindex:"-1"},null,2),V.withHeader?(Ne(),rt("header",{key:0,class:bt([X(d).e("header"),V.headerClass])},[V.$slots.title?Yn(V.$slots,"title",{key:1},()=>[Tn(" DEPRECATED SLOT ")]):Yn(V.$slots,"header",{key:0,close:X(F),titleId:X(O),titleClass:X(d).e("title")},()=>[V.$slots.title?Tn("v-if",!0):(Ne(),rt("span",{key:0,id:X(O),role:"heading","aria-level":V.headerAriaLevel,class:bt(X(d).e("title"))},pt(V.title),11,["id","aria-level"]))]),V.showClose?(Ne(),rt("button",{key:2,"aria-label":X(u)("el.drawer.close"),class:bt(X(d).e("close-btn")),type:"button",onClick:X(F)},[ot(X(Ol),{class:bt(X(d).e("close"))},{default:ze(()=>[ot(X(Cm))]),_:1},8,["class"])],10,["aria-label","onClick"])):Tn("v-if",!0)],2)):Tn("v-if",!0),X(y)?(Ne(),rt("div",{key:1,id:X(N),class:bt([X(d).e("body"),V.bodyClass])},[Yn(V.$slots,"default")],10,["id"])):Tn("v-if",!0),V.$slots.footer?(Ne(),rt("div",{key:2,class:bt([X(d).e("footer"),V.footerClass])},[Yn(V.$slots,"footer")],2)):Tn("v-if",!0)],16,["aria-label","aria-labelledby","aria-describedby","onClick"])]),_:3},8,["trapped","focus-trap-el","focus-start-el","onFocusAfterTrapped","onFocusAfterReleased","onFocusoutPrevented","onReleaseRequested"])]),_:3},8,["mask","overlay-class","z-index","onClick"]),[[Tg,X(h)]])]),_:3},8,["name","onAfterEnter","onAfterLeave","onBeforeLeave"])]),_:3},8,["to","disabled"]))}});var Qg=hm(Kg,[["__file","drawer.vue"]]);const Xg=Rm(Qg),Zg=bm({type:{type:String,default:"line",values:["line","circle","dashboard"]},percentage:{type:Number,default:0,validator:t=>t>=0&&t<=100},status:{type:String,default:"",values:["","success","exception","warning"]},indeterminate:Boolean,duration:{type:Number,default:3},strokeWidth:{type:Number,default:6},strokeLinecap:{type:ka(String),default:"round"},textInside:Boolean,width:{type:Number,default:126},showText:{type:Boolean,default:!0},color:{type:ka([String,Array,Function]),default:""},striped:Boolean,stripedFlow:Boolean,format:{type:ka(Function),default:t=>`${t}%`}}),Jg=gn({name:"ElProgress"}),jg=gn({...Jg,props:Zg,setup(t){const e=t,a={success:"#13ce66",exception:"#ff4949",warning:"#e6a23c",default:"#20a0ff"},o=Tm("progress"),c=St(()=>{const x={width:`${e.percentage}%`,animationDuration:`${e.duration}s`},G=U(e.percentage);return G.includes("gradient"Line truncated
|
||||
M 50 50
|
||||
m 0 ${G?"":"-"}${x}
|
||||
a ${x} ${x} 0 1 1 0 ${G?"-":""}${x*2}
|
||||
a ${x} ${x} 0 1 1 0 ${G?"":"-"}${x*2}
|
||||
`}),_=St(()=>2*Math.PI*d.value),p=St(()=>e.type==="dashboard"?.75:1),S=St(()=>`${-1*_.value*(1-p.value)/2}px`),h=St(()=>({strokeDasharray:`${_.value*p.value}px, ${_.value}px`,strokeDashoffset:S.value})),y=St(()=>({strokeDasharray:`${_.value*p.value*(e.percentage/100)}px, ${_.value}px`,strokeDashoffset:S.value,transition:"stroke-dasharray 0.6s ease 0s, stroke 0.6s ease, opacity ease 0.6s"})),O=St(()=>{let x;return e.color?x=U(e.percentage):x=a[e.status]||a.default,x}),N=St(()=>e.status==="warning"?Cg:e.type==="line"?e.status==="success"?Rg:Ng:e.status==="success"?yg:Cm),w=St(()=>e.type==="line"?12+e.strokeWidth*.4:e.width*.111111+2),L=St(()=>e.format(e.percentage));function D(x){const G=100/x.length;return x.map((z,$)=>_u(z)?{color:z,percentage:($+1)*G}:z).sort((z,$)=>z.percentage-$.percentage)}const U=x=>{var G;const{color:F}=e;if(Og(F))return F(x);if(_u(F))return F;{const z=D(F);for(const $ of z)if($.percentage>x)return $.color;return(G=z[z.length-1])==null?void 0:G.color}};return(x,G)=>(Ne(),rt("div",{class:bt([X(o).b(),X(o).m(x.type),X(o).is(x.status),{[X(o).m("without-text")]:!x.showText,[X(o).m("text-inside")]:x.textInside}]),role:"progressbar","aria-valuenow":x.percentage,"aria-valuemin":"0","aria-valuemax":"100"},[x.type==="line"?(Ne(),rt("div",{key:0,class:bt(X(o).b("bar"))},[it("div",{class:bt(X(o).be("bar","outer")),style:Bn({height:`${x.strokeWidth}px`})},[it("div",{class:bt([X(o).be("bar","inner"),{[X(o).bem("bar","inner","indeterminate")]:x.indeterminate},{[X(o).bem("bar","inner","striped")]:x.striped},{[X(o).bem("bar","inner","striped-flow")]:x.stripedFlow}]),style:Bn(X(c))},[(x.showText||x.$slots.default)&&x.textInside?(Ne(),rt("div",{key:0,class:bt(X(o).be("bar","innerText"))},[Yn(x.$slots,"default",{percentage:x.percentage},()=>[it("span",null,pt(X(L)),1)])],2)):Tn("v-if",!0)],6)],6)],2)):(Ne(),rt("div",{key:1,class:bt(X(o).b("circle")),style:Bn({height:`${x.width}px`,width:`${x.width}px`})},[(Ne(),rt("svg",{viewBox:"0 0 100 100"},[it("path",{class:bt(X(o).be("circle","track")),d:X(u),stroke:`var(${X(o).cssVarName("fill-color-light")}, #e5e9f2)`,"stroke-linecap":x.strokeLinecap,"stroke-width":X(s),fill:"none",style:Bn(X(h))},null,14,["d","stroke","stroke-linecap","stroke-width"]),it("path",{class:bt(X(o).be("circle","path")),d:X(u),stroke:X(O),fill:"none",opacity:x.percentage?1:0,"stroke-linecap":x.strokeLinecap,"stroke-width":X(s),style:Bn(X(y))},null,14,["d","stroke","opacity","stroke-linecap","stroke-width"])]))],6)),(x.showText||x.$slots.default)&&!x.textInside?(Ne(),rt("div",{key:2,class:bt(X(o).e("text")),style:Bn({fontSize:`${X(w)}px`})},[Yn(x.$slots,"default",{percentage:x.percentage},()=>[x.status?(Ne(),Dt(X(Ol),{key:1},{default:ze(()=>[(Ne(),Dt(Ag(X(N))))]),_:1})):(Ne(),rt("span",{key:0},pt(X(L)),1))])],6)):Tn("v-if",!0)],10,["aria-valuenow"]))}});var eE=hm(jg,[["__file","progress.vue"]]);const tE=Rm(eE),nE=Nm("fileData",()=>{const t=mu(JSON.parse(localStorage.getItem("receiveData")||"[]")||[]),e=mu(JSON.parse(localStorage.getItem("shareData")||"[]")||[]);function a(){localStorage.setItem("receiveData",JSON.stringify(t)),localStorage.setItem("shareData",JSON.stringify(e))}function o(u){t.unshift(u),a()}function c(u){e.unshift(u),a()}function s(u){t.splice(u,1),a()}function d(u){e.splice(u,1),a()}return{receiveData:t,shareData:e,save:a,addShareData:c,addReceiveData:o,deleteReceiveData:s,deleteShareData:d}}),Am=Nm("fileBox",()=>({showFileBox:pn(!1)}));function vm(t){return t instanceof Map?t.clear=t.delete=t.set=function(){throw new Error("map is read-only")}:t instanceof Set&&(t.add=t.clear=t.delete=function(){throw new Error("set is read-only")}),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(e=>{const a=t[e],o=typeof a;(o==="object"||o==="function")&&!Object.isFrozen(a)&&vm(a)}),t}class gu{constructor(e){e.data===void 0&&(e.data={}),this.data=e.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function Im(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Nn(t,...e){const a=Object.create(null);for(const o in t)a[o]=t[o];return e.forEach(function(o){for(const c in o)a[c]=o[c]}),a}const rE="</span>",Eu=t=>!!t.scope,aE=(t,{prefix:e})=>{if(t.startsWith("language:"))return t.replace("language:","language-");if(t.includes(".")){const a=t.split(".");return[`${e}${a.shift()}`,...a.map((o,c)=>`${o}${"_".repeat(c+1)}`)].join(" ")}return`${e}${t}`};class iE{constructor(e,a){this.buffer="",this.classPrefix=a.classPrefix,e.walk(this)}addText(e){this.buffer+=Im(e)}openNode(e){if(!Eu(e))return;const a=aE(e.scope,{prefix:this.classPrefix});this.span(a)}closeNode(e){Eu(e)&&(this.buffer+=rE)}value(){return this.buffer}span(e){this.buffer+=`<span class="${e}">`}}const fu=(t={})=>{const e={children:[]};return Object.assign(e,t),e};class vl{constructor(){this.rootNode=fu(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){tLine truncated
|
||||
https://github.com/highlightjs/highlight.js/issues/2277`),Ae=W,he=te),ue===void 0&&(ue=!0);const re={code:he,language:Ae};be("before:highlight",re);const Xe=re.result?re.result:h(re.language,re.code,ue);return Xe.code=re.code,be("after:highlight",Xe),Xe}function h(W,te,ue,he){const Ae=Object.create(null);function re(j,se){return j.keywords[se]}function Xe(){if(!de.keywords){Ve.addText(ye);return}let j=0;de.keywordPatternRe.lastIndex=0;let se=de.keywordPatternRe.exec(ye),Ee="";for(;se;){Ee+=ye.substring(j,se.index);const Se=ht.case_insensitive?se[0].toLowerCase():se[0],Ze=re(de,Se);if(Ze){const[Et,An]=Ze;if(Ve.addText(Ee),Ee="",Ae[Se]=(Ae[Se]||0)+1,Ae[Se]<=KE&&(ln+=An),Et.startsWith("_"))Ee+=se[0];else{const vn=ht.classNameAliases[Et]||Et;Me(se[0],vn)}}else Ee+=se[0];j=de.keywordPatternRe.lastIndex,se=de.keywordPatternRe.exec(ye)}Ee+=ye.substring(j),Ve.addText(Ee)}function st(){if(ye==="")return;let j=null;if(typeof de.subLanguage=="string"){if(!e[de.subLanguage]){Ve.addText(ye);return}j=h(de.subLanguage,ye,!0,gt[de.subLanguage]),gt[de.subLanguage]=j._top}else j=O(ye,de.subLanguage.length?de.subLanguage:null);de.relevance>0&&(ln+=j.relevance),Ve.__addSublanguage(j._emitter,j.language)}function ve(){de.subLanguage!=null?st():Xe(),ye=""}function Me(j,se){j!==""&&(Ve.startScope(se),Ve.addText(j),Ve.endScope())}function Fe(j,se){let Ee=1;const Se=se.length-1;for(;Ee<=Se;){if(!j._emit[Ee]){Ee++;continue}const Ze=ht.classNameAliases[j[Ee]]||j[Ee],Et=se[Ee];Ze?Me(Et,Ze):(ye=Et,Xe(),ye=""),Ee++}}function we(j,se){return j.scope&&typeof j.scope=="string"&&Ve.openNode(ht.classNameAliases[j.scope]||j.scope),j.beginScope&&(j.beginScope._wrap?(Me(ye,ht.classNameAliases[j.beginScope._wrap]||j.beginScope._wrap),ye=""):j.beginScope._multi&&(Fe(j.beginScope,se),ye="")),de=Object.create(j,{parent:{value:de}}),de}function Ie(j,se,Ee){let Se=uE(j.endRe,Ee);if(Se){if(j["on:end"]){const Ze=new gu(j);j["on:end"](se,Ze),Ze.isMatchIgnored&&(Se=!1)}if(Se){for(;j.endsParent&&j.parent;)j=j.parent;return j}}if(j.endsWithParent)return Ie(j.parent,se,Ee)}function Be(j){return de.matcher.regexIndex===0?(ye+=j[0],1):(Ut=!0,0)}function je(j){const se=j[0],Ee=j.rule,Se=new gu(Ee),Ze=[Ee.__beforeBegin,Ee["on:begin"]];for(const Et of Ze)if(Et&&(Et(j,Se),Se.isMatchIgnored))return Be(se);return Ee.skip?ye+=se:(Ee.excludeBegin&&(ye+=se),ve(),!Ee.returnBegin&&!Ee.excludeBegin&&(ye=se)),we(Ee,j),Ee.returnBegin?0:se.length}function et(j){const se=j[0],Ee=te.substring(j.index),Se=Ie(de,j,Ee);if(!Se)return Tu;const Ze=de;de.endScope&&de.endScope._wrap?(ve(),Me(se,de.endScope._wrap)):de.endScope&&de.endScope._multi?(ve(),Fe(de.endScope,j)):Ze.skip?ye+=se:(Ze.returnEnd||Ze.excludeEnd||(ye+=se),ve(),Ze.excludeEnd&&(ye=se));do de.scope&&Ve.closeNode(),!de.skip&&!de.subLanguage&&(ln+=de.relevance),de=de.parent;while(de!==Se.parent);return Se.starts&&we(Se.starts,j),Ze.returnEnd?0:se.length}function ut(){const j=[];for(let se=de;se!==ht;se=se.parent)se.scope&&j.unshift(se.scope);j.forEach(se=>Ve.openNode(se))}let mt={};function En(j,se){const Ee=se&&se[0];if(ye+=j,Ee==null)return ve(),0;if(mt.type==="begin"&&se.type==="end"&&mt.index===se.index&&Ee===""){if(ye+=te.slice(se.index,se.index+1),!c){const Se=new Error(`0 width match regex (${W})`);throw Se.languageName=W,Se.badRule=mt.rule,Se}return 1}if(mt=se,se.type==="begin")return je(se);if(se.type==="illegal"&&!ue){const Se=new Error('Illegal lexeme "'+Ee+'" for mode "'+(de.scope||"<unnamed>")+'"');throw Se.mode=de,Se}else if(se.type==="end"){const Se=et(se);if(Se!==Tu)return Se}if(se.type==="illegal"&&Ee==="")return ye+=`
|
||||
`,1;if(Ht>1e5&&Ht>se.index*3)throw new Error("potential infinite loop, way more iterations than matches");return ye+=Ee,Ee.length}const ht=V(W);if(!ht)throw Mn(s.replace("{}",W)),new Error('Unknown language: "'+W+'"');const on=HE(ht);let sn="",de=he||on;const gt={},Ve=new u.__emitter(u);ut();let ye="",ln=0,Rt=0,Ht=0,Ut=!1;try{if(ht.__emitTokens)ht.__emitTokens(te,Ve);else{for(de.matcher.considerAll();;){Ht++,Ut?Ut=!1:de.matcher.considerAll(),de.matcher.lastIndex=Rt;const j=de.matcher.exec(te);if(!j)break;const se=te.substring(Rt,j.index),Ee=En(se,j);Rt=j.index+Ee}En(te.substring(Rt))}return Ve.finalize(),sn=Ve.toHTML(),{language:W,value:sn,relevance:ln,illegal:!1,_emitter:Ve,_top:de}}catch(j){if(j.message&&j.message.includes("Illegal"))return{language:W,value:Pa(te),illegal:!0,relevance:0,_illegalBy:{message:j.message,index:Rt,context:te.slice(Rt-100,Rt+100),mode:j.mode,resultSoFar:sn},_emitter:Ve};if(c)return{language:W,value:Pa(te),illegal:!1,relevance:0,errorRaised:j,_emitter:Ve,_top:de};throw j}}function y(W){const te={value:Pa(W),illegal:!1,relevance:0,_top:d,_emitter:new u.__emitter(u)};return te._emitter.addText(W),te}function O(W,te){te=te||u.languages||Object.keys(e);const ue=y(W),he=te.filter(V).filter(ce).map(ve=>h(ve,W,!1));he.unshift(ue);const Ae=he.sort((ve,Me)=>{if(ve.relevance!==Me.relevance)return Me.relevance-ve.relevance;if(ve.language&&Me.language){if(V(ve.language).supersetOf===Me.language)return 1;if(V(Me.language).supersetOf===ve.language)return-1}return 0}),[re,Xe]=Ae,st=re;return st.secondBest=Xe,st}function N(W,te,ue){const he=te&&a[te]||ue;W.classList.add("hljs"),W.classList.add(`language-${he}`)}function w(W){let te=null;const ue=p(W);if(_(ue))return;if(be("before:highlightElement",{el:W,language:ue}),W.dataset.highlighted){console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",W);return}if(W.children.length>0&&(u.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(W)),u.throwUnescapedHTML))throw new $E("One of your code blocks includes unescaped HTML.",W.innerHTML);te=W;const he=te.textContent,Ae=ue?S(he,{language:ue,ignoreIllegals:!0}):O(he);W.innerHTML=Ae.value,W.dataset.highlighted="yes",N(W,ue,Ae.language),W.result={language:Ae.language,re:Ae.relevance,relevance:Ae.relevance},Ae.secondBest&&(W.secondBest={language:Ae.secondBest.language,relevance:Ae.secondBest.relevance}),be("after:highlightElement",{el:W,result:Ae,text:he})}function L(W){u=hu(u,W)}const D=()=>{G(),Un("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")};function U(){G(),Un("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")}let x=!1;function G(){function W(){G()}if(document.readyState==="loading"){x||window.addEventListener("DOMContentLoaded",W,!1),x=!0;return}document.querySelectorAll(u.cssSelector).forEach(w)}function F(W,te){let ue=null;try{ue=te(t)}catch(he){if(Mn("Language definition for '{}' could not be registered.".replace("{}",W)),c)Mn(he);else throw he;ue=d}ue.name||(ue.name=W),e[W]=ue,ue.rawDefinition=te.bind(null,t),ue.aliases&&ee(ue.aliases,{languageName:W})}function z(W){delete e[W];for(const te of Object.keys(a))a[te]===W&&delete a[te]}function $(){return Object.keys(e)}function V(W){return W=(W||"").toLowerCase(),e[W]||e[a[W]]}function ee(W,{languageName:te}){typeof W=="string"&&(W=[W]),W.forEach(ue=>{a[ue.toLowerCase()]=te})}function ce(W){const te=V(W);return te&&!te.disableAutodetect}function ne(W){W["before:highlightBlock"]&&!W["before:highlightElement"]&&(W["before:highlightElement"]=te=>{W["before:highlightBlock"](Object.assign({block:te.el},te))}),W["after:highlightBlock"]&&!W["after:highlightElement"]&&(W["after:highlightElement"]=te=>{W["after:highlightBlock"](Object.assign({block:te.el},te))})}function me(W){ne(W),o.push(W)}function pe(W){const te=o.indexOf(W);te!==-1&&o.splice(te,1)}function be(W,te){const ue=W;o.forEach(function(he){he[ue]&&he[ue](te)})}function fe(W){return Un("10.7.0","highlightBlock will be removed entirely in v12.0"),Un("10.7.0","Please use highlightElement now."),w(W)}Object.assign(t,{highlight:S,highlightAuto:O,highlightAll:G,highlightElement:w,highlightBlock:fe,configure:L,initHighlighting:D,initHighlightingOnLoad:U,registerLanguage:F,unregisterLanguage:z,listLanguages:$,getLanguage:V,registerAliases:ee,autoDetection:ce,inherit:hu,addPlugin:me,removePlugin:pe}),t.debugMode=function(){c=!1},t.safeMode=function(){c=!0},t.versionString=WE,t.regex={concat:Ln,lookahead:Dm,either:Il,optional:lE,anyNumberOfTimes:sE};for(const W in wr)typeof wr[W]=="object"&&vm(wr[W]);return Object.assign(t,wr),t},Hn=Um({});Hn.newInstance=()=>Um({});var QE=Hn;Hn.HighlightJS=Hn;Hn.default=Hn;var Fa,Cu;function XE(){if(Cu)return Fa;Cu=1;function t(e){const a="[A-Za-zА-Яа-яёЁ_][A-Za-Line truncated
|
||||
`},N]}}return Co=c,Co}var Ro,s_;function PS(){if(s_)return Ro;s_=1;function t(e){const a="[a-zA-Z_][\\w.]*",o="<\\?(lasso(script)?|=)",c="\\]|\\?>",s={$pattern:a+"|&[lg]t;",literal:"true false none minimal full all void and or not bw nbw ew new cn ncn lt lte gt gte eq neq rx nrx ft",built_in:"array date decimal duration integer map pair string tag xml null boolean bytes keyword list locale queue set stack staticarray local var variable global data self inherited currentcapture givenblock",keyword:"cache database_names database_schemanames database_tablenames define_tag define_type email_batch encode_set html_comment handle handle_error header if inline iterate ljax_target link link_currentaction link_currentgroup link_currentrecord link_detail link_firstgroup link_firstrecord link_lastgroup link_lastrecord link_nextgroup link_nextrecord link_prevgroup link_prevrecord log loop namespace_using output_none portal private protect records referer referrer repeating resultset rows search_args search_arguments select sort_args sort_arguments thread_atomic value_list while abort case else fail_if fail_ifnot fail if_empty if_false if_null if_true loop_abort loop_continue loop_count params params_up return return_value run_children soap_definetag soap_lastrequest soap_lastresponse tag_name ascending average by define descending do equals frozen group handle_failure import in into join let match max min on order parent protected provide public require returnhome skip split_thread sum take thread to trait type where with yield yieldhome"},d=e.COMMENT("<!--","-->",{relevance:0}),u={className:"meta",begin:"\\[noprocess\\]",starts:{end:"\\[/noprocess\\]",returnEnd:!0,contains:[d]}},_={className:"meta",begin:"\\[/noprocess|"+o},p={className:"symbol",begin:"'"+a+"'"},S=[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.inherit(e.C_NUMBER_MODE,{begin:e.C_NUMBER_RE+"|(-?infinity|NaN)\\b"}),e.inherit(e.APOS_STRING_MODE,{illegal:null}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null}),{className:"string",begin:"`",end:"`"},{variants:[{begin:"[#$]"+a},{begin:"#",end:"\\d+",illegal:"\\W"}]},{className:"type",begin:"::\\s*",end:a,illegal:"\\W"},{className:"params",variants:[{begin:"-(?!infinity)"+a,relevance:0},{begin:"(\\.\\.\\.)"}]},{begin:/(->|\.)\s*/,relevance:0,contains:[p]},{className:"class",beginKeywords:"define",returnEnd:!0,end:"\\(|=>",contains:[e.inherit(e.TITLE_MODE,{begin:a+"(=(?!>))?|[-+*/%](?!>)"})]}];return{name:"Lasso",aliases:["ls","lassoscript"],case_insensitive:!0,keywords:s,contains:[{className:"meta",begin:c,relevance:0,starts:{end:"\\[|"+o,returnEnd:!0,relevance:0,contains:[d]}},u,_,{className:"meta",begin:"\\[no_square_brackets",starts:{end:"\\[/no_square_brackets\\]",keywords:s,contains:[{className:"meta",begin:c,relevance:0,starts:{end:"\\[noprocess\\]|"+o,returnEnd:!0,contains:[d]}},u,_].concat(S)}},{className:"meta",begin:"\\[",relevance:0},{className:"meta",begin:"^#!",end:"lasso9$",relevance:10}].concat(S)}}return Ro=t,Ro}var No,l_;function FS(){if(l_)return No;l_=1;function t(e){const o=e.regex.either(...["(?:NeedsTeXFormat|RequirePackage|GetIdInfo)","Provides(?:Expl)?(?:Package|Class|File)","(?:DeclareOption|ProcessOptions)","(?:documentclass|usepackage|input|include)","makeat(?:letter|other)","ExplSyntax(?:On|Off)","(?:new|renew|provide)?command","(?:re)newenvironment","(?:New|Renew|Provide|Declare)(?:Expandable)?DocumentCommand","(?:New|Renew|Provide|Declare)DocumentEnvironment","(?:(?:e|g|x)?def|let)","(?:begin|end)","(?:part|chapter|(?:sub){0,2}section|(?:sub)?paragraph)","caption","(?:label|(?:eq|page|name)?ref|(?:paren|foot|super)?cite)","(?:alpha|beta|[Gg]amma|[Dd]elta|(?:var)?epsilon|zeta|eta|[Tt]heta|vartheta)","(?:iota|(?:var)?kappa|[Ll]ambda|mu|nu|[Xx]i|[Pp]i|varpi|(?:var)rho)","(?:[Ss]igma|varsigma|tau|[Uu]psilon|[Pp]hi|varphi|chi|[Pp]si|[Oo]mega)","(?:frac|sum|prod|lim|infty|times|sqrt|leq|geq|left|right|middle|[bB]igg?)","(?:[lr]angle|q?quad|[lcvdi]?dots|d?dot|hat|tilde|bar)"].map(ne=>ne+"(?![a-zA-Z@:_])")),c=new RegExp(["(?:__)?[a-zA-Z]{2,}_[a-zA-Z](?:_?[a-zA-Z])+:[a-zA-Z]*","[lgc]__?[a-zA-Z](?:_?[a-zA-Z])*_[a-zA-Z]{2,}","[qs]__?[a-zA-Z](?:_?[a-zA-Z])+","use(?:_i)?:[a-zA-Z]*","(?:else|fi|or):","(?:if|cs|exp):w","(?:hbox|vbox):n","::[a-zA-Z]_unbraced","::[a-zA-Z:]"].map(ne=>ne+"(?![a-zA-Z:_])").join("|")),s=[{begin:/[a-zA-Z@]+/},{begin:/[^a-zA-Z@]?/}],d=[{begin:/\^{6}[0-9a-f]{6}/},{begin:/\^{5}[0-9a-f]{5}/},{begin:/\^{4}[0-9a-f]{4}/},{begin:/\^{3}[0-9a-f]{3}/},{begin:/\^{2}[0-9a-f]{2}/},{begin:/\^{2}[\u0000-\u007f]/}],u={className:"keyword",begin:/\\/,relevance:0,contains:[{endsParent:!0,begin:o},{endsParent:!0,begin:c},{endsParent:!0,variants:d},{endsParent:!0,relevance:0,variants:s}]},_={className:"params",relevance:0,begin:/#+\d?/},p={variants:d},S={className:"built_in",relevance:0,begin:/[$&^_]/},h={className:"meta",begin:/% ?!(T[eE]X|tex|BIB|bib)/,end:"$",relevance:10},y=e.COMMENT("%","$",{relevance:0}),O=[u,_,p,S,h,y],N={begin:/\{/,end:/\}/,relevance:0,contains:["self",...O]},w=e.inheLine truncated
|
||||
]`,w={scope:"string",variants:[h,S,y,O]},L={scope:"number",variants:[{begin:"\\b0[bB][01]+(?:_[01]+)*\\b"},{begin:"\\b0[oO][0-7]+(?:_[0-7]+)*\\b"},{begin:"\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b"},{begin:"(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?"}],relevance:0},D=["false","null","true"],U=["__CLASS__","__DIR__","__FILE__","__FUNCTION__","__COMPILER_HALT_OFFSET__","__LINE__","__METHOD__","__NAMESPACE__","__TRAIT__","die","echo","exit","include","include_once","print","require","require_once","array","abstract","and","as","binary","bool","boolean","break","callable","case","catch","class","clone","const","continue","declare","default","do","double","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","enum","eval","extends","final","finally","float","for","foreach","from","global","goto","if","implements","instanceof","insteadof","int","integer","interface","isset","iterable","list","match|0","mixed","new","never","object","or","private","protected","public","readonly","real","return","string","switch","throw","trait","try","unset","use","var","void","while","xor","yield"],x=["Error|0","AppendIterator","ArgumentCountError","ArithmeticError","ArrayIterator","ArrayObject","AssertionError","BadFunctionCallException","BadMethodCallException","CachingIterator","CallbackFilterIterator","CompileError","Countable","DirectoryIterator","DivisionByZeroError","DomainException","EmptyIterator","ErrorException","Exception","FilesystemIterator","FilterIterator","GlobIterator","InfiniteIterator","InvalidArgumentException","IteratorIterator","LengthException","LimitIterator","LogicException","MultipleIterator","NoRewindIterator","OutOfBoundsException","OutOfRangeException","OuterIterator","OverflowException","ParentIterator","ParseError","RangeException","RecursiveArrayIterator","RecursiveCachingIterator","RecursiveCallbackFilterIterator","RecursiveDirectoryIterator","RecursiveFilterIterator","RecursiveIterator","RecursiveIteratorIterator","RecursiveRegexIterator","RecursiveTreeIterator","RegexIterator","RuntimeException","SeekableIterator","SplDoublyLinkedList","SplFileInfo","SplFileObject","SplFixedArray","SplHeap","SplMaxHeap","SplMinHeap","SplObjectStorage","SplObserver","SplPriorityQueue","SplQueue","SplStack","SplSubject","SplTempFileObject","TypeError","UnderflowException","UnexpectedValueException","UnhandledMatchError","ArrayAccess","BackedEnum","Closure","Fiber","Generator","Iterator","IteratorAggregate","Serializable","Stringable","Throwable","Traversable","UnitEnum","WeakReference","WeakMap","Directory","__PHP_Incomplete_Class","parent","php_user_filter","self","static","stdClass"],F={keyword:U,literal:(fe=>{const W=[];return fe.forEach(te=>{W.push(te),te.toLowerCase()===te?W.push(te.toUpperCase()):W.push(te.toLowerCase())}),W})(D),built_in:x},z=fe=>fe.map(W=>W.replace(/\|\d+$/,"")),$={variants:[{match:[/new/,a.concat(N,"+"),a.concat("(?!",z(x).join("\\b|"),"\\b)"),s],scope:{1:"keyword",4:"title.class"}}]},V=a.concat(c,"\\b(?!\\()"),ee={variants:[{match:[a.concat(/::/,a.lookahead(/(?!class\b)/)),V],scope:{2:"variable.constant"}},{match:[/::/,/class/],scope:{2:"variable.language"}},{match:[s,a.concat(/::/,a.lookahead(/(?!class\b)/)),V],scope:{1:"title.class",3:"variable.constant"}},{match:[s,a.concat("::",a.lookahead(/(?!class\b)/))],scope:{1:"title.class"}},{match:[s,/::/,/class/],scope:{1:"title.class",3:"variable.language"}}]},ce={scope:"attr",match:a.concat(c,a.lookahead(":"),a.lookahead(/(?!::)/))},ne={relevance:0,begin:/\(/,end:/\)/,keywords:F,contains:[ce,u,ee,e.C_BLOCK_COMMENT_MODE,w,L,$]},me={relevance:0,match:[/\b/,a.concat("(?!fn\\b|function\\b|",z(U).join("\\b|"),"|",z(x).join("\\b|"),"\\b)"),c,a.concat(N,"*"),a.lookahead(/(?=\()/)],scope:{3:"title.function.invoke"},contains:[ne]};ne.contains.push(me);const pe=[ce,ee,e.C_BLOCK_COMMENT_MODE,w,L,$],be={begin:a.concat(/#\[\s*\\?/,a.either(s,d)),beginScope:"meta",end:/]/,endScope:"meta",keywords:{literal:D,keyword:["new","array"]},contains:[{begin:/\[/,end:/]/,keywords:{literal:D,keyword:["new","array"]},contains:["self",...pe]},...pe,{scope:"meta",variants:[{match:s},{match:d}]}]};return{case_insensitive:!1,keywords:F,contains:[be,e.HASH_COMMENT_MODE,e.COMMENT("//","$"),e.COMMENT("/\\*","\\*/",{contains:[{scope:"doctag",match:"@[A-Za-z]+"}]}),{match:/__halt_compiler\(\);/,keywords:"__halt_compiler",starts:{scope:"comment",end:e.MATCH_NOTHING_RE,contains:[{match:/\?>/,scope:"meta",endsParent:!0}]}},_,{scope:"variable.language",match:/\$this\b/},u,me,ee,{match:[/const/,/\s/,c],scope:{1:"keyword",3:"variable.constant"}},$,{scope:"function",relevance:0,beginKeywords:"fn function",end:/[;{]/,excludeEnd:!0,illegal:"[$%\\[]",contains:[{beginKeywords:"use"},e.UNDERSCORE_TITLE_MODE,{begin:"=>",endsParent:!0},{scope:"params",begin:"\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0,keywords:F,contains:["self",be,u,ee,e.C_BLOCK_COMMENT_MODE,w,L]}]},{scope:"class",variants:[{beginKeywords:"enum",illegLine truncated
|
||||
]*;`,relevance:0},{begin:"[vp][0-9]+"}]}}return Ps=t,Ps}var Fs,T0;function Xb(){if(T0)return Fs;T0=1;function t(e){const a="[a-z][a-zA-Z0-9_]*",o={className:"string",begin:"\\$.{1}"},c={className:"symbol",begin:"#"+e.UNDERSCORE_IDENT_RE};return{name:"Smalltalk",aliases:["st"],keywords:["self","super","nil","true","false","thisContext"],contains:[e.COMMENT('"','"'),e.APOS_STRING_MODE,{className:"type",begin:"\\b[A-Z][A-Za-z0-9_]*",relevance:0},{begin:a+":",relevance:0},e.C_NUMBER_MODE,c,o,{begin:"\\|[ ]*"+a+"([ ]+"+a+")*[ ]*\\|",returnBegin:!0,end:/\|/,illegal:/\S/,contains:[{begin:"(\\|[ ]*)?"+a}]},{begin:"#\\(",end:"\\)",contains:[e.APOS_STRING_MODE,o,e.C_NUMBER_MODE,c]}]}}return Fs=t,Fs}var Bs,C0;function Zb(){if(C0)return Bs;C0=1;function t(e){return{name:"SML (Standard ML)",aliases:["ml"],keywords:{$pattern:"[a-z_]\\w*!?",keyword:"abstype and andalso as case datatype do else end eqtype exception fn fun functor handle if in include infix infixr let local nonfix of op open orelse raise rec sharing sig signature struct structure then type val with withtype where while",built_in:"array bool char exn int list option order real ref string substring vector unit word",literal:"true false NONE SOME LESS EQUAL GREATER nil"},illegal:/\/\/|>>/,contains:[{className:"literal",begin:/\[(\|\|)?\]|\(\)/,relevance:0},e.COMMENT("\\(\\*","\\*\\)",{contains:["self"]}),{className:"symbol",begin:"'[A-Za-z_](?!')[\\w']*"},{className:"type",begin:"`[A-Z][\\w']*"},{className:"type",begin:"\\b[A-Z][\\w']*",relevance:0},{begin:"[a-z_]\\w*'[\\w']*"},e.inherit(e.APOS_STRING_MODE,{className:"string",relevance:0}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null}),{className:"number",begin:"\\b(0[xX][a-fA-F0-9_]+[Lln]?|0[oO][0-7_]+[Lln]?|0[bB][01_]+[Lln]?|[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)",relevance:0},{begin:/[-=]>/}]}}return Bs=t,Bs}var Us,R0;function Jb(){if(R0)return Us;R0=1;function t(e){const a={className:"variable",begin:/\b_+[a-zA-Z]\w*/},o={className:"title",begin:/[a-zA-Z][a-zA-Z_0-9]*_fnc_[a-zA-Z_0-9]+/},c={className:"string",variants:[{begin:'"',end:'"',contains:[{begin:'""',relevance:0}]},{begin:"'",end:"'",contains:[{begin:"''",relevance:0}]}]},s=["break","breakWith","breakOut","breakTo","case","catch","continue","continueWith","default","do","else","exit","exitWith","for","forEach","from","if","local","private","switch","step","then","throw","to","try","waitUntil","while","with"],d=["blufor","civilian","configNull","controlNull","displayNull","diaryRecordNull","east","endl","false","grpNull","independent","lineBreak","locationNull","nil","objNull","opfor","pi","resistance","scriptNull","sideAmbientLife","sideEmpty","sideEnemy","sideFriendly","sideLogic","sideUnknown","taskNull","teamMemberNull","true","west"],u=["abs","accTime","acos","action","actionIDs","actionKeys","actionKeysEx","actionKeysImages","actionKeysNames","actionKeysNamesArray","actionName","actionParams","activateAddons","activatedAddons","activateKey","activeTitleEffectParams","add3DENConnection","add3DENEventHandler","add3DENLayer","addAction","addBackpack","addBackpackCargo","addBackpackCargoGlobal","addBackpackGlobal","addBinocularItem","addCamShake","addCuratorAddons","addCuratorCameraArea","addCuratorEditableObjects","addCuratorEditingArea","addCuratorPoints","addEditorObject","addEventHandler","addForce","addForceGeneratorRTD","addGoggles","addGroupIcon","addHandgunItem","addHeadgear","addItem","addItemCargo","addItemCargoGlobal","addItemPool","addItemToBackpack","addItemToUniform","addItemToVest","addLiveStats","addMagazine","addMagazineAmmoCargo","addMagazineCargo","addMagazineCargoGlobal","addMagazineGlobal","addMagazinePool","addMagazines","addMagazineTurret","addMenu","addMenuItem","addMissionEventHandler","addMPEventHandler","addMusicEventHandler","addonFiles","addOwnedMine","addPlayerScores","addPrimaryWeaponItem","addPublicVariableEventHandler","addRating","addResources","addScore","addScoreSide","addSecondaryWeaponItem","addSwitchableUnit","addTeamMember","addToRemainsCollector","addTorque","addUniform","addUserActionEventHandler","addVehicle","addVest","addWaypoint","addWeapon","addWeaponCargo","addWeaponCargoGlobal","addWeaponGlobal","addWeaponItem","addWeaponPool","addWeaponTurret","addWeaponWithAttachmentsCargo","addWeaponWithAttachmentsCargoGlobal","admin","agent","agents","AGLToASL","aimedAtTarget","aimPos","airDensityCurveRTD","airDensityRTD","airplaneThrottle","airportSide","AISFinishHeal","alive","all3DENEntities","allActiveTitleEffects","allAddonsInfo","allAirports","allControls","allCurators","allCutLayers","allDead","allDeadMen","allDiaryRecords","allDiarySubjects","allDisplays","allEnv3DSoundSources","allGroups","allLODs","allMapMarkers","allMines","allMissionObjects","allObjects","allow3DMode","allowCrewInImmobile","allowCuratorLogicIgnoreAreas","allowDamage","allowDammage","allowedService","allowFileOperations","allowFleeing","allowGetIn","allowService","allowSprint","allPlayers","allSimpleObjects","allSitesLine truncated
|
||||
]*?"'`},{begin:`"[^\r
|
||||
"]*"`}]},{className:"built_in",variants:[{begin:"\\b(abs|acos|asin|atan|atan2|atanh|ceil|cloglog|comb|cos|digamma|exp|floor|invcloglog|invlogit|ln|lnfact|lnfactorial|lngamma|log|log10|max|min|mod|reldif|round|sign|sin|sqrt|sum|tan|tanh|trigamma|trunc|betaden|Binomial|binorm|binormal|chi2|chi2tail|dgammapda|dgammapdada|dgammapdadx|dgammapdx|dgammapdxdx|F|Fden|Ftail|gammaden|gammap|ibeta|invbinomial|invchi2|invchi2tail|invF|invFtail|invgammap|invibeta|invnchi2|invnFtail|invnibeta|invnorm|invnormal|invttail|nbetaden|nchi2|nFden|nFtail|nibeta|norm|normal|normalden|normd|npnchi2|tden|ttail|uniform|abbrev|char|index|indexnot|length|lower|ltrim|match|plural|proper|real|regexm|regexr|regexs|reverse|rtrim|string|strlen|strlower|strltrim|strmatch|strofreal|strpos|strproper|strreverse|strrtrim|strtrim|strupper|subinstr|subinword|substr|trim|upper|word|wordcount|_caller|autocode|byteorder|chop|clip|cond|e|epsdouble|epsfloat|group|inlist|inrange|irecode|matrix|maxbyte|maxdouble|maxfloat|maxint|maxlong|mi|minbyte|mindouble|minfloat|minint|minlong|missing|r|recode|replay|return|s|scalar|d|date|day|dow|doy|halfyear|mdy|month|quarter|week|year|d|daily|dofd|dofh|dofm|dofq|dofw|dofy|h|halfyearly|hofd|m|mofd|monthly|q|qofd|quarterly|tin|twithin|w|weekly|wofd|y|yearly|yh|ym|yofd|yq|yw|cholesky|colnumb|colsof|corr|det|diag|diag0cnt|el|get|hadamard|I|inv|invsym|issym|issymmetric|J|matmissing|matuniform|mreldif|nullmat|rownumb|rowsof|sweep|syminv|trace|vec|vecdiag)(?=\\()"}]},e.COMMENT("^[ ]*\\*.*$",!1),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]}}return qs=t,qs}var zs,A0;function nh(){if(A0)return zs;A0=1;function t(e){return{name:"STEP Part 21",aliases:["p21","step","stp"],case_insensitive:!0,keywords:{$pattern:"[A-Z_][A-Z0-9_.]*",keyword:["HEADER","ENDSEC","DATA"]},contains:[{className:"meta",begin:"ISO-10303-21;",relevance:10},{className:"meta",begin:"END-ISO-10303-21;",relevance:10},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.COMMENT("/\\*\\*!","\\*/"),e.C_NUMBER_MODE,e.inherit(e.APOS_STRING_MODE,{illegal:null}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null}),{className:"string",begin:"'",end:"'"},{className:"symbol",variants:[{begin:"#",end:"\\d+",illegal:"\\W"}]}]}}return zs=t,zs}var Hs,v0;function rh(){if(v0)return Hs;v0=1;const t=p=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:p.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[p.APOS_STRING_MODE,p.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:p.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),e=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],a=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],o=[...e,...a],c=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),s=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-wLine truncated
|
||||
(multipart)?`,end:`\\]
|
||||
`},{className:"string",begin:"\\d{4}-\\d{2}-\\d{2}(\\s+)\\d{2}:\\d{2}:\\d{2}.\\d+Z"},{className:"string",begin:"(\\+|-)\\d+"},{className:"keyword",relevance:10,variants:[{begin:"^(test|testing|success|successful|failure|error|skip|xfail|uxsuccess)(:?)\\s+(test)?"},{begin:"^progress(:?)(\\s+)?(pop|push)?"},{begin:"^tags:"},{begin:"^time:"}]}]}}return Vs=t,Vs}var Ws,D0;function ih(){if(D0)return Ws;D0=1;function t(V){return V?typeof V=="string"?V:V.source:null}function e(V){return a("(?=",V,")")}function a(...V){return V.map(ce=>t(ce)).join("")}function o(V){const ee=V[V.length-1];return typeof ee=="object"&&ee.constructor===Object?(V.splice(V.length-1,1),ee):{}}function c(...V){return"("+(o(V).capture?"":"?:")+V.map(ne=>t(ne)).join("|")+")"}const s=V=>a(/\b/,V,/\w$/.test(V)?/\b/:/\B/),d=["Protocol","Type"].map(s),u=["init","self"].map(s),_=["Any","Self"],p=["actor","any","associatedtype","async","await",/as\?/,/as!/,"as","borrowing","break","case","catch","class","consume","consuming","continue","convenience","copy","default","defer","deinit","didSet","distributed","do","dynamic","each","else","enum","extension","fallthrough",/fileprivate\(set\)/,"fileprivate","final","for","func","get","guard","if","import","indirect","infix",/init\?/,/init!/,"inout",/internal\(set\)/,"internal","in","is","isolated","nonisolated","lazy","let","macro","mutating","nonmutating",/open\(set\)/,"open","operator","optional","override","package","postfix","precedencegroup","prefix",/private\(set\)/,"private","protocol",/public\(set\)/,"public","repeat","required","rethrows","return","set","some","static","struct","subscript","super","switch","throws","throw",/try\?/,/try!/,"try","typealias",/unowned\(safe\)/,/unowned\(unsafe\)/,"unowned","var","weak","where","while","willSet"],S=["false","nil","true"],h=["assignment","associativity","higherThan","left","lowerThan","none","right"],y=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","#imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warning"],O=["abs","all","any","assert","assertionFailure","debugPrint","dump","fatalError","getVaList","isKnownUniquelyReferenced","max","min","numericCast","pointwiseMax","pointwiseMin","precondition","preconditionFailure","print","readLine","repeatElement","sequence","stride","swap","swift_unboxFromSwiftValueWithType","transcode","type","unsafeBitCast","unsafeDowncast","withExtendedLifetime","withUnsafeMutablePointer","withUnsafePointer","withVaList","withoutActuallyEscaping","zip"],N=c(/[/=\-+!*%<>&|^~?]/,/[\u00A1-\u00A7]/,/[\u00A9\u00AB]/,/[\u00AC\u00AE]/,/[\u00B0\u00B1]/,/[\u00B6\u00BB\u00BF\u00D7\u00F7]/,/[\u2016-\u2017]/,/[\u2020-\u2027]/,/[\u2030-\u203E]/,/[\u2041-\u2053]/,/[\u2055-\u205E]/,/[\u2190-\u23FF]/,/[\u2500-\u2775]/,/[\u2794-\u2BFF]/,/[\u2E00-\u2E7F]/,/[\u3001-\u3003]/,/[\u3008-\u3020]/,/[\u3030]/),w=c(N,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,/[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),L=a(N,w,"*"),D=c(/[a-zA-Z_]/,/[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,/[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,/[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,/[\u1E00-\u1FFF]/,/[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,/[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,/[\u2C00-\u2DFF\u2E80-\u2FFF]/,/[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,/[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,/[\uFE47-\uFEFE\uFF00-\uFFFD]/),U=c(D,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),x=a(D,U,"*"),G=a(/[A-Z]/,U,"*"),F=["attached","autoclosure",a(/convention\(/,c("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","freestanding","frozen","GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",a(/objc\(/,x,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","Sendable","testable","UIApplicationMain","unchecked","unknown","usableFromInline","warn_unqualified_access"],z=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCatalystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"];function $(V){const ee={match:/\s+/,relevance:0},ce=V.COMMENT("/\\*","\\*/",{contains:["self"]}),ne=[V.C_LINE_COMMENT_MODE,ce],me={match:[/\./,c(...d,...u)],className:{2:"keyword"}},pe={match:a(/\./,c(...p)),relevance:0},be=p.filter(ke=>typeof ke=="string").concat(["_|0"]),fe=p.filter(ke=>typeof ke!="string").concat(_).map(s),W={variants:[{className:"keyword",match:c(...fe,...u)}]},te={$pattern:c(/\b\w+/,/#\w+/),keyword:be.concat(y),literal:S},ue=[me,pe,W],he={match:a(/\./,c(...O)),relevance:0},Ae={className:"built_in",match:a(/\b/,c(...O),/(?=\()/)},re=[he,Ae],Xe={match:/->/,relevance:0},st={className:"operatLine truncated
|
||||
`," "],Bh=["{","}","|","\\","^","`"].concat(Fh),Uh=["'"].concat(Bh),tm=["%","/","?",";","#"].concat(Uh),nm=["/","?","#"],Gh=255,rm=/^[+a-z0-9A-Z_-]{0,63}$/,Yh=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,am={javascript:!0,"javascript:":!0},im={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0};function wl(t,e){if(t&&t instanceof Br)return t;const a=new Br;return a.parse(t,e),a}Br.prototype.parse=function(t,e){let a,o,c,s=t;if(s=s.trim(),!e&&t.split("#").length===1){const p=Ph.exec(s);if(p)return this.pathname=p[1],p[2]&&(this.search=p[2]),this}let d=Lh.exec(s);if(d&&(d=d[0],a=d.toLowerCase(),this.protocol=d,s=s.substr(d.length)),(e||d||s.match(/^\/\/[^@\/]+@[^@\/]+/))&&(c=s.substr(0,2)==="//",c&&!(d&&am[d])&&(s=s.substr(2),this.slashes=!0)),!am[d]&&(c||d&&!im[d])){let p=-1;for(let N=0;N<nm.length;N++)o=s.indexOf(nm[N]),o!==-1&&(p===-1||o<p)&&(p=o);let S,h;p===-1?h=s.lastIndexOf("@"):h=s.lastIndexOf("@",p),h!==-1&&(S=s.slice(0,h),s=s.slice(h+1),this.auth=S),p=-1;for(let N=0;N<tm.length;N++)o=s.indexOf(tm[N]),o!==-1&&(p===-1||o<p)&&(p=o);p===-1&&(p=s.length),s[p-1]===":"&&p--;const y=s.slice(0,p);s=s.slice(p),this.parseHost(y),this.hostname=this.hostname||"";const O=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!O){const N=this.hostname.split(/\./);for(let w=0,L=N.length;w<L;w++){const D=N[w];if(D&&!D.match(rm)){let U="";for(let x=0,G=D.length;x<G;x++)D.charCodeAt(x)>127?U+="x":U+=D[x];if(!U.match(rm)){const x=N.slice(0,w),G=N.slice(w+1),F=D.match(Yh);F&&(x.push(F[1]),G.unshift(F[2])),G.length&&(s=G.join(".")+s),this.hostname=x.join(".");break}}}}this.hostname.length>Gh&&(this.hostname=""),O&&(this.hostname=this.hostname.substr(1,this.hostname.length-2))}const u=s.indexOf("#");u!==-1&&(this.hash=s.substr(u),s=s.slice(0,u));const _=s.indexOf("?");return _!==-1&&(this.search=s.substr(_),s=s.slice(0,_)),s&&(this.pathname=s),im[a]&&this.hostname&&!this.pathname&&(this.pathname=""),this};Br.prototype.parseHost=function(t){let e=kh.exec(t);e&&(e=e[0],e!==":"&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)};const qh=Object.freeze(Object.defineProperty({__proto__:null,decode:Vn,encode:_r,format:Ml,parse:wl},Symbol.toStringTag,{value:"Module"})),Ym=/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,qm=/[\0-\x1F\x7F-\x9F]/,zh=/[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/,Ll=/[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/,zm=/[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFALine truncated
|
||||
`};rn.fence=function(t,e,a,o,c){const s=t[e],d=s.info?Wn(s.info).trim():"";let u="",_="";if(d){const S=d.split(/(\s+)/g);u=S[0],_=S.slice(2).join("")}let p;if(a.highlight?p=a.highlight(s.content,u,_)||On(s.content):p=On(s.content),p.indexOf("<pre")===0)return p+`
|
||||
`;if(d){const S=s.attrIndex("class"),h=s.attrs?s.attrs.slice():[];S<0?h.push(["class",a.langPrefix+u]):(h[S]=h[S].slice(),h[S][1]+=" "+a.langPrefix+u);const y={attrs:h};return`<pre><code${c.renderAttrs(y)}>${p}</code></pre>
|
||||
`}return`<pre><code${c.renderAttrs(s)}>${p}</code></pre>
|
||||
`};rn.image=function(t,e,a,o,c){const s=t[e];return s.attrs[s.attrIndex("alt")][1]=c.renderInlineAsText(s.children,a,o),c.renderToken(t,e,a)};rn.hardbreak=function(t,e,a){return a.xhtmlOut?`<br />
|
||||
`:`<br>
|
||||
`};rn.softbreak=function(t,e,a){return a.breaks?a.xhtmlOut?`<br />
|
||||
`:`<br>
|
||||
`:`
|
||||
`};rn.text=function(t,e){return On(t[e].content)};rn.html_block=function(t,e){return t[e].content};rn.html_inline=function(t,e){return t[e].content};function $n(){this.rules=qr({},rn)}$n.prototype.renderAttrs=function(e){let a,o,c;if(!e.attrs)return"";for(c="",a=0,o=e.attrs.length;a<o;a++)c+=" "+On(e.attrs[a][0])+'="'+On(e.attrs[a][1])+'"';return c};$n.prototype.renderToken=function(e,a,o){const c=e[a];let s="";if(c.hidden)return"";c.block&&c.nesting!==-1&&a&&e[a-1].hidden&&(s+=`
|
||||
`),s+=(c.nesting===-1?"</":"<")+c.tag,s+=this.renderAttrs(c),c.nesting===0&&o.xhtmlOut&&(s+=" /");let d=!1;if(c.block&&(d=!0,c.nesting===1&&a+1<e.length)){const u=e[a+1];(u.type==="inline"||u.hidden||u.nesting===-1&&u.tag===c.tag)&&(d=!1)}return s+=d?`>
|
||||
`:">",s};$n.prototype.renderInline=function(t,e,a){let o="";const c=this.rules;for(let s=0,d=t.length;s<d;s++){const u=t[s].type;typeof c[u]<"u"?o+=c[u](t,s,e,a,this):o+=this.renderToken(t,s,e)}return o};$n.prototype.renderInlineAsText=function(t,e,a){let o="";for(let c=0,s=t.length;c<s;c++)switch(t[c].type){case"text":o+=t[c].content;break;case"image":o+=this.renderInlineAsText(t[c].children,e,a);break;case"html_inline":case"html_block":o+=t[c].content;break;case"softbreak":case"hardbreak":o+=`
|
||||
`;break}return o};$n.prototype.render=function(t,e,a){let o="";const c=this.rules;for(let s=0,d=t.length;s<d;s++){const u=t[s].type;u==="inline"?o+=this.renderInline(t[s].children,e,a):typeof c[u]<"u"?o+=c[u](t,s,e,a,this):o+=this.renderToken(t,s,e,a)}return o};function Ot(){this.__rules__=[],this.__cache__=null}Ot.prototype.__find__=function(t){for(let e=0;e<this.__rules__.length;e++)if(this.__rules__[e].name===t)return e;return-1};Ot.prototype.__compile__=function(){const t=this,e=[""];t.__rules__.forEach(function(a){a.enabled&&a.alt.forEach(function(o){e.indexOf(o)<0&&e.push(o)})}),t.__cache__={},e.forEach(function(a){t.__cache__[a]=[],t.__rules__.forEach(function(o){o.enabled&&(a&&o.alt.indexOf(a)<0||t.__cache__[a].push(o.fn))})})};Ot.prototype.at=function(t,e,a){const o=this.__find__(t),c=a||{};if(o===-1)throw new Error("Parser rule not found: "+t);this.__rules__[o].fn=e,this.__rules__[o].alt=c.alt||[],this.__cache__=null};Ot.prototype.before=function(t,e,a,o){const c=this.__find__(t),s=o||{};if(c===-1)throw new Error("Parser rule not found: "+t);this.__rules__.splice(c,0,{name:e,enabled:!0,fn:a,alt:s.alt||[]}),this.__cache__=null};Ot.prototype.after=function(t,e,a,o){const c=this.__find__(t),s=o||{};if(c===-1)throw new Error("Parser rule not found: "+t);this.__rules__.splice(c+1,0,{name:e,enabled:!0,fn:a,alt:s.alt||[]}),this.__cache__=null};Ot.prototype.push=function(t,e,a){const o=a||{};this.__rules__.push({name:t,enabled:!0,fn:e,alt:o.alt||[]}),this.__cache__=null};Ot.prototype.enable=function(t,e){Array.isArray(t)||(t=[t]);const a=[];return t.forEach(function(o){const c=this.__find__(o);if(c<0){if(e)return;throw new Error("Rules manager: invalid rule name "+o)}this.__rules__[c].enabled=!0,a.push(o)},this),this.__cache__=null,a};Ot.prototype.enableOnly=function(t,e){Array.isArray(t)||(t=[t]),this.__rules__.forEach(function(a){a.enabled=!1}),this.enable(t,e)};Ot.prototype.disable=function(t,e){Array.isArray(t)||(t=[t]);const a=[];return t.forEach(function(o){const c=this.__find__(o);if(c<0){if(e)return;throw new Error("Rules manager: invalid rule name "+o)}this.__rules__[c].enabled=!1,a.push(o)},this),this.__cache__=null,a};Ot.prototype.getRules=function(t){return this.__cache__===null&&this.__compile__(),this.__cache__[t]||[]};function zt(t,e,a){this.type=t,this.tag=e,this.attrs=null,this.map=null,this.nesting=a,this.level=0,this.children=null,this.content="",this.markup="",this.info="",this.meta=null,this.block=!1,this.hidden=!1}zt.prototype.attrIndex=function(e){if(!this.attrs)return-1;const a=this.attrs;for(let o=0,c=a.length;o<c;o++)if(a[o][0]===e)return o;return-1};zt.prototype.attrPush=function(e){this.attrs?this.attrs.push(e):this.attrs=[e]};zt.prototype.attrSet=function(e,a){const o=this.attrIndex(e),c=[e,a];o<0?this.attrPush(c):this.attrs[o]=c};zt.prototype.attrGet=function(e){const a=this.attrIndex(e);let o=null;return a>=0&&(o=this.attrs[a][1]),o};zt.prototype.attrJoin=function(e,a){const o=this.attrIndex(e);o<0?this.attrPush([e,a]):this.attrs[o][1]=this.attrs[o][1]+" "+a};function Qm(t,e,a){this.src=t,this.env=a,this.tokens=[],this.inlineMode=!1,this.md=e}Qm.prototype.Token=zt;const R1=/\r\n?|\n/g,N1=/\0/g;function y1(t){let e;e=t.src.replace(R1,`
|
||||
`),e=e.replace(N1,"�"),t.src=e}function O1(t){let e;t.inlineMode?(e=new t.Token("inline","",0),e.content=t.src,e.map=[0,1],e.children=[],t.tokens.push(e)):t.md.block.parse(t.src,t.md,t.env,t.tokens)}function A1(t){const e=t.tokens;for(let a=0,o=e.length;a<o;a++){const c=e[a];c.type==="inline"&&t.md.inline.parse(c.content,t.md,t.env,c.children)}}function v1(t){return/^<a[>\s]/i.test(t)}function I1(t){return/^<\/a\s*>/i.test(t)}function D1(t){const e=t.tokens;if(t.md.options.linkify)for(let a=0,o=e.length;a<o;a++){if(e[a].type!=="inline"||!t.md.linkify.pretest(e[a].content))continue;let c=e[a].children,s=0;for(let d=c.length-1;d>=0;d--){const u=c[d];if(u.type==="link_close"){for(d--;c[d].level!==u.level&&c[d].type!=="link_open";)d--;continue}if(u.type==="html_inline"&&(v1(u.content)&&s>0&&s--,I1(u.content)&&s++),!(s>0)&&u.type==="text"&&t.md.linkify.test(u.content)){const _=u.content;let p=t.md.linkify.match(_);const S=[];let h=u.level,y=0;p.length>0&&p[0].index===0&&d>0&&c[d-1].type==="text_special"&&(p=p.slice(1));for(let O=0;O<p.length;O++){const N=p[O].url,w=t.md.normalizeLink(N);if(!t.md.validateLink(w))continue;let L=p[O].text;p[O].schema?p[O].schema==="mailto:"&&!/^mailto:/i.test(L)?L=t.md.normalizeLinkText("mailto:"+L).replace(/^mailto:/,""):L=t.md.normalizeLinkText(L):L=t.md.normalizeLinkText("http://"+L).replace(/^http:\/\//,"");const D=p[O].index;if(D>y){const F=new t.Token("text","",0);F.content=_.slice(y,D),F.level=h,S.push(F)}const U=new t.Token("link_open","a",1);U.attrs=[["href",w]],U.level=h++,U.markup="linkify",U.info="auto",S.push(U);const x=new t.Token("text","",0);x.content=L,x.level=h,S.push(x);const G=new t.Token("link_close","a",-1);G.level=--h,G.markup="linkify",G.info="auto",S.push(G),y=p[O].lastIndex}if(y<_.length){const O=new t.Token("text","",0);O.content=_.slice(y),O.level=h,S.push(O)}e[a].children=c=$m(c,d,S)}}}}const Xm=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,x1=/\((c|tm|r)\)/i,M1=/\((c|tm|r)\)/ig,w1={c:"©",r:"®",tm:"™"};function L1(t,e){return w1[e.toLowerCase()]}function k1(t){let e=0;for(let a=t.length-1;a>=0;a--){const o=t[a];o.type==="text"&&!e&&(o.content=o.content.replace(M1,L1)),o.type==="link_open"&&o.info==="auto"&&e--,o.type==="link_close"&&o.info==="auto"&&e++}}function P1(t){let e=0;for(let a=t.length-1;a>=0;a--){const o=t[a];o.type==="text"&&!e&&Xm.test(o.content)&&(o.content=o.content.replace(/\+-/g,"±").replace(/\.{2,}/g,"…").replace(/([?!])…/g,"$1..").replace(/([?!]){4,}/g,"$1$1$1").replace(/,{2,}/g,",").replace(/(^|[^-])---(?=[^-]|$)/mg,"$1—").replace(/(^|\s)--(?=\s|$)/mg,"$1–").replace(/(^|[^-\s])--(?=[^-\s]|$)/mg,"$1–")),o.type==="link_open"&&o.info==="auto"&&e--,o.type==="link_close"&&o.info==="auto"&&e++}}function F1(t){let e;if(t.md.options.typographer)for(e=t.tokens.length-1;e>=0;e--)t.tokens[e].type==="inline"&&(x1.test(t.tokens[e].content)&&k1(t.tokens[e].children),Xm.test(t.tokens[e].content)&&P1(t.tokens[e].children))}const B1=/['"]/,om=/['"]/g,sm="’";function Lr(t,e,a){return t.slice(0,e)+a+t.slice(e+1)}function U1(t,e){let a;const o=[];for(let c=0;c<t.length;c++){const s=t[c],d=t[c].level;for(a=o.length-1;a>=0&&!(o[a].level<=d);a--);if(o.length=a+1,s.type!=="text")continue;let u=s.content,_=0,p=u.length;e:for(;_<p;){om.lastIndex=_;const S=om.exec(u);if(!S)break;let h=!0,y=!0;_=S.index+1;const O=S[0]==="'";let N=32;if(S.index-1>=0)N=u.charCodeAt(S.index-1);else for(a=c-1;a>=0&&!(t[a].type==="softbreak"||t[a].type==="hardbreak");a--)if(t[a].content){N=t[a].content.charCodeAt(t[a].content.length-1);break}let w=32;if(_<p)w=u.charCodeAt(_);else for(a=c+1;a<t.length&&!(t[a].type==="softbreak"||t[a].type==="hardbreak");a++)if(t[a].content){w=t[a].content.charCodeAt(0);break}const L=ur(N)||cr(String.fromCharCode(N)),D=ur(w)||cr(String.fromCharCode(w)),U=lr(N),x=lr(w);if(x?h=!1:D&&(U||L||(h=!1)),U?y=!1:L&&(x||D||(y=!1)),w===34&&S[0]==='"'&&N>=48&&N<=57&&(y=h=!1),h&&y&&(h=L,y=D),!h&&!y){O&&(s.content=Lr(s.content,S.index,sm));continue}if(y)for(a=o.length-1;a>=0;a--){let G=o[a];if(o[a].level<d)break;if(G.single===O&&o[a].level===d){G=o[a];let F,z;O?(F=e.md.options.quotes[2],z=e.md.options.quotes[3]):(F=e.md.options.quotes[0],z=e.md.options.quotes[1]),s.content=Lr(s.content,S.index,z),t[G.token].content=Lr(t[G.token].content,G.pos,F),_+=z.length-1,G.token===c&&(_+=F.length-1),u=s.content,p=u.length,o.length=a;continue e}}h?o.push({token:c,pos:S.index,single:O,level:d}):y&&O&&(s.content=Lr(s.content,S.index,sm))}}}function G1(t){if(t.md.options.typographer)for(let e=t.tokens.length-1;e>=0;e--)t.tokens[e].type!=="inline"||!B1.test(t.tokens[e].content)||U1(t.tokens[e].children,t)}function Y1(t){let e,a;const o=t.tokens,c=o.length;for(let s=0;s<c;s++){if(o[s].type!=="inline")continue;const d=o[s].children,u=d.length;for(e=0;e<u;e++)d[e].type==="text_special"&&(d[e].type="text");for(e=a=0;e<u;e++)d[e].type==="text"&&e+1<u&&d[e+1].type==="text"?d[e+1].content=d[e].content+d[e+1].content:(e!==a&&(d[a]=d[e]),a++);e!==a&&(d.length=a)}}const gl=[["normalize",Line truncated
|
||||
`,s.map=[e,t.line],!0}function V1(t,e,a,o){let c=t.bMarks[e]+t.tShift[e],s=t.eMarks[e];if(t.sCount[e]-t.blkIndent>=4||c+3>s)return!1;const d=t.src.charCodeAt(c);if(d!==126&&d!==96)return!1;let u=c;c=t.skipChars(c,d);let _=c-u;if(_<3)return!1;const p=t.src.slice(u,c),S=t.src.slice(c,s);if(d===96&&S.indexOf(String.fromCharCode(d))>=0)return!1;if(o)return!0;let h=e,y=!1;for(;h++,!(h>=a||(c=u=t.bMarks[h]+t.tShift[h],s=t.eMarks[h],c<s&&t.sCount[h]<t.blkIndent));)if(t.src.charCodeAt(c)===d&&!(t.sCount[h]-t.blkIndent>=4)&&(c=t.skipChars(c,d),!(c-u<_)&&(c=t.skipSpaces(c),!(c<s)))){y=!0;break}_=t.sCount[e],t.line=h+(y?1:0);const O=t.push("fence","code",0);return O.info=S,O.content=t.getLines(e+1,h,_,!0),O.markup=p,O.map=[e,t.line],!0}function W1(t,e,a,o){let c=t.bMarks[e]+t.tShift[e],s=t.eMarks[e];const d=t.lineMax;if(t.sCount[e]-t.blkIndent>=4||t.src.charCodeAt(c)!==62)return!1;if(o)return!0;const u=[],_=[],p=[],S=[],h=t.md.block.ruler.getRules("blockquote"),y=t.parentType;t.parentType="blockquote";let O=!1,N;for(N=e;N<a;N++){const x=t.sCount[N]<t.blkIndent;if(c=t.bMarks[N]+t.tShift[N],s=t.eMarks[N],c>=s)break;if(t.src.charCodeAt(c++)===62&&!x){let F=t.sCount[N]+1,z,$;t.src.charCodeAt(c)===32?(c++,F++,$=!1,z=!0):t.src.charCodeAt(c)===9?(z=!0,(t.bsCount[N]+F)%4===3?(c++,F++,$=!1):$=!0):z=!1;let V=F;for(u.push(t.bMarks[N]),t.bMarks[N]=c;c<s;){const ee=t.src.charCodeAt(c);if(He(ee))ee===9?V+=4-(V+t.bsCount[N]+($?1:0))%4:V++;else break;c++}O=c>=s,_.push(t.bsCount[N]),t.bsCount[N]=t.sCount[N]+1+(z?1:0),p.push(t.sCount[N]),t.sCount[N]=V-F,S.push(t.tShift[N]),t.tShift[N]=c-t.bMarks[N];continue}if(O)break;let G=!1;for(let F=0,z=h.length;F<z;F++)if(h[F](t,N,a,!0)){G=!0;break}if(G){t.lineMax=N,t.blkIndent!==0&&(u.push(t.bMarks[N]),_.push(t.bsCount[N]),S.push(t.tShift[N]),p.push(t.sCount[N]),t.sCount[N]-=t.blkIndent);break}u.push(t.bMarks[N]),_.push(t.bsCount[N]),S.push(t.tShift[N]),p.push(t.sCount[N]),t.sCount[N]=-1}const w=t.blkIndent;t.blkIndent=0;const L=t.push("blockquote_open","blockquote",1);L.markup=">";const D=[e,0];L.map=D,t.md.block.tokenize(t,e,N);const U=t.push("blockquote_close","blockquote",-1);U.markup=">",t.lineMax=d,t.parentType=y,D[1]=t.line;for(let x=0;x<S.length;x++)t.bMarks[x+e]=u[x],t.tShift[x+e]=S[x],t.sCount[x+e]=p[x],t.bsCount[x+e]=_[x];return t.blkIndent=w,!0}function $1(t,e,a,o){const c=t.eMarks[e];if(t.sCount[e]-t.blkIndent>=4)return!1;let s=t.bMarks[e]+t.tShift[e];const d=t.src.charCodeAt(s++);if(d!==42&&d!==45&&d!==95)return!1;let u=1;for(;s<c;){const p=t.src.charCodeAt(s++);if(p!==d&&!He(p))return!1;p===d&&u++}if(u<3)return!1;if(o)return!0;t.line=e+1;const _=t.push("hr","hr",0);return _.map=[e,t.line],_.markup=Array(u+1).join(String.fromCharCode(d)),!0}function cm(t,e){const a=t.eMarks[e];let o=t.bMarks[e]+t.tShift[e];const c=t.src.charCodeAt(o++);if(c!==42&&c!==45&&c!==43)return-1;if(o<a){const s=t.src.charCodeAt(o);if(!He(s))return-1}return o}function um(t,e){const a=t.bMarks[e]+t.tShift[e],o=t.eMarks[e];let c=a;if(c+1>=o)return-1;let s=t.src.charCodeAt(c++);if(s<48||s>57)return-1;for(;;){if(c>=o)return-1;if(s=t.src.charCodeAt(c++),s>=48&&s<=57){if(c-a>=10)return-1;continue}if(s===41||s===46)break;return-1}return c<o&&(s=t.src.charCodeAt(c),!He(s))?-1:c}function K1(t,e){const a=t.level+2;for(let o=e+2,c=t.tokens.length-2;o<c;o++)t.tokens[o].level===a&&t.tokens[o].type==="paragraph_open"&&(t.tokens[o+2].hidden=!0,t.tokens[o].hidden=!0,o+=2)}function Q1(t,e,a,o){let c,s,d,u,_=e,p=!0;if(t.sCount[_]-t.blkIndent>=4||t.listIndent>=0&&t.sCount[_]-t.listIndent>=4&&t.sCount[_]<t.blkIndent)return!1;let S=!1;o&&t.parentType==="paragraph"&&t.sCount[_]>=t.blkIndent&&(S=!0);let h,y,O;if((O=um(t,_))>=0){if(h=!0,d=t.bMarks[_]+t.tShift[_],y=Number(t.src.slice(d,O-1)),S&&y!==1)return!1}else if((O=cm(t,_))>=0)h=!1;else return!1;if(S&&t.skipSpaces(O)>=t.eMarks[_])return!1;if(o)return!0;const N=t.src.charCodeAt(O-1),w=t.tokens.length;h?(u=t.push("ordered_list_open","ol",1),y!==1&&(u.attrs=[["start",y]])):u=t.push("bullet_list_open","ul",1);const L=[_,0];u.map=L,u.markup=String.fromCharCode(N);let D=!1;const U=t.md.block.ruler.getRules("list"),x=t.parentType;for(t.parentType="list";_<a;){s=O,c=t.eMarks[_];const G=t.sCount[_]+O-(t.bMarks[_]+t.tShift[_]);let F=G;for(;s<c;){const fe=t.src.charCodeAt(s);if(fe===9)F+=4-(F+t.bsCount[_])%4;else if(fe===32)F++;else break;s++}const z=s;let $;z>=c?$=1:$=F-G,$>4&&($=1);const V=G+$;u=t.push("list_item_open","li",1),u.markup=String.fromCharCode(N);const ee=[_,0];u.map=ee,h&&(u.info=t.src.slice(d,O-1));const ce=t.tight,ne=t.tShift[_],me=t.sCount[_],pe=t.listIndent;if(t.listIndent=t.blkIndent,t.blkIndent=V,t.tight=!0,t.tShift[_]=z-t.bMarks[_],t.sCount[_]=F,z>=c&&t.isEmpty(_+1)?t.line=Math.min(t.line+2,a):t.md.block.tokenize(t,_,a,!0),(!t.tight||D)&&(p=!1),D=t.line-_>1&&t.isEmpty(t.line-1),t.blkIndent=t.listIndent,t.listIndent=pe,t.tShift[_]=ne,t.sCount[_]=me,t.tight=ce,u=t.push("list_item_close","li",-1),u.markup=String.fromCharCode(N),_=t.line,ee[1]=_,_>=a||t.sCount[_]<t.blkInLine truncated
|
||||
c-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14
|
||||
c0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54
|
||||
c44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10
|
||||
s173,378,173,378c0.7,0,35.3,-71,104,-213c68.7,-142,137.5,-285,206.5,-429
|
||||
c69,-144,104.5,-217.7,106.5,-221
|
||||
l`+r/2.075+" -"+r+`
|
||||
c5.3,-9.3,12,-14,20,-14
|
||||
H400000v`+(40+r)+`H845.2724
|
||||
s-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7
|
||||
c-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z
|
||||
M`+(834+r)+" "+n+"h400000v"+(40+r)+"h-400000z"},Ie=function(r,n){return"M263,"+(601+r+n)+`c0.7,0,18,39.7,52,119
|
||||
c34,79.3,68.167,158.7,102.5,238c34.3,79.3,51.8,119.3,52.5,120
|
||||
c340,-704.7,510.7,-1060.3,512,-1067
|
||||
l`+r/2.084+" -"+r+`
|
||||
c4.7,-7.3,11,-11,19,-11
|
||||
H40000v`+(40+r)+`H1012.3
|
||||
s-271.3,567,-271.3,567c-38.7,80.7,-84,175,-136,283c-52,108,-89.167,185.3,-111.5,232
|
||||
c-22.3,46.7,-33.8,70.3,-34.5,71c-4.7,4.7,-12.3,7,-23,7s-12,-1,-12,-1
|
||||
s-109,-253,-109,-253c-72.7,-168,-109.3,-252,-110,-252c-10.7,8,-22,16.7,-34,26
|
||||
c-22,17.3,-33.3,26,-34,26s-26,-26,-26,-26s76,-59,76,-59s76,-60,76,-60z
|
||||
M`+(1001+r)+" "+n+"h400000v"+(40+r)+"h-400000z"},Be=function(r,n){return"M983 "+(10+r+n)+`
|
||||
l`+r/3.13+" -"+r+`
|
||||
c4,-6.7,10,-10,18,-10 H400000v`+(40+r)+`
|
||||
H1013.1s-83.4,268,-264.1,840c-180.7,572,-277,876.3,-289,913c-4.7,4.7,-12.7,7,-24,7
|
||||
s-12,0,-12,0c-1.3,-3.3,-3.7,-11.7,-7,-25c-35.3,-125.3,-106.7,-373.3,-214,-744
|
||||
c-10,12,-21,25,-33,39s-32,39,-32,39c-6,-5.3,-15,-14,-27,-26s25,-30,25,-30
|
||||
c26.7,-32.7,52,-63,76,-91s52,-60,52,-60s208,722,208,722
|
||||
c56,-175.3,126.3,-397.3,211,-666c84.7,-268.7,153.8,-488.2,207.5,-658.5
|
||||
c53.7,-170.3,84.5,-266.8,92.5,-289.5z
|
||||
M`+(1001+r)+" "+n+"h400000v"+(40+r)+"h-400000z"},je=function(r,n){return"M424,"+(2398+r+n)+`
|
||||
c-1.3,-0.7,-38.5,-172,-111.5,-514c-73,-342,-109.8,-513.3,-110.5,-514
|
||||
c0,-2,-10.7,14.3,-32,49c-4.7,7.3,-9.8,15.7,-15.5,25c-5.7,9.3,-9.8,16,-12.5,20
|
||||
s-5,7,-5,7c-4,-3.3,-8.3,-7.7,-13,-13s-13,-13,-13,-13s76,-122,76,-122s77,-121,77,-121
|
||||
s209,968,209,968c0,-2,84.7,-361.7,254,-1079c169.3,-717.3,254.7,-1077.7,256,-1081
|
||||
l`+r/4.223+" -"+r+`c4,-6.7,10,-10,18,-10 H400000
|
||||
v`+(40+r)+`H1014.6
|
||||
s-87.3,378.7,-272.6,1166c-185.3,787.3,-279.3,1182.3,-282,1185
|
||||
c-2,6,-10,9,-24,9
|
||||
c-8,0,-12,-0.7,-12,-2z M`+(1001+r)+" "+n+`
|
||||
h400000v`+(40+r)+"h-400000z"},et=function(r,n){return"M473,"+(2713+r+n)+`
|
||||
c339.3,-1799.3,509.3,-2700,510,-2702 l`+r/5.298+" -"+r+`
|
||||
c3.3,-7.3,9.3,-11,18,-11 H400000v`+(40+r)+`H1017.7
|
||||
s-90.5,478,-276.2,1466c-185.7,988,-279.5,1483,-281.5,1485c-2,6,-10,9,-24,9
|
||||
c-8,0,-12,-0.7,-12,-2c0,-1.3,-5.3,-32,-16,-92c-50.7,-293.3,-119.7,-693.3,-207,-1200
|
||||
c0,-1.3,-5.3,8.7,-16,30c-10.7,21.3,-21.3,42.7,-32,64s-16,33,-16,33s-26,-26,-26,-26
|
||||
s76,-153,76,-153s77,-151,77,-151c0.7,0.7,35.7,202,105,604c67.3,400.7,102,602.7,104,
|
||||
606zM`+(1001+r)+" "+n+"h400000v"+(40+r)+"H1017.7z"},ut=function(r){const n=r/2;return"M400000 "+r+" H0 L"+n+" 0 l65 45 L145 "+(r-80)+" H400000z"},mt=function(r,n,i){const l=i-54-n-r;return"M702 "+(r+n)+"H400000"+(40+r)+`
|
||||
H742v`+l+`l-4 4-4 4c-.667.7 -2 1.5-4 2.5s-4.167 1.833-6.5 2.5-5.5 1-9.5 1
|
||||
h-12l-28-84c-16.667-52-96.667 -294.333-240-727l-212 -643 -85 170
|
||||
c-4-3.333-8.333-7.667-13 -13l-13-13l77-155 77-156c66 199.333 139 419.667
|
||||
219 661 l218 661zM702 `+n+"H400000v"+(40+r)+"H742z"},En=function(r,n,i){n=1e3*n;let l="";switch(r){case"sqrtMain":l=we(n,Fe);break;case"sqrtSize1":l=Ie(n,Fe);break;case"sqrtSize2":l=Be(n,Fe);break;case"sqrtSize3":l=je(n,Fe);break;case"sqrtSize4":l=et(n,Fe);break;case"sqrtTall":l=mt(n,Fe,i)}return l},ht=function(r,n){switch(r){case"⎜":return"M291 0 H417 V"+n+" H291z M291 0 H417 V"+n+" H291z";case"∣":return"M145 0 H188 V"+n+" H145z M145 0 H188 V"+n+" H145z";case"∥":return"M145 0 H188 V"+n+" H145z M145 0 H188 V"+n+" H145z"+("M367 0 H410 V"+n+" H367z M367 0 H410 V"+n+" H367z");case"⎟":return"M457 0 H583 V"+n+" H457z M457 0 H583 V"+n+" H457z";case"⎢":return"M319 0 H403 V"+n+" H319z M319 0 H403 V"+n+" H319z";case"⎥":return"M263 0 H347 V"+n+" H263z M263 0 H347 V"+n+" H263z";case"⎪":return"M384 0 H504 V"+n+" H384z M384 0 H504 V"+n+" H384z";case"⏐":return"M312 0 H355 V"+n+" H312z M312 0 H355 V"+n+" H312z";case"‖":return"M257 0 H300 V"+n+" H257z M257 0 H300 V"+n+" H257z"+("M478 0 H521 V"+n+" H478z M478 0 H521 V"+n+" H478z");default:return""}},on={doubleleftarrow:`M262 157
|
||||
l10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3
|
||||
0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28
|
||||
14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5
|
||||
c2 1.7 6.3 3.5 13 5.5 68 17.3 128.2 47.8 180.5 91.5 52.3 43.7 93.8 96.2 124.5
|
||||
157.5 9.3 8 15.3 12.3 18 13h6c12-.7 18-4 18-10 0-2-1.7-7-5-15-23.3-46-52-87
|
||||
-86-123l-10-10h399738v-40H218c328 0 0 0 0 0l-10-8c-26.7-20-65.7-43-117-69 2.7
|
||||
-2 6-3.7 10-5 36.7-16 72.3-37.3 107-64l10-8h399782v-40z
|
||||
m8 0v40h399730v-40zm0 194v40h399730v-40z`,doublerightarrow:`M399738 392l
|
||||
-10 10c-34 36-62.7 77-86 123-3.3 8-5 13.3-5 16 0 5.3 6.7 8 20 8 7.3 0 12.2-.5
|
||||
14.5-1.5 2.3-1 4.8-4.5 7.5-10.5 49.3-97.3 121.7-169.3 217-216 28-14 57.3-25 88
|
||||
-33 6.7-2 11-3.8 13-5.5 2-1.7 3-4.2 3-7.5s-1-5.8-3-7.5c-2-1.7-6.3-3.5-13-5.5-68
|
||||
-17.3-128.2-47.8-180.5-91.5-52.3-43.7-93.8-96.2-124.5-157.5-9.3-8-15.3-12.3-18
|
||||
-13h-6c-12 .7-18 4-18 10 0 2 1.7 7 5 15 23.3 46 52 87 86 123l10 10H0v40h399782
|
||||
c-328 0 0 0 0 0l10 8c26.7 20 65.7 43 117 69-2.7 2-6 3.7-10 5-36.7 16-72.3 37.3
|
||||
-107 64l-10 8H0v40zM0 157v40h399730v-40zm0 194v40h399730v-40z`,leftarrow:`M400000 241H110l3-3c68.7-52.7 113.7-120
|
||||
135-202 4-14.7 6-23 6-25 0-7.3-7-11-21-11-8 0-13.2.8-15.5 2.5-2.3 1.7-4.2 5.8
|
||||
-5.5 12.5-1.3 4.7-2.7 10.3-4 17-12 48.7-34.8 92-68.5 130S65.3 228.3 18 247
|
||||
c-10 4-16 7.7-18 11 0 8.7 6 14.3 18 17 47.3 18.7 87.8 47 121.5 85S196 441.3 208
|
||||
490c.7 2 1.3 5 2 9s1.2 6.7 1.5 8c.3 1.3 1 3.3 2 6s2.2 4.5 3.5 5.5c1.3 1 3.3
|
||||
1.8 6 2.5s6 1 10 1c14 0 21-3.7 21-11 0-2-2-10.3-6-25-20-79.3-65-146.7-135-202
|
||||
l-3-3h399890zM100 241v40h399900v-40z`,leftbrace:`M6 548l-6-6v-35l6-11c56-104 135.3-181.3 238-232 57.3-28.7 117
|
||||
-45 179-50h399577v120H403c-43.3 7-81 15-113 26-100.7 33-179.7 91-237 174-2.7
|
||||
5-6 9-10 13-.7 1-7.3 1-20 1H6z`,leftbraceunder:`M0 6l6-6h17c12.688 0 19.313.3 20 1 4 4 7.313 8.3 10 13
|
||||
35.313 51.3 80.813 93.8 136.5 127.5 55.688 33.7 117.188 55.8 184.5 66.5.688
|
||||
0 2 .3 4 1 18.688 2.7 76 4.3 172 5h399450v120H429l-6-1c-124.688-8-235-61.7
|
||||
-331-161C60.687 138.7 32.312 99.3 7 54L0 41V6z`,leftgroup:`M400000 80
|
||||
H435C64 80 168.3 229.4 21 260c-5.9 1.2-18 0-18 0-2 0-3-1-3-3v-38C76 61 257 0
|
||||
435 0h399565z`,leftgroupunder:`M400000 262
|
||||
H435C64 262 168.3 112.6 21 82c-5.9-1.2-18 0-18 0-2 0-3 1-3 3v38c76 158 257 219
|
||||
435 219h399565z`,leftharpoon:`M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3
|
||||
-3.3 10.2-9.5 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5
|
||||
-18.3 3-21-1.3-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7
|
||||
-196 228-6.7 4.7-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40z`,leftharpoonplus:`M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3-3.3 10.2-9.5
|
||||
20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5-18.3 3-21-1.3
|
||||
-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7-196 228-6.7 4.7
|
||||
-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40zM0 435v40h400000v-40z
|
||||
m0 0v40h400000v-40z`,leftharpoondown:`M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9 2 11s5.333
|
||||
5.333 12 10c90.667 54 156 130 196 228 3.333 10.667 6.333 16.333 9 17 2 .667 5
|
||||
1 9 1h5c10.667 0 16.667-2 18-6 2-2.667 1-9.667-3-21-32-87.333-82.667-157.667
|
||||
-152-211l-3-3h399907v-40zM93 281 H400000 v-40L7 241z`,leftharpoondownplus:`M7 435c-4 4-6.3 8.7-7 14 0 5.3.7 9 2 11s5.3 5.3 12
|
||||
10c90.7 54 156 130 196 228 3.3 10.7 6.3 16.3 9 17 2 .7 5 1 9 1h5c10.7 0 16.7
|
||||
-2 18-6 2-2.7 1-9.7-3-21-32-87.3-82.7-157.7-152-211l-3-3h399907v-40H7zm93 0
|
||||
v40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z`,lefthook:`M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5
|
||||
-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3
|
||||
-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21
|
||||
71.5 23h399859zM103 281v-40h399897v40z`,leftlinesegment:`M40 281 V428 H0 V94 H40 V241 H400000 v40z
|
||||
M40 281 V428 H0 V94 H40 V241 H400000 v40z`,leftmapsto:`M40 281 V448H0V74H40V241H400000v40z
|
||||
M40 281 V448H0V74H40V241H400000v40z`,leftToFrom:`M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23
|
||||
-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8
|
||||
c28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3
|
||||
68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z`,longequal:`M0 50 h400000 v40H0z m0 194h40000v40H0z
|
||||
M0 50 h400000 v40H0z m0 194h40000v40H0z`,midbrace:`M200428 334
|
||||
c-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14
|
||||
-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7
|
||||
311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11
|
||||
12 44.7 59.3 101.3 106.3 170 141s145.3 54.3 229 60h199572v120z`,midbraceunder:`M199572 214
|
||||
c100.7 8.3 195.3 44 280 108 55.3 42 101.7 93 139 153l9 14c2.7-4 5.7-8.7 9-14
|
||||
53.3-86.7 123.7-153 211-199 66.7-36 137.3-56.3 212-62h199568v120H200432c-178.3
|
||||
11.7-311.7 78.3-403 201-6 8-9.7 12-11 12-.7.7-6.7 1-18 1s-17.3-.3-18-1c-1.3 0
|
||||
-5-4-11-12-44.7-59.3-101.3-106.3-170-141s-145.3-54.3-229-60H0V214z`,oiintSize1:`M512.6 71.6c272.6 0 320.3 106.8 320.3 178.2 0 70.8-47.7 177.6
|
||||
-320.3 177.6S193.1 320.6 193.1 249.8c0-71.4 46.9-178.2 319.5-178.2z
|
||||
m368.1 178.2c0-86.4-60.9-215.4-368.1-215.4-306.4 0-367.3 129-367.3 215.4 0 85.8
|
||||
60.9 214.8 367.3 214.8 307.2 0 368.1-129 368.1-214.8z`,oiintSize2:`M757.8 100.1c384.7 0 451.1 137.6 451.1 230 0 91.3-66.4 228.8
|
||||
-451.1 228.8-386.3 0-452.7-137.5-452.7-228.8 0-92.4 66.4-230 452.7-230z
|
||||
m502.4 230c0-111.2-82.4-277.2-502.4-277.2s-504 166-504 277.2
|
||||
c0 110 84 276 504 276s502.4-166 502.4-276z`,oiiintSize1:`M681.4 71.6c408.9 0 480.5 106.8 480.5 178.2 0 70.8-71.6 177.6
|
||||
-480.5 177.6S202.1 320.6 202.1 249.8c0-71.4 70.5-178.2 479.3-178.2z
|
||||
m525.8 178.2c0-86.4-86.8-215.4-525.7-215.4-437.9 0-524.7 129-524.7 215.4 0
|
||||
85.8 86.8 214.8 524.7 214.8 438.9 0 525.7-129 525.7-214.8z`,oiiintSize2:`M1021.2 53c603.6 0 707.8 165.8 707.8 277.2 0 110-104.2 275.8
|
||||
-707.8 275.8-606 0-710.2-165.8-710.2-275.8C311 218.8 415.2 53 1021.2 53z
|
||||
m770.4 277.1c0-131.2-126.4-327.6-770.5-327.6S248.4 198.9 248.4 330.1
|
||||
c0 130 128.8 326.4 772.7 326.4s770.5-196.4 770.5-326.4z`,rightarrow:`M0 241v40h399891c-47.3 35.3-84 78-110 128
|
||||
-16.7 32-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20
|
||||
11 8 0 13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7
|
||||
39-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85
|
||||
-40.5-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5
|
||||
-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67
|
||||
151.7 139 205zm0 0v40h399900v-40z`,rightbrace:`M400000 542l
|
||||
-6 6h-17c-12.7 0-19.3-.3-20-1-4-4-7.3-8.3-10-13-35.3-51.3-80.8-93.8-136.5-127.5
|
||||
s-117.2-55.8-184.5-66.5c-.7 0-2-.3-4-1-18.7-2.7-76-4.3-172-5H0V214h399571l6 1
|
||||
c124.7 8 235 61.7 331 161 31.3 33.3 59.7 72.7 85 118l7 13v35z`,rightbraceunder:`M399994 0l6 6v35l-6 11c-56 104-135.3 181.3-238 232-57.3
|
||||
28.7-117 45-179 50H-300V214h399897c43.3-7 81-15 113-26 100.7-33 179.7-91 237
|
||||
-174 2.7-5 6-9 10-13 .7-1 7.3-1 20-1h17z`,rightgroup:`M0 80h399565c371 0 266.7 149.4 414 180 5.9 1.2 18 0 18 0 2 0
|
||||
3-1 3-3v-38c-76-158-257-219-435-219H0z`,rightgroupunder:`M0 262h399565c371 0 266.7-149.4 414-180 5.9-1.2 18 0 18
|
||||
0 2 0 3 1 3 3v38c-76 158-257 219-435 219H0z`,rightharpoon:`M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3
|
||||
-3.7-15.3-11-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2
|
||||
-10.7 0-16.7 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58
|
||||
69.2 92 94.5zm0 0v40h399900v-40z`,rightharpoonplus:`M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3-3.7-15.3-11
|
||||
-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2-10.7 0-16.7
|
||||
2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 69.2 92 94.5z
|
||||
m0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z`,rightharpoondown:`M399747 511c0 7.3 6.7 11 20 11 8 0 13-.8 15-2.5s4.7-6.8
|
||||
8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 8.5-5.8 9.5
|
||||
-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3-64.7 57-92 95
|
||||
-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 241v40h399900v-40z`,rightharpoondownplus:`M399747 705c0 7.3 6.7 11 20 11 8 0 13-.8
|
||||
15-2.5s4.7-6.8 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3
|
||||
8.5-5.8 9.5-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3
|
||||
-64.7 57-92 95-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 435v40h399900v-40z
|
||||
m0-194v40h400000v-40zm0 0v40h400000v-40z`,righthook:`M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3
|
||||
15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0
|
||||
-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21
|
||||
66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z`,rightlinesegment:`M399960 241 V94 h40 V428 h-40 V281 H0 v-40z
|
||||
M399960 241 V94 h40 V428 h-40 V281 H0 v-40z`,rightToFrom:`M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23
|
||||
1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32
|
||||
-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142
|
||||
-167z M100 147v40h399900v-40zM0 341v40h399900v-40z`,twoheadleftarrow:`M0 167c68 40
|
||||
115.7 95.7 143 167h22c15.3 0 23-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69
|
||||
-70-101l-7-8h125l9 7c50.7 39.3 85 86 103 140h46c0-4.7-6.3-18.7-19-42-18-35.3
|
||||
-40-67.3-66-96l-9-9h399716v-40H284l9-9c26-28.7 48-60.7 66-96 12.7-23.333 19
|
||||
-37.333 19-42h-46c-18 54-52.3 100.7-103 140l-9 7H95l7-8c28.7-32 52-65.7 70-101
|
||||
10.7-23.333 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 71.3 68 127 0 167z`,twoheadrightarrow:`M400000 167
|
||||
c-68-40-115.7-95.7-143-167h-22c-15.3 0-23 .3-23 1 0 1.3 5.3 13.7 16 37 18 35.3
|
||||
41.3 69 70 101l7 8h-125l-9-7c-50.7-39.3-85-86-103-140h-46c0 4.7 6.3 18.7 19 42
|
||||
18 35.3 40 67.3 66 96l9 9H0v40h399716l-9 9c-26 28.7-48 60.7-66 96-12.7 23.333
|
||||
-19 37.333-19 42h46c18-54 52.3-100.7 103-140l9-7h125l-7 8c-28.7 32-52 65.7-70
|
||||
101-10.7 23.333-16 35.7-16 37 0 .7 7.7 1 23 1h22c27.3-71.3 75-127 143-167z`,tilde1:`M200 55.538c-77 0-168 73.953-177 73.953-3 0-7
|
||||
-2.175-9-5.437L2 97c-1-2-2-4-2-6 0-4 2-7 5-9l20-12C116 12 171 0 207 0c86 0
|
||||
114 68 191 68 78 0 168-68 177-68 4 0 7 2 9 5l12 19c1 2.175 2 4.35 2 6.525 0
|
||||
4.35-2 7.613-5 9.788l-19 13.05c-92 63.077-116.937 75.308-183 76.128
|
||||
-68.267.847-113-73.952-191-73.952z`,tilde2:`M344 55.266c-142 0-300.638 81.316-311.5 86.418
|
||||
-8.01 3.762-22.5 10.91-23.5 5.562L1 120c-1-2-1-3-1-4 0-5 3-9 8-10l18.4-9C160.9
|
||||
31.9 283 0 358 0c148 0 188 122 331 122s314-97 326-97c4 0 8 2 10 7l7 21.114
|
||||
c1 2.14 1 3.21 1 4.28 0 5.347-3 9.626-7 10.696l-22.3 12.622C852.6 158.372 751
|
||||
181.476 676 181.476c-149 0-189-126.21-332-126.21z`,tilde3:`M786 59C457 59 32 175.242 13 175.242c-6 0-10-3.457
|
||||
-11-10.37L.15 138c-1-7 3-12 10-13l19.2-6.4C378.4 40.7 634.3 0 804.3 0c337 0
|
||||
411.8 157 746.8 157 328 0 754-112 773-112 5 0 10 3 11 9l1 14.075c1 8.066-.697
|
||||
16.595-6.697 17.492l-21.052 7.31c-367.9 98.146-609.15 122.696-778.15 122.696
|
||||
-338 0-409-156.573-744-156.573z`,tilde4:`M786 58C457 58 32 177.487 13 177.487c-6 0-10-3.345
|
||||
-11-10.035L.15 143c-1-7 3-12 10-13l22-6.7C381.2 35 637.15 0 807.15 0c337 0 409
|
||||
177 744 177 328 0 754-127 773-127 5 0 10 3 11 9l1 14.794c1 7.805-3 13.38-9
|
||||
14.495l-20.7 5.574c-366.85 99.79-607.3 139.372-776.3 139.372-338 0-409
|
||||
-175.236-744-175.236z`,vec:`M377 20c0-5.333 1.833-10 5.5-14S391 0 397 0c4.667 0 8.667 1.667 12 5
|
||||
3.333 2.667 6.667 9 10 19 6.667 24.667 20.333 43.667 41 57 7.333 4.667 11
|
||||
10.667 11 18 0 6-1 10-3 12s-6.667 5-14 9c-28.667 14.667-53.667 35.667-75 63
|
||||
-1.333 1.333-3.167 3.5-5.5 6.5s-4 4.833-5 5.5c-1 .667-2.5 1.333-4.5 2s-4.333 1
|
||||
-7 1c-4.667 0-9.167-1.833-13.5-5.5S337 184 337 178c0-12.667 15.667-32.333 47-59
|
||||
H213l-171-1c-8.667-6-13-12.333-13-19 0-4.667 4.333-11.333 13-20h359
|
||||
c-16-25.333-24-45-24-59z`,widehat1:`M529 0h5l519 115c5 1 9 5 9 10 0 1-1 2-1 3l-4 22
|
||||
c-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z`,widehat2:`M1181 0h2l1171 176c6 0 10 5 10 11l-2 23c-1 6-5 10
|
||||
-11 10h-1L1182 67 15 220h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z`,widehat3:`M1181 0h2l1171 236c6 0 10 5 10 11l-2 23c-1 6-5 10
|
||||
-11 10h-1L1182 67 15 280h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z`,widehat4:`M1181 0h2l1171 296c6 0 10 5 10 11l-2 23c-1 6-5 10
|
||||
-11 10h-1L1182 67 15 340h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z`,widecheck1:`M529,159h5l519,-115c5,-1,9,-5,9,-10c0,-1,-1,-2,-1,-3l-4,-22c-1,
|
||||
-5,-5,-9,-11,-9h-2l-512,92l-513,-92h-2c-5,0,-9,4,-11,9l-5,22c-1,6,2,12,8,13z`,widecheck2:`M1181,220h2l1171,-176c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,
|
||||
-11,-10h-1l-1168,153l-1167,-153h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z`,widecheck3:`M1181,280h2l1171,-236c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,
|
||||
-11,-10h-1l-1168,213l-1167,-213h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z`,widecheck4:`M1181,340h2l1171,-296c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,
|
||||
-11,-10h-1l-1168,273l-1167,-273h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z`,baraboveleftarrow:`M400000 620h-399890l3 -3c68.7 -52.7 113.7 -120 135 -202
|
||||
c4 -14.7 6 -23 6 -25c0 -7.3 -7 -11 -21 -11c-8 0 -13.2 0.8 -15.5 2.5
|
||||
c-2.3 1.7 -4.2 5.8 -5.5 12.5c-1.3 4.7 -2.7 10.3 -4 17c-12 48.7 -34.8 92 -68.5 130
|
||||
s-74.2 66.3 -121.5 85c-10 4 -16 7.7 -18 11c0 8.7 6 14.3 18 17c47.3 18.7 87.8 47
|
||||
121.5 85s56.5 81.3 68.5 130c0.7 2 1.3 5 2 9s1.2 6.7 1.5 8c0.3 1.3 1 3.3 2 6
|
||||
s2.2 4.5 3.5 5.5c1.3 1 3.3 1.8 6 2.5s6 1 10 1c14 0 21 -3.7 21 -11
|
||||
c0 -2 -2 -10.3 -6 -25c-20 -79.3 -65 -146.7 -135 -202l-3 -3h399890z
|
||||
M100 620v40h399900v-40z M0 241v40h399900v-40zM0 241v40h399900v-40z`,rightarrowabovebar:`M0 241v40h399891c-47.3 35.3-84 78-110 128-16.7 32
|
||||
-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20 11 8 0
|
||||
13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7 39
|
||||
-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85-40.5
|
||||
-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5
|
||||
-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67
|
||||
151.7 139 205zm96 379h399894v40H0zm0 0h399904v40H0z`,baraboveshortleftharpoon:`M507,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11
|
||||
c1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17
|
||||
c2,0.7,5,1,9,1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21
|
||||
c-32,-87.3,-82.7,-157.7,-152,-211c0,0,-3,-3,-3,-3l399351,0l0,-40
|
||||
c-398570,0,-399437,0,-399437,0z M593 435 v40 H399500 v-40z
|
||||
M0 281 v-40 H399908 v40z M0 281 v-40 H399908 v40z`,rightharpoonaboveshortbar:`M0,241 l0,40c399126,0,399993,0,399993,0
|
||||
c4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,
|
||||
-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6
|
||||
c-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z
|
||||
M0 241 v40 H399908 v-40z M0 475 v-40 H399500 v40z M0 475 v-40 H399500 v40z`,shortbaraboveleftharpoon:`M7,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11
|
||||
c1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17c2,0.7,5,1,9,
|
||||
1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21c-32,-87.3,-82.7,-157.7,
|
||||
-152,-211c0,0,-3,-3,-3,-3l399907,0l0,-40c-399126,0,-399993,0,-399993,0z
|
||||
M93 435 v40 H400000 v-40z M500 241 v40 H400000 v-40z M500 241 v40 H400000 v-40z`,shortrightharpoonabovebar:`M53,241l0,40c398570,0,399437,0,399437,0
|
||||
c4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,
|
||||
-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6
|
||||
c-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z
|
||||
M500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z`},sn=function(r,n){switch(r){case"lbrack":return"M403 1759 V84 H666 V0 H319 V1759 v"+n+` v1759 h347 v-84
|
||||
H403z M403 1759 V0 H319 V1759 v`+n+" v1759 h84z";case"rbrack":return"M347 1759 V0 H0 V84 H263 V1759 v"+n+` v1759 H0 v84 H347z
|
||||
M347 1759 V0 H263 V1759 v`+n+" v1759 h84z";case"vert":return"M145 15 v585 v"+n+` v585 c2.667,10,9.667,15,21,15
|
||||
c10,0,16.667,-5,20,-15 v-585 v`+-n+` v-585 c-2.667,-10,-9.667,-15,-21,-15
|
||||
c-10,0,-16.667,5,-20,15z M188 15 H145 v585 v`+n+" v585 h43z";case"doublevert":return"M145 15 v585 v"+n+` v585 c2.667,10,9.667,15,21,15
|
||||
c10,0,16.667,-5,20,-15 v-585 v`+-n+` v-585 c-2.667,-10,-9.667,-15,-21,-15
|
||||
c-10,0,-16.667,5,-20,15z M188 15 H145 v585 v`+n+` v585 h43z
|
||||
M367 15 v585 v`+n+` v585 c2.667,10,9.667,15,21,15
|
||||
c10,0,16.667,-5,20,-15 v-585 v`+-n+` v-585 c-2.667,-10,-9.667,-15,-21,-15
|
||||
c-10,0,-16.667,5,-20,15z M410 15 H367 v585 v`+n+" v585 h43z";case"lfloor":return"M319 602 V0 H403 V602 v"+n+` v1715 h263 v84 H319z
|
||||
MM319 602 V0 H403 V602 v`+n+" v1715 H319z";case"rfloor":return"M319 602 V0 H403 V602 v"+n+` v1799 H0 v-84 H319z
|
||||
MM319 602 V0 H403 V602 v`+n+" v1715 H319z";case"lceil":return"M403 1759 V84 H666 V0 H319 V1759 v"+n+` v602 h84z
|
||||
M403 1759 V0 H319 V1759 v`+n+" v602 h84z";case"rceil":return"M347 1759 V0 H0 V84 H263 V1759 v"+n+` v602 h84z
|
||||
M347 1759 V0 h-84 V1759 v`+n+" v602 h84z";case"lparen":return`M863,9c0,-2,-2,-5,-6,-9c0,0,-17,0,-17,0c-12.7,0,-19.3,0.3,-20,1
|
||||
c-5.3,5.3,-10.3,11,-15,17c-242.7,294.7,-395.3,682,-458,1162c-21.3,163.3,-33.3,349,
|
||||
-36,557 l0,`+(n+84)+`c0.2,6,0,26,0,60c2,159.3,10,310.7,24,454c53.3,528,210,
|
||||
949.7,470,1265c4.7,6,9.7,11.7,15,17c0.7,0.7,7,1,19,1c0,0,18,0,18,0c4,-4,6,-7,6,-9
|
||||
c0,-2.7,-3.3,-8.7,-10,-18c-135.3,-192.7,-235.5,-414.3,-300.5,-665c-65,-250.7,-102.5,
|
||||
-544.7,-112.5,-882c-2,-104,-3,-167,-3,-189
|
||||
l0,-`+(n+92)+`c0,-162.7,5.7,-314,17,-454c20.7,-272,63.7,-513,129,-723c65.3,
|
||||
-210,155.3,-396.3,270,-559c6.7,-9.3,10,-15.3,10,-18z`;case"rparen":return`M76,0c-16.7,0,-25,3,-25,9c0,2,2,6.3,6,13c21.3,28.7,42.3,60.3,
|
||||
63,95c96.7,156.7,172.8,332.5,228.5,527.5c55.7,195,92.8,416.5,111.5,664.5
|
||||
c11.3,139.3,17,290.7,17,454c0,28,1.7,43,3.3,45l0,`+(n+9)+`
|
||||
c-3,4,-3.3,16.7,-3.3,38c0,162,-5.7,313.7,-17,455c-18.7,248,-55.8,469.3,-111.5,664
|
||||
c-55.7,194.7,-131.8,370.3,-228.5,527c-20.7,34.7,-41.7,66.3,-63,95c-2,3.3,-4,7,-6,11
|
||||
c0,7.3,5.7,11,17,11c0,0,11,0,11,0c9.3,0,14.3,-0.3,15,-1c5.3,-5.3,10.3,-11,15,-17
|
||||
c242.7,-294.7,395.3,-681.7,458,-1161c21.3,-164.7,33.3,-350.7,36,-558
|
||||
l0,-`+(n+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,
|
||||
-470,-1265c-4.7,-6,-9.7,-11.7,-15,-17c-0.7,-0.7,-6.7,-1,-18,-1z`;default:throw new Error("Unknown stretchy delimiter.")}};class de{constructor(n){this.children=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.children=n,this.classes=[],this.height=0,this.depth=0,this.maxFontSize=0,this.style={}}hasClass(n){return D.contains(this.classes,n)}toNode(){const n=document.createDocumentFragment();for(let i=0;i<this.children.length;i++)n.appendChild(this.children[i].toNode());return n}toMarkup(){let n="";for(let i=0;i<this.children.length;i++)n+=this.children[i].toMarkup();return n}toText(){const n=i=>i.toText();return this.children.map(n).join("")}}var gt={"AMS-Regular":{32:[0,0,0,0,.25],65:[0,.68889,0,0,.72222],66:[0,.68889,0,0,.66667],67:[0,.68889,0,0,.72222],68:[0,.68889,0,0,.72222],69:[0,.68889,0,0,.66667],70:[0,.68889,0,0,.61111],71:[0,.68889,0,0,.77778],72:[0,.68889,0,0,.77778],73:[0,.68889,0,0,.38889],74:[.16667,.68889,0,0,.5],75:[0,.68889,0,0,.77778],76:[0,.68889,0,0,.66667],77:[0,.68889,0,0,.94445],78:[0,.68889,0,0,.72222],79:[.16667,.68889,0,0,.77778],80:[0,.68889,0,0,.61111],81:[.16667,.68889,0,0,.77778],82:[0,.68889,0,0,.72222],83:[0,.68889,0,0,.55556],84:[0,.68889,0,0,.66667],85:[0,.68889,0,0,.72222],86:[0,.68889,0,0,.72222],87:[0,.68889,0,0,1],88:[0,.68889,0,0,.72222],89:[0,.68889,0,0,.72222],90:[0,.68889,0,0,.66667],107:[0,.68889,0,0,.55556],160:[0,0,0,0,.25],165:[0,.675,.025,0,.75],174:[.15559,.69224,0,0,.94666],240:[0,.68889,0,0,.55556],295:[0,.68889,0,0,.54028],710:[0,.825,0,0,2.33334],732:[0,.9,0,0,2.33334],770:[0,.825,0,0,2.33334],771:[0,.9,0,0,2.33334],989:[.08167,.58167,0,0,.77778],1008:[0,.43056,.04028,0,.66667],8245:[0,.54986,0,0,.275],8463:[0,.68889,0,0,.54028],8487:[0,.68889,0,0,.72222],8498:[0,.68889,0,0,.55556],8502:[0,.68889,0,0,.66667],8503:[0,.68889,0,0,.44445],8504:[0,.68889,0,0,.66667],8513:[0,.68889,0,0,.63889],8592:[-.03598,.46402,0,0,.5],8594:[-.03598,.46402,0,0,.5],8602:[-.13313,.36687,0,0,1],8603:[-.13313,.36687,0,0,1],8606:[.01354,.52239,0,0,1],8608:[.01354,.52239,0,0,1],8610:[.01354,.52239,0,0,1.11111],8611:[.01354,.52239,0,0,1.11111],8619:[0,.54986,0,0,1],8620:[0,.54986,0,0,1],8621:[-.13313,.37788,0,0,1.38889],8622:[-.13313,.36687,0,0,1],8624:[0,.69224,0,0,.5],8625:[0,.69224,0,0,.5],8630:[0,.43056,0,0,1],8631:[0,.43056,0,0,1],8634:[.08198,.58198,0,0,.77778],8635:[.08198,.58198,0,0,.77778],8638:[.19444,.69224,0,0,.41667],8639:[.19444,.69224,0,0,.41667],8642:[.19444,.69224,0,0,.41667],8643:[.19444,.69224,0,0,.41667],8644:[.1808,.675,0,0,1],8646:[.1808,.675,0,0,1],8647:[.1808,.675,0,0,1],8648:[.19444,.69224,0,0,.83334],8649:[.1808,.675,0,0,1],8650:[.19444,.69224,0,0,.83334],8651:[.01354,.52239,0,0,1],8652:[.01354,.52239,0,0,1],8653:[-.13313,.36687,0,0,1],8654:[-.13313,.36687,0,0,1],8655:[-.13313,.36687,0,0,1],8666:[.13667,.63667,0,0,1],8667:[.13667,.63667,0,0,1],8669:[-.13313,.37788,0,0,1],8672:[-.064,.437,0,0,1.334],8674:[-.064,.437,0,0,1.334],8705:[0,.825,0,0,.5],8708:[0,.68889,0,0,.55556],8709:[.08167,.58167,0,0,.77778],8717:[0,.43056,0,0,.42917],8722:[-.03598,.46402,0,0,.5],8724:[.08198,.69224,0,0,.77778],8726:[.08167,.58167,0,0,.77778],8733:[0,.69224,0,0,.77778],8736:[0,.69224,0,0,.72222],8737:[0,.69224,0,0,.72222],8738:[.03517,.52239,0,0,.72222],8739:[.08167,.58167,0,0,.22222],8740:[.25142,.74111,0,0,.27778],8741:[.08167,.58167,0,0,.38889],8742:[.25142,.74111,0,0,.5],8756:[0,.69224,0,0,.66667],8757:[0,.69224,0,0,.66667],8764:[-.13313,.36687,0,0,.77778],8765:[-.13313,.37788,0,0,.77778],8769:[-.13313,.36687,0,0,.77778],8770:[-.03625,.46375,0,0,.77778],8774:[.30274,.79383,0,0,.77778],8776:[-.01688,.48312,0,0,.77778],8778:[.08167,.58167,0,0,.77778],8782:[.06062,.54986,0,0,.77778],8783:[.06062,.54986,0,0,.77778],8785:[.08198,.58198,0,0,.77778],8786:[.08198,.58198,0,0,.77778],8787:[.08198,.58198,0,0,.77778],8790:[0,.69224,0,0,.77778],8791:[.22958,.72958,0,0,.77778],8796:[.08198,.91667,0,0,.77778],8806:[.25583,.75583,0,0,.77778],8807:[.25583,.75583,0,0,.77778],8808:[.25142,.75726,0,0,.77778],8809:[.25142,.75726,0,0,.77778],8812:[.25583,.75583,0,0,.5],8814:[.20576,.70576,0,0,.77778],8815:[.20576,.70576,0,0,.77778],8816:[.30274,.79383,0,0,.77778],8817:[.30274,.79383,0,0,.77778],8818:[.22958,.72958,0,0,.77778],8819:[.22958,.72958,0,0,.77778],8822:[.1808,.675,0,0,.77778],8823:[.1808,.675,0,0,.77778],8828:[.13667,.63667,0,0,.77778],8829:[.13667,.63667,0,0,.77778],8830:[.22958,.72958,0,0,.77778],8831:[.22958,.72958,0,0,.77778],8832:[.20576,.70576,0,0,.77778],8833:[.20576,.70576,0,0,.77778],8840:[.30274,.79383,0,0,.77778],8841:[.30274,.79383,0,0,.77778],8842:[.13597,.63597,0,0,.77778],8843:[.13597,.63597,0,0,.77778],8847:[.03517,.54986,0,0,.77778],8848:[.03517,.54986,0,0,.77778],8858:[.08198,.58198,0,0,.77778],8859:[.08198,.58198,0,0,.77778],8861:[.08198,.58198,0,0,.77778],8862:[0,.675,0,0,.77778],8863:[0,.675,0,0,.77778],8864:[0,.675,0,0,.77778],8865:[0,.675,0,0,.77778],8872:[0,.69224,0,0,.61111],8873:[0,.69224,0,0,.72222Line truncated
|
||||
`+oe+" children.");for(let Ce=0;Ce<oe;Ce++){const Oe=new cn(B[Ce]),Le=new Wt([Oe],{width:"400em",height:J(Q),viewBox:"0 0 "+b+" "+H,preserveAspectRatio:Re[Ce]+" slice"}),qe=q.makeSvgSpan([le[Ce]],[Le],n);if(oe===1)return{span:qe,minWidth:Y,height:Q};qe.style.height=J(Q),A.push(qe)}return{span:q.makeSpan(["stretchy"],A,n),minWidth:Y,height:Q}}}const{span:l,minWidth:m,height:E}=i();return l.height=E,l.style.height=J(E),m>0&&(l.style.minWidth=J(m)),l}};function Te(r,n){if(!r||r.type!==n)throw new Error("Expected node of type "+n+", but got "+(r?"node of type "+r.type:String(r)));return r}function ua(r){const n=Nr(r);if(!n)throw new Error("Expected node of symbol group type, but got "+(r?"node of type "+r.type:String(r)));return n}function Nr(r){return r&&(r.type==="atom"||$l.hasOwnProperty(r.type))?r:null}const da=(r,n)=>{let i,l,m;r&&r.type==="supsub"?(l=Te(r.base,"accent"),i=l.base,r.base=i,m=Vl(De(r,n)),r.base=l):(l=Te(r,"accent"),i=l.base);const E=De(i,n.havingCrampedStyle()),b=l.isShifty&&D.isCharacterBox(i);let C=0;if(b){const H=D.getBaseElem(i),Q=De(H,n.havingCrampedStyle());C=Wr(Q).skew}const A=l.label==="\\c";let M=A?E.height+E.depth:Math.min(E.height,n.fontMetrics().xHeight),B;if(l.isStretchy)B=dn.svgSpan(l,n),B=q.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:E},{type:"elem",elem:B,wrapperClasses:["svg-align"],wrapperStyle:C>0?{width:"calc(100% - "+J(2*C)+")",marginLeft:J(2*C)}:void 0}]},n);else{let H,Q;l.label==="\\vec"?(H=q.staticSvg("vec",n),Q=q.svgData.vec[1]):(H=q.makeOrd({mode:l.mode,text:l.label},n,"textord"),H=Wr(H),H.italic=0,Q=H.width,A&&(M+=H.depth)),B=q.makeSpan(["accent-body"],[H]);const oe=l.label==="\\textcircled";oe&&(B.classes.push("accent-full"),M=E.height);let le=C;oe||(le-=Q/2),B.style.left=J(le),l.label==="\\textcircled"&&(B.style.top=".2em"),B=q.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:E},{type:"kern",size:-M},{type:"elem",elem:B}]},n)}const Y=q.makeSpan(["mord","accent"],[B],n);return m?(m.children[0]=Y,m.height=Math.max(Y.height,m.height),m.classes[0]="mord",m):Y},cc=(r,n)=>{const i=r.isStretchy?dn.mathMLnode(r.label):new Z.MathNode("mo",[wt(r.label,r.mode)]),l=new Z.MathNode("mover",[Ue(r.base,n),i]);return l.setAttribute("accent","true"),l},Np=new RegExp(["\\acute","\\grave","\\ddot","\\tilde","\\bar","\\breve","\\check","\\hat","\\vec","\\dot","\\mathring"].map(r=>"\\"+r).join("|"));ae({type:"accent",names:["\\acute","\\grave","\\ddot","\\tilde","\\bar","\\breve","\\check","\\hat","\\vec","\\dot","\\mathring","\\widecheck","\\widehat","\\widetilde","\\overrightarrow","\\overleftarrow","\\Overrightarrow","\\overleftrightarrow","\\overgroup","\\overlinesegment","\\overleftharpoon","\\overrightharpoon"],props:{numArgs:1},handler:(r,n)=>{const i=tr(n[0]),l=!Np.test(r.funcName),m=!l||r.funcName==="\\widehat"||r.funcName==="\\widetilde"||r.funcName==="\\widecheck";return{type:"accent",mode:r.parser.mode,label:r.funcName,isStretchy:l,isShifty:m,base:i}},htmlBuilder:da,mathmlBuilder:cc}),ae({type:"accent",names:["\\'","\\`","\\^","\\~","\\=","\\u","\\.",'\\"',"\\c","\\r","\\H","\\v","\\textcircled"],props:{numArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:["primitive"]},handler:(r,n)=>{const i=n[0];let l=r.parser.mode;return l==="math"&&(r.parser.settings.reportNonstrict("mathVsTextAccents","LaTeX's accent "+r.funcName+" works only in text mode"),l="text"),{type:"accent",mode:l,label:r.funcName,isStretchy:!1,isShifty:!0,base:i}},htmlBuilder:da,mathmlBuilder:cc}),ae({type:"accentUnder",names:["\\underleftarrow","\\underrightarrow","\\underleftrightarrow","\\undergroup","\\underlinesegment","\\utilde"],props:{numArgs:1},handler:(r,n)=>{let{parser:i,funcName:l}=r;const m=n[0];return{type:"accentUnder",mode:i.mode,label:l,base:m}},htmlBuilder:(r,n)=>{const i=De(r.base,n),l=dn.svgSpan(r,n),m=r.label==="\\utilde"?.12:0,E=q.makeVList({positionType:"top",positionData:i.height,children:[{type:"elem",elem:l,wrapperClasses:["svg-align"]},{type:"kern",size:m},{type:"elem",elem:i}]},n);return q.makeSpan(["mord","accentunder"],[E],n)},mathmlBuilder:(r,n)=>{const i=dn.mathMLnode(r.label),l=new Z.MathNode("munder",[Ue(r.base,n),i]);return l.setAttribute("accentunder","true"),l}});const yr=r=>{const n=new Z.MathNode("mpadded",r?[r]:[]);return n.setAttribute("width","+0.6em"),n.setAttribute("lspace","0.3em"),n};ae({type:"xArrow",names:["\\xleftarrow","\\xrightarrow","\\xLeftarrow","\\xRightarrow","\\xleftrightarrow","\\xLeftrightarrow","\\xhookleftarrow","\\xhookrightarrow","\\xmapsto","\\xrightharpoondown","\\xrightharpoonup","\\xleftharpoondown","\\xleftharpoonup","\\xrightleftharpoons","\\xleftrightharpoons","\\xlongequal","\\xtwoheadrightarrow","\\xtwoheadleftarrow","\\xtofrom","\\xrightleftarrows","\\xrightequilibrium","\\xleftequilibrium","\\\\cdrightarrow","\\\\cdleftarrow","\\\\cdlongequal"],props:{numArgs:1,numOptionalArgs:1},handler(r,n,i){let{parser:l,funcName:m}=r;return{type:"xArrow",mode:l.mode,label:m,body:n[0],bLine truncated
|
||||
]`,$p="\\\\[a-zA-Z@]+",Kp="\\\\[^\uD800-\uDFFF]",Qp="("+$p+")"+jc+"*",Xp=`\\\\(
|
||||
|[ \r ]+
|
||||
?)[ \r ]*`,Ia="[̀-ͯ]",Zp=new RegExp(Ia+"+$"),Jp="("+jc+"+)|"+(Xp+"|")+"([!-\\[\\]-‧-豈-]"+(Ia+"*")+"|[\uD800-\uDBFF][\uDC00-\uDFFF]"+(Ia+"*")+"|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5"+("|"+Qp)+("|"+Kp+")");class eu{constructor(n,i){this.input=void 0,this.settings=void 0,this.tokenRegex=void 0,this.catcodes=void 0,this.input=n,this.settings=i,this.tokenRegex=new RegExp(Jp,"g"),this.catcodes={"%":14,"~":13}}setCatcode(n,i){this.catcodes[n]=i}lex(){const n=this.input,i=this.tokenRegex.lastIndex;if(i===n.length)return new Lt("EOF",new It(this,i,i));const l=this.tokenRegex.exec(n);if(l===null||l.index!==i)throw new s("Unexpected character: '"+n[i]+"'",new Lt(n[i],new It(this,i,i+1)));const m=l[6]||l[3]||(l[2]?"\\ ":" ");if(this.catcodes[m]===14){const E=n.indexOf(`
|
||||
`,this.tokenRegex.lastIndex);return E===-1?(this.tokenRegex.lastIndex=n.length,this.settings.reportNonstrict("commentAtEnd","% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)")):this.tokenRegex.lastIndex=E+1,this.lex()}return new Lt(m,new It(this,i,this.tokenRegex.lastIndex))}}class jp{constructor(n,i){n===void 0&&(n={}),i===void 0&&(i={}),this.current=void 0,this.builtins=void 0,this.undefStack=void 0,this.current=i,this.builtins=n,this.undefStack=[]}beginGroup(){this.undefStack.push({})}endGroup(){if(this.undefStack.length===0)throw new s("Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug");const n=this.undefStack.pop();for(const i in n)n.hasOwnProperty(i)&&(n[i]==null?delete this.current[i]:this.current[i]=n[i])}endGroups(){for(;this.undefStack.length>0;)this.endGroup()}has(n){return this.current.hasOwnProperty(n)||this.builtins.hasOwnProperty(n)}get(n){return this.current.hasOwnProperty(n)?this.current[n]:this.builtins[n]}set(n,i,l){if(l===void 0&&(l=!1),l){for(let m=0;m<this.undefStack.length;m++)delete this.undefStack[m][n];this.undefStack.length>0&&(this.undefStack[this.undefStack.length-1][n]=i)}else{const m=this.undefStack[this.undefStack.length-1];m&&!m.hasOwnProperty(n)&&(m[n]=this.current[n])}i==null?delete this.current[n]:this.current[n]=i}}var eg=Ic;R("\\noexpand",function(r){const n=r.popToken();return r.isExpandable(n.text)&&(n.noexpand=!0,n.treatAsRelax=!0),{tokens:[n],numArgs:0}}),R("\\expandafter",function(r){const n=r.popToken();return r.expandOnce(!0),{tokens:[n],numArgs:0}}),R("\\@firstoftwo",function(r){return{tokens:r.consumeArgs(2)[0],numArgs:0}}),R("\\@secondoftwo",function(r){return{tokens:r.consumeArgs(2)[1],numArgs:0}}),R("\\@ifnextchar",function(r){const n=r.consumeArgs(3);r.consumeSpaces();const i=r.future();return n[0].length===1&&n[0][0].text===i.text?{tokens:n[1],numArgs:0}:{tokens:n[2],numArgs:0}}),R("\\@ifstar","\\@ifnextchar *{\\@firstoftwo{#1}}"),R("\\TextOrMath",function(r){const n=r.consumeArgs(2);return r.mode==="text"?{tokens:n[0],numArgs:0}:{tokens:n[1],numArgs:0}});const tu={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};R("\\char",function(r){let n=r.popToken(),i,l="";if(n.text==="'")i=8,n=r.popToken();else if(n.text==='"')i=16,n=r.popToken();else if(n.text==="`")if(n=r.popToken(),n.text[0]==="\\")l=n.text.charCodeAt(1);else{if(n.text==="EOF")throw new s("\\char` missing argument");l=n.text.charCodeAt(0)}else i=10;if(i){if(l=tu[n.text],l==null||l>=i)throw new s("Invalid base-"+i+" digit "+n.text);let m;for(;(m=tu[r.future().text])!=null&&m<i;)l*=i,l+=m,r.popToken()}return"\\@char{"+l+"}"});const Da=(r,n,i,l)=>{let m=r.consumeArg().tokens;if(m.length!==1)throw new s("\\newcommand's first argument must be a macro name");const E=m[0].text,b=r.isDefined(E);if(b&&!n)throw new s("\\newcommand{"+E+"} attempting to redefine "+(E+"; use \\renewcommand"));if(!b&&!i)throw new s("\\renewcommand{"+E+"} when command "+E+" does not yet exist; use \\newcommand");let C=0;if(m=r.consumeArg().tokens,m.length===1&&m[0].text==="["){let A="",M=r.expandNextToken();for(;M.text!=="]"&&M.text!=="EOF";)A+=M.text,M=r.expandNextToken();if(!A.match(/^\s*[0-9]+\s*$/))throw new s("Invalid number of arguments: "+A);C=parseInt(A),m=r.consumeArg().tokens}return b&&l||r.macros.set(E,{tokens:m,numArgs:C}),""};R("\\newcommand",r=>Da(r,!1,!0,!1)),R("\\renewcommand",r=>Da(r,!0,!1,!1)),R("\\providecommand",r=>Da(r,!0,!0,!0)),R("\\message",r=>{const n=r.consumeArgs(1)[0];return console.log(n.reverse().map(i=>i.text).join("")),""}),R("\\errmessage",r=>{const n=r.consumeArgs(1)[0];return console.error(n.reverse().map(i=>i.text).join("")),""}),R("\\show",r=>{const n=r.popToken(),i=n.text;return console.log(n,r.macros.get(i),hn[i],Ke.math[i],Ke.text[i]),""}),R("\\bgroup","{"),R("\\egroup","}"),R("~","\\nobreakspace"),R("\\lq","`"),R("\\rq","'"),R("\\aa","\\r a"),R("\\AA","\\r A"),R("\\textcopyright","\\html@mathml{\\textcircled{c}}{\\char`©}"),R("\\copyright","\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}"),R("\\textregistered","\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`®}"),R("ℬ","\\mathscr{B}"),R("ℰ","\\mathscr{E}"),R("ℱ","\\mathscr{F}"),R("ℋ","\\mathscr{H}"),R("ℐ","\\mathscr{I}"),R("ℒ","\\mathscr{L}"),R("ℳ","\\mathscr{M}"),R("ℛ","\\mathscr{R}"),R("ℭ","\\mathfrak{C}"),R("ℌ","\\mathfrak{H}"),R("ℨ","\\mathfrak{Z}"),R("\\Bbbk","\\Bbb{k}"),R("·","\\cdotp"),R("\\llap","\\mathllap{\\textrm{#1}}"),R("\\rlap","\\mathrlap{\\textrm{#1}}"),R("\\clap","\\mathclap{\\textrm{#1}}"),R("\\mathstrut","\\vphantom{(}"),R("\\underbar","\\underline{\\text{#1}}"),R("\\not",'\\html@mathml{\\mathrel{\\mathrlap\\@not}}{\\char"338}'),R("\\neq","\\html@mathml{\\mathrel{\\not=}}{\\mathrel{\\char`≠}}"),R("\\ne","\\neq"),R("≠","\\neq"),R("\\notin","\\html@mathml{\\mathrel{{\\in}\\mathllap{/\\mskip1mu}}}{\\mathrel{\\char`∉}}"),R("∉"Line truncated
|
||||
please report what input caused this bug`);return E=E.slice(1,-1),{type:"verb",mode:"text",body:E,star:b}}su.hasOwnProperty(i[0])&&!Ke[this.mode][i[0]]&&(this.settings.strict&&this.mode==="math"&&this.settings.reportNonstrict("unicodeTextInMathMode",'Accented Unicode text character "'+i[0]+'" used in math mode',n),i=su[i[0]]+i.slice(1));const l=Zp.exec(i);l&&(i=i.substring(0,l.index),i==="i"?i="ı":i==="j"&&(i="ȷ"));let m;if(Ke[this.mode][i]){this.settings.strict&&this.mode==="math"&&Sr.indexOf(i)>=0&&this.settings.reportNonstrict("unicodeTextInMathMode",'Latin-1/Unicode text character "'+i[0]+'" used in math mode',n);const E=Ke[this.mode][i].group,b=It.range(n);let C;if(Wl.hasOwnProperty(E)){const A=E;C={type:"atom",mode:this.mode,family:A,loc:b,text:i}}else C={type:E,mode:this.mode,loc:b,text:i};m=C}else if(i.charCodeAt(0)>=128)this.settings.strict&&(Me(i.charCodeAt(0))?this.mode==="math"&&this.settings.reportNonstrict("unicodeTextInMathMode",'Unicode text character "'+i[0]+'" used in math mode',n):this.settings.reportNonstrict("unknownSymbol",'Unrecognized Unicode character "'+i[0]+'"'+(" ("+i.charCodeAt(0)+")"),n)),m={type:"textord",mode:"text",loc:It.range(n),text:i};else return null;if(this.consume(),l)for(let E=0;E<l[0].length;E++){const b=l[0][E];if(!Ma[b])throw new s("Unknown accent ' "+b+"'",n);const C=Ma[b][this.mode]||Ma[b].text;if(!C)throw new s("Accent "+b+" unsupported in "+this.mode+" mode",n);m={type:"accent",mode:this.mode,loc:It.range(n),label:C,isStretchy:!1,isShifty:!0,base:m}}return m}}xr.endOfExpression=["}","\\endgroup","\\end","\\right","&"];var wa=function(r,n){if(!(typeof r=="string"||r instanceof String))throw new TypeError("KaTeX can only parse string typed expression");const i=new xr(r,n);delete i.gullet.macros.current["\\df@tag"];let l=i.parse();if(delete i.gullet.macros.current["\\current@color"],delete i.gullet.macros.current["\\color"],i.gullet.macros.get("\\df@tag")){if(!n.displayMode)throw new s("\\tag works only in display equations");l=[{type:"tag",mode:"text",body:l,tag:i.subparse([new Lt("\\df@tag")])}]}return l};let lu=function(r,n,i){n.textContent="";const l=La(r,i).toNode();n.appendChild(l)};typeof document<"u"&&document.compatMode!=="CSS1Compat"&&(typeof console<"u"&&console.warn("Warning: KaTeX doesn't work in quirks mode. Make sure your website has a suitable doctype."),lu=function(){throw new s("KaTeX doesn't work in quirks mode.")});const ng=function(r,n){return La(r,n).toMarkup()},rg=function(r,n){const i=new G(n);return wa(r,i)},cu=function(r,n,i){if(i.throwOnError||!(r instanceof s))throw r;const l=q.makeSpan(["katex-error"],[new At(n)]);return l.setAttribute("title",r.toString()),l.setAttribute("style","color:"+i.errorColor),l},La=function(r,n){const i=new G(n);try{const l=wa(r,i);return Sp(l,r,i)}catch(l){return cu(l,r,i)}};var ag={version:"0.16.21",render:lu,renderToString:ng,ParseError:s,SETTINGS_SCHEMA:U,__parse:rg,__renderToDomTree:La,__renderToHTMLTree:function(r,n){const i=new G(n);try{const l=wa(r,i);return bp(l,r,i)}catch(l){return cu(l,r,i)}},__setFontMetrics:ln,__defineSymbol:g,__defineFunction:ae,__defineMacro:R,__domTree:{Span:Yt,Anchor:Vt,SymbolNode:At,SvgNode:Wt,PathNode:cn,LineNode:fr}},ig=ag;return o=o.default,o}()})})(cp);var bC=cp.exports,Tl=bC;function fm(t,e){var a,o,c=t.posMax,s=!0,d=!0;return a=e>0?t.src.charCodeAt(e-1):-1,o=e+1<=c?t.src.charCodeAt(e+1):-1,(a===32||a===9||o>=48&&o<=57)&&(d=!1),(o===32||o===9)&&(s=!1),{can_open:s,can_close:d}}function hC(t,e){var a,o,c,s,d;if(t.src[t.pos]!=="$")return!1;if(s=fm(t,t.pos),!s.can_open)return e||(t.pending+="$"),t.pos+=1,!0;for(a=t.pos+1,o=a;(o=t.src.indexOf("$",o))!==-1;){for(d=o-1;t.src[d]==="\\";)d-=1;if((o-d)%2==1)break;o+=1}return o===-1?(e||(t.pending+="$"),t.pos=a,!0):o-a===0?(e||(t.pending+="$$"),t.pos=a+1,!0):(s=fm(t,o),s.can_close?(e||(c=t.push("math_inline","math",0),c.markup="$",c.content=t.src.slice(a,o)),t.pos=o+1,!0):(e||(t.pending+="$"),t.pos=a,!0))}function TC(t,e,a,o){var c,s,d,u,_=!1,p,S=t.bMarks[e]+t.tShift[e],h=t.eMarks[e];if(S+2>h||t.src.slice(S,S+2)!=="$$")return!1;if(S+=2,c=t.src.slice(S,h),o)return!0;for(c.trim().slice(-2)==="$$"&&(c=c.trim().slice(0,-2),_=!0),d=e;!_&&(d++,!(d>=a||(S=t.bMarks[d]+t.tShift[d],h=t.eMarks[d],S<h&&t.tShift[d]<t.blkIndent)));)t.src.slice(S,h).trim().slice(-2)==="$$"&&(u=t.src.slice(0,h).lastIndexOf("$$"),s=t.src.slice(S,u),_=!0);return t.line=d+1,p=t.push("math_block","math",0),p.block=!0,p.content=(c&&c.trim()?c+`
|
||||
`:"")+t.getLines(e+1,d,t.tShift[e],!0)+(s&&s.trim()?s:""),p.map=[e,t.line],p.markup="$$",!0}function Pr(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var CC=function(e,a){a=a||{},a.katex&&(Tl=a.katex),a.blockClass||(a.blockClass="");var o=function(u){a.displayMode=!1;try{return Tl.renderToString(u,a)}catch(_){return a.throwOnError&&console.log(_),`<span class='katex-error' title='${Pr(_.toString())}'>${Pr(u)}</span>`}},c=function(u,_){return o(u[_].content)},s=function(u){a.displayMode=!0;try{return`<p class="katex-block ${a.blockClass}">`+Tl.renderToString(u,a)+"</p>"}catch(_){return a.throwOnError&&console.log(_),`<p class='katex-block katex-error ${a.blockClass}' title='${Pr(_.toString())}'>${Pr(u)}</p>`}},d=function(u,_){return s(u[_].content)+`
|
||||
`};e.inline.ruler.after("escape","math_inline",hC),e.block.ruler.after("blockquote","math_block",TC,{alt:["paragraph","reference","blockquote","list"]}),e.renderer.rules.math_inline=c,e.renderer.rules.math_block=d};const RC=Al(CC);/*!
|
||||
* qrcode.vue v3.6.0
|
||||
* A Vue.js component to generate QRCode. Both support Vue 2 and Vue 3
|
||||
* © 2017-PRESENT @scopewu(https://github.com/scopewu)
|
||||
* MIT License.
|
||||
*/var nn=function(){return nn=Object.assign||function(e){for(var a,o=1,c=arguments.length;o<c;o++){a=arguments[o];for(var s in a)Object.prototype.hasOwnProperty.call(a,s)&&(e[s]=a[s])}return e},nn.apply(this,arguments)};var wn;(function(t){var e=function(){function d(u,_,p,S){if(this.version=u,this.errorCorrectionLevel=_,this.modules=[],this.isFunction=[],u<d.MIN_VERSION||u>d.MAX_VERSION)throw new RangeError("Version value out of range");if(S<-1||S>7)throw new RangeError("Mask value out of range");this.size=u*4+17;for(var h=[],y=0;y<this.size;y++)h.push(!1);for(var y=0;y<this.size;y++)this.modules.push(h.slice()),this.isFunction.push(h.slice());this.drawFunctionPatterns();var O=this.addEccAndInterleave(p);if(this.drawCodewords(O),S==-1)for(var N=1e9,y=0;y<8;y++){this.applyMask(y),this.drawFormatBits(y);var w=this.getPenaltyScore();w<N&&(S=y,N=w),this.applyMask(y)}c(0<=S&&S<=7),this.mask=S,this.applyMask(S),this.drawFormatBits(S),this.isFunction=[]}return d.encodeText=function(u,_){var p=t.QrSegment.makeSegments(u);return d.encodeSegments(p,_)},d.encodeBinary=function(u,_){var p=t.QrSegment.makeBytes(u);return d.encodeSegments([p],_)},d.encodeSegments=function(u,_,p,S,h,y){if(p===void 0&&(p=1),S===void 0&&(S=40),h===void 0&&(h=-1),y===void 0&&(y=!0),!(d.MIN_VERSION<=p&&p<=S&&S<=d.MAX_VERSION)||h<-1||h>7)throw new RangeError("Invalid value");var O,N;for(O=p;;O++){var w=d.getNumDataCodewords(O,_)*8,L=s.getTotalBits(u,O);if(L<=w){N=L;break}if(O>=S)throw new RangeError("Data too long")}for(var D=0,U=[d.Ecc.MEDIUM,d.Ecc.QUARTILE,d.Ecc.HIGH];D<U.length;D++){var x=U[D];y&&N<=d.getNumDataCodewords(O,x)*8&&(_=x)}for(var G=[],F=0,z=u;F<z.length;F++){var $=z[F];a($.mode.modeBits,4,G),a($.numChars,$.mode.numCharCountBits(O),G);for(var V=0,ee=$.getData();V<ee.length;V++){var ce=ee[V];G.push(ce)}}c(G.length==N);var ne=d.getNumDataCodewords(O,_)*8;c(G.length<=ne),a(0,Math.min(4,ne-G.length),G),a(0,(8-G.length%8)%8,G),c(G.length%8==0);for(var me=236;G.length<ne;me^=253)a(me,8,G);for(var pe=[];pe.length*8<G.length;)pe.push(0);return G.forEach(function(be,fe){return pe[fe>>>3]|=be<<7-(fe&7)}),new d(O,_,pe,h)},d.prototype.getModule=function(u,_){return 0<=u&&u<this.size&&0<=_&&_<this.size&&this.modules[_][u]},d.prototype.getModules=function(){return this.modules},d.prototype.drawFunctionPatterns=function(){for(var u=0;u<this.size;u++)this.setFunctionModule(6,u,u%2==0),this.setFunctionModule(u,6,u%2==0);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);for(var _=this.getAlignmentPatternPositions(),p=_.length,u=0;u<p;u++)for(var S=0;S<p;S++)u==0&&S==0||u==0&&S==p-1||u==p-1&&S==0||this.drawAlignmentPattern(_[u],_[S]);this.drawFormatBits(0),this.drawVersion()},d.prototype.drawFormatBits=function(u){for(var _=this.errorCorrectionLevel.formatBits<<3|u,p=_,S=0;S<10;S++)p=p<<1^(p>>>9)*1335;var h=(_<<10|p)^21522;c(h>>>15==0);for(var S=0;S<=5;S++)this.setFunctionModule(8,S,o(h,S));this.setFunctionModule(8,7,o(h,6)),this.setFunctionModule(8,8,o(h,7)),this.setFunctionModule(7,8,o(h,8));for(var S=9;S<15;S++)this.setFunctionModule(14-S,8,o(h,S));for(var S=0;S<8;S++)this.setFunctionModule(this.size-1-S,8,o(h,S));for(var S=8;S<15;S++)this.setFunctionModule(8,this.size-15+S,o(h,S));this.setFunctionModule(8,this.size-8,!0)},d.prototype.drawVersion=function(){if(!(this.version<7)){for(var u=this.version,_=0;_<12;_++)u=u<<1^(u>>>11)*7973;var p=this.version<<12|u;c(p>>>18==0);for(var _=0;_<18;_++){var S=o(p,_),h=this.size-11+_%3,y=Math.floor(_/3);this.setFunctionModule(h,y,S),this.setFunctionModule(y,h,S)}}},d.prototype.drawFinderPattern=function(u,_){for(var p=-4;p<=4;p++)for(var S=-4;S<=4;S++){var h=Math.max(Math.abs(S),Math.abs(p)),y=u+S,O=_+p;0<=y&&y<this.size&&0<=O&&O<this.size&&this.setFunctionModule(y,O,h!=2&&h!=4)}},d.prototype.drawAlignmentPattern=function(u,_){for(var p=-2;p<=2;p++)for(var S=-2;S<=2;S++)this.setFunctionModule(u+S,_+p,Math.max(Math.abs(S),Math.abs(p))!=1)},d.prototype.setFunctionModule=function(u,_,p){this.modules[_][u]=p,this.isFunction[_][u]=!0},d.prototype.addEccAndInterleave=function(u){var _=this.version,p=this.errorCorrectionLevel;if(u.length!=d.getNumDataCodewords(_,p))throw new RangeError("Invalid argument");for(var S=d.NUM_ERROR_CORRECTION_BLOCKS[p.ordinal][_],h=d.ECC_CODEWORDS_PER_BLOCK[p.ordinal][_],y=Math.floor(d.getNumRawDataModules(_)/8),O=S-y%S,N=Math.floor(y/S),w=[],L=d.reedSolomonComputeDivisor(h),D=0,U=0;D<S;D++){var x=u.slice(U,U+N-h+(D<O?0:1));U+=x.length;var G=d.reedSolomonComputeRemainder(x,L);D<O&&x.push(0),w.push(x.concat(G))}for(var F=[],z=function($){w.forEach(function(V,ee){($!=N-h||ee>=O)&&F.push(V[$])})},D=0;D<w[0].length;D++)z(D);return c(F.length==y),F},d.prototype.drawCodewords=function(u){if(u.length!=Math.floor(d.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");for(var _=0,p=this.size-1;p>=1;p-=2){p==6&&(p=5);for(var S=0;S<this.size;S++)for(var h=0;h<2;h++){var y=p-h,O=(p+1&2)==0,N=O?this.size-1-S:S;!thiLine truncated
|
||||
@@ -1,14 +0,0 @@
|
||||
import{s as Nn,l as Ln,m as Pn,n as ll,p as Rn,f as yl,U as bt,d as Fn,g as At,i as Vt,c as Nt,h as Cl,e as st,q as Tn,E as zn,t as Mn,b as On}from"./el-input-CNNwOXGP.js";import"./el-tag-5pOVEKUY.js";import{b as _n,i as wl,a as $n,E as Wn,d as dt,c as Sl}from"./el-select-LRJf3l5x.js";import{i as yt,g as Bn,k as Hn,c as An,a as xl,b as Vn,d as In,e as Kn,f as Dn,h as jn,j as Un,S as qn,E as El,C as Gn}from"./el-popper-C96qJ_vz.js";import"./el-tooltip-l0sNRNKZ.js";import{b3 as It,b4 as Yn,b5 as kl,b6 as Nl,b7 as Xn,b8 as Qn,b9 as Lt,ba as Jn,bb as Zn,E as Ie,G as we,e as ce,ag as Fe,ah as Ct,i as he,c as R,a7 as Le,aT as de,$ as ie,F as _e,s as N,al as oe,ai as Be,f as Xe,bc as nl,_ as Pe,a as j,aG as Ll,u as se,g as re,o as z,w as ee,N as te,P as V,Q as ge,h as W,j as C,A as Oe,O as ft,J as Qe,bd as ht,r as Te,ab as Ke,U as He,R as J,k as wt,n as Ae,b as $e,d as Kt,p as Dt,x as Pl,l as jt,ak as Ut,aV as pt,ao as Me,W as et,q as Rl,m as Fl,B as U,ac as vt,aW as Ve,be as ea,bf as al,bg as ta,S as la,bh as na,z as B,aS as qt,bi as aa,a5 as Je,a2 as Ne,a4 as ol,bj as Tl,a3 as oa,bk as sl,M as ke,bl as zl,bm as sa,aR as ra,bn as Ml,a0 as tt,aL as ia,aD as Gt,aQ as qe,D as Ze,a6 as ua,I as gt,t as ca,bo as rl,aY as il,C as ul,a1 as Ol,Y as da,bp as fa,a8 as ha,af as St,aF as xt}from"./index-CxMsK_Ni.js";function pa(e,t){return Nn(Ln(e,t,Pn),e+"")}function va(e,t,l){if(!It(l))return!1;var n=typeof t;return(n=="number"?yt(l)&&Yn(t,l.length):n=="string"&&t in l)?kl(l[t],e):!1}function ga(e){return pa(function(t,l){var n=-1,o=l.length,s=o>1?l[o-1]:void 0,i=o>2?l[2]:void 0;for(s=e.length>3&&typeof s=="function"?(o--,s):void 0,i&&va(l[0],l[1],i)&&(s=o<3?void 0:s,o=1),t=Object(t);++n<o;){var a=l[n];a&&e(t,a,n,s)}return t})}var ma="[object Object]",ba=Function.prototype,ya=Object.prototype,_l=ba.toString,Ca=ya.hasOwnProperty,wa=_l.call(Object);function Sa(e){if(!Nl(e)||Xn(e)!=ma)return!1;var t=Bn(e);if(t===null)return!0;var l=Ca.call(t,"constructor")&&t.constructor;return typeof l=="function"&&l instanceof l&&_l.call(l)==wa}function xa(e){return function(t,l,n){for(var o=-1,s=Object(t),i=n(t),a=i.length;a--;){var r=i[++o];if(l(s[r],r,s)===!1)break}return t}}var $l=xa();function Ea(e,t){return e&&$l(e,t,Hn)}function ka(e,t){return function(l,n){if(l==null)return l;if(!yt(l))return e(l,n);for(var o=l.length,s=-1,i=Object(l);++s<o&&n(i[s],s,i)!==!1;);return l}}var Na=ka(Ea);function Pt(e,t,l){(l!==void 0&&!kl(e[t],l)||l===void 0&&!(t in e))&&Qn(e,t,l)}function La(e){return Nl(e)&&yt(e)}function Rt(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}function Pa(e){return An(e,xl(e))}function Ra(e,t,l,n,o,s,i){var a=Rt(e,l),r=Rt(t,l),u=i.get(r);if(u){Pt(e,l,u);return}var d=s?s(a,r,l+"",e,t,i):void 0,f=d===void 0;if(f){var v=Lt(r),y=!v&&Vn(r),h=!v&&!y&&In(r);d=r,v||y||h?Lt(a)?d=a:La(a)?d=Kn(a):y?(f=!1,d=Dn(r,!0)):h?(f=!1,d=jn(r,!0)):d=[]:Sa(r)||ll(r)?(d=a,ll(a)?d=Pa(a):(!It(a)||Jn(a))&&(d=Un(r))):f=!1}f&&(i.set(r,d),o(d,r,n,s,i),i.delete(r)),Pt(e,l,d)}function Wl(e,t,l,n,o){e!==t&&$l(t,function(s,i){if(o||(o=new qn),It(s))Ra(e,t,i,l,Wl,n,o);else{var a=n?n(Rt(e,i),s,i+"",e,t,o):void 0;a===void 0&&(a=s),Pt(e,i,a)}},xl)}function Fa(e,t){var l=-1,n=yt(e)?Array(e.length):[];return Na(e,function(o,s,i){n[++l]=t(o,s,i)}),n}function Ta(e,t){var l=Lt(e)?Zn:Fa;return l(e,_n(t))}function za(e,t){return Rn(Ta(e,t))}function lt(e){return e===null}var Bl=ga(function(e,t,l){Wl(e,t,l)});const Ma=e=>Ie?window.requestAnimationFrame(e):setTimeout(e,16),Hl={modelValue:{type:[Number,String,Boolean],default:void 0},label:{type:[String,Boolean,Number,Object],default:void 0},value:{type:[String,Boolean,Number,Object],default:void 0},indeterminate:Boolean,disabled:Boolean,checked:Boolean,name:{type:String,default:void 0},trueValue:{type:[String,Number],default:void 0},falseValue:{type:[String,Number],default:void 0},trueLabel:{type:[String,Number],default:void 0},falseLabel:{type:[String,Number],default:void 0},id:{type:String,default:void 0},border:Boolean,size:Ct,tabindex:[String,Number],validateEvent:{type:Boolean,default:!0},...yl(["ariaControls"])},Al={[bt]:e=>we(e)||ce(e)||Fe(e),change:e=>we(e)||ce(e)||Fe(e)},Ue=Symbol("checkboxGroupContextKey"),Oa=({model:e,isChecked:t})=>{const l=he(Ue,void 0),n=R(()=>{var s,i;const a=(s=l==null?void 0:l.max)==null?void 0:s.value,r=(i=l==null?void 0:l.min)==null?void 0:i.value;return!Le(a)&&e.value.length>=a&&!t.value||!Le(r)&&e.value.length<=r&&t.value});return{isDisabled:Fn(R(()=>(l==null?void 0:l.disabled.value)||n.value)),isLimitDisabled:n}},_a=(e,{model:t,isLimitExceeded:l,hasOwnLabel:n,isDisabled:o,isLabeledByFormItem:s})=>{const i=he(Ue,void 0),{formItem:a}=At(),{emit:r}=de();function u(h){var b,w,S,P;return[!0,e.trueValue,e.trueLabel].includes(h)?(w=(b=e.trueValue)!=null?b:e.trueLabel)!=null?w:!0:(P=(S=e.falseValue)!=null?S:e.falseLabel)!=null?P:!1}function d(h,b){r("change",u(h),b)}function f(h){if(l.value)return;const b=h.target;r("change",u(b.checked),h)}async functionLine truncated
|
||||
* Checks if an event is supported in the current execution environment.
|
||||
*
|
||||
* NOTE: This will not work correctly for non-generic events such as `change`,
|
||||
* `reset`, `load`, `error`, and `select`.
|
||||
*
|
||||
* Borrows from Modernizr.
|
||||
*
|
||||
* @param {string} eventNameSuffix Event name, e.g. "click".
|
||||
* @param {?boolean} capture Check if the capture phase is supported.
|
||||
* @return {boolean} True if the event is supported.
|
||||
* @internal
|
||||
* @license Modernizr 3.0.0pre (Custom Build) | MIT
|
||||
*/const gs=function(e,t){if(e&&e.addEventListener){const l=function(n){const o=vs(n);t&&Reflect.apply(t,this,[n,o])};e.addEventListener("wheel",l,{passive:!0})}},ms={beforeMount(e,t){gs(e,t.value)}};let bs=1;const ys=j({name:"ElTable",directives:{Mousewheel:ms},components:{TableHeader:qo,TableBody:ts,TableFooter:as,ElScrollbar:Sl,hColgroup:Zl},props:is,emits:["select","select-all","selection-change","cell-mouse-enter","cell-mouse-leave","cell-contextmenu","cell-click","cell-dblclick","row-click","row-contextmenu","row-dblclick","header-click","header-contextmenu","sort-change","filter-change","current-change","header-dragend","expand-change","scroll"],setup(e){const{t}=Me(),l=se("table"),n=de();Dt(Re,n);const o=Wo(n,e);n.store=o;const s=new Ho({store:n.store,table:n,fit:e.fit,showHeader:e.showHeader});n.layout=s;const i=R(()=>(o.states.data.value||[]).length===0),{setCurrentRow:a,getSelectionRows:r,toggleRowSelection:u,clearSelection:d,clearFilter:f,toggleAllSelection:v,toggleRowExpansion:y,clearSort:h,sort:b,updateKeyChildren:w}=os(o),{isHidden:S,renderExpanded:P,setDragVisible:E,isGroup:c,handleMouseLeave:p,handleHeaderFooterMousewheel:g,tableSize:m,emptyBlockStyle:x,handleFixedMousewheel:L,resizeProxyVisible:M,bodyWidth:$,resizeState:O,doLayout:I,tableBodyStyles:Y,tableLayout:K,scrollbarViewStyle:q,scrollbarStyle:X}=ss(e,s,o,n),{scrollBarRef:T,scrollTo:k,setScrollLeft:_,setScrollTop:Z}=us(),le=dt(I,50),ne=`${l.namespace.value}-table_${bs++}`;n.tableId=ne,n.state={isGroup:c,resizeState:O,doLayout:I,debouncedUpdateLayout:le};const pe=R(()=>{var ue;return(ue=e.sumText)!=null?ue:t("el.table.sumText")}),me=R(()=>{var ue;return(ue=e.emptyText)!=null?ue:t("el.table.emptyText")}),Ee=R(()=>Jl(o.states.originColumns.value)[0]);return rs(n),Ol(()=>{le.cancel()}),{ns:l,layout:s,store:o,columns:Ee,handleHeaderFooterMousewheel:g,handleMouseLeave:p,tableId:ne,tableSize:m,isHidden:S,isEmpty:i,renderExpanded:P,resizeProxyVisible:M,resizeState:O,isGroup:c,bodyWidth:$,tableBodyStyles:Y,emptyBlockStyle:x,debouncedUpdateLayout:le,handleFixedMousewheel:L,setCurrentRow:a,getSelectionRows:r,toggleRowSelection:u,clearSelection:d,clearFilter:f,toggleAllSelection:v,toggleRowExpansion:y,clearSort:h,doLayout:I,sort:b,updateKeyChildren:w,t,setDragVisible:E,context:n,computedSumText:pe,computedEmptyText:me,tableLayout:K,scrollbarViewStyle:q,scrollbarStyle:X,scrollBarRef:T,scrollTo:k,setScrollLeft:_,setScrollTop:Z,allowDragLastColumn:e.allowDragLastColumn}}});function Cs(e,t,l,n,o,s){const i=ke("hColgroup"),a=ke("table-header"),r=ke("table-body"),u=ke("table-footer"),d=ke("el-scrollbar"),f=zl("mousewheel");return z(),V("div",{ref:"tableWrapper",class:W([{[e.ns.m("fit")]:e.fit,[e.ns.m("striped")]:e.stripe,[e.ns.m("border")]:e.border||e.isGroup,[e.ns.m("hidden")]:e.isHidden,[e.ns.m("group")]:e.isGroup,[e.ns.m("fluid-height")]:e.maxHeight,[e.ns.m("scrollable-x")]:e.layout.scrollX.value,[e.ns.m("scrollable-y")]:e.layout.scrollY.value,[e.ns.m("enable-row-hover")]:!e.store.states.isComplex.value,[e.ns.m("enable-row-transition")]:(e.store.states.data.value||[]).length!==0&&(e.store.states.data.value||[]).length<100,"has-footer":e.showSummary},e.ns.m(e.tableSize),e.className,e.ns.b(),e.ns.m(`layout-${e.tableLayout}`)]),style:Ae(e.style),"data-prefix":e.ns.namespace.value,onMouseleave:e.handleMouseLeave},[te("div",{class:W(e.ns.e("inner-wrapper"))},[te("div",{ref:"hiddenColumns",class:"hidden-columns"},[Te(e.$slots,"default")],512),e.showHeader&&e.tableLayout==="fixed"?Oe((z(),V("div",{key:0,ref:"headerWrapper",class:W(e.ns.e("header-wrapper"))},[te("table",{ref:"tableHeader",class:W(e.ns.e("header")),style:Ae(e.tableBodyStyles),border:"0",cellpadding:"0",cellspacing:"0"},[U(i,{columns:e.store.states.columns.value,"table-layout":e.tableLayout},null,8,["columns","table-layout"]),U(a,{ref:"tableHeaderRef",border:e.border,"default-sort":e.defaultSort,store:e.store,"append-filter-panel-to":e.appendFilterPanelTo,"allow-drag-last-column":e.allowDragLastColumn,onSetDragVisible:e.setDragVisible},null,8,["border","default-sort","store","append-filter-panel-to","allow-drag-last-column","onSetDragVisible"])],6)],2)),[[f,e.handleHeaderFooterMousewheel]]):ge("v-if",!0),te("div",{ref:"bodyWrapper",class:W(e.ns.e("body-wrapper"))},[U(d,{ref:"scrollBarRef","view-style":e.scrollbarViewStyle,"wrap-style":e.scrollbarStyle,always:e.scrollbarAlwaysOn,tabindex:e.scrollbarTabindex,onScroll:v=>e.$emit("scroll",v)},{default:ee(()=>[te("table",{ref:"tableBody",class:W(e.ns.e("body")),cellspacing:"0",cellpadding:"0",border:"0",style:Ae({width:e.bodyWidth,tableLayout:e.tableLayout})},[U(i,{columns:e.store.states.columns.value,"table-layout":e.tableLayout},null,8,["columns","table-layout"]),e.showHeader&&e.tableLayout==="auto"?(z(),re(a,{key:0,ref:"tableHeaderRef",class:W(e.ns.e("body-header")),border:e.border,"default-sort":e.defaultSort,store:e.store,"append-filter-panel-to":e.appendFilterPanelTo,onSetDragVisible:e.setDragVisible},null,8,["class","border","default-sort"Line truncated
|
||||
@@ -1 +0,0 @@
|
||||
.el-pagination{--el-pagination-font-size:14px;--el-pagination-bg-color:var(--el-fill-color-blank);--el-pagination-text-color:var(--el-text-color-primary);--el-pagination-border-radius:2px;--el-pagination-button-color:var(--el-text-color-primary);--el-pagination-button-width:32px;--el-pagination-button-height:32px;--el-pagination-button-disabled-color:var(--el-text-color-placeholder);--el-pagination-button-disabled-bg-color:var(--el-fill-color-blank);--el-pagination-button-bg-color:var(--el-fill-color);--el-pagination-hover-color:var(--el-color-primary);--el-pagination-font-size-small:12px;--el-pagination-button-width-small:24px;--el-pagination-button-height-small:24px;--el-pagination-button-width-large:40px;--el-pagination-button-height-large:40px;--el-pagination-item-gap:16px;align-items:center;color:var(--el-pagination-text-color);display:flex;font-size:var(--el-pagination-font-size);font-weight:400;white-space:nowrap}.el-pagination .el-input__inner{-moz-appearance:textfield;text-align:center}.el-pagination .el-select{width:128px}.el-pagination button{align-items:center;background:var(--el-pagination-bg-color);border:none;border-radius:var(--el-pagination-border-radius);box-sizing:border-box;color:var(--el-pagination-button-color);cursor:pointer;display:flex;font-size:var(--el-pagination-font-size);height:var(--el-pagination-button-height);justify-content:center;line-height:var(--el-pagination-button-height);min-width:var(--el-pagination-button-width);padding:0 4px;text-align:center}.el-pagination button *{pointer-events:none}.el-pagination button:focus{outline:none}.el-pagination button.is-active,.el-pagination button:hover{color:var(--el-pagination-hover-color)}.el-pagination button.is-active{cursor:default;font-weight:700}.el-pagination button.is-active.is-disabled{color:var(--el-text-color-secondary);font-weight:700}.el-pagination button.is-disabled,.el-pagination button:disabled{background-color:var(--el-pagination-button-disabled-bg-color);color:var(--el-pagination-button-disabled-color);cursor:not-allowed}.el-pagination button:focus-visible{outline:1px solid var(--el-pagination-hover-color);outline-offset:-1px}.el-pagination .btn-next .el-icon,.el-pagination .btn-prev .el-icon{display:block;font-size:12px;font-weight:700;width:inherit}.el-pagination>.is-first{margin-left:0!important}.el-pagination>.is-last{margin-right:0!important}.el-pagination .btn-prev{margin-left:var(--el-pagination-item-gap)}.el-pagination__sizes,.el-pagination__total{color:var(--el-text-color-regular);font-weight:400;margin-left:var(--el-pagination-item-gap)}.el-pagination__total[disabled=true]{color:var(--el-text-color-placeholder)}.el-pagination__jump{align-items:center;color:var(--el-text-color-regular);display:flex;font-weight:400;margin-left:var(--el-pagination-item-gap)}.el-pagination__jump[disabled=true]{color:var(--el-text-color-placeholder)}.el-pagination__goto{margin-right:8px}.el-pagination__editor{box-sizing:border-box;text-align:center}.el-pagination__editor.el-input{width:56px}.el-pagination__editor .el-input__inner::-webkit-inner-spin-button,.el-pagination__editor .el-input__inner::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}.el-pagination__classifier{margin-left:8px}.el-pagination__rightwrapper{align-items:center;display:flex;flex:1;justify-content:flex-end}.el-pagination.is-background .btn-next,.el-pagination.is-background .btn-prev,.el-pagination.is-background .el-pager li{background-color:var(--el-pagination-button-bg-color);margin:0 4px}.el-pagination.is-background .btn-next.is-active,.el-pagination.is-background .btn-prev.is-active,.el-pagination.is-background .el-pager li.is-active{background-color:var(--el-color-primary);color:var(--el-color-white)}.el-pagination.is-background .btn-next.is-disabled,.el-pagination.is-background .btn-next:disabled,.el-pagination.is-background .btn-prev.is-disabled,.el-pagination.is-background .btn-prev:disabled,.el-pagination.is-background .el-pager li.is-disabled,.el-pagination.is-background .el-pager li:disabled{background-color:var(--el-disabled-bg-color);color:var(--el-text-color-placeholder)}.el-pagination.is-background .btn-next.is-disabled.is-active,.el-pagination.is-background .btn-next:disabled.is-active,.el-pagination.is-background .btn-prev.is-disabled.is-active,.el-pagination.is-background .btn-prev:disabled.is-active,.el-pagination.is-background .el-pager li.is-disabled.is-active,.el-pagination.is-background .el-pager li:disabled.is-active{background-color:var(--el-fill-color-dark);color:var(--el-text-color-secondary)}.el-pagination.is-background .btn-prev{margin-left:var(--el-pagination-item-gap)}.el-pagination--small .btn-next,.el-pagination--small .btn-prev,.el-pagination--small .el-pager li{font-size:var(--el-pagination-font-size-small);height:var(--el-pagination-button-height-small);line-height:var(--el-pagination-button-height-small);min-width:var(--el-pagination-button-width-small)}.el-pagination--small button,.el-pagination--small spanLine truncated
|
||||
@@ -1 +0,0 @@
|
||||
:root{--el-loading-spinner-size:42px;--el-loading-fullscreen-spinner-size:50px}.el-loading-parent--relative{position:relative!important}.el-loading-parent--hidden{overflow:hidden!important}.el-loading-mask{background-color:var(--el-mask-color);bottom:0;left:0;margin:0;position:absolute;right:0;top:0;transition:opacity var(--el-transition-duration);z-index:2000}.el-loading-mask.is-fullscreen{position:fixed}.el-loading-mask.is-fullscreen .el-loading-spinner{margin-top:calc((0px - var(--el-loading-fullscreen-spinner-size))/2)}.el-loading-mask.is-fullscreen .el-loading-spinner .circular{height:var(--el-loading-fullscreen-spinner-size);width:var(--el-loading-fullscreen-spinner-size)}.el-loading-spinner{margin-top:calc((0px - var(--el-loading-spinner-size))/2);position:absolute;text-align:center;top:50%;width:100%}.el-loading-spinner .el-loading-text{color:var(--el-color-primary);font-size:14px;margin:3px 0}.el-loading-spinner .circular{animation:loading-rotate 2s linear infinite;display:inline;height:var(--el-loading-spinner-size);width:var(--el-loading-spinner-size)}.el-loading-spinner .path{animation:loading-dash 1.5s ease-in-out infinite;stroke-dasharray:90,150;stroke-dashoffset:0;stroke-width:2;stroke:var(--el-color-primary);stroke-linecap:round}.el-loading-spinner i{color:var(--el-color-primary)}.el-loading-fade-enter-from,.el-loading-fade-leave-to{opacity:0}@keyframes loading-rotate{to{transform:rotate(1turn)}}@keyframes loading-dash{0%{stroke-dasharray:1,200;stroke-dashoffset:0}50%{stroke-dasharray:90,150;stroke-dashoffset:-40px}to{stroke-dasharray:90,150;stroke-dashoffset:-120px}}.el-row{box-sizing:border-box;display:flex;flex-wrap:wrap;position:relative}.el-row.is-justify-center{justify-content:center}.el-row.is-justify-end{justify-content:flex-end}.el-row.is-justify-space-between{justify-content:space-between}.el-row.is-justify-space-around{justify-content:space-around}.el-row.is-justify-space-evenly{justify-content:space-evenly}.el-row.is-align-top{align-items:flex-start}.el-row.is-align-middle{align-items:center}.el-row.is-align-bottom{align-items:flex-end}[class*=el-col-]{box-sizing:border-box}[class*=el-col-].is-guttered{display:block;min-height:1px}.el-col-0{flex:0 0 0%;max-width:0}.el-col-0,.el-col-0.is-guttered{display:none}.el-col-offset-0{margin-left:0}.el-col-pull-0{position:relative;right:0}.el-col-push-0{left:0;position:relative}.el-col-1{flex:0 0 4.1666666667%;max-width:4.1666666667%}.el-col-1,.el-col-1.is-guttered{display:block}.el-col-offset-1{margin-left:4.1666666667%}.el-col-pull-1{position:relative;right:4.1666666667%}.el-col-push-1{left:4.1666666667%;position:relative}.el-col-2{flex:0 0 8.3333333333%;max-width:8.3333333333%}.el-col-2,.el-col-2.is-guttered{display:block}.el-col-offset-2{margin-left:8.3333333333%}.el-col-pull-2{position:relative;right:8.3333333333%}.el-col-push-2{left:8.3333333333%;position:relative}.el-col-3{flex:0 0 12.5%;max-width:12.5%}.el-col-3,.el-col-3.is-guttered{display:block}.el-col-offset-3{margin-left:12.5%}.el-col-pull-3{position:relative;right:12.5%}.el-col-push-3{left:12.5%;position:relative}.el-col-4{flex:0 0 16.6666666667%;max-width:16.6666666667%}.el-col-4,.el-col-4.is-guttered{display:block}.el-col-offset-4{margin-left:16.6666666667%}.el-col-pull-4{position:relative;right:16.6666666667%}.el-col-push-4{left:16.6666666667%;position:relative}.el-col-5{flex:0 0 20.8333333333%;max-width:20.8333333333%}.el-col-5,.el-col-5.is-guttered{display:block}.el-col-offset-5{margin-left:20.8333333333%}.el-col-pull-5{position:relative;right:20.8333333333%}.el-col-push-5{left:20.8333333333%;position:relative}.el-col-6{flex:0 0 25%;max-width:25%}.el-col-6,.el-col-6.is-guttered{display:block}.el-col-offset-6{margin-left:25%}.el-col-pull-6{position:relative;right:25%}.el-col-push-6{left:25%;position:relative}.el-col-7{flex:0 0 29.1666666667%;max-width:29.1666666667%}.el-col-7,.el-col-7.is-guttered{display:block}.el-col-offset-7{margin-left:29.1666666667%}.el-col-pull-7{position:relative;right:29.1666666667%}.el-col-push-7{left:29.1666666667%;position:relative}.el-col-8{flex:0 0 33.3333333333%;max-width:33.3333333333%}.el-col-8,.el-col-8.is-guttered{display:block}.el-col-offset-8{margin-left:33.3333333333%}.el-col-pull-8{position:relative;right:33.3333333333%}.el-col-push-8{left:33.3333333333%;position:relative}.el-col-9{flex:0 0 37.5%;max-width:37.5%}.el-col-9,.el-col-9.is-guttered{display:block}.el-col-offset-9{margin-left:37.5%}.el-col-pull-9{position:relative;right:37.5%}.el-col-push-9{left:37.5%;position:relative}.el-col-10{flex:0 0 41.6666666667%;max-width:41.6666666667%}.el-col-10,.el-col-10.is-guttered{display:block}.el-col-offset-10{margin-left:41.6666666667%}.el-col-pull-10{position:relative;right:41.6666666667%}.el-col-push-10{left:41.6666666667%;position:relative}.el-col-11{flex:0 0 45.8333333333%;max-width:45.8333333333%}.el-col-11,.el-col-11.is-guttered{display:block}.el-col-offset-11{margin-left:45.8333333333%}.el-col-pull-11{position:relative;right:45.8333Line truncated
|
||||
@@ -1 +0,0 @@
|
||||
import{o as he,E as Ae,a as We,b as Re,u as Ce}from"./el-input-CNNwOXGP.js";import{E as Xe,u as Ye,a as xe,b as Je,c as Qe,d as en}from"./config-CZWWa62X.js";import{b as Ve,m as H,d as U,_ as de,a as P,i as nn,c as k,u as _e,e as we,f as le,g as T,o as h,w as v,r as fe,n as se,h as p,j as E,k as j,l as Oe,p as tn,q as on,s as M,t as me,v as sn,x as Ne,y as Pe,z as q,A as G,B as m,C as te,T as ze,D as ae,E as je,F as O,G as Y,H as Z,I as Ee,J as an,K as ln,L as rn,M as z,N as $,O as Q,P as D,Q as _,R as V,S as ee,U as W,V as un,W as cn,X as ke,Y as Be,Z as $e,$ as ie,a0 as De,a1 as dn,a2 as ue,a3 as Fe,a4 as Ke,a5 as Se,a6 as Ie,a7 as fn,a8 as mn,a9 as vn,aa as pn,ab as gn,ac as bn,ad as yn,ae as hn,af as Cn}from"./index-CxMsK_Ni.js";import{u as wn,a as En,_ as kn}from"./CardTools.vue_vue_type_script_setup_true_lang-CdJKhv07.js";import"./vnode-Cc0RQjVK.js";import"./el-tag-5pOVEKUY.js";import"./index-CBpXPsVN.js";const Bn=Ve({tag:{type:String,default:"div"},span:{type:Number,default:24},offset:{type:Number,default:0},pull:{type:Number,default:0},push:{type:Number,default:0},xs:{type:U([Number,Object]),default:()=>H({})},sm:{type:U([Number,Object]),default:()=>H({})},md:{type:U([Number,Object]),default:()=>H({})},lg:{type:U([Number,Object]),default:()=>H({})},xl:{type:U([Number,Object]),default:()=>H({})}}),He=Symbol("rowContextKey"),$n=P({name:"ElCol"}),Sn=P({...$n,props:Bn,setup(e){const n=e,{gutter:t}=nn(He,{gutter:k(()=>0)}),s=_e("col"),r=k(()=>{const l={};return t.value&&(l.paddingLeft=l.paddingRight=`${t.value/2}px`),l}),a=k(()=>{const l=[];return["span","offset","pull","push"].forEach(o=>{const g=n[o];we(g)&&(o==="span"?l.push(s.b(`${n[o]}`)):g>0&&l.push(s.b(`${o}-${n[o]}`)))}),["xs","sm","md","lg","xl"].forEach(o=>{we(n[o])?l.push(s.b(`${o}-${n[o]}`)):le(n[o])&&Object.entries(n[o]).forEach(([g,b])=>{l.push(g!=="span"?s.b(`${o}-${g}-${b}`):s.b(`${o}-${b}`))})}),t.value&&l.push(s.is("guttered")),[s.b(),l]});return(l,c)=>(h(),T(j(l.tag),{class:p(E(a)),style:se(E(r))},{default:v(()=>[fe(l.$slots,"default")]),_:3},8,["class","style"]))}});var In=de(Sn,[["__file","col.vue"]]);const Ln=Oe(In),Tn=["start","center","end","space-around","space-between","space-evenly"],Mn=["top","middle","bottom"],An=Ve({tag:{type:String,default:"div"},gutter:{type:Number,default:0},justify:{type:String,values:Tn,default:"start"},align:{type:String,values:Mn}}),Rn=P({name:"ElRow"}),Vn=P({...Rn,props:An,setup(e){const n=e,t=_e("row"),s=k(()=>n.gutter);tn(He,{gutter:s});const r=k(()=>{const l={};return n.gutter&&(l.marginRight=l.marginLeft=`-${n.gutter/2}px`),l}),a=k(()=>[t.b(),t.is(`justify-${n.justify}`,n.justify!=="start"),t.is(`align-${n.align}`,!!n.align)]);return(l,c)=>(h(),T(j(l.tag),{class:p(E(a)),style:se(E(r))},{default:v(()=>[fe(l.$slots,"default")]),_:3},8,["class","style"]))}});var _n=de(Vn,[["__file","row.vue"]]);const On=Oe(_n),Nn=e=>["",...on].includes(e);function Pn(e){let n;const t=M(!1),s=me({...e,originalPosition:"",originalOverflow:"",visible:!1});function r(i){s.text=i}function a(){const i=s.parent,f=b.ns;if(!i.vLoadingAddClassList){let u=i.getAttribute("loading-number");u=Number.parseInt(u)-1,u?i.setAttribute("loading-number",u.toString()):(ae(i,f.bm("parent","relative")),i.removeAttribute("loading-number")),ae(i,f.bm("parent","hidden"))}l(),g.unmount()}function l(){var i,f;(f=(i=b.$el)==null?void 0:i.parentNode)==null||f.removeChild(b.$el)}function c(){var i;e.beforeClose&&!e.beforeClose()||(t.value=!0,clearTimeout(n),n=setTimeout(y,400),s.visible=!1,(i=e.closed)==null||i.call(e))}function y(){if(!t.value)return;const i=s.parent;t.value=!1,i.vLoadingAddClassList=void 0,a()}const o=P({name:"ElLoading",setup(i,{expose:f}){const{ns:u,zIndex:C}=Pe("loading");return f({ns:u,zIndex:C}),()=>{const w=s.spinner||s.svg,B=q("svg",{class:"circular",viewBox:s.svgViewBox?s.svgViewBox:"0 0 50 50",...w?{innerHTML:w}:{}},[q("circle",{class:"path",cx:"25",cy:"25",r:"20",fill:"none"})]),A=s.text?q("p",{class:u.b("text")},[s.text]):void 0;return q(ze,{name:u.b("fade"),onAfterLeave:y},{default:v(()=>[G(m("div",{style:{backgroundColor:s.background||""},class:[u.b("mask"),s.customClass,s.fullscreen?"is-fullscreen":""]},[q("div",{class:u.b("spinner")},[B,A])]),[[te,s.visible]])])})}}}),g=sn(o),b=g.mount(document.createElement("div"));return{...Ne(s),setText:r,removeElLoadingChild:l,close:c,handleAfterLeave:y,vm:b,get $el(){return b.$el}}}let ne;const zn=function(e={}){if(!je)return;const n=jn(e);if(n.fullscreen&&ne)return ne;const t=Pn({...n,closed:()=>{var r;(r=n.closed)==null||r.call(n),n.fullscreen&&(ne=void 0)}});Dn(n,n.parent,t),Le(n,n.parent,t),n.parent.vLoadingAddClassList=()=>Le(n,n.parent,t);let s=n.parent.getAttribute("loading-number");return s?s=`${Number.parseInt(s)+1}`:s="1",n.parent.setAttribute("loading-number",s),n.parent.appendChild(t.$el),O(()=>t.visible.value=n.visible),n.fullscreen&&(ne=t),t},jn=e=>{var n,t,s,r;let a;return Y(e.target)?a=(n=document.querySelector(e.target))!=null?n:document.body:a=e.target||docLine truncated
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user