Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
17331112b4 | ||
|
|
94c9c30f98 | ||
|
|
69fc66e926 | ||
|
|
4d7c9deabf | ||
|
|
731b6319d0 | ||
|
|
d178ab04a2 | ||
|
|
7ea1fe2e90 | ||
|
|
13b5306a02 | ||
|
|
799b49b81d | ||
|
|
6eeb1c50a5 | ||
|
|
1ff1d6c695 | ||
|
|
19b289d62b | ||
|
|
46a4fb70e0 | ||
|
|
2d3dcad3ad | ||
|
|
93b005bf5a | ||
|
|
96f68f457c | ||
|
|
94da526e23 | ||
|
|
36fe69e2a7 | ||
|
|
fa85521cfb | ||
|
|
d1f10a33fb | ||
|
|
4f0df03691 | ||
|
|
dbfe98ec4a | ||
|
|
aef7879612 | ||
|
|
6913132074 | ||
|
|
802d2551ff | ||
|
|
78c612c660 | ||
|
|
d35c84cc43 | ||
|
|
0d1aa81d70 | ||
|
|
cbc356ae91 | ||
|
|
ede0e62f32 | ||
|
|
f2f301f515 | ||
|
|
8973abdf2f | ||
|
|
0783f47555 | ||
|
|
037949b715 | ||
|
|
913acff5c5 | ||
|
|
0add20e722 | ||
|
|
964d091d0b | ||
|
|
7ca840cfa1 | ||
|
|
340db7fba3 | ||
|
|
1cb7d2c91c | ||
|
|
0786eb9e44 | ||
|
|
6157f0a8b2 | ||
|
|
191ac220ce | ||
|
|
3145302771 | ||
|
|
541647696d | ||
|
|
e6913960e2 | ||
|
|
828368a9e2 | ||
|
|
0c393a9890 | ||
|
|
8da960b6ca | ||
|
|
c0c1438f11 | ||
|
|
3592db09ab | ||
|
|
63b5be31e8 | ||
|
|
5238975484 | ||
|
|
59f9b119b5 | ||
|
|
651e9c5936 | ||
|
|
ae2d9f0847 | ||
|
|
efbfec2471 | ||
|
|
c40aca30b2 | ||
|
|
9348a7bcea | ||
|
|
7a4fc100c5 | ||
|
|
a884bf19b0 | ||
|
|
bf758ea3f3 | ||
|
|
b72c621dcd | ||
|
|
72ad733355 | ||
|
|
f0aca7da16 | ||
|
|
c93c5b0924 | ||
|
|
799b89dada | ||
|
|
4a48f6d5e3 | ||
|
|
529f314856 | ||
|
|
abe7581803 | ||
|
|
019684787a | ||
|
|
a50753e070 | ||
|
|
f0e7304bb2 | ||
|
|
9ba7d37796 | ||
|
|
3abe660d48 | ||
|
|
2093f19638 | ||
|
|
5ba9eba8eb | ||
|
|
e4aaafb2ad | ||
|
|
7c98046355 | ||
|
|
cc3a521d31 | ||
|
|
fd1eea7779 | ||
|
|
38c78ced14 | ||
|
|
dcd30caf26 | ||
|
|
18cf3f9a48 | ||
|
|
5051184a4d | ||
|
|
2bef407373 | ||
|
|
6c2f2caee0 | ||
|
|
d988d5bc98 | ||
|
|
83598956a1 | ||
|
|
0dca661508 | ||
|
|
3312ed72e6 | ||
|
|
f430243b27 | ||
|
|
a8a230c9f7 | ||
|
|
8d62f6ec33 | ||
|
|
6e910a6a16 | ||
|
|
a36198e1a1 | ||
|
|
fafc56bc32 | ||
|
|
8136c85c2a | ||
|
|
3edc8c959d | ||
|
|
e421ab93bc | ||
|
|
8afae1f567 | ||
|
|
b3004a305a | ||
|
|
af83340bc0 | ||
|
|
13009782b3 | ||
|
|
51b5d5e78f | ||
|
|
9ffad404d1 | ||
|
|
282f44e257 | ||
|
|
7804e36b0d | ||
|
|
cc028a4def | ||
|
|
c993077033 | ||
|
|
322e8a183a | ||
|
|
fe3bc5959f | ||
|
|
8bbdd0a734 | ||
|
|
277b98b7cb | ||
|
|
174ecb3fa2 | ||
|
|
174fb1c3f5 | ||
|
|
eab9f59008 | ||
|
|
454a4ac314 | ||
|
|
7632402b6f | ||
|
|
73f1e5af50 | ||
|
|
57e5084ae1 | ||
|
|
5086f13581 | ||
|
|
8b7327f548 | ||
|
|
2add291366 | ||
|
|
5202a6df2b | ||
|
|
3ca77ac8bf | ||
|
|
271a38fc96 | ||
|
|
eebbb9ae2e | ||
|
|
9ea264df46 | ||
|
|
06d1e4ff78 | ||
|
|
dac9a769c5 | ||
|
|
ea05fe1317 | ||
|
|
40e2335976 | ||
|
|
c13602d634 | ||
|
|
f9cd9c95c3 | ||
|
|
11696d17e8 | ||
|
|
43f0f730d3 | ||
|
|
e08f55a92c | ||
|
|
8eac6ed9fa | ||
|
|
2a3d0a95cc | ||
|
|
a891fbe826 | ||
|
|
bea89f9e19 | ||
|
|
ec905840eb | ||
|
|
c6fe556e76 | ||
|
|
4dfb75204d | ||
|
|
cf737ace93 | ||
|
|
4a58620228 | ||
|
|
b0f7f880d6 | ||
|
|
02e8dc451a | ||
|
|
01486e870f | ||
|
|
0a1ce7e32a | ||
|
|
7c72aba1af | ||
|
|
9a42f3deef | ||
|
|
d5f0b75de6 | ||
|
|
b49356852d | ||
|
|
8215ef9e4b | ||
|
|
f4abf130d2 | ||
|
|
956cea4be9 | ||
|
|
686125e369 | ||
|
|
8d950c5d10 | ||
|
|
fa5aacf980 | ||
|
|
3563b86b82 | ||
|
|
1da94636b9 | ||
|
|
9602ad3a12 | ||
|
|
9a4af6922a | ||
|
|
de129c2af1 | ||
|
|
e1e010ef15 | ||
|
|
4a353051d5 | ||
|
|
db7f26e813 | ||
|
|
e21bee9649 | ||
|
|
651eeb841d | ||
|
|
e309e89379 | ||
|
|
77a0fedcfc | ||
|
|
7b37269dfb | ||
|
|
2b3c5242df | ||
|
|
7998607ac4 | ||
|
|
c6d538b2f4 | ||
|
|
029307acce | ||
|
|
ab1d3e1718 | ||
|
|
f9196adcb3 | ||
|
|
42843a70bc | ||
|
|
7c921d4897 | ||
|
|
22b2a96d83 | ||
|
|
873eac1aa3 | ||
|
|
4e9d859ab0 | ||
|
|
c6e0d3282a | ||
|
|
ec0f4c0829 | ||
|
|
9b9b21a8e4 | ||
|
|
1bca0e007b | ||
|
|
4a27b56c94 | ||
|
|
243380a022 | ||
|
|
3e4c7255a3 | ||
|
|
62025e3d6c | ||
|
|
1eb1a1b954 | ||
|
|
d5659ebc9c | ||
|
|
2417ca9401 | ||
|
|
42c2560cc6 | ||
|
|
979d3113e6 | ||
|
|
d829df08b7 | ||
|
|
d7d2b5ff41 | ||
|
|
ae2c6d8776 | ||
|
|
0f32265043 | ||
|
|
5d08e69b14 | ||
|
|
3b84035715 | ||
|
|
4516e4439a | ||
|
|
5f675dd3c6 | ||
|
|
c64d93f943 | ||
|
|
e0636b9470 | ||
|
|
accb61cbc6 | ||
|
|
f9d1da8c29 | ||
|
|
8059f7c83f | ||
|
|
f6cbec591e |
No files matched your search
@@ -0,0 +1,50 @@
|
||||
# Git
|
||||
.git
|
||||
.gitignore
|
||||
.gitattributes
|
||||
|
||||
# IDE
|
||||
.idea
|
||||
.vscode
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# Documentation
|
||||
*.md
|
||||
docs/
|
||||
LICENSE
|
||||
|
||||
# Development
|
||||
.venv
|
||||
__pycache__
|
||||
*.pyc
|
||||
*.pyo
|
||||
.pytest_cache
|
||||
.coverage
|
||||
htmlcov/
|
||||
|
||||
# macOS
|
||||
.DS_Store
|
||||
._*
|
||||
|
||||
# Frontend source (will be built from GitHub)
|
||||
fcb-fronted/
|
||||
themes/
|
||||
|
||||
# Test files
|
||||
test_*.py
|
||||
tests/
|
||||
|
||||
# Data (should be mounted as volume)
|
||||
data/
|
||||
|
||||
# GitHub
|
||||
.github/
|
||||
|
||||
# Docker
|
||||
Dockerfile
|
||||
docker-compose.yml
|
||||
.dockerignore
|
||||
|
||||
# Claude
|
||||
.claude/
|
||||
@@ -1 +0,0 @@
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Desktop (please complete the following information):**
|
||||
- OS: [e.g. iOS]
|
||||
- Browser [e.g. chrome, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Smartphone (please complete the following information):**
|
||||
- Device: [e.g. iPhone6]
|
||||
- OS: [e.g. iOS8.1]
|
||||
- Browser [e.g. stock browser, safari]
|
||||
- Version [e.g. 22]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
name: Custom issue template
|
||||
about: Describe this issue template's purpose here.
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
|
After Width: | Height: | Size: 571 KiB |
|
After Width: | Height: | Size: 557 KiB |
|
After Width: | Height: | Size: 205 KiB |
|
After Width: | Height: | Size: 679 KiB |
|
After Width: | Height: | Size: 684 KiB |
|
After Width: | Height: | Size: 411 KiB |
|
After Width: | Height: | Size: 431 KiB |
|
After Width: | Height: | Size: 579 KiB |
|
After Width: | Height: | Size: 201 KiB |
|
After Width: | Height: | Size: 254 KiB |
|
After Width: | Height: | Size: 200 KiB |
|
After Width: | Height: | Size: 514 KiB |
|
After Width: | Height: | Size: 674 KiB |
|
After Width: | Height: | Size: 678 KiB |
|
After Width: | Height: | Size: 219 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: 240 KiB |
|
After Width: | Height: | Size: 192 KiB |
|
After Width: | Height: | Size: 233 KiB |
|
After Width: | Height: | Size: 78 KiB |
|
After Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 94 KiB |
|
After Width: | Height: | Size: 78 KiB |
|
After Width: | Height: | Size: 138 KiB |
|
After Width: | Height: | Size: 171 KiB |
@@ -2,50 +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@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
|
||||
- name: Cache Docker layers
|
||||
uses: actions/cache@v3
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
path: /tmp/.buildx-cache
|
||||
key: ${{ runner.os }}-buildx-${{ github.sha }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-buildx-
|
||||
driver-opts: |
|
||||
image=moby/buildkit:latest
|
||||
network=host
|
||||
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@v2
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v4
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ secrets.DOCKER_USERNAME }}/filecodebox:beta
|
||||
cache-from: type=local,src=/tmp/.buildx-cache
|
||||
cache-to: type=local,dest=/tmp/.buildx-cache-new,mode=max
|
||||
|
||||
- name: Move cache
|
||||
run: |
|
||||
rm -rf /tmp/.buildx-cache
|
||||
mv /tmp/.buildx-cache-new /tmp/.buildx-cache
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
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
|
||||
@@ -0,0 +1,69 @@
|
||||
# 构建 VitePress 站点并将其部署到 GitHub Pages 的示例工作流程
|
||||
#
|
||||
name: Deploy VitePress site to Pages
|
||||
|
||||
on:
|
||||
# 在针对 `main` 分支的推送上运行。如果你
|
||||
# 使用 `master` 分支作为默认分支,请将其更改为 `master`
|
||||
push:
|
||||
branches: [ master ]
|
||||
|
||||
# 允许你从 Actions 选项卡手动运行此工作流程
|
||||
workflow_dispatch:
|
||||
|
||||
# 设置 GITHUB_TOKEN 的权限,以允许部署到 GitHub Pages
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
# 只允许同时进行一次部署,跳过正在运行和最新队列之间的运行队列
|
||||
# 但是,不要取消正在进行的运行,因为我们希望允许这些生产部署完成
|
||||
concurrency:
|
||||
group: pages
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
# 构建工作
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # 如果未启用 lastUpdated,则不需要
|
||||
- uses: pnpm/action-setup@v3
|
||||
with:
|
||||
version: 9
|
||||
# - uses: oven-sh/setup-bun@v1 # 如果使用 Bun,请取消注释
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: 'docs/pnpm-lock.yaml'
|
||||
- name: Setup Pages
|
||||
uses: actions/configure-pages@v4
|
||||
- name: Install dependencies
|
||||
working-directory: docs
|
||||
run: pnpm install
|
||||
- name: Build with VitePress
|
||||
working-directory: docs
|
||||
run: pnpm run docs:build
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
with:
|
||||
path: docs/.vitepress/dist
|
||||
|
||||
# 部署工作
|
||||
deploy:
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
name: Deploy
|
||||
steps:
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v4
|
||||
@@ -0,0 +1,57 @@
|
||||
name: Create release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
actions: write
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release-please:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Create or update release
|
||||
id: release
|
||||
uses: googleapis/release-please-action@v4
|
||||
with:
|
||||
config-file: release-please-config.json
|
||||
manifest-file: .release-please-manifest.json
|
||||
|
||||
- name: Merge release pull request
|
||||
if: ${{ steps.release.outputs.prs_created == 'true' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
RELEASE_PR_JSON: ${{ steps.release.outputs.pr }}
|
||||
run: |
|
||||
RELEASE_PR="$(jq -r '.number' <<< "$RELEASE_PR_JSON")"
|
||||
for attempt in {1..120}; do
|
||||
if gh pr merge "$RELEASE_PR" --squash --delete-branch; then
|
||||
break
|
||||
fi
|
||||
if [[ "$attempt" -eq 120 ]]; then
|
||||
echo "Timed out waiting for release PR #$RELEASE_PR to merge" >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep 10
|
||||
done
|
||||
gh workflow run release.yml --ref master
|
||||
|
||||
- name: Publish release image
|
||||
if: ${{ steps.release.outputs.release_created == 'true' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
RELEASE_TAG: ${{ steps.release.outputs.tag_name }}
|
||||
run: gh workflow run docker-image.yml --ref master -f release_tag="$RELEASE_TAG"
|
||||
@@ -154,3 +154,13 @@ for_test.py
|
||||
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,3 @@
|
||||
{
|
||||
".": "2.5.3"
|
||||
}
|
||||
@@ -1,13 +1,87 @@
|
||||
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="vast@tom.com"
|
||||
LABEL version="6"
|
||||
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}"
|
||||
|
||||
|
||||
COPY . /app
|
||||
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
|
||||
RUN echo 'Asia/Shanghai' >/etc/timezone
|
||||
WORKDIR /app
|
||||
RUN pip install -r requirements.txt
|
||||
|
||||
# 复制项目文件(通过 .dockerignore 排除不必要的文件)
|
||||
COPY . .
|
||||
|
||||
# 分支镜像使用带提交号的开发版本;正式镜像使用 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/fronted-2024/dist ./themes/2024
|
||||
COPY --from=frontend-builder /build/fronted-2023/dist ./themes/2023
|
||||
|
||||
# 安装系统安全更新 + Python 依赖
|
||||
# 清理 apt 缓存,降低镜像噪音与扫描面
|
||||
RUN apt-get update \
|
||||
&& apt-get upgrade -y --no-install-recommends \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& pip install --no-cache-dir -r requirements.txt \
|
||||
&& pip cache purge || true \
|
||||
&& groupadd --system --gid 1000 appuser \
|
||||
&& useradd --system --uid 1000 --gid appuser --create-home --home-dir /home/appuser --shell /usr/sbin/nologin appuser \
|
||||
&& mkdir -p /app/data \
|
||||
&& chown -R appuser:appuser /app
|
||||
|
||||
# 非 root 运行,降低容器逃逸后的主机影响面
|
||||
USER appuser
|
||||
|
||||
# 环境变量配置
|
||||
ENV HOST="0.0.0.0" \
|
||||
PORT=12345 \
|
||||
WORKERS=1 \
|
||||
LOG_LEVEL="info" \
|
||||
FORWARDED_ALLOW_IPS=""
|
||||
|
||||
EXPOSE 12345
|
||||
CMD ["python","main.py"]
|
||||
|
||||
# 生产环境启动命令
|
||||
# FORWARDED_ALLOW_IPS 默认为空:仅信任直连 IP,避免任意客户端伪造 X-Forwarded-*。
|
||||
# 若前面有反向代理,请显式设置为代理网段,例如 "10.0.0.0/8,172.16.0.0/12"。
|
||||
CMD ["sh", "-c", "exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-}\""]
|
||||
@@ -0,0 +1,21 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Use this section to tell people about which versions of your project are
|
||||
currently being supported with security updates.
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------ |
|
||||
| 5.1.x | :white_check_mark: |
|
||||
| 5.0.x | :x: |
|
||||
| 4.0.x | :white_check_mark: |
|
||||
| < 4.0 | :x: |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Use this section to tell people how to report a vulnerability.
|
||||
|
||||
Tell them where to go, how often they can expect to get an update on a
|
||||
reported vulnerability, what to expect if the vulnerability is accepted or
|
||||
declined, etc.
|
||||
@@ -0,0 +1,184 @@
|
||||
# @Time : 2023/8/15 17:43
|
||||
# @Author : Lan
|
||||
# @File : depends.py
|
||||
# @Software: PyCharm
|
||||
from fastapi import Header, HTTPException, Depends
|
||||
from fastapi.requests import Request
|
||||
import base64
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
from core.settings import (
|
||||
ADMIN_SESSION_EXPIRE_DEFAULT,
|
||||
ADMIN_SESSION_EXPIRE_MAX,
|
||||
ADMIN_SESSION_EXPIRE_MIN,
|
||||
settings,
|
||||
)
|
||||
from apps.admin.services import FileService, ConfigService, LocalFileService
|
||||
|
||||
|
||||
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, "adminSessionExpire", 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 = hmac.new(
|
||||
_get_jwt_secret(), f"{header}.{payload}".encode(), "sha256"
|
||||
).digest()
|
||||
signature = base64.urlsafe_b64encode(signature).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
|
||||
|
||||
|
||||
def get_admin_session(authorization: str = Header(default=None)) -> dict:
|
||||
token = _extract_bearer_token(authorization)
|
||||
payload = _require_admin_payload(authorization)
|
||||
return {
|
||||
"id": "admin",
|
||||
"username": "admin",
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": payload.get("exp"),
|
||||
}
|
||||
|
||||
|
||||
ADMIN_PUBLIC_ENDPOINTS = {("POST", "/admin/login")}
|
||||
|
||||
|
||||
async def admin_required(
|
||||
authorization: str = Header(default=None), request: Request = None
|
||||
):
|
||||
"""
|
||||
验证管理员权限
|
||||
"""
|
||||
if request and (request.method, request.url.path) in ADMIN_PUBLIC_ENDPOINTS:
|
||||
return None
|
||||
return _require_admin_payload(authorization)
|
||||
|
||||
|
||||
async def share_required_login(authorization: str = Header(default=None)):
|
||||
"""
|
||||
验证分享上传权限
|
||||
|
||||
当settings.openUpload为False时,要求用户必须登录并具有管理员权限
|
||||
当settings.openUpload为True时,允许游客上传
|
||||
|
||||
:param authorization: 认证头信息
|
||||
:param request: 请求对象
|
||||
:return: 验证结果
|
||||
"""
|
||||
if not settings.openUpload:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise HTTPException(
|
||||
status_code=403, detail="本站未开启游客上传,如需上传请先登录后台"
|
||||
)
|
||||
_require_admin_payload(authorization)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
async def get_file_service():
|
||||
return FileService()
|
||||
|
||||
|
||||
async def get_config_service():
|
||||
return ConfigService()
|
||||
|
||||
|
||||
async def get_local_file_service():
|
||||
return LocalFileService()
|
||||
@@ -1,19 +0,0 @@
|
||||
# @Time : 2023/8/15 17:43
|
||||
# @Author : Lan
|
||||
# @File : depends.py
|
||||
# @Software: PyCharm
|
||||
from typing import Union
|
||||
|
||||
from fastapi import Header, HTTPException
|
||||
from fastapi.requests import Request
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
async def admin_required(authorization: Union[str, None] = Header(default=None), request: Request = None):
|
||||
is_admin = authorization == settings.admin_token
|
||||
if request.url.path.startswith('/share/'):
|
||||
if not settings.openUpload and not is_admin:
|
||||
raise HTTPException(status_code=403, detail='本站未开启游客上传,如需上传请先登录后台')
|
||||
else:
|
||||
if not is_admin:
|
||||
raise HTTPException(status_code=401, detail='未授权或授权校验失败')
|
||||
@@ -1,5 +0,0 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class IDData(BaseModel):
|
||||
id: int
|
||||
@@ -0,0 +1,74 @@
|
||||
import datetime
|
||||
from typing import Any, Optional, Union
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class IDData(BaseModel):
|
||||
id: int
|
||||
|
||||
|
||||
class IDsData(BaseModel):
|
||||
ids: list[int]
|
||||
|
||||
|
||||
class ShareItem(BaseModel):
|
||||
expire_value: int
|
||||
expire_style: str = "day"
|
||||
filename: str
|
||||
|
||||
|
||||
class DeleteItem(BaseModel):
|
||||
filename: str
|
||||
|
||||
|
||||
class LoginData(BaseModel):
|
||||
password: str
|
||||
|
||||
|
||||
class UpdateFileData(BaseModel):
|
||||
id: int
|
||||
code: Optional[str] = None
|
||||
prefix: Optional[str] = None
|
||||
suffix: Optional[str] = None
|
||||
expired_at: Optional[Union[datetime.datetime, str]] = None
|
||||
expired_count: Optional[int] = None
|
||||
|
||||
|
||||
class BatchUpdateFileData(BaseModel):
|
||||
ids: list[int]
|
||||
expired_at: Optional[Union[datetime.datetime, str]] = None
|
||||
expired_count: Optional[int] = None
|
||||
clearExpiredAt: Optional[bool] = None
|
||||
clear_expired_at: Optional[bool] = None
|
||||
|
||||
|
||||
class FilePolicyActionData(BaseModel):
|
||||
id: int
|
||||
action: str
|
||||
downloadLimit: Optional[int] = None
|
||||
download_limit: Optional[int] = None
|
||||
|
||||
|
||||
class BatchFilePolicyActionData(BaseModel):
|
||||
ids: list[int]
|
||||
action: str
|
||||
downloadLimit: Optional[int] = None
|
||||
download_limit: Optional[int] = None
|
||||
|
||||
|
||||
class FileMetadataData(BaseModel):
|
||||
id: int
|
||||
note: Optional[str] = None
|
||||
tags: Optional[list[str]] = None
|
||||
|
||||
|
||||
class FileViewPresetData(BaseModel):
|
||||
id: Optional[str] = None
|
||||
name: str
|
||||
filters: Optional[dict[str, Any]] = None
|
||||
params: Optional[dict[str, Any]] = None
|
||||
|
||||
|
||||
class FileViewPresetDeleteData(BaseModel):
|
||||
id: str
|
||||
@@ -2,53 +2,620 @@
|
||||
# @Author : Lan
|
||||
# @File : views.py
|
||||
# @Software: PyCharm
|
||||
import math
|
||||
import datetime
|
||||
from collections import Counter
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from apps.admin.depends import admin_required
|
||||
from apps.admin.pydantics import IDData
|
||||
from apps.base.models import FileCodes
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from apps.admin.services import FileService, ConfigService, LocalFileService
|
||||
from apps.admin.dependencies import (
|
||||
admin_required,
|
||||
get_admin_session,
|
||||
get_file_service,
|
||||
get_config_service,
|
||||
get_local_file_service,
|
||||
)
|
||||
from apps.admin.schemas import (
|
||||
IDData,
|
||||
IDsData,
|
||||
BatchUpdateFileData,
|
||||
BatchFilePolicyActionData,
|
||||
FilePolicyActionData,
|
||||
FileMetadataData,
|
||||
FileViewPresetData,
|
||||
FileViewPresetDeleteData,
|
||||
ShareItem,
|
||||
DeleteItem,
|
||||
LoginData,
|
||||
UpdateFileData,
|
||||
)
|
||||
from core.response import APIResponse
|
||||
from apps.base.models import FileCodes, KeyValue
|
||||
from apps.admin.dependencies import (
|
||||
create_token,
|
||||
get_admin_session_expire_seconds,
|
||||
verify_token,
|
||||
)
|
||||
from core.settings import settings
|
||||
from core.storage import file_storage
|
||||
from core.utils import get_now, verify_password
|
||||
from apps.base.utils import ip_limit
|
||||
|
||||
admin_api = APIRouter(
|
||||
prefix='/admin',
|
||||
tags=['管理'],
|
||||
prefix="/admin", tags=["管理"], dependencies=[Depends(admin_required)]
|
||||
)
|
||||
|
||||
|
||||
@admin_api.post('/login', dependencies=[Depends(admin_required)])
|
||||
async def login():
|
||||
def _pick_query_text(*values: Optional[str]) -> Optional[str]:
|
||||
for value in values:
|
||||
normalized_value = str(value or "").strip()
|
||||
if normalized_value:
|
||||
return normalized_value
|
||||
return None
|
||||
|
||||
|
||||
@admin_api.post("/login")
|
||||
async def login(data: LoginData, ip: str = Depends(ip_limit["login"])):
|
||||
# 登录失败计入 IP 频率限制,超过 loginCount/loginMinute 后暂时锁定
|
||||
if not verify_password(data.password, settings.admin_token):
|
||||
ip_limit["login"].add_ip(ip)
|
||||
raise HTTPException(status_code=401, detail="密码错误")
|
||||
|
||||
expires_in = get_admin_session_expire_seconds()
|
||||
token = create_token({"is_admin": True}, expires_in=expires_in)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"id": "admin",
|
||||
"username": "admin",
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": verify_token(token)["exp"],
|
||||
"expires_in": expires_in,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@admin_api.get("/verify")
|
||||
async def verify_admin(session: dict = Depends(get_admin_session)):
|
||||
return APIResponse(detail=session)
|
||||
|
||||
|
||||
@admin_api.post("/logout")
|
||||
async def logout_admin():
|
||||
return APIResponse(detail={"ok": True})
|
||||
|
||||
|
||||
async def build_dashboard_recent_file(file_code: FileCodes) -> dict:
|
||||
is_expired = await file_code.is_expired()
|
||||
return {
|
||||
"id": file_code.id,
|
||||
"code": file_code.code,
|
||||
"name": file_code.prefix + file_code.suffix,
|
||||
"suffix": file_code.suffix,
|
||||
"size": file_code.size,
|
||||
"text": file_code.text is not None,
|
||||
"expiredAt": file_code.expired_at,
|
||||
"expiredCount": file_code.expired_count,
|
||||
"usedCount": file_code.used_count,
|
||||
"createdAt": file_code.created_at,
|
||||
"isExpired": is_expired,
|
||||
}
|
||||
|
||||
|
||||
@admin_api.get("/dashboard")
|
||||
async def dashboard(file_service: FileService = Depends(get_file_service)):
|
||||
all_codes = await FileCodes.all()
|
||||
all_size = sum([code.size for code in all_codes])
|
||||
sys_start = await KeyValue.filter(key="sys_start").first()
|
||||
now = await get_now()
|
||||
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
yesterday_start = today_start - datetime.timedelta(days=1)
|
||||
yesterday_end = today_start - datetime.timedelta(microseconds=1)
|
||||
yesterday_codes = FileCodes.filter(
|
||||
created_at__gte=yesterday_start, created_at__lte=yesterday_end
|
||||
)
|
||||
today_codes = FileCodes.filter(created_at__gte=today_start)
|
||||
yesterday_file_codes = await yesterday_codes
|
||||
today_file_codes = await today_codes
|
||||
expired_count = 0
|
||||
for file_code in all_codes:
|
||||
if await file_code.is_expired():
|
||||
expired_count += 1
|
||||
health_summary = await file_service.build_file_health_summary(all_codes, now=now)
|
||||
|
||||
text_count = sum(1 for file_code in all_codes if file_code.text is not None)
|
||||
chunked_count = sum(1 for file_code in all_codes if file_code.is_chunked)
|
||||
used_count = sum([file_code.used_count for file_code in all_codes])
|
||||
suffix_counter = Counter(
|
||||
"Text" if file_code.text is not None else (file_code.suffix or "file")
|
||||
for file_code in all_codes
|
||||
)
|
||||
recent_file_codes = sorted(
|
||||
all_codes,
|
||||
key=lambda file_code: file_code.created_at.timestamp()
|
||||
if file_code.created_at
|
||||
else 0,
|
||||
reverse=True,
|
||||
)[:8]
|
||||
recent_activities = await file_service.list_admin_activities(limit=8)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"totalFiles": len(all_codes),
|
||||
"storageUsed": str(all_size),
|
||||
"sysUptime": sys_start.value if sys_start else None,
|
||||
"yesterdayCount": len(yesterday_file_codes),
|
||||
"yesterdaySize": str(sum([code.size for code in yesterday_file_codes])),
|
||||
"todayCount": len(today_file_codes),
|
||||
"todaySize": str(sum([code.size for code in today_file_codes])),
|
||||
"activeCount": len(all_codes) - expired_count,
|
||||
"expiredCount": expired_count,
|
||||
"textCount": text_count,
|
||||
"fileCount": len(all_codes) - text_count,
|
||||
"chunkedCount": chunked_count,
|
||||
"usedCount": used_count,
|
||||
"storageBackend": settings.file_storage,
|
||||
"uploadSizeLimit": settings.uploadSize,
|
||||
"openUpload": settings.openUpload,
|
||||
"enableChunk": settings.enableChunk,
|
||||
"maxSaveSeconds": settings.max_save_seconds,
|
||||
**health_summary,
|
||||
"healthSummary": health_summary,
|
||||
"topSuffixes": [
|
||||
{"suffix": suffix, "count": count}
|
||||
for suffix, count in suffix_counter.most_common(8)
|
||||
],
|
||||
"recentFiles": [
|
||||
await build_dashboard_recent_file(file_code)
|
||||
for file_code in recent_file_codes
|
||||
],
|
||||
"recentActivities": recent_activities["activities"],
|
||||
"recent_activities": recent_activities["activities"],
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@admin_api.get("/activities")
|
||||
async def admin_activities(
|
||||
limit: int = 20,
|
||||
action: Optional[str] = None,
|
||||
targetType: Optional[str] = None,
|
||||
target_type: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
result = await file_service.list_admin_activities(
|
||||
limit=limit,
|
||||
action=action,
|
||||
target_type=_pick_query_text(targetType, target_type),
|
||||
keyword=keyword,
|
||||
)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.delete("/file/delete")
|
||||
async def file_delete(
|
||||
data: IDData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
await file_service.delete_file(data.id)
|
||||
return APIResponse()
|
||||
|
||||
|
||||
@admin_api.delete('/file/delete', dependencies=[Depends(admin_required)])
|
||||
async def file_delete(data: IDData):
|
||||
file_code = await FileCodes.get(id=data.id)
|
||||
await file_storage.delete_file(file_code)
|
||||
await file_code.delete()
|
||||
async def batch_delete_files(
|
||||
data: IDsData,
|
||||
file_service: FileService,
|
||||
):
|
||||
if not data.ids:
|
||||
raise HTTPException(status_code=400, detail="请选择要删除的文件")
|
||||
result = await file_service.delete_files(data.ids)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.delete("/file/batch-delete")
|
||||
async def file_batch_delete(
|
||||
data: IDsData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await batch_delete_files(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/batch-delete")
|
||||
async def file_batch_delete_post(
|
||||
data: IDsData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await batch_delete_files(data, file_service)
|
||||
|
||||
|
||||
async def batch_update_files(
|
||||
data: BatchUpdateFileData,
|
||||
file_service: FileService,
|
||||
):
|
||||
if not data.ids:
|
||||
raise HTTPException(status_code=400, detail="请选择要更新的文件")
|
||||
|
||||
update_data = {}
|
||||
fields_set = data.model_fields_set
|
||||
should_clear_expired_at = bool(data.clearExpiredAt or data.clear_expired_at)
|
||||
|
||||
if should_clear_expired_at:
|
||||
update_data["expired_at"] = None
|
||||
update_data["expired_count"] = -1
|
||||
elif "expired_at" in fields_set and data.expired_at != "":
|
||||
update_data["expired_at"] = data.expired_at
|
||||
|
||||
if (
|
||||
not should_clear_expired_at
|
||||
and "expired_count" in fields_set
|
||||
and data.expired_count is not None
|
||||
):
|
||||
update_data["expired_count"] = data.expired_count
|
||||
|
||||
if not update_data:
|
||||
raise HTTPException(status_code=400, detail="请选择要更新的字段")
|
||||
|
||||
result = await file_service.update_files(data.ids, update_data)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.patch("/file/batch-update")
|
||||
async def file_batch_update(
|
||||
data: BatchUpdateFileData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await batch_update_files(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/batch-update")
|
||||
async def file_batch_update_post(
|
||||
data: BatchUpdateFileData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await batch_update_files(data, file_service)
|
||||
|
||||
|
||||
async def apply_file_policy_action(
|
||||
data: FilePolicyActionData,
|
||||
file_service: FileService,
|
||||
):
|
||||
download_limit = data.downloadLimit
|
||||
if download_limit is None:
|
||||
download_limit = data.download_limit
|
||||
|
||||
detail = await file_service.apply_file_policy_action(
|
||||
file_id=data.id,
|
||||
action=data.action,
|
||||
download_limit=download_limit,
|
||||
)
|
||||
return APIResponse(detail=detail)
|
||||
|
||||
|
||||
@admin_api.patch("/file/policy-action")
|
||||
async def file_policy_action(
|
||||
data: FilePolicyActionData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await apply_file_policy_action(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/policy-action")
|
||||
async def file_policy_action_post(
|
||||
data: FilePolicyActionData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await apply_file_policy_action(data, file_service)
|
||||
|
||||
|
||||
async def apply_batch_file_policy_action(
|
||||
data: BatchFilePolicyActionData,
|
||||
file_service: FileService,
|
||||
):
|
||||
if not data.ids:
|
||||
raise HTTPException(status_code=400, detail="请选择要更新的文件")
|
||||
|
||||
download_limit = data.downloadLimit
|
||||
if download_limit is None:
|
||||
download_limit = data.download_limit
|
||||
|
||||
result = await file_service.apply_files_policy_action(
|
||||
file_ids=data.ids,
|
||||
action=data.action,
|
||||
download_limit=download_limit,
|
||||
)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.patch("/file/batch-policy-action")
|
||||
async def file_batch_policy_action(
|
||||
data: BatchFilePolicyActionData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await apply_batch_file_policy_action(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/batch-policy-action")
|
||||
async def file_batch_policy_action_post(
|
||||
data: BatchFilePolicyActionData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await apply_batch_file_policy_action(data, file_service)
|
||||
|
||||
|
||||
@admin_api.get("/file/list")
|
||||
async def file_list(
|
||||
page: int = 1,
|
||||
size: int = 10,
|
||||
keyword: str = "",
|
||||
status: str = "",
|
||||
type: str = "",
|
||||
health: str = "",
|
||||
sortBy: str = "created_at",
|
||||
sortOrder: str = "desc",
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
page = max(page, 1)
|
||||
size = min(max(size, 1), 100)
|
||||
files, total, summary = await file_service.list_files(
|
||||
page,
|
||||
size,
|
||||
keyword,
|
||||
status=status,
|
||||
file_type=type,
|
||||
health=health,
|
||||
sort_by=sortBy,
|
||||
sort_order=sortOrder,
|
||||
)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"page": page,
|
||||
"size": size,
|
||||
"data": files,
|
||||
"total": total,
|
||||
"summary": summary,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@admin_api.get("/file/detail")
|
||||
async def file_detail(
|
||||
id: int,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
detail = await file_service.get_file_detail(id)
|
||||
return APIResponse(detail=detail)
|
||||
|
||||
|
||||
@admin_api.post("/file/detail")
|
||||
async def file_detail_post(
|
||||
data: IDData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
detail = await file_service.get_file_detail(data.id)
|
||||
return APIResponse(detail=detail)
|
||||
|
||||
|
||||
async def update_file_metadata(
|
||||
data: FileMetadataData,
|
||||
file_service: FileService,
|
||||
):
|
||||
fields_set = data.model_fields_set
|
||||
update_note = "note" in fields_set
|
||||
update_tags = "tags" in fields_set
|
||||
if not update_note and not update_tags:
|
||||
raise HTTPException(status_code=400, detail="请选择要更新的元数据")
|
||||
|
||||
detail = await file_service.update_file_metadata(
|
||||
file_id=data.id,
|
||||
note=data.note,
|
||||
tags=data.tags,
|
||||
update_note=update_note,
|
||||
update_tags=update_tags,
|
||||
)
|
||||
return APIResponse(detail=detail)
|
||||
|
||||
|
||||
@admin_api.patch("/file/metadata")
|
||||
async def file_metadata(
|
||||
data: FileMetadataData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await update_file_metadata(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/metadata")
|
||||
async def file_metadata_post(
|
||||
data: FileMetadataData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await update_file_metadata(data, file_service)
|
||||
|
||||
|
||||
@admin_api.get("/file/view-presets")
|
||||
async def file_view_presets(
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
result = await file_service.list_file_view_presets()
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
async def save_file_view_preset(
|
||||
data: FileViewPresetData,
|
||||
file_service: FileService,
|
||||
):
|
||||
filters = data.filters if data.filters is not None else data.params
|
||||
preset = await file_service.save_file_view_preset(
|
||||
preset_id=data.id,
|
||||
name=data.name,
|
||||
filters=filters or {},
|
||||
)
|
||||
return APIResponse(detail=preset)
|
||||
|
||||
|
||||
@admin_api.post("/file/view-presets")
|
||||
async def file_view_presets_save(
|
||||
data: FileViewPresetData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await save_file_view_preset(data, file_service)
|
||||
|
||||
|
||||
@admin_api.patch("/file/view-presets")
|
||||
async def file_view_presets_patch(
|
||||
data: FileViewPresetData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await save_file_view_preset(data, file_service)
|
||||
|
||||
|
||||
async def delete_file_view_preset(
|
||||
data: FileViewPresetDeleteData,
|
||||
file_service: FileService,
|
||||
):
|
||||
result = await file_service.delete_file_view_preset(data.id)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.delete("/file/view-presets")
|
||||
async def file_view_presets_delete(
|
||||
data: FileViewPresetDeleteData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await delete_file_view_preset(data, file_service)
|
||||
|
||||
|
||||
@admin_api.post("/file/view-presets/delete")
|
||||
async def file_view_presets_delete_post(
|
||||
data: FileViewPresetDeleteData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
return await delete_file_view_preset(data, file_service)
|
||||
|
||||
|
||||
@admin_api.get("/config/get")
|
||||
async def get_config(
|
||||
config_service: ConfigService = Depends(get_config_service),
|
||||
):
|
||||
return APIResponse(detail=config_service.get_config())
|
||||
|
||||
|
||||
@admin_api.patch("/config/update")
|
||||
async def update_config(
|
||||
data: dict,
|
||||
config_service: ConfigService = Depends(get_config_service),
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
data.pop("themesChoices", None)
|
||||
await config_service.update_config(data)
|
||||
await file_service.record_admin_activity(
|
||||
action="config.update",
|
||||
target_type="config",
|
||||
target_name="system",
|
||||
count=1,
|
||||
meta={"fields": sorted(data.keys())},
|
||||
)
|
||||
return APIResponse()
|
||||
|
||||
|
||||
@admin_api.get('/file/list', dependencies=[Depends(admin_required)])
|
||||
async def file_list(page: float = 1, size: int = 10):
|
||||
return APIResponse(detail={
|
||||
'page': page,
|
||||
'size': size,
|
||||
'data': await FileCodes.all().limit(size).offset((math.ceil(page) - 1) * size),
|
||||
'total': await FileCodes.all().count(),
|
||||
})
|
||||
@admin_api.get("/file/download")
|
||||
async def file_download(
|
||||
id: int,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
file_content = await file_service.download_file(id)
|
||||
return file_content
|
||||
|
||||
|
||||
@admin_api.get('/config/get', dependencies=[Depends(admin_required)])
|
||||
async def get_config():
|
||||
return APIResponse(detail=settings.__dict__)
|
||||
@admin_api.get("/file/preview")
|
||||
async def file_preview(
|
||||
id: int,
|
||||
maxChars: int = 4000,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
preview = await file_service.preview_file(id, maxChars)
|
||||
return APIResponse(detail=preview)
|
||||
|
||||
|
||||
@admin_api.patch('/config/update', dependencies=[Depends(admin_required)])
|
||||
async def update_config(data: dict):
|
||||
for k, v in data.items():
|
||||
settings.__setattr__(k, v)
|
||||
return APIResponse()
|
||||
@admin_api.get("/local/lists")
|
||||
async def get_local_lists(
|
||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||
):
|
||||
files = await local_file_service.list_files()
|
||||
return APIResponse(detail=files)
|
||||
|
||||
|
||||
@admin_api.delete("/local/delete")
|
||||
async def delete_local_file(
|
||||
item: DeleteItem,
|
||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
result = await local_file_service.delete_file(item.filename)
|
||||
await file_service.record_admin_activity(
|
||||
action="local_file.delete",
|
||||
target_type="local_file",
|
||||
target_name=item.filename,
|
||||
count=1,
|
||||
meta={"success": bool(result)},
|
||||
)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.post("/local/share")
|
||||
async def share_local_file(
|
||||
item: ShareItem,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
share_info = await file_service.share_local_file(item)
|
||||
await file_service.record_admin_activity(
|
||||
action="local_file.share",
|
||||
target_type="file",
|
||||
target_id=share_info.get("id") if isinstance(share_info, dict) else None,
|
||||
target_name=item.filename,
|
||||
count=1,
|
||||
meta={
|
||||
"expireValue": item.expire_value,
|
||||
"expireStyle": item.expire_style,
|
||||
},
|
||||
)
|
||||
return APIResponse(detail=share_info)
|
||||
|
||||
|
||||
@admin_api.patch("/file/update")
|
||||
async def update_file(
|
||||
data: UpdateFileData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
):
|
||||
file_code = await FileCodes.filter(id=data.id).first()
|
||||
if not file_code:
|
||||
raise HTTPException(status_code=404, detail="文件不存在")
|
||||
target_name = file_service._build_file_activity_name(file_code)
|
||||
update_data = {}
|
||||
|
||||
if data.code is not None and data.code != file_code.code:
|
||||
# 判断code是否存在
|
||||
if await FileCodes.filter(code=data.code).first():
|
||||
raise HTTPException(status_code=400, detail="code已存在")
|
||||
update_data["code"] = data.code
|
||||
if data.prefix is not None and data.prefix != file_code.prefix:
|
||||
update_data["prefix"] = data.prefix
|
||||
if data.suffix is not None and data.suffix != file_code.suffix:
|
||||
update_data["suffix"] = data.suffix
|
||||
if (
|
||||
data.expired_at is not None
|
||||
and data.expired_at != ""
|
||||
and data.expired_at != file_code.expired_at
|
||||
):
|
||||
update_data["expired_at"] = data.expired_at
|
||||
if data.expired_count is not None and data.expired_count != file_code.expired_count:
|
||||
update_data["expired_count"] = data.expired_count
|
||||
|
||||
await file_code.update_from_dict(update_data).save()
|
||||
if update_data:
|
||||
await file_service.record_admin_activity(
|
||||
action="file.update",
|
||||
target_type="file",
|
||||
target_id=data.id,
|
||||
target_name=target_name,
|
||||
count=1,
|
||||
meta={"fields": sorted(update_data.keys())},
|
||||
)
|
||||
return APIResponse(detail="更新成功")
|
||||
@@ -0,0 +1,103 @@
|
||||
from ipaddress import ip_address, ip_network
|
||||
from typing import Dict, Iterable, Union
|
||||
from datetime import datetime, timedelta
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
def _iter_trusted_proxies() -> Iterable[str]:
|
||||
trusted_proxies = getattr(settings, "trustedProxies", [])
|
||||
if isinstance(trusted_proxies, str):
|
||||
trusted_proxies = [item.strip() for item in trusted_proxies.split(",")]
|
||||
return [item for item in trusted_proxies if item]
|
||||
|
||||
|
||||
def _is_trusted_proxy(host: str) -> bool:
|
||||
try:
|
||||
remote_addr = ip_address(host)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
for proxy in _iter_trusted_proxies():
|
||||
try:
|
||||
if remote_addr in ip_network(proxy, strict=False):
|
||||
return True
|
||||
except ValueError:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
def _get_forwarded_for_ip(header_value: str, fallback_ip: str) -> str:
|
||||
forwarded_chain = [
|
||||
item.strip() for item in header_value.split(",") if item.strip()
|
||||
]
|
||||
if not forwarded_chain:
|
||||
return fallback_ip
|
||||
|
||||
for candidate in reversed(forwarded_chain):
|
||||
try:
|
||||
ip_address(candidate)
|
||||
except ValueError:
|
||||
return fallback_ip
|
||||
if not _is_trusted_proxy(candidate):
|
||||
return candidate
|
||||
return forwarded_chain[0]
|
||||
|
||||
|
||||
def get_client_ip(request: Request) -> str:
|
||||
client_host = request.client.host if request.client else "unknown"
|
||||
if not _is_trusted_proxy(client_host):
|
||||
return client_host
|
||||
|
||||
forwarded_for = request.headers.get("X-Forwarded-For")
|
||||
if forwarded_for:
|
||||
return _get_forwarded_for_ip(forwarded_for, client_host)
|
||||
|
||||
real_ip = request.headers.get("X-Real-IP")
|
||||
if real_ip:
|
||||
try:
|
||||
ip_address(real_ip)
|
||||
except ValueError:
|
||||
return client_host
|
||||
return real_ip
|
||||
|
||||
return client_host
|
||||
|
||||
|
||||
class IPRateLimit:
|
||||
def __init__(self, count: int, minutes: int):
|
||||
self.ips: Dict[str, Dict[str, Union[int, datetime]]] = {}
|
||||
self.count = count
|
||||
self.minutes = minutes
|
||||
|
||||
def check_ip(self, ip: str) -> bool:
|
||||
if ip in self.ips:
|
||||
ip_info = self.ips[ip]
|
||||
if ip_info["count"] >= self.count:
|
||||
if ip_info["time"] + timedelta(minutes=self.minutes) > datetime.now():
|
||||
return False
|
||||
self.ips.pop(ip)
|
||||
return True
|
||||
|
||||
def add_ip(self, ip: str) -> int:
|
||||
ip_info = self.ips.get(ip, {"count": 0, "time": datetime.now()})
|
||||
ip_info["count"] += 1
|
||||
ip_info["time"] = datetime.now()
|
||||
self.ips[ip] = ip_info
|
||||
return ip_info["count"]
|
||||
|
||||
async def remove_expired_ip(self) -> None:
|
||||
now = datetime.now()
|
||||
expiration = timedelta(minutes=self.minutes)
|
||||
self.ips = {
|
||||
ip: info
|
||||
for ip, info in self.ips.items()
|
||||
if info["time"] + expiration >= now
|
||||
}
|
||||
|
||||
def __call__(self, request: Request) -> str:
|
||||
ip = get_client_ip(request)
|
||||
if not self.check_ip(ip):
|
||||
raise HTTPException(status_code=423, detail="请求次数过多,请稍后再试")
|
||||
return ip
|
||||
@@ -1,45 +0,0 @@
|
||||
# @Time : 2023/8/14 12:20
|
||||
# @Author : Lan
|
||||
# @File : depends.py
|
||||
# @Software: PyCharm
|
||||
from typing import Union
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from fastapi import Header, HTTPException, Request
|
||||
|
||||
from core.response import APIResponse
|
||||
|
||||
|
||||
class IPRateLimit:
|
||||
def __init__(self, count, minutes):
|
||||
self.ips = {}
|
||||
self.count = count
|
||||
self.minutes = minutes
|
||||
|
||||
def check_ip(self, ip):
|
||||
# 检查ip是否被禁止
|
||||
if ip in self.ips:
|
||||
if self.ips[ip]['count'] >= self.count:
|
||||
if self.ips[ip]['time'] + timedelta(minutes=self.minutes) > datetime.now():
|
||||
return False
|
||||
else:
|
||||
self.ips.pop(ip)
|
||||
return True
|
||||
|
||||
def add_ip(self, ip):
|
||||
ip_info = self.ips.get(ip, {'count': 0, 'time': datetime.now()})
|
||||
ip_info['count'] += 1
|
||||
ip_info['time'] = datetime.now()
|
||||
self.ips[ip] = ip_info
|
||||
return ip_info['count']
|
||||
|
||||
async def remove_expired_ip(self):
|
||||
for ip in list(self.ips.keys()):
|
||||
if self.ips[ip]['time'] + timedelta(minutes=self.minutes) < datetime.now():
|
||||
self.ips.pop(ip)
|
||||
|
||||
def __call__(self, request: Request):
|
||||
ip = request.headers.get('X-Real-IP', request.headers.get('X-Forwarded-For', request.client.host))
|
||||
if not self.check_ip(ip):
|
||||
raise HTTPException(status_code=423, detail=f"请求次数过多,请稍后再试")
|
||||
return ip
|
||||
@@ -0,0 +1,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,52 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
async def create_file_codes_table():
|
||||
conn = connections.get("default")
|
||||
await conn.execute_script(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS filecodes
|
||||
(
|
||||
id INTEGER not null
|
||||
primary key autoincrement,
|
||||
code VARCHAR(255) not null
|
||||
unique,
|
||||
prefix VARCHAR(255) default '' not null,
|
||||
suffix VARCHAR(255) default '' not null,
|
||||
uuid_file_name VARCHAR(255),
|
||||
file_path VARCHAR(255),
|
||||
size INT default 0 not null,
|
||||
text TEXT,
|
||||
expired_at TIMESTAMP,
|
||||
expired_count INT default 0 not null,
|
||||
used_count INT default 0 not null,
|
||||
created_at TIMESTAMP default CURRENT_TIMESTAMP not null
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_filecodes_code_1c7ee7
|
||||
on filecodes (code);
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
async def create_key_value_table():
|
||||
conn = connections.get("default")
|
||||
await conn.execute_script(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS keyvalue
|
||||
(
|
||||
id INTEGER not null
|
||||
primary key autoincrement,
|
||||
key VARCHAR(255) not null
|
||||
unique,
|
||||
value JSON,
|
||||
created_at TIMESTAMP default CURRENT_TIMESTAMP not null
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_keyvalue_key_eab890
|
||||
on keyvalue (key);
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
async def migrate():
|
||||
await create_file_codes_table()
|
||||
await create_key_value_table()
|
||||
@@ -0,0 +1,28 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
async def create_upload_chunk_and_update_file_codes_table():
|
||||
conn = connections.get("default")
|
||||
await conn.execute_script(
|
||||
"""
|
||||
ALTER TABLE "filecodes" ADD "file_hash" VARCHAR(128);
|
||||
ALTER TABLE "filecodes" ADD "is_chunked" BOOL NOT NULL DEFAULT False;
|
||||
ALTER TABLE "filecodes" ADD "upload_id" VARCHAR(128);
|
||||
CREATE TABLE "uploadchunk" (
|
||||
id INTEGER not null primary key autoincrement,
|
||||
"upload_id" VARCHAR(36) NOT NULL,
|
||||
"chunk_index" INT NOT NULL,
|
||||
"chunk_hash" VARCHAR(128) NOT NULL,
|
||||
"total_chunks" INT NOT NULL,
|
||||
"file_size" BIGINT NOT NULL,
|
||||
"chunk_size" INT NOT NULL,
|
||||
"created_at" TIMESTAMPTZ NOT NULL,
|
||||
"file_name" VARCHAR(255) NOT NULL,
|
||||
"completed" BOOL NOT NULL
|
||||
);
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
async def migrate():
|
||||
await create_upload_chunk_and_update_file_codes_table()
|
||||
@@ -0,0 +1,26 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
async def create_presign_upload_session_table():
|
||||
conn = connections.get("default")
|
||||
await conn.execute_script(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS presignuploadsession (
|
||||
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
upload_id VARCHAR(36) NOT NULL UNIQUE,
|
||||
file_name VARCHAR(255) NOT NULL,
|
||||
file_size BIGINT NOT NULL,
|
||||
save_path VARCHAR(512) NOT NULL,
|
||||
mode VARCHAR(10) NOT NULL,
|
||||
expire_value INT NOT NULL DEFAULT 1,
|
||||
expire_style VARCHAR(20) NOT NULL DEFAULT 'day',
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at TIMESTAMP NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_presignuploadsession_upload_id ON presignuploadsession (upload_id);
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
async def migrate():
|
||||
await create_presign_upload_session_table()
|
||||
@@ -0,0 +1,14 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
async def add_save_path_to_uploadchunk():
|
||||
conn = connections.get("default")
|
||||
await conn.execute_script(
|
||||
"""
|
||||
ALTER TABLE uploadchunk ADD COLUMN save_path VARCHAR(512) NULL;
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
async def migrate():
|
||||
await add_save_path_to_uploadchunk()
|
||||
@@ -0,0 +1,72 @@
|
||||
from tortoise import connections
|
||||
|
||||
|
||||
def _need_upgrade(columns: list[tuple]) -> bool:
|
||||
for column in columns:
|
||||
# PRAGMA table_info 返回 (cid, name, type, notnull, dflt_value, pk)
|
||||
if column[1] == "size":
|
||||
column_type = (column[2] or "").upper()
|
||||
return "BIGINT" not in column_type
|
||||
return False
|
||||
|
||||
|
||||
async def migrate():
|
||||
conn = connections.get("default")
|
||||
result = await conn.execute_query("PRAGMA table_info(filecodes)")
|
||||
columns = result[1] if result and len(result) > 1 else []
|
||||
|
||||
if not columns or not _need_upgrade(columns):
|
||||
return
|
||||
|
||||
await conn.execute_script(
|
||||
"""
|
||||
BEGIN;
|
||||
CREATE TABLE IF NOT EXISTS filecodes_new
|
||||
(
|
||||
id INTEGER not null
|
||||
primary key autoincrement,
|
||||
code VARCHAR(255) not null
|
||||
unique,
|
||||
prefix VARCHAR(255) default '' not null,
|
||||
suffix VARCHAR(255) default '' not null,
|
||||
uuid_file_name VARCHAR(255),
|
||||
file_path VARCHAR(255),
|
||||
size BIGINT default 0 not null,
|
||||
text TEXT,
|
||||
expired_at TIMESTAMP,
|
||||
expired_count INT default 0 not null,
|
||||
used_count INT default 0 not null,
|
||||
created_at TIMESTAMP default CURRENT_TIMESTAMP not null,
|
||||
file_hash VARCHAR(128),
|
||||
is_chunked BOOL default False not null,
|
||||
upload_id VARCHAR(128)
|
||||
);
|
||||
|
||||
INSERT INTO filecodes_new (id, code, prefix, suffix, uuid_file_name, file_path, size, text,
|
||||
expired_at, expired_count, used_count, created_at, file_hash,
|
||||
is_chunked, upload_id)
|
||||
SELECT id,
|
||||
code,
|
||||
prefix,
|
||||
suffix,
|
||||
uuid_file_name,
|
||||
file_path,
|
||||
size,
|
||||
text,
|
||||
expired_at,
|
||||
expired_count,
|
||||
used_count,
|
||||
created_at,
|
||||
file_hash,
|
||||
is_chunked,
|
||||
upload_id
|
||||
FROM filecodes;
|
||||
|
||||
DROP TABLE filecodes;
|
||||
ALTER TABLE filecodes_new
|
||||
RENAME TO filecodes;
|
||||
CREATE INDEX IF NOT EXISTS idx_filecodes_code_1c7ee7
|
||||
on filecodes (code);
|
||||
COMMIT;
|
||||
"""
|
||||
)
|
||||
@@ -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);
|
||||
"""
|
||||
)
|
||||
@@ -2,39 +2,100 @@
|
||||
# @Author : Lan
|
||||
# @File : models.py
|
||||
# @Software: PyCharm
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from tortoise import fields
|
||||
from tortoise.models import Model
|
||||
from tortoise.contrib.pydantic import pydantic_model_creator
|
||||
|
||||
from tortoise import fields, models
|
||||
from datetime import datetime
|
||||
from core.utils import get_now
|
||||
|
||||
|
||||
class FileCodes(Model):
|
||||
id: Optional[int] = fields.IntField(pk=True)
|
||||
code: Optional[int] = fields.CharField(description='分享码', max_length=255, index=True, unique=True)
|
||||
prefix: Optional[str] = fields.CharField(max_length=255, description='前缀', default='')
|
||||
suffix: Optional[str] = fields.CharField(max_length=255, description='后缀', default='')
|
||||
uuid_file_name: Optional[str] = fields.CharField(max_length=255, description='uuid文件名', null=True)
|
||||
file_path: Optional[str] = fields.CharField(max_length=255, description='文件路径', null=True)
|
||||
size: Optional[int] = fields.IntField(description='文件大小', default=0)
|
||||
text: Optional[str] = fields.TextField(description='文本内容', null=True)
|
||||
expired_at: Optional[datetime] = fields.DatetimeField(null=True, description='过期时间')
|
||||
expired_count: Optional[int] = fields.IntField(description='可用次数', default=0)
|
||||
used_count: Optional[int] = fields.IntField(description='已用次数', default=0)
|
||||
|
||||
created_at: Optional[datetime] = fields.DatetimeField(auto_now_add=True, description='创建时间')
|
||||
class FileCodes(models.Model):
|
||||
id = fields.IntField(pk=True)
|
||||
code = fields.CharField(max_length=255, unique=True, index=True)
|
||||
prefix = fields.CharField(max_length=255, default="")
|
||||
suffix = fields.CharField(max_length=255, default="")
|
||||
uuid_file_name = fields.CharField(max_length=255, null=True)
|
||||
file_path = fields.CharField(max_length=255, null=True)
|
||||
size = fields.BigIntField(default=0)
|
||||
text = fields.TextField(null=True)
|
||||
expired_at = fields.DatetimeField(null=True)
|
||||
expired_count = fields.IntField(default=0)
|
||||
used_count = fields.IntField(default=0)
|
||||
created_at = fields.DatetimeField(auto_now_add=True)
|
||||
file_hash = fields.CharField(max_length=64, null=True)
|
||||
is_chunked = fields.BooleanField(default=False)
|
||||
upload_id = fields.CharField(max_length=36, null=True)
|
||||
|
||||
async def is_expired(self):
|
||||
if self.expired_at and (self.expired_count == -1 or self.expired_count > 0):
|
||||
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 != -1 and self.expired_count == 0
|
||||
return self.expired_count <= 0
|
||||
|
||||
async def get_file_path(self):
|
||||
return f"{self.file_path}/{self.uuid_file_name}"
|
||||
|
||||
|
||||
file_codes_pydantic = pydantic_model_creator(FileCodes, name='FileCodes')
|
||||
class UploadChunk(models.Model):
|
||||
id = fields.IntField(pk=True)
|
||||
upload_id = fields.CharField(max_length=36, index=True)
|
||||
chunk_index = fields.IntField()
|
||||
chunk_hash = fields.CharField(max_length=64)
|
||||
total_chunks = fields.IntField()
|
||||
file_size = fields.BigIntField()
|
||||
chunk_size = fields.IntField()
|
||||
file_name = fields.CharField(max_length=255)
|
||||
save_path = fields.CharField(max_length=512, null=True)
|
||||
created_at = fields.DatetimeField(auto_now_add=True)
|
||||
completed = fields.BooleanField(default=False)
|
||||
|
||||
|
||||
class KeyValue(Model):
|
||||
id: Optional[int] = fields.IntField(pk=True)
|
||||
key: Optional[str] = fields.CharField(
|
||||
max_length=255, description="键", index=True, unique=True
|
||||
)
|
||||
value: Optional[str] = fields.JSONField(description="值", null=True)
|
||||
created_at: Optional[datetime] = fields.DatetimeField(
|
||||
auto_now_add=True, description="创建时间"
|
||||
)
|
||||
|
||||
|
||||
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"
|
||||
)
|
||||
@@ -1,5 +0,0 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class SelectFileModel(BaseModel):
|
||||
code: str
|
||||
@@ -0,0 +1,119 @@
|
||||
import datetime
|
||||
|
||||
from fastapi import HTTPException
|
||||
from tortoise import connections
|
||||
|
||||
from apps.base.models import FileCodes, StorageReservation
|
||||
from core.settings import settings
|
||||
from core.utils import get_now
|
||||
|
||||
|
||||
def _detect_sql_dialect() -> str:
|
||||
"""识别当前默认连接的 SQL 方言。
|
||||
|
||||
优先使用 Tortoise capabilities.dialect;
|
||||
回退到 db_config 中的 engine 路径字符串。
|
||||
"""
|
||||
conn = connections.get("default")
|
||||
dialect = getattr(getattr(conn, "capabilities", None), "dialect", "") or ""
|
||||
if dialect:
|
||||
return dialect.lower()
|
||||
|
||||
try:
|
||||
engine = str(connections.db_config.get("default", {}).get("engine", "")).lower()
|
||||
except Exception:
|
||||
engine = ""
|
||||
if "postgres" in engine or "asyncpg" in engine or "psycopg" in engine:
|
||||
return "postgres"
|
||||
if "mysql" in engine:
|
||||
return "mysql"
|
||||
if "sqlite" in engine:
|
||||
return "sqlite"
|
||||
return "sqlite"
|
||||
|
||||
|
||||
def _sql_placeholders(count: int) -> list[str]:
|
||||
"""根据数据库方言生成参数占位符(多数据库兼容)。
|
||||
|
||||
SQLite 用 ?,PostgreSQL 用 $1/$2/...,MySQL 用 %s。
|
||||
"""
|
||||
dialect = _detect_sql_dialect()
|
||||
if dialect in {"postgres", "postgresql"}:
|
||||
return [f"${i}" for i in range(1, count + 1)]
|
||||
if dialect == "mysql":
|
||||
return ["%s"] * count
|
||||
return ["?"] * count
|
||||
|
||||
|
||||
def get_storage_limit() -> int:
|
||||
try:
|
||||
return max(0, int(getattr(settings, "storageLimit", 0)))
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
async def get_storage_usage() -> dict[str, int | None]:
|
||||
now = await get_now()
|
||||
used = await FileCodes.all().values_list("size", flat=True)
|
||||
reserved = await StorageReservation.filter(expires_at__gt=now).values_list(
|
||||
"size", flat=True
|
||||
)
|
||||
limit = get_storage_limit()
|
||||
used_bytes = sum(used)
|
||||
reserved_bytes = sum(reserved)
|
||||
return {
|
||||
"limit": limit,
|
||||
"used": used_bytes,
|
||||
"reserved": reserved_bytes,
|
||||
"available": max(0, limit - used_bytes - reserved_bytes) if limit else None,
|
||||
}
|
||||
|
||||
|
||||
async def reserve_storage(token: str, size: int, ttl_seconds: int) -> None:
|
||||
requested_size = max(0, int(size))
|
||||
limit = get_storage_limit()
|
||||
if not limit or requested_size == 0:
|
||||
return
|
||||
|
||||
now = await get_now()
|
||||
expires_at = now + datetime.timedelta(seconds=ttl_seconds)
|
||||
conn = connections.get("default")
|
||||
await StorageReservation.filter(token=token, expires_at__lte=now).delete()
|
||||
existing = await StorageReservation.filter(token=token, expires_at__gt=now).first()
|
||||
if existing:
|
||||
if existing.size == requested_size:
|
||||
return
|
||||
raise HTTPException(status_code=409, detail="上传容量预留信息不一致")
|
||||
|
||||
try:
|
||||
ph = _sql_placeholders(6)
|
||||
affected, _ = await conn.execute_query(
|
||||
f"""
|
||||
INSERT INTO storagereservation (token, size, expires_at)
|
||||
SELECT {ph[0]}, {ph[1]}, {ph[2]}
|
||||
WHERE (
|
||||
COALESCE((SELECT SUM(size) FROM filecodes), 0)
|
||||
+ COALESCE((SELECT SUM(size) FROM storagereservation WHERE expires_at > {ph[3]}), 0)
|
||||
+ {ph[4]}
|
||||
) <= {ph[5]}
|
||||
""",
|
||||
[token, requested_size, expires_at, now, requested_size, limit],
|
||||
)
|
||||
except Exception:
|
||||
concurrent = await StorageReservation.filter(
|
||||
token=token, size=requested_size, expires_at__gt=now
|
||||
).exists()
|
||||
if concurrent:
|
||||
return
|
||||
raise
|
||||
if affected != 1:
|
||||
concurrent = await StorageReservation.filter(
|
||||
token=token, size=requested_size, expires_at__gt=now
|
||||
).exists()
|
||||
if concurrent:
|
||||
return
|
||||
raise HTTPException(status_code=507, detail="存储空间已达到管理员设置的容量上限")
|
||||
|
||||
|
||||
async def release_storage(token: str) -> None:
|
||||
await StorageReservation.filter(token=token).delete()
|
||||
@@ -0,0 +1,36 @@
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class SelectFileModel(BaseModel):
|
||||
code: str
|
||||
|
||||
|
||||
class InitChunkUploadModel(BaseModel):
|
||||
file_name: str
|
||||
chunk_size: int = 5 * 1024 * 1024
|
||||
file_size: int
|
||||
file_hash: str
|
||||
|
||||
|
||||
class CompleteUploadModel(BaseModel):
|
||||
expire_value: int
|
||||
expire_style: str
|
||||
|
||||
|
||||
# 预签名上传相关模型
|
||||
class PresignUploadInitRequest(BaseModel):
|
||||
"""预签名上传初始化请求"""
|
||||
file_name: str
|
||||
file_size: int
|
||||
expire_value: int = 1
|
||||
expire_style: str = "day"
|
||||
|
||||
|
||||
class PresignUploadInitResponse(BaseModel):
|
||||
"""预签名上传初始化响应"""
|
||||
upload_id: str
|
||||
upload_url: str
|
||||
mode: str # "direct" 或 "proxy"
|
||||
save_path: str
|
||||
expires_in: int # URL过期时间(秒)
|
||||
@@ -1,79 +1,140 @@
|
||||
# @Time : 2023/8/14 01:10
|
||||
# @Author : Lan
|
||||
# @File : utils.py
|
||||
# @Software: PyCharm
|
||||
import datetime
|
||||
import uuid
|
||||
import hashlib
|
||||
import os
|
||||
from fastapi import UploadFile
|
||||
import uuid
|
||||
from urllib.parse import unquote
|
||||
|
||||
from apps.base.depends import IPRateLimit
|
||||
from fastapi import UploadFile, HTTPException
|
||||
from typing import Optional, Tuple
|
||||
|
||||
from apps.base.dependencies import IPRateLimit
|
||||
from apps.base.models import FileCodes
|
||||
from core.settings import settings
|
||||
from core.utils import get_random_num, get_random_string
|
||||
from core.utils import (
|
||||
get_random_num,
|
||||
get_random_string,
|
||||
max_save_times_desc,
|
||||
sanitize_filename,
|
||||
get_now,
|
||||
)
|
||||
|
||||
|
||||
async def get_file_path_name(file: UploadFile):
|
||||
"""
|
||||
获取文件路径和文件名
|
||||
:param file:
|
||||
:return: {
|
||||
'path': 'share/data/2021/08/13',
|
||||
'suffix': '.jpg',
|
||||
'prefix': 'test',
|
||||
'file_uuid': '44a83bbd70e04c8aa7fd93bfd8c88249',
|
||||
'uuid_file_name': '44a83bbd70e04c8aa7fd93bfd8c88249.jpg',
|
||||
'save_path': 'share/data/2021/08/13/44a83bbd70e04c8aa7fd93bfd8c88249.jpg'
|
||||
def validate_expire_style(expire_style: str) -> str:
|
||||
"""校验过期方式是否在管理员配置的白名单内。"""
|
||||
if expire_style not in settings.expireStyle:
|
||||
raise HTTPException(status_code=400, detail="过期时间类型错误")
|
||||
return expire_style
|
||||
|
||||
|
||||
async def get_file_path_name(file: UploadFile) -> Tuple[str, str, str, str, str]:
|
||||
today = await get_now()
|
||||
storage_path = settings.storage_path.strip("/")
|
||||
file_uuid = uuid.uuid4().hex
|
||||
filename = await sanitize_filename(unquote(file.filename or ""))
|
||||
base_path = f"share/data/{today.strftime('%Y/%m/%d')}/{file_uuid}"
|
||||
path = f"{storage_path}/{base_path}" if storage_path else base_path
|
||||
prefix, suffix = os.path.splitext(filename)
|
||||
save_path = f"{path}/{filename}"
|
||||
return path, suffix, prefix, filename, save_path
|
||||
|
||||
|
||||
async def get_chunk_file_path_name(
|
||||
file_name: str, upload_id: str
|
||||
) -> Tuple[str, str, str, str, str]:
|
||||
today = await get_now()
|
||||
storage_path = settings.storage_path.strip("/")
|
||||
base_path = f"share/data/{today.strftime('%Y/%m/%d')}/{upload_id}"
|
||||
path = f"{storage_path}/{base_path}" if storage_path else base_path
|
||||
prefix, suffix = os.path.splitext(file_name)
|
||||
save_path = f"{path}/{prefix}{suffix}"
|
||||
return path, suffix, prefix, file_name, save_path
|
||||
|
||||
|
||||
async def get_expire_info(
|
||||
expire_value: int, expire_style: str
|
||||
) -> Tuple[Optional[datetime.datetime], int, int, str]:
|
||||
expired_count, used_count = -1, 0
|
||||
now = await get_now()
|
||||
code = None
|
||||
|
||||
max_timedelta = (
|
||||
datetime.timedelta(seconds=settings.max_save_seconds)
|
||||
if settings.max_save_seconds > 0
|
||||
else datetime.timedelta(days=7)
|
||||
)
|
||||
detail = (
|
||||
await max_save_times_desc(settings.max_save_seconds)
|
||||
if settings.max_save_seconds > 0
|
||||
else "7天"
|
||||
)
|
||||
detail = f"限制最长时间为 {detail[0]},可换用其他方式"
|
||||
|
||||
expire_styles = {
|
||||
"day": lambda: now + datetime.timedelta(days=expire_value),
|
||||
"hour": lambda: now + datetime.timedelta(hours=expire_value),
|
||||
"minute": lambda: now + datetime.timedelta(minutes=expire_value),
|
||||
"count": lambda: (now + datetime.timedelta(days=1), expire_value),
|
||||
"forever": lambda: (None, None),
|
||||
}
|
||||
"""
|
||||
today = datetime.datetime.now()
|
||||
path = f"share/data/{today.strftime('%Y/%m/%d')}"
|
||||
prefix, suffix = os.path.splitext(file.filename)
|
||||
file_uuid = f"{uuid.uuid4().hex}"
|
||||
uuid_file_name = f"{file_uuid}{suffix}"
|
||||
save_path = f"{path}/{uuid_file_name}"
|
||||
return path, suffix, prefix, uuid_file_name, save_path
|
||||
|
||||
|
||||
async def get_expire_info(expire_value: int, expire_style: str):
|
||||
"""
|
||||
获取过期信息
|
||||
:param expire_value:
|
||||
:param expire_style:
|
||||
:return: expired_at 过期时间, expired_count 可用次数, used_count 已用次数, code 随机码
|
||||
"""
|
||||
expired_count, used_count, now, code = -1, 0, datetime.datetime.now(), None
|
||||
if expire_style == 'day':
|
||||
expired_at = now + datetime.timedelta(days=expire_value)
|
||||
elif expire_style == 'hour':
|
||||
expired_at = now + datetime.timedelta(hours=expire_value)
|
||||
elif expire_style == 'minute':
|
||||
expired_at = now + datetime.timedelta(minutes=expire_value)
|
||||
elif expire_style == 'count':
|
||||
expired_at = now + datetime.timedelta(days=1)
|
||||
expired_count = expire_value
|
||||
elif expire_style == 'forever':
|
||||
expired_at = None
|
||||
code = await get_random_code(style='string')
|
||||
if expire_style in expire_styles:
|
||||
result = expire_styles[expire_style]()
|
||||
if isinstance(result, tuple):
|
||||
expired_at, extra = result
|
||||
if expire_style == "count":
|
||||
expired_count = extra
|
||||
else:
|
||||
expired_at = result
|
||||
if expired_at and expired_at - now > max_timedelta:
|
||||
raise HTTPException(status_code=403, detail=detail)
|
||||
else:
|
||||
expired_at = now + datetime.timedelta(days=1)
|
||||
|
||||
if not code:
|
||||
code = await get_random_code()
|
||||
|
||||
return expired_at, expired_count, used_count, code
|
||||
|
||||
|
||||
async def get_random_code(style='num'):
|
||||
"""
|
||||
获取随机字符串
|
||||
:return:
|
||||
"""
|
||||
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限制器
|
||||
error_ip_limit = IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute)
|
||||
# 上传文件限制器
|
||||
upload_ip_limit = IPRateLimit(count=settings.uploadCount, minutes=settings.errorMinute)
|
||||
async def calculate_file_hash(file: UploadFile, chunk_size=1024 * 1024) -> str:
|
||||
sha = hashlib.sha256()
|
||||
await file.seek(0)
|
||||
while True:
|
||||
chunk = await file.read(chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
sha.update(chunk)
|
||||
await file.seek(0)
|
||||
return sha.hexdigest()
|
||||
|
||||
|
||||
ip_limit = {
|
||||
"error": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
|
||||
"metadata": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
|
||||
"upload": IPRateLimit(count=settings.uploadCount, minutes=settings.uploadMinute),
|
||||
"login": IPRateLimit(count=settings.loginCount, minutes=settings.loginMinute),
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
from apps.base.models import KeyValue
|
||||
from apps.base.utils import ip_limit
|
||||
from core.database import db_startup_lock
|
||||
from core.logger import logger
|
||||
from core.security import (
|
||||
generate_jwt_secret,
|
||||
is_config_initialized,
|
||||
is_valid_jwt_secret,
|
||||
prepare_security_config,
|
||||
)
|
||||
from core.settings import DEFAULT_CONFIG, settings
|
||||
from core.utils import hash_password
|
||||
|
||||
|
||||
MIN_ADMIN_PASSWORD_LENGTH = 8
|
||||
SETUP_CONFIG_FIELDS = {
|
||||
"allowed_file_types",
|
||||
"code_generate_type",
|
||||
"enableChunk",
|
||||
"errorCount",
|
||||
"errorMinute",
|
||||
"loginCount",
|
||||
"loginMinute",
|
||||
"expireStyle",
|
||||
"max_save_seconds",
|
||||
"name",
|
||||
"openUpload",
|
||||
"uploadCount",
|
||||
"uploadMinute",
|
||||
"uploadSize",
|
||||
}
|
||||
|
||||
|
||||
async def ensure_settings_row() -> None:
|
||||
initial_security = prepare_security_config(DEFAULT_CONFIG)
|
||||
_, created = await KeyValue.get_or_create(
|
||||
key="settings", defaults={"value": initial_security.config}
|
||||
)
|
||||
if created:
|
||||
logger.warning(
|
||||
"系统尚未初始化,请在浏览器中打开站点并完成管理员密码设置"
|
||||
)
|
||||
|
||||
|
||||
async def ensure_security_settings() -> None:
|
||||
config_record = await KeyValue.filter(key="settings").first()
|
||||
if not config_record:
|
||||
return
|
||||
|
||||
current_config = {**DEFAULT_CONFIG, **(config_record.value or {})}
|
||||
security_config = prepare_security_config(current_config)
|
||||
if not security_config.changed:
|
||||
return
|
||||
|
||||
config_record.value = security_config.config
|
||||
await config_record.save()
|
||||
if security_config.setup_required:
|
||||
logger.warning("检测到空密码或旧版默认管理员密码,请通过初始化页面重新设置")
|
||||
elif security_config.password_hashed:
|
||||
logger.info("已将管理员密码迁移为哈希存储")
|
||||
if security_config.jwt_secret_rotated:
|
||||
logger.info("已生成独立 JWT 签名密钥")
|
||||
await refresh_settings()
|
||||
|
||||
|
||||
def _sync_ip_limits() -> None:
|
||||
ip_limit["error"].minutes = settings.errorMinute
|
||||
ip_limit["error"].count = settings.errorCount
|
||||
ip_limit["metadata"].minutes = settings.errorMinute
|
||||
ip_limit["metadata"].count = settings.errorCount
|
||||
ip_limit["upload"].minutes = settings.uploadMinute
|
||||
ip_limit["upload"].count = settings.uploadCount
|
||||
ip_limit["login"].minutes = settings.loginMinute
|
||||
ip_limit["login"].count = settings.loginCount
|
||||
|
||||
|
||||
async def refresh_settings() -> None:
|
||||
"""从数据库读取最新配置并应用到运行时。"""
|
||||
config_record = await KeyValue.filter(key="settings").first()
|
||||
settings.user_config = config_record.value if config_record and config_record.value else {}
|
||||
_sync_ip_limits()
|
||||
|
||||
|
||||
def is_runtime_initialized() -> bool:
|
||||
return is_config_initialized(dict(settings.items()))
|
||||
|
||||
|
||||
async def initialize_system(
|
||||
admin_password: str,
|
||||
site_name: str | None = None,
|
||||
setup_options: dict | None = None,
|
||||
) -> None:
|
||||
password = str(admin_password or "").strip()
|
||||
if len(password) < MIN_ADMIN_PASSWORD_LENGTH:
|
||||
raise ValueError(f"管理员密码至少需要 {MIN_ADMIN_PASSWORD_LENGTH} 位")
|
||||
|
||||
async with db_startup_lock():
|
||||
config_record = await KeyValue.filter(key="settings").first()
|
||||
current_config = {
|
||||
**DEFAULT_CONFIG,
|
||||
**(config_record.value if config_record and config_record.value else {}),
|
||||
}
|
||||
if is_config_initialized(current_config):
|
||||
raise ValueError("系统已经初始化,请直接登录后台")
|
||||
|
||||
next_config = dict(current_config)
|
||||
for key, value in (setup_options or {}).items():
|
||||
if key in SETUP_CONFIG_FIELDS:
|
||||
next_config[key] = value
|
||||
|
||||
normalized_site_name = str(site_name or "").strip()
|
||||
if normalized_site_name:
|
||||
next_config["name"] = normalized_site_name[:80]
|
||||
|
||||
next_config["admin_token"] = hash_password(password)
|
||||
if not is_valid_jwt_secret(next_config.get("jwt_secret")):
|
||||
next_config["jwt_secret"] = generate_jwt_secret()
|
||||
|
||||
await KeyValue.update_or_create(key="settings", defaults={"value": next_config})
|
||||
await refresh_settings()
|
||||
@@ -0,0 +1,146 @@
|
||||
import asyncio
|
||||
import glob
|
||||
import importlib
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import IO
|
||||
|
||||
from tortoise import Tortoise
|
||||
|
||||
from core.logger import logger
|
||||
from core.settings import data_root
|
||||
|
||||
|
||||
_DB_FILE = os.path.join(data_root, "filecodebox.db")
|
||||
_STARTUP_LOCK_FILE = os.path.join(data_root, "filecodebox.startup.lock")
|
||||
|
||||
|
||||
def get_db_config() -> dict:
|
||||
return {
|
||||
"connections": {
|
||||
"default": {
|
||||
"engine": "tortoise.backends.sqlite",
|
||||
"credentials": {
|
||||
"file_path": _DB_FILE,
|
||||
"journal_mode": "WAL",
|
||||
"busy_timeout": 10000,
|
||||
"foreign_keys": "ON",
|
||||
},
|
||||
}
|
||||
},
|
||||
"apps": {
|
||||
"models": {
|
||||
"models": ["apps.base.models"],
|
||||
"default_connection": "default",
|
||||
}
|
||||
},
|
||||
"use_tz": False,
|
||||
"timezone": "Asia/Shanghai",
|
||||
}
|
||||
|
||||
|
||||
def _lock_file(file_obj: IO[str]) -> None:
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
# Windows 需要锁定至少 1 字节
|
||||
if os.fstat(file_obj.fileno()).st_size == 0:
|
||||
file_obj.write("0")
|
||||
file_obj.flush()
|
||||
msvcrt.locking(file_obj.fileno(), msvcrt.LK_LOCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(file_obj.fileno(), fcntl.LOCK_EX)
|
||||
|
||||
|
||||
def _unlock_file(file_obj: IO[str]) -> None:
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
msvcrt.locking(file_obj.fileno(), msvcrt.LK_UNLCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(file_obj.fileno(), fcntl.LOCK_UN)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def db_startup_lock():
|
||||
os.makedirs(data_root, exist_ok=True)
|
||||
lock_file = open(_STARTUP_LOCK_FILE, "a+", encoding="utf-8")
|
||||
try:
|
||||
await asyncio.to_thread(_lock_file, lock_file)
|
||||
yield
|
||||
finally:
|
||||
await asyncio.to_thread(_unlock_file, lock_file)
|
||||
lock_file.close()
|
||||
|
||||
|
||||
async def init_db():
|
||||
try:
|
||||
db_config = get_db_config()
|
||||
|
||||
if not Tortoise._inited:
|
||||
await Tortoise.init(config=db_config)
|
||||
|
||||
async with db_startup_lock():
|
||||
# 创建migrations表
|
||||
await Tortoise.get_connection("default").execute_script("""
|
||||
CREATE TABLE IF NOT EXISTS migrates (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
migration_file VARCHAR(255) NOT NULL UNIQUE,
|
||||
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
""")
|
||||
|
||||
# 执行迁移
|
||||
await execute_migrations()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"数据库初始化失败: {str(e)}")
|
||||
raise
|
||||
|
||||
|
||||
async def execute_migrations():
|
||||
"""执行数据库迁移"""
|
||||
try:
|
||||
# 收集迁移文件
|
||||
migration_files = []
|
||||
for root, dirs, files in os.walk("apps"):
|
||||
if "migrations" in dirs:
|
||||
migration_path = os.path.join(root, "migrations")
|
||||
migration_files.extend(glob.glob(os.path.join(migration_path, "migrations_*.py")))
|
||||
|
||||
# 按文件名排序
|
||||
migration_files.sort()
|
||||
|
||||
for migration_file in migration_files:
|
||||
file_name = os.path.basename(migration_file)
|
||||
|
||||
# 检查是否已执行
|
||||
executed = await Tortoise.get_connection("default").execute_query(
|
||||
"SELECT id FROM migrates WHERE migration_file = ?", [file_name]
|
||||
)
|
||||
|
||||
if not executed[1]:
|
||||
logger.info(f"执行迁移: {file_name}")
|
||||
# 导入并执行migration
|
||||
module_path = migration_file.replace("/", ".").replace("\\", ".").replace(".py", "")
|
||||
try:
|
||||
migration_module = importlib.import_module(module_path)
|
||||
if hasattr(migration_module, "migrate"):
|
||||
await migration_module.migrate()
|
||||
# 记录执行
|
||||
await Tortoise.get_connection("default").execute_query(
|
||||
"INSERT INTO migrates (migration_file) VALUES (?)",
|
||||
[file_name]
|
||||
)
|
||||
logger.info(f"迁移完成: {file_name}")
|
||||
except Exception as e:
|
||||
logger.error(f"迁移 {file_name} 执行失败: {str(e)}")
|
||||
raise
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"迁移过程发生错误: {str(e)}")
|
||||
raise
|
||||
@@ -0,0 +1,28 @@
|
||||
import logging
|
||||
import sys
|
||||
|
||||
|
||||
def setup_logger():
|
||||
# 创建logger对象
|
||||
_logger = logging.getLogger('FileCodeBox')
|
||||
_logger.setLevel(logging.INFO)
|
||||
|
||||
# 创建控制台处理器
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(logging.INFO)
|
||||
|
||||
# 设置日志格式
|
||||
formatter = logging.Formatter(
|
||||
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
console_handler.setFormatter(formatter)
|
||||
|
||||
# 添加处理器到logger
|
||||
_logger.addHandler(console_handler)
|
||||
|
||||
return _logger
|
||||
|
||||
|
||||
# 创建全局logger实例
|
||||
logger = setup_logger()
|
||||
@@ -2,14 +2,19 @@
|
||||
# @Author : Lan
|
||||
# @File : response.py
|
||||
# @Software: PyCharm
|
||||
from typing import Generic, TypeVar
|
||||
from typing import Generic, Optional, TypeVar
|
||||
|
||||
from pydantic.v1.generics import GenericModel
|
||||
from pydantic import BaseModel
|
||||
|
||||
T = TypeVar('T')
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class APIResponse(GenericModel, Generic[T]):
|
||||
class APIResponse(BaseModel, Generic[T]):
|
||||
code: int = 200
|
||||
message: str = 'ok'
|
||||
detail: T
|
||||
message: str = "ok"
|
||||
msg: Optional[str] = None
|
||||
detail: Optional[T] = None
|
||||
|
||||
def model_post_init(self, __context) -> None:
|
||||
if self.msg is None:
|
||||
self.msg = self.message
|
||||
@@ -0,0 +1,60 @@
|
||||
import copy
|
||||
import secrets
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from core.utils import hash_password, is_password_hashed, verify_password
|
||||
|
||||
|
||||
JWT_SECRET_MIN_LENGTH = 32
|
||||
INTERNAL_CONFIG_KEYS = {"jwt_secret"}
|
||||
LEGACY_DEFAULT_ADMIN_TOKEN = "FileCodeBox" + "2023"
|
||||
|
||||
|
||||
@dataclass
|
||||
class SecurityConfigResult:
|
||||
config: dict[str, Any]
|
||||
changed: bool = False
|
||||
password_hashed: bool = False
|
||||
jwt_secret_rotated: bool = False
|
||||
setup_required: bool = False
|
||||
|
||||
|
||||
def generate_jwt_secret() -> str:
|
||||
return secrets.token_urlsafe(48)
|
||||
|
||||
|
||||
def is_valid_jwt_secret(secret: Any) -> bool:
|
||||
return isinstance(secret, str) and len(secret) >= JWT_SECRET_MIN_LENGTH
|
||||
|
||||
|
||||
def is_config_initialized(config: dict[str, Any]) -> bool:
|
||||
admin_token = str(config.get("admin_token") or "")
|
||||
if not admin_token:
|
||||
return False
|
||||
return not verify_password(LEGACY_DEFAULT_ADMIN_TOKEN, admin_token)
|
||||
|
||||
|
||||
def prepare_security_config(config: dict[str, Any]) -> SecurityConfigResult:
|
||||
next_config = copy.deepcopy(config)
|
||||
result = SecurityConfigResult(config=next_config)
|
||||
|
||||
admin_token = str(next_config.get("admin_token") or "")
|
||||
if not admin_token:
|
||||
result.setup_required = True
|
||||
elif verify_password(LEGACY_DEFAULT_ADMIN_TOKEN, admin_token):
|
||||
next_config["admin_token"] = ""
|
||||
result.setup_required = True
|
||||
result.changed = True
|
||||
elif not is_password_hashed(admin_token):
|
||||
next_config["admin_token"] = hash_password(admin_token)
|
||||
result.password_hashed = True
|
||||
result.changed = True
|
||||
|
||||
jwt_secret = next_config.get("jwt_secret")
|
||||
if not is_valid_jwt_secret(jwt_secret):
|
||||
next_config["jwt_secret"] = generate_jwt_secret()
|
||||
result.jwt_secret_rotated = True
|
||||
result.changed = True
|
||||
|
||||
return result
|
||||
@@ -4,74 +4,111 @@
|
||||
# @Software: PyCharm
|
||||
from pathlib import Path
|
||||
|
||||
data_root = Path('./data')
|
||||
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)
|
||||
env_path = data_root / '.env2'
|
||||
default_value = {
|
||||
'file_storage': 'local',
|
||||
'name': '文件快递柜-FileCodeBox',
|
||||
'description': '开箱即用的文件快传系统',
|
||||
'keywords': 'FileCodeBox,文件快递柜,口令传送箱,匿名口令分享文本,文件',
|
||||
's3_access_key_id': '',
|
||||
's3_secret_access_key': '',
|
||||
's3_bucket_name': '',
|
||||
's3_endpoint_url': '',
|
||||
'aws_session_token': '',
|
||||
'onedrive_domain': '',
|
||||
'onedrive_client_id': '',
|
||||
'onedrive_username': '',
|
||||
'onedrive_password': '',
|
||||
'onedrive_root_path': 'filebox_storage',
|
||||
'admin_token': 'FileCodeBox2023',
|
||||
'openUpload': 1,
|
||||
'uploadSize': 1024 * 1024 * 10,
|
||||
'uploadMinute': 1,
|
||||
'opacity': 0.9,
|
||||
'background': '',
|
||||
'uploadCount': 10,
|
||||
'errorMinute': 1,
|
||||
'errorCount': 1,
|
||||
'port': 12345,
|
||||
|
||||
DEFAULT_CONFIG = {
|
||||
"file_storage": "local",
|
||||
"storage_path": "",
|
||||
"storageLimit": 0,
|
||||
"name": "文件快递柜 - FileCodeBox",
|
||||
"description": "开箱即用的文件快传系统",
|
||||
"notify_title": "系统通知",
|
||||
"notify_content": '欢迎使用 FileCodeBox,本程序开源于 <a href="https://github.com/vastsa/FileCodeBox" target="_blank">Github</a> ,欢迎Star和Fork。',
|
||||
"page_explain": "请勿上传或分享违法内容。根据《中华人民共和国网络安全法》、《中华人民共和国刑法》、《中华人民共和国治安管理处罚法》等相关规定。 传播或存储违法、违规内容,会受到相关处罚,严重者将承担刑事责任。本站坚决配合相关部门,确保网络内容的安全,和谐,打造绿色网络环境。",
|
||||
"keywords": "FileCodeBox, 文件快递柜, 口令传送箱, 匿名口令分享文本, 文件",
|
||||
"s3_access_key_id": "",
|
||||
"s3_secret_access_key": "",
|
||||
"s3_bucket_name": "",
|
||||
"s3_endpoint_url": "",
|
||||
"s3_region_name": "auto",
|
||||
"s3_signature_version": "s3v2",
|
||||
"s3_hostname": "",
|
||||
"s3_addressing_style": "auto",
|
||||
"s3_proxy": 0,
|
||||
"max_save_seconds": 0,
|
||||
"aws_session_token": "",
|
||||
"onedrive_domain": "",
|
||||
"onedrive_client_id": "",
|
||||
"onedrive_username": "",
|
||||
"onedrive_password": "",
|
||||
"onedrive_root_path": "filebox_storage",
|
||||
"onedrive_proxy": 0,
|
||||
"webdav_root_path": "filebox_storage",
|
||||
"webdav_proxy": 0,
|
||||
"admin_token": "",
|
||||
"jwt_secret": "",
|
||||
"adminSessionExpire": ADMIN_SESSION_EXPIRE_DEFAULT,
|
||||
"openUpload": 1,
|
||||
"uploadSize": 1024 * 1024 * 10,
|
||||
"allowed_file_types": ["*"],
|
||||
"expireStyle": ["day", "hour", "minute", "forever", "count"],
|
||||
"code_generate_type": "secret",
|
||||
"uploadMinute": 1,
|
||||
"enableChunk": 0,
|
||||
"webdav_url": "",
|
||||
"webdav_password": "",
|
||||
"webdav_username": "",
|
||||
"opacity": 0.9,
|
||||
"background": "",
|
||||
"uploadCount": 10,
|
||||
"themesChoices": [
|
||||
{
|
||||
"name": "2023",
|
||||
"key": "themes/2023",
|
||||
"author": "Lan",
|
||||
"version": "1.0",
|
||||
},
|
||||
{
|
||||
"name": "2024",
|
||||
"key": "themes/2024",
|
||||
"author": "Lan",
|
||||
"version": "1.0",
|
||||
},
|
||||
],
|
||||
"themesSelect": "themes/2024",
|
||||
"errorMinute": 1,
|
||||
"errorCount": 10,
|
||||
"loginCount": 5,
|
||||
"loginMinute": 15,
|
||||
"serverWorkers": 1,
|
||||
"serverHost": "0.0.0.0",
|
||||
"serverPort": 12345,
|
||||
"showAdminAddr": 0,
|
||||
"robotsText": "User-agent: *\nDisallow: /",
|
||||
"trustedProxies": [],
|
||||
}
|
||||
|
||||
|
||||
class Settings:
|
||||
__instance = None
|
||||
def __init__(self, defaults=None):
|
||||
self.default_config = defaults or {}
|
||||
self.user_config = {}
|
||||
|
||||
def __init__(self):
|
||||
# 读取.env
|
||||
if not (env_path).exists():
|
||||
with open(env_path, 'w', encoding='utf-8') as f:
|
||||
for key, value in default_value.items():
|
||||
f.write(f'{key}={value}\n')
|
||||
# 更新default_value
|
||||
with open(env_path, 'r', encoding='utf-8') as f:
|
||||
for line in f.readlines():
|
||||
key, value = line.strip().split('=', maxsplit=1)
|
||||
# 将字符串转换为原本的类型
|
||||
if not key.startswith('opendal_') and isinstance(default_value[key], int):
|
||||
value = int(value)
|
||||
default_value[key] = value
|
||||
# 更新self
|
||||
for key, value in default_value.items():
|
||||
self.__setattr__(key, value)
|
||||
|
||||
def __new__(cls, *args, **kwargs):
|
||||
if not cls.__instance:
|
||||
cls.__instance = super(Settings, cls).__new__(cls, *args, **kwargs)
|
||||
return cls.__instance
|
||||
def __getattr__(self, attr):
|
||||
if attr in self.user_config:
|
||||
return self.user_config[attr]
|
||||
if attr in self.default_config:
|
||||
return self.default_config[attr]
|
||||
raise AttributeError(
|
||||
f"'{self.__class__.__name__}' object has no attribute '{attr}'"
|
||||
)
|
||||
|
||||
def __setattr__(self, key, value):
|
||||
if not key.startswith('opendal_') and type(value) == str and value.isnumeric():
|
||||
value = int(value)
|
||||
self.__dict__[key] = value
|
||||
with open(env_path, 'w', encoding='utf-8') as f:
|
||||
for key, value in self.__dict__.items():
|
||||
f.write(f'{key}={value}\n')
|
||||
if key in ["default_config", "user_config"]:
|
||||
super().__setattr__(key, value)
|
||||
else:
|
||||
self.user_config[key] = value
|
||||
|
||||
def items(self):
|
||||
return self.__dict__.items()
|
||||
return {**self.default_config, **self.user_config}.items()
|
||||
|
||||
|
||||
settings = Settings()
|
||||
settings = Settings(DEFAULT_CONFIG)
|
||||
@@ -3,25 +3,128 @@
|
||||
# @File : tasks.py
|
||||
# @Software: PyCharm
|
||||
import asyncio
|
||||
import datetime
|
||||
import logging
|
||||
import os
|
||||
|
||||
from tortoise.expressions import Q
|
||||
|
||||
from apps.base.models import FileCodes
|
||||
from apps.base.utils import error_ip_limit, upload_ip_limit
|
||||
from core.storage import file_storage
|
||||
from apps.base.models import (
|
||||
FileCodes,
|
||||
PresignUploadSession,
|
||||
StorageReservation,
|
||||
UploadChunk,
|
||||
)
|
||||
from apps.base.utils import ip_limit, get_chunk_file_path_name
|
||||
from core.config import refresh_settings
|
||||
from core.settings import settings, data_root
|
||||
from core.storage import FileStorageInterface, storages
|
||||
from core.utils import get_now
|
||||
|
||||
|
||||
async def delete_expire_files():
|
||||
while True:
|
||||
try:
|
||||
await error_ip_limit.remove_expired_ip()
|
||||
await upload_ip_limit.remove_expired_ip()
|
||||
expire_data = await FileCodes.filter(Q(expired_at__lt=await get_now()) | Q(expired_count=0)).all()
|
||||
await refresh_settings()
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
# 遍历 share目录下的所有文件夹,删除空的文件夹,并判断父目录是否为空,如果为空也删除
|
||||
if settings.file_storage == "local":
|
||||
for root, dirs, files in os.walk(f"{data_root}/share/data"):
|
||||
if not dirs and not files:
|
||||
os.rmdir(root)
|
||||
await ip_limit["error"].remove_expired_ip()
|
||||
await ip_limit["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:
|
||||
await file_storage.delete_file(exp)
|
||||
await exp.delete()
|
||||
try:
|
||||
await file_storage.delete_file(exp)
|
||||
except Exception as e:
|
||||
logging.error(f"删除过期文件失败 code={exp.code}: {e}")
|
||||
try:
|
||||
await exp.delete()
|
||||
except Exception as e:
|
||||
logging.error(f"删除记录失败 code={exp.code}: {e}")
|
||||
except Exception as e:
|
||||
print(e)
|
||||
logging.error(e)
|
||||
finally:
|
||||
await asyncio.sleep(600)
|
||||
|
||||
|
||||
async def clean_incomplete_uploads():
|
||||
while True:
|
||||
try:
|
||||
await refresh_settings()
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
expire_hours = getattr(settings, "chunk_expire_hours", 24)
|
||||
now = await get_now()
|
||||
expire_time = now - datetime.timedelta(hours=expire_hours)
|
||||
expired_sessions = await UploadChunk.filter(
|
||||
chunk_index=-1, created_at__lt=expire_time
|
||||
).all()
|
||||
|
||||
for session in expired_sessions:
|
||||
try:
|
||||
save_path = session.save_path
|
||||
if not save_path:
|
||||
_, _, _, _, save_path = await get_chunk_file_path_name(
|
||||
session.file_name, session.upload_id
|
||||
)
|
||||
await file_storage.clean_chunks(session.upload_id, save_path)
|
||||
except Exception as e:
|
||||
logging.error(
|
||||
f"清理分片文件失败 upload_id={session.upload_id}: {e}"
|
||||
)
|
||||
|
||||
try:
|
||||
await UploadChunk.filter(upload_id=session.upload_id).delete()
|
||||
await StorageReservation.filter(
|
||||
token=f"chunk:{session.upload_id}"
|
||||
).delete()
|
||||
logging.info(f"已清理过期上传会话 upload_id={session.upload_id}")
|
||||
except Exception as e:
|
||||
logging.error(
|
||||
f"删除分片记录失败 upload_id={session.upload_id}: {e}"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"清理未完成上传任务异常: {e}")
|
||||
finally:
|
||||
await asyncio.sleep(3600)
|
||||
|
||||
|
||||
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(
|
||||
FileCodes(
|
||||
file_path=os.path.dirname(session.save_path),
|
||||
uuid_file_name=os.path.basename(session.save_path),
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
logging.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:
|
||||
logging.error(f"清理过期预签名会话异常: {e}")
|
||||
finally:
|
||||
await asyncio.sleep(900)
|
||||
@@ -4,11 +4,14 @@
|
||||
# @Software: PyCharm
|
||||
import datetime
|
||||
import hashlib
|
||||
import random
|
||||
import hmac
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import string
|
||||
import time
|
||||
|
||||
from apps.base.depends import IPRateLimit
|
||||
from core.settings import settings
|
||||
|
||||
|
||||
async def get_random_num():
|
||||
@@ -16,7 +19,7 @@ async def get_random_num():
|
||||
获取随机数
|
||||
:return:
|
||||
"""
|
||||
return random.randint(10000, 99999)
|
||||
return secrets.randbelow(90000) + 10000
|
||||
|
||||
|
||||
r_s = string.ascii_uppercase + string.digits
|
||||
@@ -27,7 +30,7 @@ async def get_random_string():
|
||||
获取随机字符串
|
||||
:return:
|
||||
"""
|
||||
return ''.join(random.choice(r_s) for _ in range(5))
|
||||
return "".join(secrets.choice(r_s) for _ in range(5))
|
||||
|
||||
|
||||
async def get_now():
|
||||
@@ -35,19 +38,26 @@ async def get_now():
|
||||
获取当前时间
|
||||
:return:
|
||||
"""
|
||||
return datetime.datetime.now(
|
||||
datetime.timezone(datetime.timedelta(hours=8))
|
||||
)
|
||||
return datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8)))
|
||||
|
||||
|
||||
async def get_select_token(code: str):
|
||||
async def get_select_token(code: str, offset: int = 0):
|
||||
"""
|
||||
获取下载token
|
||||
:param code:
|
||||
:param code: 取件码
|
||||
:param offset: 时间窗口偏移(0=当前窗口,1=上一个窗口)。
|
||||
用于兼容窗口边界竞态:用户在某窗口末尾获取的 token,
|
||||
请求到达服务器时可能已进入下一窗口。
|
||||
:return:
|
||||
"""
|
||||
token = "123456"
|
||||
return hashlib.sha256(f"{code}{int(time.time() / 1000)}000{token}".encode()).hexdigest()
|
||||
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}{time_factor}000{token}".encode()
|
||||
).hexdigest()
|
||||
|
||||
|
||||
async def get_file_url(code: str):
|
||||
@@ -56,4 +66,102 @@ async def get_file_url(code: str):
|
||||
:param code:
|
||||
:return:
|
||||
"""
|
||||
return f'/share/download?key={await get_select_token(code)}&code={code}'
|
||||
return f"/share/download?key={await get_select_token(code)}&code={code}"
|
||||
|
||||
|
||||
async def max_save_times_desc(max_save_seconds: int):
|
||||
"""
|
||||
获取最大保存时间的描述
|
||||
:param max_save_seconds:
|
||||
:return:
|
||||
"""
|
||||
|
||||
def gen_desc_zh(value: int, desc: str):
|
||||
if value > 0:
|
||||
return f"{value}{desc}"
|
||||
else:
|
||||
return ""
|
||||
|
||||
def gen_desc_en(value: int, desc: str):
|
||||
if value > 0:
|
||||
ret = f"{value} {desc}"
|
||||
if value > 1:
|
||||
ret += "s"
|
||||
ret += " "
|
||||
return ret
|
||||
else:
|
||||
return ""
|
||||
|
||||
max_timedelta = datetime.timedelta(seconds=max_save_seconds)
|
||||
desc_zh, desc_en = "最长保存时间:", "Max save time: "
|
||||
desc_zh += gen_desc_zh(max_timedelta.days, "天")
|
||||
desc_en += gen_desc_en(max_timedelta.days, "day")
|
||||
desc_zh += gen_desc_zh(max_timedelta.seconds // 3600, "小时")
|
||||
desc_en += gen_desc_en(max_timedelta.seconds // 3600, "hour")
|
||||
desc_zh += gen_desc_zh(max_timedelta.seconds % 3600 // 60, "分钟")
|
||||
desc_en += gen_desc_en(max_timedelta.seconds % 3600 // 60, "minute")
|
||||
desc_zh += gen_desc_zh(max_timedelta.seconds % 60, "秒")
|
||||
desc_en += gen_desc_en(max_timedelta.seconds % 60, "second")
|
||||
return desc_zh, desc_en
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""
|
||||
使用 SHA256 + salt 哈希密码
|
||||
返回格式: sha256$<salt>$<hash>
|
||||
"""
|
||||
salt = os.urandom(16).hex()
|
||||
password_hash = hashlib.sha256(f"{salt}{password}".encode()).hexdigest()
|
||||
return f"sha256${salt}${password_hash}"
|
||||
|
||||
|
||||
def verify_password(password: str, hashed: str) -> bool:
|
||||
"""
|
||||
验证密码是否匹配
|
||||
支持新格式 (sha256$salt$hash) 和旧格式 (明文)
|
||||
"""
|
||||
if not hashed:
|
||||
return False
|
||||
|
||||
# 新格式: sha256$salt$hash
|
||||
if hashed.startswith("sha256$"):
|
||||
parts = hashed.split("$")
|
||||
if len(parts) != 3:
|
||||
return False
|
||||
_, salt, stored_hash = parts
|
||||
password_hash = hashlib.sha256(f"{salt}{password}".encode()).hexdigest()
|
||||
return hmac.compare_digest(password_hash, stored_hash)
|
||||
|
||||
# 旧格式: 明文比较 (兼容迁移前的数据)
|
||||
return hmac.compare_digest(str(password), str(hashed))
|
||||
|
||||
|
||||
def is_password_hashed(password: str) -> bool:
|
||||
"""
|
||||
检查密码是否已经是哈希格式
|
||||
"""
|
||||
return password.startswith("sha256$") and len(password.split("$")) == 3
|
||||
|
||||
|
||||
async def sanitize_filename(filename: str) -> str:
|
||||
"""
|
||||
安全处理文件名:
|
||||
1. 剥离路径只保留文件名
|
||||
2. 替换非法字符
|
||||
3. 处理空文件名情况
|
||||
"""
|
||||
filename = os.path.basename(filename)
|
||||
illegal_chars = r'[\\/*?:"<>|\x00-\x1F]' # 包含控制字符
|
||||
# 替换非法字符为下划线
|
||||
cleaned = re.sub(illegal_chars, "_", filename)
|
||||
# 处理空格(可选替换为_)
|
||||
cleaned = cleaned.replace(" ", "_")
|
||||
# 处理连续下划线
|
||||
cleaned = re.sub(r"_+", "_", cleaned)
|
||||
# 处理首尾特殊字符
|
||||
cleaned = cleaned.strip("._")
|
||||
# 处理空文件名情况
|
||||
if not cleaned:
|
||||
cleaned = "unnamed_file"
|
||||
# 长度限制(按需调整)
|
||||
return cleaned[:255]
|
||||
@@ -0,0 +1,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,13 @@
|
||||
version: "3"
|
||||
services:
|
||||
file-code-box:
|
||||
image: lanol/filecodebox:2.5.3 # x-release-please-version
|
||||
user: "1000:1000"
|
||||
volumes:
|
||||
- fcb-data:/app/data:rw
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "12345:12345"
|
||||
volumes:
|
||||
fcb-data:
|
||||
external: false
|
||||
@@ -0,0 +1,323 @@
|
||||
import { defineConfig } from 'vitepress'
|
||||
|
||||
// https://vitepress.dev/reference/site-config
|
||||
export default defineConfig({
|
||||
title: 'FileCodeBox',
|
||||
description: 'FileCodeBox 自托管文件与文本分享服务文档',
|
||||
lang: 'zh-CN',
|
||||
lastUpdated: true,
|
||||
cleanUrls: true,
|
||||
sitemap: {
|
||||
hostname: 'https://fcb-docs.aiuo.net',
|
||||
},
|
||||
head: [
|
||||
['meta', { name: 'theme-color', content: '#111111' }],
|
||||
['link', { rel: 'icon', href: '/logo_small.png' }],
|
||||
],
|
||||
locales: {
|
||||
root: {
|
||||
label: '简体中文',
|
||||
lang: 'zh-CN',
|
||||
title: 'FileCodeBox',
|
||||
description: '匿名口令分享文本,文件',
|
||||
themeConfig: {
|
||||
logo: '/logo_small.png',
|
||||
nav: [
|
||||
{ text: '首页', link: '/' },
|
||||
{
|
||||
text: '使用指南',
|
||||
items: [
|
||||
{ text: '快速开始', link: '/guide/getting-started' },
|
||||
{ text: '上传与分享', link: '/guide/upload' },
|
||||
{ text: '管理面板', link: '/guide/management' },
|
||||
{ text: '存储配置', link: '/guide/storage' },
|
||||
],
|
||||
},
|
||||
{ text: 'API', link: '/api/' },
|
||||
{
|
||||
text: '资源',
|
||||
items: [
|
||||
{ text: '在线体验', link: 'https://share.lanol.cn' },
|
||||
{ text: '部署案例', link: '/showcase' },
|
||||
{ text: '更新日志', link: '/changelog' },
|
||||
{ text: '贡献指南', link: '/contributing' },
|
||||
{ text: 'GitHub', link: 'https://github.com/vastsa/FileCodeBox' },
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
sidebar: {
|
||||
'/guide/': [
|
||||
{
|
||||
text: '开始',
|
||||
items: [
|
||||
{
|
||||
text: '什么是 FileCodeBox',
|
||||
link: '/guide/introduction',
|
||||
},
|
||||
{ text: '快速开始', link: '/guide/getting-started' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: '使用',
|
||||
items: [
|
||||
{ text: '文件上传', link: '/guide/upload' },
|
||||
{ text: '文件分享', link: '/guide/share' },
|
||||
{ text: '文件管理', link: '/guide/management' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: '运维',
|
||||
items: [
|
||||
{ text: '存储配置', link: '/guide/storage' },
|
||||
{ text: '安全设置', link: '/guide/security' },
|
||||
{ text: '系统配置', link: '/guide/configuration' },
|
||||
{ text: '版本发布', link: '/guide/releasing' },
|
||||
],
|
||||
},
|
||||
],
|
||||
'/api/': [
|
||||
{
|
||||
text: 'API 参考',
|
||||
items: [
|
||||
{ text: 'API 概览', link: '/api/' },
|
||||
{ text: '预签名上传', link: '/api/presign-upload' },
|
||||
{ text: '分享接口', link: '/api/#分享接口' },
|
||||
{ text: '管理接口', link: '/api/#管理接口' },
|
||||
{ text: '错误响应', link: '/api/#错误响应' },
|
||||
{ text: '状态码说明', link: '/api/#状态码说明' },
|
||||
],
|
||||
},
|
||||
],
|
||||
'/showcase': [
|
||||
{
|
||||
text: '优秀案例',
|
||||
items: [
|
||||
{ text: '案例展示', link: '/showcase' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
socialLinks: [
|
||||
{ icon: 'github', link: 'https://github.com/vastsa/FileCodeBox' },
|
||||
],
|
||||
footer: {
|
||||
message: '基于 LGPL-3.0 许可证发布',
|
||||
copyright: 'Copyright © 2022-present FileCodeBox',
|
||||
},
|
||||
editLink: {
|
||||
pattern: 'https://github.com/vastsa/FileCodeBox/edit/master/docs/:path',
|
||||
text: '在 GitHub 上编辑此页',
|
||||
},
|
||||
docFooter: {
|
||||
prev: '上一篇',
|
||||
next: '下一篇',
|
||||
},
|
||||
lastUpdated: {
|
||||
text: '最后更新',
|
||||
},
|
||||
returnToTopLabel: '返回顶部',
|
||||
skipToContentLabel: '跳转到正文',
|
||||
navMenuLabel: '导航菜单',
|
||||
langMenuLabel: '切换语言',
|
||||
sidebarMenuLabel: '文档目录',
|
||||
darkModeSwitchLabel: '外观',
|
||||
lightModeSwitchTitle: '切换到浅色模式',
|
||||
darkModeSwitchTitle: '切换到深色模式',
|
||||
search: {
|
||||
provider: 'local',
|
||||
},
|
||||
outline: {
|
||||
level: [2, 3],
|
||||
label: '目录',
|
||||
},
|
||||
},
|
||||
},
|
||||
en: {
|
||||
label: 'English',
|
||||
lang: 'en-US',
|
||||
title: 'FileCodeBox',
|
||||
description: 'Simple and efficient file sharing tool',
|
||||
themeConfig: {
|
||||
logo: '/logo_small.png',
|
||||
nav: [
|
||||
{ text: 'Home', link: '/en/' },
|
||||
{
|
||||
text: 'Guides',
|
||||
items: [
|
||||
{ text: 'Getting Started', link: '/en/guide/getting-started' },
|
||||
{ text: 'Upload & Share', link: '/en/guide/upload' },
|
||||
{ text: 'Admin Panel', link: '/en/guide/management' },
|
||||
{ text: 'Storage', link: '/en/guide/storage' },
|
||||
],
|
||||
},
|
||||
{ text: 'API', link: '/en/api/' },
|
||||
{
|
||||
text: 'Resources',
|
||||
items: [
|
||||
{ text: 'Live Demo', link: 'https://share.lanol.cn' },
|
||||
{ text: 'Showcase', link: '/en/showcase' },
|
||||
{ text: 'Changelog', link: '/en/changelog' },
|
||||
{ text: 'Contributing', link: '/en/contributing' },
|
||||
{ text: 'GitHub', link: 'https://github.com/vastsa/FileCodeBox' },
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
sidebar: {
|
||||
'/en/guide/': [
|
||||
{
|
||||
text: 'Start',
|
||||
items: [
|
||||
{
|
||||
text: 'What is FileCodeBox',
|
||||
link: '/en/guide/introduction',
|
||||
},
|
||||
{
|
||||
text: 'Getting Started',
|
||||
link: '/en/guide/getting-started',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
text: 'Use',
|
||||
items: [
|
||||
{ text: 'File Upload', link: '/en/guide/upload' },
|
||||
{ text: 'File Sharing', link: '/en/guide/share' },
|
||||
{ text: 'File Management', link: '/en/guide/management' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: 'Operate',
|
||||
items: [
|
||||
{ text: 'Storage Configuration', link: '/en/guide/storage' },
|
||||
{ text: 'Security Settings', link: '/en/guide/security' },
|
||||
{
|
||||
text: 'System Configuration',
|
||||
link: '/en/guide/configuration',
|
||||
},
|
||||
{ text: 'Releasing', link: '/en/guide/releasing' },
|
||||
],
|
||||
},
|
||||
],
|
||||
'/en/api/': [
|
||||
{
|
||||
text: 'API Reference',
|
||||
items: [
|
||||
{ text: 'API Overview', link: '/en/api/' },
|
||||
{ text: 'Share API', link: '/en/api/#share-api' },
|
||||
{ text: 'Admin API', link: '/en/api/#admin-api' },
|
||||
{ text: 'Error Response', link: '/en/api/#error-response' },
|
||||
{ text: 'Status Codes', link: '/en/api/#status-codes' },
|
||||
],
|
||||
},
|
||||
],
|
||||
'/en/showcase': [
|
||||
{
|
||||
text: 'Showcase',
|
||||
items: [
|
||||
{ text: 'Case Studies', link: '/en/showcase' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
socialLinks: [
|
||||
{ icon: 'github', link: 'https://github.com/vastsa/FileCodeBox' },
|
||||
],
|
||||
footer: {
|
||||
message: 'Released under the LGPL-3.0 license',
|
||||
copyright: 'Copyright © 2022-present FileCodeBox',
|
||||
},
|
||||
editLink: {
|
||||
pattern: 'https://github.com/vastsa/FileCodeBox/edit/master/docs/:path',
|
||||
text: 'Edit this page on GitHub',
|
||||
},
|
||||
docFooter: {
|
||||
prev: 'Previous',
|
||||
next: 'Next',
|
||||
},
|
||||
lastUpdated: {
|
||||
text: 'Last updated',
|
||||
},
|
||||
returnToTopLabel: 'Return to top',
|
||||
skipToContentLabel: 'Skip to content',
|
||||
navMenuLabel: 'Navigation',
|
||||
langMenuLabel: 'Change language',
|
||||
sidebarMenuLabel: 'Documentation',
|
||||
darkModeSwitchLabel: 'Appearance',
|
||||
lightModeSwitchTitle: 'Switch to light theme',
|
||||
darkModeSwitchTitle: 'Switch to dark theme',
|
||||
search: {
|
||||
provider: 'local',
|
||||
},
|
||||
outline: {
|
||||
level: [2, 3],
|
||||
label: 'On this page',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
themeConfig: {
|
||||
// 语言切换器
|
||||
langMenuLabel: '切换语言',
|
||||
|
||||
// 社交链接
|
||||
socialLinks: [
|
||||
{ icon: 'github', link: 'https://github.com/vastsa/FileCodeBox' },
|
||||
],
|
||||
|
||||
// 页脚
|
||||
footer: {
|
||||
message: '基于 LGPL-3.0 license 发布',
|
||||
copyright: 'Copyright © 2022-present FileCodeBox',
|
||||
},
|
||||
|
||||
// 搜索
|
||||
search: {
|
||||
provider: 'local',
|
||||
options: {
|
||||
locales: {
|
||||
zh: {
|
||||
translations: {
|
||||
button: {
|
||||
buttonText: '搜索文档',
|
||||
buttonAriaLabel: '搜索文档',
|
||||
},
|
||||
modal: {
|
||||
noResultsText: '无法找到相关结果',
|
||||
resetButtonTitle: '清除查询条件',
|
||||
footer: {
|
||||
selectText: '选择',
|
||||
navigateText: '切换',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
en: {
|
||||
translations: {
|
||||
button: {
|
||||
buttonText: 'Search',
|
||||
buttonAriaLabel: 'Search docs',
|
||||
},
|
||||
modal: {
|
||||
noResultsText: 'No results found',
|
||||
resetButtonTitle: 'Clear query',
|
||||
footer: {
|
||||
selectText: 'to select',
|
||||
navigateText: 'to navigate',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
outline: {
|
||||
level: [2, 3],
|
||||
label: '目录',
|
||||
},
|
||||
externalLinkIcon: true,
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,317 @@
|
||||
:root {
|
||||
--vp-c-brand-1: #6d5dfc;
|
||||
--vp-c-brand-2: #5848e8;
|
||||
--vp-c-brand-3: #4938ce;
|
||||
--vp-c-brand-soft: rgba(109, 93, 252, 0.12);
|
||||
--vp-c-bg: #ffffff;
|
||||
--vp-c-bg-alt: #f7f7f8;
|
||||
--vp-c-bg-soft: #f2f2f3;
|
||||
--vp-c-divider: #e8e8eb;
|
||||
--vp-c-gutter: #eeeeef;
|
||||
--vp-c-text-1: #18181b;
|
||||
--vp-c-text-2: #52525b;
|
||||
--vp-c-text-3: #71717a;
|
||||
--vp-button-brand-bg: #18181b;
|
||||
--vp-button-brand-hover-bg: #2f2f33;
|
||||
--vp-button-brand-active-bg: #09090b;
|
||||
--vp-button-brand-text: #ffffff;
|
||||
--vp-home-hero-name-color: transparent;
|
||||
--vp-home-hero-name-background: linear-gradient(120deg, #18181b 15%, #6d5dfc 85%);
|
||||
--vp-home-hero-image-background-image: radial-gradient(circle, rgba(109, 93, 252, 0.24), transparent 66%);
|
||||
--vp-home-hero-image-filter: blur(48px);
|
||||
--vp-font-family-base: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans SC", sans-serif;
|
||||
--vp-font-family-mono: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--vp-c-brand-1: #a99fff;
|
||||
--vp-c-brand-2: #8d80ff;
|
||||
--vp-c-brand-3: #7565ff;
|
||||
--vp-c-brand-soft: rgba(169, 159, 255, 0.14);
|
||||
--vp-c-bg: #0b0b0d;
|
||||
--vp-c-bg-alt: #111114;
|
||||
--vp-c-bg-soft: #18181c;
|
||||
--vp-c-divider: #27272c;
|
||||
--vp-c-gutter: #18181c;
|
||||
--vp-c-text-1: #fafafa;
|
||||
--vp-c-text-2: #c4c4ca;
|
||||
--vp-c-text-3: #92929b;
|
||||
--vp-button-brand-bg: #f4f4f5;
|
||||
--vp-button-brand-hover-bg: #ffffff;
|
||||
--vp-button-brand-active-bg: #e4e4e7;
|
||||
--vp-button-brand-text: #18181b;
|
||||
--vp-home-hero-name-background: linear-gradient(120deg, #ffffff 12%, #a99fff 88%);
|
||||
}
|
||||
|
||||
html {
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
body {
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.VPNavBar {
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--vp-c-divider) 76%, transparent);
|
||||
background: color-mix(in srgb, var(--vp-c-bg) 86%, transparent) !important;
|
||||
backdrop-filter: blur(18px) saturate(160%);
|
||||
}
|
||||
|
||||
.VPNavBarTitle .logo {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
}
|
||||
|
||||
.VPNavBarTitle .title {
|
||||
font-weight: 750;
|
||||
letter-spacing: -0.03em;
|
||||
}
|
||||
|
||||
.VPNavBarMenuLink,
|
||||
.VPNavBarMenuGroup .text {
|
||||
font-size: 14px;
|
||||
font-weight: 550;
|
||||
}
|
||||
|
||||
.VPSidebar {
|
||||
border-right: 1px solid var(--vp-c-divider);
|
||||
background: color-mix(in srgb, var(--vp-c-bg) 96%, var(--vp-c-bg-alt));
|
||||
}
|
||||
|
||||
.VPSidebarItem.level-0 > .item > .text {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--vp-c-text-3);
|
||||
}
|
||||
|
||||
.VPSidebarItem.level-1 .link {
|
||||
margin: 2px 0;
|
||||
padding: 5px 10px;
|
||||
border-radius: 8px;
|
||||
transition: color 0.18s ease, background-color 0.18s ease;
|
||||
}
|
||||
|
||||
.VPSidebarItem.level-1 .link:hover,
|
||||
.VPSidebarItem.level-1.is-active > .item .link {
|
||||
background: var(--vp-c-brand-soft);
|
||||
}
|
||||
|
||||
.vp-doc {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.vp-doc h1 {
|
||||
margin-bottom: 18px;
|
||||
font-size: clamp(32px, 5vw, 44px);
|
||||
line-height: 1.12;
|
||||
letter-spacing: -0.045em;
|
||||
}
|
||||
|
||||
.vp-doc h2 {
|
||||
margin-top: 48px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid var(--vp-c-divider);
|
||||
letter-spacing: -0.025em;
|
||||
}
|
||||
|
||||
.vp-doc h3 {
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.vp-doc p,
|
||||
.vp-doc li {
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
.vp-doc a {
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
|
||||
.vp-doc div[class*="language-"] {
|
||||
margin: 22px 0;
|
||||
border: 1px solid var(--vp-c-divider);
|
||||
border-radius: 14px;
|
||||
box-shadow: 0 14px 36px rgba(24, 24, 27, 0.06);
|
||||
}
|
||||
|
||||
.dark .vp-doc div[class*="language-"] {
|
||||
box-shadow: 0 14px 38px rgba(0, 0, 0, 0.24);
|
||||
}
|
||||
|
||||
.vp-doc table {
|
||||
display: table;
|
||||
width: 100%;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.vp-doc th {
|
||||
background: var(--vp-c-bg-soft);
|
||||
}
|
||||
|
||||
.custom-block {
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.VPHome {
|
||||
padding-bottom: 72px !important;
|
||||
}
|
||||
|
||||
.VPHero {
|
||||
padding-top: 80px !important;
|
||||
}
|
||||
|
||||
.VPHero .name,
|
||||
.VPHero .text {
|
||||
letter-spacing: -0.055em;
|
||||
}
|
||||
|
||||
.VPHero .tagline {
|
||||
max-width: 620px;
|
||||
line-height: 1.65;
|
||||
}
|
||||
|
||||
.VPHero .image-bg {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.VPHero .image-src {
|
||||
max-width: 250px;
|
||||
max-height: 250px;
|
||||
}
|
||||
|
||||
.VPButton {
|
||||
border-radius: 10px !important;
|
||||
font-weight: 650 !important;
|
||||
}
|
||||
|
||||
.VPFeature {
|
||||
border: 1px solid var(--vp-c-divider) !important;
|
||||
border-radius: 16px !important;
|
||||
background: color-mix(in srgb, var(--vp-c-bg) 94%, var(--vp-c-bg-soft)) !important;
|
||||
transition: transform 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
.VPFeature:hover {
|
||||
transform: translateY(-3px);
|
||||
border-color: var(--vp-c-brand-1) !important;
|
||||
box-shadow: 0 18px 42px rgba(24, 24, 27, 0.08);
|
||||
}
|
||||
|
||||
.VPFeature .icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
border-radius: 10px;
|
||||
background: var(--vp-c-brand-soft);
|
||||
color: var(--vp-c-brand-1);
|
||||
font-family: var(--vp-font-family-mono);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.VPFeature .title {
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.VPHome .vp-doc {
|
||||
max-width: 1152px;
|
||||
margin: 36px auto 0;
|
||||
padding: 0 24px;
|
||||
}
|
||||
|
||||
.doc-paths {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 14px;
|
||||
margin: 28px 0 34px;
|
||||
}
|
||||
|
||||
.doc-path {
|
||||
display: flex;
|
||||
min-height: 154px;
|
||||
flex-direction: column;
|
||||
padding: 20px;
|
||||
border: 1px solid var(--vp-c-divider);
|
||||
border-radius: 14px;
|
||||
background: var(--vp-c-bg);
|
||||
color: var(--vp-c-text-1) !important;
|
||||
text-decoration: none !important;
|
||||
transition: transform 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
.doc-path:hover {
|
||||
transform: translateY(-3px);
|
||||
border-color: var(--vp-c-brand-1);
|
||||
box-shadow: 0 16px 36px rgba(24, 24, 27, 0.08);
|
||||
}
|
||||
|
||||
.doc-path:focus-visible {
|
||||
outline: 3px solid var(--vp-c-brand-soft);
|
||||
outline-offset: 3px;
|
||||
border-color: var(--vp-c-brand-1);
|
||||
}
|
||||
|
||||
.doc-path span {
|
||||
margin-bottom: 16px;
|
||||
color: var(--vp-c-brand-1);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.doc-path strong {
|
||||
margin-bottom: 8px;
|
||||
font-size: 17px;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.doc-path small {
|
||||
margin-top: auto;
|
||||
color: var(--vp-c-text-2);
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.VPHero {
|
||||
padding-top: 42px !important;
|
||||
}
|
||||
|
||||
.VPHero .image-src {
|
||||
max-width: 180px;
|
||||
max-height: 180px;
|
||||
}
|
||||
|
||||
.VPHome .vp-doc {
|
||||
margin-top: 20px;
|
||||
padding: 0 20px;
|
||||
}
|
||||
|
||||
.doc-paths {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.doc-path {
|
||||
min-height: 132px;
|
||||
}
|
||||
|
||||
.vp-doc table {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
html {
|
||||
scroll-behavior: auto;
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import DefaultTheme from 'vitepress/theme'
|
||||
import './custom.css'
|
||||
|
||||
export default {
|
||||
...DefaultTheme,
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
# FileCodeBox API 文档
|
||||
|
||||
## API 版本: 2.1.0
|
||||
|
||||
## 目录
|
||||
- [认证](#认证)
|
||||
- [分享接口](#分享接口)
|
||||
- [管理接口](#管理接口)
|
||||
|
||||
## 认证
|
||||
|
||||
部分接口需要在请求头中携带 `Authorization` 进行认证:
|
||||
|
||||
```
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
### 获取 Token
|
||||
|
||||
当管理面板关闭了游客上传(`openUpload=0`)时,需要先登录获取 token:
|
||||
|
||||
```bash
|
||||
curl -X POST "http://localhost:12345/admin/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"password": "<初始化时设置的管理员密码>"}'
|
||||
```
|
||||
|
||||
**响应示例:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"token": "xxx.xxx.xxx",
|
||||
"token_type": "Bearer"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 分享接口
|
||||
|
||||
### 分享文本
|
||||
|
||||
**POST** `/share/text/`
|
||||
|
||||
分享文本内容,获取分享码。
|
||||
|
||||
**请求参数:**
|
||||
|
||||
| 参数名 | 类型 | 必填 | 默认值 | 描述 |
|
||||
|-------|------|------|--------|------|
|
||||
| text | string | 是 | - | 要分享的文本内容 |
|
||||
| expire_value | integer | 否 | 1 | 过期时间值 |
|
||||
| expire_style | string | 否 | "day" | 过期时间单位(day/hour/minute/count/forever) |
|
||||
|
||||
**cURL 示例:**
|
||||
|
||||
```bash
|
||||
# 游客上传(openUpload=1 时)
|
||||
curl -X POST "http://localhost:12345/share/text/" \
|
||||
-F "text=这是要分享的文本内容" \
|
||||
-F "expire_value=1" \
|
||||
-F "expire_style=day"
|
||||
|
||||
# 需要认证时(openUpload=0 时)
|
||||
curl -X POST "http://localhost:12345/share/text/" \
|
||||
-H "Authorization: Bearer xxx.xxx.xxx" \
|
||||
-F "text=这是要分享的文本内容"
|
||||
```
|
||||
|
||||
**响应示例:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abc123"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 分享文件
|
||||
|
||||
**POST** `/share/file/`
|
||||
|
||||
上传并分享文件,获取分享码。
|
||||
|
||||
**请求参数:**
|
||||
|
||||
| 参数名 | 类型 | 必填 | 默认值 | 描述 |
|
||||
|-------|------|------|--------|------|
|
||||
| file | file | 是 | - | 要上传的文件 |
|
||||
| expire_value | integer | 否 | 1 | 过期时间值 |
|
||||
| expire_style | string | 否 | "day" | 过期时间单位(day/hour/minute/count/forever) |
|
||||
|
||||
**cURL 示例:**
|
||||
|
||||
```bash
|
||||
# 上传文件(默认1天有效期)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.txt"
|
||||
|
||||
# 上传文件(7天有效期)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.txt" \
|
||||
-F "expire_value=7" \
|
||||
-F "expire_style=day"
|
||||
|
||||
# 上传文件(可下载10次)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.txt" \
|
||||
-F "expire_value=10" \
|
||||
-F "expire_style=count"
|
||||
|
||||
# 需要认证时
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-H "Authorization: Bearer xxx.xxx.xxx" \
|
||||
-F "file=@/path/to/file.txt"
|
||||
```
|
||||
|
||||
**响应示例:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "example.txt"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 获取文件信息
|
||||
|
||||
**GET** `/share/select/`
|
||||
|
||||
通过分享码获取文件信息(直接下载文件)。
|
||||
|
||||
**请求参数:**
|
||||
|
||||
| 参数名 | 类型 | 必填 | 描述 |
|
||||
|-------|------|------|------|
|
||||
| code | string | 是 | 文件分享码 |
|
||||
|
||||
**cURL 示例:**
|
||||
|
||||
```bash
|
||||
# 通过取件码下载文件
|
||||
curl -L "http://localhost:12345/share/select/?code=abc123" -o downloaded_file
|
||||
```
|
||||
|
||||
**响应示例:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "example.txt",
|
||||
"size": 1024,
|
||||
"text": "文件内容或下载链接"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 选择文件
|
||||
|
||||
**POST** `/share/select/`
|
||||
|
||||
通过分享码选择文件。
|
||||
|
||||
**请求参数:**
|
||||
|
||||
| 参数名 | 类型 | 必填 | 描述 |
|
||||
|-------|------|------|------|
|
||||
| code | string | 是 | 文件分享码 |
|
||||
|
||||
**响应示例:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "example.txt",
|
||||
"size": 1024,
|
||||
"text": "文件内容或下载链接"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 下载文件
|
||||
|
||||
**GET** `/share/download`
|
||||
|
||||
下载分享的文件。
|
||||
|
||||
**请求参数:**
|
||||
|
||||
| 参数名 | 类型 | 必填 | 描述 |
|
||||
|-------|------|------|------|
|
||||
| key | string | 是 | 下载密钥 |
|
||||
| code | string | 是 | 文件分享码 |
|
||||
|
||||
## 管理接口
|
||||
|
||||
### 管理员登录
|
||||
|
||||
**POST** `/admin/login`
|
||||
|
||||
管理员登录获取token。
|
||||
|
||||
**请求参数:**
|
||||
|
||||
| 参数名 | 类型 | 必填 | 描述 |
|
||||
|-------|------|------|------|
|
||||
| password | string | 是 | 管理员密码 |
|
||||
|
||||
### 仪表盘数据
|
||||
|
||||
**GET** `/admin/dashboard`
|
||||
|
||||
获取系统仪表盘数据。
|
||||
|
||||
**响应示例:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"totalFiles": 100,
|
||||
"storageUsed": "1.5GB",
|
||||
"sysUptime": "10天",
|
||||
"yesterdayCount": 50,
|
||||
"yesterdaySize": "500MB",
|
||||
"todayCount": 30,
|
||||
"todaySize": "300MB"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 文件列表
|
||||
|
||||
**GET** `/admin/file/list`
|
||||
|
||||
获取系统中的文件列表。
|
||||
|
||||
**请求参数:**
|
||||
|
||||
| 参数名 | 类型 | 必填 | 默认值 | 描述 |
|
||||
|-------|------|------|--------|------|
|
||||
| page | integer | 否 | 1 | 当前页码 |
|
||||
| size | integer | 否 | 10 | 每页数量 |
|
||||
| keyword | string | 否 | "" | 搜索关键词 |
|
||||
|
||||
**响应示例:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"page": 1,
|
||||
"size": 10,
|
||||
"total": 100,
|
||||
"data": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "example.txt",
|
||||
"size": 1024,
|
||||
"created_at": "2024-01-01 12:00:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 删除文件
|
||||
|
||||
**DELETE** `/admin/file/delete`
|
||||
|
||||
删除系统中的文件。
|
||||
|
||||
**请求参数:**
|
||||
|
||||
| 参数名 | 类型 | 必填 | 描述 |
|
||||
|-------|------|------|------|
|
||||
| id | integer | 是 | 文件ID |
|
||||
|
||||
### 获取配置
|
||||
|
||||
**GET** `/admin/config/get`
|
||||
|
||||
获取系统配置信息。
|
||||
|
||||
### 更新配置
|
||||
|
||||
**PATCH** `/admin/config/update`
|
||||
|
||||
更新系统配置信息。
|
||||
|
||||
## 错误响应
|
||||
|
||||
当发生错误时,API会返回对应的错误信息:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 422,
|
||||
"detail": [
|
||||
{
|
||||
"loc": ["body", "password"],
|
||||
"msg": "密码不能为空",
|
||||
"type": "value_error"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## 状态码说明
|
||||
|
||||
- 200: 请求成功
|
||||
- 401: 未授权
|
||||
- 403: 禁止访问
|
||||
- 404: 资源不存在
|
||||
- 422: 请求参数验证错误
|
||||
- 500: 服务器内部错误
|
||||
@@ -0,0 +1,454 @@
|
||||
# 预签名上传 API 文档
|
||||
|
||||
## 概述
|
||||
|
||||
预签名上传功能提供统一的文件上传接口,根据后端存储类型自动选择最优上传方式:
|
||||
|
||||
- **S3 存储**: 返回预签名 URL,客户端直传 S3(减少服务器带宽压力)
|
||||
- **其他存储**: 返回代理上传 URL,通过服务器中转上传
|
||||
|
||||
## 上传流程
|
||||
|
||||
### 流程图
|
||||
|
||||
```
|
||||
┌─────────┐ 1. 初始化上传 ┌─────────┐
|
||||
│ 客户端 │ ──────────────────────▶ │ 服务器 │
|
||||
└─────────┘ └─────────┘
|
||||
│ │
|
||||
│◀─────── 返回 upload_url + mode ──┤
|
||||
│ │
|
||||
│ ┌─────────────────────────────────────────┐
|
||||
│ │ if mode == "direct" (S3存储) │
|
||||
│ │ 2a. PUT 文件到 upload_url (S3) │
|
||||
│ │ 3a. POST /confirm 确认上传 │
|
||||
│ │ │
|
||||
│ │ if mode == "proxy" (其他存储) │
|
||||
│ │ 2b. PUT 文件到 upload_url (服务器) │
|
||||
│ │ (自动返回分享码,无需确认) │
|
||||
│ └─────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
获取分享码
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## API 端点
|
||||
|
||||
### 1. 初始化上传
|
||||
|
||||
初始化预签名上传会话,获取上传 URL 和模式。
|
||||
|
||||
**请求**
|
||||
|
||||
```
|
||||
POST /presign/upload/init
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
**请求体**
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|
||||
| ------------ | ------- | ---- | ------ | --------------------------------------- |
|
||||
| file_name | string | ✅ | - | 文件名(含扩展名) |
|
||||
| file_size | integer | ✅ | - | 文件大小(字节) |
|
||||
| expire_value | integer | ❌ | 1 | 过期时间值 |
|
||||
| expire_style | string | ❌ | "day" | 过期类型:day/hour/minute/forever/count |
|
||||
|
||||
**请求示例**
|
||||
|
||||
```json
|
||||
{
|
||||
"file_name": "document.pdf",
|
||||
"file_size": 1048576,
|
||||
"expire_value": 7,
|
||||
"expire_style": "day"
|
||||
}
|
||||
```
|
||||
|
||||
**响应**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"upload_id": "a1b2c3d4e5f6...",
|
||||
"upload_url": "https://bucket.s3.amazonaws.com/path?X-Amz-Signature=...",
|
||||
"mode": "direct",
|
||||
"save_path": "share/data/2024/01/01/uuid/document.pdf",
|
||||
"expires_in": 900
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**响应字段说明**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| ---------- | ------- | ----------------------------------------------------- |
|
||||
| upload_id | string | 上传会话 ID,后续操作需要 |
|
||||
| upload_url | string | 上传目标 URL |
|
||||
| mode | string | 上传模式:`direct`(直传 S3)或 `proxy`(服务器代理) |
|
||||
| save_path | string | 文件存储路径 |
|
||||
| expires_in | integer | URL 有效期(秒),默认 900 秒(15 分钟) |
|
||||
|
||||
**错误响应**
|
||||
|
||||
| 状态码 | 说明 |
|
||||
| ------ | ------------------------------ |
|
||||
| 400 | 过期时间类型错误 |
|
||||
| 403 | 文件大小超过限制 / IP 频率限制 |
|
||||
|
||||
---
|
||||
|
||||
### 2a. 直传模式 - 上传文件到 S3
|
||||
|
||||
当 `mode == "direct"` 时,客户端直接将文件 PUT 到返回的预签名 URL。
|
||||
|
||||
**请求**
|
||||
|
||||
```
|
||||
PUT {upload_url}
|
||||
Content-Type: application/octet-stream
|
||||
|
||||
[文件二进制内容]
|
||||
```
|
||||
|
||||
**注意事项**
|
||||
|
||||
- 直接使用返回的 `upload_url`,不要修改
|
||||
- Content-Type 建议使用 `application/octet-stream`
|
||||
- 这是直接请求 S3,不经过服务器
|
||||
|
||||
**JavaScript 示例**
|
||||
|
||||
```javascript
|
||||
const response = await fetch(uploadUrl, {
|
||||
method: 'PUT',
|
||||
body: file,
|
||||
headers: {
|
||||
'Content-Type': 'application/octet-stream',
|
||||
},
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
// 上传成功,调用确认接口
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2b. 代理模式 - 上传文件到服务器
|
||||
|
||||
当 `mode == "proxy"` 时,客户端将文件 PUT 到服务器代理端点。
|
||||
|
||||
**请求**
|
||||
|
||||
```
|
||||
PUT /presign/upload/proxy/{upload_id}
|
||||
Content-Type: multipart/form-data
|
||||
|
||||
file: [文件]
|
||||
```
|
||||
|
||||
**路径参数**
|
||||
|
||||
| 参数 | 说明 |
|
||||
| --------- | ------------------------- |
|
||||
| upload_id | 初始化时返回的上传会话 ID |
|
||||
|
||||
**响应**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"code": "123456",
|
||||
"name": "document.pdf"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**注意**: 代理模式上传成功后直接返回分享码,无需调用确认接口。
|
||||
|
||||
**错误响应**
|
||||
|
||||
| 状态码 | 说明 |
|
||||
| ------ | --------------------------------------- |
|
||||
| 400 | 文件大小与声明不符 / 会话不支持代理上传 |
|
||||
| 404 | 上传会话不存在或已过期 |
|
||||
| 500 | 文件保存失败 |
|
||||
|
||||
---
|
||||
|
||||
### 3. 确认上传(仅直传模式)
|
||||
|
||||
直传模式下,客户端完成 S3 上传后调用此接口确认并获取分享码。
|
||||
|
||||
**请求**
|
||||
|
||||
```
|
||||
POST /presign/upload/confirm/{upload_id}
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
**路径参数**
|
||||
|
||||
| 参数 | 说明 |
|
||||
| --------- | ------------------------- |
|
||||
| upload_id | 初始化时返回的上传会话 ID |
|
||||
|
||||
**请求体**
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|
||||
| ------------ | ------- | ---- | ------ | ---------- |
|
||||
| expire_value | integer | ❌ | 1 | 过期时间值 |
|
||||
| expire_style | string | ❌ | "day" | 过期类型 |
|
||||
|
||||
**请求示例**
|
||||
|
||||
```json
|
||||
{
|
||||
"expire_value": 7,
|
||||
"expire_style": "day"
|
||||
}
|
||||
```
|
||||
|
||||
**响应**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"code": "123456",
|
||||
"name": "document.pdf"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**错误响应**
|
||||
|
||||
| 状态码 | 说明 |
|
||||
| ------ | --------------------------------------------- |
|
||||
| 400 | 会话不支持直传确认 |
|
||||
| 404 | 上传会话不存在或已过期 / 文件未上传或上传失败 |
|
||||
|
||||
---
|
||||
|
||||
### 4. 查询上传状态
|
||||
|
||||
查询上传会话的当前状态。
|
||||
|
||||
**请求**
|
||||
|
||||
```
|
||||
GET /presign/upload/status/{upload_id}
|
||||
```
|
||||
|
||||
**响应**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"upload_id": "a1b2c3d4e5f6...",
|
||||
"file_name": "document.pdf",
|
||||
"file_size": 1048576,
|
||||
"mode": "direct",
|
||||
"created_at": "2024-01-01T12:00:00",
|
||||
"expires_at": "2024-01-01T12:15:00",
|
||||
"is_expired": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**错误响应**
|
||||
|
||||
| 状态码 | 说明 |
|
||||
| ------ | -------------- |
|
||||
| 404 | 上传会话不存在 |
|
||||
|
||||
---
|
||||
|
||||
### 5. 取消上传
|
||||
|
||||
取消上传会话并清理相关资源。
|
||||
|
||||
**请求**
|
||||
|
||||
```
|
||||
DELETE /presign/upload/{upload_id}
|
||||
```
|
||||
|
||||
**响应**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"message": "上传会话已取消"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**错误响应**
|
||||
|
||||
| 状态码 | 说明 |
|
||||
| ------ | -------------- |
|
||||
| 404 | 上传会话不存在 |
|
||||
|
||||
---
|
||||
|
||||
## 前端集成示例
|
||||
|
||||
### 完整上传流程(JavaScript/TypeScript)
|
||||
|
||||
```typescript
|
||||
interface PresignInitResponse {
|
||||
upload_id: string
|
||||
upload_url: string
|
||||
mode: 'direct' | 'proxy'
|
||||
save_path: string
|
||||
expires_in: number
|
||||
}
|
||||
|
||||
interface UploadResult {
|
||||
code: string
|
||||
name: string
|
||||
}
|
||||
|
||||
async function uploadFile(
|
||||
file: File,
|
||||
expireValue: number = 1,
|
||||
expireStyle: string = 'day'
|
||||
): Promise<UploadResult> {
|
||||
// 1. 初始化上传
|
||||
const initResponse = await fetch('/presign/upload/init', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
file_name: file.name,
|
||||
file_size: file.size,
|
||||
expire_value: expireValue,
|
||||
expire_style: expireStyle,
|
||||
}),
|
||||
})
|
||||
|
||||
const initData = await initResponse.json()
|
||||
if (initData.code !== 200) {
|
||||
throw new Error(initData.detail)
|
||||
}
|
||||
|
||||
const { upload_id, upload_url, mode } = initData.detail as PresignInitResponse
|
||||
|
||||
// 2. 根据模式上传文件
|
||||
if (mode === 'direct') {
|
||||
// 直传模式:上传到S3
|
||||
const uploadResponse = await fetch(upload_url, {
|
||||
method: 'PUT',
|
||||
body: file,
|
||||
headers: { 'Content-Type': 'application/octet-stream' },
|
||||
})
|
||||
|
||||
if (!uploadResponse.ok) {
|
||||
throw new Error('S3上传失败')
|
||||
}
|
||||
|
||||
// 3. 确认上传
|
||||
const confirmResponse = await fetch(
|
||||
`/presign/upload/confirm/${upload_id}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
expire_value: expireValue,
|
||||
expire_style: expireStyle,
|
||||
}),
|
||||
}
|
||||
)
|
||||
|
||||
const confirmData = await confirmResponse.json()
|
||||
if (confirmData.code !== 200) {
|
||||
throw new Error(confirmData.detail)
|
||||
}
|
||||
|
||||
return confirmData.detail
|
||||
} else {
|
||||
// 代理模式:上传到服务器
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
|
||||
const uploadResponse = await fetch(upload_url, {
|
||||
method: 'PUT',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
const uploadData = await uploadResponse.json()
|
||||
if (uploadData.code !== 200) {
|
||||
throw new Error(uploadData.detail)
|
||||
}
|
||||
|
||||
return uploadData.detail
|
||||
}
|
||||
}
|
||||
|
||||
// 使用示例
|
||||
const file = document.querySelector('input[type="file"]').files[0]
|
||||
const result = await uploadFile(file, 7, 'day')
|
||||
console.log('分享码:', result.code)
|
||||
```
|
||||
|
||||
### Vue 3 组件示例
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div>
|
||||
<input type="file" @change="handleFileSelect" />
|
||||
<button @click="upload" :disabled="!selectedFile || uploading">
|
||||
{{ uploading ? '上传中...' : '上传' }}
|
||||
</button>
|
||||
<div v-if="shareCode">分享码: {{ shareCode }}</div>
|
||||
<div v-if="error" class="error">{{ error }}</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
|
||||
const selectedFile = ref<File | null>(null)
|
||||
const uploading = ref(false)
|
||||
const shareCode = ref('')
|
||||
const error = ref('')
|
||||
|
||||
function handleFileSelect(e: Event) {
|
||||
const input = e.target as HTMLInputElement
|
||||
selectedFile.value = input.files?.[0] || null
|
||||
}
|
||||
|
||||
async function upload() {
|
||||
if (!selectedFile.value) return
|
||||
|
||||
uploading.value = true
|
||||
error.value = ''
|
||||
|
||||
try {
|
||||
const result = await uploadFile(selectedFile.value)
|
||||
shareCode.value = result.code
|
||||
} catch (e) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
uploading.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **会话有效期**: 上传会话默认 15 分钟后过期,请在有效期内完成上传
|
||||
2. **文件大小限制**: 受系统配置 `uploadSize` 限制
|
||||
3. **过期类型**: 支持 `day`、`hour`、`minute`、`forever`、`count`
|
||||
4. **CORS**: 直传模式下,S3 需要配置正确的 CORS 策略
|
||||
5. **重试机制**: 建议实现上传失败重试逻辑
|
||||
@@ -0,0 +1,48 @@
|
||||
# Changelog
|
||||
|
||||
## [2.5.3](https://github.com/vastsa/FileCodeBox/compare/v2.5.2...v2.5.3) (2026-07-23)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add magic-byte checks, login rate limits, and non-root Docker ([eda0a31](https://github.com/vastsa/FileCodeBox/commit/eda0a3127ab562b6a2cf828c0df4a93933c44526))
|
||||
* magic-byte file checks, admin login rate limit, non-root Docker ([0ee2f04](https://github.com/vastsa/FileCodeBox/commit/0ee2f046dd057fecceaee1059d72d67de3038f19))
|
||||
|
||||
## [2.5.2](https://github.com/vastsa/FileCodeBox/compare/v2.5.1...v2.5.2) (2026-07-23)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* harden share expiry, download token, quota SQL, and CORS ([ae77026](https://github.com/vastsa/FileCodeBox/commit/ae7702603a99dc77b9b48e78746058b2a74b0bf5))
|
||||
* harden share expiry, download token, quota SQL, and CORS ([a41693f](https://github.com/vastsa/FileCodeBox/commit/a41693f90ded0234e0883c399254319bef04924a))
|
||||
|
||||
## [2.5.1](https://github.com/vastsa/FileCodeBox/compare/v2.5.0...v2.5.1) (2026-07-21)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* patch CVE dependencies and path traversal risks ([00f3abd](https://github.com/vastsa/FileCodeBox/commit/00f3abd3b20fe2344e4dbf8d53714773e23a1050))
|
||||
|
||||
## [2.5.0](https://github.com/vastsa/FileCodeBox/compare/v2.4.0...v2.5.0) (2026-07-11)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add global storage capacity limit ([818dd47](https://github.com/vastsa/FileCodeBox/commit/818dd47b2a4136d4b0d68b2484ac2d01a7ae6a3c))
|
||||
* automate version releases ([ee8f908](https://github.com/vastsa/FileCodeBox/commit/ee8f9082ab59418a4a7721a05fc358215230981f))
|
||||
* configure admin session lifetime ([#484](https://github.com/vastsa/FileCodeBox/issues/484)) ([93ff291](https://github.com/vastsa/FileCodeBox/commit/93ff291366aaac9d04c5259d3ecf01b20aed3fd0))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* build frontend on native Docker platform ([2c51384](https://github.com/vastsa/FileCodeBox/commit/2c51384c80a9ff3f4eb98eb876759b8949dfae89))
|
||||
* harden automated release workflow ([46883c9](https://github.com/vastsa/FileCodeBox/commit/46883c90ff52894631fe53bbd9b9c4100a7b27f1))
|
||||
* harden share retrieval and admin visibility ([#482](https://github.com/vastsa/FileCodeBox/issues/482), [#480](https://github.com/vastsa/FileCodeBox/issues/480)) ([8d7d856](https://github.com/vastsa/FileCodeBox/commit/8d7d856c62d73badd0797eb4daec8d2ff10a403a))
|
||||
* resolve docs dependency audit warnings ([36300ef](https://github.com/vastsa/FileCodeBox/commit/36300ef54ee09081a6cf6a5fe4e69cee7aad0162))
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- 增加全局存储容量上限配置,并对普通上传、分片上传、预签名直传和后台文件分享统一执行并发安全的容量预留。
|
||||
- 增加存储预留迁移及过期上传清理,失败、取消或过期的上传会释放预留容量。
|
||||
@@ -0,0 +1,332 @@
|
||||
# FileCodeBox API Documentation
|
||||
|
||||
## API Version: 2.1.0
|
||||
|
||||
## Table of Contents
|
||||
- [Authentication](#authentication)
|
||||
- [Share API](#share-api)
|
||||
- [Admin API](#admin-api)
|
||||
|
||||
## Authentication
|
||||
|
||||
Some APIs require `Authorization` header for authentication:
|
||||
|
||||
```
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
### Get Token
|
||||
|
||||
When guest upload is disabled in admin panel (`openUpload=0`), you need to login first:
|
||||
|
||||
```bash
|
||||
curl -X POST "http://localhost:12345/admin/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"password": "<admin-password-set-during-setup>"}'
|
||||
```
|
||||
|
||||
**Response Example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"token": "xxx.xxx.xxx",
|
||||
"token_type": "Bearer"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Share API
|
||||
|
||||
### Share Text
|
||||
|
||||
**POST** `/share/text/`
|
||||
|
||||
Share text content and get a share code.
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Required | Default | Description |
|
||||
|-----------|------|----------|---------|-------------|
|
||||
| text | string | Yes | - | Text content to share |
|
||||
| expire_value | integer | No | 1 | Expiration time value |
|
||||
| expire_style | string | No | "day" | Expiration time unit(day/hour/minute/count/forever) |
|
||||
|
||||
**cURL Example:**
|
||||
|
||||
```bash
|
||||
# Guest upload (when openUpload=1)
|
||||
curl -X POST "http://localhost:12345/share/text/" \
|
||||
-F "text=This is the text content to share" \
|
||||
-F "expire_value=1" \
|
||||
-F "expire_style=day"
|
||||
|
||||
# When authentication required (openUpload=0)
|
||||
curl -X POST "http://localhost:12345/share/text/" \
|
||||
-H "Authorization: Bearer xxx.xxx.xxx" \
|
||||
-F "text=This is the text content to share"
|
||||
```
|
||||
|
||||
**Response Example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abc123"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Share File
|
||||
|
||||
**POST** `/share/file/`
|
||||
|
||||
Upload and share a file, get a share code.
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Required | Default | Description |
|
||||
|-----------|------|----------|---------|-------------|
|
||||
| file | file | Yes | - | File to upload |
|
||||
| expire_value | integer | No | 1 | Expiration time value |
|
||||
| expire_style | string | No | "day" | Expiration time unit(day/hour/minute/count/forever) |
|
||||
|
||||
**cURL Example:**
|
||||
|
||||
```bash
|
||||
# Upload file (default 1 day expiration)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.txt"
|
||||
|
||||
# Upload file (7 days expiration)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.txt" \
|
||||
-F "expire_value=7" \
|
||||
-F "expire_style=day"
|
||||
|
||||
# Upload file (10 downloads limit)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.txt" \
|
||||
-F "expire_value=10" \
|
||||
-F "expire_style=count"
|
||||
|
||||
# When authentication required
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-H "Authorization: Bearer xxx.xxx.xxx" \
|
||||
-F "file=@/path/to/file.txt"
|
||||
```
|
||||
|
||||
**Response Example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "example.txt"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Get File Info
|
||||
|
||||
**GET** `/share/select/`
|
||||
|
||||
Get file information by share code (direct file download).
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| code | string | Yes | File share code |
|
||||
|
||||
**cURL Example:**
|
||||
|
||||
```bash
|
||||
# Download file by extraction code
|
||||
curl -L "http://localhost:12345/share/select/?code=abc123" -o downloaded_file
|
||||
```
|
||||
|
||||
**Response Example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "example.txt",
|
||||
"size": 1024,
|
||||
"text": "File content or download link"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Select File
|
||||
|
||||
**POST** `/share/select/`
|
||||
|
||||
Select file by share code.
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| code | string | Yes | File share code |
|
||||
|
||||
**Response Example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"code": "abc123",
|
||||
"name": "example.txt",
|
||||
"size": 1024,
|
||||
"text": "File content or download link"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Download File
|
||||
|
||||
**GET** `/share/download`
|
||||
|
||||
Download shared file.
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| key | string | Yes | Download key |
|
||||
| code | string | Yes | File share code |
|
||||
|
||||
## Admin API
|
||||
|
||||
### Admin Login
|
||||
|
||||
**POST** `/admin/login`
|
||||
|
||||
Admin login to get token.
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| password | string | Yes | Admin password |
|
||||
|
||||
### Dashboard Data
|
||||
|
||||
**GET** `/admin/dashboard`
|
||||
|
||||
Get system dashboard data.
|
||||
|
||||
**Response Example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"totalFiles": 100,
|
||||
"storageUsed": "1.5GB",
|
||||
"sysUptime": "10 days",
|
||||
"yesterdayCount": 50,
|
||||
"yesterdaySize": "500MB",
|
||||
"todayCount": 30,
|
||||
"todaySize": "300MB"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### File List
|
||||
|
||||
**GET** `/admin/file/list`
|
||||
|
||||
Get system file list.
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Required | Default | Description |
|
||||
|-----------|------|----------|---------|-------------|
|
||||
| page | integer | No | 1 | Current page |
|
||||
| size | integer | No | 10 | Page size |
|
||||
| keyword | string | No | "" | Search keyword |
|
||||
|
||||
**Response Example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
"detail": {
|
||||
"page": 1,
|
||||
"size": 10,
|
||||
"total": 100,
|
||||
"data": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "example.txt",
|
||||
"size": 1024,
|
||||
"created_at": "2024-01-01 12:00:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Delete File
|
||||
|
||||
**DELETE** `/admin/file/delete`
|
||||
|
||||
Delete file from system.
|
||||
|
||||
**Parameters:**
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| id | integer | Yes | File ID |
|
||||
|
||||
### Get Config
|
||||
|
||||
**GET** `/admin/config/get`
|
||||
|
||||
Get system configuration.
|
||||
|
||||
### Update Config
|
||||
|
||||
**PATCH** `/admin/config/update`
|
||||
|
||||
Update system configuration.
|
||||
|
||||
## Error Response
|
||||
|
||||
When an error occurs, the API will return corresponding error message:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 422,
|
||||
"detail": [
|
||||
{
|
||||
"loc": ["body", "password"],
|
||||
"msg": "Password cannot be empty",
|
||||
"type": "value_error"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Status Codes
|
||||
|
||||
- 200: Success
|
||||
- 401: Unauthorized
|
||||
- 403: Forbidden
|
||||
- 404: Not Found
|
||||
- 422: Validation Error
|
||||
- 500: Internal Server Error
|
||||
@@ -0,0 +1,8 @@
|
||||
## [Unreleased]
|
||||
|
||||
<!-- Current release: 2.5.3 x-release-please-version -->
|
||||
|
||||
### Added
|
||||
|
||||
- Added a global storage capacity limit with concurrency-safe reservations for regular, chunked, presigned, and admin file uploads.
|
||||
- Added the storage reservation migration and stale upload cleanup so failed, cancelled, or expired uploads release reserved capacity.
|
||||
@@ -0,0 +1,214 @@
|
||||
# Configuration Guide
|
||||
|
||||
FileCodeBox provides rich configuration options. Prefer the admin panel; directly editing the database can introduce invalid types or break security settings.
|
||||
|
||||
## Configuration Methods
|
||||
|
||||
FileCodeBox supports two configuration methods:
|
||||
|
||||
1. **Admin Panel Configuration** (Recommended): Access `/admin` to enter the admin panel and modify settings on the settings page
|
||||
2. **Database Configuration**: Configuration is stored in the `data/filecodebox.db` database
|
||||
|
||||
::: tip Note
|
||||
On first startup, the system uses default configuration from `core/settings.py`. Modified configurations are saved to the database.
|
||||
:::
|
||||
|
||||
## Basic Settings
|
||||
|
||||
### Site Information
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `name` | string | `文件快递柜 - FileCodeBox` | Site name, displayed in page title and navigation bar |
|
||||
| `description` | string | `开箱即用的文件快传系统` | Site description, used for SEO |
|
||||
| `keywords` | string | `FileCodeBox, 文件快递柜...` | Site keywords, used for SEO |
|
||||
| `serverHost` | string | `0.0.0.0` | Service listening address |
|
||||
| `serverPort` | int | `12345` | Service listening port |
|
||||
| `serverWorkers` | int | `1` | Worker count; keep one worker for SQLite deployments |
|
||||
|
||||
### Notification Settings
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `notify_title` | string | `系统通知` | Notification title |
|
||||
| `notify_content` | string | Welcome message | Notification content, supports HTML |
|
||||
| `page_explain` | string | Legal disclaimer | Footer explanation text |
|
||||
| `robotsText` | string | `User-agent: *\nDisallow: /` | robots.txt content |
|
||||
|
||||
## Upload Settings
|
||||
|
||||
### File Upload Limits
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `openUpload` | int | `1` | Enable upload functionality (1=enabled, 0=disabled) |
|
||||
| `uploadSize` | int | `10485760` | Maximum single file upload size (bytes), default 10MB |
|
||||
| `enableChunk` | int | `0` | Enable chunked upload (1=enabled, 0=disabled) |
|
||||
| `allowed_file_types` | list | `["*"]` | Allowed extensions; `*` allows every file type |
|
||||
|
||||
::: warning Note
|
||||
`uploadSize` is in bytes. 10MB = 10 * 1024 * 1024 = 10485760 bytes
|
||||
:::
|
||||
|
||||
### Upload Rate Limiting
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `uploadMinute` | int | `1` | Upload limit time window (minutes) |
|
||||
| `uploadCount` | int | `10` | Maximum uploads allowed within the time window |
|
||||
|
||||
Example: Default configuration allows up to 10 uploads per minute.
|
||||
|
||||
|
||||
### File Expiration Settings
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `expireStyle` | list | `["day","hour","minute","forever","count"]` | Available expiration methods |
|
||||
| `max_save_seconds` | int | `0` | Maximum file retention time (seconds), 0 means no limit |
|
||||
|
||||
Expiration methods explained:
|
||||
- `day` - Expire by days
|
||||
- `hour` - Expire by hours
|
||||
- `minute` - Expire by minutes
|
||||
- `forever` - Never expire
|
||||
- `count` - Expire by download count
|
||||
|
||||
## Theme Settings
|
||||
|
||||
### Theme Selection
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `themesSelect` | string | `themes/2024` | Currently active theme |
|
||||
| `themesChoices` | list | See below | Available themes list |
|
||||
|
||||
Default available themes:
|
||||
```json
|
||||
[
|
||||
{
|
||||
"name": "2023",
|
||||
"key": "themes/2023",
|
||||
"author": "Lan",
|
||||
"version": "1.0"
|
||||
},
|
||||
{
|
||||
"name": "2024",
|
||||
"key": "themes/2024",
|
||||
"author": "Lan",
|
||||
"version": "1.0"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
### Interface Style
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `opacity` | float | `0.9` | Interface opacity (0-1) |
|
||||
| `background` | string | `""` | Custom background image URL, empty uses default background |
|
||||
|
||||
## Admin Settings
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `admin_token` | string | Set during setup | Admin login password |
|
||||
| `showAdminAddr` | int | `0` | Show admin panel entry on homepage (1=show, 0=hide) |
|
||||
| `adminSessionExpire` | int | `2592000` | Admin session lifetime in seconds (30 days) |
|
||||
|
||||
::: danger Security Warning
|
||||
The setup page is shown automatically while the system is uninitialized. Complete setup before exposing a production service to the public internet.
|
||||
:::
|
||||
|
||||
## Security Settings
|
||||
|
||||
### Error Rate Limiting
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `errorMinute` | int | `1` | Error limit time window (minutes) |
|
||||
| `errorCount` | int | `10` | Maximum errors allowed within the time window |
|
||||
| `trustedProxies` | list | `[]` | Trusted reverse-proxy IPs used to resolve client addresses |
|
||||
|
||||
This setting prevents brute-force attacks on extraction codes.
|
||||
|
||||
## Storage Settings
|
||||
|
||||
### Storage Type
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `file_storage` | string | `local` | Storage backend type |
|
||||
| `storage_path` | string | `""` | Custom storage path |
|
||||
| `storageLimit` | int | `0` | Total storage quota in bytes; 0 means unlimited |
|
||||
|
||||
Supported storage types:
|
||||
- `local` - Local storage
|
||||
- `s3` - S3-compatible storage (AWS S3, Aliyun OSS, MinIO, etc.)
|
||||
- `onedrive` - OneDrive storage
|
||||
- `webdav` - WebDAV storage
|
||||
- `opendal` - OpenDAL storage
|
||||
|
||||
For detailed storage configuration, see [Storage Configuration](/en/guide/storage).
|
||||
|
||||
## Configuration Examples
|
||||
|
||||
### Example 1: Small Personal Use
|
||||
|
||||
Suitable for personal or small team use with relaxed limits:
|
||||
|
||||
```python
|
||||
{
|
||||
"name": "My File Share",
|
||||
"uploadSize": 52428800, # 50MB
|
||||
"uploadMinute": 5, # 5 minutes
|
||||
"uploadCount": 20, # Max 20 uploads
|
||||
"expireStyle": ["day", "hour", "forever"],
|
||||
"showAdminAddr": 1
|
||||
}
|
||||
```
|
||||
|
||||
### Example 2: Public Service
|
||||
|
||||
Suitable for public services requiring stricter limits:
|
||||
|
||||
```python
|
||||
{
|
||||
"name": "Public File Box",
|
||||
"uploadSize": 10485760, # 10MB
|
||||
"uploadMinute": 1, # 1 minute
|
||||
"uploadCount": 5, # Max 5 uploads
|
||||
"errorMinute": 5, # 5 minutes
|
||||
"errorCount": 3, # Max 3 errors
|
||||
"expireStyle": ["hour", "minute", "count"],
|
||||
"max_save_seconds": 86400, # Max retention 1 day
|
||||
"showAdminAddr": 0
|
||||
}
|
||||
```
|
||||
|
||||
### Example 3: Enterprise Internal Use
|
||||
|
||||
Suitable for enterprise internal use with large file and chunked upload support:
|
||||
|
||||
```python
|
||||
{
|
||||
"name": "Enterprise File Transfer",
|
||||
"uploadSize": 1073741824, # 1GB
|
||||
"enableChunk": 1, # Enable chunked upload
|
||||
"uploadMinute": 10, # 10 minutes
|
||||
"uploadCount": 100, # Max 100 uploads
|
||||
"expireStyle": ["day", "forever"],
|
||||
"file_storage": "s3", # Use S3 storage
|
||||
"showAdminAddr": 1
|
||||
}
|
||||
```
|
||||
|
||||
::: warning Configuration examples
|
||||
These dictionaries illustrate combinations of values; they are not editable configuration files. Set the admin password through first-run setup or the admin panel.
|
||||
:::
|
||||
|
||||
## Next Steps
|
||||
|
||||
- [Storage Configuration](/en/guide/storage) - Learn how to configure different storage backends
|
||||
- [Security Settings](/en/guide/security) - Learn how to enhance system security
|
||||
- [File Sharing](/en/guide/share) - Learn about file sharing features
|
||||
@@ -0,0 +1,81 @@
|
||||
# Getting Started
|
||||
|
||||
## Introduction
|
||||
|
||||
FileCodeBox is a simple and efficient file sharing tool that supports temporary file transfer, sharing, and management. This guide will help you quickly deploy and use FileCodeBox.
|
||||
|
||||
## Features
|
||||
|
||||
- 🚀 Quick Deployment: Support Docker one-click deployment
|
||||
- 🔒 Secure & Reliable: File access requires extraction code
|
||||
- ⏱️ Time Control: Support setting file expiration time
|
||||
- 📊 Download Limit: Can limit file download times
|
||||
- 🖼️ File Preview: Support preview of images, videos, audio, and other formats
|
||||
- 📱 Responsive Design: Perfect adaptation for mobile and desktop
|
||||
|
||||
## Deployment Methods
|
||||
|
||||
### Docker Deployment (Recommended)
|
||||
|
||||
```bash
|
||||
docker run -d --restart unless-stopped \
|
||||
-p 12345:12345 \
|
||||
-v fcb-data:/app/data \
|
||||
--name filecodebox \
|
||||
lanol/filecodebox:latest
|
||||
```
|
||||
|
||||
The named volume persists configuration and uploaded files across container upgrades.
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `HOST` | `0.0.0.0` | Service listening address |
|
||||
| `PORT` | `12345` | Service port |
|
||||
| `WORKERS` | `1` | Worker count; keep one worker for SQLite deployments |
|
||||
| `LOG_LEVEL` | `info` | `debug`, `info`, `warning`, or `error` |
|
||||
|
||||
### Manual Deployment
|
||||
|
||||
1. Clone the repository
|
||||
```bash
|
||||
git clone https://github.com/vastsa/FileCodeBox.git
|
||||
```
|
||||
|
||||
2. Install dependencies
|
||||
```bash
|
||||
cd FileCodeBox
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. Start the service
|
||||
```bash
|
||||
python main.py
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
1. Access the System
|
||||
Open browser and visit `http://localhost:12345`
|
||||
|
||||
2. Upload Files
|
||||
- Click upload button or drag files to upload area
|
||||
- Set file expiration time and download limit
|
||||
- Get share link and extraction code
|
||||
|
||||
3. Download Files
|
||||
- Visit share link
|
||||
- Enter extraction code
|
||||
- Download file
|
||||
|
||||
4. Admin Panel
|
||||
- Open `http://localhost:12345` on first run and complete setup
|
||||
- Visit `http://localhost:12345/#/admin`
|
||||
- Enter the admin password set during setup
|
||||
- Enter admin panel
|
||||
- View system information, files, activity records, and configuration
|
||||
|
||||
## Next Steps
|
||||
|
||||
- [Storage Configuration](/en/guide/storage) - Learn how to configure different storage methods
|
||||
- [Security Settings](/en/guide/security) - Learn how to enhance system security
|
||||
- [API Documentation](/en/api/) - Learn how to integrate through API
|
||||
@@ -0,0 +1,243 @@
|
||||
<div align="center">
|
||||
|
||||
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/static/banners/img_1.png" alt="FileCodeBox Logo">
|
||||
|
||||
<p><em>Share text and files anonymously with a passcode, like picking up a package</em></p>
|
||||
|
||||
[](https://github.com/vastsa/FileCodeBox/stargazers)
|
||||
[](https://github.com/vastsa/FileCodeBox/network)
|
||||
[](https://github.com/vastsa/FileCodeBox/issues)
|
||||
[](https://github.com/vastsa/FileCodeBox/blob/master/LICENSE)
|
||||
[](https://qm.qq.com/q/PemPzhdEIM)
|
||||
[](https://www.python.org)
|
||||
[](https://fastapi.tiangolo.com)
|
||||
[](https://v3.vuejs.org)
|
||||
|
||||
</div>
|
||||
|
||||
## 📝 Introduction
|
||||
|
||||
FileCodeBox is a lightweight file sharing tool developed with FastAPI + Vue3. It allows users to share text and files easily, where recipients only need a passcode to retrieve the files, just like picking up a package from a delivery locker.
|
||||
|
||||
## 🖼️ Preview
|
||||
|
||||
<div align="center">
|
||||
<h3>
|
||||
<a href="https://github.com/vastsa/FileCodeBoxFronted" target="_blank">
|
||||
<img src="https://img.shields.io/badge/Frontend-FileCodeBoxFronted-blue?style=for-the-badge&logo=github" alt="Frontend Repository">
|
||||
</a>
|
||||
|
||||
<a href="https://share.lanol.cn" target="_blank">
|
||||
<img src="https://img.shields.io/badge/Demo-share.lanol.cn-green?style=for-the-badge&logo=internet-explorer" alt="Demo Site">
|
||||
</a>
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
|
||||
## 🎯 Use Cases
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>📁 Temporary File Sharing</h4>
|
||||
Quick file sharing without registration
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>📝 Quick Text Sharing</h4>
|
||||
Share code snippets and text content
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🕶️ Anonymous Transfer</h4>
|
||||
Privacy-protected file transfer
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>💾 Temporary Storage</h4>
|
||||
File storage with expiration time
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🔄 Cross-platform Transfer</h4>
|
||||
Quick file transfer between devices
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🌐 Private Share Service</h4>
|
||||
Build your own file sharing service
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## ✨ Core Features
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>🚀 Lightweight</h4>
|
||||
Based on FastAPI + SQLite3 + Vue3 + ElementUI
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>📤 Easy Upload</h4>
|
||||
Support copy-paste and drag-drop
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>📦 Multiple Types</h4>
|
||||
Support text and various file types
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>🔒 Security</h4>
|
||||
|
||||
- IP upload limits
|
||||
- Error attempt limits
|
||||
- File expiration
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🎫 Passcode Sharing</h4>
|
||||
Random codes with customizable limits
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🌍 Multi-language</h4>
|
||||
Support for Simplified Chinese, Traditional Chinese, and English
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>🎭 Anonymous</h4>
|
||||
No registration required
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🛠 Admin Panel</h4>
|
||||
File and system management
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🐳 Docker</h4>
|
||||
One-click deployment
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>💾 Storage Options</h4>
|
||||
Local, S3, OneDrive support
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>📱 Responsive</h4>
|
||||
Mobile-friendly design
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>💻 CLI Support</h4>
|
||||
Command-line download
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### Docker Deployment
|
||||
|
||||
```bash
|
||||
docker run -d --restart unless-stopped -p 12345:12345 -v fcb-data:/app/data --name filecodebox lanol/filecodebox:latest
|
||||
```
|
||||
|
||||
### Manual Deployment
|
||||
|
||||
1. Clone the repository
|
||||
```bash
|
||||
git clone https://github.com/vastsa/FileCodeBox.git
|
||||
```
|
||||
|
||||
2. Install dependencies
|
||||
```bash
|
||||
cd FileCodeBox
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. Start the service
|
||||
```bash
|
||||
python main.py
|
||||
```
|
||||
|
||||
## 📖 Usage Guide
|
||||
|
||||
### Share Files
|
||||
1. Open the website, click "Share File"
|
||||
2. Select or drag files
|
||||
3. Set expiration time and count
|
||||
4. Get the passcode
|
||||
|
||||
### Retrieve Files
|
||||
1. Open the website, enter passcode
|
||||
2. Click retrieve
|
||||
3. Download file or view text
|
||||
|
||||
### Admin Panel
|
||||
1. Visit `/admin`
|
||||
2. Enter admin password
|
||||
3. Manage files and settings
|
||||
|
||||
## 🛠 Development Guide
|
||||
|
||||
### Project Structure
|
||||
```
|
||||
FileCodeBox/
|
||||
├── apps/ # Application code
|
||||
│ ├── admin/ # Admin backend
|
||||
│ └── base/ # Base functions
|
||||
├── core/ # Core functions
|
||||
├── data/ # Data directory
|
||||
└── fcb-fronted/ # Frontend code
|
||||
```
|
||||
|
||||
### Development Environment
|
||||
- Python 3.8+
|
||||
- Node.js 14+
|
||||
- Vue 3
|
||||
- FastAPI
|
||||
|
||||
### Local Development
|
||||
1. Backend development
|
||||
```bash
|
||||
python main.py
|
||||
```
|
||||
|
||||
2. Frontend development
|
||||
```bash
|
||||
cd fcb-fronted
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
1. Fork the project
|
||||
2. Create your feature branch `git checkout -b feature/xxx`
|
||||
3. Commit your changes `git commit -m 'Add xxx'`
|
||||
4. Push to the branch `git push origin feature/xxx`
|
||||
5. Open a Pull Request
|
||||
|
||||
## ❓ FAQ
|
||||
|
||||
### Q: How to modify upload size limit?
|
||||
A: Change `uploadSize` in admin panel
|
||||
|
||||
### Q: How to configure storage engine?
|
||||
A: Select storage engine and configure parameters in admin panel
|
||||
|
||||
### Q: How to backup data?
|
||||
A: Backup the `data` directory
|
||||
|
||||
For more questions, visit [Wiki](https://github.com/vastsa/FileCodeBox/wiki/常见问题)
|
||||
|
||||
## 😀 Project Statistics and Analytics
|
||||
|
||||
<div align="center">
|
||||
<a href="https://hellogithub.com/repository/75ad7ffedd404a6485b4d621ec5b47e6" target="_blank"><img src="https://api.hellogithub.com/v1/widgets/recommend.svg?rid=75ad7ffedd404a6485b4d621ec5b47e6&claim_uid=beSz6INEkCM4mDH" alt="Featured|HelloGitHub" style="width: 200px; height: 45px;" width="200" height="45" /></a>
|
||||
|
||||

|
||||
|
||||
[](https://star-history.com/#vastsa/FileCodeBox&Date)
|
||||
</div>
|
||||
|
||||
## 📜 Disclaimer
|
||||
|
||||
This project is open-source for learning purposes only. It should not be used for any illegal purposes. The author is not responsible for any consequences. Please retain the project address and copyright information when using it.
|
||||
@@ -0,0 +1,414 @@
|
||||
# Admin Panel
|
||||
|
||||
FileCodeBox provides a fully-featured admin panel that allows administrators to conveniently manage files, view system status, and modify configurations. This document introduces the various features and usage of the admin panel.
|
||||
|
||||
## Accessing the Admin Panel
|
||||
|
||||
### Login Method
|
||||
|
||||
The admin panel is located at the `/admin` path. Access method:
|
||||
|
||||
1. On first run, set the admin password on the setup page
|
||||
2. Visit `http://your-domain.com/admin` in your browser
|
||||
3. Enter the admin password (the value of the `admin_token` configuration)
|
||||
4. Click the login button
|
||||
|
||||
::: tip Tip
|
||||
The setup page is shown automatically while the system is uninitialized. Complete setup before exposing a production service to the public internet.
|
||||
:::
|
||||
|
||||
### Show Admin Entry
|
||||
|
||||
By default, the admin panel entry is not shown on the homepage. You can control whether to show it via configuration:
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `showAdminAddr` | int | `0` | Show admin entry on homepage (1=show, 0=hide) |
|
||||
|
||||
::: warning Security Recommendation
|
||||
For public services, it's recommended to keep `showAdminAddr` at `0` and access the admin panel directly via the `/admin` path to reduce the risk of malicious scanning.
|
||||
:::
|
||||
|
||||
### Authentication Mechanism
|
||||
|
||||
The admin panel uses JWT (JSON Web Token) for authentication:
|
||||
|
||||
1. After successful login, the server returns a Token containing admin identity
|
||||
2. Subsequent requests carry the Token via `Authorization: Bearer <token>` header
|
||||
3. Token is used to verify admin identity, ensuring only authorized users can access admin functions
|
||||
|
||||
## Dashboard
|
||||
|
||||
After logging in, you first see the dashboard page, which displays the overall system status.
|
||||
|
||||
### Statistics
|
||||
|
||||
The dashboard displays the following key metrics:
|
||||
|
||||
| Metric | Description |
|
||||
|--------|-------------|
|
||||
| **Total Files** (`totalFiles`) | Total number of files stored in the system |
|
||||
| **Storage Used** (`storageUsed`) | Total storage space occupied by all files (bytes) |
|
||||
| **System Uptime** (`sysUptime`) | Time when the system was first started |
|
||||
| **Yesterday's Uploads** (`yesterdayCount`) | Number of files uploaded yesterday |
|
||||
| **Yesterday's Upload Size** (`yesterdaySize`) | Total size of files uploaded yesterday (bytes) |
|
||||
| **Today's Uploads** (`todayCount`) | Number of files uploaded today so far |
|
||||
| **Today's Upload Size** (`todaySize`) | Total size of files uploaded today (bytes) |
|
||||
|
||||
### Metric Notes
|
||||
|
||||
- **Total Files**: Includes all unexpired files and text shares
|
||||
- **Storage Used**: Shows actual storage space occupied by files, excluding database and other system files
|
||||
- **Yesterday/Today Statistics**: Calculated based on file creation time, useful for understanding system usage trends
|
||||
|
||||
::: tip Tip
|
||||
Storage usage is displayed in bytes. For example, `10485760` represents approximately 10MB.
|
||||
:::
|
||||
|
||||
## File Management
|
||||
|
||||
### File List
|
||||
|
||||
The file management page displays all shared files in the system, supporting pagination and search.
|
||||
|
||||
**List information includes:**
|
||||
- File ID
|
||||
- Extraction code (code)
|
||||
- Filename prefix (prefix)
|
||||
- File extension (suffix)
|
||||
- File size
|
||||
- Creation time
|
||||
- Expiration time
|
||||
- Remaining download count
|
||||
|
||||
### Search Files
|
||||
|
||||
Use the search function to quickly find specific files:
|
||||
|
||||
1. Enter keywords in the search box
|
||||
2. System performs fuzzy matching based on filename prefix (prefix)
|
||||
3. Search results update in real-time
|
||||
|
||||
**Search examples:**
|
||||
- Enter `report` to find all files with "report" in the filename
|
||||
- Enter `.pdf` to find all PDF files (if the filename contains this string)
|
||||
|
||||
### Pagination
|
||||
|
||||
The file list supports paginated display:
|
||||
|
||||
| Parameter | Default | Description |
|
||||
|-----------|---------|-------------|
|
||||
| `page` | `1` | Current page number |
|
||||
| `size` | `10` | Items per page |
|
||||
|
||||
|
||||
### Delete Files
|
||||
|
||||
Administrators can delete any file:
|
||||
|
||||
1. Find the file to delete in the file list
|
||||
2. Click the delete button
|
||||
3. Confirm the delete operation
|
||||
|
||||
::: danger Warning
|
||||
Delete operations are irreversible! Files will be permanently deleted from the storage backend, and database records will also be removed.
|
||||
:::
|
||||
|
||||
**Delete process:**
|
||||
1. System first deletes the actual file from the storage backend (local/S3/OneDrive, etc.)
|
||||
2. Then deletes the file record from the database
|
||||
3. After deletion, the corresponding extraction code becomes invalid
|
||||
|
||||
### Download Files
|
||||
|
||||
Administrators can directly download any file:
|
||||
|
||||
1. Find the target file in the file list
|
||||
2. Click the download button
|
||||
3. File will be downloaded via browser
|
||||
|
||||
For text shares, the system returns text content directly instead of downloading a file.
|
||||
|
||||
### Modify File Information
|
||||
|
||||
Administrators can modify some information of shared files:
|
||||
|
||||
| Modifiable Field | Description |
|
||||
|------------------|-------------|
|
||||
| `code` | Extraction code (must be unique, cannot duplicate other files) |
|
||||
| `prefix` | Filename prefix |
|
||||
| `suffix` | File extension |
|
||||
| `expired_at` | Expiration time |
|
||||
| `expired_count` | Remaining download count |
|
||||
|
||||
**Modify extraction code:**
|
||||
```
|
||||
Original code: abc123
|
||||
New code: myfile2024
|
||||
```
|
||||
|
||||
::: warning Note
|
||||
When modifying extraction codes, the system checks if the new code is already in use. If an identical extraction code exists, the modification will fail.
|
||||
:::
|
||||
|
||||
## Local File Management
|
||||
|
||||
In addition to managing shared files, the admin panel also provides local file management functionality for managing files in the `data/local` directory.
|
||||
|
||||
### View Local Files
|
||||
|
||||
The local file list displays all files in the `data/local` directory:
|
||||
|
||||
| Information | Description |
|
||||
|-------------|-------------|
|
||||
| Filename | Complete filename |
|
||||
| Creation Time | File creation time |
|
||||
| File Size | File size (bytes) |
|
||||
|
||||
### Share Local Files
|
||||
|
||||
You can quickly share local files:
|
||||
|
||||
1. Select the file to share in the local file list
|
||||
2. Set expiration method and value
|
||||
3. Click the share button
|
||||
4. System generates extraction code
|
||||
|
||||
**Share parameters:**
|
||||
|
||||
| Parameter | Description |
|
||||
|-----------|-------------|
|
||||
| `filename` | Filename to share |
|
||||
| `expire_style` | Expiration method (day/hour/minute/forever/count) |
|
||||
| `expire_value` | Expiration value (days/hours/minutes/download count) |
|
||||
|
||||
### Delete Local Files
|
||||
|
||||
You can delete files in the `data/local` directory:
|
||||
|
||||
1. Find the file to delete in the local file list
|
||||
2. Click the delete button
|
||||
3. Confirm deletion
|
||||
|
||||
::: tip Use Cases
|
||||
Local file management is useful for:
|
||||
- Sharing files after batch uploading to the server
|
||||
- Managing files uploaded to the server through other means
|
||||
- Cleaning up unnecessary local files
|
||||
:::
|
||||
|
||||
## System Settings
|
||||
|
||||
### View Configuration
|
||||
|
||||
On the system settings page, you can view the current values of all configuration items. Configuration items are grouped by category:
|
||||
|
||||
- Basic settings (site name, description, etc.)
|
||||
- Upload settings (file size limits, rate limits, etc.)
|
||||
- Storage settings (storage type, path, etc.)
|
||||
- Theme settings (theme selection, opacity, etc.)
|
||||
- Security settings (admin password, error limits, etc.)
|
||||
|
||||
### Modify Configuration
|
||||
|
||||
Administrators can modify most configurations through the admin panel:
|
||||
|
||||
1. Go to the system settings page
|
||||
2. Find the configuration item to modify
|
||||
3. Enter the new value
|
||||
4. Click the save button
|
||||
|
||||
**Modifiable configuration items:**
|
||||
|
||||
| Category | Example Settings |
|
||||
|----------|------------------|
|
||||
| Basic Settings | `name`, `description`, `keywords`, `notify_title`, `notify_content` |
|
||||
| Upload Settings | `uploadSize`, `uploadMinute`, `uploadCount`, `openUpload`, `enableChunk` |
|
||||
| Expiration Settings | `expireStyle`, `max_save_seconds` |
|
||||
| Theme Settings | `themesSelect`, `opacity`, `background` |
|
||||
| Security Settings | `admin_token`, `showAdminAddr`, `errorMinute`, `errorCount` |
|
||||
| Storage Settings | `file_storage`, `storage_path` and storage backend-specific configurations |
|
||||
|
||||
::: warning Note
|
||||
- `admin_token` (admin password) cannot be set to empty
|
||||
- `themesChoices` (theme list) cannot be modified through the admin panel
|
||||
- After modifying storage settings, existing files will not be automatically migrated
|
||||
:::
|
||||
|
||||
### Configuration Effect
|
||||
|
||||
Configuration changes take effect immediately without restarting the service. Configurations are saved in the database and persist after restart.
|
||||
|
||||
**Configuration storage location:**
|
||||
- Database: `data/filecodebox.db`
|
||||
- Table name: `keyvalue`
|
||||
- Key name: `settings`
|
||||
|
||||
## API Endpoints
|
||||
|
||||
All admin panel functions are implemented through REST APIs. Here are the main endpoints:
|
||||
|
||||
### Authentication Endpoint
|
||||
|
||||
**Login**
|
||||
```
|
||||
POST /admin/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"password": "your-admin-password"
|
||||
}
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"token": "eyJhbGciOiJIUzI1NiIs...",
|
||||
"token_type": "Bearer"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Dashboard Endpoint
|
||||
|
||||
**Get Statistics**
|
||||
```
|
||||
GET /admin/dashboard
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
### File Management Endpoints
|
||||
|
||||
**Get File List**
|
||||
```
|
||||
GET /admin/file/list?page=1&size=10&keyword=
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**Delete File**
|
||||
```
|
||||
DELETE /admin/file/delete
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"id": 123
|
||||
}
|
||||
```
|
||||
|
||||
**Download File**
|
||||
```
|
||||
GET /admin/file/download?id=123
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**Modify File Information**
|
||||
```
|
||||
PATCH /admin/file/update
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"id": 123,
|
||||
"code": "newcode",
|
||||
"expired_at": "2024-12-31T23:59:59"
|
||||
}
|
||||
```
|
||||
|
||||
### Local File Endpoints
|
||||
|
||||
**Get Local File List**
|
||||
```
|
||||
GET /admin/local/lists
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**Delete Local File**
|
||||
```
|
||||
DELETE /admin/local/delete
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"filename": "example.txt"
|
||||
}
|
||||
```
|
||||
|
||||
**Share Local File**
|
||||
```
|
||||
POST /admin/local/share
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"filename": "example.txt",
|
||||
"expire_style": "day",
|
||||
"expire_value": 7
|
||||
}
|
||||
```
|
||||
|
||||
### Configuration Endpoints
|
||||
|
||||
**Get Configuration**
|
||||
```
|
||||
GET /admin/config/get
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**Update Configuration**
|
||||
```
|
||||
PATCH /admin/config/update
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"admin_token": "new-password",
|
||||
"uploadSize": 52428800
|
||||
}
|
||||
```
|
||||
|
||||
## Common Issues
|
||||
|
||||
### Forgot Admin Password
|
||||
|
||||
If you forgot the admin password, you can reset it through the following methods:
|
||||
|
||||
1. Stop the FileCodeBox service
|
||||
2. Open `data/filecodebox.db` using an SQLite tool
|
||||
3. Query the record with `key='settings'` in the `keyvalue` table
|
||||
4. Modify the `admin_token` value in the JSON
|
||||
5. Restart the service
|
||||
|
||||
```sql
|
||||
-- View current configuration
|
||||
SELECT * FROM keyvalue WHERE key = 'settings';
|
||||
|
||||
-- Or delete configuration to restore default password
|
||||
DELETE FROM keyvalue WHERE key = 'settings';
|
||||
```
|
||||
|
||||
### File Deletion Failed
|
||||
|
||||
If an error occurs when deleting files, possible reasons:
|
||||
|
||||
1. **Storage backend connection failed**: Check if storage configuration is correct
|
||||
2. **File no longer exists**: File may have been manually deleted
|
||||
3. **Insufficient permissions**: Check write permissions for storage directory
|
||||
|
||||
### Configuration Changes Not Taking Effect
|
||||
|
||||
If configuration changes don't take effect:
|
||||
|
||||
1. Check if you clicked the save button
|
||||
2. Refresh the page to see if configuration was saved
|
||||
3. Check browser console for error messages
|
||||
4. Confirm configuration value format is correct (e.g., don't enter strings for numeric types)
|
||||
|
||||
## Next Steps
|
||||
|
||||
- [Configuration Guide](/en/guide/configuration) - Learn detailed descriptions of all configuration options
|
||||
- [Security Settings](/en/guide/security) - Learn how to enhance system security
|
||||
- [Storage Configuration](/en/guide/storage) - Configure different storage backends
|
||||
@@ -0,0 +1,26 @@
|
||||
# Releasing
|
||||
|
||||
The project uses Semantic Versioning and Conventional Commits.
|
||||
|
||||
Complete these settings once in the backend GitHub repository:
|
||||
|
||||
- In `Settings → Actions → General → Workflow permissions`, grant read/write
|
||||
access and allow GitHub Actions to create pull requests. The frontend repository
|
||||
only needs the default read-only Actions permission.
|
||||
- Keep squash merging enabled. The release workflow waits for required checks
|
||||
before merging the release pull request.
|
||||
- Add `DOCKER_USERNAME` and `DOCKER_PASSWORD` Actions secrets to the backend repository.
|
||||
|
||||
1. Merge commits using Conventional Commit types such as `feat:` and `fix:` into the default branch.
|
||||
2. Release Please creates and merges the release pull request and updates `VERSION` and the changelog.
|
||||
3. The workflow then creates `vX.Y.Z`, a GitHub Release, and dispatches the production image build.
|
||||
4. Releases publish `X.Y.Z`, `X.Y`, and `latest`; branches publish `dev` or `edge-*` images.
|
||||
5. Each image build resolves the latest commit from both frontend default branches automatically.
|
||||
|
||||
Every `fix:`, `feat:`, or breaking change merged into the default branch therefore
|
||||
creates a Patch, Minor, or Major release automatically. Non-release commits such
|
||||
as `docs:` and `chore:` do not publish a release on their own.
|
||||
|
||||
The backend runtime version comes from `VERSION`. Container branch builds inject a
|
||||
commit-qualified development version through `APP_VERSION`; release tags must exactly
|
||||
match `VERSION`. OCI image labels record the resolved backend and frontend commits for traceability.
|
||||
@@ -0,0 +1,321 @@
|
||||
# Security Settings
|
||||
|
||||
FileCodeBox provides multiple layers of security mechanisms to protect your file sharing service. This document explains how to properly configure security options to ensure secure system operation.
|
||||
|
||||
## Admin Password
|
||||
|
||||
### First-Run Setup
|
||||
|
||||
::: danger Important Security Warning
|
||||
FileCodeBox does not ship with a default admin password. Open the site in your browser on first run and set the admin password on the setup page.
|
||||
:::
|
||||
|
||||
Change the admin password through the admin panel:
|
||||
|
||||
1. Access `/admin` to enter the admin panel
|
||||
2. Log in with the current password
|
||||
3. Go to the "System Settings" page
|
||||
4. Find the `admin_token` configuration item
|
||||
5. Enter a new secure password and save
|
||||
|
||||
`admin_token` is stored as a password hash. Do not write a plaintext password to the database, or admin login will stop working.
|
||||
|
||||
### Password Security Recommendations
|
||||
|
||||
- Use a strong password with at least 16 characters
|
||||
- Include uppercase and lowercase letters, numbers, and special characters
|
||||
- Avoid common words or personal information
|
||||
- Change password regularly
|
||||
|
||||
```python
|
||||
# Recommended password format example
|
||||
"admin_token": "Xk9#mP2$vL5@nQ8&wR3"
|
||||
```
|
||||
|
||||
### Hide Admin Entry
|
||||
|
||||
By default, the admin panel entry is hidden. You can control whether to show the admin entry on the homepage via the `showAdminAddr` configuration:
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `showAdminAddr` | int | `0` | Show admin entry (1=show, 0=hide) |
|
||||
|
||||
::: tip Recommendation
|
||||
For public services, it's recommended to keep `showAdminAddr` at `0` and access the admin panel directly via the `/admin` path.
|
||||
:::
|
||||
|
||||
## IP Rate Limiting
|
||||
|
||||
FileCodeBox has built-in IP-based rate limiting mechanisms to effectively prevent abuse and attacks.
|
||||
|
||||
### Upload Rate Limiting
|
||||
|
||||
Limit the number of uploads from a single IP within a specified time:
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `uploadMinute` | int | `1` | Upload limit time window (minutes) |
|
||||
| `uploadCount` | int | `10` | Maximum uploads allowed within the time window |
|
||||
|
||||
**How it works:**
|
||||
- System records upload requests from each IP
|
||||
- When an IP's upload count reaches `uploadCount` within `uploadMinute` minutes
|
||||
- Subsequent upload requests from that IP will be rejected with HTTP 423 error
|
||||
- Counter resets after the time window expires
|
||||
|
||||
**Configuration examples:**
|
||||
|
||||
```python
|
||||
# Relaxed configuration: Max 20 uploads in 5 minutes
|
||||
{
|
||||
"uploadMinute": 5,
|
||||
"uploadCount": 20
|
||||
}
|
||||
|
||||
# Strict configuration: Max 3 uploads in 1 minute
|
||||
{
|
||||
"uploadMinute": 1,
|
||||
"uploadCount": 3
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Error Rate Limiting
|
||||
|
||||
Limit the number of error attempts from a single IP to prevent brute-force attacks on extraction codes:
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `errorMinute` | int | `1` | Error limit time window (minutes) |
|
||||
| `errorCount` | int | `10` | Maximum errors allowed within the time window |
|
||||
|
||||
**How it works:**
|
||||
- When a user enters an incorrect extraction code, the system records the error count for that IP
|
||||
- When error count reaches `errorCount`, that IP will be temporarily locked
|
||||
- Lock duration is `errorMinute` minutes
|
||||
- During lockout, all extraction requests from that IP will be rejected
|
||||
|
||||
**Configuration example:**
|
||||
|
||||
```python
|
||||
# Anti-brute-force configuration: Max 3 errors in 5 minutes
|
||||
{
|
||||
"errorMinute": 5,
|
||||
"errorCount": 3
|
||||
}
|
||||
```
|
||||
|
||||
::: warning Note
|
||||
The default allows up to 10 errors per IP each minute. Public services can tighten this limit while accounting for users behind shared network addresses.
|
||||
:::
|
||||
|
||||
## Upload Restrictions
|
||||
|
||||
### File Size Limit
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `uploadSize` | int | `10485760` | Maximum single file upload size (bytes), default 10MB |
|
||||
| `openUpload` | int | `1` | Enable upload functionality (1=enabled, 0=disabled) |
|
||||
|
||||
**Common size conversions:**
|
||||
- 10MB = 10 * 1024 * 1024 = `10485760`
|
||||
- 50MB = 50 * 1024 * 1024 = `52428800`
|
||||
- 100MB = 100 * 1024 * 1024 = `104857600`
|
||||
- 1GB = 1024 * 1024 * 1024 = `1073741824`
|
||||
|
||||
### File Expiration Settings
|
||||
|
||||
Through file expiration mechanisms, you can automatically clean up expired files, reducing storage usage and security risks:
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `expireStyle` | list | `["day","hour","minute","forever","count"]` | Available expiration methods |
|
||||
| `max_save_seconds` | int | `0` | Maximum file retention time (seconds), 0 means no limit |
|
||||
|
||||
**Expiration methods explained:**
|
||||
- `day` - Expire by days
|
||||
- `hour` - Expire by hours
|
||||
- `minute` - Expire by minutes
|
||||
- `forever` - Never expire (requires alphanumeric extraction code)
|
||||
- `count` - Expire by download count
|
||||
|
||||
**Security recommendations:**
|
||||
|
||||
For public services, it's recommended to:
|
||||
1. Remove the `forever` option to avoid permanent file storage
|
||||
2. Set `max_save_seconds` to limit maximum retention time
|
||||
3. Prefer using `count` method for automatic deletion after download
|
||||
|
||||
```python
|
||||
# Recommended configuration for public services
|
||||
{
|
||||
"expireStyle": ["hour", "minute", "count"],
|
||||
"max_save_seconds": 86400 # Max retention 1 day
|
||||
}
|
||||
```
|
||||
|
||||
### Disable Upload Functionality
|
||||
|
||||
In some cases, you may need to temporarily disable upload functionality:
|
||||
|
||||
```python
|
||||
{
|
||||
"openUpload": 0 # Disable upload functionality
|
||||
}
|
||||
```
|
||||
|
||||
## Reverse Proxy Security Configuration
|
||||
|
||||
In production environments, Nginx or other reverse proxy servers are typically used. Here are security configuration recommendations:
|
||||
|
||||
### Nginx Configuration Example
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 80;
|
||||
server_name your-domain.com;
|
||||
|
||||
# Force HTTPS redirect
|
||||
return 301 https://$server_name$request_uri;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name your-domain.com;
|
||||
|
||||
# SSL certificate configuration
|
||||
ssl_certificate /path/to/cert.pem;
|
||||
ssl_certificate_key /path/to/key.pem;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
|
||||
ssl_prefer_server_ciphers on;
|
||||
|
||||
# Security headers
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-XSS-Protection "1; mode=block" always;
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
|
||||
# Limit request body size (match uploadSize configuration)
|
||||
client_max_body_size 100M;
|
||||
|
||||
# Pass real IP
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:12345;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# Static resource caching
|
||||
location /assets {
|
||||
proxy_pass http://127.0.0.1:12345;
|
||||
proxy_cache_valid 200 7d;
|
||||
add_header Cache-Control "public, max-age=604800";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Key Security Configuration Notes
|
||||
|
||||
**1. Pass Real IP**
|
||||
|
||||
FileCodeBox's IP limiting functionality depends on obtaining the client's real IP. The system obtains IP in the following order:
|
||||
1. `X-Real-IP` request header
|
||||
2. `X-Forwarded-For` request header
|
||||
3. Direct client connection IP
|
||||
|
||||
Ensure the reverse proxy correctly sets these headers:
|
||||
|
||||
```nginx
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
```
|
||||
|
||||
**2. Request Body Size Limit**
|
||||
|
||||
Nginx's `client_max_body_size` should match or be slightly larger than FileCodeBox's `uploadSize` configuration:
|
||||
|
||||
```nginx
|
||||
client_max_body_size 100M; # Allow max 100MB uploads
|
||||
```
|
||||
|
||||
**3. HTTPS Encryption**
|
||||
|
||||
It's strongly recommended to enable HTTPS in production environments:
|
||||
- Protect uploaded file content
|
||||
- Protect admin login credentials
|
||||
- Prevent man-in-the-middle attacks
|
||||
|
||||
### Caddy Configuration Example
|
||||
|
||||
```nginx
|
||||
your-domain.com {
|
||||
reverse_proxy localhost:12345
|
||||
|
||||
header {
|
||||
X-Frame-Options "SAMEORIGIN"
|
||||
X-Content-Type-Options "nosniff"
|
||||
X-XSS-Protection "1; mode=block"
|
||||
Strict-Transport-Security "max-age=31536000; includeSubDomains"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Security Checklist
|
||||
|
||||
Before deploying FileCodeBox, confirm the following security configurations:
|
||||
|
||||
- [ ] Completed first-run setup and set the admin password `admin_token`
|
||||
- [ ] Hidden admin entry `showAdminAddr: 0`
|
||||
- [ ] Configured appropriate upload rate limiting
|
||||
- [ ] Configured error rate limiting to prevent brute-force attacks
|
||||
- [ ] Set reasonable file size limits
|
||||
- [ ] Configured file expiration policy
|
||||
- [ ] Enabled HTTPS encryption
|
||||
- [ ] Reverse proxy correctly passes real IP
|
||||
- [ ] Set security response headers
|
||||
|
||||
## Recommended Security Configurations
|
||||
|
||||
### Public Service Configuration
|
||||
|
||||
```python
|
||||
{
|
||||
"admin_token": "your-very-secure-password",
|
||||
"showAdminAddr": 0,
|
||||
"uploadSize": 10485760, # 10MB
|
||||
"uploadMinute": 1,
|
||||
"uploadCount": 5,
|
||||
"errorMinute": 5,
|
||||
"errorCount": 3,
|
||||
"expireStyle": ["hour", "minute", "count"],
|
||||
"max_save_seconds": 86400, # Max 1 day
|
||||
"openUpload": 1
|
||||
}
|
||||
```
|
||||
|
||||
### Internal Service Configuration
|
||||
|
||||
```python
|
||||
{
|
||||
"admin_token": "internal-secure-password",
|
||||
"showAdminAddr": 1,
|
||||
"uploadSize": 104857600, # 100MB
|
||||
"uploadMinute": 5,
|
||||
"uploadCount": 50,
|
||||
"errorMinute": 1,
|
||||
"errorCount": 5,
|
||||
"expireStyle": ["day", "hour", "forever"],
|
||||
"max_save_seconds": 0, # No limit
|
||||
"openUpload": 1
|
||||
}
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- [Configuration Guide](/en/guide/configuration) - Learn about all configuration options
|
||||
- [Storage Configuration](/en/guide/storage) - Configure secure storage backends
|
||||
- [File Sharing](/en/guide/share) - Learn about file sharing features
|
||||
@@ -0,0 +1,342 @@
|
||||
# File Sharing
|
||||
|
||||
FileCodeBox provides simple and easy-to-use file and text sharing functionality. Users can securely share and retrieve files using extraction codes.
|
||||
|
||||
## Sharing Methods
|
||||
|
||||
FileCodeBox supports two sharing methods:
|
||||
|
||||
1. **Text Sharing** - Share text content directly, suitable for code snippets, configuration files, etc.
|
||||
2. **File Sharing** - Upload files for sharing, supports various file formats
|
||||
|
||||
## Text Sharing
|
||||
|
||||
### How to Use
|
||||
|
||||
1. Select the "Text Share" tab on the homepage
|
||||
2. Enter or paste the content to share in the text box
|
||||
3. Select expiration method and time
|
||||
4. Click the "Share" button
|
||||
5. Get the extraction code
|
||||
|
||||
### Text Size Limit
|
||||
|
||||
::: warning Note
|
||||
The maximum content size for text sharing is **222KB** (227,328 bytes). If content exceeds this limit, it's recommended to use file sharing instead.
|
||||
:::
|
||||
|
||||
Text content size is calculated using UTF-8 encoding. Chinese characters typically occupy 3 bytes.
|
||||
|
||||
### API Endpoint
|
||||
|
||||
**POST** `/share/text/`
|
||||
|
||||
Request parameters:
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| `text` | string | Yes | Text content to share |
|
||||
| `expire_value` | int | No | Expiration value, default 1 |
|
||||
| `expire_style` | string | No | Expiration method, default `day` |
|
||||
|
||||
Response example:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"code": "123456"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## File Sharing
|
||||
|
||||
### How to Use
|
||||
|
||||
1. Select the "File Share" tab on the homepage
|
||||
2. Click the upload area or drag files to the upload area
|
||||
3. Select expiration method and time
|
||||
4. Click the "Upload" button
|
||||
5. Get the extraction code
|
||||
|
||||
### File Size Limit
|
||||
|
||||
The default maximum single file upload size is **10MB**. Administrators can modify this limit via the `uploadSize` configuration.
|
||||
|
||||
::: tip Tip
|
||||
If you need to upload large files, contact the administrator to enable chunked upload functionality or adjust the `uploadSize` configuration.
|
||||
:::
|
||||
|
||||
### Supported Upload Methods
|
||||
|
||||
- **Click Upload** - Click the upload area to select files
|
||||
- **Drag Upload** - Drag files to the upload area
|
||||
- **Paste Upload** - Paste images from clipboard (supported by some themes)
|
||||
|
||||
### API Endpoint
|
||||
|
||||
**POST** `/share/file/`
|
||||
|
||||
Request parameters (multipart/form-data):
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| `file` | file | Yes | File to upload |
|
||||
| `expire_value` | int | No | Expiration value, default 1 |
|
||||
| `expire_style` | string | No | Expiration method, default `day` |
|
||||
|
||||
Response example:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"code": "654321",
|
||||
"name": "example.pdf"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Expiration Settings
|
||||
|
||||
FileCodeBox supports multiple flexible expiration methods:
|
||||
|
||||
| Expiration Method | Parameter Value | Description |
|
||||
|-------------------|-----------------|-------------|
|
||||
| By Days | `day` | File expires after specified days |
|
||||
| By Hours | `hour` | File expires after specified hours |
|
||||
| By Minutes | `minute` | File expires after specified minutes |
|
||||
| Never Expire | `forever` | File is permanently valid |
|
||||
| By Count | `count` | File expires after specified download count |
|
||||
|
||||
::: info Note
|
||||
- Administrators can control available expiration methods via the `expireStyle` configuration
|
||||
- Administrators can limit maximum file retention time via the `max_save_seconds` configuration
|
||||
:::
|
||||
|
||||
### Expiration Method Examples
|
||||
|
||||
```bash
|
||||
# File expires after 3 days
|
||||
expire_value=3, expire_style=day
|
||||
|
||||
# File expires after 12 hours
|
||||
expire_value=12, expire_style=hour
|
||||
|
||||
# File expires after 30 minutes
|
||||
expire_value=30, expire_style=minute
|
||||
|
||||
# File never expires
|
||||
expire_value=1, expire_style=forever
|
||||
|
||||
# File expires after 5 downloads
|
||||
expire_value=5, expire_style=count
|
||||
```
|
||||
|
||||
## Retrieving Files
|
||||
|
||||
### How to Use
|
||||
|
||||
1. Enter the extraction code in the "Retrieve File" area on the homepage
|
||||
2. Click the "Retrieve" button
|
||||
3. System displays file information (filename, size, etc.)
|
||||
4. Click the "Download" button to download the file, or view text content directly
|
||||
|
||||
### Extraction Code Notes
|
||||
|
||||
- Extraction codes are typically **6-digit numbers**
|
||||
- Files that never expire use **alphanumeric** extraction codes
|
||||
- Extraction codes are case-sensitive (for alphanumeric codes)
|
||||
|
||||
### API Endpoints
|
||||
|
||||
**Query File Information**
|
||||
|
||||
**POST** `/share/select/`
|
||||
|
||||
Request parameters:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": "123456"
|
||||
}
|
||||
```
|
||||
|
||||
Response example (file):
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"code": "123456",
|
||||
"name": "example.pdf",
|
||||
"size": 1048576,
|
||||
"text": "https://example.com/download/..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Response example (text):
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"code": "123456",
|
||||
"name": "Text",
|
||||
"size": 1024,
|
||||
"text": "This is the shared text content..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Direct File Download**
|
||||
|
||||
**GET** `/share/select/?code=123456`
|
||||
|
||||
This endpoint returns file content directly, suitable for direct browser access.
|
||||
|
||||
## Chunked Upload (Large Files)
|
||||
|
||||
For large file uploads, FileCodeBox supports chunked upload functionality. This feature requires administrator enablement (`enableChunk=1`).
|
||||
|
||||
### Chunked Upload Flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Client
|
||||
participant S as Server
|
||||
|
||||
C->>S: 1. Initialize upload (POST /chunk/upload/init/)
|
||||
S-->>C: Return upload_id and chunk info
|
||||
|
||||
loop Each chunk
|
||||
C->>S: 2. Upload chunk (POST /chunk/upload/chunk/{upload_id}/{chunk_index})
|
||||
S-->>C: Return chunk hash
|
||||
end
|
||||
|
||||
C->>S: 3. Complete upload (POST /chunk/upload/complete/{upload_id})
|
||||
S-->>C: Return extraction code
|
||||
```
|
||||
|
||||
### 1. Initialize Upload
|
||||
|
||||
**POST** `/chunk/upload/init/`
|
||||
|
||||
Request parameters:
|
||||
|
||||
```json
|
||||
{
|
||||
"file_name": "large_file.zip",
|
||||
"file_size": 104857600,
|
||||
"chunk_size": 5242880,
|
||||
"file_hash": "sha256_hash_of_file"
|
||||
}
|
||||
```
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| `file_name` | string | Yes | Filename |
|
||||
| `file_size` | int | Yes | Total file size (bytes) |
|
||||
| `chunk_size` | int | No | Chunk size, default 5MB |
|
||||
| `file_hash` | string | Yes | SHA256 hash of the file |
|
||||
|
||||
Response example:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"existed": false,
|
||||
"upload_id": "abc123def456",
|
||||
"chunk_size": 5242880,
|
||||
"total_chunks": 20,
|
||||
"uploaded_chunks": []
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Upload Chunk
|
||||
|
||||
**POST** `/chunk/upload/chunk/{upload_id}/{chunk_index}`
|
||||
|
||||
- `upload_id` - Upload session ID returned during initialization
|
||||
- `chunk_index` - Chunk index, starting from 0
|
||||
|
||||
Request body: Chunk file data (multipart/form-data)
|
||||
|
||||
Response example:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"chunk_hash": "sha256_hash_of_chunk"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Complete Upload
|
||||
|
||||
**POST** `/chunk/upload/complete/{upload_id}`
|
||||
|
||||
Request parameters:
|
||||
|
||||
```json
|
||||
{
|
||||
"expire_value": 1,
|
||||
"expire_style": "day"
|
||||
}
|
||||
```
|
||||
|
||||
Response example:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"code": "789012",
|
||||
"name": "large_file.zip"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Resume Upload
|
||||
|
||||
Chunked upload supports resume functionality. If upload is interrupted:
|
||||
|
||||
1. Call the initialization endpoint again with the same `file_hash`
|
||||
2. Server returns `uploaded_chunks` list containing already uploaded chunk indices
|
||||
3. Client only needs to upload chunks not in the list
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Common Error Codes
|
||||
|
||||
| Error Code | Description | Solution |
|
||||
|------------|-------------|----------|
|
||||
| 403 | File size exceeds limit | Reduce file size or contact administrator to adjust limit |
|
||||
| 403 | Content too large | Text exceeds 222KB, use file sharing instead |
|
||||
| 403 | Upload rate limit | Wait a while before retrying |
|
||||
| 404 | File not found | Check if extraction code is correct |
|
||||
| 404 | File expired | File has expired or download count exhausted |
|
||||
|
||||
### Rate Limiting
|
||||
|
||||
To prevent abuse, the system has rate limits on upload and retrieval operations:
|
||||
|
||||
- **Upload limit**: Default max 10 uploads per minute
|
||||
- **Error limit**: Default max 1 error attempt per minute
|
||||
|
||||
::: tip Tip
|
||||
If you encounter rate limiting, wait for the limit time window to pass before retrying.
|
||||
:::
|
||||
|
||||
## Next Steps
|
||||
|
||||
- [Configuration Guide](/en/guide/configuration) - Learn how to configure sharing-related settings
|
||||
- [Storage Configuration](/en/guide/storage) - Learn about file storage methods
|
||||
- [Security Settings](/en/guide/security) - Learn about security-related configurations
|
||||
- [Admin Panel](/en/guide/management) - Learn how to manage shared files
|
||||
@@ -0,0 +1,395 @@
|
||||
# Storage Configuration
|
||||
|
||||
FileCodeBox supports multiple storage backends. You can choose the appropriate storage method based on your needs. This document details the configuration methods for various storage backends.
|
||||
|
||||
## Storage Types Overview
|
||||
|
||||
| Storage Type | Config Value | Description |
|
||||
|--------------|--------------|-------------|
|
||||
| Local Storage | `local` | Default storage method, files saved on local server |
|
||||
| S3-Compatible Storage | `s3` | Supports AWS S3, Aliyun OSS, MinIO, etc. |
|
||||
| OneDrive | `onedrive` | Microsoft OneDrive cloud storage (work/school accounts only) |
|
||||
| WebDAV | `webdav` | Storage services supporting WebDAV protocol |
|
||||
| OpenDAL | `opendal` | Integrate more storage services via OpenDAL |
|
||||
|
||||
## Local Storage
|
||||
|
||||
Local storage is the default storage method. Files are saved in the server's `data/` directory.
|
||||
|
||||
### Configuration Parameters
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| `file_storage` | string | `local` | Storage type |
|
||||
| `storage_path` | string | `""` | Custom storage path (optional) |
|
||||
|
||||
### Configuration Example
|
||||
|
||||
```bash
|
||||
file_storage=local
|
||||
storage_path=
|
||||
```
|
||||
|
||||
### Notes
|
||||
|
||||
- Files are stored by default in `data/share/data/` directory
|
||||
- Subdirectories are automatically created by date: `year/month/day/fileID/`
|
||||
- In production, it's recommended to mount the `data/` directory to persistent storage
|
||||
|
||||
## S3-Compatible Storage
|
||||
|
||||
Supports all S3-compatible object storage services, including AWS S3, Aliyun OSS, MinIO, Tencent Cloud COS, etc.
|
||||
|
||||
### Configuration Parameters
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| `file_storage` | string | - | Set to `s3` |
|
||||
| `s3_access_key_id` | string | `""` | Access Key ID |
|
||||
| `s3_secret_access_key` | string | `""` | Secret Access Key |
|
||||
| `s3_bucket_name` | string | `""` | Bucket name |
|
||||
| `s3_endpoint_url` | string | `""` | S3 endpoint URL |
|
||||
| `s3_region_name` | string | `auto` | Region name |
|
||||
| `s3_signature_version` | string | `s3v2` | Signature version (`s3v2` or `s3v4`) |
|
||||
| `s3_hostname` | string | `""` | S3 hostname (alternative) |
|
||||
| `s3_proxy` | int | `0` | Download through server proxy (1=yes, 0=no) |
|
||||
| `aws_session_token` | string | `""` | AWS session token (optional) |
|
||||
|
||||
|
||||
### AWS S3 Configuration Example
|
||||
|
||||
```bash
|
||||
file_storage=s3
|
||||
s3_access_key_id=AKIAIOSFODNN7EXAMPLE
|
||||
s3_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
|
||||
s3_bucket_name=my-filecodebox-bucket
|
||||
s3_endpoint_url=https://s3.amazonaws.com
|
||||
s3_region_name=us-east-1
|
||||
s3_signature_version=s3v4
|
||||
```
|
||||
|
||||
### Aliyun OSS Configuration Example
|
||||
|
||||
```bash
|
||||
file_storage=s3
|
||||
s3_access_key_id=YourAccessKeyId
|
||||
s3_secret_access_key=YourSecretAccessKey
|
||||
s3_bucket_name=bucket-name
|
||||
s3_endpoint_url=https://bucket-name.oss-cn-hangzhou.aliyuncs.com
|
||||
s3_region_name=oss-cn-hangzhou
|
||||
s3_signature_version=s3v4
|
||||
```
|
||||
|
||||
::: tip Aliyun OSS Endpoint Format
|
||||
Endpoint URL format: `https://<bucket-name>.<region>.aliyuncs.com`
|
||||
|
||||
Common regions:
|
||||
- Hangzhou: `oss-cn-hangzhou`
|
||||
- Shanghai: `oss-cn-shanghai`
|
||||
- Beijing: `oss-cn-beijing`
|
||||
- Shenzhen: `oss-cn-shenzhen`
|
||||
:::
|
||||
|
||||
### MinIO Configuration Example
|
||||
|
||||
```bash
|
||||
file_storage=s3
|
||||
s3_access_key_id=minioadmin
|
||||
s3_secret_access_key=minioadmin
|
||||
s3_bucket_name=filecodebox
|
||||
s3_endpoint_url=http://localhost:9000
|
||||
s3_region_name=us-east-1
|
||||
s3_signature_version=s3v4
|
||||
```
|
||||
|
||||
::: warning MinIO Notes
|
||||
- `s3_endpoint_url` should be the MinIO API interface address
|
||||
- `s3_region_name` should match the `Server Location` in MinIO configuration
|
||||
- Ensure the bucket is created and has correct access permissions
|
||||
:::
|
||||
|
||||
### Tencent Cloud COS Configuration Example
|
||||
|
||||
```bash
|
||||
file_storage=s3
|
||||
s3_access_key_id=YourSecretId
|
||||
s3_secret_access_key=YourSecretKey
|
||||
s3_bucket_name=bucket-name-1250000000
|
||||
s3_endpoint_url=https://cos.ap-guangzhou.myqcloud.com
|
||||
s3_region_name=ap-guangzhou
|
||||
s3_signature_version=s3v4
|
||||
```
|
||||
|
||||
### Proxy Download
|
||||
|
||||
When `s3_proxy=1`, file downloads are proxied through the server instead of directly from S3. This is useful when:
|
||||
|
||||
- S3 bucket doesn't allow public access
|
||||
- Need to hide the actual storage address
|
||||
- Network environment restricts direct S3 access
|
||||
|
||||
## OneDrive Storage
|
||||
|
||||
OneDrive storage supports saving files to Microsoft OneDrive cloud storage.
|
||||
|
||||
::: warning Important Limitation
|
||||
OneDrive storage **only supports work or school accounts** and requires admin permissions to authorize the API. Personal accounts cannot use this feature.
|
||||
:::
|
||||
|
||||
### Configuration Parameters
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| `file_storage` | string | - | Set to `onedrive` |
|
||||
| `onedrive_domain` | string | `""` | Azure AD domain |
|
||||
| `onedrive_client_id` | string | `""` | Application (client) ID |
|
||||
| `onedrive_username` | string | `""` | Account email |
|
||||
| `onedrive_password` | string | `""` | Account password |
|
||||
| `onedrive_root_path` | string | `filebox_storage` | Storage root directory in OneDrive |
|
||||
| `onedrive_proxy` | int | `0` | Download through server proxy |
|
||||
|
||||
### Configuration Example
|
||||
|
||||
```bash
|
||||
file_storage=onedrive
|
||||
onedrive_domain=contoso.onmicrosoft.com
|
||||
onedrive_client_id=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
|
||||
onedrive_username=user@contoso.onmicrosoft.com
|
||||
onedrive_password=your_password
|
||||
onedrive_root_path=filebox_storage
|
||||
```
|
||||
|
||||
### Azure App Registration Steps
|
||||
|
||||
To use OneDrive storage, you need to register an application in the Azure portal:
|
||||
|
||||
#### 1. Get Domain
|
||||
|
||||
Log in to [Azure Portal](https://portal.azure.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade), hover over your account in the top right corner, and the **Domain** shown in the popup is the `onedrive_domain` value.
|
||||
|
||||
#### 2. Register Application
|
||||
|
||||
1. Click **+ New registration** in the top left
|
||||
2. Enter application name (e.g., FileCodeBox)
|
||||
3. **Supported account types**: Select "Accounts in any organizational directory (Any Azure AD directory - Multitenant) and personal Microsoft accounts"
|
||||
4. **Redirect URI**: Select `Web`, enter `http://localhost`
|
||||
5. Click **Register**
|
||||
|
||||
#### 3. Get Client ID
|
||||
|
||||
After registration, find the **Application (client) ID** in the **Essentials** section on the app overview page. This is the `onedrive_client_id` value.
|
||||
|
||||
#### 4. Configure Authentication
|
||||
|
||||
1. Select **Authentication** in the left menu
|
||||
2. Find **Allow public client flows**, select **Yes**
|
||||
3. Click **Save**
|
||||
|
||||
#### 5. Configure API Permissions
|
||||
|
||||
1. Select **API permissions** in the left menu
|
||||
2. Click **+ Add a permission**
|
||||
3. Select **Microsoft Graph** → **Delegated permissions**
|
||||
4. Check the following permissions:
|
||||
- `openid`
|
||||
- `Files.Read`
|
||||
- `Files.Read.All`
|
||||
- `Files.ReadWrite`
|
||||
- `Files.ReadWrite.All`
|
||||
- `User.Read`
|
||||
5. Click **Add permissions**
|
||||
6. Click **Grant admin consent for xxx**
|
||||
7. After confirmation, permission status should show **Granted**
|
||||
|
||||
### Install Dependencies
|
||||
|
||||
Using OneDrive storage requires additional Python dependencies:
|
||||
|
||||
```bash
|
||||
pip install msal Office365-REST-Python-Client
|
||||
```
|
||||
|
||||
### Verify Configuration
|
||||
|
||||
You can use the following code to test if the configuration is correct:
|
||||
|
||||
```python
|
||||
import msal
|
||||
from office365.graph_client import GraphClient
|
||||
|
||||
domain = 'your_domain'
|
||||
client_id = 'your_client_id'
|
||||
username = 'your_username'
|
||||
password = 'your_password'
|
||||
|
||||
def acquire_token_pwd():
|
||||
authority_url = f'https://login.microsoftonline.com/{domain}'
|
||||
app = msal.PublicClientApplication(
|
||||
authority=authority_url,
|
||||
client_id=client_id
|
||||
)
|
||||
result = app.acquire_token_by_username_password(
|
||||
username=username,
|
||||
password=password,
|
||||
scopes=['https://graph.microsoft.com/.default']
|
||||
)
|
||||
return result
|
||||
|
||||
# Test connection
|
||||
client = GraphClient(acquire_token_pwd)
|
||||
me = client.me.get().execute_query()
|
||||
print(f"Login successful: {me.user_principal_name}")
|
||||
```
|
||||
|
||||
|
||||
## WebDAV Storage
|
||||
|
||||
WebDAV storage supports saving files to any service that supports the WebDAV protocol, such as Nextcloud, ownCloud, Nutstore, etc.
|
||||
|
||||
### Configuration Parameters
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| `file_storage` | string | - | Set to `webdav` |
|
||||
| `webdav_url` | string | `""` | WebDAV server URL |
|
||||
| `webdav_username` | string | `""` | WebDAV username |
|
||||
| `webdav_password` | string | `""` | WebDAV password |
|
||||
| `webdav_root_path` | string | `filebox_storage` | Storage root directory in WebDAV |
|
||||
| `webdav_proxy` | int | `0` | Download through server proxy |
|
||||
|
||||
### Configuration Example
|
||||
|
||||
```bash
|
||||
file_storage=webdav
|
||||
webdav_url=https://dav.example.com/remote.php/dav/files/username/
|
||||
webdav_username=your_username
|
||||
webdav_password=your_password
|
||||
webdav_root_path=filebox_storage
|
||||
```
|
||||
|
||||
### Nextcloud Configuration Example
|
||||
|
||||
```bash
|
||||
file_storage=webdav
|
||||
webdav_url=https://your-nextcloud.com/remote.php/dav/files/username/
|
||||
webdav_username=your_username
|
||||
webdav_password=your_app_password
|
||||
webdav_root_path=FileCodeBox
|
||||
```
|
||||
|
||||
::: tip Nextcloud App Password
|
||||
It's recommended to create an app password in Nextcloud instead of using your main password:
|
||||
1. Log in to Nextcloud
|
||||
2. Go to **Settings** → **Security**
|
||||
3. Create a new app password in **Devices & sessions**
|
||||
:::
|
||||
|
||||
### Nutstore Configuration Example
|
||||
|
||||
```bash
|
||||
file_storage=webdav
|
||||
webdav_url=https://dav.jianguoyun.com/dav/
|
||||
webdav_username=your_email@example.com
|
||||
webdav_password=your_app_password
|
||||
webdav_root_path=FileCodeBox
|
||||
```
|
||||
|
||||
::: tip Nutstore App Password
|
||||
Nutstore requires an app password:
|
||||
1. Log in to Nutstore web version
|
||||
2. Go to **Account Info** → **Security Options**
|
||||
3. Add an app password
|
||||
:::
|
||||
|
||||
## OpenDAL Storage
|
||||
|
||||
OpenDAL is a unified data access layer that supports multiple storage services. Through OpenDAL, you can use Google Cloud Storage, Azure Blob Storage, and more.
|
||||
|
||||
### Configuration Parameters
|
||||
|
||||
| Parameter | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `file_storage` | string | Set to `opendal` |
|
||||
| `opendal_scheme` | string | Storage service type (e.g., `gcs`, `azblob`) |
|
||||
| `opendal_<scheme>_<setting>` | string | Service-specific configuration parameters |
|
||||
|
||||
### Install Dependencies
|
||||
|
||||
```bash
|
||||
pip install opendal
|
||||
```
|
||||
|
||||
### Google Cloud Storage Configuration Example
|
||||
|
||||
```bash
|
||||
file_storage=opendal
|
||||
opendal_scheme=gcs
|
||||
opendal_gcs_root=/filecodebox
|
||||
opendal_gcs_bucket=your-bucket-name
|
||||
opendal_gcs_credential=base64_encoded_credential
|
||||
```
|
||||
|
||||
### Azure Blob Storage Configuration Example
|
||||
|
||||
```bash
|
||||
file_storage=opendal
|
||||
opendal_scheme=azblob
|
||||
opendal_azblob_root=/filecodebox
|
||||
opendal_azblob_container=your-container
|
||||
opendal_azblob_account_name=your_account
|
||||
opendal_azblob_account_key=your_key
|
||||
```
|
||||
|
||||
### Supported Services
|
||||
|
||||
OpenDAL supports numerous storage services. For the complete list, see the [OpenDAL Official Documentation](https://opendal.apache.org/docs/rust/opendal/services/index.html).
|
||||
|
||||
Common services include:
|
||||
- `gcs` - Google Cloud Storage
|
||||
- `azblob` - Azure Blob Storage
|
||||
- `obs` - Huawei Cloud OBS
|
||||
- `oss` - Aliyun OSS (via OpenDAL)
|
||||
- `cos` - Tencent Cloud COS (via OpenDAL)
|
||||
- `hdfs` - Hadoop HDFS
|
||||
- `ftp` - FTP server
|
||||
- `sftp` - SFTP server
|
||||
|
||||
::: warning OpenDAL Notes
|
||||
1. Services integrated via OpenDAL download through server proxy, consuming both storage service and server bandwidth
|
||||
2. Compared to native S3/OneDrive support, OpenDAL may lack some debugging information
|
||||
3. OpenDAL is written in Rust with good performance
|
||||
:::
|
||||
|
||||
## Storage Selection Recommendations
|
||||
|
||||
| Scenario | Recommended Storage | Reason |
|
||||
|----------|---------------------|--------|
|
||||
| Personal/Small deployment | Local storage | Simple and easy, no extra configuration needed |
|
||||
| Enterprise intranet | MinIO + S3 | Self-hosted object storage, data control |
|
||||
| Public cloud deployment | Corresponding cloud provider S3 | Fast same-region access, low cost |
|
||||
| Existing OneDrive | OneDrive | Utilize existing resources |
|
||||
| Existing WebDAV | WebDAV | Good compatibility |
|
||||
| Special storage needs | OpenDAL | Supports more storage services |
|
||||
|
||||
## Common Issues
|
||||
|
||||
### S3 Upload Failure
|
||||
|
||||
1. Check if Access Key and Secret Key are correct
|
||||
2. Confirm bucket name and region configuration are correct
|
||||
3. Check bucket access permission settings
|
||||
4. Confirm signature version (`s3v2` or `s3v4`) matches service provider requirements
|
||||
|
||||
### OneDrive Authentication Failure
|
||||
|
||||
1. Confirm using a work/school account, not a personal account
|
||||
2. Check if Azure app has been granted admin consent
|
||||
3. Confirm API permissions are fully configured
|
||||
4. Verify username and password are correct
|
||||
|
||||
### WebDAV Connection Failure
|
||||
|
||||
1. Check if WebDAV URL format is correct
|
||||
2. Confirm username and password (or app password) are correct
|
||||
3. Check if server supports WebDAV protocol
|
||||
4. Confirm network connection is normal
|
||||
@@ -0,0 +1,421 @@
|
||||
# File Upload
|
||||
|
||||
FileCodeBox provides multiple flexible file upload methods, supporting both regular upload and chunked upload to meet different scenario requirements.
|
||||
|
||||
## Upload Methods
|
||||
|
||||
FileCodeBox supports the following upload methods:
|
||||
|
||||
### Drag and Drop Upload
|
||||
|
||||
Drag files directly to the upload area to start uploading. This is the most convenient upload method.
|
||||
|
||||
1. Open the FileCodeBox homepage
|
||||
2. Drag files from your file manager to the upload area
|
||||
3. Release the mouse, file upload begins
|
||||
4. Get the extraction code after upload completes
|
||||
|
||||
::: tip Tip
|
||||
Drag and drop upload supports dragging multiple files simultaneously (depending on theme support).
|
||||
:::
|
||||
|
||||
### Click Upload
|
||||
|
||||
Click the upload area to select files through the system file picker.
|
||||
|
||||
1. Click the "Select File" button in the upload area
|
||||
2. Select the file to upload in the popup file picker
|
||||
3. File upload begins after confirming selection
|
||||
4. Get the extraction code after upload completes
|
||||
|
||||
### Paste Upload
|
||||
|
||||
Supports pasting images directly from clipboard for upload (supported by some themes).
|
||||
|
||||
1. Copy an image to clipboard (screenshot or copy image)
|
||||
2. Use `Ctrl+V` (Windows/Linux) or `Cmd+V` (macOS) to paste in the upload area
|
||||
3. Image upload starts automatically
|
||||
4. Get the extraction code after upload completes
|
||||
|
||||
::: warning Note
|
||||
Paste upload only supports image formats, not other file types. Specific support depends on the theme being used.
|
||||
:::
|
||||
|
||||
## File Size Limits
|
||||
|
||||
### Default Limits
|
||||
|
||||
| Setting | Default | Description |
|
||||
|---------|---------|-------------|
|
||||
| `uploadSize` | 10MB | Maximum single file upload size |
|
||||
|
||||
### Modify Upload Limits
|
||||
|
||||
Administrators can modify upload size limits through the admin panel or configuration file:
|
||||
|
||||
```python
|
||||
# Set maximum upload size to 100MB
|
||||
uploadSize = 104857600 # 100 * 1024 * 1024
|
||||
```
|
||||
|
||||
::: info Note
|
||||
`uploadSize` is in bytes. Common conversions:
|
||||
- 10MB = 10485760
|
||||
- 50MB = 52428800
|
||||
- 100MB = 104857600
|
||||
- 500MB = 524288000
|
||||
- 1GB = 1073741824
|
||||
:::
|
||||
|
||||
### Exceeding Limit Handling
|
||||
|
||||
When an uploaded file exceeds the size limit, the system returns a 403 error:
|
||||
|
||||
```json
|
||||
{
|
||||
"detail": "Size exceeds limit, maximum is 10.00 MB"
|
||||
}
|
||||
```
|
||||
|
||||
## Regular Upload API
|
||||
|
||||
### File Upload Endpoint
|
||||
|
||||
**POST** `/share/file/`
|
||||
|
||||
Content-Type: `multipart/form-data`
|
||||
|
||||
**Request parameters:**
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| `file` | file | Yes | File to upload |
|
||||
| `expire_value` | int | No | Expiration value, default 1 |
|
||||
| `expire_style` | string | No | Expiration method, default `day` |
|
||||
|
||||
**Expiration method options:**
|
||||
|
||||
| Value | Description |
|
||||
|-------|-------------|
|
||||
| `day` | Expire by days |
|
||||
| `hour` | Expire by hours |
|
||||
| `minute` | Expire by minutes |
|
||||
| `forever` | Never expire |
|
||||
| `count` | Expire by download count |
|
||||
|
||||
**Response example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"code": "654321",
|
||||
"name": "example.pdf"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**cURL example:**
|
||||
|
||||
```bash
|
||||
# Upload file (default 1 day expiration)
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.pdf"
|
||||
|
||||
# Upload file with 7 days expiration
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.pdf" \
|
||||
-F "expire_value=7" \
|
||||
-F "expire_style=day"
|
||||
|
||||
# Upload file with 10 downloads limit
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-F "file=@/path/to/file.pdf" \
|
||||
-F "expire_value=10" \
|
||||
-F "expire_style=count"
|
||||
|
||||
# Share text
|
||||
curl -X POST "http://localhost:12345/share/text/" \
|
||||
-F "text=This is the text content to share"
|
||||
|
||||
# Download file by extraction code
|
||||
curl -L "http://localhost:12345/share/select/?code=YOUR_CODE" -o downloaded_file
|
||||
```
|
||||
|
||||
::: tip When Authentication Required
|
||||
If guest upload is disabled in admin panel (`openUpload=0`), you need to login first:
|
||||
|
||||
```bash
|
||||
# 1. Login to get token
|
||||
curl -X POST "http://localhost:12345/admin/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"password": "<admin-password-set-during-setup>"}'
|
||||
|
||||
# Returns: {"code":200,"msg":"success","detail":{"token":"xxx.xxx.xxx","token_type":"Bearer"}}
|
||||
|
||||
# 2. Upload file with token
|
||||
curl -X POST "http://localhost:12345/share/file/" \
|
||||
-H "Authorization: Bearer xxx.xxx.xxx" \
|
||||
-F "file=@/path/to/file.pdf"
|
||||
|
||||
# 3. Share text with token
|
||||
curl -X POST "http://localhost:12345/share/text/" \
|
||||
-H "Authorization: Bearer xxx.xxx.xxx" \
|
||||
-F "text=This is the text content to share"
|
||||
```
|
||||
:::
|
||||
|
||||
|
||||
## Chunked Upload API
|
||||
|
||||
For large files, FileCodeBox supports chunked upload functionality. Chunked upload splits large files into multiple small chunks for separate uploading, supporting resume capability.
|
||||
|
||||
::: warning Prerequisite
|
||||
Chunked upload functionality requires administrator enablement: `enableChunk=1`
|
||||
:::
|
||||
|
||||
### Chunked Upload Flow
|
||||
|
||||
```
|
||||
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
|
||||
│ Initialize │ ──▶ │Upload Chunks│ ──▶ │ Complete │
|
||||
│ /init/ │ │ /chunk/ │ │ /complete/ │
|
||||
└─────────────┘ └─────────────┘ └─────────────┘
|
||||
│
|
||||
▼
|
||||
┌───────────┐
|
||||
│ Loop │
|
||||
│each chunk │
|
||||
└───────────┘
|
||||
```
|
||||
|
||||
### 1. Initialize Upload
|
||||
|
||||
**POST** `/chunk/upload/init/`
|
||||
|
||||
**Request parameters:**
|
||||
|
||||
```json
|
||||
{
|
||||
"file_name": "large_file.zip",
|
||||
"file_size": 104857600,
|
||||
"chunk_size": 5242880,
|
||||
"file_hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||
}
|
||||
```
|
||||
|
||||
| Parameter | Type | Required | Default | Description |
|
||||
|-----------|------|----------|---------|-------------|
|
||||
| `file_name` | string | Yes | - | Filename |
|
||||
| `file_size` | int | Yes | - | Total file size (bytes) |
|
||||
| `chunk_size` | int | No | 5MB | Chunk size (bytes) |
|
||||
| `file_hash` | string | Yes | - | SHA256 hash of the file |
|
||||
|
||||
**Response example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"existed": false,
|
||||
"upload_id": "abc123def456789",
|
||||
"chunk_size": 5242880,
|
||||
"total_chunks": 20,
|
||||
"uploaded_chunks": []
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Description |
|
||||
|-------|-------------|
|
||||
| `existed` | Whether file already exists (instant upload) |
|
||||
| `upload_id` | Upload session ID |
|
||||
| `chunk_size` | Chunk size |
|
||||
| `total_chunks` | Total number of chunks |
|
||||
| `uploaded_chunks` | List of already uploaded chunk indices |
|
||||
|
||||
### 2. Upload Chunk
|
||||
|
||||
**POST** `/chunk/upload/chunk/{upload_id}/{chunk_index}`
|
||||
|
||||
**Path parameters:**
|
||||
|
||||
| Parameter | Description |
|
||||
|-----------|-------------|
|
||||
| `upload_id` | Upload session ID returned during initialization |
|
||||
| `chunk_index` | Chunk index, starting from 0 |
|
||||
|
||||
**Request body:**
|
||||
|
||||
Content-Type: `multipart/form-data`
|
||||
|
||||
| Parameter | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `chunk` | file | Chunk data |
|
||||
|
||||
**Response example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"chunk_hash": "a1b2c3d4e5f6..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**cURL example:**
|
||||
|
||||
```bash
|
||||
# Upload first chunk (index 0)
|
||||
curl -X POST "http://localhost:12345/chunk/upload/chunk/abc123def456789/0" \
|
||||
-F "chunk=@/path/to/chunk_0"
|
||||
```
|
||||
|
||||
### 3. Complete Upload
|
||||
|
||||
**POST** `/chunk/upload/complete/{upload_id}`
|
||||
|
||||
**Path parameters:**
|
||||
|
||||
| Parameter | Description |
|
||||
|-----------|-------------|
|
||||
| `upload_id` | Upload session ID |
|
||||
|
||||
**Request parameters:**
|
||||
|
||||
```json
|
||||
{
|
||||
"expire_value": 7,
|
||||
"expire_style": "day"
|
||||
}
|
||||
```
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| `expire_value` | int | Yes | Expiration value |
|
||||
| `expire_style` | string | Yes | Expiration method |
|
||||
|
||||
**Response example:**
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"code": "789012",
|
||||
"name": "large_file.zip"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Resume Upload
|
||||
|
||||
Chunked upload supports resume functionality. When upload is interrupted:
|
||||
|
||||
1. Call the initialization endpoint again with the same `file_hash`
|
||||
2. Server returns `uploaded_chunks` list containing already uploaded chunk indices
|
||||
3. Client only needs to upload chunks not in the list
|
||||
4. Call the complete endpoint after all chunks are uploaded
|
||||
|
||||
**Example flow:**
|
||||
|
||||
```javascript
|
||||
// 1. Initialize upload
|
||||
const initResponse = await fetch('/chunk/upload/init/', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
file_name: 'large_file.zip',
|
||||
file_size: fileSize,
|
||||
chunk_size: 5 * 1024 * 1024,
|
||||
file_hash: fileHash
|
||||
})
|
||||
});
|
||||
const { upload_id, uploaded_chunks, total_chunks } = await initResponse.json();
|
||||
|
||||
// 2. Upload incomplete chunks
|
||||
for (let i = 0; i < total_chunks; i++) {
|
||||
if (!uploaded_chunks.includes(i)) {
|
||||
const chunk = file.slice(i * chunkSize, (i + 1) * chunkSize);
|
||||
await fetch(`/chunk/upload/chunk/${upload_id}/${i}`, {
|
||||
method: 'POST',
|
||||
body: chunk
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Complete upload
|
||||
await fetch(`/chunk/upload/complete/${upload_id}`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
expire_value: 7,
|
||||
expire_style: 'day'
|
||||
})
|
||||
});
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Common Errors
|
||||
|
||||
| HTTP Status | Error Message | Cause | Solution |
|
||||
|-------------|---------------|-------|----------|
|
||||
| 403 | Size exceeds limit | File exceeds `uploadSize` limit | Reduce file size or contact administrator to adjust limit |
|
||||
| 403 | Upload rate limit | Exceeded IP upload rate limit | Wait for limit time window before retrying |
|
||||
| 400 | Invalid expiration type | `expire_style` value not in allowed list | Use a valid expiration method |
|
||||
| 404 | Upload session not found | `upload_id` invalid or expired | Re-initialize upload |
|
||||
| 400 | Invalid chunk index | `chunk_index` out of range | Check if chunk index is correct |
|
||||
| 400 | Incomplete chunks | Chunk count insufficient when completing upload | Ensure all chunks are uploaded |
|
||||
|
||||
### Rate Limiting
|
||||
|
||||
The system has rate limits on upload operations to prevent abuse:
|
||||
|
||||
| Setting | Default | Description |
|
||||
|---------|---------|-------------|
|
||||
| `uploadMinute` | 1 | Limit time window (minutes) |
|
||||
| `uploadCount` | 10 | Maximum uploads within time window |
|
||||
|
||||
When rate limit is exceeded, you need to wait for the time window to pass before continuing uploads.
|
||||
|
||||
### Error Response Format
|
||||
|
||||
```json
|
||||
{
|
||||
"detail": "Error message description"
|
||||
}
|
||||
```
|
||||
|
||||
## Upload Configuration
|
||||
|
||||
### Related Settings
|
||||
|
||||
| Setting | Type | Default | Description |
|
||||
|---------|------|---------|-------------|
|
||||
| `openUpload` | int | 1 | Enable upload (1=enabled, 0=disabled) |
|
||||
| `uploadSize` | int | 10485760 | Maximum upload size (bytes) |
|
||||
| `enableChunk` | int | 0 | Enable chunked upload (1=enabled, 0=disabled) |
|
||||
| `uploadMinute` | int | 1 | Upload rate limit time window (minutes) |
|
||||
| `uploadCount` | int | 10 | Maximum uploads within time window |
|
||||
| `expireStyle` | list | ["day","hour","minute","forever","count"] | Allowed expiration methods |
|
||||
|
||||
### Configuration Example
|
||||
|
||||
```python
|
||||
# Allow 100MB file uploads, enable chunked upload
|
||||
uploadSize = 104857600
|
||||
enableChunk = 1
|
||||
|
||||
# Relax upload rate limit: max 50 uploads per 5 minutes
|
||||
uploadMinute = 5
|
||||
uploadCount = 50
|
||||
|
||||
# Only allow expiration by days and count
|
||||
expireStyle = ["day", "count"]
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
- [File Sharing](/en/guide/share) - Learn the complete sharing process
|
||||
- [Configuration Guide](/en/guide/configuration) - Learn about all configuration options
|
||||
- [Storage Configuration](/en/guide/storage) - Learn about file storage methods
|
||||
- [Security Settings](/en/guide/security) - Learn about security-related configurations
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
layout: home
|
||||
|
||||
hero:
|
||||
name: "FileCodeBox"
|
||||
text: "Share files like picking up a package"
|
||||
tagline: A lightweight, modern, self-hosted service for files and text
|
||||
image:
|
||||
src: /logo_small.png
|
||||
alt: FileCodeBox
|
||||
actions:
|
||||
- theme: brand
|
||||
text: Get Started
|
||||
link: /en/guide/getting-started
|
||||
- theme: alt
|
||||
text: Live Demo
|
||||
link: https://share.lanol.cn
|
||||
- theme: alt
|
||||
text: Deployment Guide
|
||||
link: /en/guide/getting-started#docker-deployment-recommended
|
||||
|
||||
features:
|
||||
- icon: 01
|
||||
title: Share instantly
|
||||
details: Files and text in one flow, with batch, chunked, and resumable uploads
|
||||
- icon: 02
|
||||
title: Flexible expiry
|
||||
details: Expire by time or retrieval count, or keep content permanently
|
||||
- icon: 03
|
||||
title: Own your data
|
||||
details: Local, S3, OneDrive, WebDAV, and OpenDAL storage
|
||||
---
|
||||
|
||||
## Start in 30 seconds
|
||||
|
||||
```bash
|
||||
docker run -d --restart unless-stopped \
|
||||
-p 12345:12345 \
|
||||
-v ./data:/app/data \
|
||||
--name filecodebox \
|
||||
lanol/filecodebox:2.5.3 # x-release-please-version
|
||||
```
|
||||
|
||||
Open `http://localhost:12345` and complete the first-run setup.
|
||||
|
||||
<div class="doc-paths">
|
||||
<a class="doc-path" href="/en/guide/getting-started">
|
||||
<span>Get started</span>
|
||||
<strong>Deploy, initialize, and upgrade</strong>
|
||||
<small>Run FileCodeBox from a clean server →</small>
|
||||
</a>
|
||||
<a class="doc-path" href="/en/guide/storage">
|
||||
<span>Operate</span>
|
||||
<strong>Storage, configuration, and security</strong>
|
||||
<small>Choose production-ready storage and protection →</small>
|
||||
</a>
|
||||
<a class="doc-path" href="/en/api/">
|
||||
<span>Integrate</span>
|
||||
<strong>API and upload workflows</strong>
|
||||
<small>Build on sharing, chunked uploads, and administration →</small>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
::: warning Responsible use
|
||||
Use FileCodeBox only for lawful file and text sharing. Operators are responsible for deployment security, data compliance, and content moderation.
|
||||
:::
|
||||
@@ -0,0 +1,127 @@
|
||||
# Showcase
|
||||
|
||||
Here are some excellent sites built with FileCodeBox. If you've deployed FileCodeBox, feel free to submit a PR to add your site here!
|
||||
|
||||
## Official Demo
|
||||
|
||||
<div class="showcase-grid">
|
||||
|
||||
<div class="showcase-item">
|
||||
|
||||
### 🌟 FileCodeBox Demo
|
||||
|
||||
- **URL**: [share.lanol.cn](https://share.lanol.cn)
|
||||
- **Description**: Official demo site with the latest features
|
||||
- **Highlights**: Stable, full-featured
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
## Community Sites
|
||||
|
||||
::: tip Submit Your Site
|
||||
If you've built your own file sharing service using FileCodeBox, you can submit it through:
|
||||
|
||||
1. Submit a PR on [GitHub](https://github.com/vastsa/FileCodeBox) to edit this page
|
||||
2. Open an [Issue](https://github.com/vastsa/FileCodeBox/issues) with your site info
|
||||
3. Join QQ Group 739673698 to contact the admin
|
||||
:::
|
||||
|
||||
<!--
|
||||
Submission format example:
|
||||
|
||||
<div class="showcase-item">
|
||||
|
||||
### Site Name
|
||||
|
||||
- **URL**: [example.com](https://example.com)
|
||||
- **Description**: Brief description of your site
|
||||
- **Highlights**: List your site's features
|
||||
|
||||
</div>
|
||||
-->
|
||||
|
||||
<div class="showcase-grid">
|
||||
|
||||
<div class="showcase-item">
|
||||
|
||||
### QuWenJian
|
||||
|
||||
- **URL**: [www.quwenjian.cn/fby.html](https://www.quwenjian.cn/fby.html)
|
||||
- **Description**: QuWenJian - Unlimited storage, portable and limitless
|
||||
- **Highlights**: Free file transfer station
|
||||
- **Operator**: QuWenJian
|
||||
|
||||
</div>
|
||||
|
||||
<div class="showcase-item">
|
||||
|
||||
### Pandora Box
|
||||
|
||||
- **URL**: [pan.duo.la](https://pan.duo.la)
|
||||
- **Description**: Pandora Box
|
||||
- **Highlights**: Classic v1.6 version
|
||||
- **Operator**: WuXingQueXinYan
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
## Submission Requirements
|
||||
|
||||
To ensure quality, please make sure your site meets the following criteria:
|
||||
|
||||
1. **Stable**: Your site should be stable and accessible
|
||||
2. **Legal**: Content must be legal and compliant
|
||||
3. **Attribution**: We recommend keeping FileCodeBox attribution
|
||||
4. **HTTPS**: We recommend enabling HTTPS
|
||||
|
||||
## Submission Template
|
||||
|
||||
If you want to submit your site, please use the following format:
|
||||
|
||||
```markdown
|
||||
### Site Name
|
||||
|
||||
- **URL**: [domain](https://domain)
|
||||
- **Description**: One-line description of your site
|
||||
- **Highlights**: Special features or highlights
|
||||
- **Operator**: Optional, your name or organization
|
||||
```
|
||||
|
||||
<style>
|
||||
.showcase-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
|
||||
gap: 20px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.showcase-item {
|
||||
border: 1px solid var(--vp-c-divider);
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.showcase-item:hover {
|
||||
border-color: var(--vp-c-brand);
|
||||
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.showcase-item h3 {
|
||||
margin-top: 0;
|
||||
color: var(--vp-c-brand);
|
||||
}
|
||||
|
||||
.showcase-item ul {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.showcase-item li {
|
||||
margin: 8px 0;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,213 @@
|
||||
# 配置说明
|
||||
|
||||
FileCodeBox 提供了丰富的配置选项。请优先通过管理面板修改,避免直接编辑数据库造成类型错误或安全配置失效。
|
||||
|
||||
## 配置方式
|
||||
|
||||
FileCodeBox 支持两种配置方式:
|
||||
|
||||
1. **管理面板配置**(推荐):访问 `/admin` 进入管理面板,在设置页面修改配置
|
||||
2. **数据库配置**:配置存储在 `data/filecodebox.db` 数据库中
|
||||
|
||||
::: tip 提示
|
||||
首次启动时,系统会使用 `core/settings.py` 中的默认配置。修改后的配置会保存到数据库中。
|
||||
:::
|
||||
|
||||
## 基础设置
|
||||
|
||||
### 站点信息
|
||||
|
||||
| 配置项 | 类型 | 默认值 | 说明 |
|
||||
|--------|------|--------|------|
|
||||
| `name` | string | `文件快递柜 - FileCodeBox` | 站点名称,显示在页面标题和导航栏 |
|
||||
| `description` | string | `开箱即用的文件快传系统` | 站点描述,用于 SEO |
|
||||
| `keywords` | string | `FileCodeBox, 文件快递柜...` | 站点关键词,用于 SEO |
|
||||
| `serverHost` | string | `0.0.0.0` | 服务监听地址 |
|
||||
| `serverPort` | int | `12345` | 服务监听端口 |
|
||||
| `serverWorkers` | int | `1` | 工作进程数;SQLite 部署建议保持单进程 |
|
||||
|
||||
### 通知设置
|
||||
|
||||
| 配置项 | 类型 | 默认值 | 说明 |
|
||||
|--------|------|--------|------|
|
||||
| `notify_title` | string | `系统通知` | 通知标题 |
|
||||
| `notify_content` | string | 欢迎信息 | 通知内容,支持 HTML |
|
||||
| `page_explain` | string | 法律声明 | 页面底部说明文字 |
|
||||
| `robotsText` | string | `User-agent: *\nDisallow: /` | robots.txt 内容 |
|
||||
|
||||
## 上传设置
|
||||
|
||||
### 文件上传限制
|
||||
|
||||
| 配置项 | 类型 | 默认值 | 说明 |
|
||||
|--------|------|--------|------|
|
||||
| `openUpload` | int | `1` | 是否开启上传功能(1=开启,0=关闭) |
|
||||
| `uploadSize` | int | `10485760` | 单文件最大上传大小(字节),默认 10MB |
|
||||
| `enableChunk` | int | `0` | 是否启用分片上传(1=启用,0=禁用) |
|
||||
| `allowed_file_types` | list | `["*"]` | 允许上传的扩展名;`*` 表示不限制 |
|
||||
|
||||
::: warning 注意
|
||||
`uploadSize` 的单位是字节。10MB = 10 * 1024 * 1024 = 10485760 字节
|
||||
:::
|
||||
|
||||
### 上传频率限制
|
||||
|
||||
| 配置项 | 类型 | 默认值 | 说明 |
|
||||
|--------|------|--------|------|
|
||||
| `uploadMinute` | int | `1` | 上传限制的时间窗口(分钟) |
|
||||
| `uploadCount` | int | `10` | 在时间窗口内允许的最大上传次数 |
|
||||
|
||||
例如:默认配置表示每 1 分钟内最多允许上传 10 次。
|
||||
|
||||
### 文件过期设置
|
||||
|
||||
| 配置项 | 类型 | 默认值 | 说明 |
|
||||
|--------|------|--------|------|
|
||||
| `expireStyle` | list | `["day","hour","minute","forever","count"]` | 可选的过期方式 |
|
||||
| `max_save_seconds` | int | `0` | 文件最大保存时间(秒),0 表示不限制 |
|
||||
|
||||
过期方式说明:
|
||||
- `day` - 按天过期
|
||||
- `hour` - 按小时过期
|
||||
- `minute` - 按分钟过期
|
||||
- `forever` - 永不过期
|
||||
- `count` - 按下载次数过期
|
||||
|
||||
## 主题设置
|
||||
|
||||
### 主题选择
|
||||
|
||||
| 配置项 | 类型 | 默认值 | 说明 |
|
||||
|--------|------|--------|------|
|
||||
| `themesSelect` | string | `themes/2024` | 当前使用的主题 |
|
||||
| `themesChoices` | list | 见下方 | 可用主题列表 |
|
||||
|
||||
默认可用主题:
|
||||
```json
|
||||
[
|
||||
{
|
||||
"name": "2023",
|
||||
"key": "themes/2023",
|
||||
"author": "Lan",
|
||||
"version": "1.0"
|
||||
},
|
||||
{
|
||||
"name": "2024",
|
||||
"key": "themes/2024",
|
||||
"author": "Lan",
|
||||
"version": "1.0"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
### 界面样式
|
||||
|
||||
| 配置项 | 类型 | 默认值 | 说明 |
|
||||
|--------|------|--------|------|
|
||||
| `opacity` | float | `0.9` | 界面透明度(0-1) |
|
||||
| `background` | string | `""` | 自定义背景图片 URL,为空则使用默认背景 |
|
||||
|
||||
## 管理员设置
|
||||
|
||||
| 配置项 | 类型 | 默认值 | 说明 |
|
||||
|--------|------|--------|------|
|
||||
| `admin_token` | string | 初始化页面设置 | 管理员登录密码(哈希存储) |
|
||||
| `showAdminAddr` | int | `0` | 是否在首页显示管理入口(1=显示,0=隐藏) |
|
||||
| `adminSessionExpire` | int | `2592000` | 管理会话有效期(秒),默认 30 天 |
|
||||
|
||||
::: danger 安全警告
|
||||
未初始化时会自动显示初始化页面。生产环境请在服务对外开放前完成初始化。
|
||||
:::
|
||||
|
||||
## 安全设置
|
||||
|
||||
### 错误次数限制
|
||||
|
||||
| 配置项 | 类型 | 默认值 | 说明 |
|
||||
|--------|------|--------|------|
|
||||
| `errorMinute` | int | `1` | 错误限制的时间窗口(分钟) |
|
||||
| `errorCount` | int | `10` | 在时间窗口内允许的最大错误次数 |
|
||||
| `trustedProxies` | list | `[]` | 可信反向代理 IP;用于安全解析客户端地址 |
|
||||
|
||||
此设置用于防止暴力破解提取码。
|
||||
|
||||
## 存储设置
|
||||
|
||||
### 存储类型
|
||||
|
||||
| 配置项 | 类型 | 默认值 | 说明 |
|
||||
|--------|------|--------|------|
|
||||
| `file_storage` | string | `local` | 存储后端类型 |
|
||||
| `storage_path` | string | `""` | 自定义存储路径 |
|
||||
| `storageLimit` | int | `0` | 总存储配额(字节),0 表示不限制 |
|
||||
|
||||
支持的存储类型:
|
||||
- `local` - 本地存储
|
||||
- `s3` - S3 兼容存储(AWS S3、阿里云 OSS、MinIO 等)
|
||||
- `onedrive` - OneDrive 存储
|
||||
- `webdav` - WebDAV 存储
|
||||
- `opendal` - OpenDAL 存储
|
||||
|
||||
详细的存储配置请参考 [存储配置](/guide/storage)。
|
||||
|
||||
## 配置示例
|
||||
|
||||
### 示例 1:小型个人使用
|
||||
|
||||
适合个人或小团队使用,限制较宽松:
|
||||
|
||||
```python
|
||||
{
|
||||
"name": "我的文件分享",
|
||||
"uploadSize": 52428800, # 50MB
|
||||
"uploadMinute": 5, # 5分钟
|
||||
"uploadCount": 20, # 最多20次
|
||||
"expireStyle": ["day", "hour", "forever"],
|
||||
"showAdminAddr": 1
|
||||
}
|
||||
```
|
||||
|
||||
### 示例 2:公开服务
|
||||
|
||||
适合公开服务,需要更严格的限制:
|
||||
|
||||
```python
|
||||
{
|
||||
"name": "公共文件快递柜",
|
||||
"uploadSize": 10485760, # 10MB
|
||||
"uploadMinute": 1, # 1分钟
|
||||
"uploadCount": 5, # 最多5次
|
||||
"errorMinute": 5, # 5分钟
|
||||
"errorCount": 3, # 最多3次错误
|
||||
"expireStyle": ["hour", "minute", "count"],
|
||||
"max_save_seconds": 86400, # 最长保存1天
|
||||
"showAdminAddr": 0
|
||||
}
|
||||
```
|
||||
|
||||
### 示例 3:企业内部使用
|
||||
|
||||
适合企业内部使用,支持大文件和分片上传:
|
||||
|
||||
```python
|
||||
{
|
||||
"name": "企业文件中转站",
|
||||
"uploadSize": 1073741824, # 1GB
|
||||
"enableChunk": 1, # 启用分片上传
|
||||
"uploadMinute": 10, # 10分钟
|
||||
"uploadCount": 100, # 最多100次
|
||||
"expireStyle": ["day", "forever"],
|
||||
"file_storage": "s3", # 使用S3存储
|
||||
"showAdminAddr": 1
|
||||
}
|
||||
```
|
||||
|
||||
::: warning 配置示例
|
||||
以上字典仅用于展示配置值组合,不是可直接编辑的配置文件。管理员密码请在初始化页面或管理面板中设置。
|
||||
:::
|
||||
|
||||
## 下一步
|
||||
|
||||
- [存储配置](/guide/storage) - 了解如何配置不同的存储后端
|
||||
- [安全设置](/guide/security) - 了解如何增强系统安全性
|
||||
- [文件分享](/guide/share) - 了解文件分享功能
|
||||
@@ -0,0 +1,126 @@
|
||||
# 快速开始
|
||||
|
||||
## 简介
|
||||
|
||||
FileCodeBox 是一个简单高效的文件分享工具,支持文件临时中转、分享和管理。本指南将帮助您快速部署和使用 FileCodeBox。
|
||||
|
||||
## 特性
|
||||
|
||||
- 🚀 快速部署:支持 Docker 一键部署
|
||||
- 🔒 安全可靠:文件访问需要提取码
|
||||
- ⏱️ 时效控制:支持设置文件有效期
|
||||
- 📊 下载限制:可限制文件下载次数
|
||||
- 🖼️ 文件预览:支持图片、视频、音频等多种格式预览
|
||||
- 📱 响应式设计:完美适配移动端和桌面端
|
||||
|
||||
## 部署方式
|
||||
|
||||
### Docker 部署(推荐)
|
||||
|
||||
#### 快速启动
|
||||
|
||||
```bash
|
||||
docker run -d --restart unless-stopped \
|
||||
-p 12345:12345 \
|
||||
-v fcb-data:/app/data \
|
||||
--name filecodebox \
|
||||
lanol/filecodebox:latest
|
||||
```
|
||||
|
||||
#### Docker Compose
|
||||
|
||||
```yml
|
||||
version: "3"
|
||||
services:
|
||||
file-code-box:
|
||||
image: lanol/filecodebox:latest
|
||||
volumes:
|
||||
- fcb-data:/app/data:rw
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "12345:12345"
|
||||
environment:
|
||||
- WORKERS=1
|
||||
- LOG_LEVEL=info
|
||||
volumes:
|
||||
fcb-data:
|
||||
external: false
|
||||
```
|
||||
|
||||
#### 环境变量
|
||||
|
||||
| 变量 | 默认值 | 说明 |
|
||||
|------|--------|------|
|
||||
| `HOST` | `0.0.0.0` | 服务监听地址 |
|
||||
| `PORT` | `12345` | 服务端口 |
|
||||
| `WORKERS` | `1` | 工作进程数;SQLite 部署建议保持单进程 |
|
||||
| `LOG_LEVEL` | `info` | 日志级别:debug/info/warning/error |
|
||||
|
||||
#### 自定义配置示例
|
||||
|
||||
```bash
|
||||
docker run -d --restart=always \
|
||||
-p 12345:12345 \
|
||||
-v fcb-data:/app/data \
|
||||
-e WORKERS=1 \
|
||||
-e LOG_LEVEL=warning \
|
||||
--name filecodebox \
|
||||
lanol/filecodebox:latest
|
||||
```
|
||||
|
||||
### 配置反向代理(Nginx)
|
||||
|
||||
```nginx
|
||||
location / {
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_pass http://localhost:12345;
|
||||
}
|
||||
```
|
||||
|
||||
### 手动部署
|
||||
|
||||
1. 克隆项目
|
||||
```bash
|
||||
git clone https://github.com/vastsa/FileCodeBox.git
|
||||
```
|
||||
|
||||
2. 安装依赖
|
||||
```bash
|
||||
cd FileCodeBox
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. 启动服务
|
||||
```bash
|
||||
python main.py
|
||||
```
|
||||
|
||||
|
||||
## 使用方法
|
||||
|
||||
1. 访问系统
|
||||
打开浏览器访问 `http://localhost:12345`
|
||||
|
||||
2. 上传文件
|
||||
- 点击上传按钮或拖拽文件到上传区域
|
||||
- 设置文件有效期和下载次数限制
|
||||
- 获取分享链接和提取码
|
||||
|
||||
3. 下载文件
|
||||
- 访问分享链接
|
||||
- 输入提取码
|
||||
- 下载文件
|
||||
|
||||
4. 后台管理
|
||||
- 首次访问 `http://localhost:12345` 完成初始化
|
||||
- 访问 `http://localhost:12345/#/admin`
|
||||
- 输入初始化时设置的管理员密码
|
||||
- 进入后台管理页面
|
||||
- 查看系统信息、文件列表、活动记录和系统配置
|
||||
|
||||
## 下一步
|
||||
|
||||
- [存储配置](/guide/storage) - 了解如何配置不同的存储方式
|
||||
- [安全设置](/guide/security) - 了解如何增强系统安全性
|
||||
- [API 文档](/api/) - 了解如何通过 API 集成
|
||||
@@ -0,0 +1,235 @@
|
||||
<div align="center">
|
||||
|
||||
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/static/banners/img_1.png" alt="FileCodeBox Logo">
|
||||
|
||||
<p><em>匿名口令分享文本和文件,像拿快递一样取文件</em></p>
|
||||
|
||||
[](https://github.com/vastsa/FileCodeBox/stargazers)
|
||||
[](https://github.com/vastsa/FileCodeBox/network)
|
||||
[](https://github.com/vastsa/FileCodeBox/issues)
|
||||
[](https://github.com/vastsa/FileCodeBox/blob/master/LICENSE)
|
||||
[](https://qm.qq.com/q/PemPzhdEIM)
|
||||
[](https://www.python.org)
|
||||
[](https://fastapi.tiangolo.com)
|
||||
[](https://v3.vuejs.org)
|
||||
</div>
|
||||
|
||||
|
||||
## 🚀 更新计划
|
||||
- [ ] 切片上传,同文件秒传,断点续传
|
||||
- [ ] 用户登录重构
|
||||
- [x] webdav存储
|
||||
- [x] 存储支持自定义路径
|
||||
- [x] s3优化,不修改昵称为uuid,新建目录
|
||||
|
||||
## 📝 项目简介
|
||||
|
||||
FileCodeBox 是一个基于 FastAPI + Vue3 开发的轻量级文件分享工具。它允许用户通过简单的方式分享文本和文件,接收者只需要一个提取码就可以取得文件,就像从快递柜取出快递一样简单。
|
||||
|
||||
## 🎯 应用场景
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>📁 临时文件分享</h4>
|
||||
快速分享单个文件,无需注册登录
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>📝 文本快速分享</h4>
|
||||
分享代码片段、文本内容等
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🕶️ 匿名文件传输</h4>
|
||||
保护隐私的文件传输方式
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>💾 临时文件存储</h4>
|
||||
支持设置过期时间的文件存储
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🔄 跨平台传输</h4>
|
||||
在不同设备间快速传输文件
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🌐 小型分享服务</h4>
|
||||
搭建私有的文件分享服务
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## ✨ 核心特性
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>🚀 轻量简洁</h4>
|
||||
基于 FastAPI + SQLite3 + Vue3 + ElementUI,部署简单,性能出色
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>📤 便捷上传</h4>
|
||||
支持复制粘贴、拖拽上传,操作简单直观
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>📦 多种类型</h4>
|
||||
支持文本和各类文件的分享
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>🔒 安全机制</h4>
|
||||
|
||||
- IP 限制上传次数
|
||||
- 错误次数限制
|
||||
- 文件过期机制
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🎫 提取码分享</h4>
|
||||
随机提取码,可自定义次数及有效期
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🌍 多语言支持</h4>
|
||||
支持中文简体、繁体及英文
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>🎭 匿名分享</h4>
|
||||
无需注册登录,保护隐私
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🛠 管理面板</h4>
|
||||
文件管理和系统配置
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>🐳 容器部署</h4>
|
||||
支持 Docker 一键部署
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h4>💾 存储扩展</h4>
|
||||
支持本地存储、S3 协议、OneDrive 等
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>📱 响应式设计</h4>
|
||||
支持移动端访问
|
||||
</td>
|
||||
<td align="center">
|
||||
<h4>💻 终端支持</h4>
|
||||
支持命令行下载
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### Docker 部署
|
||||
|
||||
```bash
|
||||
docker run -d --restart unless-stopped -p 12345:12345 -v fcb-data:/app/data --name filecodebox lanol/filecodebox:latest
|
||||
```
|
||||
|
||||
### 手动部署
|
||||
|
||||
1. 克隆项目
|
||||
```bash
|
||||
git clone https://github.com/vastsa/FileCodeBox.git
|
||||
```
|
||||
|
||||
2. 安装依赖
|
||||
```bash
|
||||
cd FileCodeBox
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. 启动服务
|
||||
```bash
|
||||
python main.py
|
||||
```
|
||||
|
||||
## 📖 使用说明
|
||||
|
||||
### 分享文件
|
||||
1. 打开网页,点击"分享文件"
|
||||
2. 选择或拖拽文件
|
||||
3. 设置过期时间和次数
|
||||
4. 获取提取码
|
||||
|
||||
### 获取文件
|
||||
1. 打开网页,输入提取码
|
||||
2. 点击获取
|
||||
3. 下载文件或查看文本
|
||||
|
||||
### 管理面板
|
||||
1. 访问 `/admin`
|
||||
2. 输入管理员密码
|
||||
3. 管理文件和配置
|
||||
|
||||
## 🛠 开发指南
|
||||
|
||||
### 项目结构
|
||||
```
|
||||
FileCodeBox/
|
||||
├── apps/ # 应用代码
|
||||
│ ├── admin/ # 管理后台
|
||||
│ └── base/ # 基础功能
|
||||
├── core/ # 核心功能
|
||||
├── data/ # 数据目录
|
||||
└── fcb-fronted/ # 前端代码
|
||||
```
|
||||
|
||||
### 开发环境
|
||||
- Python 3.8+
|
||||
- Node.js 14+
|
||||
- Vue 3
|
||||
- FastAPI
|
||||
|
||||
### 本地开发
|
||||
1. 后端开发
|
||||
```bash
|
||||
python main.py
|
||||
```
|
||||
|
||||
2. 前端开发
|
||||
```bash
|
||||
cd fcb-fronted
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## 🤝 贡献指南
|
||||
|
||||
1. Fork 本项目
|
||||
2. 创建新分支 `git checkout -b feature/xxx`
|
||||
3. 提交更改 `git commit -m 'Add xxx'`
|
||||
4. 推送到分支 `git push origin feature/xxx`
|
||||
5. 提交 Pull Request
|
||||
|
||||
## ❓ 常见问题
|
||||
|
||||
### Q: 如何修改上传大小限制?
|
||||
A: 在管理面板中修改配置项 `uploadSize`
|
||||
|
||||
### Q: 如何配置存储引擎?
|
||||
A: 在管理面板中选择存储引擎并配置相应参数
|
||||
|
||||
### Q: 如何备份数据?
|
||||
A: 备份 `data` 目录即可
|
||||
|
||||
更多问题请访问 [Wiki](https://github.com/vastsa/FileCodeBox/wiki/常见问题)
|
||||
|
||||
## 📊 项目统计
|
||||
|
||||
<div align="center">
|
||||
<a href="https://hellogithub.com/repository/75ad7ffedd404a6485b4d621ec5b47e6" target="_blank"><img src="https://api.hellogithub.com/v1/widgets/recommend.svg?rid=75ad7ffedd404a6485b4d621ec5b47e6&claim_uid=beSz6INEkCM4mDH" alt="Featured|HelloGitHub" style="width: 200px; height: 45px;" width="200" height="45" /></a>
|
||||
|
||||

|
||||
|
||||
[](https://star-history.com/#vastsa/FileCodeBox&Date)
|
||||
</div>
|
||||
|
||||
## 📜 免责声明
|
||||
|
||||
本项目开源仅供学习使用,不得用于任何违法用途,否则后果自负,与作者无关。使用时请保留项目地址和版权信息。
|
||||
@@ -0,0 +1,413 @@
|
||||
# 管理面板
|
||||
|
||||
FileCodeBox 提供了功能完善的管理面板,让管理员可以方便地管理文件、查看系统状态和修改配置。本文档介绍管理面板的各项功能和使用方法。
|
||||
|
||||
## 访问管理面板
|
||||
|
||||
### 登录方式
|
||||
|
||||
管理面板位于 `/admin` 路径。访问方式:
|
||||
|
||||
1. 首次访问站点时,按初始化页面设置管理员密码
|
||||
2. 在浏览器中访问 `http://your-domain.com/admin`
|
||||
3. 输入管理员密码(`admin_token` 配置项的值)
|
||||
4. 点击登录按钮
|
||||
|
||||
::: tip 提示
|
||||
未初始化时会自动进入初始化页面。生产环境请先完成初始化,再开放公网访问。
|
||||
:::
|
||||
|
||||
### 显示管理入口
|
||||
|
||||
默认情况下,首页不显示管理面板入口。您可以通过配置控制是否显示:
|
||||
|
||||
| 配置项 | 类型 | 默认值 | 说明 |
|
||||
|--------|------|--------|------|
|
||||
| `showAdminAddr` | int | `0` | 是否在首页显示管理入口(1=显示,0=隐藏) |
|
||||
|
||||
::: warning 安全建议
|
||||
在公开服务中,建议保持 `showAdminAddr` 为 `0`,通过直接访问 `/admin` 路径进入管理面板,减少被恶意扫描的风险。
|
||||
:::
|
||||
|
||||
### 认证机制
|
||||
|
||||
管理面板使用 JWT(JSON Web Token)进行身份认证:
|
||||
|
||||
1. 登录成功后,服务器返回一个包含管理员身份的 Token
|
||||
2. 后续请求通过 `Authorization: Bearer <token>` 头部携带 Token
|
||||
3. Token 用于验证管理员身份,确保只有授权用户可以访问管理功能
|
||||
|
||||
## 仪表盘
|
||||
|
||||
登录后首先看到的是仪表盘页面,展示系统的整体运行状态。
|
||||
|
||||
### 统计指标
|
||||
|
||||
仪表盘显示以下关键指标:
|
||||
|
||||
| 指标 | 说明 |
|
||||
|------|------|
|
||||
| **文件总数** (`totalFiles`) | 系统中存储的文件总数量 |
|
||||
| **存储使用量** (`storageUsed`) | 所有文件占用的总存储空间(字节) |
|
||||
| **系统运行时间** (`sysUptime`) | 系统首次启动的时间 |
|
||||
| **昨日上传数** (`yesterdayCount`) | 昨天一整天上传的文件数量 |
|
||||
| **昨日上传量** (`yesterdaySize`) | 昨天上传文件的总大小(字节) |
|
||||
| **今日上传数** (`todayCount`) | 今天到目前为止上传的文件数量 |
|
||||
| **今日上传量** (`todaySize`) | 今天上传文件的总大小(字节) |
|
||||
|
||||
### 指标说明
|
||||
|
||||
- **文件总数**:包括所有未过期的文件和文本分享
|
||||
- **存储使用量**:显示实际文件占用的存储空间,不包括数据库等系统文件
|
||||
- **昨日/今日统计**:基于文件创建时间计算,用于了解系统使用趋势
|
||||
|
||||
::: tip 提示
|
||||
存储使用量显示的是字节数。例如 `10485760` 表示约 10MB。
|
||||
:::
|
||||
|
||||
## 文件管理
|
||||
|
||||
### 文件列表
|
||||
|
||||
文件管理页面展示系统中所有已分享的文件,支持分页浏览和搜索。
|
||||
|
||||
**列表信息包括:**
|
||||
- 文件 ID
|
||||
- 提取码(code)
|
||||
- 文件名前缀(prefix)
|
||||
- 文件后缀(suffix)
|
||||
- 文件大小
|
||||
- 创建时间
|
||||
- 过期时间
|
||||
- 剩余下载次数
|
||||
|
||||
### 搜索文件
|
||||
|
||||
使用搜索功能可以快速找到特定文件:
|
||||
|
||||
1. 在搜索框中输入关键词
|
||||
2. 系统会根据文件名前缀(prefix)进行模糊匹配
|
||||
3. 搜索结果实时更新
|
||||
|
||||
**搜索示例:**
|
||||
- 输入 `report` 可以找到所有文件名包含 "report" 的文件
|
||||
- 输入 `.pdf` 可以找到所有 PDF 文件(如果文件名包含此字符串)
|
||||
|
||||
### 分页浏览
|
||||
|
||||
文件列表支持分页显示:
|
||||
|
||||
| 参数 | 默认值 | 说明 |
|
||||
|------|--------|------|
|
||||
| `page` | `1` | 当前页码 |
|
||||
| `size` | `10` | 每页显示数量 |
|
||||
|
||||
### 删除文件
|
||||
|
||||
管理员可以删除任意文件:
|
||||
|
||||
1. 在文件列表中找到要删除的文件
|
||||
2. 点击删除按钮
|
||||
3. 确认删除操作
|
||||
|
||||
::: danger 警告
|
||||
删除操作不可恢复!文件将从存储后端永久删除,同时删除数据库中的记录。
|
||||
:::
|
||||
|
||||
**删除流程:**
|
||||
1. 系统首先从存储后端(本地/S3/OneDrive 等)删除实际文件
|
||||
2. 然后从数据库中删除文件记录
|
||||
3. 删除后,对应的提取码将失效
|
||||
|
||||
### 下载文件
|
||||
|
||||
管理员可以直接下载任意文件:
|
||||
|
||||
1. 在文件列表中找到目标文件
|
||||
2. 点击下载按钮
|
||||
3. 文件将通过浏览器下载
|
||||
|
||||
对于文本分享,系统会直接返回文本内容而不是下载文件。
|
||||
|
||||
### 修改文件信息
|
||||
|
||||
管理员可以修改已分享文件的部分信息:
|
||||
|
||||
| 可修改字段 | 说明 |
|
||||
|------------|------|
|
||||
| `code` | 提取码(必须唯一,不能与其他文件重复) |
|
||||
| `prefix` | 文件名前缀 |
|
||||
| `suffix` | 文件后缀名 |
|
||||
| `expired_at` | 过期时间 |
|
||||
| `expired_count` | 剩余下载次数 |
|
||||
|
||||
**修改提取码:**
|
||||
```
|
||||
原提取码:abc123
|
||||
新提取码:myfile2024
|
||||
```
|
||||
|
||||
::: warning 注意
|
||||
修改提取码时,系统会检查新提取码是否已被使用。如果已存在相同的提取码,修改将失败。
|
||||
:::
|
||||
|
||||
## 本地文件管理
|
||||
|
||||
除了管理已分享的文件,管理面板还提供了本地文件管理功能,用于管理 `data/local` 目录中的文件。
|
||||
|
||||
### 查看本地文件
|
||||
|
||||
本地文件列表显示 `data/local` 目录中的所有文件:
|
||||
|
||||
| 信息 | 说明 |
|
||||
|------|------|
|
||||
| 文件名 | 文件的完整名称 |
|
||||
| 创建时间 | 文件的创建时间 |
|
||||
| 文件大小 | 文件大小(字节) |
|
||||
|
||||
### 分享本地文件
|
||||
|
||||
可以将本地文件快速分享:
|
||||
|
||||
1. 在本地文件列表中选择要分享的文件
|
||||
2. 设置过期方式和过期值
|
||||
3. 点击分享按钮
|
||||
4. 系统生成提取码
|
||||
|
||||
**分享参数:**
|
||||
|
||||
| 参数 | 说明 |
|
||||
|------|------|
|
||||
| `filename` | 要分享的文件名 |
|
||||
| `expire_style` | 过期方式(day/hour/minute/forever/count) |
|
||||
| `expire_value` | 过期值(天数/小时数/分钟数/下载次数) |
|
||||
|
||||
### 删除本地文件
|
||||
|
||||
可以删除 `data/local` 目录中的文件:
|
||||
|
||||
1. 在本地文件列表中找到要删除的文件
|
||||
2. 点击删除按钮
|
||||
3. 确认删除
|
||||
|
||||
::: tip 使用场景
|
||||
本地文件管理功能适用于:
|
||||
- 批量上传文件到服务器后进行分享
|
||||
- 管理通过其他方式上传到服务器的文件
|
||||
- 清理不需要的本地文件
|
||||
:::
|
||||
|
||||
## 系统设置
|
||||
|
||||
### 查看配置
|
||||
|
||||
在系统设置页面可以查看当前所有配置项的值。配置项按类别分组显示:
|
||||
|
||||
- 基础设置(站点名称、描述等)
|
||||
- 上传设置(文件大小限制、频率限制等)
|
||||
- 存储设置(存储类型、路径等)
|
||||
- 主题设置(主题选择、透明度等)
|
||||
- 安全设置(管理员密码、错误限制等)
|
||||
|
||||
### 修改配置
|
||||
|
||||
管理员可以通过管理面板修改大部分配置:
|
||||
|
||||
1. 进入系统设置页面
|
||||
2. 找到要修改的配置项
|
||||
3. 输入新的值
|
||||
4. 点击保存按钮
|
||||
|
||||
**可修改的配置项:**
|
||||
|
||||
| 类别 | 配置项示例 |
|
||||
|------|------------|
|
||||
| 基础设置 | `name`, `description`, `keywords`, `notify_title`, `notify_content` |
|
||||
| 上传设置 | `uploadSize`, `uploadMinute`, `uploadCount`, `openUpload`, `enableChunk` |
|
||||
| 过期设置 | `expireStyle`, `max_save_seconds` |
|
||||
| 主题设置 | `themesSelect`, `opacity`, `background` |
|
||||
| 安全设置 | `admin_token`, `showAdminAddr`, `errorMinute`, `errorCount` |
|
||||
| 存储设置 | `file_storage`, `storage_path` 及各存储后端的配置 |
|
||||
|
||||
::: warning 注意
|
||||
- `admin_token`(管理员密码)不能设置为空
|
||||
- `themesChoices`(主题列表)不可通过管理面板修改
|
||||
- 修改存储设置后,已有文件不会自动迁移
|
||||
:::
|
||||
|
||||
### 配置生效
|
||||
|
||||
配置修改后立即生效,无需重启服务。配置保存在数据库中,重启后仍然有效。
|
||||
|
||||
**配置存储位置:**
|
||||
- 数据库:`data/filecodebox.db`
|
||||
- 表名:`keyvalue`
|
||||
- 键名:`settings`
|
||||
|
||||
## API 接口
|
||||
|
||||
管理面板的所有功能都通过 REST API 实现,以下是主要接口:
|
||||
|
||||
### 认证接口
|
||||
|
||||
**登录**
|
||||
```
|
||||
POST /admin/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"password": "your-admin-password"
|
||||
}
|
||||
```
|
||||
|
||||
响应:
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"detail": {
|
||||
"token": "eyJhbGciOiJIUzI1NiIs...",
|
||||
"token_type": "Bearer"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 仪表盘接口
|
||||
|
||||
**获取统计数据**
|
||||
```
|
||||
GET /admin/dashboard
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
### 文件管理接口
|
||||
|
||||
**获取文件列表**
|
||||
```
|
||||
GET /admin/file/list?page=1&size=10&keyword=
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**删除文件**
|
||||
```
|
||||
DELETE /admin/file/delete
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"id": 123
|
||||
}
|
||||
```
|
||||
|
||||
**下载文件**
|
||||
```
|
||||
GET /admin/file/download?id=123
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**修改文件信息**
|
||||
```
|
||||
PATCH /admin/file/update
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"id": 123,
|
||||
"code": "newcode",
|
||||
"expired_at": "2024-12-31T23:59:59"
|
||||
}
|
||||
```
|
||||
|
||||
### 本地文件接口
|
||||
|
||||
**获取本地文件列表**
|
||||
```
|
||||
GET /admin/local/lists
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**删除本地文件**
|
||||
```
|
||||
DELETE /admin/local/delete
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"filename": "example.txt"
|
||||
}
|
||||
```
|
||||
|
||||
**分享本地文件**
|
||||
```
|
||||
POST /admin/local/share
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"filename": "example.txt",
|
||||
"expire_style": "day",
|
||||
"expire_value": 7
|
||||
}
|
||||
```
|
||||
|
||||
### 配置接口
|
||||
|
||||
**获取配置**
|
||||
```
|
||||
GET /admin/config/get
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
**更新配置**
|
||||
```
|
||||
PATCH /admin/config/update
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"admin_token": "new-password",
|
||||
"uploadSize": 52428800
|
||||
}
|
||||
```
|
||||
|
||||
## 常见问题
|
||||
|
||||
### 忘记管理员密码
|
||||
|
||||
如果忘记了管理员密码,可以通过以下方式重置:
|
||||
|
||||
1. 停止 FileCodeBox 服务
|
||||
2. 使用 SQLite 工具打开 `data/filecodebox.db`
|
||||
3. 查询 `keyvalue` 表中 `key='settings'` 的记录
|
||||
4. 修改 JSON 中的 `admin_token` 值
|
||||
5. 重启服务
|
||||
|
||||
```sql
|
||||
-- 查看当前配置
|
||||
SELECT * FROM keyvalue WHERE key = 'settings';
|
||||
|
||||
-- 或者删除配置,重启后重新进入初始化流程
|
||||
DELETE FROM keyvalue WHERE key = 'settings';
|
||||
```
|
||||
|
||||
### 文件删除失败
|
||||
|
||||
如果删除文件时出现错误,可能的原因:
|
||||
|
||||
1. **存储后端连接失败**:检查存储配置是否正确
|
||||
2. **文件已不存在**:文件可能已被手动删除
|
||||
3. **权限不足**:检查存储目录的写入权限
|
||||
|
||||
### 配置修改不生效
|
||||
|
||||
如果修改配置后没有生效:
|
||||
|
||||
1. 检查是否点击了保存按钮
|
||||
2. 刷新页面查看配置是否已保存
|
||||
3. 检查浏览器控制台是否有错误信息
|
||||
4. 确认配置值的格式是否正确(如数字类型不要输入字符串)
|
||||
|
||||
## 下一步
|
||||
|
||||
- [配置说明](/guide/configuration) - 了解所有配置选项的详细说明
|
||||
- [安全设置](/guide/security) - 了解如何增强系统安全性
|
||||
- [存储配置](/guide/storage) - 配置不同的存储后端
|
||||
@@ -0,0 +1,23 @@
|
||||
# 版本发布
|
||||
|
||||
项目采用 Semantic Versioning 和 Conventional Commits 管理版本。
|
||||
|
||||
首次启用时,需要在后端 GitHub 仓库完成以下设置:
|
||||
|
||||
- `Settings → Actions → General → Workflow permissions` 选择读写权限,并允许
|
||||
GitHub Actions 创建 Pull Request。前端仓库只需要默认的 Actions 读取权限。
|
||||
- 保持 Squash merge 可用;自动发布工作流会等待必需检查通过后合并发布 PR。
|
||||
- 后端仓库配置 `DOCKER_USERNAME` 和 `DOCKER_PASSWORD` Actions Secrets。
|
||||
|
||||
1. 日常提交使用 `feat:`、`fix:` 等 Conventional Commits 前缀并合入主分支。
|
||||
2. Release Please 自动创建并合并发布 PR,更新 `VERSION` 和更新日志。
|
||||
3. 工作流随后自动创建 `vX.Y.Z`、GitHub Release 并触发正式镜像构建。
|
||||
4. 正式镜像发布 `X.Y.Z`、`X.Y` 和 `latest`;分支镜像使用 `dev` 或 `edge-*`。
|
||||
5. 镜像构建时自动读取两个前端仓库默认分支的最新提交,无需手工同步版本。
|
||||
|
||||
因此每次合入主分支的 `fix:`、`feat:` 或破坏性变更都会自动产生对应的
|
||||
Patch、Minor 或 Major 版本。`docs:`、`chore:` 等不影响版本的提交不会单独发版。
|
||||
|
||||
后端运行版本来自 `VERSION`。容器分支构建通过 `APP_VERSION` 注入带提交号的
|
||||
开发版本;正式标签必须与 `VERSION` 完全一致。Docker 镜像的 OCI 标签还记录
|
||||
后端和两个前端仓库当次解析到的精确提交,便于定位构建内容。
|
||||