Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d3e4ad904 | ||
|
|
381a539c92 | ||
|
|
6f88eae854 | ||
|
|
5da611c5de | ||
|
|
a578fc690c | ||
|
|
2073f9ba4b | ||
|
|
0a1f08fd6e | ||
|
|
9bf03bc427 | ||
|
|
264eb4f986 | ||
|
|
c973d28256 | ||
|
|
e7f761c35f | ||
|
|
8f7a1e1594 | ||
|
|
4f141eeb49 | ||
|
|
496a7139bd | ||
|
|
5b5d70c3b7 | ||
|
|
ec714dcd6f | ||
|
|
588af7b6c3 | ||
|
|
080fecf653 | ||
|
|
3d2c8ec709 | ||
|
|
f1fee1edff | ||
|
|
65f4929d40 | ||
|
|
40f22de7f8 | ||
|
|
da374b4595 | ||
|
|
d3f9e7902c | ||
|
|
2f5eab18b1 | ||
|
|
6bb1ef06c1 | ||
|
|
63e72c1455 | ||
|
|
648d578d53 | ||
|
|
031d300cae | ||
|
|
57c75a7141 | ||
|
|
82555c08ed | ||
|
|
93a30a257c | ||
|
|
3c135eb29f | ||
|
|
0d82fbe26a | ||
|
|
eb2db8f507 | ||
|
|
fda470b076 | ||
|
|
41e3ce1b9c | ||
|
|
31027e6eea | ||
|
|
d0f08a7be5 | ||
|
|
5646f41255 | ||
|
|
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 | ||
|
|
cdaf3638b8 | ||
|
|
1b6d8e7277 | ||
|
|
eb6fc627ae | ||
|
|
c1fb802223 | ||
|
|
1d03337e2f | ||
|
|
8d6eaacb70 | ||
|
|
3fe136536e | ||
|
|
aa6904a12c | ||
|
|
135dfdda9d | ||
|
|
e3ea7825bf | ||
|
|
6759539078 | ||
|
|
530f52aa1e | ||
|
|
b859ec211e | ||
|
|
8ac367d0b8 | ||
|
|
63cf725802 | ||
|
|
ccbc710d74 | ||
|
|
2d18b02005 | ||
|
|
e75fe596d0 | ||
|
|
be7ce2b30e | ||
|
|
0dbb594f4a | ||
|
|
b6aa28c345 | ||
|
|
fc6046a663 | ||
|
|
3467e973ac | ||
|
|
a1de598277 | ||
|
|
1ba0d2a044 | ||
|
|
1f0b0b791c | ||
|
|
4ae53fc4a5 | ||
|
|
35e069ccc3 | ||
|
|
2fa1faebe0 | ||
|
|
0ced9b1f38 | ||
|
|
1eb69e4cc5 | ||
|
|
71fc1ad8ea | ||
|
|
64ebc59a84 | ||
|
|
78b1dbe81f | ||
|
|
6805206efd | ||
|
|
6fe68be2dd | ||
|
|
0d71b914e4 | ||
|
|
20fcf0c3df | ||
|
|
75d345e5d0 | ||
|
|
a0c453b014 | ||
|
|
1cc901d2b9 | ||
|
|
e7b5792602 | ||
|
|
843a237fad | ||
|
|
4a9bf3a3a0 | ||
|
|
0504e6e4dc | ||
|
|
24d49e1c9a | ||
|
|
c380778336 | ||
|
|
f1c09b0b20 | ||
|
|
a3f599fe51 | ||
|
|
2e5dc532a0 | ||
|
|
7f46c58898 | ||
|
|
5a889bab47 | ||
|
|
5fee1c7b86 | ||
|
|
73017935e9 | ||
|
|
a35b3c8262 | ||
|
|
da5dc378a7 | ||
|
|
d170ca8005 | ||
|
|
0fe01c98db | ||
|
|
d5b0327f90 | ||
|
|
9120486449 | ||
|
|
f5a5e03269 | ||
|
|
ade5799db4 | ||
|
|
6b728abbeb | ||
|
|
ff1943d60c | ||
|
|
442ef5b0e0 | ||
|
|
34e36944bd | ||
|
|
ba8802ad75 | ||
|
|
bf43727531 | ||
|
|
d49a61d06e | ||
|
|
3074d9ba2e | ||
|
|
81ee640353 | ||
|
|
e87bcfcce5 | ||
|
|
e80be564a5 | ||
|
|
69972e28b3 | ||
|
|
8cdb972583 | ||
|
|
736e16a9f6 | ||
|
|
8e57a497f7 | ||
|
|
287d9aeedb | ||
|
|
f1a16a115a | ||
|
|
b2bfc045c2 | ||
|
|
900541baa5 | ||
|
|
8b813a2eaa | ||
|
|
4920b4b5db | ||
|
|
268f1537bb | ||
|
|
41b01b3faa | ||
|
|
c02fb7ce20 | ||
|
|
95f5e0dfbc | ||
|
|
e854eb068c | ||
|
|
c1966b3942 | ||
|
|
a20a0beb79 | ||
|
|
d7200f6b9b | ||
|
|
bd6f646f5d | ||
|
|
6eac746e83 | ||
|
|
5f82650c36 | ||
|
|
d3fe7b223e | ||
|
|
2d79fa5acd | ||
|
|
387f023372 | ||
|
|
e51380003c | ||
|
|
e41b3e1688 | ||
|
|
7be3b27415 | ||
|
|
bdab5bb375 | ||
|
|
c0984bfb1f | ||
|
|
62d1a23695 | ||
|
|
9a80d7a9e0 | ||
|
|
eeb70c7f44 | ||
|
|
136ea5830f | ||
|
|
c430af3d82 | ||
|
|
6fcf26fcbe | ||
|
|
f6649ecc81 | ||
|
|
3005ed1298 | ||
|
|
a23409f0af | ||
|
|
f7876c6e48 | ||
|
|
7c6aedb96e | ||
|
|
7ed09e2455 | ||
|
|
9f8e6d401f | ||
|
|
c4304d3525 | ||
|
|
e92ff30d8c | ||
|
|
fd913ababc | ||
|
|
45be97a258 | ||
|
|
fbd741ebcf | ||
|
|
e341e1afae | ||
|
|
4037ddb3b1 | ||
|
|
72190331b9 | ||
|
|
566dc3b94f | ||
|
|
cf96071167 | ||
|
|
ffe89060f4 | ||
|
|
79c1e0f949 | ||
|
|
df6722ac26 | ||
|
|
e897dbfe97 | ||
|
|
168ca8383f | ||
|
|
4d1cd4cbfc | ||
|
|
c61c2ee7fe | ||
|
|
548d625827 | ||
|
|
792f7a8a12 | ||
|
|
a65cf32214 | ||
|
|
4a50908455 | ||
|
|
c4e398bd31 | ||
|
|
39264cc32e | ||
|
|
7a15b6a44d | ||
|
|
591441e9a7 | ||
|
|
60756749b7 | ||
|
|
fdada809d9 |
No files matched your search
@@ -1,3 +1,50 @@
|
||||
*.md
|
||||
.idea
|
||||
# Git
|
||||
.git
|
||||
.gitignore
|
||||
.gitattributes
|
||||
|
||||
# IDE
|
||||
.idea
|
||||
.vscode
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# Documentation
|
||||
*.md
|
||||
docs/
|
||||
LICENSE
|
||||
|
||||
# Development
|
||||
.venv
|
||||
__pycache__
|
||||
*.pyc
|
||||
*.pyo
|
||||
.pytest_cache
|
||||
.coverage
|
||||
htmlcov/
|
||||
|
||||
# macOS
|
||||
.DS_Store
|
||||
._*
|
||||
|
||||
# Frontend source (will be built from GitHub)
|
||||
fcb-fronted/
|
||||
themes/
|
||||
|
||||
# Test files
|
||||
test_*.py
|
||||
tests/
|
||||
|
||||
# Data (should be mounted as volume)
|
||||
data/
|
||||
|
||||
# GitHub
|
||||
.github/
|
||||
|
||||
# Docker
|
||||
Dockerfile
|
||||
docker-compose.yml
|
||||
.dockerignore
|
||||
|
||||
# Claude
|
||||
.claude/
|
||||
@@ -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,67 @@
|
||||
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 'moto[s3,server]' mypy
|
||||
|
||||
- name: Ruff
|
||||
run: pipx run ruff==0.16.6 check .
|
||||
|
||||
- name: Mypy ratchet (new type errors are rejected; fix and run
|
||||
scripts/mypy_ratchet.py --regenerate to tighten the baseline)
|
||||
run: python scripts/mypy_ratchet.py
|
||||
|
||||
- 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.]+)(?:\s*;[^#\n]*)?$', 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,49 +2,124 @@ 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
|
||||
- dev
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
env:
|
||||
REGISTRY_IMAGE: ${{ secrets.DOCKER_USERNAME }}/filecodebox
|
||||
|
||||
jobs:
|
||||
buildx:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ inputs.release_tag || github.ref }}
|
||||
submodules: true
|
||||
|
||||
- name: Extract metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY_IMAGE }}
|
||||
flavor: |
|
||||
latest=false
|
||||
tags: |
|
||||
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=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@v2
|
||||
uses: docker/setup-qemu-action@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
|
||||
- name: Cache Docker layers
|
||||
uses: actions/cache@v3
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
path: /tmp/.buildx-cache
|
||||
key: ${{ runner.os }}-buildx-${{ github.sha }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-buildx-
|
||||
driver-opts: |
|
||||
image=moby/buildkit:latest
|
||||
network=host
|
||||
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@v2
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v4
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ secrets.DOCKER_USERNAME }}/filecodebox:latest
|
||||
cache-from: type=local,src=/tmp/.buildx-cache
|
||||
cache-to: type=local,dest=/tmp/.buildx-cache-new,mode=max
|
||||
- name: Move cache
|
||||
run: |
|
||||
rm -rf /tmp/.buildx-cache
|
||||
mv /tmp/.buildx-cache-new /tmp/.buildx-cache
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
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
|
||||
@@ -37,13 +37,13 @@ jobs:
|
||||
version: 9
|
||||
# - uses: oven-sh/setup-bun@v1 # 如果使用 Bun,请取消注释
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 20
|
||||
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
|
||||
@@ -51,7 +51,7 @@ jobs:
|
||||
working-directory: docs
|
||||
run: pnpm run docs:build
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
uses: actions/upload-pages-artifact@v5
|
||||
with:
|
||||
path: docs/.vitepress/dist
|
||||
|
||||
|
||||
@@ -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@v5
|
||||
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,10 +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/
|
||||
@@ -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.8.5"
|
||||
}
|
||||
@@ -1,24 +1,86 @@
|
||||
FROM python:3.9.5-slim-buster
|
||||
# 第一阶段:构建前端主题
|
||||
# 前端产物与 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++
|
||||
|
||||
RUN corepack enable && \
|
||||
corepack prepare pnpm@9.15.9 --activate
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
# 克隆并构建固定版本的 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 && \
|
||||
VITE_GIT_COMMIT="$(git rev-parse HEAD)" pnpm run build
|
||||
|
||||
# 克隆并构建固定版本的 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}"
|
||||
|
||||
# 将当前目录下的文件复制到容器的 /app 目录
|
||||
COPY . /app
|
||||
|
||||
# 设置时区为亚洲/上海
|
||||
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone
|
||||
|
||||
# 设置工作目录
|
||||
WORKDIR /app
|
||||
|
||||
# 删除不必要的目录,减少镜像体积
|
||||
RUN rm -rf docs fcb-fronted
|
||||
# 复制项目文件(通过 .dockerignore 排除不必要的文件)
|
||||
COPY . .
|
||||
|
||||
# 安装依赖
|
||||
RUN pip install -r requirements.txt
|
||||
# 分支镜像使用带提交号的开发版本;正式镜像使用 VERSION 中的版本。
|
||||
ENV APP_VERSION="${APP_VERSION}"
|
||||
|
||||
# 设置时区
|
||||
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
|
||||
echo 'Asia/Shanghai' > /etc/timezone
|
||||
|
||||
# 从构建阶段复制编译好的前端主题
|
||||
COPY --from=frontend-builder /build/FileCodeBox/themes/2024 ./themes/2024
|
||||
COPY --from=frontend-builder /build/fronted-2023/dist ./themes/2023
|
||||
|
||||
# 安装系统安全更新 + 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 \
|
||||
APP_ENV="production" \
|
||||
LOG_LEVEL="warning" \
|
||||
ACCESS_LOG="false" \
|
||||
FORWARDED_ALLOW_IPS="" \
|
||||
TIMEOUT_KEEP_ALIVE=5 \
|
||||
MALLOC_TRIM_THRESHOLD_=65536
|
||||
|
||||
# 暴露端口
|
||||
EXPOSE 12345
|
||||
|
||||
# 启动应用
|
||||
CMD ["python", "main.py"]
|
||||
# 生产环境启动命令
|
||||
# FORWARDED_ALLOW_IPS 默认为空:仅信任直连 IP,避免任意客户端伪造 X-Forwarded-*。
|
||||
# 若前面有反向代理,请显式设置为代理网段,例如 "10.0.0.0/8,172.16.0.0/12"。
|
||||
# 容器以 root 运行:兼容存量 root 属主的数据卷,以及 NAS/只读 bind mount。
|
||||
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\" --timeout-keep-alive \"${TIMEOUT_KEEP_ALIVE:-5}\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-}\""]
|
||||
@@ -0,0 +1,160 @@
|
||||
"""System config write path (ConfigService) + the KeyValue JSON lock.
|
||||
|
||||
keyvalue_write_lock lives here because ConfigService.update_config is its
|
||||
primary consumer; FileService imports it (one-way, no cycle).
|
||||
"""
|
||||
import asyncio
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from core.settings import (
|
||||
ADMIN_SESSION_EXPIRE_MAX,
|
||||
ADMIN_SESSION_EXPIRE_MIN,
|
||||
settings,
|
||||
)
|
||||
from apps.base.config import refresh_settings
|
||||
from core.security import (
|
||||
INTERNAL_CONFIG_KEYS,
|
||||
OUTBOUND_ENDPOINT_CONFIG_KEYS,
|
||||
generate_jwt_secret,
|
||||
validate_outbound_endpoint,
|
||||
validate_outbound_hostname,
|
||||
)
|
||||
from apps.base.models import KeyValue
|
||||
from core.utils import hash_password, is_password_hashed, validate_background_url
|
||||
|
||||
# KeyValue 里的 settings/activities/presets 都是整块 JSON 读-改-写;
|
||||
# 进程内写锁串行化这三个写路径,避免并发管理操作互相覆盖(last-writer-wins)。
|
||||
# 多进程部署下锁不跨进程——文档已锁定单 worker 部署。
|
||||
keyvalue_write_lock = asyncio.Lock()
|
||||
|
||||
|
||||
class ConfigService:
|
||||
INT_FIELDS = {
|
||||
"admin_session_expire",
|
||||
"enable_chunk",
|
||||
"error_count",
|
||||
"error_minute",
|
||||
"login_count",
|
||||
"login_minute",
|
||||
"max_save_seconds",
|
||||
"onedrive_proxy",
|
||||
"open_upload",
|
||||
"mcp_require_token",
|
||||
"port",
|
||||
"s3_proxy",
|
||||
"server_port",
|
||||
"server_workers",
|
||||
"show_admin_addr",
|
||||
"storage_limit",
|
||||
"upload_count",
|
||||
"upload_minute",
|
||||
"upload_size",
|
||||
"webdav_proxy",
|
||||
}
|
||||
FLOAT_FIELDS = {"opacity"}
|
||||
|
||||
def get_config(self):
|
||||
config = dict(settings.items())
|
||||
config["admin_token"] = ""
|
||||
for key in INTERNAL_CONFIG_KEYS:
|
||||
config.pop(key, None)
|
||||
return config
|
||||
|
||||
async def update_config(self, data: dict):
|
||||
current_config = dict(settings.items())
|
||||
next_config = dict(current_config)
|
||||
update_data = {
|
||||
key: value
|
||||
for key, value in data.items()
|
||||
if key in settings.default_config and key not in INTERNAL_CONFIG_KEYS
|
||||
}
|
||||
|
||||
admin_token = update_data.get("admin_token")
|
||||
admin_password_changed = False
|
||||
if admin_token is None or admin_token == "":
|
||||
update_data.pop("admin_token", None)
|
||||
elif not is_password_hashed(admin_token):
|
||||
update_data["admin_token"] = hash_password(admin_token)
|
||||
admin_password_changed = True
|
||||
else:
|
||||
admin_password_changed = True
|
||||
|
||||
for key, value in update_data.items():
|
||||
if value == "" and key in self.INT_FIELDS | self.FLOAT_FIELDS:
|
||||
continue
|
||||
|
||||
try:
|
||||
if key in self.INT_FIELDS:
|
||||
next_config[key] = int(value)
|
||||
elif key in self.FLOAT_FIELDS:
|
||||
next_config[key] = float(value)
|
||||
else:
|
||||
next_config[key] = value
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail=f"{key} 配置值格式错误")
|
||||
|
||||
try:
|
||||
session_expire = int(str(next_config.get("admin_session_expire")))
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="admin_session_expire 配置值格式错误",
|
||||
)
|
||||
if (
|
||||
not ADMIN_SESSION_EXPIRE_MIN <= session_expire <= ADMIN_SESSION_EXPIRE_MAX
|
||||
or session_expire % ADMIN_SESSION_EXPIRE_MIN != 0
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="admin_session_expire 必须是 1 到 365 个整天",
|
||||
)
|
||||
next_config["admin_session_expire"] = session_expire
|
||||
|
||||
if int(next_config.get("storage_limit", 0)) < 0:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="storage_limit 不能小于 0",
|
||||
)
|
||||
|
||||
# 只校验"发生变化"的值:升级前存入的旧格式 background(相对路径、含空格
|
||||
# 或括号)在旧版本是合法的,若每次保存都重新校验,存量部署会连无关设置项
|
||||
# 都保存不了(一律 400)。渲染侧仍然 html 转义,而任何修改都必须通过校验。
|
||||
current_background = str(settings.background or "")
|
||||
candidate_background = str(next_config.get("background") or "")
|
||||
if candidate_background != current_background:
|
||||
try:
|
||||
validate_background_url(candidate_background)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
|
||||
# 只校验"发生变化"的值:企业内网 minio/webdav 是正当场景,存量部署历史
|
||||
# 合法写入的内网 endpoint 若每次保存都重新校验,会连无关设置都保存不了
|
||||
# (background 曾有同款回归,上游 #528 修复过——本处沿用同一语义)。
|
||||
# s3_hostname 是裸主机名(存储层按 https://{hostname} 拼接),单独分档校验。
|
||||
for endpoint_key in OUTBOUND_ENDPOINT_CONFIG_KEYS:
|
||||
if endpoint_key not in next_config:
|
||||
continue
|
||||
candidate = str(next_config[endpoint_key] or "")
|
||||
current = str(getattr(settings, endpoint_key, "") or "")
|
||||
if candidate == current:
|
||||
continue
|
||||
validator = (
|
||||
validate_outbound_hostname
|
||||
if endpoint_key == "s3_hostname"
|
||||
else validate_outbound_endpoint
|
||||
)
|
||||
try:
|
||||
# 写回规范化值(validator 去除首尾空白):校验通过但入库脏值
|
||||
# 会让存储层在连接期才报错,应在校验点归一。
|
||||
next_config[endpoint_key] = validator(candidate)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
|
||||
if admin_password_changed:
|
||||
next_config["jwt_secret"] = generate_jwt_secret()
|
||||
|
||||
async with keyvalue_write_lock:
|
||||
await KeyValue.update_or_create(key="settings", defaults={"value": next_config})
|
||||
await refresh_settings(force=True)
|
||||
|
||||
@@ -2,97 +2,67 @@
|
||||
# @Author : Lan
|
||||
# @File : depends.py
|
||||
# @Software: PyCharm
|
||||
from fastapi import Header, HTTPException, Depends
|
||||
|
||||
from fastapi import Header
|
||||
from fastapi.requests import Request
|
||||
import base64
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
from core.settings import settings
|
||||
from apps.admin.services import FileService, ConfigService, LocalFileService
|
||||
|
||||
from apps.admin.services import ConfigService, FileService, LocalFileService
|
||||
from apps.base.auth import (
|
||||
_extract_bearer_token,
|
||||
_get_jwt_secret,
|
||||
_require_admin_payload,
|
||||
create_token,
|
||||
get_admin_session_expire_seconds,
|
||||
share_required_login,
|
||||
verify_token,
|
||||
)
|
||||
|
||||
# 认证原语(JWT 创建/校验、Bearer 提取、分享上传门控)已下沉 apps.base.auth
|
||||
# ——base 分享面与本模块共同消费,留在 base 避免 base→admin 反向依赖。
|
||||
# 此处 re-export 保持既有 import 路径兼容(tests/admin.views 等)。
|
||||
|
||||
__all__ = [
|
||||
"_extract_bearer_token",
|
||||
"_get_jwt_secret",
|
||||
"_require_admin_payload",
|
||||
"ADMIN_PUBLIC_ENDPOINTS",
|
||||
"admin_required",
|
||||
"create_token",
|
||||
"get_admin_session",
|
||||
"get_admin_session_expire_seconds",
|
||||
"get_config_service",
|
||||
"get_file_service",
|
||||
"get_local_file_service",
|
||||
"share_required_login",
|
||||
"verify_token",
|
||||
]
|
||||
|
||||
|
||||
def create_token(data: dict, expires_in: int = 3600 * 24) -> str:
|
||||
"""
|
||||
创建JWT token
|
||||
:param data: 数据负载
|
||||
:param expires_in: 过期时间(秒)
|
||||
"""
|
||||
header = base64.b64encode(
|
||||
json.dumps({"alg": "HS256", "typ": "JWT"}).encode()
|
||||
).decode()
|
||||
payload = base64.b64encode(
|
||||
json.dumps({**data, "exp": int(time.time()) + expires_in}).encode()
|
||||
).decode()
|
||||
|
||||
signature = hmac.new(
|
||||
settings.admin_token.encode(), f"{header}.{payload}".encode(), "sha256"
|
||||
).digest()
|
||||
signature = base64.b64encode(signature).decode()
|
||||
|
||||
return f"{header}.{payload}.{signature}"
|
||||
def get_admin_session(authorization: str = Header(default=None)) -> dict:
|
||||
token = _extract_bearer_token(authorization)
|
||||
payload = _require_admin_payload(authorization)
|
||||
return {
|
||||
"id": "admin",
|
||||
"username": "admin",
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": payload.get("exp"),
|
||||
}
|
||||
|
||||
|
||||
def verify_token(token: str) -> dict:
|
||||
"""
|
||||
验证JWT token
|
||||
:param token: JWT token
|
||||
:return: 解码后的数据
|
||||
"""
|
||||
try:
|
||||
header_b64, payload_b64, signature_b64 = token.split(".")
|
||||
|
||||
# 验证签名
|
||||
expected_signature = hmac.new(
|
||||
settings.admin_token.encode(),
|
||||
f"{header_b64}.{payload_b64}".encode(),
|
||||
"sha256",
|
||||
).digest()
|
||||
expected_signature_b64 = base64.b64encode(expected_signature).decode()
|
||||
|
||||
if signature_b64 != expected_signature_b64:
|
||||
raise ValueError("无效的签名")
|
||||
|
||||
# 解码payload
|
||||
payload = json.loads(base64.b64decode(payload_b64))
|
||||
|
||||
# 检查是否过期
|
||||
if payload.get("exp", 0) < time.time():
|
||||
raise ValueError("token已过期")
|
||||
|
||||
return payload
|
||||
except Exception as e:
|
||||
raise ValueError(f"token验证失败: {str(e)}")
|
||||
ADMIN_PUBLIC_ENDPOINTS = {("POST", "/admin/login")}
|
||||
|
||||
|
||||
async def admin_required(
|
||||
authorization: str = Header(default=None), request: Request = None
|
||||
authorization: str = Header(default=None),
|
||||
request: Request = None, # type: ignore[assignment] # FastAPI 运行时注入 Request;可选语义由下方 if request 判断
|
||||
):
|
||||
"""
|
||||
验证管理员权限
|
||||
"""
|
||||
try:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
is_admin = False
|
||||
else:
|
||||
try:
|
||||
token = authorization.split(" ")[1]
|
||||
payload = verify_token(token)
|
||||
is_admin = payload.get("is_admin", False)
|
||||
except ValueError as e:
|
||||
is_admin = False
|
||||
|
||||
if request.url.path.startswith("/share/"):
|
||||
if not settings.openUpload and not is_admin:
|
||||
raise HTTPException(
|
||||
status_code=403, detail="本站未开启游客上传,如需上传请先登录后台"
|
||||
)
|
||||
else:
|
||||
if not is_admin:
|
||||
raise HTTPException(status_code=401, detail="未授权或授权校验失败")
|
||||
return is_admin
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=401, detail=str(e))
|
||||
if request and (request.method, request.url.path) in ADMIN_PUBLIC_ENDPOINTS:
|
||||
return None
|
||||
return _require_admin_payload(authorization)
|
||||
|
||||
|
||||
async def get_file_service():
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Admin-side local (NAS) file browsing and deletion."""
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from apps.base.local_share import (
|
||||
MAX_LIST_ENTRIES,
|
||||
format_local_ctime,
|
||||
get_local_root,
|
||||
normalize_local_relpath,
|
||||
resolve_under_local,
|
||||
)
|
||||
|
||||
|
||||
class LocalFileService:
|
||||
async def list_files(self, path: str = ""):
|
||||
relpath = normalize_local_relpath(path, allow_empty=True)
|
||||
directory = resolve_under_local(relpath)
|
||||
if not directory.exists() or not directory.is_dir():
|
||||
raise HTTPException(status_code=404, detail="目录不存在")
|
||||
|
||||
root = get_local_root()
|
||||
items: list[dict[str, Any]] = []
|
||||
try:
|
||||
children = list(directory.iterdir())
|
||||
except OSError as exc:
|
||||
raise HTTPException(status_code=500, detail="无法读取目录") from exc
|
||||
|
||||
children.sort(key=lambda p: (not p.is_dir(), p.name.lower()))
|
||||
truncated = False
|
||||
for child in children:
|
||||
if len(items) >= MAX_LIST_ENTRIES:
|
||||
truncated = True
|
||||
break
|
||||
try:
|
||||
resolved = child.resolve()
|
||||
resolved.relative_to(root)
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
if not resolved.is_file() and not resolved.is_dir():
|
||||
continue
|
||||
child_rel = child.name if not relpath else f"{relpath}/{child.name}"
|
||||
is_dir = resolved.is_dir()
|
||||
items.append(
|
||||
{
|
||||
"file": child.name,
|
||||
"name": child.name,
|
||||
"path": child_rel,
|
||||
"type": "dir" if is_dir else "file",
|
||||
"ctime": format_local_ctime(resolved),
|
||||
"size": None if is_dir else resolved.stat().st_size,
|
||||
}
|
||||
)
|
||||
|
||||
parent = ""
|
||||
if relpath:
|
||||
parent_path = Path(relpath).parent.as_posix()
|
||||
parent = "" if parent_path == "." else parent_path
|
||||
return {
|
||||
"path": relpath,
|
||||
"parent": parent,
|
||||
"truncated": truncated,
|
||||
"items": items,
|
||||
}
|
||||
|
||||
async def delete_file(self, filename: str):
|
||||
file = LocalFileClass(filename)
|
||||
if await file.exists():
|
||||
await file.delete()
|
||||
return "删除成功"
|
||||
raise HTTPException(status_code=404, detail="文件不存在")
|
||||
|
||||
|
||||
class LocalFileClass:
|
||||
def __init__(self, file):
|
||||
relpath = normalize_local_relpath(file)
|
||||
self.file = relpath
|
||||
self.name = Path(relpath).name
|
||||
self.path = resolve_under_local(relpath)
|
||||
if self.path.is_file():
|
||||
self.ctime = format_local_ctime(self.path)
|
||||
self.size = self.path.stat().st_size
|
||||
else:
|
||||
self.ctime = None
|
||||
self.size = None
|
||||
|
||||
async def read(self) -> bytes:
|
||||
with open(self.path, "rb") as fh:
|
||||
return fh.read()
|
||||
|
||||
async def delete(self):
|
||||
if not self.path.is_file():
|
||||
raise HTTPException(status_code=404, detail="文件不存在")
|
||||
self.path.unlink()
|
||||
|
||||
async def exists(self):
|
||||
return self.path.is_file()
|
||||
@@ -1,3 +1,6 @@
|
||||
import datetime
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
@@ -5,6 +8,10 @@ class IDData(BaseModel):
|
||||
id: int
|
||||
|
||||
|
||||
class IDsData(BaseModel):
|
||||
ids: list[int]
|
||||
|
||||
|
||||
class ShareItem(BaseModel):
|
||||
expire_value: int
|
||||
expire_style: str = "day"
|
||||
@@ -17,3 +24,48 @@ class DeleteItem(BaseModel):
|
||||
|
||||
class LoginData(BaseModel):
|
||||
password: str
|
||||
|
||||
|
||||
class UpdateFileData(BaseModel):
|
||||
id: int
|
||||
code: Optional[str] = None
|
||||
prefix: Optional[str] = None
|
||||
suffix: Optional[str] = None
|
||||
expired_at: Optional[Union[datetime.datetime, str]] = None
|
||||
expired_count: Optional[int] = None
|
||||
|
||||
|
||||
class BatchUpdateFileData(BaseModel):
|
||||
ids: list[int]
|
||||
expired_at: Optional[Union[datetime.datetime, str]] = None
|
||||
expired_count: Optional[int] = None
|
||||
clear_expired_at: Optional[bool] = None
|
||||
|
||||
|
||||
class FilePolicyActionData(BaseModel):
|
||||
id: int
|
||||
action: str
|
||||
download_limit: Optional[int] = None
|
||||
|
||||
|
||||
class BatchFilePolicyActionData(BaseModel):
|
||||
ids: list[int]
|
||||
action: str
|
||||
download_limit: Optional[int] = None
|
||||
|
||||
|
||||
class FileMetadataData(BaseModel):
|
||||
id: int
|
||||
note: Optional[str] = None
|
||||
tags: Optional[list[str]] = None
|
||||
|
||||
|
||||
class FileViewPresetData(BaseModel):
|
||||
id: Optional[str] = None
|
||||
name: str
|
||||
filters: Optional[dict[str, Any]] = None
|
||||
params: Optional[dict[str, Any]] = None
|
||||
|
||||
|
||||
class FileViewPresetDeleteData(BaseModel):
|
||||
id: str
|
||||
@@ -3,146 +3,632 @@
|
||||
# @File : views.py
|
||||
# @Software: PyCharm
|
||||
import datetime
|
||||
from typing import Any
|
||||
from collections import Counter
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from apps.admin.services import FileService, ConfigService, LocalFileService
|
||||
from apps.admin.dependencies import (
|
||||
admin_required,
|
||||
get_admin_session,
|
||||
get_file_service,
|
||||
get_config_service,
|
||||
get_local_file_service,
|
||||
)
|
||||
from apps.admin.schemas import IDData, ShareItem, DeleteItem, LoginData
|
||||
from apps.admin.schemas import (
|
||||
IDData,
|
||||
IDsData,
|
||||
BatchUpdateFileData,
|
||||
BatchFilePolicyActionData,
|
||||
FilePolicyActionData,
|
||||
FileMetadataData,
|
||||
FileViewPresetData,
|
||||
FileViewPresetDeleteData,
|
||||
ShareItem,
|
||||
DeleteItem,
|
||||
LoginData,
|
||||
UpdateFileData,
|
||||
)
|
||||
from core.response import APIResponse
|
||||
from apps.base.models import FileCodes, KeyValue
|
||||
from apps.admin.dependencies import create_token
|
||||
from apps.base.quota import owned_storage_queryset
|
||||
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, hash_password, password_needs_rehash, verify_password
|
||||
from apps.base.utils import ip_limit
|
||||
|
||||
admin_api = APIRouter(prefix="/admin", tags=["管理"])
|
||||
admin_api = APIRouter(
|
||||
prefix="/admin", tags=["管理"], dependencies=[Depends(admin_required)]
|
||||
)
|
||||
|
||||
|
||||
def _pick_query_text(*values: Optional[str]) -> Optional[str]:
|
||||
for value in values:
|
||||
normalized_value = str(value or "").strip()
|
||||
if normalized_value:
|
||||
return normalized_value
|
||||
return None
|
||||
|
||||
|
||||
@admin_api.post("/login")
|
||||
async def login(data: LoginData):
|
||||
# 验证管理员密码
|
||||
if data.password != settings.admin_token:
|
||||
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
|
||||
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)
|
||||
|
||||
|
||||
@admin_api.get("/dashboard")
|
||||
async def dashboard(admin: bool = Depends(admin_required)):
|
||||
all_codes = await FileCodes.all()
|
||||
all_size = str(sum([code.size for code in all_codes]))
|
||||
sys_start = await KeyValue.filter(key="sys_start").first()
|
||||
# 获取当前日期时间
|
||||
now = datetime.datetime.now()
|
||||
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
yesterday_start = today_start - datetime.timedelta(days=1)
|
||||
yesterday_end = today_start - datetime.timedelta(microseconds=1)
|
||||
# 统计昨天一整天的记录数(从昨天0点到23:59:59)
|
||||
yesterday_codes = FileCodes.filter(
|
||||
created_at__gte=yesterday_start, created_at__lte=yesterday_end
|
||||
)
|
||||
# 统计今天到现在的记录数(从今天0点到现在)
|
||||
today_codes = FileCodes.filter(created_at__gte=today_start)
|
||||
expires_in = get_admin_session_expire_seconds()
|
||||
token = create_token({"is_admin": True}, expires_in=expires_in)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"totalFiles": len(all_codes),
|
||||
"storageUsed": all_size,
|
||||
"sysUptime": sys_start.value,
|
||||
"yesterdayCount": await yesterday_codes.count(),
|
||||
"yesterdaySize": str(sum([code.size for code in await yesterday_codes])),
|
||||
"todayCount": await today_codes.count(),
|
||||
"todaySize": str(sum([code.size for code in await today_codes])),
|
||||
"id": "admin",
|
||||
"username": "admin",
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": verify_token(token)["exp"],
|
||||
"expires_in": expires_in,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@admin_api.get("/verify")
|
||||
async def verify_admin(session: dict = Depends(get_admin_session)):
|
||||
return APIResponse(detail=session)
|
||||
|
||||
|
||||
@admin_api.post("/logout")
|
||||
async def logout_admin():
|
||||
return APIResponse(detail={"ok": True})
|
||||
|
||||
|
||||
async def build_dashboard_recent_file(file_code: FileCodes) -> dict:
|
||||
is_expired = await file_code.is_expired()
|
||||
return {
|
||||
"id": file_code.id,
|
||||
"code": file_code.code,
|
||||
"name": file_code.prefix + file_code.suffix,
|
||||
"suffix": file_code.suffix,
|
||||
"size": file_code.size,
|
||||
"text": file_code.text is not None,
|
||||
"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)):
|
||||
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)
|
||||
|
||||
# 简单计数全部走 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(owned_storage_queryset())
|
||||
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(
|
||||
owned_storage_queryset(
|
||||
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(
|
||||
owned_storage_queryset(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(
|
||||
{((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_activities = await file_service.list_admin_activities(limit=8)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"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,
|
||||
"health_summary": health_summary,
|
||||
"top_suffixes": [
|
||||
{"suffix": suffix, "count": count}
|
||||
for suffix, count in suffix_counter.most_common(8)
|
||||
],
|
||||
"recent_files": [
|
||||
await build_dashboard_recent_file(file_code)
|
||||
for file_code in recent_file_codes
|
||||
],
|
||||
"recent_activities": recent_activities["activities"],
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@admin_api.get("/activities")
|
||||
async def admin_activities(
|
||||
limit: int = 20,
|
||||
action: Optional[str] = None,
|
||||
targetType: Optional[str] = None,
|
||||
target_type: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
result = await file_service.list_admin_activities(
|
||||
limit=limit,
|
||||
action=action,
|
||||
target_type=_pick_query_text(targetType, target_type),
|
||||
keyword=keyword,
|
||||
)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.delete("/file/delete")
|
||||
async def file_delete(
|
||||
data: IDData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
data: IDData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
await file_service.delete_file(data.id)
|
||||
return APIResponse()
|
||||
|
||||
|
||||
async def batch_delete_files(
|
||||
data: IDsData,
|
||||
file_service: FileService,
|
||||
):
|
||||
if not data.ids:
|
||||
raise HTTPException(status_code=400, detail="请选择要删除的文件")
|
||||
result = await file_service.delete_files(data.ids)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.delete("/file/batch-delete")
|
||||
async def file_batch_delete(
|
||||
data: IDsData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await batch_delete_files(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/batch-delete")
|
||||
async def file_batch_delete_post(
|
||||
data: IDsData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await batch_delete_files(data, file_service)
|
||||
|
||||
|
||||
async def batch_update_files(
|
||||
data: BatchUpdateFileData,
|
||||
file_service: FileService,
|
||||
):
|
||||
if not data.ids:
|
||||
raise HTTPException(status_code=400, detail="请选择要更新的文件")
|
||||
|
||||
update_data: dict[str, Any] = {}
|
||||
fields_set = data.model_fields_set
|
||||
should_clear_expired_at = bool(data.clear_expired_at)
|
||||
|
||||
if should_clear_expired_at:
|
||||
update_data["expired_at"] = None
|
||||
update_data["expired_count"] = -1
|
||||
elif "expired_at" in fields_set and data.expired_at != "":
|
||||
# schema 声明 Union[datetime, str]——透传两种形态,tortoise 均可序列化
|
||||
update_data["expired_at"] = data.expired_at
|
||||
|
||||
if (
|
||||
not should_clear_expired_at
|
||||
and "expired_count" in fields_set
|
||||
and data.expired_count is not None
|
||||
):
|
||||
update_data["expired_count"] = data.expired_count
|
||||
|
||||
if not update_data:
|
||||
raise HTTPException(status_code=400, detail="请选择要更新的字段")
|
||||
|
||||
result = await file_service.update_files(data.ids, update_data)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.patch("/file/batch-update")
|
||||
async def file_batch_update(
|
||||
data: BatchUpdateFileData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await batch_update_files(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/batch-update")
|
||||
async def file_batch_update_post(
|
||||
data: BatchUpdateFileData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await batch_update_files(data, file_service)
|
||||
|
||||
|
||||
async def apply_file_policy_action(
|
||||
data: FilePolicyActionData,
|
||||
file_service: FileService,
|
||||
):
|
||||
download_limit = data.download_limit
|
||||
|
||||
detail = await file_service.apply_file_policy_action(
|
||||
file_id=data.id,
|
||||
action=data.action,
|
||||
download_limit=download_limit,
|
||||
)
|
||||
return APIResponse(detail=detail)
|
||||
|
||||
|
||||
@admin_api.patch("/file/policy-action")
|
||||
async def file_policy_action(
|
||||
data: FilePolicyActionData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await apply_file_policy_action(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/policy-action")
|
||||
async def file_policy_action_post(
|
||||
data: FilePolicyActionData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await apply_file_policy_action(data, file_service)
|
||||
|
||||
|
||||
async def apply_batch_file_policy_action(
|
||||
data: BatchFilePolicyActionData,
|
||||
file_service: FileService,
|
||||
):
|
||||
if not data.ids:
|
||||
raise HTTPException(status_code=400, detail="请选择要更新的文件")
|
||||
|
||||
download_limit = data.download_limit
|
||||
|
||||
result = await file_service.apply_files_policy_action(
|
||||
file_ids=data.ids,
|
||||
action=data.action,
|
||||
download_limit=download_limit,
|
||||
)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.patch("/file/batch-policy-action")
|
||||
async def file_batch_policy_action(
|
||||
data: BatchFilePolicyActionData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await apply_batch_file_policy_action(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/batch-policy-action")
|
||||
async def file_batch_policy_action_post(
|
||||
data: BatchFilePolicyActionData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await apply_batch_file_policy_action(data, file_service)
|
||||
|
||||
|
||||
@admin_api.get("/file/list")
|
||||
async def file_list(
|
||||
page: int = 1,
|
||||
size: int = 10,
|
||||
keyword: str = "",
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
page: int = 1,
|
||||
size: int = 10,
|
||||
keyword: str = "",
|
||||
status: str = "",
|
||||
type: str = "",
|
||||
health: str = "",
|
||||
sort_by: str = "created_at",
|
||||
sort_order: str = "desc",
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
files, total = await file_service.list_files(page, size, keyword)
|
||||
page = max(page, 1)
|
||||
size = min(max(size, 1), 100)
|
||||
files, total, summary = await file_service.list_files(
|
||||
page,
|
||||
size,
|
||||
keyword,
|
||||
status=status,
|
||||
file_type=type,
|
||||
health=health,
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"page": page,
|
||||
"size": size,
|
||||
"data": files,
|
||||
"total": total,
|
||||
"summary": summary,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@admin_api.get("/file/detail")
|
||||
async def file_detail(
|
||||
id: int,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
detail = await file_service.get_file_detail(id)
|
||||
return APIResponse(detail=detail)
|
||||
|
||||
|
||||
@admin_api.post("/file/detail")
|
||||
async def file_detail_post(
|
||||
data: IDData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
detail = await file_service.get_file_detail(data.id)
|
||||
return APIResponse(detail=detail)
|
||||
|
||||
|
||||
async def update_file_metadata(
|
||||
data: FileMetadataData,
|
||||
file_service: FileService,
|
||||
):
|
||||
fields_set = data.model_fields_set
|
||||
update_note = "note" in fields_set
|
||||
update_tags = "tags" in fields_set
|
||||
if not update_note and not update_tags:
|
||||
raise HTTPException(status_code=400, detail="请选择要更新的元数据")
|
||||
|
||||
detail = await file_service.update_file_metadata(
|
||||
file_id=data.id,
|
||||
note=data.note,
|
||||
tags=data.tags,
|
||||
update_note=update_note,
|
||||
update_tags=update_tags,
|
||||
)
|
||||
return APIResponse(detail=detail)
|
||||
|
||||
|
||||
@admin_api.patch("/file/metadata")
|
||||
async def file_metadata(
|
||||
data: FileMetadataData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await update_file_metadata(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/metadata")
|
||||
async def file_metadata_post(
|
||||
data: FileMetadataData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await update_file_metadata(data, file_service)
|
||||
|
||||
|
||||
@admin_api.get("/file/view-presets")
|
||||
async def file_view_presets(
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
result = await file_service.list_file_view_presets()
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
async def save_file_view_preset(
|
||||
data: FileViewPresetData,
|
||||
file_service: FileService,
|
||||
):
|
||||
filters = data.filters if data.filters is not None else data.params
|
||||
preset = await file_service.save_file_view_preset(
|
||||
preset_id=data.id,
|
||||
name=data.name,
|
||||
filters=filters or {},
|
||||
)
|
||||
return APIResponse(detail=preset)
|
||||
|
||||
|
||||
@admin_api.post("/file/view-presets")
|
||||
async def file_view_presets_save(
|
||||
data: FileViewPresetData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await save_file_view_preset(data, file_service)
|
||||
|
||||
|
||||
@admin_api.patch("/file/view-presets")
|
||||
async def file_view_presets_patch(
|
||||
data: FileViewPresetData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await save_file_view_preset(data, file_service)
|
||||
|
||||
|
||||
async def delete_file_view_preset(
|
||||
data: FileViewPresetDeleteData,
|
||||
file_service: FileService,
|
||||
):
|
||||
result = await file_service.delete_file_view_preset(data.id)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.delete("/file/view-presets")
|
||||
async def file_view_presets_delete(
|
||||
data: FileViewPresetDeleteData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await delete_file_view_preset(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/view-presets/delete")
|
||||
async def file_view_presets_delete_post(
|
||||
data: FileViewPresetDeleteData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await delete_file_view_preset(data, file_service)
|
||||
|
||||
|
||||
@admin_api.get("/config/get")
|
||||
async def get_config(
|
||||
config_service: ConfigService = Depends(get_config_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
config_service: ConfigService = Depends(get_config_service),
|
||||
):
|
||||
return APIResponse(detail=config_service.get_config())
|
||||
|
||||
|
||||
@admin_api.patch("/config/update")
|
||||
async def update_config(
|
||||
data: dict,
|
||||
config_service: ConfigService = Depends(get_config_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
data: dict,
|
||||
config_service: ConfigService = Depends(get_config_service),
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
data.pop("themesChoices")
|
||||
data.pop("themes_choices", None)
|
||||
await config_service.update_config(data)
|
||||
await file_service.record_admin_activity(
|
||||
action="config.update",
|
||||
target_type="config",
|
||||
target_name="system",
|
||||
count=1,
|
||||
meta={"fields": sorted(data.keys())},
|
||||
)
|
||||
return APIResponse()
|
||||
|
||||
|
||||
@admin_api.get("/file/download")
|
||||
async def file_download(
|
||||
id: int,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
id: int,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
file_content = await file_service.download_file(id)
|
||||
return file_content
|
||||
|
||||
|
||||
@admin_api.get("/file/preview")
|
||||
async def file_preview(
|
||||
id: int,
|
||||
max_chars: int = 4000,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
preview = await file_service.preview_file(id, max_chars)
|
||||
return APIResponse(detail=preview)
|
||||
|
||||
|
||||
@admin_api.get("/local/lists")
|
||||
async def get_local_lists(
|
||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
path: str = "",
|
||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||
):
|
||||
files = await local_file_service.list_files()
|
||||
files = await local_file_service.list_files(path)
|
||||
return APIResponse(detail=files)
|
||||
|
||||
|
||||
@admin_api.delete("/local/delete")
|
||||
async def delete_local_file(
|
||||
item: DeleteItem,
|
||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
item: DeleteItem,
|
||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
result = await local_file_service.delete_file(item.filename)
|
||||
await file_service.record_admin_activity(
|
||||
action="local_file.delete",
|
||||
target_type="local_file",
|
||||
target_name=item.filename,
|
||||
count=1,
|
||||
meta={"success": bool(result)},
|
||||
)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.post("/local/share")
|
||||
async def share_local_file(
|
||||
item: ShareItem,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
item: ShareItem,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
share_info = await file_service.share_local_file(item)
|
||||
await file_service.record_admin_activity(
|
||||
action="local_file.share",
|
||||
target_type="file",
|
||||
target_id=share_info.get("id") if isinstance(share_info, dict) else None,
|
||||
target_name=item.filename,
|
||||
count=1,
|
||||
meta={
|
||||
"expire_value": item.expire_value,
|
||||
"expire_style": item.expire_style,
|
||||
},
|
||||
)
|
||||
return APIResponse(detail=share_info)
|
||||
|
||||
|
||||
@admin_api.patch("/file/update")
|
||||
async def update_file(
|
||||
data: UpdateFileData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
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="更新成功")
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Cross-cutting auth primitives and the share-upload gate.
|
||||
|
||||
Lives in apps.base because BOTH the share surface (base.views) and the
|
||||
admin surface (admin.views) consume it; keeping it here avoids the
|
||||
base → admin reverse dependency. Admin-only session gating stays in
|
||||
apps.admin.dependencies, which re-exports these primitives for
|
||||
compatibility.
|
||||
"""
|
||||
import base64
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
|
||||
from fastapi import Header, HTTPException
|
||||
|
||||
from core.settings import (
|
||||
ADMIN_SESSION_EXPIRE_DEFAULT,
|
||||
ADMIN_SESSION_EXPIRE_MAX,
|
||||
ADMIN_SESSION_EXPIRE_MIN,
|
||||
settings,
|
||||
)
|
||||
|
||||
|
||||
def _get_jwt_secret() -> bytes:
|
||||
secret = getattr(settings, "jwt_secret", "")
|
||||
if not secret:
|
||||
raise RuntimeError("JWT签名密钥未初始化")
|
||||
return secret.encode()
|
||||
|
||||
|
||||
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: 过期时间(秒)
|
||||
"""
|
||||
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_digest = hmac.new(
|
||||
_get_jwt_secret(), f"{header}.{payload}".encode(), "sha256"
|
||||
).digest()
|
||||
signature = base64.urlsafe_b64encode(signature_digest).decode().rstrip("=")
|
||||
|
||||
return f"{header}.{payload}.{signature}"
|
||||
|
||||
|
||||
def verify_token(token: str) -> dict:
|
||||
"""
|
||||
验证JWT token
|
||||
:param token: JWT token
|
||||
:return: 解码后的数据
|
||||
"""
|
||||
try:
|
||||
header_b64, payload_b64, signature_b64 = token.split(".")
|
||||
|
||||
# 验证签名
|
||||
expected_signature = hmac.new(
|
||||
_get_jwt_secret(),
|
||||
f"{header_b64}.{payload_b64}".encode(),
|
||||
"sha256",
|
||||
).digest()
|
||||
expected_signature_b64 = (
|
||||
base64.urlsafe_b64encode(expected_signature).decode().rstrip("=")
|
||||
)
|
||||
|
||||
if not hmac.compare_digest(signature_b64, expected_signature_b64):
|
||||
raise ValueError("无效的签名")
|
||||
|
||||
# 解码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():
|
||||
raise ValueError("token已过期")
|
||||
|
||||
return payload
|
||||
except Exception as e:
|
||||
raise ValueError(f"token验证失败: {str(e)}")
|
||||
|
||||
|
||||
def _extract_bearer_token(authorization: str) -> str:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise HTTPException(status_code=401, detail="未授权或授权校验失败")
|
||||
token = authorization.split(" ", 1)[1].strip()
|
||||
if not token:
|
||||
raise HTTPException(status_code=401, detail="未授权或授权校验失败")
|
||||
return token
|
||||
|
||||
|
||||
def _require_admin_payload(authorization: str) -> dict:
|
||||
token = _extract_bearer_token(authorization)
|
||||
try:
|
||||
payload = verify_token(token)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=401, detail=str(e))
|
||||
if not payload.get("is_admin", False):
|
||||
raise HTTPException(status_code=401, detail="未授权或授权校验失败")
|
||||
return payload
|
||||
|
||||
|
||||
async def share_required_login(authorization: str = Header(default=None)):
|
||||
"""
|
||||
验证分享上传权限
|
||||
|
||||
当 settings.open_upload 为False时,要求用户必须登录并具有管理员权限
|
||||
当 settings.open_upload 为True时,允许游客上传
|
||||
|
||||
:param authorization: 认证头信息
|
||||
:param request: 请求对象
|
||||
:return: 验证结果
|
||||
"""
|
||||
if not settings.open_upload:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise HTTPException(
|
||||
status_code=403, detail="本站未开启游客上传,如需上传请先登录后台"
|
||||
)
|
||||
_require_admin_payload(authorization)
|
||||
|
||||
return True
|
||||
@@ -0,0 +1,140 @@
|
||||
from apps.base.models import KeyValue
|
||||
from apps.base.utils import ip_limit
|
||||
from core.database import db_startup_lock
|
||||
from core.logger import logger
|
||||
from core.security import (
|
||||
generate_jwt_secret,
|
||||
is_config_initialized,
|
||||
is_valid_jwt_secret,
|
||||
prepare_security_config,
|
||||
)
|
||||
from core.settings import DEFAULT_CONFIG, settings
|
||||
from core.utils import hash_password
|
||||
|
||||
|
||||
MIN_ADMIN_PASSWORD_LENGTH = 8
|
||||
SETUP_CONFIG_FIELDS = {
|
||||
"allowed_file_types",
|
||||
"code_generate_type",
|
||||
"enable_chunk",
|
||||
"error_count",
|
||||
"error_minute",
|
||||
"login_count",
|
||||
"login_minute",
|
||||
"expire_style",
|
||||
"max_save_seconds",
|
||||
"name",
|
||||
"open_upload",
|
||||
"upload_count",
|
||||
"upload_minute",
|
||||
"upload_size",
|
||||
}
|
||||
|
||||
|
||||
async def ensure_settings_row() -> None:
|
||||
initial_security = prepare_security_config(DEFAULT_CONFIG)
|
||||
_, created = await KeyValue.get_or_create(
|
||||
key="settings", defaults={"value": initial_security.config}
|
||||
)
|
||||
if created:
|
||||
logger.warning(
|
||||
"系统尚未初始化,请在浏览器中打开站点并完成管理员密码设置"
|
||||
)
|
||||
|
||||
|
||||
async def ensure_security_settings() -> None:
|
||||
config_record = await KeyValue.filter(key="settings").first()
|
||||
if not config_record:
|
||||
return
|
||||
|
||||
current_config = {**DEFAULT_CONFIG, **(config_record.value or {})}
|
||||
security_config = prepare_security_config(current_config)
|
||||
if not security_config.changed:
|
||||
return
|
||||
|
||||
config_record.value = security_config.config
|
||||
await config_record.save()
|
||||
if security_config.setup_required:
|
||||
logger.warning("检测到空密码或旧版默认管理员密码,请通过初始化页面重新设置")
|
||||
elif security_config.password_hashed:
|
||||
logger.info("已将管理员密码迁移为哈希存储")
|
||||
if security_config.jwt_secret_rotated:
|
||||
logger.info("已生成独立 JWT 签名密钥")
|
||||
await refresh_settings(force=True)
|
||||
|
||||
|
||||
def _sync_ip_limits() -> None:
|
||||
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
|
||||
|
||||
|
||||
# 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:
|
||||
return is_config_initialized(dict(settings.items()))
|
||||
|
||||
|
||||
async def initialize_system(
|
||||
admin_password: str,
|
||||
site_name: str | None = None,
|
||||
setup_options: dict | None = None,
|
||||
) -> None:
|
||||
password = str(admin_password or "").strip()
|
||||
if len(password) < MIN_ADMIN_PASSWORD_LENGTH:
|
||||
raise ValueError(f"管理员密码至少需要 {MIN_ADMIN_PASSWORD_LENGTH} 位")
|
||||
|
||||
async with db_startup_lock():
|
||||
config_record = await KeyValue.filter(key="settings").first()
|
||||
current_config = {
|
||||
**DEFAULT_CONFIG,
|
||||
**(config_record.value if config_record and config_record.value else {}),
|
||||
}
|
||||
if is_config_initialized(current_config):
|
||||
raise ValueError("系统已经初始化,请直接登录后台")
|
||||
|
||||
next_config = dict(current_config)
|
||||
for key, value in (setup_options or {}).items():
|
||||
if key in SETUP_CONFIG_FIELDS:
|
||||
next_config[key] = value
|
||||
|
||||
normalized_site_name = str(site_name or "").strip()
|
||||
if normalized_site_name:
|
||||
next_config["name"] = normalized_site_name[:80]
|
||||
|
||||
next_config["admin_token"] = hash_password(password)
|
||||
if not is_valid_jwt_secret(next_config.get("jwt_secret")):
|
||||
next_config["jwt_secret"] = generate_jwt_secret()
|
||||
|
||||
await KeyValue.update_or_create(key="settings", defaults={"value": next_config})
|
||||
await refresh_settings(force=True)
|
||||
@@ -1,45 +1,136 @@
|
||||
from typing import Dict, Union
|
||||
from datetime import datetime, timedelta
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
from ipaddress import ip_address, ip_network
|
||||
from typing import Iterable, TypedDict
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
def _iter_trusted_proxies() -> Iterable[str]:
|
||||
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]
|
||||
|
||||
|
||||
def _is_trusted_proxy(host: str) -> bool:
|
||||
try:
|
||||
remote_addr = ip_address(host)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
for proxy in _iter_trusted_proxies():
|
||||
try:
|
||||
if remote_addr in ip_network(proxy, strict=False):
|
||||
return True
|
||||
except ValueError:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
def _get_forwarded_for_ip(header_value: str, fallback_ip: str) -> str:
|
||||
forwarded_chain = [
|
||||
item.strip() for item in header_value.split(",") if item.strip()
|
||||
]
|
||||
if not forwarded_chain:
|
||||
return fallback_ip
|
||||
|
||||
for candidate in reversed(forwarded_chain):
|
||||
try:
|
||||
ip_address(candidate)
|
||||
except ValueError:
|
||||
return fallback_ip
|
||||
if not _is_trusted_proxy(candidate):
|
||||
return candidate
|
||||
return forwarded_chain[0]
|
||||
|
||||
|
||||
def get_client_ip(request: Request) -> str:
|
||||
client_host = request.client.host if request.client else "unknown"
|
||||
if not _is_trusted_proxy(client_host):
|
||||
return client_host
|
||||
|
||||
forwarded_for = request.headers.get("X-Forwarded-For")
|
||||
if forwarded_for:
|
||||
return _get_forwarded_for_ip(forwarded_for, client_host)
|
||||
|
||||
real_ip = request.headers.get("X-Real-IP")
|
||||
if real_ip:
|
||||
try:
|
||||
ip_address(real_ip)
|
||||
except ValueError:
|
||||
return client_host
|
||||
return real_ip
|
||||
|
||||
return client_host
|
||||
|
||||
|
||||
class _IPRecord(TypedDict):
|
||||
count: int
|
||||
last_seen: float
|
||||
|
||||
|
||||
# Upper bound for tracked source IPs per limiter. Without it a scan using
|
||||
# spoofed/rotating addresses grows the dict forever on a small VPS.
|
||||
DEFAULT_MAX_TRACKED_IPS = 10_000
|
||||
|
||||
|
||||
class IPRateLimit:
|
||||
def __init__(self, count: int, minutes: int):
|
||||
self.ips: Dict[str, Dict[str, Union[int, datetime]]] = {}
|
||||
def __init__(
|
||||
self,
|
||||
count: int,
|
||||
minutes: int,
|
||||
max_ips: int = DEFAULT_MAX_TRACKED_IPS,
|
||||
):
|
||||
# Ordered by last activity (oldest first) so capacity eviction and the
|
||||
# periodic cleanup are both O(1)/O(expired) instead of a full rebuild.
|
||||
self.ips: OrderedDict[str, _IPRecord] = OrderedDict()
|
||||
self.count = count
|
||||
self.minutes = minutes
|
||||
self.max_ips = max(1, max_ips)
|
||||
|
||||
def _window_seconds(self) -> float:
|
||||
# minutes is mutable at runtime via apps.base.config._sync_ip_limits.
|
||||
return float(self.minutes) * 60
|
||||
|
||||
def check_ip(self, ip: str) -> bool:
|
||||
if ip in self.ips:
|
||||
ip_info = self.ips[ip]
|
||||
if ip_info["count"] >= self.count:
|
||||
if ip_info["time"] + timedelta(minutes=self.minutes) > datetime.now():
|
||||
return False
|
||||
self.ips.pop(ip)
|
||||
record = self.ips.get(ip)
|
||||
if record is None:
|
||||
return True
|
||||
if record["count"] >= self.count:
|
||||
if record["last_seen"] + self._window_seconds() > time.monotonic():
|
||||
return False
|
||||
self.ips.pop(ip, None)
|
||||
return True
|
||||
|
||||
def add_ip(self, ip: str) -> int:
|
||||
ip_info = self.ips.get(ip, {"count": 0, "time": datetime.now()})
|
||||
ip_info["count"] += 1
|
||||
ip_info["time"] = datetime.now()
|
||||
self.ips[ip] = ip_info
|
||||
return ip_info["count"]
|
||||
now = time.monotonic()
|
||||
record = self.ips.get(ip)
|
||||
if record is None:
|
||||
record = {"count": 0, "last_seen": now}
|
||||
self.ips[ip] = record
|
||||
else:
|
||||
self.ips.move_to_end(ip)
|
||||
record["count"] += 1
|
||||
record["last_seen"] = now
|
||||
while len(self.ips) > self.max_ips:
|
||||
# Evict the least recently active IP; fail-open for the evicted
|
||||
# address is preferable to unbounded memory growth.
|
||||
self.ips.popitem(last=False)
|
||||
return record["count"]
|
||||
|
||||
async def remove_expired_ip(self) -> None:
|
||||
now = datetime.now()
|
||||
expiration = timedelta(minutes=self.minutes)
|
||||
self.ips = {
|
||||
ip: info
|
||||
for ip, info in self.ips.items()
|
||||
if info["time"] + expiration >= now
|
||||
}
|
||||
now = time.monotonic()
|
||||
window = self._window_seconds()
|
||||
while self.ips:
|
||||
_, record = next(iter(self.ips.items()))
|
||||
if record["last_seen"] + window >= now:
|
||||
break
|
||||
self.ips.popitem(last=False)
|
||||
|
||||
def __call__(self, request: Request) -> str:
|
||||
ip = (
|
||||
request.headers.get("X-Real-IP")
|
||||
or request.headers.get("X-Forwarded-For")
|
||||
or request.client.host
|
||||
)
|
||||
ip = get_client_ip(request)
|
||||
if not self.check_ip(ip):
|
||||
raise HTTPException(status_code=423, detail="请求次数过多,请稍后再试")
|
||||
return ip
|
||||
@@ -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,104 @@
|
||||
"""Local NAS-style share helpers.
|
||||
|
||||
Files under ``data/local`` can be browsed by admin and turned into extract
|
||||
codes without copying them into ``data/share``. The original file is never
|
||||
deleted when a share expires or is removed from the file list.
|
||||
|
||||
``FileCodes.file_path`` is the sentinel ``local-ref``; ``uuid_file_name``
|
||||
stores the posix relative path under ``data/local``. Accidental storage
|
||||
deletes therefore look at ``data/local-ref/...`` and cannot touch the
|
||||
original NAS file.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from core.errors import StorageError
|
||||
from core.storage import StoredDownload, build_attachment_headers
|
||||
|
||||
LOCAL_REF_MARKER = "local-ref"
|
||||
MAX_RELPATH_LEN = 255
|
||||
MAX_LIST_ENTRIES = 500
|
||||
|
||||
|
||||
def is_local_ref(file_code) -> bool:
|
||||
return (getattr(file_code, "file_path", None) or "") == LOCAL_REF_MARKER
|
||||
|
||||
|
||||
def should_skip_storage_delete(file_code) -> bool:
|
||||
return is_local_ref(file_code) or getattr(file_code, "text", None) is not None
|
||||
|
||||
|
||||
def get_local_root() -> Path:
|
||||
from core.settings import data_root
|
||||
|
||||
root = (Path(data_root) / "local").resolve()
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
return root
|
||||
|
||||
|
||||
def normalize_local_relpath(raw: str, *, allow_empty: bool = False) -> str:
|
||||
text = str(raw or "").replace("\\", "/").strip()
|
||||
if not text:
|
||||
if allow_empty:
|
||||
return ""
|
||||
raise HTTPException(status_code=400, detail="非法文件名")
|
||||
if (
|
||||
text in {".", ".."}
|
||||
or text.startswith("/")
|
||||
or text.startswith("~")
|
||||
or "\x00" in text
|
||||
or ":" in text.split("/", 1)[0]
|
||||
):
|
||||
raise HTTPException(status_code=400, detail="非法文件名")
|
||||
|
||||
parts = [part for part in text.split("/") if part not in {"", "."}]
|
||||
if not parts or any(part == ".." for part in parts):
|
||||
raise HTTPException(status_code=400, detail="非法文件名")
|
||||
|
||||
relpath = "/".join(parts)
|
||||
if len(relpath) > MAX_RELPATH_LEN:
|
||||
raise HTTPException(status_code=400, detail="路径过长")
|
||||
return relpath
|
||||
|
||||
|
||||
def resolve_under_local(relpath: str) -> Path:
|
||||
root = get_local_root()
|
||||
if not relpath:
|
||||
return root
|
||||
candidate = (root / relpath).resolve()
|
||||
try:
|
||||
candidate.relative_to(root)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail="非法文件路径") from exc
|
||||
return candidate
|
||||
|
||||
|
||||
def format_local_ctime(path: Path) -> str | None:
|
||||
try:
|
||||
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(path.stat().st_ctime))
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def build_local_ref_download(file_code) -> StoredDownload:
|
||||
try:
|
||||
relpath = normalize_local_relpath(getattr(file_code, "uuid_file_name", None) or "")
|
||||
path = resolve_under_local(relpath)
|
||||
except HTTPException as exc:
|
||||
raise StorageError(status_code=404, detail="文件已过期删除") from exc
|
||||
if not path.is_file():
|
||||
raise StorageError(status_code=404, detail="文件已过期删除")
|
||||
|
||||
filename = f"{getattr(file_code, 'prefix', '') or ''}{getattr(file_code, 'suffix', '') or ''}"
|
||||
if not filename:
|
||||
filename = path.name
|
||||
headers = build_attachment_headers(filename)
|
||||
try:
|
||||
headers["Content-Length"] = str(path.stat().st_size)
|
||||
except OSError:
|
||||
pass
|
||||
return StoredDownload(filename=filename, headers=headers, path=path)
|
||||
@@ -0,0 +1,231 @@
|
||||
"""Stateless MCP Streamable HTTP endpoint for quick share uploads."""
|
||||
import base64
|
||||
import binascii
|
||||
import html
|
||||
import io
|
||||
import json
|
||||
from typing import Any
|
||||
from urllib.parse import quote, urlsplit
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, UploadFile
|
||||
from starlette.datastructures import Headers
|
||||
from starlette.responses import JSONResponse, Response
|
||||
|
||||
from apps.base.auth import _require_admin_payload
|
||||
from apps.base.file_validation import validate_file_type, validate_upload_file
|
||||
from apps.base.services import FileUploadService, validate_file_size
|
||||
from apps.base.utils import ip_limit, validate_expire_style
|
||||
from core.settings import settings
|
||||
from core.utils import sanitize_filename
|
||||
|
||||
router = APIRouter(tags=["MCP"])
|
||||
|
||||
MCP_PROTOCOL_VERSION = "2025-03-26"
|
||||
TEXT_SHARE_MAX_BYTES = 222 * 1024
|
||||
MAX_MCP_BODY_BYTES = 64 * 1024 * 1024
|
||||
|
||||
|
||||
def _jsonrpc_error(request_id, code: int, message: str) -> dict:
|
||||
return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}}
|
||||
|
||||
|
||||
def _jsonrpc_result(request_id, result: dict) -> dict:
|
||||
return {"jsonrpc": "2.0", "id": request_id, "result": result}
|
||||
|
||||
|
||||
def _validate_origin(request: Request) -> None:
|
||||
"""Reject browser cross-site POSTs before parsing any upload tool."""
|
||||
origin = request.headers.get("origin")
|
||||
fetch_site = request.headers.get("sec-fetch-site", "").lower()
|
||||
if fetch_site == "cross-site":
|
||||
raise HTTPException(status_code=403, detail="跨站请求已拒绝")
|
||||
if not origin:
|
||||
return # Native MCP clients do not send Origin and use no ambient cookies.
|
||||
try:
|
||||
parsed = urlsplit(origin)
|
||||
host = request.headers.get("host", "").lower()
|
||||
if (
|
||||
parsed.scheme not in {"http", "https"}
|
||||
or not parsed.netloc
|
||||
or parsed.netloc.lower() != host
|
||||
or parsed.username is not None
|
||||
or parsed.password is not None
|
||||
or parsed.path not in {"", "/"}
|
||||
or parsed.query
|
||||
or parsed.fragment
|
||||
):
|
||||
raise ValueError("origin mismatch")
|
||||
except (ValueError, TypeError):
|
||||
raise HTTPException(status_code=403, detail="跨站请求已拒绝")
|
||||
|
||||
|
||||
async def _read_limited_body(request: Request) -> bytes:
|
||||
max_size = min(
|
||||
MAX_MCP_BODY_BYTES,
|
||||
max(1024 * 1024, int(settings.upload_size * 4 / 3) + 256 * 1024),
|
||||
)
|
||||
declared_size = request.headers.get("content-length")
|
||||
if declared_size:
|
||||
try:
|
||||
if int(declared_size) > max_size:
|
||||
raise HTTPException(status_code=413, detail="MCP 请求体过大")
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Content-Length 无效")
|
||||
body = bytearray()
|
||||
async for chunk in request.stream():
|
||||
body.extend(chunk)
|
||||
if len(body) > max_size:
|
||||
raise HTTPException(status_code=413, detail="MCP 请求体过大")
|
||||
return bytes(body)
|
||||
|
||||
|
||||
def _tool_definitions() -> list[dict]:
|
||||
return [
|
||||
{
|
||||
"name": "share_text",
|
||||
"description": "将文本快速上传到 FileCodeBox 并创建分享链接。",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"text": {"type": "string", "description": "要分享的文本"},
|
||||
"expire_value": {"type": "integer", "minimum": 1, "default": 1},
|
||||
"expire_style": {"type": "string", "enum": ["day", "hour", "minute", "forever", "count"], "default": "day"},
|
||||
},
|
||||
"required": ["text"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "share_file",
|
||||
"description": "将 Base64 编码的文件上传到 FileCodeBox 并创建分享链接。",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"filename": {"type": "string", "description": "文件名"},
|
||||
"content_base64": {"type": "string", "description": "文件内容的标准 Base64 编码"},
|
||||
"content_type": {"type": "string", "default": "application/octet-stream"},
|
||||
"expire_value": {"type": "integer", "minimum": 1, "default": 1},
|
||||
"expire_style": {"type": "string", "enum": ["day", "hour", "minute", "forever", "count"], "default": "day"},
|
||||
},
|
||||
"required": ["filename", "content_base64"],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def _share_result(request: Request, code: str, name: str) -> dict:
|
||||
base_url = str(request.base_url).rstrip("/")
|
||||
share_url = f"{base_url}/#/?code={quote(code, safe='')}"
|
||||
markdown_name = html.escape(name).replace("[", "\\[").replace("]", "\\]")
|
||||
return {
|
||||
"code": code,
|
||||
"name": name,
|
||||
"url": share_url,
|
||||
"markdown": f"[{markdown_name}]({share_url})",
|
||||
}
|
||||
|
||||
|
||||
async def _call_tool(request: Request, tool_name: str, arguments: dict) -> dict:
|
||||
authorization = request.headers.get("authorization", "")
|
||||
if settings.mcp_require_token or not settings.open_upload:
|
||||
_require_admin_payload(authorization)
|
||||
ip = ip_limit["upload"](request)
|
||||
|
||||
if tool_name == "share_text":
|
||||
text = arguments.get("text")
|
||||
if not isinstance(text, str):
|
||||
raise ValueError("text 必须是字符串")
|
||||
if len(text.encode("utf-8")) > TEXT_SHARE_MAX_BYTES:
|
||||
raise ValueError("内容过多,请改用文件分享")
|
||||
expire_value = int(arguments.get("expire_value", 1))
|
||||
expire_style = str(arguments.get("expire_style", "day"))
|
||||
if expire_value < 1:
|
||||
raise ValueError("expire_value 必须大于 0")
|
||||
validate_expire_style(expire_style)
|
||||
code = await FileUploadService.create_text_share(text, expire_value, expire_style)
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
return _share_result(request, code, "Text")
|
||||
|
||||
if tool_name == "share_file":
|
||||
filename = arguments.get("filename")
|
||||
encoded_content = arguments.get("content_base64")
|
||||
content_type = str(arguments.get("content_type", "application/octet-stream"))
|
||||
if not isinstance(filename, str) or not filename.strip():
|
||||
raise ValueError("filename 不能为空")
|
||||
if not isinstance(encoded_content, str):
|
||||
raise ValueError("content_base64 必须是字符串")
|
||||
try:
|
||||
content = base64.b64decode(encoded_content, validate=True)
|
||||
except (ValueError, binascii.Error):
|
||||
raise ValueError("content_base64 不是有效的标准 Base64")
|
||||
safe_name = await sanitize_filename(filename.rsplit("/", 1)[-1].rsplit("\\", 1)[-1])
|
||||
validate_file_type(safe_name, content_type)
|
||||
upload = UploadFile(filename=safe_name, file=io.BytesIO(content), size=len(content), headers=Headers({"content-type": content_type}))
|
||||
size = await validate_file_size(upload, settings.upload_size)
|
||||
await validate_upload_file(upload)
|
||||
expire_value = int(arguments.get("expire_value", 1))
|
||||
expire_style = str(arguments.get("expire_style", "day"))
|
||||
if expire_value < 1:
|
||||
raise ValueError("expire_value 必须大于 0")
|
||||
validate_expire_style(expire_style)
|
||||
share = await FileUploadService.create_file_share(upload, size=size, expire_value=expire_value, expire_style=expire_style)
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
return _share_result(request, share["code"], share["name"])
|
||||
|
||||
raise LookupError(f"未知工具:{tool_name}")
|
||||
|
||||
|
||||
@router.post("/mcp", include_in_schema=False)
|
||||
async def mcp_endpoint(request: Request):
|
||||
_validate_origin(request)
|
||||
media_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
||||
if media_type != "application/json":
|
||||
raise HTTPException(status_code=415, detail="MCP 请求必须使用 application/json")
|
||||
try:
|
||||
message = json.loads(await _read_limited_body(request))
|
||||
except (json.JSONDecodeError, UnicodeDecodeError):
|
||||
return JSONResponse(_jsonrpc_error(None, -32700, "Parse error"), status_code=400)
|
||||
if not isinstance(message, dict) or message.get("jsonrpc") != "2.0" or not isinstance(message.get("method"), str):
|
||||
return JSONResponse(_jsonrpc_error(message.get("id") if isinstance(message, dict) else None, -32600, "Invalid Request"), status_code=400)
|
||||
|
||||
request_id = message.get("id")
|
||||
method = message["method"]
|
||||
if request_id is None and method.startswith("notifications/"):
|
||||
return Response(status_code=202)
|
||||
result: dict[str, Any] = {}
|
||||
try:
|
||||
if method == "initialize":
|
||||
result = {
|
||||
"protocolVersion": MCP_PROTOCOL_VERSION,
|
||||
"capabilities": {"tools": {"listChanged": False}},
|
||||
"serverInfo": {"name": "filecodebox", "version": "1.0.0"},
|
||||
}
|
||||
elif method == "ping":
|
||||
result = {}
|
||||
elif method == "tools/list":
|
||||
result = {"tools": _tool_definitions()}
|
||||
elif method == "tools/call":
|
||||
params = message.get("params")
|
||||
if not isinstance(params, dict) or not isinstance(params.get("name"), str):
|
||||
return JSONResponse(_jsonrpc_error(request_id, -32602, "Invalid params"))
|
||||
arguments = params.get("arguments", {})
|
||||
if not isinstance(arguments, dict):
|
||||
return JSONResponse(_jsonrpc_error(request_id, -32602, "Invalid params"))
|
||||
try:
|
||||
tool_value = await _call_tool(request, params["name"], arguments)
|
||||
result = {"content": [{"type": "text", "text": json.dumps(tool_value, ensure_ascii=False)}], "structuredContent": tool_value}
|
||||
except LookupError as exc:
|
||||
return JSONResponse(_jsonrpc_error(request_id, -32602, str(exc)))
|
||||
except HTTPException as exc:
|
||||
if exc.status_code in {401, 403}:
|
||||
raise
|
||||
result = {"content": [{"type": "text", "text": str(exc.detail)}], "isError": True}
|
||||
except (TypeError, ValueError) as exc:
|
||||
result = {"content": [{"type": "text", "text": str(exc)}], "isError": True}
|
||||
else:
|
||||
return JSONResponse(_jsonrpc_error(request_id, -32601, "Method not found"))
|
||||
return JSONResponse(_jsonrpc_result(request_id, result), headers={"MCP-Protocol-Version": MCP_PROTOCOL_VERSION})
|
||||
except HTTPException as exc:
|
||||
return JSONResponse(
|
||||
_jsonrpc_error(request_id, -32001 if exc.status_code == 401 else -32003, str(exc.detail)),
|
||||
status_code=exc.status_code,
|
||||
)
|
||||
@@ -0,0 +1,28 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
async def create_upload_chunk_and_update_file_codes_table():
|
||||
conn = connections.get("default")
|
||||
await conn.execute_script(
|
||||
"""
|
||||
ALTER TABLE "filecodes" ADD "file_hash" VARCHAR(128);
|
||||
ALTER TABLE "filecodes" ADD "is_chunked" BOOL NOT NULL DEFAULT False;
|
||||
ALTER TABLE "filecodes" ADD "upload_id" VARCHAR(128);
|
||||
CREATE TABLE "uploadchunk" (
|
||||
id INTEGER not null primary key autoincrement,
|
||||
"upload_id" VARCHAR(36) NOT NULL,
|
||||
"chunk_index" INT NOT NULL,
|
||||
"chunk_hash" VARCHAR(128) NOT NULL,
|
||||
"total_chunks" INT NOT NULL,
|
||||
"file_size" BIGINT NOT NULL,
|
||||
"chunk_size" INT NOT NULL,
|
||||
"created_at" TIMESTAMPTZ NOT NULL,
|
||||
"file_name" VARCHAR(255) NOT NULL,
|
||||
"completed" BOOL NOT NULL
|
||||
);
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
async def migrate():
|
||||
await create_upload_chunk_and_update_file_codes_table()
|
||||
@@ -0,0 +1,26 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
async def create_presign_upload_session_table():
|
||||
conn = connections.get("default")
|
||||
await conn.execute_script(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS presignuploadsession (
|
||||
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
upload_id VARCHAR(36) NOT NULL UNIQUE,
|
||||
file_name VARCHAR(255) NOT NULL,
|
||||
file_size BIGINT NOT NULL,
|
||||
save_path VARCHAR(512) NOT NULL,
|
||||
mode VARCHAR(10) NOT NULL,
|
||||
expire_value INT NOT NULL DEFAULT 1,
|
||||
expire_style VARCHAR(20) NOT NULL DEFAULT 'day',
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at TIMESTAMP NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_presignuploadsession_upload_id ON presignuploadsession (upload_id);
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
async def migrate():
|
||||
await create_presign_upload_session_table()
|
||||
@@ -0,0 +1,14 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
async def add_save_path_to_uploadchunk():
|
||||
conn = connections.get("default")
|
||||
await conn.execute_script(
|
||||
"""
|
||||
ALTER TABLE uploadchunk ADD COLUMN save_path VARCHAR(512) NULL;
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
async def migrate():
|
||||
await add_save_path_to_uploadchunk()
|
||||
@@ -0,0 +1,72 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
def _need_upgrade(columns: list[tuple]) -> bool:
|
||||
for column in columns:
|
||||
# PRAGMA table_info 返回 (cid, name, type, notnull, dflt_value, pk)
|
||||
if column[1] == "size":
|
||||
column_type = (column[2] or "").upper()
|
||||
return "BIGINT" not in column_type
|
||||
return False
|
||||
|
||||
|
||||
async def migrate():
|
||||
conn = connections.get("default")
|
||||
result = await conn.execute_query("PRAGMA table_info(filecodes)")
|
||||
columns = result[1] if result and len(result) > 1 else []
|
||||
|
||||
if not columns or not _need_upgrade(columns):
|
||||
return
|
||||
|
||||
await conn.execute_script(
|
||||
"""
|
||||
BEGIN;
|
||||
CREATE TABLE IF NOT EXISTS filecodes_new
|
||||
(
|
||||
id INTEGER not null
|
||||
primary key autoincrement,
|
||||
code VARCHAR(255) not null
|
||||
unique,
|
||||
prefix VARCHAR(255) default '' not null,
|
||||
suffix VARCHAR(255) default '' not null,
|
||||
uuid_file_name VARCHAR(255),
|
||||
file_path VARCHAR(255),
|
||||
size BIGINT default 0 not null,
|
||||
text TEXT,
|
||||
expired_at TIMESTAMP,
|
||||
expired_count INT default 0 not null,
|
||||
used_count INT default 0 not null,
|
||||
created_at TIMESTAMP default CURRENT_TIMESTAMP not null,
|
||||
file_hash VARCHAR(128),
|
||||
is_chunked BOOL default False not null,
|
||||
upload_id VARCHAR(128)
|
||||
);
|
||||
|
||||
INSERT INTO filecodes_new (id, code, prefix, suffix, uuid_file_name, file_path, size, text,
|
||||
expired_at, expired_count, used_count, created_at, file_hash,
|
||||
is_chunked, upload_id)
|
||||
SELECT id,
|
||||
code,
|
||||
prefix,
|
||||
suffix,
|
||||
uuid_file_name,
|
||||
file_path,
|
||||
size,
|
||||
text,
|
||||
expired_at,
|
||||
expired_count,
|
||||
used_count,
|
||||
created_at,
|
||||
file_hash,
|
||||
is_chunked,
|
||||
upload_id
|
||||
FROM filecodes;
|
||||
|
||||
DROP TABLE filecodes;
|
||||
ALTER TABLE filecodes_new
|
||||
RENAME TO filecodes;
|
||||
CREATE INDEX IF NOT EXISTS idx_filecodes_code_1c7ee7
|
||||
on filecodes (code);
|
||||
COMMIT;
|
||||
"""
|
||||
)
|
||||
@@ -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"]],
|
||||
)
|
||||
@@ -0,0 +1,26 @@
|
||||
from tortoise import connections
|
||||
|
||||
# 高频查询字段索引。真实部署的 schema 全部由迁移建立
|
||||
# (init_db 不调用 generate_schemas),因此索引必须写在迁移里;
|
||||
# apps/base/models.py 中的 index/Meta 仅用于测试的 generate_schemas 路径。
|
||||
#
|
||||
# - filecodes(expired_at):过期扫描(delete_expire_files)与后台过期统计。
|
||||
# - filecodes(created_at):后台默认倒序列表、首页最近记录、今日/昨日统计。
|
||||
# - uploadchunk(upload_id, chunk_index):分片状态检查与合并;其前缀同时
|
||||
# 覆盖仅按 upload_id 的删除/清理查询(原先没有对应索引)。
|
||||
# 已知缺口:clean_incomplete_uploads 的 chunk_index=-1 AND created_at<? 用不上
|
||||
# 该复合索引,待清理任务改为分批查询后再评估。
|
||||
|
||||
|
||||
async def migrate():
|
||||
conn = connections.get("default")
|
||||
await conn.execute_script(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_filecodes_expired_at
|
||||
ON filecodes (expired_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_filecodes_created_at
|
||||
ON filecodes (created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_uploadchunk_upload_chunk
|
||||
ON uploadchunk (upload_id, chunk_index);
|
||||
"""
|
||||
)
|
||||
@@ -2,130 +2,108 @@
|
||||
# @Author : Lan
|
||||
# @File : models.py
|
||||
# @Software: PyCharm
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from tortoise import fields
|
||||
from typing import Any
|
||||
|
||||
from tortoise.models import Model
|
||||
from tortoise.contrib.pydantic import pydantic_model_creator
|
||||
|
||||
from tortoise import fields, models
|
||||
from core.utils import get_now
|
||||
|
||||
|
||||
class FileCodes(Model):
|
||||
id: Optional[int] = fields.IntField(pk=True)
|
||||
code: Optional[int] = fields.CharField(
|
||||
description="分享码", max_length=255, index=True, unique=True
|
||||
)
|
||||
prefix: Optional[str] = fields.CharField(
|
||||
max_length=255, description="前缀", default=""
|
||||
)
|
||||
suffix: Optional[str] = fields.CharField(
|
||||
max_length=255, description="后缀", default=""
|
||||
)
|
||||
uuid_file_name: Optional[str] = fields.CharField(
|
||||
max_length=255, description="uuid文件名", null=True
|
||||
)
|
||||
file_path: Optional[str] = fields.CharField(
|
||||
max_length=255, description="文件路径", null=True
|
||||
)
|
||||
size: Optional[int] = fields.IntField(description="文件大小", default=0)
|
||||
text: Optional[str] = fields.TextField(description="文本内容", null=True)
|
||||
expired_at: Optional[datetime] = fields.DatetimeField(
|
||||
null=True, description="过期时间"
|
||||
)
|
||||
expired_count: Optional[int] = fields.IntField(description="可用次数", default=0)
|
||||
used_count: Optional[int] = fields.IntField(description="已用次数", default=0)
|
||||
created_at: Optional[datetime] = fields.DatetimeField(
|
||||
auto_now_add=True, description="创建时间"
|
||||
)
|
||||
#
|
||||
# file_hash = fields.CharField(
|
||||
# max_length=128, # SHA-256需要64字符,这里预留扩展空间
|
||||
# description="文件哈希值",
|
||||
# unique=True,
|
||||
# null=True # 允许旧数据为空
|
||||
# )
|
||||
# hash_algorithm = fields.CharField(
|
||||
# max_length=20,
|
||||
# description="哈希算法类型",
|
||||
# null=True,
|
||||
# default="sha256"
|
||||
# )
|
||||
|
||||
# # 新增分片字段
|
||||
# chunk_size = fields.IntField(
|
||||
# description="分片大小(字节)",
|
||||
# default=0
|
||||
# )
|
||||
# total_chunks = fields.IntField(
|
||||
# description="总分片数",
|
||||
# default=0
|
||||
# )
|
||||
# uploaded_chunks = fields.IntField(
|
||||
# description="已上传分片数",
|
||||
# default=0
|
||||
# )
|
||||
# upload_status = fields.CharField(
|
||||
# max_length=20,
|
||||
# description="上传状态",
|
||||
# default="pending", # pending/in_progress/completed
|
||||
# choices=["pending", "in_progress", "completed"]
|
||||
# )
|
||||
# is_chunked = fields.BooleanField(
|
||||
# description="是否分片上传",
|
||||
# default=False
|
||||
# )
|
||||
class FileCodes(models.Model):
|
||||
id = fields.IntField(pk=True)
|
||||
code = fields.CharField(max_length=255, unique=True, index=True)
|
||||
prefix = fields.CharField(max_length=255, default="")
|
||||
suffix = fields.CharField(max_length=255, default="")
|
||||
uuid_file_name = fields.CharField(max_length=255, null=True)
|
||||
file_path = fields.CharField(max_length=255, null=True)
|
||||
size = fields.BigIntField(default=0)
|
||||
text = fields.TextField(null=True)
|
||||
# 过期扫描与后台过期统计的高频过滤列
|
||||
expired_at = fields.DatetimeField(null=True, index=True)
|
||||
# -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, index=True)
|
||||
file_hash = fields.CharField(max_length=64, null=True)
|
||||
is_chunked = fields.BooleanField(default=False)
|
||||
upload_id = fields.CharField(max_length=36, null=True)
|
||||
|
||||
async def is_expired(self):
|
||||
# 按时间
|
||||
if self.expired_at is None:
|
||||
return False
|
||||
if self.expired_at and self.expired_count < 0:
|
||||
return self.expired_at < await get_now()
|
||||
# 按次数
|
||||
else:
|
||||
return self.expired_count <= 0
|
||||
return self.expired_count <= 0
|
||||
|
||||
async def get_file_path(self):
|
||||
return f"{self.file_path}/{self.uuid_file_name}"
|
||||
|
||||
|
||||
#
|
||||
# class FileChunks(Model):
|
||||
# id = fields.IntField(pk=True)
|
||||
# file_code = fields.ForeignKeyField(
|
||||
# "models.FileCodes",
|
||||
# related_name="chunks",
|
||||
# on_delete=fields.CASCADE
|
||||
# )
|
||||
# chunk_number = fields.IntField(description="分片序号")
|
||||
# chunk_hash = fields.CharField(
|
||||
# max_length=128,
|
||||
# description="分片哈希校验值"
|
||||
# )
|
||||
# chunk_path = fields.CharField(
|
||||
# max_length=255,
|
||||
# description="分片存储路径"
|
||||
# )
|
||||
# created_at = fields.DatetimeField(
|
||||
# auto_now_add=True,
|
||||
# description="上传时间"
|
||||
# )
|
||||
#
|
||||
# class Meta:
|
||||
# unique_together = [("file_code", "chunk_number")]
|
||||
class UploadChunk(models.Model):
|
||||
id = fields.IntField(pk=True)
|
||||
# 上传会话/分片查询始终同时带 upload_id;复合索引前缀已覆盖仅按 upload_id
|
||||
# 的删除与清理查询,单列索引会造成重复。
|
||||
upload_id = fields.CharField(max_length=36)
|
||||
chunk_index = fields.IntField()
|
||||
chunk_hash = fields.CharField(max_length=64)
|
||||
total_chunks = fields.IntField()
|
||||
file_size = fields.BigIntField()
|
||||
chunk_size = fields.IntField()
|
||||
file_name = fields.CharField(max_length=255)
|
||||
save_path = fields.CharField(max_length=512, null=True)
|
||||
created_at = fields.DatetimeField(auto_now_add=True)
|
||||
completed = fields.BooleanField(default=False)
|
||||
|
||||
class Meta:
|
||||
indexes = [("upload_id", "chunk_index")]
|
||||
|
||||
|
||||
class KeyValue(Model):
|
||||
id: Optional[int] = fields.IntField(pk=True)
|
||||
key: Optional[str] = fields.CharField(
|
||||
max_length=255, description="键", index=True, unique=True
|
||||
)
|
||||
value: Optional[str] = fields.JSONField(description="值", null=True)
|
||||
created_at: Optional[datetime] = fields.DatetimeField(
|
||||
auto_now_add=True, description="创建时间"
|
||||
)
|
||||
# 与 FileCodes 保持同一风格:类属性不写值注解(等号右侧的 Field 描述符
|
||||
# 才是类级真身;实例级由 tortoise 运行时给出对应 Python 值)
|
||||
id = fields.IntField(pk=True)
|
||||
key = fields.CharField(max_length=255, description="键", index=True, unique=True)
|
||||
# JSONField 实际承载 dict/list(如 settings 配置)
|
||||
value: Any = fields.JSONField(description="值", null=True)
|
||||
created_at = fields.DatetimeField(auto_now_add=True, description="创建时间")
|
||||
|
||||
|
||||
class PresignUploadSession(models.Model):
|
||||
"""预签名上传会话模型"""
|
||||
|
||||
id = fields.IntField(pk=True)
|
||||
upload_id = fields.CharField(max_length=36, unique=True, index=True)
|
||||
file_name = fields.CharField(max_length=255)
|
||||
file_size = fields.BigIntField()
|
||||
save_path = fields.CharField(max_length=512)
|
||||
mode = fields.CharField(max_length=10) # "direct" 或 "proxy"
|
||||
expire_value = fields.IntField(default=1)
|
||||
expire_style = fields.CharField(max_length=20, default="day")
|
||||
created_at = fields.DatetimeField(auto_now_add=True)
|
||||
expires_at = fields.DatetimeField() # 会话过期时间
|
||||
|
||||
async def is_expired(self):
|
||||
"""检查会话是否已过期"""
|
||||
return self.expires_at < await get_now()
|
||||
|
||||
|
||||
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")
|
||||
presign_upload_session_pydantic = pydantic_model_creator(
|
||||
PresignUploadSession, name="PresignUploadSession"
|
||||
)
|
||||
@@ -0,0 +1,223 @@
|
||||
"""Public-facing pages and routes: setup wizard, theme assets, index,
|
||||
robots.txt, and the public config endpoints."""
|
||||
import html
|
||||
import re
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, 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
|
||||
|
||||
|
||||
# Vite 产物带内容指纹(如 index-BX2s1QqP.js),内容变化时文件名必然变化,
|
||||
# 可以安全地长缓存;public/ 下的未哈希资源原地升级时名字不变,只给短缓存,
|
||||
# 过期后靠 FileResponse 自带的 ETag/Last-Modified 走 304。
|
||||
_HASHED_ASSET_RE = re.compile(
|
||||
r"-[A-Za-z0-9_-]{8,}\.(?:js|mjs|css|map|woff2?|ttf|otf|eot|svg|png|jpe?g|gif|webp|avif|ico)$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_IMMUTABLE_ASSET_CACHE = "public, max-age=31536000, immutable"
|
||||
_DEFAULT_ASSET_CACHE = "public, max-age=86400"
|
||||
|
||||
|
||||
def _asset_cache_control(asset_path: str) -> str:
|
||||
if _HASHED_ASSET_RE.search(asset_path):
|
||||
return _IMMUTABLE_ASSET_CACHE
|
||||
return _DEFAULT_ASSET_CACHE
|
||||
|
||||
|
||||
@lru_cache(maxsize=8)
|
||||
def _render_index_html(
|
||||
template_path: str,
|
||||
inode: int,
|
||||
mtime_ns: int,
|
||||
size: int,
|
||||
title: str,
|
||||
description: str,
|
||||
keywords: str,
|
||||
opacity: str,
|
||||
background: str,
|
||||
) -> str:
|
||||
"""Render index.html once per (theme file version, site config) pair.
|
||||
|
||||
The stat fields keep the cache honest when a theme is replaced in place;
|
||||
config values are part of the key so admin edits are visible immediately
|
||||
without any cross-module invalidation hook.
|
||||
"""
|
||||
return (
|
||||
Path(template_path)
|
||||
.read_text(encoding="utf-8")
|
||||
.replace("{{title}}", html.escape(title))
|
||||
.replace("{{description}}", html.escape(description))
|
||||
.replace("{{keywords}}", html.escape(keywords))
|
||||
.replace("{{opacity}}", html.escape(opacity))
|
||||
.replace("{{background}}", html.escape(background))
|
||||
)
|
||||
|
||||
|
||||
@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),
|
||||
headers={"Cache-Control": _asset_cache_control(asset_path)},
|
||||
)
|
||||
|
||||
|
||||
async def not_found_handler(request, exc=None):
|
||||
"""区分"浏览器导航到未知路径"与"API 处理器抛出的 404"。
|
||||
|
||||
Starlette 的 status-code handler 优先于 HTTPException 类 handler,
|
||||
直接注册 index 会让全应用所有 HTTPException(404) 变成 200 HTML 页
|
||||
(负路径测试抓到的存量 bug)。浏览器(Accept 含 text/html)仍拿到
|
||||
主题首页做 SPA 兜底;API 客户端拿到 JSON 404。
|
||||
"""
|
||||
json_404 = JSONResponse(
|
||||
status_code=404,
|
||||
content={"code": 404, "message": "Not Found", "detail": "资源不存在"},
|
||||
)
|
||||
if request is not None and request.method in {"GET", "HEAD"} and "text/html" in (
|
||||
request.headers.get("accept", "")
|
||||
):
|
||||
try:
|
||||
return await index(request, exc)
|
||||
except HTTPException:
|
||||
return json_404
|
||||
return json_404
|
||||
|
||||
|
||||
@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).
|
||||
template_path = resolve_theme_file("index.html")
|
||||
try:
|
||||
stat_result = template_path.stat()
|
||||
except OSError:
|
||||
# resolve_theme_file 与 stat 之间文件被删除/替换时仍按 404 处理,
|
||||
# 不能退回缓存内容。
|
||||
raise HTTPException(status_code=404, detail="资源不存在")
|
||||
content = _render_index_html(
|
||||
str(template_path),
|
||||
stat_result.st_ino,
|
||||
stat_result.st_mtime_ns,
|
||||
stat_result.st_size,
|
||||
str(settings.name),
|
||||
str(settings.description),
|
||||
str(settings.keywords),
|
||||
str(settings.opacity),
|
||||
str(settings.background),
|
||||
)
|
||||
return HTMLResponse(
|
||||
content=content,
|
||||
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,132 @@
|
||||
import datetime
|
||||
|
||||
from fastapi import HTTPException
|
||||
from tortoise import connections
|
||||
from tortoise.expressions import Q
|
||||
from tortoise.functions import Sum
|
||||
|
||||
from apps.base.models import FileCodes, StorageReservation
|
||||
from apps.base.local_share import LOCAL_REF_MARKER
|
||||
from core.settings import settings
|
||||
from core.utils import get_now
|
||||
|
||||
|
||||
def owned_storage_queryset(queryset=None):
|
||||
"""FileCodes that occupy FileCodeBox storage (exclude NAS local-ref rows).
|
||||
|
||||
SQL ``file_path != 'local-ref'`` drops NULLs, so keep null paths explicitly.
|
||||
"""
|
||||
qs = FileCodes.all() if queryset is None else queryset
|
||||
return qs.filter(Q(file_path__isnull=True) | ~Q(file_path=LOCAL_REF_MARKER))
|
||||
|
||||
|
||||
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 owned_storage_queryset().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 WHERE file_path IS NULL OR file_path != '{LOCAL_REF_MARKER}'), 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()
|
||||
@@ -3,3 +3,33 @@ from pydantic import BaseModel
|
||||
|
||||
class SelectFileModel(BaseModel):
|
||||
code: str
|
||||
|
||||
|
||||
class InitChunkUploadModel(BaseModel):
|
||||
file_name: str
|
||||
chunk_size: int = 5 * 1024 * 1024
|
||||
file_size: int
|
||||
file_hash: str
|
||||
|
||||
|
||||
class CompleteUploadModel(BaseModel):
|
||||
expire_value: int
|
||||
expire_style: str
|
||||
|
||||
|
||||
# 预签名上传相关模型
|
||||
class PresignUploadInitRequest(BaseModel):
|
||||
"""预签名上传初始化请求"""
|
||||
file_name: str
|
||||
file_size: int
|
||||
expire_value: int = 1
|
||||
expire_style: str = "day"
|
||||
|
||||
|
||||
class PresignUploadInitResponse(BaseModel):
|
||||
"""预签名上传初始化响应"""
|
||||
upload_id: str
|
||||
upload_url: str
|
||||
mode: str # "direct" 或 "proxy"
|
||||
save_path: str
|
||||
expires_in: int # URL过期时间(秒)
|
||||
@@ -0,0 +1,435 @@
|
||||
"""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 tortoise.transactions import in_transaction
|
||||
|
||||
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.local_share import build_local_ref_download, is_local_ref
|
||||
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 get_stored_download(file_code, file_storage: FileStorageInterface | None = None) -> StoredDownload:
|
||||
if is_local_ref(file_code):
|
||||
return build_local_ref_download(file_code)
|
||||
storage = file_storage or storages[settings.file_storage]()
|
||||
return await storage.get_file_response(stored_file_of(file_code))
|
||||
|
||||
|
||||
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:
|
||||
# 无长度声明的上传(如 chunked 传输):必须走底层文件对象拿末尾偏移。
|
||||
# 注意两层都不能用:UploadFile.seek 只接受单参数(TypeError);
|
||||
# 底层 SpooledTemporaryFile.seek 是同步方法(不能 await)。
|
||||
file.file.seek(0, 2)
|
||||
size = file.file.tell()
|
||||
file.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)
|
||||
# UploadFile.filename 类型为 str | None;路径生成已用 "" 兜底,
|
||||
# 响应处保持 str 以匹配 dict[str, str] 契约
|
||||
return {"code": code, "name": file.filename or ""}
|
||||
|
||||
@staticmethod
|
||||
async def complete_chunked_upload(
|
||||
upload_id: str, chunk_info: UploadChunk, expire_value: int, expire_style: str
|
||||
) -> dict[str, str]:
|
||||
"""分片合并:配额 → 完整性/大小校验 → 合并 → 建分享记录 → 清理分片。
|
||||
|
||||
失败路径的配额释放与清理范围与原实现逐一对齐:
|
||||
完整性校验失败仅抛 400(预留由 TTL 兜底);合并失败清理分片文件后抛 500。
|
||||
"""
|
||||
if chunk_info.completed:
|
||||
raise HTTPException(409, "上传会话已完成,仅待清理")
|
||||
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, chunk_index__gte=0
|
||||
).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
|
||||
cleanup_succeeded = True
|
||||
if save_path:
|
||||
try:
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
except Exception:
|
||||
cleanup_succeeded = False
|
||||
logger.warning(
|
||||
"分片超限中止:清理分片文件失败 upload_id=%s",
|
||||
upload_id,
|
||||
exc_info=True,
|
||||
)
|
||||
if cleanup_succeeded:
|
||||
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
|
||||
)
|
||||
# 发布记录与会话终态一起提交;即使分享过期删除,会话也不能被复用。
|
||||
async with in_transaction() as connection:
|
||||
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,
|
||||
using_db=connection,
|
||||
)
|
||||
chunk_info.completed = True
|
||||
await chunk_info.save(using_db=connection, update_fields=["completed"])
|
||||
try:
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
except Exception:
|
||||
# 分享已创建:不把清理故障伪装成合并失败,保留会话供定时任务重试。
|
||||
logger.warning(
|
||||
"分片合并完成:清理临时分片文件失败 upload_id=%s",
|
||||
upload_id,
|
||||
exc_info=True,
|
||||
)
|
||||
else:
|
||||
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
|
||||
)
|
||||
if download.stream_factory is None:
|
||||
# 数据契约要求三者至少其一;防御性 500 语义
|
||||
raise ValueError("StoredDownload 缺少可用的下载载荷")
|
||||
return StreamingResponse(
|
||||
download.stream_factory(),
|
||||
media_type=download.media_type,
|
||||
headers=download.headers,
|
||||
background=download.background,
|
||||
)
|
||||
@@ -0,0 +1,694 @@
|
||||
"""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 typing import Any
|
||||
|
||||
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[str, Any], 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[str, Any], 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[str, Any],
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
# @Time : 2023/8/15 22:00
|
||||
# @Author : Lan
|
||||
# @File : tasks.py
|
||||
# @Software: PyCharm
|
||||
import asyncio
|
||||
import datetime
|
||||
import os
|
||||
|
||||
from tortoise.expressions import Q
|
||||
|
||||
from apps.base.models import (
|
||||
FileCodes,
|
||||
PresignUploadSession,
|
||||
StorageReservation,
|
||||
UploadChunk,
|
||||
)
|
||||
from apps.base.utils import ip_limit, get_chunk_file_path_name
|
||||
from apps.base.config import refresh_settings
|
||||
from core.logger import logger
|
||||
from core.settings import settings, data_root
|
||||
from core.storage import FileStorageInterface, StoredFile, storages
|
||||
from apps.base.services import stored_file_of
|
||||
from apps.base.local_share import is_local_ref
|
||||
from core.utils import get_now
|
||||
|
||||
async def delete_expire_files():
|
||||
while True:
|
||||
try:
|
||||
await refresh_settings()
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
# 遍历 share目录下的所有文件夹,删除空的文件夹,并判断父目录是否为空,如果为空也删除
|
||||
if settings.file_storage == "local":
|
||||
for root, dirs, files in os.walk(f"{data_root}/share/data"):
|
||||
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:
|
||||
if not is_local_ref(exp):
|
||||
await file_storage.delete_file(stored_file_of(exp))
|
||||
except Exception as e:
|
||||
logger.error(f"删除过期文件失败 code={exp.code}: {e}")
|
||||
try:
|
||||
await exp.delete()
|
||||
except Exception as e:
|
||||
logger.error(f"删除记录失败 code={exp.code}: {e}")
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
finally:
|
||||
await asyncio.sleep(600)
|
||||
|
||||
|
||||
async def clean_incomplete_uploads():
|
||||
while True:
|
||||
try:
|
||||
await refresh_settings()
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
expire_hours = getattr(settings, "chunk_expire_hours", 24)
|
||||
now = await get_now()
|
||||
expire_time = now - datetime.timedelta(hours=expire_hours)
|
||||
expired_sessions = await UploadChunk.filter(
|
||||
chunk_index=-1, created_at__lt=expire_time
|
||||
).all()
|
||||
|
||||
for session in expired_sessions:
|
||||
try:
|
||||
save_path = session.save_path
|
||||
if not save_path:
|
||||
_, _, _, _, save_path = await get_chunk_file_path_name(
|
||||
session.file_name, session.upload_id
|
||||
)
|
||||
await file_storage.clean_chunks(session.upload_id, save_path)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"清理分片文件失败 upload_id={session.upload_id}: {e}"
|
||||
)
|
||||
# 存储清理失败(包括部分删除)时保留记录,下轮继续重试。
|
||||
continue
|
||||
|
||||
try:
|
||||
await UploadChunk.filter(upload_id=session.upload_id).delete()
|
||||
await StorageReservation.filter(
|
||||
token=f"chunk:{session.upload_id}"
|
||||
).delete()
|
||||
logger.info(f"已清理过期上传会话 upload_id={session.upload_id}")
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"删除分片记录失败 upload_id={session.upload_id}: {e}"
|
||||
)
|
||||
|
||||
except Exception as 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,6 +1,7 @@
|
||||
import datetime
|
||||
import os
|
||||
import uuid
|
||||
from urllib.parse import unquote
|
||||
|
||||
from fastapi import UploadFile, HTTPException
|
||||
from typing import Optional, Tuple
|
||||
@@ -8,33 +9,55 @@ from typing import Optional, Tuple
|
||||
from apps.base.dependencies import IPRateLimit
|
||||
from apps.base.models import FileCodes
|
||||
from core.settings import settings
|
||||
from core.utils import get_random_num, get_random_string, max_save_times_desc
|
||||
from core.utils import (
|
||||
get_random_num,
|
||||
get_random_string,
|
||||
max_save_times_desc,
|
||||
sanitize_filename,
|
||||
get_now,
|
||||
)
|
||||
|
||||
|
||||
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("/")
|
||||
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}/{prefix}{suffix}"
|
||||
return path, suffix, prefix, filename, save_path
|
||||
|
||||
|
||||
async def get_file_path_name(file: UploadFile) -> Tuple[str, str, str, str, str]:
|
||||
"""获取文件路径和文件名"""
|
||||
today = datetime.datetime.now()
|
||||
storage_path = settings.storage_path.strip("/") # 移除开头和结尾的斜杠
|
||||
file_uuid = uuid.uuid4().hex
|
||||
return await build_file_path(file.filename or "", uuid.uuid4().hex)
|
||||
|
||||
# 使用 UUID 作为子目录名
|
||||
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(file.filename)
|
||||
# 保持原始文件名
|
||||
save_path = f"{path}/{file.filename}"
|
||||
return path, suffix, prefix, file.filename, save_path
|
||||
async def get_chunk_file_path_name(
|
||||
file_name: str, upload_id: str
|
||||
) -> Tuple[str, str, str, str, str]:
|
||||
return await build_file_path(file_name, upload_id)
|
||||
|
||||
|
||||
async def get_expire_info(
|
||||
expire_value: int, expire_style: str
|
||||
) -> Tuple[Optional[datetime.datetime], int, int, str]:
|
||||
"""获取过期信息"""
|
||||
expired_count, used_count = -1, 0
|
||||
now = datetime.datetime.now()
|
||||
now = await get_now()
|
||||
code = None
|
||||
|
||||
max_timedelta = (
|
||||
@@ -54,7 +77,7 @@ async def get_expire_info(
|
||||
"hour": lambda: now + datetime.timedelta(hours=expire_value),
|
||||
"minute": lambda: now + datetime.timedelta(minutes=expire_value),
|
||||
"count": lambda: (now + datetime.timedelta(days=1), expire_value),
|
||||
"forever": lambda: (None, None), # 修改这里
|
||||
"forever": lambda: (None, None),
|
||||
}
|
||||
|
||||
if expire_style in expire_styles:
|
||||
@@ -63,8 +86,6 @@ async def get_expire_info(
|
||||
expired_at, extra = result
|
||||
if expire_style == "count":
|
||||
expired_count = extra
|
||||
elif expire_style == "forever":
|
||||
code = await get_random_code(style="string") # 移动到这里
|
||||
else:
|
||||
expired_at = result
|
||||
if expired_at and expired_at - now > max_timedelta:
|
||||
@@ -78,15 +99,33 @@ async def get_expire_info(
|
||||
return expired_at, expired_count, used_count, code
|
||||
|
||||
|
||||
async def get_random_code(style="num") -> str:
|
||||
"""获取随机字符串"""
|
||||
def get_code_generate_type() -> str:
|
||||
code_generate_type = getattr(settings, "code_generate_type", "secret")
|
||||
if code_generate_type in {"secret", "string"}:
|
||||
return "secret"
|
||||
return "number"
|
||||
|
||||
|
||||
async def get_random_code(style: str | None = None) -> str:
|
||||
code_style = style or get_code_generate_type()
|
||||
if code_style == "num":
|
||||
code_style = "number"
|
||||
if code_style == "string":
|
||||
code_style = "secret"
|
||||
|
||||
while True:
|
||||
code = await get_random_num() if style == "num" else await get_random_string()
|
||||
code = (
|
||||
await get_random_num()
|
||||
if code_style == "number"
|
||||
else await get_random_string()
|
||||
)
|
||||
if not await FileCodes.filter(code=code).exists():
|
||||
return code
|
||||
return str(code)
|
||||
|
||||
|
||||
ip_limit = {
|
||||
"error": IPRateLimit(count=settings.uploadCount, minutes=settings.errorMinute),
|
||||
"upload": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
|
||||
"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,93 +1,106 @@
|
||||
from fastapi import APIRouter, Form, UploadFile, File, Depends, HTTPException
|
||||
from apps.admin.dependencies import admin_required
|
||||
from apps.base.models import FileCodes
|
||||
from apps.base.schemas import SelectFileModel
|
||||
from apps.base.utils import get_expire_info, get_file_path_name, ip_limit
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import uuid
|
||||
from datetime import timedelta
|
||||
from urllib.parse import unquote
|
||||
|
||||
from typing import Optional, Tuple, Union
|
||||
|
||||
from fastapi import APIRouter, Form, Request, UploadFile, File, Depends, HTTPException
|
||||
from pydantic import BaseModel, ValidationError
|
||||
from starlette import status
|
||||
from starlette.responses import Response
|
||||
from tortoise.expressions import Case, F, Q, When
|
||||
|
||||
from apps.base.auth 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,
|
||||
get_stored_download,
|
||||
response_from_download,
|
||||
stored_file_of,
|
||||
validate_file_size,
|
||||
)
|
||||
from core.storage import StoredFile, build_attachment_headers
|
||||
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 (
|
||||
ip_limit,
|
||||
get_chunk_file_path_name,
|
||||
validate_expire_style,
|
||||
)
|
||||
from apps.base.local_share import is_local_ref
|
||||
from core.response import APIResponse
|
||||
from core.settings import settings
|
||||
from core.storage import storages, FileStorageInterface
|
||||
from core.utils import get_select_token
|
||||
from core.utils import (
|
||||
get_file_url as get_proxy_file_url,
|
||||
get_select_token,
|
||||
get_now,
|
||||
sanitize_filename,
|
||||
)
|
||||
|
||||
share_api = APIRouter(prefix="/share", tags=["分享"])
|
||||
|
||||
|
||||
async def validate_file_size(file: UploadFile, max_size: int):
|
||||
if file.size > max_size:
|
||||
max_size_mb = max_size / (1024 * 1024)
|
||||
raise HTTPException(
|
||||
status_code=403, detail=f"大小超过限制,最大为{max_size_mb:.2f} MB"
|
||||
)
|
||||
# ============ 公共服务层 ============
|
||||
|
||||
|
||||
async def create_file_code(code, **kwargs):
|
||||
return await FileCodes.create(code=code, **kwargs)
|
||||
def normalize_share_code(code: str) -> str:
|
||||
return str(code or "").strip()
|
||||
|
||||
|
||||
@share_api.post("/text/", dependencies=[Depends(admin_required)])
|
||||
@share_api.post("/text/", dependencies=[Depends(share_required_login)])
|
||||
async def share_text(
|
||||
text: str = Form(...),
|
||||
expire_value: int = Form(default=1, gt=0),
|
||||
expire_style: str = Form(default="day"),
|
||||
ip: str = Depends(ip_limit["upload"]),
|
||||
):
|
||||
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})
|
||||
|
||||
|
||||
@share_api.post("/file/", dependencies=[Depends(admin_required)])
|
||||
@share_api.post("/file/", dependencies=[Depends(share_required_login)])
|
||||
async def share_file(
|
||||
expire_value: int = Form(default=1, gt=0),
|
||||
expire_style: str = Form(default="day"),
|
||||
file: UploadFile = File(...),
|
||||
ip: str = Depends(ip_limit["upload"]),
|
||||
):
|
||||
await validate_file_size(file, settings.uploadSize)
|
||||
|
||||
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(code, check=True):
|
||||
file_code = await FileCodes.filter(code=code).first()
|
||||
async def get_code_file_by_code(
|
||||
code: str, check: bool = True
|
||||
) -> Tuple[bool, Union[FileCodes, str]]:
|
||||
normalized_code = normalize_share_code(code)
|
||||
if not normalized_code:
|
||||
return False, "文件不存在"
|
||||
file_code = await FileCodes.filter(code=normalized_code).first()
|
||||
if not file_code:
|
||||
return False, "文件不存在"
|
||||
if await file_code.is_expired() and check:
|
||||
@@ -95,11 +108,92 @@ async def get_code_file_by_code(code, check=True):
|
||||
return True, file_code
|
||||
|
||||
|
||||
async def update_file_usage(file_code):
|
||||
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:
|
||||
is_text = file_code.text is not None
|
||||
remaining_downloads = (
|
||||
file_code.expired_count if file_code.expired_count > 0 else None
|
||||
)
|
||||
return {
|
||||
"code": file_code.code,
|
||||
"name": file_code.prefix + file_code.suffix,
|
||||
"size": file_code.size,
|
||||
"type": "text" if is_text else "file",
|
||||
"is_text": is_text,
|
||||
"created_at": file_code.created_at,
|
||||
"expired_at": file_code.expired_at,
|
||||
"expired_count": file_code.expired_count,
|
||||
"used_count": file_code.used_count,
|
||||
"remaining_downloads": remaining_downloads,
|
||||
}
|
||||
|
||||
|
||||
async def build_select_detail(
|
||||
file_code: FileCodes, file_storage: FileStorageInterface
|
||||
) -> dict:
|
||||
metadata = build_file_metadata(file_code)
|
||||
if file_code.text is not None:
|
||||
download_url = None
|
||||
elif file_code.expired_count >= 0 or is_local_ref(file_code):
|
||||
# 次数限制与 NAS 引用都必须走下载接口,避免直链绕过次数或打到错误存储。
|
||||
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,
|
||||
"text": content if content is not None else download_url,
|
||||
"content": content,
|
||||
"download_url": download_url,
|
||||
}
|
||||
|
||||
|
||||
@share_api.get("/metadata/")
|
||||
async def get_file_metadata(code: str, ip: str = Depends(ip_limit["metadata"])):
|
||||
has, file_code = await get_code_file_by_code(code)
|
||||
if not has:
|
||||
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["metadata"])
|
||||
):
|
||||
has, file_code = await get_code_file_by_code(data.code)
|
||||
if not has:
|
||||
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.get("/select/")
|
||||
@@ -110,8 +204,17 @@ async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])):
|
||||
ip_limit["error"].add_ip(ip)
|
||||
return APIResponse(code=404, detail=file_code)
|
||||
|
||||
await update_file_usage(file_code)
|
||||
return await file_storage.get_file_response(file_code)
|
||||
assert isinstance(file_code, FileCodes)
|
||||
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=build_attachment_headers(filename),
|
||||
)
|
||||
return response_from_download(await get_stored_download(file_code, file_storage))
|
||||
|
||||
|
||||
@share_api.post("/select/")
|
||||
@@ -122,33 +225,472 @@ async def select_file(data: SelectFileModel, ip: str = Depends(ip_limit["error"]
|
||||
ip_limit["error"].add_ip(ip)
|
||||
return APIResponse(code=404, detail=file_code)
|
||||
|
||||
await update_file_usage(file_code)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"code": file_code.code,
|
||||
"name": file_code.prefix + file_code.suffix,
|
||||
"size": file_code.size,
|
||||
"text": (
|
||||
file_code.text
|
||||
if file_code.text is not None
|
||||
else await file_storage.get_file_url(file_code)
|
||||
),
|
||||
}
|
||||
assert isinstance(file_code, FileCodes)
|
||||
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]()
|
||||
if await get_select_token(code) != key:
|
||||
normalized_code = normalize_share_code(code)
|
||||
# 同时接受当前窗口与上一窗口 token,避免时间窗边界竞态导致偶发 403。
|
||||
# 逐个常量时间比较(hmac.compare_digest),避免 set 成员判断的时序侧信道。
|
||||
valid_keys = [
|
||||
await get_select_token(normalized_code, offset=0),
|
||||
await get_select_token(normalized_code, offset=1),
|
||||
]
|
||||
if not any(
|
||||
hmac.compare_digest(key.encode(), candidate.encode())
|
||||
for candidate in valid_keys
|
||||
):
|
||||
ip_limit["error"].add_ip(ip)
|
||||
|
||||
has, file_code = await get_code_file_by_code(code, False)
|
||||
raise HTTPException(status_code=403, detail="下载鉴权失败")
|
||||
has, file_code = await get_code_file_by_code(normalized_code)
|
||||
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 get_stored_download(file_code, file_storage))
|
||||
)
|
||||
|
||||
|
||||
chunk_api = APIRouter(prefix="/chunk", tags=["切片"])
|
||||
|
||||
|
||||
async def parse_body_model(request: Request, model_class: type[BaseModel]):
|
||||
content_type = request.headers.get("content-type", "").lower()
|
||||
try:
|
||||
if "application/x-www-form-urlencoded" in content_type or "multipart/form-data" in content_type:
|
||||
payload = dict(await request.form())
|
||||
else:
|
||||
payload = await request.json()
|
||||
return model_class.model_validate(payload)
|
||||
except ValidationError as e:
|
||||
raise HTTPException(status_code=422, detail=e.errors())
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="请求体格式错误")
|
||||
|
||||
|
||||
async def parse_init_chunk_upload(request: Request) -> InitChunkUploadModel:
|
||||
return await parse_body_model(request, InitChunkUploadModel)
|
||||
|
||||
|
||||
async def parse_complete_upload(request: Request) -> CompleteUploadModel:
|
||||
return await parse_body_model(request, CompleteUploadModel)
|
||||
|
||||
|
||||
@chunk_api.post("/upload/init/", dependencies=[Depends(share_required_login)])
|
||||
async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chunk_upload)):
|
||||
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.upload_size:
|
||||
max_size_mb = settings.upload_size / (1024 * 1024)
|
||||
raise HTTPException(
|
||||
status_code=403, detail=f"文件大小超过限制,最大为 {max_size_mb:.2f} MB"
|
||||
)
|
||||
|
||||
# 断点续传:检查是否存在相同文件的未完成上传会话
|
||||
existing_session = await UploadChunk.filter(
|
||||
chunk_hash=data.file_hash,
|
||||
chunk_index=-1,
|
||||
completed=False,
|
||||
file_size=data.file_size,
|
||||
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, chunk_index__gte=0
|
||||
).values_list("chunk_index", flat=True)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"existed": False,
|
||||
"upload_id": existing_session.upload_id,
|
||||
"chunk_size": existing_session.chunk_size,
|
||||
"total_chunks": existing_session.total_chunks,
|
||||
"uploaded_chunks": list(uploaded_chunks),
|
||||
}
|
||||
)
|
||||
|
||||
# 创建新的上传会话
|
||||
upload_id = uuid.uuid4().hex
|
||||
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,
|
||||
"upload_id": upload_id,
|
||||
"chunk_size": data.chunk_size,
|
||||
"total_chunks": total_chunks,
|
||||
"uploaded_chunks": [],
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@chunk_api.post(
|
||||
"/upload/chunk/{upload_id}/{chunk_index}",
|
||||
dependencies=[Depends(share_required_login)],
|
||||
)
|
||||
async def upload_chunk(
|
||||
upload_id: str,
|
||||
chunk_index: int,
|
||||
chunk: UploadFile = File(...),
|
||||
):
|
||||
# 获取上传会话信息
|
||||
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||
if not chunk_info:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在")
|
||||
if chunk_info.completed:
|
||||
raise HTTPException(409, "上传会话已完成,仅待清理")
|
||||
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:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="无效的分片索引")
|
||||
|
||||
# 检查是否已上传(支持断点续传)
|
||||
existing_chunk = await UploadChunk.filter(
|
||||
upload_id=upload_id, chunk_index=chunk_index, completed=True
|
||||
).first()
|
||||
if existing_chunk:
|
||||
return APIResponse(
|
||||
detail={"chunk_hash": existing_chunk.chunk_hash, "skipped": True}
|
||||
)
|
||||
|
||||
# 读取分片数据并计算哈希
|
||||
chunk_data = await chunk.read()
|
||||
if chunk_index == 0:
|
||||
validate_header_bytes(chunk_info.file_name, None, chunk_data[:64])
|
||||
chunk_size = len(chunk_data)
|
||||
|
||||
# 校验分片大小不超过声明的 chunk_size
|
||||
if chunk_size > chunk_info.chunk_size:
|
||||
raise HTTPException(
|
||||
status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"分片大小超过声明值: 最大 {chunk_info.chunk_size}, 实际 {chunk_size}",
|
||||
)
|
||||
|
||||
# 计算已上传分片数,校验累计大小不超限(用分片数 * chunk_size 估算)
|
||||
uploaded_count = await UploadChunk.filter(
|
||||
upload_id=upload_id, completed=True, chunk_index__gte=0
|
||||
).count()
|
||||
# 已上传分片的最大可能大小 + 当前分片
|
||||
max_uploaded_size = uploaded_count * chunk_info.chunk_size + chunk_size
|
||||
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"
|
||||
)
|
||||
|
||||
chunk_hash = hashlib.sha256(chunk_data).hexdigest()
|
||||
|
||||
save_path = chunk_info.save_path
|
||||
|
||||
# 保存分片到存储
|
||||
storage = storages[settings.file_storage]()
|
||||
try:
|
||||
await storage.save_chunk(
|
||||
upload_id, chunk_index, chunk_data, chunk_hash, save_path
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"分片保存失败: {str(e)}"
|
||||
)
|
||||
|
||||
# 更新或创建分片记录(保存成功后再记录)
|
||||
await UploadChunk.update_or_create(
|
||||
upload_id=upload_id,
|
||||
chunk_index=chunk_index,
|
||||
defaults={
|
||||
"chunk_hash": chunk_hash,
|
||||
"completed": True,
|
||||
"file_size": chunk_info.file_size,
|
||||
"total_chunks": chunk_info.total_chunks,
|
||||
"chunk_size": chunk_info.chunk_size,
|
||||
"file_name": chunk_info.file_name,
|
||||
"save_path": chunk_info.save_path,
|
||||
},
|
||||
)
|
||||
return APIResponse(detail={"chunk_hash": chunk_hash})
|
||||
|
||||
|
||||
@chunk_api.delete("/upload/{upload_id}", dependencies=[Depends(share_required_login)])
|
||||
async def cancel_upload(upload_id: str):
|
||||
"""取消上传并清理临时文件"""
|
||||
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||
if not chunk_info:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在")
|
||||
|
||||
save_path = chunk_info.save_path
|
||||
|
||||
# 清理存储中的临时文件
|
||||
storage = storages[settings.file_storage]()
|
||||
if save_path:
|
||||
try:
|
||||
await storage.clean_chunks(upload_id, save_path)
|
||||
except Exception:
|
||||
logger.warning("取消分片上传:清理分片文件失败 upload_id=%s", upload_id, exc_info=True)
|
||||
raise HTTPException(503, "分片清理失败,请稍后重试")
|
||||
|
||||
# 清理数据库记录
|
||||
await UploadChunk.filter(upload_id=upload_id).delete()
|
||||
await release_storage(f"chunk:{upload_id}")
|
||||
|
||||
return APIResponse(detail={"message": "上传已取消"})
|
||||
|
||||
|
||||
@chunk_api.get(
|
||||
"/upload/status/{upload_id}", dependencies=[Depends(share_required_login)]
|
||||
)
|
||||
async def get_upload_status(upload_id: str):
|
||||
"""获取上传状态"""
|
||||
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||
if not chunk_info:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在")
|
||||
|
||||
# 获取已上传的分片列表
|
||||
uploaded_chunks = await UploadChunk.filter(
|
||||
upload_id=upload_id, completed=True, chunk_index__gte=0
|
||||
).values_list("chunk_index", flat=True)
|
||||
|
||||
return APIResponse(
|
||||
detail={
|
||||
"upload_id": upload_id,
|
||||
"file_name": chunk_info.file_name,
|
||||
"file_size": chunk_info.file_size,
|
||||
"chunk_size": chunk_info.chunk_size,
|
||||
"total_chunks": chunk_info.total_chunks,
|
||||
"uploaded_chunks": list(uploaded_chunks),
|
||||
"progress": len(uploaded_chunks) / chunk_info.total_chunks * 100,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@chunk_api.post(
|
||||
"/upload/complete/{upload_id}", dependencies=[Depends(share_required_login)]
|
||||
)
|
||||
async def complete_upload(
|
||||
upload_id: str,
|
||||
data: CompleteUploadModel = Depends(parse_complete_upload),
|
||||
ip: str = Depends(ip_limit["upload"]),
|
||||
):
|
||||
# 获取上传基本信息
|
||||
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||
if not chunk_info:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在")
|
||||
if chunk_info.completed:
|
||||
raise HTTPException(409, "上传会话已完成,仅待清理")
|
||||
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=["预签名上传"])
|
||||
|
||||
|
||||
def build_proxy_upload_urls(upload_id: str) -> dict:
|
||||
proxy_upload_url = f"/presign/upload/proxy/{upload_id}"
|
||||
return {
|
||||
"proxy_upload_url": proxy_upload_url,
|
||||
"legacy_proxy_upload_url": f"/api{proxy_upload_url}",
|
||||
}
|
||||
|
||||
|
||||
async def _get_valid_session(
|
||||
upload_id: str, expected_mode: Optional[str] = None
|
||||
) -> PresignUploadSession:
|
||||
"""获取并验证会话"""
|
||||
session = await PresignUploadSession.filter(upload_id=upload_id).first()
|
||||
if not session:
|
||||
raise HTTPException(404, "上传会话不存在")
|
||||
if await session.is_expired():
|
||||
await session.delete()
|
||||
await release_storage(f"presign:{upload_id}")
|
||||
raise HTTPException(404, "上传会话已过期")
|
||||
if expected_mode and session.mode != expected_mode:
|
||||
raise HTTPException(400, f"此会话不支持{expected_mode}模式")
|
||||
return session
|
||||
|
||||
|
||||
@presign_api.post("/upload/init", dependencies=[Depends(share_required_login)])
|
||||
async def presign_upload_init(
|
||||
data: PresignUploadInitRequest, ip: str = Depends(ip_limit["upload"])
|
||||
):
|
||||
"""初始化预签名上传,S3返回直传URL,其他存储返回代理URL"""
|
||||
validate_file_type(data.file_name)
|
||||
if data.file_size > settings.upload_size:
|
||||
raise HTTPException(
|
||||
403,
|
||||
f"文件大小超过限制,最大为 {settings.upload_size / (1024 * 1024):.2f} MB",
|
||||
)
|
||||
validate_expire_style(data.expire_style)
|
||||
|
||||
upload_id = uuid.uuid4().hex
|
||||
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 = {
|
||||
"upload_id": upload_id,
|
||||
"upload_url": upload_url,
|
||||
"mode": mode,
|
||||
"expires_in": PRESIGN_SESSION_EXPIRES,
|
||||
}
|
||||
if mode == "proxy":
|
||||
detail.update(proxy_urls)
|
||||
|
||||
return APIResponse(
|
||||
detail=detail
|
||||
)
|
||||
|
||||
|
||||
@presign_api.put(
|
||||
"/upload/proxy/{upload_id}", dependencies=[Depends(share_required_login)]
|
||||
)
|
||||
async def presign_upload_proxy(
|
||||
upload_id: str, file: UploadFile = File(...), ip: str = Depends(ip_limit["upload"])
|
||||
):
|
||||
"""代理模式上传,服务器转存到存储后端"""
|
||||
session = await _get_valid_session(upload_id, expected_mode="proxy")
|
||||
code = await FileUploadService.commit_proxy_upload(session, file)
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
return APIResponse(detail={"code": code, "name": session.file_name})
|
||||
|
||||
|
||||
@presign_api.post(
|
||||
"/upload/confirm/{upload_id}", dependencies=[Depends(share_required_login)]
|
||||
)
|
||||
async def presign_upload_confirm(upload_id: str, ip: str = Depends(ip_limit["upload"])):
|
||||
"""直传确认,客户端完成S3直传后调用获取分享码"""
|
||||
session = await _get_valid_session(upload_id, expected_mode="direct")
|
||||
code = await FileUploadService.confirm_direct_upload(session)
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
return APIResponse(detail={"code": code, "name": session.file_name})
|
||||
|
||||
|
||||
@presign_api.get(
|
||||
"/upload/status/{upload_id}", dependencies=[Depends(share_required_login)]
|
||||
)
|
||||
async def presign_upload_status(upload_id: str):
|
||||
"""查询上传会话状态"""
|
||||
session = await PresignUploadSession.filter(upload_id=upload_id).first()
|
||||
if not session:
|
||||
raise HTTPException(404, "上传会话不存在")
|
||||
|
||||
return APIResponse(
|
||||
detail={
|
||||
"upload_id": session.upload_id,
|
||||
"file_name": session.file_name,
|
||||
"file_size": session.file_size,
|
||||
"mode": session.mode,
|
||||
"created_at": session.created_at.isoformat(),
|
||||
"expires_at": session.expires_at.isoformat(),
|
||||
"is_expired": await session.is_expired(),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@presign_api.delete("/upload/{upload_id}", dependencies=[Depends(share_required_login)])
|
||||
async def presign_upload_cancel(upload_id: str):
|
||||
"""取消上传会话"""
|
||||
session = await PresignUploadSession.filter(upload_id=upload_id).first()
|
||||
if not session:
|
||||
raise HTTPException(404, "上传会话不存在")
|
||||
|
||||
if session.mode == "direct":
|
||||
storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
try:
|
||||
if await storage.file_exists(session.save_path):
|
||||
temp_file_code = 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:
|
||||
logger.warning("取消预签名会话:清理临时文件失败 upload_id=%s", upload_id, exc_info=True)
|
||||
|
||||
await session.delete()
|
||||
await release_storage(f"presign:{upload_id}")
|
||||
return APIResponse(detail={"message": "上传会话已取消"})
|
||||
@@ -1,38 +1,115 @@
|
||||
import asyncio
|
||||
import glob
|
||||
import importlib
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import IO
|
||||
|
||||
from tortoise import Tortoise
|
||||
|
||||
from core.logger import logger
|
||||
from core.settings import data_root
|
||||
|
||||
|
||||
_DB_FILE = os.path.join(data_root, "filecodebox.db")
|
||||
_STARTUP_LOCK_FILE = os.path.join(data_root, "filecodebox.startup.lock")
|
||||
|
||||
|
||||
def get_db_config() -> dict:
|
||||
return {
|
||||
"connections": {
|
||||
"default": {
|
||||
"engine": "tortoise.backends.sqlite",
|
||||
"credentials": {
|
||||
"file_path": _DB_FILE,
|
||||
"journal_mode": "WAL",
|
||||
"busy_timeout": 10000,
|
||||
"foreign_keys": "ON",
|
||||
# 小内存 VPS 下的 IOPS 与内存折中。Tortoise 的 SqliteClient 会把
|
||||
# credentials 中 file_path 以外的键逐条执行成 PRAGMA,且 SQLite
|
||||
# 后端只维持单条连接,因此这些设置在进程生命周期内全局生效。
|
||||
# synchronous=NORMAL:WAL 下应用崩溃不丢已提交事务,
|
||||
# 仅 OS/断电可能丢最后若干事务,省去每次提交的 fsync。
|
||||
# temp_store=MEMORY:临时表与排序走内存,小库收益明显;
|
||||
# 后台大排序的内存峰值需在压测中关注。
|
||||
# cache_size=-8000:page cache 上限约 8MB(负数单位为 KiB)。
|
||||
"synchronous": "NORMAL",
|
||||
"temp_store": "MEMORY",
|
||||
"cache_size": -8000,
|
||||
},
|
||||
}
|
||||
},
|
||||
"apps": {
|
||||
"models": {
|
||||
"models": ["apps.base.models"],
|
||||
"default_connection": "default",
|
||||
}
|
||||
},
|
||||
"use_tz": False,
|
||||
"timezone": "Asia/Shanghai",
|
||||
}
|
||||
|
||||
|
||||
def _lock_file(file_obj: IO[str]) -> None:
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
# Windows 需要锁定至少 1 字节
|
||||
if os.fstat(file_obj.fileno()).st_size == 0:
|
||||
file_obj.write("0")
|
||||
file_obj.flush()
|
||||
msvcrt.locking(file_obj.fileno(), msvcrt.LK_LOCK, 1) # type: ignore[attr-defined]
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(file_obj.fileno(), fcntl.LOCK_EX)
|
||||
|
||||
|
||||
def _unlock_file(file_obj: IO[str]) -> None:
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
msvcrt.locking(file_obj.fileno(), msvcrt.LK_UNLCK, 1) # type: ignore[attr-defined]
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(file_obj.fileno(), fcntl.LOCK_UN)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def db_startup_lock():
|
||||
os.makedirs(data_root, exist_ok=True)
|
||||
lock_file = open(_STARTUP_LOCK_FILE, "a+", encoding="utf-8")
|
||||
try:
|
||||
await asyncio.to_thread(_lock_file, lock_file)
|
||||
yield
|
||||
finally:
|
||||
await asyncio.to_thread(_unlock_file, lock_file)
|
||||
lock_file.close()
|
||||
|
||||
|
||||
async def init_db():
|
||||
try:
|
||||
# 使用正确的Tortoise初始化配置格式
|
||||
db_config = {
|
||||
"db_url": f"sqlite://{data_root}/filecodebox.db",
|
||||
"modules": {"models": ["apps.base.models"]},
|
||||
"use_tz": False,
|
||||
"timezone": "Asia/Shanghai"
|
||||
}
|
||||
db_config = get_db_config()
|
||||
|
||||
await Tortoise.init(**db_config)
|
||||
if not Tortoise._inited:
|
||||
await Tortoise.init(config=db_config)
|
||||
|
||||
# 创建migrations表
|
||||
await Tortoise.get_connection("default").execute_script("""
|
||||
CREATE TABLE IF NOT EXISTS migrates (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
migration_file VARCHAR(255) NOT NULL UNIQUE,
|
||||
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
""")
|
||||
async with db_startup_lock():
|
||||
# 创建migrations表
|
||||
await Tortoise.get_connection("default").execute_script("""
|
||||
CREATE TABLE IF NOT EXISTS migrates (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
migration_file VARCHAR(255) NOT NULL UNIQUE,
|
||||
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
""")
|
||||
|
||||
# 执行迁移
|
||||
await execute_migrations()
|
||||
# 执行迁移
|
||||
await execute_migrations()
|
||||
|
||||
except Exception as e:
|
||||
print(f"数据库初始化失败: {str(e)}")
|
||||
logger.error(f"数据库初始化失败: {str(e)}")
|
||||
raise
|
||||
|
||||
|
||||
@@ -58,7 +135,7 @@ async def execute_migrations():
|
||||
)
|
||||
|
||||
if not executed[1]:
|
||||
print(f"执行迁移: {file_name}")
|
||||
logger.info(f"执行迁移: {file_name}")
|
||||
# 导入并执行migration
|
||||
module_path = migration_file.replace("/", ".").replace("\\", ".").replace(".py", "")
|
||||
try:
|
||||
@@ -70,11 +147,11 @@ async def execute_migrations():
|
||||
"INSERT INTO migrates (migration_file) VALUES (?)",
|
||||
[file_name]
|
||||
)
|
||||
print(f"迁移完成: {file_name}")
|
||||
logger.info(f"迁移完成: {file_name}")
|
||||
except Exception as e:
|
||||
print(f"迁移 {file_name} 执行失败: {str(e)}")
|
||||
logger.error(f"迁移 {file_name} 执行失败: {str(e)}")
|
||||
raise
|
||||
|
||||
except Exception as e:
|
||||
print(f"迁移过程发生错误: {str(e)}")
|
||||
logger.error(f"迁移过程发生错误: {str(e)}")
|
||||
raise
|
||||
@@ -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)
|
||||
@@ -0,0 +1,62 @@
|
||||
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 = logging.getLogger("FileCodeBox")
|
||||
level = get_log_level()
|
||||
_logger.setLevel(level)
|
||||
_logger.propagate = False
|
||||
|
||||
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",
|
||||
)
|
||||
console_handler.setFormatter(formatter)
|
||||
|
||||
return _logger
|
||||
|
||||
|
||||
# 创建全局logger实例
|
||||
logger = setup_logger()
|
||||
@@ -1,15 +1,11 @@
|
||||
# @Time : 2023/8/14 11:48
|
||||
# @Author : Lan
|
||||
# @File : response.py
|
||||
# @Software: PyCharm
|
||||
from typing import Generic, TypeVar
|
||||
from typing import Generic, Optional, TypeVar
|
||||
|
||||
from pydantic.v1.generics import GenericModel
|
||||
from pydantic import BaseModel
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class APIResponse(GenericModel, Generic[T]):
|
||||
class APIResponse(BaseModel, Generic[T]):
|
||||
code: int = 200
|
||||
message: str = "ok"
|
||||
detail: T
|
||||
detail: Optional[T] = None
|
||||
@@ -0,0 +1,172 @@
|
||||
import copy
|
||||
import ipaddress
|
||||
import os
|
||||
import secrets
|
||||
import socket
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from core.utils import hash_password, is_password_hashed, verify_password
|
||||
|
||||
|
||||
JWT_SECRET_MIN_LENGTH = 32
|
||||
INTERNAL_CONFIG_KEYS = {"jwt_secret"}
|
||||
LEGACY_DEFAULT_ADMIN_TOKEN = "FileCodeBox" + "2023"
|
||||
|
||||
|
||||
@dataclass
|
||||
class SecurityConfigResult:
|
||||
config: dict[str, Any]
|
||||
changed: bool = False
|
||||
password_hashed: bool = False
|
||||
jwt_secret_rotated: bool = False
|
||||
setup_required: bool = False
|
||||
|
||||
|
||||
def generate_jwt_secret() -> str:
|
||||
return secrets.token_urlsafe(48)
|
||||
|
||||
|
||||
def is_valid_jwt_secret(secret: Any) -> bool:
|
||||
return isinstance(secret, str) and len(secret) >= JWT_SECRET_MIN_LENGTH
|
||||
|
||||
|
||||
def is_config_initialized(config: dict[str, Any]) -> bool:
|
||||
"""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)
|
||||
|
||||
|
||||
def prepare_security_config(config: dict[str, Any]) -> SecurityConfigResult:
|
||||
next_config = copy.deepcopy(config)
|
||||
result = SecurityConfigResult(config=next_config)
|
||||
|
||||
admin_token = str(next_config.get("admin_token") or "")
|
||||
if not admin_token:
|
||||
result.setup_required = True
|
||||
elif verify_password(LEGACY_DEFAULT_ADMIN_TOKEN, admin_token):
|
||||
next_config["admin_token"] = ""
|
||||
result.setup_required = True
|
||||
result.changed = True
|
||||
elif not is_password_hashed(admin_token):
|
||||
next_config["admin_token"] = hash_password(admin_token)
|
||||
result.password_hashed = True
|
||||
result.changed = True
|
||||
|
||||
jwt_secret = next_config.get("jwt_secret")
|
||||
if not is_valid_jwt_secret(jwt_secret):
|
||||
next_config["jwt_secret"] = generate_jwt_secret()
|
||||
result.jwt_secret_rotated = True
|
||||
result.changed = True
|
||||
|
||||
return result
|
||||
|
||||
|
||||
# 出站端点白名单/黑名单(SSRF 防护)。
|
||||
# 这些配置项会被服务器直接当作上游地址访问:被劫持的管理员会话可以把实例
|
||||
# 变成内网代理跳板,或把数据发往任意地址。校验只在写入入口(update_config),
|
||||
# 已存值不受影响;APP_ENV 非 production(本地开发,如 minio/webdav)时放行。
|
||||
OUTBOUND_ENDPOINT_CONFIG_KEYS = ("s3_endpoint_url", "s3_hostname", "webdav_url")
|
||||
|
||||
_ENDPOINT_SCHEME_WHITELIST = {"http", "https"}
|
||||
_ENDPOINT_HOST_DENY_SUFFIXES = (
|
||||
".local",
|
||||
".internal",
|
||||
".lan",
|
||||
".home.arpa",
|
||||
".corp",
|
||||
".localhost",
|
||||
)
|
||||
|
||||
|
||||
def _endpoint_ip_is_denied(ip_str: str) -> bool:
|
||||
try:
|
||||
ip = ipaddress.ip_address(ip_str)
|
||||
except ValueError:
|
||||
return False
|
||||
return (
|
||||
ip.is_private
|
||||
or ip.is_loopback
|
||||
or ip.is_link_local
|
||||
or ip.is_reserved
|
||||
or ip.is_multicast
|
||||
or ip.is_unspecified
|
||||
)
|
||||
|
||||
|
||||
def _endpoint_host_is_denied(host: str) -> bool:
|
||||
host = host.strip("[]").lower()
|
||||
if host in {"localhost"} or host.endswith(_ENDPOINT_HOST_DENY_SUFFIXES):
|
||||
return True
|
||||
# 字面 IP 直接判;非字面形态(速记 "127.1"、十进制 2130706433、十六进制、
|
||||
# *.localhost、nip.io 类 DNS 映射)交给解析后逐 IP 复判——静态字符串
|
||||
# 黑名单对它们全部失效,这是探测中实测确认的绕过面。
|
||||
if _endpoint_ip_is_denied(host):
|
||||
return True
|
||||
try:
|
||||
infos = socket.getaddrinfo(host, None)
|
||||
except (socket.gaierror, UnicodeError, OSError):
|
||||
return False
|
||||
for info in infos:
|
||||
# getaddrinfo 的 sockaddr 首元素在 IPv4/IPv6 下均为 str(int 仅出现在
|
||||
# AF_UNIX 等异形族)——显式 str() 让类型检查器与运行时一致。
|
||||
if _endpoint_ip_is_denied(str(info[4][0])):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def validate_outbound_endpoint(value: Any) -> str:
|
||||
"""校验完整 URL 形态的出站端点(s3_endpoint_url / webdav_url)。"""
|
||||
endpoint = str(value or "").strip()
|
||||
if not endpoint:
|
||||
return ""
|
||||
|
||||
if os.environ.get("APP_ENV", "development") != "production":
|
||||
return endpoint
|
||||
|
||||
parts = urlsplit(endpoint)
|
||||
if parts.scheme.lower() not in _ENDPOINT_SCHEME_WHITELIST:
|
||||
raise ValueError(f"端点协议必须是 http(s):{endpoint}")
|
||||
host = parts.hostname or ""
|
||||
if not host:
|
||||
raise ValueError(f"端点缺少主机名:{endpoint}")
|
||||
if _endpoint_host_is_denied(host):
|
||||
raise ValueError(f"端点不允许指向内网/保留地址:{endpoint}")
|
||||
return endpoint
|
||||
|
||||
|
||||
def validate_outbound_hostname(value: Any) -> str:
|
||||
"""校验裸主机名形态的出站端点(s3_hostname,存储层拼接 https://{hostname})。"""
|
||||
hostname = str(value or "").strip()
|
||||
if not hostname:
|
||||
return ""
|
||||
|
||||
if os.environ.get("APP_ENV", "development") != "production":
|
||||
return hostname
|
||||
|
||||
if "://" in hostname or "/" in hostname or "@" in hostname:
|
||||
raise ValueError(f"s3_hostname 应为裸主机名,不含协议、路径或 userinfo:{hostname}")
|
||||
# 取主机部分:[v6] 形态取括号内;host:port 取冒号前;裸 IPv6(多个冒号)整体
|
||||
if "[" in hostname:
|
||||
host = hostname.split("[", 1)[1].split("]", 1)[0]
|
||||
rest = hostname.split("]", 1)[1] if "]" in hostname else ""
|
||||
if rest and not rest.startswith(":"):
|
||||
raise ValueError(f"s3_hostname 的 IPv6 括号后只允许端口:{hostname}")
|
||||
elif hostname.count(":") == 1:
|
||||
host = hostname.split(":")[0]
|
||||
else:
|
||||
host = hostname
|
||||
if not host or _endpoint_host_is_denied(host):
|
||||
raise ValueError(f"端点不允许指向内网/保留地址:{hostname}")
|
||||
return hostname
|
||||
@@ -1,18 +1,24 @@
|
||||
from typing import Any
|
||||
# @Time : 2023/8/15 09:51
|
||||
# @Author : Lan
|
||||
# @File : settings.py
|
||||
# @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"
|
||||
|
||||
if not data_root.exists():
|
||||
data_root.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
DEFAULT_CONFIG = {
|
||||
DEFAULT_CONFIG: dict[str, Any] = {
|
||||
"file_storage": "local",
|
||||
"storage_path": "",
|
||||
"storage_limit": 0,
|
||||
"name": "文件快递柜 - FileCodeBox",
|
||||
"description": "开箱即用的文件快传系统",
|
||||
"notify_title": "系统通知",
|
||||
@@ -26,6 +32,7 @@ DEFAULT_CONFIG = {
|
||||
"s3_region_name": "auto",
|
||||
"s3_signature_version": "s3v2",
|
||||
"s3_hostname": "",
|
||||
"s3_addressing_style": "auto",
|
||||
"s3_proxy": 0,
|
||||
"max_save_seconds": 0,
|
||||
"aws_session_token": "",
|
||||
@@ -35,21 +42,26 @@ DEFAULT_CONFIG = {
|
||||
"onedrive_password": "",
|
||||
"onedrive_root_path": "filebox_storage",
|
||||
"onedrive_proxy": 0,
|
||||
"webdav_hostname": "",
|
||||
"webdav_root_path": "filebox_storage",
|
||||
"webdav_proxy": 0,
|
||||
"admin_token": "FileCodeBox2023",
|
||||
"openUpload": 1,
|
||||
"uploadSize": 1024 * 1024 * 10,
|
||||
"expireStyle": ["day", "hour", "minute", "forever", "count"],
|
||||
"uploadMinute": 1,
|
||||
"admin_token": "",
|
||||
"jwt_secret": "",
|
||||
"admin_session_expire": ADMIN_SESSION_EXPIRE_DEFAULT,
|
||||
"open_upload": 1,
|
||||
"mcp_require_token": 0,
|
||||
"upload_size": 1024 * 1024 * 10,
|
||||
"allowed_file_types": ["*"],
|
||||
"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",
|
||||
@@ -63,12 +75,19 @@ DEFAULT_CONFIG = {
|
||||
"version": "1.0",
|
||||
},
|
||||
],
|
||||
"themesSelect": "themes/2024",
|
||||
"errorMinute": 1,
|
||||
"errorCount": 1,
|
||||
"port": 12345,
|
||||
"showAdminAddr": 0,
|
||||
"robotsText": "User-agent: *\nDisallow: /",
|
||||
"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",
|
||||
}
|
||||
|
||||
|
||||
@@ -92,6 +111,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()
|
||||
|
||||
|
||||
@@ -1,531 +0,0 @@
|
||||
# @Time : 2023/8/11 20:06
|
||||
# @Author : Lan
|
||||
# @File : storage.py
|
||||
# @Software: PyCharm
|
||||
from typing import Optional
|
||||
from urllib.parse import quote, unquote
|
||||
import aiohttp
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
import datetime
|
||||
import io
|
||||
import re
|
||||
import sys
|
||||
import aioboto3
|
||||
from botocore.config import Config
|
||||
from fastapi import HTTPException, Response, UploadFile
|
||||
from core.response import APIResponse
|
||||
from core.settings import data_root, settings
|
||||
from apps.base.models import FileCodes
|
||||
from core.utils import get_file_url
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
|
||||
class FileStorageInterface:
|
||||
_instance: Optional["FileStorageInterface"] = None
|
||||
|
||||
def __new__(cls, *args, **kwargs):
|
||||
if cls._instance is None:
|
||||
cls._instance = super(FileStorageInterface, cls).__new__(
|
||||
cls, *args, **kwargs
|
||||
)
|
||||
return cls._instance
|
||||
|
||||
async def save_file(self, file: UploadFile, save_path: str):
|
||||
"""
|
||||
保存文件
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
async def delete_file(self, file_code: FileCodes):
|
||||
"""
|
||||
删除文件
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
async def get_file_url(self, file_code: FileCodes):
|
||||
"""
|
||||
获取文件分享的url
|
||||
|
||||
如果服务不支持直接访问文件,可以通过服务器中转下载。
|
||||
此时,此方法可以调用 utils.py 中的 `get_file_url` 方法,获取服务器中转下载的url
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
async def get_file_response(self, file_code: FileCodes):
|
||||
"""
|
||||
获取文件响应
|
||||
|
||||
如果服务不支持直接访问文件,则需要实现该方法,返回文件响应
|
||||
其余情况,可以不实现该方法
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class SystemFileStorage(FileStorageInterface):
|
||||
def __init__(self):
|
||||
self.chunk_size = 256 * 1024
|
||||
self.root_path = data_root
|
||||
|
||||
def _save(self, file, save_path):
|
||||
with open(save_path, "wb") as f:
|
||||
chunk = file.read(self.chunk_size)
|
||||
while chunk:
|
||||
f.write(chunk)
|
||||
chunk = file.read(self.chunk_size)
|
||||
|
||||
async def save_file(self, file: UploadFile, save_path: str):
|
||||
save_path = self.root_path / save_path
|
||||
if not save_path.parent.exists():
|
||||
save_path.parent.mkdir(parents=True)
|
||||
await asyncio.to_thread(self._save, file.file, save_path)
|
||||
|
||||
async def delete_file(self, file_code: FileCodes):
|
||||
save_path = self.root_path / await file_code.get_file_path()
|
||||
if save_path.exists():
|
||||
save_path.unlink()
|
||||
|
||||
async def get_file_url(self, file_code: FileCodes):
|
||||
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()
|
||||
if not file_path.exists():
|
||||
return APIResponse(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}"
|
||||
return FileResponse(
|
||||
file_path,
|
||||
headers={"Content-Disposition": content_disposition},
|
||||
filename=filename # 保留原始文件名以备某些场景使用
|
||||
)
|
||||
|
||||
|
||||
class S3FileStorage(FileStorageInterface):
|
||||
def __init__(self):
|
||||
self.access_key_id = settings.s3_access_key_id
|
||||
self.secret_access_key = settings.s3_secret_access_key
|
||||
self.bucket_name = settings.s3_bucket_name
|
||||
self.s3_hostname = settings.s3_hostname
|
||||
self.region_name = settings.s3_region_name
|
||||
self.signature_version = settings.s3_signature_version
|
||||
self.endpoint_url = settings.s3_endpoint_url or f"https://{self.s3_hostname}"
|
||||
self.aws_session_token = settings.aws_session_token
|
||||
self.proxy = settings.s3_proxy
|
||||
self.session = aioboto3.Session(
|
||||
aws_access_key_id=self.access_key_id,
|
||||
aws_secret_access_key=self.secret_access_key,
|
||||
)
|
||||
if not settings.s3_endpoint_url:
|
||||
self.endpoint_url = f"https://{self.s3_hostname}"
|
||||
else:
|
||||
# 如果提供了 s3_endpoint_url,则优先使用它
|
||||
self.endpoint_url = settings.s3_endpoint_url
|
||||
|
||||
async def save_file(self, file: UploadFile, save_path: str):
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
await s3.put_object(
|
||||
Bucket=self.bucket_name,
|
||||
Key=save_path,
|
||||
Body=await file.read(),
|
||||
ContentType=file.content_type,
|
||||
)
|
||||
|
||||
async def delete_file(self, file_code: FileCodes):
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
await s3.delete_object(
|
||||
Bucket=self.bucket_name, Key=await file_code.get_file_path()
|
||||
)
|
||||
|
||||
async def get_file_response(self, file_code: FileCodes):
|
||||
try:
|
||||
filename = file_code.prefix + file_code.suffix
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
link = await s3.generate_presigned_url(
|
||||
"get_object",
|
||||
Params={
|
||||
"Bucket": self.bucket_name,
|
||||
"Key": await file_code.get_file_path(),
|
||||
},
|
||||
ExpiresIn=3600,
|
||||
)
|
||||
tmp = io.BytesIO()
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(link) as resp:
|
||||
tmp.write(await resp.read())
|
||||
tmp.seek(0)
|
||||
content = tmp.read()
|
||||
tmp.close()
|
||||
return Response(
|
||||
content,
|
||||
media_type="application/octet-stream",
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="{filename.encode("utf-8").decode("latin-1")}"'
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=503, detail="服务代理下载异常,请稍后再试")
|
||||
|
||||
async def get_file_url(self, file_code: FileCodes):
|
||||
if file_code.prefix == "文本分享":
|
||||
return file_code.text
|
||||
if self.proxy:
|
||||
return await get_file_url(file_code.code)
|
||||
else:
|
||||
async with self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
region_name=self.region_name,
|
||||
config=Config(signature_version=self.signature_version),
|
||||
) as s3:
|
||||
result = await s3.generate_presigned_url(
|
||||
"get_object",
|
||||
Params={
|
||||
"Bucket": self.bucket_name,
|
||||
"Key": await file_code.get_file_path(),
|
||||
},
|
||||
ExpiresIn=3600,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
class OneDriveFileStorage(FileStorageInterface):
|
||||
def __init__(self):
|
||||
try:
|
||||
import msal
|
||||
from office365.graph_client import GraphClient
|
||||
from office365.runtime.client_request_exception import (
|
||||
ClientRequestException,
|
||||
)
|
||||
except ImportError:
|
||||
raise ImportError("请先安装`msal`和`Office365-REST-Python-Client`")
|
||||
self.msal = msal
|
||||
self.domain = settings.onedrive_domain
|
||||
self.client_id = settings.onedrive_client_id
|
||||
self.username = settings.onedrive_username
|
||||
self.password = settings.onedrive_password
|
||||
self.proxy = settings.onedrive_proxy
|
||||
self._ClientRequestException = ClientRequestException
|
||||
|
||||
try:
|
||||
client = GraphClient(self.acquire_token_pwd)
|
||||
self.root_path = (
|
||||
client.me.drive.root.get_by_path(settings.onedrive_root_path)
|
||||
.get()
|
||||
.execute_query()
|
||||
)
|
||||
except ClientRequestException as e:
|
||||
if e.code == "itemNotFound":
|
||||
client.me.drive.root.create_folder(settings.onedrive_root_path)
|
||||
self.root_path = (
|
||||
client.me.drive.root.get_by_path(settings.onedrive_root_path)
|
||||
.get()
|
||||
.execute_query()
|
||||
)
|
||||
else:
|
||||
raise e
|
||||
except Exception as e:
|
||||
raise Exception("OneDrive验证失败,请检查配置是否正确\n" + str(e))
|
||||
|
||||
def acquire_token_pwd(self):
|
||||
authority_url = f"https://login.microsoftonline.com/{self.domain}"
|
||||
app = self.msal.PublicClientApplication(
|
||||
authority=authority_url, client_id=self.client_id
|
||||
)
|
||||
result = app.acquire_token_by_username_password(
|
||||
username=self.username,
|
||||
password=self.password,
|
||||
scopes=["https://graph.microsoft.com/.default"],
|
||||
)
|
||||
return result
|
||||
|
||||
def _get_path_str(self, path):
|
||||
if isinstance(path, str):
|
||||
path = path.replace("\\", "/").replace("//", "/").split("/")
|
||||
elif isinstance(path, Path):
|
||||
path = str(path).replace("\\", "/").replace("//", "/").split("/")
|
||||
else:
|
||||
raise TypeError("path must be str or Path")
|
||||
path[-1] = path[-1].split(".")[0]
|
||||
return "/".join(path)
|
||||
|
||||
def _save(self, file, save_path):
|
||||
content = file.file.read()
|
||||
name = 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, file: UploadFile, save_path: str):
|
||||
await asyncio.to_thread(self._save, file, save_path)
|
||||
|
||||
def _delete(self, save_path):
|
||||
path = self._get_path_str(save_path)
|
||||
try:
|
||||
self.root_path.get_by_path(path).delete_object().execute_query()
|
||||
except self._ClientRequestException as e:
|
||||
if e.code == "itemNotFound":
|
||||
pass
|
||||
else:
|
||||
raise e
|
||||
|
||||
async def delete_file(self, file_code: FileCodes):
|
||||
await asyncio.to_thread(self._delete, await file_code.get_file_path())
|
||||
|
||||
def _convert_link_to_download_link(self, link):
|
||||
p1 = re.search(r"https:\/\/(.+)\.sharepoint\.com", link).group(1)
|
||||
p2 = re.search(r"personal\/(.+)\/", link).group(1)
|
||||
p3 = re.search(rf"{p2}\/(.+)", link).group(1)
|
||||
return f"https://{p1}.sharepoint.com/personal/{p2}/_layouts/52/download.aspx?share={p3}"
|
||||
|
||||
def _get_file_url(self, save_path, name):
|
||||
path = self._get_path_str(save_path)
|
||||
remote_file = self.root_path.get_by_path(path + "/" + name)
|
||||
expiration_datetime = datetime.datetime.now(
|
||||
tz=datetime.timezone.utc
|
||||
) + datetime.timedelta(hours=1)
|
||||
expiration_datetime = expiration_datetime.strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
premission = remote_file.create_link(
|
||||
"view", "anonymous", expiration_datetime=expiration_datetime
|
||||
).execute_query()
|
||||
return self._convert_link_to_download_link(premission.link.webUrl)
|
||||
|
||||
async def get_file_response(self, file_code: FileCodes):
|
||||
try:
|
||||
filename = file_code.prefix + file_code.suffix
|
||||
link = await asyncio.to_thread(
|
||||
self._get_file_url, await file_code.get_file_path(), filename
|
||||
)
|
||||
tmp = io.BytesIO()
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(link) as resp:
|
||||
tmp.write(await resp.read())
|
||||
tmp.seek(0)
|
||||
content = tmp.read()
|
||||
tmp.close()
|
||||
return Response(
|
||||
content,
|
||||
media_type="application/octet-stream",
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="{filename.encode("utf-8").decode("latin-1")}"'
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=503, detail="服务代理下载异常,请稍后再试")
|
||||
|
||||
async def get_file_url(self, file_code: FileCodes):
|
||||
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(),
|
||||
f"{file_code.prefix}{file_code.suffix}",
|
||||
)
|
||||
|
||||
|
||||
class OpenDALFileStorage(FileStorageInterface):
|
||||
def __init__(self):
|
||||
try:
|
||||
import opendal
|
||||
except ImportError:
|
||||
raise ImportError('请先安装 `opendal`, 例如: "pip install opendal"')
|
||||
self.service = settings.opendal_scheme
|
||||
service_settings = {}
|
||||
for key, value in settings.items():
|
||||
if key.startswith("opendal_" + self.service):
|
||||
setting_name = key.split("_", 2)[2]
|
||||
service_settings[setting_name] = value
|
||||
self.operator = opendal.AsyncOperator(
|
||||
settings.opendal_scheme, **service_settings
|
||||
)
|
||||
|
||||
async def save_file(self, file: UploadFile, save_path: str):
|
||||
await self.operator.write(save_path, file.file.read())
|
||||
|
||||
async def delete_file(self, file_code: FileCodes):
|
||||
await self.operator.delete(await file_code.get_file_path())
|
||||
|
||||
async def get_file_url(self, file_code: FileCodes):
|
||||
return await get_file_url(file_code.code)
|
||||
|
||||
async def get_file_response(self, file_code: FileCodes):
|
||||
try:
|
||||
filename = file_code.prefix + file_code.suffix
|
||||
content = await self.operator.read(await file_code.get_file_path())
|
||||
headers = {"Content-Disposition": f'attachment; filename="{filename}"'}
|
||||
return Response(
|
||||
content, headers=headers, media_type="application/octet-stream"
|
||||
)
|
||||
except Exception as e:
|
||||
print(e, file=sys.stderr)
|
||||
raise HTTPException(status_code=404, detail="文件已过期删除")
|
||||
|
||||
|
||||
class WebDAVFileStorage(FileStorageInterface):
|
||||
_instance: Optional["WebDAVFileStorage"] = None
|
||||
|
||||
def __init__(self):
|
||||
if not hasattr(self, "_initialized"):
|
||||
self.base_url = settings.webdav_url.rstrip("/") + "/"
|
||||
self.auth = aiohttp.BasicAuth(
|
||||
login=settings.webdav_username, password=settings.webdav_password
|
||||
)
|
||||
self._initialized = True
|
||||
|
||||
def _build_url(self, path: str) -> str:
|
||||
encoded_path = quote(str(path).lstrip("/"))
|
||||
return f"{self.base_url}{encoded_path}"
|
||||
|
||||
async def _mkdir_p(self, directory_path: str):
|
||||
"""递归创建目录(类似mkdir -p)"""
|
||||
path_obj = Path(unquote(directory_path))
|
||||
current_path = ""
|
||||
|
||||
async with aiohttp.ClientSession(auth=self.auth) as session:
|
||||
# 逐级检查目录是否存在
|
||||
for part in path_obj.parts:
|
||||
current_path = str(Path(current_path) / part)
|
||||
url = self._build_url(current_path)
|
||||
|
||||
# 检查目录是否存在
|
||||
async with session.head(url) as resp:
|
||||
if resp.status == 404:
|
||||
# 创建目录
|
||||
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(
|
||||
status_code=mkcol_resp.status,
|
||||
detail=f"目录创建失败: {content[:200]}",
|
||||
)
|
||||
|
||||
async def _is_dir_empty(self, dir_path: str) -> bool:
|
||||
"""检查目录是否为空"""
|
||||
url = self._build_url(dir_path)
|
||||
|
||||
async with aiohttp.ClientSession(auth=self.auth) as session:
|
||||
async with session.request("PROPFIND", url, headers={"Depth": "1"}) as resp:
|
||||
if resp.status != 207: # 207 是 Multi-Status 响应
|
||||
return False
|
||||
content = await resp.text()
|
||||
# 如果只有一个 response(当前目录),说明目录为空
|
||||
return content.count("<D:response>") <= 1
|
||||
|
||||
async def _delete_empty_dirs(self, file_path: str, session: aiohttp.ClientSession):
|
||||
"""递归删除空目录"""
|
||||
path_obj = Path(file_path)
|
||||
current_path = path_obj.parent
|
||||
|
||||
while str(current_path) != ".":
|
||||
if not await self._is_dir_empty(str(current_path)):
|
||||
break
|
||||
|
||||
url = self._build_url(str(current_path))
|
||||
async with session.delete(url) as resp:
|
||||
if resp.status not in (200, 204, 404):
|
||||
break
|
||||
|
||||
current_path = current_path.parent
|
||||
|
||||
async def save_file(self, file: UploadFile, save_path: str):
|
||||
"""保存文件(自动创建目录)"""
|
||||
# 分离文件名和目录路径
|
||||
path_obj = Path(save_path)
|
||||
directory_path = str(path_obj.parent)
|
||||
|
||||
try:
|
||||
# 先创建目录结构
|
||||
await self._mkdir_p(directory_path)
|
||||
|
||||
# 上传文件
|
||||
url = self._build_url(save_path)
|
||||
async with aiohttp.ClientSession(auth=self.auth) as session:
|
||||
content = await file.read() # 注意:大文件需要分块读取
|
||||
async with session.put(
|
||||
url, data=content, headers={"Content-Type": file.content_type}
|
||||
) as resp:
|
||||
if resp.status not in (200, 201, 204):
|
||||
content = await resp.text()
|
||||
raise HTTPException(
|
||||
status_code=resp.status,
|
||||
detail=f"文件上传失败: {content[:200]}",
|
||||
)
|
||||
except aiohttp.ClientError as e:
|
||||
raise HTTPException(status_code=503, detail=f"WebDAV连接异常: {str(e)}")
|
||||
|
||||
async def delete_file(self, file_code: FileCodes):
|
||||
"""删除WebDAV文件及空目录"""
|
||||
file_path = await file_code.get_file_path()
|
||||
url = self._build_url(file_path)
|
||||
|
||||
try:
|
||||
async with aiohttp.ClientSession(auth=self.auth) as session:
|
||||
# 删除文件
|
||||
async with session.delete(url) as resp:
|
||||
if resp.status not in (200, 204, 404):
|
||||
content = await resp.text()
|
||||
raise HTTPException(
|
||||
status_code=resp.status,
|
||||
detail=f"WebDAV删除失败: {content[:200]}",
|
||||
)
|
||||
|
||||
# 使用同一个 session 删除空目录
|
||||
await self._delete_empty_dirs(file_path, session)
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
raise HTTPException(status_code=503, detail=f"WebDAV连接异常: {str(e)}")
|
||||
|
||||
async def get_file_url(self, file_code: FileCodes):
|
||||
return await get_file_url(file_code.code)
|
||||
|
||||
async def get_file_response(self, file_code: FileCodes):
|
||||
"""获取文件响应(代理模式)"""
|
||||
try:
|
||||
filename = file_code.prefix + file_code.suffix
|
||||
url = self._build_url(await file_code.get_file_path())
|
||||
async with aiohttp.ClientSession(auth=self.auth) as session:
|
||||
async with session.get(url) as resp:
|
||||
if resp.status != 200:
|
||||
raise HTTPException(
|
||||
status_code=resp.status,
|
||||
detail=f"文件获取失败: {await resp.text()}",
|
||||
)
|
||||
# 读取内容到内存
|
||||
content = await resp.read()
|
||||
return Response(
|
||||
content=content,
|
||||
media_type=resp.headers.get(
|
||||
"Content-Type", "application/octet-stream"
|
||||
),
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="{filename.encode("utf-8").decode()}"'
|
||||
},
|
||||
)
|
||||
except aiohttp.ClientError as e:
|
||||
raise HTTPException(status_code=503, detail=f"WebDAV连接异常: {str(e)}")
|
||||
|
||||
|
||||
storages = {
|
||||
"local": SystemFileStorage,
|
||||
"s3": S3FileStorage,
|
||||
"onedrive": OneDriveFileStorage,
|
||||
"opendal": OpenDALFileStorage,
|
||||
"webdav": WebDAVFileStorage,
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Storage backend package (split from the former 1400+ line storage.py).
|
||||
|
||||
Public surface is re-exported here — `from core.storage import X` keeps
|
||||
working for every historical name.
|
||||
"""
|
||||
from core.storage._base import ( # noqa: F401
|
||||
FileStorageInterface,
|
||||
S3_MIN_MULTIPART_PART_SIZE,
|
||||
StoredDownload,
|
||||
StoredFile,
|
||||
build_attachment_headers,
|
||||
)
|
||||
from core.storage.local import SystemFileStorage # noqa: F401
|
||||
from core.storage.s3 import S3FileStorage # noqa: F401
|
||||
from core.storage.onedrive import OneDriveFileStorage # noqa: F401
|
||||
from core.storage.opendal import OpenDALFileStorage # noqa: F401
|
||||
from core.storage.webdav import WebDAVFileStorage # noqa: F401
|
||||
|
||||
storages = {
|
||||
"local": SystemFileStorage,
|
||||
"s3": S3FileStorage,
|
||||
"onedrive": OneDriveFileStorage,
|
||||
"opendal": OpenDALFileStorage,
|
||||
"webdav": WebDAVFileStorage,
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
# @Time : 2023/8/11 20:06
|
||||
# @Author : Lan
|
||||
# @File : storage.py
|
||||
# @Software: PyCharm
|
||||
import hashlib
|
||||
import re
|
||||
from typing import BinaryIO, Optional
|
||||
from urllib.parse import quote
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@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: Path | None = None
|
||||
content: bytes | None = None
|
||||
stream_factory: Callable[[], Any] | None = None
|
||||
background: Any = None # starlette BackgroundTask(core 层不 import starlette)
|
||||
|
||||
|
||||
@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}"
|
||||
|
||||
|
||||
|
||||
|
||||
# S3 multipart 除最后一片外每部分最小 5MB(服务端强制,小于即 EntityTooSmall)
|
||||
S3_MIN_MULTIPART_PART_SIZE = 5 * 1024 * 1024
|
||||
|
||||
|
||||
def build_attachment_headers(filename: str, content_length=None) -> dict:
|
||||
"""所有存储后端统一的下载响应头。
|
||||
|
||||
Content-Disposition: attachment 是防御存储型 XSS 的关键——同源下载路径
|
||||
(/share/download)因此永不内联渲染 HTML/SVG。此函数是唯一构造点,
|
||||
新增后端必须复用(tests/test_attachment_guard.py 有源码级 tripwire)。
|
||||
"""
|
||||
# Older Android download managers ignore filename*. Keep an ASCII fallback
|
||||
# with the extension, without allowing quoted-string/header injection.
|
||||
fallback = re.sub(r"[^A-Za-z0-9._ -]", "_", filename).strip(" .") or "download"
|
||||
encoded_filename = quote(filename, safe="")
|
||||
headers = {
|
||||
"Content-Disposition": (
|
||||
f'attachment; filename="{fallback}"; filename*=UTF-8\'\'{encoded_filename}'
|
||||
)
|
||||
}
|
||||
if content_length is not None:
|
||||
headers["Content-Length"] = str(content_length)
|
||||
return headers
|
||||
|
||||
class FileStorageInterface:
|
||||
|
||||
@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: StoredFile):
|
||||
"""
|
||||
删除文件
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
async def get_file_url(self, file_code: StoredFile):
|
||||
"""
|
||||
获取文件分享的url
|
||||
|
||||
如果服务不支持直接访问文件,可以通过服务器中转下载。
|
||||
此时,此方法可以调用 utils.py 中的 `get_file_url` 方法,获取服务器中转下载的url
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
async def get_file_response(self, file_code: StoredFile):
|
||||
"""
|
||||
获取文件响应
|
||||
|
||||
如果服务不支持直接访问文件,则需要实现该方法,返回文件响应
|
||||
其余情况,可以不实现该方法
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str):
|
||||
"""
|
||||
保存分片文件
|
||||
:param upload_id: 上传会话ID
|
||||
:param chunk_index: 分片索引
|
||||
:param chunk_data: 分片数据
|
||||
:param chunk_hash: 分片哈希值
|
||||
:param save_path: 文件保存路径
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
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
|
||||
:param chunk_info: 分片信息
|
||||
:param save_path: 文件保存路径
|
||||
:return: (文件路径, 文件哈希值)
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
async def generate_presigned_upload_url(self, save_path: str, expires_in: int = 900) -> Optional[str]:
|
||||
"""
|
||||
生成预签名上传URL
|
||||
:param save_path: 文件保存路径
|
||||
:param expires_in: URL过期时间(秒),默认15分钟
|
||||
:return: 预签名URL,如果不支持直传则返回None
|
||||
"""
|
||||
return None # 默认不支持直传,使用代理模式
|
||||
|
||||
async def file_exists(self, save_path: str) -> bool:
|
||||
"""
|
||||
检查文件是否存在
|
||||
:param save_path: 文件路径
|
||||
:return: 文件是否存在
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
async def clean_chunks(self, upload_id: str, save_path: str):
|
||||
"""
|
||||
清理临时分片文件
|
||||
:param upload_id: 上传会话ID
|
||||
:param save_path: 文件保存路径
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import hashlib
|
||||
from core.logger import logger
|
||||
import shutil
|
||||
from typing import BinaryIO, Optional
|
||||
|
||||
import aiofiles
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
from core.errors import StorageError
|
||||
from core.settings import data_root
|
||||
from core.utils import get_file_url, sanitize_filename
|
||||
|
||||
from core.storage._base import (
|
||||
FileStorageInterface,
|
||||
StoredDownload,
|
||||
StoredFile,
|
||||
build_attachment_headers,
|
||||
)
|
||||
|
||||
|
||||
class SystemFileStorage(FileStorageInterface):
|
||||
def __init__(self):
|
||||
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)
|
||||
while chunk:
|
||||
f.write(chunk)
|
||||
chunk = file.read(self.chunk_size)
|
||||
|
||||
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._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, stream, safe_save_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: StoredFile):
|
||||
return await get_file_url(file_code.code)
|
||||
|
||||
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():
|
||||
raise StorageError(status_code=404, detail="文件已过期删除")
|
||||
filename = f"{file_code.prefix}{file_code.suffix}"
|
||||
try:
|
||||
headers = build_attachment_headers(filename, file_path.stat().st_size)
|
||||
except OSError:
|
||||
# 文件大小不可得时省略 Content-Length
|
||||
headers = build_attachment_headers(filename)
|
||||
|
||||
return StoredDownload(
|
||||
filename=filename,
|
||||
headers=headers,
|
||||
path=file_path,
|
||||
)
|
||||
|
||||
async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str):
|
||||
"""
|
||||
保存分片文件到本地文件系统
|
||||
:param upload_id: 上传会话ID
|
||||
:param chunk_index: 分片索引
|
||||
:param chunk_data: 分片数据
|
||||
:param chunk_hash: 分片哈希值
|
||||
:param save_path: 文件保存路径
|
||||
"""
|
||||
# 先校验目标文件路径合法,再将分片落到同级 chunks 目录。
|
||||
self._resolve_safe_path(save_path)
|
||||
chunk_path = self._resolve_safe_path(
|
||||
str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part")
|
||||
)
|
||||
if not chunk_path.parent.exists():
|
||||
chunk_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# 使用临时文件写入,确保原子性
|
||||
temp_path = chunk_path.with_suffix('.tmp')
|
||||
try:
|
||||
async with aiofiles.open(temp_path, "wb") as f:
|
||||
await f.write(chunk_data)
|
||||
# 原子重命名
|
||||
temp_path.rename(chunk_path)
|
||||
except Exception as e:
|
||||
if temp_path.exists():
|
||||
temp_path.unlink()
|
||||
raise e
|
||||
|
||||
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
|
||||
:param chunk_info: 分片信息
|
||||
:param save_path: 文件保存路径
|
||||
:return: (文件路径, 文件哈希值)
|
||||
"""
|
||||
output_path = self._resolve_safe_path(save_path)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
chunk_base_dir = self._resolve_safe_path(
|
||||
str(Path(save_path).parent / "chunks" / upload_id)
|
||||
)
|
||||
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(total_chunks):
|
||||
# 获取分片记录
|
||||
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()
|
||||
self._verify_and_hash_chunk(i, chunk_record, chunk_data, file_sha256)
|
||||
await out_file.write(chunk_data)
|
||||
# 原子重命名
|
||||
temp_output.rename(output_path)
|
||||
except Exception as e:
|
||||
if temp_output.exists():
|
||||
temp_output.unlink()
|
||||
raise e
|
||||
return str(output_path), file_sha256.hexdigest()
|
||||
|
||||
async def clean_chunks(self, upload_id: str, save_path: str):
|
||||
"""
|
||||
清理本地文件系统的临时分片文件
|
||||
:param upload_id: 上传会话ID
|
||||
:param save_path: 文件保存路径
|
||||
"""
|
||||
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.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.warning(f"清理 chunks 父目录失败: {e}")
|
||||
|
||||
async def file_exists(self, save_path: str) -> bool:
|
||||
"""
|
||||
检查文件是否存在于本地文件系统
|
||||
:param save_path: 文件路径
|
||||
:return: 文件是否存在
|
||||
"""
|
||||
try:
|
||||
file_path = self._resolve_safe_path(save_path)
|
||||
except ValueError:
|
||||
return False
|
||||
return file_path.exists()
|
||||
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
import hashlib
|
||||
import os
|
||||
import tempfile
|
||||
from core.logger import logger
|
||||
from typing import BinaryIO, Optional
|
||||
|
||||
import aiofiles
|
||||
import aiohttp
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
import datetime
|
||||
import re
|
||||
from core.errors import StorageError
|
||||
from core.settings import settings
|
||||
from core.utils import get_file_url, sanitize_filename
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
from core.storage._base import (
|
||||
FileStorageInterface,
|
||||
StoredDownload,
|
||||
StoredFile,
|
||||
build_attachment_headers,
|
||||
)
|
||||
|
||||
|
||||
class OneDriveFileStorage(FileStorageInterface):
|
||||
def __init__(self):
|
||||
try:
|
||||
import msal
|
||||
from office365.graph_client import GraphClient
|
||||
from office365.runtime.client_request_exception import (
|
||||
ClientRequestException,
|
||||
)
|
||||
except ImportError:
|
||||
raise ImportError("请先安装`msal`和`Office365-REST-Python-Client`")
|
||||
self.msal = msal
|
||||
self.domain = settings.onedrive_domain
|
||||
self.client_id = settings.onedrive_client_id
|
||||
self.username = settings.onedrive_username
|
||||
self.password = settings.onedrive_password
|
||||
self.proxy = settings.onedrive_proxy
|
||||
self._ClientRequestException = ClientRequestException
|
||||
|
||||
try:
|
||||
client = GraphClient(self.acquire_token_pwd)
|
||||
self.root_path = (
|
||||
client.me.drive.root.get_by_path(settings.onedrive_root_path)
|
||||
.get()
|
||||
.execute_query()
|
||||
)
|
||||
except ClientRequestException as e:
|
||||
if e.code == "itemNotFound":
|
||||
client.me.drive.root.create_folder(settings.onedrive_root_path)
|
||||
self.root_path = (
|
||||
client.me.drive.root.get_by_path(
|
||||
settings.onedrive_root_path)
|
||||
.get()
|
||||
.execute_query()
|
||||
)
|
||||
else:
|
||||
raise e
|
||||
except Exception as e:
|
||||
raise Exception("OneDrive验证失败,请检查配置是否正确\n" + str(e))
|
||||
|
||||
def acquire_token_pwd(self):
|
||||
authority_url = f"https://login.microsoftonline.com/{self.domain}"
|
||||
app = self.msal.PublicClientApplication(
|
||||
authority=authority_url, client_id=self.client_id
|
||||
)
|
||||
result = app.acquire_token_by_username_password(
|
||||
username=self.username,
|
||||
password=self.password,
|
||||
scopes=["https://graph.microsoft.com/.default"],
|
||||
)
|
||||
return result
|
||||
|
||||
def _get_path_str(self, path):
|
||||
if isinstance(path, str):
|
||||
path = path.replace("\\", "/").replace("//", "/").split("/")
|
||||
elif isinstance(path, Path):
|
||||
path = str(path).replace("\\", "/").replace("//", "/").split("/")
|
||||
else:
|
||||
raise TypeError("path must be str or Path")
|
||||
path[-1] = path[-1].split(".")[0]
|
||||
return "/".join(path)
|
||||
|
||||
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])
|
||||
|
||||
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)
|
||||
try:
|
||||
self.root_path.get_by_path(path).delete_object().execute_query()
|
||||
except self._ClientRequestException as e:
|
||||
if e.code == "itemNotFound":
|
||||
pass
|
||||
else:
|
||||
raise e
|
||||
|
||||
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)
|
||||
p2 = re.search(r"personal/(.+)/", link).group(1)
|
||||
p3 = re.search(rf"{p2}/(.+)", link).group(1)
|
||||
return f"https://{p1}.sharepoint.com/personal/{p2}/_layouts/52/download.aspx?share={p3}"
|
||||
|
||||
def _get_file_url(self, save_path, name):
|
||||
path = self._get_path_str(save_path)
|
||||
remote_file = self.root_path.get_by_path(path + "/" + name)
|
||||
expiration_datetime = datetime.datetime.now(
|
||||
tz=datetime.timezone.utc
|
||||
) + datetime.timedelta(hours=1)
|
||||
expiration_datetime = expiration_datetime.strftime(
|
||||
"%Y-%m-%dT%H:%M:%SZ")
|
||||
permission = remote_file.create_link(
|
||||
"view", "anonymous", expiration_datetime=expiration_datetime
|
||||
).execute_query()
|
||||
return self._convert_link_to_download_link(permission.link.webUrl)
|
||||
|
||||
async def get_file_response(self, file_code: StoredFile):
|
||||
try:
|
||||
filename = file_code.prefix + file_code.suffix
|
||||
try:
|
||||
link = await asyncio.to_thread(
|
||||
self._get_file_url, file_code.get_file_path(), filename
|
||||
)
|
||||
except self._ClientRequestException as e:
|
||||
# 对象不存在时前置 404(与 local/S3/WebDAV 语义对齐),
|
||||
# 不再落入外层兜底的 503
|
||||
if str(getattr(e, "code", "")).lower() in {"itemnotfound", "404"}:
|
||||
raise StorageError(
|
||||
status_code=404, detail="文件已过期删除"
|
||||
) from e
|
||||
raise
|
||||
|
||||
content_length = None # 初始化为 None,表示未知大小
|
||||
|
||||
# 创建ClientSession并复用
|
||||
session = aiohttp.ClientSession()
|
||||
|
||||
# 尝试发送HEAD请求获取Content-Length
|
||||
try:
|
||||
async with session.head(link) as resp:
|
||||
if resp.status == 200 and 'Content-Length' in resp.headers:
|
||||
content_length = int(resp.headers['Content-Length'])
|
||||
except Exception:
|
||||
# 如果HEAD请求失败,则不提供 Content-Length
|
||||
pass
|
||||
|
||||
async def stream_generator():
|
||||
try:
|
||||
async with session.get(link) as resp:
|
||||
if resp.status != 200:
|
||||
raise StorageError(
|
||||
status_code=resp.status,
|
||||
detail=f"从OneDrive获取文件失败: {resp.status}"
|
||||
)
|
||||
chunk_size = 65536
|
||||
while True:
|
||||
chunk = await resp.content.read(chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
headers = build_attachment_headers(filename, content_length)
|
||||
return StoredDownload(
|
||||
filename=filename,
|
||||
headers=headers,
|
||||
stream_factory=stream_generator,
|
||||
# 兜底关闭会话:客户端中断时与 generator finally 双保险
|
||||
background=BackgroundTask(session.close),
|
||||
)
|
||||
except StorageError:
|
||||
raise
|
||||
except Exception:
|
||||
raise StorageError(status_code=503, detail="服务代理下载异常,请稍后再试")
|
||||
|
||||
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,
|
||||
file_code.get_file_path(),
|
||||
f"{file_code.prefix}{file_code.suffix}",
|
||||
)
|
||||
|
||||
def _save_chunk(self, chunk_path: str, chunk_data: bytes):
|
||||
"""同步保存分片到 OneDrive"""
|
||||
path_parts = chunk_path.replace("\\", "/").split("/")
|
||||
filename = path_parts[-1]
|
||||
dir_path = "/".join(path_parts[:-1])
|
||||
|
||||
# 确保目录存在
|
||||
current_folder = self.root_path
|
||||
for part in dir_path.split("/"):
|
||||
if part:
|
||||
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
|
||||
|
||||
# 上传分片
|
||||
current_folder.upload(filename, chunk_data).execute_query()
|
||||
|
||||
async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str):
|
||||
"""保存分片到 OneDrive"""
|
||||
chunk_path = str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part")
|
||||
await asyncio.to_thread(self._save_chunk, chunk_path, chunk_data)
|
||||
|
||||
def _read_chunk(self, chunk_path: str) -> bytes:
|
||||
"""同步读取分片"""
|
||||
path = self._get_path_str(chunk_path)
|
||||
file_obj = self.root_path.get_by_path(path).get().execute_query()
|
||||
return file_obj.get_content().execute_query().value
|
||||
|
||||
def _upload_merged(self, save_path: str, data: bytes):
|
||||
"""同步上传合并后的文件"""
|
||||
path_parts = save_path.replace("\\", "/").split("/")
|
||||
filename = path_parts[-1]
|
||||
dir_path = "/".join(path_parts[:-1])
|
||||
|
||||
# 确保目录存在
|
||||
current_folder = self.root_path
|
||||
for part in dir_path.split("/"):
|
||||
if part:
|
||||
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
|
||||
|
||||
current_folder.upload(filename, data).execute_query()
|
||||
|
||||
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)
|
||||
|
||||
# 使用临时文件存储合并数据
|
||||
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
||||
temp_path = temp_file.name
|
||||
|
||||
try:
|
||||
async with aiofiles.open(temp_path, 'wb') as out_file:
|
||||
for i in range(total_chunks):
|
||||
chunk_path = f"{chunk_dir}/{i}.part"
|
||||
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}")
|
||||
|
||||
self._verify_and_hash_chunk(i, chunk_record, chunk_data, file_sha256)
|
||||
await out_file.write(chunk_data)
|
||||
del chunk_data # 释放内存
|
||||
|
||||
# 读取临时文件并上传
|
||||
async with aiofiles.open(temp_path, 'rb') as f:
|
||||
merged_content = await f.read()
|
||||
await asyncio.to_thread(self._upload_merged, save_path, merged_content)
|
||||
finally:
|
||||
# 清理临时文件
|
||||
if os.path.exists(temp_path):
|
||||
os.unlink(temp_path)
|
||||
|
||||
return save_path, file_sha256.hexdigest()
|
||||
|
||||
def _delete_chunk_dir(self, chunk_dir: str):
|
||||
"""同步删除分片目录"""
|
||||
try:
|
||||
path = self._get_path_str(chunk_dir)
|
||||
self.root_path.get_by_path(path).delete_object().execute_query()
|
||||
except self._ClientRequestException as e:
|
||||
if e.code != "itemNotFound":
|
||||
raise e
|
||||
|
||||
async def clean_chunks(self, upload_id: str, save_path: str):
|
||||
"""清理 OneDrive 上的临时分片文件"""
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
try:
|
||||
await asyncio.to_thread(self._delete_chunk_dir, chunk_dir)
|
||||
except Exception as e:
|
||||
logger.warning(f"清理 OneDrive 分片时出错: {e}")
|
||||
|
||||
def _file_exists(self, save_path: str) -> bool:
|
||||
"""同步检查文件是否存在"""
|
||||
try:
|
||||
path = self._get_path_str(save_path)
|
||||
self.root_path.get_by_path(path).get().execute_query()
|
||||
return True
|
||||
except self._ClientRequestException as e:
|
||||
if e.code == "itemNotFound":
|
||||
return False
|
||||
raise e
|
||||
|
||||
async def file_exists(self, save_path: str) -> bool:
|
||||
"""
|
||||
检查文件是否存在于OneDrive
|
||||
:param save_path: 文件路径
|
||||
:return: 文件是否存在
|
||||
"""
|
||||
return await asyncio.to_thread(self._file_exists, save_path)
|
||||
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import hashlib
|
||||
import os
|
||||
import tempfile
|
||||
from core.logger import logger
|
||||
from typing import BinaryIO, Optional
|
||||
|
||||
import aiofiles
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
from core.errors import StorageError
|
||||
from core.settings import settings
|
||||
from core.utils import get_file_url
|
||||
|
||||
from core.storage._base import (
|
||||
FileStorageInterface,
|
||||
StoredDownload,
|
||||
StoredFile,
|
||||
build_attachment_headers,
|
||||
)
|
||||
|
||||
|
||||
class OpenDALFileStorage(FileStorageInterface):
|
||||
def __init__(self):
|
||||
try:
|
||||
import opendal
|
||||
except ImportError:
|
||||
raise ImportError('请先安装 `opendal`, 例如: "pip install opendal"')
|
||||
self.service = settings.opendal_scheme
|
||||
service_settings = {}
|
||||
for key, value in settings.items():
|
||||
if key.startswith("opendal_" + self.service):
|
||||
setting_name = key.split("_", 2)[2]
|
||||
service_settings[setting_name] = value
|
||||
self.operator = opendal.AsyncOperator(
|
||||
settings.opendal_scheme, **service_settings
|
||||
)
|
||||
|
||||
async def save_file(
|
||||
self, stream: BinaryIO, save_path: str, content_type: Optional[str] = None
|
||||
):
|
||||
# 使用 asyncio.to_thread 避免阻塞事件循环
|
||||
content = await asyncio.to_thread(stream.read)
|
||||
await self.operator.write(save_path, content)
|
||||
|
||||
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: StoredFile):
|
||||
return await get_file_url(file_code.code)
|
||||
|
||||
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(file_code.get_file_path())
|
||||
if hasattr(stat_result, 'content_length') and stat_result.content_length:
|
||||
content_length = stat_result.content_length
|
||||
elif hasattr(stat_result, 'size') and stat_result.size:
|
||||
content_length = stat_result.size
|
||||
except Exception:
|
||||
# 如果获取大小失败,则不提供 Content-Length
|
||||
pass
|
||||
|
||||
# 尝试使用流式读取器
|
||||
try:
|
||||
# OpenDAL 可能提供 reader 方法返回一个异步读取器
|
||||
reader = await self.operator.reader(file_code.get_file_path())
|
||||
except AttributeError:
|
||||
# 如果 reader 方法不存在,回退到全量读取(兼容旧版本)
|
||||
content = await self.operator.read(file_code.get_file_path())
|
||||
headers = build_attachment_headers(filename, content_length)
|
||||
return StoredDownload(
|
||||
filename=filename,
|
||||
headers=headers,
|
||||
content=content,
|
||||
)
|
||||
|
||||
async def stream_generator():
|
||||
chunk_size = 65536
|
||||
while True:
|
||||
chunk = await reader.read(chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
|
||||
headers = build_attachment_headers(filename, content_length)
|
||||
return StoredDownload(
|
||||
filename=filename,
|
||||
headers=headers,
|
||||
stream_factory=stream_generator,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.info(e)
|
||||
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, 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)
|
||||
|
||||
# 使用临时文件存储合并数据
|
||||
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
||||
temp_path = temp_file.name
|
||||
|
||||
try:
|
||||
async with aiofiles.open(temp_path, 'wb') as out_file:
|
||||
for i in range(total_chunks):
|
||||
chunk_path = f"{chunk_dir}/{i}.part"
|
||||
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}")
|
||||
|
||||
self._verify_and_hash_chunk(i, chunk_record, chunk_data, file_sha256)
|
||||
await out_file.write(chunk_data)
|
||||
del chunk_data # 释放内存
|
||||
|
||||
# 读取临时文件并写入存储
|
||||
async with aiofiles.open(temp_path, 'rb') as f:
|
||||
merged_content = await f.read()
|
||||
await self.operator.write(save_path, merged_content)
|
||||
finally:
|
||||
# 清理临时文件
|
||||
if os.path.exists(temp_path):
|
||||
os.unlink(temp_path)
|
||||
|
||||
return save_path, file_sha256.hexdigest()
|
||||
|
||||
async def clean_chunks(self, upload_id: str, save_path: str):
|
||||
"""清理 OpenDAL 存储上的临时分片文件"""
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
try:
|
||||
# OpenDAL 支持递归删除
|
||||
await self.operator.remove_all(chunk_dir)
|
||||
except Exception as e:
|
||||
logger.warning(f"清理 OpenDAL 分片时出错: {e}")
|
||||
|
||||
async def file_exists(self, save_path: str) -> bool:
|
||||
"""
|
||||
检查文件是否存在于OpenDAL存储
|
||||
:param save_path: 文件路径
|
||||
:return: 文件是否存在
|
||||
"""
|
||||
try:
|
||||
await self.operator.stat(save_path)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
from botocore.exceptions import ClientError
|
||||
import hashlib
|
||||
from core.logger import logger
|
||||
from typing import BinaryIO, Optional
|
||||
|
||||
import aiohttp
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
import aioboto3
|
||||
from botocore.config import Config
|
||||
from core.errors import StorageError
|
||||
from core.settings import settings
|
||||
from core.utils import get_file_url
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
from core.storage._base import (
|
||||
FileStorageInterface,
|
||||
S3_MIN_MULTIPART_PART_SIZE,
|
||||
StoredDownload,
|
||||
StoredFile,
|
||||
build_attachment_headers,
|
||||
)
|
||||
|
||||
|
||||
class S3FileStorage(FileStorageInterface):
|
||||
def __init__(self):
|
||||
self.access_key_id = settings.s3_access_key_id
|
||||
self.secret_access_key = settings.s3_secret_access_key
|
||||
self.bucket_name = settings.s3_bucket_name
|
||||
self.s3_hostname = settings.s3_hostname
|
||||
self.region_name = settings.s3_region_name
|
||||
self.signature_version = settings.s3_signature_version
|
||||
self.endpoint_url = settings.s3_endpoint_url or f"https://{self.s3_hostname}"
|
||||
self.aws_session_token = settings.aws_session_token
|
||||
self.addressing_style = str(settings.s3_addressing_style or "auto").lower()
|
||||
self.proxy = settings.s3_proxy
|
||||
self.session = aioboto3.Session(
|
||||
aws_access_key_id=self.access_key_id,
|
||||
aws_secret_access_key=self.secret_access_key,
|
||||
)
|
||||
if not settings.s3_endpoint_url:
|
||||
self.endpoint_url = f"https://{self.s3_hostname}"
|
||||
else:
|
||||
# 如果提供了 s3_endpoint_url,则优先使用它
|
||||
self.endpoint_url = settings.s3_endpoint_url
|
||||
|
||||
def _client_config(self) -> Config:
|
||||
# OSS 等兼容服务不支持默认 flexible checksum 的 aws-chunked trailer。
|
||||
config = {
|
||||
"signature_version": self.signature_version,
|
||||
"request_checksum_calculation": "when_required",
|
||||
"response_checksum_validation": "when_required",
|
||||
}
|
||||
s3_config = {}
|
||||
if self.addressing_style in {"path", "virtual", "auto"}:
|
||||
s3_config["addressing_style"] = self.addressing_style
|
||||
if s3_config:
|
||||
config["s3"] = s3_config
|
||||
return Config(**config)
|
||||
|
||||
def _client(self):
|
||||
return self.session.client(
|
||||
"s3",
|
||||
endpoint_url=self.endpoint_url,
|
||||
aws_session_token=self.aws_session_token,
|
||||
region_name=self.region_name,
|
||||
config=self._client_config(),
|
||||
)
|
||||
|
||||
async def save_file(
|
||||
self, stream: BinaryIO, save_path: str, content_type: Optional[str] = None
|
||||
):
|
||||
async with self._client() as s3:
|
||||
# 使用 upload_fileobj 流式上传,避免将整个文件加载到内存
|
||||
await s3.upload_fileobj(
|
||||
stream,
|
||||
self.bucket_name,
|
||||
save_path,
|
||||
ExtraArgs={"ContentType": content_type or "application/octet-stream"},
|
||||
)
|
||||
|
||||
async def delete_file(self, file_code: StoredFile):
|
||||
async with self._client() as s3:
|
||||
await s3.delete_object(
|
||||
Bucket=self.bucket_name, Key=file_code.get_file_path()
|
||||
)
|
||||
|
||||
async def get_file_response(self, file_code: StoredFile):
|
||||
try:
|
||||
filename = file_code.prefix + file_code.suffix
|
||||
content_length = None # 初始化为 None,表示未知大小
|
||||
|
||||
async with self._client() as s3:
|
||||
# 尝试获取文件大小(HEAD请求);对象不存在时前置 404——
|
||||
# 与 local 后端语义一致(M2 行为统一),不能签出 200 的坏流
|
||||
try:
|
||||
head_response = await s3.head_object(
|
||||
Bucket=self.bucket_name,
|
||||
Key=file_code.get_file_path()
|
||||
)
|
||||
# 从HEAD响应中获取Content-Length
|
||||
if 'ContentLength' in head_response:
|
||||
content_length = head_response['ContentLength']
|
||||
elif 'Content-Length' in head_response['ResponseMetadata']['HTTPHeaders']:
|
||||
content_length = int(head_response['ResponseMetadata']['HTTPHeaders']['Content-Length'])
|
||||
except ClientError as e:
|
||||
error_code = e.response.get("Error", {}).get("Code", "")
|
||||
if error_code in {"404", "NoSuchKey", "NotFound"}:
|
||||
raise StorageError(
|
||||
status_code=404, detail="文件已过期删除"
|
||||
) from e
|
||||
# 其他 HEAD 错误不阻断:流式下载阶段会给出真实状态
|
||||
except Exception:
|
||||
# 如果HEAD请求失败,则不提供 Content-Length
|
||||
pass
|
||||
|
||||
link = await s3.generate_presigned_url(
|
||||
"get_object",
|
||||
Params={
|
||||
"Bucket": self.bucket_name,
|
||||
"Key": file_code.get_file_path(),
|
||||
},
|
||||
ExpiresIn=3600,
|
||||
)
|
||||
|
||||
# 创建ClientSession并传递给生成器复用
|
||||
session = aiohttp.ClientSession()
|
||||
|
||||
async def stream_generator():
|
||||
try:
|
||||
async with session.get(link) as resp:
|
||||
if resp.status != 200:
|
||||
raise StorageError(
|
||||
status_code=resp.status,
|
||||
detail=f"从S3获取文件失败: {resp.status}"
|
||||
)
|
||||
# 设置块大小(例如64KB)
|
||||
chunk_size = 65536
|
||||
while True:
|
||||
chunk = await resp.content.read(chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
headers = build_attachment_headers(filename, content_length)
|
||||
return StoredDownload(
|
||||
filename=filename,
|
||||
headers=headers,
|
||||
stream_factory=stream_generator,
|
||||
# 兜底关闭会话:客户端中断时与 generator finally 双保险
|
||||
background=BackgroundTask(session.close),
|
||||
)
|
||||
except StorageError:
|
||||
raise
|
||||
except Exception:
|
||||
raise StorageError(status_code=503, detail="服务代理下载异常,请稍后再试")
|
||||
|
||||
async def get_file_url(self, file_code: StoredFile):
|
||||
if file_code.prefix == "文本分享":
|
||||
return file_code.text
|
||||
if self.proxy:
|
||||
return await get_file_url(file_code.code)
|
||||
else:
|
||||
async with self._client() as s3:
|
||||
result = await s3.generate_presigned_url(
|
||||
"get_object",
|
||||
Params={
|
||||
"Bucket": self.bucket_name,
|
||||
"Key": file_code.get_file_path(),
|
||||
},
|
||||
ExpiresIn=3600,
|
||||
)
|
||||
return result
|
||||
|
||||
async def save_chunk(self, upload_id: str, chunk_index: int, chunk_data: bytes, chunk_hash: str, save_path: str):
|
||||
"""
|
||||
保存分片到 S3(使用独立对象存储每个分片)
|
||||
注意:这里不使用 S3 原生的 multipart upload,而是将每个分片作为独立对象存储
|
||||
"""
|
||||
chunk_key = str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part")
|
||||
async with self._client() as s3:
|
||||
# 将分片作为独立对象上传
|
||||
await s3.put_object(
|
||||
Bucket=self.bucket_name,
|
||||
Key=chunk_key,
|
||||
Body=chunk_data,
|
||||
Metadata={
|
||||
'chunk-hash': chunk_hash,
|
||||
'chunk-index': str(chunk_index)
|
||||
}
|
||||
)
|
||||
|
||||
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 实现流式合并,避免内存问题
|
||||
"""
|
||||
file_sha256 = hashlib.sha256()
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
|
||||
async with self._client() as s3:
|
||||
# 创建 multipart upload
|
||||
mpu = await s3.create_multipart_upload(
|
||||
Bucket=self.bucket_name,
|
||||
Key=save_path,
|
||||
ContentType='application/octet-stream'
|
||||
)
|
||||
mpu_id = mpu['UploadId']
|
||||
parts = []
|
||||
|
||||
try:
|
||||
# 按顺序读取、验证每个分片;S3 multipart 规范要求除最后一片外
|
||||
# 每个部分 ≥5MB(EntityTooSmall),而分片大小由客户端决定(常见
|
||||
# 2-4MB)——因此缓冲到 S3_MIN_MULTIPART_PART_SIZE 再上传 part,
|
||||
# 内存上界 = 5MB + 单个分片,不破坏流式合并的初衷。
|
||||
part_buffer = bytearray()
|
||||
part_number = 0
|
||||
|
||||
async def _flush_part():
|
||||
nonlocal part_number
|
||||
if not part_buffer:
|
||||
return
|
||||
part_number += 1
|
||||
part_response = await s3.upload_part(
|
||||
Bucket=self.bucket_name,
|
||||
Key=save_path,
|
||||
UploadId=mpu_id,
|
||||
PartNumber=part_number,
|
||||
Body=bytes(part_buffer),
|
||||
)
|
||||
parts.append({
|
||||
'PartNumber': part_number,
|
||||
'ETag': part_response['ETag']
|
||||
})
|
||||
part_buffer.clear()
|
||||
|
||||
for i in range(total_chunks):
|
||||
chunk_key = f"{chunk_dir}/{i}.part"
|
||||
chunk_record = self._get_chunk_record(chunk_records, i)
|
||||
|
||||
try:
|
||||
response = await s3.get_object(
|
||||
Bucket=self.bucket_name,
|
||||
Key=chunk_key
|
||||
)
|
||||
chunk_data = await response['Body'].read()
|
||||
except Exception as e:
|
||||
raise ValueError(f"分片{i}文件不存在: {e}")
|
||||
|
||||
self._verify_and_hash_chunk(i, chunk_record, chunk_data, file_sha256)
|
||||
part_buffer.extend(chunk_data)
|
||||
if len(part_buffer) >= S3_MIN_MULTIPART_PART_SIZE:
|
||||
await _flush_part()
|
||||
|
||||
# 收尾:剩余缓冲作为最后一个 part(S3 允许最后一片小于 5MB;
|
||||
# 恰好整除时缓冲为空,跳过)
|
||||
await _flush_part()
|
||||
|
||||
# 完成 multipart upload
|
||||
await s3.complete_multipart_upload(
|
||||
Bucket=self.bucket_name,
|
||||
Key=save_path,
|
||||
UploadId=mpu_id,
|
||||
MultipartUpload={'Parts': parts}
|
||||
)
|
||||
except Exception as e:
|
||||
# 出错时取消 multipart upload
|
||||
await s3.abort_multipart_upload(
|
||||
Bucket=self.bucket_name,
|
||||
Key=save_path,
|
||||
UploadId=mpu_id
|
||||
)
|
||||
raise e
|
||||
|
||||
return save_path, file_sha256.hexdigest()
|
||||
|
||||
async def clean_chunks(self, upload_id: str, save_path: str):
|
||||
"""
|
||||
清理 S3 上的临时分片文件
|
||||
:param upload_id: 上传会话ID
|
||||
:param save_path: 文件保存路径
|
||||
"""
|
||||
# 尾部斜杠防止误删 upload_id 相同前缀的其他会话。
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id) + "/"
|
||||
async with self._client() as s3:
|
||||
paginator = s3.get_paginator("list_objects_v2")
|
||||
async for page in paginator.paginate(Bucket=self.bucket_name, Prefix=chunk_dir):
|
||||
for obj in page.get("Contents", []):
|
||||
# OSS 批量删除要求 Content-MD5;单对象删除不依赖该扩展。
|
||||
# 失败向调用方传播,保留会话供重试,不能当作清理成功。
|
||||
await s3.delete_object(Bucket=self.bucket_name, Key=obj["Key"])
|
||||
|
||||
async def generate_presigned_upload_url(self, save_path: str, expires_in: int = 900) -> Optional[str]:
|
||||
"""
|
||||
生成S3预签名上传URL
|
||||
:param save_path: 文件保存路径
|
||||
:param expires_in: URL过期时间(秒),默认15分钟
|
||||
:return: 预签名PUT URL
|
||||
"""
|
||||
async with self._client() as s3:
|
||||
return await s3.generate_presigned_url(
|
||||
"put_object",
|
||||
Params={
|
||||
"Bucket": self.bucket_name,
|
||||
"Key": save_path,
|
||||
},
|
||||
ExpiresIn=expires_in,
|
||||
)
|
||||
|
||||
async def file_exists(self, save_path: str) -> bool:
|
||||
"""
|
||||
检查文件是否存在于S3
|
||||
:param save_path: 文件路径
|
||||
:return: 文件是否存在
|
||||
"""
|
||||
async with self._client() as s3:
|
||||
last_error = None
|
||||
for attempt in range(3):
|
||||
try:
|
||||
await s3.head_object(Bucket=self.bucket_name, Key=save_path)
|
||||
return True
|
||||
except Exception as e:
|
||||
last_error = e
|
||||
if attempt < 2:
|
||||
await asyncio.sleep(0.2 * (attempt + 1))
|
||||
|
||||
try:
|
||||
result = await s3.list_objects_v2(
|
||||
Bucket=self.bucket_name,
|
||||
Prefix=save_path,
|
||||
MaxKeys=1,
|
||||
)
|
||||
for item in result.get("Contents", []):
|
||||
if item.get("Key") == save_path:
|
||||
return True
|
||||
except Exception as e:
|
||||
last_error = e
|
||||
|
||||
logger.warning(f"S3文件确认失败 key={save_path}: {last_error}")
|
||||
return False
|
||||
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
import tempfile
|
||||
from core.logger import logger
|
||||
from typing import BinaryIO, Optional
|
||||
from urllib.parse import quote, unquote
|
||||
|
||||
import aiofiles
|
||||
import aiohttp
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
import re
|
||||
from core.errors import StorageError
|
||||
from core.settings import settings
|
||||
from core.utils import get_file_url, sanitize_filename
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
from core.storage._base import (
|
||||
FileStorageInterface,
|
||||
StoredDownload,
|
||||
StoredFile,
|
||||
build_attachment_headers,
|
||||
)
|
||||
|
||||
|
||||
class WebDAVFileStorage(FileStorageInterface):
|
||||
def __init__(self):
|
||||
if not hasattr(self, "_initialized"):
|
||||
self.base_url = settings.webdav_url.rstrip("/") + "/"
|
||||
# aiohttp 4.0 移除 BasicAuth(auth=...) 参数——改用编码后的 Authorization 头
|
||||
self.auth_headers = {
|
||||
"Authorization": aiohttp.encode_basic_auth(
|
||||
settings.webdav_username, settings.webdav_password
|
||||
)
|
||||
}
|
||||
self._initialized = True
|
||||
|
||||
def _build_url(self, path: str) -> str:
|
||||
encoded_path = quote(str(path.replace("\\", "/").lstrip("/")).lstrip("/"))
|
||||
return f"{self.base_url}{encoded_path}"
|
||||
|
||||
async def _mkdir_p(self, directory_path: str):
|
||||
"""递归创建目录(类似mkdir -p)"""
|
||||
path_obj = Path(unquote(directory_path))
|
||||
current_path = ""
|
||||
|
||||
async with aiohttp.ClientSession(headers=self.auth_headers) as session:
|
||||
# 逐级检查目录是否存在
|
||||
for part in path_obj.parts:
|
||||
current_path = str(Path(current_path) / part)
|
||||
url = self._build_url(current_path)
|
||||
|
||||
# 检查目录是否存在
|
||||
async with session.head(url) as resp:
|
||||
if resp.status == 404:
|
||||
# 创建目录
|
||||
async with session.request("MKCOL", url) as mkcol_resp:
|
||||
if mkcol_resp.status not in (200, 201, 409):
|
||||
content = await mkcol_resp.text()
|
||||
raise StorageError(
|
||||
status_code=mkcol_resp.status,
|
||||
detail=f"目录创建失败: {content[:200]}",
|
||||
)
|
||||
|
||||
async def _is_dir_empty(self, dir_path: str) -> bool:
|
||||
"""检查目录是否为空"""
|
||||
url = self._build_url(dir_path)
|
||||
|
||||
async with aiohttp.ClientSession(headers=self.auth_headers) as session:
|
||||
async with session.request("PROPFIND", url, headers={"Depth": "1"}) as resp:
|
||||
if resp.status != 207: # 207 是 Multi-Status 响应
|
||||
return False
|
||||
content = await resp.text()
|
||||
# 如果只有一个 response(当前目录),说明目录为空
|
||||
return content.count("<D:response>") <= 1
|
||||
|
||||
async def _delete_empty_dirs(self, file_path: str, session: aiohttp.ClientSession):
|
||||
"""递归删除空目录"""
|
||||
path_obj = Path(file_path)
|
||||
current_path = path_obj.parent
|
||||
|
||||
while str(current_path) != ".":
|
||||
if not await self._is_dir_empty(str(current_path)):
|
||||
break
|
||||
|
||||
url = self._build_url(str(current_path))
|
||||
async with session.delete(url) as resp:
|
||||
if resp.status not in (200, 204, 404):
|
||||
break
|
||||
|
||||
current_path = current_path.parent
|
||||
|
||||
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)
|
||||
# 提取原始文件名并进行清理
|
||||
filename = await sanitize_filename(path_obj.name)
|
||||
# 构建安全的保存路径
|
||||
safe_save_path = str(Path(directory_path) / filename)
|
||||
|
||||
try:
|
||||
# 先创建目录结构
|
||||
await self._mkdir_p(directory_path)
|
||||
# 上传文件(流式)
|
||||
url = self._build_url(safe_save_path)
|
||||
|
||||
async def file_sender():
|
||||
"""流式读取文件内容"""
|
||||
chunk_size = 256 * 1024 # 256KB chunks
|
||||
while True:
|
||||
chunk = await asyncio.to_thread(stream.read, chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
|
||||
async with aiohttp.ClientSession(headers=self.auth_headers) as session:
|
||||
async with session.put(
|
||||
url,
|
||||
data=file_sender(),
|
||||
headers={"Content-Type": content_type or "application/octet-stream"}
|
||||
) as resp:
|
||||
if resp.status not in (200, 201, 204):
|
||||
content = await resp.text()
|
||||
raise StorageError(
|
||||
status_code=resp.status,
|
||||
detail=f"文件上传失败: {content[:200]}",
|
||||
)
|
||||
except aiohttp.ClientError as e:
|
||||
raise StorageError(
|
||||
status_code=503, detail=f"WebDAV连接异常: {str(e)}")
|
||||
|
||||
async def delete_file(self, file_code: StoredFile):
|
||||
"""删除WebDAV文件及空目录"""
|
||||
file_path = file_code.get_file_path()
|
||||
url = self._build_url(file_path)
|
||||
try:
|
||||
async with aiohttp.ClientSession(headers=self.auth_headers) as session:
|
||||
# 删除文件
|
||||
async with session.delete(url) as resp:
|
||||
if resp.status not in (200, 204, 404):
|
||||
content = await resp.text()
|
||||
raise StorageError(
|
||||
status_code=resp.status,
|
||||
detail=f"WebDAV删除失败: {content[:200]}",
|
||||
)
|
||||
|
||||
# 使用同一个 session 删除空目录
|
||||
await self._delete_empty_dirs(file_path, session)
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
raise StorageError(
|
||||
status_code=503, detail=f"WebDAV连接异常: {str(e)}")
|
||||
|
||||
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: StoredFile):
|
||||
"""获取文件响应(代理模式)"""
|
||||
try:
|
||||
filename = file_code.prefix + file_code.suffix
|
||||
url = self._build_url(file_code.get_file_path())
|
||||
content_length = None # 初始化为 None,表示未知大小
|
||||
|
||||
# 创建ClientSession并复用(包含认证头)
|
||||
session = aiohttp.ClientSession(headers={
|
||||
"Authorization": f"Basic {base64.b64encode(f'{settings.webdav_username}:{settings.webdav_password}'.encode()).decode()}"
|
||||
})
|
||||
|
||||
# 尝试发送HEAD请求获取Content-Length;对象不存在时前置 404
|
||||
# (与 local/S3 语义对齐),连接层错误映射 503——两者都不能
|
||||
# 静默吞掉后签出 200 坏流。异常路径回收 session 防泄漏。
|
||||
try:
|
||||
try:
|
||||
async with session.head(url) as resp:
|
||||
if resp.status == 404:
|
||||
raise StorageError(
|
||||
status_code=404, detail="文件已过期删除"
|
||||
)
|
||||
if resp.status == 200 and 'Content-Length' in resp.headers:
|
||||
content_length = int(resp.headers['Content-Length'])
|
||||
except StorageError:
|
||||
raise
|
||||
except aiohttp.ClientError as e:
|
||||
raise StorageError(
|
||||
status_code=503, detail=f"WebDAV连接异常: {str(e)}"
|
||||
) from e
|
||||
except Exception:
|
||||
# 其他 HEAD 异常不阻断:流式下载阶段会给出真实状态
|
||||
pass
|
||||
|
||||
except BaseException:
|
||||
await session.close()
|
||||
raise
|
||||
|
||||
async def stream_generator():
|
||||
try:
|
||||
async with session.get(url) as resp:
|
||||
if resp.status != 200:
|
||||
raise StorageError(
|
||||
status_code=resp.status,
|
||||
detail=f"文件获取失败{resp.status}: {await resp.text()}",
|
||||
)
|
||||
chunk_size = 65536
|
||||
while True:
|
||||
chunk = await resp.content.read(chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
headers = build_attachment_headers(filename, content_length)
|
||||
return StoredDownload(
|
||||
filename=filename,
|
||||
headers=headers,
|
||||
stream_factory=stream_generator,
|
||||
# 兜底关闭会话:客户端中断时与 generator finally 双保险
|
||||
background=BackgroundTask(session.close),
|
||||
)
|
||||
except aiohttp.ClientError as e:
|
||||
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):
|
||||
"""保存分片到 WebDAV"""
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
chunk_path = f"{chunk_dir}/{chunk_index}.part"
|
||||
|
||||
# 先创建目录结构
|
||||
await self._mkdir_p(chunk_dir)
|
||||
|
||||
chunk_url = self._build_url(chunk_path)
|
||||
async with aiohttp.ClientSession(headers=self.auth_headers) as session:
|
||||
async with session.put(chunk_url, data=chunk_data) as resp:
|
||||
if resp.status not in (200, 201, 204):
|
||||
content = await resp.text()
|
||||
raise StorageError(
|
||||
status_code=resp.status,
|
||||
detail=f"分片上传失败: {content[:200]}"
|
||||
)
|
||||
|
||||
async def merge_chunks(self, upload_id: str, total_chunks: int, chunk_size: int, save_path: str, chunk_records: dict) -> tuple[str, str]:
|
||||
"""
|
||||
合并 WebDAV 上的分片文件
|
||||
使用临时文件避免内存问题
|
||||
"""
|
||||
file_sha256 = hashlib.sha256()
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
|
||||
# 使用临时文件存储合并数据,避免内存问题
|
||||
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
||||
temp_path = temp_file.name
|
||||
|
||||
try:
|
||||
async with aiohttp.ClientSession(headers=self.auth_headers) as session:
|
||||
# 按顺序读取并验证每个分片,写入临时文件
|
||||
async with aiofiles.open(temp_path, 'wb') as out_file:
|
||||
for i in range(total_chunks):
|
||||
chunk_path = f"{chunk_dir}/{i}.part"
|
||||
chunk_url = self._build_url(chunk_path)
|
||||
|
||||
# 获取分片记录
|
||||
chunk_record = self._get_chunk_record(chunk_records, i)
|
||||
|
||||
# 下载分片数据
|
||||
async with session.get(chunk_url) as resp:
|
||||
if resp.status != 200:
|
||||
raise ValueError(f"分片{i}文件不存在或无法访问")
|
||||
chunk_data = await resp.read()
|
||||
|
||||
# 验证哈希
|
||||
self._verify_and_hash_chunk(i, chunk_record, chunk_data, file_sha256)
|
||||
await out_file.write(chunk_data)
|
||||
del chunk_data # 释放内存
|
||||
|
||||
# 确保目标目录存在
|
||||
output_dir = str(Path(save_path).parent)
|
||||
await self._mkdir_p(output_dir)
|
||||
|
||||
# 流式上传合并后的文件
|
||||
output_url = self._build_url(save_path)
|
||||
|
||||
async def file_sender():
|
||||
async with aiofiles.open(temp_path, 'rb') as f:
|
||||
while True:
|
||||
chunk = await f.read(256 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
|
||||
async with session.put(output_url, data=file_sender()) as resp:
|
||||
if resp.status not in (200, 201, 204):
|
||||
content = await resp.text()
|
||||
raise StorageError(
|
||||
status_code=resp.status,
|
||||
detail=f"合并文件上传失败: {content[:200]}"
|
||||
)
|
||||
finally:
|
||||
# 清理临时文件
|
||||
if os.path.exists(temp_path):
|
||||
os.unlink(temp_path)
|
||||
|
||||
return save_path, file_sha256.hexdigest()
|
||||
|
||||
async def clean_chunks(self, upload_id: str, save_path: str):
|
||||
"""
|
||||
清理 WebDAV 上的临时分片文件
|
||||
:param upload_id: 上传会话ID
|
||||
:param save_path: 文件保存路径
|
||||
"""
|
||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||
chunk_dir_url = self._build_url(chunk_dir)
|
||||
async with aiohttp.ClientSession(headers=self.auth_headers) as session:
|
||||
try:
|
||||
# 检查分片目录是否存在
|
||||
async with session.request("PROPFIND", chunk_dir_url, headers={"Depth": "1"}) as resp:
|
||||
if resp.status == 207: # 207 表示 Multi-Status
|
||||
# 获取目录下的所有分片文件
|
||||
xml_data = await resp.text()
|
||||
file_paths = re.findall(
|
||||
r'<D:href>(.*?)</D:href>', xml_data)
|
||||
for file_path in file_paths:
|
||||
if file_path.endswith(".part"):
|
||||
# 删除分片文件
|
||||
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.warning(f"删除分片文件失败: {file_path}")
|
||||
|
||||
# 删除分片目录
|
||||
async with session.delete(chunk_dir_url) as delete_resp:
|
||||
if delete_resp.status not in (200, 204, 404):
|
||||
logger.warning(f"删除分片目录失败: {chunk_dir_url}")
|
||||
else:
|
||||
logger.info(f"分片目录不存在: {chunk_dir_url}")
|
||||
except Exception as e:
|
||||
logger.warning(f"清理 WebDAV 分片时出错: {e}")
|
||||
|
||||
async def file_exists(self, save_path: str) -> bool:
|
||||
"""
|
||||
检查文件是否存在于WebDAV
|
||||
:param save_path: 文件路径
|
||||
:return: 文件是否存在
|
||||
"""
|
||||
url = self._build_url(save_path)
|
||||
async with aiohttp.ClientSession(headers=self.auth_headers) as session:
|
||||
async with session.head(url) as resp:
|
||||
return resp.status == 200
|
||||
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
# @Time : 2023/8/15 22:00
|
||||
# @Author : Lan
|
||||
# @File : tasks.py
|
||||
# @Software: PyCharm
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
from tortoise.expressions import Q
|
||||
|
||||
from apps.base.models import FileCodes
|
||||
from apps.base.utils import ip_limit
|
||||
from core.settings import settings, data_root
|
||||
from core.storage import FileStorageInterface, storages
|
||||
from core.utils import get_now
|
||||
|
||||
|
||||
async def delete_expire_files():
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
while True:
|
||||
try:
|
||||
# 遍历 share目录下的所有文件夹,删除空的文件夹,并判断父目录是否为空,如果为空也删除
|
||||
if settings.file_storage == "local":
|
||||
for root, dirs, files in os.walk(f"{data_root}/share/data"):
|
||||
if not dirs and not files:
|
||||
os.rmdir(root)
|
||||
await ip_limit["error"].remove_expired_ip()
|
||||
await ip_limit["upload"].remove_expired_ip()
|
||||
expire_data = await FileCodes.filter(
|
||||
Q(expired_at__lt=await get_now()) | Q(expired_count=0)
|
||||
).all()
|
||||
for exp in expire_data:
|
||||
await file_storage.delete_file(exp)
|
||||
await exp.delete()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
finally:
|
||||
await asyncio.sleep(600)
|
||||
@@ -4,9 +4,13 @@
|
||||
# @Software: PyCharm
|
||||
import datetime
|
||||
import hashlib
|
||||
import random
|
||||
import hmac
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import string
|
||||
import time
|
||||
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
@@ -15,18 +19,39 @@ async def get_random_num():
|
||||
获取随机数
|
||||
:return:
|
||||
"""
|
||||
return random.randint(10000, 99999)
|
||||
return secrets.randbelow(90000) + 10000
|
||||
|
||||
|
||||
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():
|
||||
"""
|
||||
获取随机字符串
|
||||
:return:
|
||||
"""
|
||||
return "".join(random.choice(r_s) for _ in range(5))
|
||||
return "".join(secrets.choice(r_s) for _ in range(5))
|
||||
|
||||
|
||||
async def get_now():
|
||||
@@ -37,15 +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 = settings.admin_token
|
||||
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()
|
||||
|
||||
|
||||
@@ -92,3 +124,108 @@ async def max_save_times_desc(max_save_seconds: int):
|
||||
desc_zh += gen_desc_zh(max_timedelta.seconds % 60, "秒")
|
||||
desc_en += gen_desc_en(max_timedelta.seconds % 60, "second")
|
||||
return desc_zh, desc_en
|
||||
|
||||
|
||||
# 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:
|
||||
"""
|
||||
使用 scrypt(memory-hard)哈希密码
|
||||
返回格式: scrypt$<n>$<r>$<p>$<salt>$<hash>
|
||||
"""
|
||||
salt = os.urandom(16).hex()
|
||||
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:
|
||||
"""
|
||||
验证密码是否匹配
|
||||
支持格式: scrypt$n$r$p$salt$hash(现行)、sha256$salt$hash(历史)、明文(最老)
|
||||
"""
|
||||
if not hashed:
|
||||
return False
|
||||
|
||||
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()
|
||||
# 默认解释器对超范围的 n/r/p 抛 TypeError/ValueError;部分构建会抛
|
||||
# OverflowError,一并视为校验失败,避免坏掉的存量哈希影响登录路径。
|
||||
except (ValueError, TypeError, OverflowError):
|
||||
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 hmac.compare_digest(password_hash, stored_hash)
|
||||
|
||||
# 旧格式: 明文比较 (兼容迁移前的数据)
|
||||
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. 剥离路径只保留文件名
|
||||
2. 替换非法字符
|
||||
3. 处理空文件名情况
|
||||
"""
|
||||
filename = os.path.basename(filename)
|
||||
illegal_chars = r'[\\/*?:"<>|\x00-\x1F]' # 包含控制字符
|
||||
# 替换非法字符为下划线
|
||||
cleaned = re.sub(illegal_chars, "_", filename)
|
||||
# 处理空格(可选替换为_)
|
||||
cleaned = cleaned.replace(" ", "_")
|
||||
# 处理连续下划线
|
||||
cleaned = re.sub(r"_+", "_", cleaned)
|
||||
# 处理首尾特殊字符
|
||||
cleaned = cleaned.strip("._")
|
||||
# 处理空文件名情况
|
||||
if not cleaned:
|
||||
cleaned = "unnamed_file"
|
||||
# 长度限制(按需调整)
|
||||
return cleaned[:255]
|
||||
@@ -0,0 +1,20 @@
|
||||
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()
|
||||
@@ -0,0 +1,24 @@
|
||||
version: "3"
|
||||
services:
|
||||
file-code-box:
|
||||
image: lanol/filecodebox:2.8.5 # x-release-please-version
|
||||
volumes:
|
||||
- fcb-data:/app/data:rw
|
||||
# NAS 已有文件:把共享目录挂到 /app/data/local,即可在后台「本地分享」里生成提取码,无需再上传
|
||||
# - /volume1/share:/app/data/local:ro
|
||||
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
|
||||
@@ -1,275 +0,0 @@
|
||||
import {
|
||||
useMediaQuery
|
||||
} from "./chunk-KT7LHMJ2.js";
|
||||
import {
|
||||
computed,
|
||||
ref,
|
||||
shallowRef,
|
||||
watch
|
||||
} from "./chunk-CQOUZRMK.js";
|
||||
|
||||
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/index.js
|
||||
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/fonts.css";
|
||||
|
||||
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/without-fonts.js
|
||||
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/vars.css";
|
||||
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/base.css";
|
||||
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/icons.css";
|
||||
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/utils.css";
|
||||
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/components/custom-block.css";
|
||||
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/components/vp-code.css";
|
||||
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/components/vp-code-group.css";
|
||||
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/components/vp-doc.css";
|
||||
import "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/styles/components/vp-sponsor.css";
|
||||
import VPBadge from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPBadge.vue";
|
||||
import Layout from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/Layout.vue";
|
||||
import { default as default2 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPBadge.vue";
|
||||
import { default as default3 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPButton.vue";
|
||||
import { default as default4 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPDocAsideSponsors.vue";
|
||||
import { default as default5 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPFeatures.vue";
|
||||
import { default as default6 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPHomeContent.vue";
|
||||
import { default as default7 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPHomeFeatures.vue";
|
||||
import { default as default8 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPHomeHero.vue";
|
||||
import { default as default9 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPHomeSponsors.vue";
|
||||
import { default as default10 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPImage.vue";
|
||||
import { default as default11 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPLink.vue";
|
||||
import { default as default12 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPNavBarSearch.vue";
|
||||
import { default as default13 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPSocialLink.vue";
|
||||
import { default as default14 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPSocialLinks.vue";
|
||||
import { default as default15 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPSponsors.vue";
|
||||
import { default as default16 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPTeamMembers.vue";
|
||||
import { default as default17 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPTeamPage.vue";
|
||||
import { default as default18 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPTeamPageSection.vue";
|
||||
import { default as default19 } from "/Users/lan/Project/Python/FileCodeBox/docs/node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/components/VPTeamPageTitle.vue";
|
||||
|
||||
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/local-nav.js
|
||||
import { onContentUpdated } from "vitepress";
|
||||
|
||||
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/outline.js
|
||||
import { getScrollOffset } from "vitepress";
|
||||
|
||||
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/support/utils.js
|
||||
import { withBase } from "vitepress";
|
||||
|
||||
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/data.js
|
||||
import { useData as useData$ } from "vitepress";
|
||||
var useData = useData$;
|
||||
|
||||
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/support/utils.js
|
||||
function ensureStartingSlash(path) {
|
||||
return path.startsWith("/") ? path : `/${path}`;
|
||||
}
|
||||
|
||||
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/support/sidebar.js
|
||||
function getSidebar(_sidebar, path) {
|
||||
if (Array.isArray(_sidebar))
|
||||
return addBase(_sidebar);
|
||||
if (_sidebar == null)
|
||||
return [];
|
||||
path = ensureStartingSlash(path);
|
||||
const dir = Object.keys(_sidebar).sort((a, b) => {
|
||||
return b.split("/").length - a.split("/").length;
|
||||
}).find((dir2) => {
|
||||
return path.startsWith(ensureStartingSlash(dir2));
|
||||
});
|
||||
const sidebar = dir ? _sidebar[dir] : [];
|
||||
return Array.isArray(sidebar) ? addBase(sidebar) : addBase(sidebar.items, sidebar.base);
|
||||
}
|
||||
function getSidebarGroups(sidebar) {
|
||||
const groups = [];
|
||||
let lastGroupIndex = 0;
|
||||
for (const index in sidebar) {
|
||||
const item = sidebar[index];
|
||||
if (item.items) {
|
||||
lastGroupIndex = groups.push(item);
|
||||
continue;
|
||||
}
|
||||
if (!groups[lastGroupIndex]) {
|
||||
groups.push({ items: [] });
|
||||
}
|
||||
groups[lastGroupIndex].items.push(item);
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
function addBase(items, _base) {
|
||||
return [...items].map((_item) => {
|
||||
const item = { ..._item };
|
||||
const base = item.base || _base;
|
||||
if (base && item.link)
|
||||
item.link = base + item.link;
|
||||
if (item.items)
|
||||
item.items = addBase(item.items, base);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/sidebar.js
|
||||
function useSidebar() {
|
||||
const { frontmatter, page, theme: theme2 } = useData();
|
||||
const is960 = useMediaQuery("(min-width: 960px)");
|
||||
const isOpen = ref(false);
|
||||
const _sidebar = computed(() => {
|
||||
const sidebarConfig = theme2.value.sidebar;
|
||||
const relativePath = page.value.relativePath;
|
||||
return sidebarConfig ? getSidebar(sidebarConfig, relativePath) : [];
|
||||
});
|
||||
const sidebar = ref(_sidebar.value);
|
||||
watch(_sidebar, (next, prev) => {
|
||||
if (JSON.stringify(next) !== JSON.stringify(prev))
|
||||
sidebar.value = _sidebar.value;
|
||||
});
|
||||
const hasSidebar = computed(() => {
|
||||
return frontmatter.value.sidebar !== false && sidebar.value.length > 0 && frontmatter.value.layout !== "home";
|
||||
});
|
||||
const leftAside = computed(() => {
|
||||
if (hasAside)
|
||||
return frontmatter.value.aside == null ? theme2.value.aside === "left" : frontmatter.value.aside === "left";
|
||||
return false;
|
||||
});
|
||||
const hasAside = computed(() => {
|
||||
if (frontmatter.value.layout === "home")
|
||||
return false;
|
||||
if (frontmatter.value.aside != null)
|
||||
return !!frontmatter.value.aside;
|
||||
return theme2.value.aside !== false;
|
||||
});
|
||||
const isSidebarEnabled = computed(() => hasSidebar.value && is960.value);
|
||||
const sidebarGroups = computed(() => {
|
||||
return hasSidebar.value ? getSidebarGroups(sidebar.value) : [];
|
||||
});
|
||||
function open() {
|
||||
isOpen.value = true;
|
||||
}
|
||||
function close() {
|
||||
isOpen.value = false;
|
||||
}
|
||||
function toggle() {
|
||||
isOpen.value ? close() : open();
|
||||
}
|
||||
return {
|
||||
isOpen,
|
||||
sidebar,
|
||||
sidebarGroups,
|
||||
hasSidebar,
|
||||
hasAside,
|
||||
leftAside,
|
||||
isSidebarEnabled,
|
||||
open,
|
||||
close,
|
||||
toggle
|
||||
};
|
||||
}
|
||||
|
||||
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/outline.js
|
||||
var ignoreRE = /\b(?:VPBadge|header-anchor|footnote-ref|ignore-header)\b/;
|
||||
var resolvedHeaders = [];
|
||||
function getHeaders(range) {
|
||||
const headers = [
|
||||
...document.querySelectorAll(".VPDoc :where(h1,h2,h3,h4,h5,h6)")
|
||||
].filter((el) => el.id && el.hasChildNodes()).map((el) => {
|
||||
const level = Number(el.tagName[1]);
|
||||
return {
|
||||
element: el,
|
||||
title: serializeHeader(el),
|
||||
link: "#" + el.id,
|
||||
level
|
||||
};
|
||||
});
|
||||
return resolveHeaders(headers, range);
|
||||
}
|
||||
function serializeHeader(h) {
|
||||
let ret = "";
|
||||
for (const node of h.childNodes) {
|
||||
if (node.nodeType === 1) {
|
||||
if (ignoreRE.test(node.className))
|
||||
continue;
|
||||
ret += node.textContent;
|
||||
} else if (node.nodeType === 3) {
|
||||
ret += node.textContent;
|
||||
}
|
||||
}
|
||||
return ret.trim();
|
||||
}
|
||||
function resolveHeaders(headers, range) {
|
||||
if (range === false) {
|
||||
return [];
|
||||
}
|
||||
const levelsRange = (typeof range === "object" && !Array.isArray(range) ? range.level : range) || 2;
|
||||
const [high, low] = typeof levelsRange === "number" ? [levelsRange, levelsRange] : levelsRange === "deep" ? [2, 6] : levelsRange;
|
||||
return buildTree(headers, high, low);
|
||||
}
|
||||
function buildTree(data, min, max) {
|
||||
resolvedHeaders.length = 0;
|
||||
const result = [];
|
||||
const stack = [];
|
||||
data.forEach((item) => {
|
||||
const node = { ...item, children: [] };
|
||||
let parent = stack[stack.length - 1];
|
||||
while (parent && parent.level >= node.level) {
|
||||
stack.pop();
|
||||
parent = stack[stack.length - 1];
|
||||
}
|
||||
if (node.element.classList.contains("ignore-header") || parent && "shouldIgnore" in parent) {
|
||||
stack.push({ level: node.level, shouldIgnore: true });
|
||||
return;
|
||||
}
|
||||
if (node.level > max || node.level < min)
|
||||
return;
|
||||
resolvedHeaders.push({ element: node.element, link: node.link });
|
||||
if (parent)
|
||||
parent.children.push(node);
|
||||
else
|
||||
result.push(node);
|
||||
stack.push(node);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/local-nav.js
|
||||
function useLocalNav() {
|
||||
const { theme: theme2, frontmatter } = useData();
|
||||
const headers = shallowRef([]);
|
||||
const hasLocalNav = computed(() => {
|
||||
return headers.value.length > 0;
|
||||
});
|
||||
onContentUpdated(() => {
|
||||
headers.value = getHeaders(frontmatter.value.outline ?? theme2.value.outline);
|
||||
});
|
||||
return {
|
||||
headers,
|
||||
hasLocalNav
|
||||
};
|
||||
}
|
||||
|
||||
// node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/without-fonts.js
|
||||
var theme = {
|
||||
Layout,
|
||||
enhanceApp: ({ app }) => {
|
||||
app.component("Badge", VPBadge);
|
||||
}
|
||||
};
|
||||
var without_fonts_default = theme;
|
||||
export {
|
||||
default2 as VPBadge,
|
||||
default3 as VPButton,
|
||||
default4 as VPDocAsideSponsors,
|
||||
default5 as VPFeatures,
|
||||
default6 as VPHomeContent,
|
||||
default7 as VPHomeFeatures,
|
||||
default8 as VPHomeHero,
|
||||
default9 as VPHomeSponsors,
|
||||
default10 as VPImage,
|
||||
default11 as VPLink,
|
||||
default12 as VPNavBarSearch,
|
||||
default13 as VPSocialLink,
|
||||
default14 as VPSocialLinks,
|
||||
default15 as VPSponsors,
|
||||
default16 as VPTeamMembers,
|
||||
default17 as VPTeamPage,
|
||||
default18 as VPTeamPageSection,
|
||||
default19 as VPTeamPageTitle,
|
||||
without_fonts_default as default,
|
||||
useLocalNav,
|
||||
useSidebar
|
||||
};
|
||||
//# sourceMappingURL=@theme_index.js.map
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"version": 3,
|
||||
"sources": ["../../../node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/index.js", "../../../node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/without-fonts.js", "../../../node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/local-nav.js", "../../../node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/outline.js", "../../../node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/support/utils.js", "../../../node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/data.js", "../../../node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/support/sidebar.js", "../../../node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/composables/sidebar.js"],
|
||||
"sourcesContent": ["import './styles/fonts.css';\nexport * from './without-fonts';\nexport { default as default } from './without-fonts';\n", "import './styles/vars.css';\nimport './styles/base.css';\nimport './styles/icons.css';\nimport './styles/utils.css';\nimport './styles/components/custom-block.css';\nimport './styles/components/vp-code.css';\nimport './styles/components/vp-code-group.css';\nimport './styles/components/vp-doc.css';\nimport './styles/components/vp-sponsor.css';\nimport VPBadge from './components/VPBadge.vue';\nimport Layout from './Layout.vue';\nexport { default as VPBadge } from './components/VPBadge.vue';\nexport { default as VPButton } from './components/VPButton.vue';\nexport { default as VPDocAsideSponsors } from './components/VPDocAsideSponsors.vue';\nexport { default as VPFeatures } from './components/VPFeatures.vue';\nexport { default as VPHomeContent } from './components/VPHomeContent.vue';\nexport { default as VPHomeFeatures } from './components/VPHomeFeatures.vue';\nexport { default as VPHomeHero } from './components/VPHomeHero.vue';\nexport { default as VPHomeSponsors } from './components/VPHomeSponsors.vue';\nexport { default as VPImage } from './components/VPImage.vue';\nexport { default as VPLink } from './components/VPLink.vue';\nexport { default as VPNavBarSearch } from './components/VPNavBarSearch.vue';\nexport { default as VPSocialLink } from './components/VPSocialLink.vue';\nexport { default as VPSocialLinks } from './components/VPSocialLinks.vue';\nexport { default as VPSponsors } from './components/VPSponsors.vue';\nexport { default as VPTeamMembers } from './components/VPTeamMembers.vue';\nexport { default as VPTeamPage } from './components/VPTeamPage.vue';\nexport { default as VPTeamPageSection } from './components/VPTeamPageSection.vue';\nexport { default as VPTeamPageTitle } from './components/VPTeamPageTitle.vue';\nexport { useLocalNav } from './composables/local-nav';\nexport { useSidebar } from './composables/sidebar';\nconst theme = {\n Layout,\n enhanceApp: ({ app }) => {\n app.component('Badge', VPBadge);\n }\n};\nexport default theme;\n", "import { onContentUpdated } from 'vitepress';\nimport { computed, shallowRef } from 'vue';\nimport { getHeaders } from '../composables/outline';\nimport { useData } from './data';\nexport function useLocalNav() {\n const { theme, frontmatter } = useData();\n const headers = shallowRef([]);\n const hasLocalNav = computed(() => {\n return headers.value.length > 0;\n });\n onContentUpdated(() => {\n headers.value = getHeaders(frontmatter.value.outline ?? theme.value.outline);\n });\n return {\n headers,\n hasLocalNav\n };\n}\n", "import { getScrollOffset } from 'vitepress';\nimport { onMounted, onUnmounted, onUpdated } from 'vue';\nimport { throttleAndDebounce } from '../support/utils';\nimport { useAside } from './aside';\nconst ignoreRE = /\\b(?:VPBadge|header-anchor|footnote-ref|ignore-header)\\b/;\n// cached list of anchor elements from resolveHeaders\nconst resolvedHeaders = [];\nexport function resolveTitle(theme) {\n return ((typeof theme.outline === 'object' &&\n !Array.isArray(theme.outline) &&\n theme.outline.label) ||\n theme.outlineTitle ||\n 'On this page');\n}\nexport function getHeaders(range) {\n const headers = [\n ...document.querySelectorAll('.VPDoc :where(h1,h2,h3,h4,h5,h6)')\n ]\n .filter((el) => el.id && el.hasChildNodes())\n .map((el) => {\n const level = Number(el.tagName[1]);\n return {\n element: el,\n title: serializeHeader(el),\n link: '#' + el.id,\n level\n };\n });\n return resolveHeaders(headers, range);\n}\nfunction serializeHeader(h) {\n let ret = '';\n for (const node of h.childNodes) {\n if (node.nodeType === 1) {\n if (ignoreRE.test(node.className))\n continue;\n ret += node.textContent;\n }\n else if (node.nodeType === 3) {\n ret += node.textContent;\n }\n }\n return ret.trim();\n}\nexport function resolveHeaders(headers, range) {\n if (range === false) {\n return [];\n }\n const levelsRange = (typeof range === 'object' && !Array.isArray(range)\n ? range.level\n : range) || 2;\n const [high, low] = typeof levelsRange === 'number'\n ? [levelsRange, levelsRange]\n : levelsRange === 'deep'\n ? [2, 6]\n : levelsRange;\n return buildTree(headers, high, low);\n}\nexport function useActiveAnchor(container, marker) {\n const { isAsideEnabled } = useAside();\n const onScroll = throttleAndDebounce(setActiveLink, 100);\n let prevActiveLink = null;\n onMounted(() => {\n requestAnimationFrame(setActiveLink);\n window.addEventListener('scroll', onScroll);\n });\n onUpdated(() => {\n // sidebar update means Line truncated
|
||||
"mappings": "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",
|
||||
"names": ["default", "dir", "theme", "theme"]
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
{
|
||||
"hash": "d07f6dee",
|
||||
"configHash": "dee2d3bc",
|
||||
"lockfileHash": "bd28b2c2",
|
||||
"browserHash": "b96651ac",
|
||||
"optimized": {
|
||||
"vue": {
|
||||
"src": "../../../node_modules/.pnpm/vue@3.5.13/node_modules/vue/dist/vue.runtime.esm-bundler.js",
|
||||
"file": "vue.js",
|
||||
"fileHash": "bc5c7f34",
|
||||
"needsInterop": false
|
||||
},
|
||||
"vitepress > @vue/devtools-api": {
|
||||
"src": "../../../node_modules/.pnpm/@vue+devtools-api@7.7.1/node_modules/@vue/devtools-api/dist/index.js",
|
||||
"file": "vitepress___@vue_devtools-api.js",
|
||||
"fileHash": "00859881",
|
||||
"needsInterop": false
|
||||
},
|
||||
"vitepress > @vueuse/core": {
|
||||
"src": "../../../node_modules/.pnpm/@vueuse+core@12.5.0/node_modules/@vueuse/core/index.mjs",
|
||||
"file": "vitepress___@vueuse_core.js",
|
||||
"fileHash": "1c6da938",
|
||||
"needsInterop": false
|
||||
},
|
||||
"vitepress > @vueuse/integrations/useFocusTrap": {
|
||||
"src": "../../../node_modules/.pnpm/@vueuse+integrations@12.5.0_focus-trap@7.6.4/node_modules/@vueuse/integrations/useFocusTrap.mjs",
|
||||
"file": "vitepress___@vueuse_integrations_useFocusTrap.js",
|
||||
"fileHash": "11c08fcf",
|
||||
"needsInterop": false
|
||||
},
|
||||
"vitepress > mark.js/src/vanilla.js": {
|
||||
"src": "../../../node_modules/.pnpm/mark.js@8.11.1/node_modules/mark.js/src/vanilla.js",
|
||||
"file": "vitepress___mark__js_src_vanilla__js.js",
|
||||
"fileHash": "b93dbfe7",
|
||||
"needsInterop": false
|
||||
},
|
||||
"vitepress > minisearch": {
|
||||
"src": "../../../node_modules/.pnpm/minisearch@7.1.1/node_modules/minisearch/dist/es/index.js",
|
||||
"file": "vitepress___minisearch.js",
|
||||
"fileHash": "bfb6c3ac",
|
||||
"needsInterop": false
|
||||
},
|
||||
"@theme/index": {
|
||||
"src": "../../../node_modules/.pnpm/vitepress@1.6.3_@algolia+client-search@5.20.2_postcss@8.5.2_search-insights@2.17.3/node_modules/vitepress/dist/client/theme-default/index.js",
|
||||
"file": "@theme_index.js",
|
||||
"fileHash": "07512287",
|
||||
"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_FRAGMENT\",\n \"NEED_PATCH\": 512,\n \"512\": \"NEED_PATCH\",\n \"DYNAMIC_SLine truncated
|
||||
"mappings": "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 truncated
|
||||
"names": ["map", "computed", "computed", "self", "hasOwnProperty", "isRef", "readonly", "effect", "isRef", "isRef", "p", "version", "callHook", "remove", "ref", "patchProp", "hydrate", "hasWarned", "resolve", "watch", "render", "computed", "h", "createApp", "effect", "remove2", "track", "trigger", "isModelListener", "emit", "render2", "warn", "warn", "callHook", "resolve", "watch", "isBoolean", "def", "enterCbKey", "compile", "warn"]
|
||||
}
|
||||
@@ -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": "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 truncated
|
||||
"names": ["get", "set", "ref", "keys", "invoke", "toRef", "toRefs", "toValue", "window", "document", "timestamp", "navigator", "events", "getValue", "defaults", "toRef", "set", "onUpdated", "preventDefault", "toRefs", "now", "keys", "get", "isReadonly"]
|
||||
}
|
||||
@@ -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": "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 truncated
|
||||
"names": ["hooks", "hooks", "hook", "hook", "hooks", "clearTimeout", "setTimeout", "__create", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__getProtoOf", "__hasOwnProp", "__esm", "__commonJS", "__copyProps", "__toESM", "init_esm_shims", "init_esm_shims", "init_esm_shims", "_a", "init_esm_shims", "init_esm_shims", "init_esm_shims", "_a2", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "__toESM", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "_a22", "init_esm_shims", "init_esm_shims"]
|
||||
}
|
||||
@@ -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": "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 truncated
|
||||
"names": ["candidateSelectors", "candidateSelector", "join", "NoElement", "Element", "matches", "prototype", "msMatchesSelector", "webkitMatchesSelector", "getRootNode", "element", "_element$getRootNode", "call", "ownerDocument", "isInert", "node", "lookUp", "_node$getAttribute", "inertAtt", "getAttribute", "inert", "result", "parentNode", "isContentEditable", "_node$getAttribute2", "attValue", "getCandidates", "el", "includeContainer", "filter", "candidates", "Array", "slice", "apply", "querySelectorAll", "unshift", "getCandidatesIteratively", "elements", "options", "elementsToCheck", "from", "length", "shift", "tagName", "assigned", "assignedElements", "content", "children", "nestedCandidates", "flatten", "push", "scopeParent", "validCandidate", "includes", "shadowRoot", "getShadowRoot", "validShadowRoot", "shadowRootFilter", "hasTabIndex", "isNaN", "parseInt", "getTabIndex", "Error", "tabIndex", "test", "getSortOrderTabIndex", "isScope", "sortOrderedTabbables", "a", "b", "documentOrder", "isInput", "isHiddenInput", "type", "isDetailsWithSummary", "r", "some", "child", "getCheckedRadio", "nodes", "form", "i", "checked", "isTabbableRadio", "name", "radioScope", "queryRadios", "radioSet", "window", "CSS", "escape", "err", "console", "error", "message", "isRadio", "isNonTabbableRadio", "isNodeAttached", "_nodeRoot", "nodeRoot", "nodeRootHost", "host", "attached", "_nodeRootHost", "_nodeRootHost$ownerDo", "_node$ownerDocument", "contains", "_nodeRoot2", "_nodeRootHost2", "_nodeRootHost2$ownerD", "isZeroArea", "_node$getBoundingClie", "getBoundingClientRect", "width", "height", "isHidden", "_ref", "displayCheck", "getComputedStyle", "visibility", "isDirectSummary", "nodeUnderDetails", "parentElement", "originalNode", "rootNode", "assignedSlot", "getClientRects", "isDisabledFromFieldset", "disabled", "item", "isNodeMatchingSelectorFocusable", "isNodeMatchingSelectorTabbable", "isValidShadowRootTabbable", "shadowHostNode", "sortByOrder", "regularTabbables", "orderedTabbables", "forEach", "candidateTabindex", "sort", "reduce", "acc", "sortable", "concat", "tabbable", "container", "bind", "focusable", "isTabbable", "focusableCandidateSelector", "isFocusable", "activeFocusTraps", "activateTrap", "trapStack", "trap", "length", "activeTrap", "_setPausedState", "trapIndex", "indexOf", "push", "splice", "deactivateTrap", "_isManuallyPaused", "isSelectableInput", "node", "tagName", "toLowerCase", "select", "isEscapeEvent", "e", "key", "keyCode", "isTabEvent", "isKeyForward", "shiftKey", "isKeyBackward", "delay", "fn", "setTimeout", "valueOrHandler", "value", "_len", "arguments", "params", "Array", "_key", "apply", "getActualTarget", "event", "target", "shadowRoot", "composedPath", "internalTrapStack", "createFocusTrap", "elements", "userOptions", "doc", "document", "config", "_objectSpread", "returnFocusOnDeactivate", "escapeDeactivates", "delayInitialFocus", "state", "containers", "containerGroups", "tabbableGroups", "nodeFocusedBeforeActivation", "mostRecentlyFocusedNode", "active", "paused", "manuallyPaused", "delayInitialFocusTimer", "undefined", "recentNavEvent", "getOption", "configOverrideOptions", "optionName", "configOptionName", "findContainerIndex", "element", "findIndex", "_ref", "container", "tabbableNodes", "contains", "includes", "find", "getNodeForOption", "_ref2", "_ref2$hasFallback", "hasFallback", "_ref2$params", "optionValue", "_toConsumableArray", "Error", "concat", "querySelector", "err", "message", "getInitialFocusNode", "isFocusable", "tabbableOptions", "activeElement", "firstTabbableGroup", "firstTabbableNode", "updateTabbableNodes", "map", "tabbable", "focusableNodes", "focusable", "lastTabbableNode", "firstDomTabbableNode", "isTabbable", "lastDomTabbableNode", "slice", "reverse", "posTabIndexesFound", "getTabIndex", "nextTabbableNode", "forward", "nodeIdx", "el", "filter", "group", "g", "getActiveElement", "tryFocus", "focus", "preventScroll", "getReturnFocusNode", "previousActiveElement", "findNextNavNode", "_ref3", "_ref3$isBackward", "isBackward", "destinationNode", "containerIndex", "containerGroup", "startOfGroupIndex", "_ref4", "destinationGroupIndex", "destinationGroup", "lastOfGroupIndex", "_ref5", "checkPointerDown", "clickOutsideDeactivates", "deactivate", "returnFocus", "allowOutsideClick", "preventDefault", "checkFocusIn", "targetContained", "Document", "stopImmediatePropagation", "nextNode", "navAcrossContainers", "mruContainerIdx", "mruTabIdx", "some", "n", "checkKeyNav", "checkTabKey", "checkEscapeKey", "checkClick", "addListeners", "addEventListener", "capture", "passive", "removeListeners", "removeEventListener", "checkDomRemoval", "mutations", "isFocusedNodeRemoved", "mutation", "removedNodes", "from", "mutationObserver", "window", "MutationObserver", "updateObservedNodes", "disconnect", "observe", "subtree", "childList", "activate", "activateOptions", "onActivate", "onPostActivate", "checkCanFocusTrap", "finishActivation", "then", "deactivateOptions", "options", "onDeactiLine truncated
|
||||
}
|
||||