Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
31027e6eea | ||
|
|
18d344cc9b | ||
|
|
8215f91edf | ||
|
|
775f3fc4ce | ||
|
|
13f572a86a | ||
|
|
800bac0128 | ||
|
|
8972344235 | ||
|
|
6e7580b8dc | ||
|
|
c7b5eabe7c | ||
|
|
bb40f40a18 | ||
|
|
a49727b63d | ||
|
|
0038636a2a | ||
|
|
3c93718d4b | ||
|
|
baecebd81e | ||
|
|
bb95017aa3 | ||
|
|
61d72ab6cc | ||
|
|
ec424dd909 | ||
|
|
5121db6edc | ||
|
|
c5d525df08 | ||
|
|
61724cbf32 | ||
|
|
6587ec86be | ||
|
|
832266101e | ||
|
|
ad3d319362 | ||
|
|
892fb24ffc | ||
|
|
3396644da3 | ||
|
|
81d33b70de | ||
|
|
a75936d85a | ||
|
|
357ab2fb6f | ||
|
|
443cfe7472 | ||
|
|
bde1fee17e | ||
|
|
964cba3636 | ||
|
|
4904695955 | ||
|
|
4cab625d5a | ||
|
|
a8c4072497 | ||
|
|
2bc278a58e | ||
|
|
3f58e42be1 | ||
|
|
625e50ca95 | ||
|
|
177a212c0f | ||
|
|
d701c6e00e | ||
|
|
6c76aabe1e | ||
|
|
e08555a6e8 | ||
|
|
5537f56b88 | ||
|
|
00f1f1d8da | ||
|
|
5a7195c5c7 | ||
|
|
da1dd06655 | ||
|
|
d510aa7f57 | ||
|
|
cebac32145 | ||
|
|
f76d1e9841 | ||
|
|
287b647da1 | ||
|
|
fbcd4a5b2b | ||
|
|
fc0cbeb4f0 | ||
|
|
24bf6e1a81 | ||
|
|
0ee2f046dd | ||
|
|
eda0a3127a | ||
|
|
c11059b851 | ||
|
|
ae7702603a | ||
|
|
a41693f90d | ||
|
|
59ed733f3a | ||
|
|
cf6d364c2b | ||
|
|
00f3abd3b2 | ||
|
|
c676458370 | ||
|
|
f2277e1649 | ||
|
|
f20a7a5704 | ||
|
|
fe1a7727f7 | ||
|
|
a30e52ba9d | ||
|
|
ab5178a73a | ||
|
|
9219b74333 | ||
|
|
46883c90ff | ||
|
|
ee8f9082ab | ||
|
|
818dd47b2a | ||
|
|
93ff291366 | ||
|
|
2c51384c80 | ||
|
|
8d7d856c62 | ||
|
|
36300ef54e | ||
|
|
5c72562af7 |
No files matched your search
@@ -0,0 +1,18 @@
|
||||
version: 2
|
||||
updates:
|
||||
# Runtime deps. requirements.txt pins direct deps; requirements.lock.txt is
|
||||
# the hashed, transitive-resolved lockfile. Dependabot raises version PRs
|
||||
# against requirements.txt; regenerate the lockfile in the same PR
|
||||
# (uv pip compile requirements.txt --generate-hashes --universal -o requirements.lock.txt).
|
||||
- package-ecosystem: "pip"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
- package-ecosystem: "docker"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
|
Before Width: | Height: | Size: 571 KiB |
|
Before Width: | Height: | Size: 557 KiB |
|
Before Width: | Height: | Size: 205 KiB |
|
Before Width: | Height: | Size: 679 KiB |
|
Before Width: | Height: | Size: 684 KiB |
|
Before Width: | Height: | Size: 411 KiB |
|
Before Width: | Height: | Size: 431 KiB |
|
Before Width: | Height: | Size: 579 KiB |
|
Before Width: | Height: | Size: 201 KiB |
|
Before Width: | Height: | Size: 254 KiB |
|
Before Width: | Height: | Size: 200 KiB |
|
Before Width: | Height: | Size: 514 KiB |
|
Before Width: | Height: | Size: 674 KiB |
|
Before Width: | Height: | Size: 678 KiB |
|
Before Width: | Height: | Size: 219 KiB |
|
After Width: | Height: | Size: 69 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 84 KiB |
|
After Width: | Height: | Size: 76 KiB |
|
After Width: | Height: | Size: 133 KiB |
|
After Width: | Height: | Size: 130 KiB |
@@ -0,0 +1,134 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="420 360 1208 1208">
|
||||
<defs>
|
||||
<linearGradient id="blue" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#75A7FF"/>
|
||||
<stop offset="0.52" stop-color="#4E86F7"/>
|
||||
<stop offset="1" stop-color="#3769D8"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="blueSoft" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#EDF4FF"/>
|
||||
<stop offset="1" stop-color="#C9DCFF"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="ear" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#F8FBFF"/>
|
||||
<stop offset="1" stop-color="#DDE9FF"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="earInner" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#FFD8A8"/>
|
||||
<stop offset="1" stop-color="#F3A76E"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="tail" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#6EA2FF"/>
|
||||
<stop offset="1" stop-color="#315FC8"/>
|
||||
</linearGradient>
|
||||
<filter id="softShadow" x="-30%" y="-30%" width="160%" height="180%">
|
||||
<feDropShadow dx="0" dy="24" stdDeviation="26" flood-color="#1D376C" flood-opacity="0.18"/>
|
||||
</filter>
|
||||
<filter id="tinyShadow" x="-50%" y="-50%" width="200%" height="200%">
|
||||
<feDropShadow dx="0" dy="10" stdDeviation="10" flood-color="#243E72" flood-opacity="0.18"/>
|
||||
</filter>
|
||||
</defs>
|
||||
|
||||
<!-- 透明底:已去除外围白底 / 圆角框 / 光晕 -->
|
||||
|
||||
<!-- Floating audio particles -->
|
||||
<g fill="#6A9BFA" opacity="0.9">
|
||||
<circle cx="529" cy="777" r="20"/>
|
||||
<circle cx="1561" cy="728" r="16"/>
|
||||
<circle cx="1516" cy="1302" r="14"/>
|
||||
</g>
|
||||
<g fill="none" stroke="#8EB4FF" stroke-width="20" stroke-linecap="round" opacity="0.72">
|
||||
<path d="M440 942c-36 36-36 94 0 130"/>
|
||||
<path d="M1608 940c36 36 36 94 0 130"/>
|
||||
</g>
|
||||
|
||||
<!-- Tail: a listening loop that wraps the box -->
|
||||
<path d="M1351 1309c176 27 249 166 165 287-65 93-226 95-337 12"
|
||||
fill="none" stroke="url(#tail)" stroke-width="114" stroke-linecap="round"
|
||||
filter="url(#softShadow)"/>
|
||||
<path d="M1418 1460c57 29 71 80 35 116-38 38-100 25-136-8"
|
||||
fill="none" stroke="#DDE9FF" stroke-width="54" stroke-linecap="round"/>
|
||||
|
||||
<!-- Headphones behind the mascot -->
|
||||
<path d="M702 1048c0-318 145-507 322-507s322 189 322 507"
|
||||
fill="none" stroke="#18264A" stroke-width="86" stroke-linecap="round"
|
||||
filter="url(#tinyShadow)"/>
|
||||
<path d="M706 834c41-189 160-293 318-293 157 0 278 104 318 293"
|
||||
fill="none" stroke="#4F86F7" stroke-width="34" stroke-linecap="round"/>
|
||||
<rect x="625" y="972" width="160" height="300" rx="76" fill="#18264A"/>
|
||||
<rect x="1263" y="972" width="160" height="300" rx="76" fill="#18264A"/>
|
||||
<rect x="655" y="1010" width="98" height="225" rx="49" fill="url(#blue)"/>
|
||||
<rect x="1295" y="1010" width="98" height="225" rx="49" fill="url(#blue)"/>
|
||||
|
||||
<!-- Open audio box -->
|
||||
<g filter="url(#softShadow)">
|
||||
<path d="M594 1191c0-49 40-89 89-89h682c49 0 89 40 89 89v331c0 77-62 139-139 139H733c-77 0-139-62-139-139z"
|
||||
fill="url(#blue)"/>
|
||||
<ellipse cx="1024" cy="1122" rx="430" ry="126" fill="#24345E"/>
|
||||
<ellipse cx="1024" cy="1118" rx="365" ry="89" fill="#111B37"/>
|
||||
<path d="M594 1216c189 62 671 62 860 0v311c0 74-60 134-134 134H728c-74 0-134-60-134-134z"
|
||||
fill="url(#blue)"/>
|
||||
<path d="M633 1287c181 50 601 55 782 4" fill="none" stroke="#9BC0FF" stroke-width="18" opacity="0.54"/>
|
||||
</g>
|
||||
|
||||
<!-- Fox ears -->
|
||||
<g filter="url(#softShadow)">
|
||||
<path d="M719 854C664 713 683 520 751 397c26-47 91-42 115 5l170 331z"
|
||||
fill="url(#ear)" stroke="#20335F" stroke-width="24" stroke-linejoin="round"/>
|
||||
<path d="M1329 854c55-141 36-334-32-457-26-47-91-42-115 5l-170 331z"
|
||||
fill="url(#ear)" stroke="#20335F" stroke-width="24" stroke-linejoin="round"/>
|
||||
<path d="M758 726c-25-93-16-200 18-271 12-24 44-20 56 4l111 235z"
|
||||
fill="url(#earInner)"/>
|
||||
<path d="M1290 726c25-93 16-200-18-271-12-24-44-20-56 4l-111 235z"
|
||||
fill="url(#earInner)"/>
|
||||
</g>
|
||||
|
||||
<!-- Fox head -->
|
||||
<g filter="url(#softShadow)">
|
||||
<path d="M741 788c52-125 160-205 283-205s231 80 283 205c38 92 48 232 3 338-45 105-154 170-286 170s-241-65-286-170c-45-106-35-246 3-338z"
|
||||
fill="#F9FBFF" stroke="#20335F" stroke-width="26"/>
|
||||
<path d="M824 1068c52-35 119-51 200-51s148 16 200 51c-20 110-91 179-200 179s-180-69-200-179z"
|
||||
fill="#E8F0FF"/>
|
||||
<path d="M780 856c54-30 102-37 156-16" fill="none" stroke="#D1E0FF" stroke-width="26" stroke-linecap="round"/>
|
||||
<path d="M1268 856c-54-30-102-37-156-16" fill="none" stroke="#D1E0FF" stroke-width="26" stroke-linecap="round"/>
|
||||
</g>
|
||||
|
||||
<!-- Face -->
|
||||
<g fill="none" stroke="#1E2E56" stroke-width="26" stroke-linecap="round">
|
||||
<path d="M862 946c26 27 60 27 86 0"/>
|
||||
<path d="M1100 946c26 27 60 27 86 0"/>
|
||||
</g>
|
||||
<path d="M972 1027c0-30 24-54 54-54s54 24 54 54c0 22-14 39-30 51-15 11-33 11-48 0-16-12-30-29-30-51z"
|
||||
fill="#192544"/>
|
||||
<circle cx="1045" cy="1005" r="10" fill="#FFFFFF" opacity="0.9"/>
|
||||
<path d="M1026 1079c-2 46-30 73-72 77" fill="none" stroke="#1E2E56" stroke-width="20" stroke-linecap="round"/>
|
||||
<path d="M1026 1079c2 46 30 73 72 77" fill="none" stroke="#1E2E56" stroke-width="20" stroke-linecap="round"/>
|
||||
<circle cx="824" cy="1041" r="34" fill="#F4B18B" opacity="0.62"/>
|
||||
<circle cx="1224" cy="1041" r="34" fill="#F4B18B" opacity="0.62"/>
|
||||
|
||||
<!-- Paws resting on the box -->
|
||||
<g filter="url(#tinyShadow)">
|
||||
<ellipse cx="790" cy="1190" rx="116" ry="78" fill="#F9FBFF" stroke="#20335F" stroke-width="22"/>
|
||||
<ellipse cx="1258" cy="1190" rx="116" ry="78" fill="#F9FBFF" stroke="#20335F" stroke-width="22"/>
|
||||
<path d="M756 1189c18 22 46 31 72 20M1224 1189c18 22 46 31 72 20"
|
||||
fill="none" stroke="#CADBFA" stroke-width="15" stroke-linecap="round"/>
|
||||
</g>
|
||||
|
||||
<!-- Audio waveform badge -->
|
||||
<g transform="translate(1024 1442)" filter="url(#tinyShadow)">
|
||||
<circle cx="0" cy="0" r="116" fill="#FFFFFF" opacity="0.96"/>
|
||||
<circle cx="0" cy="0" r="98" fill="#EAF2FF"/>
|
||||
<g stroke="#4D83F2" stroke-width="24" stroke-linecap="round">
|
||||
<line x1="-50" y1="-18" x2="-50" y2="18"/>
|
||||
<line x1="-17" y1="-49" x2="-17" y2="49"/>
|
||||
<line x1="17" y1="-70" x2="17" y2="70"/>
|
||||
<line x1="50" y1="-35" x2="50" y2="35"/>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<!-- Tiny AI spark -->
|
||||
<g transform="translate(1437 520)" fill="#5E91F6">
|
||||
<path d="M0-66c12 42 24 54 66 66-42 12-54 24-66 66-12-42-24-54-66-66 42-12 54-24 66-66z"/>
|
||||
<circle cx="-91" cy="91" r="15" opacity="0.55"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 6.4 KiB |
|
After Width: | Height: | Size: 92 KiB |
|
After Width: | Height: | Size: 94 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 68 KiB |
@@ -0,0 +1,63 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- dev
|
||||
pull_request:
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Lint and test
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
# The hashed lockfile is the deploy artifact; install from it with
|
||||
# --require-hashes so CI fails on lockfile drift, exactly like the
|
||||
# Docker build does.
|
||||
pip install --require-hashes -r requirements.lock.txt
|
||||
pip install pytest pytest-asyncio httpx
|
||||
|
||||
- name: Ruff
|
||||
run: pipx run ruff==0.16.6 check .
|
||||
|
||||
- name: Verify lockfile matches requirements.txt
|
||||
# Dependabot bumps requirements.txt but cannot regenerate the hashed
|
||||
# lockfile; without this check a stale lockfile would silently keep
|
||||
# the Docker build on old versions.
|
||||
run: |
|
||||
python - <<'PY'
|
||||
import re, sys
|
||||
pins = dict(re.findall(r'^([\w-]+)==([\w.]+)$', open('requirements.txt').read(), re.M))
|
||||
lock = open('requirements.lock.txt').read()
|
||||
stale = []
|
||||
for name, ver in pins.items():
|
||||
m = re.search(rf'(?mi)^{re.escape(name)}==([\w.]+)\b', lock)
|
||||
if m is None or m.group(1) != ver:
|
||||
stale.append((name, ver, m.group(1) if m else 'ABSENT'))
|
||||
for name, req_ver, lock_ver in stale:
|
||||
print(f'STALE LOCKFILE: {name} requirements.txt={req_ver} lock={lock_ver}')
|
||||
sys.exit(1 if stale else 0)
|
||||
PY
|
||||
|
||||
- name: Run tests
|
||||
run: pytest -q
|
||||
@@ -2,6 +2,11 @@ name: Build and push Docker image
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: Optional release tag created by Release Please
|
||||
required: false
|
||||
type: string
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
@@ -20,6 +25,7 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ inputs.release_tag || github.ref }}
|
||||
submodules: true
|
||||
|
||||
- name: Extract metadata
|
||||
@@ -27,14 +33,63 @@ jobs:
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY_IMAGE }}
|
||||
flavor: |
|
||||
latest=false
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=ref,event=pr
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=ref,event=branch,enable=${{ inputs.release_tag == '' }}
|
||||
type=ref,event=pr,enable=${{ inputs.release_tag == '' }}
|
||||
type=semver,pattern={{version}},enable=${{ inputs.release_tag == '' }}
|
||||
type=semver,pattern={{major}}.{{minor}},enable=${{ inputs.release_tag == '' }}
|
||||
type=semver,value=${{ inputs.release_tag }},pattern={{version}},enable=${{ inputs.release_tag != '' }}
|
||||
type=semver,value=${{ inputs.release_tag }},pattern={{major}}.{{minor}},enable=${{ inputs.release_tag != '' }}
|
||||
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}}
|
||||
type=sha,prefix=edge-,enable=${{ github.ref == 'refs/heads/master' && inputs.release_tag == '' }}
|
||||
type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/v') || inputs.release_tag != '' }}
|
||||
|
||||
- name: Verify release version
|
||||
if: ${{ startsWith(github.ref, 'refs/tags/v') || inputs.release_tag != '' }}
|
||||
shell: bash
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.release_tag || github.ref_name }}
|
||||
run: |
|
||||
source_version="$(tr -d '[:space:]' < VERSION)"
|
||||
tag_version="${RELEASE_TAG#v}"
|
||||
test "$source_version" = "$tag_version" || {
|
||||
echo "Version mismatch: VERSION=$source_version, tag=$tag_version" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
- name: Resolve source revision
|
||||
id: source-revision
|
||||
shell: bash
|
||||
run: |
|
||||
revision="$(git rev-parse HEAD)"
|
||||
echo "value=$revision" >> "$GITHUB_OUTPUT"
|
||||
echo "short=${revision::12}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Resolve latest frontend revisions
|
||||
id: frontend-revisions
|
||||
shell: bash
|
||||
run: |
|
||||
frontend_2024_ref="$(git ls-remote https://github.com/vastsa/FileCodeBoxFronted.git HEAD | cut -f1)"
|
||||
frontend_2023_ref="$(git ls-remote https://github.com/vastsa/FileCodeBoxFronted2023.git HEAD | cut -f1)"
|
||||
test -n "$frontend_2024_ref"
|
||||
test -n "$frontend_2023_ref"
|
||||
echo "frontend_2024=$frontend_2024_ref" >> "$GITHUB_OUTPUT"
|
||||
echo "frontend_2023=$frontend_2023_ref" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Resolve application version
|
||||
id: app-version
|
||||
shell: bash
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
run: |
|
||||
source_version="$(tr -d '[:space:]' < VERSION)"
|
||||
if [[ "$GITHUB_REF" == refs/tags/v* || -n "$RELEASE_TAG" ]]; then
|
||||
echo "value=$source_version" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "value=${source_version}-dev+${{ steps.source-revision.outputs.short }}" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
@@ -60,6 +115,11 @@ jobs:
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
build-args: |
|
||||
APP_VERSION=${{ steps.app-version.outputs.value }}
|
||||
VCS_REF=${{ steps.source-revision.outputs.value }}
|
||||
FRONTEND_2024_REF=${{ steps.frontend-revisions.outputs.frontend_2024 }}
|
||||
FRONTEND_2023_REF=${{ steps.frontend-revisions.outputs.frontend_2023 }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
provenance: false
|
||||
@@ -43,7 +43,7 @@ jobs:
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: 'docs/pnpm-lock.yaml'
|
||||
- name: Setup Pages
|
||||
uses: actions/configure-pages@v4
|
||||
uses: actions/configure-pages@v6
|
||||
- name: Install dependencies
|
||||
working-directory: docs
|
||||
run: pnpm install
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
name: Create release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
actions: write
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release-please:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Create or update release
|
||||
id: release
|
||||
uses: googleapis/release-please-action@v4
|
||||
with:
|
||||
config-file: release-please-config.json
|
||||
manifest-file: .release-please-manifest.json
|
||||
|
||||
- name: Merge release pull request
|
||||
if: ${{ steps.release.outputs.prs_created == 'true' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
RELEASE_PR_JSON: ${{ steps.release.outputs.pr }}
|
||||
run: |
|
||||
RELEASE_PR="$(jq -r '.number' <<< "$RELEASE_PR_JSON")"
|
||||
for attempt in {1..120}; do
|
||||
if gh pr merge "$RELEASE_PR" --squash --delete-branch; then
|
||||
break
|
||||
fi
|
||||
if [[ "$attempt" -eq 120 ]]; then
|
||||
echo "Timed out waiting for release PR #$RELEASE_PR to merge" >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep 10
|
||||
done
|
||||
gh workflow run release.yml --ref master
|
||||
|
||||
- name: Publish release image
|
||||
if: ${{ steps.release.outputs.release_created == 'true' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
RELEASE_TAG: ${{ steps.release.outputs.tag_name }}
|
||||
run: gh workflow run docker-image.yml --ref master -f release_tag="$RELEASE_TAG"
|
||||
@@ -80,8 +80,8 @@ docs/_build/
|
||||
.pybuilder/
|
||||
target/
|
||||
*.db
|
||||
./filecodebox.db-shm
|
||||
./filecodebox.db-wal
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
@@ -147,19 +147,15 @@ cython_debug/
|
||||
# Project
|
||||
.vscode
|
||||
.DS_Store
|
||||
for_test.py
|
||||
.html
|
||||
/evaluate/temp.py
|
||||
/evaluation/back.json
|
||||
data/.env
|
||||
.backup/
|
||||
/cloc-1.64.exe
|
||||
|
||||
# Ignore node_modules
|
||||
node_modules/
|
||||
docs/.vitepress/cache/
|
||||
|
||||
AGENTS.md
|
||||
|
||||
dist/
|
||||
# Frontend themes (built from GitHub during Docker build)
|
||||
themes/
|
||||
themes/
|
||||
@@ -0,0 +1,8 @@
|
||||
# First-time setup: pre-commit install
|
||||
# Behind a proxy: HTTPS_PROXY=http://<proxy-host>:<port> pre-commit run --all-files
|
||||
repos:
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.16.6
|
||||
hooks:
|
||||
- id: ruff-check
|
||||
args: [--fix]
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
".": "2.6.0"
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
# 第一阶段:构建前端主题
|
||||
FROM node:20-alpine AS frontend-builder
|
||||
# 前端产物与 CPU 架构无关,使用原生构建平台避免在 QEMU 中运行 Node/pnpm。
|
||||
FROM --platform=$BUILDPLATFORM node:20-alpine AS frontend-builder
|
||||
|
||||
ARG FRONTEND_2024_REF=main
|
||||
ARG FRONTEND_2023_REF=main
|
||||
|
||||
RUN apk add --no-cache git python3 make g++
|
||||
|
||||
@@ -8,28 +12,43 @@ RUN corepack enable && \
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
# 克隆并构建 2024 主题
|
||||
RUN git clone --depth 1 https://github.com/vastsa/FileCodeBoxFronted.git /build/fronted-2024 && \
|
||||
# 克隆并构建固定版本的 2024 主题
|
||||
RUN git clone --filter=blob:none --no-checkout https://github.com/vastsa/FileCodeBoxFronted.git /build/fronted-2024 && \
|
||||
cd /build/fronted-2024 && \
|
||||
git fetch --depth 1 origin "${FRONTEND_2024_REF}" && \
|
||||
git checkout --detach FETCH_HEAD && \
|
||||
pnpm install --frozen-lockfile --prod=false && \
|
||||
pnpm run build
|
||||
VITE_GIT_COMMIT="$(git rev-parse HEAD)" pnpm run build
|
||||
|
||||
# 克隆并构建 2023 主题
|
||||
RUN git clone --depth 1 https://github.com/vastsa/FileCodeBoxFronted2023.git /build/fronted-2023 && \
|
||||
# 克隆并构建固定版本的 2023 主题
|
||||
RUN git clone --filter=blob:none --no-checkout https://github.com/vastsa/FileCodeBoxFronted2023.git /build/fronted-2023 && \
|
||||
cd /build/fronted-2023 && \
|
||||
git fetch --depth 1 origin "${FRONTEND_2023_REF}" && \
|
||||
git checkout --detach FETCH_HEAD && \
|
||||
npm install --legacy-peer-deps && \
|
||||
npm run build
|
||||
|
||||
# 第二阶段:构建最终镜像
|
||||
FROM python:3.12-slim-bookworm
|
||||
ARG APP_VERSION
|
||||
ARG VCS_REF=unknown
|
||||
ARG FRONTEND_2024_REF=main
|
||||
ARG FRONTEND_2023_REF=main
|
||||
LABEL author="Lan"
|
||||
LABEL email="xzu@live.com"
|
||||
LABEL org.opencontainers.image.version="${APP_VERSION}"
|
||||
LABEL org.opencontainers.image.revision="${VCS_REF}"
|
||||
LABEL org.opencontainers.image.filecodebox.frontend-2024-revision="${FRONTEND_2024_REF}"
|
||||
LABEL org.opencontainers.image.filecodebox.frontend-2023-revision="${FRONTEND_2023_REF}"
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# 复制项目文件(通过 .dockerignore 排除不必要的文件)
|
||||
COPY . .
|
||||
|
||||
# 分支镜像使用带提交号的开发版本;正式镜像使用 VERSION 中的版本。
|
||||
ENV APP_VERSION="${APP_VERSION}"
|
||||
|
||||
# 设置时区
|
||||
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
|
||||
echo 'Asia/Shanghai' > /etc/timezone
|
||||
@@ -38,16 +57,27 @@ RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
|
||||
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
|
||||
# 安装系统安全更新 + Python 依赖
|
||||
# 依赖从带哈希的锁定文件安装(--require-hashes),保证构建可复现、防供应链篡改。
|
||||
# 清理 apt 缓存,降低镜像噪音与扫描面
|
||||
RUN apt-get update \
|
||||
&& apt-get upgrade -y --no-install-recommends \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& pip install --no-cache-dir --require-hashes -r requirements.lock.txt \
|
||||
&& pip cache purge || true
|
||||
|
||||
# 环境变量配置
|
||||
ENV HOST="0.0.0.0" \
|
||||
PORT=12345 \
|
||||
WORKERS=1 \
|
||||
LOG_LEVEL="info"
|
||||
APP_ENV="production" \
|
||||
LOG_LEVEL="warning" \
|
||||
ACCESS_LOG="false" \
|
||||
FORWARDED_ALLOW_IPS=""
|
||||
|
||||
EXPOSE 12345
|
||||
|
||||
# 生产环境启动命令
|
||||
CMD ["sh", "-c", "exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" --proxy-headers --forwarded-allow-ips '*'"]
|
||||
# FORWARDED_ALLOW_IPS 默认为空:仅信任直连 IP,避免任意客户端伪造 X-Forwarded-*。
|
||||
# 若前面有反向代理,请显式设置为代理网段,例如 "10.0.0.0/8,172.16.0.0/12"。
|
||||
CMD ["sh", "-c", "access_log_arg=--no-access-log; if [ \"${APP_ENV:-development}\" != \"production\" ] || [ \"${ACCESS_LOG:-false}\" = \"true\" ]; then access_log_arg=--access-log; fi; exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" \"$access_log_arg\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-}\""]
|
||||
@@ -2,13 +2,18 @@
|
||||
# @Author : Lan
|
||||
# @File : depends.py
|
||||
# @Software: PyCharm
|
||||
from fastapi import Header, HTTPException, Depends
|
||||
from fastapi import Header, HTTPException
|
||||
from fastapi.requests import Request
|
||||
import base64
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
from core.settings import settings
|
||||
from core.settings import (
|
||||
ADMIN_SESSION_EXPIRE_DEFAULT,
|
||||
ADMIN_SESSION_EXPIRE_MAX,
|
||||
ADMIN_SESSION_EXPIRE_MIN,
|
||||
settings,
|
||||
)
|
||||
from apps.admin.services import FileService, ConfigService, LocalFileService
|
||||
|
||||
|
||||
@@ -19,21 +24,44 @@ def _get_jwt_secret() -> bytes:
|
||||
return secret.encode()
|
||||
|
||||
|
||||
def create_token(data: dict, expires_in: int = 3600 * 24 * 30) -> str:
|
||||
def get_admin_session_expire_seconds() -> int:
|
||||
try:
|
||||
expires_in = int(
|
||||
getattr(settings, "admin_session_expire", ADMIN_SESSION_EXPIRE_DEFAULT)
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
return ADMIN_SESSION_EXPIRE_DEFAULT
|
||||
if (
|
||||
not ADMIN_SESSION_EXPIRE_MIN <= expires_in <= ADMIN_SESSION_EXPIRE_MAX
|
||||
or expires_in % ADMIN_SESSION_EXPIRE_MIN != 0
|
||||
):
|
||||
return ADMIN_SESSION_EXPIRE_DEFAULT
|
||||
return expires_in
|
||||
|
||||
|
||||
def create_token(data: dict, expires_in: int | None = None) -> str:
|
||||
"""
|
||||
创建JWT token
|
||||
:param data: 数据负载
|
||||
:param expires_in: 过期时间(秒)
|
||||
"""
|
||||
header = base64.b64encode(
|
||||
json.dumps({"alg": "HS256", "typ": "JWT"}).encode()
|
||||
).decode()
|
||||
payload = base64.b64encode(
|
||||
json.dumps({**data, "exp": int(time.time()) + expires_in}).encode()
|
||||
).decode()
|
||||
token_lifetime = (
|
||||
get_admin_session_expire_seconds() if expires_in is None else expires_in
|
||||
)
|
||||
header = base64.urlsafe_b64encode(
|
||||
json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode()
|
||||
).decode().rstrip("=")
|
||||
payload = base64.urlsafe_b64encode(
|
||||
json.dumps(
|
||||
{**data, "exp": int(time.time()) + token_lifetime},
|
||||
separators=(",", ":"),
|
||||
).encode()
|
||||
).decode().rstrip("=")
|
||||
|
||||
signature = hmac.new(_get_jwt_secret(), f"{header}.{payload}".encode(), "sha256").digest()
|
||||
signature = base64.b64encode(signature).decode()
|
||||
signature = hmac.new(
|
||||
_get_jwt_secret(), f"{header}.{payload}".encode(), "sha256"
|
||||
).digest()
|
||||
signature = base64.urlsafe_b64encode(signature).decode().rstrip("=")
|
||||
|
||||
return f"{header}.{payload}.{signature}"
|
||||
|
||||
@@ -53,13 +81,20 @@ def verify_token(token: str) -> dict:
|
||||
f"{header_b64}.{payload_b64}".encode(),
|
||||
"sha256",
|
||||
).digest()
|
||||
expected_signature_b64 = base64.b64encode(expected_signature).decode()
|
||||
expected_signature_b64 = (
|
||||
base64.urlsafe_b64encode(expected_signature).decode().rstrip("=")
|
||||
)
|
||||
|
||||
if not hmac.compare_digest(signature_b64, expected_signature_b64):
|
||||
raise ValueError("无效的签名")
|
||||
|
||||
# 解码payload
|
||||
payload = json.loads(base64.b64decode(payload_b64))
|
||||
# 解码payload(兼容历史标准 base64 与 urlsafe base64)
|
||||
padded = payload_b64 + "=" * (-len(payload_b64) % 4)
|
||||
try:
|
||||
payload_bytes = base64.urlsafe_b64decode(padded)
|
||||
except Exception:
|
||||
payload_bytes = base64.b64decode(padded)
|
||||
payload = json.loads(payload_bytes)
|
||||
|
||||
# 检查是否过期
|
||||
if payload.get("exp", 0) < time.time():
|
||||
@@ -120,14 +155,14 @@ async def share_required_login(authorization: str = Header(default=None)):
|
||||
"""
|
||||
验证分享上传权限
|
||||
|
||||
当settings.openUpload为False时,要求用户必须登录并具有管理员权限
|
||||
当settings.openUpload为True时,允许游客上传
|
||||
当 settings.open_upload 为False时,要求用户必须登录并具有管理员权限
|
||||
当 settings.open_upload 为True时,允许游客上传
|
||||
|
||||
:param authorization: 认证头信息
|
||||
:param request: 请求对象
|
||||
:return: 验证结果
|
||||
"""
|
||||
if not settings.openUpload:
|
||||
if not settings.open_upload:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise HTTPException(
|
||||
status_code=403, detail="本站未开启游客上传,如需上传请先登录后台"
|
||||
|
||||
@@ -39,21 +39,18 @@ 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
|
||||
|
||||
|
||||
|
||||
@@ -31,9 +31,17 @@ from apps.admin.schemas import (
|
||||
)
|
||||
from core.response import APIResponse
|
||||
from apps.base.models import FileCodes, KeyValue
|
||||
from apps.admin.dependencies import create_token
|
||||
from tortoise.expressions import Q
|
||||
from tortoise.functions import Count, Sum
|
||||
from apps.admin.dependencies import (
|
||||
create_token,
|
||||
get_admin_session_expire_seconds,
|
||||
verify_token,
|
||||
)
|
||||
from core.logger import logger
|
||||
from core.settings import settings
|
||||
from core.utils import get_now, verify_password
|
||||
from core.utils import get_now, hash_password, password_needs_rehash, verify_password
|
||||
from apps.base.utils import ip_limit
|
||||
|
||||
admin_api = APIRouter(
|
||||
prefix="/admin", tags=["管理"], dependencies=[Depends(admin_required)]
|
||||
@@ -49,12 +57,38 @@ def _pick_query_text(*values: Optional[str]) -> Optional[str]:
|
||||
|
||||
|
||||
@admin_api.post("/login")
|
||||
async def login(data: LoginData):
|
||||
async def login(data: LoginData, ip: str = Depends(ip_limit["login"])):
|
||||
# 登录失败计入 IP 频率限制,超过 login_count/login_minute 后暂时锁定
|
||||
if not verify_password(data.password, settings.admin_token):
|
||||
ip_limit["login"].add_ip(ip)
|
||||
raise HTTPException(status_code=401, detail="密码错误")
|
||||
|
||||
token = create_token({"is_admin": True})
|
||||
return APIResponse(detail={"token": token, "token_type": "Bearer"})
|
||||
# 透明重哈希:存量 sha256/明文口令在登录成功(已证明持有口令)时升级为 scrypt
|
||||
if password_needs_rehash(settings.admin_token):
|
||||
try:
|
||||
record = await KeyValue.filter(key="settings").first()
|
||||
if record:
|
||||
stored = dict(record.value or {})
|
||||
stored["admin_token"] = hash_password(data.password)
|
||||
record.value = stored
|
||||
await record.save()
|
||||
settings.admin_token = stored["admin_token"]
|
||||
logger.info("管理员口令已升级为 scrypt 哈希")
|
||||
except Exception:
|
||||
logger.warning("口令哈希升级失败,保持旧格式", exc_info=True)
|
||||
|
||||
expires_in = get_admin_session_expire_seconds()
|
||||
token = create_token({"is_admin": True}, expires_in=expires_in)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"id": "admin",
|
||||
"username": "admin",
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": verify_token(token)["exp"],
|
||||
"expires_in": expires_in,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@admin_api.get("/verify")
|
||||
@@ -76,81 +110,99 @@ async def build_dashboard_recent_file(file_code: FileCodes) -> dict:
|
||||
"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,
|
||||
"expired_at": file_code.expired_at,
|
||||
"expired_count": file_code.expired_count,
|
||||
"used_count": file_code.used_count,
|
||||
"created_at": file_code.created_at,
|
||||
"is_expired": is_expired,
|
||||
}
|
||||
|
||||
|
||||
def _expired_predicate(now: datetime.datetime) -> Q:
|
||||
"""SQL version of FileCodes.is_expired:
|
||||
expired_at IS NOT NULL AND ((expired_count < 0 AND expired_at < now) OR expired_count = 0)
|
||||
"""
|
||||
return Q(expired_at__isnull=False) & (
|
||||
Q(expired_count__lt=0, expired_at__lt=now) | Q(expired_count=0)
|
||||
)
|
||||
|
||||
|
||||
async def _sum_size(queryset) -> int:
|
||||
rows = await queryset.annotate(total=Sum("size")).values("total")
|
||||
return rows[0]["total"] or 0
|
||||
|
||||
|
||||
@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])
|
||||
# 简单计数全部走 SQL 聚合,避免整表载入内存(D3)。
|
||||
# 健康摘要依赖逐行 rules engine(_build_file_status_insights),保留一次遍历。
|
||||
total_files = await FileCodes.all().count()
|
||||
expired_count = await FileCodes.filter(_expired_predicate(now)).count()
|
||||
all_size = await _sum_size(FileCodes.all())
|
||||
used_count = (
|
||||
await FileCodes.all().annotate(total=Sum("used_count")).values("total")
|
||||
)[0]["total"] or 0
|
||||
text_count = await FileCodes.filter(text__isnull=False).count()
|
||||
chunked_count = await FileCodes.filter(is_chunked=True).count()
|
||||
yesterday_count = await FileCodes.filter(
|
||||
created_at__gte=yesterday_start, created_at__lte=yesterday_end
|
||||
).count()
|
||||
yesterday_size = await _sum_size(
|
||||
FileCodes.filter(created_at__gte=yesterday_start, created_at__lte=yesterday_end)
|
||||
)
|
||||
today_count = await FileCodes.filter(created_at__gte=today_start).count()
|
||||
today_size = await _sum_size(FileCodes.filter(created_at__gte=today_start))
|
||||
|
||||
suffix_rows = (
|
||||
await FileCodes.filter(text__isnull=True)
|
||||
.annotate(count=Count("id"))
|
||||
.values("suffix", "count")
|
||||
)
|
||||
suffix_counter = Counter(
|
||||
"Text" if file_code.text is not None else (file_code.suffix or "file")
|
||||
for file_code in all_codes
|
||||
{((row["suffix"] or "file") or "file"): row["count"] for row in suffix_rows}
|
||||
)
|
||||
|
||||
recent_file_codes = await FileCodes.all().order_by("-created_at").limit(8)
|
||||
health_summary = await file_service.build_file_health_summary(
|
||||
await FileCodes.all(), now=now
|
||||
)
|
||||
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,
|
||||
"total_files": total_files,
|
||||
"storage_used": str(all_size),
|
||||
"sys_uptime": sys_start.value if sys_start else None,
|
||||
"yesterday_count": yesterday_count,
|
||||
"yesterday_size": str(yesterday_size),
|
||||
"today_count": today_count,
|
||||
"today_size": str(today_size),
|
||||
"active_count": total_files - expired_count,
|
||||
"expired_count": expired_count,
|
||||
"text_count": text_count,
|
||||
"file_count": total_files - text_count,
|
||||
"chunked_count": chunked_count,
|
||||
"used_count": used_count,
|
||||
"storage_backend": settings.file_storage,
|
||||
"upload_size_limit": settings.upload_size,
|
||||
"open_upload": settings.open_upload,
|
||||
"enable_chunk": settings.enable_chunk,
|
||||
"max_save_seconds": settings.max_save_seconds,
|
||||
**health_summary,
|
||||
"healthSummary": health_summary,
|
||||
"topSuffixes": [
|
||||
"health_summary": health_summary,
|
||||
"top_suffixes": [
|
||||
{"suffix": suffix, "count": count}
|
||||
for suffix, count in suffix_counter.most_common(8)
|
||||
],
|
||||
"recentFiles": [
|
||||
"recent_files": [
|
||||
await build_dashboard_recent_file(file_code)
|
||||
for file_code in recent_file_codes
|
||||
],
|
||||
"recentActivities": recent_activities["activities"],
|
||||
"recent_activities": recent_activities["activities"],
|
||||
}
|
||||
)
|
||||
@@ -218,7 +270,7 @@ async def batch_update_files(
|
||||
|
||||
update_data = {}
|
||||
fields_set = data.model_fields_set
|
||||
should_clear_expired_at = bool(data.clearExpiredAt or data.clear_expired_at)
|
||||
should_clear_expired_at = bool(data.clear_expired_at)
|
||||
|
||||
if should_clear_expired_at:
|
||||
update_data["expired_at"] = None
|
||||
@@ -260,9 +312,7 @@ 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
|
||||
download_limit = data.download_limit
|
||||
|
||||
detail = await file_service.apply_file_policy_action(
|
||||
file_id=data.id,
|
||||
@@ -295,9 +345,7 @@ async def apply_batch_file_policy_action(
|
||||
if not data.ids:
|
||||
raise HTTPException(status_code=400, detail="请选择要更新的文件")
|
||||
|
||||
download_limit = data.downloadLimit
|
||||
if download_limit is None:
|
||||
download_limit = data.download_limit
|
||||
download_limit = data.download_limit
|
||||
|
||||
result = await file_service.apply_files_policy_action(
|
||||
file_ids=data.ids,
|
||||
@@ -331,8 +379,8 @@ async def file_list(
|
||||
status: str = "",
|
||||
type: str = "",
|
||||
health: str = "",
|
||||
sortBy: str = "created_at",
|
||||
sortOrder: str = "desc",
|
||||
sort_by: str = "created_at",
|
||||
sort_order: str = "desc",
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
page = max(page, 1)
|
||||
@@ -344,8 +392,8 @@ async def file_list(
|
||||
status=status,
|
||||
file_type=type,
|
||||
health=health,
|
||||
sort_by=sortBy,
|
||||
sort_order=sortOrder,
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
)
|
||||
return APIResponse(
|
||||
detail={
|
||||
@@ -486,7 +534,7 @@ async def update_config(
|
||||
config_service: ConfigService = Depends(get_config_service),
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
data.pop("themesChoices", None)
|
||||
data.pop("themes_choices", None)
|
||||
await config_service.update_config(data)
|
||||
await file_service.record_admin_activity(
|
||||
action="config.update",
|
||||
@@ -510,10 +558,10 @@ async def file_download(
|
||||
@admin_api.get("/file/preview")
|
||||
async def file_preview(
|
||||
id: int,
|
||||
maxChars: int = 4000,
|
||||
max_chars: int = 4000,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
preview = await file_service.preview_file(id, maxChars)
|
||||
preview = await file_service.preview_file(id, max_chars)
|
||||
return APIResponse(detail=preview)
|
||||
|
||||
|
||||
@@ -555,8 +603,8 @@ async def share_local_file(
|
||||
target_name=item.filename,
|
||||
count=1,
|
||||
meta={
|
||||
"expireValue": item.expire_value,
|
||||
"expireStyle": item.expire_style,
|
||||
"expire_value": item.expire_value,
|
||||
"expire_style": item.expire_style,
|
||||
},
|
||||
)
|
||||
return APIResponse(detail=share_info)
|
||||
@@ -567,38 +615,12 @@ async def update_file(
|
||||
data: UpdateFileData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
file_code = await FileCodes.filter(id=data.id).first()
|
||||
if not file_code:
|
||||
raise HTTPException(status_code=404, detail="文件不存在")
|
||||
target_name = file_service._build_file_activity_name(file_code)
|
||||
update_data = {}
|
||||
|
||||
if data.code is not None and data.code != file_code.code:
|
||||
# 判断code是否存在
|
||||
if await FileCodes.filter(code=data.code).first():
|
||||
raise HTTPException(status_code=400, detail="code已存在")
|
||||
update_data["code"] = data.code
|
||||
if data.prefix is not None and data.prefix != file_code.prefix:
|
||||
update_data["prefix"] = data.prefix
|
||||
if data.suffix is not None and data.suffix != file_code.suffix:
|
||||
update_data["suffix"] = data.suffix
|
||||
if (
|
||||
data.expired_at is not None
|
||||
and data.expired_at != ""
|
||||
and data.expired_at != file_code.expired_at
|
||||
):
|
||||
update_data["expired_at"] = data.expired_at
|
||||
if data.expired_count is not None and data.expired_count != file_code.expired_count:
|
||||
update_data["expired_count"] = data.expired_count
|
||||
|
||||
await file_code.update_from_dict(update_data).save()
|
||||
if update_data:
|
||||
await file_service.record_admin_activity(
|
||||
action="file.update",
|
||||
target_type="file",
|
||||
target_id=data.id,
|
||||
target_name=target_name,
|
||||
count=1,
|
||||
meta={"fields": sorted(update_data.keys())},
|
||||
)
|
||||
await file_service.update_file(
|
||||
file_id=data.id,
|
||||
code=data.code,
|
||||
prefix=data.prefix,
|
||||
suffix=data.suffix,
|
||||
expired_at=data.expired_at,
|
||||
expired_count=data.expired_count,
|
||||
)
|
||||
return APIResponse(detail="更新成功")
|
||||
@@ -16,16 +16,18 @@ MIN_ADMIN_PASSWORD_LENGTH = 8
|
||||
SETUP_CONFIG_FIELDS = {
|
||||
"allowed_file_types",
|
||||
"code_generate_type",
|
||||
"enableChunk",
|
||||
"errorCount",
|
||||
"errorMinute",
|
||||
"expireStyle",
|
||||
"enable_chunk",
|
||||
"error_count",
|
||||
"error_minute",
|
||||
"login_count",
|
||||
"login_minute",
|
||||
"expire_style",
|
||||
"max_save_seconds",
|
||||
"name",
|
||||
"openUpload",
|
||||
"uploadCount",
|
||||
"uploadMinute",
|
||||
"uploadSize",
|
||||
"open_upload",
|
||||
"upload_count",
|
||||
"upload_minute",
|
||||
"upload_size",
|
||||
}
|
||||
|
||||
|
||||
@@ -58,21 +60,45 @@ async def ensure_security_settings() -> None:
|
||||
logger.info("已将管理员密码迁移为哈希存储")
|
||||
if security_config.jwt_secret_rotated:
|
||||
logger.info("已生成独立 JWT 签名密钥")
|
||||
await refresh_settings()
|
||||
await refresh_settings(force=True)
|
||||
|
||||
|
||||
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
|
||||
ip_limit["error"].minutes = settings.error_minute
|
||||
ip_limit["error"].count = settings.error_count
|
||||
ip_limit["metadata"].minutes = settings.error_minute
|
||||
ip_limit["metadata"].count = settings.error_count
|
||||
ip_limit["upload"].minutes = settings.upload_minute
|
||||
ip_limit["upload"].count = settings.upload_count
|
||||
ip_limit["login"].minutes = settings.login_minute
|
||||
ip_limit["login"].count = settings.login_count
|
||||
|
||||
|
||||
async def refresh_settings() -> None:
|
||||
"""从数据库读取最新配置并应用到运行时。"""
|
||||
# Per-process config cache: the middleware refreshes settings on every request,
|
||||
# which otherwise means one DB read per request. Writes call refresh_settings(force=True)
|
||||
# so same-process visibility is immediate; other processes converge within the TTL
|
||||
# (documented deployment is a single worker).
|
||||
CONFIG_CACHE_TTL_SECONDS = 2.0
|
||||
_config_cached_until = 0.0
|
||||
|
||||
|
||||
async def refresh_settings(force: bool = False) -> None:
|
||||
"""从数据库读取最新配置并应用到运行时。
|
||||
|
||||
默认带短 TTL 缓存(避免每请求查库);写配置的代码路径必须传 force=True。
|
||||
"""
|
||||
global _config_cached_until
|
||||
import time as _time
|
||||
|
||||
if not force and _time.monotonic() < _config_cached_until:
|
||||
return
|
||||
config_record = await KeyValue.filter(key="settings").first()
|
||||
settings.user_config = config_record.value if config_record and config_record.value else {}
|
||||
unknown = settings.unknown_keys(settings.user_config)
|
||||
if unknown:
|
||||
logger.warning("配置中存在未登记的键(将被忽略其类型语义,仅透传): %s", unknown)
|
||||
_sync_ip_limits()
|
||||
_config_cached_until = _time.monotonic() + CONFIG_CACHE_TTL_SECONDS
|
||||
|
||||
|
||||
def is_runtime_initialized() -> bool:
|
||||
@@ -111,4 +137,4 @@ async def initialize_system(
|
||||
next_config["jwt_secret"] = generate_jwt_secret()
|
||||
|
||||
await KeyValue.update_or_create(key="settings", defaults={"value": next_config})
|
||||
await refresh_settings()
|
||||
await refresh_settings(force=True)
|
||||
@@ -7,7 +7,7 @@ from core.settings import settings
|
||||
|
||||
|
||||
def _iter_trusted_proxies() -> Iterable[str]:
|
||||
trusted_proxies = getattr(settings, "trustedProxies", [])
|
||||
trusted_proxies = getattr(settings, "trusted_proxies", [])
|
||||
if isinstance(trusted_proxies, str):
|
||||
trusted_proxies = [item.strip() for item in trusted_proxies.split(",")]
|
||||
return [item for item in trusted_proxies if item]
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
"""文件类型校验:扩展名 / MIME 白名单 + magic bytes 防伪造。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import HTTPException, UploadFile
|
||||
from fnmatch import fnmatchcase
|
||||
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FileKind:
|
||||
name: str
|
||||
extensions: tuple[str, ...]
|
||||
mimes: tuple[str, ...]
|
||||
signatures: tuple[bytes, ...]
|
||||
|
||||
|
||||
FILE_KINDS: tuple[FileKind, ...] = (
|
||||
FileKind("png", (".png",), ("image/png",), (b"\x89PNG\r\n\x1a\n",)),
|
||||
FileKind("jpg", (".jpg", ".jpeg"), ("image/jpeg",), (b"\xff\xd8\xff",)),
|
||||
FileKind("gif", (".gif",), ("image/gif",), (b"GIF87a", b"GIF89a")),
|
||||
FileKind("webp", (".webp",), ("image/webp",), ()),
|
||||
FileKind("bmp", (".bmp",), ("image/bmp", "image/x-ms-bmp"), (b"BM",)),
|
||||
FileKind("pdf", (".pdf",), ("application/pdf",), (b"%PDF",)),
|
||||
FileKind(
|
||||
"zip",
|
||||
(".zip", ".docx", ".xlsx", ".pptx", ".apk", ".jar"),
|
||||
(
|
||||
"application/zip",
|
||||
"application/x-zip-compressed",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||
"application/java-archive",
|
||||
"application/vnd.android.package-archive",
|
||||
),
|
||||
(b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08"),
|
||||
),
|
||||
FileKind(
|
||||
"rar",
|
||||
(".rar",),
|
||||
("application/x-rar-compressed", "application/vnd.rar"),
|
||||
(b"Rar!\x1a\x07\x00", b"Rar!\x1a\x07\x01\x00"),
|
||||
),
|
||||
FileKind("7z", (".7z",), ("application/x-7z-compressed",), (b"7z\xbc\xaf'\x1c",)),
|
||||
FileKind("gz", (".gz", ".tgz"), ("application/gzip", "application/x-gzip"), (b"\x1f\x8b",)),
|
||||
FileKind(
|
||||
"mp3",
|
||||
(".mp3",),
|
||||
("audio/mpeg",),
|
||||
(b"ID3", b"\xff\xfb", b"\xff\xf3", b"\xff\xf2"),
|
||||
),
|
||||
FileKind("mp4", (".mp4", ".m4a", ".mov"), ("video/mp4", "audio/mp4", "video/quicktime"), ()),
|
||||
FileKind(
|
||||
"exe",
|
||||
(".exe", ".dll", ".sys"),
|
||||
("application/x-msdownload", "application/x-dosexec"),
|
||||
(b"MZ",),
|
||||
),
|
||||
FileKind("elf", (".elf", ".so", ".o"), ("application/x-executable",), (b"\x7fELF",)),
|
||||
)
|
||||
|
||||
KNOWN_EXTENSIONS = {ext for kind in FILE_KINDS for ext in kind.extensions}
|
||||
|
||||
|
||||
def normalize_allowed_file_types() -> list[str]:
|
||||
raw_value = settings.allowed_file_types
|
||||
if isinstance(raw_value, str):
|
||||
values = [item.strip() for item in raw_value.split(",")]
|
||||
elif isinstance(raw_value, (list, tuple, set)):
|
||||
values = [str(item).strip() for item in raw_value]
|
||||
else:
|
||||
values = []
|
||||
normalized = [item.lower() for item in values if item]
|
||||
return normalized or ["*"]
|
||||
|
||||
|
||||
def _extension_of(file_name: str) -> str:
|
||||
return Path(file_name or "").suffix.lower()
|
||||
|
||||
|
||||
def _match_allow_rule(rule: str, file_name: str, content_type: str) -> bool:
|
||||
if rule in {"*", "*/*"}:
|
||||
return True
|
||||
if "/" in rule:
|
||||
return fnmatchcase(content_type, rule)
|
||||
extension = rule if rule.startswith(".") else f".{rule}"
|
||||
return file_name.endswith(extension)
|
||||
|
||||
|
||||
def is_type_allowed(file_name: str, content_type: Optional[str] = None) -> bool:
|
||||
allowed = normalize_allowed_file_types()
|
||||
if any(rule in {"*", "*/*"} for rule in allowed):
|
||||
return True
|
||||
normalized_name = (file_name or "").strip().lower()
|
||||
normalized_content_type = (content_type or "").strip().lower()
|
||||
return any(
|
||||
_match_allow_rule(rule, normalized_name, normalized_content_type)
|
||||
for rule in allowed
|
||||
)
|
||||
|
||||
|
||||
def detect_file_kind(header: bytes) -> Optional[FileKind]:
|
||||
if not header:
|
||||
return None
|
||||
|
||||
if len(header) >= 12 and header.startswith(b"RIFF") and header[8:12] == b"WEBP":
|
||||
return next(kind for kind in FILE_KINDS if kind.name == "webp")
|
||||
|
||||
if len(header) >= 12 and header[4:8] == b"ftyp":
|
||||
return next(kind for kind in FILE_KINDS if kind.name == "mp4")
|
||||
|
||||
candidates: list[tuple[int, FileKind]] = []
|
||||
for kind in FILE_KINDS:
|
||||
for signature in kind.signatures:
|
||||
if signature and header.startswith(signature):
|
||||
candidates.append((len(signature), kind))
|
||||
if not candidates:
|
||||
return None
|
||||
candidates.sort(key=lambda item: item[0], reverse=True)
|
||||
return candidates[0][1]
|
||||
|
||||
|
||||
def validate_file_type(file_name: str, content_type: Optional[str] = None) -> None:
|
||||
if not is_type_allowed(file_name, content_type):
|
||||
raise HTTPException(status_code=403, detail="不允许上传该类型文件")
|
||||
|
||||
|
||||
def _kind_matches_ext(kind: FileKind, extension: str) -> bool:
|
||||
return extension in kind.extensions
|
||||
|
||||
|
||||
def _kind_matches_mime(kind: FileKind, mime: str) -> bool:
|
||||
return mime in kind.mimes
|
||||
|
||||
|
||||
def validate_file_magic(
|
||||
file_name: str,
|
||||
content_type: Optional[str],
|
||||
header: Optional[bytes],
|
||||
) -> None:
|
||||
"""白名单通过后,用 magic bytes 防止扩展名 / MIME 伪造。"""
|
||||
validate_file_type(file_name, content_type)
|
||||
if not header:
|
||||
return
|
||||
|
||||
claimed_ext = _extension_of(file_name)
|
||||
claimed_mime = (content_type or "").strip().lower()
|
||||
detected = detect_file_kind(header)
|
||||
|
||||
if claimed_ext in KNOWN_EXTENSIONS:
|
||||
if detected is None or not _kind_matches_ext(detected, claimed_ext):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="文件内容与扩展名不匹配,疑似伪造类型",
|
||||
)
|
||||
|
||||
if claimed_mime and any(claimed_mime in kind.mimes for kind in FILE_KINDS):
|
||||
if detected is None or not _kind_matches_mime(detected, claimed_mime):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="文件内容与 Content-Type 不匹配,疑似伪造类型",
|
||||
)
|
||||
|
||||
allowed = normalize_allowed_file_types()
|
||||
if detected and not any(rule in {"*", "*/*"} for rule in allowed):
|
||||
allowed_by_detected = any(
|
||||
is_type_allowed(f"file{ext}", mime)
|
||||
for ext in detected.extensions
|
||||
for mime in (detected.mimes or (None,))
|
||||
)
|
||||
if not allowed_by_detected:
|
||||
raise HTTPException(status_code=403, detail="不允许上传该类型文件")
|
||||
|
||||
|
||||
async def read_upload_header(file: UploadFile, size: int = 64) -> bytes:
|
||||
await file.seek(0)
|
||||
header = await file.read(size)
|
||||
await file.seek(0)
|
||||
return header or b""
|
||||
|
||||
|
||||
async def validate_upload_file(file: UploadFile) -> None:
|
||||
header = await read_upload_header(file)
|
||||
validate_file_magic(file.filename or "", file.content_type, header)
|
||||
|
||||
|
||||
def validate_header_bytes(
|
||||
file_name: str, content_type: Optional[str], header: bytes
|
||||
) -> None:
|
||||
validate_file_magic(file_name, content_type, header)
|
||||
@@ -0,0 +1,19 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
async def migrate():
|
||||
conn = connections.get("default")
|
||||
await conn.execute_script(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS storagereservation (
|
||||
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
token VARCHAR(64) NOT NULL UNIQUE,
|
||||
size BIGINT NOT NULL,
|
||||
expires_at TIMESTAMP NOT NULL
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_storagereservation_token
|
||||
ON storagereservation (token);
|
||||
CREATE INDEX IF NOT EXISTS idx_storagereservation_expires_at
|
||||
ON storagereservation (expires_at);
|
||||
"""
|
||||
)
|
||||
@@ -0,0 +1,51 @@
|
||||
import json
|
||||
|
||||
from tortoise import connections
|
||||
|
||||
# 配置键驼峰 -> snake_case 统一(2.5)。settings 存于 KeyValue 表的 JSON 值中,
|
||||
# 迁移在 Python 层读取、改写键名后写回,保证存量部署升级后键名与代码一致。
|
||||
|
||||
KEY_RENAMES = {
|
||||
"adminSessionExpire": "admin_session_expire",
|
||||
"enableChunk": "enable_chunk",
|
||||
"errorCount": "error_count",
|
||||
"errorMinute": "error_minute",
|
||||
"expireStyle": "expire_style",
|
||||
"loginCount": "login_count",
|
||||
"loginMinute": "login_minute",
|
||||
"openUpload": "open_upload",
|
||||
"robotsText": "robots_text",
|
||||
"serverHost": "server_host",
|
||||
"serverPort": "server_port",
|
||||
"serverWorkers": "server_workers",
|
||||
"showAdminAddr": "show_admin_addr",
|
||||
"storageLimit": "storage_limit",
|
||||
"themesChoices": "themes_choices",
|
||||
"themesSelect": "themes_select",
|
||||
"trustedProxies": "trusted_proxies",
|
||||
"uploadCount": "upload_count",
|
||||
"uploadMinute": "upload_minute",
|
||||
"uploadSize": "upload_size",
|
||||
}
|
||||
|
||||
|
||||
async def migrate():
|
||||
conn = connections.get("default")
|
||||
rows = await conn.execute_query_dict(
|
||||
"SELECT id, value FROM keyvalue WHERE key = 'settings'"
|
||||
)
|
||||
for row in rows:
|
||||
value = row["value"]
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
value = json.loads(value)
|
||||
except ValueError:
|
||||
continue
|
||||
if not isinstance(value, dict):
|
||||
continue
|
||||
renamed = {KEY_RENAMES.get(k, k): v for k, v in value.items()}
|
||||
if renamed != value:
|
||||
await conn.execute_query(
|
||||
"UPDATE keyvalue SET value = ? WHERE id = ?",
|
||||
[json.dumps(renamed, ensure_ascii=False), row["id"]],
|
||||
)
|
||||
@@ -22,7 +22,9 @@ class FileCodes(models.Model):
|
||||
size = fields.BigIntField(default=0)
|
||||
text = fields.TextField(null=True)
|
||||
expired_at = fields.DatetimeField(null=True)
|
||||
expired_count = fields.IntField(default=0)
|
||||
# -1 = 时间式(看 expired_at),<=0 的 0 = 次数耗尽。默认 -1 而非 0:
|
||||
# 0 语义是"次数已用完即过期",忘传该字段的创建路径会得到立即过期的记录。
|
||||
expired_count = fields.IntField(default=-1)
|
||||
used_count = fields.IntField(default=0)
|
||||
created_at = fields.DatetimeField(auto_now_add=True)
|
||||
file_hash = fields.CharField(max_length=64, null=True)
|
||||
@@ -84,6 +86,15 @@ class PresignUploadSession(models.Model):
|
||||
return self.expires_at < await get_now()
|
||||
|
||||
|
||||
class StorageReservation(models.Model):
|
||||
"""尚未写入 FileCodes 的上传容量预留。"""
|
||||
|
||||
id = fields.IntField(pk=True)
|
||||
token = fields.CharField(max_length=64, unique=True, index=True)
|
||||
size = fields.BigIntField()
|
||||
expires_at = fields.DatetimeField(index=True)
|
||||
|
||||
|
||||
file_codes_pydantic = pydantic_model_creator(FileCodes, name="FileCodes")
|
||||
upload_chunk_pydantic = pydantic_model_creator(UploadChunk, name="UploadChunk")
|
||||
key_value_pydantic = pydantic_model_creator(KeyValue, name="KeyValue")
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Public-facing pages and routes: setup wizard, theme assets, index,
|
||||
robots.txt, and the public config endpoints."""
|
||||
import html
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.responses import FileResponse, HTMLResponse, RedirectResponse
|
||||
|
||||
from apps.base.config import initialize_system, is_runtime_initialized
|
||||
from apps.base.setup_wizard import (
|
||||
build_public_config,
|
||||
build_public_meta,
|
||||
build_setup_page,
|
||||
build_setup_success_page,
|
||||
parse_setup_options,
|
||||
read_setup_payload,
|
||||
setup_response,
|
||||
)
|
||||
from core.response import APIResponse
|
||||
from core.settings import BASE_DIR, DEFAULT_CONFIG, settings
|
||||
from core.version import APP_VERSION
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/setup", include_in_schema=False)
|
||||
@router.get("/setup/", include_in_schema=False)
|
||||
async def setup_page():
|
||||
if is_runtime_initialized():
|
||||
return RedirectResponse(url="/", status_code=303)
|
||||
return setup_response(build_setup_page())
|
||||
|
||||
|
||||
@router.post("/setup", include_in_schema=False)
|
||||
@router.post("/setup/", include_in_schema=False)
|
||||
async def setup_submit(request: Request):
|
||||
if is_runtime_initialized():
|
||||
return RedirectResponse(url="/", status_code=303)
|
||||
|
||||
data = await read_setup_payload(request)
|
||||
admin_password = str(data.get("admin_password") or "")
|
||||
confirm_password = str(data.get("confirm_password") or "")
|
||||
site_name = str(data.get("site_name") or "")
|
||||
|
||||
if admin_password != confirm_password:
|
||||
return setup_response(build_setup_page("两次输入的管理员密码不一致", data), 400)
|
||||
|
||||
try:
|
||||
setup_options = parse_setup_options(data)
|
||||
await initialize_system(
|
||||
admin_password=admin_password,
|
||||
site_name=site_name,
|
||||
setup_options=setup_options,
|
||||
)
|
||||
except ValueError as exc:
|
||||
return setup_response(build_setup_page(str(exc), data), 400)
|
||||
|
||||
if "application/json" in request.headers.get("accept", ""):
|
||||
return APIResponse(detail={"ok": True, "admin": "/#/admin"})
|
||||
return setup_response(build_setup_success_page())
|
||||
|
||||
def resolve_theme_root():
|
||||
themes_root = (BASE_DIR / "themes").resolve()
|
||||
theme_root = (BASE_DIR / str(settings.themes_select)).resolve()
|
||||
try:
|
||||
theme_root.relative_to(themes_root)
|
||||
except ValueError:
|
||||
theme_root = (BASE_DIR / DEFAULT_CONFIG["themes_select"]).resolve()
|
||||
if not theme_root.exists():
|
||||
theme_root = (BASE_DIR / DEFAULT_CONFIG["themes_select"]).resolve()
|
||||
return theme_root
|
||||
|
||||
|
||||
def resolve_theme_file(*parts: str):
|
||||
theme_root = resolve_theme_root()
|
||||
file_path = theme_root.joinpath(*parts).resolve()
|
||||
# 防止通过 /assets/../ 读取主题目录外的文件。
|
||||
try:
|
||||
file_path.relative_to(theme_root)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=404, detail="资源不存在")
|
||||
if not file_path.is_file():
|
||||
raise HTTPException(status_code=404, detail="资源不存在")
|
||||
return file_path
|
||||
|
||||
|
||||
@router.get("/assets/{asset_path:path}", include_in_schema=False)
|
||||
async def theme_asset(asset_path: str):
|
||||
return FileResponse(resolve_theme_file("assets", asset_path))
|
||||
|
||||
|
||||
@router.get("/")
|
||||
async def index(request=None, exc=None):
|
||||
# Site config is admin input (and during the setup window anyone can claim it);
|
||||
# always escape before injecting into the theme template to prevent stored XSS
|
||||
# (mirrors the setup page).
|
||||
return HTMLResponse(
|
||||
content=resolve_theme_file("index.html")
|
||||
.read_text(encoding="utf-8")
|
||||
.replace("{{title}}", html.escape(str(settings.name)))
|
||||
.replace("{{description}}", html.escape(str(settings.description)))
|
||||
.replace("{{keywords}}", html.escape(str(settings.keywords)))
|
||||
.replace("{{opacity}}", html.escape(str(settings.opacity)))
|
||||
.replace("{{background}}", html.escape(str(settings.background))),
|
||||
media_type="text/html",
|
||||
headers={"Cache-Control": "no-cache"},
|
||||
)
|
||||
|
||||
@router.get("/robots.txt")
|
||||
async def robots():
|
||||
return HTMLResponse(content=settings.robots_text, media_type="text/plain")
|
||||
|
||||
|
||||
@router.post("/")
|
||||
async def get_config():
|
||||
return APIResponse(detail=build_public_config())
|
||||
|
||||
|
||||
@router.get("/api/v1/config")
|
||||
async def get_public_config():
|
||||
return APIResponse(
|
||||
detail={
|
||||
"config": build_public_config(),
|
||||
"meta": build_public_meta(),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health_check():
|
||||
return APIResponse(
|
||||
detail={
|
||||
"status": "ok",
|
||||
"version": APP_VERSION,
|
||||
"storage": settings.file_storage,
|
||||
"theme": settings.themes_select,
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,121 @@
|
||||
import datetime
|
||||
|
||||
from fastapi import HTTPException
|
||||
from tortoise import connections
|
||||
from tortoise.functions import Sum
|
||||
|
||||
from apps.base.models import FileCodes, StorageReservation
|
||||
from core.settings import settings
|
||||
from core.utils import get_now
|
||||
|
||||
|
||||
def _detect_sql_dialect() -> str:
|
||||
"""识别当前默认连接的 SQL 方言。
|
||||
|
||||
优先使用 Tortoise capabilities.dialect;
|
||||
回退到 db_config 中的 engine 路径字符串。
|
||||
"""
|
||||
conn = connections.get("default")
|
||||
dialect = getattr(getattr(conn, "capabilities", None), "dialect", "") or ""
|
||||
if dialect:
|
||||
return dialect.lower()
|
||||
|
||||
try:
|
||||
engine = str(connections.db_config.get("default", {}).get("engine", "")).lower()
|
||||
except Exception:
|
||||
engine = ""
|
||||
if "postgres" in engine or "asyncpg" in engine or "psycopg" in engine:
|
||||
return "postgres"
|
||||
if "mysql" in engine:
|
||||
return "mysql"
|
||||
if "sqlite" in engine:
|
||||
return "sqlite"
|
||||
return "sqlite"
|
||||
|
||||
|
||||
def _sql_placeholders(count: int) -> list[str]:
|
||||
"""根据数据库方言生成参数占位符(多数据库兼容)。
|
||||
|
||||
SQLite 用 ?,PostgreSQL 用 $1/$2/...,MySQL 用 %s。
|
||||
"""
|
||||
dialect = _detect_sql_dialect()
|
||||
if dialect in {"postgres", "postgresql"}:
|
||||
return [f"${i}" for i in range(1, count + 1)]
|
||||
if dialect == "mysql":
|
||||
return ["%s"] * count
|
||||
return ["?"] * count
|
||||
|
||||
|
||||
def get_storage_limit() -> int:
|
||||
try:
|
||||
return max(0, int(getattr(settings, "storage_limit", 0)))
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
async def get_storage_usage() -> dict[str, int | None]:
|
||||
now = await get_now()
|
||||
# SQL 聚合:此函数在每次上传配额检查时调用,禁止全表拉取(D3)
|
||||
used_rows = await FileCodes.all().annotate(total=Sum("size")).values("total")
|
||||
reserved_rows = await StorageReservation.filter(expires_at__gt=now).annotate(
|
||||
total=Sum("size")
|
||||
).values("total")
|
||||
limit = get_storage_limit()
|
||||
used_bytes = used_rows[0]["total"] or 0
|
||||
reserved_bytes = reserved_rows[0]["total"] or 0
|
||||
return {
|
||||
"limit": limit,
|
||||
"used": used_bytes,
|
||||
"reserved": reserved_bytes,
|
||||
"available": max(0, limit - used_bytes - reserved_bytes) if limit else None,
|
||||
}
|
||||
|
||||
|
||||
async def reserve_storage(token: str, size: int, ttl_seconds: int) -> None:
|
||||
requested_size = max(0, int(size))
|
||||
limit = get_storage_limit()
|
||||
if not limit or requested_size == 0:
|
||||
return
|
||||
|
||||
now = await get_now()
|
||||
expires_at = now + datetime.timedelta(seconds=ttl_seconds)
|
||||
conn = connections.get("default")
|
||||
await StorageReservation.filter(token=token, expires_at__lte=now).delete()
|
||||
existing = await StorageReservation.filter(token=token, expires_at__gt=now).first()
|
||||
if existing:
|
||||
if existing.size == requested_size:
|
||||
return
|
||||
raise HTTPException(status_code=409, detail="上传容量预留信息不一致")
|
||||
|
||||
try:
|
||||
ph = _sql_placeholders(6)
|
||||
affected, _ = await conn.execute_query(
|
||||
f"""
|
||||
INSERT INTO storagereservation (token, size, expires_at)
|
||||
SELECT {ph[0]}, {ph[1]}, {ph[2]}
|
||||
WHERE (
|
||||
COALESCE((SELECT SUM(size) FROM filecodes), 0)
|
||||
+ COALESCE((SELECT SUM(size) FROM storagereservation WHERE expires_at > {ph[3]}), 0)
|
||||
+ {ph[4]}
|
||||
) <= {ph[5]}
|
||||
""",
|
||||
[token, requested_size, expires_at, now, requested_size, limit],
|
||||
)
|
||||
except Exception:
|
||||
concurrent = await StorageReservation.filter(
|
||||
token=token, size=requested_size, expires_at__gt=now
|
||||
).exists()
|
||||
if concurrent:
|
||||
return
|
||||
raise
|
||||
if affected != 1:
|
||||
concurrent = await StorageReservation.filter(
|
||||
token=token, size=requested_size, expires_at__gt=now
|
||||
).exists()
|
||||
if concurrent:
|
||||
return
|
||||
raise HTTPException(status_code=507, detail="存储空间已达到管理员设置的容量上限")
|
||||
|
||||
|
||||
async def release_storage(token: str) -> None:
|
||||
await StorageReservation.filter(token=token).delete()
|
||||
@@ -1,5 +1,4 @@
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class SelectFileModel(BaseModel):
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
"""apps.base service layer: upload orchestration shared by share/chunk/presign.
|
||||
|
||||
Handlers in views.py keep HTTP concerns (form parsing, session lookup, status
|
||||
codes for malformed requests, rate limiting); this module owns the business
|
||||
workflow: quota reservation, storage writes, share-record creation, and
|
||||
failure rollback/cleanup.
|
||||
"""
|
||||
import os
|
||||
|
||||
from fastapi import HTTPException, UploadFile
|
||||
from fastapi.responses import FileResponse, Response, StreamingResponse
|
||||
|
||||
from core.logger import logger
|
||||
from core.settings import settings
|
||||
from core.storage import FileStorageInterface, StoredDownload, StoredFile, storages
|
||||
|
||||
from apps.base.file_validation import validate_upload_file
|
||||
from apps.base.models import FileCodes, PresignUploadSession, UploadChunk
|
||||
from apps.base.quota import release_storage, reserve_storage
|
||||
from apps.base.utils import build_file_path, get_expire_info
|
||||
|
||||
import uuid
|
||||
|
||||
# 预签名上传会话有效期(秒)
|
||||
PRESIGN_SESSION_EXPIRES = 900 # 15分钟
|
||||
|
||||
|
||||
def stored_file_of(code: FileCodes) -> StoredFile:
|
||||
"""Adapter: project an ORM FileCodes row onto the storage-layer contract."""
|
||||
return StoredFile(
|
||||
file_path=code.file_path,
|
||||
uuid_file_name=code.uuid_file_name,
|
||||
code=code.code,
|
||||
prefix=code.prefix,
|
||||
suffix=code.suffix,
|
||||
text=code.text or "",
|
||||
)
|
||||
|
||||
|
||||
async def rollback_saved_file(
|
||||
storage: FileStorageInterface,
|
||||
file_path: str,
|
||||
uuid_file_name: str,
|
||||
*,
|
||||
context: str,
|
||||
upload_id: str | None = None,
|
||||
) -> None:
|
||||
"""Best-effort delete of a stored file after a failed upload workflow.
|
||||
|
||||
Rollback failures are logged (with traceback) and swallowed: the original
|
||||
error must propagate; the file, if left behind, is cleaned by the expiry
|
||||
task once its orphaned record ages out.
|
||||
"""
|
||||
try:
|
||||
await storage.delete_file(
|
||||
StoredFile(file_path=file_path, uuid_file_name=uuid_file_name)
|
||||
)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"%s:回滚删除已保存文件失败%s",
|
||||
context,
|
||||
f" upload_id={upload_id}" if upload_id else "",
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
|
||||
async def validate_file_size(file: UploadFile, max_size: int) -> int:
|
||||
"""Return the upload's size, rejecting anything above max_size."""
|
||||
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 chunk_reservation_ttl() -> int:
|
||||
ttl = max(1, int(getattr(settings, "chunk_expire_hours", 24))) * 3600
|
||||
return ttl
|
||||
|
||||
|
||||
class FileUploadService:
|
||||
"""统一的文件上传服务"""
|
||||
|
||||
@staticmethod
|
||||
def _storage() -> FileStorageInterface:
|
||||
return storages[settings.file_storage]()
|
||||
|
||||
@staticmethod
|
||||
async def generate_file_path(
|
||||
file_name: str, upload_id: str | None = None
|
||||
) -> tuple[str, str, str, str, str]:
|
||||
"""Delegates path generation to apps.base.utils.build_file_path."""
|
||||
return await build_file_path(file_name, upload_id or uuid.uuid4().hex)
|
||||
|
||||
@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
|
||||
|
||||
@staticmethod
|
||||
async def create_text_share(
|
||||
text: str, expire_value: int, expire_style: str
|
||||
) -> str:
|
||||
"""文本分享:配额预留 → 建分享记录 → 释放配额。"""
|
||||
text_size = len(text.encode("utf-8"))
|
||||
token = f"text:{uuid.uuid4().hex}"
|
||||
await reserve_storage(token, text_size, ttl_seconds=300)
|
||||
try:
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(
|
||||
expire_value, expire_style
|
||||
)
|
||||
await FileCodes.create(
|
||||
code=code,
|
||||
text=text,
|
||||
expired_at=expired_at,
|
||||
expired_count=expired_count,
|
||||
used_count=used_count,
|
||||
size=text_size,
|
||||
prefix="Text",
|
||||
)
|
||||
finally:
|
||||
await release_storage(token)
|
||||
return code
|
||||
|
||||
@staticmethod
|
||||
async def create_file_share(
|
||||
file: UploadFile, *, size: int, expire_value: int, expire_style: str
|
||||
) -> dict[str, str]:
|
||||
"""文件分享:路径生成 → 配额预留 → 存储写入 → 建分享记录,失败回滚已存文件。"""
|
||||
path, suffix, prefix, uuid_file_name, save_path = (
|
||||
await FileUploadService.generate_file_path(file.filename or "")
|
||||
)
|
||||
token = f"file:{uuid.uuid4().hex}"
|
||||
await reserve_storage(token, size, ttl_seconds=3600)
|
||||
storage = FileUploadService._storage()
|
||||
try:
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(
|
||||
expire_value, expire_style
|
||||
)
|
||||
await storage.save_file(file.file, save_path, file.content_type)
|
||||
await FileCodes.create(
|
||||
code=code,
|
||||
prefix=prefix,
|
||||
suffix=suffix,
|
||||
uuid_file_name=uuid_file_name,
|
||||
file_path=path,
|
||||
size=size,
|
||||
expired_at=expired_at,
|
||||
expired_count=expired_count,
|
||||
used_count=used_count,
|
||||
)
|
||||
except Exception:
|
||||
await rollback_saved_file(
|
||||
storage, path, uuid_file_name, context="分享上传"
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
await release_storage(token)
|
||||
return {"code": code, "name": file.filename}
|
||||
|
||||
@staticmethod
|
||||
async def complete_chunked_upload(
|
||||
upload_id: str, chunk_info: UploadChunk, expire_value: int, expire_style: str
|
||||
) -> dict[str, str]:
|
||||
"""分片合并:配额 → 完整性/大小校验 → 合并 → 建分享记录 → 清理分片。
|
||||
|
||||
失败路径的配额释放与清理范围与原实现逐一对齐:
|
||||
完整性校验失败仅抛 400(预留由 TTL 兜底);合并失败清理分片文件后抛 500。
|
||||
"""
|
||||
storage = FileUploadService._storage()
|
||||
await reserve_storage(
|
||||
f"chunk:{upload_id}", chunk_info.file_size, ttl_seconds=chunk_reservation_ttl()
|
||||
)
|
||||
|
||||
completed_chunks = await UploadChunk.filter(
|
||||
upload_id=upload_id, completed=True
|
||||
).all()
|
||||
if len(completed_chunks) != chunk_info.total_chunks:
|
||||
raise HTTPException(400, "分片不完整")
|
||||
|
||||
# 用分片数 * chunk_size 校验最大可能大小
|
||||
max_total_size = len(completed_chunks) * chunk_info.chunk_size
|
||||
if max_total_size > settings.upload_size:
|
||||
save_path = chunk_info.save_path
|
||||
if save_path:
|
||||
try:
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"分片超限中止:清理分片文件失败 upload_id=%s",
|
||||
upload_id,
|
||||
exc_info=True,
|
||||
)
|
||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||
await release_storage(f"chunk:{upload_id}")
|
||||
max_size_mb = settings.upload_size / (1024 * 1024)
|
||||
raise HTTPException(
|
||||
403, f"实际上传大小超过限制,最大为 {max_size_mb:.2f} MB"
|
||||
)
|
||||
|
||||
save_path = chunk_info.save_path
|
||||
path = os.path.dirname(save_path) if save_path else ""
|
||||
safe_file_name = os.path.basename(save_path) if save_path else ""
|
||||
prefix, suffix = os.path.splitext(safe_file_name)
|
||||
|
||||
try:
|
||||
records = {r.chunk_index: r for r in completed_chunks}
|
||||
_, file_hash = await storage.merge_chunks(
|
||||
upload_id,
|
||||
chunk_info.total_chunks,
|
||||
chunk_info.chunk_size,
|
||||
save_path,
|
||||
records,
|
||||
)
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(
|
||||
expire_value, 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=safe_file_name,
|
||||
prefix=prefix,
|
||||
suffix=suffix,
|
||||
)
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||
await release_storage(f"chunk:{upload_id}")
|
||||
return {"code": code, "name": safe_file_name}
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e))
|
||||
except Exception as e:
|
||||
# 合并失败时清理临时文件
|
||||
try:
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"分片合并失败:清理临时分片文件失败 upload_id=%s",
|
||||
upload_id,
|
||||
exc_info=True,
|
||||
)
|
||||
raise HTTPException(500, f"文件合并失败: {str(e)}")
|
||||
|
||||
@staticmethod
|
||||
async def commit_proxy_upload(
|
||||
session: PresignUploadSession, file: UploadFile
|
||||
) -> str:
|
||||
"""预签名代理上传:配额 → 大小/类型/一致性校验 → 转存 → 建记录 → 会话清理。
|
||||
|
||||
校验失败不释放预留(与原实现一致,由 TTL 兜底)。
|
||||
"""
|
||||
await reserve_storage(
|
||||
f"presign:{session.upload_id}",
|
||||
session.file_size,
|
||||
ttl_seconds=PRESIGN_SESSION_EXPIRES,
|
||||
)
|
||||
|
||||
file_size = await validate_file_size(file, settings.upload_size)
|
||||
await validate_upload_file(file)
|
||||
if abs(file_size - session.file_size) > 1024:
|
||||
raise HTTPException(400, "文件大小与声明不符")
|
||||
|
||||
storage = FileUploadService._storage()
|
||||
try:
|
||||
await storage.save_file(file.file, session.save_path, file.content_type)
|
||||
except Exception as e:
|
||||
raise HTTPException(500, f"文件保存失败: {str(e)}")
|
||||
|
||||
try:
|
||||
code = await FileUploadService.create_file_record(
|
||||
session.file_name,
|
||||
file_size,
|
||||
os.path.dirname(session.save_path),
|
||||
session.expire_value,
|
||||
session.expire_style,
|
||||
)
|
||||
except Exception:
|
||||
await rollback_saved_file(
|
||||
storage,
|
||||
os.path.dirname(session.save_path),
|
||||
os.path.basename(session.save_path),
|
||||
context="预签名代理上传:记录创建失败",
|
||||
upload_id=session.upload_id,
|
||||
)
|
||||
raise
|
||||
|
||||
await session.delete()
|
||||
await release_storage(f"presign:{session.upload_id}")
|
||||
return code
|
||||
|
||||
@staticmethod
|
||||
async def confirm_direct_upload(session: PresignUploadSession) -> str:
|
||||
"""预签名直传确认:配额 → 文件存在性 → 建记录 → 会话清理。
|
||||
|
||||
预留失败说明配额已耗尽,此时清理远端临时文件与会话后原样抛出。
|
||||
"""
|
||||
try:
|
||||
await reserve_storage(
|
||||
f"presign:{session.upload_id}",
|
||||
session.file_size,
|
||||
ttl_seconds=PRESIGN_SESSION_EXPIRES,
|
||||
)
|
||||
except HTTPException:
|
||||
storage = FileUploadService._storage()
|
||||
try:
|
||||
if await storage.file_exists(session.save_path):
|
||||
await storage.delete_file(
|
||||
StoredFile(
|
||||
file_path=os.path.dirname(session.save_path),
|
||||
uuid_file_name=os.path.basename(session.save_path),
|
||||
)
|
||||
)
|
||||
finally:
|
||||
await session.delete()
|
||||
await release_storage(f"presign:{session.upload_id}")
|
||||
raise
|
||||
|
||||
storage = FileUploadService._storage()
|
||||
if not await storage.file_exists(session.save_path):
|
||||
raise HTTPException(404, "文件未上传或上传失败")
|
||||
|
||||
try:
|
||||
code = await FileUploadService.create_file_record(
|
||||
session.file_name,
|
||||
session.file_size,
|
||||
os.path.dirname(session.save_path),
|
||||
session.expire_value,
|
||||
session.expire_style,
|
||||
)
|
||||
except Exception:
|
||||
await rollback_saved_file(
|
||||
storage,
|
||||
os.path.dirname(session.save_path),
|
||||
os.path.basename(session.save_path),
|
||||
context="预签名确认:记录创建失败",
|
||||
upload_id=session.upload_id,
|
||||
)
|
||||
raise
|
||||
|
||||
await session.delete()
|
||||
await release_storage(f"presign:{session.upload_id}")
|
||||
return code
|
||||
|
||||
|
||||
def response_from_download(download: StoredDownload):
|
||||
"""Build the starlette Response for a StoredDownload (view-layer duty)."""
|
||||
if download.path is not None:
|
||||
return FileResponse(
|
||||
download.path,
|
||||
media_type=download.media_type,
|
||||
headers=download.headers,
|
||||
filename=download.filename,
|
||||
)
|
||||
if download.content is not None:
|
||||
return Response(
|
||||
download.content, media_type=download.media_type, headers=download.headers
|
||||
)
|
||||
return StreamingResponse(
|
||||
download.stream_factory(),
|
||||
media_type=download.media_type,
|
||||
headers=download.headers,
|
||||
background=download.background,
|
||||
)
|
||||
@@ -0,0 +1,692 @@
|
||||
"""Setup wizard: form parsing rules and the two admin-facing HTML pages.
|
||||
|
||||
Pure presentation/logic — no router here; routes live in apps.base.pages.
|
||||
"""
|
||||
import html
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
from fastapi import Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
from core.settings import DEFAULT_CONFIG, settings
|
||||
from core.version import APP_VERSION
|
||||
|
||||
|
||||
FILE_SIZE_UNITS = {"KB": 1024, "MB": 1024**2, "GB": 1024**3}
|
||||
SAVE_TIME_UNITS = {"second": 1, "minute": 60, "hour": 3600, "day": 86400}
|
||||
EXPIRE_STYLE_OPTIONS = [
|
||||
("day", "按天"),
|
||||
("hour", "按小时"),
|
||||
("minute", "按分钟"),
|
||||
("forever", "永久"),
|
||||
("count", "按取件次数"),
|
||||
]
|
||||
|
||||
|
||||
def normalize_public_flag(value) -> int:
|
||||
if isinstance(value, str):
|
||||
return int(value.strip().lower() in {"1", "true", "on", "yes"})
|
||||
return int(bool(value))
|
||||
|
||||
|
||||
def build_public_config() -> dict:
|
||||
return {
|
||||
"name": settings.name,
|
||||
"description": settings.description,
|
||||
"explain": settings.page_explain,
|
||||
"upload_size": settings.upload_size,
|
||||
"allowed_file_types": settings.allowed_file_types,
|
||||
"expire_style": settings.expire_style,
|
||||
"enable_chunk": settings.enable_chunk,
|
||||
"open_upload": settings.open_upload,
|
||||
"notify_title": settings.notify_title,
|
||||
"notify_content": settings.notify_content,
|
||||
"show_admin_address": normalize_public_flag(settings.show_admin_addr),
|
||||
"max_save_seconds": settings.max_save_seconds,
|
||||
}
|
||||
|
||||
|
||||
def build_public_meta() -> dict:
|
||||
return {
|
||||
"version": APP_VERSION,
|
||||
"api": {
|
||||
"legacy_config": "/",
|
||||
"public_config": "/api/v1/config",
|
||||
"health": "/health",
|
||||
},
|
||||
"features": {
|
||||
"chunk_upload": bool(settings.enable_chunk),
|
||||
"guest_upload": bool(settings.open_upload),
|
||||
"admin_address_visible": bool(normalize_public_flag(settings.show_admin_addr)),
|
||||
"expiration_modes": settings.expire_style,
|
||||
},
|
||||
"limits": {
|
||||
"upload_size": settings.upload_size,
|
||||
"allowed_file_types": settings.allowed_file_types,
|
||||
"max_save_seconds": settings.max_save_seconds,
|
||||
"upload_window_minutes": settings.upload_minute,
|
||||
"upload_window_count": settings.upload_count,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def get_form_value(data: dict, key: str, default: str = "") -> str:
|
||||
value = data.get(key, default)
|
||||
if isinstance(value, list):
|
||||
value = value[-1] if value else default
|
||||
return str(value if value is not None else default)
|
||||
|
||||
|
||||
def get_form_list(data: dict, key: str) -> list[str]:
|
||||
value = data.get(key, [])
|
||||
if isinstance(value, list):
|
||||
return [str(item) for item in value if str(item)]
|
||||
if value:
|
||||
return [str(value)]
|
||||
return []
|
||||
|
||||
|
||||
def normalize_bool_field(data: dict, key: str, default: bool) -> bool:
|
||||
if key not in data:
|
||||
return default
|
||||
return get_form_value(data, key).lower() in {"1", "true", "on", "yes"}
|
||||
|
||||
|
||||
def parse_int_field(
|
||||
data: dict,
|
||||
key: str,
|
||||
default: int,
|
||||
label: str,
|
||||
min_value: int = 0,
|
||||
max_value: int | None = None,
|
||||
) -> int:
|
||||
raw_value = get_form_value(data, key, str(default)).strip()
|
||||
try:
|
||||
value = int(raw_value)
|
||||
except ValueError:
|
||||
raise ValueError(f"{label} 必须是整数")
|
||||
if value < min_value:
|
||||
raise ValueError(f"{label} 不能小于 {min_value}")
|
||||
if max_value is not None and value > max_value:
|
||||
raise ValueError(f"{label} 不能大于 {max_value}")
|
||||
return value
|
||||
|
||||
|
||||
def parse_allowed_file_types(value: str) -> list[str]:
|
||||
items = [item.strip() for item in value.split(",") if item.strip()]
|
||||
return items or ["*"]
|
||||
|
||||
|
||||
def parse_setup_options(data: dict) -> dict:
|
||||
upload_size_unit = get_form_value(data, "upload_size_unit", "MB").upper()
|
||||
if upload_size_unit not in FILE_SIZE_UNITS:
|
||||
raise ValueError("文件大小单位不正确")
|
||||
upload_size_value = parse_int_field(
|
||||
data, "upload_size_value", 10, "文件大小限制", min_value=1
|
||||
)
|
||||
|
||||
save_time_unit = get_form_value(data, "save_time_unit", "day")
|
||||
if save_time_unit not in SAVE_TIME_UNITS:
|
||||
raise ValueError("最长保存时间单位不正确")
|
||||
save_time_value = parse_int_field(
|
||||
data, "save_time_value", 0, "最长保存时间", min_value=0
|
||||
)
|
||||
|
||||
expire_styles = get_form_list(data, "expire_style")
|
||||
valid_expire_styles = {style for style, _label in EXPIRE_STYLE_OPTIONS}
|
||||
expire_styles = [style for style in expire_styles if style in valid_expire_styles]
|
||||
if not expire_styles:
|
||||
raise ValueError("至少需要选择一种过期方式")
|
||||
|
||||
code_generate_type = get_form_value(
|
||||
data, "code_generate_type", DEFAULT_CONFIG["code_generate_type"]
|
||||
)
|
||||
if code_generate_type not in {"number", "secret"}:
|
||||
raise ValueError("提取码类型不正确")
|
||||
|
||||
return {
|
||||
"allowed_file_types": parse_allowed_file_types(
|
||||
get_form_value(data, "allowed_file_types", "*")
|
||||
),
|
||||
"code_generate_type": code_generate_type,
|
||||
"enable_chunk": int(normalize_bool_field(data, "enable_chunk", False)),
|
||||
"error_count": parse_int_field(
|
||||
data, "error_count", DEFAULT_CONFIG["error_count"], "取件错误次数限制", 1
|
||||
),
|
||||
"error_minute": parse_int_field(
|
||||
data, "error_minute", DEFAULT_CONFIG["error_minute"], "取件错误检测窗口", 1
|
||||
),
|
||||
"login_count": parse_int_field(
|
||||
data, "login_count", DEFAULT_CONFIG["login_count"], "登录失败次数限制", 1
|
||||
),
|
||||
"login_minute": parse_int_field(
|
||||
data, "login_minute", DEFAULT_CONFIG["login_minute"], "登录失败检测窗口", 1
|
||||
),
|
||||
"expire_style": expire_styles,
|
||||
"max_save_seconds": save_time_value * SAVE_TIME_UNITS[save_time_unit],
|
||||
"open_upload": int(normalize_bool_field(data, "open_upload", True)),
|
||||
"upload_count": parse_int_field(
|
||||
data, "upload_count", DEFAULT_CONFIG["upload_count"], "上传次数限制", 1
|
||||
),
|
||||
"upload_minute": parse_int_field(
|
||||
data, "upload_minute", DEFAULT_CONFIG["upload_minute"], "上传检测窗口", 1
|
||||
),
|
||||
"upload_size": upload_size_value * FILE_SIZE_UNITS[upload_size_unit],
|
||||
}
|
||||
|
||||
def build_expire_style_inputs(selected_styles: list[str]) -> str:
|
||||
inputs = []
|
||||
selected = set(selected_styles)
|
||||
for style, label in EXPIRE_STYLE_OPTIONS:
|
||||
checked = " checked" if style in selected else ""
|
||||
inputs.append(
|
||||
f'<label class="check"><input type="checkbox" name="expire_style" value="{style}"{checked}> {label}</label>'
|
||||
)
|
||||
return "\n ".join(inputs)
|
||||
|
||||
def build_setup_page(error: str = "", form: dict | None = None) -> str:
|
||||
form = form or {}
|
||||
escaped_error = html.escape(error)
|
||||
escaped_site_name = html.escape(
|
||||
get_form_value(form, "site_name", DEFAULT_CONFIG["name"])
|
||||
)
|
||||
escaped_allowed_types = html.escape(get_form_value(form, "allowed_file_types", "*"))
|
||||
upload_size_value = html.escape(get_form_value(form, "upload_size_value", "10"))
|
||||
upload_size_unit = get_form_value(form, "upload_size_unit", "MB").upper()
|
||||
save_time_value = html.escape(get_form_value(form, "save_time_value", "0"))
|
||||
save_time_unit = get_form_value(form, "save_time_unit", "day")
|
||||
upload_minute = html.escape(
|
||||
get_form_value(form, "upload_minute", str(DEFAULT_CONFIG["upload_minute"]))
|
||||
)
|
||||
upload_count = html.escape(
|
||||
get_form_value(form, "upload_count", str(DEFAULT_CONFIG["upload_count"]))
|
||||
)
|
||||
error_minute = html.escape(
|
||||
get_form_value(form, "error_minute", str(DEFAULT_CONFIG["error_minute"]))
|
||||
)
|
||||
error_count = html.escape(
|
||||
get_form_value(form, "error_count", str(DEFAULT_CONFIG["error_count"]))
|
||||
)
|
||||
login_minute = html.escape(
|
||||
get_form_value(form, "login_minute", str(DEFAULT_CONFIG["login_minute"]))
|
||||
)
|
||||
login_count = html.escape(
|
||||
get_form_value(form, "login_count", str(DEFAULT_CONFIG["login_count"]))
|
||||
)
|
||||
open_upload_checked = (
|
||||
" checked" if normalize_bool_field(form, "open_upload", True) else ""
|
||||
)
|
||||
chunk_checked = (
|
||||
" checked" if normalize_bool_field(form, "enable_chunk", False) else ""
|
||||
)
|
||||
code_generate_type = get_form_value(
|
||||
form, "code_generate_type", DEFAULT_CONFIG["code_generate_type"]
|
||||
)
|
||||
selected_expire_styles = get_form_list(form, "expire_style") or list(
|
||||
DEFAULT_CONFIG["expire_style"]
|
||||
)
|
||||
expire_style_inputs = build_expire_style_inputs(selected_expire_styles)
|
||||
size_unit_options = "\n".join(
|
||||
f'<option value="{unit}"{" selected" if unit == upload_size_unit else ""}>{unit}</option>'
|
||||
for unit in FILE_SIZE_UNITS
|
||||
)
|
||||
save_time_unit_options = "\n".join(
|
||||
f'<option value="{unit}"{" selected" if unit == save_time_unit else ""}>{label}</option>'
|
||||
for unit, label in [
|
||||
("second", "秒"),
|
||||
("minute", "分钟"),
|
||||
("hour", "小时"),
|
||||
("day", "天"),
|
||||
]
|
||||
)
|
||||
code_type_options = "\n".join(
|
||||
f'<option value="{value}"{" selected" if value == code_generate_type else ""}>{label}</option>'
|
||||
for value, label in [("number", "数字"), ("secret", "随机字符")]
|
||||
)
|
||||
error_block = (
|
||||
f'<div class="alert" role="alert">{escaped_error}</div>' if escaped_error else ""
|
||||
)
|
||||
return f"""<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>初始化 FileCodeBox</title>
|
||||
<style>
|
||||
:root {{
|
||||
color-scheme: light;
|
||||
--bg: #f5f5f7;
|
||||
--panel: rgba(255, 255, 255, .86);
|
||||
--panel-strong: rgba(255, 255, 255, .96);
|
||||
--text: #18181b;
|
||||
--muted: #71717a;
|
||||
--line: rgba(228, 228, 231, .9);
|
||||
--line-strong: rgba(212, 212, 216, .95);
|
||||
--primary: #18181b;
|
||||
--primary-soft: #f4f4f5;
|
||||
--danger-bg: #fef2f2;
|
||||
--danger: #b91c1c;
|
||||
}}
|
||||
* {{ box-sizing: border-box; }}
|
||||
body {{
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 14px;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}}
|
||||
main {{
|
||||
width: min(100%, 1040px);
|
||||
padding: 14px;
|
||||
border: 1px solid rgba(255, 255, 255, .8);
|
||||
border-radius: 20px;
|
||||
background: rgba(255, 255, 255, .62);
|
||||
box-shadow: 0 22px 70px -34px rgba(24, 24, 27, .32);
|
||||
backdrop-filter: blur(22px);
|
||||
}}
|
||||
.setup-header {{
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding: 10px 10px 12px;
|
||||
}}
|
||||
.brand-mark {{
|
||||
flex: 0 0 auto;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
border-radius: 14px;
|
||||
background: #18181b;
|
||||
color: #fff;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0;
|
||||
box-shadow: 0 16px 34px -14px rgba(24, 24, 27, .42);
|
||||
}}
|
||||
.title-wrap {{
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}}
|
||||
h1 {{
|
||||
margin: 0;
|
||||
font-size: 21px;
|
||||
line-height: 1.25;
|
||||
letter-spacing: 0;
|
||||
font-weight: 750;
|
||||
}}
|
||||
p {{
|
||||
margin: 2px 0 0;
|
||||
color: var(--muted);
|
||||
line-height: 1.35;
|
||||
font-size: 13px;
|
||||
}}
|
||||
form {{
|
||||
margin: 0;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 16px;
|
||||
background: var(--panel);
|
||||
}}
|
||||
.panel-grid {{
|
||||
display: grid;
|
||||
grid-template-columns: 1.05fr 1fr 1fr;
|
||||
gap: 10px;
|
||||
}}
|
||||
.panel {{
|
||||
min-width: 0;
|
||||
padding: 10px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
background: rgba(255, 255, 255, .68);
|
||||
}}
|
||||
.panel-wide {{
|
||||
grid-column: 1 / -1;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.3fr) minmax(0, .9fr);
|
||||
gap: 12px;
|
||||
align-items: end;
|
||||
}}
|
||||
.panel-title {{
|
||||
margin: 0 0 2px;
|
||||
color: #18181b;
|
||||
font-size: 13px;
|
||||
font-weight: 760;
|
||||
}}
|
||||
label {{
|
||||
display: block;
|
||||
margin: 8px 0 5px;
|
||||
font-weight: 650;
|
||||
font-size: 12px;
|
||||
color: #3f3f46;
|
||||
}}
|
||||
input, select {{
|
||||
width: 100%;
|
||||
height: 34px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
padding: 0 10px;
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
outline: none;
|
||||
background: rgba(255, 255, 255, .84);
|
||||
transition: border-color .2s ease, box-shadow .2s ease, background-color .2s ease;
|
||||
}}
|
||||
input:focus, select:focus {{
|
||||
border-color: #a1a1aa;
|
||||
background: #fff;
|
||||
box-shadow: 0 10px 22px -12px rgba(24, 24, 27, .2), 0 0 0 3px rgba(24, 24, 27, .06);
|
||||
}}
|
||||
.grid {{
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 6px 12px;
|
||||
}}
|
||||
.full {{ grid-column: 1 / -1; }}
|
||||
.span-2 {{ grid-column: span 2; }}
|
||||
.row {{
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 88px;
|
||||
gap: 8px;
|
||||
}}
|
||||
.checks {{
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 5px;
|
||||
}}
|
||||
.check {{
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-height: 36px;
|
||||
margin: 0;
|
||||
padding: 0 9px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
font-weight: 550;
|
||||
font-size: 13px;
|
||||
color: var(--text);
|
||||
white-space: nowrap;
|
||||
background: rgba(255, 255, 255, .72);
|
||||
transition: border-color .2s ease, background-color .2s ease, box-shadow .2s ease;
|
||||
}}
|
||||
.check:hover {{
|
||||
border-color: var(--line-strong);
|
||||
background: #fff;
|
||||
box-shadow: 0 8px 20px -8px rgba(0, 0, 0, .1);
|
||||
}}
|
||||
.check input {{
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
padding: 0;
|
||||
box-shadow: none;
|
||||
}}
|
||||
.section-title {{
|
||||
display: none;
|
||||
}}
|
||||
.help {{
|
||||
margin: 4px 0 0;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}}
|
||||
.alert {{
|
||||
margin-bottom: 8px;
|
||||
padding: 9px 12px;
|
||||
border-radius: 12px;
|
||||
background: var(--danger-bg);
|
||||
color: var(--danger);
|
||||
font-size: 13px;
|
||||
}}
|
||||
button {{
|
||||
width: 100%;
|
||||
height: 38px;
|
||||
margin-top: 12px;
|
||||
border: 0;
|
||||
border-radius: 12px;
|
||||
background: var(--primary);
|
||||
color: white;
|
||||
font: inherit;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 16px 34px -14px rgba(24, 24, 27, .42);
|
||||
transition: background-color .2s ease, box-shadow .2s ease;
|
||||
}}
|
||||
button:hover {{
|
||||
background: #27272a;
|
||||
box-shadow: 0 16px 34px -14px rgba(24, 24, 27, .56);
|
||||
}}
|
||||
.hint {{
|
||||
margin-top: 8px;
|
||||
margin-bottom: 0;
|
||||
font-size: 12px;
|
||||
}}
|
||||
.compact-help {{
|
||||
display: inline;
|
||||
margin-left: 6px;
|
||||
color: var(--muted);
|
||||
font-weight: 500;
|
||||
font-size: 12px;
|
||||
}}
|
||||
.topline {{
|
||||
display: none;
|
||||
}}
|
||||
.badge {{
|
||||
min-height: 26px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0 10px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 255, 255, .76);
|
||||
color: #52525b;
|
||||
font-size: 12px;
|
||||
font-weight: 650;
|
||||
white-space: nowrap;
|
||||
}}
|
||||
@media (max-width: 640px) {{
|
||||
body {{ padding: 10px; }}
|
||||
main {{ padding: 10px; }}
|
||||
.setup-header {{ align-items: flex-start; padding: 6px 4px 10px; }}
|
||||
.title-wrap {{ align-items: flex-start; }}
|
||||
.panel-grid, .panel-wide {{ grid-template-columns: 1fr; }}
|
||||
.grid, .checks {{ grid-template-columns: 1fr; }}
|
||||
.span-2 {{ grid-column: auto; }}
|
||||
.row {{ grid-template-columns: 1fr; }}
|
||||
.badge {{ display: none; }}
|
||||
}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="setup-header">
|
||||
<div class="title-wrap">
|
||||
<div class="brand-mark">FCB</div>
|
||||
<div>
|
||||
<h1>初始化 FileCodeBox</h1>
|
||||
<p>首次配置管理员密码、上传限制和取件策略,后续可在后台调整。</p>
|
||||
</div>
|
||||
</div>
|
||||
<span class="badge">首次配置向导</span>
|
||||
</div>
|
||||
<form method="post" action="/setup" autocomplete="off">
|
||||
{error_block}
|
||||
<div class="panel-grid">
|
||||
<section class="panel">
|
||||
<div class="panel-title">基础设置</div>
|
||||
<label for="site_name">站点名称</label>
|
||||
<input id="site_name" name="site_name" maxlength="80" value="{escaped_site_name}" placeholder="文件快递柜 - FileCodeBox">
|
||||
|
||||
<label for="admin_password">管理员密码</label>
|
||||
<input id="admin_password" name="admin_password" type="password" minlength="8" required autofocus>
|
||||
|
||||
<label for="confirm_password">确认管理员密码</label>
|
||||
<input id="confirm_password" name="confirm_password" type="password" minlength="8" required>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-title">上传设置</div>
|
||||
<label for="upload_size_value">单文件大小限制</label>
|
||||
<div class="row">
|
||||
<input id="upload_size_value" name="upload_size_value" type="number" min="1" value="{upload_size_value}" required>
|
||||
<select name="upload_size_unit" aria-label="文件大小单位">
|
||||
{size_unit_options}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<label for="upload_count">上传频率 <span class="compact-help">次数 / 分钟</span></label>
|
||||
<div class="row">
|
||||
<input id="upload_count" name="upload_count" type="number" min="1" value="{upload_count}" required>
|
||||
<input name="upload_minute" type="number" min="1" value="{upload_minute}" aria-label="上传检测窗口分钟" required>
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
<input type="hidden" name="open_upload" value="0">
|
||||
<label class="check"><input type="checkbox" name="open_upload" value="1"{open_upload_checked}> 允许游客上传</label>
|
||||
<input type="hidden" name="enable_chunk" value="0">
|
||||
<label class="check"><input type="checkbox" name="enable_chunk" value="1"{chunk_checked}> 启用切片上传</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-title">取件与保存</div>
|
||||
<label for="error_count">取件错误频率 <span class="compact-help">次数 / 分钟</span></label>
|
||||
<div class="row">
|
||||
<input id="error_count" name="error_count" type="number" min="1" value="{error_count}" required>
|
||||
<input name="error_minute" type="number" min="1" value="{error_minute}" aria-label="取件错误检测窗口分钟" required>
|
||||
</div>
|
||||
|
||||
<label for="login_count">管理员登录失败频率 <span class="compact-help">次数 / 分钟</span></label>
|
||||
<div class="row">
|
||||
<input id="login_count" name="login_count" type="number" min="1" value="{login_count}" required>
|
||||
<input name="login_minute" type="number" min="1" value="{login_minute}" aria-label="登录失败检测窗口分钟" required>
|
||||
</div>
|
||||
|
||||
<label for="save_time_value">最长保存时间</label>
|
||||
<div class="row">
|
||||
<input id="save_time_value" name="save_time_value" type="number" min="0" value="{save_time_value}" required>
|
||||
<select name="save_time_unit" aria-label="最长保存时间单位">
|
||||
{save_time_unit_options}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<label for="code_generate_type">提取码类型</label>
|
||||
<select id="code_generate_type" name="code_generate_type">
|
||||
{code_type_options}
|
||||
</select>
|
||||
</section>
|
||||
|
||||
<section class="panel panel-wide">
|
||||
<div>
|
||||
<div class="panel-title">可用策略</div>
|
||||
<label>允许的过期方式</label>
|
||||
<div class="checks">
|
||||
{expire_style_inputs}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label for="allowed_file_types">允许文件类型 <span class="compact-help">逗号分隔,* 表示不限制</span></label>
|
||||
<input id="allowed_file_types" name="allowed_file_types" value="{escaped_allowed_types}" placeholder="* 或 .zip, image/*">
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<button type="submit">完成初始化</button>
|
||||
</form>
|
||||
</main>
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
|
||||
def build_setup_success_page() -> str:
|
||||
return """<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta http-equiv="refresh" content="2;url=/#/admin">
|
||||
<title>初始化完成</title>
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 24px;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
background: #f6f8fb;
|
||||
color: #172033;
|
||||
}
|
||||
main {
|
||||
width: min(100%, 420px);
|
||||
padding: 28px;
|
||||
border: 1px solid #d9e1ec;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
text-align: center;
|
||||
box-shadow: 0 18px 50px rgba(23, 32, 51, .08);
|
||||
}
|
||||
h1 { margin: 0 0 10px; font-size: 24px; letter-spacing: 0; }
|
||||
p { margin: 0 0 22px; color: #60708a; line-height: 1.65; }
|
||||
a {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 42px;
|
||||
padding: 0 18px;
|
||||
border-radius: 6px;
|
||||
background: #2563eb;
|
||||
color: white;
|
||||
text-decoration: none;
|
||||
font-weight: 700;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>初始化完成</h1>
|
||||
<p>管理员密码已设置,请使用刚才的密码登录后台。</p>
|
||||
<a href="/#/admin">进入后台</a>
|
||||
</main>
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
def setup_response(content: str, status_code: int = 200) -> HTMLResponse:
|
||||
return HTMLResponse(
|
||||
content=content,
|
||||
status_code=status_code,
|
||||
media_type="text/html",
|
||||
headers={"Cache-Control": "no-store"},
|
||||
)
|
||||
|
||||
|
||||
def is_setup_path(path: str) -> bool:
|
||||
return path.rstrip("/") == "/setup"
|
||||
|
||||
|
||||
def wants_html_response(request: Request) -> bool:
|
||||
if request.method not in {"GET", "HEAD"}:
|
||||
return False
|
||||
accept = request.headers.get("accept", "")
|
||||
return not accept or "text/html" in accept or "*/*" in accept
|
||||
|
||||
|
||||
async def read_setup_payload(request: Request) -> dict:
|
||||
content_type = request.headers.get("content-type", "")
|
||||
if "application/json" in content_type:
|
||||
data = await request.json()
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
body = (await request.body()).decode("utf-8")
|
||||
return {
|
||||
key: values if len(values) > 1 else values[-1]
|
||||
for key, values in parse_qs(body).items()
|
||||
}
|
||||
@@ -4,16 +4,22 @@
|
||||
# @Software: PyCharm
|
||||
import asyncio
|
||||
import datetime
|
||||
import logging
|
||||
import os
|
||||
|
||||
from tortoise.expressions import Q
|
||||
|
||||
from apps.base.models import FileCodes, UploadChunk
|
||||
from apps.base.models import (
|
||||
FileCodes,
|
||||
PresignUploadSession,
|
||||
StorageReservation,
|
||||
UploadChunk,
|
||||
)
|
||||
from apps.base.utils import ip_limit, get_chunk_file_path_name
|
||||
from core.config import refresh_settings
|
||||
from apps.base.config import refresh_settings
|
||||
from core.logger import logger
|
||||
from core.settings import settings, data_root
|
||||
from core.storage import FileStorageInterface, storages
|
||||
from core.storage import FileStorageInterface, StoredFile, storages
|
||||
from apps.base.services import stored_file_of
|
||||
from core.utils import get_now
|
||||
|
||||
|
||||
@@ -28,21 +34,23 @@ async def delete_expire_files():
|
||||
if not dirs and not files:
|
||||
os.rmdir(root)
|
||||
await ip_limit["error"].remove_expired_ip()
|
||||
await ip_limit["metadata"].remove_expired_ip()
|
||||
await ip_limit["upload"].remove_expired_ip()
|
||||
await StorageReservation.filter(expires_at__lte=await get_now()).delete()
|
||||
expire_data = await FileCodes.filter(
|
||||
Q(expired_at__lt=await get_now()) | Q(expired_count=0)
|
||||
).all()
|
||||
for exp in expire_data:
|
||||
try:
|
||||
await file_storage.delete_file(exp)
|
||||
await file_storage.delete_file(stored_file_of(exp))
|
||||
except Exception as e:
|
||||
logging.error(f"删除过期文件失败 code={exp.code}: {e}")
|
||||
logger.error(f"删除过期文件失败 code={exp.code}: {e}")
|
||||
try:
|
||||
await exp.delete()
|
||||
except Exception as e:
|
||||
logging.error(f"删除记录失败 code={exp.code}: {e}")
|
||||
logger.error(f"删除记录失败 code={exp.code}: {e}")
|
||||
except Exception as e:
|
||||
logging.error(e)
|
||||
logger.error(e)
|
||||
finally:
|
||||
await asyncio.sleep(600)
|
||||
|
||||
@@ -68,19 +76,56 @@ async def clean_incomplete_uploads():
|
||||
)
|
||||
await file_storage.clean_chunks(session.upload_id, save_path)
|
||||
except Exception as e:
|
||||
logging.error(
|
||||
logger.error(
|
||||
f"清理分片文件失败 upload_id={session.upload_id}: {e}"
|
||||
)
|
||||
|
||||
try:
|
||||
await UploadChunk.filter(upload_id=session.upload_id).delete()
|
||||
logging.info(f"已清理过期上传会话 upload_id={session.upload_id}")
|
||||
await StorageReservation.filter(
|
||||
token=f"chunk:{session.upload_id}"
|
||||
).delete()
|
||||
logger.info(f"已清理过期上传会话 upload_id={session.upload_id}")
|
||||
except Exception as e:
|
||||
logging.error(
|
||||
logger.error(
|
||||
f"删除分片记录失败 upload_id={session.upload_id}: {e}"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"清理未完成上传任务异常: {e}")
|
||||
logger.error(f"清理未完成上传任务异常: {e}")
|
||||
finally:
|
||||
await asyncio.sleep(3600)
|
||||
|
||||
|
||||
async def clean_expired_presign_sessions():
|
||||
while True:
|
||||
try:
|
||||
await refresh_settings()
|
||||
storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
now = await get_now()
|
||||
expired_sessions = await PresignUploadSession.filter(
|
||||
expires_at__lt=now
|
||||
).all()
|
||||
for session in expired_sessions:
|
||||
if session.mode == "direct":
|
||||
try:
|
||||
if await storage.file_exists(session.save_path):
|
||||
await storage.delete_file(
|
||||
StoredFile(
|
||||
file_path=os.path.dirname(session.save_path),
|
||||
uuid_file_name=os.path.basename(session.save_path),
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"清理过期直传文件失败 "
|
||||
f"upload_id={session.upload_id}: {e}"
|
||||
)
|
||||
await StorageReservation.filter(
|
||||
token=f"presign:{session.upload_id}"
|
||||
).delete()
|
||||
await session.delete()
|
||||
except Exception as e:
|
||||
logger.error(f"清理过期预签名会话异常: {e}")
|
||||
finally:
|
||||
await asyncio.sleep(900)
|
||||
@@ -1,5 +1,4 @@
|
||||
import datetime
|
||||
import hashlib
|
||||
import os
|
||||
import uuid
|
||||
from urllib.parse import unquote
|
||||
@@ -19,28 +18,39 @@ from core.utils import (
|
||||
)
|
||||
|
||||
|
||||
async def get_file_path_name(file: UploadFile) -> Tuple[str, str, str, str, str]:
|
||||
def validate_expire_style(expire_style: str) -> str:
|
||||
"""校验过期方式是否在管理员配置的白名单内。"""
|
||||
if expire_style not in settings.expire_style:
|
||||
raise HTTPException(status_code=400, detail="过期时间类型错误")
|
||||
return expire_style
|
||||
|
||||
|
||||
async def build_file_path(
|
||||
file_name: str, file_uuid: str
|
||||
) -> Tuple[str, str, str, str, str]:
|
||||
"""Single source of storage path generation (date dir + UUID), shared by
|
||||
regular, chunked, and presigned uploads.
|
||||
|
||||
Always use get_now() (UTC+8); do not switch to server-local time.
|
||||
"""
|
||||
today = await get_now()
|
||||
storage_path = settings.storage_path.strip("/")
|
||||
file_uuid = uuid.uuid4().hex
|
||||
filename = await sanitize_filename(unquote(file.filename or ""))
|
||||
filename = await sanitize_filename(unquote(file_name 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}"
|
||||
save_path = f"{path}/{prefix}{suffix}"
|
||||
return path, suffix, prefix, filename, save_path
|
||||
|
||||
|
||||
async def get_file_path_name(file: UploadFile) -> Tuple[str, str, str, str, str]:
|
||||
return await build_file_path(file.filename or "", uuid.uuid4().hex)
|
||||
|
||||
|
||||
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
|
||||
return await build_file_path(file_name, upload_id)
|
||||
|
||||
|
||||
async def get_expire_info(
|
||||
@@ -90,7 +100,7 @@ async def get_expire_info(
|
||||
|
||||
|
||||
def get_code_generate_type() -> str:
|
||||
code_generate_type = getattr(settings, "code_generate_type", "number")
|
||||
code_generate_type = getattr(settings, "code_generate_type", "secret")
|
||||
if code_generate_type in {"secret", "string"}:
|
||||
return "secret"
|
||||
return "number"
|
||||
@@ -113,19 +123,9 @@ async def get_random_code(style: str | None = None) -> str:
|
||||
return str(code)
|
||||
|
||||
|
||||
async def calculate_file_hash(file: UploadFile, chunk_size=1024 * 1024) -> str:
|
||||
sha = hashlib.sha256()
|
||||
await file.seek(0)
|
||||
while True:
|
||||
chunk = await file.read(chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
sha.update(chunk)
|
||||
await file.seek(0)
|
||||
return sha.hexdigest()
|
||||
|
||||
|
||||
ip_limit = {
|
||||
"error": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
|
||||
"upload": IPRateLimit(count=settings.uploadCount, minutes=settings.uploadMinute),
|
||||
"error": IPRateLimit(count=settings.error_count, minutes=settings.error_minute),
|
||||
"metadata": IPRateLimit(count=settings.error_count, minutes=settings.error_minute),
|
||||
"upload": IPRateLimit(count=settings.upload_count, minutes=settings.upload_minute),
|
||||
"login": IPRateLimit(count=settings.login_count, minutes=settings.login_minute),
|
||||
}
|
||||
@@ -1,136 +1,55 @@
|
||||
import datetime
|
||||
from fnmatch import fnmatchcase
|
||||
import hashlib
|
||||
import os
|
||||
import uuid
|
||||
from datetime import timedelta
|
||||
from urllib.parse import unquote
|
||||
from urllib.parse import quote, 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 starlette.responses import Response
|
||||
from tortoise.expressions import Case, F, Q, When
|
||||
|
||||
from apps.admin.dependencies import share_required_login
|
||||
from apps.base.models import FileCodes, UploadChunk, PresignUploadSession
|
||||
from apps.base.quota import release_storage, reserve_storage
|
||||
from apps.base.services import (
|
||||
PRESIGN_SESSION_EXPIRES,
|
||||
FileUploadService,
|
||||
response_from_download,
|
||||
stored_file_of,
|
||||
validate_file_size,
|
||||
)
|
||||
from core.storage import StoredFile
|
||||
from core.logger import logger
|
||||
from apps.base.schemas import (
|
||||
SelectFileModel,
|
||||
InitChunkUploadModel,
|
||||
CompleteUploadModel,
|
||||
PresignUploadInitRequest,
|
||||
)
|
||||
from apps.base.file_validation import validate_file_type, validate_upload_file, validate_header_bytes
|
||||
from apps.base.utils import (
|
||||
get_expire_info,
|
||||
get_file_path_name,
|
||||
ip_limit,
|
||||
get_chunk_file_path_name,
|
||||
validate_expire_style,
|
||||
)
|
||||
from core.response import APIResponse
|
||||
from core.settings import settings
|
||||
from core.storage import storages, FileStorageInterface
|
||||
from core.utils import get_select_token, get_now, sanitize_filename
|
||||
from core.utils import (
|
||||
get_file_url as get_proxy_file_url,
|
||||
get_select_token,
|
||||
get_now,
|
||||
sanitize_filename,
|
||||
)
|
||||
|
||||
share_api = APIRouter(prefix="/share", tags=["分享"])
|
||||
|
||||
|
||||
# ============ 公共服务层 ============
|
||||
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:
|
||||
@@ -144,23 +63,13 @@ async def share_text(
|
||||
expire_style: str = Form(default="day"),
|
||||
ip: str = Depends(ip_limit["upload"]),
|
||||
):
|
||||
validate_expire_style(expire_style)
|
||||
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="Text",
|
||||
)
|
||||
code = await FileUploadService.create_text_share(text, expire_value, expire_style)
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
return APIResponse(detail={"code": code})
|
||||
|
||||
@@ -172,29 +81,14 @@ async def share_file(
|
||||
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
|
||||
)
|
||||
path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name(file)
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
await file_storage.save_file(file, save_path)
|
||||
await create_file_code(
|
||||
code=code,
|
||||
prefix=prefix,
|
||||
suffix=suffix,
|
||||
uuid_file_name=uuid_file_name,
|
||||
file_path=path,
|
||||
size=file_size,
|
||||
expired_at=expired_at,
|
||||
expired_count=expired_count,
|
||||
used_count=used_count,
|
||||
file_size = await validate_file_size(file, settings.upload_size)
|
||||
await validate_upload_file(file)
|
||||
validate_expire_style(expire_style)
|
||||
detail = await FileUploadService.create_file_share(
|
||||
file, size=file_size, expire_value=expire_value, expire_style=expire_style
|
||||
)
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
return APIResponse(detail={"code": code, "name": file.filename})
|
||||
return APIResponse(detail=detail)
|
||||
|
||||
|
||||
async def get_code_file_by_code(
|
||||
@@ -211,11 +105,25 @@ async def get_code_file_by_code(
|
||||
return True, 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()
|
||||
async def consume_file_usage(file_code: FileCodes) -> bool:
|
||||
"""原子校验分享状态并记录一次实际领取。"""
|
||||
now = await get_now()
|
||||
eligible = (
|
||||
Q(expired_count__gt=0)
|
||||
| Q(expired_count__lt=0, expired_at__gt=now)
|
||||
| Q(expired_count__lt=0, expired_at=None)
|
||||
)
|
||||
updated = await FileCodes.filter(Q(id=file_code.id) & eligible).update(
|
||||
expired_count=Case(
|
||||
When(expired_count__gt=0, then=F("expired_count") - 1),
|
||||
default=F("expired_count"),
|
||||
),
|
||||
used_count=F("used_count") + 1,
|
||||
)
|
||||
if not updated:
|
||||
return False
|
||||
await file_code.refresh_from_db()
|
||||
return True
|
||||
|
||||
|
||||
def build_file_metadata(file_code: FileCodes) -> dict:
|
||||
@@ -231,7 +139,6 @@ def build_file_metadata(file_code: FileCodes) -> dict:
|
||||
"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,
|
||||
@@ -242,9 +149,13 @@ 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)
|
||||
)
|
||||
if file_code.text is not None:
|
||||
download_url = None
|
||||
elif file_code.expired_count >= 0:
|
||||
# 有次数限制的文件必须经过下载接口,第三方直链无法阻止重复使用。
|
||||
download_url = await get_proxy_file_url(file_code.code)
|
||||
else:
|
||||
download_url = await file_storage.get_file_url(stored_file_of(file_code))
|
||||
content = file_code.text if file_code.text is not None else None
|
||||
return {
|
||||
**metadata,
|
||||
@@ -255,24 +166,28 @@ async def build_select_detail(
|
||||
|
||||
|
||||
@share_api.get("/metadata/")
|
||||
async def get_file_metadata(code: str, ip: str = Depends(ip_limit["error"])):
|
||||
async def get_file_metadata(code: str, ip: str = Depends(ip_limit["metadata"])):
|
||||
has, file_code = await get_code_file_by_code(code)
|
||||
if not has:
|
||||
ip_limit["error"].add_ip(ip)
|
||||
ip_limit["metadata"].add_ip(ip)
|
||||
return APIResponse(code=404, detail=file_code)
|
||||
|
||||
assert isinstance(file_code, FileCodes)
|
||||
ip_limit["metadata"].add_ip(ip)
|
||||
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"])):
|
||||
async def post_file_metadata(
|
||||
data: SelectFileModel, ip: str = Depends(ip_limit["metadata"])
|
||||
):
|
||||
has, file_code = await get_code_file_by_code(data.code)
|
||||
if not has:
|
||||
ip_limit["error"].add_ip(ip)
|
||||
ip_limit["metadata"].add_ip(ip)
|
||||
return APIResponse(code=404, detail=file_code)
|
||||
|
||||
assert isinstance(file_code, FileCodes)
|
||||
ip_limit["metadata"].add_ip(ip)
|
||||
return APIResponse(detail=build_file_metadata(file_code))
|
||||
|
||||
|
||||
@@ -285,8 +200,20 @@ async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])):
|
||||
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)
|
||||
if not await consume_file_usage(file_code):
|
||||
return APIResponse(code=404, detail="文件已过期")
|
||||
if file_code.text is not None:
|
||||
filename = f"{file_code.prefix or 'Text'}{file_code.suffix or '.txt'}"
|
||||
return Response(
|
||||
content=file_code.text,
|
||||
media_type="text/plain",
|
||||
headers={
|
||||
"Content-Disposition": (
|
||||
f"attachment; filename*=UTF-8''{quote(filename, safe='')}"
|
||||
)
|
||||
},
|
||||
)
|
||||
return response_from_download(await file_storage.get_file_response(stored_file_of(file_code)))
|
||||
|
||||
|
||||
@share_api.post("/select/")
|
||||
@@ -298,25 +225,40 @@ async def select_file(data: SelectFileModel, ip: str = Depends(ip_limit["error"]
|
||||
return APIResponse(code=404, detail=file_code)
|
||||
|
||||
assert isinstance(file_code, FileCodes)
|
||||
await update_file_usage(file_code)
|
||||
return APIResponse(detail=await build_select_detail(file_code, file_storage))
|
||||
detail = await build_select_detail(file_code, file_storage)
|
||||
download_url = detail.get("download_url")
|
||||
consumes_on_download = isinstance(download_url, str) and download_url.startswith(
|
||||
"/share/download?"
|
||||
)
|
||||
if not consumes_on_download and not await consume_file_usage(file_code):
|
||||
return APIResponse(code=404, detail="文件已过期")
|
||||
if not consumes_on_download:
|
||||
detail.update(build_file_metadata(file_code))
|
||||
return APIResponse(detail=detail)
|
||||
|
||||
|
||||
@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:
|
||||
# 同时接受当前窗口与上一窗口 token,避免时间窗边界竞态导致偶发 403
|
||||
valid_keys = {
|
||||
await get_select_token(normalized_code, offset=0),
|
||||
await get_select_token(normalized_code, offset=1),
|
||||
}
|
||||
if key not in valid_keys:
|
||||
ip_limit["error"].add_ip(ip)
|
||||
raise HTTPException(status_code=403, detail="下载鉴权失败")
|
||||
has, file_code = await get_code_file_by_code(normalized_code, False)
|
||||
has, file_code = await get_code_file_by_code(normalized_code)
|
||||
if not has:
|
||||
return APIResponse(code=404, detail="文件不存在")
|
||||
return APIResponse(code=404, detail=file_code)
|
||||
assert isinstance(file_code, FileCodes)
|
||||
if not await consume_file_usage(file_code):
|
||||
return APIResponse(code=404, detail="文件已过期")
|
||||
return (
|
||||
APIResponse(detail=file_code.text)
|
||||
if file_code.text
|
||||
else await file_storage.get_file_response(file_code)
|
||||
else response_from_download(await file_storage.get_file_response(stored_file_of(file_code)))
|
||||
)
|
||||
|
||||
|
||||
@@ -347,43 +289,38 @@ async def parse_complete_upload(request: Request) -> CompleteUploadModel:
|
||||
|
||||
@chunk_api.post("/upload/init/", dependencies=[Depends(share_required_login)])
|
||||
async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chunk_upload)):
|
||||
validate_file_type(data.file_name)
|
||||
safe_file_name = await sanitize_filename(unquote(data.file_name or ""))
|
||||
validate_file_type(safe_file_name)
|
||||
# 服务端校验:根据 total_chunks * chunk_size 计算理论最大上传量
|
||||
total_chunks = (data.file_size + data.chunk_size - 1) // data.chunk_size
|
||||
max_possible_size = total_chunks * data.chunk_size
|
||||
if max_possible_size > settings.uploadSize:
|
||||
max_size_mb = settings.uploadSize / (1024 * 1024)
|
||||
if max_possible_size > settings.upload_size:
|
||||
max_size_mb = settings.upload_size / (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,
|
||||
file_name=safe_file_name,
|
||||
).first()
|
||||
|
||||
if existing_session:
|
||||
if not existing_session.save_path:
|
||||
await UploadChunk.filter(upload_id=existing_session.upload_id).delete()
|
||||
await release_storage(f"chunk:{existing_session.upload_id}")
|
||||
else:
|
||||
await reserve_storage(
|
||||
f"chunk:{existing_session.upload_id}",
|
||||
existing_session.file_size,
|
||||
ttl_seconds=max(
|
||||
1, int(getattr(settings, "chunk_expire_hours", 24))
|
||||
)
|
||||
* 3600,
|
||||
)
|
||||
uploaded_chunks = await UploadChunk.filter(
|
||||
upload_id=existing_session.upload_id, completed=True
|
||||
).values_list("chunk_index", flat=True)
|
||||
@@ -399,17 +336,28 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
|
||||
|
||||
# 创建新的上传会话
|
||||
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,
|
||||
reservation_token = f"chunk:{upload_id}"
|
||||
chunk_expire_seconds = max(1, int(getattr(settings, "chunk_expire_hours", 24))) * 3600
|
||||
await reserve_storage(
|
||||
reservation_token, data.file_size, ttl_seconds=chunk_expire_seconds
|
||||
)
|
||||
_, _, _, safe_file_name, save_path = await get_chunk_file_path_name(
|
||||
data.file_name, upload_id
|
||||
)
|
||||
try:
|
||||
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=safe_file_name,
|
||||
save_path=save_path,
|
||||
)
|
||||
except Exception:
|
||||
await release_storage(reservation_token)
|
||||
raise
|
||||
return APIResponse(
|
||||
detail={
|
||||
"existed": False,
|
||||
@@ -434,6 +382,11 @@ async def upload_chunk(
|
||||
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="上传会话不存在")
|
||||
await reserve_storage(
|
||||
f"chunk:{upload_id}",
|
||||
chunk_info.file_size,
|
||||
ttl_seconds=max(1, int(getattr(settings, "chunk_expire_hours", 24))) * 3600,
|
||||
)
|
||||
|
||||
# 检查分片索引有效性
|
||||
if chunk_index < 0 or chunk_index >= chunk_info.total_chunks:
|
||||
@@ -450,6 +403,8 @@ async def upload_chunk(
|
||||
|
||||
# 读取分片数据并计算哈希
|
||||
chunk_data = await chunk.read()
|
||||
if chunk_index == 0:
|
||||
validate_header_bytes(chunk_info.file_name, None, chunk_data[:64])
|
||||
chunk_size = len(chunk_data)
|
||||
|
||||
# 校验分片大小不超过声明的 chunk_size
|
||||
@@ -465,8 +420,8 @@ async def upload_chunk(
|
||||
).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)
|
||||
if max_uploaded_size > settings.upload_size:
|
||||
max_size_mb = settings.upload_size / (1024 * 1024)
|
||||
raise HTTPException(
|
||||
status_code=403, detail=f"累计上传大小超过限制,最大为 {max_size_mb:.2f} MB"
|
||||
)
|
||||
@@ -517,11 +472,12 @@ async def cancel_upload(upload_id: str):
|
||||
if save_path:
|
||||
try:
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
except Exception as e:
|
||||
pass
|
||||
except Exception:
|
||||
logger.warning("取消分片上传:清理分片文件失败 upload_id=%s", upload_id, exc_info=True)
|
||||
|
||||
# 清理数据库记录
|
||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||
await release_storage(f"chunk:{upload_id}")
|
||||
|
||||
return APIResponse(detail={"message": "上传已取消"})
|
||||
|
||||
@@ -565,79 +521,17 @@ async def complete_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)}"
|
||||
)
|
||||
validate_expire_style(data.expire_style)
|
||||
detail = await FileUploadService.complete_chunked_upload(
|
||||
upload_id, chunk_info, data.expire_value, data.expire_style
|
||||
)
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
return APIResponse(detail=detail)
|
||||
|
||||
|
||||
# ============ 预签名上传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}"
|
||||
@@ -656,6 +550,7 @@ async def _get_valid_session(
|
||||
raise HTTPException(404, "上传会话不存在")
|
||||
if await session.is_expired():
|
||||
await session.delete()
|
||||
await release_storage(f"presign:{upload_id}")
|
||||
raise HTTPException(404, "上传会话已过期")
|
||||
if expected_mode and session.mode != expected_mode:
|
||||
raise HTTPException(400, f"此会话不支持{expected_mode}模式")
|
||||
@@ -668,38 +563,42 @@ async def presign_upload_init(
|
||||
):
|
||||
"""初始化预签名上传,S3返回直传URL,其他存储返回代理URL"""
|
||||
validate_file_type(data.file_name)
|
||||
if data.file_size > settings.uploadSize:
|
||||
if data.file_size > settings.upload_size:
|
||||
raise HTTPException(
|
||||
403,
|
||||
f"文件大小超过限制,最大为 {settings.uploadSize / (1024 * 1024):.2f} MB",
|
||||
f"文件大小超过限制,最大为 {settings.upload_size / (1024 * 1024):.2f} MB",
|
||||
)
|
||||
if data.expire_style not in settings.expireStyle:
|
||||
raise HTTPException(400, "过期时间类型错误")
|
||||
validate_expire_style(data.expire_style)
|
||||
|
||||
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),
|
||||
reservation_token = f"presign:{upload_id}"
|
||||
await reserve_storage(
|
||||
reservation_token, data.file_size, ttl_seconds=PRESIGN_SESSION_EXPIRES
|
||||
)
|
||||
try:
|
||||
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),
|
||||
)
|
||||
except Exception:
|
||||
await release_storage(reservation_token)
|
||||
raise
|
||||
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
detail = {
|
||||
@@ -724,26 +623,7 @@ async def presign_upload_proxy(
|
||||
):
|
||||
"""代理模式上传,服务器转存到存储后端"""
|
||||
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()
|
||||
code = await FileUploadService.commit_proxy_upload(session, file)
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
return APIResponse(detail={"code": code, "name": session.file_name})
|
||||
|
||||
@@ -754,20 +634,7 @@ async def presign_upload_proxy(
|
||||
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()
|
||||
code = await FileUploadService.confirm_direct_upload(session)
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
return APIResponse(detail={"code": code, "name": session.file_name})
|
||||
|
||||
@@ -805,13 +672,14 @@ async def presign_upload_cancel(upload_id: str):
|
||||
storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
try:
|
||||
if await storage.file_exists(session.save_path):
|
||||
temp_file_code = FileCodes(
|
||||
temp_file_code = StoredFile(
|
||||
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
|
||||
logger.warning("取消预签名会话:清理临时文件失败 upload_id=%s", upload_id, exc_info=True)
|
||||
|
||||
await session.delete()
|
||||
await release_storage(f"presign:{upload_id}")
|
||||
return APIResponse(detail={"message": "上传会话已取消"})
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Framework-neutral errors raised by storage backends.
|
||||
|
||||
main.py registers an exception handler that renders these exactly like
|
||||
FastAPI's HTTPException responses ({"detail": ...} with the same status
|
||||
code), so callers need no per-site wrapping while core/ stays framework-free.
|
||||
"""
|
||||
|
||||
|
||||
class StorageError(Exception):
|
||||
def __init__(self, status_code: int, detail: str):
|
||||
self.status_code = status_code
|
||||
self.detail = detail
|
||||
super().__init__(detail)
|
||||
@@ -1,26 +1,60 @@
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
PRODUCTION_ENVIRONMENTS = {"production", "prod"}
|
||||
LOG_LEVELS = {
|
||||
"debug": logging.DEBUG,
|
||||
"info": logging.INFO,
|
||||
"warning": logging.WARNING,
|
||||
"error": logging.ERROR,
|
||||
"critical": logging.CRITICAL,
|
||||
}
|
||||
|
||||
|
||||
def is_production_environment() -> bool:
|
||||
environment = os.getenv("APP_ENV", "development").strip().lower()
|
||||
return environment in PRODUCTION_ENVIRONMENTS
|
||||
|
||||
|
||||
def get_log_level_name() -> str:
|
||||
configured_level = os.getenv("LOG_LEVEL", "").strip().lower()
|
||||
if configured_level in LOG_LEVELS:
|
||||
return configured_level
|
||||
return "warning" if is_production_environment() else "info"
|
||||
|
||||
|
||||
def get_log_level() -> int:
|
||||
return LOG_LEVELS[get_log_level_name()]
|
||||
|
||||
|
||||
def is_access_log_enabled() -> bool:
|
||||
configured_value = os.getenv("ACCESS_LOG")
|
||||
if configured_value is not None:
|
||||
return configured_value.strip().lower() in {"1", "true", "yes", "on"}
|
||||
return not is_production_environment()
|
||||
|
||||
|
||||
def setup_logger():
|
||||
# 创建logger对象
|
||||
_logger = logging.getLogger('FileCodeBox')
|
||||
_logger.setLevel(logging.INFO)
|
||||
_logger = logging.getLogger("FileCodeBox")
|
||||
level = get_log_level()
|
||||
_logger.setLevel(level)
|
||||
_logger.propagate = False
|
||||
|
||||
# 创建控制台处理器
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(logging.INFO)
|
||||
if not _logger.handlers:
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
_logger.addHandler(console_handler)
|
||||
else:
|
||||
console_handler = _logger.handlers[0]
|
||||
console_handler.setLevel(level)
|
||||
|
||||
# 设置日志格式
|
||||
formatter = logging.Formatter(
|
||||
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
"%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
||||
datefmt="%Y-%m-%d %H:%M:%S",
|
||||
)
|
||||
console_handler.setFormatter(formatter)
|
||||
|
||||
# 添加处理器到logger
|
||||
_logger.addHandler(console_handler)
|
||||
|
||||
return _logger
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
# @Time : 2023/8/14 11:48
|
||||
# @Author : Lan
|
||||
# @File : response.py
|
||||
# @Software: PyCharm
|
||||
from typing import Generic, Optional, TypeVar
|
||||
|
||||
from pydantic import BaseModel
|
||||
@@ -12,9 +8,4 @@ T = TypeVar("T")
|
||||
class APIResponse(BaseModel, Generic[T]):
|
||||
code: int = 200
|
||||
message: str = "ok"
|
||||
msg: Optional[str] = None
|
||||
detail: Optional[T] = None
|
||||
|
||||
def model_post_init(self, __context) -> None:
|
||||
if self.msg is None:
|
||||
self.msg = self.message
|
||||
@@ -29,9 +29,18 @@ def is_valid_jwt_secret(secret: Any) -> bool:
|
||||
|
||||
|
||||
def is_config_initialized(config: dict[str, Any]) -> bool:
|
||||
"""Cheap initialization probe — runs on EVERY request via the middleware.
|
||||
|
||||
Must never run a slow hash: a scrypt-stored token cannot be the legacy
|
||||
default (which only ever existed as plaintext or sha256), so those tokens
|
||||
are initialized without any verification. Only plaintext/sha256 tokens go
|
||||
through the legacy-default comparison, which is microseconds.
|
||||
"""
|
||||
admin_token = str(config.get("admin_token") or "")
|
||||
if not admin_token:
|
||||
return False
|
||||
if is_password_hashed(admin_token) and admin_token.startswith("scrypt$"):
|
||||
return True
|
||||
return not verify_password(LEGACY_DEFAULT_ADMIN_TOKEN, admin_token)
|
||||
|
||||
|
||||
|
||||
@@ -4,6 +4,10 @@
|
||||
# @Software: PyCharm
|
||||
from pathlib import Path
|
||||
|
||||
ADMIN_SESSION_EXPIRE_DEFAULT = 30 * 24 * 60 * 60
|
||||
ADMIN_SESSION_EXPIRE_MIN = 24 * 60 * 60
|
||||
ADMIN_SESSION_EXPIRE_MAX = 365 * 24 * 60 * 60
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
data_root = BASE_DIR / "data"
|
||||
|
||||
@@ -13,6 +17,7 @@ if not data_root.exists():
|
||||
DEFAULT_CONFIG = {
|
||||
"file_storage": "local",
|
||||
"storage_path": "",
|
||||
"storage_limit": 0,
|
||||
"name": "文件快递柜 - FileCodeBox",
|
||||
"description": "开箱即用的文件快传系统",
|
||||
"notify_title": "系统通知",
|
||||
@@ -40,20 +45,21 @@ DEFAULT_CONFIG = {
|
||||
"webdav_proxy": 0,
|
||||
"admin_token": "",
|
||||
"jwt_secret": "",
|
||||
"openUpload": 1,
|
||||
"uploadSize": 1024 * 1024 * 10,
|
||||
"admin_session_expire": ADMIN_SESSION_EXPIRE_DEFAULT,
|
||||
"open_upload": 1,
|
||||
"upload_size": 1024 * 1024 * 10,
|
||||
"allowed_file_types": ["*"],
|
||||
"expireStyle": ["day", "hour", "minute", "forever", "count"],
|
||||
"code_generate_type": "number",
|
||||
"uploadMinute": 1,
|
||||
"enableChunk": 0,
|
||||
"expire_style": ["day", "hour", "minute", "forever", "count"],
|
||||
"code_generate_type": "secret",
|
||||
"upload_minute": 1,
|
||||
"enable_chunk": 0,
|
||||
"webdav_url": "",
|
||||
"webdav_password": "",
|
||||
"webdav_username": "",
|
||||
"opacity": 0.9,
|
||||
"background": "",
|
||||
"uploadCount": 10,
|
||||
"themesChoices": [
|
||||
"upload_count": 10,
|
||||
"themes_choices": [
|
||||
{
|
||||
"name": "2023",
|
||||
"key": "themes/2023",
|
||||
@@ -67,15 +73,19 @@ DEFAULT_CONFIG = {
|
||||
"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: /",
|
||||
"trustedProxies": [],
|
||||
"themes_select": "themes/2024",
|
||||
"error_minute": 1,
|
||||
"error_count": 10,
|
||||
"login_count": 5,
|
||||
"login_minute": 15,
|
||||
"server_workers": 1,
|
||||
"server_host": "0.0.0.0",
|
||||
"server_port": 12345,
|
||||
"show_admin_addr": 0,
|
||||
"robots_text": "User-agent: *\nDisallow: /",
|
||||
"trusted_proxies": [],
|
||||
"chunk_expire_hours": 24,
|
||||
"opendal_scheme": "s3",
|
||||
}
|
||||
|
||||
|
||||
@@ -99,6 +109,14 @@ class Settings:
|
||||
else:
|
||||
self.user_config[key] = value
|
||||
|
||||
def unknown_keys(self, config: dict) -> list[str]:
|
||||
"""Keys in `config` that DEFAULT_CONFIG does not define.
|
||||
|
||||
Unknown keys silently fall through __getattr__ and crash later at the
|
||||
usage site; callers (refresh_settings) surface them at load time.
|
||||
"""
|
||||
return sorted(k for k in config if k not in self.default_config)
|
||||
|
||||
def items(self):
|
||||
return {**self.default_config, **self.user_config}.items()
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import os
|
||||
import tempfile
|
||||
from core.logger import logger
|
||||
import shutil
|
||||
from typing import Optional
|
||||
from typing import BinaryIO, Optional
|
||||
from urllib.parse import quote, unquote
|
||||
|
||||
import aiofiles
|
||||
@@ -16,32 +16,98 @@ import aiohttp
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
import datetime
|
||||
from dataclasses import dataclass
|
||||
import re
|
||||
import aioboto3
|
||||
from botocore.config import Config
|
||||
from fastapi import HTTPException, Response, UploadFile
|
||||
from core.response import APIResponse
|
||||
from core.errors import StorageError
|
||||
from core.settings import data_root, settings
|
||||
from apps.base.models import FileCodes, UploadChunk
|
||||
from core.utils import get_file_url, sanitize_filename
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
|
||||
@dataclass
|
||||
class StoredDownload:
|
||||
"""Framework-free description of a file download.
|
||||
|
||||
Backends return this; the view layer builds the starlette Response:
|
||||
- ``path`` set -> FileResponse (local files, Range support for free)
|
||||
- ``content`` set -> small full-read Response (legacy OpenDAL fallback)
|
||||
- ``stream_factory`` set -> StreamingResponse(stream_factory(), ...)
|
||||
``background`` is an optional response-sent cleanup hook.
|
||||
"""
|
||||
|
||||
filename: str
|
||||
headers: dict
|
||||
media_type: str = "application/octet-stream"
|
||||
path: object = None
|
||||
content: object = None
|
||||
stream_factory: object = None
|
||||
background: object = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class StoredFile:
|
||||
"""Plain, framework- and ORM-free description of a stored file.
|
||||
|
||||
Storage backends accept this instead of ORM models so core/ never imports
|
||||
apps/. Callers (views/tasks/services) build it from their own records.
|
||||
"""
|
||||
|
||||
file_path: str
|
||||
uuid_file_name: str
|
||||
code: str = ""
|
||||
prefix: str = ""
|
||||
suffix: str = ""
|
||||
text: str = ""
|
||||
|
||||
def get_file_path(self) -> str:
|
||||
return f"{self.file_path}/{self.uuid_file_name}"
|
||||
|
||||
|
||||
class FileStorageInterface:
|
||||
|
||||
async def save_file(self, file: UploadFile, save_path: str):
|
||||
"""
|
||||
保存文件
|
||||
@staticmethod
|
||||
def _get_chunk_record(chunk_records: dict, index: int):
|
||||
"""Look up the caller-provided record for chunk `index`.
|
||||
|
||||
Records are plain objects exposing ``chunk_hash``; fetching them from
|
||||
the DB is the caller's job (keeps storage ORM-free).
|
||||
"""
|
||||
chunk_record = chunk_records.get(index)
|
||||
if not chunk_record:
|
||||
raise ValueError(f"分片{index}记录不存在")
|
||||
return chunk_record
|
||||
|
||||
def _verify_and_hash_chunk(
|
||||
self,
|
||||
index: int,
|
||||
chunk_record,
|
||||
chunk_data: bytes,
|
||||
file_sha256,
|
||||
) -> None:
|
||||
"""Verify a chunk against its recorded hash, then stripe it into the
|
||||
whole-file digest. Raises the shared ValueError wording on mismatch."""
|
||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||
if current_hash != chunk_record.chunk_hash:
|
||||
raise ValueError(
|
||||
f"分片{index}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}"
|
||||
)
|
||||
file_sha256.update(chunk_data)
|
||||
|
||||
async def save_file(
|
||||
self, stream: BinaryIO, save_path: str, content_type: Optional[str] = None
|
||||
):
|
||||
"""Save a binary stream (caller owns closing the stream)."""
|
||||
raise NotImplementedError
|
||||
|
||||
async def delete_file(self, file_code: FileCodes):
|
||||
async def delete_file(self, file_code: StoredFile):
|
||||
"""
|
||||
删除文件
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
async def get_file_url(self, file_code: FileCodes):
|
||||
async def get_file_url(self, file_code: StoredFile):
|
||||
"""
|
||||
获取文件分享的url
|
||||
|
||||
@@ -50,7 +116,7 @@ class FileStorageInterface:
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
async def get_file_response(self, file_code: FileCodes):
|
||||
async def get_file_response(self, file_code: StoredFile):
|
||||
"""
|
||||
获取文件响应
|
||||
|
||||
@@ -70,7 +136,7 @@ class FileStorageInterface:
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
async def merge_chunks(self, upload_id: str, chunk_info: UploadChunk, save_path: str) -> tuple[str, str]:
|
||||
async def merge_chunks(self, upload_id: str, total_chunks: int, chunk_size: int, save_path: str, chunk_records: dict) -> tuple[str, str]:
|
||||
"""
|
||||
合并分片文件并返回文件路径和完整哈希值
|
||||
:param upload_id: 上传会话ID
|
||||
@@ -111,6 +177,19 @@ class SystemFileStorage(FileStorageInterface):
|
||||
self.chunk_size = 256 * 1024
|
||||
self.root_path = data_root
|
||||
|
||||
def _resolve_safe_path(self, relative_path: str) -> Path:
|
||||
"""将相对路径解析到数据根目录内,阻止路径穿越。"""
|
||||
root = self.root_path.resolve()
|
||||
raw = str(relative_path or "").replace("\\", "/").lstrip("/")
|
||||
if any(part == ".." for part in raw.split("/")):
|
||||
raise ValueError("非法文件路径")
|
||||
candidate = (root / raw).resolve()
|
||||
try:
|
||||
candidate.relative_to(root)
|
||||
except ValueError as exc:
|
||||
raise ValueError("非法文件路径") from exc
|
||||
return candidate
|
||||
|
||||
def _save(self, file, save_path):
|
||||
with open(save_path, "wb") as f:
|
||||
chunk = file.read(self.chunk_size)
|
||||
@@ -118,30 +197,32 @@ class SystemFileStorage(FileStorageInterface):
|
||||
f.write(chunk)
|
||||
chunk = file.read(self.chunk_size)
|
||||
|
||||
async def save_file(self, file: UploadFile, save_path: str):
|
||||
path_obj = Path(save_path)
|
||||
directory = str(path_obj.parent)
|
||||
async def save_file(
|
||||
self, stream: BinaryIO, save_path: str, content_type: Optional[str] = None
|
||||
):
|
||||
path_obj = Path(str(save_path).replace("\\", "/"))
|
||||
directory = str(path_obj.parent).replace("\\", "/").lstrip("/")
|
||||
# 提取原始文件名并进行清理
|
||||
filename = await sanitize_filename(path_obj.name)
|
||||
# 构建安全的完整保存路径
|
||||
safe_save_path = self.root_path / directory / filename
|
||||
safe_save_path = self._resolve_safe_path(f"{directory}/{filename}" if directory not in {"", "."} else filename)
|
||||
# 确保目录存在
|
||||
if not safe_save_path.parent.exists():
|
||||
safe_save_path.parent.mkdir(parents=True)
|
||||
await asyncio.to_thread(self._save, file.file, safe_save_path)
|
||||
await asyncio.to_thread(self._save, stream, safe_save_path)
|
||||
|
||||
async def delete_file(self, file_code: FileCodes):
|
||||
save_path = self.root_path / await file_code.get_file_path()
|
||||
async def delete_file(self, file_code: StoredFile):
|
||||
save_path = self._resolve_safe_path(file_code.get_file_path())
|
||||
if save_path.exists():
|
||||
save_path.unlink()
|
||||
|
||||
async def get_file_url(self, file_code: FileCodes):
|
||||
async def get_file_url(self, file_code: StoredFile):
|
||||
return await get_file_url(file_code.code)
|
||||
|
||||
async def get_file_response(self, file_code: FileCodes):
|
||||
file_path = self.root_path / await file_code.get_file_path()
|
||||
async def get_file_response(self, file_code: StoredFile):
|
||||
file_path = self._resolve_safe_path(file_code.get_file_path())
|
||||
if not file_path.exists():
|
||||
return APIResponse(code=404, detail="文件已过期删除")
|
||||
raise StorageError(status_code=404, detail="文件已过期删除")
|
||||
filename = f"{file_code.prefix}{file_code.suffix}"
|
||||
encoded_filename = quote(filename, safe='')
|
||||
content_disposition = f"attachment; filename*=UTF-8''{encoded_filename}"
|
||||
@@ -155,11 +236,10 @@ class SystemFileStorage(FileStorageInterface):
|
||||
# 如果获取文件大小失败,则不提供 Content-Length
|
||||
pass
|
||||
|
||||
return FileResponse(
|
||||
file_path,
|
||||
media_type="application/octet-stream",
|
||||
return StoredDownload(
|
||||
filename=filename,
|
||||
headers=headers,
|
||||
filename=filename # 保留原始文件名以备某些场景使用
|
||||
path=file_path,
|
||||
)
|
||||
|
||||
async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str):
|
||||
@@ -171,8 +251,11 @@ class SystemFileStorage(FileStorageInterface):
|
||||
:param chunk_hash: 分片哈希值
|
||||
:param save_path: 文件保存路径
|
||||
"""
|
||||
chunk_dir = self.root_path / save_path
|
||||
chunk_path = chunk_dir.parent / 'chunks' / upload_id / f"{chunk_index}.part"
|
||||
# 先校验目标文件路径合法,再将分片落到同级 chunks 目录。
|
||||
self._resolve_safe_path(save_path)
|
||||
chunk_path = self._resolve_safe_path(
|
||||
str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part")
|
||||
)
|
||||
if not chunk_path.parent.exists():
|
||||
chunk_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# 使用临时文件写入,确保原子性
|
||||
@@ -187,7 +270,7 @@ class SystemFileStorage(FileStorageInterface):
|
||||
temp_path.unlink()
|
||||
raise e
|
||||
|
||||
async def merge_chunks(self, upload_id: str, chunk_info: UploadChunk, save_path: str) -> tuple[str, str]:
|
||||
async def merge_chunks(self, upload_id: str, total_chunks: int, chunk_size: int, save_path: str, chunk_records: dict) -> tuple[str, str]:
|
||||
"""
|
||||
合并本地文件系统的分片文件并返回文件路径和完整哈希值
|
||||
:param upload_id: 上传会话ID
|
||||
@@ -195,29 +278,26 @@ class SystemFileStorage(FileStorageInterface):
|
||||
:param save_path: 文件保存路径
|
||||
:return: (文件路径, 文件哈希值)
|
||||
"""
|
||||
output_path = self.root_path / save_path
|
||||
output_path = self._resolve_safe_path(save_path)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
chunk_base_dir = output_path.parent / 'chunks' / upload_id
|
||||
chunk_base_dir = self._resolve_safe_path(
|
||||
str(Path(save_path).parent / "chunks" / upload_id)
|
||||
)
|
||||
file_sha256 = hashlib.sha256()
|
||||
|
||||
# 使用临时文件写入,确保原子性
|
||||
temp_output = output_path.with_suffix('.merging')
|
||||
try:
|
||||
async with aiofiles.open(temp_output, "wb") as out_file:
|
||||
for i in range(chunk_info.total_chunks):
|
||||
for i in range(total_chunks):
|
||||
# 获取分片记录
|
||||
chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first()
|
||||
if not chunk_record:
|
||||
raise ValueError(f"分片{i}记录不存在")
|
||||
chunk_record = self._get_chunk_record(chunk_records, i)
|
||||
chunk_path = chunk_base_dir / f"{i}.part"
|
||||
if not chunk_path.exists():
|
||||
raise ValueError(f"分片{i}文件不存在")
|
||||
async with aiofiles.open(chunk_path, "rb") as in_file:
|
||||
chunk_data = await in_file.read()
|
||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||
if current_hash != chunk_record.chunk_hash:
|
||||
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
||||
file_sha256.update(chunk_data)
|
||||
self._verify_and_hash_chunk(i, chunk_record, chunk_data, file_sha256)
|
||||
await out_file.write(chunk_data)
|
||||
# 原子重命名
|
||||
temp_output.rename(output_path)
|
||||
@@ -233,19 +313,21 @@ class SystemFileStorage(FileStorageInterface):
|
||||
:param upload_id: 上传会话ID
|
||||
:param save_path: 文件保存路径
|
||||
"""
|
||||
chunk_dir = (self.root_path / save_path).parent / 'chunks' / upload_id
|
||||
chunk_dir = self._resolve_safe_path(
|
||||
str(Path(save_path).parent / "chunks" / upload_id)
|
||||
)
|
||||
if chunk_dir.exists():
|
||||
try:
|
||||
shutil.rmtree(chunk_dir)
|
||||
except Exception as e:
|
||||
logger.info(f"清理本地分片目录失败: {e}")
|
||||
logger.warning(f"清理本地分片目录失败: {e}")
|
||||
# 清理父级 chunks 目录(如果为空)
|
||||
chunks_parent = chunk_dir.parent
|
||||
if chunks_parent.exists() and not any(chunks_parent.iterdir()):
|
||||
try:
|
||||
chunks_parent.rmdir()
|
||||
except Exception as e:
|
||||
logger.info(f"清理 chunks 父目录失败: {e}")
|
||||
logger.warning(f"清理 chunks 父目录失败: {e}")
|
||||
|
||||
async def file_exists(self, save_path: str) -> bool:
|
||||
"""
|
||||
@@ -253,7 +335,10 @@ class SystemFileStorage(FileStorageInterface):
|
||||
:param save_path: 文件路径
|
||||
:return: 文件是否存在
|
||||
"""
|
||||
file_path = self.root_path / save_path
|
||||
try:
|
||||
file_path = self._resolve_safe_path(save_path)
|
||||
except ValueError:
|
||||
return False
|
||||
return file_path.exists()
|
||||
|
||||
|
||||
@@ -297,23 +382,25 @@ class S3FileStorage(FileStorageInterface):
|
||||
config=self._client_config(),
|
||||
)
|
||||
|
||||
async def save_file(self, file: UploadFile, save_path: str):
|
||||
async def save_file(
|
||||
self, stream: BinaryIO, save_path: str, content_type: Optional[str] = None
|
||||
):
|
||||
async with self._client() as s3:
|
||||
# 使用 upload_fileobj 流式上传,避免将整个文件加载到内存
|
||||
await s3.upload_fileobj(
|
||||
file.file,
|
||||
stream,
|
||||
self.bucket_name,
|
||||
save_path,
|
||||
ExtraArgs={"ContentType": file.content_type or "application/octet-stream"},
|
||||
ExtraArgs={"ContentType": content_type or "application/octet-stream"},
|
||||
)
|
||||
|
||||
async def delete_file(self, file_code: FileCodes):
|
||||
async def delete_file(self, file_code: StoredFile):
|
||||
async with self._client() as s3:
|
||||
await s3.delete_object(
|
||||
Bucket=self.bucket_name, Key=await file_code.get_file_path()
|
||||
Bucket=self.bucket_name, Key=file_code.get_file_path()
|
||||
)
|
||||
|
||||
async def get_file_response(self, file_code: FileCodes):
|
||||
async def get_file_response(self, file_code: StoredFile):
|
||||
try:
|
||||
filename = file_code.prefix + file_code.suffix
|
||||
content_length = None # 初始化为 None,表示未知大小
|
||||
@@ -323,7 +410,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
try:
|
||||
head_response = await s3.head_object(
|
||||
Bucket=self.bucket_name,
|
||||
Key=await file_code.get_file_path()
|
||||
Key=file_code.get_file_path()
|
||||
)
|
||||
# 从HEAD响应中获取Content-Length
|
||||
if 'ContentLength' in head_response:
|
||||
@@ -338,7 +425,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
"get_object",
|
||||
Params={
|
||||
"Bucket": self.bucket_name,
|
||||
"Key": await file_code.get_file_path(),
|
||||
"Key": file_code.get_file_path(),
|
||||
},
|
||||
ExpiresIn=3600,
|
||||
)
|
||||
@@ -350,7 +437,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
try:
|
||||
async with session.get(link) as resp:
|
||||
if resp.status != 200:
|
||||
raise HTTPException(
|
||||
raise StorageError(
|
||||
status_code=resp.status,
|
||||
detail=f"从S3获取文件失败: {resp.status}"
|
||||
)
|
||||
@@ -364,24 +451,25 @@ class S3FileStorage(FileStorageInterface):
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
from fastapi.responses import StreamingResponse
|
||||
encoded_filename = quote(filename, safe='')
|
||||
headers = {
|
||||
"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
|
||||
}
|
||||
if content_length is not None:
|
||||
headers["Content-Length"] = str(content_length)
|
||||
return StreamingResponse(
|
||||
stream_generator(),
|
||||
media_type="application/octet-stream",
|
||||
headers=headers
|
||||
return StoredDownload(
|
||||
filename=filename,
|
||||
headers=headers,
|
||||
stream_factory=stream_generator,
|
||||
# 兜底关闭会话:客户端中断时与 generator finally 双保险
|
||||
background=BackgroundTask(session.close),
|
||||
)
|
||||
except HTTPException:
|
||||
except StorageError:
|
||||
raise
|
||||
except Exception:
|
||||
raise HTTPException(status_code=503, detail="服务代理下载异常,请稍后再试")
|
||||
raise StorageError(status_code=503, detail="服务代理下载异常,请稍后再试")
|
||||
|
||||
async def get_file_url(self, file_code: FileCodes):
|
||||
async def get_file_url(self, file_code: StoredFile):
|
||||
if file_code.prefix == "文本分享":
|
||||
return file_code.text
|
||||
if self.proxy:
|
||||
@@ -392,7 +480,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
"get_object",
|
||||
Params={
|
||||
"Bucket": self.bucket_name,
|
||||
"Key": await file_code.get_file_path(),
|
||||
"Key": file_code.get_file_path(),
|
||||
},
|
||||
ExpiresIn=3600,
|
||||
)
|
||||
@@ -416,7 +504,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
}
|
||||
)
|
||||
|
||||
async def merge_chunks(self, upload_id: str, chunk_info: UploadChunk, save_path: str) -> tuple[str, str]:
|
||||
async def merge_chunks(self, upload_id: str, total_chunks: int, chunk_size: int, save_path: str, chunk_records: dict) -> tuple[str, str]:
|
||||
"""
|
||||
合并 S3 上的分片文件
|
||||
使用 S3 的 multipart upload API 实现流式合并,避免内存问题
|
||||
@@ -436,11 +524,9 @@ class S3FileStorage(FileStorageInterface):
|
||||
|
||||
try:
|
||||
# 按顺序读取、验证并上传每个分片
|
||||
for i in range(chunk_info.total_chunks):
|
||||
for i in range(total_chunks):
|
||||
chunk_key = f"{chunk_dir}/{i}.part"
|
||||
chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first()
|
||||
if not chunk_record:
|
||||
raise ValueError(f"分片{i}记录不存在")
|
||||
chunk_record = self._get_chunk_record(chunk_records, i)
|
||||
|
||||
try:
|
||||
response = await s3.get_object(
|
||||
@@ -451,11 +537,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
except Exception as e:
|
||||
raise ValueError(f"分片{i}文件不存在: {e}")
|
||||
|
||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||
if current_hash != chunk_record.chunk_hash:
|
||||
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
||||
|
||||
file_sha256.update(chunk_data)
|
||||
self._verify_and_hash_chunk(i, chunk_record, chunk_data, file_sha256)
|
||||
|
||||
# 上传分片到 multipart upload
|
||||
part_response = await s3.upload_part(
|
||||
@@ -511,7 +593,7 @@ class S3FileStorage(FileStorageInterface):
|
||||
Delete={'Objects': delete_objects}
|
||||
)
|
||||
except Exception as e:
|
||||
logger.info(f"清理 S3 分片数据时出错: {e}")
|
||||
logger.warning(f"清理 S3 分片数据时出错: {e}")
|
||||
|
||||
async def generate_presigned_upload_url(self, save_path: str, expires_in: int = 900) -> Optional[str]:
|
||||
"""
|
||||
@@ -624,14 +706,32 @@ class OneDriveFileStorage(FileStorageInterface):
|
||||
path[-1] = path[-1].split(".")[0]
|
||||
return "/".join(path)
|
||||
|
||||
def _save(self, file, save_path):
|
||||
content = file.file.read()
|
||||
name = save_path(file.filename)
|
||||
path = self._get_path_str(save_path)
|
||||
self.root_path.get_by_path(path).upload(name, content).execute_query()
|
||||
async def save_file(
|
||||
self, stream: BinaryIO, save_path: str, content_type: Optional[str] = None
|
||||
):
|
||||
"""保存文件(自动创建目录;修复旧实现把 save_path 字符串当函数调用的崩溃)"""
|
||||
content = await asyncio.to_thread(stream.read)
|
||||
normalized = str(save_path).replace("\\", "/")
|
||||
name = await sanitize_filename(Path(normalized).name)
|
||||
dir_path = "/".join(normalized.split("/")[:-1])
|
||||
|
||||
async def save_file(self, file: UploadFile, save_path: str):
|
||||
await asyncio.to_thread(self._save, file, save_path)
|
||||
current_folder = self.root_path
|
||||
for part in dir_path.split("/"):
|
||||
if not part:
|
||||
continue
|
||||
try:
|
||||
current_folder = current_folder.get_by_path(part).get().execute_query()
|
||||
except self._ClientRequestException as e:
|
||||
if e.code == "itemNotFound":
|
||||
current_folder = current_folder.create_folder(part).execute_query()
|
||||
else:
|
||||
raise e
|
||||
|
||||
await asyncio.to_thread(
|
||||
lambda: current_folder.get_by_path(name)
|
||||
.upload(name, content)
|
||||
.execute_query()
|
||||
)
|
||||
|
||||
def _delete(self, save_path):
|
||||
path = self._get_path_str(save_path)
|
||||
@@ -643,8 +743,8 @@ class OneDriveFileStorage(FileStorageInterface):
|
||||
else:
|
||||
raise e
|
||||
|
||||
async def delete_file(self, file_code: FileCodes):
|
||||
await asyncio.to_thread(self._delete, await file_code.get_file_path())
|
||||
async def delete_file(self, file_code: StoredFile):
|
||||
await asyncio.to_thread(self._delete, file_code.get_file_path())
|
||||
|
||||
def _convert_link_to_download_link(self, link):
|
||||
p1 = re.search(r"https://(.+)\.sharepoint\.com", link).group(1)
|
||||
@@ -665,11 +765,11 @@ class OneDriveFileStorage(FileStorageInterface):
|
||||
).execute_query()
|
||||
return self._convert_link_to_download_link(permission.link.webUrl)
|
||||
|
||||
async def get_file_response(self, file_code: FileCodes):
|
||||
async def get_file_response(self, file_code: StoredFile):
|
||||
try:
|
||||
filename = file_code.prefix + file_code.suffix
|
||||
link = await asyncio.to_thread(
|
||||
self._get_file_url, await file_code.get_file_path(), filename
|
||||
self._get_file_url, file_code.get_file_path(), filename
|
||||
)
|
||||
|
||||
content_length = None # 初始化为 None,表示未知大小
|
||||
@@ -690,7 +790,7 @@ class OneDriveFileStorage(FileStorageInterface):
|
||||
try:
|
||||
async with session.get(link) as resp:
|
||||
if resp.status != 200:
|
||||
raise HTTPException(
|
||||
raise StorageError(
|
||||
status_code=resp.status,
|
||||
detail=f"从OneDrive获取文件失败: {resp.status}"
|
||||
)
|
||||
@@ -709,23 +809,25 @@ class OneDriveFileStorage(FileStorageInterface):
|
||||
}
|
||||
if content_length is not None:
|
||||
headers["Content-Length"] = str(content_length)
|
||||
return StreamingResponse(
|
||||
stream_generator(),
|
||||
media_type="application/octet-stream",
|
||||
headers=headers
|
||||
return StoredDownload(
|
||||
filename=filename,
|
||||
headers=headers,
|
||||
stream_factory=stream_generator,
|
||||
# 兜底关闭会话:客户端中断时与 generator finally 双保险
|
||||
background=BackgroundTask(session.close),
|
||||
)
|
||||
except HTTPException:
|
||||
except StorageError:
|
||||
raise
|
||||
except Exception:
|
||||
raise HTTPException(status_code=503, detail="服务代理下载异常,请稍后再试")
|
||||
raise StorageError(status_code=503, detail="服务代理下载异常,请稍后再试")
|
||||
|
||||
async def get_file_url(self, file_code: FileCodes):
|
||||
async def get_file_url(self, file_code: StoredFile):
|
||||
if self.proxy:
|
||||
return await get_file_url(file_code.code)
|
||||
else:
|
||||
return await asyncio.to_thread(
|
||||
self._get_file_url,
|
||||
await file_code.get_file_path(),
|
||||
file_code.get_file_path(),
|
||||
f"{file_code.prefix}{file_code.suffix}",
|
||||
)
|
||||
|
||||
@@ -781,7 +883,7 @@ class OneDriveFileStorage(FileStorageInterface):
|
||||
|
||||
current_folder.upload(filename, data).execute_query()
|
||||
|
||||
async def merge_chunks(self, upload_id: str, chunk_info: UploadChunk, save_path: str) -> tuple[str, str]:
|
||||
async def merge_chunks(self, upload_id: str, total_chunks: int, chunk_size: int, save_path: str, chunk_records: dict) -> tuple[str, str]:
|
||||
"""合并 OneDrive 上的分片文件,使用临时文件避免内存问题"""
|
||||
file_sha256 = hashlib.sha256()
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
@@ -792,22 +894,16 @@ class OneDriveFileStorage(FileStorageInterface):
|
||||
|
||||
try:
|
||||
async with aiofiles.open(temp_path, 'wb') as out_file:
|
||||
for i in range(chunk_info.total_chunks):
|
||||
for i in range(total_chunks):
|
||||
chunk_path = f"{chunk_dir}/{i}.part"
|
||||
chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first()
|
||||
if not chunk_record:
|
||||
raise ValueError(f"分片{i}记录不存在")
|
||||
chunk_record = self._get_chunk_record(chunk_records, i)
|
||||
|
||||
try:
|
||||
chunk_data = await asyncio.to_thread(self._read_chunk, chunk_path)
|
||||
except Exception as e:
|
||||
raise ValueError(f"分片{i}文件不存在: {e}")
|
||||
|
||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||
if current_hash != chunk_record.chunk_hash:
|
||||
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
||||
|
||||
file_sha256.update(chunk_data)
|
||||
self._verify_and_hash_chunk(i, chunk_record, chunk_data, file_sha256)
|
||||
await out_file.write(chunk_data)
|
||||
del chunk_data # 释放内存
|
||||
|
||||
@@ -837,7 +933,7 @@ class OneDriveFileStorage(FileStorageInterface):
|
||||
try:
|
||||
await asyncio.to_thread(self._delete_chunk_dir, chunk_dir)
|
||||
except Exception as e:
|
||||
logger.info(f"清理 OneDrive 分片时出错: {e}")
|
||||
logger.warning(f"清理 OneDrive 分片时出错: {e}")
|
||||
|
||||
def _file_exists(self, save_path: str) -> bool:
|
||||
"""同步检查文件是否存在"""
|
||||
@@ -875,25 +971,27 @@ class OpenDALFileStorage(FileStorageInterface):
|
||||
settings.opendal_scheme, **service_settings
|
||||
)
|
||||
|
||||
async def save_file(self, file: UploadFile, save_path: str):
|
||||
async def save_file(
|
||||
self, stream: BinaryIO, save_path: str, content_type: Optional[str] = None
|
||||
):
|
||||
# 使用 asyncio.to_thread 避免阻塞事件循环
|
||||
content = await asyncio.to_thread(file.file.read)
|
||||
content = await asyncio.to_thread(stream.read)
|
||||
await self.operator.write(save_path, content)
|
||||
|
||||
async def delete_file(self, file_code: FileCodes):
|
||||
await self.operator.delete(await file_code.get_file_path())
|
||||
async def delete_file(self, file_code: StoredFile):
|
||||
await self.operator.delete(file_code.get_file_path())
|
||||
|
||||
async def get_file_url(self, file_code: FileCodes):
|
||||
async def get_file_url(self, file_code: StoredFile):
|
||||
return await get_file_url(file_code.code)
|
||||
|
||||
async def get_file_response(self, file_code: FileCodes):
|
||||
async def get_file_response(self, file_code: StoredFile):
|
||||
try:
|
||||
filename = file_code.prefix + file_code.suffix
|
||||
content_length = None # 初始化为 None,表示未知大小
|
||||
|
||||
# 尝试获取文件大小
|
||||
try:
|
||||
stat_result = await self.operator.stat(await file_code.get_file_path())
|
||||
stat_result = await self.operator.stat(file_code.get_file_path())
|
||||
if hasattr(stat_result, 'content_length') and stat_result.content_length:
|
||||
content_length = stat_result.content_length
|
||||
elif hasattr(stat_result, 'size') and stat_result.size:
|
||||
@@ -905,18 +1003,20 @@ class OpenDALFileStorage(FileStorageInterface):
|
||||
# 尝试使用流式读取器
|
||||
try:
|
||||
# OpenDAL 可能提供 reader 方法返回一个异步读取器
|
||||
reader = await self.operator.reader(await file_code.get_file_path())
|
||||
reader = await self.operator.reader(file_code.get_file_path())
|
||||
except AttributeError:
|
||||
# 如果 reader 方法不存在,回退到全量读取(兼容旧版本)
|
||||
content = await self.operator.read(await file_code.get_file_path())
|
||||
content = await self.operator.read(file_code.get_file_path())
|
||||
encoded_filename = quote(filename, safe='')
|
||||
headers = {
|
||||
"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
|
||||
}
|
||||
if content_length is not None:
|
||||
headers["Content-Length"] = str(content_length)
|
||||
return Response(
|
||||
content, headers=headers, media_type="application/octet-stream"
|
||||
return StoredDownload(
|
||||
filename=filename,
|
||||
headers=headers,
|
||||
content=content,
|
||||
)
|
||||
|
||||
async def stream_generator():
|
||||
@@ -933,21 +1033,21 @@ class OpenDALFileStorage(FileStorageInterface):
|
||||
}
|
||||
if content_length is not None:
|
||||
headers["Content-Length"] = str(content_length)
|
||||
return StreamingResponse(
|
||||
stream_generator(),
|
||||
media_type="application/octet-stream",
|
||||
headers=headers
|
||||
return StoredDownload(
|
||||
filename=filename,
|
||||
headers=headers,
|
||||
stream_factory=stream_generator,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.info(e)
|
||||
raise HTTPException(status_code=404, detail="文件已过期删除")
|
||||
raise StorageError(status_code=404, detail="文件已过期删除")
|
||||
|
||||
async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str):
|
||||
"""保存分片到 OpenDAL 存储"""
|
||||
chunk_path = str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part")
|
||||
await self.operator.write(chunk_path, chunk_data)
|
||||
|
||||
async def merge_chunks(self, upload_id: str, chunk_info: UploadChunk, save_path: str) -> tuple[str, str]:
|
||||
async def merge_chunks(self, upload_id: str, total_chunks: int, chunk_size: int, save_path: str, chunk_records: dict) -> tuple[str, str]:
|
||||
"""合并 OpenDAL 存储上的分片文件,使用临时文件避免内存问题"""
|
||||
file_sha256 = hashlib.sha256()
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
@@ -958,22 +1058,16 @@ class OpenDALFileStorage(FileStorageInterface):
|
||||
|
||||
try:
|
||||
async with aiofiles.open(temp_path, 'wb') as out_file:
|
||||
for i in range(chunk_info.total_chunks):
|
||||
for i in range(total_chunks):
|
||||
chunk_path = f"{chunk_dir}/{i}.part"
|
||||
chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first()
|
||||
if not chunk_record:
|
||||
raise ValueError(f"分片{i}记录不存在")
|
||||
chunk_record = self._get_chunk_record(chunk_records, i)
|
||||
|
||||
try:
|
||||
chunk_data = await self.operator.read(chunk_path)
|
||||
except Exception as e:
|
||||
raise ValueError(f"分片{i}文件不存在: {e}")
|
||||
|
||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||
if current_hash != chunk_record.chunk_hash:
|
||||
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
||||
|
||||
file_sha256.update(chunk_data)
|
||||
self._verify_and_hash_chunk(i, chunk_record, chunk_data, file_sha256)
|
||||
await out_file.write(chunk_data)
|
||||
del chunk_data # 释放内存
|
||||
|
||||
@@ -995,7 +1089,7 @@ class OpenDALFileStorage(FileStorageInterface):
|
||||
# OpenDAL 支持递归删除
|
||||
await self.operator.remove_all(chunk_dir)
|
||||
except Exception as e:
|
||||
logger.info(f"清理 OpenDAL 分片时出错: {e}")
|
||||
logger.warning(f"清理 OpenDAL 分片时出错: {e}")
|
||||
|
||||
async def file_exists(self, save_path: str) -> bool:
|
||||
"""
|
||||
@@ -1043,7 +1137,7 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
async with session.request("MKCOL", url) as mkcol_resp:
|
||||
if mkcol_resp.status not in (200, 201, 409):
|
||||
content = await mkcol_resp.text()
|
||||
raise HTTPException(
|
||||
raise StorageError(
|
||||
status_code=mkcol_resp.status,
|
||||
detail=f"目录创建失败: {content[:200]}",
|
||||
)
|
||||
@@ -1076,7 +1170,9 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
|
||||
current_path = current_path.parent
|
||||
|
||||
async def save_file(self, file: UploadFile, save_path: str):
|
||||
async def save_file(
|
||||
self, stream: BinaryIO, save_path: str, content_type: Optional[str] = None
|
||||
):
|
||||
"""保存文件(自动创建目录,流式上传)"""
|
||||
path_obj = Path(save_path)
|
||||
directory_path = str(path_obj.parent)
|
||||
@@ -1095,7 +1191,7 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
"""流式读取文件内容"""
|
||||
chunk_size = 256 * 1024 # 256KB chunks
|
||||
while True:
|
||||
chunk = await asyncio.to_thread(file.file.read, chunk_size)
|
||||
chunk = await asyncio.to_thread(stream.read, chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
@@ -1104,21 +1200,21 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
async with session.put(
|
||||
url,
|
||||
data=file_sender(),
|
||||
headers={"Content-Type": file.content_type or "application/octet-stream"}
|
||||
headers={"Content-Type": content_type or "application/octet-stream"}
|
||||
) as resp:
|
||||
if resp.status not in (200, 201, 204):
|
||||
content = await resp.text()
|
||||
raise HTTPException(
|
||||
raise StorageError(
|
||||
status_code=resp.status,
|
||||
detail=f"文件上传失败: {content[:200]}",
|
||||
)
|
||||
except aiohttp.ClientError as e:
|
||||
raise HTTPException(
|
||||
raise StorageError(
|
||||
status_code=503, detail=f"WebDAV连接异常: {str(e)}")
|
||||
|
||||
async def delete_file(self, file_code: FileCodes):
|
||||
async def delete_file(self, file_code: StoredFile):
|
||||
"""删除WebDAV文件及空目录"""
|
||||
file_path = await file_code.get_file_path()
|
||||
file_path = file_code.get_file_path()
|
||||
url = self._build_url(file_path)
|
||||
try:
|
||||
async with aiohttp.ClientSession(auth=self.auth) as session:
|
||||
@@ -1126,7 +1222,7 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
async with session.delete(url) as resp:
|
||||
if resp.status not in (200, 204, 404):
|
||||
content = await resp.text()
|
||||
raise HTTPException(
|
||||
raise StorageError(
|
||||
status_code=resp.status,
|
||||
detail=f"WebDAV删除失败: {content[:200]}",
|
||||
)
|
||||
@@ -1135,17 +1231,17 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
await self._delete_empty_dirs(file_path, session)
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
raise HTTPException(
|
||||
raise StorageError(
|
||||
status_code=503, detail=f"WebDAV连接异常: {str(e)}")
|
||||
|
||||
async def get_file_url(self, file_code: FileCodes):
|
||||
async def get_file_url(self, file_code: StoredFile):
|
||||
return await get_file_url(file_code.code)
|
||||
|
||||
async def get_file_response(self, file_code: FileCodes):
|
||||
async def get_file_response(self, file_code: StoredFile):
|
||||
"""获取文件响应(代理模式)"""
|
||||
try:
|
||||
filename = file_code.prefix + file_code.suffix
|
||||
url = self._build_url(await file_code.get_file_path())
|
||||
url = self._build_url(file_code.get_file_path())
|
||||
content_length = None # 初始化为 None,表示未知大小
|
||||
|
||||
# 创建ClientSession并复用(包含认证头)
|
||||
@@ -1166,7 +1262,7 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
try:
|
||||
async with session.get(url) as resp:
|
||||
if resp.status != 200:
|
||||
raise HTTPException(
|
||||
raise StorageError(
|
||||
status_code=resp.status,
|
||||
detail=f"文件获取失败{resp.status}: {await resp.text()}",
|
||||
)
|
||||
@@ -1185,13 +1281,15 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
}
|
||||
if content_length is not None:
|
||||
headers["Content-Length"] = str(content_length)
|
||||
return StreamingResponse(
|
||||
stream_generator(),
|
||||
media_type="application/octet-stream",
|
||||
headers=headers
|
||||
return StoredDownload(
|
||||
filename=filename,
|
||||
headers=headers,
|
||||
stream_factory=stream_generator,
|
||||
# 兜底关闭会话:客户端中断时与 generator finally 双保险
|
||||
background=BackgroundTask(session.close),
|
||||
)
|
||||
except aiohttp.ClientError as e:
|
||||
raise HTTPException(
|
||||
raise StorageError(
|
||||
status_code=503, detail=f"WebDAV连接异常: {str(e)}")
|
||||
|
||||
async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str):
|
||||
@@ -1207,12 +1305,12 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
async with session.put(chunk_url, data=chunk_data) as resp:
|
||||
if resp.status not in (200, 201, 204):
|
||||
content = await resp.text()
|
||||
raise HTTPException(
|
||||
raise StorageError(
|
||||
status_code=resp.status,
|
||||
detail=f"分片上传失败: {content[:200]}"
|
||||
)
|
||||
|
||||
async def merge_chunks(self, upload_id: str, chunk_info: UploadChunk, save_path: str) -> tuple[str, str]:
|
||||
async def merge_chunks(self, upload_id: str, total_chunks: int, chunk_size: int, save_path: str, chunk_records: dict) -> tuple[str, str]:
|
||||
"""
|
||||
合并 WebDAV 上的分片文件
|
||||
使用临时文件避免内存问题
|
||||
@@ -1228,14 +1326,12 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
async with aiohttp.ClientSession(auth=self.auth) as session:
|
||||
# 按顺序读取并验证每个分片,写入临时文件
|
||||
async with aiofiles.open(temp_path, 'wb') as out_file:
|
||||
for i in range(chunk_info.total_chunks):
|
||||
for i in range(total_chunks):
|
||||
chunk_path = f"{chunk_dir}/{i}.part"
|
||||
chunk_url = self._build_url(chunk_path)
|
||||
|
||||
# 获取分片记录
|
||||
chunk_record = await UploadChunk.filter(upload_id=upload_id, chunk_index=i).first()
|
||||
if not chunk_record:
|
||||
raise ValueError(f"分片{i}记录不存在")
|
||||
chunk_record = self._get_chunk_record(chunk_records, i)
|
||||
|
||||
# 下载分片数据
|
||||
async with session.get(chunk_url) as resp:
|
||||
@@ -1244,11 +1340,7 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
chunk_data = await resp.read()
|
||||
|
||||
# 验证哈希
|
||||
current_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||
if current_hash != chunk_record.chunk_hash:
|
||||
raise ValueError(f"分片{i}哈希不匹配: 期望 {chunk_record.chunk_hash}, 实际 {current_hash}")
|
||||
|
||||
file_sha256.update(chunk_data)
|
||||
self._verify_and_hash_chunk(i, chunk_record, chunk_data, file_sha256)
|
||||
await out_file.write(chunk_data)
|
||||
del chunk_data # 释放内存
|
||||
|
||||
@@ -1270,7 +1362,7 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
async with session.put(output_url, data=file_sender()) as resp:
|
||||
if resp.status not in (200, 201, 204):
|
||||
content = await resp.text()
|
||||
raise HTTPException(
|
||||
raise StorageError(
|
||||
status_code=resp.status,
|
||||
detail=f"合并文件上传失败: {content[:200]}"
|
||||
)
|
||||
@@ -1304,16 +1396,16 @@ class WebDAVFileStorage(FileStorageInterface):
|
||||
file_url = self._build_url(file_path)
|
||||
async with session.delete(file_url) as delete_resp:
|
||||
if delete_resp.status not in (200, 204, 404):
|
||||
logger.info(f"删除分片文件失败: {file_path}")
|
||||
logger.warning(f"删除分片文件失败: {file_path}")
|
||||
|
||||
# 删除分片目录
|
||||
async with session.delete(chunk_dir_url) as delete_resp:
|
||||
if delete_resp.status not in (200, 204, 404):
|
||||
logger.info(f"删除分片目录失败: {chunk_dir_url}")
|
||||
logger.warning(f"删除分片目录失败: {chunk_dir_url}")
|
||||
else:
|
||||
logger.info(f"分片目录不存在: {chunk_dir_url}")
|
||||
except Exception as e:
|
||||
logger.info(f"清理 WebDAV 分片时出错: {e}")
|
||||
logger.warning(f"清理 WebDAV 分片时出错: {e}")
|
||||
|
||||
async def file_exists(self, save_path: str) -> bool:
|
||||
"""
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
# @Software: PyCharm
|
||||
import datetime
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
@@ -24,6 +25,27 @@ async def get_random_num():
|
||||
r_s = string.ascii_uppercase + string.digits
|
||||
|
||||
|
||||
def validate_background_url(value) -> str:
|
||||
"""Validate the site background config before it reaches the theme template.
|
||||
|
||||
Themes inject this value into inline CSS ``url('...')`` where html escaping
|
||||
cannot neutralize a single-quote breakout, so only well-formed http(s) URLs
|
||||
(or an empty string) are accepted.
|
||||
"""
|
||||
value = str(value or "").strip()
|
||||
if not value:
|
||||
return ""
|
||||
from urllib.parse import urlparse
|
||||
|
||||
parsed = urlparse(value)
|
||||
if parsed.scheme not in ("http", "https") or not parsed.netloc:
|
||||
raise ValueError("background 必须是 http(s) 完整 URL 或留空")
|
||||
# quote()/whitespace would break out of the CSS url('') quoting context
|
||||
if any(ch in value for ch in ("'", '"', "(", ")", " ", "\\", ";")):
|
||||
raise ValueError("background URL 含有不允许的字符")
|
||||
return value
|
||||
|
||||
|
||||
async def get_random_string():
|
||||
"""
|
||||
获取随机字符串
|
||||
@@ -40,17 +62,22 @@ async def get_now():
|
||||
return datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8)))
|
||||
|
||||
|
||||
async def get_select_token(code: str):
|
||||
async def get_select_token(code: str, offset: int = 0):
|
||||
"""
|
||||
获取下载token
|
||||
:param code:
|
||||
:param code: 取件码
|
||||
:param offset: 时间窗口偏移(0=当前窗口,1=上一个窗口)。
|
||||
用于兼容窗口边界竞态:用户在某窗口末尾获取的 token,
|
||||
请求到达服务器时可能已进入下一窗口。
|
||||
:return:
|
||||
"""
|
||||
token = getattr(settings, "jwt_secret", "")
|
||||
if not token:
|
||||
raise RuntimeError("应用签名密钥未初始化")
|
||||
# 每个窗口约 1000 秒;offset 允许校验上一窗口,避免边界竞态
|
||||
time_factor = int(time.time() / 1000) - max(0, int(offset))
|
||||
return hashlib.sha256(
|
||||
f"{code}{int(time.time() / 1000)}000{token}".encode()
|
||||
f"{code}{time_factor}000{token}".encode()
|
||||
).hexdigest()
|
||||
|
||||
|
||||
@@ -99,44 +126,85 @@ async def max_save_times_desc(max_save_seconds: int):
|
||||
return desc_zh, desc_en
|
||||
|
||||
|
||||
# scrypt work factors (OWASP-recommended memory-hard parameters; ~50ms/verify)
|
||||
SCRYPT_N = 2**14
|
||||
SCRYPT_R = 8
|
||||
SCRYPT_P = 1
|
||||
_SCRYPT_MAXMEM = 64 * 1024 * 1024 # hashlib default cap (32MB) is too low for n=2^14,r=8
|
||||
|
||||
PASSWORD_SCHEME = "scrypt" # current scheme for new hashes; sha256/plaintext stay verifiable
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""
|
||||
使用 SHA256 + salt 哈希密码
|
||||
返回格式: sha256$<salt>$<hash>
|
||||
使用 scrypt(memory-hard)哈希密码
|
||||
返回格式: scrypt$<n>$<r>$<p>$<salt>$<hash>
|
||||
"""
|
||||
salt = os.urandom(16).hex()
|
||||
password_hash = hashlib.sha256(f"{salt}{password}".encode()).hexdigest()
|
||||
return f"sha256${salt}${password_hash}"
|
||||
password_hash = hashlib.scrypt(
|
||||
password.encode(),
|
||||
salt=salt.encode(),
|
||||
n=SCRYPT_N,
|
||||
r=SCRYPT_R,
|
||||
p=SCRYPT_P,
|
||||
maxmem=_SCRYPT_MAXMEM,
|
||||
).hex()
|
||||
return f"scrypt${SCRYPT_N}${SCRYPT_R}${SCRYPT_P}${salt}${password_hash}"
|
||||
|
||||
|
||||
def verify_password(password: str, hashed: str) -> bool:
|
||||
"""
|
||||
验证密码是否匹配
|
||||
支持新格式 (sha256$salt$hash) 和旧格式 (明文)
|
||||
支持格式: scrypt$n$r$p$salt$hash(现行)、sha256$salt$hash(历史)、明文(最老)
|
||||
"""
|
||||
if not hashed:
|
||||
return False
|
||||
|
||||
# 新格式: sha256$salt$hash
|
||||
if hashed.startswith("scrypt$"):
|
||||
parts = hashed.split("$")
|
||||
if len(parts) != 6:
|
||||
return False
|
||||
try:
|
||||
scheme, n, r, p, salt, stored_hash = parts
|
||||
password_hash = hashlib.scrypt(
|
||||
password.encode(),
|
||||
salt=salt.encode(),
|
||||
n=int(n),
|
||||
r=int(r),
|
||||
p=int(p),
|
||||
maxmem=_SCRYPT_MAXMEM,
|
||||
).hex()
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
return hmac.compare_digest(password_hash, stored_hash)
|
||||
|
||||
# sha256 格式: 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 hmac.compare_digest(password_hash, stored_hash)
|
||||
|
||||
# 旧格式: 明文比较 (兼容迁移前的数据)
|
||||
return password == hashed
|
||||
return hmac.compare_digest(str(password), str(hashed))
|
||||
|
||||
|
||||
def is_password_hashed(password: str) -> bool:
|
||||
"""
|
||||
检查密码是否已经是哈希格式
|
||||
检查密码是否已经是哈希格式(现行或历史哈希均视为已哈希)
|
||||
"""
|
||||
if password.startswith("scrypt$") and len(password.split("$")) == 6:
|
||||
return True
|
||||
return password.startswith("sha256$") and len(password.split("$")) == 3
|
||||
|
||||
|
||||
def password_needs_rehash(hashed: str) -> bool:
|
||||
"""True when the stored hash uses a legacy scheme (sha256/plaintext)."""
|
||||
return bool(hashed) and not hashed.startswith(f"{PASSWORD_SCHEME}$")
|
||||
|
||||
|
||||
async def sanitize_filename(filename: str) -> str:
|
||||
"""
|
||||
安全处理文件名:
|
||||
|
||||
@@ -1 +1,20 @@
|
||||
APP_VERSION = "2.4.0"
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
VERSION_FILE = Path(__file__).resolve().parents[1] / "VERSION"
|
||||
VERSION_PATTERN = re.compile(
|
||||
r"^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$"
|
||||
)
|
||||
|
||||
|
||||
def load_app_version() -> str:
|
||||
version = os.getenv("APP_VERSION") or VERSION_FILE.read_text(encoding="utf-8")
|
||||
version = version.strip()
|
||||
if not VERSION_PATTERN.fullmatch(version):
|
||||
raise RuntimeError(f"无效的应用版本号: {version!r}")
|
||||
return version
|
||||
|
||||
|
||||
APP_VERSION = load_app_version()
|
||||
@@ -1,12 +1,22 @@
|
||||
version: "3"
|
||||
services:
|
||||
file-code-box:
|
||||
image: lanol/filecodebox:latest
|
||||
image: lanol/filecodebox:2.6.0 # x-release-please-version
|
||||
volumes:
|
||||
- fcb-data:/app/data:rw
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "12345:12345"
|
||||
environment:
|
||||
- APP_ENV=production
|
||||
- LOG_LEVEL=warning
|
||||
- ACCESS_LOG=false
|
||||
- WORKERS=1
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
volumes:
|
||||
fcb-data:
|
||||
external: false
|
||||
external: false
|
||||
@@ -1,52 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"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_F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eAAO,OAAO;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AACA,SAAO,IAAI,KAAK;AAClB;AACA,SAAS,eAAe,OAAO;AAC7B,MAAI,CAAC,MAAO,QAAO;AACnB,MAAI,EAAE,OAAO,OAAO,MAAM,IAAI;AAC9B,MAAI,SAAS,CAAC,SAAS,KAAK,GAAG;AAC7B,UAAM,QAAQ,eAAe,KAAK;AAAA,EACpC;AACA,MAAI,OAAO;AACT,UAAM,QAAQ,eAAe,KAAK;AAAA,EACpC;AACA,SAAO;AACT;AAEA,IAAM,YAAY;AAClB,IAAM,WAAW;AACjB,IAAM,YAAY;AAClB,IAAM,YAAY;AAClB,IAAM,YAA4B,QAAQ,SAAS;AACnD,IAAM,WAA2B,QAAQ,QAAQ;AACjD,IAAM,cAA8B,QAAQ,SAAS;AACrD,IAAM,YAA4B,QAAQ,SAAS;AAEnD,IAAM,sBAAsB;AAC5B,IAAM,uBAAuC,QAAQ,mBAAmB;AACxE,IAAM,gBAAgC;AAAA,EACpC,sBAAsB;AACxB;AACA,SAAS,mBAAmB,OAAO;AACjC,SAAO,CAAC,CAAC,SAAS,UAAU;AAC9B;AAmBA,IAAM,kBAAkC;AAAA,EACtC;AACF;AACA,IAAM,iBAAiC;AAAA,EACrC;AACF;AACA,IAAM,oBAAoC;AAAA,EACxC;AACF;AACA,SAAS,sBAAsB,OAAO;AACpC,MAAI,SAAS,MAAM;AACjB,WAAO;AAAA,EACT;AACA,QAAM,OAAO,OAAO;AACpB,SAAO,SAAS,YAAY,SAAS,YAAY,SAAS;AAC5D;AA6CA,IAAM,4BAA4B;AAClC,SAAS,qBAAqB,KAAK,cAAc;AAC/C,SAAO,ILine 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"]
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"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,WAA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toValue", "window", "document", "timestamp", "navigator", "events", "getValue", "defaults", "toRef", "set", "onUpdated", "preventDefault", "toRefs", "now", "keys", "get", "isReadonly"]
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"type": "module"
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"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": ";AAAA,IAAI,WAAW,OAAO;AACtB,IAAI,YAAY,OAAO;AACvB,IAAI,mBAAmB,OAAO;AAC9B,IAAI,oBAAoB,OAAO;AAC/B,IAAI,eAAe,OAAO;AAC1B,IAAI,eAAe,OAAO,UAAU;AACpC,IAAI,QAAQ,CAAC,IAAI,QAAQ,SAAS,SAAS;AACzC,SAAO,OAAO,OAAO,GAAG,GAAG,kBAAkB,EAAE,EAAE,CAAC,CAAC,GAAG,KAAK,CAAC,IAAI;AAClE;AACA,IAAI,aAAa,CAAC,IAAI,QAAQ,SAAS,YAAY;AACjD,SAAO,QAAQ,GAAG,GAAG,kBAAkB,EAAE,EAAE,CAAC,CAAC,IAAI,MAAM,EAAE,SAAS,CAAC,EAAE,GAAG,SAAS,GAAG,GAAG,IAAI;AAC7F;AACA,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AChD,YAAI,MAAM,QAAQ,CAAC,EAAG,QAAO,WAAW,GAAG,KAAK;AAChD,YAAI,EAAE,gBAAgB,WAAW,UAAU,oBAAoB,IAAI,EAAE,WAAW,IAAI;AAClF,iBAAO,QAAQ,GAAG,KAAK;AAAA,QACzB;AACA,cAAM,KAAK,CAAC;AACZ,aAAK,KAAK,CAAC;AACX,gBAAQ,KAAK,EAAE;AACf,mBAAW,KAAK,GAAG;AACjB,cAAI,OAAO,eAAe,KAAK,GAAG,CAAC,MAAM,MAAO;AAChD,gBAAM,MAAM,EAAE,CAAC;AACf,cAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM;AAC3C,eAAG,CAAC,IAAI;AAAA,UACV,WAAW,IAAI,gBAAgB,WLine 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"]
|
||||
}
|
||||
@@ -1,581 +0,0 @@
|
||||
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
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"version": 3,
|
||||
"sources": [],
|
||||
"sourcesContent": [],
|
||||
"mappings": "",
|
||||
"names": []
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"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": ";;;;;;;;;;;;;;AAKA,IAAMA,qBAAqB,CACzB,sBACA,uBACA,yBACA,wBACA,uBACA,qCACA,gCACA,gCACA,iEACA,8CACA,sBAAsB;AAExB,IAAMC,oBAAoCD,mBAAmBE,KAAK,GAAG;AAErE,IAAMC,YAAY,OAAOC,YAAY;AAErC,IAAMC,UAAUF,YACZ,WAAY;AAAA,IACZC,QAAQE,UAAUD,WAClBD,QAAQE,UAAUC,qBAClBH,QAAQE,UAAUE;AAEtB,IAAMC,cACJ,CAACN,aAAaC,QAAQE,UAAUG,cAC5B,SAACC,SAAO;AAAA,MAAAC;AAAA,SAAKD,YAAAA,QAAAA,YAAOC,SAAAA,UAAAA,uBAAPD,QAASD,iBAAW,QAAAE,yBAApBA,SAAAA,SAAAA,qBAAAC,KAAAF,OAAuB;AAAC,IACrC,SAACA,SAA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AAA,WAAAC,wBAAZD,cAAc1F,mBAAa,QAAA2F,0BAAA,UAA3BA,sBAA6BE,SAASN,YAAY,KAClDrF,SAAI,QAAJA,SAAI0F,WAAAA,sBAAJ1F,KAAMF,mBAAa4F,QAAAA,wBAAA,UAAnBA,oBAAqBC,SAAS3F,IAAI;AAGpC,WAAO,CAACuF,YAAYF,cAAc;AAAA,UAAAO,YAAAC,gBAAAC;AAIhCV,iBAAW1F,YAAY2F,YAAY;AACnCA,sBAAYO,aAAGR,cAAQ,QAAAQ,eAAA,SAAA,SAARA,WAAUN;AACzBC,iLine 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
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"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": ";AAoBA,IAAqB,cAArB,MAAqB,aAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAe/B,YAAY,KAAK,UAAU,MAAM,UAAU,CAAC,GAAG,iBAAiB,KAAM;AAOpE,SAAK,MAAM;AAMX,SAAK,UAAU;AAKf,SAAK,UAAU;AAKf,SAAK,iBAAiB;AAAA,EACxB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,OAAO,QAAQ,SAAS,UAAU;AAChC,UAAM,YAAY,OAAO,aAAa,WAAW,CAAC,QAAQ,IAAI,UAC5D,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,SAAS,KAAK;AAC9C,QAAI,MAAM,OACR,UAAU;AACZ,QAAI,QAAQ,CAAC,SAAS,MAAM;AAC1B,UAAI,QAAQ,QAAQ,SAAS;AAC3B,cAAM;AACN,kBAAU,QAAQ;AAAA,MACpB;AAAA,IACF,CAAC;AACD,QAAI,KAAK,kBAAkB,MAAM,UAAU,OAAO,GAAG;AACnD,UAAI,QAAQ,SAAS,CAAC,SAAS;AAC7B,YAAI,KAAK;AAAA,UACP,KAAK;AAAA,UACL,SAAS;AAAA,QACX,CAAC;AAAA,MACH,WAAW,QAAQ,SAAS,CAAC,SAAS;AACpC,YAAI,GAAG,EAAE,UAAU;AAAA,MACrB;AACA,aAAO;AAAA,IACT;AACA,QAAI,QAAQ,OAAO;AACjB,UAAI,KAAK;AAAA,QACP,KLine truncated
|
||||
"names": ["ctx", "ifr", "node", "dct", "Mark"]
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"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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K,OAAO,GAAG;AACtC,WAAO,SAAS,SAAY,KAAK,IAAI,IAAI,IAAI;;;;;;;EAQ/C,IAAK,KAAW;AACd,UAAM,OAAO,OAAO,KAAK,OAAO,GAAG;AACnC,WAAO,SAAS,UAAa,KAAK,IAAI,IAAI;;;;;;EAO5C,OAAI;AACF,WAAO,IAAI,aAAa,MAAM,IAAI;;;;;;;;EASpC,IAAK,KAAa,OAAQ;AACxB,QAAI,OAAO,QAAQ,UAAU;AAAE,YAAM,IAAI,MAAM,sBAAsB;;AACrE,SAAK,QAAQ;AACb,UAAM,OAAO,WAAW,KAAK,OAAO,GAAG;AACvC,SAAK,IAAI,MAAM,KAAK;AACpB,WAAO;;;;;EAMT,IAAI,OAAI;AACN,QAAI,KAAK,OAAO;AAAE,aAAO,KAAK;;AAE9B,SAAK,QAAQ;AAEb,UAAM,OAAO,KAAK,QAAO;AACzB,WAAO,CAAC,KAAK,KAAI,EAAG;AAAM,WAAK,SAAU;AAEzC,WAAO,KAAK;;;;;;;;;;;;;;;;;;;;;;EAuBd,OAAQ,KAAa,IAA+B;AAClD,QAAI,OAAO,QAAQ,UAAU;AAAE,YAAM,IAAI,MAAM,sBAAsB;;AACrE,SAAK,QAAQ;AACb,UAAM,OAAO,WAAW,KAAK,OAAO,GAAG;AACvC,SAAK,IAAI,MAAM,GAAG,KAAK,IAAI,IAAI,CAAC,CAAC;AACjC,WAAO;;;;;;;;;;;;;;;;;;EAmBT,MAAO,KAAa,SAAgB;AAClC,QAAI,OAAO,QAAQ,UAAU;AAAE,YAAM,IAAI,MAAM,sBAAsB;;AACrE,SAAK,QAAQ;Line truncated
|
||||
"names": ["last", "node", "child", "key", "chunk", "promise", "conditions", "options", "results", "query", "boosts", "data"]
|
||||
}
|
||||
@@ -1,343 +0,0 @@
|
||||
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
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"version": 3,
|
||||
"sources": [],
|
||||
"sourcesContent": [],
|
||||
"mappings": "",
|
||||
"names": []
|
||||
}
|
||||
@@ -3,9 +3,17 @@ import { defineConfig } from 'vitepress'
|
||||
// https://vitepress.dev/reference/site-config
|
||||
export default defineConfig({
|
||||
title: 'FileCodeBox',
|
||||
description: '简单高效的文件分享工具',
|
||||
description: 'FileCodeBox 自托管文件与文本分享服务文档',
|
||||
lang: 'zh-CN',
|
||||
lastUpdated: true,
|
||||
cleanUrls: true,
|
||||
sitemap: {
|
||||
hostname: 'https://fcb-docs.aiuo.net',
|
||||
},
|
||||
head: [
|
||||
['meta', { name: 'theme-color', content: '#111111' }],
|
||||
['link', { rel: 'icon', href: '/logo_small.png' }],
|
||||
],
|
||||
locales: {
|
||||
root: {
|
||||
label: '简体中文',
|
||||
@@ -16,15 +24,24 @@ export default defineConfig({
|
||||
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: '了解更多',
|
||||
text: '使用指南',
|
||||
items: [
|
||||
{ text: '快速开始', link: '/guide/getting-started' },
|
||||
{ text: '上传与分享', link: '/guide/upload' },
|
||||
{ text: '管理面板', link: '/guide/management' },
|
||||
{ text: '存储配置', link: '/guide/storage' },
|
||||
],
|
||||
},
|
||||
{ text: 'API', link: '/api/' },
|
||||
{
|
||||
text: '资源',
|
||||
items: [
|
||||
{ text: '在线体验', link: 'https://share.lanol.cn' },
|
||||
{ text: '部署案例', link: '/showcase' },
|
||||
{ text: '更新日志', link: '/changelog' },
|
||||
{ text: '贡献指南', link: '/contributing' },
|
||||
{ text: 'GitHub', link: 'https://github.com/vastsa/FileCodeBox' },
|
||||
],
|
||||
},
|
||||
],
|
||||
@@ -32,7 +49,7 @@ export default defineConfig({
|
||||
sidebar: {
|
||||
'/guide/': [
|
||||
{
|
||||
text: '介绍',
|
||||
text: '开始',
|
||||
items: [
|
||||
{
|
||||
text: '什么是 FileCodeBox',
|
||||
@@ -42,7 +59,7 @@ export default defineConfig({
|
||||
],
|
||||
},
|
||||
{
|
||||
text: '基础功能',
|
||||
text: '使用',
|
||||
items: [
|
||||
{ text: '文件上传', link: '/guide/upload' },
|
||||
{ text: '文件分享', link: '/guide/share' },
|
||||
@@ -50,11 +67,12 @@ export default defineConfig({
|
||||
],
|
||||
},
|
||||
{
|
||||
text: '高级特性',
|
||||
text: '运维',
|
||||
items: [
|
||||
{ text: '存储配置', link: '/guide/storage' },
|
||||
{ text: '安全设置', link: '/guide/security' },
|
||||
{ text: '系统配置', link: '/guide/configuration' },
|
||||
{ text: '版本发布', link: '/guide/releasing' },
|
||||
],
|
||||
},
|
||||
],
|
||||
@@ -62,6 +80,8 @@ export default defineConfig({
|
||||
{
|
||||
text: 'API 参考',
|
||||
items: [
|
||||
{ text: 'API 概览', link: '/api/' },
|
||||
{ text: '预签名上传', link: '/api/presign-upload' },
|
||||
{ text: '分享接口', link: '/api/#分享接口' },
|
||||
{ text: '管理接口', link: '/api/#管理接口' },
|
||||
{ text: '错误响应', link: '/api/#错误响应' },
|
||||
@@ -82,9 +102,28 @@ export default defineConfig({
|
||||
{ icon: 'github', link: 'https://github.com/vastsa/FileCodeBox' },
|
||||
],
|
||||
footer: {
|
||||
message: '基于 LGPL-3.0 license 发布',
|
||||
message: '基于 LGPL-3.0 许可证发布',
|
||||
copyright: 'Copyright © 2022-present FileCodeBox',
|
||||
},
|
||||
editLink: {
|
||||
pattern: 'https://github.com/vastsa/FileCodeBox/edit/master/docs/:path',
|
||||
text: '在 GitHub 上编辑此页',
|
||||
},
|
||||
docFooter: {
|
||||
prev: '上一篇',
|
||||
next: '下一篇',
|
||||
},
|
||||
lastUpdated: {
|
||||
text: '最后更新',
|
||||
},
|
||||
returnToTopLabel: '返回顶部',
|
||||
skipToContentLabel: '跳转到正文',
|
||||
navMenuLabel: '导航菜单',
|
||||
langMenuLabel: '切换语言',
|
||||
sidebarMenuLabel: '文档目录',
|
||||
darkModeSwitchLabel: '外观',
|
||||
lightModeSwitchTitle: '切换到浅色模式',
|
||||
darkModeSwitchTitle: '切换到深色模式',
|
||||
search: {
|
||||
provider: 'local',
|
||||
},
|
||||
@@ -103,15 +142,24 @@ export default defineConfig({
|
||||
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',
|
||||
text: 'Guides',
|
||||
items: [
|
||||
{ text: 'Getting Started', link: '/en/guide/getting-started' },
|
||||
{ text: 'Upload & Share', link: '/en/guide/upload' },
|
||||
{ text: 'Admin Panel', link: '/en/guide/management' },
|
||||
{ text: 'Storage', link: '/en/guide/storage' },
|
||||
],
|
||||
},
|
||||
{ text: 'API', link: '/en/api/' },
|
||||
{
|
||||
text: 'Resources',
|
||||
items: [
|
||||
{ text: 'Live Demo', link: 'https://share.lanol.cn' },
|
||||
{ text: 'Showcase', link: '/en/showcase' },
|
||||
{ text: 'Changelog', link: '/en/changelog' },
|
||||
{ text: 'Contributing', link: '/en/contributing' },
|
||||
{ text: 'GitHub', link: 'https://github.com/vastsa/FileCodeBox' },
|
||||
],
|
||||
},
|
||||
],
|
||||
@@ -119,7 +167,7 @@ export default defineConfig({
|
||||
sidebar: {
|
||||
'/en/guide/': [
|
||||
{
|
||||
text: 'Introduction',
|
||||
text: 'Start',
|
||||
items: [
|
||||
{
|
||||
text: 'What is FileCodeBox',
|
||||
@@ -132,7 +180,7 @@ export default defineConfig({
|
||||
],
|
||||
},
|
||||
{
|
||||
text: 'Basic Features',
|
||||
text: 'Use',
|
||||
items: [
|
||||
{ text: 'File Upload', link: '/en/guide/upload' },
|
||||
{ text: 'File Sharing', link: '/en/guide/share' },
|
||||
@@ -140,7 +188,7 @@ export default defineConfig({
|
||||
],
|
||||
},
|
||||
{
|
||||
text: 'Advanced Features',
|
||||
text: 'Operate',
|
||||
items: [
|
||||
{ text: 'Storage Configuration', link: '/en/guide/storage' },
|
||||
{ text: 'Security Settings', link: '/en/guide/security' },
|
||||
@@ -148,6 +196,7 @@ export default defineConfig({
|
||||
text: 'System Configuration',
|
||||
link: '/en/guide/configuration',
|
||||
},
|
||||
{ text: 'Releasing', link: '/en/guide/releasing' },
|
||||
],
|
||||
},
|
||||
],
|
||||
@@ -155,6 +204,8 @@ export default defineConfig({
|
||||
{
|
||||
text: 'API Reference',
|
||||
items: [
|
||||
{ text: 'API Overview', link: '/en/api/' },
|
||||
{ text: 'Presigned Upload', link: '/en/api/presign-upload' },
|
||||
{ text: 'Share API', link: '/en/api/#share-api' },
|
||||
{ text: 'Admin API', link: '/en/api/#admin-api' },
|
||||
{ text: 'Error Response', link: '/en/api/#error-response' },
|
||||
@@ -178,12 +229,31 @@ export default defineConfig({
|
||||
message: 'Released under the LGPL-3.0 license',
|
||||
copyright: 'Copyright © 2022-present FileCodeBox',
|
||||
},
|
||||
editLink: {
|
||||
pattern: 'https://github.com/vastsa/FileCodeBox/edit/master/docs/:path',
|
||||
text: 'Edit this page on GitHub',
|
||||
},
|
||||
docFooter: {
|
||||
prev: 'Previous',
|
||||
next: 'Next',
|
||||
},
|
||||
lastUpdated: {
|
||||
text: 'Last updated',
|
||||
},
|
||||
returnToTopLabel: 'Return to top',
|
||||
skipToContentLabel: 'Skip to content',
|
||||
navMenuLabel: 'Navigation',
|
||||
langMenuLabel: 'Change language',
|
||||
sidebarMenuLabel: 'Documentation',
|
||||
darkModeSwitchLabel: 'Appearance',
|
||||
lightModeSwitchTitle: 'Switch to light theme',
|
||||
darkModeSwitchTitle: 'Switch to dark theme',
|
||||
search: {
|
||||
provider: 'local',
|
||||
},
|
||||
outline: {
|
||||
level: [2, 3],
|
||||
label: '目录',
|
||||
label: 'On this page',
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -249,5 +319,6 @@ export default defineConfig({
|
||||
level: [2, 3],
|
||||
label: '目录',
|
||||
},
|
||||
externalLinkIcon: true,
|
||||
},
|
||||
})
|
||||
@@ -1,473 +1,317 @@
|
||||
:root {
|
||||
--vp-c-brand-1: #6d5dfc;
|
||||
--vp-c-brand-2: #5848e8;
|
||||
--vp-c-brand-3: #4938ce;
|
||||
--vp-c-brand-soft: rgba(109, 93, 252, 0.12);
|
||||
--vp-c-bg: #ffffff;
|
||||
--vp-c-bg-alt: #f7f7f8;
|
||||
--vp-c-bg-soft: #f2f2f3;
|
||||
--vp-c-divider: #e8e8eb;
|
||||
--vp-c-gutter: #eeeeef;
|
||||
--vp-c-text-1: #18181b;
|
||||
--vp-c-text-2: #52525b;
|
||||
--vp-c-text-3: #71717a;
|
||||
--vp-button-brand-bg: #18181b;
|
||||
--vp-button-brand-hover-bg: #2f2f33;
|
||||
--vp-button-brand-active-bg: #09090b;
|
||||
--vp-button-brand-text: #ffffff;
|
||||
--vp-home-hero-name-color: transparent;
|
||||
--vp-home-hero-name-background: linear-gradient(120deg, #18181b 15%, #6d5dfc 85%);
|
||||
--vp-home-hero-image-background-image: radial-gradient(circle, rgba(109, 93, 252, 0.24), transparent 66%);
|
||||
--vp-home-hero-image-filter: blur(48px);
|
||||
--vp-font-family-base: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans SC", sans-serif;
|
||||
--vp-font-family-mono: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
|
||||
}
|
||||
|
||||
: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);
|
||||
.dark {
|
||||
--vp-c-brand-1: #a99fff;
|
||||
--vp-c-brand-2: #8d80ff;
|
||||
--vp-c-brand-3: #7565ff;
|
||||
--vp-c-brand-soft: rgba(169, 159, 255, 0.14);
|
||||
--vp-c-bg: #0b0b0d;
|
||||
--vp-c-bg-alt: #111114;
|
||||
--vp-c-bg-soft: #18181c;
|
||||
--vp-c-divider: #27272c;
|
||||
--vp-c-gutter: #18181c;
|
||||
--vp-c-text-1: #fafafa;
|
||||
--vp-c-text-2: #c4c4ca;
|
||||
--vp-c-text-3: #92929b;
|
||||
--vp-button-brand-bg: #f4f4f5;
|
||||
--vp-button-brand-hover-bg: #ffffff;
|
||||
--vp-button-brand-active-bg: #e4e4e7;
|
||||
--vp-button-brand-text: #18181b;
|
||||
--vp-home-hero-name-background: linear-gradient(120deg, #ffffff 12%, #a99fff 88%);
|
||||
}
|
||||
|
||||
/* --- 背景色:极简与通透 --- */
|
||||
--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 */
|
||||
html {
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
/* --- 边框与分隔 --- */
|
||||
--vp-c-border: #e2e8f0;
|
||||
--vp-c-divider: #f1f5f9;
|
||||
body {
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
/* --- 阴影:扩散柔光 --- */
|
||||
--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);
|
||||
.VPNavBar {
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--vp-c-divider) 76%, transparent);
|
||||
background: color-mix(in srgb, var(--vp-c-bg) 86%, transparent) !important;
|
||||
backdrop-filter: blur(18px) saturate(160%);
|
||||
}
|
||||
|
||||
/* --- 布局参数 --- */
|
||||
--vp-nav-height: 64px;
|
||||
--vp-sidebar-width: 280px;
|
||||
--vp-radius-default: 12px;
|
||||
--vp-radius-small: 6px;
|
||||
}
|
||||
.VPNavBarTitle .logo {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
}
|
||||
|
||||
/* * ==========================================
|
||||
* 暗黑模式重构 (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 */
|
||||
.VPNavBarTitle .title {
|
||||
font-weight: 750;
|
||||
letter-spacing: -0.03em;
|
||||
}
|
||||
|
||||
/* 边框:更细腻的深色线条 */
|
||||
--vp-c-border: #1e293b;
|
||||
--vp-c-divider: #0f172a;
|
||||
.VPNavBarMenuLink,
|
||||
.VPNavBarMenuGroup .text {
|
||||
font-size: 14px;
|
||||
font-weight: 550;
|
||||
}
|
||||
|
||||
/* 品牌色:调亮,产生荧光感 */
|
||||
--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); /* 淡淡的荧光底色 */
|
||||
.VPSidebar {
|
||||
border-right: 1px solid var(--vp-c-divider);
|
||||
background: color-mix(in srgb, var(--vp-c-bg) 96%, var(--vp-c-bg-alt));
|
||||
}
|
||||
|
||||
/* 阴影:暗色环境下的微光 */
|
||||
--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); /* 品牌色发光 */
|
||||
}
|
||||
.VPSidebarItem.level-0 > .item > .text {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--vp-c-text-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;
|
||||
}
|
||||
.VPSidebarItem.level-1 .link {
|
||||
margin: 2px 0;
|
||||
padding: 5px 10px;
|
||||
border-radius: 8px;
|
||||
transition: color 0.18s ease, background-color 0.18s ease;
|
||||
}
|
||||
|
||||
a { text-decoration: none; color: inherit; transition: color 0.2s; }
|
||||
.VPSidebarItem.level-1 .link:hover,
|
||||
.VPSidebarItem.level-1.is-active > .item .link {
|
||||
background: var(--vp-c-brand-soft);
|
||||
}
|
||||
|
||||
/* -------------------------------------------
|
||||
布局结构 (模拟 VitePress 布局)
|
||||
------------------------------------------- */
|
||||
.app-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 100vh;
|
||||
}
|
||||
.vp-doc {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
/* 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);
|
||||
}
|
||||
.vp-doc h1 {
|
||||
margin-bottom: 18px;
|
||||
font-size: clamp(32px, 5vw, 44px);
|
||||
line-height: 1.12;
|
||||
letter-spacing: -0.045em;
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
.vp-doc h2 {
|
||||
margin-top: 48px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid var(--vp-c-divider);
|
||||
letter-spacing: -0.025em;
|
||||
}
|
||||
|
||||
.nav-links {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
color: var(--vp-c-text-2);
|
||||
}
|
||||
.vp-doc h3 {
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.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); /* 激活状态发光 */
|
||||
}
|
||||
.vp-doc p,
|
||||
.vp-doc li {
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
/* 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); }
|
||||
}
|
||||
.vp-doc a {
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
|
||||
.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; }
|
||||
.vp-doc div[class*="language-"] {
|
||||
margin: 22px 0;
|
||||
border: 1px solid var(--vp-c-divider);
|
||||
border-radius: 14px;
|
||||
box-shadow: 0 14px 36px rgba(24, 24, 27, 0.06);
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
.dark .vp-doc div[class*="language-"] {
|
||||
box-shadow: 0 14px 38px rgba(0, 0, 0, 0.24);
|
||||
}
|
||||
|
||||
.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);
|
||||
}
|
||||
.vp-doc table {
|
||||
display: table;
|
||||
width: 100%;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.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); /* 左侧高亮条 */
|
||||
}
|
||||
.vp-doc th {
|
||||
background: var(--vp-c-bg-soft);
|
||||
}
|
||||
|
||||
/* 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; }
|
||||
}
|
||||
.custom-block {
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
/* 内容排版 (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));
|
||||
}
|
||||
.VPHome {
|
||||
padding-bottom: 72px !important;
|
||||
}
|
||||
|
||||
.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);
|
||||
}
|
||||
.VPHero {
|
||||
padding-top: 80px !important;
|
||||
}
|
||||
|
||||
.vp-doc p {
|
||||
line-height: 1.8;
|
||||
margin-bottom: 1.2rem;
|
||||
color: var(--vp-c-text-2);
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
.VPHero .name,
|
||||
.VPHero .text {
|
||||
letter-spacing: -0.055em;
|
||||
}
|
||||
|
||||
/* 代码块美化 */
|
||||
.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);
|
||||
}
|
||||
.VPHero .tagline {
|
||||
max-width: 620px;
|
||||
line-height: 1.65;
|
||||
}
|
||||
|
||||
/* 引用块 (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);
|
||||
}
|
||||
.VPHero .image-bg {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
/* 按钮与卡片 (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;
|
||||
}
|
||||
.VPHero .image-src {
|
||||
max-width: 250px;
|
||||
max-height: 250px;
|
||||
}
|
||||
|
||||
.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; /* 暗色模式下按钮文字用深色,因为背景亮 */
|
||||
}
|
||||
.VPButton {
|
||||
border-radius: 10px !important;
|
||||
font-weight: 650 !important;
|
||||
}
|
||||
|
||||
.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); /* 发光增强 */
|
||||
}
|
||||
.VPFeature {
|
||||
border: 1px solid var(--vp-c-divider) !important;
|
||||
border-radius: 16px !important;
|
||||
background: color-mix(in srgb, var(--vp-c-bg) 94%, var(--vp-c-bg-soft)) !important;
|
||||
transition: transform 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
.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);
|
||||
}
|
||||
.VPFeature:hover {
|
||||
transform: translateY(-3px);
|
||||
border-color: var(--vp-c-brand-1) !important;
|
||||
box-shadow: 0 18px 42px rgba(24, 24, 27, 0.08);
|
||||
}
|
||||
|
||||
/* 工具类 */
|
||||
.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;
|
||||
}
|
||||
.VPFeature .icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
border-radius: 10px;
|
||||
background: var(--vp-c-brand-soft);
|
||||
color: var(--vp-c-brand-1);
|
||||
font-family: var(--vp-font-family-mono);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.VPFeature .title {
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.VPHome .vp-doc {
|
||||
max-width: 1152px;
|
||||
margin: 36px auto 0;
|
||||
padding: 0 24px;
|
||||
}
|
||||
|
||||
.doc-paths {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 14px;
|
||||
margin: 28px 0 34px;
|
||||
}
|
||||
|
||||
.doc-path {
|
||||
display: flex;
|
||||
min-height: 154px;
|
||||
flex-direction: column;
|
||||
padding: 20px;
|
||||
border: 1px solid var(--vp-c-divider);
|
||||
border-radius: 14px;
|
||||
background: var(--vp-c-bg);
|
||||
color: var(--vp-c-text-1) !important;
|
||||
text-decoration: none !important;
|
||||
transition: transform 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
.doc-path:hover {
|
||||
transform: translateY(-3px);
|
||||
border-color: var(--vp-c-brand-1);
|
||||
box-shadow: 0 16px 36px rgba(24, 24, 27, 0.08);
|
||||
}
|
||||
|
||||
.doc-path:focus-visible {
|
||||
outline: 3px solid var(--vp-c-brand-soft);
|
||||
outline-offset: 3px;
|
||||
border-color: var(--vp-c-brand-1);
|
||||
}
|
||||
|
||||
.doc-path span {
|
||||
margin-bottom: 16px;
|
||||
color: var(--vp-c-brand-1);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.doc-path strong {
|
||||
margin-bottom: 8px;
|
||||
font-size: 17px;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.doc-path small {
|
||||
margin-top: auto;
|
||||
color: var(--vp-c-text-2);
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.VPHero {
|
||||
padding-top: 42px !important;
|
||||
}
|
||||
|
||||
.VPHero .image-src {
|
||||
max-width: 180px;
|
||||
max-height: 180px;
|
||||
}
|
||||
|
||||
.VPHome .vp-doc {
|
||||
margin-top: 20px;
|
||||
padding: 0 20px;
|
||||
}
|
||||
|
||||
.doc-paths {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.doc-path {
|
||||
min-height: 132px;
|
||||
}
|
||||
|
||||
.vp-doc table {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
html {
|
||||
scroll-behavior: auto;
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
# FileCodeBox API 文档
|
||||
|
||||
## API 版本: 2.1.0
|
||||
## API 版本: 2.5.6
|
||||
|
||||
## 目录
|
||||
- [认证](#认证)
|
||||
@@ -30,7 +30,7 @@ curl -X POST "http://localhost:12345/admin/login" \
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"message": "success",
|
||||
"detail": {
|
||||
"token": "xxx.xxx.xxx",
|
||||
"token_type": "Bearer"
|
||||
@@ -74,7 +74,7 @@ curl -X POST "http://localhost:12345/share/text/" \
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"message": "success",
|
||||
"detail": {
|
||||
"code": "abc123"
|
||||
}
|
||||
@@ -125,7 +125,7 @@ curl -X POST "http://localhost:12345/share/file/" \
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"message": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "example.txt"
|
||||
@@ -157,7 +157,7 @@ curl -L "http://localhost:12345/share/select/?code=abc123" -o downloaded_file
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"message": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "example.txt",
|
||||
@@ -184,7 +184,7 @@ curl -L "http://localhost:12345/share/select/?code=abc123" -o downloaded_file
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"message": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "example.txt",
|
||||
@@ -232,15 +232,15 @@ curl -L "http://localhost:12345/share/select/?code=abc123" -o downloaded_file
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"message": "success",
|
||||
"detail": {
|
||||
"totalFiles": 100,
|
||||
"storageUsed": "1.5GB",
|
||||
"sysUptime": "10天",
|
||||
"yesterdayCount": 50,
|
||||
"yesterdaySize": "500MB",
|
||||
"todayCount": 30,
|
||||
"todaySize": "300MB"
|
||||
"total_files": 100,
|
||||
"storage_used": "1610612736",
|
||||
"sys_uptime": 1725489600.0,
|
||||
"yesterday_count": 50,
|
||||
"yesterday_size": "524288000",
|
||||
"today_count": 30,
|
||||
"today_size": "314572800",
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -258,13 +258,15 @@ curl -L "http://localhost:12345/share/select/?code=abc123" -o downloaded_file
|
||||
| page | integer | 否 | 1 | 当前页码 |
|
||||
| size | integer | 否 | 10 | 每页数量 |
|
||||
| keyword | string | 否 | "" | 搜索关键词 |
|
||||
| sort_by | string | 否 | "created_at" | 排序字段(created_at/expired_at/name/size/used_count/code) |
|
||||
| sort_order | string | 否 | "desc" | 排序方向(asc/desc) |
|
||||
|
||||
**响应示例:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"message": "success",
|
||||
"detail": {
|
||||
"page": 1,
|
||||
"size": 10,
|
||||
|
||||
@@ -76,7 +76,6 @@ Content-Type: application/json
|
||||
"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
|
||||
}
|
||||
}
|
||||
@@ -89,7 +88,6 @@ Content-Type: application/json
|
||||
| upload_id | string | 上传会话 ID,后续操作需要 |
|
||||
| upload_url | string | 上传目标 URL |
|
||||
| mode | string | 上传模式:`direct`(直传 S3)或 `proxy`(服务器代理) |
|
||||
| save_path | string | 文件存储路径 |
|
||||
| expires_in | integer | URL 有效期(秒),默认 900 秒(15 分钟) |
|
||||
|
||||
**错误响应**
|
||||
@@ -308,7 +306,6 @@ interface PresignInitResponse {
|
||||
upload_id: string
|
||||
upload_url: string
|
||||
mode: 'direct' | 'proxy'
|
||||
save_path: string
|
||||
expires_in: number
|
||||
}
|
||||
|
||||
@@ -448,7 +445,7 @@ async function upload() {
|
||||
## 注意事项
|
||||
|
||||
1. **会话有效期**: 上传会话默认 15 分钟后过期,请在有效期内完成上传
|
||||
2. **文件大小限制**: 受系统配置 `uploadSize` 限制
|
||||
2. **文件大小限制**: 受系统配置 `upload_size` 限制
|
||||
3. **过期类型**: 支持 `day`、`hour`、`minute`、`forever`、`count`
|
||||
4. **CORS**: 直传模式下,S3 需要配置正确的 CORS 策略
|
||||
5. **重试机制**: 建议实现上传失败重试逻辑
|
||||
@@ -0,0 +1,97 @@
|
||||
# Changelog
|
||||
|
||||
## [2.6.0](https://github.com/vastsa/FileCodeBox/compare/v2.5.6...v2.6.0) (2026-09-14)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* declare missing config keys (opendal_scheme, chunk_expire_hours) and add config schema guard ([c5d525d](https://github.com/vastsa/FileCodeBox/commit/c5d525df08bb9534d1efb3ab5ff9357b52240fe9))
|
||||
* rename all config keys to snake_case with DB migration 007 ([5121db6](https://github.com/vastsa/FileCodeBox/commit/5121db6edcdac57318d058e28d7249efb9ea4d03))
|
||||
* upgrade password hashing to memory-hard scrypt with transparent rehash ([443cfe7](https://github.com/vastsa/FileCodeBox/commit/443cfe7472693bb954845f4cc4ac77e3abfcbd23))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* FileCodes.expired_count defaults to -1 (time-based) instead of instantly-expired 0 (D4) ([3c93718](https://github.com/vastsa/FileCodeBox/commit/3c93718d4b2f3a8e93978c7eb7a4a3b2553b0855))
|
||||
* save_file accepts plain binary streams; repair admin local file share (D2) ([bb95017](https://github.com/vastsa/FileCodeBox/commit/bb95017aa398e80e5eca512aa9a330aaeeceb364))
|
||||
* serialize KeyValue JSON read-modify-write sections behind a process lock (D5) ([0038636](https://github.com/vastsa/FileCodeBox/commit/0038636a2a5fc8e73f944c38789dce8de0354c3a))
|
||||
* snake_case the public config contract (D7 follow-up) ([800bac0](https://github.com/vastsa/FileCodeBox/commit/800bac01285dd6eb827e28460996997dbb80e2c3))
|
||||
* validate background config as http(s) URL to close CSS quote-breakout in 2023 theme ([4cab625](https://github.com/vastsa/FileCodeBox/commit/4cab625d5ab2fe5921f8f621ebe015623afb6fb8))
|
||||
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* cache settings refresh behind a 2s TTL, force refresh on write paths (D6) ([61d72ab](https://github.com/vastsa/FileCodeBox/commit/61d72ab6ccba5df121945ef825de2967c45888b4))
|
||||
* dashboard counters and storage quota use SQL aggregation (D3) ([baecebd](https://github.com/vastsa/FileCodeBox/commit/baecebd81efc9677acac29d5335e281d6bb5a252))
|
||||
* make is_config_initialized cheap — no scrypt on the per-request probe (D1) ([ec424dd](https://github.com/vastsa/FileCodeBox/commit/ec424dd9093d94b69ec3a118f321cd1f85c7dd54))
|
||||
|
||||
## [2.5.6](https://github.com/vastsa/FileCodeBox/compare/v2.5.5...v2.5.6) (2026-09-01)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **logging:** reduce production log noise ([5537f56](https://github.com/vastsa/FileCodeBox/commit/5537f56b884a15eda015665c67c3f8469e4e9d89))
|
||||
|
||||
## [2.5.5](https://github.com/vastsa/FileCodeBox/compare/v2.5.4...v2.5.5) (2026-08-29)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **chunk-upload:** persist sanitized filenames ([da1dd06](https://github.com/vastsa/FileCodeBox/commit/da1dd066551cc7cc9a631a0c982b5675bd4b1967))
|
||||
* harden chunk upload filename metadata ([5a7195c](https://github.com/vastsa/FileCodeBox/commit/5a7195c5c7d1028500b0e363c6b47130d260e11c))
|
||||
* sanitize chunk upload file_name to prevent path traversal ([cebac32](https://github.com/vastsa/FileCodeBox/commit/cebac32145f948bfca7c44c663a0bcdcd9c56830))
|
||||
|
||||
## [2.5.4](https://github.com/vastsa/FileCodeBox/compare/v2.5.3...v2.5.4) (2026-07-23)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* run Docker as root for volume compatibility ([fbcd4a5](https://github.com/vastsa/FileCodeBox/commit/fbcd4a5b2b788cdfc8e86d920f9c5a7299dc839a))
|
||||
* run Docker image as root for data volume compatibility ([fc0cbeb](https://github.com/vastsa/FileCodeBox/commit/fc0cbeb4f0c7485d2e7abc0501a5fd9b1456cc22))
|
||||
|
||||
## [2.5.3](https://github.com/vastsa/FileCodeBox/compare/v2.5.2...v2.5.3) (2026-07-23)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add magic-byte checks, login rate limits, and non-root Docker ([eda0a31](https://github.com/vastsa/FileCodeBox/commit/eda0a3127ab562b6a2cf828c0df4a93933c44526))
|
||||
* magic-byte file checks, admin login rate limit, non-root Docker ([0ee2f04](https://github.com/vastsa/FileCodeBox/commit/0ee2f046dd057fecceaee1059d72d67de3038f19))
|
||||
|
||||
## [2.5.2](https://github.com/vastsa/FileCodeBox/compare/v2.5.1...v2.5.2) (2026-07-23)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* harden share expiry, download token, quota SQL, and CORS ([ae77026](https://github.com/vastsa/FileCodeBox/commit/ae7702603a99dc77b9b48e78746058b2a74b0bf5))
|
||||
* harden share expiry, download token, quota SQL, and CORS ([a41693f](https://github.com/vastsa/FileCodeBox/commit/a41693f90ded0234e0883c399254319bef04924a))
|
||||
|
||||
## [2.5.1](https://github.com/vastsa/FileCodeBox/compare/v2.5.0...v2.5.1) (2026-07-21)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* patch CVE dependencies and path traversal risks ([00f3abd](https://github.com/vastsa/FileCodeBox/commit/00f3abd3b20fe2344e4dbf8d53714773e23a1050))
|
||||
|
||||
## [2.5.0](https://github.com/vastsa/FileCodeBox/compare/v2.4.0...v2.5.0) (2026-07-11)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add global storage capacity limit ([818dd47](https://github.com/vastsa/FileCodeBox/commit/818dd47b2a4136d4b0d68b2484ac2d01a7ae6a3c))
|
||||
* automate version releases ([ee8f908](https://github.com/vastsa/FileCodeBox/commit/ee8f9082ab59418a4a7721a05fc358215230981f))
|
||||
* configure admin session lifetime ([#484](https://github.com/vastsa/FileCodeBox/issues/484)) ([93ff291](https://github.com/vastsa/FileCodeBox/commit/93ff291366aaac9d04c5259d3ecf01b20aed3fd0))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* build frontend on native Docker platform ([2c51384](https://github.com/vastsa/FileCodeBox/commit/2c51384c80a9ff3f4eb98eb876759b8949dfae89))
|
||||
* harden automated release workflow ([46883c9](https://github.com/vastsa/FileCodeBox/commit/46883c90ff52894631fe53bbd9b9c4100a7b27f1))
|
||||
* harden share retrieval and admin visibility ([#482](https://github.com/vastsa/FileCodeBox/issues/482), [#480](https://github.com/vastsa/FileCodeBox/issues/480)) ([8d7d856](https://github.com/vastsa/FileCodeBox/commit/8d7d856c62d73badd0797eb4daec8d2ff10a403a))
|
||||
* resolve docs dependency audit warnings ([36300ef](https://github.com/vastsa/FileCodeBox/commit/36300ef54ee09081a6cf6a5fe4e69cee7aad0162))
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- 增加全局存储容量上限配置,并对普通上传、分片上传、预签名直传和后台文件分享统一执行并发安全的容量预留。
|
||||
- 增加存储预留迁移及过期上传清理,失败、取消或过期的上传会释放预留容量。
|
||||
@@ -1,6 +1,6 @@
|
||||
# FileCodeBox API Documentation
|
||||
|
||||
## API Version: 2.1.0
|
||||
## API Version: 2.5.6
|
||||
|
||||
## Table of Contents
|
||||
- [Authentication](#authentication)
|
||||
@@ -30,7 +30,7 @@ curl -X POST "http://localhost:12345/admin/login" \
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"message": "success",
|
||||
"detail": {
|
||||
"token": "xxx.xxx.xxx",
|
||||
"token_type": "Bearer"
|
||||
@@ -74,7 +74,7 @@ curl -X POST "http://localhost:12345/share/text/" \
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"message": "success",
|
||||
"detail": {
|
||||
"code": "abc123"
|
||||
}
|
||||
@@ -125,7 +125,7 @@ curl -X POST "http://localhost:12345/share/file/" \
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"message": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "example.txt"
|
||||
@@ -157,7 +157,7 @@ curl -L "http://localhost:12345/share/select/?code=abc123" -o downloaded_file
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"message": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "example.txt",
|
||||
@@ -184,7 +184,7 @@ Select file by share code.
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"message": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "example.txt",
|
||||
@@ -232,15 +232,15 @@ Get system dashboard data.
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"message": "success",
|
||||
"detail": {
|
||||
"totalFiles": 100,
|
||||
"storageUsed": "1.5GB",
|
||||
"sysUptime": "10 days",
|
||||
"yesterdayCount": 50,
|
||||
"yesterdaySize": "500MB",
|
||||
"todayCount": 30,
|
||||
"todaySize": "300MB"
|
||||
"total_files": 100,
|
||||
"storage_used": "1610612736",
|
||||
"sys_uptime": 1725489600.0,
|
||||
"yesterday_count": 50,
|
||||
"yesterday_size": "524288000",
|
||||
"today_count": 30,
|
||||
"today_size": "314572800",
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -258,13 +258,15 @@ Get system file list.
|
||||
| page | integer | No | 1 | Current page |
|
||||
| size | integer | No | 10 | Page size |
|
||||
| keyword | string | No | "" | Search keyword |
|
||||
| sort_by | string | No | "created_at" | Sort field(created_at/expired_at/name/size/used_count/code) |
|
||||
| sort_order | string | No | "desc" | Sort direction(asc/desc) |
|
||||
|
||||
**Response Example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"message": "success",
|
||||
"detail": {
|
||||
"page": 1,
|
||||
"size": 10,
|
||||
|
||||
@@ -0,0 +1,389 @@
|
||||
# Presigned Upload API
|
||||
|
||||
## Overview
|
||||
|
||||
The presigned upload feature provides a unified file upload interface that automatically picks the optimal upload method based on the configured storage backend:
|
||||
|
||||
- **S3 storage**: returns a presigned URL so the client uploads directly to S3 (reduces server bandwidth usage)
|
||||
- **Other storage**: returns a proxy upload URL and the file is transferred through the server
|
||||
|
||||
## Upload Flow
|
||||
|
||||
### Flow Diagram
|
||||
|
||||
```
|
||||
┌─────────┐ 1. Initialize upload ┌─────────┐
|
||||
│ Client │ ───────────────────────▶ │ Server │
|
||||
└─────────┘ └─────────┘
|
||||
│ │
|
||||
│◀──── upload_url + mode ──────────┤
|
||||
│ │
|
||||
│ ┌─────────────────────────────────────────┐
|
||||
│ │ if mode == "direct" (S3 storage) │
|
||||
│ │ 2a. PUT file to upload_url (S3) │
|
||||
│ │ 3a. POST /confirm to finish │
|
||||
│ │ │
|
||||
│ │ if mode == "proxy" (other storage) │
|
||||
│ │ 2b. PUT file to upload_url (server) │
|
||||
│ │ (share code returned automatically, │
|
||||
│ │ no confirmation needed) │
|
||||
│ └─────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
Get share code
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### 1. Initialize Upload
|
||||
|
||||
Initialize a presigned upload session and get the upload URL and mode.
|
||||
|
||||
**Request**
|
||||
|
||||
```
|
||||
POST /presign/upload/init
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
**Request Body**
|
||||
|
||||
| Field | Type | Required | Default | Description |
|
||||
| ------------ | ------- | -------- | ------- | --------------------------------------- |
|
||||
| file_name | string | ✅ | - | File name (with extension) |
|
||||
| file_size | integer | ✅ | - | File size in bytes |
|
||||
| expire_value | integer | ❌ | 1 | Expiration time value |
|
||||
| expire_style | string | ❌ | "day" | Expiration type: day/hour/minute/forever/count |
|
||||
|
||||
**Request Example**
|
||||
|
||||
```json
|
||||
{
|
||||
"file_name": "document.pdf",
|
||||
"file_size": 1048576,
|
||||
"expire_value": 7,
|
||||
"expire_style": "day"
|
||||
}
|
||||
```
|
||||
|
||||
**Response**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"upload_id": "a1b2c3d4e5f6...",
|
||||
"upload_url": "https://bucket.s3.amazonaws.com/path?X-Amz-Signature=...",
|
||||
"mode": "direct",
|
||||
"expires_in": 900
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Response Fields**
|
||||
|
||||
| Field | Type | Description |
|
||||
| ---------- | ------- | --------------------------------------------------------------- |
|
||||
| upload_id | string | Upload session ID, required by all subsequent operations |
|
||||
| upload_url | string | Target upload URL |
|
||||
| mode | string | Upload mode: `direct` (direct to S3) or `proxy` (via server) |
|
||||
| expires_in | integer | URL validity in seconds, default 900 seconds (15 minutes) |
|
||||
|
||||
In `proxy` mode the response also includes `proxy_upload_url` (and `legacy_proxy_upload_url`); `upload_url` equals the proxy URL.
|
||||
|
||||
**Error Responses**
|
||||
|
||||
| Status | Description |
|
||||
| ------ | -------------------------------------------------- |
|
||||
| 400 | Invalid expiration type |
|
||||
| 403 | File size exceeds limit / IP rate limit exceeded |
|
||||
|
||||
---
|
||||
|
||||
### 2a. Direct Mode - Upload File to S3
|
||||
|
||||
When `mode == "direct"`, the client PUTs the file directly to the returned presigned URL.
|
||||
|
||||
**Request**
|
||||
|
||||
```
|
||||
PUT {upload_url}
|
||||
Content-Type: application/octet-stream
|
||||
|
||||
[binary file content]
|
||||
```
|
||||
|
||||
**Notes**
|
||||
|
||||
- Use the returned `upload_url` as-is, do not modify it
|
||||
- `application/octet-stream` is the recommended Content-Type
|
||||
- The request goes directly to S3, it does not pass through the server
|
||||
|
||||
**JavaScript Example**
|
||||
|
||||
```javascript
|
||||
const response = await fetch(uploadUrl, {
|
||||
method: 'PUT',
|
||||
body: file,
|
||||
headers: {
|
||||
'Content-Type': 'application/octet-stream',
|
||||
},
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
// Upload succeeded, call the confirm endpoint
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2b. Proxy Mode - Upload File to Server
|
||||
|
||||
When `mode == "proxy"`, the client PUTs the file to the server proxy endpoint.
|
||||
|
||||
**Request**
|
||||
|
||||
```
|
||||
PUT /presign/upload/proxy/{upload_id}
|
||||
Content-Type: multipart/form-data
|
||||
|
||||
file: [file]
|
||||
```
|
||||
|
||||
**Path Parameters**
|
||||
|
||||
| Parameter | Description |
|
||||
| --------- | ----------------------------------------------- |
|
||||
| upload_id | Upload session ID returned by the init endpoint |
|
||||
|
||||
**Response**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"code": "123456",
|
||||
"name": "document.pdf"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Note**: In proxy mode the share code is returned immediately after upload; no confirmation call is needed.
|
||||
|
||||
**Error Responses**
|
||||
|
||||
| Status | Description |
|
||||
| ------ | ------------------------------------------------------------------ |
|
||||
| 400 | File size mismatches declared size / session does not support proxy |
|
||||
| 404 | Upload session does not exist or has expired |
|
||||
| 500 | Failed to save file |
|
||||
|
||||
---
|
||||
|
||||
### 3. Confirm Upload (direct mode only)
|
||||
|
||||
In direct mode, call this endpoint after the S3 upload completes to obtain the share code.
|
||||
|
||||
**Request**
|
||||
|
||||
```
|
||||
POST /presign/upload/confirm/{upload_id}
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
**Path Parameters**
|
||||
|
||||
| Parameter | Description |
|
||||
| --------- | ----------------------------------------------- |
|
||||
| upload_id | Upload session ID returned by the init endpoint |
|
||||
|
||||
**Response**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"code": "123456",
|
||||
"name": "document.pdf"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Error Responses**
|
||||
|
||||
| Status | Description |
|
||||
| ------ | ------------------------------------------------------------------------------- |
|
||||
| 400 | Session does not support direct confirmation |
|
||||
| 404 | Upload session does not exist or has expired / file not uploaded or upload failed |
|
||||
|
||||
---
|
||||
|
||||
### 4. Query Upload Status
|
||||
|
||||
Query the current state of an upload session.
|
||||
|
||||
**Request**
|
||||
|
||||
```
|
||||
GET /presign/upload/status/{upload_id}
|
||||
```
|
||||
|
||||
**Response**
|
||||
|
||||
```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
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Error Responses**
|
||||
|
||||
| Status | Description |
|
||||
| ------ | ---------------------------------- |
|
||||
| 404 | Upload session does not exist |
|
||||
|
||||
---
|
||||
|
||||
### 5. Cancel Upload
|
||||
|
||||
Cancel an upload session and clean up related resources.
|
||||
|
||||
**Request**
|
||||
|
||||
```
|
||||
DELETE /presign/upload/{upload_id}
|
||||
```
|
||||
|
||||
**Response**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"message": "Upload session cancelled"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Error Responses**
|
||||
|
||||
| Status | Description |
|
||||
| ------ | ---------------------------------- |
|
||||
| 404 | Upload session does not exist |
|
||||
|
||||
---
|
||||
|
||||
## Frontend Integration Example
|
||||
|
||||
### Complete Upload Flow (JavaScript/TypeScript)
|
||||
|
||||
```typescript
|
||||
interface PresignInitResponse {
|
||||
upload_id: string
|
||||
upload_url: string
|
||||
mode: 'direct' | 'proxy'
|
||||
expires_in: number
|
||||
}
|
||||
|
||||
interface UploadResult {
|
||||
code: string
|
||||
name: string
|
||||
}
|
||||
|
||||
async function uploadFile(
|
||||
file: File,
|
||||
expireValue: number = 1,
|
||||
expireStyle: string = 'day'
|
||||
): Promise<UploadResult> {
|
||||
// 1. Initialize upload
|
||||
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. Upload file based on mode
|
||||
if (mode === 'direct') {
|
||||
// Direct mode: upload to S3
|
||||
const uploadResponse = await fetch(upload_url, {
|
||||
method: 'PUT',
|
||||
body: file,
|
||||
headers: { 'Content-Type': 'application/octet-stream' },
|
||||
})
|
||||
|
||||
if (!uploadResponse.ok) {
|
||||
throw new Error('S3 upload failed')
|
||||
}
|
||||
|
||||
// 3. Confirm upload
|
||||
const confirmResponse = await fetch(
|
||||
`/presign/upload/confirm/${upload_id}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}
|
||||
)
|
||||
|
||||
const confirmData = await confirmResponse.json()
|
||||
if (confirmData.code !== 200) {
|
||||
throw new Error(confirmData.detail)
|
||||
}
|
||||
|
||||
return confirmData.detail
|
||||
} else {
|
||||
// Proxy mode: upload through the server
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// Usage example
|
||||
const file = document.querySelector('input[type="file"]').files[0]
|
||||
const result = await uploadFile(file, 7, 'day')
|
||||
console.log('Share code:', result.code)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
1. **Session validity**: upload sessions expire after 15 minutes by default; complete the upload within the window
|
||||
2. **File size limit**: bounded by the `upload_size` system setting
|
||||
3. **Expiration types**: `day`, `hour`, `minute`, `forever`, `count`
|
||||
4. **CORS**: in direct mode, S3 must have a proper CORS policy configured
|
||||
5. **Retry**: implement upload retry logic on the client side for failed uploads
|
||||
@@ -0,0 +1,8 @@
|
||||
## [Unreleased]
|
||||
|
||||
<!-- Current release: 2.6.0 x-release-please-version -->
|
||||
|
||||
### Added
|
||||
|
||||
- Added a global storage capacity limit with concurrency-safe reservations for regular, chunked, presigned, and admin file uploads.
|
||||
- Added the storage reservation migration and stale upload cleanup so failed, cancelled, or expired uploads release reserved capacity.
|
||||
@@ -1,6 +1,6 @@
|
||||
# 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.
|
||||
FileCodeBox provides rich configuration options. Prefer the admin panel; directly editing the database can introduce invalid types or break security settings.
|
||||
|
||||
## Configuration Methods
|
||||
|
||||
@@ -22,7 +22,9 @@ On first startup, the system uses default configuration from `core/settings.py`.
|
||||
| `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 |
|
||||
| `server_host` | string | `0.0.0.0` | Service listening address |
|
||||
| `server_port` | int | `12345` | Service listening port |
|
||||
| `server_workers` | int | `1` | Worker count; keep one worker for SQLite deployments |
|
||||
|
||||
### Notification Settings
|
||||
|
||||
@@ -31,7 +33,7 @@ On first startup, the system uses default configuration from `core/settings.py`.
|
||||
| `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 |
|
||||
| `robots_text` | string | `User-agent: *\nDisallow: /` | robots.txt content |
|
||||
|
||||
## Upload Settings
|
||||
|
||||
@@ -39,20 +41,21 @@ On first startup, the system uses default configuration from `core/settings.py`.
|
||||
|
||||
| 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) |
|
||||
| `open_upload` | int | `1` | Enable upload functionality (1=enabled, 0=disabled) |
|
||||
| `upload_size` | int | `10485760` | Maximum single file upload size (bytes), default 10MB |
|
||||
| `enable_chunk` | int | `0` | Enable chunked upload (1=enabled, 0=disabled) |
|
||||
| `allowed_file_types` | list | `["*"]` | Allowed extensions; `*` allows every file type |
|
||||
|
||||
::: warning Note
|
||||
`uploadSize` is in bytes. 10MB = 10 * 1024 * 1024 = 10485760 bytes
|
||||
`upload_size` 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 |
|
||||
| `upload_minute` | int | `1` | Upload limit time window (minutes) |
|
||||
| `upload_count` | int | `10` | Maximum uploads allowed within the time window |
|
||||
|
||||
Example: Default configuration allows up to 10 uploads per minute.
|
||||
|
||||
@@ -61,7 +64,7 @@ Example: Default configuration allows up to 10 uploads per minute.
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `expireStyle` | list | `["day","hour","minute","forever","count"]` | Available expiration methods |
|
||||
| `expire_style` | 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:
|
||||
@@ -77,8 +80,8 @@ Expiration methods explained:
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `themesSelect` | string | `themes/2024` | Currently active theme |
|
||||
| `themesChoices` | list | See below | Available themes list |
|
||||
| `themes_select` | string | `themes/2024` | Currently active theme |
|
||||
| `themes_choices` | list | See below | Available themes list |
|
||||
|
||||
Default available themes:
|
||||
```json
|
||||
@@ -110,7 +113,8 @@ Default available themes:
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `admin_token` | string | Set during setup | Admin login password |
|
||||
| `showAdminAddr` | int | `0` | Show admin panel entry on homepage (1=show, 0=hide) |
|
||||
| `show_admin_addr` | int | `0` | Show admin panel entry on homepage (1=show, 0=hide) |
|
||||
| `admin_session_expire` | int | `2592000` | Admin session lifetime in seconds (30 days) |
|
||||
|
||||
::: danger Security Warning
|
||||
The setup page is shown automatically while the system is uninitialized. Complete setup before exposing a production service to the public internet.
|
||||
@@ -122,8 +126,9 @@ The setup page is shown automatically while the system is uninitialized. Complet
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `errorMinute` | int | `1` | Error limit time window (minutes) |
|
||||
| `errorCount` | int | `1` | Maximum errors allowed within the time window |
|
||||
| `error_minute` | int | `1` | Error limit time window (minutes) |
|
||||
| `error_count` | int | `10` | Maximum errors allowed within the time window |
|
||||
| `trusted_proxies` | list | `[]` | Trusted reverse-proxy IPs used to resolve client addresses |
|
||||
|
||||
This setting prevents brute-force attacks on extraction codes.
|
||||
|
||||
@@ -135,6 +140,7 @@ This setting prevents brute-force attacks on extraction codes.
|
||||
|---------|------|---------|-------------|
|
||||
| `file_storage` | string | `local` | Storage backend type |
|
||||
| `storage_path` | string | `""` | Custom storage path |
|
||||
| `storage_limit` | int | `0` | Total storage quota in bytes; 0 means unlimited |
|
||||
|
||||
Supported storage types:
|
||||
- `local` - Local storage
|
||||
@@ -154,12 +160,11 @@ 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
|
||||
"upload_size": 52428800, # 50MB
|
||||
"upload_minute": 5, # 5 minutes
|
||||
"upload_count": 20, # Max 20 uploads
|
||||
"expire_style": ["day", "hour", "forever"],
|
||||
"show_admin_addr": 1
|
||||
}
|
||||
```
|
||||
|
||||
@@ -170,15 +175,14 @@ 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"],
|
||||
"upload_size": 10485760, # 10MB
|
||||
"upload_minute": 1, # 1 minute
|
||||
"upload_count": 5, # Max 5 uploads
|
||||
"error_minute": 5, # 5 minutes
|
||||
"error_count": 3, # Max 3 errors
|
||||
"expire_style": ["hour", "minute", "count"],
|
||||
"max_save_seconds": 86400, # Max retention 1 day
|
||||
"admin_token": "very-secure-password-123",
|
||||
"showAdminAddr": 0
|
||||
"show_admin_addr": 0
|
||||
}
|
||||
```
|
||||
|
||||
@@ -189,17 +193,20 @@ 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"],
|
||||
"upload_size": 1073741824, # 1GB
|
||||
"enable_chunk": 1, # Enable chunked upload
|
||||
"upload_minute": 10, # 10 minutes
|
||||
"upload_count": 100, # Max 100 uploads
|
||||
"expire_style": ["day", "forever"],
|
||||
"file_storage": "s3", # Use S3 storage
|
||||
"admin_token": "enterprise-secure-token",
|
||||
"showAdminAddr": 1
|
||||
"show_admin_addr": 1
|
||||
}
|
||||
```
|
||||
|
||||
::: warning Configuration examples
|
||||
These dictionaries illustrate combinations of values; they are not editable configuration files. Set the admin password through first-run setup or the admin panel.
|
||||
:::
|
||||
|
||||
## Next Steps
|
||||
|
||||
- [Storage Configuration](/en/guide/storage) - Learn how to configure different storage backends
|
||||
|
||||
@@ -15,12 +15,33 @@ FileCodeBox is a simple and efficient file sharing tool that supports temporary
|
||||
|
||||
## Deployment Methods
|
||||
|
||||
### Docker Deployment
|
||||
### Docker Deployment (Recommended)
|
||||
|
||||
```bash
|
||||
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:beta
|
||||
docker run -d --restart unless-stopped \
|
||||
-p 12345:12345 \
|
||||
-v fcb-data:/app/data \
|
||||
-e APP_ENV=production \
|
||||
-e LOG_LEVEL=warning \
|
||||
--log-opt max-size=10m \
|
||||
--log-opt max-file=3 \
|
||||
--name filecodebox \
|
||||
lanol/filecodebox:latest
|
||||
```
|
||||
|
||||
The named volume persists configuration and uploaded files across container upgrades.
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `HOST` | `0.0.0.0` | Service listening address |
|
||||
| `PORT` | `12345` | Service port |
|
||||
| `WORKERS` | `1` | Worker count; keep one worker for SQLite deployments |
|
||||
| `APP_ENV` | `production` (Docker) | Runtime environment; production disables HTTP access logs by default |
|
||||
| `LOG_LEVEL` | `warning` (Docker) | `debug`, `info`, `warning`, or `error` |
|
||||
| `ACCESS_LOG` | `false` (production) | Enable HTTP access logs; set to `true` when debugging requests |
|
||||
|
||||
Production deployments output only warning, error, and other key events by default. Docker retains at most three 10 MB log files.
|
||||
|
||||
### Manual Deployment
|
||||
|
||||
1. Clone the repository
|
||||
@@ -59,7 +80,7 @@ python main.py
|
||||
- Visit `http://localhost:12345/#/admin`
|
||||
- Enter the admin password set during setup
|
||||
- Enter admin panel
|
||||
- View system information, file list, user management, etc.
|
||||
- View system information, files, activity records, and configuration
|
||||
|
||||
## Next Steps
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<div align="center">
|
||||
|
||||
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/static/banners/img_1.png" alt="FileCodeBox Logo">
|
||||
<img src="/screenshots/retrieve.webp" alt="FileCodeBox" width="860" />
|
||||
|
||||
<p><em>Share text and files anonymously with a passcode, like picking up a package</em></p>
|
||||
|
||||
@@ -136,7 +136,15 @@ Command-line download
|
||||
### Docker Deployment
|
||||
|
||||
```bash
|
||||
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:beta
|
||||
docker run -d --restart unless-stopped \
|
||||
-p 12345:12345 \
|
||||
-v fcb-data:/app/data \
|
||||
-e APP_ENV=production \
|
||||
-e LOG_LEVEL=warning \
|
||||
--log-opt max-size=10m \
|
||||
--log-opt max-file=3 \
|
||||
--name filecodebox \
|
||||
lanol/filecodebox:latest
|
||||
```
|
||||
|
||||
### Manual Deployment
|
||||
@@ -218,7 +226,7 @@ npm run dev
|
||||
## ❓ FAQ
|
||||
|
||||
### Q: How to modify upload size limit?
|
||||
A: Change `uploadSize` in admin panel
|
||||
A: Change `upload_size` in admin panel
|
||||
|
||||
### Q: How to configure storage engine?
|
||||
A: Select storage engine and configure parameters in admin panel
|
||||
@@ -240,4 +248,4 @@ For more questions, visit [Wiki](https://github.com/vastsa/FileCodeBox/wiki/常
|
||||
|
||||
## 📜 Disclaimer
|
||||
|
||||
This project is open-source for learning purposes only. It should not be used for any illegal purposes. The author is not responsible for any consequences. Please retain the project address and copyright information when using it.
|
||||
This project is open-source for learning 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.
|
||||
@@ -4,6 +4,10 @@ FileCodeBox provides a fully-featured admin panel that allows administrators to
|
||||
|
||||
## Accessing the Admin Panel
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/login.webp" alt="Admin login" width="640" />
|
||||
</p>
|
||||
|
||||
### Login Method
|
||||
|
||||
The admin panel is located at the `/admin` path. Access method:
|
||||
@@ -23,10 +27,10 @@ By default, the admin panel entry is not shown on the homepage. You can control
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `showAdminAddr` | int | `0` | Show admin entry on homepage (1=show, 0=hide) |
|
||||
| `show_admin_addr` | 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.
|
||||
For public services, it's recommended to keep `show_admin_addr` at `0` and access the admin panel directly via the `/admin` path to reduce the risk of malicious scanning.
|
||||
:::
|
||||
|
||||
### Authentication Mechanism
|
||||
@@ -39,6 +43,10 @@ The admin panel uses JWT (JSON Web Token) for authentication:
|
||||
|
||||
## Dashboard
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/dashboard.webp" alt="Dashboard" width="860" />
|
||||
</p>
|
||||
|
||||
After logging in, you first see the dashboard page, which displays the overall system status.
|
||||
|
||||
### Statistics
|
||||
@@ -67,6 +75,10 @@ Storage usage is displayed in bytes. For example, `10485760` represents approxim
|
||||
|
||||
## File Management
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/files.webp" alt="File management" width="860" />
|
||||
</p>
|
||||
|
||||
### File List
|
||||
|
||||
The file management page displays all shared files in the system, supporting pagination and search.
|
||||
@@ -200,6 +212,10 @@ Local file management is useful for:
|
||||
|
||||
## System Settings
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/settings.webp" alt="System settings" width="860" />
|
||||
</p>
|
||||
|
||||
### View Configuration
|
||||
|
||||
On the system settings page, you can view the current values of all configuration items. Configuration items are grouped by category:
|
||||
@@ -224,15 +240,15 @@ Administrators can modify most configurations through the admin panel:
|
||||
| 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` |
|
||||
| Upload Settings | `upload_size`, `upload_minute`, `upload_count`, `open_upload`, `enable_chunk` |
|
||||
| Expiration Settings | `expire_style`, `max_save_seconds` |
|
||||
| Theme Settings | `themes_select`, `opacity`, `background` |
|
||||
| Security Settings | `admin_token`, `show_admin_addr`, `error_minute`, `error_count` |
|
||||
| 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
|
||||
- `themes_choices` (theme list) cannot be modified through the admin panel
|
||||
- After modifying storage settings, existing files will not be automatically migrated
|
||||
:::
|
||||
|
||||
@@ -366,7 +382,7 @@ Content-Type: application/json
|
||||
|
||||
{
|
||||
"admin_token": "new-password",
|
||||
"uploadSize": 52428800
|
||||
"upload_size": 52428800
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# Releasing
|
||||
|
||||
The project uses Semantic Versioning and Conventional Commits.
|
||||
|
||||
Complete these settings once in the backend GitHub repository:
|
||||
|
||||
- In `Settings → Actions → General → Workflow permissions`, grant read/write
|
||||
access and allow GitHub Actions to create pull requests. The frontend repository
|
||||
only needs the default read-only Actions permission.
|
||||
- Keep squash merging enabled. The release workflow waits for required checks
|
||||
before merging the release pull request.
|
||||
- Add `DOCKER_USERNAME` and `DOCKER_PASSWORD` Actions secrets to the backend repository.
|
||||
|
||||
1. Merge commits using Conventional Commit types such as `feat:` and `fix:` into the default branch.
|
||||
2. Release Please creates and merges the release pull request and updates `VERSION` and the changelog.
|
||||
3. The workflow then creates `vX.Y.Z`, a GitHub Release, and dispatches the production image build.
|
||||
4. Releases publish `X.Y.Z`, `X.Y`, and `latest`; branches publish `dev` or `edge-*` images.
|
||||
5. Each image build resolves the latest commit from both frontend default branches automatically.
|
||||
|
||||
Every `fix:`, `feat:`, or breaking change merged into the default branch therefore
|
||||
creates a Patch, Minor, or Major release automatically. Non-release commits such
|
||||
as `docs:` and `chore:` do not publish a release on their own.
|
||||
|
||||
The backend runtime version comes from `VERSION`. Container branch builds inject a
|
||||
commit-qualified development version through `APP_VERSION`; release tags must exactly
|
||||
match `VERSION`. OCI image labels record the resolved backend and frontend commits for traceability.
|
||||
@@ -10,9 +10,7 @@ FileCodeBox provides multiple layers of security mechanisms to protect your file
|
||||
FileCodeBox does not ship with a default admin password. Open the site in your browser on first run and set the admin password on the setup page.
|
||||
:::
|
||||
|
||||
There are two ways to change the admin password:
|
||||
|
||||
**Method 1: Via Admin Panel (Recommended)**
|
||||
Change the admin password through the admin panel:
|
||||
|
||||
1. Access `/admin` to enter the admin panel
|
||||
2. Log in with the current password
|
||||
@@ -20,9 +18,7 @@ There are two ways to change the admin password:
|
||||
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.
|
||||
`admin_token` is stored as a password hash. Do not write a plaintext password to the database, or admin login will stop working.
|
||||
|
||||
### Password Security Recommendations
|
||||
|
||||
@@ -38,14 +34,14 @@ Configuration is stored in the `keyvalue` table of the `data/filecodebox.db` dat
|
||||
|
||||
### 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:
|
||||
By default, the admin panel entry is hidden. You can control whether to show the admin entry on the homepage via the `show_admin_addr` configuration:
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `showAdminAddr` | int | `0` | Show admin entry (1=show, 0=hide) |
|
||||
| `show_admin_addr` | 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.
|
||||
For public services, it's recommended to keep `show_admin_addr` at `0` and access the admin panel directly via the `/admin` path.
|
||||
:::
|
||||
|
||||
## IP Rate Limiting
|
||||
@@ -58,12 +54,12 @@ 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 |
|
||||
| `upload_minute` | int | `1` | Upload limit time window (minutes) |
|
||||
| `upload_count` | 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
|
||||
- When an IP's upload count reaches `upload_count` within `upload_minute` minutes
|
||||
- Subsequent upload requests from that IP will be rejected with HTTP 423 error
|
||||
- Counter resets after the time window expires
|
||||
|
||||
@@ -72,14 +68,14 @@ Limit the number of uploads from a single IP within a specified time:
|
||||
```python
|
||||
# Relaxed configuration: Max 20 uploads in 5 minutes
|
||||
{
|
||||
"uploadMinute": 5,
|
||||
"uploadCount": 20
|
||||
"upload_minute": 5,
|
||||
"upload_count": 20
|
||||
}
|
||||
|
||||
# Strict configuration: Max 3 uploads in 1 minute
|
||||
{
|
||||
"uploadMinute": 1,
|
||||
"uploadCount": 3
|
||||
"upload_minute": 1,
|
||||
"upload_count": 3
|
||||
}
|
||||
```
|
||||
|
||||
@@ -90,13 +86,13 @@ Limit the number of error attempts from a single IP to prevent brute-force attac
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `errorMinute` | int | `1` | Error limit time window (minutes) |
|
||||
| `errorCount` | int | `1` | Maximum errors allowed within the time window |
|
||||
| `error_minute` | int | `1` | Error limit time window (minutes) |
|
||||
| `error_count` | int | `10` | 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
|
||||
- When error count reaches `error_count`, that IP will be temporarily locked
|
||||
- Lock duration is `error_minute` minutes
|
||||
- During lockout, all extraction requests from that IP will be rejected
|
||||
|
||||
**Configuration example:**
|
||||
@@ -104,13 +100,13 @@ Limit the number of error attempts from a single IP to prevent brute-force attac
|
||||
```python
|
||||
# Anti-brute-force configuration: Max 3 errors in 5 minutes
|
||||
{
|
||||
"errorMinute": 5,
|
||||
"errorCount": 3
|
||||
"error_minute": 5,
|
||||
"error_count": 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.
|
||||
The default allows up to 10 errors per IP each minute. Public services can tighten this limit while accounting for users behind shared network addresses.
|
||||
:::
|
||||
|
||||
## Upload Restrictions
|
||||
@@ -119,8 +115,8 @@ The default configuration `errorMinute=1, errorCount=1` is very strict, meaning
|
||||
|
||||
| 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) |
|
||||
| `upload_size` | int | `10485760` | Maximum single file upload size (bytes), default 10MB |
|
||||
| `open_upload` | int | `1` | Enable upload functionality (1=enabled, 0=disabled) |
|
||||
|
||||
**Common size conversions:**
|
||||
- 10MB = 10 * 1024 * 1024 = `10485760`
|
||||
@@ -134,7 +130,7 @@ Through file expiration mechanisms, you can automatically clean up expired files
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `expireStyle` | list | `["day","hour","minute","forever","count"]` | Available expiration methods |
|
||||
| `expire_style` | 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:**
|
||||
@@ -154,7 +150,7 @@ For public services, it's recommended to:
|
||||
```python
|
||||
# Recommended configuration for public services
|
||||
{
|
||||
"expireStyle": ["hour", "minute", "count"],
|
||||
"expire_style": ["hour", "minute", "count"],
|
||||
"max_save_seconds": 86400 # Max retention 1 day
|
||||
}
|
||||
```
|
||||
@@ -165,7 +161,7 @@ In some cases, you may need to temporarily disable upload functionality:
|
||||
|
||||
```python
|
||||
{
|
||||
"openUpload": 0 # Disable upload functionality
|
||||
"open_upload": 0 # Disable upload functionality
|
||||
}
|
||||
```
|
||||
|
||||
@@ -201,7 +197,7 @@ server {
|
||||
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)
|
||||
# Limit request body size (match upload_size configuration)
|
||||
client_max_body_size 100M;
|
||||
|
||||
# Pass real IP
|
||||
@@ -240,7 +236,7 @@ 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's `client_max_body_size` should match or be slightly larger than FileCodeBox's `upload_size` configuration:
|
||||
|
||||
```nginx
|
||||
client_max_body_size 100M; # Allow max 100MB uploads
|
||||
@@ -273,7 +269,7 @@ your-domain.com {
|
||||
Before deploying FileCodeBox, confirm the following security configurations:
|
||||
|
||||
- [ ] Completed first-run setup and set the admin password `admin_token`
|
||||
- [ ] Hidden admin entry `showAdminAddr: 0`
|
||||
- [ ] Hidden admin entry `show_admin_addr: 0`
|
||||
- [ ] Configured appropriate upload rate limiting
|
||||
- [ ] Configured error rate limiting to prevent brute-force attacks
|
||||
- [ ] Set reasonable file size limits
|
||||
@@ -289,15 +285,15 @@ Before deploying FileCodeBox, confirm the following security configurations:
|
||||
```python
|
||||
{
|
||||
"admin_token": "your-very-secure-password",
|
||||
"showAdminAddr": 0,
|
||||
"uploadSize": 10485760, # 10MB
|
||||
"uploadMinute": 1,
|
||||
"uploadCount": 5,
|
||||
"errorMinute": 5,
|
||||
"errorCount": 3,
|
||||
"expireStyle": ["hour", "minute", "count"],
|
||||
"show_admin_addr": 0,
|
||||
"upload_size": 10485760, # 10MB
|
||||
"upload_minute": 1,
|
||||
"upload_count": 5,
|
||||
"error_minute": 5,
|
||||
"error_count": 3,
|
||||
"expire_style": ["hour", "minute", "count"],
|
||||
"max_save_seconds": 86400, # Max 1 day
|
||||
"openUpload": 1
|
||||
"open_upload": 1
|
||||
}
|
||||
```
|
||||
|
||||
@@ -306,15 +302,15 @@ Before deploying FileCodeBox, confirm the following security configurations:
|
||||
```python
|
||||
{
|
||||
"admin_token": "internal-secure-password",
|
||||
"showAdminAddr": 1,
|
||||
"uploadSize": 104857600, # 100MB
|
||||
"uploadMinute": 5,
|
||||
"uploadCount": 50,
|
||||
"errorMinute": 1,
|
||||
"errorCount": 5,
|
||||
"expireStyle": ["day", "hour", "forever"],
|
||||
"show_admin_addr": 1,
|
||||
"upload_size": 104857600, # 100MB
|
||||
"upload_minute": 5,
|
||||
"upload_count": 50,
|
||||
"error_minute": 1,
|
||||
"error_count": 5,
|
||||
"expire_style": ["day", "hour", "forever"],
|
||||
"max_save_seconds": 0, # No limit
|
||||
"openUpload": 1
|
||||
"open_upload": 1
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -4,6 +4,10 @@ FileCodeBox provides simple and easy-to-use file and text sharing functionality.
|
||||
|
||||
## Sharing Methods
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/send.webp" alt="Send page" width="720" />
|
||||
</p>
|
||||
|
||||
FileCodeBox supports two sharing methods:
|
||||
|
||||
1. **Text Sharing** - Share text content directly, suitable for code snippets, configuration files, etc.
|
||||
@@ -62,10 +66,10 @@ Response example:
|
||||
|
||||
### File Size Limit
|
||||
|
||||
The default maximum single file upload size is **10MB**. Administrators can modify this limit via the `uploadSize` configuration.
|
||||
The default maximum single file upload size is **10MB**. Administrators can modify this limit via the `upload_size` configuration.
|
||||
|
||||
::: tip Tip
|
||||
If you need to upload large files, contact the administrator to enable chunked upload functionality or adjust the `uploadSize` configuration.
|
||||
If you need to upload large files, contact the administrator to enable chunked upload functionality or adjust the `upload_size` configuration.
|
||||
:::
|
||||
|
||||
### Supported Upload Methods
|
||||
@@ -112,7 +116,7 @@ FileCodeBox supports multiple flexible expiration methods:
|
||||
| By Count | `count` | File expires after specified download count |
|
||||
|
||||
::: info Note
|
||||
- Administrators can control available expiration methods via the `expireStyle` configuration
|
||||
- Administrators can control available expiration methods via the `expire_style` configuration
|
||||
- Administrators can limit maximum file retention time via the `max_save_seconds` configuration
|
||||
:::
|
||||
|
||||
@@ -137,6 +141,10 @@ expire_value=5, expire_style=count
|
||||
|
||||
## Retrieving Files
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/retrieve.webp" alt="Retrieve page" width="720" />
|
||||
</p>
|
||||
|
||||
### How to Use
|
||||
|
||||
1. Enter the extraction code in the "Retrieve File" area on the homepage
|
||||
@@ -200,7 +208,7 @@ 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`).
|
||||
For large file uploads, FileCodeBox supports chunked upload functionality. This feature requires administrator enablement (`enable_chunk=1`).
|
||||
|
||||
### Chunked Upload Flow
|
||||
|
||||
|
||||
@@ -4,6 +4,10 @@ FileCodeBox provides multiple flexible file upload methods, supporting both regu
|
||||
|
||||
## Upload Methods
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/send.webp" alt="Upload and send page" width="720" />
|
||||
</p>
|
||||
|
||||
FileCodeBox supports the following upload methods:
|
||||
|
||||
### Drag and Drop Upload
|
||||
@@ -47,7 +51,7 @@ Paste upload only supports image formats, not other file types. Specific support
|
||||
|
||||
| Setting | Default | Description |
|
||||
|---------|---------|-------------|
|
||||
| `uploadSize` | 10MB | Maximum single file upload size |
|
||||
| `upload_size` | 10MB | Maximum single file upload size |
|
||||
|
||||
### Modify Upload Limits
|
||||
|
||||
@@ -55,11 +59,11 @@ Administrators can modify upload size limits through the admin panel or configur
|
||||
|
||||
```python
|
||||
# Set maximum upload size to 100MB
|
||||
uploadSize = 104857600 # 100 * 1024 * 1024
|
||||
upload_size = 104857600 # 100 * 1024 * 1024
|
||||
```
|
||||
|
||||
::: info Note
|
||||
`uploadSize` is in bytes. Common conversions:
|
||||
`upload_size` is in bytes. Common conversions:
|
||||
- 10MB = 10485760
|
||||
- 50MB = 52428800
|
||||
- 100MB = 104857600
|
||||
@@ -143,7 +147,7 @@ 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:
|
||||
If guest upload is disabled in admin panel (`open_upload=0`), you need to login first:
|
||||
|
||||
```bash
|
||||
# 1. Login to get token
|
||||
@@ -171,7 +175,7 @@ curl -X POST "http://localhost:12345/share/text/" \
|
||||
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 functionality requires administrator enablement: `enable_chunk=1`
|
||||
:::
|
||||
|
||||
### Chunked Upload Flow
|
||||
@@ -359,7 +363,7 @@ await fetch(`/chunk/upload/complete/${upload_id}`, {
|
||||
|
||||
| HTTP Status | Error Message | Cause | Solution |
|
||||
|-------------|---------------|-------|----------|
|
||||
| 403 | Size exceeds limit | File exceeds `uploadSize` limit | Reduce file size or contact administrator to adjust limit |
|
||||
| 403 | Size exceeds limit | File exceeds `upload_size` 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 |
|
||||
@@ -372,8 +376,8 @@ 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 |
|
||||
| `upload_minute` | 1 | Limit time window (minutes) |
|
||||
| `upload_count` | 10 | Maximum uploads within time window |
|
||||
|
||||
When rate limit is exceeded, you need to wait for the time window to pass before continuing uploads.
|
||||
|
||||
@@ -391,26 +395,26 @@ When rate limit is exceeded, you need to wait for the time window to pass before
|
||||
|
||||
| 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 |
|
||||
| `open_upload` | int | 1 | Enable upload (1=enabled, 0=disabled) |
|
||||
| `upload_size` | int | 10485760 | Maximum upload size (bytes) |
|
||||
| `enable_chunk` | int | 0 | Enable chunked upload (1=enabled, 0=disabled) |
|
||||
| `upload_minute` | int | 1 | Upload rate limit time window (minutes) |
|
||||
| `upload_count` | int | 10 | Maximum uploads within time window |
|
||||
| `expire_style` | list | ["day","hour","minute","forever","count"] | Allowed expiration methods |
|
||||
|
||||
### Configuration Example
|
||||
|
||||
```python
|
||||
# Allow 100MB file uploads, enable chunked upload
|
||||
uploadSize = 104857600
|
||||
enableChunk = 1
|
||||
upload_size = 104857600
|
||||
enable_chunk = 1
|
||||
|
||||
# Relax upload rate limit: max 50 uploads per 5 minutes
|
||||
uploadMinute = 5
|
||||
uploadCount = 50
|
||||
upload_minute = 5
|
||||
upload_count = 50
|
||||
|
||||
# Only allow expiration by days and count
|
||||
expireStyle = ["day", "count"]
|
||||
expire_style = ["day", "count"]
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
@@ -3,8 +3,8 @@ layout: home
|
||||
|
||||
hero:
|
||||
name: "FileCodeBox"
|
||||
text: "File Express Box"
|
||||
tagline: Share text and files anonymously with access codes, just like picking up a package
|
||||
text: "Share files like picking up a package"
|
||||
tagline: A lightweight, modern, self-hosted service for files and text
|
||||
image:
|
||||
src: /logo_small.png
|
||||
alt: FileCodeBox
|
||||
@@ -16,26 +16,75 @@ hero:
|
||||
text: Live Demo
|
||||
link: https://share.lanol.cn
|
||||
- theme: alt
|
||||
text: View on GitHub
|
||||
link: https://github.com/vastsa/FileCodeBox
|
||||
text: Deployment Guide
|
||||
link: /en/guide/getting-started#docker-deployment-recommended
|
||||
|
||||
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
|
||||
---
|
||||
- icon: 01
|
||||
title: Share instantly
|
||||
details: Files and text in one flow, with batch, chunked, and resumable uploads
|
||||
- icon: 02
|
||||
title: Flexible expiry
|
||||
details: Expire by time or retrieval count, or keep content permanently
|
||||
- icon: 03
|
||||
title: Own your data
|
||||
details: Local, S3, OneDrive, WebDAV, and OpenDAL storage
|
||||
---
|
||||
|
||||
## Start in 30 seconds
|
||||
|
||||
```bash
|
||||
docker run -d --restart unless-stopped \
|
||||
-p 12345:12345 \
|
||||
-v ./data:/app/data \
|
||||
-e APP_ENV=production \
|
||||
-e LOG_LEVEL=warning \
|
||||
--log-opt max-size=10m \
|
||||
--log-opt max-file=3 \
|
||||
--name filecodebox \
|
||||
lanol/filecodebox:2.6.0 # x-release-please-version
|
||||
```
|
||||
|
||||
Open `http://localhost:12345` and complete the first-run setup.
|
||||
|
||||
<div class="doc-paths">
|
||||
<a class="doc-path" href="/en/guide/getting-started">
|
||||
<span>Get started</span>
|
||||
<strong>Deploy, initialize, and upgrade</strong>
|
||||
<small>Run FileCodeBox from a clean server →</small>
|
||||
</a>
|
||||
<a class="doc-path" href="/en/guide/storage">
|
||||
<span>Operate</span>
|
||||
<strong>Storage, configuration, and security</strong>
|
||||
<small>Choose production-ready storage and protection →</small>
|
||||
</a>
|
||||
<a class="doc-path" href="/en/api/">
|
||||
<span>Integrate</span>
|
||||
<strong>API and upload workflows</strong>
|
||||
<small>Build on sharing, chunked uploads, and administration →</small>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
## Interface preview
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/retrieve.webp" alt="Retrieve files" width="860" />
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="/screenshots/send.webp" alt="Send files" width="48%" />
|
||||
|
||||
<img src="/screenshots/dashboard.webp" alt="Admin dashboard" width="48%" />
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="33%"><img src="/screenshots/login.webp" alt="Admin login" /></td>
|
||||
<td width="33%"><img src="/screenshots/files.webp" alt="File management" /></td>
|
||||
<td width="33%"><img src="/screenshots/settings.webp" alt="System settings" /></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
::: warning Responsible use
|
||||
Use FileCodeBox only for lawful file and text sharing. Operators are responsible for deployment security, data compliance, and content moderation.
|
||||
:::
|
||||