Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1ec397af0c | ||
|
|
eb6fc627ae | ||
|
|
c1fb802223 | ||
|
|
1d03337e2f | ||
|
|
8d6eaacb70 | ||
|
|
3fe136536e | ||
|
|
aa6904a12c | ||
|
|
135dfdda9d | ||
|
|
e3ea7825bf | ||
|
|
6759539078 | ||
|
|
530f52aa1e | ||
|
|
b859ec211e | ||
|
|
8ac367d0b8 | ||
|
|
63cf725802 | ||
|
|
ccbc710d74 | ||
|
|
2d18b02005 | ||
|
|
e75fe596d0 | ||
|
|
be7ce2b30e | ||
|
|
0dbb594f4a | ||
|
|
b6aa28c345 | ||
|
|
fc6046a663 | ||
|
|
3467e973ac | ||
|
|
a1de598277 | ||
|
|
1ba0d2a044 | ||
|
|
1f0b0b791c | ||
|
|
4ae53fc4a5 | ||
|
|
35e069ccc3 | ||
|
|
2fa1faebe0 | ||
|
|
0ced9b1f38 | ||
|
|
1eb69e4cc5 | ||
|
|
71fc1ad8ea | ||
|
|
64ebc59a84 | ||
|
|
78b1dbe81f | ||
|
|
6805206efd | ||
|
|
6fe68be2dd | ||
|
|
0d71b914e4 | ||
|
|
20fcf0c3df | ||
|
|
75d345e5d0 | ||
|
|
a0c453b014 | ||
|
|
1cc901d2b9 | ||
|
|
e7b5792602 | ||
|
|
843a237fad | ||
|
|
4a9bf3a3a0 | ||
|
|
0504e6e4dc | ||
|
|
24d49e1c9a | ||
|
|
c380778336 | ||
|
|
f1c09b0b20 | ||
|
|
a3f599fe51 | ||
|
|
2e5dc532a0 | ||
|
|
7f46c58898 | ||
|
|
5a889bab47 | ||
|
|
5fee1c7b86 | ||
|
|
73017935e9 | ||
|
|
a35b3c8262 | ||
|
|
da5dc378a7 | ||
|
|
d170ca8005 | ||
|
|
0fe01c98db | ||
|
|
d5b0327f90 | ||
|
|
9120486449 | ||
|
|
f5a5e03269 | ||
|
|
ade5799db4 | ||
|
|
6b728abbeb | ||
|
|
ff1943d60c | ||
|
|
442ef5b0e0 | ||
|
|
34e36944bd | ||
|
|
ba8802ad75 | ||
|
|
bf43727531 | ||
|
|
d49a61d06e | ||
|
|
3074d9ba2e | ||
|
|
81ee640353 | ||
|
|
e87bcfcce5 | ||
|
|
e80be564a5 | ||
|
|
69972e28b3 | ||
|
|
8cdb972583 | ||
|
|
736e16a9f6 | ||
|
|
8e57a497f7 | ||
|
|
287d9aeedb | ||
|
|
f1a16a115a | ||
|
|
b2bfc045c2 | ||
|
|
900541baa5 | ||
|
|
8b813a2eaa | ||
|
|
4920b4b5db | ||
|
|
268f1537bb | ||
|
|
41b01b3faa | ||
|
|
c02fb7ce20 | ||
|
|
95f5e0dfbc | ||
|
|
e854eb068c | ||
|
|
c1966b3942 | ||
|
|
a20a0beb79 | ||
|
|
d7200f6b9b | ||
|
|
bd6f646f5d | ||
|
|
6eac746e83 | ||
|
|
5f82650c36 | ||
|
|
d3fe7b223e | ||
|
|
2d79fa5acd | ||
|
|
387f023372 | ||
|
|
e51380003c | ||
|
|
e41b3e1688 | ||
|
|
7be3b27415 | ||
|
|
bdab5bb375 | ||
|
|
c0984bfb1f | ||
|
|
62d1a23695 | ||
|
|
9a80d7a9e0 | ||
|
|
eeb70c7f44 | ||
|
|
136ea5830f | ||
|
|
c430af3d82 | ||
|
|
6fcf26fcbe | ||
|
|
f6649ecc81 | ||
|
|
3005ed1298 | ||
|
|
a23409f0af | ||
|
|
f7876c6e48 | ||
|
|
7c6aedb96e | ||
|
|
7ed09e2455 | ||
|
|
9f8e6d401f | ||
|
|
c4304d3525 | ||
|
|
e92ff30d8c | ||
|
|
fd913ababc | ||
|
|
45be97a258 | ||
|
|
fbd741ebcf | ||
|
|
e341e1afae | ||
|
|
4037ddb3b1 | ||
|
|
72190331b9 | ||
|
|
566dc3b94f | ||
|
|
cf96071167 | ||
|
|
ffe89060f4 | ||
|
|
79c1e0f949 | ||
|
|
df6722ac26 | ||
|
|
e897dbfe97 | ||
|
|
168ca8383f | ||
|
|
4d1cd4cbfc | ||
|
|
c61c2ee7fe | ||
|
|
548d625827 | ||
|
|
792f7a8a12 | ||
|
|
a65cf32214 | ||
|
|
4a50908455 | ||
|
|
c4e398bd31 | ||
|
|
39264cc32e | ||
|
|
7a15b6a44d | ||
|
|
591441e9a7 | ||
|
|
60756749b7 | ||
|
|
fdada809d9 | ||
|
|
17331112b4 | ||
|
|
94c9c30f98 | ||
|
|
69fc66e926 | ||
|
|
4d7c9deabf | ||
|
|
731b6319d0 | ||
|
|
d178ab04a2 | ||
|
|
7ea1fe2e90 | ||
|
|
13b5306a02 | ||
|
|
799b49b81d | ||
|
|
6eeb1c50a5 | ||
|
|
1ff1d6c695 | ||
|
|
19b289d62b | ||
|
|
46a4fb70e0 | ||
|
|
2d3dcad3ad | ||
|
|
93b005bf5a | ||
|
|
96f68f457c | ||
|
|
94da526e23 | ||
|
|
36fe69e2a7 | ||
|
|
fa85521cfb | ||
|
|
d1f10a33fb | ||
|
|
4f0df03691 | ||
|
|
dbfe98ec4a | ||
|
|
aef7879612 | ||
|
|
6913132074 | ||
|
|
802d2551ff | ||
|
|
78c612c660 | ||
|
|
d35c84cc43 | ||
|
|
0d1aa81d70 | ||
|
|
cbc356ae91 | ||
|
|
ede0e62f32 | ||
|
|
f2f301f515 | ||
|
|
8973abdf2f | ||
|
|
0783f47555 | ||
|
|
037949b715 | ||
|
|
913acff5c5 | ||
|
|
0add20e722 | ||
|
|
964d091d0b | ||
|
|
7ca840cfa1 | ||
|
|
340db7fba3 | ||
|
|
1cb7d2c91c | ||
|
|
0786eb9e44 | ||
|
|
6157f0a8b2 | ||
|
|
191ac220ce | ||
|
|
3145302771 | ||
|
|
541647696d | ||
|
|
e6913960e2 | ||
|
|
828368a9e2 | ||
|
|
0c393a9890 | ||
|
|
8da960b6ca | ||
|
|
c0c1438f11 | ||
|
|
3592db09ab | ||
|
|
63b5be31e8 | ||
|
|
5238975484 | ||
|
|
59f9b119b5 | ||
|
|
651e9c5936 | ||
|
|
ae2d9f0847 | ||
|
|
efbfec2471 | ||
|
|
c40aca30b2 | ||
|
|
9348a7bcea | ||
|
|
7a4fc100c5 | ||
|
|
a884bf19b0 | ||
|
|
bf758ea3f3 | ||
|
|
b72c621dcd | ||
|
|
72ad733355 | ||
|
|
f0aca7da16 | ||
|
|
c93c5b0924 | ||
|
|
799b89dada | ||
|
|
4a48f6d5e3 | ||
|
|
529f314856 | ||
|
|
abe7581803 | ||
|
|
019684787a | ||
|
|
a50753e070 | ||
|
|
f0e7304bb2 | ||
|
|
9ba7d37796 | ||
|
|
3abe660d48 | ||
|
|
2093f19638 | ||
|
|
5ba9eba8eb | ||
|
|
e4aaafb2ad | ||
|
|
7c98046355 | ||
|
|
cc3a521d31 | ||
|
|
fd1eea7779 | ||
|
|
38c78ced14 | ||
|
|
dcd30caf26 | ||
|
|
18cf3f9a48 | ||
|
|
5051184a4d | ||
|
|
2bef407373 | ||
|
|
6c2f2caee0 | ||
|
|
d988d5bc98 | ||
|
|
83598956a1 | ||
|
|
0dca661508 | ||
|
|
3312ed72e6 | ||
|
|
f430243b27 | ||
|
|
a8a230c9f7 | ||
|
|
8d62f6ec33 | ||
|
|
6e910a6a16 | ||
|
|
a36198e1a1 | ||
|
|
fafc56bc32 | ||
|
|
8136c85c2a | ||
|
|
3edc8c959d | ||
|
|
e421ab93bc | ||
|
|
8afae1f567 | ||
|
|
b3004a305a | ||
|
|
af83340bc0 | ||
|
|
13009782b3 | ||
|
|
51b5d5e78f | ||
|
|
9ffad404d1 | ||
|
|
282f44e257 | ||
|
|
7804e36b0d | ||
|
|
cc028a4def | ||
|
|
c993077033 | ||
|
|
322e8a183a | ||
|
|
fe3bc5959f | ||
|
|
8bbdd0a734 | ||
|
|
277b98b7cb | ||
|
|
174ecb3fa2 | ||
|
|
174fb1c3f5 | ||
|
|
eab9f59008 | ||
|
|
454a4ac314 | ||
|
|
7632402b6f | ||
|
|
73f1e5af50 | ||
|
|
57e5084ae1 | ||
|
|
5086f13581 | ||
|
|
8b7327f548 | ||
|
|
2add291366 | ||
|
|
5202a6df2b | ||
|
|
3ca77ac8bf | ||
|
|
271a38fc96 | ||
|
|
eebbb9ae2e | ||
|
|
9ea264df46 | ||
|
|
06d1e4ff78 | ||
|
|
dac9a769c5 | ||
|
|
ea05fe1317 | ||
|
|
40e2335976 |
No files matched your search
@@ -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/
|
||||
@@ -1,2 +0,0 @@
|
||||
custom: ["http://afdian.net/a/filecodebox"]
|
||||
|
||||
|
After Width: | Height: | Size: 205 KiB |
|
After Width: | Height: | Size: 679 KiB |
|
After Width: | Height: | Size: 684 KiB |
|
After Width: | Height: | Size: 411 KiB |
|
After Width: | Height: | Size: 431 KiB |
|
After Width: | Height: | Size: 674 KiB |
|
After Width: | Height: | Size: 678 KiB |
|
After Width: | Height: | Size: 219 KiB |
@@ -5,47 +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:beta
|
||||
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
|
||||
@@ -0,0 +1,69 @@
|
||||
# 构建 VitePress 站点并将其部署到 GitHub Pages 的示例工作流程
|
||||
#
|
||||
name: Deploy VitePress site to Pages
|
||||
|
||||
on:
|
||||
# 在针对 `main` 分支的推送上运行。如果你
|
||||
# 使用 `master` 分支作为默认分支,请将其更改为 `master`
|
||||
push:
|
||||
branches: [ master ]
|
||||
|
||||
# 允许你从 Actions 选项卡手动运行此工作流程
|
||||
workflow_dispatch:
|
||||
|
||||
# 设置 GITHUB_TOKEN 的权限,以允许部署到 GitHub Pages
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
# 只允许同时进行一次部署,跳过正在运行和最新队列之间的运行队列
|
||||
# 但是,不要取消正在进行的运行,因为我们希望允许这些生产部署完成
|
||||
concurrency:
|
||||
group: pages
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
# 构建工作
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # 如果未启用 lastUpdated,则不需要
|
||||
- uses: pnpm/action-setup@v3
|
||||
with:
|
||||
version: 9
|
||||
# - uses: oven-sh/setup-bun@v1 # 如果使用 Bun,请取消注释
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: 'docs/pnpm-lock.yaml'
|
||||
- name: Setup Pages
|
||||
uses: actions/configure-pages@v4
|
||||
- name: Install dependencies
|
||||
working-directory: docs
|
||||
run: pnpm install
|
||||
- name: Build with VitePress
|
||||
working-directory: docs
|
||||
run: pnpm run docs:build
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
with:
|
||||
path: docs/.vitepress/dist
|
||||
|
||||
# 部署工作
|
||||
deploy:
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
name: Deploy
|
||||
steps:
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v4
|
||||
@@ -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/
|
||||
@@ -1,11 +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="vast@tom.com"
|
||||
LABEL email="xzu@live.com"
|
||||
|
||||
COPY . /app
|
||||
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
|
||||
RUN echo 'Asia/Shanghai' >/etc/timezone
|
||||
WORKDIR /app
|
||||
RUN pip install -r requirements.txt
|
||||
|
||||
# 复制项目文件(通过 .dockerignore 排除不必要的文件)
|
||||
COPY . .
|
||||
|
||||
# 设置时区
|
||||
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 '*'"]
|
||||
@@ -0,0 +1,144 @@
|
||||
# @Time : 2023/8/15 17:43
|
||||
# @Author : Lan
|
||||
# @File : depends.py
|
||||
# @Software: PyCharm
|
||||
from fastapi import Header, HTTPException, Depends
|
||||
from fastapi.requests import Request
|
||||
import base64
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
from core.settings import settings
|
||||
from apps.admin.services import FileService, ConfigService, LocalFileService
|
||||
|
||||
|
||||
def create_token(data: dict, expires_in: int = 3600 * 24 * 30) -> str:
|
||||
"""
|
||||
创建JWT token
|
||||
:param data: 数据负载
|
||||
:param expires_in: 过期时间(秒)
|
||||
"""
|
||||
header = base64.b64encode(
|
||||
json.dumps({"alg": "HS256", "typ": "JWT"}).encode()
|
||||
).decode()
|
||||
payload = base64.b64encode(
|
||||
json.dumps({**data, "exp": int(time.time()) + expires_in}).encode()
|
||||
).decode()
|
||||
|
||||
signature = hmac.new(
|
||||
settings.admin_token.encode(), f"{header}.{payload}".encode(), "sha256"
|
||||
).digest()
|
||||
signature = base64.b64encode(signature).decode()
|
||||
|
||||
return f"{header}.{payload}.{signature}"
|
||||
|
||||
|
||||
def verify_token(token: str) -> dict:
|
||||
"""
|
||||
验证JWT token
|
||||
:param token: JWT token
|
||||
:return: 解码后的数据
|
||||
"""
|
||||
try:
|
||||
header_b64, payload_b64, signature_b64 = token.split(".")
|
||||
|
||||
# 验证签名
|
||||
expected_signature = hmac.new(
|
||||
settings.admin_token.encode(),
|
||||
f"{header_b64}.{payload_b64}".encode(),
|
||||
"sha256",
|
||||
).digest()
|
||||
expected_signature_b64 = base64.b64encode(expected_signature).decode()
|
||||
|
||||
if not hmac.compare_digest(signature_b64, expected_signature_b64):
|
||||
raise ValueError("无效的签名")
|
||||
|
||||
# 解码payload
|
||||
payload = json.loads(base64.b64decode(payload_b64))
|
||||
|
||||
# 检查是否过期
|
||||
if payload.get("exp", 0) < time.time():
|
||||
raise ValueError("token已过期")
|
||||
|
||||
return payload
|
||||
except Exception as e:
|
||||
raise ValueError(f"token验证失败: {str(e)}")
|
||||
|
||||
|
||||
def _extract_bearer_token(authorization: str) -> str:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise HTTPException(status_code=401, detail="未授权或授权校验失败")
|
||||
token = authorization.split(" ", 1)[1].strip()
|
||||
if not token:
|
||||
raise HTTPException(status_code=401, detail="未授权或授权校验失败")
|
||||
return token
|
||||
|
||||
|
||||
def _require_admin_payload(authorization: str) -> dict:
|
||||
token = _extract_bearer_token(authorization)
|
||||
try:
|
||||
payload = verify_token(token)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=401, detail=str(e))
|
||||
if not payload.get("is_admin", False):
|
||||
raise HTTPException(status_code=401, detail="未授权或授权校验失败")
|
||||
return payload
|
||||
|
||||
|
||||
def get_admin_session(authorization: str = Header(default=None)) -> dict:
|
||||
token = _extract_bearer_token(authorization)
|
||||
payload = _require_admin_payload(authorization)
|
||||
return {
|
||||
"id": "admin",
|
||||
"username": "admin",
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": payload.get("exp"),
|
||||
}
|
||||
|
||||
|
||||
ADMIN_PUBLIC_ENDPOINTS = {("POST", "/admin/login")}
|
||||
|
||||
|
||||
async def admin_required(
|
||||
authorization: str = Header(default=None), request: Request = None
|
||||
):
|
||||
"""
|
||||
验证管理员权限
|
||||
"""
|
||||
if request and (request.method, request.url.path) in ADMIN_PUBLIC_ENDPOINTS:
|
||||
return None
|
||||
return _require_admin_payload(authorization)
|
||||
|
||||
|
||||
async def share_required_login(authorization: str = Header(default=None)):
|
||||
"""
|
||||
验证分享上传权限
|
||||
|
||||
当settings.openUpload为False时,要求用户必须登录并具有管理员权限
|
||||
当settings.openUpload为True时,允许游客上传
|
||||
|
||||
:param authorization: 认证头信息
|
||||
:param request: 请求对象
|
||||
:return: 验证结果
|
||||
"""
|
||||
if not settings.openUpload:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise HTTPException(
|
||||
status_code=403, detail="本站未开启游客上传,如需上传请先登录后台"
|
||||
)
|
||||
_require_admin_payload(authorization)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
async def get_file_service():
|
||||
return FileService()
|
||||
|
||||
|
||||
async def get_config_service():
|
||||
return ConfigService()
|
||||
|
||||
|
||||
async def get_local_file_service():
|
||||
return LocalFileService()
|
||||
@@ -1,19 +0,0 @@
|
||||
# @Time : 2023/8/15 17:43
|
||||
# @Author : Lan
|
||||
# @File : depends.py
|
||||
# @Software: PyCharm
|
||||
from typing import Union
|
||||
|
||||
from fastapi import Header, HTTPException
|
||||
from fastapi.requests import Request
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
async def admin_required(authorization: Union[str, None] = Header(default=None), request: Request = None):
|
||||
is_admin = authorization == str(settings.admin_token)
|
||||
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='未授权或授权校验失败')
|
||||
@@ -1,5 +0,0 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class IDData(BaseModel):
|
||||
id: int
|
||||
@@ -0,0 +1,74 @@
|
||||
import datetime
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class IDData(BaseModel):
|
||||
id: int
|
||||
|
||||
|
||||
class IDsData(BaseModel):
|
||||
ids: list[int]
|
||||
|
||||
|
||||
class ShareItem(BaseModel):
|
||||
expire_value: int
|
||||
expire_style: str = "day"
|
||||
filename: str
|
||||
|
||||
|
||||
class DeleteItem(BaseModel):
|
||||
filename: str
|
||||
|
||||
|
||||
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
|
||||
@@ -2,81 +2,603 @@
|
||||
# @Author : Lan
|
||||
# @File : views.py
|
||||
# @Software: PyCharm
|
||||
import math
|
||||
import datetime
|
||||
from collections import Counter
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from apps.admin.depends import admin_required
|
||||
from apps.admin.pydantics import IDData
|
||||
from apps.base.models import FileCodes, KeyValue
|
||||
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,
|
||||
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.storage import file_storage
|
||||
from core.utils import get_now, verify_password
|
||||
|
||||
admin_api = APIRouter(
|
||||
prefix='/admin',
|
||||
tags=['管理'],
|
||||
prefix="/admin", tags=["管理"], dependencies=[Depends(admin_required)]
|
||||
)
|
||||
|
||||
|
||||
@admin_api.post('/login', dependencies=[Depends(admin_required)])
|
||||
async def login():
|
||||
def _pick_query_text(*values: Optional[str]) -> Optional[str]:
|
||||
for value in values:
|
||||
normalized_value = str(value or "").strip()
|
||||
if normalized_value:
|
||||
return normalized_value
|
||||
return None
|
||||
|
||||
|
||||
@admin_api.post("/login")
|
||||
async def login(data: LoginData):
|
||||
if not verify_password(data.password, settings.admin_token):
|
||||
raise HTTPException(status_code=401, detail="密码错误")
|
||||
|
||||
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(file_service: FileService = Depends(get_file_service)):
|
||||
all_codes = await FileCodes.all()
|
||||
all_size = sum([code.size for code in all_codes])
|
||||
sys_start = await KeyValue.filter(key="sys_start").first()
|
||||
now = await get_now()
|
||||
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
yesterday_start = today_start - datetime.timedelta(days=1)
|
||||
yesterday_end = today_start - datetime.timedelta(microseconds=1)
|
||||
yesterday_codes = FileCodes.filter(
|
||||
created_at__gte=yesterday_start, created_at__lte=yesterday_end
|
||||
)
|
||||
today_codes = FileCodes.filter(created_at__gte=today_start)
|
||||
yesterday_file_codes = await yesterday_codes
|
||||
today_file_codes = await today_codes
|
||||
expired_count = 0
|
||||
for file_code in all_codes:
|
||||
if await file_code.is_expired():
|
||||
expired_count += 1
|
||||
health_summary = await file_service.build_file_health_summary(all_codes, now=now)
|
||||
|
||||
text_count = sum(1 for file_code in all_codes if file_code.text is not None)
|
||||
chunked_count = sum(1 for file_code in all_codes if file_code.is_chunked)
|
||||
used_count = sum([file_code.used_count for file_code in all_codes])
|
||||
suffix_counter = Counter(
|
||||
"Text" if file_code.text is not None else (file_code.suffix or "file")
|
||||
for file_code in all_codes
|
||||
)
|
||||
recent_file_codes = sorted(
|
||||
all_codes,
|
||||
key=lambda file_code: file_code.created_at.timestamp()
|
||||
if file_code.created_at
|
||||
else 0,
|
||||
reverse=True,
|
||||
)[:8]
|
||||
recent_activities = await file_service.list_admin_activities(limit=8)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"totalFiles": len(all_codes),
|
||||
"storageUsed": 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),
|
||||
):
|
||||
await file_service.delete_file(data.id)
|
||||
return APIResponse()
|
||||
|
||||
|
||||
@admin_api.delete('/file/delete', dependencies=[Depends(admin_required)])
|
||||
async def file_delete(data: IDData):
|
||||
file_code = await FileCodes.get(id=data.id)
|
||||
await file_storage.delete_file(file_code)
|
||||
await file_code.delete()
|
||||
async def batch_delete_files(
|
||||
data: IDsData,
|
||||
file_service: FileService,
|
||||
):
|
||||
if not data.ids:
|
||||
raise HTTPException(status_code=400, detail="请选择要删除的文件")
|
||||
result = await file_service.delete_files(data.ids)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.delete("/file/batch-delete")
|
||||
async def file_batch_delete(
|
||||
data: IDsData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await batch_delete_files(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/batch-delete")
|
||||
async def file_batch_delete_post(
|
||||
data: IDsData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await batch_delete_files(data, file_service)
|
||||
|
||||
|
||||
async def batch_update_files(
|
||||
data: BatchUpdateFileData,
|
||||
file_service: FileService,
|
||||
):
|
||||
if not data.ids:
|
||||
raise HTTPException(status_code=400, detail="请选择要更新的文件")
|
||||
|
||||
update_data = {}
|
||||
fields_set = data.model_fields_set
|
||||
should_clear_expired_at = bool(data.clearExpiredAt or data.clear_expired_at)
|
||||
|
||||
if should_clear_expired_at:
|
||||
update_data["expired_at"] = None
|
||||
update_data["expired_count"] = -1
|
||||
elif "expired_at" in fields_set and data.expired_at != "":
|
||||
update_data["expired_at"] = data.expired_at
|
||||
|
||||
if (
|
||||
not should_clear_expired_at
|
||||
and "expired_count" in fields_set
|
||||
and data.expired_count is not None
|
||||
):
|
||||
update_data["expired_count"] = data.expired_count
|
||||
|
||||
if not update_data:
|
||||
raise HTTPException(status_code=400, detail="请选择要更新的字段")
|
||||
|
||||
result = await file_service.update_files(data.ids, update_data)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.patch("/file/batch-update")
|
||||
async def file_batch_update(
|
||||
data: BatchUpdateFileData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await batch_update_files(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/batch-update")
|
||||
async def file_batch_update_post(
|
||||
data: BatchUpdateFileData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await batch_update_files(data, file_service)
|
||||
|
||||
|
||||
async def apply_file_policy_action(
|
||||
data: FilePolicyActionData,
|
||||
file_service: FileService,
|
||||
):
|
||||
download_limit = data.downloadLimit
|
||||
if download_limit is None:
|
||||
download_limit = data.download_limit
|
||||
|
||||
detail = await file_service.apply_file_policy_action(
|
||||
file_id=data.id,
|
||||
action=data.action,
|
||||
download_limit=download_limit,
|
||||
)
|
||||
return APIResponse(detail=detail)
|
||||
|
||||
|
||||
@admin_api.patch("/file/policy-action")
|
||||
async def file_policy_action(
|
||||
data: FilePolicyActionData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await apply_file_policy_action(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/policy-action")
|
||||
async def file_policy_action_post(
|
||||
data: FilePolicyActionData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await apply_file_policy_action(data, file_service)
|
||||
|
||||
|
||||
async def apply_batch_file_policy_action(
|
||||
data: BatchFilePolicyActionData,
|
||||
file_service: FileService,
|
||||
):
|
||||
if not data.ids:
|
||||
raise HTTPException(status_code=400, detail="请选择要更新的文件")
|
||||
|
||||
download_limit = data.downloadLimit
|
||||
if download_limit is None:
|
||||
download_limit = data.download_limit
|
||||
|
||||
result = await file_service.apply_files_policy_action(
|
||||
file_ids=data.ids,
|
||||
action=data.action,
|
||||
download_limit=download_limit,
|
||||
)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.patch("/file/batch-policy-action")
|
||||
async def file_batch_policy_action(
|
||||
data: BatchFilePolicyActionData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await apply_batch_file_policy_action(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/batch-policy-action")
|
||||
async def file_batch_policy_action_post(
|
||||
data: BatchFilePolicyActionData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await apply_batch_file_policy_action(data, file_service)
|
||||
|
||||
|
||||
@admin_api.get("/file/list")
|
||||
async def file_list(
|
||||
page: int = 1,
|
||||
size: int = 10,
|
||||
keyword: str = "",
|
||||
status: str = "",
|
||||
type: str = "",
|
||||
health: str = "",
|
||||
sortBy: str = "created_at",
|
||||
sortOrder: str = "desc",
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
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),
|
||||
):
|
||||
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),
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
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/list', dependencies=[Depends(admin_required)])
|
||||
async def file_list(page: float = 1, size: int = 10):
|
||||
return APIResponse(detail={
|
||||
'page': page,
|
||||
'size': size,
|
||||
'data': await FileCodes.all().limit(size).offset((math.ceil(page) - 1) * size),
|
||||
'total': await FileCodes.all().count(),
|
||||
})
|
||||
@admin_api.get("/file/download")
|
||||
async def file_download(
|
||||
id: int,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
file_content = await file_service.download_file(id)
|
||||
return file_content
|
||||
|
||||
|
||||
@admin_api.get('/config/get', dependencies=[Depends(admin_required)])
|
||||
async def get_config():
|
||||
return APIResponse(detail=settings.items())
|
||||
@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.patch('/config/update', dependencies=[Depends(admin_required)])
|
||||
async def update_config(data: dict):
|
||||
admin_token = data.get('admin_token')
|
||||
if admin_token is None or admin_token == '':
|
||||
return APIResponse(code=400, detail='管理员密码不能为空')
|
||||
await KeyValue.filter(key='settings').update(value=data)
|
||||
for k, v in data.items():
|
||||
settings.__setattr__(k, v)
|
||||
return APIResponse()
|
||||
@admin_api.get("/local/lists")
|
||||
async def get_local_lists(
|
||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||
):
|
||||
files = await local_file_service.list_files()
|
||||
return APIResponse(detail=files)
|
||||
|
||||
|
||||
# 根据code获取文件
|
||||
async def get_file_by_id(id):
|
||||
# 查询文件
|
||||
file_code = await FileCodes.filter(id=id).first()
|
||||
# 检查文件是否存在
|
||||
@admin_api.delete("/local/delete")
|
||||
async def delete_local_file(
|
||||
item: DeleteItem,
|
||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
result = await local_file_service.delete_file(item.filename)
|
||||
await file_service.record_admin_activity(
|
||||
action="local_file.delete",
|
||||
target_type="local_file",
|
||||
target_name=item.filename,
|
||||
count=1,
|
||||
meta={"success": bool(result)},
|
||||
)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.post("/local/share")
|
||||
async def share_local_file(
|
||||
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:
|
||||
return False, '文件不存在'
|
||||
return True, 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
|
||||
|
||||
@admin_api.get('/file/download', dependencies=[Depends(admin_required)])
|
||||
async def file_download(id: int):
|
||||
has, file_code = await get_file_by_id(id)
|
||||
# 检查文件是否存在
|
||||
if not has:
|
||||
# 返回API响应
|
||||
return APIResponse(code=404, detail='文件不存在')
|
||||
# 如果文件是文本,返回文本内容,否则返回文件响应
|
||||
if file_code.text:
|
||||
return APIResponse(detail=file_code.text)
|
||||
else:
|
||||
return await file_storage.get_file_response(file_code)
|
||||
await file_code.update_from_dict(update_data).save()
|
||||
if update_data:
|
||||
await file_service.record_admin_activity(
|
||||
action="file.update",
|
||||
target_type="file",
|
||||
target_id=data.id,
|
||||
target_name=target_name,
|
||||
count=1,
|
||||
meta={"fields": sorted(update_data.keys())},
|
||||
)
|
||||
return APIResponse(detail="更新成功")
|
||||
@@ -0,0 +1,45 @@
|
||||
from typing import Dict, Union
|
||||
from datetime import datetime, timedelta
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
|
||||
class IPRateLimit:
|
||||
def __init__(self, count: int, minutes: int):
|
||||
self.ips: Dict[str, Dict[str, Union[int, datetime]]] = {}
|
||||
self.count = count
|
||||
self.minutes = minutes
|
||||
|
||||
def check_ip(self, ip: str) -> bool:
|
||||
if ip in self.ips:
|
||||
ip_info = self.ips[ip]
|
||||
if ip_info["count"] >= self.count:
|
||||
if ip_info["time"] + timedelta(minutes=self.minutes) > datetime.now():
|
||||
return False
|
||||
self.ips.pop(ip)
|
||||
return True
|
||||
|
||||
def add_ip(self, ip: str) -> int:
|
||||
ip_info = self.ips.get(ip, {"count": 0, "time": datetime.now()})
|
||||
ip_info["count"] += 1
|
||||
ip_info["time"] = datetime.now()
|
||||
self.ips[ip] = ip_info
|
||||
return ip_info["count"]
|
||||
|
||||
async def remove_expired_ip(self) -> None:
|
||||
now = datetime.now()
|
||||
expiration = timedelta(minutes=self.minutes)
|
||||
self.ips = {
|
||||
ip: info
|
||||
for ip, info in self.ips.items()
|
||||
if info["time"] + expiration >= now
|
||||
}
|
||||
|
||||
def __call__(self, request: Request) -> str:
|
||||
ip = (
|
||||
request.headers.get("X-Real-IP")
|
||||
or request.headers.get("X-Forwarded-For")
|
||||
or request.client.host
|
||||
)
|
||||
if not self.check_ip(ip):
|
||||
raise HTTPException(status_code=423, detail="请求次数过多,请稍后再试")
|
||||
return ip
|
||||
@@ -1,45 +0,0 @@
|
||||
# @Time : 2023/8/14 12:20
|
||||
# @Author : Lan
|
||||
# @File : depends.py
|
||||
# @Software: PyCharm
|
||||
from typing import Union
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from fastapi import Header, HTTPException, Request
|
||||
|
||||
from core.response import APIResponse
|
||||
|
||||
|
||||
class IPRateLimit:
|
||||
def __init__(self, count, minutes):
|
||||
self.ips = {}
|
||||
self.count = count
|
||||
self.minutes = minutes
|
||||
|
||||
def check_ip(self, ip):
|
||||
# 检查ip是否被禁止
|
||||
if ip in self.ips:
|
||||
if self.ips[ip]['count'] >= self.count:
|
||||
if self.ips[ip]['time'] + timedelta(minutes=self.minutes) > datetime.now():
|
||||
return False
|
||||
else:
|
||||
self.ips.pop(ip)
|
||||
return True
|
||||
|
||||
def add_ip(self, ip):
|
||||
ip_info = self.ips.get(ip, {'count': 0, 'time': datetime.now()})
|
||||
ip_info['count'] += 1
|
||||
ip_info['time'] = datetime.now()
|
||||
self.ips[ip] = ip_info
|
||||
return ip_info['count']
|
||||
|
||||
async def remove_expired_ip(self):
|
||||
for ip in list(self.ips.keys()):
|
||||
if self.ips[ip]['time'] + timedelta(minutes=self.minutes) < datetime.now():
|
||||
self.ips.pop(ip)
|
||||
|
||||
def __call__(self, request: Request):
|
||||
ip = request.headers.get('X-Real-IP', request.headers.get('X-Forwarded-For', request.client.host))
|
||||
if not self.check_ip(ip):
|
||||
raise HTTPException(status_code=423, detail=f"请求次数过多,请稍后再试")
|
||||
return ip
|
||||
@@ -0,0 +1,52 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
async def create_file_codes_table():
|
||||
conn = connections.get("default")
|
||||
await conn.execute_script(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS filecodes
|
||||
(
|
||||
id INTEGER not null
|
||||
primary key autoincrement,
|
||||
code VARCHAR(255) not null
|
||||
unique,
|
||||
prefix VARCHAR(255) default '' not null,
|
||||
suffix VARCHAR(255) default '' not null,
|
||||
uuid_file_name VARCHAR(255),
|
||||
file_path VARCHAR(255),
|
||||
size INT default 0 not null,
|
||||
text TEXT,
|
||||
expired_at TIMESTAMP,
|
||||
expired_count INT default 0 not null,
|
||||
used_count INT default 0 not null,
|
||||
created_at TIMESTAMP default CURRENT_TIMESTAMP not null
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_filecodes_code_1c7ee7
|
||||
on filecodes (code);
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
async def create_key_value_table():
|
||||
conn = connections.get("default")
|
||||
await conn.execute_script(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS keyvalue
|
||||
(
|
||||
id INTEGER not null
|
||||
primary key autoincrement,
|
||||
key VARCHAR(255) not null
|
||||
unique,
|
||||
value JSON,
|
||||
created_at TIMESTAMP default CURRENT_TIMESTAMP not null
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_keyvalue_key_eab890
|
||||
on keyvalue (key);
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
async def migrate():
|
||||
await create_file_codes_table()
|
||||
await create_key_value_table()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,14 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
async def add_save_path_to_uploadchunk():
|
||||
conn = connections.get("default")
|
||||
await conn.execute_script(
|
||||
"""
|
||||
ALTER TABLE uploadchunk ADD COLUMN save_path VARCHAR(512) NULL;
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
async def migrate():
|
||||
await add_save_path_to_uploadchunk()
|
||||
@@ -0,0 +1,72 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
def _need_upgrade(columns: list[tuple]) -> bool:
|
||||
for column in columns:
|
||||
# PRAGMA table_info 返回 (cid, name, type, notnull, dflt_value, pk)
|
||||
if column[1] == "size":
|
||||
column_type = (column[2] or "").upper()
|
||||
return "BIGINT" not in column_type
|
||||
return False
|
||||
|
||||
|
||||
async def migrate():
|
||||
conn = connections.get("default")
|
||||
result = await conn.execute_query("PRAGMA table_info(filecodes)")
|
||||
columns = result[1] if result and len(result) > 1 else []
|
||||
|
||||
if not columns or not _need_upgrade(columns):
|
||||
return
|
||||
|
||||
await conn.execute_script(
|
||||
"""
|
||||
BEGIN;
|
||||
CREATE TABLE IF NOT EXISTS filecodes_new
|
||||
(
|
||||
id INTEGER not null
|
||||
primary key autoincrement,
|
||||
code VARCHAR(255) not null
|
||||
unique,
|
||||
prefix VARCHAR(255) default '' not null,
|
||||
suffix VARCHAR(255) default '' not null,
|
||||
uuid_file_name VARCHAR(255),
|
||||
file_path VARCHAR(255),
|
||||
size BIGINT default 0 not null,
|
||||
text TEXT,
|
||||
expired_at TIMESTAMP,
|
||||
expired_count INT default 0 not null,
|
||||
used_count INT default 0 not null,
|
||||
created_at TIMESTAMP default CURRENT_TIMESTAMP not null,
|
||||
file_hash VARCHAR(128),
|
||||
is_chunked BOOL default False not null,
|
||||
upload_id VARCHAR(128)
|
||||
);
|
||||
|
||||
INSERT INTO filecodes_new (id, code, prefix, suffix, uuid_file_name, file_path, size, text,
|
||||
expired_at, expired_count, used_count, created_at, file_hash,
|
||||
is_chunked, upload_id)
|
||||
SELECT id,
|
||||
code,
|
||||
prefix,
|
||||
suffix,
|
||||
uuid_file_name,
|
||||
file_path,
|
||||
size,
|
||||
text,
|
||||
expired_at,
|
||||
expired_count,
|
||||
used_count,
|
||||
created_at,
|
||||
file_hash,
|
||||
is_chunked,
|
||||
upload_id
|
||||
FROM filecodes;
|
||||
|
||||
DROP TABLE filecodes;
|
||||
ALTER TABLE filecodes_new
|
||||
RENAME TO filecodes;
|
||||
CREATE INDEX IF NOT EXISTS idx_filecodes_code_1c7ee7
|
||||
on filecodes (code);
|
||||
COMMIT;
|
||||
"""
|
||||
)
|
||||
@@ -2,49 +2,91 @@
|
||||
# @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='创建时间')
|
||||
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 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):
|
||||
id: Optional[int] = fields.IntField(pk=True)
|
||||
key: Optional[str] = fields.CharField(max_length=255, description='键', index=True, unique=True)
|
||||
value: Optional[str] = fields.JSONField(description='值', null=True)
|
||||
created_at: Optional[datetime] = fields.DatetimeField(auto_now_add=True, description='创建时间')
|
||||
key: Optional[str] = fields.CharField(
|
||||
max_length=255, description="键", index=True, unique=True
|
||||
)
|
||||
value: Optional[str] = fields.JSONField(description="值", null=True)
|
||||
created_at: Optional[datetime] = fields.DatetimeField(
|
||||
auto_now_add=True, description="创建时间"
|
||||
)
|
||||
|
||||
|
||||
file_codes_pydantic = pydantic_model_creator(FileCodes, name='FileCodes')
|
||||
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"
|
||||
)
|
||||
@@ -1,5 +0,0 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class SelectFileModel(BaseModel):
|
||||
code: str
|
||||
@@ -0,0 +1,36 @@
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class SelectFileModel(BaseModel):
|
||||
code: str
|
||||
|
||||
|
||||
class InitChunkUploadModel(BaseModel):
|
||||
file_name: str
|
||||
chunk_size: int = 5 * 1024 * 1024
|
||||
file_size: int
|
||||
file_hash: str
|
||||
|
||||
|
||||
class CompleteUploadModel(BaseModel):
|
||||
expire_value: int
|
||||
expire_style: str
|
||||
|
||||
|
||||
# 预签名上传相关模型
|
||||
class PresignUploadInitRequest(BaseModel):
|
||||
"""预签名上传初始化请求"""
|
||||
file_name: str
|
||||
file_size: int
|
||||
expire_value: int = 1
|
||||
expire_style: str = "day"
|
||||
|
||||
|
||||
class PresignUploadInitResponse(BaseModel):
|
||||
"""预签名上传初始化响应"""
|
||||
upload_id: str
|
||||
upload_url: str
|
||||
mode: str # "direct" 或 "proxy"
|
||||
save_path: str
|
||||
expires_in: int # URL过期时间(秒)
|
||||
@@ -1,92 +1,116 @@
|
||||
# @Time : 2023/8/14 01:10
|
||||
# @Author : Lan
|
||||
# @File : utils.py
|
||||
# @Software: PyCharm
|
||||
import datetime
|
||||
import uuid
|
||||
import hashlib
|
||||
import os
|
||||
from fastapi import UploadFile, HTTPException
|
||||
import uuid
|
||||
from urllib.parse import unquote
|
||||
|
||||
from apps.base.depends import IPRateLimit
|
||||
from fastapi import UploadFile, HTTPException
|
||||
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):
|
||||
"""
|
||||
获取文件路径和文件名
|
||||
:param file:
|
||||
:return: {
|
||||
'path': 'share/data/2021/08/13',
|
||||
'suffix': '.jpg',
|
||||
'prefix': 'test',
|
||||
'file_uuid': '44a83bbd70e04c8aa7fd93bfd8c88249',
|
||||
'uuid_file_name': '44a83bbd70e04c8aa7fd93bfd8c88249.jpg',
|
||||
'save_path': 'share/data/2021/08/13/44a83bbd70e04c8aa7fd93bfd8c88249.jpg'
|
||||
async def get_file_path_name(file: UploadFile) -> Tuple[str, str, str, str, str]:
|
||||
today = await get_now()
|
||||
storage_path = settings.storage_path.strip("/")
|
||||
file_uuid = uuid.uuid4().hex
|
||||
filename = await sanitize_filename(unquote(file.filename or ""))
|
||||
base_path = f"share/data/{today.strftime('%Y/%m/%d')}/{file_uuid}"
|
||||
path = f"{storage_path}/{base_path}" if storage_path else base_path
|
||||
prefix, suffix = os.path.splitext(filename)
|
||||
save_path = f"{path}/{filename}"
|
||||
return path, suffix, prefix, filename, save_path
|
||||
|
||||
|
||||
async def get_chunk_file_path_name(
|
||||
file_name: str, upload_id: str
|
||||
) -> Tuple[str, str, str, str, str]:
|
||||
today = 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 = await get_now()
|
||||
code = None
|
||||
|
||||
max_timedelta = (
|
||||
datetime.timedelta(seconds=settings.max_save_seconds)
|
||||
if settings.max_save_seconds > 0
|
||||
else datetime.timedelta(days=7)
|
||||
)
|
||||
detail = (
|
||||
await max_save_times_desc(settings.max_save_seconds)
|
||||
if settings.max_save_seconds > 0
|
||||
else "7天"
|
||||
)
|
||||
detail = f"限制最长时间为 {detail[0]},可换用其他方式"
|
||||
|
||||
expire_styles = {
|
||||
"day": lambda: now + datetime.timedelta(days=expire_value),
|
||||
"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),
|
||||
}
|
||||
"""
|
||||
today = datetime.datetime.now()
|
||||
path = f"share/data/{today.strftime('%Y/%m/%d')}"
|
||||
prefix, suffix = os.path.splitext(file.filename)
|
||||
file_uuid = f"{uuid.uuid4().hex}"
|
||||
uuid_file_name = f"{file_uuid}{suffix}"
|
||||
save_path = f"{path}/{uuid_file_name}"
|
||||
return path, suffix, prefix, uuid_file_name, save_path
|
||||
|
||||
|
||||
async def get_expire_info(expire_value: int, expire_style: str):
|
||||
"""
|
||||
获取过期信息
|
||||
:param expire_value:
|
||||
:param expire_style:
|
||||
:return: expired_at 过期时间, expired_count 可用次数, used_count 已用次数, code 随机码
|
||||
"""
|
||||
expired_count, used_count, now, code = -1, 0, datetime.datetime.now(), None
|
||||
if settings.max_save_seconds > 0:
|
||||
max_timedelta = datetime.timedelta(seconds=settings.max_save_seconds)
|
||||
detail = await max_save_times_desc(settings.max_save_seconds)
|
||||
detail = f'保存时间超过限制,{detail[0]}'
|
||||
else:
|
||||
max_timedelta = datetime.timedelta(days=7)
|
||||
detail = '保存时间超过限制,最长保存时间:7天'
|
||||
if expire_style == 'day':
|
||||
if datetime.timedelta(days=expire_value) > max_timedelta:
|
||||
if expire_style in expire_styles:
|
||||
result = expire_styles[expire_style]()
|
||||
if isinstance(result, tuple):
|
||||
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:
|
||||
raise HTTPException(status_code=403, detail=detail)
|
||||
expired_at = now + datetime.timedelta(days=expire_value)
|
||||
elif expire_style == 'hour':
|
||||
if datetime.timedelta(hours=expire_value) > max_timedelta:
|
||||
raise HTTPException(status_code=403, detail=detail)
|
||||
expired_at = now + datetime.timedelta(hours=expire_value)
|
||||
elif expire_style == 'minute':
|
||||
if datetime.timedelta(minutes=expire_value) > max_timedelta:
|
||||
raise HTTPException(status_code=403, detail=detail)
|
||||
expired_at = now + datetime.timedelta(minutes=expire_value)
|
||||
elif expire_style == 'count':
|
||||
expired_at = now + datetime.timedelta(days=1)
|
||||
expired_count = expire_value
|
||||
elif expire_style == 'forever':
|
||||
expired_at = None
|
||||
code = await get_random_code(style='string')
|
||||
else:
|
||||
expired_at = now + datetime.timedelta(days=1)
|
||||
|
||||
if not code:
|
||||
code = await get_random_code()
|
||||
|
||||
return expired_at, expired_count, used_count, code
|
||||
|
||||
|
||||
async def get_random_code(style='num'):
|
||||
"""
|
||||
获取随机字符串
|
||||
:return:
|
||||
"""
|
||||
async def get_random_code(style: str = "num") -> str:
|
||||
while True:
|
||||
code = await get_random_num() if style == 'num' else await get_random_string()
|
||||
code = await get_random_num() if style == "num" else await get_random_string()
|
||||
if not await FileCodes.filter(code=code).exists():
|
||||
return code
|
||||
return str(code)
|
||||
|
||||
|
||||
# 错误IP限制器
|
||||
error_ip_limit = IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute)
|
||||
# 上传文件限制器
|
||||
upload_ip_limit = IPRateLimit(count=settings.uploadCount, minutes=settings.errorMinute)
|
||||
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.errorCount, minutes=settings.errorMinute),
|
||||
"upload": IPRateLimit(count=settings.uploadCount, minutes=settings.uploadMinute),
|
||||
}
|
||||
@@ -1,159 +1,817 @@
|
||||
# @Time : 2023/8/14 03:59
|
||||
# @Author : Lan
|
||||
# @File : views.py
|
||||
# @Software: PyCharm
|
||||
# 导入所需的库和模块
|
||||
from fastapi import APIRouter, Form, UploadFile, File, Depends, HTTPException
|
||||
from apps.admin.depends import admin_required
|
||||
from apps.base.models import FileCodes
|
||||
from apps.base.pydantics import SelectFileModel
|
||||
from apps.base.utils import get_expire_info, get_file_path_name, error_ip_limit, upload_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 file_storage
|
||||
from core.utils import get_select_token
|
||||
from core.storage import storages, FileStorageInterface
|
||||
from core.utils import get_select_token, get_now, sanitize_filename
|
||||
|
||||
# 创建一个API路由
|
||||
share_api = APIRouter(
|
||||
prefix='/share', # 路由前缀
|
||||
tags=['分享'], # 标签
|
||||
)
|
||||
share_api = APIRouter(prefix="/share", tags=["分享"])
|
||||
|
||||
|
||||
# 分享文本的API
|
||||
@share_api.post('/text/', dependencies=[Depends(admin_required)])
|
||||
async def share_text(text: str = Form(...), expire_value: int = Form(default=1, gt=0), expire_style: str = Form(default='day'), ip: str = Depends(upload_ip_limit)):
|
||||
# 获取过期信息
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(expire_value, expire_style)
|
||||
# 创建一个新的FileCodes实例
|
||||
await FileCodes.create(
|
||||
# ============ 公共服务层 ============
|
||||
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)
|
||||
|
||||
|
||||
def normalize_share_code(code: str) -> str:
|
||||
return str(code or "").strip()
|
||||
|
||||
|
||||
@share_api.post("/text/", dependencies=[Depends(share_required_login)])
|
||||
async def share_text(
|
||||
text: str = Form(...),
|
||||
expire_value: int = Form(default=1, gt=0),
|
||||
expire_style: str = Form(default="day"),
|
||||
ip: str = Depends(ip_limit["upload"]),
|
||||
):
|
||||
text_size = len(text.encode("utf-8"))
|
||||
max_txt_size = 222 * 1024
|
||||
if text_size > max_txt_size:
|
||||
raise HTTPException(status_code=403, detail="内容过多,建议采用文件形式")
|
||||
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(
|
||||
expire_value, expire_style
|
||||
)
|
||||
await create_file_code(
|
||||
code=code,
|
||||
text=text,
|
||||
expired_at=expired_at,
|
||||
expired_count=expired_count,
|
||||
used_count=used_count,
|
||||
size=len(text),
|
||||
prefix='文本分享'
|
||||
prefix="Text",
|
||||
)
|
||||
# 添加IP到限制列表
|
||||
upload_ip_limit.add_ip(ip)
|
||||
# 返回API响应
|
||||
return APIResponse(detail={
|
||||
'code': code,
|
||||
})
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
return APIResponse(detail={"code": code})
|
||||
|
||||
|
||||
# 分享文件的API
|
||||
@share_api.post('/file/', dependencies=[Depends(admin_required)])
|
||||
async def share_file(expire_value: int = Form(default=1, gt=0), expire_style: str = Form(default='day'), file: UploadFile = File(...), ip: str = Depends(upload_ip_limit)):
|
||||
# 检查文件大小是否超过限制
|
||||
if file.size > settings.uploadSize:
|
||||
raise HTTPException(status_code=403, detail=f'文件大小超过限制,最大为{settings.uploadSize}字节')
|
||||
# 获取过期信息
|
||||
@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"]),
|
||||
):
|
||||
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)
|
||||
# 获取文件路径和名称
|
||||
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)
|
||||
# 创建一个新的FileCodes实例
|
||||
await FileCodes.create(
|
||||
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,
|
||||
)
|
||||
# 添加IP到限制列表
|
||||
upload_ip_limit.add_ip(ip)
|
||||
# 返回API响应
|
||||
return APIResponse(detail={
|
||||
'code': code,
|
||||
'name': file.filename,
|
||||
})
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
return APIResponse(detail={"code": code, "name": file.filename})
|
||||
|
||||
|
||||
# 根据code获取文件
|
||||
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, '文件不存在'
|
||||
# 检查文件是否过期
|
||||
return False, "文件不存在"
|
||||
if await file_code.is_expired() and check:
|
||||
return False, '文件已过期',
|
||||
return False, "文件已过期"
|
||||
return True, file_code
|
||||
|
||||
|
||||
# 获取文件的API
|
||||
@share_api.get('/select/')
|
||||
async def get_code_file(code: str, ip: str = Depends(error_ip_limit)):
|
||||
# 获取文件
|
||||
has, file_code = await get_code_file_by_code(code)
|
||||
# 检查文件是否存在
|
||||
if not has:
|
||||
# 添加IP到限制列表
|
||||
error_ip_limit.add_ip(ip)
|
||||
# 返回API响应
|
||||
return APIResponse(code=404, detail=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]()
|
||||
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)
|
||||
await update_file_usage(file_code)
|
||||
return await file_storage.get_file_response(file_code)
|
||||
|
||||
|
||||
# 选择文件的API
|
||||
@share_api.post('/select/')
|
||||
async def select_file(data: SelectFileModel, ip: str = Depends(error_ip_limit)):
|
||||
# 获取文件
|
||||
@share_api.post("/select/")
|
||||
async def select_file(data: SelectFileModel, ip: str = Depends(ip_limit["error"])):
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
has, file_code = await get_code_file_by_code(data.code)
|
||||
# 检查文件是否存在
|
||||
if not has:
|
||||
# 添加IP到限制列表
|
||||
error_ip_limit.add_ip(ip)
|
||||
# 返回API响应
|
||||
ip_limit["error"].add_ip(ip)
|
||||
return APIResponse(code=404, detail=file_code)
|
||||
# 更新文件的使用次数和过期次数
|
||||
file_code.used_count += 1
|
||||
if file_code.expired_count > 0:
|
||||
file_code.expired_count -= 1
|
||||
# 保存文件
|
||||
await file_code.save()
|
||||
# 返回API响应
|
||||
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),
|
||||
})
|
||||
|
||||
assert isinstance(file_code, FileCodes)
|
||||
await update_file_usage(file_code)
|
||||
return APIResponse(detail=await build_select_detail(file_code, file_storage))
|
||||
|
||||
|
||||
# 下载文件的API
|
||||
@share_api.get('/download')
|
||||
async def download_file(key: str, code: str, ip: str = Depends(error_ip_limit)):
|
||||
# 检查token是否有效
|
||||
is_valid = await get_select_token(code) == key
|
||||
if not is_valid:
|
||||
# 添加IP到限制列表
|
||||
error_ip_limit.add_ip(ip)
|
||||
# 获取文件
|
||||
has, file_code = await get_code_file_by_code(code, False)
|
||||
# 检查文件是否存在
|
||||
@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]()
|
||||
normalized_code = normalize_share_code(code)
|
||||
if await get_select_token(normalized_code) != key:
|
||||
ip_limit["error"].add_ip(ip)
|
||||
raise HTTPException(status_code=403, detail="下载鉴权失败")
|
||||
has, file_code = await get_code_file_by_code(normalized_code, False)
|
||||
if not has:
|
||||
# 返回API响应
|
||||
return APIResponse(code=404, detail='文件不存在')
|
||||
# 如果文件是文本,返回文本内容,否则返回文件响应
|
||||
if file_code.text:
|
||||
return APIResponse(detail=file_code.text)
|
||||
else:
|
||||
return await file_storage.get_file_response(file_code)
|
||||
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": "上传会话已取消"})
|
||||
@@ -0,0 +1,21 @@
|
||||
from apps.base.models import KeyValue
|
||||
from apps.base.utils import ip_limit
|
||||
from core.settings import DEFAULT_CONFIG, settings
|
||||
|
||||
|
||||
async def ensure_settings_row() -> None:
|
||||
await KeyValue.get_or_create(key="settings", defaults={"value": DEFAULT_CONFIG})
|
||||
|
||||
|
||||
def _sync_ip_limits() -> None:
|
||||
ip_limit["error"].minutes = settings.errorMinute
|
||||
ip_limit["error"].count = settings.errorCount
|
||||
ip_limit["upload"].minutes = settings.uploadMinute
|
||||
ip_limit["upload"].count = settings.uploadCount
|
||||
|
||||
|
||||
async def refresh_settings() -> None:
|
||||
"""从数据库读取最新配置并应用到运行时。"""
|
||||
config_record = await KeyValue.filter(key="settings").first()
|
||||
settings.user_config = config_record.value if config_record and config_record.value else {}
|
||||
_sync_ip_limits()
|
||||
@@ -0,0 +1,146 @@
|
||||
import asyncio
|
||||
import glob
|
||||
import importlib
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import IO
|
||||
|
||||
from tortoise import Tortoise
|
||||
|
||||
from core.logger import logger
|
||||
from core.settings import data_root
|
||||
|
||||
|
||||
_DB_FILE = os.path.join(data_root, "filecodebox.db")
|
||||
_STARTUP_LOCK_FILE = os.path.join(data_root, "filecodebox.startup.lock")
|
||||
|
||||
|
||||
def get_db_config() -> dict:
|
||||
return {
|
||||
"connections": {
|
||||
"default": {
|
||||
"engine": "tortoise.backends.sqlite",
|
||||
"credentials": {
|
||||
"file_path": _DB_FILE,
|
||||
"journal_mode": "WAL",
|
||||
"busy_timeout": 10000,
|
||||
"foreign_keys": "ON",
|
||||
},
|
||||
}
|
||||
},
|
||||
"apps": {
|
||||
"models": {
|
||||
"models": ["apps.base.models"],
|
||||
"default_connection": "default",
|
||||
}
|
||||
},
|
||||
"use_tz": False,
|
||||
"timezone": "Asia/Shanghai",
|
||||
}
|
||||
|
||||
|
||||
def _lock_file(file_obj: IO[str]) -> None:
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
# Windows 需要锁定至少 1 字节
|
||||
if os.fstat(file_obj.fileno()).st_size == 0:
|
||||
file_obj.write("0")
|
||||
file_obj.flush()
|
||||
msvcrt.locking(file_obj.fileno(), msvcrt.LK_LOCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(file_obj.fileno(), fcntl.LOCK_EX)
|
||||
|
||||
|
||||
def _unlock_file(file_obj: IO[str]) -> None:
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
msvcrt.locking(file_obj.fileno(), msvcrt.LK_UNLCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(file_obj.fileno(), fcntl.LOCK_UN)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def db_startup_lock():
|
||||
os.makedirs(data_root, exist_ok=True)
|
||||
lock_file = open(_STARTUP_LOCK_FILE, "a+", encoding="utf-8")
|
||||
try:
|
||||
await asyncio.to_thread(_lock_file, lock_file)
|
||||
yield
|
||||
finally:
|
||||
await asyncio.to_thread(_unlock_file, lock_file)
|
||||
lock_file.close()
|
||||
|
||||
|
||||
async def init_db():
|
||||
try:
|
||||
db_config = get_db_config()
|
||||
|
||||
if not Tortoise._inited:
|
||||
await Tortoise.init(config=db_config)
|
||||
|
||||
async with db_startup_lock():
|
||||
# 创建migrations表
|
||||
await Tortoise.get_connection("default").execute_script("""
|
||||
CREATE TABLE IF NOT EXISTS migrates (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
migration_file VARCHAR(255) NOT NULL UNIQUE,
|
||||
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
""")
|
||||
|
||||
# 执行迁移
|
||||
await execute_migrations()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"数据库初始化失败: {str(e)}")
|
||||
raise
|
||||
|
||||
|
||||
async def execute_migrations():
|
||||
"""执行数据库迁移"""
|
||||
try:
|
||||
# 收集迁移文件
|
||||
migration_files = []
|
||||
for root, dirs, files in os.walk("apps"):
|
||||
if "migrations" in dirs:
|
||||
migration_path = os.path.join(root, "migrations")
|
||||
migration_files.extend(glob.glob(os.path.join(migration_path, "migrations_*.py")))
|
||||
|
||||
# 按文件名排序
|
||||
migration_files.sort()
|
||||
|
||||
for migration_file in migration_files:
|
||||
file_name = os.path.basename(migration_file)
|
||||
|
||||
# 检查是否已执行
|
||||
executed = await Tortoise.get_connection("default").execute_query(
|
||||
"SELECT id FROM migrates WHERE migration_file = ?", [file_name]
|
||||
)
|
||||
|
||||
if not executed[1]:
|
||||
logger.info(f"执行迁移: {file_name}")
|
||||
# 导入并执行migration
|
||||
module_path = migration_file.replace("/", ".").replace("\\", ".").replace(".py", "")
|
||||
try:
|
||||
migration_module = importlib.import_module(module_path)
|
||||
if hasattr(migration_module, "migrate"):
|
||||
await migration_module.migrate()
|
||||
# 记录执行
|
||||
await Tortoise.get_connection("default").execute_query(
|
||||
"INSERT INTO migrates (migration_file) VALUES (?)",
|
||||
[file_name]
|
||||
)
|
||||
logger.info(f"迁移完成: {file_name}")
|
||||
except Exception as e:
|
||||
logger.error(f"迁移 {file_name} 执行失败: {str(e)}")
|
||||
raise
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"迁移过程发生错误: {str(e)}")
|
||||
raise
|
||||
@@ -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()
|
||||
@@ -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')
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class APIResponse(GenericModel, Generic[T]):
|
||||
class APIResponse(BaseModel, Generic[T]):
|
||||
code: int = 200
|
||||
message: str = 'ok'
|
||||
detail: T
|
||||
message: str = "ok"
|
||||
msg: Optional[str] = None
|
||||
detail: Optional[T] = None
|
||||
|
||||
def model_post_init(self, __context) -> None:
|
||||
if self.msg is None:
|
||||
self.msg = self.message
|
||||
@@ -2,50 +2,77 @@
|
||||
# @Author : Lan
|
||||
# @File : settings.py
|
||||
# @Software: PyCharm
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
data_root = BASE_DIR / 'data'
|
||||
data_root = BASE_DIR / "data"
|
||||
|
||||
if not data_root.exists():
|
||||
data_root.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
DEFAULT_CONFIG = {
|
||||
'file_storage': 'local',
|
||||
'name': '文件快递柜-FileCodeBox',
|
||||
'description': '开箱即用的文件快传系统',
|
||||
'notify_title': '系统通知',
|
||||
'notify_content': '欢迎使用FileCodeBox,本程序开源于 <a href="https://github.com/vastsa/FileCodeBox" target="_blank">Github</a> ,欢迎Star和Fork。',
|
||||
'page_explain': '根据《中华人民共和国网络安全法》、《中华人民共和国刑法》、《中华人民共和国治安管理处罚法》等相关规定。 传播或存储违法、违规内容,会受到相关处罚,严重者将承担刑事责任。请勿上传非法文件,本站坚决配合相关部门,确保网络内容的安全,和谐,打造绿色网络环境。',
|
||||
'keywords': 'FileCodeBox, 文件快递柜, 口令传送箱, 匿名口令分享文本, 文件',
|
||||
's3_access_key_id': '',
|
||||
's3_secret_access_key': '',
|
||||
's3_bucket_name': '',
|
||||
's3_endpoint_url': '',
|
||||
's3_region_name': 'auto',
|
||||
's3_signature_version': 's3v2',
|
||||
's3_hostname': '',
|
||||
's3_proxy': 0,
|
||||
'max_save_seconds': 0,
|
||||
'aws_session_token': '',
|
||||
'onedrive_domain': '',
|
||||
'onedrive_client_id': '',
|
||||
'onedrive_username': '',
|
||||
'onedrive_password': '',
|
||||
'onedrive_root_path': 'filebox_storage',
|
||||
'onedrive_proxy': 0,
|
||||
'admin_token': 'FileCodeBox2023',
|
||||
'openUpload': 1,
|
||||
'uploadSize': 1024 * 1024 * 10,
|
||||
'expireStyle': ['day', 'hour', 'minute', 'forever', 'count'],
|
||||
'uploadMinute': 1,
|
||||
'opacity': 0.9,
|
||||
'background': '',
|
||||
'uploadCount': 10,
|
||||
'errorMinute': 1,
|
||||
'errorCount': 1,
|
||||
'port': 12345,
|
||||
"file_storage": "local",
|
||||
"storage_path": "",
|
||||
"name": "文件快递柜 - FileCodeBox",
|
||||
"description": "开箱即用的文件快传系统",
|
||||
"notify_title": "系统通知",
|
||||
"notify_content": '欢迎使用 FileCodeBox,本程序开源于 <a href="https://github.com/vastsa/FileCodeBox" target="_blank">Github</a> ,欢迎Star和Fork。',
|
||||
"page_explain": "请勿上传或分享违法内容。根据《中华人民共和国网络安全法》、《中华人民共和国刑法》、《中华人民共和国治安管理处罚法》等相关规定。 传播或存储违法、违规内容,会受到相关处罚,严重者将承担刑事责任。本站坚决配合相关部门,确保网络内容的安全,和谐,打造绿色网络环境。",
|
||||
"keywords": "FileCodeBox, 文件快递柜, 口令传送箱, 匿名口令分享文本, 文件",
|
||||
"s3_access_key_id": "",
|
||||
"s3_secret_access_key": "",
|
||||
"s3_bucket_name": "",
|
||||
"s3_endpoint_url": "",
|
||||
"s3_region_name": "auto",
|
||||
"s3_signature_version": "s3v2",
|
||||
"s3_hostname": "",
|
||||
"s3_addressing_style": "auto",
|
||||
"s3_proxy": 0,
|
||||
"max_save_seconds": 0,
|
||||
"aws_session_token": "",
|
||||
"onedrive_domain": "",
|
||||
"onedrive_client_id": "",
|
||||
"onedrive_username": "",
|
||||
"onedrive_password": "",
|
||||
"onedrive_root_path": "filebox_storage",
|
||||
"onedrive_proxy": 0,
|
||||
"webdav_root_path": "filebox_storage",
|
||||
"webdav_proxy": 0,
|
||||
"admin_token": "FileCodeBox2023",
|
||||
"openUpload": 1,
|
||||
"uploadSize": 1024 * 1024 * 10,
|
||||
"allowed_file_types": ["*"],
|
||||
"expireStyle": ["day", "hour", "minute", "forever", "count"],
|
||||
"uploadMinute": 1,
|
||||
"enableChunk": 0,
|
||||
"webdav_url": "",
|
||||
"webdav_password": "",
|
||||
"webdav_username": "",
|
||||
"opacity": 0.9,
|
||||
"background": "",
|
||||
"uploadCount": 10,
|
||||
"themesChoices": [
|
||||
{
|
||||
"name": "2023",
|
||||
"key": "themes/2023",
|
||||
"author": "Lan",
|
||||
"version": "1.0",
|
||||
},
|
||||
{
|
||||
"name": "2024",
|
||||
"key": "themes/2024",
|
||||
"author": "Lan",
|
||||
"version": "1.0",
|
||||
},
|
||||
],
|
||||
"themesSelect": "themes/2024",
|
||||
"errorMinute": 1,
|
||||
"errorCount": 10,
|
||||
"serverWorkers": 1,
|
||||
"serverHost": "0.0.0.0",
|
||||
"serverPort": 12345,
|
||||
"showAdminAddr": 0,
|
||||
"robotsText": "User-agent: *\nDisallow: /",
|
||||
}
|
||||
|
||||
|
||||
@@ -59,10 +86,12 @@ class Settings:
|
||||
return self.user_config[attr]
|
||||
if attr in self.default_config:
|
||||
return self.default_config[attr]
|
||||
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{attr}'")
|
||||
raise AttributeError(
|
||||
f"'{self.__class__.__name__}' object has no attribute '{attr}'"
|
||||
)
|
||||
|
||||
def __setattr__(self, key, value):
|
||||
if key in ['default_config', 'user_config']:
|
||||
if key in ["default_config", "user_config"]:
|
||||
super().__setattr__(key, value)
|
||||
else:
|
||||
self.user_config[key] = value
|
||||
|
||||
@@ -3,25 +3,84 @@
|
||||
# @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 error_ip_limit, upload_ip_limit
|
||||
from core.storage import file_storage
|
||||
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():
|
||||
while True:
|
||||
try:
|
||||
await error_ip_limit.remove_expired_ip()
|
||||
await upload_ip_limit.remove_expired_ip()
|
||||
expire_data = await FileCodes.filter(Q(expired_at__lt=await get_now()) | Q(expired_count=0)).all()
|
||||
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"):
|
||||
if not dirs and not files:
|
||||
os.rmdir(root)
|
||||
await ip_limit["error"].remove_expired_ip()
|
||||
await ip_limit["upload"].remove_expired_ip()
|
||||
expire_data = await FileCodes.filter(
|
||||
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)
|
||||
@@ -4,11 +4,13 @@
|
||||
# @Software: PyCharm
|
||||
import datetime
|
||||
import hashlib
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import string
|
||||
import time
|
||||
|
||||
from apps.base.depends import IPRateLimit
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
async def get_random_num():
|
||||
@@ -27,7 +29,7 @@ async def get_random_string():
|
||||
获取随机字符串
|
||||
:return:
|
||||
"""
|
||||
return ''.join(random.choice(r_s) for _ in range(5))
|
||||
return "".join(random.choice(r_s) for _ in range(5))
|
||||
|
||||
|
||||
async def get_now():
|
||||
@@ -35,9 +37,7 @@ async def get_now():
|
||||
获取当前时间
|
||||
:return:
|
||||
"""
|
||||
return datetime.datetime.now(
|
||||
datetime.timezone(datetime.timedelta(hours=8))
|
||||
)
|
||||
return datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8)))
|
||||
|
||||
|
||||
async def get_select_token(code: str):
|
||||
@@ -46,8 +46,10 @@ async def get_select_token(code: str):
|
||||
:param code:
|
||||
:return:
|
||||
"""
|
||||
token = "123456"
|
||||
return hashlib.sha256(f"{code}{int(time.time() / 1000)}000{token}".encode()).hexdigest()
|
||||
token = settings.admin_token
|
||||
return hashlib.sha256(
|
||||
f"{code}{int(time.time() / 1000)}000{token}".encode()
|
||||
).hexdigest()
|
||||
|
||||
|
||||
async def get_file_url(code: str):
|
||||
@@ -56,7 +58,7 @@ async def get_file_url(code: str):
|
||||
:param code:
|
||||
:return:
|
||||
"""
|
||||
return f'/share/download?key={await get_select_token(code)}&code={code}'
|
||||
return f"/share/download?key={await get_select_token(code)}&code={code}"
|
||||
|
||||
|
||||
async def max_save_times_desc(max_save_seconds: int):
|
||||
@@ -68,28 +70,90 @@ async def max_save_times_desc(max_save_seconds: int):
|
||||
|
||||
def gen_desc_zh(value: int, desc: str):
|
||||
if value > 0:
|
||||
return f'{value}{desc}'
|
||||
return f"{value}{desc}"
|
||||
else:
|
||||
return ''
|
||||
return ""
|
||||
|
||||
def gen_desc_en(value: int, desc: str):
|
||||
if value > 0:
|
||||
ret = f'{value} {desc}'
|
||||
ret = f"{value} {desc}"
|
||||
if value > 1:
|
||||
ret += 's'
|
||||
ret += ' '
|
||||
ret += "s"
|
||||
ret += " "
|
||||
return ret
|
||||
else:
|
||||
return ''
|
||||
return ""
|
||||
|
||||
max_timedelta = datetime.timedelta(seconds=max_save_seconds)
|
||||
desc_zh, desc_en = '最长保存时间:', 'Max save time: '
|
||||
desc_zh += gen_desc_zh(max_timedelta.days, '天')
|
||||
desc_en += gen_desc_en(max_timedelta.days, 'day')
|
||||
desc_zh += gen_desc_zh(max_timedelta.seconds // 3600, '小时')
|
||||
desc_en += gen_desc_en(max_timedelta.seconds // 3600, 'hour')
|
||||
desc_zh += gen_desc_zh(max_timedelta.seconds % 3600 // 60, '分钟')
|
||||
desc_en += gen_desc_en(max_timedelta.seconds % 3600 // 60, 'minute')
|
||||
desc_zh += gen_desc_zh(max_timedelta.seconds % 60, '秒')
|
||||
desc_en += gen_desc_en(max_timedelta.seconds % 60, 'second')
|
||||
desc_zh, desc_en = "最长保存时间:", "Max save time: "
|
||||
desc_zh += gen_desc_zh(max_timedelta.days, "天")
|
||||
desc_en += gen_desc_en(max_timedelta.days, "day")
|
||||
desc_zh += gen_desc_zh(max_timedelta.seconds // 3600, "小时")
|
||||
desc_en += gen_desc_en(max_timedelta.seconds // 3600, "hour")
|
||||
desc_zh += gen_desc_zh(max_timedelta.seconds % 3600 // 60, "分钟")
|
||||
desc_en += gen_desc_en(max_timedelta.seconds % 3600 // 60, "minute")
|
||||
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]
|
||||
@@ -0,0 +1 @@
|
||||
APP_VERSION = "2.0.0-dev"
|
||||
@@ -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
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"hash": "8f855eaf",
|
||||
"configHash": "1b3ca22f",
|
||||
"lockfileHash": "bd28b2c2",
|
||||
"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": "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": "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": "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": "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": "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": "cc176c9c",
|
||||
"needsInterop": false
|
||||
}
|
||||
},
|
||||
"chunks": {
|
||||
"chunk-KT7LHMJ2": {
|
||||
"file": "chunk-KT7LHMJ2.js"
|
||||
},
|
||||
"chunk-CQOUZRMK": {
|
||||
"file": "chunk-CQOUZRMK.js"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": 3,
|
||||
"sources": ["../../../node_modules/.pnpm/@vue+shared@3.5.13/node_modules/@vue/shared/dist/shared.esm-bundler.js", "../../../node_modules/.pnpm/@vue+reactivity@3.5.13/node_modules/@vue/reactivity/dist/reactivity.esm-bundler.js", "../../../node_modules/.pnpm/@vue+runtime-core@3.5.13/node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js", "../../../node_modules/.pnpm/@vue+runtime-dom@3.5.13/node_modules/@vue/runtime-dom/dist/runtime-dom.esm-bundler.js", "../../../node_modules/.pnpm/vue@3.5.13/node_modules/vue/dist/vue.runtime.esm-bundler.js"],
|
||||
"sourcesContent": ["/**\n* @vue/shared v3.5.13\n* (c) 2018-present Yuxi (Evan) You and Vue contributors\n* @license MIT\n**/\n/*! #__NO_SIDE_EFFECTS__ */\n// @__NO_SIDE_EFFECTS__\nfunction makeMap(str) {\n const map = /* @__PURE__ */ Object.create(null);\n for (const key of str.split(\",\")) map[key] = 1;\n return (val) => val in map;\n}\n\nconst EMPTY_OBJ = !!(process.env.NODE_ENV !== \"production\") ? Object.freeze({}) : {};\nconst EMPTY_ARR = !!(process.env.NODE_ENV !== \"production\") ? Object.freeze([]) : [];\nconst NOOP = () => {\n};\nconst NO = () => false;\nconst isOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // uppercase letter\n(key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97);\nconst isModelListener = (key) => key.startsWith(\"onUpdate:\");\nconst extend = Object.assign;\nconst remove = (arr, el) => {\n const i = arr.indexOf(el);\n if (i > -1) {\n arr.splice(i, 1);\n }\n};\nconst hasOwnProperty = Object.prototype.hasOwnProperty;\nconst hasOwn = (val, key) => hasOwnProperty.call(val, key);\nconst isArray = Array.isArray;\nconst isMap = (val) => toTypeString(val) === \"[object Map]\";\nconst isSet = (val) => toTypeString(val) === \"[object Set]\";\nconst isDate = (val) => toTypeString(val) === \"[object Date]\";\nconst isRegExp = (val) => toTypeString(val) === \"[object RegExp]\";\nconst isFunction = (val) => typeof val === \"function\";\nconst isString = (val) => typeof val === \"string\";\nconst isSymbol = (val) => typeof val === \"symbol\";\nconst isObject = (val) => val !== null && typeof val === \"object\";\nconst isPromise = (val) => {\n return (isObject(val) || isFunction(val)) && isFunction(val.then) && isFunction(val.catch);\n};\nconst objectToString = Object.prototype.toString;\nconst toTypeString = (value) => objectToString.call(value);\nconst toRawType = (value) => {\n return toTypeString(value).slice(8, -1);\n};\nconst isPlainObject = (val) => toTypeString(val) === \"[object Object]\";\nconst isIntegerKey = (key) => isString(key) && key !== \"NaN\" && key[0] !== \"-\" && \"\" + parseInt(key, 10) === key;\nconst isReservedProp = /* @__PURE__ */ makeMap(\n // the leading comma is intentional so empty string \"\" is also included\n \",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted\"\n);\nconst isBuiltInDirective = /* @__PURE__ */ makeMap(\n \"bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo\"\n);\nconst cacheStringFunction = (fn) => {\n const cache = /* @__PURE__ */ Object.create(null);\n return (str) => {\n const hit = cache[str];\n return hit || (cache[str] = fn(str));\n };\n};\nconst camelizeRE = /-(\\w)/g;\nconst camelize = cacheStringFunction(\n (str) => {\n return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : \"\");\n }\n);\nconst hyphenateRE = /\\B([A-Z])/g;\nconst hyphenate = cacheStringFunction(\n (str) => str.replace(hyphenateRE, \"-$1\").toLowerCase()\n);\nconst capitalize = cacheStringFunction((str) => {\n return str.charAt(0).toUpperCase() + str.slice(1);\n});\nconst toHandlerKey = cacheStringFunction(\n (str) => {\n const s = str ? `on${capitalize(str)}` : ``;\n return s;\n }\n);\nconst hasChanged = (value, oldValue) => !Object.is(value, oldValue);\nconst invokeArrayFns = (fns, ...arg) => {\n for (let i = 0; i < fns.length; i++) {\n fns[i](...arg);\n }\n};\nconst def = (obj, key, value, writable = false) => {\n Object.defineProperty(obj, key, {\n configurable: true,\n enumerable: false,\n writable,\n value\n });\n};\nconst looseToNumber = (val) => {\n const n = parseFloat(val);\n return isNaN(n) ? val : n;\n};\nconst toNumber = (val) => {\n const n = isString(val) ? Number(val) : NaN;\n return isNaN(n) ? val : n;\n};\nlet _globalThis;\nconst getGlobalThis = () => {\n return _globalThis || (_globalThis = typeof globalThis !== \"undefined\" ? globalThis : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : typeof global !== \"undefined\" ? global : {});\n};\nconst identRE = /^[_$a-zA-Z\\xA0-\\uFFFF][_$a-zA-Z0-9\\xA0-\\uFFFF]*$/;\nfunction genPropsAccessExp(name) {\n return identRE.test(name) ? `__props.${name}` : `__props[${JSON.stringify(name)}]`;\n}\nfunction genCacheKey(source, options) {\n return source + JSON.stringify(\n options,\n (_, val) => typeof val === \"function\" ? val.toString() : val\n );\n}\n\nconst PatchFlags = {\n \"TEXT\": 1,\n \"1\": \"TEXT\",\n \"CLASS\": 2,\n \"2\": \"CLASS\",\n \"STYLE\": 4,\n \"4\": \"STYLE\",\n \"PROPS\": 8,\n \"8\": \"PROPS\",\n \"FULL_PROPS\": 16,\n \"16\": \"FULL_PROPS\",\n \"NEED_HYDRATION\": 32,\n \"32\": \"NEED_HYDRATION\",\n \"STABLE_FRAGMENT\": 64,\n \"64\": \"STABLE_FRAGMENT\",\n \"KEYED_FRAGMENT\": 128,\n \"128\": \"KEYED_FRAGMENT\",\n \"UNKEYED_FRAGMENT\": 256,\n \"256\": \"UNKEYED_FRAGMENT\",\n \"NEED_PATCH\": 512,\n \"512\": \"NEED_PATCH\",\n \"DYNAMIC_SLine truncated
|
||||
"mappings": "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 truncated
|
||||
"names": ["map", "computed", "computed", "self", "hasOwnProperty", "isRef", "readonly", "effect", "isRef", "isRef", "p", "version", "callHook", "remove", "ref", "patchProp", "hydrate", "hasWarned", "resolve", "watch", "render", "computed", "h", "createApp", "effect", "remove2", "track", "trigger", "isModelListener", "emit", "render2", "warn", "warn", "callHook", "resolve", "watch", "isBoolean", "def", "enterCbKey", "compile", "warn"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": 3,
|
||||
"sources": ["../../../node_modules/.pnpm/@vueuse+shared@12.5.0/node_modules/@vueuse/shared/index.mjs", "../../../node_modules/.pnpm/@vueuse+core@12.5.0/node_modules/@vueuse/core/index.mjs"],
|
||||
"sourcesContent": ["import { shallowRef, watchEffect, readonly, ref, watch, customRef, getCurrentScope, onScopeDispose, effectScope, getCurrentInstance, hasInjectionContext, inject, provide, isRef, unref, toValue as toValue$1, computed, reactive, toRefs as toRefs$1, toRef as toRef$1, onBeforeMount, nextTick, onBeforeUnmount, onMounted, onUnmounted, isReactive } from 'vue';\n\nfunction computedEager(fn, options) {\n var _a;\n const result = shallowRef();\n watchEffect(() => {\n result.value = fn();\n }, {\n ...options,\n flush: (_a = options == null ? undefined : options.flush) != null ? _a : \"sync\"\n });\n return readonly(result);\n}\n\nfunction computedWithControl(source, fn) {\n let v = undefined;\n let track;\n let trigger;\n const dirty = ref(true);\n const update = () => {\n dirty.value = true;\n trigger();\n };\n watch(source, update, { flush: \"sync\" });\n const get = typeof fn === \"function\" ? fn : fn.get;\n const set = typeof fn === \"function\" ? undefined : fn.set;\n const result = customRef((_track, _trigger) => {\n track = _track;\n trigger = _trigger;\n return {\n get() {\n if (dirty.value) {\n v = get(v);\n dirty.value = false;\n }\n track();\n return v;\n },\n set(v2) {\n set == null ? undefined : set(v2);\n }\n };\n });\n if (Object.isExtensible(result))\n result.trigger = update;\n return result;\n}\n\nfunction tryOnScopeDispose(fn) {\n if (getCurrentScope()) {\n onScopeDispose(fn);\n return true;\n }\n return false;\n}\n\nfunction createEventHook() {\n const fns = /* @__PURE__ */ new Set();\n const off = (fn) => {\n fns.delete(fn);\n };\n const clear = () => {\n fns.clear();\n };\n const on = (fn) => {\n fns.add(fn);\n const offFn = () => off(fn);\n tryOnScopeDispose(offFn);\n return {\n off: offFn\n };\n };\n const trigger = (...args) => {\n return Promise.all(Array.from(fns).map((fn) => fn(...args)));\n };\n return {\n on,\n off,\n trigger,\n clear\n };\n}\n\nfunction createGlobalState(stateFactory) {\n let initialized = false;\n let state;\n const scope = effectScope(true);\n return (...args) => {\n if (!initialized) {\n state = scope.run(() => stateFactory(...args));\n initialized = true;\n }\n return state;\n };\n}\n\nconst localProvidedStateMap = /* @__PURE__ */ new WeakMap();\n\nconst injectLocal = (...args) => {\n var _a;\n const key = args[0];\n const instance = (_a = getCurrentInstance()) == null ? undefined : _a.proxy;\n if (instance == null && !hasInjectionContext())\n throw new Error(\"injectLocal must be called in setup\");\n if (instance && localProvidedStateMap.has(instance) && key in localProvidedStateMap.get(instance))\n return localProvidedStateMap.get(instance)[key];\n return inject(...args);\n};\n\nconst provideLocal = (key, value) => {\n var _a;\n const instance = (_a = getCurrentInstance()) == null ? undefined : _a.proxy;\n if (instance == null)\n throw new Error(\"provideLocal must be called in setup\");\n if (!localProvidedStateMap.has(instance))\n localProvidedStateMap.set(instance, /* @__PURE__ */ Object.create(null));\n const localProvidedState = localProvidedStateMap.get(instance);\n localProvidedState[key] = value;\n provide(key, value);\n};\n\nfunction createInjectionState(composable, options) {\n const key = (options == null ? undefined : options.injectionKey) || Symbol(composable.name || \"InjectionState\");\n const defaultValue = options == null ? undefined : options.defaultValue;\n const useProvidingState = (...args) => {\n const state = composable(...args);\n provideLocal(key, state);\n return state;\n };\n const useInjectedState = () => injectLocal(key, defaultValue);\n return [useProvidingState, useInjectedState];\n}\n\nfunction createSharedComposable(composable) {\n let subscribers = 0;\n let state;\n let scope;\n const dispose = () => {\n subscribers -= 1;\n if (scope && subscribers <= 0) {\n scope.stop();\n state = undefined;\n scope = undefined;\n }\n };\n return (...args) => {\n subscribers += 1;\n if (!scope) {\n scope = effectScope(true);\n state = scope.run(() => composable(...args));\n }\n tryOnScopeDispose(dispose);\n return state;\n };\n}\n\nfunction extendRef(ref, extend, { enumerable = false, unwrap = true } = {}) {\n for (const [key, value] of Object.entries(extend)) {\n if (key === \"value\")\n continue;\n if (isRef(value) && unwrap) {\n Object.defineProperty(ref, key, {\n get() {\n return value.value;\n },\n set(v) {\n value.value = v;\n },\n enumerable\n });\n } else {\n Object.defineProperty(ref, key, { value, enumerable });\n }\n }\n return ref;\n}\n\nfunction get(obj, key) {\n if (key == null)\n return unref(obj);\n return unref(obj)[kLine truncated
|
||||
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,cAAc,IAAI,SAAS;AAClC,MAAI;AACJ,QAAM,SAAS,WAAW;AAC1B,cAAY,MAAM;AAChB,WAAO,QAAQ,GAAG;AAAA,EACpB,GAAG;AAAA,IACD,GAAG;AAAA,IACH,QAAQ,KAAK,WAAW,OAAO,SAAY,QAAQ,UAAU,OAAO,KAAK;AAAA,EAC3E,CAAC;AACD,SAAO,SAAS,MAAM;AACxB;AAEA,SAAS,oBAAoB,QAAQ,IAAI;AACvC,MAAI,IAAI;AACR,MAAI;AACJ,MAAI;AACJ,QAAM,QAAQ,IAAI,IAAI;AACtB,QAAM,SAAS,MAAM;AACnB,UAAM,QAAQ;AACd,YAAQ;AAAA,EACV;AACA,QAAM,QAAQ,QAAQ,EAAE,OAAO,OAAO,CAAC;AACvC,QAAMA,OAAM,OAAO,OAAO,aAAa,KAAK,GAAG;AAC/C,QAAMC,OAAM,OAAO,OAAO,aAAa,SAAY,GAAG;AACtD,QAAM,SAAS,UAAU,CAAC,QAAQ,aAAa;AAC7C,YAAQ;AACR,cAAU;AACV,WAAO;AAAA,MACL,MAAM;AACJ,YAAI,MAAM,OAAO;AACf,cAAID,KAAI,CAAC;AACT,gBAAM,QAAQ;AAAA,QAChB;AACA,cAAM;AACN,eAAO;AAAA,MACT;AAAA,MACA,IAAI,IAAI;AACN,QAAAC,QAAO,OAAO,SAAYA,KAAI,EAAE;AAAA,MAClC;AAAA,IACF;AAAA,EACF,CAAC;AACD,MAAI,OAAO,aAAa,MAAM;AAC5B,WAAO,UAAU;AACnB,SAAO;AACT;AAEA,SAAS,kBAAkB,IAAI;AAC7B,MAAI,gBAAgB,GAAG;AACrB,mBAAe,EAAE;AACjB,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,SAAS,kBAAkB;AACzB,QAAM,MAAsB,oBAAI,IAAI;AACpC,QAAM,MAAM,CAAC,OAAO;AAClB,QAAI,OAAO,EAAE;AAAA,EACf;AACA,QAAM,QAAQ,MAAM;AAClB,QAAI,MAAM;AAAA,EACZ;AACA,QAAM,KAAK,CAAC,OAAO;AACjB,QAAI,IAAI,EAAE;AACV,UAAM,QAAQ,MAAM,IAAI,EAAE;AAC1B,sBAAkB,KAAK;AACvB,WAAO;AAAA,MACL,KAAK;AAAA,IACP;AAAA,EACF;AACA,QAAM,UAAU,IAAI,SAAS;AAC3B,WAAO,QAAQ,IAAI,MAAM,KAAK,GAAG,EAAE,IAAI,CAAC,OAAO,GAAG,GAAG,IAAI,CAAC,CAAC;AAAA,EAC7D;AACA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEA,SAAS,kBAAkB,cAAc;AACvC,MAAI,cAAc;AAClB,MAAI;AACJ,QAAM,QAAQ,YAAY,IAAI;AAC9B,SAAO,IAAI,SAAS;AAClB,QAAI,CAAC,aAAa;AAChB,cAAQ,MAAM,IAAI,MAAM,aAAa,GAAG,IAAI,CAAC;AAC7C,oBAAc;AAAA,IAChB;AACA,WAAO;AAAA,EACT;AACF;AAEA,IAAM,wBAAwC,oBAAI,QAAQ;AAE1D,IAAM,cAAc,IAAI,SAAS;AAC/B,MAAI;AACJ,QAAM,MAAM,KAAK,CAAC;AAClB,QAAM,YAAY,KAAK,mBAAmB,MAAM,OAAO,SAAY,GAAG;AACtE,MAAI,YAAY,QAAQ,CAAC,oBAAoB;AAC3C,UAAM,IAAI,MAAM,qCAAqC;AACvD,MAAI,YAAY,sBAAsB,IAAI,QAAQ,KAAK,OAAO,sBAAsB,IAAI,QAAQ;AAC9F,WAAO,sBAAsB,IAAI,QAAQ,EAAE,GAAG;AAChD,SAAO,OAAO,GAAG,IAAI;AACvB;AAEA,IAAM,eAAe,CAAC,KAAK,UAAU;AACnC,MAAI;AACJ,QAAM,YAAY,KAAK,mBAAmB,MAAM,OAAO,SAAY,GAAG;AACtE,MAAI,YAAY;AACd,UAAM,IAAI,MAAM,sCAAsC;AACxD,MAAI,CAAC,sBAAsB,IAAI,QAAQ;AACrC,0BAAsB,IAAI,UAA0B,uBAAO,OAAO,IAAI,CAAC;AACzE,QAAM,qBAAqB,sBAAsB,IAAI,QAAQ;AAC7D,qBAAmB,GAAG,IAAI;AAC1B,UAAQ,KAAK,KAAK;AACpB;AAEA,SAAS,qBAAqB,YAAY,SAAS;AACjD,QAAM,OAAO,WAAW,OAAO,SAAY,QAAQ,iBAAiB,OAAO,WAAW,QAAQ,gBAAgB;AAC9G,QAAM,eAAe,WAAW,OAAO,SAAY,QAAQ;AAC3D,QAAM,oBAAoB,IAAI,SAAS;AACrC,UAAM,QAAQ,WAAW,GAAG,IAAI;AAChC,iBAAa,KAAK,KAAK;AACvB,WAAO;AAAA,EACT;AACA,QAAM,mBAAmB,MAAM,YAAY,KAAK,YAAY;AAC5D,SAAO,CAAC,mBAAmB,gBAAgB;AAC7C;AAEA,SAAS,uBAAuB,YAAY;AAC1C,MAAI,cAAc;AAClB,MAAI;AACJ,MAAI;AACJ,QAAM,UAAU,MAAM;AACpB,mBAAe;AACf,QAAI,SAAS,eAAe,GAAG;AAC7B,YAAM,KAAK;AACX,cAAQ;AACR,cAAQ;AAAA,IACV;AAAA,EACF;AACA,SAAO,IAAI,SAAS;AAClB,mBAAe;AACf,QAAI,CAAC,OAAO;AACV,cAAQ,YAAY,IAAI;AACxB,cAAQ,MAAM,IAAI,MAAM,WAAW,GAAG,IAAI,CAAC;AAAA,IAC7C;AACA,sBAAkB,OAAO;AACzB,WAAO;AAAA,EACT;AACF;AAEA,SAAS,UAAUC,MAAK,QAAQ,EAAE,aAAa,OAAO,SAAS,KAAK,IAAI,CAAC,GAAG;AAC1E,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AACjD,QAAI,QAAQ;AACV;AACF,QAAI,MAAM,KAAK,KAAK,QAAQ;AAC1B,aAAO,eAAeA,MAAK,KAAK;AAAA,QAC9B,MAAM;AACJ,iBAAO,MAAM;AAAA,QACf;AAAA,QACA,IAAI,GAAG;AACL,gBAAM,QAAQ;AAAA,QAChB;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH,OAAO;AACL,aAAO,eAAeA,MAAK,KAAK,EAAE,OAAO,WAAW,CAAC;AAAA,IACvD;AAAA,EACF;AACA,SAAOA;AACT;AAEA,SAAS,IAAI,KAAK,KAAK;AACrB,MAAI,OAAO;AACT,WAAO,MAAM,GAAG;AAClB,SAAO,MAAM,GAAG,EAAE,GAAG;AACvB;AAEA,SAAS,UAAU,GAAG;AACpB,SAAO,MAAM,CAAC,KAAK;AACrB;AAEA,SAAS,mBAAmB,KAAK,KAAK;AACpC,MAAI,OAAO,WAAW,aAAa;AACjC,UAAM,QAAQ,EAAE,GAAG,IAAI;AACvB,WAAO,eAAe,OAAO,OAAO,UAAU;AAAA,MAC5C,YAAY;AAAA,MACZ,QAAQ;AACN,YAAI,QAAQ;AACZ,eAAO;AAAA,UACL,MAAM,OAAO;AAAA,YACX,OAAO,IAAI,OAAO;AAAA,YAClB,MAAM,QAAQ,IAAI;AAAA,UACpB;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AACD,WAAO;AAAA,EACT,OAAO;AACL,WAAO,OAAO,OAAO,CAAC,GAAG,GAAG,GAAG,GAAG;AAAA,EACpC;AACF;AAEA,SAAS,SAAS,IAAI,SAAS;AAC7B,QAAM,WAAW,WAAW,OAAO,SAAY,QAAQ,oBAAoB,QAAQ,QAAQ;AAC3F,SAAO,YAAY,MAAM;AACvB,WAAO,SAAS,MAAM,GAAG,MAAM,MAAM,KAAK,IAAI,CAAC,MAAM,QAAQ,CAAC,CAAC,CAAC,CAAC;AAAA,EACnE;AACF;AAEA,SAAS,eAAe,KAAK,gBAAgB,CAAC,GAAG;AAC/C,MAAIC,QAAO,CAAC;AACZ,MAAI;AACJ,MAAI,MAAM,QAAQ,aAAa,GAAG;AAChC,IAAAA,QAAO;AAAA,EACT,OAAO;AACL,cAAU;AACV,UAAM,EAAE,uBAAuB,KAAK,IAAI;AACxC,IAAAA,MAAK,KAAK,GAAG,OAAO,KAAK,GAAG,CAAC;AAC7B,QAAI;AACF,MAAAA,MAAK,KAAK,GAAG,OAAO,oBAAoB,GAAG,CAAC;AAAA,EAChD;AACA,SAAO,OAAO;AAAA,IACZA,MAAK,IAAI,CAAC,QAAQ;AAChB,YAAM,QAAQ,IAAI,GAAG;AACrB,aAAO;AAAA,QACL;AAAA,QACA,OAAO,UAAU,aAAa,SAAS,MAAM,KAAK,GAAG,GAAG,OAAO,IAAI;AAAA,MACrE;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAEA,SAAS,WAAW,WAAW;AAC7B,MAAI,CAAC,MAAM,SAAS;AAClB,WAAO,SAAS,SAAS;AAC3B,QAAM,QAAQ,IAAI,MAAM,CAAC,GAAG;AAAA,IAC1B,IAAI,GAAG,GAAG,UAAU;AAClB,aAAO,MAAM,QAAQ,IAAI,UAAU,OAAO,GAAG,QAAQ,CAAC;AAAA,IACxD;AAAA,IACA,IAAI,GAAG,GAAG,OAAO;AACf,UAAI,MAAM,UAAU,MAAM,CAAC,CAAC,KAAK,CAAC,MAAM,KAAK;AAC3C,kBAAU,MAAM,CAAC,EAAE,QAAQ;AAAA;AAE3B,kBAAU,MAAM,CAAC,IAAI;AACvB,aAAO;AAAA,IACT;AAAA,IACA,eAAe,GAAG,GAAG;AACnB,aAAO,QAAQ,eAAe,UAAU,OAAO,CAAC;AAAA,IAClD;AAAA,IACA,IAAI,GAAG,GAAG;AALine truncated
|
||||
"names": ["get", "set", "ref", "keys", "invoke", "toRef", "toRefs", "toValue", "window", "document", "timestamp", "navigator", "events", "getValue", "defaults", "toRef", "set", "onUpdated", "preventDefault", "toRefs", "now", "keys", "get", "isReadonly"]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"type": "module"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": 3,
|
||||
"sources": ["../../../node_modules/.pnpm/@vue+devtools-shared@7.7.1/node_modules/@vue/devtools-shared/dist/index.js", "../../../node_modules/.pnpm/perfect-debounce@1.0.0/node_modules/perfect-debounce/dist/index.mjs", "../../../node_modules/.pnpm/hookable@5.5.3/node_modules/hookable/dist/index.mjs", "../../../node_modules/.pnpm/birpc@0.2.19/node_modules/birpc/dist/index.mjs", "../../../node_modules/.pnpm/@vue+devtools-kit@7.7.1/node_modules/@vue/devtools-kit/dist/index.js"],
|
||||
"sourcesContent": ["var __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __esm = (fn, res) => function __init() {\n return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;\n};\nvar __commonJS = (cb, mod) => function __require() {\n return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target2) => (target2 = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target2, \"default\", { value: mod, enumerable: true }) : target2,\n mod\n));\n\n// ../../node_modules/.pnpm/tsup@8.3.5_@microsoft+api-extractor@7.48.1_@types+node@22.10.5__jiti@2.4.2_postcss@8.4.49_tsx_s7k37zks4wtn7x2grzma6lrsfa/node_modules/tsup/assets/esm_shims.js\nvar init_esm_shims = __esm({\n \"../../node_modules/.pnpm/tsup@8.3.5_@microsoft+api-extractor@7.48.1_@types+node@22.10.5__jiti@2.4.2_postcss@8.4.49_tsx_s7k37zks4wtn7x2grzma6lrsfa/node_modules/tsup/assets/esm_shims.js\"() {\n \"use strict\";\n }\n});\n\n// ../../node_modules/.pnpm/rfdc@1.4.1/node_modules/rfdc/index.js\nvar require_rfdc = __commonJS({\n \"../../node_modules/.pnpm/rfdc@1.4.1/node_modules/rfdc/index.js\"(exports, module) {\n \"use strict\";\n init_esm_shims();\n module.exports = rfdc2;\n function copyBuffer(cur) {\n if (cur instanceof Buffer) {\n return Buffer.from(cur);\n }\n return new cur.constructor(cur.buffer.slice(), cur.byteOffset, cur.length);\n }\n function rfdc2(opts) {\n opts = opts || {};\n if (opts.circles) return rfdcCircles(opts);\n const constructorHandlers = /* @__PURE__ */ new Map();\n constructorHandlers.set(Date, (o) => new Date(o));\n constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn)));\n constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn)));\n if (opts.constructorHandlers) {\n for (const handler2 of opts.constructorHandlers) {\n constructorHandlers.set(handler2[0], handler2[1]);\n }\n }\n let handler = null;\n return opts.proto ? cloneProto : clone;\n function cloneArray(a, fn) {\n const keys = Object.keys(a);\n const a2 = new Array(keys.length);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n const cur = a[k];\n if (typeof cur !== \"object\" || cur === null) {\n a2[k] = cur;\n } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {\n a2[k] = handler(cur, fn);\n } else if (ArrayBuffer.isView(cur)) {\n a2[k] = copyBuffer(cur);\n } else {\n a2[k] = fn(cur);\n }\n }\n return a2;\n }\n function clone(o) {\n if (typeof o !== \"object\" || o === null) return o;\n if (Array.isArray(o)) return cloneArray(o, clone);\n if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) {\n return handler(o, clone);\n }\n const o2 = {};\n for (const k in o) {\n if (Object.hasOwnProperty.call(o, k) === false) continue;\n const cur = o[k];\n if (typeof cur !== \"object\" || cur === null) {\n o2[k] = cur;\n } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {\n o2[k] = handler(cur, clone);\n } else if (ArrayBuffer.isView(cur)) {\n o2[k] = copyBuffer(cur);\n } else {\n o2[k] = clone(cur);\n }\n }\n return o2;\n }\n function cloneProto(o) {\n if (typeof o !== \"object\" || o === null) return o;\n if (Array.isArray(o)) return cloneArray(o, cloneProto);\n if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) {\n return handler(o, cloneProto);\n }\n const o2 = {};\n for (const k in o) {\n const cur = o[k];\n if (tLine truncated
|
||||
"mappings": "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 truncated
|
||||
"names": ["hooks", "hooks", "hook", "hook", "hooks", "clearTimeout", "setTimeout", "__create", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__getProtoOf", "__hasOwnProp", "__esm", "__commonJS", "__copyProps", "__toESM", "init_esm_shims", "init_esm_shims", "init_esm_shims", "_a", "init_esm_shims", "init_esm_shims", "init_esm_shims", "_a2", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "__toESM", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "_a22", "init_esm_shims", "init_esm_shims"]
|
||||
}
|
||||
@@ -0,0 +1,581 @@
|
||||
import {
|
||||
DefaultMagicKeysAliasMap,
|
||||
StorageSerializers,
|
||||
TransitionPresets,
|
||||
assert,
|
||||
breakpointsAntDesign,
|
||||
breakpointsBootstrapV5,
|
||||
breakpointsElement,
|
||||
breakpointsMasterCss,
|
||||
breakpointsPrimeFlex,
|
||||
breakpointsQuasar,
|
||||
breakpointsSematic,
|
||||
breakpointsTailwind,
|
||||
breakpointsVuetify,
|
||||
breakpointsVuetifyV2,
|
||||
breakpointsVuetifyV3,
|
||||
bypassFilter,
|
||||
camelize,
|
||||
clamp,
|
||||
cloneFnJSON,
|
||||
computedAsync,
|
||||
computedEager,
|
||||
computedInject,
|
||||
computedWithControl,
|
||||
containsProp,
|
||||
controlledRef,
|
||||
createEventHook,
|
||||
createFetch,
|
||||
createFilterWrapper,
|
||||
createGlobalState,
|
||||
createInjectionState,
|
||||
createReusableTemplate,
|
||||
createSharedComposable,
|
||||
createSingletonPromise,
|
||||
createTemplatePromise,
|
||||
createUnrefFn,
|
||||
customStorageEventName,
|
||||
debounceFilter,
|
||||
defaultDocument,
|
||||
defaultLocation,
|
||||
defaultNavigator,
|
||||
defaultWindow,
|
||||
executeTransition,
|
||||
extendRef,
|
||||
formatDate,
|
||||
formatTimeAgo,
|
||||
get,
|
||||
getLifeCycleTarget,
|
||||
getSSRHandler,
|
||||
hasOwn,
|
||||
hyphenate,
|
||||
identity,
|
||||
increaseWithUnit,
|
||||
injectLocal,
|
||||
invoke,
|
||||
isClient,
|
||||
isDef,
|
||||
isDefined,
|
||||
isIOS,
|
||||
isObject,
|
||||
isWorker,
|
||||
makeDestructurable,
|
||||
mapGamepadToXbox360Controller,
|
||||
noop,
|
||||
normalizeDate,
|
||||
notNullish,
|
||||
now,
|
||||
objectEntries,
|
||||
objectOmit,
|
||||
objectPick,
|
||||
onClickOutside,
|
||||
onElementRemoval,
|
||||
onKeyDown,
|
||||
onKeyPressed,
|
||||
onKeyStroke,
|
||||
onKeyUp,
|
||||
onLongPress,
|
||||
onStartTyping,
|
||||
pausableFilter,
|
||||
promiseTimeout,
|
||||
provideLocal,
|
||||
provideSSRWidth,
|
||||
pxValue,
|
||||
rand,
|
||||
reactify,
|
||||
reactifyObject,
|
||||
reactiveComputed,
|
||||
reactiveOmit,
|
||||
reactivePick,
|
||||
refAutoReset,
|
||||
refDebounced,
|
||||
refDefault,
|
||||
refThrottled,
|
||||
refWithControl,
|
||||
resolveRef,
|
||||
resolveUnref,
|
||||
set,
|
||||
setSSRHandler,
|
||||
syncRef,
|
||||
syncRefs,
|
||||
templateRef,
|
||||
throttleFilter,
|
||||
timestamp,
|
||||
toArray,
|
||||
toReactive,
|
||||
toRef,
|
||||
toRefs,
|
||||
toValue,
|
||||
tryOnBeforeMount,
|
||||
tryOnBeforeUnmount,
|
||||
tryOnMounted,
|
||||
tryOnScopeDispose,
|
||||
tryOnUnmounted,
|
||||
unrefElement,
|
||||
until,
|
||||
useActiveElement,
|
||||
useAnimate,
|
||||
useArrayDifference,
|
||||
useArrayEvery,
|
||||
useArrayFilter,
|
||||
useArrayFind,
|
||||
useArrayFindIndex,
|
||||
useArrayFindLast,
|
||||
useArrayIncludes,
|
||||
useArrayJoin,
|
||||
useArrayMap,
|
||||
useArrayReduce,
|
||||
useArraySome,
|
||||
useArrayUnique,
|
||||
useAsyncQueue,
|
||||
useAsyncState,
|
||||
useBase64,
|
||||
useBattery,
|
||||
useBluetooth,
|
||||
useBreakpoints,
|
||||
useBroadcastChannel,
|
||||
useBrowserLocation,
|
||||
useCached,
|
||||
useClipboard,
|
||||
useClipboardItems,
|
||||
useCloned,
|
||||
useColorMode,
|
||||
useConfirmDialog,
|
||||
useCountdown,
|
||||
useCounter,
|
||||
useCssVar,
|
||||
useCurrentElement,
|
||||
useCycleList,
|
||||
useDark,
|
||||
useDateFormat,
|
||||
useDebounceFn,
|
||||
useDebouncedRefHistory,
|
||||
useDeviceMotion,
|
||||
useDeviceOrientation,
|
||||
useDevicePixelRatio,
|
||||
useDevicesList,
|
||||
useDisplayMedia,
|
||||
useDocumentVisibility,
|
||||
useDraggable,
|
||||
useDropZone,
|
||||
useElementBounding,
|
||||
useElementByPoint,
|
||||
useElementHover,
|
||||
useElementSize,
|
||||
useElementVisibility,
|
||||
useEventBus,
|
||||
useEventListener,
|
||||
useEventSource,
|
||||
useEyeDropper,
|
||||
useFavicon,
|
||||
useFetch,
|
||||
useFileDialog,
|
||||
useFileSystemAccess,
|
||||
useFocus,
|
||||
useFocusWithin,
|
||||
useFps,
|
||||
useFullscreen,
|
||||
useGamepad,
|
||||
useGeolocation,
|
||||
useIdle,
|
||||
useImage,
|
||||
useInfiniteScroll,
|
||||
useIntersectionObserver,
|
||||
useInterval,
|
||||
useIntervalFn,
|
||||
useKeyModifier,
|
||||
useLastChanged,
|
||||
useLocalStorage,
|
||||
useMagicKeys,
|
||||
useManualRefHistory,
|
||||
useMediaControls,
|
||||
useMediaQuery,
|
||||
useMemoize,
|
||||
useMemory,
|
||||
useMounted,
|
||||
useMouse,
|
||||
useMouseInElement,
|
||||
useMousePressed,
|
||||
useMutationObserver,
|
||||
useNavigatorLanguage,
|
||||
useNetwork,
|
||||
useNow,
|
||||
useObjectUrl,
|
||||
useOffsetPagination,
|
||||
useOnline,
|
||||
usePageLeave,
|
||||
useParallax,
|
||||
useParentElement,
|
||||
usePerformanceObserver,
|
||||
usePermission,
|
||||
usePointer,
|
||||
usePointerLock,
|
||||
usePointerSwipe,
|
||||
usePreferredColorScheme,
|
||||
usePreferredContrast,
|
||||
usePreferredDark,
|
||||
usePreferredLanguages,
|
||||
usePreferredReducedMotion,
|
||||
usePreferredReducedTransparency,
|
||||
usePrevious,
|
||||
useRafFn,
|
||||
useRefHistory,
|
||||
useResizeObserver,
|
||||
useSSRWidth,
|
||||
useScreenOrientation,
|
||||
useScreenSafeArea,
|
||||
useScriptTag,
|
||||
useScroll,
|
||||
useScrollLock,
|
||||
useSessionStorage,
|
||||
useShare,
|
||||
useSorted,
|
||||
useSpeechRecognition,
|
||||
useSpeechSynthesis,
|
||||
useStepper,
|
||||
useStorage,
|
||||
useStorageAsync,
|
||||
useStyleTag,
|
||||
useSupported,
|
||||
useSwipe,
|
||||
useTemplateRefsList,
|
||||
useTextDirection,
|
||||
useTextSelection,
|
||||
useTextareaAutosize,
|
||||
useThrottleFn,
|
||||
useThrottledRefHistory,
|
||||
useTimeAgo,
|
||||
useTimeout,
|
||||
useTimeoutFn,
|
||||
useTimeoutPoll,
|
||||
useTimestamp,
|
||||
useTitle,
|
||||
useToNumber,
|
||||
useToString,
|
||||
useToggle,
|
||||
useTransition,
|
||||
useUrlSearchParams,
|
||||
useUserMedia,
|
||||
useVModel,
|
||||
useVModels,
|
||||
useVibrate,
|
||||
useVirtualList,
|
||||
useWakeLock,
|
||||
useWebNotification,
|
||||
useWebSocket,
|
||||
useWebWorker,
|
||||
useWebWorkerFn,
|
||||
useWindowFocus,
|
||||
useWindowScroll,
|
||||
useWindowSize,
|
||||
watchArray,
|
||||
watchAtMost,
|
||||
watchDebounced,
|
||||
watchDeep,
|
||||
watchIgnorable,
|
||||
watchImmediate,
|
||||
watchOnce,
|
||||
watchPausable,
|
||||
watchThrottled,
|
||||
watchTriggerable,
|
||||
watchWithFilter,
|
||||
whenever
|
||||
} from "./chunk-KT7LHMJ2.js";
|
||||
import "./chunk-CQOUZRMK.js";
|
||||
export {
|
||||
DefaultMagicKeysAliasMap,
|
||||
StorageSerializers,
|
||||
TransitionPresets,
|
||||
assert,
|
||||
computedAsync as asyncComputed,
|
||||
refAutoReset as autoResetRef,
|
||||
breakpointsAntDesign,
|
||||
breakpointsBootstrapV5,
|
||||
breakpointsElement,
|
||||
breakpointsMasterCss,
|
||||
breakpointsPrimeFlex,
|
||||
breakpointsQuasar,
|
||||
breakpointsSematic,
|
||||
breakpointsTailwind,
|
||||
breakpointsVuetify,
|
||||
breakpointsVuetifyV2,
|
||||
breakpointsVuetifyV3,
|
||||
bypassFilter,
|
||||
camelize,
|
||||
clamp,
|
||||
cloneFnJSON,
|
||||
computedAsync,
|
||||
computedEager,
|
||||
computedInject,
|
||||
computedWithControl,
|
||||
containsProp,
|
||||
computedWithControl as controlledComputed,
|
||||
controlledRef,
|
||||
createEventHook,
|
||||
createFetch,
|
||||
createFilterWrapper,
|
||||
createGlobalState,
|
||||
createInjectionState,
|
||||
reactify as createReactiveFn,
|
||||
createReusableTemplate,
|
||||
createSharedComposable,
|
||||
createSingletonPromise,
|
||||
createTemplatePromise,
|
||||
createUnrefFn,
|
||||
customStorageEventName,
|
||||
debounceFilter,
|
||||
refDebounced as debouncedRef,
|
||||
watchDebounced as debouncedWatch,
|
||||
defaultDocument,
|
||||
defaultLocation,
|
||||
defaultNavigator,
|
||||
defaultWindow,
|
||||
computedEager as eagerComputed,
|
||||
executeTransition,
|
||||
extendRef,
|
||||
formatDate,
|
||||
formatTimeAgo,
|
||||
get,
|
||||
getLifeCycleTarget,
|
||||
getSSRHandler,
|
||||
hasOwn,
|
||||
hyphenate,
|
||||
identity,
|
||||
watchIgnorable as ignorableWatch,
|
||||
increaseWithUnit,
|
||||
injectLocal,
|
||||
invoke,
|
||||
isClient,
|
||||
isDef,
|
||||
isDefined,
|
||||
isIOS,
|
||||
isObject,
|
||||
isWorker,
|
||||
makeDestructurable,
|
||||
mapGamepadToXbox360Controller,
|
||||
noop,
|
||||
normalizeDate,
|
||||
notNullish,
|
||||
now,
|
||||
objectEntries,
|
||||
objectOmit,
|
||||
objectPick,
|
||||
onClickOutside,
|
||||
onElementRemoval,
|
||||
onKeyDown,
|
||||
onKeyPressed,
|
||||
onKeyStroke,
|
||||
onKeyUp,
|
||||
onLongPress,
|
||||
onStartTyping,
|
||||
pausableFilter,
|
||||
watchPausable as pausableWatch,
|
||||
promiseTimeout,
|
||||
provideLocal,
|
||||
provideSSRWidth,
|
||||
pxValue,
|
||||
rand,
|
||||
reactify,
|
||||
reactifyObject,
|
||||
reactiveComputed,
|
||||
reactiveOmit,
|
||||
reactivePick,
|
||||
refAutoReset,
|
||||
refDebounced,
|
||||
refDefault,
|
||||
refThrottled,
|
||||
refWithControl,
|
||||
resolveRef,
|
||||
resolveUnref,
|
||||
set,
|
||||
setSSRHandler,
|
||||
syncRef,
|
||||
syncRefs,
|
||||
templateRef,
|
||||
throttleFilter,
|
||||
refThrottled as throttledRef,
|
||||
watchThrottled as throttledWatch,
|
||||
timestamp,
|
||||
toArray,
|
||||
toReactive,
|
||||
toRef,
|
||||
toRefs,
|
||||
toValue,
|
||||
tryOnBeforeMount,
|
||||
tryOnBeforeUnmount,
|
||||
tryOnMounted,
|
||||
tryOnScopeDispose,
|
||||
tryOnUnmounted,
|
||||
unrefElement,
|
||||
until,
|
||||
useActiveElement,
|
||||
useAnimate,
|
||||
useArrayDifference,
|
||||
useArrayEvery,
|
||||
useArrayFilter,
|
||||
useArrayFind,
|
||||
useArrayFindIndex,
|
||||
useArrayFindLast,
|
||||
useArrayIncludes,
|
||||
useArrayJoin,
|
||||
useArrayMap,
|
||||
useArrayReduce,
|
||||
useArraySome,
|
||||
useArrayUnique,
|
||||
useAsyncQueue,
|
||||
useAsyncState,
|
||||
useBase64,
|
||||
useBattery,
|
||||
useBluetooth,
|
||||
useBreakpoints,
|
||||
useBroadcastChannel,
|
||||
useBrowserLocation,
|
||||
useCached,
|
||||
useClipboard,
|
||||
useClipboardItems,
|
||||
useCloned,
|
||||
useColorMode,
|
||||
useConfirmDialog,
|
||||
useCountdown,
|
||||
useCounter,
|
||||
useCssVar,
|
||||
useCurrentElement,
|
||||
useCycleList,
|
||||
useDark,
|
||||
useDateFormat,
|
||||
refDebounced as useDebounce,
|
||||
useDebounceFn,
|
||||
useDebouncedRefHistory,
|
||||
useDeviceMotion,
|
||||
useDeviceOrientation,
|
||||
useDevicePixelRatio,
|
||||
useDevicesList,
|
||||
useDisplayMedia,
|
||||
useDocumentVisibility,
|
||||
useDraggable,
|
||||
useDropZone,
|
||||
useElementBounding,
|
||||
useElementByPoint,
|
||||
useElementHover,
|
||||
useElementSize,
|
||||
useElementVisibility,
|
||||
useEventBus,
|
||||
useEventListener,
|
||||
useEventSource,
|
||||
useEyeDropper,
|
||||
useFavicon,
|
||||
useFetch,
|
||||
useFileDialog,
|
||||
useFileSystemAccess,
|
||||
useFocus,
|
||||
useFocusWithin,
|
||||
useFps,
|
||||
useFullscreen,
|
||||
useGamepad,
|
||||
useGeolocation,
|
||||
useIdle,
|
||||
useImage,
|
||||
useInfiniteScroll,
|
||||
useIntersectionObserver,
|
||||
useInterval,
|
||||
useIntervalFn,
|
||||
useKeyModifier,
|
||||
useLastChanged,
|
||||
useLocalStorage,
|
||||
useMagicKeys,
|
||||
useManualRefHistory,
|
||||
useMediaControls,
|
||||
useMediaQuery,
|
||||
useMemoize,
|
||||
useMemory,
|
||||
useMounted,
|
||||
useMouse,
|
||||
useMouseInElement,
|
||||
useMousePressed,
|
||||
useMutationObserver,
|
||||
useNavigatorLanguage,
|
||||
useNetwork,
|
||||
useNow,
|
||||
useObjectUrl,
|
||||
useOffsetPagination,
|
||||
useOnline,
|
||||
usePageLeave,
|
||||
useParallax,
|
||||
useParentElement,
|
||||
usePerformanceObserver,
|
||||
usePermission,
|
||||
usePointer,
|
||||
usePointerLock,
|
||||
usePointerSwipe,
|
||||
usePreferredColorScheme,
|
||||
usePreferredContrast,
|
||||
usePreferredDark,
|
||||
usePreferredLanguages,
|
||||
usePreferredReducedMotion,
|
||||
usePreferredReducedTransparency,
|
||||
usePrevious,
|
||||
useRafFn,
|
||||
useRefHistory,
|
||||
useResizeObserver,
|
||||
useSSRWidth,
|
||||
useScreenOrientation,
|
||||
useScreenSafeArea,
|
||||
useScriptTag,
|
||||
useScroll,
|
||||
useScrollLock,
|
||||
useSessionStorage,
|
||||
useShare,
|
||||
useSorted,
|
||||
useSpeechRecognition,
|
||||
useSpeechSynthesis,
|
||||
useStepper,
|
||||
useStorage,
|
||||
useStorageAsync,
|
||||
useStyleTag,
|
||||
useSupported,
|
||||
useSwipe,
|
||||
useTemplateRefsList,
|
||||
useTextDirection,
|
||||
useTextSelection,
|
||||
useTextareaAutosize,
|
||||
refThrottled as useThrottle,
|
||||
useThrottleFn,
|
||||
useThrottledRefHistory,
|
||||
useTimeAgo,
|
||||
useTimeout,
|
||||
useTimeoutFn,
|
||||
useTimeoutPoll,
|
||||
useTimestamp,
|
||||
useTitle,
|
||||
useToNumber,
|
||||
useToString,
|
||||
useToggle,
|
||||
useTransition,
|
||||
useUrlSearchParams,
|
||||
useUserMedia,
|
||||
useVModel,
|
||||
useVModels,
|
||||
useVibrate,
|
||||
useVirtualList,
|
||||
useWakeLock,
|
||||
useWebNotification,
|
||||
useWebSocket,
|
||||
useWebWorker,
|
||||
useWebWorkerFn,
|
||||
useWindowFocus,
|
||||
useWindowScroll,
|
||||
useWindowSize,
|
||||
watchArray,
|
||||
watchAtMost,
|
||||
watchDebounced,
|
||||
watchDeep,
|
||||
watchIgnorable,
|
||||
watchImmediate,
|
||||
watchOnce,
|
||||
watchPausable,
|
||||
watchThrottled,
|
||||
watchTriggerable,
|
||||
watchWithFilter,
|
||||
whenever
|
||||
};
|
||||
//# sourceMappingURL=vitepress___@vueuse_core.js.map
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": 3,
|
||||
"sources": [],
|
||||
"sourcesContent": [],
|
||||
"mappings": "",
|
||||
"names": []
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": 3,
|
||||
"sources": ["../../../node_modules/.pnpm/tabbable@6.2.0/node_modules/tabbable/src/index.js", "../../../node_modules/.pnpm/focus-trap@7.6.4/node_modules/focus-trap/index.js", "../../../node_modules/.pnpm/@vueuse+integrations@12.5.0_focus-trap@7.6.4/node_modules/@vueuse/integrations/useFocusTrap.mjs"],
|
||||
"sourcesContent": ["// NOTE: separate `:not()` selectors has broader browser support than the newer\n// `:not([inert], [inert] *)` (Feb 2023)\n// CAREFUL: JSDom does not support `:not([inert] *)` as a selector; using it causes\n// the entire query to fail, resulting in no nodes found, which will break a lot\n// of things... so we have to rely on JS to identify nodes inside an inert container\nconst candidateSelectors = [\n 'input:not([inert])',\n 'select:not([inert])',\n 'textarea:not([inert])',\n 'a[href]:not([inert])',\n 'button:not([inert])',\n '[tabindex]:not(slot):not([inert])',\n 'audio[controls]:not([inert])',\n 'video[controls]:not([inert])',\n '[contenteditable]:not([contenteditable=\"false\"]):not([inert])',\n 'details>summary:first-of-type:not([inert])',\n 'details:not([inert])',\n];\nconst candidateSelector = /* #__PURE__ */ candidateSelectors.join(',');\n\nconst NoElement = typeof Element === 'undefined';\n\nconst matches = NoElement\n ? function () {}\n : Element.prototype.matches ||\n Element.prototype.msMatchesSelector ||\n Element.prototype.webkitMatchesSelector;\n\nconst getRootNode =\n !NoElement && Element.prototype.getRootNode\n ? (element) => element?.getRootNode?.()\n : (element) => element?.ownerDocument;\n\n/**\n * Determines if a node is inert or in an inert ancestor.\n * @param {Element} [node]\n * @param {boolean} [lookUp] If true and `node` is not inert, looks up at ancestors to\n * see if any of them are inert. If false, only `node` itself is considered.\n * @returns {boolean} True if inert itself or by way of being in an inert ancestor.\n * False if `node` is falsy.\n */\nconst isInert = function (node, lookUp = true) {\n // CAREFUL: JSDom does not support inert at all, so we can't use the `HTMLElement.inert`\n // JS API property; we have to check the attribute, which can either be empty or 'true';\n // if it's `null` (not specified) or 'false', it's an active element\n const inertAtt = node?.getAttribute?.('inert');\n const inert = inertAtt === '' || inertAtt === 'true';\n\n // NOTE: this could also be handled with `node.matches('[inert], :is([inert] *)')`\n // if it weren't for `matches()` not being a function on shadow roots; the following\n // code works for any kind of node\n // CAREFUL: JSDom does not appear to support certain selectors like `:not([inert] *)`\n // so it likely would not support `:is([inert] *)` either...\n const result = inert || (lookUp && node && isInert(node.parentNode)); // recursive\n\n return result;\n};\n\n/**\n * Determines if a node's content is editable.\n * @param {Element} [node]\n * @returns True if it's content-editable; false if it's not or `node` is falsy.\n */\nconst isContentEditable = function (node) {\n // CAREFUL: JSDom does not support the `HTMLElement.isContentEditable` API so we have\n // to use the attribute directly to check for this, which can either be empty or 'true';\n // if it's `null` (not specified) or 'false', it's a non-editable element\n const attValue = node?.getAttribute?.('contenteditable');\n return attValue === '' || attValue === 'true';\n};\n\n/**\n * @param {Element} el container to check in\n * @param {boolean} includeContainer add container to check\n * @param {(node: Element) => boolean} filter filter candidates\n * @returns {Element[]}\n */\nconst getCandidates = function (el, includeContainer, filter) {\n // even if `includeContainer=false`, we still have to check it for inertness because\n // if it's inert, all its children are inert\n if (isInert(el)) {\n return [];\n }\n\n let candidates = Array.prototype.slice.apply(\n el.querySelectorAll(candidateSelector)\n );\n if (includeContainer && matches.call(el, candidateSelector)) {\n candidates.unshift(el);\n }\n candidates = candidates.filter(filter);\n return candidates;\n};\n\n/**\n * @callback GetShadowRoot\n * @param {Element} element to check for shadow root\n * @returns {ShadowRoot|boolean} ShadowRoot if available or boolean indicating if a shadowRoot is attached but not available.\n */\n\n/**\n * @callback ShadowRootFilter\n * @param {Element} shadowHostNode the element which contains shadow content\n * @returns {boolean} true if a shadow root could potentially contain valid candidates.\n */\n\n/**\n * @typedef {Object} CandidateScope\n * @property {Element} scopeParent contains inner candidates\n * @property {Element[]} candidates list of candidates found in the scope parent\n */\n\n/**\n * @typedef {Object} IterativeOptions\n * @property {GetShadowRoot|boolean} getShadowRoot true if shadow support is enabled; falsy if not;\n * if a function, implies shadow support is enabled and either returns the shadow root of an element\n * or a boolean stating if it has an undisclosed shadow root\n * @property {(node: Element) => boolean} filter filter candidates\n * @property {boolean} flatten if true then result will flatten any CandidateScope into the returned list\n * @property {Line truncated
|
||||
"mappings": "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 truncated
|
||||
"names": ["candidateSelectors", "candidateSelector", "join", "NoElement", "Element", "matches", "prototype", "msMatchesSelector", "webkitMatchesSelector", "getRootNode", "element", "_element$getRootNode", "call", "ownerDocument", "isInert", "node", "lookUp", "_node$getAttribute", "inertAtt", "getAttribute", "inert", "result", "parentNode", "isContentEditable", "_node$getAttribute2", "attValue", "getCandidates", "el", "includeContainer", "filter", "candidates", "Array", "slice", "apply", "querySelectorAll", "unshift", "getCandidatesIteratively", "elements", "options", "elementsToCheck", "from", "length", "shift", "tagName", "assigned", "assignedElements", "content", "children", "nestedCandidates", "flatten", "push", "scopeParent", "validCandidate", "includes", "shadowRoot", "getShadowRoot", "validShadowRoot", "shadowRootFilter", "hasTabIndex", "isNaN", "parseInt", "getTabIndex", "Error", "tabIndex", "test", "getSortOrderTabIndex", "isScope", "sortOrderedTabbables", "a", "b", "documentOrder", "isInput", "isHiddenInput", "type", "isDetailsWithSummary", "r", "some", "child", "getCheckedRadio", "nodes", "form", "i", "checked", "isTabbableRadio", "name", "radioScope", "queryRadios", "radioSet", "window", "CSS", "escape", "err", "console", "error", "message", "isRadio", "isNonTabbableRadio", "isNodeAttached", "_nodeRoot", "nodeRoot", "nodeRootHost", "host", "attached", "_nodeRootHost", "_nodeRootHost$ownerDo", "_node$ownerDocument", "contains", "_nodeRoot2", "_nodeRootHost2", "_nodeRootHost2$ownerD", "isZeroArea", "_node$getBoundingClie", "getBoundingClientRect", "width", "height", "isHidden", "_ref", "displayCheck", "getComputedStyle", "visibility", "isDirectSummary", "nodeUnderDetails", "parentElement", "originalNode", "rootNode", "assignedSlot", "getClientRects", "isDisabledFromFieldset", "disabled", "item", "isNodeMatchingSelectorFocusable", "isNodeMatchingSelectorTabbable", "isValidShadowRootTabbable", "shadowHostNode", "sortByOrder", "regularTabbables", "orderedTabbables", "forEach", "candidateTabindex", "sort", "reduce", "acc", "sortable", "concat", "tabbable", "container", "bind", "focusable", "isTabbable", "focusableCandidateSelector", "isFocusable", "activeFocusTraps", "activateTrap", "trapStack", "trap", "length", "activeTrap", "_setPausedState", "trapIndex", "indexOf", "push", "splice", "deactivateTrap", "_isManuallyPaused", "isSelectableInput", "node", "tagName", "toLowerCase", "select", "isEscapeEvent", "e", "key", "keyCode", "isTabEvent", "isKeyForward", "shiftKey", "isKeyBackward", "delay", "fn", "setTimeout", "valueOrHandler", "value", "_len", "arguments", "params", "Array", "_key", "apply", "getActualTarget", "event", "target", "shadowRoot", "composedPath", "internalTrapStack", "createFocusTrap", "elements", "userOptions", "doc", "document", "config", "_objectSpread", "returnFocusOnDeactivate", "escapeDeactivates", "delayInitialFocus", "state", "containers", "containerGroups", "tabbableGroups", "nodeFocusedBeforeActivation", "mostRecentlyFocusedNode", "active", "paused", "manuallyPaused", "delayInitialFocusTimer", "undefined", "recentNavEvent", "getOption", "configOverrideOptions", "optionName", "configOptionName", "findContainerIndex", "element", "findIndex", "_ref", "container", "tabbableNodes", "contains", "includes", "find", "getNodeForOption", "_ref2", "_ref2$hasFallback", "hasFallback", "_ref2$params", "optionValue", "_toConsumableArray", "Error", "concat", "querySelector", "err", "message", "getInitialFocusNode", "isFocusable", "tabbableOptions", "activeElement", "firstTabbableGroup", "firstTabbableNode", "updateTabbableNodes", "map", "tabbable", "focusableNodes", "focusable", "lastTabbableNode", "firstDomTabbableNode", "isTabbable", "lastDomTabbableNode", "slice", "reverse", "posTabIndexesFound", "getTabIndex", "nextTabbableNode", "forward", "nodeIdx", "el", "filter", "group", "g", "getActiveElement", "tryFocus", "focus", "preventScroll", "getReturnFocusNode", "previousActiveElement", "findNextNavNode", "_ref3", "_ref3$isBackward", "isBackward", "destinationNode", "containerIndex", "containerGroup", "startOfGroupIndex", "_ref4", "destinationGroupIndex", "destinationGroup", "lastOfGroupIndex", "_ref5", "checkPointerDown", "clickOutsideDeactivates", "deactivate", "returnFocus", "allowOutsideClick", "preventDefault", "checkFocusIn", "targetContained", "Document", "stopImmediatePropagation", "nextNode", "navAcrossContainers", "mruContainerIdx", "mruTabIdx", "some", "n", "checkKeyNav", "checkTabKey", "checkEscapeKey", "checkClick", "addListeners", "addEventListener", "capture", "passive", "removeListeners", "removeEventListener", "checkDomRemoval", "mutations", "isFocusedNodeRemoved", "mutation", "removedNodes", "from", "mutationObserver", "window", "MutationObserver", "updateObservedNodes", "disconnect", "observe", "subtree", "childList", "activate", "activateOptions", "onActivate", "onPostActivate", "checkCanFocusTrap", "finishActivation", "then", "deactivateOptions", "options", "onDeactiLine truncated
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": 3,
|
||||
"sources": ["../../../node_modules/.pnpm/mark.js@8.11.1/node_modules/mark.js/src/lib/domiterator.js", "../../../node_modules/.pnpm/mark.js@8.11.1/node_modules/mark.js/src/lib/mark.js", "../../../node_modules/.pnpm/mark.js@8.11.1/node_modules/mark.js/src/vanilla.js"],
|
||||
"sourcesContent": ["/**\n * A NodeIterator with iframes support and a method to check if an element is\n * matching a specified selector\n * @example\n * const iterator = new DOMIterator(\n * document.querySelector(\"#context\"), true\n * );\n * iterator.forEachNode(NodeFilter.SHOW_TEXT, node => {\n * console.log(node);\n * }, node => {\n * if(DOMIterator.matches(node.parentNode, \".ignore\")){\n * return NodeFilter.FILTER_REJECT;\n * } else {\n * return NodeFilter.FILTER_ACCEPT;\n * }\n * }, () => {\n * console.log(\"DONE\");\n * });\n * @todo Outsource into separate repository\n */\nexport default class DOMIterator {\n\n /**\n * @param {HTMLElement|HTMLElement[]|NodeList|string} ctx - The context DOM\n * element, an array of DOM elements, a NodeList or a selector\n * @param {boolean} [iframes=true] - A boolean indicating if iframes should\n * be handled\n * @param {string[]} [exclude=[]] - An array containing exclusion selectors\n * for iframes\n * @param {number} [iframesTimeout=5000] - A number indicating the ms to\n * wait before an iframe should be skipped, in case the load event isn't\n * fired. This also applies if the user is offline and the resource of the\n * iframe is online (either by the browsers \"offline\" mode or because\n * there's no internet connection)\n */\n constructor(ctx, iframes = true, exclude = [], iframesTimeout = 5000) {\n /**\n * The context of the instance. Either a DOM element, an array of DOM\n * elements, a NodeList or a selector\n * @type {HTMLElement|HTMLElement[]|NodeList|string}\n * @access protected\n */\n this.ctx = ctx;\n /**\n * Boolean indicating if iframe support is enabled\n * @type {boolean}\n * @access protected\n */\n this.iframes = iframes;\n /**\n * An array containing exclusion selectors for iframes\n * @type {string[]}\n */\n this.exclude = exclude;\n /**\n * The maximum ms to wait for a load event before skipping an iframe\n * @type {number}\n */\n this.iframesTimeout = iframesTimeout;\n }\n\n /**\n * Checks if the specified DOM element matches the selector\n * @param {HTMLElement} element - The DOM element\n * @param {string|string[]} selector - The selector or an array with\n * selectors\n * @return {boolean}\n * @access public\n */\n static matches(element, selector) {\n const selectors = typeof selector === 'string' ? [selector] : selector,\n fn = (\n element.matches ||\n element.matchesSelector ||\n element.msMatchesSelector ||\n element.mozMatchesSelector ||\n element.oMatchesSelector ||\n element.webkitMatchesSelector\n );\n if (fn) {\n let match = false;\n selectors.every(sel => {\n if (fn.call(element, sel)) {\n match = true;\n return false;\n }\n return true;\n });\n return match;\n } else { // may be false e.g. when el is a textNode\n return false;\n }\n }\n\n /**\n * Returns all contexts filtered by duplicates (even nested)\n * @return {HTMLElement[]} - An array containing DOM contexts\n * @access protected\n */\n getContexts() {\n let ctx,\n filteredCtx = [];\n if (typeof this.ctx === 'undefined' || !this.ctx) { // e.g. null\n ctx = [];\n } else if (NodeList.prototype.isPrototypeOf(this.ctx)) {\n ctx = Array.prototype.slice.call(this.ctx);\n } else if (Array.isArray(this.ctx)) {\n ctx = this.ctx;\n } else if (typeof this.ctx === 'string') {\n ctx = Array.prototype.slice.call(\n document.querySelectorAll(this.ctx)\n );\n } else { // e.g. HTMLElement or element inside iframe\n ctx = [this.ctx];\n }\n // filter duplicate text nodes\n ctx.forEach(ctx => {\n const isDescendant = filteredCtx.filter(contexts => {\n return contexts.contains(ctx);\n }).length > 0;\n if (filteredCtx.indexOf(ctx) === -1 && !isDescendant) {\n filteredCtx.push(ctx);\n }\n });\n return filteredCtx;\n }\n\n /**\n * @callback DOMIterator~getIframeContentsSuccessCallback\n * @param {HTMLDocument} contents - The contentDocument of the iframe\n */\n /**\n * Calls the success callback function with the iframe document. If it can't\n * be accessed it calls the error callback function\n * @param {HTMLElement} ifr - The iframe DOM element\n * @param {DOMIterator~getIframeContentsSuccessCallback} successFn\n * @param {function} [errorFn]\n * @access protected\n */\n getIframeContents(ifr, successFn, errorFn = () => {}) {\n let doc;\n try {\n const ifrWin = ifr.contentWindow;\n doc = ifrWin.document;\n if (!ifrWin || !doc) { // no permission = null. Undefined in Phantom\n throw new Error('iframe inaccessible');\n }\n } catch (e) {\n errorFn();\n }\n if (doc) {\n successFn(doc);\n }\n }\n\n /Line truncated
|
||||
"mappings": "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 truncated
|
||||
"names": ["ctx", "ifr", "node", "dct", "Mark"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": 3,
|
||||
"sources": ["../../../node_modules/.pnpm/minisearch@7.1.1/node_modules/minisearch/node_modules/tslib/tslib.es6.js", "../../../node_modules/.pnpm/minisearch@7.1.1/node_modules/minisearch/src/SearchableMap/TreeIterator.ts", "../../../node_modules/.pnpm/minisearch@7.1.1/node_modules/minisearch/src/SearchableMap/fuzzySearch.ts", "../../../node_modules/.pnpm/minisearch@7.1.1/node_modules/minisearch/src/SearchableMap/SearchableMap.ts", "../../../node_modules/.pnpm/minisearch@7.1.1/node_modules/minisearch/src/MiniSearch.ts"],
|
||||
"sourcesContent": ["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n iLine truncated
|
||||
"mappings": "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 truncated
|
||||
"names": ["last", "node", "child", "key", "chunk", "promise", "conditions", "options", "results", "query", "boosts", "data"]
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
import {
|
||||
BaseTransition,
|
||||
BaseTransitionPropsValidators,
|
||||
Comment,
|
||||
DeprecationTypes,
|
||||
EffectScope,
|
||||
ErrorCodes,
|
||||
ErrorTypeStrings,
|
||||
Fragment,
|
||||
KeepAlive,
|
||||
ReactiveEffect,
|
||||
Static,
|
||||
Suspense,
|
||||
Teleport,
|
||||
Text,
|
||||
TrackOpTypes,
|
||||
Transition,
|
||||
TransitionGroup,
|
||||
TriggerOpTypes,
|
||||
VueElement,
|
||||
assertNumber,
|
||||
callWithAsyncErrorHandling,
|
||||
callWithErrorHandling,
|
||||
camelize,
|
||||
capitalize,
|
||||
cloneVNode,
|
||||
compatUtils,
|
||||
compile,
|
||||
computed,
|
||||
createApp,
|
||||
createBaseVNode,
|
||||
createBlock,
|
||||
createCommentVNode,
|
||||
createElementBlock,
|
||||
createHydrationRenderer,
|
||||
createPropsRestProxy,
|
||||
createRenderer,
|
||||
createSSRApp,
|
||||
createSlots,
|
||||
createStaticVNode,
|
||||
createTextVNode,
|
||||
createVNode,
|
||||
customRef,
|
||||
defineAsyncComponent,
|
||||
defineComponent,
|
||||
defineCustomElement,
|
||||
defineEmits,
|
||||
defineExpose,
|
||||
defineModel,
|
||||
defineOptions,
|
||||
defineProps,
|
||||
defineSSRCustomElement,
|
||||
defineSlots,
|
||||
devtools,
|
||||
effect,
|
||||
effectScope,
|
||||
getCurrentInstance,
|
||||
getCurrentScope,
|
||||
getCurrentWatcher,
|
||||
getTransitionRawChildren,
|
||||
guardReactiveProps,
|
||||
h,
|
||||
handleError,
|
||||
hasInjectionContext,
|
||||
hydrate,
|
||||
hydrateOnIdle,
|
||||
hydrateOnInteraction,
|
||||
hydrateOnMediaQuery,
|
||||
hydrateOnVisible,
|
||||
initCustomFormatter,
|
||||
initDirectivesForSSR,
|
||||
inject,
|
||||
isMemoSame,
|
||||
isProxy,
|
||||
isReactive,
|
||||
isReadonly,
|
||||
isRef,
|
||||
isRuntimeOnly,
|
||||
isShallow,
|
||||
isVNode,
|
||||
markRaw,
|
||||
mergeDefaults,
|
||||
mergeModels,
|
||||
mergeProps,
|
||||
nextTick,
|
||||
normalizeClass,
|
||||
normalizeProps,
|
||||
normalizeStyle,
|
||||
onActivated,
|
||||
onBeforeMount,
|
||||
onBeforeUnmount,
|
||||
onBeforeUpdate,
|
||||
onDeactivated,
|
||||
onErrorCaptured,
|
||||
onMounted,
|
||||
onRenderTracked,
|
||||
onRenderTriggered,
|
||||
onScopeDispose,
|
||||
onServerPrefetch,
|
||||
onUnmounted,
|
||||
onUpdated,
|
||||
onWatcherCleanup,
|
||||
openBlock,
|
||||
popScopeId,
|
||||
provide,
|
||||
proxyRefs,
|
||||
pushScopeId,
|
||||
queuePostFlushCb,
|
||||
reactive,
|
||||
readonly,
|
||||
ref,
|
||||
registerRuntimeCompiler,
|
||||
render,
|
||||
renderList,
|
||||
renderSlot,
|
||||
resolveComponent,
|
||||
resolveDirective,
|
||||
resolveDynamicComponent,
|
||||
resolveFilter,
|
||||
resolveTransitionHooks,
|
||||
setBlockTracking,
|
||||
setDevtoolsHook,
|
||||
setTransitionHooks,
|
||||
shallowReactive,
|
||||
shallowReadonly,
|
||||
shallowRef,
|
||||
ssrContextKey,
|
||||
ssrUtils,
|
||||
stop,
|
||||
toDisplayString,
|
||||
toHandlerKey,
|
||||
toHandlers,
|
||||
toRaw,
|
||||
toRef,
|
||||
toRefs,
|
||||
toValue,
|
||||
transformVNodeArgs,
|
||||
triggerRef,
|
||||
unref,
|
||||
useAttrs,
|
||||
useCssModule,
|
||||
useCssVars,
|
||||
useHost,
|
||||
useId,
|
||||
useModel,
|
||||
useSSRContext,
|
||||
useShadowRoot,
|
||||
useSlots,
|
||||
useTemplateRef,
|
||||
useTransitionState,
|
||||
vModelCheckbox,
|
||||
vModelDynamic,
|
||||
vModelRadio,
|
||||
vModelSelect,
|
||||
vModelText,
|
||||
vShow,
|
||||
version,
|
||||
warn,
|
||||
watch,
|
||||
watchEffect,
|
||||
watchPostEffect,
|
||||
watchSyncEffect,
|
||||
withAsyncContext,
|
||||
withCtx,
|
||||
withDefaults,
|
||||
withDirectives,
|
||||
withKeys,
|
||||
withMemo,
|
||||
withModifiers,
|
||||
withScopeId
|
||||
} from "./chunk-CQOUZRMK.js";
|
||||
export {
|
||||
BaseTransition,
|
||||
BaseTransitionPropsValidators,
|
||||
Comment,
|
||||
DeprecationTypes,
|
||||
EffectScope,
|
||||
ErrorCodes,
|
||||
ErrorTypeStrings,
|
||||
Fragment,
|
||||
KeepAlive,
|
||||
ReactiveEffect,
|
||||
Static,
|
||||
Suspense,
|
||||
Teleport,
|
||||
Text,
|
||||
TrackOpTypes,
|
||||
Transition,
|
||||
TransitionGroup,
|
||||
TriggerOpTypes,
|
||||
VueElement,
|
||||
assertNumber,
|
||||
callWithAsyncErrorHandling,
|
||||
callWithErrorHandling,
|
||||
camelize,
|
||||
capitalize,
|
||||
cloneVNode,
|
||||
compatUtils,
|
||||
compile,
|
||||
computed,
|
||||
createApp,
|
||||
createBlock,
|
||||
createCommentVNode,
|
||||
createElementBlock,
|
||||
createBaseVNode as createElementVNode,
|
||||
createHydrationRenderer,
|
||||
createPropsRestProxy,
|
||||
createRenderer,
|
||||
createSSRApp,
|
||||
createSlots,
|
||||
createStaticVNode,
|
||||
createTextVNode,
|
||||
createVNode,
|
||||
customRef,
|
||||
defineAsyncComponent,
|
||||
defineComponent,
|
||||
defineCustomElement,
|
||||
defineEmits,
|
||||
defineExpose,
|
||||
defineModel,
|
||||
defineOptions,
|
||||
defineProps,
|
||||
defineSSRCustomElement,
|
||||
defineSlots,
|
||||
devtools,
|
||||
effect,
|
||||
effectScope,
|
||||
getCurrentInstance,
|
||||
getCurrentScope,
|
||||
getCurrentWatcher,
|
||||
getTransitionRawChildren,
|
||||
guardReactiveProps,
|
||||
h,
|
||||
handleError,
|
||||
hasInjectionContext,
|
||||
hydrate,
|
||||
hydrateOnIdle,
|
||||
hydrateOnInteraction,
|
||||
hydrateOnMediaQuery,
|
||||
hydrateOnVisible,
|
||||
initCustomFormatter,
|
||||
initDirectivesForSSR,
|
||||
inject,
|
||||
isMemoSame,
|
||||
isProxy,
|
||||
isReactive,
|
||||
isReadonly,
|
||||
isRef,
|
||||
isRuntimeOnly,
|
||||
isShallow,
|
||||
isVNode,
|
||||
markRaw,
|
||||
mergeDefaults,
|
||||
mergeModels,
|
||||
mergeProps,
|
||||
nextTick,
|
||||
normalizeClass,
|
||||
normalizeProps,
|
||||
normalizeStyle,
|
||||
onActivated,
|
||||
onBeforeMount,
|
||||
onBeforeUnmount,
|
||||
onBeforeUpdate,
|
||||
onDeactivated,
|
||||
onErrorCaptured,
|
||||
onMounted,
|
||||
onRenderTracked,
|
||||
onRenderTriggered,
|
||||
onScopeDispose,
|
||||
onServerPrefetch,
|
||||
onUnmounted,
|
||||
onUpdated,
|
||||
onWatcherCleanup,
|
||||
openBlock,
|
||||
popScopeId,
|
||||
provide,
|
||||
proxyRefs,
|
||||
pushScopeId,
|
||||
queuePostFlushCb,
|
||||
reactive,
|
||||
readonly,
|
||||
ref,
|
||||
registerRuntimeCompiler,
|
||||
render,
|
||||
renderList,
|
||||
renderSlot,
|
||||
resolveComponent,
|
||||
resolveDirective,
|
||||
resolveDynamicComponent,
|
||||
resolveFilter,
|
||||
resolveTransitionHooks,
|
||||
setBlockTracking,
|
||||
setDevtoolsHook,
|
||||
setTransitionHooks,
|
||||
shallowReactive,
|
||||
shallowReadonly,
|
||||
shallowRef,
|
||||
ssrContextKey,
|
||||
ssrUtils,
|
||||
stop,
|
||||
toDisplayString,
|
||||
toHandlerKey,
|
||||
toHandlers,
|
||||
toRaw,
|
||||
toRef,
|
||||
toRefs,
|
||||
toValue,
|
||||
transformVNodeArgs,
|
||||
triggerRef,
|
||||
unref,
|
||||
useAttrs,
|
||||
useCssModule,
|
||||
useCssVars,
|
||||
useHost,
|
||||
useId,
|
||||
useModel,
|
||||
useSSRContext,
|
||||
useShadowRoot,
|
||||
useSlots,
|
||||
useTemplateRef,
|
||||
useTransitionState,
|
||||
vModelCheckbox,
|
||||
vModelDynamic,
|
||||
vModelRadio,
|
||||
vModelSelect,
|
||||
vModelText,
|
||||
vShow,
|
||||
version,
|
||||
warn,
|
||||
watch,
|
||||
watchEffect,
|
||||
watchPostEffect,
|
||||
watchSyncEffect,
|
||||
withAsyncContext,
|
||||
withCtx,
|
||||
withDefaults,
|
||||
withDirectives,
|
||||
withKeys,
|
||||
withMemo,
|
||||
withModifiers,
|
||||
withScopeId
|
||||
};
|
||||
//# sourceMappingURL=vue.js.map
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"version": 3,
|
||||
"sources": [],
|
||||
"sourcesContent": [],
|
||||
"mappings": "",
|
||||
"names": []
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
import { defineConfig } from 'vitepress'
|
||||
|
||||
// https://vitepress.dev/reference/site-config
|
||||
export default defineConfig({
|
||||
title: 'FileCodeBox',
|
||||
description: '简单高效的文件分享工具',
|
||||
lang: 'zh-CN',
|
||||
lastUpdated: true,
|
||||
locales: {
|
||||
root: {
|
||||
label: '简体中文',
|
||||
lang: 'zh-CN',
|
||||
title: 'FileCodeBox',
|
||||
description: '匿名口令分享文本,文件',
|
||||
themeConfig: {
|
||||
logo: '/logo_small.png',
|
||||
nav: [
|
||||
{ text: '首页', link: '/' },
|
||||
{ text: '指南', link: '/guide/getting-started' },
|
||||
{ text: 'API', link: '/api/' },
|
||||
{ text: '优秀案例', link: '/showcase' },
|
||||
{ text: 'Demo', link: 'https://share.lanol.cn' },
|
||||
{
|
||||
text: '了解更多',
|
||||
items: [
|
||||
{ text: '更新日志', link: '/changelog' },
|
||||
{ text: '贡献指南', link: '/contributing' },
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
sidebar: {
|
||||
'/guide/': [
|
||||
{
|
||||
text: '介绍',
|
||||
items: [
|
||||
{
|
||||
text: '什么是 FileCodeBox',
|
||||
link: '/guide/introduction',
|
||||
},
|
||||
{ text: '快速开始', link: '/guide/getting-started' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: '基础功能',
|
||||
items: [
|
||||
{ text: '文件上传', link: '/guide/upload' },
|
||||
{ text: '文件分享', link: '/guide/share' },
|
||||
{ text: '文件管理', link: '/guide/management' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: '高级特性',
|
||||
items: [
|
||||
{ text: '存储配置', link: '/guide/storage' },
|
||||
{ text: '安全设置', link: '/guide/security' },
|
||||
{ text: '系统配置', link: '/guide/configuration' },
|
||||
],
|
||||
},
|
||||
],
|
||||
'/api/': [
|
||||
{
|
||||
text: 'API 参考',
|
||||
items: [
|
||||
{ text: '分享接口', link: '/api/#分享接口' },
|
||||
{ text: '管理接口', link: '/api/#管理接口' },
|
||||
{ text: '错误响应', link: '/api/#错误响应' },
|
||||
{ text: '状态码说明', link: '/api/#状态码说明' },
|
||||
],
|
||||
},
|
||||
],
|
||||
'/showcase': [
|
||||
{
|
||||
text: '优秀案例',
|
||||
items: [
|
||||
{ text: '案例展示', link: '/showcase' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
socialLinks: [
|
||||
{ icon: 'github', link: 'https://github.com/vastsa/FileCodeBox' },
|
||||
],
|
||||
footer: {
|
||||
message: '基于 LGPL-3.0 license 发布',
|
||||
copyright: 'Copyright © 2022-present FileCodeBox',
|
||||
},
|
||||
search: {
|
||||
provider: 'local',
|
||||
},
|
||||
outline: {
|
||||
level: [2, 3],
|
||||
label: '目录',
|
||||
},
|
||||
},
|
||||
},
|
||||
en: {
|
||||
label: 'English',
|
||||
lang: 'en-US',
|
||||
title: 'FileCodeBox',
|
||||
description: 'Simple and efficient file sharing tool',
|
||||
themeConfig: {
|
||||
logo: '/logo_small.png',
|
||||
nav: [
|
||||
{ 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',
|
||||
items: [
|
||||
{ text: 'Changelog', link: '/en/changelog' },
|
||||
{ text: 'Contributing', link: '/en/contributing' },
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
sidebar: {
|
||||
'/en/guide/': [
|
||||
{
|
||||
text: 'Introduction',
|
||||
items: [
|
||||
{
|
||||
text: 'What is FileCodeBox',
|
||||
link: '/en/guide/introduction',
|
||||
},
|
||||
{
|
||||
text: 'Getting Started',
|
||||
link: '/en/guide/getting-started',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
text: 'Basic Features',
|
||||
items: [
|
||||
{ text: 'File Upload', link: '/en/guide/upload' },
|
||||
{ text: 'File Sharing', link: '/en/guide/share' },
|
||||
{ text: 'File Management', link: '/en/guide/management' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: 'Advanced Features',
|
||||
items: [
|
||||
{ text: 'Storage Configuration', link: '/en/guide/storage' },
|
||||
{ text: 'Security Settings', link: '/en/guide/security' },
|
||||
{
|
||||
text: 'System Configuration',
|
||||
link: '/en/guide/configuration',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
'/en/api/': [
|
||||
{
|
||||
text: 'API Reference',
|
||||
items: [
|
||||
{ text: 'Share API', link: '/en/api/#share-api' },
|
||||
{ text: 'Admin API', link: '/en/api/#admin-api' },
|
||||
{ text: 'Error Response', link: '/en/api/#error-response' },
|
||||
{ text: 'Status Codes', link: '/en/api/#status-codes' },
|
||||
],
|
||||
},
|
||||
],
|
||||
'/en/showcase': [
|
||||
{
|
||||
text: 'Showcase',
|
||||
items: [
|
||||
{ text: 'Case Studies', link: '/en/showcase' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
socialLinks: [
|
||||
{ icon: 'github', link: 'https://github.com/vastsa/FileCodeBox' },
|
||||
],
|
||||
footer: {
|
||||
message: 'Released under the LGPL-3.0 license',
|
||||
copyright: 'Copyright © 2022-present FileCodeBox',
|
||||
},
|
||||
search: {
|
||||
provider: 'local',
|
||||
},
|
||||
outline: {
|
||||
level: [2, 3],
|
||||
label: '目录',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
themeConfig: {
|
||||
// 语言切换器
|
||||
langMenuLabel: '切换语言',
|
||||
|
||||
// 社交链接
|
||||
socialLinks: [
|
||||
{ icon: 'github', link: 'https://github.com/vastsa/FileCodeBox' },
|
||||
],
|
||||
|
||||
// 页脚
|
||||
footer: {
|
||||
message: '基于 LGPL-3.0 license 发布',
|
||||
copyright: 'Copyright © 2022-present FileCodeBox',
|
||||
},
|
||||
|
||||
// 搜索
|
||||
search: {
|
||||
provider: 'local',
|
||||
options: {
|
||||
locales: {
|
||||
zh: {
|
||||
translations: {
|
||||
button: {
|
||||
buttonText: '搜索文档',
|
||||
buttonAriaLabel: '搜索文档',
|
||||
},
|
||||
modal: {
|
||||
noResultsText: '无法找到相关结果',
|
||||
resetButtonTitle: '清除查询条件',
|
||||
footer: {
|
||||
selectText: '选择',
|
||||
navigateText: '切换',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
en: {
|
||||
translations: {
|
||||
button: {
|
||||
buttonText: 'Search',
|
||||
buttonAriaLabel: 'Search docs',
|
||||
},
|
||||
modal: {
|
||||
noResultsText: 'No results found',
|
||||
resetButtonTitle: 'Clear query',
|
||||
footer: {
|
||||
selectText: 'to select',
|
||||
navigateText: 'to navigate',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
outline: {
|
||||
level: [2, 3],
|
||||
label: '目录',
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import DefaultTheme from 'vitepress/theme'
|
||||
import './custom.css'
|
||||
|
||||
export default {
|
||||
...DefaultTheme,
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
# FileCodeBox API 文档
|
||||
|
||||
## API 版本: 2.1.0
|
||||
|
||||
## 目录
|
||||
- [认证](#认证)
|
||||
- [分享接口](#分享接口)
|
||||
- [管理接口](#管理接口)
|
||||
|
||||
## 认证
|
||||
|
||||
部分接口需要在请求头中携带 `Authorization` 进行认证:
|
||||
|
||||
```
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
### 获取 Token
|
||||
|
||||
当管理面板关闭了游客上传(`openUpload=0`)时,需要先登录获取 token:
|
||||
|
||||
```bash
|
||||
curl -X POST "http://localhost:12345/admin/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"password": "FileCodeBox2023"}'
|
||||
```
|
||||
|
||||
**响应示例:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"token": "xxx.xxx.xxx",
|
||||
"token_type": "Bearer"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 分享接口
|
||||
|
||||
### 分享文本
|
||||
|
||||
**POST** `/share/text/`
|
||||
|
||||
分享文本内容,获取分享码。
|
||||
|
||||
**请求参数:**
|
||||
|
||||
| 参数名 | 类型 | 必填 | 默认值 | 描述 |
|
||||
|-------|------|------|--------|------|
|
||||
| text | string | 是 | - | 要分享的文本内容 |
|
||||
| expire_value | integer | 否 | 1 | 过期时间值 |
|
||||
| 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=这是要分享的文本内容"
|
||||
```
|
||||
|
||||
**响应示例:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abc123"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 分享文件
|
||||
|
||||
**POST** `/share/file/`
|
||||
|
||||
上传并分享文件,获取分享码。
|
||||
|
||||
**请求参数:**
|
||||
|
||||
| 参数名 | 类型 | 必填 | 默认值 | 描述 |
|
||||
|-------|------|------|--------|------|
|
||||
| file | file | 是 | - | 要上传的文件 |
|
||||
| expire_value | integer | 否 | 1 | 过期时间值 |
|
||||
| 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"
|
||||
```
|
||||
|
||||
**响应示例:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "example.txt"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 获取文件信息
|
||||
|
||||
**GET** `/share/select/`
|
||||
|
||||
通过分享码获取文件信息(直接下载文件)。
|
||||
|
||||
**请求参数:**
|
||||
|
||||
| 参数名 | 类型 | 必填 | 描述 |
|
||||
|-------|------|------|------|
|
||||
| code | string | 是 | 文件分享码 |
|
||||
|
||||
**cURL 示例:**
|
||||
|
||||
```bash
|
||||
# 通过取件码下载文件
|
||||
curl -L "http://localhost:12345/share/select/?code=abc123" -o downloaded_file
|
||||
```
|
||||
|
||||
**响应示例:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "example.txt",
|
||||
"size": 1024,
|
||||
"text": "文件内容或下载链接"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 选择文件
|
||||
|
||||
**POST** `/share/select/`
|
||||
|
||||
通过分享码选择文件。
|
||||
|
||||
**请求参数:**
|
||||
|
||||
| 参数名 | 类型 | 必填 | 描述 |
|
||||
|-------|------|------|------|
|
||||
| code | string | 是 | 文件分享码 |
|
||||
|
||||
**响应示例:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "example.txt",
|
||||
"size": 1024,
|
||||
"text": "文件内容或下载链接"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 下载文件
|
||||
|
||||
**GET** `/share/download`
|
||||
|
||||
下载分享的文件。
|
||||
|
||||
**请求参数:**
|
||||
|
||||
| 参数名 | 类型 | 必填 | 描述 |
|
||||
|-------|------|------|------|
|
||||
| key | string | 是 | 下载密钥 |
|
||||
| code | string | 是 | 文件分享码 |
|
||||
|
||||
## 管理接口
|
||||
|
||||
### 管理员登录
|
||||
|
||||
**POST** `/admin/login`
|
||||
|
||||
管理员登录获取token。
|
||||
|
||||
**请求参数:**
|
||||
|
||||
| 参数名 | 类型 | 必填 | 描述 |
|
||||
|-------|------|------|------|
|
||||
| password | string | 是 | 管理员密码 |
|
||||
|
||||
### 仪表盘数据
|
||||
|
||||
**GET** `/admin/dashboard`
|
||||
|
||||
获取系统仪表盘数据。
|
||||
|
||||
**响应示例:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"totalFiles": 100,
|
||||
"storageUsed": "1.5GB",
|
||||
"sysUptime": "10天",
|
||||
"yesterdayCount": 50,
|
||||
"yesterdaySize": "500MB",
|
||||
"todayCount": 30,
|
||||
"todaySize": "300MB"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 文件列表
|
||||
|
||||
**GET** `/admin/file/list`
|
||||
|
||||
获取系统中的文件列表。
|
||||
|
||||
**请求参数:**
|
||||
|
||||
| 参数名 | 类型 | 必填 | 默认值 | 描述 |
|
||||
|-------|------|------|--------|------|
|
||||
| page | integer | 否 | 1 | 当前页码 |
|
||||
| size | integer | 否 | 10 | 每页数量 |
|
||||
| keyword | string | 否 | "" | 搜索关键词 |
|
||||
|
||||
**响应示例:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"page": 1,
|
||||
"size": 10,
|
||||
"total": 100,
|
||||
"data": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "example.txt",
|
||||
"size": 1024,
|
||||
"created_at": "2024-01-01 12:00:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 删除文件
|
||||
|
||||
**DELETE** `/admin/file/delete`
|
||||
|
||||
删除系统中的文件。
|
||||
|
||||
**请求参数:**
|
||||
|
||||
| 参数名 | 类型 | 必填 | 描述 |
|
||||
|-------|------|------|------|
|
||||
| id | integer | 是 | 文件ID |
|
||||
|
||||
### 获取配置
|
||||
|
||||
**GET** `/admin/config/get`
|
||||
|
||||
获取系统配置信息。
|
||||
|
||||
### 更新配置
|
||||
|
||||
**PATCH** `/admin/config/update`
|
||||
|
||||
更新系统配置信息。
|
||||
|
||||
## 错误响应
|
||||
|
||||
当发生错误时,API会返回对应的错误信息:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 422,
|
||||
"detail": [
|
||||
{
|
||||
"loc": ["body", "password"],
|
||||
"msg": "密码不能为空",
|
||||
"type": "value_error"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## 状态码说明
|
||||
|
||||
- 200: 请求成功
|
||||
- 401: 未授权
|
||||
- 403: 禁止访问
|
||||
- 404: 资源不存在
|
||||
- 422: 请求参数验证错误
|
||||
- 500: 服务器内部错误
|
||||
@@ -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. **重试机制**: 建议实现上传失败重试逻辑
|
||||
@@ -0,0 +1,196 @@
|
||||
# 本轮开发交付报告
|
||||
|
||||
生成日期:2026-06-06
|
||||
|
||||
本文档记录 `feature/development-plan` 分支本轮开发完成情况、验证结果和后续处理建议。
|
||||
|
||||
## 分支状态
|
||||
|
||||
当前工作区包含两个独立 Git 仓库,均已切换到本轮开发分支:
|
||||
|
||||
- 后端仓库:`FileCodeBox`
|
||||
- 前端仓库:`FileCodeBoxFronted`
|
||||
- 当前分支:`feature/development-plan`
|
||||
|
||||
本轮变更尚未提交。
|
||||
|
||||
## 开发目标
|
||||
|
||||
本轮目标是根据 `docs/development-plan.md` 完成下一阶段的优先开发项:
|
||||
|
||||
1. 补齐取件文件预览链路。
|
||||
2. 建立前端最小测试体系。
|
||||
3. 加固后端预签名上传回归测试。
|
||||
4. 区分前端检查脚本和自动修复脚本。
|
||||
5. 拆分管理文件模块的部分纯函数、状态逻辑和批量操作 UI。
|
||||
|
||||
## 完成范围
|
||||
|
||||
### P0:取件文件预览链路
|
||||
|
||||
已在取件页完成文件预览接线:
|
||||
|
||||
- `RetrievewFileView.vue` 绑定文件详情弹窗的 `preview-file` 事件。
|
||||
- 取件页渲染并控制 `MediaPreviewModal`。
|
||||
- 取件详情中的可预览文件现在可以打开媒体预览弹窗。
|
||||
|
||||
### P0:前端最小测试体系
|
||||
|
||||
已建立 Vitest 测试基础:
|
||||
|
||||
- 新增 `vitest.config.ts`。
|
||||
- 新增 `package.json` 的 `test` 脚本。
|
||||
- 引入 `vitest`、`@vue/test-utils`、`jsdom` 等测试依赖。
|
||||
- 更新 `pnpm-lock.yaml`。
|
||||
|
||||
首批测试覆盖:
|
||||
|
||||
- 文件类型规则。
|
||||
- 下载动作解析。
|
||||
- 内容预览处理。
|
||||
- 发送记录工具逻辑。
|
||||
- 预签名上传相关流程。
|
||||
- 上传策略分支。
|
||||
- 管理文件摘要、视图预设和批量选择逻辑。
|
||||
|
||||
### P1:后端上传回归加固
|
||||
|
||||
已补充后端预签名上传流程测试:
|
||||
|
||||
- 新增 `tests/conftest.py`,固定测试导入路径。
|
||||
- 新增 `tests/test_presign_upload_flow.py`。
|
||||
|
||||
覆盖场景包括:
|
||||
|
||||
- `init` 直传模式。
|
||||
- `init` 代理上传模式。
|
||||
- `confirm` 成功创建文件记录。
|
||||
- `confirm` 拒绝缺失的直传文件。
|
||||
- `proxy` 上传大小不一致校验。
|
||||
- `cancel` 取消并清理已上传对象。
|
||||
- 过期上传会话自动删除并拒绝继续操作。
|
||||
|
||||
### P1:质量脚本调整
|
||||
|
||||
已区分自动修复和只检查命令:
|
||||
|
||||
```json
|
||||
{
|
||||
"lint": "eslint . --fix",
|
||||
"lint:check": "eslint ."
|
||||
}
|
||||
```
|
||||
|
||||
同时,架构检查脚本已忽略测试文件,避免测试代码影响前端分层规则检查。
|
||||
|
||||
### P2:管理文件模块拆分
|
||||
|
||||
已完成第一轮低风险拆分:
|
||||
|
||||
- 新增 `admin-file-view-preset.ts`,承载管理文件视图预设规则。
|
||||
- 新增 `admin-file-summary.ts`,承载管理文件摘要计算逻辑。
|
||||
- 新增 `useAdminFileSelection.ts`,承载批量选择状态逻辑。
|
||||
- 新增 `AdminBatchActionBar.vue`,承载管理页批量操作栏 UI。
|
||||
- `FileManageView.vue` 已接入新的批量操作栏组件。
|
||||
|
||||
本轮拆分优先处理纯函数和单一职责状态逻辑,避免一次性重构整个管理页。
|
||||
|
||||
## 关键设计决策
|
||||
|
||||
1. 优先补用户可见断点,再推进模块拆分。
|
||||
2. 先给工具函数和 composable 补测试,再扩大重构范围。
|
||||
3. `lint` 保留自动修复语义,新增 `lint:check` 用于 CI 和人工验证。
|
||||
4. 管理文件页拆分采用渐进方式,每次只抽离职责清晰、影响边界可控的模块。
|
||||
5. 后端上传测试使用替身对象和临时状态,避免依赖真实网络、真实 S3 或污染运行数据目录。
|
||||
|
||||
## 验证记录
|
||||
|
||||
本轮已完成以下验证:
|
||||
|
||||
```bash
|
||||
cd FileCodeBoxFronted
|
||||
pnpm test
|
||||
pnpm check:architecture
|
||||
pnpm type-check
|
||||
pnpm lint:check
|
||||
pnpm build
|
||||
|
||||
cd ../FileCodeBox
|
||||
pytest
|
||||
|
||||
git diff --check
|
||||
```
|
||||
|
||||
验证结果:
|
||||
|
||||
- 前端 `pnpm test`:9 files / 27 tests passed。
|
||||
- 前端 `pnpm check:architecture`:通过。
|
||||
- 前端 `pnpm type-check`:通过。
|
||||
- 前端 `pnpm lint:check`:通过。
|
||||
- 前端 `pnpm build`:通过。
|
||||
- 后端 `pytest`:21 passed,仅存在 Tortoise ORM deprecation warnings。
|
||||
- 前后端 `git diff --check`:通过。
|
||||
|
||||
## 当前未提交文件
|
||||
|
||||
### 后端仓库
|
||||
|
||||
新增文件:
|
||||
|
||||
- `docs/development-plan.md`
|
||||
- `docs/development-delivery-report.md`
|
||||
- `tests/conftest.py`
|
||||
- `tests/test_presign_upload_flow.py`
|
||||
|
||||
### 前端仓库
|
||||
|
||||
修改文件:
|
||||
|
||||
- `package.json`
|
||||
- `pnpm-lock.yaml`
|
||||
- `scripts/check-architecture.mjs`
|
||||
- `src/composables/useAdminFiles.ts`
|
||||
- `src/composables/useSendFlow.ts`
|
||||
- `src/utils/download-action.ts`
|
||||
- `src/views/RetrievewFileView.vue`
|
||||
- `src/views/manage/FileManageView.vue`
|
||||
- `tsconfig.app.json`
|
||||
|
||||
新增文件:
|
||||
|
||||
- `src/components/common/AdminBatchActionBar.vue`
|
||||
- `src/composables/useAdminFileSelection.ts`
|
||||
- `src/composables/useAdminFileSelection.test.ts`
|
||||
- `src/composables/usePresignedUpload.test.ts`
|
||||
- `src/services/upload-strategy.test.ts`
|
||||
- `src/utils/admin-file-summary.ts`
|
||||
- `src/utils/admin-file-summary.test.ts`
|
||||
- `src/utils/admin-file-view-preset.ts`
|
||||
- `src/utils/admin-file-view-preset.test.ts`
|
||||
- `src/utils/content-preview.test.ts`
|
||||
- `src/utils/download-action.test.ts`
|
||||
- `src/utils/file-type.ts`
|
||||
- `src/utils/file-type.test.ts`
|
||||
- `src/utils/send-record.test.ts`
|
||||
- `vitest.config.ts`
|
||||
|
||||
## 后续建议
|
||||
|
||||
1. 提交前再次执行前后端验证命令,确保工作区未被其他改动影响。
|
||||
2. 分别在两个仓库创建提交,避免跨仓库状态混淆。
|
||||
3. 下一轮继续拆分管理文件模块时,优先处理筛选栏、详情侧栏和元数据编辑逻辑。
|
||||
4. 后端可继续补充 `allowed_file_types`、S3 `file_exists` 降级、主题资源路径穿越保护等测试。
|
||||
|
||||
## 推荐提交信息
|
||||
|
||||
后端仓库:
|
||||
|
||||
```bash
|
||||
git commit -m "test: add presign upload flow coverage"
|
||||
```
|
||||
|
||||
前端仓库:
|
||||
|
||||
```bash
|
||||
git commit -m "feat: add retrieve preview and frontend tests"
|
||||
```
|
||||
@@ -0,0 +1,211 @@
|
||||
# 下一步开发计划
|
||||
|
||||
本文档记录 FileCodeBox 下一阶段开发优先级、并行拆分方式、验收标准和质量门禁。
|
||||
|
||||
## 背景
|
||||
|
||||
当前工作区包含两个独立仓库:
|
||||
|
||||
- `FileCodeBox`:FastAPI 后端,包含接口、存储、管理后台 API、文档和后端测试。
|
||||
- `FileCodeBoxFronted`:Vue 3 + Vite 前端,包含公开取件/发件页和管理后台界面。
|
||||
|
||||
近期提交主要集中在 S3 存储、取件码归一化、文件类型限制、主题资源加载、前端管理页和上传下载体验。
|
||||
|
||||
下一阶段应优先处理用户可见断点和自动化回归保护,再推进大模块拆分。
|
||||
|
||||
## 优先级总览
|
||||
|
||||
### P0:补齐取件文件预览链路
|
||||
|
||||
目标:打通前端已存在但尚未完整接线的文件预览能力。
|
||||
|
||||
涉及模块:
|
||||
|
||||
- `RetrievewFileView.vue`
|
||||
- `FileDetailModal.vue`
|
||||
- `MediaPreviewModal.vue`
|
||||
- `useRetrieveFlow.ts`
|
||||
|
||||
主要工作:
|
||||
|
||||
1. 在取件详情弹窗中绑定文件预览事件。
|
||||
2. 在取件页渲染媒体预览弹窗。
|
||||
3. 确认图片、视频、音频、PDF 等可预览文件能正常打开。
|
||||
4. 保持关闭、下载、错误提示等状态行为一致。
|
||||
|
||||
验收标准:
|
||||
|
||||
```bash
|
||||
pnpm check:architecture
|
||||
pnpm build
|
||||
```
|
||||
|
||||
手工验收:
|
||||
|
||||
1. 上传非文本文件并获取取件码。
|
||||
2. 取件后打开详情弹窗。
|
||||
3. 点击预览,确认弹窗可打开。
|
||||
4. 确认关闭和下载动作正常。
|
||||
|
||||
### P0:建立最小前端测试体系
|
||||
|
||||
目标:为核心前端流程建立可持续的自动化回归保护。
|
||||
|
||||
现状:
|
||||
|
||||
- 前端暂无测试目录。
|
||||
- `package.json` 中暂无 `test` 脚本。
|
||||
- 最近改动涉及上传、下载、Markdown 预览、配置表单等高风险路径。
|
||||
|
||||
建议引入:
|
||||
|
||||
```bash
|
||||
vitest
|
||||
@vue/test-utils
|
||||
jsdom
|
||||
```
|
||||
|
||||
首批测试范围:
|
||||
|
||||
- 文件类型限制规则。
|
||||
- 过期时间限制校验。
|
||||
- Markdown 渲染和 HTML 清洗。
|
||||
- 下载动作解析。
|
||||
- 预签名上传与分片上传提交分支。
|
||||
|
||||
验收标准:
|
||||
|
||||
```bash
|
||||
pnpm test
|
||||
```
|
||||
|
||||
要求:
|
||||
|
||||
- 测试能在 60 秒内完成。
|
||||
- 核心工具函数至少具备首批单元测试。
|
||||
- 测试脚本不修改源码文件。
|
||||
|
||||
### P1:后端上传与存储回归加固
|
||||
|
||||
目标:把近期修复沉淀为后端测试,降低存储和上传链路回归风险。
|
||||
|
||||
涉及模块:
|
||||
|
||||
- `apps/base/views.py`
|
||||
- `core/storage.py`
|
||||
- `main.py`
|
||||
- `tests/`
|
||||
|
||||
优先测试场景:
|
||||
|
||||
1. 预签名上传 `init` / `confirm` / `cancel`。
|
||||
2. 代理上传文件大小校验。
|
||||
3. `allowed_file_types` 的扩展名、MIME、通配规则。
|
||||
4. S3 `file_exists` 的 `head_object` 失败降级逻辑。
|
||||
5. 主题资源路径穿越保护。
|
||||
|
||||
验收标准:
|
||||
|
||||
```bash
|
||||
pytest
|
||||
```
|
||||
|
||||
要求:
|
||||
|
||||
- 测试使用临时目录和替身对象,避免污染 `data/`。
|
||||
- 外部存储相关测试不依赖真实网络或真实 S3。
|
||||
- 异常路径和边界值必须覆盖。
|
||||
|
||||
### P1:调整质量脚本
|
||||
|
||||
目标:区分“检查”和“自动修复”,避免 CI 或验证命令改写源码。
|
||||
|
||||
当前问题:
|
||||
|
||||
```json
|
||||
"lint": "eslint . --fix"
|
||||
```
|
||||
|
||||
建议调整:
|
||||
|
||||
```json
|
||||
{
|
||||
"lint": "eslint . --fix",
|
||||
"lint:check": "eslint ."
|
||||
}
|
||||
```
|
||||
|
||||
推荐前端验证顺序:
|
||||
|
||||
```bash
|
||||
pnpm check:architecture
|
||||
pnpm type-check
|
||||
pnpm lint:check
|
||||
pnpm test
|
||||
pnpm build
|
||||
```
|
||||
|
||||
### P2:拆分管理文件模块
|
||||
|
||||
目标:降低管理文件页面和业务 composable 的维护复杂度。
|
||||
|
||||
现状:
|
||||
|
||||
- `FileManageView.vue` 体量较大。
|
||||
- `useAdminFiles.ts` 同时承载列表、筛选、视图预设、批量操作、详情、元数据、下载和预览等职责。
|
||||
|
||||
拆分顺序:
|
||||
|
||||
1. 抽纯函数:筛选参数归一化、视图预设归一化、摘要计算、详情视图模型转换。
|
||||
2. 抽 composable:批量操作、详情弹窗、元数据编辑、视图预设。
|
||||
3. 抽 UI 子组件:批量工具栏、筛选栏、详情侧栏、预设选择器。
|
||||
|
||||
约束:
|
||||
|
||||
- 每次只拆一块。
|
||||
- 拆分前后行为保持一致。
|
||||
- 先给纯函数补测试,再推进 UI 拆分。
|
||||
|
||||
## 并行开发安排
|
||||
|
||||
第一轮可并行拆分为四个互不冲突的任务:
|
||||
|
||||
1. 前端 A:接线取件文件预览。
|
||||
2. 前端 B:搭建 Vitest 与首批工具函数测试。
|
||||
3. 后端 C:补充上传和存储回归测试。
|
||||
4. 工程 D:新增 `lint:check` 并整理验证命令。
|
||||
|
||||
合并前统一验证:
|
||||
|
||||
```bash
|
||||
cd FileCodeBoxFronted
|
||||
pnpm check:architecture
|
||||
pnpm type-check
|
||||
pnpm lint:check
|
||||
pnpm test
|
||||
pnpm build
|
||||
|
||||
cd ../FileCodeBox
|
||||
pytest
|
||||
```
|
||||
|
||||
## 质量门禁
|
||||
|
||||
每个开发任务完成时必须记录:
|
||||
|
||||
- 改动范围。
|
||||
- 关键设计决策。
|
||||
- 执行过的验证命令。
|
||||
- 未覆盖风险和后续事项。
|
||||
|
||||
涉及上传、删除、存储、认证、配置等功能时,必须补充异常路径测试。
|
||||
|
||||
## 推荐执行顺序
|
||||
|
||||
1. 先完成 P0 的取件预览接线。
|
||||
2. 同步建立前端最小测试体系。
|
||||
3. 补齐后端上传和存储回归测试。
|
||||
4. 调整前端质量脚本。
|
||||
5. 等测试保护到位后,再拆分管理文件模块。
|
||||
|
||||
结论:下一阶段以“取件预览接线 + 测试体系建设”为主线,先修用户可见断点,再提升长期维护质量。
|
||||
@@ -0,0 +1,332 @@
|
||||
# FileCodeBox API Documentation
|
||||
|
||||
## API Version: 2.1.0
|
||||
|
||||
## Table of Contents
|
||||
- [Authentication](#authentication)
|
||||
- [Share API](#share-api)
|
||||
- [Admin API](#admin-api)
|
||||
|
||||
## Authentication
|
||||
|
||||
Some APIs require `Authorization` header for authentication:
|
||||
|
||||
```
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
### Get Token
|
||||
|
||||
When guest upload is disabled in admin panel (`openUpload=0`), you need to login first:
|
||||
|
||||
```bash
|
||||
curl -X POST "http://localhost:12345/admin/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"password": "FileCodeBox2023"}'
|
||||
```
|
||||
|
||||
**Response Example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"token": "xxx.xxx.xxx",
|
||||
"token_type": "Bearer"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Share API
|
||||
|
||||
### Share Text
|
||||
|
||||
**POST** `/share/text/`
|
||||
|
||||
Share text content and get a share code.
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Required | Default | Description |
|
||||
|-----------|------|----------|---------|-------------|
|
||||
| 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/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:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abc123"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Share File
|
||||
|
||||
**POST** `/share/file/`
|
||||
|
||||
Upload and share a file, get a share code.
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Required | Default | Description |
|
||||
|-----------|------|----------|---------|-------------|
|
||||
| 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/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:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "example.txt"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Get File Info
|
||||
|
||||
**GET** `/share/select/`
|
||||
|
||||
Get file information by share code (direct file download).
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| 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
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "example.txt",
|
||||
"size": 1024,
|
||||
"text": "File content or download link"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Select File
|
||||
|
||||
**POST** `/share/select/`
|
||||
|
||||
Select file by share code.
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| code | string | Yes | File share code |
|
||||
|
||||
**Response Example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "example.txt",
|
||||
"size": 1024,
|
||||
"text": "File content or download link"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Download File
|
||||
|
||||
**GET** `/share/download`
|
||||
|
||||
Download shared file.
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| key | string | Yes | Download key |
|
||||
| code | string | Yes | File share code |
|
||||
|
||||
## Admin API
|
||||
|
||||
### Admin Login
|
||||
|
||||
**POST** `/admin/login`
|
||||
|
||||
Admin login to get token.
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| password | string | Yes | Admin password |
|
||||
|
||||
### Dashboard Data
|
||||
|
||||
**GET** `/admin/dashboard`
|
||||
|
||||
Get system dashboard data.
|
||||
|
||||
**Response Example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"totalFiles": 100,
|
||||
"storageUsed": "1.5GB",
|
||||
"sysUptime": "10 days",
|
||||
"yesterdayCount": 50,
|
||||
"yesterdaySize": "500MB",
|
||||
"todayCount": 30,
|
||||
"todaySize": "300MB"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### File List
|
||||
|
||||
**GET** `/admin/file/list`
|
||||
|
||||
Get system file list.
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Required | Default | Description |
|
||||
|-----------|------|----------|---------|-------------|
|
||||
| page | integer | No | 1 | Current page |
|
||||
| size | integer | No | 10 | Page size |
|
||||
| keyword | string | No | "" | Search keyword |
|
||||
|
||||
**Response Example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"page": 1,
|
||||
"size": 10,
|
||||
"total": 100,
|
||||
"data": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "example.txt",
|
||||
"size": 1024,
|
||||
"created_at": "2024-01-01 12:00:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Delete File
|
||||
|
||||
**DELETE** `/admin/file/delete`
|
||||
|
||||
Delete file from system.
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| id | integer | Yes | File ID |
|
||||
|
||||
### Get Config
|
||||
|
||||
**GET** `/admin/config/get`
|
||||
|
||||
Get system configuration.
|
||||
|
||||
### Update Config
|
||||
|
||||
**PATCH** `/admin/config/update`
|
||||
|
||||
Update system configuration.
|
||||
|
||||
## Error Response
|
||||
|
||||
When an error occurs, the API will return corresponding error message:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 422,
|
||||
"detail": [
|
||||
{
|
||||
"loc": ["body", "password"],
|
||||
"msg": "Password cannot be empty",
|
||||
"type": "value_error"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Status Codes
|
||||
|
||||
- 200: Success
|
||||
- 401: Unauthorized
|
||||
- 403: Forbidden
|
||||
- 404: Not Found
|
||||
- 422: Validation Error
|
||||
- 500: Internal Server Error
|
||||
@@ -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 | `FileCodeBox2023` | Admin login password |
|
||||
| `showAdminAddr` | int | `0` | Show admin panel entry on homepage (1=show, 0=hide) |
|
||||
|
||||
::: danger Security Warning
|
||||
Always change the default `admin_token` in production environments! Using the default password poses serious security risks.
|
||||
:::
|
||||
|
||||
## 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
|
||||
@@ -0,0 +1,67 @@
|
||||
# Getting Started
|
||||
|
||||
## Introduction
|
||||
|
||||
FileCodeBox is a simple and efficient file sharing tool that supports temporary file transfer, sharing, and management. This guide will help you quickly deploy and use FileCodeBox.
|
||||
|
||||
## Features
|
||||
|
||||
- 🚀 Quick Deployment: Support Docker one-click deployment
|
||||
- 🔒 Secure & Reliable: File access requires extraction code
|
||||
- ⏱️ Time Control: Support setting file expiration time
|
||||
- 📊 Download Limit: Can limit file download times
|
||||
- 🖼️ File Preview: Support preview of images, videos, audio, and other formats
|
||||
- 📱 Responsive Design: Perfect adaptation for mobile and desktop
|
||||
|
||||
## Deployment Methods
|
||||
|
||||
### Docker Deployment
|
||||
|
||||
```bash
|
||||
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:beta
|
||||
```
|
||||
|
||||
### Manual Deployment
|
||||
|
||||
1. Clone the repository
|
||||
```bash
|
||||
git clone https://github.com/vastsa/FileCodeBox.git
|
||||
```
|
||||
|
||||
2. Install dependencies
|
||||
```bash
|
||||
cd FileCodeBox
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. Start the service
|
||||
```bash
|
||||
python main.py
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
1. Access the System
|
||||
Open browser and visit `http://localhost:12345`
|
||||
|
||||
2. Upload Files
|
||||
- Click upload button or drag files to upload area
|
||||
- Set file expiration time and download limit
|
||||
- Get share link and extraction code
|
||||
|
||||
3. Download Files
|
||||
- Visit share link
|
||||
- Enter extraction code
|
||||
- Download file
|
||||
|
||||
4. Admin Panel
|
||||
- Visit `http://localhost:12345/#/admin`
|
||||
- Enter admin password: `FileCodeBox2023`
|
||||
- Enter admin panel
|
||||
- View system information, file list, user management, etc.
|
||||
|
||||
## Next Steps
|
||||
|
||||
- [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
|
||||
@@ -0,0 +1,243 @@
|
||||
<div align="center">
|
||||
|
||||
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/static/banners/img_1.png" alt="FileCodeBox Logo">
|
||||
|
||||
<p><em>Share text and files anonymously with a passcode, like picking up a package</em></p>
|
||||
|
||||
[](https://github.com/vastsa/FileCodeBox/stargazers)
|
||||
[](https://github.com/vastsa/FileCodeBox/network)
|
||||
[](https://github.com/vastsa/FileCodeBox/issues)
|
||||
[](https://github.com/vastsa/FileCodeBox/blob/master/LICENSE)
|
||||
[](https://qm.qq.com/q/PemPzhdEIM)
|
||||
[](https://www.python.org)
|
||||
[](https://fastapi.tiangolo.com)
|
||||
[](https://v3.vuejs.org)
|
||||
|
||||
</div>
|
||||
|
||||
## 📝 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.
|
||||
|
||||
## 🖼️ Preview
|
||||
|
||||
<div align="center">
|
||||
<h3>
|
||||
<a href="https://github.com/vastsa/FileCodeBoxFronted" target="_blank">
|
||||
<img src="https://img.shields.io/badge/Frontend-FileCodeBoxFronted-blue?style=for-the-badge&logo=github" alt="Frontend Repository">
|
||||
</a>
|
||||
|
||||
<a href="https://share.lanol.cn" target="_blank">
|
||||
<img src="https://img.shields.io/badge/Demo-share.lanol.cn-green?style=for-the-badge&logo=internet-explorer" alt="Demo Site">
|
||||
</a>
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
|
||||
## 🎯 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
|
||||
|
||||
```bash
|
||||
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:beta
|
||||
```
|
||||
|
||||
### Manual Deployment
|
||||
|
||||
1. Clone the repository
|
||||
```bash
|
||||
git clone https://github.com/vastsa/FileCodeBox.git
|
||||
```
|
||||
|
||||
2. Install dependencies
|
||||
```bash
|
||||
cd FileCodeBox
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. Start the service
|
||||
```bash
|
||||
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
|
||||
|
||||
### Retrieve Files
|
||||
1. Open the website, enter passcode
|
||||
2. Click retrieve
|
||||
3. Download file or view text
|
||||
|
||||
### Admin Panel
|
||||
1. Visit `/admin`
|
||||
2. Enter admin password
|
||||
3. Manage files and settings
|
||||
|
||||
## 🛠 Development Guide
|
||||
|
||||
### Project Structure
|
||||
```
|
||||
FileCodeBox/
|
||||
├── apps/ # Application code
|
||||
│ ├── admin/ # Admin backend
|
||||
│ └── base/ # Base functions
|
||||
├── core/ # Core functions
|
||||
├── data/ # Data directory
|
||||
└── fcb-fronted/ # Frontend code
|
||||
```
|
||||
|
||||
### Development Environment
|
||||
- Python 3.8+
|
||||
- Node.js 14+
|
||||
- Vue 3
|
||||
- FastAPI
|
||||
|
||||
### Local Development
|
||||
1. Backend development
|
||||
```bash
|
||||
python main.py
|
||||
```
|
||||
|
||||
2. Frontend development
|
||||
```bash
|
||||
cd fcb-fronted
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
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
|
||||
|
||||
## ❓ FAQ
|
||||
|
||||
### Q: How to modify upload size limit?
|
||||
A: Change `uploadSize` in admin panel
|
||||
|
||||
### Q: How to configure storage engine?
|
||||
A: Select storage engine and configure parameters in admin panel
|
||||
|
||||
### Q: How to backup data?
|
||||
A: Backup the `data` directory
|
||||
|
||||
For more questions, visit [Wiki](https://github.com/vastsa/FileCodeBox/wiki/常见问题)
|
||||
|
||||
## 😀 Project Statistics and Analytics
|
||||
|
||||
<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>
|
||||
|
||||

|
||||
|
||||
[](https://star-history.com/#vastsa/FileCodeBox&Date)
|
||||
</div>
|
||||
|
||||
## 📜 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.
|
||||
@@ -0,0 +1,413 @@
|
||||
# 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. Visit `http://your-domain.com/admin` in your browser
|
||||
2. Enter the admin password (the value of the `admin_token` configuration)
|
||||
3. Click the login button
|
||||
|
||||
::: tip Tip
|
||||
The default admin password is `FileCodeBox2023`. Be sure to change this password in production environments. See [Security Settings](/en/guide/security) for details.
|
||||
:::
|
||||
|
||||
### 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
|
||||
@@ -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
|
||||
|
||||
### Change Default Password
|
||||
|
||||
::: danger Important Security Warning
|
||||
FileCodeBox's default admin password is `FileCodeBox2023`. **You must change this password immediately in production environments!** Using the default password allows anyone to access your admin panel.
|
||||
:::
|
||||
|
||||
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:
|
||||
|
||||
- [ ] Changed default 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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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": "FileCodeBox2023"}'
|
||||
|
||||
# Returns: {"code":200,"msg":"success","detail":{"token":"xxx.xxx.xxx","token_type":"Bearer"}}
|
||||
|
||||
# 2. Upload file with token
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-H "Authorization: Bearer xxx.xxx.xxx" \
|
||||
-F "file=@/path/to/file.pdf"
|
||||
|
||||
# 3. Share text with token
|
||||
curl -X POST "http://localhost:12345/share/text/" \
|
||||
-H "Authorization: Bearer xxx.xxx.xxx" \
|
||||
-F "text=This is the text content to share"
|
||||
```
|
||||
:::
|
||||
|
||||
|
||||
## Chunked Upload API
|
||||
|
||||
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
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
layout: home
|
||||
|
||||
hero:
|
||||
name: "FileCodeBox"
|
||||
text: "File Express Box"
|
||||
tagline: Share text and files anonymously with access codes, just like picking up a package
|
||||
image:
|
||||
src: /logo_small.png
|
||||
alt: FileCodeBox
|
||||
actions:
|
||||
- theme: brand
|
||||
text: Get Started
|
||||
link: /en/guide/getting-started
|
||||
- theme: alt
|
||||
text: Live Demo
|
||||
link: https://share.lanol.cn
|
||||
- theme: alt
|
||||
text: View on GitHub
|
||||
link: https://github.com/vastsa/FileCodeBox
|
||||
|
||||
features:
|
||||
- icon: 🚀
|
||||
title: Quick Deployment
|
||||
details: Supports one-click Docker deployment, simple and fast, no complex configuration needed
|
||||
- icon: 🔒
|
||||
title: Secure & Reliable
|
||||
details: File access requires an access code, supports expiration time and download limit settings
|
||||
- icon: 💻
|
||||
title: Clean Interface
|
||||
details: Clean user interface with drag-and-drop upload support for excellent user experience
|
||||
- icon: 🛠️
|
||||
title: Feature Rich
|
||||
details: Supports file preview, online playback, image processing, and many other features
|
||||
- icon: 📦
|
||||
title: Storage Extensions
|
||||
details: Supports various storage methods including local storage and object storage
|
||||
- icon: 🔌
|
||||
title: API Support
|
||||
details: Provides complete REST API for easy integration with other systems
|
||||
---
|
||||
@@ -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>
|
||||
@@ -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 | `FileCodeBox2023` | 管理员登录密码 |
|
||||
| `showAdminAddr` | int | `0` | 是否在首页显示管理入口(1=显示,0=隐藏) |
|
||||
|
||||
::: danger 安全警告
|
||||
请务必在生产环境中修改默认的 `admin_token`!使用默认密码会导致严重的安全风险。
|
||||
:::
|
||||
|
||||
## 安全设置
|
||||
|
||||
### 错误次数限制
|
||||
|
||||
| 配置项 | 类型 | 默认值 | 说明 |
|
||||
|--------|------|--------|------|
|
||||
| `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) - 了解文件分享功能
|
||||
@@ -0,0 +1,121 @@
|
||||
# 快速开始
|
||||
|
||||
## 简介
|
||||
|
||||
FileCodeBox 是一个简单高效的文件分享工具,支持文件临时中转、分享和管理。本指南将帮助您快速部署和使用 FileCodeBox。
|
||||
|
||||
## 特性
|
||||
|
||||
- 🚀 快速部署:支持 Docker 一键部署
|
||||
- 🔒 安全可靠:文件访问需要提取码
|
||||
- ⏱️ 时效控制:支持设置文件有效期
|
||||
- 📊 下载限制:可限制文件下载次数
|
||||
- 🖼️ 文件预览:支持图片、视频、音频等多种格式预览
|
||||
- 📱 响应式设计:完美适配移动端和桌面端
|
||||
|
||||
## 部署方式
|
||||
|
||||
### Docker 部署(推荐)
|
||||
|
||||
#### 快速启动
|
||||
|
||||
```bash
|
||||
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;
|
||||
}
|
||||
```
|
||||
|
||||
### 手动部署
|
||||
|
||||
1. 克隆项目
|
||||
```bash
|
||||
git clone https://github.com/vastsa/FileCodeBox.git
|
||||
```
|
||||
|
||||
2. 安装依赖
|
||||
```bash
|
||||
cd FileCodeBox
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. 启动服务
|
||||
```bash
|
||||
python main.py
|
||||
```
|
||||
|
||||
|
||||
## 使用方法
|
||||
|
||||
1. 访问系统
|
||||
打开浏览器访问 `http://localhost:12345`
|
||||
|
||||
2. 上传文件
|
||||
- 点击上传按钮或拖拽文件到上传区域
|
||||
- 设置文件有效期和下载次数限制
|
||||
- 获取分享链接和提取码
|
||||
|
||||
3. 下载文件
|
||||
- 访问分享链接
|
||||
- 输入提取码
|
||||
- 下载文件
|
||||
|
||||
4. 后台管理
|
||||
- 访问 `http://localhost:12345/#/admin`
|
||||
- 输入管理员密码:`FileCodeBox2023`
|
||||
- 进入后台管理页面
|
||||
- 查看系统信息、文件列表、用户管理等
|
||||
|
||||
## 下一步
|
||||
|
||||
- [存储配置](/guide/storage) - 了解如何配置不同的存储方式
|
||||
- [安全设置](/guide/security) - 了解如何增强系统安全性
|
||||
- [API 文档](/api/) - 了解如何通过 API 集成
|
||||
@@ -0,0 +1,235 @@
|
||||
<div align="center">
|
||||
|
||||
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/static/banners/img_1.png" alt="FileCodeBox Logo">
|
||||
|
||||
<p><em>匿名口令分享文本和文件,像拿快递一样取文件</em></p>
|
||||
|
||||
[](https://github.com/vastsa/FileCodeBox/stargazers)
|
||||
[](https://github.com/vastsa/FileCodeBox/network)
|
||||
[](https://github.com/vastsa/FileCodeBox/issues)
|
||||
[](https://github.com/vastsa/FileCodeBox/blob/master/LICENSE)
|
||||
[](https://qm.qq.com/q/PemPzhdEIM)
|
||||
[](https://www.python.org)
|
||||
[](https://fastapi.tiangolo.com)
|
||||
[](https://v3.vuejs.org)
|
||||
</div>
|
||||
|
||||
|
||||
## 🚀 更新计划
|
||||
- [ ] 切片上传,同文件秒传,断点续传
|
||||
- [ ] 用户登录重构
|
||||
- [x] webdav存储
|
||||
- [x] 存储支持自定义路径
|
||||
- [x] s3优化,不修改昵称为uuid,新建目录
|
||||
|
||||
## 📝 项目简介
|
||||
|
||||
FileCodeBox 是一个基于 FastAPI + Vue3 开发的轻量级文件分享工具。它允许用户通过简单的方式分享文本和文件,接收者只需要一个提取码就可以取得文件,就像从快递柜取出快递一样简单。
|
||||
|
||||
## 🎯 应用场景
|
||||
|
||||
<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 部署
|
||||
|
||||
```bash
|
||||
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:beta
|
||||
```
|
||||
|
||||
### 手动部署
|
||||
|
||||
1. 克隆项目
|
||||
```bash
|
||||
git clone https://github.com/vastsa/FileCodeBox.git
|
||||
```
|
||||
|
||||
2. 安装依赖
|
||||
```bash
|
||||
cd FileCodeBox
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. 启动服务
|
||||
```bash
|
||||
python main.py
|
||||
```
|
||||
|
||||
## 📖 使用说明
|
||||
|
||||
### 分享文件
|
||||
1. 打开网页,点击"分享文件"
|
||||
2. 选择或拖拽文件
|
||||
3. 设置过期时间和次数
|
||||
4. 获取提取码
|
||||
|
||||
### 获取文件
|
||||
1. 打开网页,输入提取码
|
||||
2. 点击获取
|
||||
3. 下载文件或查看文本
|
||||
|
||||
### 管理面板
|
||||
1. 访问 `/admin`
|
||||
2. 输入管理员密码
|
||||
3. 管理文件和配置
|
||||
|
||||
## 🛠 开发指南
|
||||
|
||||
### 项目结构
|
||||
```
|
||||
FileCodeBox/
|
||||
├── apps/ # 应用代码
|
||||
│ ├── admin/ # 管理后台
|
||||
│ └── base/ # 基础功能
|
||||
├── core/ # 核心功能
|
||||
├── data/ # 数据目录
|
||||
└── fcb-fronted/ # 前端代码
|
||||
```
|
||||
|
||||
### 开发环境
|
||||
- Python 3.8+
|
||||
- Node.js 14+
|
||||
- Vue 3
|
||||
- FastAPI
|
||||
|
||||
### 本地开发
|
||||
1. 后端开发
|
||||
```bash
|
||||
python main.py
|
||||
```
|
||||
|
||||
2. 前端开发
|
||||
```bash
|
||||
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
|
||||
|
||||
## ❓ 常见问题
|
||||
|
||||
### Q: 如何修改上传大小限制?
|
||||
A: 在管理面板中修改配置项 `uploadSize`
|
||||
|
||||
### Q: 如何配置存储引擎?
|
||||
A: 在管理面板中选择存储引擎并配置相应参数
|
||||
|
||||
### Q: 如何备份数据?
|
||||
A: 备份 `data` 目录即可
|
||||
|
||||
更多问题请访问 [Wiki](https://github.com/vastsa/FileCodeBox/wiki/常见问题)
|
||||
|
||||
## 📊 项目统计
|
||||
|
||||
<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>
|
||||
|
||||

|
||||
|
||||
[](https://star-history.com/#vastsa/FileCodeBox&Date)
|
||||
</div>
|
||||
|
||||
## 📜 免责声明
|
||||
|
||||
本项目开源仅供学习使用,不得用于任何违法用途,否则后果自负,与作者无关。使用时请保留项目地址和版权信息。
|
||||
@@ -0,0 +1,412 @@
|
||||
# 管理面板
|
||||
|
||||
FileCodeBox 提供了功能完善的管理面板,让管理员可以方便地管理文件、查看系统状态和修改配置。本文档介绍管理面板的各项功能和使用方法。
|
||||
|
||||
## 访问管理面板
|
||||
|
||||
### 登录方式
|
||||
|
||||
管理面板位于 `/admin` 路径。访问方式:
|
||||
|
||||
1. 在浏览器中访问 `http://your-domain.com/admin`
|
||||
2. 输入管理员密码(`admin_token` 配置项的值)
|
||||
3. 点击登录按钮
|
||||
|
||||
::: tip 提示
|
||||
默认管理员密码是 `FileCodeBox2023`。请务必在生产环境中修改此密码,详见 [安全设置](/guide/security)。
|
||||
:::
|
||||
|
||||
### 显示管理入口
|
||||
|
||||
默认情况下,首页不显示管理面板入口。您可以通过配置控制是否显示:
|
||||
|
||||
| 配置项 | 类型 | 默认值 | 说明 |
|
||||
|--------|------|--------|------|
|
||||
| `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) - 配置不同的存储后端
|
||||
@@ -0,0 +1,324 @@
|
||||
# 安全设置
|
||||
|
||||
FileCodeBox 提供了多层安全机制来保护您的文件分享服务。本文档介绍如何正确配置安全选项,确保系统安全运行。
|
||||
|
||||
## 管理员密码
|
||||
|
||||
### 修改默认密码
|
||||
|
||||
::: danger 重要安全警告
|
||||
FileCodeBox 的默认管理员密码是 `FileCodeBox2023`。**在生产环境中必须立即修改此密码!**使用默认密码会导致任何人都可以访问您的管理面板。
|
||||
:::
|
||||
|
||||
修改管理员密码有两种方式:
|
||||
|
||||
**方式一:通过管理面板修改(推荐)**
|
||||
|
||||
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) - 了解文件分享功能
|
||||
@@ -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) - 了解如何管理分享的文件
|
||||
@@ -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. 确认网络连接正常
|
||||
@@ -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": "FileCodeBox2023"}'
|
||||
|
||||
# 返回: {"code":200,"msg":"success","detail":{"token":"xxx.xxx.xxx","token_type":"Bearer"}}
|
||||
|
||||
# 2. 使用 token 上传文件
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-H "Authorization: Bearer xxx.xxx.xxx" \
|
||||
-F "file=@/path/to/file.pdf"
|
||||
|
||||
# 3. 使用 token 分享文本
|
||||
curl -X POST "http://localhost:12345/share/text/" \
|
||||
-H "Authorization: Bearer xxx.xxx.xxx" \
|
||||
-F "text=这是要分享的文本内容"
|
||||
```
|
||||
:::
|
||||
|
||||
## 分片上传 API
|
||||
|
||||
对于大文件,FileCodeBox 支持分片上传功能。分片上传将大文件分割成多个小块分别上传,支持断点续传。
|
||||
|
||||
::: 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) - 了解安全相关配置
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
layout: home
|
||||
|
||||
hero:
|
||||
name: "FileCodeBox"
|
||||
text: "文件快递柜"
|
||||
tagline: 匿名口令分享文本,文件,像拿快递一样取文件
|
||||
image:
|
||||
src: /logo_small.png
|
||||
alt: FileCodeBox
|
||||
actions:
|
||||
- theme: brand
|
||||
text: 快速开始
|
||||
link: /guide/getting-started
|
||||
- theme: alt
|
||||
text: 在线体验
|
||||
link: https://share.lanol.cn
|
||||
- theme: alt
|
||||
text: 在 GitHub 上查看
|
||||
link: https://github.com/vastsa/FileCodeBox
|
||||
|
||||
features:
|
||||
- icon: 🚀
|
||||
title: 快速部署
|
||||
details: 支持 Docker 一键部署,简单快捷,无需复杂配置
|
||||
- icon: 🔒
|
||||
title: 安全可靠
|
||||
details: 文件访问需要提取码,支持设置有效期和下载次数限制
|
||||
- icon: 💻
|
||||
title: 简洁界面
|
||||
details: 清爽的用户界面,支持拖拽上传,使用体验极佳
|
||||
- icon: 🛠️
|
||||
title: 功能丰富
|
||||
details: 支持文件预览、在线播放、图片处理等多种功能
|
||||
- icon: 📦
|
||||
title: 存储扩展
|
||||
details: 支持本地存储、对象存储等多种存储方式
|
||||
- icon: 🔌
|
||||
title: API 支持
|
||||
details: 提供完整的 REST API,方便与其他系统集成
|
||||
---
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"devDependencies": {
|
||||
"vitepress": "^1.6.3"
|
||||
},
|
||||
"scripts": {
|
||||
"docs:dev": "vitepress dev",
|
||||
"docs:build": "vitepress build",
|
||||
"docs:preview": "vitepress preview"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 92 KiB |
@@ -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>
|
||||
@@ -0,0 +1,843 @@
|
||||
# 功能与用户体验提升规划
|
||||
|
||||
生成日期:2026-06-06
|
||||
|
||||
本文档承接 `development-plan.md` 和 `development-delivery-report.md`,用于规划下一轮“功能增强 + 用户体验提升”开发。重点不是重做界面,而是让发送、取件和管理流程更清楚、更可恢复、更适合反复使用。
|
||||
|
||||
## 当前基线
|
||||
|
||||
当前工作区包含两个独立仓库:
|
||||
|
||||
- `FileCodeBox`:FastAPI 后端,提供分享、取件、分片上传、预签名上传、管理后台、配置和本地文件管理接口。
|
||||
- `FileCodeBoxFronted`:Vue 3 + Vite 前端,提供公开取件页、发件页、登录页、管理仪表盘、文件管理和系统设置。
|
||||
|
||||
本轮已完成的基础能力:
|
||||
|
||||
- 取件文件预览链路已接通。
|
||||
- 前端 Vitest 测试体系已建立。
|
||||
- 后端预签名上传流程已有回归测试。
|
||||
- 管理文件页已抽出部分纯函数、批量选择逻辑和批量操作栏。
|
||||
|
||||
下一轮应把重点从“能用”推进到“好用、稳定、可解释”。
|
||||
|
||||
## 体验目标
|
||||
|
||||
1. 发送流程要让用户明确知道当前文件是否可发、发到哪一步、失败后如何继续。
|
||||
2. 取件流程要避免误消耗取件次数,先展示文件摘要,再由用户确认下载或预览。
|
||||
3. 管理后台要提高高频操作效率,减少大页面内工具堆叠和重复确认成本。
|
||||
4. 所有危险操作要有清晰影响范围,避免误删、误批量修改和不可逆操作。
|
||||
5. 错误提示要从“发生错误”升级为“原因 + 可执行下一步”。
|
||||
|
||||
## 规划依据
|
||||
|
||||
本轮规划基于前后端只读审阅结果:
|
||||
|
||||
- 前端主流程已完整,但取件前确认、上传取消/重试、发送成功结果区和后台强确认仍不足。
|
||||
- 后端接口能力较全,但取件扣次数、下载票据、预签名直传确认、错误响应和审计追踪仍需要加固。
|
||||
- 下一轮应优先处理“安全边界 + 关键路径体验”,再扩展管理效率和长期产品能力。
|
||||
|
||||
## P0:取件扣次数与下载票据一致性
|
||||
|
||||
目标:确保取件次数只在真实授权动作中消耗,并且旧下载地址不能绕过过期或次数限制。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- `/share/select/` 当前会调用 `update_file_usage()`,取件前缺少确认时容易误消耗次数。
|
||||
- `/share/download` 使用 `check=False` 获取文件记录,已生成的下载地址存在被继续复用的窗口。
|
||||
- 下载票据由 `get_select_token()` 生成,缺少明确的短期过期语义和服务端状态绑定。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 将“查看元数据”和“确认取件授权”严格分离。
|
||||
2. 为确认取件生成短期下载票据:
|
||||
- 票据绑定取件码。
|
||||
- 票据包含过期时间。
|
||||
- 票据校验时重新检查文件是否过期、次数是否耗尽。
|
||||
3. 并发场景下保证 `expired_count=1` 只能成功一次。
|
||||
4. 下载接口拒绝已过期、次数耗尽或票据失效的请求。
|
||||
5. 响应中明确返回剩余次数和下一步动作。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `apps/base/views.py`
|
||||
- `core/utils.py`
|
||||
- `apps/base/models.py`
|
||||
- `tests/`
|
||||
|
||||
### 数据模型影响
|
||||
|
||||
第一阶段可先使用签名票据,不强制新增表。
|
||||
|
||||
如果要做更完整审计,后续新增:
|
||||
|
||||
- `DownloadTicket`
|
||||
- `FileAccessLog`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 元数据查询不消耗下载次数。
|
||||
2. 确认取件后才消耗次数并返回下载票据。
|
||||
3. `expired_count=1` 并发取件时只能成功一次。
|
||||
4. 旧下载地址在文件过期或次数耗尽后不可继续下载。
|
||||
5. 后端测试覆盖票据过期、次数耗尽和并发边界。
|
||||
|
||||
## P0:公开取件体验升级
|
||||
|
||||
目标:取件码输入后先确认内容,再执行会消耗次数的取件动作。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- `RetrievewFileView.vue` 在取件码长度达到 5 位时直接调用 `handleSubmit()`。
|
||||
- `handleSubmit()` 调用 `/share/select/`,会执行 `update_file_usage()`,可能消耗下载次数。
|
||||
- `useRetrieveFlow.ts` 已有 `inspectCode()` 和 `inspectedFile`,但页面当前未形成完整的“预检查确认”体验。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 输入 5 位取件码后调用 `inspectCode()`,请求 `/share/metadata/`。
|
||||
2. 页面展示文件摘要卡片:
|
||||
- 文件名或文本类型。
|
||||
- 文件大小。
|
||||
- 过期时间。
|
||||
- 剩余下载次数。
|
||||
- 是否可预览。
|
||||
3. 用户点击“取件”后再调用 `handleSubmit()`。
|
||||
4. 如果文件已过期或次数耗尽,直接展示不可取原因,不再进入下载动作。
|
||||
5. 查询参数 `?code=xxxxx` 进入页面时,也走同样的预检查流程。
|
||||
6. 与服务端下载票据机制配合,确认取件后再获得可下载地址。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `RetrievewFileView.vue`
|
||||
- `RetrieveForm.vue`
|
||||
- `useRetrieveFlow.ts`
|
||||
- `FileDetailModal.vue`
|
||||
- `download-action.ts`
|
||||
- `src/i18n/locales/zh-CN.ts`
|
||||
- `src/i18n/locales/en-US.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
```bash
|
||||
cd FileCodeBoxFronted
|
||||
pnpm test
|
||||
pnpm check:architecture
|
||||
pnpm type-check
|
||||
pnpm lint:check
|
||||
pnpm build
|
||||
```
|
||||
|
||||
手工验收:
|
||||
|
||||
1. 输入有效取件码,只展示摘要,不立即消耗下载次数。
|
||||
2. 点击确认取件后,才新增取件记录并打开详情或预览。
|
||||
3. 输入过期取件码时展示明确原因。
|
||||
4. 从 `?code=xxxxx` 访问时能自动展示摘要。
|
||||
|
||||
## P0:发送结果页增强
|
||||
|
||||
目标:发送成功后让用户更快完成复制、分享、复查和再次发送。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- `useSendFlow.ts` 发送成功后会自动复制链接并打开记录详情。
|
||||
- 用户能看到结果,但结果区域更像历史详情,不像一次明确的“发送完成”状态。
|
||||
- 多文件、文本、单文件的结果反馈可以更聚焦。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 新增发送成功结果面板,替代只依赖记录详情弹窗:
|
||||
- 取件码大号展示。
|
||||
- 一键复制取件码。
|
||||
- 一键复制链接。
|
||||
- 二维码展示入口。
|
||||
- 重新发送按钮。
|
||||
2. 明确自动复制结果:
|
||||
- 复制成功展示“链接已复制”。
|
||||
- 复制失败展示“请手动复制”。
|
||||
3. 多文件上传成功后展示文件数量和压缩包/批量记录说明。
|
||||
4. 文本发送成功后提供“预览文本”和“复制原文”。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `SendFileView.vue`
|
||||
- `SentRecordDetailModal.vue`
|
||||
- `SentRecordList.vue`
|
||||
- `useSendFlow.ts`
|
||||
- `sent-record-actions.ts`
|
||||
- `send-record.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 单文件、文本、多文件发送成功后都有明确完成态。
|
||||
2. 复制取件码、复制链接、二维码入口可用。
|
||||
3. 发送成功后再次选择文件或文本不会残留上一次进度。
|
||||
4. 自动复制失败时有人工复制路径。
|
||||
|
||||
## P0:上传失败恢复与取消
|
||||
|
||||
目标:上传过程可中断、可重试、可解释。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- 前端已有上传进度、速度和预签名上传封装。
|
||||
- 用户在上传中无法主动取消。
|
||||
- 失败后缺少保留文件并重试的明确路径。
|
||||
- 预签名上传会话存在后端取消接口,但前端体验还可以更完整。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 上传中展示取消按钮。
|
||||
2. 取消时调用对应取消逻辑:
|
||||
- 预签名上传:`DELETE /presign/upload/{upload_id}`。
|
||||
- 分片上传:`DELETE /chunk/upload/{upload_id}`。
|
||||
3. 失败后保留已选择文件,提供“重试”按钮。
|
||||
4. 错误提示按类型分层:
|
||||
- 文件过大。
|
||||
- 文件类型不允许。
|
||||
- 网络中断。
|
||||
- 服务端拒绝。
|
||||
- 上传会话过期。
|
||||
5. 上传过程中离开页面时提示用户确认。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `FileUploadArea.vue`
|
||||
- `SendFileView.vue`
|
||||
- `useSendFlow.ts`
|
||||
- `useSendSubmit.ts`
|
||||
- `usePresignedUpload.ts`
|
||||
- `upload-strategy.ts`
|
||||
- `FileService`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 上传中可以取消,后端临时会话或分片状态被清理。
|
||||
2. 网络失败后可以直接重试,不需要重新选择文件。
|
||||
3. 取消上传后进度归零,按钮状态恢复。
|
||||
4. 页面跳转或关闭前有上传中提示。
|
||||
|
||||
## P0:预签名直传确认加固
|
||||
|
||||
目标:直传文件确认不只检查“对象存在”,还要确认大小、状态和失败原因。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- `presign_upload_confirm()` 当前主要依赖 `file_exists()`。
|
||||
- 直传对象大小不符、上传中断、对象异常时,服务端难以给出准确原因。
|
||||
- `PresignUploadSession` 当前缺少状态字段,前端只能通过接口错误推断上传阶段。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 存储接口增加对象元信息读取能力:
|
||||
- `stat_file(save_path)`
|
||||
- 返回是否存在、实际大小、更新时间和存储后端错误。
|
||||
2. `presign_upload_confirm()` 校验实际大小与声明大小一致。
|
||||
3. 上传会话状态响应补充原因:
|
||||
- `pending`
|
||||
- `uploading`
|
||||
- `uploaded`
|
||||
- `confirmed`
|
||||
- `expired`
|
||||
- `cancelled`
|
||||
- `failed`
|
||||
4. 失败时返回明确错误码和可展示文案。
|
||||
5. 取消或失败后清理可清理的临时对象。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `apps/base/views.py`
|
||||
- `apps/base/models.py`
|
||||
- `core/storage.py`
|
||||
- `src/composables/usePresignedUpload.ts`
|
||||
- `src/services/presign-upload.ts`
|
||||
- `tests/test_presign_upload_flow.py`
|
||||
|
||||
### 数据模型影响
|
||||
|
||||
建议为 `PresignUploadSession` 增加:
|
||||
|
||||
- `status`
|
||||
- `actual_size`
|
||||
- `error_message`
|
||||
|
||||
第一阶段如果不做迁移,也可以先在状态接口中计算并返回原因。
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 直传对象不存在时返回明确错误。
|
||||
2. 直传对象大小不符时拒绝创建分享记录。
|
||||
3. 会话过期、取消、确认成功均有稳定状态。
|
||||
4. 前端能展示初始化、上传中、确认中、失败、成功状态。
|
||||
5. 后端测试覆盖对象不存在、大小不符、取消清理和会话过期。
|
||||
|
||||
## P0:统一错误响应与请求追踪
|
||||
|
||||
目标:让前端能稳定识别业务错误、网络错误和权限错误,并展示可执行下一步。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- 部分接口抛出 `HTTPException`,部分接口返回 `APIResponse(code=404)`。
|
||||
- 客户端难以稳定区分上传超限、类型不允许、取件码不存在、会话过期等业务失败。
|
||||
- 缺少请求 ID,线上排查问题时难以关联日志和用户反馈。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 统一错误响应结构:
|
||||
- `code`
|
||||
- `message`
|
||||
- `error_code`
|
||||
- `request_id`
|
||||
- `detail`
|
||||
2. 增加全局异常处理中间件或异常处理器。
|
||||
3. 上传、取件、登录、配置保存等关键接口返回稳定错误码。
|
||||
4. 前端错误提示按 `error_code` 映射文案和建议动作。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `core/response.py`
|
||||
- `main.py`
|
||||
- `apps/base/views.py`
|
||||
- `apps/admin/views.py`
|
||||
- `src/utils/common.ts`
|
||||
- `src/services/client.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 上传超限、类型不允许、取件码不存在、登录失败返回统一结构。
|
||||
2. 前端提示包含原因和下一步动作。
|
||||
3. 日志中可按 `request_id` 定位请求。
|
||||
4. 后端测试覆盖全局错误响应格式。
|
||||
|
||||
## P0:管理高风险操作确认升级
|
||||
|
||||
目标:删除、批量修改、批量策略等不可逆操作必须让管理员清楚知道影响范围。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- `useAdminFiles.ts` 中多处仍使用 `window.confirm()`。
|
||||
- 批量删除、批量更新和批量策略操作缺少文件样例、影响数量和不可逆提示。
|
||||
- 视图预设删除、单文件删除和批量删除的确认体验不统一。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 替换 `window.confirm()` 为统一确认弹窗。
|
||||
2. 确认弹窗展示:
|
||||
- 操作类型。
|
||||
- 影响文件数量。
|
||||
- 文件样例。
|
||||
- 是否不可逆。
|
||||
- 操作执行后可能的结果。
|
||||
3. 操作执行中禁用确认按钮和相关批量按钮。
|
||||
4. 操作完成后展示成功数量、失败数量和失败原因。
|
||||
5. 删除本地浏览器记录时明确提示“不删除服务器文件”。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `FileManageView.vue`
|
||||
- `AdminBatchActionBar.vue`
|
||||
- `BaseModal.vue`
|
||||
- `useAdminFiles.ts`
|
||||
- `SentRecordList.vue`
|
||||
- `FileRecordList.vue`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 单文件删除、批量删除、批量更新、批量策略动作均使用统一确认弹窗。
|
||||
2. 批量删除前可看到选中数量和至少 3 个文件样例。
|
||||
3. 操作中按钮禁用,避免重复提交。
|
||||
4. 取消操作不会改变选中状态。
|
||||
5. 操作结果能区分全部成功、部分成功和全部失败。
|
||||
|
||||
## P0:配置保存强校验
|
||||
|
||||
目标:把配置错误拦在保存阶段,而不是等用户上传或下载时才暴露。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- 配置存储在 `KeyValue` 中,更新入口需要更强字段校验。
|
||||
- 存储后端切换、上传限制、过期策略、文件类型规则等配置一旦错误,会直接影响公开流程。
|
||||
- 前端设置页有未保存状态,但配置变更风险没有形成统一摘要。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 后端保存配置前做字段级校验:
|
||||
- `file_storage` 必须是支持的存储后端。
|
||||
- 上传大小、限流和保存时长不能为负数。
|
||||
- `expireStyle` 必须属于允许枚举。
|
||||
- S3、WebDAV、OpenDAL、OneDrive 的必填项按存储类型校验。
|
||||
2. 前端保存前展示变更摘要:
|
||||
- 已变更字段。
|
||||
- 是否影响现有上传。
|
||||
- 是否需要管理员复查。
|
||||
3. 高风险配置显示明确提示:
|
||||
- 公开上传。
|
||||
- 允许全部文件类型。
|
||||
- 永久保存。
|
||||
- 默认管理员口令。
|
||||
4. 设置页离开、刷新、切换后台页面时提示保存或放弃。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
前端:
|
||||
|
||||
- `SystemSettingsView.vue`
|
||||
- `useSystemConfig.ts`
|
||||
- `router/index.ts`
|
||||
- `config-storage.ts`
|
||||
|
||||
后端:
|
||||
|
||||
- `apps/admin/services.py`
|
||||
- `apps/admin/views.py`
|
||||
- `core/settings.py`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 非法配置会被后端拒绝,并返回具体字段原因。
|
||||
2. 前端保存前展示变更摘要。
|
||||
3. 未保存配置离开页面会触发确认。
|
||||
4. 默认管理员口令、公开上传、允许所有文件类型会有高风险提示。
|
||||
|
||||
## P1:管理文件页信息架构优化
|
||||
|
||||
目标:把管理页从“功能堆在一个表格上”调整为更适合高频扫描和批量处理的工作台。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- `FileManageView.vue` 仍承担较多职责。
|
||||
- 筛选、预设、批量操作、表格、详情、编辑弹窗集中在同一个页面。
|
||||
- 单行操作按钮较多,在窄屏或大量数据时容易拥挤。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 拆分筛选区组件:
|
||||
- `AdminFileFilterBar.vue`
|
||||
- 负责关键词、状态、健康度、类型、排序和预设入口。
|
||||
2. 拆分详情侧栏:
|
||||
- `AdminFileDetailDrawer.vue`
|
||||
- 替代过重弹窗,保留复制、下载、编辑、预览入口。
|
||||
3. 表格行操作收敛为主操作 + 更多菜单:
|
||||
- 详情作为主操作。
|
||||
- 下载、编辑、删除进入更多菜单。
|
||||
4. 增加快捷筛选:
|
||||
- 即将过期。
|
||||
- 从未取件。
|
||||
- 已耗尽次数。
|
||||
- 存储异常。
|
||||
5. 表格空状态提供可执行动作:
|
||||
- 清空筛选。
|
||||
- 创建视图预设。
|
||||
- 返回全部文件。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `FileManageView.vue`
|
||||
- `AdminBatchActionBar.vue`
|
||||
- `useAdminFiles.ts`
|
||||
- `admin-file-summary.ts`
|
||||
- `admin-file-view-preset.ts`
|
||||
- `src/i18n/locales/zh-CN.ts`
|
||||
- `src/i18n/locales/en-US.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 筛选区、批量操作区、表格区职责清晰。
|
||||
2. 窄屏下表格行操作不溢出。
|
||||
3. 快捷筛选能正确改变请求参数并刷新数据。
|
||||
4. 已有批量选择、批量删除、批量策略动作不回归。
|
||||
|
||||
## P1:管理后台操作反馈增强
|
||||
|
||||
目标:让管理员明确知道批量操作影响了哪些文件、哪些成功、哪些失败。
|
||||
|
||||
### 现状能力
|
||||
|
||||
- 后端已有批量删除、批量更新、策略动作和活动记录。
|
||||
- 前端已有批量操作栏。
|
||||
- 后端 `FileService` 已具备管理活动记录能力。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 批量操作执行前展示影响摘要:
|
||||
- 选中文件数。
|
||||
- 即将修改的字段。
|
||||
- 不可逆风险。
|
||||
2. 批量操作完成后展示结果摘要:
|
||||
- 成功数量。
|
||||
- 失败数量。
|
||||
- 跳过原因。
|
||||
3. 活动记录支持从文件详情进入:
|
||||
- 展示该文件最近操作。
|
||||
- 展示操作者、动作和时间。
|
||||
4. 危险操作确认文案包含文件名或数量,而不是只问“是否删除”。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
前端:
|
||||
|
||||
- `AdminBatchActionBar.vue`
|
||||
- `FileManageView.vue`
|
||||
- `useAdminFiles.ts`
|
||||
- `DashboardView.vue`
|
||||
|
||||
后端:
|
||||
|
||||
- `apps/admin/views.py`
|
||||
- `apps/admin/services.py`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 批量删除和批量更新前有明确影响摘要。
|
||||
2. 批量操作结果能展示部分失败,不只显示统一成功或失败。
|
||||
3. 操作记录能按文件或关键词过滤。
|
||||
4. 后端测试覆盖活动记录过滤和批量操作结果结构。
|
||||
|
||||
## P1:下载与预览体验统一
|
||||
|
||||
目标:用户在公开页和管理页面对“文本、图片、视频、音频、PDF、未知文件”时,操作路径一致。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 抽统一文件能力判断工具:
|
||||
- 是否可文本预览。
|
||||
- 是否可媒体预览。
|
||||
- 是否建议下载。
|
||||
- 是否可复制内容。
|
||||
2. 统一公开取件和管理页的预览入口文案。
|
||||
3. PDF、图片、音视频预览失败时提供下载兜底。
|
||||
4. 文本预览支持复制、下载为 `.txt`、查看原始内容。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `MediaPreviewModal.vue`
|
||||
- `ContentPreviewModal.vue`
|
||||
- `FileDetailModal.vue`
|
||||
- `FileManageView.vue`
|
||||
- `content-preview.ts`
|
||||
- `download-action.ts`
|
||||
- `file-type.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 同一文件类型在公开页和管理页展示一致。
|
||||
2. 预览失败时始终能回退到下载。
|
||||
3. 文本内容复制和导出行为一致。
|
||||
4. 文件类型判断工具具备单元测试。
|
||||
|
||||
## P1:上传前文件清单与限制提示
|
||||
|
||||
目标:多文件或大文件上传前,让用户提前知道会发生什么,减少上传中途失败。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- 多文件上传会先打包为 zip,但用户只看到“正在打包文件”。
|
||||
- 文件清单、总大小、超限原因和打包后行为没有在提交前集中展示。
|
||||
- `FileUploadArea.vue` 已支持更多上传状态,但页面当前只传入 `uploading` 和 `idle`。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 多文件选择后展示文件清单:
|
||||
- 文件数量。
|
||||
- 总大小。
|
||||
- 最大文件。
|
||||
- 不允许类型或超限文件。
|
||||
2. 明确提示多文件将被打包为 zip。
|
||||
3. 打包阶段展示独立状态,避免和上传阶段混淆。
|
||||
4. 提交前对所有文件逐项校验,并返回具体失败原因。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `FileUploadArea.vue`
|
||||
- `SendFileView.vue`
|
||||
- `useSendFlow.ts`
|
||||
- `useSendSubmit.ts`
|
||||
- `ExpirationSelector.vue`
|
||||
- `file-type.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 多文件选择后可看到数量、总大小和打包提示。
|
||||
2. 超限文件能逐项展示原因。
|
||||
3. 打包中、上传中、确认中三个阶段状态不同。
|
||||
4. 文件清单在取消或重新选择后正确重置。
|
||||
|
||||
## P1:服务端状态字段与可操作能力
|
||||
|
||||
目标:为前端展示更清楚的状态和主操作提供稳定数据,减少前端重复推断。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 分享记录增加明确状态字段:
|
||||
- `active`
|
||||
- `expired`
|
||||
- `download_limit_exhausted`
|
||||
- `storage_missing`
|
||||
2. 公开元数据接口补充可操作能力:
|
||||
- `canPreview`
|
||||
- `canDownload`
|
||||
- `canCopy`
|
||||
- `primaryAction`
|
||||
3. 管理列表支持快捷筛选参数:
|
||||
- `expiringSoon`
|
||||
- `neverUsed`
|
||||
- `exhausted`
|
||||
- `storageIssue`
|
||||
4. 后端响应保留必要的 snake_case 和 camelCase 兼容。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `apps/base/views.py`
|
||||
- `apps/base/schemas.py`
|
||||
- `apps/admin/views.py`
|
||||
- `apps/admin/services.py`
|
||||
- `src/types/file.ts`
|
||||
- `src/services/file.ts`
|
||||
- `tests/`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 元数据接口能直接告诉前端主操作是什么。
|
||||
2. 管理文件列表能按快捷状态筛选。
|
||||
3. 状态字段有后端测试覆盖。
|
||||
4. 前端不再依赖 `filename === 'Text'` 这类脆弱判断。
|
||||
|
||||
## P1:审计日志表化
|
||||
|
||||
目标:让上传、下载、删除、配置变更等关键动作可追踪、可过滤、可定位。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- 管理活动当前主要保存在 `KeyValue` 中,容量和查询能力有限。
|
||||
- 活动记录缺少 IP、User-Agent、请求 ID、结果状态等排障信息。
|
||||
- 批量操作失败时,缺少逐项结果追踪。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 新增审计日志模型,记录:
|
||||
- 动作类型。
|
||||
- 操作者。
|
||||
- IP。
|
||||
- User-Agent。
|
||||
- 请求 ID。
|
||||
- 目标类型和目标 ID。
|
||||
- 执行结果。
|
||||
- 元数据。
|
||||
- 创建时间。
|
||||
2. `/admin/activities` 支持分页和筛选:
|
||||
- 动作。
|
||||
- 对象类型。
|
||||
- 关键词。
|
||||
- 时间范围。
|
||||
- 结果状态。
|
||||
3. 文件详情中展示该文件最近操作。
|
||||
4. 配置变更记录变更摘要,不记录密钥明文。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `apps/admin/services.py`
|
||||
- `apps/admin/views.py`
|
||||
- `apps/base/models.py`
|
||||
- `tests/`
|
||||
|
||||
### 数据模型影响
|
||||
|
||||
建议新增:
|
||||
|
||||
- `AuditLog`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 删除、批量更新、配置变更会写入审计日志。
|
||||
2. 审计列表支持分页和筛选。
|
||||
3. 日志不泄露 Token、密码、密钥。
|
||||
4. 后端测试覆盖写入、过滤和敏感字段脱敏。
|
||||
|
||||
## P1:管理查询性能优化
|
||||
|
||||
目标:让后台在千级、万级文件记录下仍能稳定分页、筛选和统计。
|
||||
|
||||
### 现状问题
|
||||
|
||||
- 文件列表和仪表盘部分统计、过滤、排序在 Python 内存中完成。
|
||||
- 数据量增加后,后台打开、筛选和统计会逐渐变慢。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 文件列表筛选和排序尽量下推到数据库。
|
||||
2. 仪表盘统计改为聚合查询。
|
||||
3. 为高频字段补索引:
|
||||
- `created_at`
|
||||
- `expired_at`
|
||||
- `suffix`
|
||||
- `is_chunked`
|
||||
- `used_count`
|
||||
- `file_hash`
|
||||
4. 大量记录下避免一次性加载所有文件再过滤。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `apps/admin/views.py`
|
||||
- `apps/admin/services.py`
|
||||
- `apps/base/models.py`
|
||||
- `tests/`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 千级和万级记录下分页耗时稳定。
|
||||
2. 仪表盘统计结果与现有结果一致。
|
||||
3. 筛选、排序、分页返回结构保持兼容。
|
||||
4. 后端测试覆盖主要过滤组合。
|
||||
|
||||
## P2:取件与发送记录体验增强
|
||||
|
||||
目标:让浏览器本地记录更适合长期使用。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 记录支持搜索:
|
||||
- 取件码。
|
||||
- 文件名。
|
||||
- 类型。
|
||||
2. 记录支持分组:
|
||||
- 今天。
|
||||
- 最近 7 天。
|
||||
- 更早。
|
||||
3. 记录详情展示来源:
|
||||
- 手动输入。
|
||||
- 链接打开。
|
||||
- 历史记录。
|
||||
4. 支持清空记录前二次确认,并说明只清理本地记录,不删除服务器文件。
|
||||
5. 支持导出发送记录为 JSON。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
- `SideDrawer.vue`
|
||||
- `SentRecordList.vue`
|
||||
- `FileRecordList.vue`
|
||||
- `fileData` store
|
||||
- `send-record.ts`
|
||||
- `download-action.ts`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 本地记录超过 20 条时仍易于查找。
|
||||
2. 清空记录不会误导用户以为删除了服务器文件。
|
||||
3. 导出的记录可重新导入或至少可人工读取。
|
||||
|
||||
## P2:系统设置体验增强
|
||||
|
||||
目标:在强校验之外,给管理员提供配置自检、连接测试和修复建议。
|
||||
|
||||
### 建议实现
|
||||
|
||||
1. 设置页增加配置自检:
|
||||
- 当前存储后端是否可用。
|
||||
- 上传大小限制是否合理。
|
||||
- 允许文件类型是否能被正确解析。
|
||||
- 管理地址是否公开。
|
||||
2. 存储配置增加测试连接按钮:
|
||||
- S3。
|
||||
- WebDAV。
|
||||
- OpenDAL。
|
||||
- OneDrive。
|
||||
3. 自检结果返回修复建议:
|
||||
- 缺少必填项。
|
||||
- 存储连接失败。
|
||||
- 上传限制过宽。
|
||||
- 管理地址暴露。
|
||||
4. 支持导出当前非敏感配置快照,便于排障。
|
||||
|
||||
### 涉及模块
|
||||
|
||||
前端:
|
||||
|
||||
- `SystemSettingsView.vue`
|
||||
- `config-storage.ts`
|
||||
- `config` types
|
||||
|
||||
后端:
|
||||
|
||||
- `apps/admin/views.py`
|
||||
- `apps/admin/services.py`
|
||||
- `core/storage.py`
|
||||
- `core/settings.py`
|
||||
|
||||
### 验收标准
|
||||
|
||||
1. 保存设置前能看到变更摘要。
|
||||
2. 错误配置不会只在上传时暴露。
|
||||
3. 存储连接失败能返回可理解原因。
|
||||
4. 配置自检接口有后端测试覆盖。
|
||||
|
||||
## 并行开发拆分
|
||||
|
||||
第一轮建议拆成四个互不冲突任务,先处理会影响安全边界和关键体验的事项:
|
||||
|
||||
1. 后端 A:取件扣次数与下载票据一致性。
|
||||
2. 前端 B:取件前确认卡片和查询参数自动预检查。
|
||||
3. 后端 C:统一错误响应和请求追踪。
|
||||
4. 前端 D:发送成功结果面板和复制反馈。
|
||||
|
||||
第二轮在第一轮稳定后推进:
|
||||
|
||||
1. 后端 E:预签名直传确认加固和上传会话状态原因。
|
||||
2. 前端 F:上传取消、失败重试和离页确认。
|
||||
3. 前端 G:管理高风险操作确认弹窗。
|
||||
4. 后端 H:配置保存强校验。
|
||||
|
||||
第三轮推进管理效率和长期维护:
|
||||
|
||||
1. 前端 I:管理文件筛选区、详情侧栏和行操作收敛。
|
||||
2. 后端 J:服务端状态字段、快捷筛选和管理查询性能优化。
|
||||
3. 后端 K:审计日志表化。
|
||||
4. 前端 L:记录搜索、分组、导出和国际化补齐。
|
||||
|
||||
## 推荐执行顺序
|
||||
|
||||
1. 先做 P0 取件票据和扣次数一致性,修正服务端安全边界。
|
||||
2. 接着做 P0 取件前确认卡片,避免用户误消耗次数。
|
||||
3. 同步推进统一错误响应,让前端能展示稳定错误文案。
|
||||
4. 再做发送成功结果区,提升公开用户最常见路径。
|
||||
5. 然后做上传取消/重试和预签名直传确认加固。
|
||||
6. 管理页按强确认、筛选拆分、详情侧栏的顺序渐进推进。
|
||||
|
||||
## 质量门禁
|
||||
|
||||
前端每轮合并前执行:
|
||||
|
||||
```bash
|
||||
cd FileCodeBoxFronted
|
||||
pnpm test
|
||||
pnpm check:architecture
|
||||
pnpm type-check
|
||||
pnpm lint:check
|
||||
pnpm build
|
||||
```
|
||||
|
||||
后端每轮合并前执行:
|
||||
|
||||
```bash
|
||||
cd FileCodeBox
|
||||
pytest
|
||||
```
|
||||
|
||||
涉及上传、删除、配置、权限和批量操作时,必须补充异常路径测试。
|
||||
|
||||
## 风险与注意事项
|
||||
|
||||
1. 取件预检查不能调用会消耗次数的接口。
|
||||
2. 上传取消需要确认不同上传策略的清理路径一致。
|
||||
3. 管理页组件拆分必须保持现有批量操作行为不变。
|
||||
4. 配置自检不能泄露密钥、Token 或内部路径。
|
||||
5. 本地记录增强只影响浏览器存储,不应让用户误解为服务端记录。
|
||||
|
||||
## 下一步建议
|
||||
|
||||
下一轮优先实现:
|
||||
|
||||
1. `P0:取件扣次数与下载票据一致性`
|
||||
2. `P0:公开取件体验升级`
|
||||
3. `P0:统一错误响应与请求追踪`
|
||||
4. `P0:发送结果页增强`
|
||||
|
||||
这四项组合能同时修正服务端边界和公开用户体验,为后续上传恢复、管理工作台优化打基础。
|
||||
@@ -1,15 +0,0 @@
|
||||
/* eslint-env node */
|
||||
require('@rushstack/eslint-patch/modern-module-resolution')
|
||||
|
||||
module.exports = {
|
||||
root: true,
|
||||
'extends': [
|
||||
'plugin:vue/vue3-essential',
|
||||
'eslint:recommended',
|
||||
'@vue/eslint-config-typescript',
|
||||
'@vue/eslint-config-prettier/skip-formatting'
|
||||
],
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest'
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
.vite/
|
||||
node_modules
|
||||
.DS_Store
|
||||
dist-ssr
|
||||
coverage
|
||||
*.local
|
||||
.git
|
||||
/cypress/videos/
|
||||
/cypress/screenshots/
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||