Compare commits

...
143 Commits
Author SHA1 Message Date
Lan 5c72562af7 chore: rebuild docker image 2026-06-16 01:35:42 +08:00
Lan cdaf3638b8 feat: add first-run setup security flow 2026-06-16 00:49:43 +08:00
Lan 1b6d8e7277 fix: harden share rate limit and code generation (#479) 2026-06-09 00:53:11 +08:00
Lan eb6fc627ae feat: update me 2026-06-05 21:14:37 +08:00
Lan c1fb802223 fix: #473 normalize retrieve codes before lookup 2026-06-05 11:40:11 +08:00
Lan 1d03337e2f fix: #476 serve assets from selected theme 2026-06-05 11:37:44 +08:00
Lan 8d6eaacb70 fix: #478 make s3 upload confirmation resilient 2026-06-05 11:33:21 +08:00
Lan 3fe136536e fix: #461 support s3 path style addressing 2026-06-05 11:32:31 +08:00
Lan aa6904a12c fix: #465 restrict uploads by allowed file types 2026-06-05 11:29:37 +08:00
Lan 135dfdda9d fix: #464 serialize admin file list items safely 2026-06-05 11:28:22 +08:00
Lan e3ea7825bf fix: build frontend with pnpm in Docker 2026-06-03 19:56:39 +08:00
Lan 6759539078 Merge branch 'feature/ux-compat-platform' 2026-06-03 18:40:50 +08:00
Lan 530f52aa1e refactor: centralize app version 2026-06-03 12:22:12 +08:00
Lan b859ec211e refactor: remove settings diagnostics recommendations 2026-06-03 10:37:17 +08:00
Lan 8ac367d0b8 refactor: remove admin recommendation summaries 2026-06-03 10:24:07 +08:00
Lan 63cf725802 feat: add admin file view summary 2026-06-03 10:00:58 +08:00
Lan ccbc710d74 feat: add admin maintenance queue 2026-06-03 08:18:41 +08:00
Lan 2d18b02005 feat: add admin config diagnostics 2026-06-03 08:01:55 +08:00
Lan e75fe596d0 feat: add admin operational insights 2026-06-03 07:47:33 +08:00
Lan be7ce2b30e feat: add admin activity timeline filters 2026-06-03 07:36:48 +08:00
Lan 0dbb594f4a feat: add admin activity stream 2026-06-03 07:19:56 +08:00
Lan b6aa28c345 feat: add admin file view presets 2026-06-03 07:01:38 +08:00
Lan fc6046a663 feat: add admin file metadata 2026-06-03 06:37:56 +08:00
Lan 3467e973ac feat: add batch file policy actions 2026-06-03 06:22:56 +08:00
Lan a1de598277 feat: add dashboard health actions 2026-06-03 06:15:15 +08:00
Lan 1ba0d2a044 feat: add admin file health filters 2026-06-03 05:55:18 +08:00
Lan 1f0b0b791c feat: add admin file policy actions 2026-06-03 05:45:02 +08:00
Lan 4ae53fc4a5 feat: add admin file detail insights 2026-06-03 05:28:11 +08:00
Lan 35e069ccc3 feat: add admin file detail endpoint 2026-06-03 04:58:19 +08:00
Lan 2fa1faebe0 feat: add admin batch file policy update 2026-06-03 04:38:30 +08:00
Lan 0ced9b1f38 feat: add admin batch file deletion 2026-06-03 04:24:16 +08:00
Lan 1eb69e4cc5 feat: add admin text preview endpoint 2026-06-03 04:05:52 +08:00
Lan 71fc1ad8ea feat: enhance admin file list filters 2026-06-03 03:45:30 +08:00
Lan 64ebc59a84 feat: expand dashboard statistics 2026-06-03 03:32:12 +08:00
Lan 78b1dbe81f feat: add retrieve metadata endpoint 2026-06-03 03:17:01 +08:00
Lan 6805206efd fix: tolerate partial config updates 2026-06-03 03:08:19 +08:00
Lan 6fe68be2dd fix: support legacy presign proxy upload URLs 2026-06-03 02:57:29 +08:00
Lan 0d71b914e4 feat: add admin auth compatibility endpoints 2026-06-03 02:44:42 +08:00
Lan 20fcf0c3df feat: add legacy msg response field 2026-06-03 02:25:36 +08:00
Lan 75d345e5d0 fix: accept form payloads for chunk uploads 2026-06-03 02:24:08 +08:00
Lan a0c453b014 feat: add public config and health endpoints 2026-06-03 02:15:15 +08:00
Lan 1cc901d2b9 feat: add migration for filecodes table and update size field to BigInt 2026-02-27 23:38:27 +08:00
Lan e7b5792602 feat: add configuration management with async settings refresh and middleware integration 2026-02-13 23:45:44 +08:00
Lan 843a237fad fix: implement async database startup lock and refactor db configuration 2026-02-13 23:30:48 +08:00
Lan 4a9bf3a3a0 Merge pull request #460 from vastsa/dev
feat: 优化代码结构
2026-01-27 10:52:06 +08:00
Lan 0504e6e4dc chore: update Dockerfile to set HOST to 0.0.0.0 and reduce WORKERS to 1 2026-01-27 10:37:17 +08:00
Lan 24d49e1c9a chore: reduce number of workers in Dockerfile from 4 to 2 2026-01-27 10:05:33 +08:00
Lan c380778336 revert: dockerfile 2026-01-26 12:43:53 +08:00
Lan f1c09b0b20 fix: reduce default number of workers in Dockerfile to improve resource management 2026-01-26 12:14:11 +08:00
Lan a3f599fe51 refactor: streamline admin authorization logic and improve token handling 2026-01-25 23:40:15 +08:00
Lan 2e5dc532a0 perf: optimize memory usage for large file uploads 2026-01-25 21:28:16 +08:00
Lan 7f46c58898 ci: add dev branch support for Docker image builds 2026-01-25 21:27:59 +08:00
Lan 5a889bab47 feat: enhance file retrieval by using Pydantic models for serialization 2026-01-25 20:53:04 +08:00
Lan 5fee1c7b86 docs: update README files with improved formatting and additional features 2026-01-25 14:12:20 +08:00
Lan 73017935e9 fix: make detail field optional in APIResponse model 2026-01-24 15:28:17 +08:00
Lan a35b3c8262 feat: update Docker configuration and add environment variable documentation 2026-01-24 11:58:23 +08:00
Lan da5dc378a7 fix: return a dictionary from get_config method in ConfigService 2026-01-24 11:28:32 +08:00
Lan d170ca8005 feat: update Dockerfile to clone frontend themes into build directory and add legacy peer dependencies 2026-01-24 11:03:33 +08:00
Lan 0fe01c98db feat: update Dockerfile to use Node.js 20 and add build dependencies 2026-01-24 10:57:32 +08:00
Lan d5b0327f90 feat: add configuration documentation for OneDrive and OpenDAL storage integration 2026-01-24 10:53:48 +08:00
Lan 9120486449 Merge pull request #454 from jerryliang122/proxy-download
优化启用下载代理
2026-01-24 10:44:48 +08:00
Lan f5a5e03269 feat: update Dockerfile for multi-stage build and add frontend themes; update dependencies in requirements.txt 2026-01-24 10:31:43 +08:00
jerryliang ade5799db4 fix: 仅在获取到文件大小时才设置 Content-Length 头 2026-01-16 17:55:12 +08:00
jerryliang 6b728abbeb perf: 复用ClientSession提升文件下载性能 2026-01-16 17:33:22 +08:00
jerryliang ff1943d60c fix: 使用标准方法编码下载文件名 2026-01-16 17:18:14 +08:00
jerryliang 442ef5b0e0 feat: 优化文件下载响应中的Content-Length获取逻辑
为所有存储后端添加文件大小获取逻辑,优先从实际存储系统获取文件大小,失败时回退到数据库记录的大小
2026-01-16 16:53:39 +08:00
jerryliang 34e36944bd feat: 在所有存储实现中添加Content-Length响应头 2026-01-16 16:44:06 +08:00
jerryliang ba8802ad75 feat: 为所有存储后端实现流式文件下载
将文件下载方式从全量读取改为流式传输,减少内存占用并提高大文件下载性能
支持S3、OneDrive、OpenDAL和WebDAV存储后端的流式下载
添加错误处理和HTTP异常捕获
2026-01-16 15:45:12 +08:00
Lan bf43727531 Merge remote-tracking branch 'origin/master' 2026-01-11 14:26:02 +08:00
Lan d49a61d06e chore: update dependencies in requirements.txt 2026-01-11 14:25:53 +08:00
Lan 3074d9ba2e feat: https://github.com/vastsa/FileCodeBox/issues/442 密码进行hash存储 2026-01-07 20:36:59 +08:00
Lan 81ee640353 feat: https://github.com/vastsa/FileCodeBox/issues/386 https://github.com/vastsa/FileCodeBox/issues/380 2026-01-07 20:28:06 +08:00
Lan e87bcfcce5 fix: https://github.com/vastsa/FileCodeBox/issues/407 2026-01-07 20:04:44 +08:00
Lan e80be564a5 fix: https://github.com/vastsa/FileCodeBox/issues/362 2026-01-07 19:50:02 +08:00
Lan 69972e28b3 fix: https://github.com/vastsa/FileCodeBox/issues/449 2026-01-01 12:46:10 +08:00
Lan 8cdb972583 fix: https://github.com/vastsa/FileCodeBox/issues/444 2025-12-31 03:45:52 +08:00
Lan 736e16a9f6 fix: https://github.com/vastsa/FileCodeBox/issues/446 2025-12-31 03:36:14 +08:00
Lan 8e57a497f7 feat: 支持S3预签名上传 2025-12-31 03:25:09 +08:00
Lan 287d9aeedb feat: 支持S3 预签名上传 2025-12-31 03:24:25 +08:00
Lan f1a16a115a revert: 重新使用0.0.0.0 后续新增后台配置,延长后台时间 2025-12-19 10:17:37 +08:00
Lan b2bfc045c2 ci(docker): Optimize Docker build workflow and configuration
- Add environment variable for Docker registry image to reduce duplication
- Set job timeout to 60 minutes to prevent hanging builds
- Update docker/build-push-action from v5 to v6 for latest features
- Configure Docker Buildx with moby/buildkit:latest and host network
- Disable provenance attestation to improve build performance
- Replace hardcoded registry image reference with env variable for maintainability
2025-12-18 23:19:37 +08:00
Lan 900541baa5 feat(config): Add configurable workers and host settings
- Add "workers" configuration option to DEFAULT_CONFIG with default value of 1
- Add "host" configuration option to DEFAULT_CONFIG with default value of "::"
- Update uvicorn.run() to use settings.host and settings.workers instead of hardcoded values
- Reorganize imports in main.py for better readability and consistency
- Add blank line after time import in core/utils.py for PEP 8 compliance
- Allow dynamic configuration of server workers and binding host address
2025-12-18 23:08:40 +08:00
Lan 8b813a2eaa feat: 新增案例站点 2025-12-11 23:15:43 +08:00
Lan 4920b4b5db Merge remote-tracking branch 'origin/master' 2025-12-11 23:08:37 +08:00
Lan 268f1537bb feat: 新增优秀案例投稿页面 2025-12-11 23:08:00 +08:00
Lan 41b01b3faa fix: 兼容后台修改永久取件 2025-12-01 21:21:37 +08:00
Lan c02fb7ce20 fix: 后台无法修改永久取件码的信息 2025-12-01 19:09:23 +08:00
Lan 95f5e0dfbc feat: 更新2024主题 2025-12-01 15:35:14 +08:00
Lan e854eb068c fix: 自动清理过期的chunk 2025-12-01 15:24:47 +08:00
Lan c1966b3942 feat: s3适配切片上传 2025-12-01 15:13:33 +08:00
Lan a20a0beb79 feat: 利用AI更新文档 2025-12-01 14:10:06 +08:00
Lan d7200f6b9b Merge remote-tracking branch 'origin/master' 2025-12-01 11:31:24 +08:00
Lan bd6f646f5d fix: some error 2025-12-01 11:30:52 +08:00
Lan 6eac746e83 Update readme.md 2025-11-26 19:40:11 +08:00
Lan 5f82650c36 fix: https://github.com/vastsa/FileCodeBox/issues/420 2025-11-25 14:27:48 +08:00
Lan d3fe7b223e fix: https://github.com/vastsa/FileCodeBox/issues/420 2025-11-24 19:25:14 +08:00
Lan 2d79fa5acd feat: ui 优化 2025-09-04 14:11:55 +08:00
Lan 387f023372 feat: 完善docker-image.yml 2025-09-04 03:08:30 +08:00
Lan e51380003c Merge pull request #378 from Do1e/master
fix: 下载文件类型不符的问题 #372
2025-08-08 21:57:56 +08:00
Do1e e41b3e1688 fix: 下载文件类型不符的问题 #372 2025-08-05 17:25:25 +08:00
Lan 7be3b27415 fix: 文本传输存在xss问题 2025-08-01 13:25:59 +08:00
Lan bdab5bb375 feat:code style 2025-07-05 00:02:04 +08:00
Lan c0984bfb1f Merge pull request #364 from jtcymc/master
fix(base): 修复文件名中的中文编码问题
2025-06-28 22:13:45 +08:00
shaw 62d1a23695 fix(base): 修复文件名中的中文编码问题
- 在 sanitize_filename 函数中添加 unquote 导入并使用其解码文件名
- 这个修改解决了非 ASCII 字符在文件名中显示为编码形式的问题
- Non-ASCll filename uploads don't comply with RFC 7578
2025-06-20 15:44:23 +08:00
Lan 9a80d7a9e0 fix: #350 需要通过添加反代确保真实IP来源 2025-05-28 23:29:13 +08:00
Lan eeb70c7f44 fix: #349 2025-05-21 00:14:40 +08:00
Lan 136ea5830f fix: 适配webdav在window环境下路径 2025-04-25 22:31:06 +08:00
Lan c430af3d82 feat: 适配alist webdav 2025-04-19 17:58:58 +08:00
Lan 6fcf26fcbe fix: some bug 2025-03-30 22:21:38 +08:00
Lan f6649ecc81 Merge remote-tracking branch 'origin/master' 2025-03-30 22:21:35 +08:00
Lan 3005ed1298 fix: some bug 2025-03-30 22:21:24 +08:00
Lan a23409f0af Update readme.md 2025-03-21 16:23:15 +08:00
Lan f7876c6e48 fix: some bug 2025-03-16 23:06:38 +08:00
Lan 7c6aedb96e fix: some bug 2025-03-16 22:24:17 +08:00
Lan 7ed09e2455 fix: #278 #297 2025-03-16 22:14:26 +08:00
Lan 9f8e6d401f fix: #290 #292 2025-03-15 23:42:33 +08:00
Lan c4304d3525 feat: 适配pwa 2025-03-12 22:46:25 +08:00
Lan e92ff30d8c Merge pull request #289 from Mr-Ao-Dragon/dev/docker/compose
add: deployment with docker compose
2025-03-12 22:20:07 +08:00
敖律风 fd913ababc docs(readme): 添加 Docker Compose 部署方式
- 在 readme.md 和 readme_en.md 中添加了 Docker Compose 部署步骤
- 新增 docker-compose.yml 文件,用于定义 FileCodeBox服务
- 该文件包含服务配置、端口映射和数据卷设置
2025-03-12 18:56:27 +08:00
Lan 45be97a258 fix: #272 #283 #273 2025-03-09 22:46:17 +08:00
Lan fbd741ebcf fix:#277 2025-03-06 18:28:01 +08:00
Lan e341e1afae fix: 前端去除/ 2025-03-06 00:44:42 +08:00
Lan 4037ddb3b1 fix: 前端去除/ 2025-03-06 00:39:21 +08:00
Lan 72190331b9 fix: 前端去除/ 2025-03-06 00:25:02 +08:00
Lan 566dc3b94f feat: 后台新增版本号 2025-03-04 00:16:12 +08:00
Lan cf96071167 feat: 新增管理员编辑记录,优化取件失败提示 2025-03-04 00:09:06 +08:00
Lan ffe89060f4 feat: #151 优化寄件 2025-03-03 23:07:51 +08:00
Lan 79c1e0f949 feat: docs add minio 2025-03-02 20:43:58 +08:00
Lan df6722ac26 fix: #266 2025-03-02 20:29:24 +08:00
Lan e897dbfe97 feat: 后台页面优化 2025-03-02 16:11:53 +08:00
Lan 168ca8383f feat: 优化上传时间检查 2025-03-02 15:26:41 +08:00
Lan 4d1cd4cbfc feat: 优化上传检查 2025-03-02 15:15:02 +08:00
Lan c61c2ee7fe feat: #212 2025-03-02 15:01:24 +08:00
Lan 548d625827 feat: #258 2025-03-02 14:52:01 +08:00
Lan 792f7a8a12 feat: 从剪切板读取文件 2025-03-02 13:28:44 +08:00
Lan a65cf32214 revert: 取消秒传 2025-03-01 11:20:37 +08:00
Lan 4a50908455 feat:存储设置,新增阿里云教程 2025-02-27 22:43:22 +08:00
Lan c4e398bd31 fix: share auth 2025-02-25 22:55:42 +08:00
Lan 39264cc32e fix: share text 2025-02-25 22:37:08 +08:00
Lan 7a15b6a44d fix: share text 2025-02-25 22:33:10 +08:00
Lan 591441e9a7 fix: #256 2025-02-24 13:51:42 +08:00
Lan 60756749b7 Delete path/to/frontend/file 2025-02-23 21:05:34 +08:00
Lan fdada809d9 wip: 切片上传、文件秒传、断点续传陆续适配中当前进度(本地存储已适配) 2025-02-23 20:49:51 +08:00
182 changed files with 12363 additions and 2004 deletions

No files matched your search

+49 -2
View File
@@ -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/
+34 -19
View File
@@ -5,46 +5,61 @@ on:
push:
branches:
- master
- dev
tags:
- 'v*'
env:
REGISTRY_IMAGE: ${{ secrets.DOCKER_USERNAME }}/filecodebox
jobs:
buildx:
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
submodules: true
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY_IMAGE }}
tags: |
type=ref,event=branch
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}}
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Cache Docker layers
uses: actions/cache@v3
uses: docker/setup-buildx-action@v3
with:
path: /tmp/.buildx-cache
key: ${{ runner.os }}-buildx-${{ github.sha }}
restore-keys: |
${{ runner.os }}-buildx-
driver-opts: |
image=moby/buildkit:latest
network=host
- name: Login to DockerHub
uses: docker/login-action@v2
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Build and push
uses: docker/build-push-action@v4
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ secrets.DOCKER_USERNAME }}/filecodebox:latest
cache-from: type=local,src=/tmp/.buildx-cache
cache-to: type=local,dest=/tmp/.buildx-cache-new,mode=max
- name: Move cache
run: |
rm -rf /tmp/.buildx-cache
mv /tmp/.buildx-cache-new /tmp/.buildx-cache
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
provenance: false
+9
View File
@@ -154,3 +154,12 @@ for_test.py
data/.env
.backup/
/cloc-1.64.exe
# Ignore node_modules
node_modules/
AGENTS.md
dist/
# Frontend themes (built from GitHub during Docker build)
themes/
+44 -15
View File
@@ -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 '*'"]
+69 -27
View File
@@ -12,7 +12,14 @@ from core.settings import settings
from apps.admin.services import FileService, ConfigService, LocalFileService
def create_token(data: dict, expires_in: int = 3600 * 24) -> str:
def _get_jwt_secret() -> bytes:
secret = getattr(settings, "jwt_secret", "")
if not secret:
raise RuntimeError("JWT签名密钥未初始化")
return secret.encode()
def create_token(data: dict, expires_in: int = 3600 * 24 * 30) -> str:
"""
创建JWT token
:param data: 数据负载
@@ -25,9 +32,7 @@ def create_token(data: dict, expires_in: int = 3600 * 24) -> str:
json.dumps({**data, "exp": int(time.time()) + expires_in}).encode()
).decode()
signature = hmac.new(
settings.admin_token.encode(), f"{header}.{payload}".encode(), "sha256"
).digest()
signature = hmac.new(_get_jwt_secret(), f"{header}.{payload}".encode(), "sha256").digest()
signature = base64.b64encode(signature).decode()
return f"{header}.{payload}.{signature}"
@@ -44,13 +49,13 @@ def verify_token(token: str) -> dict:
# 验证签名
expected_signature = hmac.new(
settings.admin_token.encode(),
_get_jwt_secret(),
f"{header_b64}.{payload_b64}".encode(),
"sha256",
).digest()
expected_signature_b64 = base64.b64encode(expected_signature).decode()
if signature_b64 != expected_signature_b64:
if not hmac.compare_digest(signature_b64, expected_signature_b64):
raise ValueError("无效的签名")
# 解码payload
@@ -65,34 +70,71 @@ 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 and (request.method, request.url.path) in ADMIN_PUBLIC_ENDPOINTS:
return None
return _require_admin_payload(authorization)
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))
async def share_required_login(authorization: str = Header(default=None)):
"""
验证分享上传权限
当settings.openUpload为False时,要求用户必须登录并具有管理员权限
当settings.openUpload为True时,允许游客上传
:param authorization: 认证头信息
:param request: 请求对象
:return: 验证结果
"""
if not settings.openUpload:
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(
status_code=403, detail="本站未开启游客上传,如需上传请先登录后台"
)
_require_admin_payload(authorization)
return True
async def get_file_service():
+55
View File
@@ -1,3 +1,6 @@
import datetime
from typing import Any, Optional, Union
from pydantic import BaseModel
@@ -5,6 +8,10 @@ class IDData(BaseModel):
id: int
class IDsData(BaseModel):
ids: list[int]
class ShareItem(BaseModel):
expire_value: int
expire_style: str = "day"
@@ -17,3 +24,51 @@ class DeleteItem(BaseModel):
class LoginData(BaseModel):
password: str
class UpdateFileData(BaseModel):
id: int
code: Optional[str] = None
prefix: Optional[str] = None
suffix: Optional[str] = None
expired_at: Optional[Union[datetime.datetime, str]] = None
expired_count: Optional[int] = None
class BatchUpdateFileData(BaseModel):
ids: list[int]
expired_at: Optional[Union[datetime.datetime, str]] = None
expired_count: Optional[int] = None
clearExpiredAt: Optional[bool] = None
clear_expired_at: Optional[bool] = None
class FilePolicyActionData(BaseModel):
id: int
action: str
downloadLimit: Optional[int] = None
download_limit: Optional[int] = None
class BatchFilePolicyActionData(BaseModel):
ids: list[int]
action: str
downloadLimit: Optional[int] = None
download_limit: Optional[int] = None
class 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
+1508 -40
View File
File diff suppressed because it is too large. Load diff
+499 -43
View File
@@ -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
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,19 +527,78 @@ 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,
file_service: FileService = Depends(get_file_service),
):
file_code = await FileCodes.filter(id=data.id).first()
if not file_code:
raise HTTPException(status_code=404, detail="文件不存在")
target_name = file_service._build_file_activity_name(file_code)
update_data = {}
if data.code is not None and data.code != file_code.code:
# 判断code是否存在
if await FileCodes.filter(code=data.code).first():
raise HTTPException(status_code=400, detail="code已存在")
update_data["code"] = data.code
if data.prefix is not None and data.prefix != file_code.prefix:
update_data["prefix"] = data.prefix
if data.suffix is not None and data.suffix != file_code.suffix:
update_data["suffix"] = data.suffix
if (
data.expired_at is not None
and data.expired_at != ""
and data.expired_at != file_code.expired_at
):
update_data["expired_at"] = data.expired_at
if data.expired_count is not None and data.expired_count != file_code.expired_count:
update_data["expired_count"] = data.expired_count
await file_code.update_from_dict(update_data).save()
if update_data:
await file_service.record_admin_activity(
action="file.update",
target_type="file",
target_id=data.id,
target_name=target_name,
count=1,
meta={"fields": sorted(update_data.keys())},
)
return APIResponse(detail="更新成功")
+64 -6
View File
@@ -1,7 +1,69 @@
from typing import Dict, Union
from ipaddress import ip_address, ip_network
from typing import Dict, Iterable, Union
from datetime import datetime, timedelta
from fastapi import HTTPException, Request
from core.settings import settings
def _iter_trusted_proxies() -> Iterable[str]:
trusted_proxies = getattr(settings, "trustedProxies", [])
if isinstance(trusted_proxies, str):
trusted_proxies = [item.strip() for item in trusted_proxies.split(",")]
return [item for item in trusted_proxies if item]
def _is_trusted_proxy(host: str) -> bool:
try:
remote_addr = ip_address(host)
except ValueError:
return False
for proxy in _iter_trusted_proxies():
try:
if remote_addr in ip_network(proxy, strict=False):
return True
except ValueError:
continue
return False
def _get_forwarded_for_ip(header_value: str, fallback_ip: str) -> str:
forwarded_chain = [
item.strip() for item in header_value.split(",") if item.strip()
]
if not forwarded_chain:
return fallback_ip
for candidate in reversed(forwarded_chain):
try:
ip_address(candidate)
except ValueError:
return fallback_ip
if not _is_trusted_proxy(candidate):
return candidate
return forwarded_chain[0]
def get_client_ip(request: Request) -> str:
client_host = request.client.host if request.client else "unknown"
if not _is_trusted_proxy(client_host):
return client_host
forwarded_for = request.headers.get("X-Forwarded-For")
if forwarded_for:
return _get_forwarded_for_ip(forwarded_for, client_host)
real_ip = request.headers.get("X-Real-IP")
if real_ip:
try:
ip_address(real_ip)
except ValueError:
return client_host
return real_ip
return client_host
class IPRateLimit:
def __init__(self, count: int, minutes: int):
@@ -35,11 +97,7 @@ class IPRateLimit:
}
def __call__(self, request: Request) -> str:
ip = (
request.headers.get("X-Real-IP")
or request.headers.get("X-Forwarded-For")
or request.client.host
)
ip = get_client_ip(request)
if not self.check_ip(ip):
raise HTTPException(status_code=423, detail="请求次数过多,请稍后再试")
return ip
+28
View File
@@ -0,0 +1,28 @@
from tortoise import connections
async def create_upload_chunk_and_update_file_codes_table():
conn = connections.get("default")
await conn.execute_script(
"""
ALTER TABLE "filecodes" ADD "file_hash" VARCHAR(128);
ALTER TABLE "filecodes" ADD "is_chunked" BOOL NOT NULL DEFAULT False;
ALTER TABLE "filecodes" ADD "upload_id" VARCHAR(128);
CREATE TABLE "uploadchunk" (
id INTEGER not null primary key autoincrement,
"upload_id" VARCHAR(36) NOT NULL,
"chunk_index" INT NOT NULL,
"chunk_hash" VARCHAR(128) NOT NULL,
"total_chunks" INT NOT NULL,
"file_size" BIGINT NOT NULL,
"chunk_size" INT NOT NULL,
"created_at" TIMESTAMPTZ NOT NULL,
"file_name" VARCHAR(255) NOT NULL,
"completed" BOOL NOT NULL
);
"""
)
async def migrate():
await create_upload_chunk_and_update_file_codes_table()
+26
View File
@@ -0,0 +1,26 @@
from tortoise import connections
async def create_presign_upload_session_table():
conn = connections.get("default")
await conn.execute_script(
"""
CREATE TABLE IF NOT EXISTS presignuploadsession (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
upload_id VARCHAR(36) NOT NULL UNIQUE,
file_name VARCHAR(255) NOT NULL,
file_size BIGINT NOT NULL,
save_path VARCHAR(512) NOT NULL,
mode VARCHAR(10) NOT NULL,
expire_value INT NOT NULL DEFAULT 1,
expire_style VARCHAR(20) NOT NULL DEFAULT 'day',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_presignuploadsession_upload_id ON presignuploadsession (upload_id);
"""
)
async def migrate():
await create_presign_upload_session_table()
+14
View File
@@ -0,0 +1,14 @@
from tortoise import connections
async def add_save_path_to_uploadchunk():
conn = connections.get("default")
await conn.execute_script(
"""
ALTER TABLE uploadchunk ADD COLUMN save_path VARCHAR(512) NULL;
"""
)
async def migrate():
await add_save_path_to_uploadchunk()
+72
View File
@@ -0,0 +1,72 @@
from tortoise import connections
def _need_upgrade(columns: list[tuple]) -> bool:
for column in columns:
# PRAGMA table_info 返回 (cid, name, type, notnull, dflt_value, pk)
if column[1] == "size":
column_type = (column[2] or "").upper()
return "BIGINT" not in column_type
return False
async def migrate():
conn = connections.get("default")
result = await conn.execute_query("PRAGMA table_info(filecodes)")
columns = result[1] if result and len(result) > 1 else []
if not columns or not _need_upgrade(columns):
return
await conn.execute_script(
"""
BEGIN;
CREATE TABLE IF NOT EXISTS filecodes_new
(
id INTEGER not null
primary key autoincrement,
code VARCHAR(255) not null
unique,
prefix VARCHAR(255) default '' not null,
suffix VARCHAR(255) default '' not null,
uuid_file_name VARCHAR(255),
file_path VARCHAR(255),
size BIGINT default 0 not null,
text TEXT,
expired_at TIMESTAMP,
expired_count INT default 0 not null,
used_count INT default 0 not null,
created_at TIMESTAMP default CURRENT_TIMESTAMP not null,
file_hash VARCHAR(128),
is_chunked BOOL default False not null,
upload_id VARCHAR(128)
);
INSERT INTO filecodes_new (id, code, prefix, suffix, uuid_file_name, file_path, size, text,
expired_at, expired_count, used_count, created_at, file_hash,
is_chunked, upload_id)
SELECT id,
code,
prefix,
suffix,
uuid_file_name,
file_path,
size,
text,
expired_at,
expired_count,
used_count,
created_at,
file_hash,
is_chunked,
upload_id
FROM filecodes;
DROP TABLE filecodes;
ALTER TABLE filecodes_new
RENAME TO filecodes;
CREATE INDEX IF NOT EXISTS idx_filecodes_code_1c7ee7
on filecodes (code);
COMMIT;
"""
)
+55 -94
View File
@@ -2,119 +2,56 @@
# @Author : Lan
# @File : models.py
# @Software: PyCharm
from datetime import datetime
from typing import Optional
from tortoise import fields
from tortoise.models import Model
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise import fields, models
from datetime import datetime
from core.utils import get_now
class FileCodes(Model):
id: Optional[int] = fields.IntField(pk=True)
code: Optional[int] = fields.CharField(
description="分享码", max_length=255, index=True, unique=True
)
prefix: Optional[str] = fields.CharField(
max_length=255, description="前缀", default=""
)
suffix: Optional[str] = fields.CharField(
max_length=255, description="后缀", default=""
)
uuid_file_name: Optional[str] = fields.CharField(
max_length=255, description="uuid文件名", null=True
)
file_path: Optional[str] = fields.CharField(
max_length=255, description="文件路径", null=True
)
size: Optional[int] = fields.IntField(description="文件大小", default=0)
text: Optional[str] = fields.TextField(description="文本内容", null=True)
expired_at: Optional[datetime] = fields.DatetimeField(
null=True, description="过期时间"
)
expired_count: Optional[int] = fields.IntField(description="可用次数", default=0)
used_count: Optional[int] = fields.IntField(description="已用次数", default=0)
created_at: Optional[datetime] = fields.DatetimeField(
auto_now_add=True, description="创建时间"
)
#
# file_hash = fields.CharField(
# max_length=128, # SHA-256需要64字符,这里预留扩展空间
# description="文件哈希值",
# unique=True,
# null=True # 允许旧数据为空
# )
# hash_algorithm = fields.CharField(
# max_length=20,
# description="哈希算法类型",
# null=True,
# default="sha256"
# )
# # 新增分片字段
# chunk_size = fields.IntField(
# description="分片大小(字节)",
# default=0
# )
# total_chunks = fields.IntField(
# description="总分片数",
# default=0
# )
# uploaded_chunks = fields.IntField(
# description="已上传分片数",
# default=0
# )
# upload_status = fields.CharField(
# max_length=20,
# description="上传状态",
# default="pending", # pending/in_progress/completed
# choices=["pending", "in_progress", "completed"]
# )
# is_chunked = fields.BooleanField(
# description="是否分片上传",
# default=False
# )
class FileCodes(models.Model):
id = fields.IntField(pk=True)
code = fields.CharField(max_length=255, unique=True, index=True)
prefix = fields.CharField(max_length=255, default="")
suffix = fields.CharField(max_length=255, default="")
uuid_file_name = fields.CharField(max_length=255, null=True)
file_path = fields.CharField(max_length=255, null=True)
size = fields.BigIntField(default=0)
text = fields.TextField(null=True)
expired_at = fields.DatetimeField(null=True)
expired_count = fields.IntField(default=0)
used_count = fields.IntField(default=0)
created_at = fields.DatetimeField(auto_now_add=True)
file_hash = fields.CharField(max_length=64, null=True)
is_chunked = fields.BooleanField(default=False)
upload_id = fields.CharField(max_length=36, null=True)
async def is_expired(self):
# 按时间
if self.expired_at is None:
return False
if self.expired_at and self.expired_count < 0:
return self.expired_at < await get_now()
# 按次数
else:
return self.expired_count <= 0
return self.expired_count <= 0
async def get_file_path(self):
return f"{self.file_path}/{self.uuid_file_name}"
#
# class FileChunks(Model):
# id = fields.IntField(pk=True)
# file_code = fields.ForeignKeyField(
# "models.FileCodes",
# related_name="chunks",
# on_delete=fields.CASCADE
# )
# chunk_number = fields.IntField(description="分片序号")
# chunk_hash = fields.CharField(
# max_length=128,
# description="分片哈希校验值"
# )
# chunk_path = fields.CharField(
# max_length=255,
# description="分片存储路径"
# )
# created_at = fields.DatetimeField(
# auto_now_add=True,
# description="上传时间"
# )
#
# class Meta:
# unique_together = [("file_code", "chunk_number")]
class UploadChunk(models.Model):
id = fields.IntField(pk=True)
upload_id = fields.CharField(max_length=36, index=True)
chunk_index = fields.IntField()
chunk_hash = fields.CharField(max_length=64)
total_chunks = fields.IntField()
file_size = fields.BigIntField()
chunk_size = fields.IntField()
file_name = fields.CharField(max_length=255)
save_path = fields.CharField(max_length=512, null=True)
created_at = fields.DatetimeField(auto_now_add=True)
completed = fields.BooleanField(default=False)
class KeyValue(Model):
@@ -128,4 +65,28 @@ 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)
file_size = fields.BigIntField()
save_path = fields.CharField(max_length=512)
mode = fields.CharField(max_length=10) # "direct" 或 "proxy"
expire_value = fields.IntField(default=1)
expire_style = fields.CharField(max_length=20, default="day")
created_at = fields.DatetimeField(auto_now_add=True)
expires_at = fields.DatetimeField() # 会话过期时间
async def is_expired(self):
"""检查会话是否已过期"""
return self.expires_at < await get_now()
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"
)
+31
View File
@@ -1,5 +1,36 @@
from pydantic import BaseModel
from typing import Optional
class SelectFileModel(BaseModel):
code: str
class InitChunkUploadModel(BaseModel):
file_name: str
chunk_size: int = 5 * 1024 * 1024
file_size: int
file_hash: str
class CompleteUploadModel(BaseModel):
expire_value: int
expire_style: str
# 预签名上传相关模型
class PresignUploadInitRequest(BaseModel):
"""预签名上传初始化请求"""
file_name: str
file_size: int
expire_value: int = 1
expire_style: str = "day"
class PresignUploadInitResponse(BaseModel):
"""预签名上传初始化响应"""
upload_id: str
upload_url: str
mode: str # "direct" 或 "proxy"
save_path: str
expires_in: int # URL过期时间(秒)
+62 -23
View File
@@ -1,6 +1,8 @@
import datetime
import hashlib
import os
import uuid
from urllib.parse import unquote
from fastapi import UploadFile, HTTPException
from typing import Optional, Tuple
@@ -8,33 +10,44 @@ 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
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
# 使用 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
prefix, suffix = os.path.splitext(file.filename)
# 保持原始文件名
save_path = f"{path}/{file.filename}"
return path, suffix, prefix, file.filename, save_path
async def get_chunk_file_path_name(
file_name: str, upload_id: str
) -> Tuple[str, str, str, str, str]:
today = await get_now()
storage_path = settings.storage_path.strip("/")
base_path = f"share/data/{today.strftime('%Y/%m/%d')}/{upload_id}"
path = f"{storage_path}/{base_path}" if storage_path else base_path
prefix, suffix = os.path.splitext(file_name)
save_path = f"{path}/{prefix}{suffix}"
return path, suffix, prefix, file_name, save_path
async def get_expire_info(
expire_value: int, expire_style: str
) -> Tuple[Optional[datetime.datetime], int, int, str]:
"""获取过期信息"""
expired_count, used_count = -1, 0
now = datetime.datetime.now()
now = await get_now()
code = None
max_timedelta = (
@@ -54,7 +67,7 @@ async def get_expire_info(
"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:
@@ -63,8 +76,6 @@ async def get_expire_info(
expired_at, extra = result
if expire_style == "count":
expired_count = extra
elif expire_style == "forever":
code = await get_random_code(style="string") # 移动到这里
else:
expired_at = result
if expired_at and expired_at - now > max_timedelta:
@@ -78,15 +89,43 @@ async def get_expire_info(
return expired_at, expired_count, used_count, code
async def get_random_code(style="num") -> str:
"""获取随机字符串"""
def get_code_generate_type() -> str:
code_generate_type = getattr(settings, "code_generate_type", "number")
if code_generate_type in {"secret", "string"}:
return "secret"
return "number"
async def get_random_code(style: str | None = None) -> str:
code_style = style or get_code_generate_type()
if code_style == "num":
code_style = "number"
if code_style == "string":
code_style = "secret"
while True:
code = await get_random_num() if style == "num" else await get_random_string()
code = (
await get_random_num()
if code_style == "number"
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:
sha = hashlib.sha256()
await file.seek(0)
while True:
chunk = await file.read(chunk_size)
if not chunk:
break
sha.update(chunk)
await file.seek(0)
return sha.hexdigest()
ip_limit = {
"error": IPRateLimit(count=settings.uploadCount, minutes=settings.errorMinute),
"upload": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
"error": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
"upload": IPRateLimit(count=settings.uploadCount, minutes=settings.uploadMinute),
}
+698 -35
View File
@@ -1,29 +1,143 @@
from fastapi import APIRouter, Form, UploadFile, File, Depends, HTTPException
from apps.admin.dependencies import admin_required
from apps.base.models import FileCodes
from apps.base.schemas import SelectFileModel
from apps.base.utils import get_expire_info, get_file_path_name, ip_limit
import datetime
from fnmatch import fnmatchcase
import hashlib
import os
import uuid
from datetime import timedelta
from urllib.parse import unquote
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 core.response import APIResponse
from core.settings import settings
from core.storage import storages, FileStorageInterface
from core.utils import get_select_token
from core.utils import get_select_token, get_now, sanitize_filename
share_api = APIRouter(prefix="/share", tags=["分享"])
async def validate_file_size(file: UploadFile, max_size: int):
if file.size > max_size:
# ============ 公共服务层 ============
class FileUploadService:
"""统一的文件上传服务"""
@staticmethod
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("/")
file_uuid = upload_id or uuid.uuid4().hex
filename = await sanitize_filename(unquote(file_name))
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
@staticmethod
async def create_file_record(
file_name: str,
file_size: int,
file_path: str,
expire_value: int,
expire_style: str,
**extra_fields,
) -> str:
"""统一创建FileCodes记录,返回code"""
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(
code=code,
prefix=prefix,
suffix=suffix,
uuid_file_name=file_name,
file_path=file_path,
size=file_size,
expired_at=expired_at,
expired_count=expired_count,
used_count=used_count,
**extra_fields,
)
return code
async def validate_file_size(file: UploadFile, max_size: int) -> int:
size = file.size
if size is None:
await file.seek(0, 2) # type: ignore[arg-type]
size = file.file.tell()
await file.seek(0)
if size > max_size:
max_size_mb = max_size / (1024 * 1024)
raise HTTPException(
status_code=403, detail=f"大小超过限制,最大为{max_size_mb:.2f} MB"
)
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)
@share_api.post("/text/", dependencies=[Depends(admin_required)])
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),
@@ -51,33 +165,30 @@ async def share_text(
return APIResponse(detail={"code": code})
@share_api.post("/file/", dependencies=[Depends(admin_required)])
@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"]),
):
await validate_file_size(file, settings.uploadSize)
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
)
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)
await create_file_code(
code=code,
prefix=prefix,
suffix=suffix,
uuid_file_name=uuid_file_name,
file_path=path,
size=file.size,
size=file_size,
expired_at=expired_at,
expired_count=expired_count,
used_count=used_count,
@@ -86,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:
@@ -95,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]()
@@ -110,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)
@@ -122,33 +297,521 @@ 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)
has, file_code = await get_code_file_by_code(code, False)
raise HTTPException(status_code=403, detail="下载鉴权失败")
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
else await file_storage.get_file_response(file_code)
)
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 = 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"
)
# # 秒传检查
# existing = await FileCodes.filter(file_hash=data.file_hash).first()
# if existing:
# if await existing.is_expired():
# file_storage: FileStorageInterface = storages[settings.file_storage](
# )
# await file_storage.delete_file(existing)
# await existing.delete()
# else:
# return APIResponse(detail={
# "code": existing.code,
# "existed": True,
# "name": f'{existing.prefix}{existing.suffix}'
# })
# 断点续传:检查是否存在相同文件的未完成上传会话
existing_session = await UploadChunk.filter(
chunk_hash=data.file_hash,
chunk_index=-1,
file_size=data.file_size,
file_name=data.file_name,
).first()
if existing_session:
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,
total_chunks=total_chunks,
file_size=data.file_size,
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": [],
}
)
@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(...),
):
# 获取上传会话信息
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="上传会话不存在")
# 检查分片索引有效性
if chunk_index < 0 or chunk_index >= chunk_info.total_chunks:
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="无效的分片索引")
# 检查是否已上传(支持断点续传)
existing_chunk = await UploadChunk.filter(
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}
)
# 读取分片数据并计算哈希
chunk_data = await chunk.read()
chunk_size = len(chunk_data)
# 校验分片大小不超过声明的 chunk_size
if chunk_size > chunk_info.chunk_size:
raise HTTPException(
status.HTTP_400_BAD_REQUEST,
detail=f"分片大小超过声明值: 最大 {chunk_info.chunk_size}, 实际 {chunk_size}",
)
# 计算已上传分片数,校验累计大小不超限(用分片数 * chunk_size 估算)
uploaded_count = await UploadChunk.filter(
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"
)
chunk_hash = hashlib.sha256(chunk_data).hexdigest()
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
)
except Exception as 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,
"save_path": chunk_info.save_path,
},
)
return APIResponse(detail={"chunk_hash": chunk_hash})
@chunk_api.delete("/upload/{upload_id}", dependencies=[Depends(share_required_login)])
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 = chunk_info.save_path
# 清理存储中的临时文件
storage = storages[settings.file_storage]()
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)]
)
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,
}
)
@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:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在")
storage = storages[settings.file_storage]()
# 验证所有分片
completed_chunks_list = await UploadChunk.filter(
upload_id=upload_id, completed=True
).all()
if len(completed_chunks_list) != chunk_info.total_chunks:
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="分片不完整")
# 用分片数 * chunk_size 校验最大可能大小
max_total_size = len(completed_chunks_list) * chunk_info.chunk_size
if max_total_size > settings.uploadSize:
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"
)
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
)
await FileCodes.create(
code=code,
file_hash=file_hash, # 使用合并后计算的哈希
is_chunked=True,
upload_id=upload_id,
size=chunk_info.file_size,
expired_at=expired_at,
expired_count=expired_count,
used_count=used_count,
file_path=path,
uuid_file_name=f"{prefix}{suffix}",
prefix=prefix,
suffix=suffix,
)
# 清理临时文件
await storage.clean_chunks(upload_id, save_path)
# 清理数据库中的分片记录
await UploadChunk.filter(upload_id=upload_id).delete()
ip_limit["upload"].add_ip(ip)
return APIResponse(detail={"code": code, "name": chunk_info.file_name})
except ValueError as e:
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail=str(e))
except Exception as e:
# 合并失败时清理临时文件
try:
await storage.clean_chunks(upload_id, save_path)
except Exception:
pass
raise HTTPException(
status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"文件合并失败: {str(e)}"
)
# ============ 预签名上传API ============
presign_api = APIRouter(prefix="/presign", tags=["预签名上传"])
PRESIGN_SESSION_EXPIRES = 900 # 15分钟
def build_proxy_upload_urls(upload_id: str) -> dict:
proxy_upload_url = f"/presign/upload/proxy/{upload_id}"
return {
"proxy_upload_url": proxy_upload_url,
"legacy_proxy_upload_url": f"/api{proxy_upload_url}",
}
async def _get_valid_session(
upload_id: str, expected_mode: Optional[str] = None
) -> PresignUploadSession:
"""获取并验证会话"""
session = await PresignUploadSession.filter(upload_id=upload_id).first()
if not session:
raise HTTPException(404, "上传会话不存在")
if await session.is_expired():
await session.delete()
raise HTTPException(404, "上传会话已过期")
if expected_mode and session.mode != expected_mode:
raise HTTPException(400, f"此会话不支持{expected_mode}模式")
return session
@presign_api.post("/upload/init", dependencies=[Depends(share_required_login)])
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",
)
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
)
storage: FileStorageInterface = storages[settings.file_storage]()
presigned_url = await storage.generate_presigned_upload_url(
save_path, PRESIGN_SESSION_EXPIRES
)
mode = "direct" if presigned_url else "proxy"
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,
file_name=filename,
file_size=data.file_size,
save_path=save_path,
mode=mode,
expire_value=data.expire_value,
expire_style=data.expire_style,
expires_at=await get_now() + timedelta(seconds=PRESIGN_SESSION_EXPIRES),
)
ip_limit["upload"].add_ip(ip)
detail = {
"upload_id": upload_id,
"upload_url": upload_url,
"mode": mode,
"expires_in": PRESIGN_SESSION_EXPIRES,
}
if mode == "proxy":
detail.update(proxy_urls)
return APIResponse(
detail=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"])
):
"""代理模式上传,服务器转存到存储后端"""
session = await _get_valid_session(upload_id, expected_mode="proxy")
file_size = await validate_file_size(file, settings.uploadSize)
if abs(file_size - session.file_size) > 1024:
raise HTTPException(400, "文件大小与声明不符")
storage: FileStorageInterface = storages[settings.file_storage]()
try:
await storage.save_file(file, session.save_path)
except Exception as e:
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,
)
await session.delete()
ip_limit["upload"].add_ip(ip)
return APIResponse(detail={"code": code, "name": session.file_name})
@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")
storage: FileStorageInterface = storages[settings.file_storage]()
if not await storage.file_exists(session.save_path):
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,
)
await session.delete()
ip_limit["upload"].add_ip(ip)
return APIResponse(detail={"code": code, "name": session.file_name})
@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(),
}
)
@presign_api.delete("/upload/{upload_id}", dependencies=[Depends(share_required_login)])
async def presign_upload_cancel(upload_id: str):
"""取消上传会话"""
session = await PresignUploadSession.filter(upload_id=upload_id).first()
if not session:
raise HTTPException(404, "上传会话不存在")
if session.mode == "direct":
storage: FileStorageInterface = storages[settings.file_storage]()
try:
if await storage.file_exists(session.save_path):
temp_file_code = FileCodes(
file_path=os.path.dirname(session.save_path),
uuid_file_name=os.path.basename(session.save_path),
)
await storage.delete_file(temp_file_code)
except Exception:
pass
await session.delete()
return APIResponse(detail={"message": "上传会话已取消"})
+114
View File
@@ -0,0 +1,114 @@
from apps.base.models import KeyValue
from apps.base.utils import ip_limit
from core.database import db_startup_lock
from core.logger import logger
from core.security import (
generate_jwt_secret,
is_config_initialized,
is_valid_jwt_secret,
prepare_security_config,
)
from core.settings import DEFAULT_CONFIG, settings
from core.utils import hash_password
MIN_ADMIN_PASSWORD_LENGTH = 8
SETUP_CONFIG_FIELDS = {
"allowed_file_types",
"code_generate_type",
"enableChunk",
"errorCount",
"errorMinute",
"expireStyle",
"max_save_seconds",
"name",
"openUpload",
"uploadCount",
"uploadMinute",
"uploadSize",
}
async def ensure_settings_row() -> None:
initial_security = prepare_security_config(DEFAULT_CONFIG)
_, created = await KeyValue.get_or_create(
key="settings", defaults={"value": initial_security.config}
)
if created:
logger.warning(
"系统尚未初始化,请在浏览器中打开站点并完成管理员密码设置"
)
async def ensure_security_settings() -> None:
config_record = await KeyValue.filter(key="settings").first()
if not config_record:
return
current_config = {**DEFAULT_CONFIG, **(config_record.value or {})}
security_config = prepare_security_config(current_config)
if not security_config.changed:
return
config_record.value = security_config.config
await config_record.save()
if security_config.setup_required:
logger.warning("检测到空密码或旧版默认管理员密码,请通过初始化页面重新设置")
elif security_config.password_hashed:
logger.info("已将管理员密码迁移为哈希存储")
if security_config.jwt_secret_rotated:
logger.info("已生成独立 JWT 签名密钥")
await refresh_settings()
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()
def is_runtime_initialized() -> bool:
return is_config_initialized(dict(settings.items()))
async def initialize_system(
admin_password: str,
site_name: str | None = None,
setup_options: dict | None = None,
) -> None:
password = str(admin_password or "").strip()
if len(password) < MIN_ADMIN_PASSWORD_LENGTH:
raise ValueError(f"管理员密码至少需要 {MIN_ADMIN_PASSWORD_LENGTH} 位")
async with db_startup_lock():
config_record = await KeyValue.filter(key="settings").first()
current_config = {
**DEFAULT_CONFIG,
**(config_record.value if config_record and config_record.value else {}),
}
if is_config_initialized(current_config):
raise ValueError("系统已经初始化,请直接登录后台")
next_config = dict(current_config)
for key, value in (setup_options or {}).items():
if key in SETUP_CONFIG_FIELDS:
next_config[key] = value
normalized_site_name = str(site_name or "").strip()
if normalized_site_name:
next_config["name"] = normalized_site_name[:80]
next_config["admin_token"] = hash_password(password)
if not is_valid_jwt_secret(next_config.get("jwt_secret")):
next_config["jwt_secret"] = generate_jwt_secret()
await KeyValue.update_or_create(key="settings", defaults={"value": next_config})
await refresh_settings()
+89 -23
View File
@@ -1,38 +1,104 @@
import asyncio
import glob
import importlib
import os
from contextlib import asynccontextmanager
from typing import IO
from tortoise import Tortoise
from core.logger import logger
from core.settings import data_root
_DB_FILE = os.path.join(data_root, "filecodebox.db")
_STARTUP_LOCK_FILE = os.path.join(data_root, "filecodebox.startup.lock")
def get_db_config() -> dict:
return {
"connections": {
"default": {
"engine": "tortoise.backends.sqlite",
"credentials": {
"file_path": _DB_FILE,
"journal_mode": "WAL",
"busy_timeout": 10000,
"foreign_keys": "ON",
},
}
},
"apps": {
"models": {
"models": ["apps.base.models"],
"default_connection": "default",
}
},
"use_tz": False,
"timezone": "Asia/Shanghai",
}
def _lock_file(file_obj: IO[str]) -> None:
if os.name == "nt":
import msvcrt
# Windows 需要锁定至少 1 字节
if os.fstat(file_obj.fileno()).st_size == 0:
file_obj.write("0")
file_obj.flush()
msvcrt.locking(file_obj.fileno(), msvcrt.LK_LOCK, 1)
else:
import fcntl
fcntl.flock(file_obj.fileno(), fcntl.LOCK_EX)
def _unlock_file(file_obj: IO[str]) -> None:
if os.name == "nt":
import msvcrt
msvcrt.locking(file_obj.fileno(), msvcrt.LK_UNLCK, 1)
else:
import fcntl
fcntl.flock(file_obj.fileno(), fcntl.LOCK_UN)
@asynccontextmanager
async def db_startup_lock():
os.makedirs(data_root, exist_ok=True)
lock_file = open(_STARTUP_LOCK_FILE, "a+", encoding="utf-8")
try:
await asyncio.to_thread(_lock_file, lock_file)
yield
finally:
await asyncio.to_thread(_unlock_file, lock_file)
lock_file.close()
async def init_db():
try:
# 使用正确的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:
print(f"数据库初始化失败: {str(e)}")
logger.error(f"数据库初始化失败: {str(e)}")
raise
@@ -58,7 +124,7 @@ async def execute_migrations():
)
if not executed[1]:
print(f"执行迁移: {file_name}")
logger.info(f"执行迁移: {file_name}")
# 导入并执行migration
module_path = migration_file.replace("/", ".").replace("\\", ".").replace(".py", "")
try:
@@ -70,11 +136,11 @@ async def execute_migrations():
"INSERT INTO migrates (migration_file) VALUES (?)",
[file_name]
)
print(f"迁移完成: {file_name}")
logger.info(f"迁移完成: {file_name}")
except Exception as e:
print(f"迁移 {file_name} 执行失败: {str(e)}")
logger.error(f"迁移 {file_name} 执行失败: {str(e)}")
raise
except Exception as e:
print(f"迁移过程发生错误: {str(e)}")
logger.error(f"迁移过程发生错误: {str(e)}")
raise
+28
View File
@@ -0,0 +1,28 @@
import logging
import sys
def setup_logger():
# 创建logger对象
_logger = logging.getLogger('FileCodeBox')
_logger.setLevel(logging.INFO)
# 创建控制台处理器
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
# 设置日志格式
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
console_handler.setFormatter(formatter)
# 添加处理器到logger
_logger.addHandler(console_handler)
return _logger
# 创建全局logger实例
logger = setup_logger()
+9 -4
View File
@@ -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
+60
View File
@@ -0,0 +1,60 @@
import copy
import secrets
from dataclasses import dataclass
from typing import Any
from core.utils import hash_password, is_password_hashed, verify_password
JWT_SECRET_MIN_LENGTH = 32
INTERNAL_CONFIG_KEYS = {"jwt_secret"}
LEGACY_DEFAULT_ADMIN_TOKEN = "FileCodeBox" + "2023"
@dataclass
class SecurityConfigResult:
config: dict[str, Any]
changed: bool = False
password_hashed: bool = False
jwt_secret_rotated: bool = False
setup_required: bool = False
def generate_jwt_secret() -> str:
return secrets.token_urlsafe(48)
def is_valid_jwt_secret(secret: Any) -> bool:
return isinstance(secret, str) and len(secret) >= JWT_SECRET_MIN_LENGTH
def is_config_initialized(config: dict[str, Any]) -> bool:
admin_token = str(config.get("admin_token") or "")
if not admin_token:
return False
return not verify_password(LEGACY_DEFAULT_ADMIN_TOKEN, admin_token)
def prepare_security_config(config: dict[str, Any]) -> SecurityConfigResult:
next_config = copy.deepcopy(config)
result = SecurityConfigResult(config=next_config)
admin_token = str(next_config.get("admin_token") or "")
if not admin_token:
result.setup_required = True
elif verify_password(LEGACY_DEFAULT_ADMIN_TOKEN, admin_token):
next_config["admin_token"] = ""
result.setup_required = True
result.changed = True
elif not is_password_hashed(admin_token):
next_config["admin_token"] = hash_password(admin_token)
result.password_hashed = True
result.changed = True
jwt_secret = next_config.get("jwt_secret")
if not is_valid_jwt_secret(jwt_secret):
next_config["jwt_secret"] = generate_jwt_secret()
result.jwt_secret_rotated = True
result.changed = True
return result
+11 -4
View File
@@ -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": "",
@@ -35,14 +36,17 @@ DEFAULT_CONFIG = {
"onedrive_password": "",
"onedrive_root_path": "filebox_storage",
"onedrive_proxy": 0,
"webdav_hostname": "",
"webdav_root_path": "filebox_storage",
"webdav_proxy": 0,
"admin_token": "FileCodeBox2023",
"admin_token": "",
"jwt_secret": "",
"openUpload": 1,
"uploadSize": 1024 * 1024 * 10,
"allowed_file_types": ["*"],
"expireStyle": ["day", "hour", "minute", "forever", "count"],
"code_generate_type": "number",
"uploadMinute": 1,
"enableChunk": 0,
"webdav_url": "",
"webdav_password": "",
"webdav_username": "",
@@ -65,10 +69,13 @@ DEFAULT_CONFIG = {
],
"themesSelect": "themes/2024",
"errorMinute": 1,
"errorCount": 1,
"port": 12345,
"errorCount": 10,
"serverWorkers": 1,
"serverHost": "0.0.0.0",
"serverPort": 12345,
"showAdminAddr": 0,
"robotsText": "User-agent: *\nDisallow: /",
"trustedProxies": [],
}
+917 -112
View File
File diff suppressed because it is too large. Load diff
+55 -6
View File
@@ -3,21 +3,25 @@
# @File : tasks.py
# @Software: PyCharm
import asyncio
import datetime
import logging
import os
from tortoise.expressions import Q
from apps.base.models import FileCodes
from apps.base.utils import ip_limit
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"):
@@ -29,9 +33,54 @@ async def delete_expire_files():
Q(expired_at__lt=await get_now()) | Q(expired_count=0)
).all()
for exp in expire_data:
await file_storage.delete_file(exp)
await exp.delete()
try:
await file_storage.delete_file(exp)
except Exception as e:
logging.error(f"删除过期文件失败 code={exp.code}: {e}")
try:
await exp.delete()
except Exception as e:
logging.error(f"删除记录失败 code={exp.code}: {e}")
except Exception as e:
print(e)
logging.error(e)
finally:
await asyncio.sleep(600)
async def clean_incomplete_uploads():
while True:
try:
await refresh_settings()
file_storage: FileStorageInterface = storages[settings.file_storage]()
expire_hours = getattr(settings, "chunk_expire_hours", 24)
now = await get_now()
expire_time = now - datetime.timedelta(hours=expire_hours)
expired_sessions = await UploadChunk.filter(
chunk_index=-1, created_at__lt=expire_time
).all()
for session in expired_sessions:
try:
save_path = session.save_path
if not save_path:
_, _, _, _, save_path = await get_chunk_file_path_name(
session.file_name, session.upload_id
)
await file_storage.clean_chunks(session.upload_id, save_path)
except Exception as e:
logging.error(
f"清理分片文件失败 upload_id={session.upload_id}: {e}"
)
try:
await UploadChunk.filter(upload_id=session.upload_id).delete()
logging.info(f"已清理过期上传会话 upload_id={session.upload_id}")
except Exception as e:
logging.error(
f"删除分片记录失败 upload_id={session.upload_id}: {e}"
)
except Exception as e:
logging.error(f"清理未完成上传任务异常: {e}")
finally:
await asyncio.sleep(3600)
+71 -4
View File
@@ -4,9 +4,12 @@
# @Software: PyCharm
import datetime
import hashlib
import random
import os
import re
import secrets
import string
import time
from core.settings import settings
@@ -15,7 +18,7 @@ async def get_random_num():
获取随机数
:return:
"""
return random.randint(10000, 99999)
return secrets.randbelow(90000) + 10000
r_s = string.ascii_uppercase + string.digits
@@ -26,7 +29,7 @@ async def get_random_string():
获取随机字符串
:return:
"""
return "".join(random.choice(r_s) for _ in range(5))
return "".join(secrets.choice(r_s) for _ in range(5))
async def get_now():
@@ -43,7 +46,9 @@ async def get_select_token(code: str):
:param code:
:return:
"""
token = settings.admin_token
token = getattr(settings, "jwt_secret", "")
if not token:
raise RuntimeError("应用签名密钥未初始化")
return hashlib.sha256(
f"{code}{int(time.time() / 1000)}000{token}".encode()
).hexdigest()
@@ -92,3 +97,65 @@ async def max_save_times_desc(max_save_seconds: int):
desc_zh += gen_desc_zh(max_timedelta.seconds % 60, "秒")
desc_en += gen_desc_en(max_timedelta.seconds % 60, "second")
return desc_zh, desc_en
def hash_password(password: str) -> str:
"""
使用 SHA256 + salt 哈希密码
返回格式: sha256$<salt>$<hash>
"""
salt = os.urandom(16).hex()
password_hash = hashlib.sha256(f"{salt}{password}".encode()).hexdigest()
return f"sha256${salt}${password_hash}"
def verify_password(password: str, hashed: str) -> bool:
"""
验证密码是否匹配
支持新格式 (sha256$salt$hash) 和旧格式 (明文)
"""
if not hashed:
return False
# 新格式: sha256$salt$hash
if hashed.startswith("sha256$"):
parts = hashed.split("$")
if len(parts) != 3:
return False
_, salt, stored_hash = parts
password_hash = hashlib.sha256(f"{salt}{password}".encode()).hexdigest()
return 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:
"""
安全处理文件名:
1. 剥离路径只保留文件名
2. 替换非法字符
3. 处理空文件名情况
"""
filename = os.path.basename(filename)
illegal_chars = r'[\\/*?:"<>|\x00-\x1F]' # 包含控制字符
# 替换非法字符为下划线
cleaned = re.sub(illegal_chars, "_", filename)
# 处理空格(可选替换为_)
cleaned = cleaned.replace(" ", "_")
# 处理连续下划线
cleaned = re.sub(r"_+", "_", cleaned)
# 处理首尾特殊字符
cleaned = cleaned.strip("._")
# 处理空文件名情况
if not cleaned:
cleaned = "unnamed_file"
# 长度限制(按需调整)
return cleaned[:255]
+1
View File
@@ -0,0 +1 @@
APP_VERSION = "2.4.0"
+12
View File
@@ -0,0 +1,12 @@
version: "3"
services:
file-code-box:
image: lanol/filecodebox:latest
volumes:
- fcb-data:/app/data:rw
restart: unless-stopped
ports:
- "12345:12345"
volumes:
fcb-data:
external: false
-275
View File
@@ -1,275 +0,0 @@
import {
useMediaQuery
} from "./chunk-KT7LHMJ2.js";
import {
computed,
ref,
shallowRef,
watch
} from "./chunk-CQOUZRMK.js";
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/index.js
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/fonts.css";
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/without-fonts.js
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/vars.css";
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/base.css";
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/icons.css";
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/utils.css";
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/components/custom-block.css";
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/components/vp-code.css";
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/components/vp-code-group.css";
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/components/vp-doc.css";
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/components/vp-sponsor.css";
import VPBadge from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPBadge.vue";
import Layout from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/Layout.vue";
import { default as default2 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPBadge.vue";
import { default as default3 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPButton.vue";
import { default as default4 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPDocAsideSponsors.vue";
import { default as default5 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPFeatures.vue";
import { default as default6 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPHomeContent.vue";
import { default as default7 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPHomeFeatures.vue";
import { default as default8 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPHomeHero.vue";
import { default as default9 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPHomeSponsors.vue";
import { default as default10 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPImage.vue";
import { default as default11 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPLink.vue";
import { default as default12 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPNavBarSearch.vue";
import { default as default13 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPSocialLink.vue";
import { default as default14 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPSocialLinks.vue";
import { default as default15 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPSponsors.vue";
import { default as default16 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPTeamMembers.vue";
import { default as default17 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPTeamPage.vue";
import { default as default18 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPTeamPageSection.vue";
import { default as default19 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPTeamPageTitle.vue";
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/local-nav.js
import { onContentUpdated } from "vitepress";
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/outline.js
import { getScrollOffset } from "vitepress";
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/support/utils.js
import { withBase } from "vitepress";
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/data.js
import { useData as useData$ } from "vitepress";
var useData = useData$;
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/support/utils.js
function ensureStartingSlash(path) {
return path.startsWith("/") ? path : `/${path}`;
}
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/support/sidebar.js
function getSidebar(_sidebar, path) {
if (Array.isArray(_sidebar))
return addBase(_sidebar);
if (_sidebar == null)
return [];
path = ensureStartingSlash(path);
const dir = Object.keys(_sidebar).sort((a, b) => {
return b.split("/").length - a.split("/").length;
}).find((dir2) => {
return path.startsWith(ensureStartingSlash(dir2));
});
const sidebar = dir ? _sidebar[dir] : [];
return Array.isArray(sidebar) ? addBase(sidebar) : addBase(sidebar.items, sidebar.base);
}
function getSidebarGroups(sidebar) {
const groups = [];
let lastGroupIndex = 0;
for (const index in sidebar) {
const item = sidebar[index];
if (item.items) {
lastGroupIndex = groups.push(item);
continue;
}
if (!groups[lastGroupIndex]) {
groups.push({ items: [] });
}
groups[lastGroupIndex].items.push(item);
}
return groups;
}
function addBase(items, _base) {
return [...items].map((_item) => {
const item = { ..._item };
const base = item.base || _base;
if (base && item.link)
item.link = base + item.link;
if (item.items)
item.items = addBase(item.items, base);
return item;
});
}
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/sidebar.js
function useSidebar() {
const { frontmatter, page, theme: theme2 } = useData();
const is960 = useMediaQuery("(min-width: 960px)");
const isOpen = ref(false);
const _sidebar = computed(() => {
const sidebarConfig = theme2.value.sidebar;
const relativePath = page.value.relativePath;
return sidebarConfig ? getSidebar(sidebarConfig, relativePath) : [];
});
const sidebar = ref(_sidebar.value);
watch(_sidebar, (next, prev) => {
if (JSON.stringify(next) !== JSON.stringify(prev))
sidebar.value = _sidebar.value;
});
const hasSidebar = computed(() => {
return frontmatter.value.sidebar !== false && sidebar.value.length > 0 && frontmatter.value.layout !== "home";
});
const leftAside = computed(() => {
if (hasAside)
return frontmatter.value.aside == null ? theme2.value.aside === "left" : frontmatter.value.aside === "left";
return false;
});
const hasAside = computed(() => {
if (frontmatter.value.layout === "home")
return false;
if (frontmatter.value.aside != null)
return !!frontmatter.value.aside;
return theme2.value.aside !== false;
});
const isSidebarEnabled = computed(() => hasSidebar.value && is960.value);
const sidebarGroups = computed(() => {
return hasSidebar.value ? getSidebarGroups(sidebar.value) : [];
});
function open() {
isOpen.value = true;
}
function close() {
isOpen.value = false;
}
function toggle() {
isOpen.value ? close() : open();
}
return {
isOpen,
sidebar,
sidebarGroups,
hasSidebar,
hasAside,
leftAside,
isSidebarEnabled,
open,
close,
toggle
};
}
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/outline.js
var ignoreRE = /\b(?:VPBadge|header-anchor|footnote-ref|ignore-header)\b/;
var resolvedHeaders = [];
function getHeaders(range) {
const headers = [
...document.querySelectorAll(".VPDoc :where(h1,h2,h3,h4,h5,h6)")
].filter((el) => el.id && el.hasChildNodes()).map((el) => {
const level = Number(el.tagName[1]);
return {
element: el,
title: serializeHeader(el),
link: "#" + el.id,
level
};
});
return resolveHeaders(headers, range);
}
function serializeHeader(h) {
let ret = "";
for (const node of h.childNodes) {
if (node.nodeType === 1) {
if (ignoreRE.test(node.className))
continue;
ret += node.textContent;
} else if (node.nodeType === 3) {
ret += node.textContent;
}
}
return ret.trim();
}
function resolveHeaders(headers, range) {
if (range === false) {
return [];
}
const levelsRange = (typeof range === "object" && !Array.isArray(range) ? range.level : range) || 2;
const [high, low] = typeof levelsRange === "number" ? [levelsRange, levelsRange] : levelsRange === "deep" ? [2, 6] : levelsRange;
return buildTree(headers, high, low);
}
function buildTree(data, min, max) {
resolvedHeaders.length = 0;
const result = [];
const stack = [];
data.forEach((item) => {
const node = { ...item, children: [] };
let parent = stack[stack.length - 1];
while (parent && parent.level >= node.level) {
stack.pop();
parent = stack[stack.length - 1];
}
if (node.element.classList.contains("ignore-header") || parent && "shouldIgnore" in parent) {
stack.push({ level: node.level, shouldIgnore: true });
return;
}
if (node.level > max || node.level < min)
return;
resolvedHeaders.push({ element: node.element, link: node.link });
if (parent)
parent.children.push(node);
else
result.push(node);
stack.push(node);
});
return result;
}
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/local-nav.js
function useLocalNav() {
const { theme: theme2, frontmatter } = useData();
const headers = shallowRef([]);
const hasLocalNav = computed(() => {
return headers.value.length > 0;
});
onContentUpdated(() => {
headers.value = getHeaders(frontmatter.value.outline ?? theme2.value.outline);
});
return {
headers,
hasLocalNav
};
}
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/without-fonts.js
var theme = {
Layout,
enhanceApp: ({ app }) => {
app.component("Badge", VPBadge);
}
};
var without_fonts_default = theme;
export {
default2 as VPBadge,
default3 as VPButton,
default4 as VPDocAsideSponsors,
default5 as VPFeatures,
default6 as VPHomeContent,
default7 as VPHomeFeatures,
default8 as VPHomeHero,
default9 as VPHomeSponsors,
default10 as VPImage,
default11 as VPLink,
default12 as VPNavBarSearch,
default13 as VPSocialLink,
default14 as VPSocialLinks,
default15 as VPSponsors,
default16 as VPTeamMembers,
default17 as VPTeamPage,
default18 as VPTeamPageSection,
default19 as VPTeamPageTitle,
without_fonts_default as default,
useLocalNav,
useSidebar
};
//# sourceMappingURL=@theme_index.js.map
-7
View File
@@ -1,7 +0,0 @@
{
"version": 3,
"sources": ["../../../node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/index.js", "../../../node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/without-fonts.js", "../../../node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/local-nav.js", "../../../node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/outline.js", "../../../node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/support/utils.js", "../../../node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/data.js", "../../../node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/support/sidebar.js", "../../../node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/sidebar.js"],
"sourcesContent": ["import './styles/fonts.css';\nexport * from './without-fonts';\nexport { default as default } from './without-fonts';\n", "import './styles/vars.css';\nimport './styles/base.css';\nimport './styles/icons.css';\nimport './styles/utils.css';\nimport './styles/components/custom-block.css';\nimport './styles/components/vp-code.css';\nimport './styles/components/vp-code-group.css';\nimport './styles/components/vp-doc.css';\nimport './styles/components/vp-sponsor.css';\nimport VPBadge from './components/VPBadge.vue';\nimport Layout from './Layout.vue';\nexport { default as VPBadge } from './components/VPBadge.vue';\nexport { default as VPButton } from './components/VPButton.vue';\nexport { default as VPDocAsideSponsors } from './components/VPDocAsideSponsors.vue';\nexport { default as VPFeatures } from './components/VPFeatures.vue';\nexport { default as VPHomeContent } from './components/VPHomeContent.vue';\nexport { default as VPHomeFeatures } from './components/VPHomeFeatures.vue';\nexport { default as VPHomeHero } from './components/VPHomeHero.vue';\nexport { default as VPHomeSponsors } from './components/VPHomeSponsors.vue';\nexport { default as VPImage } from './components/VPImage.vue';\nexport { default as VPLink } from './components/VPLink.vue';\nexport { default as VPNavBarSearch } from './components/VPNavBarSearch.vue';\nexport { default as VPSocialLink } from './components/VPSocialLink.vue';\nexport { default as VPSocialLinks } from './components/VPSocialLinks.vue';\nexport { default as VPSponsors } from './components/VPSponsors.vue';\nexport { default as VPTeamMembers } from './components/VPTeamMembers.vue';\nexport { default as VPTeamPage } from './components/VPTeamPage.vue';\nexport { default as VPTeamPageSection } from './components/VPTeamPageSection.vue';\nexport { default as VPTeamPageTitle } from './components/VPTeamPageTitle.vue';\nexport { useLocalNav } from './composables/local-nav';\nexport { useSidebar } from './composables/sidebar';\nconst theme = {\n Layout,\n enhanceApp: ({ app }) => {\n app.component('Badge', VPBadge);\n }\n};\nexport default theme;\n", "import { onContentUpdated } from 'vitepress';\nimport { computed, shallowRef } from 'vue';\nimport { getHeaders } from '../composables/outline';\nimport { useData } from './data';\nexport function useLocalNav() {\n const { theme, frontmatter } = useData();\n const headers = shallowRef([]);\n const hasLocalNav = computed(() => {\n return headers.value.length > 0;\n });\n onContentUpdated(() => {\n headers.value = getHeaders(frontmatter.value.outline ?? theme.value.outline);\n });\n return {\n headers,\n hasLocalNav\n };\n}\n", "import { getScrollOffset } from 'vitepress';\nimport { onMounted, onUnmounted, onUpdated } from 'vue';\nimport { throttleAndDebounce } from '../support/utils';\nimport { useAside } from './aside';\nconst ignoreRE = /\\b(?:VPBadge|header-anchor|footnote-ref|ignore-header)\\b/;\n// cached list of anchor elements from resolveHeaders\nconst resolvedHeaders = [];\nexport function resolveTitle(theme) {\n return ((typeof theme.outline === 'object' &&\n !Array.isArray(theme.outline) &&\n theme.outline.label) ||\n theme.outlineTitle ||\n 'On this page');\n}\nexport function getHeaders(range) {\n const headers = [\n ...document.querySelectorAll('.VPDoc :where(h1,h2,h3,h4,h5,h6)')\n ]\n .filter((el) => el.id && el.hasChildNodes())\n .map((el) => {\n const level = Number(el.tagName[1]);\n return {\n element: el,\n title: serializeHeader(el),\n link: '#' + el.id,\n level\n };\n });\n return resolveHeaders(headers, range);\n}\nfunction serializeHeader(h) {\n let ret = '';\n for (const node of h.childNodes) {\n if (node.nodeType === 1) {\n if (ignoreRE.test(node.className))\n continue;\n ret += node.textContent;\n }\n else if (node.nodeType === 3) {\n ret += node.textContent;\n }\n }\n return ret.trim();\n}\nexport function resolveHeaders(headers, range) {\n if (range === false) {\n return [];\n }\n const levelsRange = (typeof range === 'object' && !Array.isArray(range)\n ? range.level\n : range) || 2;\n const [high, low] = typeof levelsRange === 'number'\n ? [levelsRange, levelsRange]\n : levelsRange === 'deep'\n ? [2, 6]\n : levelsRange;\n return buildTree(headers, high, low);\n}\nexport function useActiveAnchor(container, marker) {\n const { isAsideEnabled } = useAside();\n const onScroll = throttleAndDebounce(setActiveLink, 100);\n let prevActiveLink = null;\n onMounted(() => {\n requestAnimationFrame(setActiveLink);\n window.addEventListener('scroll', onScroll);\n });\n onUpdated(() => {\n // sidebar update means Line truncated
"mappings": ";;;;;;;;;;;AAAA,OAAO;;;ACAP,OAAO;AACP,OAAO;AACP,OAAO;AACP,OAAO;AACP,OAAO;AACP,OAAO;AACP,OAAO;AACP,OAAO;AACP,OAAO;AACP,OAAO,aAAa;AACpB,OAAO,YAAY;AACnB,SAAoB,WAAXA,gBAA0B;AACnC,SAAoB,WAAXA,gBAA2B;AACpC,SAAoB,WAAXA,gBAAqC;AAC9C,SAAoB,WAAXA,gBAA6B;AACtC,SAAoB,WAAXA,gBAAgC;AACzC,SAAoB,WAAXA,gBAAiC;AAC1C,SAAoB,WAAXA,gBAA6B;AACtC,SAAoB,WAAXA,gBAAiC;AAC1C,SAAoB,WAAXA,iBAA0B;AACnC,SAAoB,WAAXA,iBAAyB;AAClC,SAAoB,WAAXA,iBAAiC;AAC1C,SAAoB,WAAXA,iBAA+B;AACxC,SAAoB,WAAXA,iBAAgC;AACzC,SAAoB,WAAXA,iBAA6B;AACtC,SAAoB,WAAXA,iBAAgC;AACzC,SAAoB,WAAXA,iBAA6B;AACtC,SAAoB,WAAXA,iBAAoC;AAC7C,SAAoB,WAAXA,iBAAkC;;;AC5B3C,SAAS,wBAAwB;;;ACAjC,SAAS,uBAAuB;;;ACAhC,SAAS,gBAAgB;;;ACAzB,SAAS,WAAW,gBAAgB;AAC7B,IAAM,UAAU;;;ADgBhB,SAAS,oBAAoB,MAAM;AACtC,SAAO,KAAK,WAAW,GAAG,IAAI,OAAO,IAAI,IAAI;AACjD;;;AEXO,SAAS,WAAW,UAAU,MAAM;AACvC,MAAI,MAAM,QAAQ,QAAQ;AACtB,WAAO,QAAQ,QAAQ;AAC3B,MAAI,YAAY;AACZ,WAAO,CAAC;AACZ,SAAO,oBAAoB,IAAI;AAC/B,QAAM,MAAM,OAAO,KAAK,QAAQ,EAC3B,KAAK,CAAC,GAAG,MAAM;AAChB,WAAO,EAAE,MAAM,GAAG,EAAE,SAAS,EAAE,MAAM,GAAG,EAAE;AAAA,EAC9C,CAAC,EACI,KAAK,CAACC,SAAQ;AAEf,WAAO,KAAK,WAAW,oBAAoBA,IAAG,CAAC;AAAA,EACnD,CAAC;AACD,QAAM,UAAU,MAAM,SAAS,GAAG,IAAI,CAAC;AACvC,SAAO,MAAM,QAAQ,OAAO,IACtB,QAAQ,OAAO,IACf,QAAQ,QAAQ,OAAO,QAAQ,IAAI;AAC7C;AAIO,SAAS,iBAAiB,SAAS;AACtC,QAAM,SAAS,CAAC;AAChB,MAAI,iBAAiB;AACrB,aAAW,SAAS,SAAS;AACzB,UAAM,OAAO,QAAQ,KAAK;AAC1B,QAAI,KAAK,OAAO;AACZ,uBAAiB,OAAO,KAAK,IAAI;AACjC;AAAA,IACJ;AACA,QAAI,CAAC,OAAO,cAAc,GAAG;AACzB,aAAO,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC;AAAA,IAC7B;AACA,WAAO,cAAc,EAAE,MAAM,KAAK,IAAI;AAAA,EAC1C;AACA,SAAO;AACX;AAiCA,SAAS,QAAQ,OAAO,OAAO;AAC3B,SAAO,CAAC,GAAG,KAAK,EAAE,IAAI,CAAC,UAAU;AAC7B,UAAM,OAAO,EAAE,GAAG,MAAM;AACxB,UAAM,OAAO,KAAK,QAAQ;AAC1B,QAAI,QAAQ,KAAK;AACb,WAAK,OAAO,OAAO,KAAK;AAC5B,QAAI,KAAK;AACL,WAAK,QAAQ,QAAQ,KAAK,OAAO,IAAI;AACzC,WAAO;AAAA,EACX,CAAC;AACL;;;ACnFO,SAAS,aAAa;AACzB,QAAM,EAAE,aAAa,MAAM,OAAAC,OAAM,IAAI,QAAQ;AAC7C,QAAM,QAAQ,cAAc,oBAAoB;AAChD,QAAM,SAAS,IAAI,KAAK;AACxB,QAAM,WAAW,SAAS,MAAM;AAC5B,UAAM,gBAAgBA,OAAM,MAAM;AAClC,UAAM,eAAe,KAAK,MAAM;AAChC,WAAO,gBAAgB,WAAW,eAAe,YAAY,IAAI,CAAC;AAAA,EACtE,CAAC;AACD,QAAM,UAAU,IAAI,SAAS,KAAK;AAClC,QAAM,UAAU,CAAC,MAAM,SAAS;AAC5B,QAAI,KAAK,UAAU,IAAI,MAAM,KAAK,UAAU,IAAI;AAC5C,cAAQ,QAAQ,SAAS;AAAA,EACjC,CAAC;AACD,QAAM,aAAa,SAAS,MAAM;AAC9B,WAAQ,YAAY,MAAM,YAAY,SAClC,QAAQ,MAAM,SAAS,KACvB,YAAY,MAAM,WAAW;AAAA,EACrC,CAAC;AACD,QAAM,YAAY,SAAS,MAAM;AAC7B,QAAI;AACA,aAAO,YAAY,MAAM,SAAS,OAC5BA,OAAM,MAAM,UAAU,SACtB,YAAY,MAAM,UAAU;AACtC,WAAO;AAAA,EACX,CAAC;AACD,QAAM,WAAW,SAAS,MAAM;AAC5B,QAAI,YAAY,MAAM,WAAW;AAC7B,aAAO;AACX,QAAI,YAAY,MAAM,SAAS;AAC3B,aAAO,CAAC,CAAC,YAAY,MAAM;AAC/B,WAAOA,OAAM,MAAM,UAAU;AAAA,EACjC,CAAC;AACD,QAAM,mBAAmB,SAAS,MAAM,WAAW,SAAS,MAAM,KAAK;AACvE,QAAM,gBAAgB,SAAS,MAAM;AACjC,WAAO,WAAW,QAAQ,iBAAiB,QAAQ,KAAK,IAAI,CAAC;AAAA,EACjE,CAAC;AACD,WAAS,OAAO;AACZ,WAAO,QAAQ;AAAA,EACnB;AACA,WAAS,QAAQ;AACb,WAAO,QAAQ;AAAA,EACnB;AACA,WAAS,SAAS;AACd,WAAO,QAAQ,MAAM,IAAI,KAAK;AAAA,EAClC;AACA,SAAO;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACJ;AACJ;;;AJ3DA,IAAM,WAAW;AAEjB,IAAM,kBAAkB,CAAC;AAQlB,SAAS,WAAW,OAAO;AAC9B,QAAM,UAAU;AAAA,IACZ,GAAG,SAAS,iBAAiB,kCAAkC;AAAA,EACnE,EACK,OAAO,CAAC,OAAO,GAAG,MAAM,GAAG,cAAc,CAAC,EAC1C,IAAI,CAAC,OAAO;AACb,UAAM,QAAQ,OAAO,GAAG,QAAQ,CAAC,CAAC;AAClC,WAAO;AAAA,MACH,SAAS;AAAA,MACT,OAAO,gBAAgB,EAAE;AAAA,MACzB,MAAM,MAAM,GAAG;AAAA,MACf;AAAA,IACJ;AAAA,EACJ,CAAC;AACD,SAAO,eAAe,SAAS,KAAK;AACxC;AACA,SAAS,gBAAgB,GAAG;AACxB,MAAI,MAAM;AACV,aAAW,QAAQ,EAAE,YAAY;AAC7B,QAAI,KAAK,aAAa,GAAG;AACrB,UAAI,SAAS,KAAK,KAAK,SAAS;AAC5B;AACJ,aAAO,KAAK;AAAA,IAChB,WACS,KAAK,aAAa,GAAG;AAC1B,aAAO,KAAK;AAAA,IAChB;AAAA,EACJ;AACA,SAAO,IAAI,KAAK;AACpB;AACO,SAAS,eAAe,SAAS,OAAO;AAC3C,MAAI,UAAU,OAAO;AACjB,WAAO,CAAC;AAAA,EACZ;AACA,QAAM,eAAe,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IAChE,MAAM,QACN,UAAU;AAChB,QAAM,CAAC,MAAM,GAAG,IAAI,OAAO,gBAAgB,WACrC,CAAC,aAAa,WAAW,IACzB,gBAAgB,SACZ,CAAC,GAAG,CAAC,IACL;AACV,SAAO,UAAU,SAAS,MAAM,GAAG;AACvC;AA8FA,SAAS,UAAU,MAAM,KAAK,KAAK;AAC/B,kBAAgB,SAAS;AACzB,QAAM,SAAS,CAAC;AAChB,QAAM,QAAQ,CAAC;AACf,OAAK,QAAQ,CAAC,SAAS;AACnB,UAAM,OAAO,EAAE,GAAG,MAAM,UAAU,CAAC,EAAE;AACrC,QAAI,SAAS,MAAM,MAAM,SAAS,CAAC;AACnC,WAAO,UAAU,OAAO,SAAS,KAAK,OAAO;AACzC,YAAM,IAAI;AACV,eAAS,MAAM,MAAM,SAAS,CAAC;AAAA,IACnC;AACA,QAAI,KAAK,QAAQ,UAAU,SAAS,eAAe,KAC9C,UAAU,kBAAkB,QAAS;AACtC,YAAM,KAAK,EAAE,OAAO,KAAK,OAAO,cAAc,KAAK,CAAC;AACpD;AAAA,IACJ;AACA,QAAI,KAAK,QAAQ,OAAO,KAAK,QAAQ;AACjC;AACJ,oBAAgB,KAAK,EAAE,SAAS,KAAK,SAAS,MAAM,KAAK,KAAK,CAAC;AAC/D,QAAI;AACA,aAAO,SAAS,KAAK,IAAI;AAAA;AAEzB,aAAO,KAAK,IAAI;AACpB,UAAM,KAAK,IAAI;AAAA,EACnB,CAAC;AACD,SAAO;AACX;;;AD7KO,SAAS,cAAc;AAC1B,QAAM,EAAE,OAAAC,QAAO,YAAY,IAAI,QAAQ;AACvC,QAAM,UAAU,WAAW,CAAC,CAAC;AAC7B,QAAM,cAAc,SAAS,MAAM;AAC/B,WAAO,QAAQ,MAAM,SAAS;AAAA,EAClC,CAAC;AACD,mBAAiB,MAAM;AACnB,YAAQ,QAAQ,WAAW,YAAY,MAAM,WAAWA,OAAM,MAAM,OAAO;AAAA,EAC/E,CAAC;AACD,SAAO;AAAA,IACH;AAAA,IACA;AAAA,EACJ;AACJ;;;ADcA,IAAM,QAAQ;AAAA,EACV;AAAA,EACA,YAAY,CAAC,EAAE,IAAI,MAAM;AACrB,QAAI,UAAU,SAAS,OAAO;AAAA,EAClC;AACJ;AACA,IAAO,wBAAQ;",
"names": ["default", "dir", "theme", "theme"]
}
+9 -15
View File
@@ -1,49 +1,43 @@
{
"hash": "d07f6dee",
"configHash": "dee2d3bc",
"hash": "8f855eaf",
"configHash": "1b3ca22f",
"lockfileHash": "bd28b2c2",
"browserHash": "b96651ac",
"browserHash": "29e84937",
"optimized": {
"vue": {
"src": "../../../node_modules/.pnpm/vue@3.5.13/node_modules/vue/dist/vue.runtime.esm-bundler.js",
"file": "vue.js",
"fileHash": "bc5c7f34",
"fileHash": "3215885f",
"needsInterop": false
},
"vitepress > @vue/devtools-api": {
"src": "../../../node_modules/.pnpm/@vue+devtools-api@7.7.1/node_modules/@vue/devtools-api/dist/index.js",
"file": "vitepress___@vue_devtools-api.js",
"fileHash": "00859881",
"fileHash": "5a5f95ef",
"needsInterop": false
},
"vitepress > @vueuse/core": {
"src": "../../../node_modules/.pnpm/@vueuse+core@12.5.0/node_modules/@vueuse/core/index.mjs",
"file": "vitepress___@vueuse_core.js",
"fileHash": "1c6da938",
"fileHash": "0fbf66f0",
"needsInterop": false
},
"vitepress > @vueuse/integrations/useFocusTrap": {
"src": "../../../node_modules/.pnpm/@vueuse+integrations@12.5.0_focus-trap@7.6.4/node_modules/@vueuse/integrations/useFocusTrap.mjs",
"file": "vitepress___@vueuse_integrations_useFocusTrap.js",
"fileHash": "11c08fcf",
"fileHash": "91b03896",
"needsInterop": false
},
"vitepress > mark.js/src/vanilla.js": {
"src": "../../../node_modules/.pnpm/mark.js@8.11.1/node_modules/mark.js/src/vanilla.js",
"file": "vitepress___mark__js_src_vanilla__js.js",
"fileHash": "b93dbfe7",
"fileHash": "99e4f81c",
"needsInterop": false
},
"vitepress > minisearch": {
"src": "../../../node_modules/.pnpm/minisearch@7.1.1/node_modules/minisearch/dist/es/index.js",
"file": "vitepress___minisearch.js",
"fileHash": "bfb6c3ac",
"needsInterop": false
},
"@theme/index": {
"src": "../../../node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/index.js",
"file": "@theme_index.js",
"fileHash": "07512287",
"fileHash": "cc176c9c",
"needsInterop": false
}
},
+18
View File
@@ -18,6 +18,7 @@ export default defineConfig({
{ text: '首页', link: '/' },
{ text: '指南', link: '/guide/getting-started' },
{ text: 'API', link: '/api/' },
{ text: '优秀案例', link: '/showcase' },
{ text: 'Demo', link: 'https://share.lanol.cn' },
{
text: '了解更多',
@@ -68,6 +69,14 @@ export default defineConfig({
],
},
],
'/showcase': [
{
text: '优秀案例',
items: [
{ text: '案例展示', link: '/showcase' },
],
},
],
},
socialLinks: [
{ icon: 'github', link: 'https://github.com/vastsa/FileCodeBox' },
@@ -96,6 +105,7 @@ export default defineConfig({
{ text: 'Home', link: '/en/' },
{ text: 'Guide', link: '/en/guide/getting-started' },
{ text: 'API', link: '/en/api/' },
{ text: 'Showcase', link: '/en/showcase' },
{ text: 'Demo', link: 'https://share.lanol.cn' },
{
text: 'More',
@@ -152,6 +162,14 @@ export default defineConfig({
],
},
],
'/en/showcase': [
{
text: 'Showcase',
items: [
{ text: 'Case Studies', link: '/en/showcase' },
],
},
],
},
socialLinks: [
{ icon: 'github', link: 'https://github.com/vastsa/FileCodeBox' },
+473
View File
@@ -0,0 +1,473 @@
:root {
/* --- 核心色板:清晨薄雾 (Teal -> Sky) --- */
--vp-c-brand-1: #14b8a6; /* Teal 500 */
--vp-c-brand-2: #0ea5e9; /* Sky 500 */
--vp-c-brand-3: #0f766e; /* Teal 700 */
--vp-c-brand-soft: rgba(20, 184, 166, 0.14);
/* --- 背景色:极简与通透 --- */
--vp-c-bg: #ffffff;
--vp-c-bg-alt: #f8fafc; /* Slate 50 */
--vp-c-bg-elv: #ffffff;
/* --- 文字颜色:柔和的深灰,而非纯黑 --- */
--vp-c-text-1: #334155; /* Slate 700 */
--vp-c-text-2: #64748b; /* Slate 500 */
--vp-c-text-3: #94a3b8; /* Slate 400 */
/* --- 边框与分隔 --- */
--vp-c-border: #e2e8f0;
--vp-c-divider: #f1f5f9;
/* --- 阴影:扩散柔光 --- */
--vp-shadow-1: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
--vp-shadow-2: 0 10px 15px -3px rgba(0, 0, 0, 0.05), 0 4px 6px -2px rgba(0, 0, 0, 0.025);
--vp-shadow-brand: 0 4px 14px 0 rgba(20, 184, 166, 0.3);
/* --- 布局参数 --- */
--vp-nav-height: 64px;
--vp-sidebar-width: 280px;
--vp-radius-default: 12px;
--vp-radius-small: 6px;
}
/* * ==========================================
* 暗黑模式重构 (Deep Ocean Theme)
* ==========================================
*/
.dark {
/* 背景:更深邃的蓝黑色,更有沉浸感 */
--vp-c-bg: #020617; /* Slate 950 */
--vp-c-bg-alt: #0f172a; /* Slate 900 */
--vp-c-bg-elv: #1e293b; /* Slate 800 */
/* 文字:降低纯白刺眼感,提高舒适度 */
--vp-c-text-1: #f8fafc; /* Slate 50 */
--vp-c-text-2: #94a3b8; /* Slate 400 */
--vp-c-text-3: #64748b; /* Slate 500 */
/* 边框:更细腻的深色线条 */
--vp-c-border: #1e293b;
--vp-c-divider: #0f172a;
/* 品牌色:调亮,产生荧光感 */
--vp-c-brand-1: #2dd4bf; /* Teal 400 */
--vp-c-brand-2: #38bdf8; /* Sky 400 */
--vp-c-brand-3: #14b8a6; /* Teal 500 */
--vp-c-brand-soft: rgba(45, 212, 191, 0.15); /* 淡淡的荧光底色 */
/* 阴影:暗色环境下的微光 */
--vp-shadow-1: 0 4px 6px -1px rgba(0, 0, 0, 0.5);
--vp-shadow-2: 0 10px 15px -3px rgba(0, 0, 0, 0.5);
--vp-shadow-brand: 0 0 20px rgba(45, 212, 191, 0.3); /* 品牌色发光 */
}
/* 全局基础设置 */
body {
font-family: 'Noto Sans SC', sans-serif;
background-color: var(--vp-c-bg-alt);
color: var(--vp-c-text-1);
margin: 0;
transition: background-color 0.3s, color 0.3s;
overflow-x: hidden;
}
a { text-decoration: none; color: inherit; transition: color 0.2s; }
/* -------------------------------------------
布局结构 (模拟 VitePress 布局)
------------------------------------------- */
.app-container {
display: flex;
flex-direction: column;
min-height: 100vh;
}
/* 1. 导航栏:毛玻璃 + 悬浮感 */
.VPNavBar {
position: fixed;
top: 0;
left: 0;
right: 0;
height: var(--vp-nav-height);
background-color: rgba(255, 255, 255, 0.85); /* 稍微增加不透明度 */
backdrop-filter: blur(20px) saturate(180%);
-webkit-backdrop-filter: blur(20px) saturate(180%);
border-bottom: 1px solid rgba(226, 232, 240, 0.6);
z-index: 50;
display: flex;
align-items: center;
padding: 0 24px;
justify-content: space-between;
}
.dark .VPNavBar {
background-color: rgba(2, 6, 23, 0.85); /* 深色背景半透 */
border-bottom: 1px solid rgba(30, 41, 59, 0.7);
}
.nav-logo {
font-weight: 700;
font-size: 1.2rem;
background: linear-gradient(120deg, var(--vp-c-brand-1), var(--vp-c-brand-2));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
display: flex;
align-items: center;
gap: 8px;
}
.nav-links {
display: flex;
gap: 24px;
font-size: 0.9rem;
font-weight: 500;
color: var(--vp-c-text-2);
}
.nav-link:hover {
color: var(--vp-c-brand-1);
}
.nav-link.active {
color: var(--vp-c-brand-1);
position: relative;
}
.nav-link.active::after {
content: '';
position: absolute;
bottom: -22px;
left: 0;
width: 100%;
height: 2px;
background: var(--vp-c-brand-1);
border-radius: 2px 2px 0 0;
box-shadow: 0 -2px 10px var(--vp-c-brand-1); /* 激活状态发光 */
}
/* 2. 侧边栏:极简卡片式 */
.VPSidebar {
position: fixed;
top: var(--vp-nav-height);
left: 0;
bottom: 0;
width: var(--vp-sidebar-width);
background-color: var(--vp-c-bg); /* 实色背景 */
border-right: 1px solid var(--vp-c-border);
padding: 32px 24px;
overflow-y: auto;
transform: translateX(0);
transition: transform 0.3s ease;
z-index: 40;
}
.dark .VPSidebar {
background-color: var(--vp-c-bg-alt); /* 侧边栏比内容区稍微亮一点点/或者暗一点 */
}
@media (max-width: 960px) {
.VPSidebar { transform: translateX(-100%); }
.VPSidebar.open { transform: translateX(0); }
}
.sidebar-group-title {
font-weight: 700;
color: var(--vp-c-text-1);
margin-bottom: 12px;
margin-top: 24px;
font-size: 1rem;
}
.sidebar-group-title:first-child { margin-top: 0; }
.sidebar-link {
display: block;
padding: 8px 12px;
margin: 4px 0;
border-radius: var(--vp-radius-small);
color: var(--vp-c-text-2);
font-size: 0.95rem;
transition: all 0.2s;
}
.sidebar-link:hover {
background-color: var(--vp-c-bg-alt);
color: var(--vp-c-brand-1);
}
.dark .sidebar-link:hover {
background-color: var(--vp-c-bg-elv);
}
.sidebar-link.active {
background-color: var(--vp-c-brand-soft);
color: var(--vp-c-brand-3);
font-weight: 600;
}
.dark .sidebar-link.active {
color: var(--vp-c-brand-1);
background-color: rgba(45, 212, 191, 0.1); /* 暗色模式下更通透 */
box-shadow: inset 2px 0 0 0 var(--vp-c-brand-1); /* 左侧高亮条 */
}
/* 3. 主内容区:居中与留白 */
.VPContent {
margin-top: var(--vp-nav-height);
margin-left: var(--vp-sidebar-width);
padding: 48px 64px;
min-height: calc(100vh - var(--vp-nav-height));
background-color: var(--vp-c-bg);
transition: margin-left 0.3s ease;
}
@media (max-width: 960px) {
.VPContent { margin-left: 0; padding: 32px 24px; }
}
/* 内容排版 (Typography) */
.vp-doc h1 {
font-size: 2.5rem;
font-weight: 800;
margin-bottom: 1.5rem;
line-height: 1.2;
background: linear-gradient(120deg, var(--vp-c-brand-1), var(--vp-c-brand-2));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
display: inline-block;
/* 暗色模式下加一点文字阴影增强可读性 */
filter: drop-shadow(0 0 2em rgba(20, 184, 166, 0.2));
}
.dark .vp-doc h1 {
filter: drop-shadow(0 0 25px rgba(45, 212, 191, 0.2));
}
.vp-doc h2 {
font-size: 1.8rem;
margin-top: 3rem;
margin-bottom: 1rem;
padding-bottom: 0.5rem;
border-bottom: 1px solid var(--vp-c-border);
color: var(--vp-c-text-1);
}
.vp-doc h3 {
font-size: 1.4rem;
margin-top: 2rem;
margin-bottom: 0.8rem;
color: var(--vp-c-text-1);
}
.vp-doc p {
line-height: 1.8;
margin-bottom: 1.2rem;
color: var(--vp-c-text-2);
font-size: 1.05rem;
}
/* 代码块美化 */
.vp-doc pre {
background-color: #1e293b; /* Dark Slate */
border-radius: var(--vp-radius-default);
padding: 20px;
overflow-x: auto;
color: #f8fafc;
margin: 24px 0;
border: 1px solid rgba(0,0,0,0.1);
box-shadow: var(--vp-shadow-1);
}
.dark .vp-doc pre {
background-color: #0f172a; /* 更深一层的背景 */
border: 1px solid #1e293b;
}
.vp-doc code {
font-family: 'Menlo', 'Monaco', 'Courier New', monospace;
font-size: 0.9em;
}
.vp-doc p code {
background-color: var(--vp-c-brand-soft);
color: var(--vp-c-brand-3);
padding: 2px 6px;
border-radius: 4px;
font-size: 0.9em;
}
.dark .vp-doc p code {
color: var(--vp-c-brand-1);
background-color: rgba(45, 212, 191, 0.1);
}
/* 引用块 (Blockquote) */
.vp-doc blockquote {
margin: 1.5rem 0;
padding: 16px 24px;
background-color: var(--vp-c-bg-alt);
border-left: 4px solid var(--vp-c-brand-1);
border-radius: 0 var(--vp-radius-default) var(--vp-radius-default) 0;
color: var(--vp-c-text-2);
}
.dark .vp-doc blockquote {
background-color: rgba(30, 41, 59, 0.5);
}
/* 按钮与卡片 (Features) */
.vp-button {
display: inline-block;
padding: 0 24px;
height: 48px;
line-height: 48px;
border-radius: 24px; /* Pill shape */
font-weight: 600;
font-size: 1rem;
transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
cursor: pointer;
border: none;
}
.vp-button.brand {
background: linear-gradient(135deg, var(--vp-c-brand-1), var(--vp-c-brand-2));
color: white;
box-shadow: var(--vp-shadow-brand);
}
.dark .vp-button.brand {
color: #020617; /* 暗色模式下按钮文字用深色,因为背景亮 */
}
.vp-button.brand:hover {
transform: translateY(-2px);
box-shadow: 0 8px 25px -4px rgba(20, 184, 166, 0.5);
}
.dark .vp-button.brand:hover {
box-shadow: 0 0 30px -4px rgba(45, 212, 191, 0.6); /* 发光增强 */
}
.vp-button.alt {
background-color: var(--vp-c-bg-alt);
color: var(--vp-c-text-1);
border: 1px solid var(--vp-c-border);
}
.dark .vp-button.alt {
background-color: transparent;
border-color: var(--vp-c-text-2);
color: var(--vp-c-text-1);
}
.vp-button.alt:hover {
border-color: var(--vp-c-brand-1);
color: var(--vp-c-brand-1);
}
/* 工具类 */
.theme-toggle {
background: none;
border: none;
cursor: pointer;
font-size: 1.5rem;
color: var(--vp-c-text-2);
display: flex;
align-items: center;
justify-content: center;
padding: 8px;
border-radius: 50%;
transition: background 0.2s;
}
.theme-toggle:hover {
background-color: var(--vp-c-bg-alt);
color: var(--vp-c-brand-1);
}
.dark .theme-toggle:hover {
background-color: var(--vp-c-bg-elv);
}
.mobile-menu-btn {
display: none;
background: none;
border: none;
font-size: 1.5rem;
color: var(--vp-c-text-1);
cursor: pointer;
}
@media (max-width: 960px) {
.mobile-menu-btn { display: block; }
.nav-links { display: none; }
}
/* 首页 Hero 样式模拟 */
.hero-section {
text-align: center;
padding: 80px 20px;
max-width: 800px;
margin: 0 auto;
}
.hero-title {
font-size: 3.5rem;
font-weight: 900;
line-height: 1.1;
margin-bottom: 24px;
}
.hero-title span {
background: linear-gradient(120deg, var(--vp-c-brand-1), var(--vp-c-brand-2));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.hero-desc {
font-size: 1.5rem;
color: var(--vp-c-text-2);
margin-bottom: 40px;
}
.hero-actions {
display: flex;
gap: 16px;
justify-content: center;
}
/* Features Grid */
.features-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 24px;
margin-top: 64px;
}
.feature-card {
background-color: var(--vp-c-bg-alt);
padding: 24px;
border-radius: var(--vp-radius-default);
transition: transform 0.3s, box-shadow 0.3s;
border: 1px solid transparent;
}
.dark .feature-card {
background-color: rgba(30, 41, 59, 0.3); /* 微微透明 */
border: 1px solid rgba(255,255,255,0.05);
}
.feature-card:hover {
background-color: var(--vp-c-bg);
transform: translateY(-4px);
box-shadow: var(--vp-shadow-2);
border-color: var(--vp-c-brand-soft);
}
.dark .feature-card:hover {
background-color: var(--vp-c-bg-elv);
border-color: var(--vp-c-brand-1);
box-shadow: 0 0 15px rgba(45, 212, 191, 0.1);
}
.feature-icon {
font-size: 2rem;
margin-bottom: 16px;
color: var(--vp-c-brand-1);
background-color: var(--vp-c-brand-soft);
width: 48px;
height: 48px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 12px;
}
.feature-title {
font-weight: 700;
margin-bottom: 8px;
color: var(--vp-c-text-1);
}
.feature-details {
color: var(--vp-c-text-2);
font-size: 0.95rem;
line-height: 1.6;
}
+6
View File
@@ -0,0 +1,6 @@
import DefaultTheme from 'vitepress/theme'
import './custom.css'
export default {
...DefaultTheme,
}
+75 -6
View File
@@ -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": "<初始化时设置的管理员密码>"}'
```
**响应示例:**
```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
@@ -260,4 +329,4 @@ Authorization: Bearer <token>
- 403: 禁止访问
- 404: 资源不存在
- 422: 请求参数验证错误
- 500: 服务器内部错误
- 500: 服务器内部错误
+454
View File
@@ -0,0 +1,454 @@
# 预签名上传 API 文档
## 概述
预签名上传功能提供统一的文件上传接口,根据后端存储类型自动选择最优上传方式:
- **S3 存储**: 返回预签名 URL,客户端直传 S3(减少服务器带宽压力)
- **其他存储**: 返回代理上传 URL,通过服务器中转上传
## 上传流程
### 流程图
```
┌─────────┐ 1. 初始化上传 ┌─────────┐
│ 客户端 │ ──────────────────────▶ │ 服务器 │
└─────────┘ └─────────┘
│ │
│◀─────── 返回 upload_url + mode ──┤
│ │
│ ┌─────────────────────────────────────────┐
│ │ if mode == "direct" (S3存储) │
│ │ 2a. PUT 文件到 upload_url (S3) │
│ │ 3a. POST /confirm 确认上传 │
│ │ │
│ │ if mode == "proxy" (其他存储) │
│ │ 2b. PUT 文件到 upload_url (服务器) │
│ │ (自动返回分享码,无需确认) │
│ └─────────────────────────────────────────┘
│
▼
获取分享码
```
---
## API 端点
### 1. 初始化上传
初始化预签名上传会话,获取上传 URL 和模式。
**请求**
```
POST /presign/upload/init
Content-Type: application/json
```
**请求体**
| 字段 | 类型 | 必填 | 默认值 | 说明 |
| ------------ | ------- | ---- | ------ | --------------------------------------- |
| file_name | string | ✅ | - | 文件名(含扩展名) |
| file_size | integer | ✅ | - | 文件大小(字节) |
| expire_value | integer | ❌ | 1 | 过期时间值 |
| expire_style | string | ❌ | "day" | 过期类型:day/hour/minute/forever/count |
**请求示例**
```json
{
"file_name": "document.pdf",
"file_size": 1048576,
"expire_value": 7,
"expire_style": "day"
}
```
**响应**
```json
{
"code": 200,
"detail": {
"upload_id": "a1b2c3d4e5f6...",
"upload_url": "https://bucket.s3.amazonaws.com/path?X-Amz-Signature=...",
"mode": "direct",
"save_path": "share/data/2024/01/01/uuid/document.pdf",
"expires_in": 900
}
}
```
**响应字段说明**
| 字段 | 类型 | 说明 |
| ---------- | ------- | ----------------------------------------------------- |
| upload_id | string | 上传会话 ID,后续操作需要 |
| upload_url | string | 上传目标 URL |
| mode | string | 上传模式:`direct`(直传 S3)或 `proxy`(服务器代理) |
| save_path | string | 文件存储路径 |
| expires_in | integer | URL 有效期(秒),默认 900 秒(15 分钟) |
**错误响应**
| 状态码 | 说明 |
| ------ | ------------------------------ |
| 400 | 过期时间类型错误 |
| 403 | 文件大小超过限制 / IP 频率限制 |
---
### 2a. 直传模式 - 上传文件到 S3
当 `mode == "direct"` 时,客户端直接将文件 PUT 到返回的预签名 URL。
**请求**
```
PUT {upload_url}
Content-Type: application/octet-stream
[文件二进制内容]
```
**注意事项**
- 直接使用返回的 `upload_url`,不要修改
- Content-Type 建议使用 `application/octet-stream`
- 这是直接请求 S3,不经过服务器
**JavaScript 示例**
```javascript
const response = await fetch(uploadUrl, {
method: 'PUT',
body: file,
headers: {
'Content-Type': 'application/octet-stream',
},
})
if (response.ok) {
// 上传成功,调用确认接口
}
```
---
### 2b. 代理模式 - 上传文件到服务器
当 `mode == "proxy"` 时,客户端将文件 PUT 到服务器代理端点。
**请求**
```
PUT /presign/upload/proxy/{upload_id}
Content-Type: multipart/form-data
file: [文件]
```
**路径参数**
| 参数 | 说明 |
| --------- | ------------------------- |
| upload_id | 初始化时返回的上传会话 ID |
**响应**
```json
{
"code": 200,
"detail": {
"code": "123456",
"name": "document.pdf"
}
}
```
**注意**: 代理模式上传成功后直接返回分享码,无需调用确认接口。
**错误响应**
| 状态码 | 说明 |
| ------ | --------------------------------------- |
| 400 | 文件大小与声明不符 / 会话不支持代理上传 |
| 404 | 上传会话不存在或已过期 |
| 500 | 文件保存失败 |
---
### 3. 确认上传(仅直传模式)
直传模式下,客户端完成 S3 上传后调用此接口确认并获取分享码。
**请求**
```
POST /presign/upload/confirm/{upload_id}
Content-Type: application/json
```
**路径参数**
| 参数 | 说明 |
| --------- | ------------------------- |
| upload_id | 初始化时返回的上传会话 ID |
**请求体**
| 字段 | 类型 | 必填 | 默认值 | 说明 |
| ------------ | ------- | ---- | ------ | ---------- |
| expire_value | integer | ❌ | 1 | 过期时间值 |
| expire_style | string | ❌ | "day" | 过期类型 |
**请求示例**
```json
{
"expire_value": 7,
"expire_style": "day"
}
```
**响应**
```json
{
"code": 200,
"detail": {
"code": "123456",
"name": "document.pdf"
}
}
```
**错误响应**
| 状态码 | 说明 |
| ------ | --------------------------------------------- |
| 400 | 会话不支持直传确认 |
| 404 | 上传会话不存在或已过期 / 文件未上传或上传失败 |
---
### 4. 查询上传状态
查询上传会话的当前状态。
**请求**
```
GET /presign/upload/status/{upload_id}
```
**响应**
```json
{
"code": 200,
"detail": {
"upload_id": "a1b2c3d4e5f6...",
"file_name": "document.pdf",
"file_size": 1048576,
"mode": "direct",
"created_at": "2024-01-01T12:00:00",
"expires_at": "2024-01-01T12:15:00",
"is_expired": false
}
}
```
**错误响应**
| 状态码 | 说明 |
| ------ | -------------- |
| 404 | 上传会话不存在 |
---
### 5. 取消上传
取消上传会话并清理相关资源。
**请求**
```
DELETE /presign/upload/{upload_id}
```
**响应**
```json
{
"code": 200,
"detail": {
"message": "上传会话已取消"
}
}
```
**错误响应**
| 状态码 | 说明 |
| ------ | -------------- |
| 404 | 上传会话不存在 |
---
## 前端集成示例
### 完整上传流程(JavaScript/TypeScript)
```typescript
interface PresignInitResponse {
upload_id: string
upload_url: string
mode: 'direct' | 'proxy'
save_path: string
expires_in: number
}
interface UploadResult {
code: string
name: string
}
async function uploadFile(
file: File,
expireValue: number = 1,
expireStyle: string = 'day'
): Promise<UploadResult> {
// 1. 初始化上传
const initResponse = await fetch('/presign/upload/init', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
file_name: file.name,
file_size: file.size,
expire_value: expireValue,
expire_style: expireStyle,
}),
})
const initData = await initResponse.json()
if (initData.code !== 200) {
throw new Error(initData.detail)
}
const { upload_id, upload_url, mode } = initData.detail as PresignInitResponse
// 2. 根据模式上传文件
if (mode === 'direct') {
// 直传模式:上传到S3
const uploadResponse = await fetch(upload_url, {
method: 'PUT',
body: file,
headers: { 'Content-Type': 'application/octet-stream' },
})
if (!uploadResponse.ok) {
throw new Error('S3上传失败')
}
// 3. 确认上传
const confirmResponse = await fetch(
`/presign/upload/confirm/${upload_id}`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
expire_value: expireValue,
expire_style: expireStyle,
}),
}
)
const confirmData = await confirmResponse.json()
if (confirmData.code !== 200) {
throw new Error(confirmData.detail)
}
return confirmData.detail
} else {
// 代理模式:上传到服务器
const formData = new FormData()
formData.append('file', file)
const uploadResponse = await fetch(upload_url, {
method: 'PUT',
body: formData,
})
const uploadData = await uploadResponse.json()
if (uploadData.code !== 200) {
throw new Error(uploadData.detail)
}
return uploadData.detail
}
}
// 使用示例
const file = document.querySelector('input[type="file"]').files[0]
const result = await uploadFile(file, 7, 'day')
console.log('分享码:', result.code)
```
### Vue 3 组件示例
```vue
<template>
<div>
<input type="file" @change="handleFileSelect" />
<button @click="upload" :disabled="!selectedFile || uploading">
{{ uploading ? '上传中...' : '上传' }}
</button>
<div v-if="shareCode">分享码: {{ shareCode }}</div>
<div v-if="error" class="error">{{ error }}</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const selectedFile = ref<File | null>(null)
const uploading = ref(false)
const shareCode = ref('')
const error = ref('')
function handleFileSelect(e: Event) {
const input = e.target as HTMLInputElement
selectedFile.value = input.files?.[0] || null
}
async function upload() {
if (!selectedFile.value) return
uploading.value = true
error.value = ''
try {
const result = await uploadFile(selectedFile.value)
shareCode.value = result.code
} catch (e) {
error.value = e.message
} finally {
uploading.value = false
}
}
</script>
```
---
## 注意事项
1. **会话有效期**: 上传会话默认 15 分钟后过期,请在有效期内完成上传
2. **文件大小限制**: 受系统配置 `uploadSize` 限制
3. **过期类型**: 支持 `day`、`hour`、`minute`、`forever`、`count`
4. **CORS**: 直传模式下,S3 需要配置正确的 CORS 策略
5. **重试机制**: 建议实现上传失败重试逻辑
+75 -6
View File
@@ -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": "<admin-password-set-during-setup>"}'
```
**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
@@ -260,4 +329,4 @@ When an error occurs, the API will return corresponding error message:
- 403: Forbidden
- 404: Not Found
- 422: Validation Error
- 500: Internal Server Error
- 500: Internal Server Error
+207
View File
@@ -0,0 +1,207 @@
# Configuration Guide
FileCodeBox provides rich configuration options that can be customized through the admin panel or by directly modifying the configuration. This document details all available configuration options.
## Configuration Methods
FileCodeBox supports two configuration methods:
1. **Admin Panel Configuration** (Recommended): Access `/admin` to enter the admin panel and modify settings on the settings page
2. **Database Configuration**: Configuration is stored in the `data/filecodebox.db` database
::: tip Note
On first startup, the system uses default configuration from `core/settings.py`. Modified configurations are saved to the database.
:::
## Basic Settings
### Site Information
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `name` | string | `文件快递柜 - FileCodeBox` | Site name, displayed in page title and navigation bar |
| `description` | string | `开箱即用的文件快传系统` | Site description, used for SEO |
| `keywords` | string | `FileCodeBox, 文件快递柜...` | Site keywords, used for SEO |
| `port` | int | `12345` | Service listening port |
### Notification Settings
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `notify_title` | string | `系统通知` | Notification title |
| `notify_content` | string | Welcome message | Notification content, supports HTML |
| `page_explain` | string | Legal disclaimer | Footer explanation text |
| `robotsText` | string | `User-agent: *\nDisallow: /` | robots.txt content |
## Upload Settings
### File Upload Limits
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `openUpload` | int | `1` | Enable upload functionality (1=enabled, 0=disabled) |
| `uploadSize` | int | `10485760` | Maximum single file upload size (bytes), default 10MB |
| `enableChunk` | int | `0` | Enable chunked upload (1=enabled, 0=disabled) |
::: warning Note
`uploadSize` is in bytes. 10MB = 10 * 1024 * 1024 = 10485760 bytes
:::
### Upload Rate Limiting
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `uploadMinute` | int | `1` | Upload limit time window (minutes) |
| `uploadCount` | int | `10` | Maximum uploads allowed within the time window |
Example: Default configuration allows up to 10 uploads per minute.
### File Expiration Settings
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `expireStyle` | list | `["day","hour","minute","forever","count"]` | Available expiration methods |
| `max_save_seconds` | int | `0` | Maximum file retention time (seconds), 0 means no limit |
Expiration methods explained:
- `day` - Expire by days
- `hour` - Expire by hours
- `minute` - Expire by minutes
- `forever` - Never expire
- `count` - Expire by download count
## Theme Settings
### Theme Selection
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `themesSelect` | string | `themes/2024` | Currently active theme |
| `themesChoices` | list | See below | Available themes list |
Default available themes:
```json
[
{
"name": "2023",
"key": "themes/2023",
"author": "Lan",
"version": "1.0"
},
{
"name": "2024",
"key": "themes/2024",
"author": "Lan",
"version": "1.0"
}
]
```
### Interface Style
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `opacity` | float | `0.9` | Interface opacity (0-1) |
| `background` | string | `""` | Custom background image URL, empty uses default background |
## Admin Settings
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `admin_token` | string | Set during setup | Admin login password |
| `showAdminAddr` | int | `0` | Show admin panel entry on homepage (1=show, 0=hide) |
::: danger Security Warning
The setup page is shown automatically while the system is uninitialized. Complete setup before exposing a production service to the public internet.
:::
## Security Settings
### Error Rate Limiting
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `errorMinute` | int | `1` | Error limit time window (minutes) |
| `errorCount` | int | `1` | Maximum errors allowed within the time window |
This setting prevents brute-force attacks on extraction codes.
## Storage Settings
### Storage Type
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `file_storage` | string | `local` | Storage backend type |
| `storage_path` | string | `""` | Custom storage path |
Supported storage types:
- `local` - Local storage
- `s3` - S3-compatible storage (AWS S3, Aliyun OSS, MinIO, etc.)
- `onedrive` - OneDrive storage
- `webdav` - WebDAV storage
- `opendal` - OpenDAL storage
For detailed storage configuration, see [Storage Configuration](/en/guide/storage).
## Configuration Examples
### Example 1: Small Personal Use
Suitable for personal or small team use with relaxed limits:
```python
{
"name": "My File Share",
"uploadSize": 52428800, # 50MB
"uploadMinute": 5, # 5 minutes
"uploadCount": 20, # Max 20 uploads
"expireStyle": ["day", "hour", "forever"],
"admin_token": "your-secure-password",
"showAdminAddr": 1
}
```
### Example 2: Public Service
Suitable for public services requiring stricter limits:
```python
{
"name": "Public File Box",
"uploadSize": 10485760, # 10MB
"uploadMinute": 1, # 1 minute
"uploadCount": 5, # Max 5 uploads
"errorMinute": 5, # 5 minutes
"errorCount": 3, # Max 3 errors
"expireStyle": ["hour", "minute", "count"],
"max_save_seconds": 86400, # Max retention 1 day
"admin_token": "very-secure-password-123",
"showAdminAddr": 0
}
```
### Example 3: Enterprise Internal Use
Suitable for enterprise internal use with large file and chunked upload support:
```python
{
"name": "Enterprise File Transfer",
"uploadSize": 1073741824, # 1GB
"enableChunk": 1, # Enable chunked upload
"uploadMinute": 10, # 10 minutes
"uploadCount": 100, # Max 100 uploads
"expireStyle": ["day", "forever"],
"file_storage": "s3", # Use S3 storage
"admin_token": "enterprise-secure-token",
"showAdminAddr": 1
}
```
## Next Steps
- [Storage Configuration](/en/guide/storage) - Learn how to configure different storage backends
- [Security Settings](/en/guide/security) - Learn how to enhance system security
- [File Sharing](/en/guide/share) - Learn about file sharing features
+3 -2
View File
@@ -55,8 +55,9 @@ python main.py
- Download file
4. Admin Panel
- Open `http://localhost:12345` on first run and complete setup
- Visit `http://localhost:12345/#/admin`
- Enter admin password: `FileCodeBox2023`
- Enter the admin password set during setup
- Enter admin panel
- View system information, file list, user management, etc.
@@ -64,4 +65,4 @@ python main.py
- [Storage Configuration](/en/guide/storage) - Learn how to configure different storage methods
- [Security Settings](/en/guide/security) - Learn how to enhance system security
- [API Documentation](/en/api/) - Learn how to integrate through API
- [API Documentation](/en/api/) - Learn how to integrate through API
+414
View File
@@ -0,0 +1,414 @@
# Admin Panel
FileCodeBox provides a fully-featured admin panel that allows administrators to conveniently manage files, view system status, and modify configurations. This document introduces the various features and usage of the admin panel.
## Accessing the Admin Panel
### Login Method
The admin panel is located at the `/admin` path. Access method:
1. On first run, set the admin password on the setup page
2. Visit `http://your-domain.com/admin` in your browser
3. Enter the admin password (the value of the `admin_token` configuration)
4. Click the login button
::: tip Tip
The setup page is shown automatically while the system is uninitialized. Complete setup before exposing a production service to the public internet.
:::
### Show Admin Entry
By default, the admin panel entry is not shown on the homepage. You can control whether to show it via configuration:
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `showAdminAddr` | int | `0` | Show admin entry on homepage (1=show, 0=hide) |
::: warning Security Recommendation
For public services, it's recommended to keep `showAdminAddr` at `0` and access the admin panel directly via the `/admin` path to reduce the risk of malicious scanning.
:::
### Authentication Mechanism
The admin panel uses JWT (JSON Web Token) for authentication:
1. After successful login, the server returns a Token containing admin identity
2. Subsequent requests carry the Token via `Authorization: Bearer <token>` header
3. Token is used to verify admin identity, ensuring only authorized users can access admin functions
## Dashboard
After logging in, you first see the dashboard page, which displays the overall system status.
### Statistics
The dashboard displays the following key metrics:
| Metric | Description |
|--------|-------------|
| **Total Files** (`totalFiles`) | Total number of files stored in the system |
| **Storage Used** (`storageUsed`) | Total storage space occupied by all files (bytes) |
| **System Uptime** (`sysUptime`) | Time when the system was first started |
| **Yesterday's Uploads** (`yesterdayCount`) | Number of files uploaded yesterday |
| **Yesterday's Upload Size** (`yesterdaySize`) | Total size of files uploaded yesterday (bytes) |
| **Today's Uploads** (`todayCount`) | Number of files uploaded today so far |
| **Today's Upload Size** (`todaySize`) | Total size of files uploaded today (bytes) |
### Metric Notes
- **Total Files**: Includes all unexpired files and text shares
- **Storage Used**: Shows actual storage space occupied by files, excluding database and other system files
- **Yesterday/Today Statistics**: Calculated based on file creation time, useful for understanding system usage trends
::: tip Tip
Storage usage is displayed in bytes. For example, `10485760` represents approximately 10MB.
:::
## File Management
### File List
The file management page displays all shared files in the system, supporting pagination and search.
**List information includes:**
- File ID
- Extraction code (code)
- Filename prefix (prefix)
- File extension (suffix)
- File size
- Creation time
- Expiration time
- Remaining download count
### Search Files
Use the search function to quickly find specific files:
1. Enter keywords in the search box
2. System performs fuzzy matching based on filename prefix (prefix)
3. Search results update in real-time
**Search examples:**
- Enter `report` to find all files with "report" in the filename
- Enter `.pdf` to find all PDF files (if the filename contains this string)
### Pagination
The file list supports paginated display:
| Parameter | Default | Description |
|-----------|---------|-------------|
| `page` | `1` | Current page number |
| `size` | `10` | Items per page |
### Delete Files
Administrators can delete any file:
1. Find the file to delete in the file list
2. Click the delete button
3. Confirm the delete operation
::: danger Warning
Delete operations are irreversible! Files will be permanently deleted from the storage backend, and database records will also be removed.
:::
**Delete process:**
1. System first deletes the actual file from the storage backend (local/S3/OneDrive, etc.)
2. Then deletes the file record from the database
3. After deletion, the corresponding extraction code becomes invalid
### Download Files
Administrators can directly download any file:
1. Find the target file in the file list
2. Click the download button
3. File will be downloaded via browser
For text shares, the system returns text content directly instead of downloading a file.
### Modify File Information
Administrators can modify some information of shared files:
| Modifiable Field | Description |
|------------------|-------------|
| `code` | Extraction code (must be unique, cannot duplicate other files) |
| `prefix` | Filename prefix |
| `suffix` | File extension |
| `expired_at` | Expiration time |
| `expired_count` | Remaining download count |
**Modify extraction code:**
```
Original code: abc123
New code: myfile2024
```
::: warning Note
When modifying extraction codes, the system checks if the new code is already in use. If an identical extraction code exists, the modification will fail.
:::
## Local File Management
In addition to managing shared files, the admin panel also provides local file management functionality for managing files in the `data/local` directory.
### View Local Files
The local file list displays all files in the `data/local` directory:
| Information | Description |
|-------------|-------------|
| Filename | Complete filename |
| Creation Time | File creation time |
| File Size | File size (bytes) |
### Share Local Files
You can quickly share local files:
1. Select the file to share in the local file list
2. Set expiration method and value
3. Click the share button
4. System generates extraction code
**Share parameters:**
| Parameter | Description |
|-----------|-------------|
| `filename` | Filename to share |
| `expire_style` | Expiration method (day/hour/minute/forever/count) |
| `expire_value` | Expiration value (days/hours/minutes/download count) |
### Delete Local Files
You can delete files in the `data/local` directory:
1. Find the file to delete in the local file list
2. Click the delete button
3. Confirm deletion
::: tip Use Cases
Local file management is useful for:
- Sharing files after batch uploading to the server
- Managing files uploaded to the server through other means
- Cleaning up unnecessary local files
:::
## System Settings
### View Configuration
On the system settings page, you can view the current values of all configuration items. Configuration items are grouped by category:
- Basic settings (site name, description, etc.)
- Upload settings (file size limits, rate limits, etc.)
- Storage settings (storage type, path, etc.)
- Theme settings (theme selection, opacity, etc.)
- Security settings (admin password, error limits, etc.)
### Modify Configuration
Administrators can modify most configurations through the admin panel:
1. Go to the system settings page
2. Find the configuration item to modify
3. Enter the new value
4. Click the save button
**Modifiable configuration items:**
| Category | Example Settings |
|----------|------------------|
| Basic Settings | `name`, `description`, `keywords`, `notify_title`, `notify_content` |
| Upload Settings | `uploadSize`, `uploadMinute`, `uploadCount`, `openUpload`, `enableChunk` |
| Expiration Settings | `expireStyle`, `max_save_seconds` |
| Theme Settings | `themesSelect`, `opacity`, `background` |
| Security Settings | `admin_token`, `showAdminAddr`, `errorMinute`, `errorCount` |
| Storage Settings | `file_storage`, `storage_path` and storage backend-specific configurations |
::: warning Note
- `admin_token` (admin password) cannot be set to empty
- `themesChoices` (theme list) cannot be modified through the admin panel
- After modifying storage settings, existing files will not be automatically migrated
:::
### Configuration Effect
Configuration changes take effect immediately without restarting the service. Configurations are saved in the database and persist after restart.
**Configuration storage location:**
- Database: `data/filecodebox.db`
- Table name: `keyvalue`
- Key name: `settings`
## API Endpoints
All admin panel functions are implemented through REST APIs. Here are the main endpoints:
### Authentication Endpoint
**Login**
```
POST /admin/login
Content-Type: application/json
{
"password": "your-admin-password"
}
```
Response:
```json
{
"code": 200,
"detail": {
"token": "eyJhbGciOiJIUzI1NiIs...",
"token_type": "Bearer"
}
}
```
### Dashboard Endpoint
**Get Statistics**
```
GET /admin/dashboard
Authorization: Bearer <token>
```
### File Management Endpoints
**Get File List**
```
GET /admin/file/list?page=1&size=10&keyword=
Authorization: Bearer <token>
```
**Delete File**
```
DELETE /admin/file/delete
Authorization: Bearer <token>
Content-Type: application/json
{
"id": 123
}
```
**Download File**
```
GET /admin/file/download?id=123
Authorization: Bearer <token>
```
**Modify File Information**
```
PATCH /admin/file/update
Authorization: Bearer <token>
Content-Type: application/json
{
"id": 123,
"code": "newcode",
"expired_at": "2024-12-31T23:59:59"
}
```
### Local File Endpoints
**Get Local File List**
```
GET /admin/local/lists
Authorization: Bearer <token>
```
**Delete Local File**
```
DELETE /admin/local/delete
Authorization: Bearer <token>
Content-Type: application/json
{
"filename": "example.txt"
}
```
**Share Local File**
```
POST /admin/local/share
Authorization: Bearer <token>
Content-Type: application/json
{
"filename": "example.txt",
"expire_style": "day",
"expire_value": 7
}
```
### Configuration Endpoints
**Get Configuration**
```
GET /admin/config/get
Authorization: Bearer <token>
```
**Update Configuration**
```
PATCH /admin/config/update
Authorization: Bearer <token>
Content-Type: application/json
{
"admin_token": "new-password",
"uploadSize": 52428800
}
```
## Common Issues
### Forgot Admin Password
If you forgot the admin password, you can reset it through the following methods:
1. Stop the FileCodeBox service
2. Open `data/filecodebox.db` using an SQLite tool
3. Query the record with `key='settings'` in the `keyvalue` table
4. Modify the `admin_token` value in the JSON
5. Restart the service
```sql
-- View current configuration
SELECT * FROM keyvalue WHERE key = 'settings';
-- Or delete configuration to restore default password
DELETE FROM keyvalue WHERE key = 'settings';
```
### File Deletion Failed
If an error occurs when deleting files, possible reasons:
1. **Storage backend connection failed**: Check if storage configuration is correct
2. **File no longer exists**: File may have been manually deleted
3. **Insufficient permissions**: Check write permissions for storage directory
### Configuration Changes Not Taking Effect
If configuration changes don't take effect:
1. Check if you clicked the save button
2. Refresh the page to see if configuration was saved
3. Check browser console for error messages
4. Confirm configuration value format is correct (e.g., don't enter strings for numeric types)
## Next Steps
- [Configuration Guide](/en/guide/configuration) - Learn detailed descriptions of all configuration options
- [Security Settings](/en/guide/security) - Learn how to enhance system security
- [Storage Configuration](/en/guide/storage) - Configure different storage backends
+325
View File
@@ -0,0 +1,325 @@
# Security Settings
FileCodeBox provides multiple layers of security mechanisms to protect your file sharing service. This document explains how to properly configure security options to ensure secure system operation.
## Admin Password
### First-Run Setup
::: danger Important Security Warning
FileCodeBox does not ship with a default admin password. Open the site in your browser on first run and set the admin password on the setup page.
:::
There are two ways to change the admin password:
**Method 1: Via Admin Panel (Recommended)**
1. Access `/admin` to enter the admin panel
2. Log in with the current password
3. Go to the "System Settings" page
4. Find the `admin_token` configuration item
5. Enter a new secure password and save
**Method 2: Via Database**
Configuration is stored in the `keyvalue` table of the `data/filecodebox.db` database. You can directly modify the `admin_token` value.
### Password Security Recommendations
- Use a strong password with at least 16 characters
- Include uppercase and lowercase letters, numbers, and special characters
- Avoid common words or personal information
- Change password regularly
```python
# Recommended password format example
"admin_token": "Xk9#mP2$vL5@nQ8&wR3"
```
### Hide Admin Entry
By default, the admin panel entry is hidden. You can control whether to show the admin entry on the homepage via the `showAdminAddr` configuration:
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `showAdminAddr` | int | `0` | Show admin entry (1=show, 0=hide) |
::: tip Recommendation
For public services, it's recommended to keep `showAdminAddr` at `0` and access the admin panel directly via the `/admin` path.
:::
## IP Rate Limiting
FileCodeBox has built-in IP-based rate limiting mechanisms to effectively prevent abuse and attacks.
### Upload Rate Limiting
Limit the number of uploads from a single IP within a specified time:
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `uploadMinute` | int | `1` | Upload limit time window (minutes) |
| `uploadCount` | int | `10` | Maximum uploads allowed within the time window |
**How it works:**
- System records upload requests from each IP
- When an IP's upload count reaches `uploadCount` within `uploadMinute` minutes
- Subsequent upload requests from that IP will be rejected with HTTP 423 error
- Counter resets after the time window expires
**Configuration examples:**
```python
# Relaxed configuration: Max 20 uploads in 5 minutes
{
"uploadMinute": 5,
"uploadCount": 20
}
# Strict configuration: Max 3 uploads in 1 minute
{
"uploadMinute": 1,
"uploadCount": 3
}
```
### Error Rate Limiting
Limit the number of error attempts from a single IP to prevent brute-force attacks on extraction codes:
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `errorMinute` | int | `1` | Error limit time window (minutes) |
| `errorCount` | int | `1` | Maximum errors allowed within the time window |
**How it works:**
- When a user enters an incorrect extraction code, the system records the error count for that IP
- When error count reaches `errorCount`, that IP will be temporarily locked
- Lock duration is `errorMinute` minutes
- During lockout, all extraction requests from that IP will be rejected
**Configuration example:**
```python
# Anti-brute-force configuration: Max 3 errors in 5 minutes
{
"errorMinute": 5,
"errorCount": 3
}
```
::: warning Note
The default configuration `errorMinute=1, errorCount=1` is very strict, meaning you need to wait 1 minute after entering one incorrect extraction code before retrying. Adjust this configuration based on actual needs.
:::
## Upload Restrictions
### File Size Limit
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `uploadSize` | int | `10485760` | Maximum single file upload size (bytes), default 10MB |
| `openUpload` | int | `1` | Enable upload functionality (1=enabled, 0=disabled) |
**Common size conversions:**
- 10MB = 10 * 1024 * 1024 = `10485760`
- 50MB = 50 * 1024 * 1024 = `52428800`
- 100MB = 100 * 1024 * 1024 = `104857600`
- 1GB = 1024 * 1024 * 1024 = `1073741824`
### File Expiration Settings
Through file expiration mechanisms, you can automatically clean up expired files, reducing storage usage and security risks:
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `expireStyle` | list | `["day","hour","minute","forever","count"]` | Available expiration methods |
| `max_save_seconds` | int | `0` | Maximum file retention time (seconds), 0 means no limit |
**Expiration methods explained:**
- `day` - Expire by days
- `hour` - Expire by hours
- `minute` - Expire by minutes
- `forever` - Never expire (requires alphanumeric extraction code)
- `count` - Expire by download count
**Security recommendations:**
For public services, it's recommended to:
1. Remove the `forever` option to avoid permanent file storage
2. Set `max_save_seconds` to limit maximum retention time
3. Prefer using `count` method for automatic deletion after download
```python
# Recommended configuration for public services
{
"expireStyle": ["hour", "minute", "count"],
"max_save_seconds": 86400 # Max retention 1 day
}
```
### Disable Upload Functionality
In some cases, you may need to temporarily disable upload functionality:
```python
{
"openUpload": 0 # Disable upload functionality
}
```
## Reverse Proxy Security Configuration
In production environments, Nginx or other reverse proxy servers are typically used. Here are security configuration recommendations:
### Nginx Configuration Example
```nginx
server {
listen 80;
server_name your-domain.com;
# Force HTTPS redirect
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name your-domain.com;
# SSL certificate configuration
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers on;
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# Limit request body size (match uploadSize configuration)
client_max_body_size 100M;
# Pass real IP
location / {
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;
}
# Static resource caching
location /assets {
proxy_pass http://127.0.0.1:12345;
proxy_cache_valid 200 7d;
add_header Cache-Control "public, max-age=604800";
}
}
```
### Key Security Configuration Notes
**1. Pass Real IP**
FileCodeBox's IP limiting functionality depends on obtaining the client's real IP. The system obtains IP in the following order:
1. `X-Real-IP` request header
2. `X-Forwarded-For` request header
3. Direct client connection IP
Ensure the reverse proxy correctly sets these headers:
```nginx
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
```
**2. Request Body Size Limit**
Nginx's `client_max_body_size` should match or be slightly larger than FileCodeBox's `uploadSize` configuration:
```nginx
client_max_body_size 100M; # Allow max 100MB uploads
```
**3. HTTPS Encryption**
It's strongly recommended to enable HTTPS in production environments:
- Protect uploaded file content
- Protect admin login credentials
- Prevent man-in-the-middle attacks
### Caddy Configuration Example
```nginx
your-domain.com {
reverse_proxy localhost:12345
header {
X-Frame-Options "SAMEORIGIN"
X-Content-Type-Options "nosniff"
X-XSS-Protection "1; mode=block"
Strict-Transport-Security "max-age=31536000; includeSubDomains"
}
}
```
## Security Checklist
Before deploying FileCodeBox, confirm the following security configurations:
- [ ] Completed first-run setup and set the admin password `admin_token`
- [ ] Hidden admin entry `showAdminAddr: 0`
- [ ] Configured appropriate upload rate limiting
- [ ] Configured error rate limiting to prevent brute-force attacks
- [ ] Set reasonable file size limits
- [ ] Configured file expiration policy
- [ ] Enabled HTTPS encryption
- [ ] Reverse proxy correctly passes real IP
- [ ] Set security response headers
## Recommended Security Configurations
### Public Service Configuration
```python
{
"admin_token": "your-very-secure-password",
"showAdminAddr": 0,
"uploadSize": 10485760, # 10MB
"uploadMinute": 1,
"uploadCount": 5,
"errorMinute": 5,
"errorCount": 3,
"expireStyle": ["hour", "minute", "count"],
"max_save_seconds": 86400, # Max 1 day
"openUpload": 1
}
```
### Internal Service Configuration
```python
{
"admin_token": "internal-secure-password",
"showAdminAddr": 1,
"uploadSize": 104857600, # 100MB
"uploadMinute": 5,
"uploadCount": 50,
"errorMinute": 1,
"errorCount": 5,
"expireStyle": ["day", "hour", "forever"],
"max_save_seconds": 0, # No limit
"openUpload": 1
}
```
## Next Steps
- [Configuration Guide](/en/guide/configuration) - Learn about all configuration options
- [Storage Configuration](/en/guide/storage) - Configure secure storage backends
- [File Sharing](/en/guide/share) - Learn about file sharing features
+342
View File
@@ -0,0 +1,342 @@
# File Sharing
FileCodeBox provides simple and easy-to-use file and text sharing functionality. Users can securely share and retrieve files using extraction codes.
## Sharing Methods
FileCodeBox supports two sharing methods:
1. **Text Sharing** - Share text content directly, suitable for code snippets, configuration files, etc.
2. **File Sharing** - Upload files for sharing, supports various file formats
## Text Sharing
### How to Use
1. Select the "Text Share" tab on the homepage
2. Enter or paste the content to share in the text box
3. Select expiration method and time
4. Click the "Share" button
5. Get the extraction code
### Text Size Limit
::: warning Note
The maximum content size for text sharing is **222KB** (227,328 bytes). If content exceeds this limit, it's recommended to use file sharing instead.
:::
Text content size is calculated using UTF-8 encoding. Chinese characters typically occupy 3 bytes.
### API Endpoint
**POST** `/share/text/`
Request parameters:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `text` | string | Yes | Text content to share |
| `expire_value` | int | No | Expiration value, default 1 |
| `expire_style` | string | No | Expiration method, default `day` |
Response example:
```json
{
"code": 200,
"detail": {
"code": "123456"
}
}
```
## File Sharing
### How to Use
1. Select the "File Share" tab on the homepage
2. Click the upload area or drag files to the upload area
3. Select expiration method and time
4. Click the "Upload" button
5. Get the extraction code
### File Size Limit
The default maximum single file upload size is **10MB**. Administrators can modify this limit via the `uploadSize` configuration.
::: tip Tip
If you need to upload large files, contact the administrator to enable chunked upload functionality or adjust the `uploadSize` configuration.
:::
### Supported Upload Methods
- **Click Upload** - Click the upload area to select files
- **Drag Upload** - Drag files to the upload area
- **Paste Upload** - Paste images from clipboard (supported by some themes)
### API Endpoint
**POST** `/share/file/`
Request parameters (multipart/form-data):
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `file` | file | Yes | File to upload |
| `expire_value` | int | No | Expiration value, default 1 |
| `expire_style` | string | No | Expiration method, default `day` |
Response example:
```json
{
"code": 200,
"detail": {
"code": "654321",
"name": "example.pdf"
}
}
```
## Expiration Settings
FileCodeBox supports multiple flexible expiration methods:
| Expiration Method | Parameter Value | Description |
|-------------------|-----------------|-------------|
| By Days | `day` | File expires after specified days |
| By Hours | `hour` | File expires after specified hours |
| By Minutes | `minute` | File expires after specified minutes |
| Never Expire | `forever` | File is permanently valid |
| By Count | `count` | File expires after specified download count |
::: info Note
- Administrators can control available expiration methods via the `expireStyle` configuration
- Administrators can limit maximum file retention time via the `max_save_seconds` configuration
:::
### Expiration Method Examples
```bash
# File expires after 3 days
expire_value=3, expire_style=day
# File expires after 12 hours
expire_value=12, expire_style=hour
# File expires after 30 minutes
expire_value=30, expire_style=minute
# File never expires
expire_value=1, expire_style=forever
# File expires after 5 downloads
expire_value=5, expire_style=count
```
## Retrieving Files
### How to Use
1. Enter the extraction code in the "Retrieve File" area on the homepage
2. Click the "Retrieve" button
3. System displays file information (filename, size, etc.)
4. Click the "Download" button to download the file, or view text content directly
### Extraction Code Notes
- Extraction codes are typically **6-digit numbers**
- Files that never expire use **alphanumeric** extraction codes
- Extraction codes are case-sensitive (for alphanumeric codes)
### API Endpoints
**Query File Information**
**POST** `/share/select/`
Request parameters:
```json
{
"code": "123456"
}
```
Response example (file):
```json
{
"code": 200,
"detail": {
"code": "123456",
"name": "example.pdf",
"size": 1048576,
"text": "https://example.com/download/..."
}
}
```
Response example (text):
```json
{
"code": 200,
"detail": {
"code": "123456",
"name": "Text",
"size": 1024,
"text": "This is the shared text content..."
}
}
```
**Direct File Download**
**GET** `/share/select/?code=123456`
This endpoint returns file content directly, suitable for direct browser access.
## Chunked Upload (Large Files)
For large file uploads, FileCodeBox supports chunked upload functionality. This feature requires administrator enablement (`enableChunk=1`).
### Chunked Upload Flow
```mermaid
sequenceDiagram
participant C as Client
participant S as Server
C->>S: 1. Initialize upload (POST /chunk/upload/init/)
S-->>C: Return upload_id and chunk info
loop Each chunk
C->>S: 2. Upload chunk (POST /chunk/upload/chunk/{upload_id}/{chunk_index})
S-->>C: Return chunk hash
end
C->>S: 3. Complete upload (POST /chunk/upload/complete/{upload_id})
S-->>C: Return extraction code
```
### 1. Initialize Upload
**POST** `/chunk/upload/init/`
Request parameters:
```json
{
"file_name": "large_file.zip",
"file_size": 104857600,
"chunk_size": 5242880,
"file_hash": "sha256_hash_of_file"
}
```
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `file_name` | string | Yes | Filename |
| `file_size` | int | Yes | Total file size (bytes) |
| `chunk_size` | int | No | Chunk size, default 5MB |
| `file_hash` | string | Yes | SHA256 hash of the file |
Response example:
```json
{
"code": 200,
"detail": {
"existed": false,
"upload_id": "abc123def456",
"chunk_size": 5242880,
"total_chunks": 20,
"uploaded_chunks": []
}
}
```
### 2. Upload Chunk
**POST** `/chunk/upload/chunk/{upload_id}/{chunk_index}`
- `upload_id` - Upload session ID returned during initialization
- `chunk_index` - Chunk index, starting from 0
Request body: Chunk file data (multipart/form-data)
Response example:
```json
{
"code": 200,
"detail": {
"chunk_hash": "sha256_hash_of_chunk"
}
}
```
### 3. Complete Upload
**POST** `/chunk/upload/complete/{upload_id}`
Request parameters:
```json
{
"expire_value": 1,
"expire_style": "day"
}
```
Response example:
```json
{
"code": 200,
"detail": {
"code": "789012",
"name": "large_file.zip"
}
}
```
### Resume Upload
Chunked upload supports resume functionality. If upload is interrupted:
1. Call the initialization endpoint again with the same `file_hash`
2. Server returns `uploaded_chunks` list containing already uploaded chunk indices
3. Client only needs to upload chunks not in the list
## Error Handling
### Common Error Codes
| Error Code | Description | Solution |
|------------|-------------|----------|
| 403 | File size exceeds limit | Reduce file size or contact administrator to adjust limit |
| 403 | Content too large | Text exceeds 222KB, use file sharing instead |
| 403 | Upload rate limit | Wait a while before retrying |
| 404 | File not found | Check if extraction code is correct |
| 404 | File expired | File has expired or download count exhausted |
### Rate Limiting
To prevent abuse, the system has rate limits on upload and retrieval operations:
- **Upload limit**: Default max 10 uploads per minute
- **Error limit**: Default max 1 error attempt per minute
::: tip Tip
If you encounter rate limiting, wait for the limit time window to pass before retrying.
:::
## Next Steps
- [Configuration Guide](/en/guide/configuration) - Learn how to configure sharing-related settings
- [Storage Configuration](/en/guide/storage) - Learn about file storage methods
- [Security Settings](/en/guide/security) - Learn about security-related configurations
- [Admin Panel](/en/guide/management) - Learn how to manage shared files
+395
View File
@@ -0,0 +1,395 @@
# Storage Configuration
FileCodeBox supports multiple storage backends. You can choose the appropriate storage method based on your needs. This document details the configuration methods for various storage backends.
## Storage Types Overview
| Storage Type | Config Value | Description |
|--------------|--------------|-------------|
| Local Storage | `local` | Default storage method, files saved on local server |
| S3-Compatible Storage | `s3` | Supports AWS S3, Aliyun OSS, MinIO, etc. |
| OneDrive | `onedrive` | Microsoft OneDrive cloud storage (work/school accounts only) |
| WebDAV | `webdav` | Storage services supporting WebDAV protocol |
| OpenDAL | `opendal` | Integrate more storage services via OpenDAL |
## Local Storage
Local storage is the default storage method. Files are saved in the server's `data/` directory.
### Configuration Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `file_storage` | string | `local` | Storage type |
| `storage_path` | string | `""` | Custom storage path (optional) |
### Configuration Example
```bash
file_storage=local
storage_path=
```
### Notes
- Files are stored by default in `data/share/data/` directory
- Subdirectories are automatically created by date: `year/month/day/fileID/`
- In production, it's recommended to mount the `data/` directory to persistent storage
## S3-Compatible Storage
Supports all S3-compatible object storage services, including AWS S3, Aliyun OSS, MinIO, Tencent Cloud COS, etc.
### Configuration Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `file_storage` | string | - | Set to `s3` |
| `s3_access_key_id` | string | `""` | Access Key ID |
| `s3_secret_access_key` | string | `""` | Secret Access Key |
| `s3_bucket_name` | string | `""` | Bucket name |
| `s3_endpoint_url` | string | `""` | S3 endpoint URL |
| `s3_region_name` | string | `auto` | Region name |
| `s3_signature_version` | string | `s3v2` | Signature version (`s3v2` or `s3v4`) |
| `s3_hostname` | string | `""` | S3 hostname (alternative) |
| `s3_proxy` | int | `0` | Download through server proxy (1=yes, 0=no) |
| `aws_session_token` | string | `""` | AWS session token (optional) |
### AWS S3 Configuration Example
```bash
file_storage=s3
s3_access_key_id=AKIAIOSFODNN7EXAMPLE
s3_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
s3_bucket_name=my-filecodebox-bucket
s3_endpoint_url=https://s3.amazonaws.com
s3_region_name=us-east-1
s3_signature_version=s3v4
```
### Aliyun OSS Configuration Example
```bash
file_storage=s3
s3_access_key_id=YourAccessKeyId
s3_secret_access_key=YourSecretAccessKey
s3_bucket_name=bucket-name
s3_endpoint_url=https://bucket-name.oss-cn-hangzhou.aliyuncs.com
s3_region_name=oss-cn-hangzhou
s3_signature_version=s3v4
```
::: tip Aliyun OSS Endpoint Format
Endpoint URL format: `https://<bucket-name>.<region>.aliyuncs.com`
Common regions:
- Hangzhou: `oss-cn-hangzhou`
- Shanghai: `oss-cn-shanghai`
- Beijing: `oss-cn-beijing`
- Shenzhen: `oss-cn-shenzhen`
:::
### MinIO Configuration Example
```bash
file_storage=s3
s3_access_key_id=minioadmin
s3_secret_access_key=minioadmin
s3_bucket_name=filecodebox
s3_endpoint_url=http://localhost:9000
s3_region_name=us-east-1
s3_signature_version=s3v4
```
::: warning MinIO Notes
- `s3_endpoint_url` should be the MinIO API interface address
- `s3_region_name` should match the `Server Location` in MinIO configuration
- Ensure the bucket is created and has correct access permissions
:::
### Tencent Cloud COS Configuration Example
```bash
file_storage=s3
s3_access_key_id=YourSecretId
s3_secret_access_key=YourSecretKey
s3_bucket_name=bucket-name-1250000000
s3_endpoint_url=https://cos.ap-guangzhou.myqcloud.com
s3_region_name=ap-guangzhou
s3_signature_version=s3v4
```
### Proxy Download
When `s3_proxy=1`, file downloads are proxied through the server instead of directly from S3. This is useful when:
- S3 bucket doesn't allow public access
- Need to hide the actual storage address
- Network environment restricts direct S3 access
## OneDrive Storage
OneDrive storage supports saving files to Microsoft OneDrive cloud storage.
::: warning Important Limitation
OneDrive storage **only supports work or school accounts** and requires admin permissions to authorize the API. Personal accounts cannot use this feature.
:::
### Configuration Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `file_storage` | string | - | Set to `onedrive` |
| `onedrive_domain` | string | `""` | Azure AD domain |
| `onedrive_client_id` | string | `""` | Application (client) ID |
| `onedrive_username` | string | `""` | Account email |
| `onedrive_password` | string | `""` | Account password |
| `onedrive_root_path` | string | `filebox_storage` | Storage root directory in OneDrive |
| `onedrive_proxy` | int | `0` | Download through server proxy |
### Configuration Example
```bash
file_storage=onedrive
onedrive_domain=contoso.onmicrosoft.com
onedrive_client_id=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
onedrive_username=user@contoso.onmicrosoft.com
onedrive_password=your_password
onedrive_root_path=filebox_storage
```
### Azure App Registration Steps
To use OneDrive storage, you need to register an application in the Azure portal:
#### 1. Get Domain
Log in to [Azure Portal](https://portal.azure.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade), hover over your account in the top right corner, and the **Domain** shown in the popup is the `onedrive_domain` value.
#### 2. Register Application
1. Click **+ New registration** in the top left
2. Enter application name (e.g., FileCodeBox)
3. **Supported account types**: Select "Accounts in any organizational directory (Any Azure AD directory - Multitenant) and personal Microsoft accounts"
4. **Redirect URI**: Select `Web`, enter `http://localhost`
5. Click **Register**
#### 3. Get Client ID
After registration, find the **Application (client) ID** in the **Essentials** section on the app overview page. This is the `onedrive_client_id` value.
#### 4. Configure Authentication
1. Select **Authentication** in the left menu
2. Find **Allow public client flows**, select **Yes**
3. Click **Save**
#### 5. Configure API Permissions
1. Select **API permissions** in the left menu
2. Click **+ Add a permission**
3. Select **Microsoft Graph** → **Delegated permissions**
4. Check the following permissions:
- `openid`
- `Files.Read`
- `Files.Read.All`
- `Files.ReadWrite`
- `Files.ReadWrite.All`
- `User.Read`
5. Click **Add permissions**
6. Click **Grant admin consent for xxx**
7. After confirmation, permission status should show **Granted**
### Install Dependencies
Using OneDrive storage requires additional Python dependencies:
```bash
pip install msal Office365-REST-Python-Client
```
### Verify Configuration
You can use the following code to test if the configuration is correct:
```python
import msal
from office365.graph_client import GraphClient
domain = 'your_domain'
client_id = 'your_client_id'
username = 'your_username'
password = 'your_password'
def acquire_token_pwd():
authority_url = f'https://login.microsoftonline.com/{domain}'
app = msal.PublicClientApplication(
authority=authority_url,
client_id=client_id
)
result = app.acquire_token_by_username_password(
username=username,
password=password,
scopes=['https://graph.microsoft.com/.default']
)
return result
# Test connection
client = GraphClient(acquire_token_pwd)
me = client.me.get().execute_query()
print(f"Login successful: {me.user_principal_name}")
```
## WebDAV Storage
WebDAV storage supports saving files to any service that supports the WebDAV protocol, such as Nextcloud, ownCloud, Nutstore, etc.
### Configuration Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `file_storage` | string | - | Set to `webdav` |
| `webdav_url` | string | `""` | WebDAV server URL |
| `webdav_username` | string | `""` | WebDAV username |
| `webdav_password` | string | `""` | WebDAV password |
| `webdav_root_path` | string | `filebox_storage` | Storage root directory in WebDAV |
| `webdav_proxy` | int | `0` | Download through server proxy |
### Configuration Example
```bash
file_storage=webdav
webdav_url=https://dav.example.com/remote.php/dav/files/username/
webdav_username=your_username
webdav_password=your_password
webdav_root_path=filebox_storage
```
### Nextcloud Configuration Example
```bash
file_storage=webdav
webdav_url=https://your-nextcloud.com/remote.php/dav/files/username/
webdav_username=your_username
webdav_password=your_app_password
webdav_root_path=FileCodeBox
```
::: tip Nextcloud App Password
It's recommended to create an app password in Nextcloud instead of using your main password:
1. Log in to Nextcloud
2. Go to **Settings** → **Security**
3. Create a new app password in **Devices & sessions**
:::
### Nutstore Configuration Example
```bash
file_storage=webdav
webdav_url=https://dav.jianguoyun.com/dav/
webdav_username=your_email@example.com
webdav_password=your_app_password
webdav_root_path=FileCodeBox
```
::: tip Nutstore App Password
Nutstore requires an app password:
1. Log in to Nutstore web version
2. Go to **Account Info** → **Security Options**
3. Add an app password
:::
## OpenDAL Storage
OpenDAL is a unified data access layer that supports multiple storage services. Through OpenDAL, you can use Google Cloud Storage, Azure Blob Storage, and more.
### Configuration Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `file_storage` | string | Set to `opendal` |
| `opendal_scheme` | string | Storage service type (e.g., `gcs`, `azblob`) |
| `opendal_<scheme>_<setting>` | string | Service-specific configuration parameters |
### Install Dependencies
```bash
pip install opendal
```
### Google Cloud Storage Configuration Example
```bash
file_storage=opendal
opendal_scheme=gcs
opendal_gcs_root=/filecodebox
opendal_gcs_bucket=your-bucket-name
opendal_gcs_credential=base64_encoded_credential
```
### Azure Blob Storage Configuration Example
```bash
file_storage=opendal
opendal_scheme=azblob
opendal_azblob_root=/filecodebox
opendal_azblob_container=your-container
opendal_azblob_account_name=your_account
opendal_azblob_account_key=your_key
```
### Supported Services
OpenDAL supports numerous storage services. For the complete list, see the [OpenDAL Official Documentation](https://opendal.apache.org/docs/rust/opendal/services/index.html).
Common services include:
- `gcs` - Google Cloud Storage
- `azblob` - Azure Blob Storage
- `obs` - Huawei Cloud OBS
- `oss` - Aliyun OSS (via OpenDAL)
- `cos` - Tencent Cloud COS (via OpenDAL)
- `hdfs` - Hadoop HDFS
- `ftp` - FTP server
- `sftp` - SFTP server
::: warning OpenDAL Notes
1. Services integrated via OpenDAL download through server proxy, consuming both storage service and server bandwidth
2. Compared to native S3/OneDrive support, OpenDAL may lack some debugging information
3. OpenDAL is written in Rust with good performance
:::
## Storage Selection Recommendations
| Scenario | Recommended Storage | Reason |
|----------|---------------------|--------|
| Personal/Small deployment | Local storage | Simple and easy, no extra configuration needed |
| Enterprise intranet | MinIO + S3 | Self-hosted object storage, data control |
| Public cloud deployment | Corresponding cloud provider S3 | Fast same-region access, low cost |
| Existing OneDrive | OneDrive | Utilize existing resources |
| Existing WebDAV | WebDAV | Good compatibility |
| Special storage needs | OpenDAL | Supports more storage services |
## Common Issues
### S3 Upload Failure
1. Check if Access Key and Secret Key are correct
2. Confirm bucket name and region configuration are correct
3. Check bucket access permission settings
4. Confirm signature version (`s3v2` or `s3v4`) matches service provider requirements
### OneDrive Authentication Failure
1. Confirm using a work/school account, not a personal account
2. Check if Azure app has been granted admin consent
3. Confirm API permissions are fully configured
4. Verify username and password are correct
### WebDAV Connection Failure
1. Check if WebDAV URL format is correct
2. Confirm username and password (or app password) are correct
3. Check if server supports WebDAV protocol
4. Confirm network connection is normal
View File
Whitespace-only changes.
+421
View File
@@ -0,0 +1,421 @@
# File Upload
FileCodeBox provides multiple flexible file upload methods, supporting both regular upload and chunked upload to meet different scenario requirements.
## Upload Methods
FileCodeBox supports the following upload methods:
### Drag and Drop Upload
Drag files directly to the upload area to start uploading. This is the most convenient upload method.
1. Open the FileCodeBox homepage
2. Drag files from your file manager to the upload area
3. Release the mouse, file upload begins
4. Get the extraction code after upload completes
::: tip Tip
Drag and drop upload supports dragging multiple files simultaneously (depending on theme support).
:::
### Click Upload
Click the upload area to select files through the system file picker.
1. Click the "Select File" button in the upload area
2. Select the file to upload in the popup file picker
3. File upload begins after confirming selection
4. Get the extraction code after upload completes
### Paste Upload
Supports pasting images directly from clipboard for upload (supported by some themes).
1. Copy an image to clipboard (screenshot or copy image)
2. Use `Ctrl+V` (Windows/Linux) or `Cmd+V` (macOS) to paste in the upload area
3. Image upload starts automatically
4. Get the extraction code after upload completes
::: warning Note
Paste upload only supports image formats, not other file types. Specific support depends on the theme being used.
:::
## File Size Limits
### Default Limits
| Setting | Default | Description |
|---------|---------|-------------|
| `uploadSize` | 10MB | Maximum single file upload size |
### Modify Upload Limits
Administrators can modify upload size limits through the admin panel or configuration file:
```python
# Set maximum upload size to 100MB
uploadSize = 104857600 # 100 * 1024 * 1024
```
::: info Note
`uploadSize` is in bytes. Common conversions:
- 10MB = 10485760
- 50MB = 52428800
- 100MB = 104857600
- 500MB = 524288000
- 1GB = 1073741824
:::
### Exceeding Limit Handling
When an uploaded file exceeds the size limit, the system returns a 403 error:
```json
{
"detail": "Size exceeds limit, maximum is 10.00 MB"
}
```
## Regular Upload API
### File Upload Endpoint
**POST** `/share/file/`
Content-Type: `multipart/form-data`
**Request parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `file` | file | Yes | File to upload |
| `expire_value` | int | No | Expiration value, default 1 |
| `expire_style` | string | No | Expiration method, default `day` |
**Expiration method options:**
| Value | Description |
|-------|-------------|
| `day` | Expire by days |
| `hour` | Expire by hours |
| `minute` | Expire by minutes |
| `forever` | Never expire |
| `count` | Expire by download count |
**Response example:**
```json
{
"code": 200,
"detail": {
"code": "654321",
"name": "example.pdf"
}
}
```
**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": "<admin-password-set-during-setup>"}'
# 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
For large files, FileCodeBox supports chunked upload functionality. Chunked upload splits large files into multiple small chunks for separate uploading, supporting resume capability.
::: warning Prerequisite
Chunked upload functionality requires administrator enablement: `enableChunk=1`
:::
### Chunked Upload Flow
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Initialize │ ──▶ │Upload Chunks│ ──▶ │ Complete │
│ /init/ │ │ /chunk/ │ │ /complete/ │
└─────────────┘ └─────────────┘ └─────────────┘
│
▼
┌───────────┐
│ Loop │
│each chunk │
└───────────┘
```
### 1. Initialize Upload
**POST** `/chunk/upload/init/`
**Request parameters:**
```json
{
"file_name": "large_file.zip",
"file_size": 104857600,
"chunk_size": 5242880,
"file_hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
```
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `file_name` | string | Yes | - | Filename |
| `file_size` | int | Yes | - | Total file size (bytes) |
| `chunk_size` | int | No | 5MB | Chunk size (bytes) |
| `file_hash` | string | Yes | - | SHA256 hash of the file |
**Response example:**
```json
{
"code": 200,
"detail": {
"existed": false,
"upload_id": "abc123def456789",
"chunk_size": 5242880,
"total_chunks": 20,
"uploaded_chunks": []
}
}
```
| Field | Description |
|-------|-------------|
| `existed` | Whether file already exists (instant upload) |
| `upload_id` | Upload session ID |
| `chunk_size` | Chunk size |
| `total_chunks` | Total number of chunks |
| `uploaded_chunks` | List of already uploaded chunk indices |
### 2. Upload Chunk
**POST** `/chunk/upload/chunk/{upload_id}/{chunk_index}`
**Path parameters:**
| Parameter | Description |
|-----------|-------------|
| `upload_id` | Upload session ID returned during initialization |
| `chunk_index` | Chunk index, starting from 0 |
**Request body:**
Content-Type: `multipart/form-data`
| Parameter | Type | Description |
|-----------|------|-------------|
| `chunk` | file | Chunk data |
**Response example:**
```json
{
"code": 200,
"detail": {
"chunk_hash": "a1b2c3d4e5f6..."
}
}
```
**cURL example:**
```bash
# Upload first chunk (index 0)
curl -X POST "http://localhost:12345/chunk/upload/chunk/abc123def456789/0" \
-F "chunk=@/path/to/chunk_0"
```
### 3. Complete Upload
**POST** `/chunk/upload/complete/{upload_id}`
**Path parameters:**
| Parameter | Description |
|-----------|-------------|
| `upload_id` | Upload session ID |
**Request parameters:**
```json
{
"expire_value": 7,
"expire_style": "day"
}
```
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `expire_value` | int | Yes | Expiration value |
| `expire_style` | string | Yes | Expiration method |
**Response example:**
```json
{
"code": 200,
"detail": {
"code": "789012",
"name": "large_file.zip"
}
}
```
### Resume Upload
Chunked upload supports resume functionality. When upload is interrupted:
1. Call the initialization endpoint again with the same `file_hash`
2. Server returns `uploaded_chunks` list containing already uploaded chunk indices
3. Client only needs to upload chunks not in the list
4. Call the complete endpoint after all chunks are uploaded
**Example flow:**
```javascript
// 1. Initialize upload
const initResponse = await fetch('/chunk/upload/init/', {
method: 'POST',
body: JSON.stringify({
file_name: 'large_file.zip',
file_size: fileSize,
chunk_size: 5 * 1024 * 1024,
file_hash: fileHash
})
});
const { upload_id, uploaded_chunks, total_chunks } = await initResponse.json();
// 2. Upload incomplete chunks
for (let i = 0; i < total_chunks; i++) {
if (!uploaded_chunks.includes(i)) {
const chunk = file.slice(i * chunkSize, (i + 1) * chunkSize);
await fetch(`/chunk/upload/chunk/${upload_id}/${i}`, {
method: 'POST',
body: chunk
});
}
}
// 3. Complete upload
await fetch(`/chunk/upload/complete/${upload_id}`, {
method: 'POST',
body: JSON.stringify({
expire_value: 7,
expire_style: 'day'
})
});
```
## Error Handling
### Common Errors
| HTTP Status | Error Message | Cause | Solution |
|-------------|---------------|-------|----------|
| 403 | Size exceeds limit | File exceeds `uploadSize` limit | Reduce file size or contact administrator to adjust limit |
| 403 | Upload rate limit | Exceeded IP upload rate limit | Wait for limit time window before retrying |
| 400 | Invalid expiration type | `expire_style` value not in allowed list | Use a valid expiration method |
| 404 | Upload session not found | `upload_id` invalid or expired | Re-initialize upload |
| 400 | Invalid chunk index | `chunk_index` out of range | Check if chunk index is correct |
| 400 | Incomplete chunks | Chunk count insufficient when completing upload | Ensure all chunks are uploaded |
### Rate Limiting
The system has rate limits on upload operations to prevent abuse:
| Setting | Default | Description |
|---------|---------|-------------|
| `uploadMinute` | 1 | Limit time window (minutes) |
| `uploadCount` | 10 | Maximum uploads within time window |
When rate limit is exceeded, you need to wait for the time window to pass before continuing uploads.
### Error Response Format
```json
{
"detail": "Error message description"
}
```
## Upload Configuration
### Related Settings
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `openUpload` | int | 1 | Enable upload (1=enabled, 0=disabled) |
| `uploadSize` | int | 10485760 | Maximum upload size (bytes) |
| `enableChunk` | int | 0 | Enable chunked upload (1=enabled, 0=disabled) |
| `uploadMinute` | int | 1 | Upload rate limit time window (minutes) |
| `uploadCount` | int | 10 | Maximum uploads within time window |
| `expireStyle` | list | ["day","hour","minute","forever","count"] | Allowed expiration methods |
### Configuration Example
```python
# Allow 100MB file uploads, enable chunked upload
uploadSize = 104857600
enableChunk = 1
# Relax upload rate limit: max 50 uploads per 5 minutes
uploadMinute = 5
uploadCount = 50
# Only allow expiration by days and count
expireStyle = ["day", "count"]
```
## Next Steps
- [File Sharing](/en/guide/share) - Learn the complete sharing process
- [Configuration Guide](/en/guide/configuration) - Learn about all configuration options
- [Storage Configuration](/en/guide/storage) - Learn about file storage methods
- [Security Settings](/en/guide/security) - Learn about security-related configurations
+127
View File
@@ -0,0 +1,127 @@
# Showcase
Here are some excellent sites built with FileCodeBox. If you've deployed FileCodeBox, feel free to submit a PR to add your site here!
## Official Demo
<div class="showcase-grid">
<div class="showcase-item">
### 🌟 FileCodeBox Demo
- **URL**: [share.lanol.cn](https://share.lanol.cn)
- **Description**: Official demo site with the latest features
- **Highlights**: Stable, full-featured
</div>
</div>
## Community Sites
::: tip Submit Your Site
If you've built your own file sharing service using FileCodeBox, you can submit it through:
1. Submit a PR on [GitHub](https://github.com/vastsa/FileCodeBox) to edit this page
2. Open an [Issue](https://github.com/vastsa/FileCodeBox/issues) with your site info
3. Join QQ Group 739673698 to contact the admin
:::
<!--
Submission format example:
<div class="showcase-item">
### Site Name
- **URL**: [example.com](https://example.com)
- **Description**: Brief description of your site
- **Highlights**: List your site's features
</div>
-->
<div class="showcase-grid">
<div class="showcase-item">
### QuWenJian
- **URL**: [www.quwenjian.cn/fby.html](https://www.quwenjian.cn/fby.html)
- **Description**: QuWenJian - Unlimited storage, portable and limitless
- **Highlights**: Free file transfer station
- **Operator**: QuWenJian
</div>
<div class="showcase-item">
### Pandora Box
- **URL**: [pan.duo.la](https://pan.duo.la)
- **Description**: Pandora Box
- **Highlights**: Classic v1.6 version
- **Operator**: WuXingQueXinYan
</div>
</div>
## Submission Requirements
To ensure quality, please make sure your site meets the following criteria:
1. **Stable**: Your site should be stable and accessible
2. **Legal**: Content must be legal and compliant
3. **Attribution**: We recommend keeping FileCodeBox attribution
4. **HTTPS**: We recommend enabling HTTPS
## Submission Template
If you want to submit your site, please use the following format:
```markdown
### Site Name
- **URL**: [domain](https://domain)
- **Description**: One-line description of your site
- **Highlights**: Special features or highlights
- **Operator**: Optional, your name or organization
```
<style>
.showcase-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 20px;
margin: 20px 0;
}
.showcase-item {
border: 1px solid var(--vp-c-divider);
border-radius: 8px;
padding: 20px;
transition: all 0.3s ease;
}
.showcase-item:hover {
border-color: var(--vp-c-brand);
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
.showcase-item h3 {
margin-top: 0;
color: var(--vp-c-brand);
}
.showcase-item ul {
list-style: none;
padding: 0;
margin: 0;
}
.showcase-item li {
margin: 8px 0;
}
</style>
+206
View File
@@ -0,0 +1,206 @@
# 配置说明
FileCodeBox 提供了丰富的配置选项,可以通过管理面板或直接修改配置来自定义系统行为。本文档详细介绍所有可用的配置项。
## 配置方式
FileCodeBox 支持两种配置方式:
1. **管理面板配置**(推荐):访问 `/admin` 进入管理面板,在设置页面修改配置
2. **数据库配置**:配置存储在 `data/filecodebox.db` 数据库中
::: tip 提示
首次启动时,系统会使用 `core/settings.py` 中的默认配置。修改后的配置会保存到数据库中。
:::
## 基础设置
### 站点信息
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `name` | string | `文件快递柜 - FileCodeBox` | 站点名称,显示在页面标题和导航栏 |
| `description` | string | `开箱即用的文件快传系统` | 站点描述,用于 SEO |
| `keywords` | string | `FileCodeBox, 文件快递柜...` | 站点关键词,用于 SEO |
| `port` | int | `12345` | 服务监听端口 |
### 通知设置
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `notify_title` | string | `系统通知` | 通知标题 |
| `notify_content` | string | 欢迎信息 | 通知内容,支持 HTML |
| `page_explain` | string | 法律声明 | 页面底部说明文字 |
| `robotsText` | string | `User-agent: *\nDisallow: /` | robots.txt 内容 |
## 上传设置
### 文件上传限制
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `openUpload` | int | `1` | 是否开启上传功能(1=开启,0=关闭) |
| `uploadSize` | int | `10485760` | 单文件最大上传大小(字节),默认 10MB |
| `enableChunk` | int | `0` | 是否启用分片上传(1=启用,0=禁用) |
::: warning 注意
`uploadSize` 的单位是字节。10MB = 10 * 1024 * 1024 = 10485760 字节
:::
### 上传频率限制
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `uploadMinute` | int | `1` | 上传限制的时间窗口(分钟) |
| `uploadCount` | int | `10` | 在时间窗口内允许的最大上传次数 |
例如:默认配置表示每 1 分钟内最多允许上传 10 次。
### 文件过期设置
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `expireStyle` | list | `["day","hour","minute","forever","count"]` | 可选的过期方式 |
| `max_save_seconds` | int | `0` | 文件最大保存时间(秒),0 表示不限制 |
过期方式说明:
- `day` - 按天过期
- `hour` - 按小时过期
- `minute` - 按分钟过期
- `forever` - 永不过期
- `count` - 按下载次数过期
## 主题设置
### 主题选择
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `themesSelect` | string | `themes/2024` | 当前使用的主题 |
| `themesChoices` | list | 见下方 | 可用主题列表 |
默认可用主题:
```json
[
{
"name": "2023",
"key": "themes/2023",
"author": "Lan",
"version": "1.0"
},
{
"name": "2024",
"key": "themes/2024",
"author": "Lan",
"version": "1.0"
}
]
```
### 界面样式
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `opacity` | float | `0.9` | 界面透明度(0-1) |
| `background` | string | `""` | 自定义背景图片 URL,为空则使用默认背景 |
## 管理员设置
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `admin_token` | string | 初始化页面设置 | 管理员登录密码(哈希存储) |
| `showAdminAddr` | int | `0` | 是否在首页显示管理入口(1=显示,0=隐藏) |
::: danger 安全警告
未初始化时会自动显示初始化页面。生产环境请在服务对外开放前完成初始化。
:::
## 安全设置
### 错误次数限制
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `errorMinute` | int | `1` | 错误限制的时间窗口(分钟) |
| `errorCount` | int | `1` | 在时间窗口内允许的最大错误次数 |
此设置用于防止暴力破解提取码。
## 存储设置
### 存储类型
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `file_storage` | string | `local` | 存储后端类型 |
| `storage_path` | string | `""` | 自定义存储路径 |
支持的存储类型:
- `local` - 本地存储
- `s3` - S3 兼容存储(AWS S3、阿里云 OSS、MinIO 等)
- `onedrive` - OneDrive 存储
- `webdav` - WebDAV 存储
- `opendal` - OpenDAL 存储
详细的存储配置请参考 [存储配置](/guide/storage)。
## 配置示例
### 示例 1:小型个人使用
适合个人或小团队使用,限制较宽松:
```python
{
"name": "我的文件分享",
"uploadSize": 52428800, # 50MB
"uploadMinute": 5, # 5分钟
"uploadCount": 20, # 最多20次
"expireStyle": ["day", "hour", "forever"],
"admin_token": "your-secure-password",
"showAdminAddr": 1
}
```
### 示例 2:公开服务
适合公开服务,需要更严格的限制:
```python
{
"name": "公共文件快递柜",
"uploadSize": 10485760, # 10MB
"uploadMinute": 1, # 1分钟
"uploadCount": 5, # 最多5次
"errorMinute": 5, # 5分钟
"errorCount": 3, # 最多3次错误
"expireStyle": ["hour", "minute", "count"],
"max_save_seconds": 86400, # 最长保存1天
"admin_token": "very-secure-password-123",
"showAdminAddr": 0
}
```
### 示例 3:企业内部使用
适合企业内部使用,支持大文件和分片上传:
```python
{
"name": "企业文件中转站",
"uploadSize": 1073741824, # 1GB
"enableChunk": 1, # 启用分片上传
"uploadMinute": 10, # 10分钟
"uploadCount": 100, # 最多100次
"expireStyle": ["day", "forever"],
"file_storage": "s3", # 使用S3存储
"admin_token": "enterprise-secure-token",
"showAdminAddr": 1
}
```
## 下一步
- [存储配置](/guide/storage) - 了解如何配置不同的存储后端
- [安全设置](/guide/security) - 了解如何增强系统安全性
- [文件分享](/guide/share) - 了解文件分享功能
+57 -3
View File
@@ -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;
}
```
### 手动部署
@@ -56,8 +109,9 @@ python main.py
- 下载文件
4. 后台管理
- 首次访问 `http://localhost:12345` 完成初始化
- 访问 `http://localhost:12345/#/admin`
- 输入管理员密码:`FileCodeBox2023`
- 输入初始化时设置的管理员密码
- 进入后台管理页面
- 查看系统信息、文件列表、用户管理等
@@ -65,4 +119,4 @@ python main.py
- [存储配置](/guide/storage) - 了解如何配置不同的存储方式
- [安全设置](/guide/security) - 了解如何增强系统安全性
- [API 文档](/api/) - 了解如何通过 API 集成
- [API 文档](/api/) - 了解如何通过 API 集成
+413
View File
@@ -0,0 +1,413 @@
# 管理面板
FileCodeBox 提供了功能完善的管理面板,让管理员可以方便地管理文件、查看系统状态和修改配置。本文档介绍管理面板的各项功能和使用方法。
## 访问管理面板
### 登录方式
管理面板位于 `/admin` 路径。访问方式:
1. 首次访问站点时,按初始化页面设置管理员密码
2. 在浏览器中访问 `http://your-domain.com/admin`
3. 输入管理员密码(`admin_token` 配置项的值)
4. 点击登录按钮
::: tip 提示
未初始化时会自动进入初始化页面。生产环境请先完成初始化,再开放公网访问。
:::
### 显示管理入口
默认情况下,首页不显示管理面板入口。您可以通过配置控制是否显示:
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `showAdminAddr` | int | `0` | 是否在首页显示管理入口(1=显示,0=隐藏) |
::: warning 安全建议
在公开服务中,建议保持 `showAdminAddr` 为 `0`,通过直接访问 `/admin` 路径进入管理面板,减少被恶意扫描的风险。
:::
### 认证机制
管理面板使用 JWT(JSON Web Token)进行身份认证:
1. 登录成功后,服务器返回一个包含管理员身份的 Token
2. 后续请求通过 `Authorization: Bearer <token>` 头部携带 Token
3. Token 用于验证管理员身份,确保只有授权用户可以访问管理功能
## 仪表盘
登录后首先看到的是仪表盘页面,展示系统的整体运行状态。
### 统计指标
仪表盘显示以下关键指标:
| 指标 | 说明 |
|------|------|
| **文件总数** (`totalFiles`) | 系统中存储的文件总数量 |
| **存储使用量** (`storageUsed`) | 所有文件占用的总存储空间(字节) |
| **系统运行时间** (`sysUptime`) | 系统首次启动的时间 |
| **昨日上传数** (`yesterdayCount`) | 昨天一整天上传的文件数量 |
| **昨日上传量** (`yesterdaySize`) | 昨天上传文件的总大小(字节) |
| **今日上传数** (`todayCount`) | 今天到目前为止上传的文件数量 |
| **今日上传量** (`todaySize`) | 今天上传文件的总大小(字节) |
### 指标说明
- **文件总数**:包括所有未过期的文件和文本分享
- **存储使用量**:显示实际文件占用的存储空间,不包括数据库等系统文件
- **昨日/今日统计**:基于文件创建时间计算,用于了解系统使用趋势
::: tip 提示
存储使用量显示的是字节数。例如 `10485760` 表示约 10MB。
:::
## 文件管理
### 文件列表
文件管理页面展示系统中所有已分享的文件,支持分页浏览和搜索。
**列表信息包括:**
- 文件 ID
- 提取码(code)
- 文件名前缀(prefix)
- 文件后缀(suffix)
- 文件大小
- 创建时间
- 过期时间
- 剩余下载次数
### 搜索文件
使用搜索功能可以快速找到特定文件:
1. 在搜索框中输入关键词
2. 系统会根据文件名前缀(prefix)进行模糊匹配
3. 搜索结果实时更新
**搜索示例:**
- 输入 `report` 可以找到所有文件名包含 "report" 的文件
- 输入 `.pdf` 可以找到所有 PDF 文件(如果文件名包含此字符串)
### 分页浏览
文件列表支持分页显示:
| 参数 | 默认值 | 说明 |
|------|--------|------|
| `page` | `1` | 当前页码 |
| `size` | `10` | 每页显示数量 |
### 删除文件
管理员可以删除任意文件:
1. 在文件列表中找到要删除的文件
2. 点击删除按钮
3. 确认删除操作
::: danger 警告
删除操作不可恢复!文件将从存储后端永久删除,同时删除数据库中的记录。
:::
**删除流程:**
1. 系统首先从存储后端(本地/S3/OneDrive 等)删除实际文件
2. 然后从数据库中删除文件记录
3. 删除后,对应的提取码将失效
### 下载文件
管理员可以直接下载任意文件:
1. 在文件列表中找到目标文件
2. 点击下载按钮
3. 文件将通过浏览器下载
对于文本分享,系统会直接返回文本内容而不是下载文件。
### 修改文件信息
管理员可以修改已分享文件的部分信息:
| 可修改字段 | 说明 |
|------------|------|
| `code` | 提取码(必须唯一,不能与其他文件重复) |
| `prefix` | 文件名前缀 |
| `suffix` | 文件后缀名 |
| `expired_at` | 过期时间 |
| `expired_count` | 剩余下载次数 |
**修改提取码:**
```
原提取码:abc123
新提取码:myfile2024
```
::: warning 注意
修改提取码时,系统会检查新提取码是否已被使用。如果已存在相同的提取码,修改将失败。
:::
## 本地文件管理
除了管理已分享的文件,管理面板还提供了本地文件管理功能,用于管理 `data/local` 目录中的文件。
### 查看本地文件
本地文件列表显示 `data/local` 目录中的所有文件:
| 信息 | 说明 |
|------|------|
| 文件名 | 文件的完整名称 |
| 创建时间 | 文件的创建时间 |
| 文件大小 | 文件大小(字节) |
### 分享本地文件
可以将本地文件快速分享:
1. 在本地文件列表中选择要分享的文件
2. 设置过期方式和过期值
3. 点击分享按钮
4. 系统生成提取码
**分享参数:**
| 参数 | 说明 |
|------|------|
| `filename` | 要分享的文件名 |
| `expire_style` | 过期方式(day/hour/minute/forever/count) |
| `expire_value` | 过期值(天数/小时数/分钟数/下载次数) |
### 删除本地文件
可以删除 `data/local` 目录中的文件:
1. 在本地文件列表中找到要删除的文件
2. 点击删除按钮
3. 确认删除
::: tip 使用场景
本地文件管理功能适用于:
- 批量上传文件到服务器后进行分享
- 管理通过其他方式上传到服务器的文件
- 清理不需要的本地文件
:::
## 系统设置
### 查看配置
在系统设置页面可以查看当前所有配置项的值。配置项按类别分组显示:
- 基础设置(站点名称、描述等)
- 上传设置(文件大小限制、频率限制等)
- 存储设置(存储类型、路径等)
- 主题设置(主题选择、透明度等)
- 安全设置(管理员密码、错误限制等)
### 修改配置
管理员可以通过管理面板修改大部分配置:
1. 进入系统设置页面
2. 找到要修改的配置项
3. 输入新的值
4. 点击保存按钮
**可修改的配置项:**
| 类别 | 配置项示例 |
|------|------------|
| 基础设置 | `name`, `description`, `keywords`, `notify_title`, `notify_content` |
| 上传设置 | `uploadSize`, `uploadMinute`, `uploadCount`, `openUpload`, `enableChunk` |
| 过期设置 | `expireStyle`, `max_save_seconds` |
| 主题设置 | `themesSelect`, `opacity`, `background` |
| 安全设置 | `admin_token`, `showAdminAddr`, `errorMinute`, `errorCount` |
| 存储设置 | `file_storage`, `storage_path` 及各存储后端的配置 |
::: warning 注意
- `admin_token`(管理员密码)不能设置为空
- `themesChoices`(主题列表)不可通过管理面板修改
- 修改存储设置后,已有文件不会自动迁移
:::
### 配置生效
配置修改后立即生效,无需重启服务。配置保存在数据库中,重启后仍然有效。
**配置存储位置:**
- 数据库:`data/filecodebox.db`
- 表名:`keyvalue`
- 键名:`settings`
## API 接口
管理面板的所有功能都通过 REST API 实现,以下是主要接口:
### 认证接口
**登录**
```
POST /admin/login
Content-Type: application/json
{
"password": "your-admin-password"
}
```
响应:
```json
{
"code": 200,
"detail": {
"token": "eyJhbGciOiJIUzI1NiIs...",
"token_type": "Bearer"
}
}
```
### 仪表盘接口
**获取统计数据**
```
GET /admin/dashboard
Authorization: Bearer <token>
```
### 文件管理接口
**获取文件列表**
```
GET /admin/file/list?page=1&size=10&keyword=
Authorization: Bearer <token>
```
**删除文件**
```
DELETE /admin/file/delete
Authorization: Bearer <token>
Content-Type: application/json
{
"id": 123
}
```
**下载文件**
```
GET /admin/file/download?id=123
Authorization: Bearer <token>
```
**修改文件信息**
```
PATCH /admin/file/update
Authorization: Bearer <token>
Content-Type: application/json
{
"id": 123,
"code": "newcode",
"expired_at": "2024-12-31T23:59:59"
}
```
### 本地文件接口
**获取本地文件列表**
```
GET /admin/local/lists
Authorization: Bearer <token>
```
**删除本地文件**
```
DELETE /admin/local/delete
Authorization: Bearer <token>
Content-Type: application/json
{
"filename": "example.txt"
}
```
**分享本地文件**
```
POST /admin/local/share
Authorization: Bearer <token>
Content-Type: application/json
{
"filename": "example.txt",
"expire_style": "day",
"expire_value": 7
}
```
### 配置接口
**获取配置**
```
GET /admin/config/get
Authorization: Bearer <token>
```
**更新配置**
```
PATCH /admin/config/update
Authorization: Bearer <token>
Content-Type: application/json
{
"admin_token": "new-password",
"uploadSize": 52428800
}
```
## 常见问题
### 忘记管理员密码
如果忘记了管理员密码,可以通过以下方式重置:
1. 停止 FileCodeBox 服务
2. 使用 SQLite 工具打开 `data/filecodebox.db`
3. 查询 `keyvalue` 表中 `key='settings'` 的记录
4. 修改 JSON 中的 `admin_token` 值
5. 重启服务
```sql
-- 查看当前配置
SELECT * FROM keyvalue WHERE key = 'settings';
-- 或者删除配置,重启后重新进入初始化流程
DELETE FROM keyvalue WHERE key = 'settings';
```
### 文件删除失败
如果删除文件时出现错误,可能的原因:
1. **存储后端连接失败**:检查存储配置是否正确
2. **文件已不存在**:文件可能已被手动删除
3. **权限不足**:检查存储目录的写入权限
### 配置修改不生效
如果修改配置后没有生效:
1. 检查是否点击了保存按钮
2. 刷新页面查看配置是否已保存
3. 检查浏览器控制台是否有错误信息
4. 确认配置值的格式是否正确(如数字类型不要输入字符串)
## 下一步
- [配置说明](/guide/configuration) - 了解所有配置选项的详细说明
- [安全设置](/guide/security) - 了解如何增强系统安全性
- [存储配置](/guide/storage) - 配置不同的存储后端
+324
View File
@@ -0,0 +1,324 @@
# 安全设置
FileCodeBox 提供了多层安全机制来保护您的文件分享服务。本文档介绍如何正确配置安全选项,确保系统安全运行。
## 管理员密码
### 首次初始化
::: danger 重要安全警告
FileCodeBox 首次启动时不会生成默认管理员密码。请在浏览器中打开站点,按初始化页面设置管理员密码,并妥善保存。
:::
修改管理员密码有两种方式:
**方式一:通过管理面板修改(推荐)**
1. 访问 `/admin` 进入管理面板
2. 使用当前密码登录
3. 进入「系统设置」页面
4. 找到 `admin_token` 配置项
5. 输入新的安全密码并保存
**方式二:通过数据库修改**
配置存储在 `data/filecodebox.db` 数据库的 `keyvalue` 表中,可以直接修改 `admin_token` 的值。
### 密码安全建议
- 使用至少 16 个字符的强密码
- 包含大小写字母、数字和特殊字符
- 避免使用常见词汇或个人信息
- 定期更换密码
```python
# 推荐的密码格式示例
"admin_token": "Xk9#mP2$vL5@nQ8&wR3"
```
### 隐藏管理入口
默认情况下,管理面板入口是隐藏的。您可以通过 `showAdminAddr` 配置控制是否在首页显示管理入口:
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `showAdminAddr` | int | `0` | 是否显示管理入口(1=显示,0=隐藏) |
::: tip 建议
在公开服务中,建议保持 `showAdminAddr` 为 `0`,通过直接访问 `/admin` 路径进入管理面板。
:::
## IP 速率限制
FileCodeBox 内置了基于 IP 的速率限制机制,可以有效防止滥用和攻击。
### 上传频率限制
限制单个 IP 在指定时间内的上传次数:
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `uploadMinute` | int | `1` | 上传限制的时间窗口(分钟) |
| `uploadCount` | int | `10` | 在时间窗口内允许的最大上传次数 |
**工作原理:**
- 系统记录每个 IP 的上传请求
- 当某 IP 在 `uploadMinute` 分钟内的上传次数达到 `uploadCount` 时
- 该 IP 的后续上传请求将被拒绝,返回 HTTP 423 错误
- 等待时间窗口过期后,计数器重置
**配置示例:**
```python
# 宽松配置:5分钟内最多上传20次
{
"uploadMinute": 5,
"uploadCount": 20
}
# 严格配置:1分钟内最多上传3次
{
"uploadMinute": 1,
"uploadCount": 3
}
```
### 错误次数限制
限制单个 IP 的错误尝试次数,防止暴力破解提取码:
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `errorMinute` | int | `1` | 错误限制的时间窗口(分钟) |
| `errorCount` | int | `1` | 在时间窗口内允许的最大错误次数 |
**工作原理:**
- 当用户输入错误的提取码时,系统记录该 IP 的错误次数
- 当错误次数达到 `errorCount` 时,该 IP 将被暂时锁定
- 锁定时间为 `errorMinute` 分钟
- 锁定期间,该 IP 的所有提取请求都将被拒绝
**配置示例:**
```python
# 防暴力破解配置:5分钟内最多允许3次错误
{
"errorMinute": 5,
"errorCount": 3
}
```
::: warning 注意
默认配置 `errorMinute=1, errorCount=1` 非常严格,意味着输入一次错误的提取码后需要等待1分钟才能重试。根据实际需求调整此配置。
:::
## 上传限制
### 文件大小限制
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `uploadSize` | int | `10485760` | 单文件最大上传大小(字节),默认 10MB |
| `openUpload` | int | `1` | 是否开启上传功能(1=开启,0=关闭) |
**常用大小换算:**
- 10MB = 10 * 1024 * 1024 = `10485760`
- 50MB = 50 * 1024 * 1024 = `52428800`
- 100MB = 100 * 1024 * 1024 = `104857600`
- 1GB = 1024 * 1024 * 1024 = `1073741824`
### 文件过期设置
通过文件过期机制,可以自动清理过期文件,减少存储占用和安全风险:
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `expireStyle` | list | `["day","hour","minute","forever","count"]` | 可选的过期方式 |
| `max_save_seconds` | int | `0` | 文件最大保存时间(秒),0 表示不限制 |
**过期方式说明:**
- `day` - 按天数过期
- `hour` - 按小时过期
- `minute` - 按分钟过期
- `forever` - 永不过期(需要字符串提取码)
- `count` - 按下载次数过期
**安全建议:**
对于公开服务,建议:
1. 移除 `forever` 选项,避免文件永久存储
2. 设置 `max_save_seconds` 限制最长保存时间
3. 优先使用 `count` 方式,下载后自动删除
```python
# 公开服务推荐配置
{
"expireStyle": ["hour", "minute", "count"],
"max_save_seconds": 86400 # 最长保存1天
}
```
### 关闭上传功能
在某些情况下,您可能需要临时关闭上传功能:
```python
{
"openUpload": 0 # 关闭上传功能
}
```
## 反向代理安全配置
在生产环境中,通常会使用 Nginx 或其他反向代理服务器。以下是安全配置建议:
### Nginx 配置示例
```nginx
server {
listen 80;
server_name your-domain.com;
# 强制 HTTPS 重定向
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name your-domain.com;
# SSL 证书配置
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers on;
# 安全头部
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# 限制请求体大小(与 uploadSize 配置一致)
client_max_body_size 100M;
# 传递真实 IP
location / {
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;
}
# 静态资源缓存
location /assets {
proxy_pass http://127.0.0.1:12345;
proxy_cache_valid 200 7d;
add_header Cache-Control "public, max-age=604800";
}
}
```
### 关键安全配置说明
**1. 传递真实 IP**
FileCodeBox 的 IP 限制功能依赖于获取客户端真实 IP。系统会按以下顺序获取 IP:
1. `X-Real-IP` 请求头
2. `X-Forwarded-For` 请求头
3. 直接连接的客户端 IP
确保反向代理正确设置这些头部:
```nginx
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
```
**2. 请求体大小限制**
Nginx 的 `client_max_body_size` 应该与 FileCodeBox 的 `uploadSize` 配置一致或略大:
```nginx
client_max_body_size 100M; # 允许上传最大 100MB
```
**3. HTTPS 加密**
强烈建议在生产环境中启用 HTTPS:
- 保护用户上传的文件内容
- 保护管理员登录凭据
- 防止中间人攻击
### Caddy 配置示例
```nginx
your-domain.com {
reverse_proxy localhost:12345
header {
X-Frame-Options "SAMEORIGIN"
X-Content-Type-Options "nosniff"
X-XSS-Protection "1; mode=block"
Strict-Transport-Security "max-age=31536000; includeSubDomains"
}
}
```
## 安全检查清单
部署 FileCodeBox 前,请确认以下安全配置:
- [ ] 已完成首次初始化并设置管理员密码 `admin_token`
- [ ] 已隐藏管理入口 `showAdminAddr: 0`
- [ ] 已配置合适的上传频率限制
- [ ] 已配置错误次数限制防止暴力破解
- [ ] 已设置合理的文件大小限制
- [ ] 已配置文件过期策略
- [ ] 已启用 HTTPS 加密
- [ ] 反向代理已正确传递真实 IP
- [ ] 已设置安全响应头部
## 推荐安全配置
### 公开服务配置
```python
{
"admin_token": "your-very-secure-password",
"showAdminAddr": 0,
"uploadSize": 10485760, # 10MB
"uploadMinute": 1,
"uploadCount": 5,
"errorMinute": 5,
"errorCount": 3,
"expireStyle": ["hour", "minute", "count"],
"max_save_seconds": 86400, # 最长1天
"openUpload": 1
}
```
### 内部服务配置
```python
{
"admin_token": "internal-secure-password",
"showAdminAddr": 1,
"uploadSize": 104857600, # 100MB
"uploadMinute": 5,
"uploadCount": 50,
"errorMinute": 1,
"errorCount": 5,
"expireStyle": ["day", "hour", "forever"],
"max_save_seconds": 0, # 不限制
"openUpload": 1
}
```
## 下一步
- [配置说明](/guide/configuration) - 了解所有配置选项
- [存储配置](/guide/storage) - 配置安全的存储后端
- [文件分享](/guide/share) - 了解文件分享功能
+341
View File
@@ -0,0 +1,341 @@
# 文件分享
FileCodeBox 提供了简单易用的文件和文本分享功能。用户可以通过提取码安全地分享和获取文件。
## 分享方式
FileCodeBox 支持两种分享方式:
1. **文本分享** - 直接分享文本内容,适合代码片段、配置文件等
2. **文件分享** - 上传文件进行分享,支持各种文件格式
## 文本分享
### 使用方法
1. 在首页选择「文本分享」标签
2. 在文本框中输入或粘贴要分享的内容
3. 选择过期方式和时间
4. 点击「分享」按钮
5. 获取提取码
### 文本大小限制
::: warning 注意
文本分享的最大内容大小为 **222KB**(227,328 字节)。如果内容超过此限制,建议使用文件分享方式。
:::
文本内容大小按 UTF-8 编码计算,中文字符通常占用 3 个字节。
### API 接口
**POST** `/share/text/`
请求参数:
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `text` | string | 是 | 要分享的文本内容 |
| `expire_value` | int | 否 | 过期数值,默认 1 |
| `expire_style` | string | 否 | 过期方式,默认 `day` |
响应示例:
```json
{
"code": 200,
"detail": {
"code": "123456"
}
}
```
## 文件分享
### 使用方法
1. 在首页选择「文件分享」标签
2. 点击上传区域或拖拽文件到上传区域
3. 选择过期方式和时间
4. 点击「上传」按钮
5. 获取提取码
### 文件大小限制
默认单文件最大上传大小为 **10MB**。管理员可以通过 `uploadSize` 配置项修改此限制。
::: tip 提示
如果需要上传大文件,请联系管理员启用分片上传功能,或调整 `uploadSize` 配置。
:::
### 支持的上传方式
- **点击上传** - 点击上传区域选择文件
- **拖拽上传** - 将文件拖拽到上传区域
- **粘贴上传** - 从剪贴板粘贴图片(部分主题支持)
### API 接口
**POST** `/share/file/`
请求参数(multipart/form-data):
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `file` | file | 是 | 要上传的文件 |
| `expire_value` | int | 否 | 过期数值,默认 1 |
| `expire_style` | string | 否 | 过期方式,默认 `day` |
响应示例:
```json
{
"code": 200,
"detail": {
"code": "654321",
"name": "example.pdf"
}
}
```
## 过期设置
FileCodeBox 支持多种灵活的过期方式:
| 过期方式 | 参数值 | 说明 |
|----------|--------|------|
| 按天过期 | `day` | 文件在指定天数后过期 |
| 按小时过期 | `hour` | 文件在指定小时后过期 |
| 按分钟过期 | `minute` | 文件在指定分钟后过期 |
| 永不过期 | `forever` | 文件永久有效 |
| 按次数过期 | `count` | 文件在被下载指定次数后过期 |
::: info 说明
- 管理员可以通过 `expireStyle` 配置项控制用户可选的过期方式
- 管理员可以通过 `max_save_seconds` 配置项限制文件的最长保存时间
:::
### 过期方式示例
```bash
# 文件 3 天后过期
expire_value=3, expire_style=day
# 文件 12 小时后过期
expire_value=12, expire_style=hour
# 文件 30 分钟后过期
expire_value=30, expire_style=minute
# 文件永不过期
expire_value=1, expire_style=forever
# 文件被下载 5 次后过期
expire_value=5, expire_style=count
```
## 提取文件
### 使用方法
1. 在首页的「提取文件」区域输入提取码
2. 点击「提取」按钮
3. 系统会显示文件信息(文件名、大小等)
4. 点击「下载」按钮下载文件,或直接查看文本内容
### 提取码说明
- 提取码通常为 **6 位数字**
- 永不过期的文件使用 **字母数字混合** 的提取码
- 提取码区分大小写(针对字母数字混合的情况)
### API 接口
**查询文件信息**
**POST** `/share/select/`
请求参数:
```json
{
"code": "123456"
}
```
响应示例(文件):
```json
{
"code": 200,
"detail": {
"code": "123456",
"name": "example.pdf",
"size": 1048576,
"text": "https://example.com/download/..."
}
}
```
响应示例(文本):
```json
{
"code": 200,
"detail": {
"code": "123456",
"name": "Text",
"size": 1024,
"text": "这是分享的文本内容..."
}
}
```
**直接下载文件**
**GET** `/share/select/?code=123456`
此接口会直接返回文件内容,适合在浏览器中直接访问。
## 分片上传(大文件)
对于大文件上传,FileCodeBox 支持分片上传功能。此功能需要管理员启用(`enableChunk=1`)。
### 分片上传流程
```mermaid
sequenceDiagram
participant C as 客户端
participant S as 服务器
C->>S: 1. 初始化上传 (POST /chunk/upload/init/)
S-->>C: 返回 upload_id 和分片信息
loop 每个分片
C->>S: 2. 上传分片 (POST /chunk/upload/chunk/{upload_id}/{chunk_index})
S-->>C: 返回分片哈希
end
C->>S: 3. 完成上传 (POST /chunk/upload/complete/{upload_id})
S-->>C: 返回提取码
```
### 1. 初始化上传
**POST** `/chunk/upload/init/`
请求参数:
```json
{
"file_name": "large_file.zip",
"file_size": 104857600,
"chunk_size": 5242880,
"file_hash": "sha256_hash_of_file"
}
```
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `file_name` | string | 是 | 文件名 |
| `file_size` | int | 是 | 文件总大小(字节) |
| `chunk_size` | int | 否 | 分片大小,默认 5MB |
| `file_hash` | string | 是 | 文件的 SHA256 哈希值 |
响应示例:
```json
{
"code": 200,
"detail": {
"existed": false,
"upload_id": "abc123def456",
"chunk_size": 5242880,
"total_chunks": 20,
"uploaded_chunks": []
}
}
```
### 2. 上传分片
**POST** `/chunk/upload/chunk/{upload_id}/{chunk_index}`
- `upload_id` - 初始化时返回的上传会话 ID
- `chunk_index` - 分片索引,从 0 开始
请求体:分片文件数据(multipart/form-data)
响应示例:
```json
{
"code": 200,
"detail": {
"chunk_hash": "sha256_hash_of_chunk"
}
}
```
### 3. 完成上传
**POST** `/chunk/upload/complete/{upload_id}`
请求参数:
```json
{
"expire_value": 1,
"expire_style": "day"
}
```
响应示例:
```json
{
"code": 200,
"detail": {
"code": "789012",
"name": "large_file.zip"
}
}
```
### 断点续传
分片上传支持断点续传。如果上传中断,可以:
1. 重新调用初始化接口,使用相同的 `file_hash`
2. 服务器会返回已上传的分片列表 `uploaded_chunks`
3. 客户端只需上传未完成的分片
## 错误处理
### 常见错误码
| 错误码 | 说明 | 解决方案 |
|--------|------|----------|
| 403 | 文件大小超过限制 | 减小文件大小或联系管理员调整限制 |
| 403 | 内容过多 | 文本超过 222KB,请使用文件分享 |
| 403 | 上传频率限制 | 等待一段时间后重试 |
| 404 | 文件不存在 | 检查提取码是否正确 |
| 404 | 文件已过期 | 文件已过期或下载次数已用完 |
### 频率限制
为防止滥用,系统对上传和提取操作有频率限制:
- **上传限制**:默认每分钟最多 10 次上传
- **错误限制**:默认每分钟最多 1 次错误尝试
::: tip 提示
如果遇到频率限制,请等待限制时间窗口过后再重试。
:::
## 下一步
- [配置说明](/guide/configuration) - 了解如何配置分享相关设置
- [存储配置](/guide/storage) - 了解文件存储方式
- [安全设置](/guide/security) - 了解安全相关配置
- [管理面板](/guide/management) - 了解如何管理分享的文件
File renamed without changes.
File renamed without changes.
+395
View File
@@ -0,0 +1,395 @@
# 存储配置
FileCodeBox 支持多种存储后端,您可以根据需求选择合适的存储方式。本文档将详细介绍各种存储后端的配置方法。
## 存储类型概览
| 存储类型 | 配置值 | 说明 |
|---------|--------|------|
| 本地存储 | `local` | 默认存储方式,文件保存在服务器本地 |
| S3 兼容存储 | `s3` | 支持 AWS S3、阿里云 OSS、MinIO 等 |
| OneDrive | `onedrive` | 微软 OneDrive 云存储(仅支持工作/学校账户) |
| WebDAV | `webdav` | 支持 WebDAV 协议的存储服务 |
| OpenDAL | `opendal` | 通过 OpenDAL 集成更多存储服务 |
## 本地存储
本地存储是默认的存储方式,文件将保存在服务器的 `data/` 目录下。
### 配置参数
| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `file_storage` | string | `local` | 存储类型 |
| `storage_path` | string | `""` | 自定义存储路径(可选) |
### 配置示例
```bash
file_storage=local
storage_path=
```
### 说明
- 文件默认存储在 `data/share/data/` 目录下
- 按日期自动创建子目录:`年/月/日/文件ID/`
- 建议在生产环境中将 `data/` 目录挂载到持久化存储
## S3 兼容存储
支持所有 S3 兼容的对象存储服务,包括 AWS S3、阿里云 OSS、MinIO、腾讯云 COS 等。
### 配置参数
| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `file_storage` | string | - | 设置为 `s3` |
| `s3_access_key_id` | string | `""` | Access Key ID |
| `s3_secret_access_key` | string | `""` | Secret Access Key |
| `s3_bucket_name` | string | `""` | 存储桶名称 |
| `s3_endpoint_url` | string | `""` | S3 端点 URL |
| `s3_region_name` | string | `auto` | 区域名称 |
| `s3_signature_version` | string | `s3v2` | 签名版本(`s3v2` 或 `s3v4`) |
| `s3_hostname` | string | `""` | S3 主机名(备用) |
| `s3_proxy` | int | `0` | 是否通过服务器代理下载(1=是,0=否) |
| `aws_session_token` | string | `""` | AWS 会话令牌(可选) |
### AWS S3 配置示例
```bash
file_storage=s3
s3_access_key_id=AKIAIOSFODNN7EXAMPLE
s3_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
s3_bucket_name=my-filecodebox-bucket
s3_endpoint_url=https://s3.amazonaws.com
s3_region_name=us-east-1
s3_signature_version=s3v4
```
### 阿里云 OSS 配置示例
```bash
file_storage=s3
s3_access_key_id=您的AccessKeyId
s3_secret_access_key=您的SecretAccessKey
s3_bucket_name=bucket-name
s3_endpoint_url=https://bucket-name.oss-cn-hangzhou.aliyuncs.com
s3_region_name=oss-cn-hangzhou
s3_signature_version=s3v4
```
::: tip 阿里云 OSS 端点格式
端点 URL 格式为:`https://<bucket-name>.<region>.aliyuncs.com`
常用区域:
- 杭州:`oss-cn-hangzhou`
- 上海:`oss-cn-shanghai`
- 北京:`oss-cn-beijing`
- 深圳:`oss-cn-shenzhen`
:::
### MinIO 配置示例
```bash
file_storage=s3
s3_access_key_id=minioadmin
s3_secret_access_key=minioadmin
s3_bucket_name=filecodebox
s3_endpoint_url=http://localhost:9000
s3_region_name=us-east-1
s3_signature_version=s3v4
```
::: warning MinIO 注意事项
- `s3_endpoint_url` 填写 MinIO 的 API 接口地址
- `s3_region_name` 根据 MinIO 配置中的 `Server Location` 设置
- 确保存储桶已创建且有正确的访问权限
:::
### 腾讯云 COS 配置示例
```bash
file_storage=s3
s3_access_key_id=您的SecretId
s3_secret_access_key=您的SecretKey
s3_bucket_name=bucket-name-1250000000
s3_endpoint_url=https://cos.ap-guangzhou.myqcloud.com
s3_region_name=ap-guangzhou
s3_signature_version=s3v4
```
### 代理下载
当 `s3_proxy=1` 时,文件下载将通过服务器中转,而不是直接从 S3 下载。这在以下情况下有用:
- S3 存储桶不允许公开访问
- 需要隐藏实际的存储地址
- 网络环境限制直接访问 S3
## OneDrive 存储
OneDrive 存储支持将文件保存到微软 OneDrive 云存储。
::: warning 重要限制
OneDrive 存储**仅支持工作或学校账户**,并且需要有管理员权限以授权 API。个人账户无法使用此功能。
:::
### 配置参数
| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `file_storage` | string | - | 设置为 `onedrive` |
| `onedrive_domain` | string | `""` | Azure AD 域名 |
| `onedrive_client_id` | string | `""` | 应用程序(客户端)ID |
| `onedrive_username` | string | `""` | 账户邮箱 |
| `onedrive_password` | string | `""` | 账户密码 |
| `onedrive_root_path` | string | `filebox_storage` | OneDrive 中的存储根目录 |
| `onedrive_proxy` | int | `0` | 是否通过服务器代理下载 |
### 配置示例
```bash
file_storage=onedrive
onedrive_domain=contoso.onmicrosoft.com
onedrive_client_id=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
onedrive_username=user@contoso.onmicrosoft.com
onedrive_password=your_password
onedrive_root_path=filebox_storage
```
### Azure 应用注册步骤
要使用 OneDrive 存储,您需要在 Azure 门户中注册应用程序:
#### 1. 获取域名
登录 [Azure 门户](https://portal.azure.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade),将鼠标置于右上角账号处,浮窗显示的**域**即为 `onedrive_domain` 的值。
#### 2. 注册应用
1. 点击左上角的 **+ 新注册**
2. 输入应用名称(如:FileCodeBox)
3. **受支持的帐户类型**:选择"任何组织目录(任何 Azure AD 目录 - 多租户)中的帐户和个人 Microsoft 帐户"
4. **重定向 URI**:选择 `Web`,输入 `http://localhost`
5. 点击**注册**
#### 3. 获取客户端 ID
注册完成后,在应用概述页面的**概要**中找到**应用程序(客户端)ID**,即为 `onedrive_client_id` 的值。
#### 4. 配置身份验证
1. 在左侧菜单选择**身份验证**
2. 找到**允许公共客户端流**,选择**是**
3. 点击**保存**
#### 5. 配置 API 权限
1. 在左侧菜单选择 **API 权限**
2. 点击 **+ 添加权限**
3. 选择 **Microsoft Graph** → **委托的权限**
4. 勾选以下权限:
- `openid`
- `Files.Read`
- `Files.Read.All`
- `Files.ReadWrite`
- `Files.ReadWrite.All`
- `User.Read`
5. 点击**添加权限**
6. 点击**代表 xxx 授予管理员同意**
7. 确认后,权限状态应显示为**已授予**
### 安装依赖
使用 OneDrive 存储需要安装额外的 Python 依赖:
```bash
pip install msal Office365-REST-Python-Client
```
### 验证配置
您可以使用以下代码测试配置是否正确:
```python
import msal
from office365.graph_client import GraphClient
domain = 'your_domain'
client_id = 'your_client_id'
username = 'your_username'
password = 'your_password'
def acquire_token_pwd():
authority_url = f'https://login.microsoftonline.com/{domain}'
app = msal.PublicClientApplication(
authority=authority_url,
client_id=client_id
)
result = app.acquire_token_by_username_password(
username=username,
password=password,
scopes=['https://graph.microsoft.com/.default']
)
return result
# 测试连接
client = GraphClient(acquire_token_pwd)
me = client.me.get().execute_query()
print(f"登录成功:{me.user_principal_name}")
```
## WebDAV 存储
WebDAV 存储支持将文件保存到任何支持 WebDAV 协议的服务,如 Nextcloud、ownCloud、坚果云等。
### 配置参数
| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `file_storage` | string | - | 设置为 `webdav` |
| `webdav_url` | string | `""` | WebDAV 服务器 URL |
| `webdav_username` | string | `""` | WebDAV 用户名 |
| `webdav_password` | string | `""` | WebDAV 密码 |
| `webdav_root_path` | string | `filebox_storage` | WebDAV 中的存储根目录 |
| `webdav_proxy` | int | `0` | 是否通过服务器代理下载 |
### 配置示例
```bash
file_storage=webdav
webdav_url=https://dav.example.com/remote.php/dav/files/username/
webdav_username=your_username
webdav_password=your_password
webdav_root_path=filebox_storage
```
### Nextcloud 配置示例
```bash
file_storage=webdav
webdav_url=https://your-nextcloud.com/remote.php/dav/files/username/
webdav_username=your_username
webdav_password=your_app_password
webdav_root_path=FileCodeBox
```
::: tip Nextcloud 应用密码
建议在 Nextcloud 中创建应用密码,而不是使用主密码:
1. 登录 Nextcloud
2. 进入**设置** → **安全**
3. 在**设备与会话**中创建新的应用密码
:::
### 坚果云配置示例
```bash
file_storage=webdav
webdav_url=https://dav.jianguoyun.com/dav/
webdav_username=your_email@example.com
webdav_password=your_app_password
webdav_root_path=FileCodeBox
```
::: tip 坚果云应用密码
坚果云需要使用应用密码:
1. 登录坚果云网页版
2. 进入**账户信息** → **安全选项**
3. 添加应用密码
:::
## OpenDAL 存储
OpenDAL 是一个统一的数据访问层,支持多种存储服务。通过 OpenDAL,您可以使用 Google Cloud Storage、Azure Blob Storage 等更多存储服务。
### 配置参数
| 参数 | 类型 | 说明 |
|------|------|------|
| `file_storage` | string | 设置为 `opendal` |
| `opendal_scheme` | string | 存储服务类型(如 `gcs`、`azblob`) |
| `opendal_<scheme>_<setting>` | string | 服务特定的配置参数 |
### 安装依赖
```bash
pip install opendal
```
### Google Cloud Storage 配置示例
```bash
file_storage=opendal
opendal_scheme=gcs
opendal_gcs_root=/filecodebox
opendal_gcs_bucket=your-bucket-name
opendal_gcs_credential=base64_encoded_credential
```
### Azure Blob Storage 配置示例
```bash
file_storage=opendal
opendal_scheme=azblob
opendal_azblob_root=/filecodebox
opendal_azblob_container=your-container
opendal_azblob_account_name=your_account
opendal_azblob_account_key=your_key
```
### 支持的服务
OpenDAL 支持众多存储服务,完整列表请参考 [OpenDAL 官方文档](https://opendal.apache.org/docs/rust/opendal/services/index.html)。
常用服务包括:
- `gcs` - Google Cloud Storage
- `azblob` - Azure Blob Storage
- `obs` - 华为云 OBS
- `oss` - 阿里云 OSS(通过 OpenDAL)
- `cos` - 腾讯云 COS(通过 OpenDAL)
- `hdfs` - Hadoop HDFS
- `ftp` - FTP 服务器
- `sftp` - SFTP 服务器
::: warning OpenDAL 注意事项
1. 通过 OpenDAL 集成的服务均通过服务器中转下载,会同时消耗存储服务和服务器的流量
2. 相比原生 S3/OneDrive 支持,OpenDAL 方式可能缺少一些调试信息
3. OpenDAL 采用 Rust 编写,性能较好
:::
## 存储选择建议
| 场景 | 推荐存储 | 原因 |
|------|----------|------|
| 个人/小型部署 | 本地存储 | 简单易用,无需额外配置 |
| 企业内网 | MinIO + S3 | 自建对象存储,数据可控 |
| 公有云部署 | 对应云厂商 S3 | 同区域访问快,成本低 |
| 已有 OneDrive | OneDrive | 利用现有资源 |
| 已有 WebDAV | WebDAV | 兼容性好 |
| 特殊存储需求 | OpenDAL | 支持更多存储服务 |
## 常见问题
### S3 上传失败
1. 检查 Access Key 和 Secret Key 是否正确
2. 确认存储桶名称和区域配置正确
3. 检查存储桶的访问权限设置
4. 确认签名版本(`s3v2` 或 `s3v4`)与服务商要求一致
### OneDrive 认证失败
1. 确认使用的是工作/学校账户,而非个人账户
2. 检查 Azure 应用是否已授予管理员同意
3. 确认 API 权限配置完整
4. 验证用户名和密码是否正确
### WebDAV 连接失败
1. 检查 WebDAV URL 格式是否正确
2. 确认用户名和密码(或应用密码)正确
3. 检查服务器是否支持 WebDAV 协议
4. 确认网络连接正常
+420
View File
@@ -0,0 +1,420 @@
# 文件上传
FileCodeBox 提供了多种灵活的文件上传方式,支持普通上传和分片上传,满足不同场景的需求。
## 上传方式
FileCodeBox 支持以下几种上传方式:
### 拖拽上传
将文件直接拖拽到上传区域即可开始上传。这是最便捷的上传方式。
1. 打开 FileCodeBox 首页
2. 将文件从文件管理器拖拽到上传区域
3. 松开鼠标,文件开始上传
4. 上传完成后获取提取码
::: tip 提示
拖拽上传支持同时拖拽多个文件(取决于主题支持)。
:::
### 点击上传
点击上传区域,通过系统文件选择器选择文件。
1. 点击上传区域的「选择文件」按钮
2. 在弹出的文件选择器中选择要上传的文件
3. 确认选择后文件开始上传
4. 上传完成后获取提取码
### 粘贴上传
支持从剪贴板直接粘贴图片进行上传(部分主题支持)。
1. 复制图片到剪贴板(截图或复制图片)
2. 在上传区域使用 `Ctrl+V`(Windows/Linux)或 `Cmd+V`(macOS)粘贴
3. 图片自动开始上传
4. 上传完成后获取提取码
::: warning 注意
粘贴上传仅支持图片格式,不支持其他文件类型。具体支持情况取决于所使用的主题。
:::
## 文件大小限制
### 默认限制
| 配置项 | 默认值 | 说明 |
|--------|--------|------|
| `uploadSize` | 10MB | 单文件最大上传大小 |
### 修改上传限制
管理员可以通过管理面板或配置文件修改上传大小限制:
```python
# 设置最大上传大小为 100MB
uploadSize = 104857600 # 100 * 1024 * 1024
```
::: info 说明
`uploadSize` 的单位是字节。常用换算:
- 10MB = 10485760
- 50MB = 52428800
- 100MB = 104857600
- 500MB = 524288000
- 1GB = 1073741824
:::
### 超出限制的处理
当上传文件超过大小限制时,系统会返回 403 错误:
```json
{
"detail": "大小超过限制,最大为10.00 MB"
}
```
## 普通上传 API
### 文件上传接口
**POST** `/share/file/`
Content-Type: `multipart/form-data`
**请求参数:**
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `file` | file | 是 | 要上传的文件 |
| `expire_value` | int | 否 | 过期数值,默认 1 |
| `expire_style` | string | 否 | 过期方式,默认 `day` |
**过期方式选项:**
| 值 | 说明 |
|----|------|
| `day` | 按天过期 |
| `hour` | 按小时过期 |
| `minute` | 按分钟过期 |
| `forever` | 永不过期 |
| `count` | 按下载次数过期 |
**响应示例:**
```json
{
"code": 200,
"detail": {
"code": "654321",
"name": "example.pdf"
}
}
```
**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": "<初始化时设置的管理员密码>"}'
# 返回: {"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 支持分片上传功能。分片上传将大文件分割成多个小块分别上传,支持断点续传。
::: warning 前提条件
分片上传功能需要管理员启用:`enableChunk=1`
:::
### 分片上传流程
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ 初始化上传 │ ──▶ │ 上传分片 │ ──▶ │ 完成上传 │
│ /init/ │ │ /chunk/ │ │ /complete/ │
└─────────────┘ └─────────────┘ └─────────────┘
│
▼
┌───────────┐
│ 循环上传 │
│ 每个分片 │
└───────────┘
```
### 1. 初始化上传
**POST** `/chunk/upload/init/`
**请求参数:**
```json
{
"file_name": "large_file.zip",
"file_size": 104857600,
"chunk_size": 5242880,
"file_hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}
```
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| `file_name` | string | 是 | - | 文件名 |
| `file_size` | int | 是 | - | 文件总大小(字节) |
| `chunk_size` | int | 否 | 5MB | 分片大小(字节) |
| `file_hash` | string | 是 | - | 文件的 SHA256 哈希值 |
**响应示例:**
```json
{
"code": 200,
"detail": {
"existed": false,
"upload_id": "abc123def456789",
"chunk_size": 5242880,
"total_chunks": 20,
"uploaded_chunks": []
}
}
```
| 字段 | 说明 |
|------|------|
| `existed` | 文件是否已存在(秒传) |
| `upload_id` | 上传会话 ID |
| `chunk_size` | 分片大小 |
| `total_chunks` | 总分片数 |
| `uploaded_chunks` | 已上传的分片索引列表 |
### 2. 上传分片
**POST** `/chunk/upload/chunk/{upload_id}/{chunk_index}`
**路径参数:**
| 参数 | 说明 |
|------|------|
| `upload_id` | 初始化时返回的上传会话 ID |
| `chunk_index` | 分片索引,从 0 开始 |
**请求体:**
Content-Type: `multipart/form-data`
| 参数 | 类型 | 说明 |
|------|------|------|
| `chunk` | file | 分片数据 |
**响应示例:**
```json
{
"code": 200,
"detail": {
"chunk_hash": "a1b2c3d4e5f6..."
}
}
```
**cURL 示例:**
```bash
# 上传第一个分片(索引为 0)
curl -X POST "http://localhost:12345/chunk/upload/chunk/abc123def456789/0" \
-F "chunk=@/path/to/chunk_0"
```
### 3. 完成上传
**POST** `/chunk/upload/complete/{upload_id}`
**路径参数:**
| 参数 | 说明 |
|------|------|
| `upload_id` | 上传会话 ID |
**请求参数:**
```json
{
"expire_value": 7,
"expire_style": "day"
}
```
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `expire_value` | int | 是 | 过期数值 |
| `expire_style` | string | 是 | 过期方式 |
**响应示例:**
```json
{
"code": 200,
"detail": {
"code": "789012",
"name": "large_file.zip"
}
}
```
### 断点续传
分片上传支持断点续传。当上传中断后:
1. 使用相同的 `file_hash` 重新调用初始化接口
2. 服务器返回 `uploaded_chunks` 列表,包含已上传的分片索引
3. 客户端只需上传不在列表中的分片
4. 所有分片上传完成后调用完成接口
**示例流程:**
```javascript
// 1. 初始化上传
const initResponse = await fetch('/chunk/upload/init/', {
method: 'POST',
body: JSON.stringify({
file_name: 'large_file.zip',
file_size: fileSize,
chunk_size: 5 * 1024 * 1024,
file_hash: fileHash
})
});
const { upload_id, uploaded_chunks, total_chunks } = await initResponse.json();
// 2. 上传未完成的分片
for (let i = 0; i < total_chunks; i++) {
if (!uploaded_chunks.includes(i)) {
const chunk = file.slice(i * chunkSize, (i + 1) * chunkSize);
await fetch(`/chunk/upload/chunk/${upload_id}/${i}`, {
method: 'POST',
body: chunk
});
}
}
// 3. 完成上传
await fetch(`/chunk/upload/complete/${upload_id}`, {
method: 'POST',
body: JSON.stringify({
expire_value: 7,
expire_style: 'day'
})
});
```
## 错误处理
### 常见错误
| HTTP 状态码 | 错误信息 | 原因 | 解决方案 |
|-------------|----------|------|----------|
| 403 | 大小超过限制 | 文件超过 `uploadSize` 限制 | 减小文件大小或联系管理员调整限制 |
| 403 | 上传频率限制 | 超过 IP 上传频率限制 | 等待限制时间窗口后重试 |
| 400 | 过期时间类型错误 | `expire_style` 值不在允许列表中 | 使用有效的过期方式 |
| 404 | 上传会话不存在 | `upload_id` 无效或已过期 | 重新初始化上传 |
| 400 | 无效的分片索引 | `chunk_index` 超出范围 | 检查分片索引是否正确 |
| 400 | 分片不完整 | 完成上传时分片数量不足 | 确保所有分片都已上传 |
### 频率限制
系统对上传操作有频率限制,防止滥用:
| 配置项 | 默认值 | 说明 |
|--------|--------|------|
| `uploadMinute` | 1 | 限制时间窗口(分钟) |
| `uploadCount` | 10 | 时间窗口内最大上传次数 |
当超过频率限制时,需要等待时间窗口过后才能继续上传。
### 错误响应格式
```json
{
"detail": "错误信息描述"
}
```
## 上传配置
### 相关配置项
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `openUpload` | int | 1 | 是否开放上传(1=开放,0=关闭) |
| `uploadSize` | int | 10485760 | 最大上传大小(字节) |
| `enableChunk` | int | 0 | 是否启用分片上传(1=启用,0=禁用) |
| `uploadMinute` | int | 1 | 上传频率限制时间窗口(分钟) |
| `uploadCount` | int | 10 | 时间窗口内最大上传次数 |
| `expireStyle` | list | ["day","hour","minute","forever","count"] | 允许的过期方式 |
### 配置示例
```python
# 允许上传 100MB 文件,启用分片上传
uploadSize = 104857600
enableChunk = 1
# 放宽上传频率限制:每 5 分钟最多 50 次
uploadMinute = 5
uploadCount = 50
# 只允许按天和按次数过期
expireStyle = ["day", "count"]
```
## 下一步
- [文件分享](/guide/share) - 了解完整的分享流程
- [配置说明](/guide/configuration) - 了解所有配置选项
- [存储配置](/guide/storage) - 了解文件存储方式
- [安全设置](/guide/security) - 了解安全相关配置
+127
View File
@@ -0,0 +1,127 @@
# 优秀案例
这里收录了一些使用 FileCodeBox 搭建的优秀站点。如果你也部署了 FileCodeBox,欢迎提交 PR 将你的站点添加到这里!
## 官方演示站
<div class="showcase-grid">
<div class="showcase-item">
### 🌟 FileCodeBox Demo
- **网址**:[share.lanol.cn](https://share.lanol.cn)
- **简介**:官方演示站点,体验最新功能
- **特点**:稳定运行,功能完整
</div>
</div>
## 社区站点
::: tip 提交你的站点
如果你使用 FileCodeBox 搭建了自己的文件分享服务,欢迎通过以下方式提交:
1. 在 [GitHub](https://github.com/vastsa/FileCodeBox) 提交 PR,编辑此页面
2. 在 [Issues](https://github.com/vastsa/FileCodeBox/issues) 中提交你的站点信息
3. 加入 QQ 群 739673698 联系管理员
:::
<!--
提交格式示例:
<div class="showcase-item">
### 站点名称
- **网址**:[example.com](https://example.com)
- **简介**:简短描述你的站点
- **特点**:列出站点特色
</div>
-->
<div class="showcase-grid">
<div class="showcase-item">
### 取文件
- **网址**:[www.quwenjian.cn/fby.html](https://www.quwenjian.cn/fby.html)
- **简介**:取文件 - 存储无界,便携无限
- **特点**:永久免费的文件中转站
- **运营者**:取文件&取文件网盘
</div>
<div class="showcase-item">
### 潘多拉盒子
- **网址**:[pan.duo.la](https://pan.duo.la)
- **简介**:潘多拉盒子
- **特点**:经典1.6版本
- **运营者**:五行缺心眼
</div>
</div>
## 提交要求
为了保证收录站点的质量,请确保你的站点满足以下条件:
1. **稳定运行**:站点需要稳定运行,能够正常访问
2. **合法合规**:站点内容需要合法合规,不得包含违法违规内容
3. **保留版权**:建议保留 FileCodeBox 的版权信息
4. **HTTPS 支持**:建议启用 HTTPS 加密访问
## 案例展示模板
如果你想提交站点,请按照以下格式:
```markdown
### 站点名称
- **网址**:[域名](https://域名)
- **简介**:一句话描述站点用途
- **特点**:站点的特色功能或亮点
- **运营者**:可选,你的名字或组织
```
<style>
.showcase-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 20px;
margin: 20px 0;
}
.showcase-item {
border: 1px solid var(--vp-c-divider);
border-radius: 8px;
padding: 20px;
transition: all 0.3s ease;
}
.showcase-item:hover {
border-color: var(--vp-c-brand);
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
.showcase-item h3 {
margin-top: 0;
color: var(--vp-c-brand);
}
.showcase-item ul {
list-style: none;
padding: 0;
margin: 0;
}
.showcase-item li {
margin: 8px 0;
}
</style>
+799 -50
View File
@@ -3,70 +3,746 @@
# @File : main.py
# @Software: PyCharm
import asyncio
import html
import time
from contextlib import asynccontextmanager
from urllib.parse import parse_qs
from fastapi import FastAPI
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse
from tortoise import Tortoise
from tortoise.contrib.fastapi import register_tortoise
from apps.admin.views import admin_api
from apps.base.models import KeyValue
from apps.base.utils import ip_limit
from apps.base.views import share_api
from apps.admin.views import admin_api
from core.database import init_db
from apps.base.views import share_api, chunk_api, presign_api
from core.config import (
ensure_security_settings,
ensure_settings_row,
initialize_system,
is_runtime_initialized,
refresh_settings,
)
from core.database import db_startup_lock, get_db_config, init_db
from core.logger import logger
from core.response import APIResponse
from core.settings import data_root, settings, BASE_DIR, DEFAULT_CONFIG
from core.tasks import delete_expire_files
from core.settings import settings, BASE_DIR, DEFAULT_CONFIG
from core.tasks import delete_expire_files, clean_incomplete_uploads
from core.version import APP_VERSION
from contextlib import asynccontextmanager
from tortoise import Tortoise
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,
},
}
FILE_SIZE_UNITS = {"KB": 1024, "MB": 1024**2, "GB": 1024**3}
SAVE_TIME_UNITS = {"second": 1, "minute": 60, "hour": 3600, "day": 86400}
EXPIRE_STYLE_OPTIONS = [
("day", "按天"),
("hour", "按小时"),
("minute", "按分钟"),
("forever", "永久"),
("count", "按取件次数"),
]
def get_form_value(data: dict, key: str, default: str = "") -> str:
value = data.get(key, default)
if isinstance(value, list):
value = value[-1] if value else default
return str(value if value is not None else default)
def get_form_list(data: dict, key: str) -> list[str]:
value = data.get(key, [])
if isinstance(value, list):
return [str(item) for item in value if str(item)]
if value:
return [str(value)]
return []
def normalize_bool_field(data: dict, key: str, default: bool) -> bool:
if key not in data:
return default
return get_form_value(data, key).lower() in {"1", "true", "on", "yes"}
def parse_int_field(
data: dict,
key: str,
default: int,
label: str,
min_value: int = 0,
max_value: int | None = None,
) -> int:
raw_value = get_form_value(data, key, str(default)).strip()
try:
value = int(raw_value)
except ValueError:
raise ValueError(f"{label} 必须是整数")
if value < min_value:
raise ValueError(f"{label} 不能小于 {min_value}")
if max_value is not None and value > max_value:
raise ValueError(f"{label} 不能大于 {max_value}")
return value
def parse_allowed_file_types(value: str) -> list[str]:
items = [item.strip() for item in value.split(",") if item.strip()]
return items or ["*"]
def parse_setup_options(data: dict) -> dict:
upload_size_unit = get_form_value(data, "upload_size_unit", "MB").upper()
if upload_size_unit not in FILE_SIZE_UNITS:
raise ValueError("文件大小单位不正确")
upload_size_value = parse_int_field(
data, "upload_size_value", 10, "文件大小限制", min_value=1
)
save_time_unit = get_form_value(data, "save_time_unit", "day")
if save_time_unit not in SAVE_TIME_UNITS:
raise ValueError("最长保存时间单位不正确")
save_time_value = parse_int_field(
data, "save_time_value", 0, "最长保存时间", min_value=0
)
expire_styles = get_form_list(data, "expireStyle")
valid_expire_styles = {style for style, _label in EXPIRE_STYLE_OPTIONS}
expire_styles = [style for style in expire_styles if style in valid_expire_styles]
if not expire_styles:
raise ValueError("至少需要选择一种过期方式")
code_generate_type = get_form_value(data, "code_generate_type", "number")
if code_generate_type not in {"number", "secret"}:
raise ValueError("提取码类型不正确")
return {
"allowed_file_types": parse_allowed_file_types(
get_form_value(data, "allowed_file_types", "*")
),
"code_generate_type": code_generate_type,
"enableChunk": int(normalize_bool_field(data, "enableChunk", False)),
"errorCount": parse_int_field(
data, "errorCount", DEFAULT_CONFIG["errorCount"], "取件错误次数限制", 1
),
"errorMinute": parse_int_field(
data, "errorMinute", DEFAULT_CONFIG["errorMinute"], "取件错误检测窗口", 1
),
"expireStyle": expire_styles,
"max_save_seconds": save_time_value * SAVE_TIME_UNITS[save_time_unit],
"openUpload": int(normalize_bool_field(data, "openUpload", True)),
"uploadCount": parse_int_field(
data, "uploadCount", DEFAULT_CONFIG["uploadCount"], "上传次数限制", 1
),
"uploadMinute": parse_int_field(
data, "uploadMinute", DEFAULT_CONFIG["uploadMinute"], "上传检测窗口", 1
),
"uploadSize": upload_size_value * FILE_SIZE_UNITS[upload_size_unit],
}
def build_expire_style_inputs(selected_styles: list[str]) -> str:
inputs = []
selected = set(selected_styles)
for style, label in EXPIRE_STYLE_OPTIONS:
checked = " checked" if style in selected else ""
inputs.append(
f'<label class="check"><input type="checkbox" name="expireStyle" value="{style}"{checked}> {label}</label>'
)
return "\n ".join(inputs)
def build_setup_page(error: str = "", form: dict | None = None) -> str:
form = form or {}
escaped_error = html.escape(error)
escaped_site_name = html.escape(
get_form_value(form, "site_name", DEFAULT_CONFIG["name"])
)
escaped_allowed_types = html.escape(get_form_value(form, "allowed_file_types", "*"))
upload_size_value = html.escape(get_form_value(form, "upload_size_value", "10"))
upload_size_unit = get_form_value(form, "upload_size_unit", "MB").upper()
save_time_value = html.escape(get_form_value(form, "save_time_value", "0"))
save_time_unit = get_form_value(form, "save_time_unit", "day")
upload_minute = html.escape(
get_form_value(form, "uploadMinute", str(DEFAULT_CONFIG["uploadMinute"]))
)
upload_count = html.escape(
get_form_value(form, "uploadCount", str(DEFAULT_CONFIG["uploadCount"]))
)
error_minute = html.escape(
get_form_value(form, "errorMinute", str(DEFAULT_CONFIG["errorMinute"]))
)
error_count = html.escape(
get_form_value(form, "errorCount", str(DEFAULT_CONFIG["errorCount"]))
)
open_upload_checked = (
" checked" if normalize_bool_field(form, "openUpload", True) else ""
)
chunk_checked = (
" checked" if normalize_bool_field(form, "enableChunk", False) else ""
)
code_generate_type = get_form_value(form, "code_generate_type", "number")
selected_expire_styles = get_form_list(form, "expireStyle") or list(
DEFAULT_CONFIG["expireStyle"]
)
expire_style_inputs = build_expire_style_inputs(selected_expire_styles)
size_unit_options = "\n".join(
f'<option value="{unit}"{" selected" if unit == upload_size_unit else ""}>{unit}</option>'
for unit in FILE_SIZE_UNITS
)
save_time_unit_options = "\n".join(
f'<option value="{unit}"{" selected" if unit == save_time_unit else ""}>{label}</option>'
for unit, label in [
("second", "秒"),
("minute", "分钟"),
("hour", "小时"),
("day", "天"),
]
)
code_type_options = "\n".join(
f'<option value="{value}"{" selected" if value == code_generate_type else ""}>{label}</option>'
for value, label in [("number", "数字"), ("secret", "随机字符")]
)
error_block = (
f'<div class="alert" role="alert">{escaped_error}</div>' if escaped_error else ""
)
return f"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>初始化 FileCodeBox</title>
<style>
:root {{
color-scheme: light;
--bg: #f5f5f7;
--panel: rgba(255, 255, 255, .86);
--panel-strong: rgba(255, 255, 255, .96);
--text: #18181b;
--muted: #71717a;
--line: rgba(228, 228, 231, .9);
--line-strong: rgba(212, 212, 216, .95);
--primary: #18181b;
--primary-soft: #f4f4f5;
--danger-bg: #fef2f2;
--danger: #b91c1c;
}}
* {{ box-sizing: border-box; }}
body {{
margin: 0;
min-height: 100vh;
display: grid;
place-items: center;
padding: 14px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: var(--bg);
color: var(--text);
}}
main {{
width: min(100%, 1040px);
padding: 14px;
border: 1px solid rgba(255, 255, 255, .8);
border-radius: 20px;
background: rgba(255, 255, 255, .62);
box-shadow: 0 22px 70px -34px rgba(24, 24, 27, .32);
backdrop-filter: blur(22px);
}}
.setup-header {{
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 10px 10px 12px;
}}
.brand-mark {{
flex: 0 0 auto;
width: 40px;
height: 40px;
display: grid;
place-items: center;
border-radius: 14px;
background: #18181b;
color: #fff;
font-weight: 800;
letter-spacing: 0;
box-shadow: 0 16px 34px -14px rgba(24, 24, 27, .42);
}}
.title-wrap {{
min-width: 0;
display: flex;
align-items: center;
gap: 12px;
}}
h1 {{
margin: 0;
font-size: 21px;
line-height: 1.25;
letter-spacing: 0;
font-weight: 750;
}}
p {{
margin: 2px 0 0;
color: var(--muted);
line-height: 1.35;
font-size: 13px;
}}
form {{
margin: 0;
padding: 12px;
border: 1px solid var(--line);
border-radius: 16px;
background: var(--panel);
}}
.panel-grid {{
display: grid;
grid-template-columns: 1.05fr 1fr 1fr;
gap: 10px;
}}
.panel {{
min-width: 0;
padding: 10px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255, 255, 255, .68);
}}
.panel-wide {{
grid-column: 1 / -1;
display: grid;
grid-template-columns: minmax(0, 1.3fr) minmax(0, .9fr);
gap: 12px;
align-items: end;
}}
.panel-title {{
margin: 0 0 2px;
color: #18181b;
font-size: 13px;
font-weight: 760;
}}
label {{
display: block;
margin: 8px 0 5px;
font-weight: 650;
font-size: 12px;
color: #3f3f46;
}}
input, select {{
width: 100%;
height: 34px;
border: 1px solid var(--line);
border-radius: 10px;
padding: 0 10px;
font: inherit;
color: var(--text);
outline: none;
background: rgba(255, 255, 255, .84);
transition: border-color .2s ease, box-shadow .2s ease, background-color .2s ease;
}}
input:focus, select:focus {{
border-color: #a1a1aa;
background: #fff;
box-shadow: 0 10px 22px -12px rgba(24, 24, 27, .2), 0 0 0 3px rgba(24, 24, 27, .06);
}}
.grid {{
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 6px 12px;
}}
.full {{ grid-column: 1 / -1; }}
.span-2 {{ grid-column: span 2; }}
.row {{
display: grid;
grid-template-columns: minmax(0, 1fr) 88px;
gap: 8px;
}}
.checks {{
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 5px;
}}
.check {{
display: flex;
align-items: center;
gap: 8px;
min-height: 36px;
margin: 0;
padding: 0 9px;
border: 1px solid var(--line);
border-radius: 10px;
font-weight: 550;
font-size: 13px;
color: var(--text);
white-space: nowrap;
background: rgba(255, 255, 255, .72);
transition: border-color .2s ease, background-color .2s ease, box-shadow .2s ease;
}}
.check:hover {{
border-color: var(--line-strong);
background: #fff;
box-shadow: 0 8px 20px -8px rgba(0, 0, 0, .1);
}}
.check input {{
width: 16px;
height: 16px;
padding: 0;
box-shadow: none;
}}
.section-title {{
display: none;
}}
.help {{
margin: 4px 0 0;
font-size: 12px;
color: var(--muted);
}}
.alert {{
margin-bottom: 8px;
padding: 9px 12px;
border-radius: 12px;
background: var(--danger-bg);
color: var(--danger);
font-size: 13px;
}}
button {{
width: 100%;
height: 38px;
margin-top: 12px;
border: 0;
border-radius: 12px;
background: var(--primary);
color: white;
font: inherit;
font-weight: 700;
cursor: pointer;
box-shadow: 0 16px 34px -14px rgba(24, 24, 27, .42);
transition: background-color .2s ease, box-shadow .2s ease;
}}
button:hover {{
background: #27272a;
box-shadow: 0 16px 34px -14px rgba(24, 24, 27, .56);
}}
.hint {{
margin-top: 8px;
margin-bottom: 0;
font-size: 12px;
}}
.compact-help {{
display: inline;
margin-left: 6px;
color: var(--muted);
font-weight: 500;
font-size: 12px;
}}
.topline {{
display: none;
}}
.badge {{
min-height: 26px;
display: inline-flex;
align-items: center;
padding: 0 10px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(255, 255, 255, .76);
color: #52525b;
font-size: 12px;
font-weight: 650;
white-space: nowrap;
}}
@media (max-width: 640px) {{
body {{ padding: 10px; }}
main {{ padding: 10px; }}
.setup-header {{ align-items: flex-start; padding: 6px 4px 10px; }}
.title-wrap {{ align-items: flex-start; }}
.panel-grid, .panel-wide {{ grid-template-columns: 1fr; }}
.grid, .checks {{ grid-template-columns: 1fr; }}
.span-2 {{ grid-column: auto; }}
.row {{ grid-template-columns: 1fr; }}
.badge {{ display: none; }}
}}
</style>
</head>
<body>
<main>
<div class="setup-header">
<div class="title-wrap">
<div class="brand-mark">FCB</div>
<div>
<h1>初始化 FileCodeBox</h1>
<p>首次配置管理员密码、上传限制和取件策略,后续可在后台调整。</p>
</div>
</div>
<span class="badge">首次配置向导</span>
</div>
<form method="post" action="/setup" autocomplete="off">
{error_block}
<div class="panel-grid">
<section class="panel">
<div class="panel-title">基础设置</div>
<label for="site_name">站点名称</label>
<input id="site_name" name="site_name" maxlength="80" value="{escaped_site_name}" placeholder="文件快递柜 - FileCodeBox">
<label for="admin_password">管理员密码</label>
<input id="admin_password" name="admin_password" type="password" minlength="8" required autofocus>
<label for="confirm_password">确认管理员密码</label>
<input id="confirm_password" name="confirm_password" type="password" minlength="8" required>
</section>
<section class="panel">
<div class="panel-title">上传设置</div>
<label for="upload_size_value">单文件大小限制</label>
<div class="row">
<input id="upload_size_value" name="upload_size_value" type="number" min="1" value="{upload_size_value}" required>
<select name="upload_size_unit" aria-label="文件大小单位">
{size_unit_options}
</select>
</div>
<label for="uploadCount">上传频率 <span class="compact-help">次数 / 分钟</span></label>
<div class="row">
<input id="uploadCount" name="uploadCount" type="number" min="1" value="{upload_count}" required>
<input name="uploadMinute" type="number" min="1" value="{upload_minute}" aria-label="上传检测窗口分钟" required>
</div>
<div class="grid">
<input type="hidden" name="openUpload" value="0">
<label class="check"><input type="checkbox" name="openUpload" value="1"{open_upload_checked}> 允许游客上传</label>
<input type="hidden" name="enableChunk" value="0">
<label class="check"><input type="checkbox" name="enableChunk" value="1"{chunk_checked}> 启用切片上传</label>
</div>
</section>
<section class="panel">
<div class="panel-title">取件与保存</div>
<label for="errorCount">取件错误频率 <span class="compact-help">次数 / 分钟</span></label>
<div class="row">
<input id="errorCount" name="errorCount" type="number" min="1" value="{error_count}" required>
<input name="errorMinute" type="number" min="1" value="{error_minute}" aria-label="取件错误检测窗口分钟" required>
</div>
<label for="save_time_value">最长保存时间</label>
<div class="row">
<input id="save_time_value" name="save_time_value" type="number" min="0" value="{save_time_value}" required>
<select name="save_time_unit" aria-label="最长保存时间单位">
{save_time_unit_options}
</select>
</div>
<label for="code_generate_type">提取码类型</label>
<select id="code_generate_type" name="code_generate_type">
{code_type_options}
</select>
</section>
<section class="panel panel-wide">
<div>
<div class="panel-title">可用策略</div>
<label>允许的过期方式</label>
<div class="checks">
{expire_style_inputs}
</div>
</div>
<div>
<label for="allowed_file_types">允许文件类型 <span class="compact-help">逗号分隔,* 表示不限制</span></label>
<input id="allowed_file_types" name="allowed_file_types" value="{escaped_allowed_types}" placeholder="* 或 .zip, image/*">
</div>
</section>
</div>
<button type="submit">完成初始化</button>
</form>
</main>
</body>
</html>"""
def build_setup_success_page() -> str:
return """<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="2;url=/#/admin">
<title>初始化完成</title>
<style>
body {
margin: 0;
min-height: 100vh;
display: grid;
place-items: center;
padding: 24px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: #f6f8fb;
color: #172033;
}
main {
width: min(100%, 420px);
padding: 28px;
border: 1px solid #d9e1ec;
border-radius: 8px;
background: #fff;
text-align: center;
box-shadow: 0 18px 50px rgba(23, 32, 51, .08);
}
h1 { margin: 0 0 10px; font-size: 24px; letter-spacing: 0; }
p { margin: 0 0 22px; color: #60708a; line-height: 1.65; }
a {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 42px;
padding: 0 18px;
border-radius: 6px;
background: #2563eb;
color: white;
text-decoration: none;
font-weight: 700;
}
</style>
</head>
<body>
<main>
<h1>初始化完成</h1>
<p>管理员密码已设置,请使用刚才的密码登录后台。</p>
<a href="/#/admin">进入后台</a>
</main>
</body>
</html>"""
def setup_response(content: str, status_code: int = 200) -> HTMLResponse:
return HTMLResponse(
content=content,
status_code=status_code,
media_type="text/html",
headers={"Cache-Control": "no-store"},
)
def is_setup_path(path: str) -> bool:
return path.rstrip("/") == "/setup"
def wants_html_response(request: Request) -> bool:
if request.method not in {"GET", "HEAD"}:
return False
accept = request.headers.get("accept", "")
return not accept or "text/html" in accept or "*/*" in accept
async def read_setup_payload(request: Request) -> dict:
content_type = request.headers.get("content-type", "")
if "application/json" in content_type:
data = await request.json()
return data if isinstance(data, dict) else {}
body = (await request.body()).decode("utf-8")
return {
key: values if len(values) > 1 else values[-1]
for key, values in parse_qs(body).items()
}
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("正在初始化应用...")
# 初始化数据库
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())
logger.info("应用初始化完成")
try:
yield
finally:
# 清理操作
logger.info("正在关闭应用...")
task.cancel()
await asyncio.gather(task, return_exceptions=True)
chunk_cleanup_task.cancel()
await asyncio.gather(task, chunk_cleanup_task, return_exceptions=True)
await Tortoise.close_connections()
logger.info("应用已关闭")
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 ensure_security_settings()
ip_limit["error"].minutes = settings.errorMinute
ip_limit["error"].count = settings.errorCount
ip_limit["upload"].minutes = settings.uploadMinute
ip_limit["upload"].count = settings.uploadCount
app = FastAPI(lifespan=lifespan)
@app.middleware("http")
async def refresh_settings_middleware(request, call_next):
await refresh_settings()
if not is_runtime_initialized() and not is_setup_path(request.url.path):
if wants_html_response(request):
return setup_response(build_setup_page())
return JSONResponse(
status_code=428,
content={
"code": 428,
"message": "系统未初始化,请先完成初始化",
"msg": "系统未初始化,请先完成初始化",
"detail": {"setup": "/setup"},
},
)
return await call_next(request)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
@@ -78,36 +754,95 @@ 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,
)
app.include_router(share_api)
app.include_router(chunk_api)
app.include_router(presign_api)
app.include_router(presign_api, prefix="/api")
app.include_router(admin_api)
@app.get("/setup", include_in_schema=False)
@app.get("/setup/", include_in_schema=False)
async def setup_page():
if is_runtime_initialized():
return RedirectResponse(url="/", status_code=303)
return setup_response(build_setup_page())
@app.post("/setup", include_in_schema=False)
@app.post("/setup/", include_in_schema=False)
async def setup_submit(request: Request):
if is_runtime_initialized():
return RedirectResponse(url="/", status_code=303)
data = await read_setup_payload(request)
admin_password = str(data.get("admin_password") or "")
confirm_password = str(data.get("confirm_password") or "")
site_name = str(data.get("site_name") or "")
if admin_password != confirm_password:
return setup_response(build_setup_page("两次输入的管理员密码不一致", data), 400)
try:
setup_options = parse_setup_options(data)
await initialize_system(
admin_password=admin_password,
site_name=site_name,
setup_options=setup_options,
)
except ValueError as exc:
return setup_response(build_setup_page(str(exc), data), 400)
if "application/json" in request.headers.get("accept", ""):
return APIResponse(detail={"ok": True, "admin": "/#/admin"})
return setup_response(build_setup_success_page())
def resolve_theme_root():
themes_root = (BASE_DIR / "themes").resolve()
theme_root = (BASE_DIR / str(settings.themesSelect)).resolve()
try:
theme_root.relative_to(themes_root)
except ValueError:
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"},
@@ -121,17 +856,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,
"openUpload": settings.openUpload,
"notify_title": settings.notify_title,
"notify_content": settings.notify_content,
"show_admin_address": settings.showAdminAddr,
"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,
}
)
@@ -140,5 +885,9 @@ if __name__ == "__main__":
import uvicorn
uvicorn.run(
app="main:app", host="0.0.0.0", port=settings.port, reload=False, workers=1
app="main:app",
host=settings.serverHost,
port=settings.serverPort,
reload=False,
workers=settings.serverWorkers,
)
-54
View File
@@ -1,54 +0,0 @@
import { request } from '@/utils/request'; // 假设这是你的请求函数
import { ElMessage } from 'element-plus'; // Element Plus 的消息组件
import { t } from '@/locales'; // 国际化函数
import { saveFileByWebApi, saveFileByElementA } from '@/utils/file'; // 文件保存工具函数
const downloadFile = (id: number) => {
request({
url: '/admin/file/download',
method: 'get',
params: {
id,
},
responseType: 'blob'
}).then((response: any) => {
const contentDisposition = response.headers?.['content-disposition'] || '';
let filename = 'file';
try {
// 先尝试获取 filename* 参数
const filenameStarMatch = contentDisposition.match(/filename\*=UTF-8''([^;]*)/);
if (filenameStarMatch) {
filename = decodeURIComponent(filenameStarMatch[1]);
} else {
// 如果没有 filename*,则尝试获取普通 filename
const filenameMatch = contentDisposition.match(/filename="([^"]*)"/) || contentDisposition.match(/filename=([^;]*)/);
if (filenameMatch) {
filename = filenameMatch[1];
}
}
} catch (error) {
console.warn('解析文件名失败:', error);
// 如果解析失败,使用默认文件名
filename = `download_${id}`;
}
// @ts-ignore
if (window.showSaveFilePicker) {
saveFileByWebApi(response.data, filename).catch(() => {
saveFileByElementA(response.data, filename).catch(() => {
ElMessage.error(t('admin.fileView.download_fail'));
});
});
} else {
saveFileByElementA(response.data, filename).catch(() => {
ElMessage.error(t('admin.fileView.download_fail'));
});
}
}).catch(error => {
console.error('下载文件失败:', error);
ElMessage.error(t('admin.fileView.download_fail'));
});
};
export default downloadFile;
+380 -206
View File
@@ -1,298 +1,472 @@
# 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>
### 文件快递柜 - 匿名口令分享文本和文件
[![GitHub stars](https://img.shields.io/github/stars/vastsa/FileCodeBox)](https://github.com/vastsa/FileCodeBox/stargazers)
[![GitHub forks](https://img.shields.io/github/forks/vastsa/FileCodeBox)](https://github.com/vastsa/FileCodeBox/network)
[![GitHub issues](https://img.shields.io/github/issues/vastsa/FileCodeBox)](https://github.com/vastsa/FileCodeBox/issues)
[![GitHub license](https://img.shields.io/github/license/vastsa/FileCodeBox)](https://github.com/vastsa/FileCodeBox/blob/master/LICENSE)
[![QQ Group](https://img.shields.io/badge/QQ%20Group-739673698-blue.svg)](https://qm.qq.com/q/PemPzhdEIM)
[![Python Version](https://img.shields.io/badge/Python-3.8+-blue.svg)](https://www.python.org)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.68+-green.svg)](https://fastapi.tiangolo.com)
[![Vue Version](https://img.shields.io/badge/Vue.js-3.x-brightgreen.svg)](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/常见问题)
像拿快递一样取文件,无需注册,输入口令即可获取
[![GitHub stars](https://img.shields.io/github/stars/vastsa/FileCodeBox?style=flat-square&logo=github)](https://github.com/vastsa/FileCodeBox/stargazers)
[![GitHub forks](https://img.shields.io/github/forks/vastsa/FileCodeBox?style=flat-square&logo=github)](https://github.com/vastsa/FileCodeBox/network)
[![GitHub issues](https://img.shields.io/github/issues/vastsa/FileCodeBox?style=flat-square&logo=github)](https://github.com/vastsa/FileCodeBox/issues)
[![GitHub license](https://img.shields.io/github/license/vastsa/FileCodeBox?style=flat-square)](https://github.com/vastsa/FileCodeBox/blob/master/LICENSE)
[![Docker Pulls](https://img.shields.io/docker/pulls/lanol/filecodebox?style=flat-square&logo=docker)](https://hub.docker.com/r/lanol/filecodebox)
[![Python](https://img.shields.io/badge/Python-3.8+-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.68+-009688?style=flat-square&logo=fastapi&logoColor=white)](https://fastapi.tiangolo.com)
[![Vue.js](https://img.shields.io/badge/Vue.js-3.x-4FC08D?style=flat-square&logo=vue.js&logoColor=white)](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>
---
## 🚀 更新计划
- [ ] 切片上传,同文件秒传,断点续传
- [x] 适配子目录
- [x] 用户登录重构
- [x] webdav存储
- [x] 存储支持自定义路径
- [x] s3优化,不修改昵称为uuid,新建目录
## 目录
- [项目简介](#-项目简介)
- [功能特性](#-功能特性)
- [界面预览](#-界面预览)
- [快速开始](#-快速开始)
- [使用指南](#-使用指南)
- [开发指南](#-开发指南)
- [常见问题](#-常见问题)
- [贡献指南](#-贡献指南)
- [项目统计](#-项目统计)
- [免责声明](#-免责声明)
---
## 📝 项目简介
FileCodeBox 是一个基于 FastAPI + Vue3 开发的轻量级文件分享工具。它允许用户通过简单的方式分享文本和文件,接收者只需要一个提取码就可以取得文件,就像从快递柜取出快递一样简单。
FileCodeBox 是一个轻量级的文件分享工具,基于 **FastAPI + Vue3** 开发。用户可以通过简单的方式匿名分享文本和文件,接收者只需输入提取码即可获取内容——就像从快递柜取出快递一样简单。
## 🖼️ 功能预览
### 应用场景
<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>
&nbsp;&nbsp;&nbsp;&nbsp;
<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**
```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**
```yaml
services:
filecodebox:
image: lanol/filecodebox:latest
container_name: filecodebox
restart: unless-stopped
ports:
- "12345:12345"
volumes:
- ./data:/app/data
environment:
- WORKERS=4
- LOG_LEVEL=info
```
```bash
docker compose up -d
```
**环境变量说明**
| 变量 | 默认值 | 说明 |
|------|--------|------|
| `HOST` | `::` | 监听地址(支持 IPv4/IPv6 双栈) |
| `PORT` | `12345` | 服务端口 |
| `WORKERS` | `4` | 工作进程数(建议设为 CPU 核心数) |
| `LOG_LEVEL` | `info` | 日志级别:`debug` / `info` / `warning` / `error` |
### 反向代理配置
使用 Nginx 时,请添加以下配置以正确获取客户端 IP:
```nginx
location / {
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; # 根据需要调整上传大小限制
}
```
### 手动部署
1. 克隆项目
```bash
# 1. 克隆项目
git clone https://github.com/vastsa/FileCodeBox.git
```
2. 安装依赖
```bash
cd FileCodeBox
pip install -r requirements.txt
```
3. 启动服务
```bash
# 2. 安装依赖
pip install -r requirements.txt
# 3. 启动服务
python main.py
```
## 📖 使用说明
---
### 分享文件
1. 打开网页,点击"分享文件"
2. 选择或拖拽文件
3. 设置过期时间和次数
4. 获取提取码
## 📖 使用指南
### 获取文件
1. 打开网页,输入提取码
2. 点击获取
3. 下载文件或查看文本
### 基础操作
### 管理面板
1. 访问 `/admin`
2. 输入管理员密码
3. 管理文件和配置
| 操作 | 步骤 |
|------|------|
| **分享文件** | 打开网页 → 选择/拖拽文件 → 设置有效期 → 获取提取码 |
| **获取文件** | 打开网页 → 输入提取码 → 下载文件或查看文本 |
| **管理后台** | 首次访问站点完成初始化 → 访问 `/#/admin` → 输入初始化时设置的密码 |
### 命令行使用(curl)
<details>
<summary><b>点击展开 curl 使用示例</b></summary>
**上传文件**
```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": "<初始化时设置的管理员密码>"}'
# 2. 携带 token 上传
curl -X POST "http://localhost:12345/share/file/" \
-H "Authorization: Bearer <token>" \
-F "file=@/path/to/file.txt"
```
</details>
---
## 🛠 开发指南
### 项目结构
```
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: 如何修改上传大小限制?
A: 在管理面板中修改配置项 `uploadSize`
<details>
<summary><b>如何修改上传大小限制?</b></summary>
### Q: 如何配置存储引擎?
A: 在管理面板中选择存储引擎并配置相应参数
在管理面板中修改 `uploadSize` 配置项。如果使用 Nginx 反向代理,还需修改 `client_max_body_size`。
</details>
### Q: 如何备份数据?
A: 备份 `data` 目录即可
<details>
<summary><b>如何配置存储引擎?</b></summary>
更多问题请访问 [Wiki](https://github.com/vastsa/FileCodeBox/wiki/常见问题)
在管理面板中选择存储引擎类型并配置相应参数。支持本地存储、S3、OneDrive、OpenDAL 等。
</details>
<details>
<summary><b>如何备份数据?</b></summary>
备份 `data` 目录即可,包含数据库和上传的文件。
</details>
<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>
![Repobeats](https://repobeats.axiom.co/api/embed/7a6c92f1d96ee57e6fb67f0df371528397b0c9ac.svg)
[![Star History](https://api.star-history.com/svg?repos=vastsa/FileCodeBox&type=Date)](https://star-history.com/#vastsa/FileCodeBox&Date)
</div>
---
## 🗓 更新计划
- [ ] 2025 年新皮肤
- [ ] 文件收集功能
---
## 📜 免责声明
本项目开源仅供学习使用,不得用于任何违法用途,否则后果自负,与作者无关。使用时请保留项目地址和版权信息。
本项目开源仅供学习交流使用,不得用于任何违法用途,否则后果自负,与作者无关。使用本项目时请保留项目地址和版权信息。
---
<div align="center">
**如果觉得项目不错,欢迎 ⭐ Star 支持!**
Made with ❤️ by [vastsa](https://github.com/vastsa)
</div>
+382 -200
View File
@@ -1,289 +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
[![GitHub stars](https://img.shields.io/github/stars/vastsa/FileCodeBox)](https://github.com/vastsa/FileCodeBox/stargazers)
[![GitHub forks](https://img.shields.io/github/forks/vastsa/FileCodeBox)](https://github.com/vastsa/FileCodeBox/network)
[![GitHub issues](https://img.shields.io/github/issues/vastsa/FileCodeBox)](https://github.com/vastsa/FileCodeBox/issues)
[![GitHub license](https://img.shields.io/github/license/vastsa/FileCodeBox)](https://github.com/vastsa/FileCodeBox/blob/master/LICENSE)
[![QQ Group](https://img.shields.io/badge/QQ%20Group-739673698-blue.svg)](https://qm.qq.com/q/PemPzhdEIM)
[![Python Version](https://img.shields.io/badge/Python-3.8+-blue.svg)](https://www.python.org)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.68+-green.svg)](https://fastapi.tiangolo.com)
[![Vue Version](https://img.shields.io/badge/Vue.js-3.x-brightgreen.svg)](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
[![GitHub stars](https://img.shields.io/github/stars/vastsa/FileCodeBox?style=flat-square&logo=github)](https://github.com/vastsa/FileCodeBox/stargazers)
[![GitHub forks](https://img.shields.io/github/forks/vastsa/FileCodeBox?style=flat-square&logo=github)](https://github.com/vastsa/FileCodeBox/network)
[![GitHub issues](https://img.shields.io/github/issues/vastsa/FileCodeBox?style=flat-square&logo=github)](https://github.com/vastsa/FileCodeBox/issues)
[![GitHub license](https://img.shields.io/github/license/vastsa/FileCodeBox?style=flat-square)](https://github.com/vastsa/FileCodeBox/blob/master/LICENSE)
[![Docker Pulls](https://img.shields.io/docker/pulls/lanol/filecodebox?style=flat-square&logo=docker)](https://hub.docker.com/r/lanol/filecodebox)
[![Python](https://img.shields.io/badge/Python-3.8+-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.128+-009688?style=flat-square&logo=fastapi&logoColor=white)](https://fastapi.tiangolo.com)
[![Vue.js](https://img.shields.io/badge/Vue.js-3.x-4FC08D?style=flat-square&logo=vue.js&logoColor=white)](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>
&nbsp;&nbsp;&nbsp;&nbsp;
<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)
**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
```
**Option 2: Docker Compose**
```yaml
services:
filecodebox:
image: lanol/filecodebox:latest
container_name: filecodebox
restart: unless-stopped
ports:
- "12345:12345"
volumes:
- ./data:/app/data
environment:
- WORKERS=4
- LOG_LEVEL=info
```
```bash
docker compose up -d
```
**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_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
pip install -r requirements.txt
```
3. Start the service
```bash
# 2. Install dependencies
pip install -r requirements.txt
# 3. Start the service
python main.py
```
---
## 📖 Usage Guide
### Share Files
1. Open the website, click "Share File"
2. Select or drag files
3. Set expiration time and count
4. Get the passcode
### Basic Operations
### Retrieve Files
1. Open the website, enter passcode
2. Click retrieve
3. Download file or view text
| 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** | Complete first-run setup → Visit `/#/admin` → Enter the password set during setup |
### Admin Panel
1. Visit `/admin`
2. Enter admin password
3. Manage files and settings
### Command Line Usage (curl)
## 🛠 Development Guide
<details>
<summary><b>Click to expand curl examples</b></summary>
**Upload File**
```bash
# Basic upload (default 1 day expiration)
curl -X POST "http://localhost:12345/share/file/" \
-F "file=@/path/to/file.txt"
# 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": "<admin-password-set-during-setup>"}'
# 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?
A: Change `uploadSize` in admin panel
<details>
<summary><b>How to modify upload size limit?</b></summary>
### Q: How to configure storage engine?
A: Select storage engine and configure parameters 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 backup data?
A: Backup the `data` directory
<details>
<summary><b>How to configure storage engine?</b></summary>
For more questions, visit [Wiki](https://github.com/vastsa/FileCodeBox/wiki/常见问题)
Select the storage engine type and configure parameters in the admin panel. Supports local storage, S3, OneDrive, OpenDAL, etc.
</details>
## �� Project Statistics and Analytics
<details>
<summary><b>How to backup data?</b></summary>
Backup the `data` directory, which contains the database and uploaded files.
</details>
<details>
<summary><b>How to change admin password?</b></summary>
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>
![Repobeats](https://repobeats.axiom.co/api/embed/7a6c92f1d96ee57e6fb67f0df371528397b0c9ac.svg)
[![Star History](https://api.star-history.com/svg?repos=vastsa/FileCodeBox&type=Date)](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 -8
View File
@@ -1,8 +1,8 @@
aioboto3==11.2.0
aiohttp==3.10.11
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
+221
View File
@@ -0,0 +1,221 @@
import asyncio
import copy
import unittest
import apps.admin.services as admin_services
import core.config as core_config
from apps.admin.dependencies import create_token, verify_token
from apps.admin.services import ConfigService
from main import parse_setup_options
from core.security import (
LEGACY_DEFAULT_ADMIN_TOKEN,
is_config_initialized,
prepare_security_config,
)
from core.settings import DEFAULT_CONFIG, settings
from core.utils import hash_password, verify_password
class SettingsOverrideMixin:
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
class SecurityConfigTests(unittest.TestCase):
def test_initial_security_config_requires_setup_and_generates_jwt_secret(self):
result = prepare_security_config(DEFAULT_CONFIG)
self.assertTrue(result.changed)
self.assertTrue(result.setup_required)
self.assertEqual(result.config["admin_token"], "")
self.assertFalse(is_config_initialized(result.config))
self.assertGreaterEqual(len(result.config["jwt_secret"]), 32)
def test_legacy_default_password_requires_setup(self):
config = copy.deepcopy(DEFAULT_CONFIG)
config["admin_token"] = hash_password(LEGACY_DEFAULT_ADMIN_TOKEN)
config["jwt_secret"] = "j" * 48
result = prepare_security_config(config)
self.assertTrue(result.setup_required)
self.assertEqual(result.config["admin_token"], "")
self.assertEqual(result.config["jwt_secret"], "j" * 48)
def test_custom_plaintext_password_is_hashed_and_initialized(self):
config = copy.deepcopy(DEFAULT_CONFIG)
config["admin_token"] = "custom-password"
config["jwt_secret"] = "j" * 48
result = prepare_security_config(config)
self.assertTrue(result.password_hashed)
self.assertTrue(is_config_initialized(result.config))
self.assertTrue(verify_password("custom-password", result.config["admin_token"]))
class SetupOptionTests(unittest.TestCase):
def test_parse_setup_options_converts_common_fields(self):
options = parse_setup_options(
{
"upload_size_value": "20",
"upload_size_unit": "MB",
"save_time_value": "7",
"save_time_unit": "day",
"uploadCount": "30",
"uploadMinute": "2",
"errorCount": "5",
"errorMinute": "1",
"openUpload": ["0", "1"],
"enableChunk": "0",
"code_generate_type": "secret",
"expireStyle": ["day", "count"],
"allowed_file_types": ".zip, image/*",
}
)
self.assertEqual(options["uploadSize"], 20 * 1024 * 1024)
self.assertEqual(options["max_save_seconds"], 7 * 86400)
self.assertEqual(options["uploadCount"], 30)
self.assertEqual(options["uploadMinute"], 2)
self.assertEqual(options["errorCount"], 5)
self.assertEqual(options["errorMinute"], 1)
self.assertEqual(options["openUpload"], 1)
self.assertEqual(options["enableChunk"], 0)
self.assertEqual(options["code_generate_type"], "secret")
self.assertEqual(options["expireStyle"], ["day", "count"])
self.assertEqual(options["allowed_file_types"], [".zip", "image/*"])
def test_parse_setup_options_allows_turning_guest_upload_off(self):
options = parse_setup_options(
{
"openUpload": "0",
"expireStyle": ["day"],
}
)
self.assertEqual(options["openUpload"], 0)
def test_parse_setup_options_requires_expire_style(self):
with self.assertRaises(ValueError):
parse_setup_options({"expireStyle": []})
class AdminJwtTests(SettingsOverrideMixin, unittest.TestCase):
def test_admin_jwt_signature_uses_independent_secret(self):
settings.admin_token = hash_password("old-admin-password")
settings.jwt_secret = "j" * 48
token = create_token({"is_admin": True}, expires_in=60)
self.assertTrue(verify_token(token)["is_admin"])
settings.admin_token = hash_password("new-admin-password")
self.assertTrue(verify_token(token)["is_admin"])
settings.jwt_secret = "k" * 48
with self.assertRaises(ValueError):
verify_token(token)
class FakeKeyValue:
saved_value = None
@classmethod
async def update_or_create(cls, key, defaults):
cls.saved_value = defaults["value"]
return None, True
async def fake_refresh_settings():
return None
class FakeConfigRecord:
def __init__(self, value):
self.value = value
class FakeConfigQuery:
async def first(self):
return FakeConfigKeyValue.record
class FakeConfigKeyValue:
record = None
saved_value = None
@classmethod
def filter(cls, key):
return FakeConfigQuery()
@classmethod
async def update_or_create(cls, key, defaults):
cls.saved_value = defaults["value"]
return None, True
class ConfigServiceSecurityTests(SettingsOverrideMixin, unittest.TestCase):
def test_admin_password_update_rotates_jwt_secret(self):
old_secret = "j" * 48
settings.user_config = {
**copy.deepcopy(DEFAULT_CONFIG),
"admin_token": hash_password("old-admin-password"),
"jwt_secret": old_secret,
}
original_key_value = admin_services.KeyValue
original_refresh_settings = admin_services.refresh_settings
admin_services.KeyValue = FakeKeyValue
admin_services.refresh_settings = fake_refresh_settings
FakeKeyValue.saved_value = None
try:
asyncio.run(ConfigService().update_config({"admin_token": "new-admin-password"}))
finally:
admin_services.KeyValue = original_key_value
admin_services.refresh_settings = original_refresh_settings
self.assertIsNotNone(FakeKeyValue.saved_value)
self.assertTrue(verify_password("new-admin-password", FakeKeyValue.saved_value["admin_token"]))
self.assertNotEqual(FakeKeyValue.saved_value["jwt_secret"], old_secret)
self.assertGreaterEqual(len(FakeKeyValue.saved_value["jwt_secret"]), 32)
def test_initialize_system_sets_admin_password_and_jwt_secret(self):
original_key_value = core_config.KeyValue
original_refresh_settings = core_config.refresh_settings
FakeConfigKeyValue.record = FakeConfigRecord(
{
**copy.deepcopy(DEFAULT_CONFIG),
"admin_token": "",
"jwt_secret": "",
}
)
FakeConfigKeyValue.saved_value = None
core_config.KeyValue = FakeConfigKeyValue
core_config.refresh_settings = fake_refresh_settings
try:
asyncio.run(
core_config.initialize_system(
admin_password="new-admin-password",
site_name="我的文件快递柜",
setup_options={
"uploadSize": 50 * 1024 * 1024,
"errorCount": 6,
"expireStyle": ["day", "count"],
},
)
)
finally:
core_config.KeyValue = original_key_value
core_config.refresh_settings = original_refresh_settings
self.assertIsNotNone(FakeConfigKeyValue.saved_value)
self.assertTrue(
verify_password("new-admin-password", FakeConfigKeyValue.saved_value["admin_token"])
)
self.assertGreaterEqual(len(FakeConfigKeyValue.saved_value["jwt_secret"]), 32)
self.assertEqual(FakeConfigKeyValue.saved_value["name"], "我的文件快递柜")
self.assertEqual(FakeConfigKeyValue.saved_value["uploadSize"], 50 * 1024 * 1024)
self.assertEqual(FakeConfigKeyValue.saved_value["errorCount"], 6)
self.assertEqual(FakeConfigKeyValue.saved_value["expireStyle"], ["day", "count"])
+33
View File
@@ -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)
+65
View File
@@ -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"])
+31
View File
@@ -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)
+34
View File
@@ -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")
+53
View File
@@ -0,0 +1,53 @@
import asyncio
import unittest
from fastapi import HTTPException
from core.settings import BASE_DIR, 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 get_theme_index_asset(self, theme: str) -> str:
assets = sorted((BASE_DIR / theme / "assets").glob("index-*.js"))
self.assertTrue(assets, f"{theme} 缺少 index JS 资源")
return assets[0].name
def test_resolves_assets_from_current_theme(self):
settings.themesSelect = "themes/2023"
theme_2023_asset = resolve_theme_file(
"assets", self.get_theme_index_asset("themes/2023")
)
settings.themesSelect = "themes/2024"
theme_2024_asset = resolve_theme_file(
"assets", self.get_theme_index_asset("themes/2024")
)
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)
+46
View File
@@ -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)
-1
View File
@@ -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-5orz1M6_.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
View File
@@ -1 +0,0 @@
import{k as ie,T as Ke,t as ce,E as Qe,b as Xe}from"./el-input-D_xPEeA2.js";import{E as Ye,a as Ze}from"./el-form-item-CzDqJHnU.js";import"./el-tooltip-l0sNRNKZ.js";import{E as Pe,C as Je}from"./el-popper-DxfKqvb2.js";import{u as et,a as tt}from"./index-CX7K5KgQ.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-5orz1M6_.js";import{f as Mt}from"./vnode-DkiIqzI4.js";import"./_baseClone-IT_4yc7W.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-D_xPEeA2.js";import{u as _g,a as mg}from"./index-CX7K5KgQ.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-5orz1M6_.js";import{e as Fg,f as Bg,g as Ug,E as Gg,h as Yg,d as qg}from"./config-C0oXmCul.js";import{E as zg}from"./el-tag-DsWzxe9q.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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}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
-14
View File
@@ -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-D_xPEeA2.js";import"./el-tag-DsWzxe9q.js";import{b as _n,i as wl,a as $n,E as Wn,d as dt,c as Sl}from"./el-select-lHlEhHIn.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-DxfKqvb2.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-5orz1M6_.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
View File
@@ -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
View File
@@ -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
View File
@@ -1 +0,0 @@
import{o as he,E as Ae,a as We,b as Re,u as Ce}from"./el-input-D_xPEeA2.js";import{E as Xe,u as Ye,a as xe,b as Je,c as Qe,d as en}from"./config-C0oXmCul.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-5orz1M6_.js";import{u as wn,a as En,_ as kn}from"./CardTools.vue_vue_type_script_setup_true_lang-CMcmqUZX.js";import"./vnode-DkiIqzI4.js";import"./el-tag-DsWzxe9q.js";import"./index-CX7K5KgQ.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.
Loaded 100 of 182 files, more files were not shown because too many files have changed in this diff. Show more