feat: add SproutWorkCollect apps
This commit is contained in:
19
.gitignore
vendored
19
.gitignore
vendored
@@ -5,6 +5,18 @@ dist/
|
||||
build/
|
||||
works/
|
||||
|
||||
# Env / secrets (do not commit real credentials)
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
!.env.sample
|
||||
*.pem
|
||||
*.key
|
||||
*.p12
|
||||
*.pfx
|
||||
*.crt
|
||||
*.cer
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
@@ -16,13 +28,20 @@ venv/
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
debug-logs/
|
||||
|
||||
# OS / editor
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Local runtime data
|
||||
data/
|
||||
|
||||
# Project-specific (legacy paths)
|
||||
SmyWorkCollect-Frontend/build/
|
||||
SmyWorkCollect-Frontend/node_modules/
|
||||
SmyWorkCollect-Backend/__pycache__/
|
||||
SmyWorkCollect-Backend/works/
|
||||
|
||||
# Project-specific (SproutWorkCollect)
|
||||
SproutWorkCollect-Backend-Python/config/settings.json
|
||||
|
||||
@@ -94,7 +94,7 @@
|
||||
|
||||
- **前端页面**: http://localhost:3000
|
||||
- **后端API**: http://localhost:5000
|
||||
- **管理员界面**: http://localhost:3000/admin?token=shumengya520
|
||||
- **管理员界面**: http://localhost:3000/admin?token=<ADMIN_TOKEN>
|
||||
|
||||
### 📁 项目结构
|
||||
|
||||
@@ -147,7 +147,7 @@
|
||||
|
||||
2. **按照上面的快速开始指南操作**
|
||||
|
||||
3. **使用token访问管理员面板**: `shumengya520`
|
||||
3. **使用 token 访问管理员面板**: 先设置环境变量 `ADMIN_TOKEN`(或 `SPROUTWORKCOLLECT_ADMIN_TOKEN`),再访问 `/admin?token=<ADMIN_TOKEN>`
|
||||
|
||||
### 📄 许可证
|
||||
|
||||
@@ -195,8 +195,8 @@
|
||||
#### 访问管理员界面
|
||||
|
||||
1. 确保后端和前端服务都已启动
|
||||
2. 访问: http://localhost:3000/admin?token=shumengya520
|
||||
3. 管理员token: `shumengya520`
|
||||
2. 访问: http://localhost:3000/admin?token=<ADMIN_TOKEN>
|
||||
3. 管理员 token:环境变量 `ADMIN_TOKEN`(或 `SPROUTWORKCOLLECT_ADMIN_TOKEN`)
|
||||
|
||||
#### 主要功能
|
||||
|
||||
|
||||
4
SproutWorkCollect-Backend-Golang/.dockerignore
Normal file
4
SproutWorkCollect-Backend-Golang/.dockerignore
Normal file
@@ -0,0 +1,4 @@
|
||||
data/
|
||||
*.tmp
|
||||
.git
|
||||
*.md
|
||||
40
SproutWorkCollect-Backend-Golang/Dockerfile
Normal file
40
SproutWorkCollect-Backend-Golang/Dockerfile
Normal file
@@ -0,0 +1,40 @@
|
||||
# ─── Build Stage ──────────────────────────────────────────────────────────────
|
||||
FROM golang:1.21-alpine AS builder
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
# Allow go to fetch modules even without a pre-generated go.sum
|
||||
ENV GOFLAGS=-mod=mod
|
||||
ENV GONOSUMDB=*
|
||||
|
||||
COPY go.mod ./
|
||||
RUN go mod download
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
|
||||
go build -ldflags="-w -s" -o sproutworkcollect-backend .
|
||||
|
||||
# ─── Runtime Stage ────────────────────────────────────────────────────────────
|
||||
FROM alpine:3.19
|
||||
|
||||
RUN apk add --no-cache ca-certificates tzdata wget && \
|
||||
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
|
||||
echo "Asia/Shanghai" > /etc/timezone
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY --from=builder /build/sproutworkcollect-backend .
|
||||
|
||||
# Default data directories; override by mounting volumes at runtime
|
||||
RUN mkdir -p /data/works /data/config
|
||||
|
||||
EXPOSE 5000
|
||||
|
||||
ENV SPROUTWORKCOLLECT_DATA_DIR=/data
|
||||
ENV PORT=5000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=15s --retries=3 \
|
||||
CMD wget -qO- http://localhost:5000/api/settings || exit 1
|
||||
|
||||
CMD ["./sproutworkcollect-backend"]
|
||||
29
SproutWorkCollect-Backend-Golang/docker-compose.yml
Normal file
29
SproutWorkCollect-Backend-Golang/docker-compose.yml
Normal file
@@ -0,0 +1,29 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
sproutworkcollect-api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: sproutworkcollect-backend-go
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${SPROUTWORKCOLLECT_PORT:-5000}:5000"
|
||||
environment:
|
||||
- PORT=5000
|
||||
- SPROUTWORKCOLLECT_DATA_DIR=/data
|
||||
# Override the default admin token (strongly recommended in production):
|
||||
# - ADMIN_TOKEN=your_secure_token_here
|
||||
# Enable verbose Gin logging (set to 1 for debugging):
|
||||
# - GIN_DEBUG=0
|
||||
volumes:
|
||||
# 默认挂载项目目录下的 data/,部署到服务器时设置 SPROUTWORKCOLLECT_DATA_PATH 覆盖
|
||||
# 例如:export SPROUTWORKCOLLECT_DATA_PATH=/shumengya/docker/sproutworkcollect/data
|
||||
- "${SPROUTWORKCOLLECT_DATA_PATH:-./data}/works:/data/works"
|
||||
- "${SPROUTWORKCOLLECT_DATA_PATH:-./data}/config:/data/config"
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://localhost:5000/api/settings"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 15s
|
||||
37
SproutWorkCollect-Backend-Golang/go.mod
Normal file
37
SproutWorkCollect-Backend-Golang/go.mod
Normal file
@@ -0,0 +1,37 @@
|
||||
module sproutworkcollect-backend
|
||||
|
||||
go 1.21
|
||||
|
||||
require (
|
||||
github.com/gin-contrib/cors v1.5.0
|
||||
github.com/gin-gonic/gin v1.9.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bytedance/sonic v1.10.1 // indirect
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
|
||||
github.com/chenzhuoyu/iasm v0.9.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.15.5 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.5 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/leodido/go-urn v1.2.4 // indirect
|
||||
github.com/mattn/go-isatty v0.0.19 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.11 // indirect
|
||||
golang.org/x/arch v0.5.0 // indirect
|
||||
golang.org/x/crypto v0.14.0 // indirect
|
||||
golang.org/x/net v0.16.0 // indirect
|
||||
golang.org/x/sys v0.13.0 // indirect
|
||||
golang.org/x/text v0.13.0 // indirect
|
||||
google.golang.org/protobuf v1.31.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
102
SproutWorkCollect-Backend-Golang/go.sum
Normal file
102
SproutWorkCollect-Backend-Golang/go.sum
Normal file
@@ -0,0 +1,102 @@
|
||||
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
|
||||
github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM=
|
||||
github.com/bytedance/sonic v1.10.1 h1:7a1wuFXL1cMy7a3f7/VFcEtriuXQnUBhtoVfOZiaysc=
|
||||
github.com/bytedance/sonic v1.10.1/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpVsBuRksnlj1mLy4AWzRNQYxauNi62uWcE3to6eA=
|
||||
github.com/chenzhuoyu/iasm v0.9.0 h1:9fhXjVzq5hUy2gkhhgHl95zG2cEAhw9OSGs8toWWAwo=
|
||||
github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
|
||||
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
|
||||
github.com/gin-contrib/cors v1.5.0 h1:DgGKV7DDoOn36DFkNtbHrjoRiT5ExCe+PC9/xp7aKvk=
|
||||
github.com/gin-contrib/cors v1.5.0/go.mod h1:TvU7MAZ3EwrPLI2ztzTt3tqgvBCq+wn8WpZmfADjupI=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
|
||||
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.15.5 h1:LEBecTWb/1j5TNY1YYG2RcOUN3R7NLylN+x8TTueE24=
|
||||
github.com/go-playground/validator/v10 v10.15.5/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.5 h1:0E5MSMDEoAulmXNFquVs//DdoomxaoTY1kUhbc/qbZg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.5/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
|
||||
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
|
||||
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4=
|
||||
github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
|
||||
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
|
||||
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/arch v0.5.0 h1:jpGode6huXQxcskEIpOCvrU+tzo81b6+oFLUYXWtH/Y=
|
||||
golang.org/x/arch v0.5.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
|
||||
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
|
||||
golang.org/x/net v0.16.0 h1:7eBu7KsSvFDtSXUIDbh3aqlK4DPsZ1rByC8PFfBThos=
|
||||
golang.org/x/net v0.16.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
|
||||
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
|
||||
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||
79
SproutWorkCollect-Backend-Golang/internal/config/config.go
Normal file
79
SproutWorkCollect-Backend-Golang/internal/config/config.go
Normal file
@@ -0,0 +1,79 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Config holds all runtime configuration resolved from environment variables.
|
||||
type Config struct {
|
||||
Port int
|
||||
AdminToken string
|
||||
WorksDir string
|
||||
ConfigDir string
|
||||
Debug bool
|
||||
}
|
||||
|
||||
// Load reads environment variables and returns a fully-populated Config.
|
||||
//
|
||||
// Directory resolution priority:
|
||||
// 1. SPROUTWORKCOLLECT_WORKS_DIR / SPROUTWORKCOLLECT_CONFIG_DIR (per-dir override)
|
||||
// 2. SPROUTWORKCOLLECT_DATA_DIR / DATA_DIR (data root, works/ and config/ appended)
|
||||
// 3. ./data/works and ./data/config (relative to current working directory)
|
||||
func Load() *Config {
|
||||
cfg := &Config{
|
||||
Port: 5000,
|
||||
// Do not commit real admin tokens; override via ADMIN_TOKEN / SPROUTWORKCOLLECT_ADMIN_TOKEN.
|
||||
AdminToken: "change-me",
|
||||
}
|
||||
|
||||
if v := os.Getenv("PORT"); v != "" {
|
||||
if p, err := strconv.Atoi(v); err == nil {
|
||||
cfg.Port = p
|
||||
}
|
||||
}
|
||||
|
||||
if v := firstEnv("SPROUTWORKCOLLECT_ADMIN_TOKEN", "ADMIN_TOKEN"); v != "" {
|
||||
cfg.AdminToken = v
|
||||
}
|
||||
|
||||
dbg := os.Getenv("GIN_DEBUG")
|
||||
cfg.Debug = dbg == "1" || dbg == "true"
|
||||
|
||||
dataDir := firstEnv("SPROUTWORKCOLLECT_DATA_DIR", "DATA_DIR")
|
||||
|
||||
worksDir := firstEnv("SPROUTWORKCOLLECT_WORKS_DIR", "WORKS_DIR")
|
||||
if worksDir == "" {
|
||||
if dataDir != "" {
|
||||
worksDir = filepath.Join(dataDir, "works")
|
||||
} else {
|
||||
wd, _ := os.Getwd()
|
||||
worksDir = filepath.Join(wd, "data", "works")
|
||||
}
|
||||
}
|
||||
|
||||
configDir := firstEnv("SPROUTWORKCOLLECT_CONFIG_DIR", "CONFIG_DIR")
|
||||
if configDir == "" {
|
||||
if dataDir != "" {
|
||||
configDir = filepath.Join(dataDir, "config")
|
||||
} else {
|
||||
wd, _ := os.Getwd()
|
||||
configDir = filepath.Join(wd, "data", "config")
|
||||
}
|
||||
}
|
||||
|
||||
cfg.WorksDir = filepath.Clean(worksDir)
|
||||
cfg.ConfigDir = filepath.Clean(configDir)
|
||||
|
||||
return cfg
|
||||
}
|
||||
|
||||
func firstEnv(keys ...string) string {
|
||||
for _, k := range keys {
|
||||
if v := os.Getenv(k); v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
317
SproutWorkCollect-Backend-Golang/internal/handler/admin.go
Normal file
317
SproutWorkCollect-Backend-Golang/internal/handler/admin.go
Normal file
@@ -0,0 +1,317 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"sproutworkcollect-backend/internal/model"
|
||||
"sproutworkcollect-backend/internal/service"
|
||||
)
|
||||
|
||||
const maxUploadBytes = 5000 << 20 // 5 000 MB
|
||||
|
||||
// AdminHandler handles admin-only API endpoints (protected by AdminAuth middleware).
|
||||
type AdminHandler struct {
|
||||
workSvc *service.WorkService
|
||||
}
|
||||
|
||||
// NewAdminHandler wires up an AdminHandler.
|
||||
func NewAdminHandler(workSvc *service.WorkService) *AdminHandler {
|
||||
return &AdminHandler{workSvc: workSvc}
|
||||
}
|
||||
|
||||
// GetWorks handles GET /api/admin/works
|
||||
func (h *AdminHandler) GetWorks(c *gin.Context) {
|
||||
works, err := h.workSvc.LoadAllWorks()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
responses := make([]*model.WorkResponse, len(works))
|
||||
for i, w := range works {
|
||||
responses[i] = h.workSvc.BuildResponse(w)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": responses, "total": len(responses)})
|
||||
}
|
||||
|
||||
// CreateWork handles POST /api/admin/works
|
||||
func (h *AdminHandler) CreateWork(c *gin.Context) {
|
||||
var data model.WorkConfig
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "请求数据格式错误"})
|
||||
return
|
||||
}
|
||||
if data.WorkID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "作品ID不能为空"})
|
||||
return
|
||||
}
|
||||
|
||||
ts := time.Now().Format("2006-01-02T15:04:05.000000")
|
||||
data.UploadTime = ts
|
||||
data.UpdateTime = ts
|
||||
data.UpdateCount = 0
|
||||
data.Downloads = 0
|
||||
data.Views = 0
|
||||
data.Likes = 0
|
||||
data.Normalize()
|
||||
|
||||
if err := h.workSvc.CreateWork(&data); err != nil {
|
||||
status := http.StatusInternalServerError
|
||||
if strings.Contains(err.Error(), "已存在") {
|
||||
status = http.StatusConflict
|
||||
}
|
||||
c.JSON(status, gin.H{"success": false, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "message": "创建成功", "work_id": data.WorkID})
|
||||
}
|
||||
|
||||
// UpdateWork handles PUT /api/admin/works/:work_id
|
||||
func (h *AdminHandler) UpdateWork(c *gin.Context) {
|
||||
workID := c.Param("work_id")
|
||||
var data model.WorkConfig
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "请求数据格式错误"})
|
||||
return
|
||||
}
|
||||
if err := h.workSvc.UpdateWork(workID, &data); err != nil {
|
||||
status := http.StatusInternalServerError
|
||||
if strings.Contains(err.Error(), "不存在") {
|
||||
status = http.StatusNotFound
|
||||
}
|
||||
c.JSON(status, gin.H{"success": false, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "message": "更新成功"})
|
||||
}
|
||||
|
||||
// DeleteWork handles DELETE /api/admin/works/:work_id
|
||||
func (h *AdminHandler) DeleteWork(c *gin.Context) {
|
||||
if err := h.workSvc.DeleteWork(c.Param("work_id")); err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"success": false, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "message": "删除成功"})
|
||||
}
|
||||
|
||||
// UploadFile handles POST /api/admin/upload/:work_id/:file_type
|
||||
// file_type: "image" | "video" | "platform"
|
||||
// For "platform", the form field "platform" must specify the target platform name.
|
||||
func (h *AdminHandler) UploadFile(c *gin.Context) {
|
||||
workID := c.Param("work_id")
|
||||
fileType := c.Param("file_type")
|
||||
|
||||
if !h.workSvc.WorkExists(workID) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"success": false, "message": "作品不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
fh, err := c.FormFile("file")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "没有文件"})
|
||||
return
|
||||
}
|
||||
if fh.Size > maxUploadBytes {
|
||||
c.JSON(http.StatusRequestEntityTooLarge, gin.H{
|
||||
"success": false,
|
||||
"message": fmt.Sprintf("文件太大,最大支持 %dMB,当前 %dMB",
|
||||
maxUploadBytes>>20, fh.Size>>20),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
originalName := fh.Filename
|
||||
safeName := service.SafeFilename(originalName)
|
||||
ext := strings.ToLower(filepath.Ext(safeName))
|
||||
|
||||
allowed := map[string]bool{
|
||||
".png": true, ".jpg": true, ".jpeg": true, ".gif": true,
|
||||
".mp4": true, ".avi": true, ".mov": true,
|
||||
".zip": true, ".rar": true, ".apk": true, ".exe": true, ".dmg": true,
|
||||
}
|
||||
if !allowed[ext] {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "不支持的文件格式"})
|
||||
return
|
||||
}
|
||||
|
||||
// Determine destination directory and resolve a unique filename.
|
||||
// ModifyWork (called later) re-checks uniqueness under a write lock to avoid races.
|
||||
work, err := h.workSvc.LoadWork(workID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"success": false, "message": "作品配置不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
var saveDir string
|
||||
var platform string
|
||||
|
||||
switch fileType {
|
||||
case "image":
|
||||
saveDir = filepath.Join(h.workSvc.WorksDir(), workID, "image")
|
||||
case "video":
|
||||
saveDir = filepath.Join(h.workSvc.WorksDir(), workID, "video")
|
||||
case "platform":
|
||||
platform = c.PostForm("platform")
|
||||
if platform == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "平台参数缺失"})
|
||||
return
|
||||
}
|
||||
saveDir = filepath.Join(h.workSvc.WorksDir(), workID, "platform", platform)
|
||||
default:
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "不支持的文件类型"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(saveDir, 0755); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "创建目录失败"})
|
||||
return
|
||||
}
|
||||
|
||||
// Pre-compute unique filename based on current state.
|
||||
// The authoritative assignment happens inside ModifyWork below.
|
||||
var previewName string
|
||||
switch fileType {
|
||||
case "image":
|
||||
previewName = service.UniqueFilename(safeName, work.Screenshots)
|
||||
case "video":
|
||||
previewName = service.UniqueFilename(safeName, work.VideoFiles)
|
||||
case "platform":
|
||||
previewName = service.UniqueFilename(safeName, work.FileNames[platform])
|
||||
}
|
||||
|
||||
destPath := filepath.Join(saveDir, previewName)
|
||||
if err := c.SaveUploadedFile(fh, destPath); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"success": false,
|
||||
"message": fmt.Sprintf("保存文件失败: %v", err),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Atomically update the work config under a write lock.
|
||||
var finalName string
|
||||
modErr := h.workSvc.ModifyWork(workID, func(w *model.WorkConfig) {
|
||||
// Re-derive the unique name inside the lock to handle concurrent uploads.
|
||||
switch fileType {
|
||||
case "image":
|
||||
finalName = service.UniqueFilename(safeName, w.Screenshots)
|
||||
case "video":
|
||||
finalName = service.UniqueFilename(safeName, w.VideoFiles)
|
||||
case "platform":
|
||||
finalName = service.UniqueFilename(safeName, w.FileNames[platform])
|
||||
}
|
||||
|
||||
// Rename the file on disk if the finalName differs from the pre-computed one.
|
||||
if finalName != previewName {
|
||||
newDest := filepath.Join(saveDir, finalName)
|
||||
_ = os.Rename(destPath, newDest)
|
||||
}
|
||||
|
||||
if w.OriginalNames == nil {
|
||||
w.OriginalNames = make(map[string]string)
|
||||
}
|
||||
w.OriginalNames[finalName] = originalName
|
||||
|
||||
switch fileType {
|
||||
case "image":
|
||||
if !service.ContainsString(w.Screenshots, finalName) {
|
||||
w.Screenshots = append(w.Screenshots, finalName)
|
||||
}
|
||||
if w.Cover == "" {
|
||||
w.Cover = finalName
|
||||
}
|
||||
case "video":
|
||||
if !service.ContainsString(w.VideoFiles, finalName) {
|
||||
w.VideoFiles = append(w.VideoFiles, finalName)
|
||||
}
|
||||
case "platform":
|
||||
if w.FileNames == nil {
|
||||
w.FileNames = make(map[string][]string)
|
||||
}
|
||||
if !service.ContainsString(w.FileNames[platform], finalName) {
|
||||
w.FileNames[platform] = append(w.FileNames[platform], finalName)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if modErr != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "更新配置失败"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "上传成功",
|
||||
"filename": finalName,
|
||||
"file_size": fh.Size,
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteFile handles DELETE /api/admin/delete-file/:work_id/:file_type/:filename
|
||||
func (h *AdminHandler) DeleteFile(c *gin.Context) {
|
||||
workID := c.Param("work_id")
|
||||
fileType := c.Param("file_type")
|
||||
filename := c.Param("filename")
|
||||
|
||||
if _, err := h.workSvc.LoadWork(workID); err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"success": false, "message": "作品不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
platform := c.Query("platform")
|
||||
|
||||
var filePath string
|
||||
switch fileType {
|
||||
case "image":
|
||||
filePath = filepath.Join(h.workSvc.WorksDir(), workID, "image", filename)
|
||||
case "video":
|
||||
filePath = filepath.Join(h.workSvc.WorksDir(), workID, "video", filename)
|
||||
case "platform":
|
||||
if platform == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "平台参数缺失"})
|
||||
return
|
||||
}
|
||||
filePath = filepath.Join(h.workSvc.WorksDir(), workID, "platform", platform, filename)
|
||||
default:
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "不支持的文件类型"})
|
||||
return
|
||||
}
|
||||
|
||||
_ = os.Remove(filePath)
|
||||
|
||||
modErr := h.workSvc.ModifyWork(workID, func(w *model.WorkConfig) {
|
||||
if w.OriginalNames != nil {
|
||||
delete(w.OriginalNames, filename)
|
||||
}
|
||||
switch fileType {
|
||||
case "image":
|
||||
w.Screenshots = service.RemoveString(w.Screenshots, filename)
|
||||
if w.Cover == filename {
|
||||
if len(w.Screenshots) > 0 {
|
||||
w.Cover = w.Screenshots[0]
|
||||
} else {
|
||||
w.Cover = ""
|
||||
}
|
||||
}
|
||||
case "video":
|
||||
w.VideoFiles = service.RemoveString(w.VideoFiles, filename)
|
||||
case "platform":
|
||||
if w.FileNames != nil {
|
||||
w.FileNames[platform] = service.RemoveString(w.FileNames[platform], filename)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if modErr != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "更新配置失败"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "message": "删除成功"})
|
||||
}
|
||||
72
SproutWorkCollect-Backend-Golang/internal/handler/media.go
Normal file
72
SproutWorkCollect-Backend-Golang/internal/handler/media.go
Normal file
@@ -0,0 +1,72 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"sproutworkcollect-backend/internal/service"
|
||||
)
|
||||
|
||||
// MediaHandler serves static media files (images, videos, and downloadable assets).
|
||||
type MediaHandler struct {
|
||||
workSvc *service.WorkService
|
||||
rateLimiter *service.RateLimiter
|
||||
}
|
||||
|
||||
// NewMediaHandler wires up a MediaHandler with its dependencies.
|
||||
func NewMediaHandler(workSvc *service.WorkService, rateLimiter *service.RateLimiter) *MediaHandler {
|
||||
return &MediaHandler{workSvc: workSvc, rateLimiter: rateLimiter}
|
||||
}
|
||||
|
||||
// ServeImage handles GET /api/image/:work_id/:filename
|
||||
func (h *MediaHandler) ServeImage(c *gin.Context) {
|
||||
imgPath := filepath.Join(
|
||||
h.workSvc.WorksDir(),
|
||||
c.Param("work_id"),
|
||||
"image",
|
||||
c.Param("filename"),
|
||||
)
|
||||
if _, err := os.Stat(imgPath); os.IsNotExist(err) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "图片不存在"})
|
||||
return
|
||||
}
|
||||
c.File(imgPath)
|
||||
}
|
||||
|
||||
// ServeVideo handles GET /api/video/:work_id/:filename
|
||||
func (h *MediaHandler) ServeVideo(c *gin.Context) {
|
||||
videoPath := filepath.Join(
|
||||
h.workSvc.WorksDir(),
|
||||
c.Param("work_id"),
|
||||
"video",
|
||||
c.Param("filename"),
|
||||
)
|
||||
if _, err := os.Stat(videoPath); os.IsNotExist(err) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "视频不存在"})
|
||||
return
|
||||
}
|
||||
c.File(videoPath)
|
||||
}
|
||||
|
||||
// DownloadFile handles GET /api/download/:work_id/:platform/:filename
|
||||
func (h *MediaHandler) DownloadFile(c *gin.Context) {
|
||||
workID := c.Param("work_id")
|
||||
platform := c.Param("platform")
|
||||
filename := c.Param("filename")
|
||||
|
||||
filePath := filepath.Join(h.workSvc.WorksDir(), workID, "platform", platform, filename)
|
||||
if _, err := os.Stat(filePath); os.IsNotExist(err) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "文件不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
fp := service.Fingerprint(c.ClientIP(), c.GetHeader("User-Agent"))
|
||||
if h.rateLimiter.CanPerform(fp, "download", workID) {
|
||||
_ = h.workSvc.UpdateStats(workID, "download")
|
||||
}
|
||||
|
||||
c.FileAttachment(filePath, filename)
|
||||
}
|
||||
145
SproutWorkCollect-Backend-Golang/internal/handler/public.go
Normal file
145
SproutWorkCollect-Backend-Golang/internal/handler/public.go
Normal file
@@ -0,0 +1,145 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"sproutworkcollect-backend/internal/service"
|
||||
)
|
||||
|
||||
// PublicHandler handles all publicly accessible API endpoints.
|
||||
type PublicHandler struct {
|
||||
workSvc *service.WorkService
|
||||
settingsSvc *service.SettingsService
|
||||
rateLimiter *service.RateLimiter
|
||||
}
|
||||
|
||||
// NewPublicHandler wires up a PublicHandler with its dependencies.
|
||||
func NewPublicHandler(
|
||||
workSvc *service.WorkService,
|
||||
settingsSvc *service.SettingsService,
|
||||
rateLimiter *service.RateLimiter,
|
||||
) *PublicHandler {
|
||||
return &PublicHandler{
|
||||
workSvc: workSvc,
|
||||
settingsSvc: settingsSvc,
|
||||
rateLimiter: rateLimiter,
|
||||
}
|
||||
}
|
||||
|
||||
// GetSettings handles GET /api/settings
|
||||
func (h *PublicHandler) GetSettings(c *gin.Context) {
|
||||
settings, err := h.settingsSvc.Load()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, settings)
|
||||
}
|
||||
|
||||
// GetWorks handles GET /api/works
|
||||
func (h *PublicHandler) GetWorks(c *gin.Context) {
|
||||
works, err := h.workSvc.LoadAllWorks()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responses := make([]any, len(works))
|
||||
for i, w := range works {
|
||||
responses[i] = h.workSvc.BuildResponse(w)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": responses,
|
||||
"total": len(responses),
|
||||
})
|
||||
}
|
||||
|
||||
// GetWorkDetail handles GET /api/works/:work_id
|
||||
func (h *PublicHandler) GetWorkDetail(c *gin.Context) {
|
||||
workID := c.Param("work_id")
|
||||
|
||||
work, err := h.workSvc.LoadWork(workID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"success": false, "message": "作品不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
fp := service.Fingerprint(c.ClientIP(), c.GetHeader("User-Agent"))
|
||||
if h.rateLimiter.CanPerform(fp, "view", workID) {
|
||||
_ = h.workSvc.UpdateStats(workID, "view")
|
||||
// Reload to return the updated view count.
|
||||
if fresh, err2 := h.workSvc.LoadWork(workID); err2 == nil {
|
||||
work = fresh
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": h.workSvc.BuildResponse(work),
|
||||
})
|
||||
}
|
||||
|
||||
// SearchWorks handles GET /api/search?q=...&category=...
|
||||
func (h *PublicHandler) SearchWorks(c *gin.Context) {
|
||||
works, err := h.workSvc.SearchWorks(c.Query("q"), c.Query("category"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
responses := make([]any, len(works))
|
||||
for i, w := range works {
|
||||
responses[i] = h.workSvc.BuildResponse(w)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": responses,
|
||||
"total": len(responses),
|
||||
})
|
||||
}
|
||||
|
||||
// GetCategories handles GET /api/categories
|
||||
func (h *PublicHandler) GetCategories(c *gin.Context) {
|
||||
cats, err := h.workSvc.AllCategories()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": cats})
|
||||
}
|
||||
|
||||
// LikeWork handles POST /api/like/:work_id
|
||||
func (h *PublicHandler) LikeWork(c *gin.Context) {
|
||||
workID := c.Param("work_id")
|
||||
|
||||
if _, err := h.workSvc.LoadWork(workID); err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"success": false, "message": "作品不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
fp := service.Fingerprint(c.ClientIP(), c.GetHeader("User-Agent"))
|
||||
if !h.rateLimiter.CanPerform(fp, "like", workID) {
|
||||
c.JSON(http.StatusTooManyRequests, gin.H{
|
||||
"success": false,
|
||||
"message": "操作太频繁,请稍后再试",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.workSvc.UpdateStats(workID, "like"); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "点赞失败"})
|
||||
return
|
||||
}
|
||||
|
||||
work, _ := h.workSvc.LoadWork(workID)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "点赞成功",
|
||||
"likes": work.Likes,
|
||||
})
|
||||
}
|
||||
27
SproutWorkCollect-Backend-Golang/internal/middleware/auth.go
Normal file
27
SproutWorkCollect-Backend-Golang/internal/middleware/auth.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// AdminAuth returns a Gin middleware that validates the admin token.
|
||||
// The token may be supplied via the `token` query parameter or the
|
||||
// `Authorization` request header.
|
||||
func AdminAuth(token string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
t := c.Query("token")
|
||||
if t == "" {
|
||||
t = c.GetHeader("Authorization")
|
||||
}
|
||||
if t != token {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
|
||||
"success": false,
|
||||
"message": "权限不足",
|
||||
})
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
16
SproutWorkCollect-Backend-Golang/internal/model/settings.go
Normal file
16
SproutWorkCollect-Backend-Golang/internal/model/settings.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package model
|
||||
|
||||
// Settings represents the site-wide configuration stored in config/settings.json.
|
||||
type Settings struct {
|
||||
SiteName string `json:"网站名字"`
|
||||
SiteDesc string `json:"网站描述"`
|
||||
Author string `json:"站长"`
|
||||
ContactEmail string `json:"联系邮箱"`
|
||||
ThemeColor string `json:"主题颜色"`
|
||||
PageSize int `json:"每页作品数量"`
|
||||
EnableSearch bool `json:"启用搜索"`
|
||||
EnableCategory bool `json:"启用分类"`
|
||||
Icp string `json:"备案号"`
|
||||
Footer string `json:"网站页尾"`
|
||||
Logo string `json:"网站logo"`
|
||||
}
|
||||
75
SproutWorkCollect-Backend-Golang/internal/model/work.go
Normal file
75
SproutWorkCollect-Backend-Golang/internal/model/work.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package model
|
||||
|
||||
// WorkConfig is the data persisted in each work's work_config.json.
|
||||
// JSON field names are kept in Chinese to maintain backward compatibility
|
||||
// with data files written by the original Python backend.
|
||||
type WorkConfig struct {
|
||||
WorkID string `json:"作品ID"`
|
||||
WorkName string `json:"作品作品"`
|
||||
WorkDesc string `json:"作品描述"`
|
||||
Author string `json:"作者"`
|
||||
Version string `json:"作品版本号"`
|
||||
Category string `json:"作品分类"`
|
||||
Tags []string `json:"作品标签"`
|
||||
UploadTime string `json:"上传时间"`
|
||||
UpdateTime string `json:"更新时间"`
|
||||
Platforms []string `json:"支持平台"`
|
||||
FileNames map[string][]string `json:"文件名称"`
|
||||
// 外部下载:每个平台可以配置多个外链下载(带别名)。
|
||||
ExternalDownloads map[string][]ExternalDownload `json:"外部下载,omitempty"`
|
||||
Screenshots []string `json:"作品截图"`
|
||||
VideoFiles []string `json:"作品视频"`
|
||||
Cover string `json:"作品封面"`
|
||||
Downloads int `json:"作品下载量"`
|
||||
Views int `json:"作品浏览量"`
|
||||
Likes int `json:"作品点赞量"`
|
||||
UpdateCount int `json:"作品更新次数"`
|
||||
OriginalNames map[string]string `json:"原始文件名,omitempty"`
|
||||
}
|
||||
|
||||
type ExternalDownload struct {
|
||||
Alias string `json:"别名"`
|
||||
URL string `json:"链接"`
|
||||
}
|
||||
|
||||
// Normalize replaces nil slices/maps with empty equivalents so JSON
|
||||
// serialization produces [] / {} instead of null, matching Python behaviour.
|
||||
func (w *WorkConfig) Normalize() {
|
||||
if w.Tags == nil {
|
||||
w.Tags = []string{}
|
||||
}
|
||||
if w.Platforms == nil {
|
||||
w.Platforms = []string{}
|
||||
}
|
||||
if w.FileNames == nil {
|
||||
w.FileNames = map[string][]string{}
|
||||
}
|
||||
if w.ExternalDownloads == nil {
|
||||
w.ExternalDownloads = map[string][]ExternalDownload{}
|
||||
}
|
||||
if w.Screenshots == nil {
|
||||
w.Screenshots = []string{}
|
||||
}
|
||||
if w.VideoFiles == nil {
|
||||
w.VideoFiles = []string{}
|
||||
}
|
||||
}
|
||||
|
||||
// WorkResponse is a WorkConfig with dynamically computed link fields appended.
|
||||
// These link fields are NEVER stored in work_config.json; they are built on
|
||||
// the fly at response time.
|
||||
type WorkResponse struct {
|
||||
WorkConfig
|
||||
// 下载链接 is always present (empty map when there are no download files).
|
||||
DownloadLinks map[string][]string `json:"下载链接"`
|
||||
// 下载资源:统一返回“本地下载 + 外部下载”,前端可直接按别名渲染按钮/链接。
|
||||
DownloadResources map[string][]DownloadResource `json:"下载资源"`
|
||||
ImageLinks []string `json:"图片链接,omitempty"`
|
||||
VideoLinks []string `json:"视频链接,omitempty"`
|
||||
}
|
||||
|
||||
type DownloadResource struct {
|
||||
Type string `json:"类型"` // local | external
|
||||
Alias string `json:"别名"`
|
||||
URL string `json:"链接"`
|
||||
}
|
||||
81
SproutWorkCollect-Backend-Golang/internal/router/router.go
Normal file
81
SproutWorkCollect-Backend-Golang/internal/router/router.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"sproutworkcollect-backend/internal/config"
|
||||
"sproutworkcollect-backend/internal/handler"
|
||||
"sproutworkcollect-backend/internal/middleware"
|
||||
"sproutworkcollect-backend/internal/service"
|
||||
)
|
||||
|
||||
// Setup creates and configures the Gin engine: middleware, services, handlers, and routes.
|
||||
func Setup(cfg *config.Config) *gin.Engine {
|
||||
if !cfg.Debug {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
}
|
||||
|
||||
r := gin.Default()
|
||||
|
||||
// Allow files up to 32 MB to stay in memory; larger ones spill to temp disk files.
|
||||
// This keeps RAM usage bounded even for gigabyte-scale uploads.
|
||||
r.MaxMultipartMemory = 32 << 20
|
||||
|
||||
// 允许所有来源,并显式放开 Authorization 头,解决跨域访问后台接口时的预检失败问题。
|
||||
corsCfg := cors.Config{
|
||||
AllowOrigins: []string{"*"},
|
||||
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
|
||||
AllowHeaders: []string{
|
||||
"Origin",
|
||||
"Content-Type",
|
||||
"Accept",
|
||||
"Authorization",
|
||||
"X-Requested-With",
|
||||
},
|
||||
ExposeHeaders: []string{"Content-Length"},
|
||||
AllowCredentials: false,
|
||||
MaxAge: 12 * time.Hour,
|
||||
}
|
||||
r.Use(cors.New(corsCfg))
|
||||
|
||||
// ─── Services ─────────────────────────────────────────────────────────────
|
||||
workSvc := service.NewWorkService(cfg)
|
||||
settingsSvc := service.NewSettingsService(cfg)
|
||||
rateLimiter := service.NewRateLimiter()
|
||||
|
||||
// ─── Handlers ─────────────────────────────────────────────────────────────
|
||||
pub := handler.NewPublicHandler(workSvc, settingsSvc, rateLimiter)
|
||||
media := handler.NewMediaHandler(workSvc, rateLimiter)
|
||||
admin := handler.NewAdminHandler(workSvc)
|
||||
|
||||
// ─── Public routes ────────────────────────────────────────────────────────
|
||||
api := r.Group("/api")
|
||||
{
|
||||
api.GET("/settings", pub.GetSettings)
|
||||
api.GET("/works", pub.GetWorks)
|
||||
api.GET("/works/:work_id", pub.GetWorkDetail)
|
||||
api.GET("/search", pub.SearchWorks)
|
||||
api.GET("/categories", pub.GetCategories)
|
||||
api.POST("/like/:work_id", pub.LikeWork)
|
||||
|
||||
api.GET("/image/:work_id/:filename", media.ServeImage)
|
||||
api.GET("/video/:work_id/:filename", media.ServeVideo)
|
||||
api.GET("/download/:work_id/:platform/:filename", media.DownloadFile)
|
||||
}
|
||||
|
||||
// ─── Admin routes (token-protected) ──────────────────────────────────────
|
||||
adm := api.Group("/admin", middleware.AdminAuth(cfg.AdminToken))
|
||||
{
|
||||
adm.GET("/works", admin.GetWorks)
|
||||
adm.POST("/works", admin.CreateWork)
|
||||
adm.PUT("/works/:work_id", admin.UpdateWork)
|
||||
adm.DELETE("/works/:work_id", admin.DeleteWork)
|
||||
adm.POST("/upload/:work_id/:file_type", admin.UploadFile)
|
||||
adm.DELETE("/delete-file/:work_id/:file_type/:filename", admin.DeleteFile)
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// rateLimits defines minimum seconds between the same action by the same user on the same work.
|
||||
var rateLimits = map[string]int64{
|
||||
"view": 60,
|
||||
"download": 300,
|
||||
"like": 3600,
|
||||
}
|
||||
|
||||
// RateLimiter provides per-user, per-action, per-work rate limiting backed by an in-memory store.
|
||||
// The store is never persisted; it resets on service restart (same behaviour as the Python version).
|
||||
type RateLimiter struct {
|
||||
mu sync.Mutex
|
||||
// fingerprint → actionType → workID → last unix timestamp
|
||||
actions map[string]map[string]map[string]int64
|
||||
}
|
||||
|
||||
// NewRateLimiter allocates a new empty RateLimiter.
|
||||
func NewRateLimiter() *RateLimiter {
|
||||
return &RateLimiter{
|
||||
actions: make(map[string]map[string]map[string]int64),
|
||||
}
|
||||
}
|
||||
|
||||
// CanPerform returns true and records the timestamp if the rate limit window has elapsed.
|
||||
// Returns false if the action is too frequent.
|
||||
func (rl *RateLimiter) CanPerform(fingerprint, actionType, workID string) bool {
|
||||
rl.mu.Lock()
|
||||
defer rl.mu.Unlock()
|
||||
|
||||
limit, ok := rateLimits[actionType]
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
|
||||
if rl.actions[fingerprint] == nil {
|
||||
rl.actions[fingerprint] = make(map[string]map[string]int64)
|
||||
}
|
||||
if rl.actions[fingerprint][actionType] == nil {
|
||||
rl.actions[fingerprint][actionType] = make(map[string]int64)
|
||||
}
|
||||
|
||||
last := rl.actions[fingerprint][actionType][workID]
|
||||
if now-last >= limit {
|
||||
rl.actions[fingerprint][actionType][workID] = now
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Fingerprint creates an MD5 hex string from IP and User-Agent for rate-limit keying.
|
||||
func Fingerprint(ip, userAgent string) string {
|
||||
h := md5.Sum([]byte(ip + ":" + userAgent))
|
||||
return fmt.Sprintf("%x", h)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"sproutworkcollect-backend/internal/config"
|
||||
"sproutworkcollect-backend/internal/model"
|
||||
)
|
||||
|
||||
var defaultSettings = model.Settings{
|
||||
SiteName: "✨ 萌芽作品集 ✨",
|
||||
SiteDesc: "🎨 展示个人制作的一些小创意和小项目,欢迎交流讨论 💬",
|
||||
Author: "👨💻 by-树萌芽",
|
||||
ContactEmail: "3205788256@qq.com",
|
||||
ThemeColor: "#81c784",
|
||||
PageSize: 6,
|
||||
EnableSearch: true,
|
||||
EnableCategory: true,
|
||||
Icp: "📄 蜀ICP备2025151694号",
|
||||
Footer: "✨ 萌芽作品集 ✨ | Copyright © 2025-2025 smy ",
|
||||
Logo: "assets/logo.png",
|
||||
}
|
||||
|
||||
// SettingsService manages the site-wide settings file.
|
||||
type SettingsService struct {
|
||||
cfg *config.Config
|
||||
}
|
||||
|
||||
// NewSettingsService creates a SettingsService with the given config.
|
||||
func NewSettingsService(cfg *config.Config) *SettingsService {
|
||||
return &SettingsService{cfg: cfg}
|
||||
}
|
||||
|
||||
// Load reads settings.json, returning built-in defaults when the file is absent or malformed.
|
||||
func (s *SettingsService) Load() (*model.Settings, error) {
|
||||
path := filepath.Join(s.cfg.ConfigDir, "settings.json")
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
d := defaultSettings
|
||||
return &d, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
var settings model.Settings
|
||||
if err := json.Unmarshal(data, &settings); err != nil {
|
||||
d := defaultSettings
|
||||
return &d, nil
|
||||
}
|
||||
return &settings, nil
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"sproutworkcollect-backend/internal/config"
|
||||
"sproutworkcollect-backend/internal/model"
|
||||
)
|
||||
|
||||
// WorkService manages all work data operations with concurrent-safe file I/O.
|
||||
type WorkService struct {
|
||||
cfg *config.Config
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewWorkService creates a WorkService with the given config.
|
||||
func NewWorkService(cfg *config.Config) *WorkService {
|
||||
return &WorkService{cfg: cfg}
|
||||
}
|
||||
|
||||
// WorksDir returns the configured works root directory.
|
||||
func (s *WorkService) WorksDir() string { return s.cfg.WorksDir }
|
||||
|
||||
// WorkExists reports whether a work directory is present on disk.
|
||||
func (s *WorkService) WorkExists(workID string) bool {
|
||||
_, err := os.Stat(filepath.Join(s.cfg.WorksDir, workID))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// ─── Read operations ──────────────────────────────────────────────────────────
|
||||
|
||||
// LoadWork loads and returns a single work config from disk (read-locked).
|
||||
func (s *WorkService) LoadWork(workID string) (*model.WorkConfig, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.loadWork(workID)
|
||||
}
|
||||
|
||||
// loadWork is the internal (unlocked) loader; callers must hold at least an RLock.
|
||||
func (s *WorkService) loadWork(workID string) (*model.WorkConfig, error) {
|
||||
path := filepath.Join(s.cfg.WorksDir, workID, "work_config.json")
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var work model.WorkConfig
|
||||
if err := json.Unmarshal(data, &work); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
work.Normalize()
|
||||
return &work, nil
|
||||
}
|
||||
|
||||
// LoadAllWorks loads every work and returns them sorted by UpdateTime descending.
|
||||
func (s *WorkService) LoadAllWorks() ([]*model.WorkConfig, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
entries, err := os.ReadDir(s.cfg.WorksDir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return []*model.WorkConfig{}, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var works []*model.WorkConfig
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() {
|
||||
continue
|
||||
}
|
||||
w, err := s.loadWork(e.Name())
|
||||
if err != nil {
|
||||
continue // skip broken configs
|
||||
}
|
||||
works = append(works, w)
|
||||
}
|
||||
|
||||
sort.Slice(works, func(i, j int) bool {
|
||||
return works[i].UpdateTime > works[j].UpdateTime
|
||||
})
|
||||
return works, nil
|
||||
}
|
||||
|
||||
// SearchWorks filters all works by keyword (name / desc / tags) and/or category.
|
||||
func (s *WorkService) SearchWorks(query, category string) ([]*model.WorkConfig, error) {
|
||||
all, err := s.LoadAllWorks()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
q := strings.ToLower(query)
|
||||
var result []*model.WorkConfig
|
||||
for _, w := range all {
|
||||
if q != "" {
|
||||
matched := strings.Contains(strings.ToLower(w.WorkName), q) ||
|
||||
strings.Contains(strings.ToLower(w.WorkDesc), q)
|
||||
if !matched {
|
||||
for _, tag := range w.Tags {
|
||||
if strings.Contains(strings.ToLower(tag), q) {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if category != "" && w.Category != category {
|
||||
continue
|
||||
}
|
||||
result = append(result, w)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// AllCategories returns a deduplicated list of all work categories.
|
||||
func (s *WorkService) AllCategories() ([]string, error) {
|
||||
all, err := s.LoadAllWorks()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seen := make(map[string]struct{})
|
||||
var cats []string
|
||||
for _, w := range all {
|
||||
if w.Category != "" {
|
||||
if _, ok := seen[w.Category]; !ok {
|
||||
seen[w.Category] = struct{}{}
|
||||
cats = append(cats, w.Category)
|
||||
}
|
||||
}
|
||||
}
|
||||
if cats == nil {
|
||||
cats = []string{}
|
||||
}
|
||||
return cats, nil
|
||||
}
|
||||
|
||||
// BuildResponse attaches dynamically computed link fields to a work for API responses.
|
||||
// These fields are never written back to disk.
|
||||
func (s *WorkService) BuildResponse(w *model.WorkConfig) *model.WorkResponse {
|
||||
resp := &model.WorkResponse{
|
||||
WorkConfig: *w,
|
||||
DownloadLinks: make(map[string][]string),
|
||||
DownloadResources: make(map[string][]model.DownloadResource),
|
||||
}
|
||||
|
||||
for _, platform := range w.Platforms {
|
||||
if files, ok := w.FileNames[platform]; ok && len(files) > 0 {
|
||||
links := make([]string, len(files))
|
||||
for i, f := range files {
|
||||
rel := fmt.Sprintf("/api/download/%s/%s/%s", w.WorkID, platform, f)
|
||||
links[i] = rel
|
||||
resp.DownloadResources[platform] = append(resp.DownloadResources[platform], model.DownloadResource{
|
||||
Type: "local",
|
||||
Alias: f,
|
||||
URL: rel,
|
||||
})
|
||||
}
|
||||
resp.DownloadLinks[platform] = links
|
||||
}
|
||||
|
||||
// 外部下载链接(带别名)
|
||||
if extList, ok := w.ExternalDownloads[platform]; ok && len(extList) > 0 {
|
||||
for _, item := range extList {
|
||||
if strings.TrimSpace(item.URL) == "" {
|
||||
continue
|
||||
}
|
||||
alias := strings.TrimSpace(item.Alias)
|
||||
if alias == "" {
|
||||
alias = "外部下载"
|
||||
}
|
||||
resp.DownloadResources[platform] = append(resp.DownloadResources[platform], model.DownloadResource{
|
||||
Type: "external",
|
||||
Alias: alias,
|
||||
URL: strings.TrimSpace(item.URL),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(w.Screenshots) > 0 {
|
||||
resp.ImageLinks = make([]string, len(w.Screenshots))
|
||||
for i, img := range w.Screenshots {
|
||||
resp.ImageLinks[i] = fmt.Sprintf("/api/image/%s/%s", w.WorkID, img)
|
||||
}
|
||||
}
|
||||
|
||||
if len(w.VideoFiles) > 0 {
|
||||
resp.VideoLinks = make([]string, len(w.VideoFiles))
|
||||
for i, vid := range w.VideoFiles {
|
||||
resp.VideoLinks[i] = fmt.Sprintf("/api/video/%s/%s", w.WorkID, vid)
|
||||
}
|
||||
}
|
||||
|
||||
return resp
|
||||
}
|
||||
|
||||
// ─── Write operations ─────────────────────────────────────────────────────────
|
||||
|
||||
// SaveWork atomically persists a work config (write-locked).
|
||||
// It writes to a .tmp file first, then renames to guarantee atomicity.
|
||||
func (s *WorkService) SaveWork(work *model.WorkConfig) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.saveWork(work)
|
||||
}
|
||||
|
||||
// saveWork is the internal (unlocked) writer; callers must hold the write lock.
|
||||
func (s *WorkService) saveWork(work *model.WorkConfig) error {
|
||||
configPath := filepath.Join(s.cfg.WorksDir, work.WorkID, "work_config.json")
|
||||
data, err := json.MarshalIndent(work, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("序列化配置失败: %w", err)
|
||||
}
|
||||
tmp := configPath + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, 0644); err != nil {
|
||||
return fmt.Errorf("写入临时文件失败: %w", err)
|
||||
}
|
||||
if err := os.Rename(tmp, configPath); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return fmt.Errorf("原子写入失败: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ModifyWork loads a work under a write lock, applies fn, then saves the result.
|
||||
// Using this helper avoids the load–modify–save TOCTOU race for concurrent requests.
|
||||
func (s *WorkService) ModifyWork(workID string, fn func(*model.WorkConfig)) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
work, err := s.loadWork(workID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fn(work)
|
||||
work.UpdateTime = now()
|
||||
return s.saveWork(work)
|
||||
}
|
||||
|
||||
// UpdateStats increments a statistical counter ("view" | "download" | "like").
|
||||
func (s *WorkService) UpdateStats(workID, statType string) error {
|
||||
return s.ModifyWork(workID, func(w *model.WorkConfig) {
|
||||
switch statType {
|
||||
case "view":
|
||||
w.Views++
|
||||
case "download":
|
||||
w.Downloads++
|
||||
case "like":
|
||||
w.Likes++
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// CreateWork initialises a new work directory tree and writes the first config.
|
||||
func (s *WorkService) CreateWork(work *model.WorkConfig) error {
|
||||
workDir := filepath.Join(s.cfg.WorksDir, work.WorkID)
|
||||
if _, err := os.Stat(workDir); err == nil {
|
||||
return fmt.Errorf("作品ID已存在")
|
||||
}
|
||||
|
||||
dirs := []string{
|
||||
workDir,
|
||||
filepath.Join(workDir, "image"),
|
||||
filepath.Join(workDir, "video"),
|
||||
filepath.Join(workDir, "platform"),
|
||||
}
|
||||
for _, p := range work.Platforms {
|
||||
dirs = append(dirs, filepath.Join(workDir, "platform", p))
|
||||
}
|
||||
for _, d := range dirs {
|
||||
if err := os.MkdirAll(d, 0755); err != nil {
|
||||
return fmt.Errorf("创建目录失败 %s: %w", d, err)
|
||||
}
|
||||
}
|
||||
return s.SaveWork(work)
|
||||
}
|
||||
|
||||
// UpdateWork merges incoming data into the existing config, preserving statistics
|
||||
// when the caller does not provide them (zero values).
|
||||
func (s *WorkService) UpdateWork(workID string, incoming *model.WorkConfig) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
existing, err := s.loadWork(workID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("作品不存在: %w", err)
|
||||
}
|
||||
|
||||
// 兼容旧前端:如果某些字段未带上,则保留旧值,避免被清空。
|
||||
if incoming.FileNames == nil {
|
||||
incoming.FileNames = existing.FileNames
|
||||
}
|
||||
if incoming.ExternalDownloads == nil {
|
||||
incoming.ExternalDownloads = existing.ExternalDownloads
|
||||
}
|
||||
if incoming.Screenshots == nil {
|
||||
incoming.Screenshots = existing.Screenshots
|
||||
}
|
||||
if incoming.VideoFiles == nil {
|
||||
incoming.VideoFiles = existing.VideoFiles
|
||||
}
|
||||
if incoming.Cover == "" {
|
||||
incoming.Cover = existing.Cover
|
||||
}
|
||||
if incoming.OriginalNames == nil {
|
||||
incoming.OriginalNames = existing.OriginalNames
|
||||
}
|
||||
|
||||
if incoming.Downloads == 0 {
|
||||
incoming.Downloads = existing.Downloads
|
||||
}
|
||||
if incoming.Views == 0 {
|
||||
incoming.Views = existing.Views
|
||||
}
|
||||
if incoming.Likes == 0 {
|
||||
incoming.Likes = existing.Likes
|
||||
}
|
||||
if incoming.UploadTime == "" {
|
||||
incoming.UploadTime = existing.UploadTime
|
||||
}
|
||||
|
||||
incoming.WorkID = workID
|
||||
incoming.UpdateTime = now()
|
||||
incoming.UpdateCount = existing.UpdateCount + 1
|
||||
incoming.Normalize()
|
||||
|
||||
return s.saveWork(incoming)
|
||||
}
|
||||
|
||||
// DeleteWork removes the entire work directory.
|
||||
func (s *WorkService) DeleteWork(workID string) error {
|
||||
workDir := filepath.Join(s.cfg.WorksDir, workID)
|
||||
if _, err := os.Stat(workDir); os.IsNotExist(err) {
|
||||
return fmt.Errorf("作品不存在")
|
||||
}
|
||||
return os.RemoveAll(workDir)
|
||||
}
|
||||
|
||||
// ─── Utility helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
// SafeFilename sanitises a filename while preserving CJK (Chinese) characters.
|
||||
func SafeFilename(filename string) string {
|
||||
if filename == "" {
|
||||
return "unnamed_file"
|
||||
}
|
||||
var sb strings.Builder
|
||||
for _, r := range filename {
|
||||
switch {
|
||||
case r >= 0x4E00 && r <= 0x9FFF: // CJK Unified Ideographs
|
||||
sb.WriteRune(r)
|
||||
case unicode.IsLetter(r) || unicode.IsDigit(r):
|
||||
sb.WriteRune(r)
|
||||
case r == '-' || r == '_' || r == '.' || r == ' ':
|
||||
sb.WriteRune(r)
|
||||
}
|
||||
}
|
||||
safe := strings.ReplaceAll(sb.String(), " ", "_")
|
||||
safe = strings.Trim(safe, "._")
|
||||
if safe == "" {
|
||||
return "unnamed_file"
|
||||
}
|
||||
return safe
|
||||
}
|
||||
|
||||
// UniqueFilename returns a filename that does not appear in existing.
|
||||
// If base already conflicts, it appends _1, _2, … until unique.
|
||||
func UniqueFilename(base string, existing []string) string {
|
||||
set := make(map[string]bool, len(existing))
|
||||
for _, f := range existing {
|
||||
set[f] = true
|
||||
}
|
||||
if !set[base] {
|
||||
return base
|
||||
}
|
||||
ext := filepath.Ext(base)
|
||||
stem := strings.TrimSuffix(base, ext)
|
||||
for i := 1; ; i++ {
|
||||
name := fmt.Sprintf("%s_%d%s", stem, i, ext)
|
||||
if !set[name] {
|
||||
return name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ContainsString reports whether slice s contains value v.
|
||||
func ContainsString(s []string, v string) bool {
|
||||
for _, item := range s {
|
||||
if item == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// RemoveString returns a copy of s with the first occurrence of v removed.
|
||||
func RemoveString(s []string, v string) []string {
|
||||
out := make([]string, 0, len(s))
|
||||
for _, item := range s {
|
||||
if item != v {
|
||||
out = append(out, item)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// now returns the current local time in Python-compatible ISO8601 format.
|
||||
func now() string {
|
||||
return time.Now().Format("2006-01-02T15:04:05.000000")
|
||||
}
|
||||
24
SproutWorkCollect-Backend-Golang/main.go
Normal file
24
SproutWorkCollect-Backend-Golang/main.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"sproutworkcollect-backend/internal/config"
|
||||
"sproutworkcollect-backend/internal/router"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg := config.Load()
|
||||
|
||||
r := router.Setup(cfg)
|
||||
|
||||
addr := fmt.Sprintf("0.0.0.0:%d", cfg.Port)
|
||||
log.Printf("[SproutWorkCollect] 服务启动 → http://%s", addr)
|
||||
log.Printf("[SproutWorkCollect] WorksDir : %s", cfg.WorksDir)
|
||||
log.Printf("[SproutWorkCollect] ConfigDir : %s", cfg.ConfigDir)
|
||||
|
||||
if err := r.Run(addr); err != nil {
|
||||
log.Fatalf("服务启动失败: %v", err)
|
||||
}
|
||||
}
|
||||
48
SproutWorkCollect-Backend-Python/.dockerignore
Normal file
48
SproutWorkCollect-Backend-Python/.dockerignore
Normal file
@@ -0,0 +1,48 @@
|
||||
# Git
|
||||
.git
|
||||
.gitignore
|
||||
|
||||
# Node
|
||||
node_modules
|
||||
npm-debug.log
|
||||
|
||||
# Python
|
||||
__pycache__
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.pyd
|
||||
.Python
|
||||
*.egg-info
|
||||
dist
|
||||
build
|
||||
|
||||
# IDE
|
||||
.vscode
|
||||
.idea
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# 环境变量
|
||||
.env
|
||||
.env.local
|
||||
.env.backup
|
||||
**/.env.local
|
||||
**/.env.production.local
|
||||
**/.env.development.local
|
||||
|
||||
# 日志
|
||||
*.log
|
||||
logs
|
||||
|
||||
# 测试
|
||||
test
|
||||
*.test.js
|
||||
|
||||
# 临时文件
|
||||
*.tmp
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# README
|
||||
README.md
|
||||
29
SproutWorkCollect-Backend-Python/Dockerfile
Normal file
29
SproutWorkCollect-Backend-Python/Dockerfile
Normal file
@@ -0,0 +1,29 @@
|
||||
# 后端 Dockerfile
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app/backend
|
||||
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
# 安装系统依赖
|
||||
RUN apt-get update && apt-get install -y \
|
||||
gcc \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# 复制依赖文件
|
||||
COPY requirements.txt .
|
||||
|
||||
# 安装 Python 依赖
|
||||
RUN pip install --no-cache-dir -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
|
||||
|
||||
# 复制后端代码
|
||||
COPY . .
|
||||
|
||||
# 默认数据目录(可在运行时通过挂载覆盖)
|
||||
RUN mkdir -p /data/works /data/config
|
||||
|
||||
# 暴露端口
|
||||
EXPOSE 5000
|
||||
|
||||
# 启动后端服务
|
||||
CMD ["python", "app.py"]
|
||||
838
SproutWorkCollect-Backend-Python/app.py
Normal file
838
SproutWorkCollect-Backend-Python/app.py
Normal file
@@ -0,0 +1,838 @@
|
||||
from flask import Flask, jsonify, send_from_directory, request
|
||||
from flask_cors import CORS
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import hashlib
|
||||
import time
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
from werkzeug.utils import secure_filename
|
||||
import tempfile
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
import string
|
||||
import math
|
||||
import calendar
|
||||
|
||||
|
||||
# 配置日志
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
app = Flask(__name__)
|
||||
CORS(app) # 允许跨域请求
|
||||
|
||||
# 设置上传文件大小限制为5000MB
|
||||
app.config['MAX_CONTENT_LENGTH'] = 5000 * 1024 * 1024 # 5000MB
|
||||
|
||||
# 优化Flask配置以处理大文件
|
||||
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
|
||||
app.config['MAX_FORM_MEMORY_SIZE'] = 1024 * 1024 * 1024 # 1GB
|
||||
app.config['MAX_FORM_PARTS'] = 1000
|
||||
|
||||
# 获取项目根目录
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
def _normalize_dir_path(path):
|
||||
if not path:
|
||||
return None
|
||||
|
||||
expanded = os.path.expandvars(os.path.expanduser(path))
|
||||
return os.path.abspath(expanded)
|
||||
|
||||
# 数据目录(用于 Docker 持久化)。
|
||||
# 推荐在容器内设置 SPROUTWORKCOLLECT_DATA_DIR=/data,并挂载宿主机目录到 /data
|
||||
DATA_DIR = _normalize_dir_path(
|
||||
os.environ.get('SPROUTWORKCOLLECT_DATA_DIR') or os.environ.get('DATA_DIR')
|
||||
)
|
||||
|
||||
DEFAULT_WORKS_DIR = os.path.join(DATA_DIR, 'works') if DATA_DIR else os.path.join(BASE_DIR, 'works')
|
||||
DEFAULT_CONFIG_DIR = os.path.join(DATA_DIR, 'config') if DATA_DIR else os.path.join(BASE_DIR, 'config')
|
||||
|
||||
# works/config 目录(可分别覆盖)
|
||||
WORKS_DIR = (
|
||||
_normalize_dir_path(os.environ.get('SPROUTWORKCOLLECT_WORKS_DIR') or os.environ.get('WORKS_DIR'))
|
||||
or DEFAULT_WORKS_DIR
|
||||
)
|
||||
CONFIG_DIR = (
|
||||
_normalize_dir_path(os.environ.get('SPROUTWORKCOLLECT_CONFIG_DIR') or os.environ.get('CONFIG_DIR'))
|
||||
or DEFAULT_CONFIG_DIR
|
||||
)
|
||||
|
||||
# 管理员 token(不要硬编码到仓库中;请通过环境变量配置)
|
||||
ADMIN_TOKEN = (
|
||||
os.environ.get('SPROUTWORKCOLLECT_ADMIN_TOKEN')
|
||||
or os.environ.get('ADMIN_TOKEN')
|
||||
or ''
|
||||
).strip()
|
||||
|
||||
# 允许的文件扩展名
|
||||
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'mp4', 'avi', 'mov', 'zip', 'rar', 'apk', 'exe', 'dmg'}
|
||||
|
||||
# 防刷机制:存储用户操作记录
|
||||
# 格式: {user_fingerprint: {action_type: {work_id: last_action_time}}}
|
||||
user_actions = {}
|
||||
|
||||
# 防刷时间间隔(秒)
|
||||
RATE_LIMITS = {
|
||||
'view': 60, # 浏览:1分钟内同一用户同一作品只能计数一次
|
||||
'download': 300, # 下载:5分钟内同一用户同一作品只能计数一次
|
||||
'like': 3600 # 点赞:1小时内同一用户同一作品只能计数一次
|
||||
}
|
||||
|
||||
def allowed_file(filename):
|
||||
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
||||
|
||||
def safe_filename(filename):
|
||||
"""
|
||||
安全处理文件名,支持中文字符
|
||||
"""
|
||||
if not filename:
|
||||
return ''
|
||||
|
||||
# 保留原始文件名用于显示
|
||||
original_name = filename
|
||||
|
||||
# 规范化Unicode字符
|
||||
filename = unicodedata.normalize('NFKC', filename)
|
||||
|
||||
# 移除或替换危险字符,但保留中文、英文、数字、点、下划线、连字符
|
||||
# 允许的字符:中文字符、英文字母、数字、点、下划线、连字符、空格
|
||||
safe_chars = re.sub(r'[^\w\s\-_.\u4e00-\u9fff]', '', filename)
|
||||
|
||||
# 将多个空格替换为单个下划线
|
||||
safe_chars = re.sub(r'\s+', '_', safe_chars)
|
||||
|
||||
# 移除开头和结尾的点和空格
|
||||
safe_chars = safe_chars.strip('. ')
|
||||
|
||||
# 确保文件名不为空
|
||||
if not safe_chars:
|
||||
return 'unnamed_file'
|
||||
|
||||
# 限制文件名长度(不包括扩展名)
|
||||
name_part, ext_part = os.path.splitext(safe_chars)
|
||||
if len(name_part.encode('utf-8')) > 200: # 限制为200字节
|
||||
# 截断文件名但保持完整的字符
|
||||
name_bytes = name_part.encode('utf-8')[:200]
|
||||
# 确保不会截断中文字符
|
||||
try:
|
||||
name_part = name_bytes.decode('utf-8')
|
||||
except UnicodeDecodeError:
|
||||
# 如果截断位置在中文字符中间,向前查找完整字符
|
||||
for i in range(len(name_bytes) - 1, -1, -1):
|
||||
try:
|
||||
name_part = name_bytes[:i].decode('utf-8')
|
||||
break
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
|
||||
return name_part + ext_part
|
||||
|
||||
def verify_admin_token():
|
||||
"""验证管理员token"""
|
||||
token = request.args.get('token') or request.headers.get('Authorization')
|
||||
return token == ADMIN_TOKEN
|
||||
|
||||
def get_user_fingerprint():
|
||||
"""生成用户指纹,用于防刷"""
|
||||
# 使用IP地址和User-Agent生成指纹
|
||||
ip = request.environ.get('HTTP_X_FORWARDED_FOR', request.environ.get('REMOTE_ADDR', ''))
|
||||
user_agent = request.headers.get('User-Agent', '')
|
||||
fingerprint_string = f"{ip}:{user_agent}"
|
||||
return hashlib.md5(fingerprint_string.encode()).hexdigest()
|
||||
|
||||
def can_perform_action(action_type, work_id):
|
||||
"""检查用户是否可以执行某个操作(防刷检查)"""
|
||||
fingerprint = get_user_fingerprint()
|
||||
current_time = time.time()
|
||||
|
||||
# 如果用户从未记录过,允许操作
|
||||
if fingerprint not in user_actions:
|
||||
user_actions[fingerprint] = {}
|
||||
|
||||
if action_type not in user_actions[fingerprint]:
|
||||
user_actions[fingerprint][action_type] = {}
|
||||
|
||||
# 检查这个作品的上次操作时间
|
||||
last_action_time = user_actions[fingerprint][action_type].get(work_id, 0)
|
||||
time_diff = current_time - last_action_time
|
||||
|
||||
# 如果时间间隔足够,允许操作
|
||||
if time_diff >= RATE_LIMITS.get(action_type, 0):
|
||||
user_actions[fingerprint][action_type][work_id] = current_time
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def update_work_stats(work_id, stat_type, increment=1):
|
||||
"""更新作品统计数据"""
|
||||
work_dir = os.path.join(WORKS_DIR, work_id)
|
||||
config_path = os.path.join(work_dir, 'work_config.json')
|
||||
|
||||
if not os.path.exists(config_path):
|
||||
return False
|
||||
|
||||
try:
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
config = json.load(f)
|
||||
|
||||
# 确保统计字段存在
|
||||
stat_fields = ['作品下载量', '作品浏览量', '作品点赞量', '作品更新次数']
|
||||
for field in stat_fields:
|
||||
if field not in config:
|
||||
config[field] = 0
|
||||
|
||||
# 更新指定统计数据
|
||||
if stat_type in config:
|
||||
config[stat_type] += increment
|
||||
config['更新时间'] = datetime.now().isoformat()
|
||||
|
||||
with open(config_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(config, f, ensure_ascii=False, indent=2)
|
||||
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"更新统计数据失败: {e}")
|
||||
return False
|
||||
|
||||
return False
|
||||
|
||||
#加载网站设置
|
||||
def load_settings():
|
||||
"""加载网站设置"""
|
||||
settings_path = os.path.join(CONFIG_DIR, 'settings.json')
|
||||
try:
|
||||
with open(settings_path, 'r', encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
except FileNotFoundError:
|
||||
return {
|
||||
"网站名字": "✨ 树萌芽の作品集 ✨",
|
||||
"网站描述": "🎨 展示个人制作的一些小创意和小项目,欢迎交流讨论 💬",
|
||||
"站长": "👨💻 by-树萌芽",
|
||||
"联系邮箱": "3205788256@qq.com",
|
||||
"主题颜色": "#81c784",
|
||||
"每页作品数量": 6,
|
||||
"启用搜索": True,
|
||||
"启用分类": True,
|
||||
"备案号": "📄 蜀ICP备2025151694号",
|
||||
"网站页尾": "🌱 树萌芽の作品集 | Copyright © 2025-2025 smy ✨",
|
||||
"网站logo": "assets/logo.png"
|
||||
}
|
||||
|
||||
#加载单个作品配置
|
||||
def load_work_config(work_id):
|
||||
"""加载单个作品配置"""
|
||||
work_path = os.path.join(WORKS_DIR, work_id, 'work_config.json')
|
||||
try:
|
||||
with open(work_path, 'r', encoding='utf-8') as f:
|
||||
config = json.load(f)
|
||||
# 添加下载链接
|
||||
config['下载链接'] = {}
|
||||
if '支持平台' in config and '文件名称' in config:
|
||||
for platform in config['支持平台']:
|
||||
if platform in config['文件名称']:
|
||||
files = config['文件名称'][platform]
|
||||
config['下载链接'][platform] = [
|
||||
f"/api/download/{work_id}/{platform}/{file}"
|
||||
for file in files
|
||||
]
|
||||
|
||||
# 添加图片链接
|
||||
if '作品截图' in config:
|
||||
config['图片链接'] = [
|
||||
f"/api/image/{work_id}/{img}"
|
||||
for img in config['作品截图']
|
||||
]
|
||||
|
||||
# 添加视频链接
|
||||
if '作品视频' in config:
|
||||
config['视频链接'] = [
|
||||
f"/api/video/{work_id}/{video}"
|
||||
for video in config['作品视频']
|
||||
]
|
||||
|
||||
return config
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
|
||||
|
||||
#==============================公开API接口===============================
|
||||
#获取所有作品
|
||||
def get_all_works():
|
||||
"""获取所有作品"""
|
||||
works = []
|
||||
if not os.path.exists(WORKS_DIR):
|
||||
return works
|
||||
|
||||
for work_id in os.listdir(WORKS_DIR):
|
||||
work_dir = os.path.join(WORKS_DIR, work_id)
|
||||
if os.path.isdir(work_dir):
|
||||
config = load_work_config(work_id)
|
||||
if config:
|
||||
works.append(config)
|
||||
|
||||
# 按更新时间排序
|
||||
works.sort(key=lambda x: x.get('更新时间', ''), reverse=True)
|
||||
return works
|
||||
|
||||
#获取网站设置
|
||||
@app.route('/api/settings')
|
||||
def get_settings():
|
||||
"""获取网站设置"""
|
||||
return jsonify(load_settings())
|
||||
|
||||
#获取所有作品列表
|
||||
@app.route('/api/works')
|
||||
def get_works():
|
||||
"""获取所有作品列表"""
|
||||
works = get_all_works()
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'data': works,
|
||||
'total': len(works)
|
||||
})
|
||||
|
||||
#获取单个作品详情
|
||||
@app.route('/api/works/<work_id>')
|
||||
def get_work_detail(work_id):
|
||||
"""获取单个作品详情"""
|
||||
config = load_work_config(work_id)
|
||||
if config:
|
||||
# 增加浏览量(防刷检查)
|
||||
if can_perform_action('view', work_id):
|
||||
update_work_stats(work_id, '作品浏览量')
|
||||
# 重新加载配置获取最新数据
|
||||
config = load_work_config(work_id)
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'data': config
|
||||
})
|
||||
else:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'message': '作品不存在'
|
||||
}), 404
|
||||
|
||||
#提供作品图片
|
||||
@app.route('/api/image/<work_id>/<filename>')
|
||||
def serve_image(work_id, filename):
|
||||
"""提供作品图片"""
|
||||
image_dir = os.path.join(WORKS_DIR, work_id, 'image')
|
||||
if os.path.exists(os.path.join(image_dir, filename)):
|
||||
return send_from_directory(image_dir, filename)
|
||||
return jsonify({'error': '图片不存在'}), 404
|
||||
|
||||
#提供作品视频
|
||||
@app.route('/api/video/<work_id>/<filename>')
|
||||
def serve_video(work_id, filename):
|
||||
"""提供作品视频"""
|
||||
video_dir = os.path.join(WORKS_DIR, work_id, 'video')
|
||||
if os.path.exists(os.path.join(video_dir, filename)):
|
||||
return send_from_directory(video_dir, filename)
|
||||
return jsonify({'error': '视频不存在'}), 404
|
||||
|
||||
#提供作品下载
|
||||
@app.route('/api/download/<work_id>/<platform>/<filename>')
|
||||
def download_file(work_id, platform, filename):
|
||||
"""提供作品下载"""
|
||||
platform_dir = os.path.join(WORKS_DIR, work_id, 'platform', platform)
|
||||
if os.path.exists(os.path.join(platform_dir, filename)):
|
||||
# 增加下载量(防刷检查)
|
||||
if can_perform_action('download', work_id):
|
||||
update_work_stats(work_id, '作品下载量')
|
||||
|
||||
return send_from_directory(platform_dir, filename, as_attachment=True)
|
||||
return jsonify({'error': '文件不存在'}), 404
|
||||
|
||||
#搜索作品
|
||||
@app.route('/api/search')
|
||||
def search_works():
|
||||
"""搜索作品"""
|
||||
from flask import request
|
||||
query = request.args.get('q', '').lower()
|
||||
category = request.args.get('category', '')
|
||||
|
||||
works = get_all_works()
|
||||
|
||||
if query:
|
||||
filtered_works = []
|
||||
for work in works:
|
||||
# 在作品名称、描述、标签中搜索
|
||||
if (query in work.get('作品作品', '').lower() or
|
||||
query in work.get('作品描述', '').lower() or
|
||||
any(query in tag.lower() for tag in work.get('作品标签', []))):
|
||||
filtered_works.append(work)
|
||||
works = filtered_works
|
||||
|
||||
if category:
|
||||
works = [work for work in works if work.get('作品分类', '') == category]
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'data': works,
|
||||
'total': len(works)
|
||||
})
|
||||
|
||||
#获取所有分类
|
||||
@app.route('/api/categories')
|
||||
def get_categories():
|
||||
"""获取所有分类"""
|
||||
works = get_all_works()
|
||||
categories = list(set(work.get('作品分类', '') for work in works if work.get('作品分类')))
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'data': categories
|
||||
})
|
||||
|
||||
@app.route('/api/like/<work_id>', methods=['POST'])
|
||||
def like_work(work_id):
|
||||
"""点赞作品"""
|
||||
# 检查作品是否存在
|
||||
config = load_work_config(work_id)
|
||||
if not config:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'message': '作品不存在'
|
||||
}), 404
|
||||
|
||||
# 防刷检查
|
||||
if not can_perform_action('like', work_id):
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'message': '操作太频繁,请稍后再试'
|
||||
}), 429
|
||||
|
||||
# 增加点赞量
|
||||
if update_work_stats(work_id, '作品点赞量'):
|
||||
# 获取最新的点赞数
|
||||
updated_config = load_work_config(work_id)
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'message': '点赞成功',
|
||||
'likes': updated_config.get('作品点赞量', 0)
|
||||
})
|
||||
else:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'message': '点赞失败'
|
||||
}), 500
|
||||
#==============================公开API接口===============================
|
||||
|
||||
|
||||
|
||||
# ===========================================
|
||||
# 管理员API接口
|
||||
# ===========================================
|
||||
|
||||
@app.route('/api/admin/works', methods=['GET'])
|
||||
def admin_get_works():
|
||||
"""管理员获取所有作品(包含更多详细信息)"""
|
||||
if not verify_admin_token():
|
||||
return jsonify({'success': False, 'message': '权限不足'}), 403
|
||||
|
||||
works = get_all_works()
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'data': works,
|
||||
'total': len(works)
|
||||
})
|
||||
|
||||
@app.route('/api/admin/works/<work_id>', methods=['PUT'])
|
||||
def admin_update_work(work_id):
|
||||
"""管理员更新作品信息"""
|
||||
if not verify_admin_token():
|
||||
return jsonify({'success': False, 'message': '权限不足'}), 403
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
work_dir = os.path.join(WORKS_DIR, work_id)
|
||||
config_path = os.path.join(work_dir, 'work_config.json')
|
||||
|
||||
if not os.path.exists(config_path):
|
||||
return jsonify({'success': False, 'message': '作品不存在'}), 404
|
||||
|
||||
# 读取现有配置获取当前统计数据
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
current_config = json.load(f)
|
||||
|
||||
# 确保统计字段存在并保持原值
|
||||
stat_fields = ['作品下载量', '作品浏览量', '作品点赞量', '作品更新次数']
|
||||
for field in stat_fields:
|
||||
if field not in data:
|
||||
data[field] = current_config.get(field, 0)
|
||||
|
||||
# 更新时间和更新次数
|
||||
data['更新时间'] = datetime.now().isoformat()
|
||||
data['作品更新次数'] = current_config.get('作品更新次数', 0) + 1
|
||||
|
||||
# 保存配置文件
|
||||
with open(config_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||
|
||||
return jsonify({'success': True, 'message': '更新成功'})
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'message': f'更新失败: {str(e)}'}), 500
|
||||
|
||||
@app.route('/api/admin/works/<work_id>', methods=['DELETE'])
|
||||
def admin_delete_work(work_id):
|
||||
"""管理员删除作品"""
|
||||
if not verify_admin_token():
|
||||
return jsonify({'success': False, 'message': '权限不足'}), 403
|
||||
|
||||
try:
|
||||
work_dir = os.path.join(WORKS_DIR, work_id)
|
||||
|
||||
if not os.path.exists(work_dir):
|
||||
return jsonify({'success': False, 'message': '作品不存在'}), 404
|
||||
|
||||
# 删除整个作品目录
|
||||
shutil.rmtree(work_dir)
|
||||
|
||||
return jsonify({'success': True, 'message': '删除成功'})
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'message': f'删除失败: {str(e)}'}), 500
|
||||
|
||||
@app.route('/api/admin/works', methods=['POST'])
|
||||
def admin_create_work():
|
||||
"""管理员创建新作品"""
|
||||
if not verify_admin_token():
|
||||
return jsonify({'success': False, 'message': '权限不足'}), 403
|
||||
|
||||
try:
|
||||
data = request.get_json()
|
||||
work_id = data.get('作品ID')
|
||||
|
||||
if not work_id:
|
||||
return jsonify({'success': False, 'message': '作品ID不能为空'}), 400
|
||||
|
||||
work_dir = os.path.join(WORKS_DIR, work_id)
|
||||
|
||||
# 检查作品是否已存在
|
||||
if os.path.exists(work_dir):
|
||||
return jsonify({'success': False, 'message': '作品ID已存在'}), 409
|
||||
|
||||
# 创建作品目录结构
|
||||
os.makedirs(work_dir, exist_ok=True)
|
||||
os.makedirs(os.path.join(work_dir, 'image'), exist_ok=True)
|
||||
os.makedirs(os.path.join(work_dir, 'video'), exist_ok=True)
|
||||
os.makedirs(os.path.join(work_dir, 'platform'), exist_ok=True)
|
||||
|
||||
# 创建平台子目录
|
||||
platforms = data.get('支持平台', [])
|
||||
for platform in platforms:
|
||||
platform_dir = os.path.join(work_dir, 'platform', platform)
|
||||
os.makedirs(platform_dir, exist_ok=True)
|
||||
|
||||
# 设置默认值
|
||||
current_time = datetime.now().isoformat()
|
||||
config = {
|
||||
'作品ID': work_id,
|
||||
'作品作品': data.get('作品作品', ''),
|
||||
'作品描述': data.get('作品描述', ''),
|
||||
'作者': data.get('作者', '树萌芽'),
|
||||
'作品版本号': data.get('作品版本号', '1.0.0'),
|
||||
'作品分类': data.get('作品分类', '其他'),
|
||||
'作品标签': data.get('作品标签', []),
|
||||
'上传时间': current_time,
|
||||
'更新时间': current_time,
|
||||
'支持平台': platforms,
|
||||
'文件名称': {},
|
||||
'作品截图': [],
|
||||
'作品视频': [],
|
||||
'作品封面': '',
|
||||
'作品下载量': 0,
|
||||
'作品浏览量': 0,
|
||||
'作品点赞量': 0,
|
||||
'作品更新次数': 0
|
||||
}
|
||||
|
||||
# 保存配置文件
|
||||
config_path = os.path.join(work_dir, 'work_config.json')
|
||||
with open(config_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(config, f, ensure_ascii=False, indent=2)
|
||||
|
||||
return jsonify({'success': True, 'message': '创建成功', 'work_id': work_id})
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'message': f'创建失败: {str(e)}'}), 500
|
||||
|
||||
@app.route('/api/admin/upload/<work_id>/<file_type>', methods=['POST'])
|
||||
def admin_upload_file(work_id, file_type):
|
||||
"""管理员上传文件(优化大文件处理)"""
|
||||
if not verify_admin_token():
|
||||
return jsonify({'success': False, 'message': '权限不足'}), 403
|
||||
|
||||
temp_file_path = None
|
||||
try:
|
||||
logger.info(f"开始上传文件 - 作品ID: {work_id}, 文件类型: {file_type}")
|
||||
|
||||
work_dir = os.path.join(WORKS_DIR, work_id)
|
||||
if not os.path.exists(work_dir):
|
||||
logger.error(f"作品目录不存在: {work_dir}")
|
||||
return jsonify({'success': False, 'message': '作品不存在'}), 404
|
||||
|
||||
if 'file' not in request.files:
|
||||
logger.error("请求中没有文件")
|
||||
return jsonify({'success': False, 'message': '没有文件'}), 400
|
||||
|
||||
file = request.files['file']
|
||||
if file.filename == '':
|
||||
logger.error("没有选择文件")
|
||||
return jsonify({'success': False, 'message': '没有选择文件'}), 400
|
||||
|
||||
# 保存原始文件名(包含中文)
|
||||
original_filename = file.filename
|
||||
logger.info(f"原始文件名: {original_filename}")
|
||||
|
||||
# 检查文件格式
|
||||
if not allowed_file(original_filename):
|
||||
logger.error(f"不支持的文件格式: {original_filename}")
|
||||
return jsonify({'success': False, 'message': '不支持的文件格式'}), 400
|
||||
|
||||
# 使用安全的文件名处理函数
|
||||
safe_original_filename = safe_filename(original_filename)
|
||||
file_extension = safe_original_filename.rsplit('.', 1)[1].lower() if '.' in safe_original_filename else 'unknown'
|
||||
|
||||
logger.info(f"安全处理后的文件名: {safe_original_filename}")
|
||||
|
||||
# 读取现有配置来生成新文件名
|
||||
config_path = os.path.join(work_dir, 'work_config.json')
|
||||
if not os.path.exists(config_path):
|
||||
logger.error(f"配置文件不存在: {config_path}")
|
||||
return jsonify({'success': False, 'message': '作品配置不存在'}), 404
|
||||
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
config = json.load(f)
|
||||
|
||||
# 根据文件类型确定保存目录和文件名
|
||||
if file_type == 'image':
|
||||
save_dir = os.path.join(work_dir, 'image')
|
||||
existing_images = config.get('作品截图', [])
|
||||
|
||||
# 尝试使用原始文件名,如果重复则添加序号
|
||||
base_name = safe_original_filename
|
||||
filename = base_name
|
||||
counter = 1
|
||||
while filename in existing_images:
|
||||
name_part, ext_part = os.path.splitext(base_name)
|
||||
filename = f"{name_part}_{counter}{ext_part}"
|
||||
counter += 1
|
||||
|
||||
elif file_type == 'video':
|
||||
save_dir = os.path.join(work_dir, 'video')
|
||||
existing_videos = config.get('作品视频', [])
|
||||
|
||||
# 尝试使用原始文件名,如果重复则添加序号
|
||||
base_name = safe_original_filename
|
||||
filename = base_name
|
||||
counter = 1
|
||||
while filename in existing_videos:
|
||||
name_part, ext_part = os.path.splitext(base_name)
|
||||
filename = f"{name_part}_{counter}{ext_part}"
|
||||
counter += 1
|
||||
|
||||
elif file_type == 'platform':
|
||||
platform = request.form.get('platform')
|
||||
if not platform:
|
||||
logger.error("平台参数缺失")
|
||||
return jsonify({'success': False, 'message': '平台参数缺失'}), 400
|
||||
save_dir = os.path.join(work_dir, 'platform', platform)
|
||||
|
||||
# 对于平台文件,也尝试保留原始文件名
|
||||
existing_files = config.get('文件名称', {}).get(platform, [])
|
||||
base_name = safe_original_filename
|
||||
filename = base_name
|
||||
counter = 1
|
||||
while filename in existing_files:
|
||||
name_part, ext_part = os.path.splitext(base_name)
|
||||
filename = f"{name_part}_{counter}{ext_part}"
|
||||
counter += 1
|
||||
else:
|
||||
logger.error(f"不支持的文件类型: {file_type}")
|
||||
return jsonify({'success': False, 'message': '不支持的文件类型'}), 400
|
||||
|
||||
# 确保目录存在
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
final_file_path = os.path.join(save_dir, filename)
|
||||
|
||||
logger.info(f"目标文件路径: {final_file_path}")
|
||||
|
||||
# 使用临时文件进行流式保存,避免内存溢出
|
||||
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
||||
temp_file_path = temp_file.name
|
||||
logger.info(f"临时文件路径: {temp_file_path}")
|
||||
|
||||
# 分块读取和写入文件,减少内存使用
|
||||
chunk_size = 8192 # 8KB chunks
|
||||
total_size = 0
|
||||
|
||||
while True:
|
||||
chunk = file.stream.read(chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
temp_file.write(chunk)
|
||||
total_size += len(chunk)
|
||||
|
||||
# 检查文件大小
|
||||
max_size = 5000 * 1024 * 1024 # 5000MB
|
||||
if total_size > max_size:
|
||||
logger.error(f"文件太大: {total_size} bytes")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'message': f'文件太大,最大支持 {max_size // (1024*1024)}MB,当前文件大小:{total_size // (1024*1024)}MB'
|
||||
}), 413
|
||||
|
||||
logger.info(f"文件写入临时文件完成,总大小: {total_size} bytes")
|
||||
|
||||
# 移动临时文件到最终位置
|
||||
shutil.move(temp_file_path, final_file_path)
|
||||
temp_file_path = None # 标记已移动,避免重复删除
|
||||
|
||||
logger.info(f"文件移动到最终位置完成: {final_file_path}")
|
||||
|
||||
# 更新配置文件
|
||||
if file_type == 'image':
|
||||
if filename not in config.get('作品截图', []):
|
||||
config.setdefault('作品截图', []).append(filename)
|
||||
# 记录原始文件名映射
|
||||
config.setdefault('原始文件名', {})
|
||||
config['原始文件名'][filename] = original_filename
|
||||
if not config.get('作品封面'):
|
||||
config['作品封面'] = filename
|
||||
elif file_type == 'video':
|
||||
if filename not in config.get('作品视频', []):
|
||||
config.setdefault('作品视频', []).append(filename)
|
||||
# 记录原始文件名映射
|
||||
config.setdefault('原始文件名', {})
|
||||
config['原始文件名'][filename] = original_filename
|
||||
elif file_type == 'platform':
|
||||
platform = request.form.get('platform')
|
||||
config.setdefault('文件名称', {}).setdefault(platform, [])
|
||||
if filename not in config['文件名称'][platform]:
|
||||
config['文件名称'][platform].append(filename)
|
||||
# 记录原始文件名映射
|
||||
config.setdefault('原始文件名', {})
|
||||
config['原始文件名'][filename] = original_filename
|
||||
|
||||
config['更新时间'] = datetime.now().isoformat()
|
||||
|
||||
# 原子性更新配置文件
|
||||
temp_config_path = config_path + '.tmp'
|
||||
try:
|
||||
with open(temp_config_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(config, f, ensure_ascii=False, indent=2)
|
||||
shutil.move(temp_config_path, config_path)
|
||||
except Exception as e:
|
||||
# 清理临时配置文件
|
||||
if os.path.exists(temp_config_path):
|
||||
os.remove(temp_config_path)
|
||||
raise e
|
||||
|
||||
logger.info(f"文件上传成功: {filename}, 大小: {total_size} bytes")
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'message': '上传成功',
|
||||
'filename': filename,
|
||||
'file_size': total_size
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
# 清理临时文件
|
||||
if temp_file_path and os.path.exists(temp_file_path):
|
||||
try:
|
||||
os.remove(temp_file_path)
|
||||
except:
|
||||
pass
|
||||
|
||||
logger.error(f"文件上传错误: {str(e)}")
|
||||
logger.error(f"错误类型: {type(e)}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
# 特殊处理文件大小超限错误
|
||||
if 'Request Entity Too Large' in str(e) or 'exceeded maximum allowed payload' in str(e):
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'message': '文件太大,请选择小于5000MB的文件'
|
||||
}), 413
|
||||
|
||||
return jsonify({'success': False, 'message': f'上传失败: {str(e)}'}), 500
|
||||
|
||||
@app.route('/api/admin/delete-file/<work_id>/<file_type>/<filename>', methods=['DELETE'])
|
||||
def admin_delete_file(work_id, file_type, filename):
|
||||
"""管理员删除文件"""
|
||||
if not verify_admin_token():
|
||||
return jsonify({'success': False, 'message': '权限不足'}), 403
|
||||
|
||||
try:
|
||||
work_dir = os.path.join(WORKS_DIR, work_id)
|
||||
config_path = os.path.join(work_dir, 'work_config.json')
|
||||
|
||||
if not os.path.exists(config_path):
|
||||
return jsonify({'success': False, 'message': '作品不存在'}), 404
|
||||
|
||||
# 确定文件路径
|
||||
if file_type == 'image':
|
||||
file_path = os.path.join(work_dir, 'image', filename)
|
||||
elif file_type == 'video':
|
||||
file_path = os.path.join(work_dir, 'video', filename)
|
||||
elif file_type == 'platform':
|
||||
platform = request.args.get('platform')
|
||||
if not platform:
|
||||
return jsonify({'success': False, 'message': '平台参数缺失'}), 400
|
||||
file_path = os.path.join(work_dir, 'platform', platform, filename)
|
||||
else:
|
||||
return jsonify({'success': False, 'message': '不支持的文件类型'}), 400
|
||||
|
||||
# 删除文件
|
||||
if os.path.exists(file_path):
|
||||
os.remove(file_path)
|
||||
|
||||
# 更新配置文件
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
config = json.load(f)
|
||||
|
||||
if file_type == 'image':
|
||||
if filename in config.get('作品截图', []):
|
||||
config['作品截图'].remove(filename)
|
||||
# 清理原始文件名映射
|
||||
if '原始文件名' in config and filename in config['原始文件名']:
|
||||
del config['原始文件名'][filename]
|
||||
if config.get('作品封面') == filename:
|
||||
config['作品封面'] = config['作品截图'][0] if config['作品截图'] else ''
|
||||
elif file_type == 'video':
|
||||
if filename in config.get('作品视频', []):
|
||||
config['作品视频'].remove(filename)
|
||||
# 清理原始文件名映射
|
||||
if '原始文件名' in config and filename in config['原始文件名']:
|
||||
del config['原始文件名'][filename]
|
||||
elif file_type == 'platform':
|
||||
platform = request.args.get('platform')
|
||||
if platform in config.get('文件名称', {}):
|
||||
if filename in config['文件名称'][platform]:
|
||||
config['文件名称'][platform].remove(filename)
|
||||
# 清理原始文件名映射
|
||||
if '原始文件名' in config and filename in config['原始文件名']:
|
||||
del config['原始文件名'][filename]
|
||||
|
||||
config['更新时间'] = datetime.now().isoformat()
|
||||
|
||||
with open(config_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(config, f, ensure_ascii=False, indent=2)
|
||||
|
||||
return jsonify({'success': True, 'message': '删除成功'})
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'message': f'删除失败: {str(e)}'}), 500
|
||||
|
||||
if __name__ == '__main__':
|
||||
port = int(os.environ.get('PORT', '5000'))
|
||||
debug = os.environ.get('FLASK_DEBUG', '').lower() in {'1', 'true', 'yes'}
|
||||
app.run(debug=debug, host='0.0.0.0', port=port)
|
||||
24
SproutWorkCollect-Backend-Python/docker-compose.yml
Normal file
24
SproutWorkCollect-Backend-Python/docker-compose.yml
Normal file
@@ -0,0 +1,24 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
sproutworkcollect-api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: sproutworkcollect-backend
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${SPROUTWORKCOLLECT_PORT:-5000}:5000"
|
||||
environment:
|
||||
- PORT=5000
|
||||
- SPROUTWORKCOLLECT_DATA_DIR=/data
|
||||
volumes:
|
||||
# 默认后端持久化路径:/shumengya/docker/sproutworkcollect/data/
|
||||
- "${SPROUTWORKCOLLECT_DATA_PATH:-/shumengya/docker/sproutworkcollect/data}/works:/data/works"
|
||||
- "${SPROUTWORKCOLLECT_DATA_PATH:-/shumengya/docker/sproutworkcollect/data}/config:/data/config"
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:5000/api/settings').read()"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 40s
|
||||
8
SproutWorkCollect-Backend-Python/requirements.txt
Normal file
8
SproutWorkCollect-Backend-Python/requirements.txt
Normal file
@@ -0,0 +1,8 @@
|
||||
Flask==3.0.0
|
||||
Flask-CORS==4.0.0
|
||||
Werkzeug==3.0.1
|
||||
Jinja2==3.1.2
|
||||
MarkupSafe==2.1.3
|
||||
itsdangerous==2.1.2
|
||||
click==8.1.7
|
||||
blinker==1.7.0
|
||||
167
SproutWorkCollect-Backend-Python/后端返回接口.json
Normal file
167
SproutWorkCollect-Backend-Python/后端返回接口.json
Normal file
@@ -0,0 +1,167 @@
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"上传时间": "2025-01-01T00:00:00",
|
||||
"下载链接": {
|
||||
"Android": [
|
||||
"/api/download/aicodevartool/Android/aicodevartool_android.zip"
|
||||
],
|
||||
"Linux": [
|
||||
"/api/download/aicodevartool/Linux/aicodevartool_linux.zip"
|
||||
],
|
||||
"Windows": [
|
||||
"/api/download/aicodevartool/Windows/aicodevartool_windows.zip"
|
||||
]
|
||||
},
|
||||
"作品ID": "aicodevartool",
|
||||
"作品作品": "AI代码变量工具",
|
||||
"作品分类": "开发工具",
|
||||
"作品封面": "image1.jpg",
|
||||
"作品截图": [
|
||||
"image1.jpg",
|
||||
"image2.jpg",
|
||||
"image3.jpg"
|
||||
],
|
||||
"作品描述": "一个强大的AI辅助代码变量命名和管理工具,帮助开发者提高编程效率",
|
||||
"作品标签": [
|
||||
"AI",
|
||||
"开发工具",
|
||||
"代码助手",
|
||||
"原创"
|
||||
],
|
||||
"作品版本号": "1.0.0",
|
||||
"作品视频": [],
|
||||
"作者": "树萌芽",
|
||||
"图片链接": [
|
||||
"/api/image/aicodevartool/image1.jpg",
|
||||
"/api/image/aicodevartool/image2.jpg",
|
||||
"/api/image/aicodevartool/image3.jpg"
|
||||
],
|
||||
"支持平台": [
|
||||
"Windows",
|
||||
"Android",
|
||||
"Linux"
|
||||
],
|
||||
"文件名称": {
|
||||
"Android": [
|
||||
"aicodevartool_android.zip"
|
||||
],
|
||||
"Linux": [
|
||||
"aicodevartool_linux.zip"
|
||||
],
|
||||
"Windows": [
|
||||
"aicodevartool_windows.zip"
|
||||
]
|
||||
},
|
||||
"更新时间": "2025-01-01T00:00:00",
|
||||
"视频链接": []
|
||||
},
|
||||
{
|
||||
"上传时间": "2024-12-15T00:00:00",
|
||||
"下载链接": {
|
||||
"Android": [
|
||||
"/api/download/mengyafarm/Android/mengyafarm_android.apk"
|
||||
],
|
||||
"Windows": [
|
||||
"/api/download/mengyafarm/Windows/mengyafarm_windows.zip"
|
||||
]
|
||||
},
|
||||
"作品ID": "mengyafarm",
|
||||
"作品作品": "萌芽农场",
|
||||
"作品分类": "游戏",
|
||||
"作品封面": "image1.png",
|
||||
"作品截图": [
|
||||
"image1.png",
|
||||
"image2.png",
|
||||
"image3.png",
|
||||
"image4.png",
|
||||
"image5.png",
|
||||
"image6.png"
|
||||
],
|
||||
"作品描述": "一款可爱的模拟经营类游戏,体验种植的乐趣,建设属于你的梦想农场",
|
||||
"作品标签": [
|
||||
"模拟经营",
|
||||
"农场",
|
||||
"休闲游戏",
|
||||
"原创"
|
||||
],
|
||||
"作品版本号": "2.1.0",
|
||||
"作品视频": [],
|
||||
"作者": "树萌芽",
|
||||
"图片链接": [
|
||||
"/api/image/mengyafarm/image1.png",
|
||||
"/api/image/mengyafarm/image2.png",
|
||||
"/api/image/mengyafarm/image3.png",
|
||||
"/api/image/mengyafarm/image4.png",
|
||||
"/api/image/mengyafarm/image5.png",
|
||||
"/api/image/mengyafarm/image6.png"
|
||||
],
|
||||
"支持平台": [
|
||||
"Windows",
|
||||
"Android"
|
||||
],
|
||||
"文件名称": {
|
||||
"Android": [
|
||||
"mengyafarm_android.apk"
|
||||
],
|
||||
"Windows": [
|
||||
"mengyafarm_windows.zip"
|
||||
]
|
||||
},
|
||||
"更新时间": "2025-01-01T00:00:00",
|
||||
"视频链接": []
|
||||
},
|
||||
{
|
||||
"上传时间": "2025-01-01T00:00:00",
|
||||
"下载链接": {
|
||||
"Windows": [
|
||||
"/api/download/mml_cgj2025/Windows/mml_cgj2025_windows.zip"
|
||||
]
|
||||
},
|
||||
"作品ID": "mml_cgj2025",
|
||||
"作品作品": "MML创意游戏大赛2025",
|
||||
"作品分类": "游戏",
|
||||
"作品封面": "image1.jpg",
|
||||
"作品截图": [
|
||||
"image1.jpg",
|
||||
"image2.jpg",
|
||||
"image3.jpg",
|
||||
"image4.jpg",
|
||||
"image5.jpg"
|
||||
],
|
||||
"作品描述": "参加2025年MML创意游戏大赛的参赛作品,展现独特的游戏创意和技术实力",
|
||||
"作品标签": [
|
||||
"比赛作品",
|
||||
"创意游戏",
|
||||
"2025",
|
||||
"原创"
|
||||
],
|
||||
"作品版本号": "1.0.0",
|
||||
"作品视频": [
|
||||
"video1.mp4"
|
||||
],
|
||||
"作者": "树萌芽",
|
||||
"图片链接": [
|
||||
"/api/image/mml_cgj2025/image1.jpg",
|
||||
"/api/image/mml_cgj2025/image2.jpg",
|
||||
"/api/image/mml_cgj2025/image3.jpg",
|
||||
"/api/image/mml_cgj2025/image4.jpg",
|
||||
"/api/image/mml_cgj2025/image5.jpg"
|
||||
],
|
||||
"支持平台": [
|
||||
"Windows"
|
||||
],
|
||||
"文件名称": {
|
||||
"Windows": [
|
||||
"mml_cgj2025_windows.zip"
|
||||
]
|
||||
},
|
||||
"更新时间": "2025-01-01T00:00:00",
|
||||
"视频链接": [
|
||||
"/api/video/mml_cgj2025/video1.mp4"
|
||||
]
|
||||
}
|
||||
],
|
||||
"success": true,
|
||||
"total": 3
|
||||
}
|
||||
29
SproutWorkCollect-Frontend/Dockerfile
Normal file
29
SproutWorkCollect-Frontend/Dockerfile
Normal file
@@ -0,0 +1,29 @@
|
||||
# 前端构建阶段
|
||||
FROM node:18-alpine as builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# 复制 package 文件
|
||||
COPY package*.json ./
|
||||
|
||||
# 安装依赖
|
||||
RUN npm install
|
||||
|
||||
# 复制源代码
|
||||
COPY . .
|
||||
|
||||
# 构建前端
|
||||
RUN npm run build
|
||||
|
||||
# Nginx 运行阶段
|
||||
FROM nginx:alpine
|
||||
|
||||
# 复制构建产物到 nginx
|
||||
COPY --from=builder /app/build /usr/share/nginx/html
|
||||
|
||||
# 复制 nginx 配置
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
20412
SproutWorkCollect-Frontend/package-lock.json
generated
Normal file
20412
SproutWorkCollect-Frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
42
SproutWorkCollect-Frontend/package.json
Normal file
42
SproutWorkCollect-Frontend/package.json
Normal file
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "shumengya-works",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@testing-library/jest-dom": "^5.16.4",
|
||||
"@testing-library/react": "^13.3.0",
|
||||
"@testing-library/user-event": "^13.5.0",
|
||||
"axios": "^1.4.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-router-dom": "^6.8.0",
|
||||
"react-scripts": "5.0.1",
|
||||
"styled-components": "^5.3.9",
|
||||
"web-vitals": "^2.1.4"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"eject": "react-scripts eject"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
},
|
||||
"proxy": "http://localhost:5000"
|
||||
}
|
||||
15
SproutWorkCollect-Frontend/public/.htaccess
Normal file
15
SproutWorkCollect-Frontend/public/.htaccess
Normal file
@@ -0,0 +1,15 @@
|
||||
# Apache配置 - SPA路由支持
|
||||
Options -MultiViews
|
||||
RewriteEngine On
|
||||
RewriteCond %{REQUEST_FILENAME} !-f
|
||||
RewriteRule ^ index.html [QSA,L]
|
||||
|
||||
# 大文件上传支持
|
||||
# 注意:这些配置可能需要服务器级别的权限才能生效
|
||||
# 如果遇到问题,请联系服务器管理员
|
||||
<IfModule mod_php.c>
|
||||
php_value upload_max_filesize 500M
|
||||
php_value post_max_size 500M
|
||||
php_value max_execution_time 300
|
||||
php_value max_input_time 300
|
||||
</IfModule>
|
||||
2
SproutWorkCollect-Frontend/public/_redirects
Normal file
2
SproutWorkCollect-Frontend/public/_redirects
Normal file
@@ -0,0 +1,2 @@
|
||||
# Netlify redirects for SPA
|
||||
/* /index.html 200
|
||||
BIN
SproutWorkCollect-Frontend/public/assets/favicon.ico
Normal file
BIN
SproutWorkCollect-Frontend/public/assets/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 112 KiB |
BIN
SproutWorkCollect-Frontend/public/assets/logo.png
Normal file
BIN
SproutWorkCollect-Frontend/public/assets/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.8 MiB |
34
SproutWorkCollect-Frontend/public/index.html
Normal file
34
SproutWorkCollect-Frontend/public/index.html
Normal file
@@ -0,0 +1,34 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" type="image/png" href="%PUBLIC_URL%/assets/icon.png" />
|
||||
<link rel="apple-touch-icon" href="%PUBLIC_URL%/assets/icon.png" />
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.webmanifest" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#81c784" />
|
||||
<meta name="description" content="树萌芽の作品集 - 展示我的创意作品和项目" />
|
||||
<title>树萌芽の作品集</title>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
|
||||
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
||||
sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
background: linear-gradient(135deg, #e8f5e8 0%, #f1f8e9 100%);
|
||||
min-height: 100vh;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>您需要启用JavaScript来运行此应用程序。</noscript>
|
||||
<div id="root"></div>
|
||||
</body>
|
||||
</html>
|
||||
27
SproutWorkCollect-Frontend/public/manifest.webmanifest
Normal file
27
SproutWorkCollect-Frontend/public/manifest.webmanifest
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "萌芽作品集",
|
||||
"short_name": "萌芽作品集",
|
||||
"lang": "zh-CN",
|
||||
"start_url": ".",
|
||||
"scope": ".",
|
||||
"display": "standalone",
|
||||
"orientation": "any",
|
||||
"background_color": "#e8f5e9",
|
||||
"theme_color": "#81c784",
|
||||
"description": "展示个人制作的一些小创意和小项目,支持安装到桌面使用。",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/assets/icon.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "any"
|
||||
},
|
||||
{
|
||||
"src": "/assets/icon.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "any maskable"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
277
SproutWorkCollect-Frontend/src/App.js
Normal file
277
SproutWorkCollect-Frontend/src/App.js
Normal file
@@ -0,0 +1,277 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { HashRouter as Router, Routes, Route } from 'react-router-dom';
|
||||
import styled from 'styled-components';
|
||||
import Header from './components/Header';
|
||||
import WorkCard from './components/WorkCard';
|
||||
import WorkDetail from './components/WorkDetail';
|
||||
import AdminPanel from './components/AdminPanel';
|
||||
import SearchBar from './components/SearchBar';
|
||||
import CategoryFilter from './components/CategoryFilter';
|
||||
import LoadingSpinner from './components/LoadingSpinner';
|
||||
import Footer from './components/Footer';
|
||||
import Pagination from './components/Pagination';
|
||||
import { getWorks, getSettings, getCategories, searchWorks } from './services/api';
|
||||
import { BACKGROUND_CONFIG, pickBackgroundImage } from './config/background';
|
||||
|
||||
const AppContainer = styled.div`
|
||||
min-height: 100vh;
|
||||
background: ${({ $backgroundUrl }) =>
|
||||
$backgroundUrl
|
||||
? `url(${$backgroundUrl}) center/cover no-repeat fixed`
|
||||
: `linear-gradient(
|
||||
135deg,
|
||||
rgba(232, 245, 232, 0.4) 0%,
|
||||
rgba(200, 230, 201, 0.4) 20%,
|
||||
rgba(165, 214, 167, 0.4) 40%,
|
||||
rgba(255, 255, 224, 0.3) 60%,
|
||||
rgba(255, 255, 200, 0.3) 80%,
|
||||
rgba(240, 255, 240, 0.4) 100%
|
||||
)`};
|
||||
background-size: ${({ $backgroundUrl }) => ($backgroundUrl ? 'cover' : '400% 400%')};
|
||||
animation: ${({ $backgroundUrl }) => ($backgroundUrl ? 'none' : 'gentleShift 25s ease infinite')};
|
||||
position: relative;
|
||||
|
||||
&:before {
|
||||
content: '';
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: ${({ $blurOverlayOpacity }) =>
|
||||
`rgba(255, 255, 255, ${$blurOverlayOpacity})`};
|
||||
backdrop-filter: ${({ $blurAmount }) => `blur(${$blurAmount})`};
|
||||
pointer-events: none;
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
@keyframes gentleShift {
|
||||
0% {
|
||||
background-position: 0% 50%;
|
||||
}
|
||||
50% {
|
||||
background-position: 100% 50%;
|
||||
}
|
||||
100% {
|
||||
background-position: 0% 50%;
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const MainContent = styled.main`
|
||||
max-width: 1440px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
const WorksGrid = styled.div`
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 20px;
|
||||
margin-top: 20px;
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 15px;
|
||||
}
|
||||
`;
|
||||
|
||||
const FilterSection = styled.div`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 15px;
|
||||
margin-bottom: 20px;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
`;
|
||||
|
||||
const NoResults = styled.div`
|
||||
text-align: center;
|
||||
padding: 40px 20px;
|
||||
color: #666;
|
||||
font-size: 18px;
|
||||
`;
|
||||
|
||||
// 首页组件
|
||||
const HomePage = ({ settings }) => {
|
||||
const [works, setWorks] = useState([]);
|
||||
const [allWorks, setAllWorks] = useState([]); // 存储所有作品数据
|
||||
const [categories, setCategories] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [selectedCategory, setSelectedCategory] = useState('');
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
|
||||
// 从设置中获取每页作品数量,默认12(三行四列)
|
||||
const itemsPerPage = settings['每页作品数量'] || 12;
|
||||
|
||||
useEffect(() => {
|
||||
loadInitialData();
|
||||
}, []);
|
||||
|
||||
const loadInitialData = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const [worksData, categoriesData] = await Promise.all([
|
||||
getWorks(),
|
||||
getCategories()
|
||||
]);
|
||||
|
||||
const allWorksData = worksData.data || [];
|
||||
setAllWorks(allWorksData);
|
||||
setWorks(allWorksData);
|
||||
setCategories(categoriesData.data || []);
|
||||
setCurrentPage(1); // 重置到第一页
|
||||
} catch (error) {
|
||||
console.error('加载数据失败:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSearch = async (query) => {
|
||||
setSearchQuery(query);
|
||||
await performSearch(query, selectedCategory);
|
||||
};
|
||||
|
||||
const handleCategoryChange = async (category) => {
|
||||
setSelectedCategory(category);
|
||||
await performSearch(searchQuery, category);
|
||||
};
|
||||
|
||||
const performSearch = async (query, category) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
if (query || category) {
|
||||
const searchData = await searchWorks(query, category);
|
||||
setAllWorks(searchData.data || []);
|
||||
setWorks(searchData.data || []);
|
||||
} else {
|
||||
const worksData = await getWorks();
|
||||
setAllWorks(worksData.data || []);
|
||||
setWorks(worksData.data || []);
|
||||
}
|
||||
setCurrentPage(1); // 搜索后重置到第一页
|
||||
} catch (error) {
|
||||
console.error('搜索失败:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 分页相关的计算
|
||||
const totalPages = Math.ceil(works.length / itemsPerPage);
|
||||
const startIndex = (currentPage - 1) * itemsPerPage;
|
||||
const endIndex = startIndex + itemsPerPage;
|
||||
const currentWorks = works.slice(startIndex, endIndex);
|
||||
|
||||
// 处理页面变化
|
||||
const handlePageChange = (page) => {
|
||||
setCurrentPage(page);
|
||||
// 滚动到顶部
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
};
|
||||
|
||||
return (
|
||||
<MainContent>
|
||||
<FilterSection>
|
||||
<SearchBar onSearch={handleSearch} />
|
||||
<CategoryFilter
|
||||
categories={categories}
|
||||
selectedCategory={selectedCategory}
|
||||
onCategoryChange={handleCategoryChange}
|
||||
/>
|
||||
</FilterSection>
|
||||
|
||||
{loading ? (
|
||||
<LoadingSpinner />
|
||||
) : works.length > 0 ? (
|
||||
<>
|
||||
<WorksGrid>
|
||||
{currentWorks.map((work) => (
|
||||
<WorkCard key={work.作品ID} work={work} />
|
||||
))}
|
||||
</WorksGrid>
|
||||
<Pagination
|
||||
currentPage={currentPage}
|
||||
totalPages={totalPages}
|
||||
totalItems={works.length}
|
||||
itemsPerPage={itemsPerPage}
|
||||
onPageChange={handlePageChange}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<NoResults>
|
||||
{searchQuery || selectedCategory ? '🔍 没有找到匹配的作品' : '📝 暂无作品'}
|
||||
</NoResults>
|
||||
)}
|
||||
</MainContent>
|
||||
);
|
||||
};
|
||||
|
||||
function App() {
|
||||
const [settings, setSettings] = useState({});
|
||||
const [backgroundUrl, setBackgroundUrl] = useState(null);
|
||||
const [blurConfig] = useState(BACKGROUND_CONFIG.blur || { enabled: true, amount: '6px', overlayOpacity: 0.35 });
|
||||
|
||||
useEffect(() => {
|
||||
loadSettings();
|
||||
}, []);
|
||||
|
||||
// 将后端 settings.json 中的「网站名字」同步到浏览器标签页标题
|
||||
useEffect(() => {
|
||||
if (settings['网站名字']) {
|
||||
document.title = settings['网站名字'];
|
||||
}
|
||||
}, [settings]);
|
||||
|
||||
// 页面初始化时,根据设备类型随机选择一张背景图
|
||||
useEffect(() => {
|
||||
const isMobile = window.innerWidth <= 768;
|
||||
const url = pickBackgroundImage(isMobile);
|
||||
if (url) {
|
||||
setBackgroundUrl(url);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadSettings = async () => {
|
||||
try {
|
||||
const settingsData = await getSettings();
|
||||
setSettings(settingsData);
|
||||
} catch (error) {
|
||||
console.error('加载设置失败:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Router>
|
||||
<AppContainer
|
||||
$backgroundUrl={backgroundUrl}
|
||||
$blurAmount={blurConfig.enabled ? blurConfig.amount : '0px'}
|
||||
$blurOverlayOpacity={blurConfig.enabled ? blurConfig.overlayOpacity : 0}
|
||||
>
|
||||
<Header settings={settings} />
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage settings={settings} />} />
|
||||
<Route path="/work/:workId" element={<WorkDetail />} />
|
||||
<Route path="/admin" element={<AdminPanel />} />
|
||||
</Routes>
|
||||
<Footer settings={settings} />
|
||||
</AppContainer>
|
||||
</Router>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
324
SproutWorkCollect-Frontend/src/components/AdminPanel.js
Normal file
324
SproutWorkCollect-Frontend/src/components/AdminPanel.js
Normal file
@@ -0,0 +1,324 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useSearchParams, useNavigate } from 'react-router-dom';
|
||||
import styled from 'styled-components';
|
||||
import LoadingSpinner from './LoadingSpinner';
|
||||
import WorkEditor from './WorkEditor';
|
||||
import { setAdminToken, adminGetWorks, adminDeleteWork, getAdminToken } from '../services/adminApi';
|
||||
|
||||
const AdminContainer = styled.div`
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
const AdminHeader = styled.div`
|
||||
background: white;
|
||||
border-radius: 15px;
|
||||
padding: 20px;
|
||||
margin-bottom: 20px;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
flex-direction: column;
|
||||
gap: 15px;
|
||||
text-align: center;
|
||||
}
|
||||
`;
|
||||
|
||||
const AdminTitle = styled.h1`
|
||||
color: #2e7d32;
|
||||
font-size: 1.8rem;
|
||||
margin: 0;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
`;
|
||||
|
||||
const ButtonGroup = styled.div`
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
}
|
||||
`;
|
||||
|
||||
const Button = styled.button`
|
||||
background: ${props => props.variant === 'danger' ? '#f44336' : '#81c784'};
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 10px 20px;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
transition: background 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
background: ${props => props.variant === 'danger' ? '#d32f2f' : '#66bb6a'};
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
background: #ccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 12px 16px;
|
||||
width: 100%;
|
||||
}
|
||||
`;
|
||||
|
||||
const WorksList = styled.div`
|
||||
background: white;
|
||||
border-radius: 15px;
|
||||
padding: 20px;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 15px;
|
||||
}
|
||||
`;
|
||||
|
||||
const WorkItem = styled.div`
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 15px;
|
||||
border: 1px solid #eee;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 10px;
|
||||
transition: background 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
background: #f8f9fa;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
const WorkInfo = styled.div`
|
||||
flex: 1;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
text-align: center;
|
||||
}
|
||||
`;
|
||||
|
||||
const WorkTitle = styled.h3`
|
||||
color: #2e7d32;
|
||||
margin: 0 0 5px 0;
|
||||
font-size: 1.1rem;
|
||||
`;
|
||||
|
||||
const WorkMeta = styled.p`
|
||||
color: #666;
|
||||
margin: 0;
|
||||
font-size: 0.9rem;
|
||||
`;
|
||||
|
||||
const WorkActions = styled.div`
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
justify-content: center;
|
||||
}
|
||||
`;
|
||||
|
||||
const SmallButton = styled.button`
|
||||
background: ${props => {
|
||||
if (props.variant === 'danger') return '#f44336';
|
||||
if (props.variant === 'secondary') return '#757575';
|
||||
return '#81c784';
|
||||
}};
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 6px 12px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
transition: background 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
background: ${props => {
|
||||
if (props.variant === 'danger') return '#d32f2f';
|
||||
if (props.variant === 'secondary') return '#616161';
|
||||
return '#66bb6a';
|
||||
}};
|
||||
}
|
||||
`;
|
||||
|
||||
const ErrorMessage = styled.div`
|
||||
background: #ffebee;
|
||||
color: #c62828;
|
||||
padding: 15px;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 20px;
|
||||
text-align: center;
|
||||
`;
|
||||
|
||||
const AdminPanel = () => {
|
||||
const [searchParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const [works, setWorks] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
const [showEditor, setShowEditor] = useState(false);
|
||||
const [editingWork, setEditingWork] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
const urlToken = searchParams.get('token');
|
||||
const currentToken = getAdminToken();
|
||||
|
||||
// 如果没有 URL token 且也没有之前设置的 token,则认为未授权,返回首页
|
||||
if (!urlToken && !currentToken) {
|
||||
navigate('/');
|
||||
return;
|
||||
}
|
||||
|
||||
// URL 上有 token 时,更新全局 admin token
|
||||
if (urlToken && urlToken !== currentToken) {
|
||||
setAdminToken(urlToken);
|
||||
}
|
||||
|
||||
loadWorks();
|
||||
}, [searchParams, navigate]);
|
||||
|
||||
const loadWorks = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const response = await adminGetWorks();
|
||||
if (response.success) {
|
||||
setWorks(response.data);
|
||||
} else {
|
||||
setError(response.message);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载作品失败:', error);
|
||||
setError('加载作品失败,请检查网络连接');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateWork = () => {
|
||||
setEditingWork(null);
|
||||
setShowEditor(true);
|
||||
};
|
||||
|
||||
const handleEditWork = (work) => {
|
||||
setEditingWork(work);
|
||||
setShowEditor(true);
|
||||
};
|
||||
|
||||
const handleDeleteWork = async (workId) => {
|
||||
if (!window.confirm('确定要删除这个作品吗?此操作不可恢复!')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await adminDeleteWork(workId);
|
||||
if (response.success) {
|
||||
alert('删除成功!');
|
||||
loadWorks();
|
||||
} else {
|
||||
alert(`删除失败:${response.message}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('删除作品失败:', error);
|
||||
alert('删除失败,请稍后重试');
|
||||
}
|
||||
};
|
||||
|
||||
const handleEditorClose = () => {
|
||||
setShowEditor(false);
|
||||
setEditingWork(null);
|
||||
loadWorks();
|
||||
};
|
||||
|
||||
const handleBackToHome = () => {
|
||||
navigate('/');
|
||||
};
|
||||
|
||||
if (showEditor) {
|
||||
return (
|
||||
<WorkEditor
|
||||
work={editingWork}
|
||||
onClose={handleEditorClose}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AdminContainer>
|
||||
<AdminHeader>
|
||||
<AdminTitle>管理员面板</AdminTitle>
|
||||
<ButtonGroup>
|
||||
<Button onClick={handleCreateWork}>
|
||||
+ 添加新作品
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={handleBackToHome}>
|
||||
返回首页
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
</AdminHeader>
|
||||
|
||||
{error && <ErrorMessage>{error}</ErrorMessage>}
|
||||
|
||||
{loading ? (
|
||||
<LoadingSpinner text="加载作品列表中..." />
|
||||
) : (
|
||||
<WorksList>
|
||||
<h2 style={{ color: '#2e7d32', marginBottom: '20px' }}>
|
||||
作品列表 ({works.length}个)
|
||||
</h2>
|
||||
|
||||
{works.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', color: '#666', padding: '40px' }}>
|
||||
暂无作品,点击上方按钮添加新作品
|
||||
</div>
|
||||
) : (
|
||||
works.map((work) => (
|
||||
<WorkItem key={work.作品ID}>
|
||||
<WorkInfo>
|
||||
<WorkTitle>{work.作品作品}</WorkTitle>
|
||||
<WorkMeta>
|
||||
ID: {work.作品ID} | 分类: {work.作品分类} | 版本: {work.作品版本号} |
|
||||
更新: {new Date(work.更新时间).toLocaleDateString('zh-CN')}
|
||||
</WorkMeta>
|
||||
</WorkInfo>
|
||||
<WorkActions>
|
||||
<SmallButton onClick={() => handleEditWork(work)}>
|
||||
编辑
|
||||
</SmallButton>
|
||||
<SmallButton
|
||||
variant="danger"
|
||||
onClick={() => handleDeleteWork(work.作品ID)}
|
||||
>
|
||||
删除
|
||||
</SmallButton>
|
||||
</WorkActions>
|
||||
</WorkItem>
|
||||
))
|
||||
)}
|
||||
</WorksList>
|
||||
)}
|
||||
</AdminContainer>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdminPanel;
|
||||
80
SproutWorkCollect-Frontend/src/components/CategoryFilter.js
Normal file
80
SproutWorkCollect-Frontend/src/components/CategoryFilter.js
Normal file
@@ -0,0 +1,80 @@
|
||||
import React from 'react';
|
||||
import styled from 'styled-components';
|
||||
import { getGlassOpacity } from '../config/background';
|
||||
|
||||
const glassOpacity = getGlassOpacity();
|
||||
|
||||
const FilterContainer = styled.div`
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 8px;
|
||||
}
|
||||
`;
|
||||
|
||||
const FilterLabel = styled.label`
|
||||
font-weight: 500;
|
||||
color: #2e7d32;
|
||||
white-space: nowrap;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
font-size: 14px;
|
||||
}
|
||||
`;
|
||||
|
||||
const FilterSelect = styled.select`
|
||||
padding: 8px 12px;
|
||||
border: 2px solid #e0e0e0;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
background: rgba(255, 255, 255, ${glassOpacity});
|
||||
color: #333;
|
||||
outline: none;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
min-width: 120px;
|
||||
|
||||
&:focus {
|
||||
border-color: #81c784;
|
||||
box-shadow: 0 0 0 3px rgba(129, 199, 132, 0.1);
|
||||
}
|
||||
|
||||
&:hover {
|
||||
border-color: #81c784;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
width: 100%;
|
||||
min-width: auto;
|
||||
}
|
||||
`;
|
||||
|
||||
const CategoryFilter = ({ categories, selectedCategory, onCategoryChange }) => {
|
||||
const handleChange = (e) => {
|
||||
onCategoryChange(e.target.value);
|
||||
};
|
||||
|
||||
return (
|
||||
<FilterContainer>
|
||||
<FilterLabel htmlFor="category-filter">分类筛选:</FilterLabel>
|
||||
<FilterSelect
|
||||
id="category-filter"
|
||||
value={selectedCategory}
|
||||
onChange={handleChange}
|
||||
>
|
||||
<option value="">全部分类</option>
|
||||
{categories.map((category) => (
|
||||
<option key={category} value={category}>
|
||||
{category}
|
||||
</option>
|
||||
))}
|
||||
</FilterSelect>
|
||||
</FilterContainer>
|
||||
);
|
||||
};
|
||||
|
||||
export default CategoryFilter;
|
||||
228
SproutWorkCollect-Frontend/src/components/Footer.js
Normal file
228
SproutWorkCollect-Frontend/src/components/Footer.js
Normal file
@@ -0,0 +1,228 @@
|
||||
import React from 'react';
|
||||
import styled from 'styled-components';
|
||||
import { getGlassOpacity } from '../config/background';
|
||||
|
||||
const glassOpacity = getGlassOpacity();
|
||||
|
||||
const FooterContainer = styled.footer`
|
||||
/* 底部整体背景完全透明,仅保留内部内容样式 */
|
||||
background: transparent;
|
||||
background-color: transparent;
|
||||
color: #1b5e20;
|
||||
padding: 35px 0 25px;
|
||||
margin-top: 50px;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
border-radius: 25px 25px 0 0;
|
||||
box-shadow: 0 -8px 32px rgba(27, 94, 32, 0.15);
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 3px;
|
||||
background: linear-gradient(90deg, #4caf50, #66bb6a, #81c784, #66bb6a, #4caf50);
|
||||
background-size: 200% 100%;
|
||||
animation: flowingTopBorder 3s ease-in-out infinite;
|
||||
}
|
||||
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
left: -100%;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
|
||||
animation: shimmer 5s infinite;
|
||||
}
|
||||
|
||||
@keyframes flowingTopBorder {
|
||||
0%, 100% { background-position: 0% 50%; }
|
||||
50% { background-position: 100% 50%; }
|
||||
}
|
||||
|
||||
@keyframes shimmer {
|
||||
0% { left: -100%; }
|
||||
100% { left: 100%; }
|
||||
}
|
||||
|
||||
&:hover {
|
||||
transform: translateY(-3px);
|
||||
box-shadow: 0 -12px 40px rgba(27, 94, 32, 0.2);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 25px 0 20px;
|
||||
margin-top: 35px;
|
||||
}
|
||||
`;
|
||||
|
||||
const FooterContent = styled.div`
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 0 20px;
|
||||
text-align: center;
|
||||
animation: fadeInUp 0.8s ease-out;
|
||||
|
||||
@keyframes fadeInUp {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(30px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 0 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
const FooterText = styled.p`
|
||||
font-size: 0.9rem;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
text-shadow: 0 2px 8px rgba(27, 94, 32, 0.3);
|
||||
margin-bottom: 10px;
|
||||
transition: all 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
color: rgba(255, 255, 255, 1);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
font-size: 0.8rem;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
`;
|
||||
|
||||
const ContactInfo = styled.div`
|
||||
margin-bottom: 15px;
|
||||
animation: slideInLeft 0.8s ease-out 0.2s both;
|
||||
|
||||
@keyframes slideInLeft {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(-20px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
`;
|
||||
|
||||
const ContactLink = styled.a`
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
text-decoration: none;
|
||||
text-shadow: 0 2px 8px rgba(27, 94, 32, 0.3);
|
||||
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
position: relative;
|
||||
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
bottom: -2px;
|
||||
left: 0;
|
||||
width: 0;
|
||||
height: 2px;
|
||||
background: linear-gradient(90deg, rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 1));
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
color: rgba(255, 255, 255, 1);
|
||||
transform: translateY(-1px);
|
||||
|
||||
&::after {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const RecordNumber = styled.p`
|
||||
font-size: 0.8rem;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
text-shadow: 0 2px 8px rgba(27, 94, 32, 0.3);
|
||||
margin-bottom: 5px;
|
||||
animation: slideInRight 0.8s ease-out 0.4s both;
|
||||
transition: all 0.3s ease;
|
||||
|
||||
@keyframes slideInRight {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(20px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
}
|
||||
|
||||
&:hover {
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
`;
|
||||
|
||||
const Copyright = styled.p`
|
||||
font-size: 0.8rem;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
text-shadow: 0 2px 8px rgba(27, 94, 32, 0.3);
|
||||
animation: fadeIn 0.8s ease-out 0.6s both;
|
||||
transition: all 0.3s ease;
|
||||
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 0.7; }
|
||||
}
|
||||
|
||||
&:hover {
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
`;
|
||||
|
||||
const Footer = ({ settings }) => {
|
||||
return (
|
||||
<FooterContainer>
|
||||
<FooterContent>
|
||||
<ContactInfo>
|
||||
<FooterText>
|
||||
📧 联系邮箱: <ContactLink href={`mailto:${settings.联系邮箱}`}>
|
||||
{settings.联系邮箱}
|
||||
</ContactLink>
|
||||
</FooterText>
|
||||
</ContactInfo>
|
||||
|
||||
{settings.备案号 && (
|
||||
<RecordNumber>{settings.备案号}</RecordNumber>
|
||||
)}
|
||||
|
||||
<Copyright>
|
||||
{settings.网站页尾 || '🌱 树萌芽の作品集 | Copyright © 2025 smy ✨'}
|
||||
</Copyright>
|
||||
</FooterContent>
|
||||
</FooterContainer>
|
||||
);
|
||||
};
|
||||
|
||||
export default Footer;
|
||||
284
SproutWorkCollect-Frontend/src/components/Header.js
Normal file
284
SproutWorkCollect-Frontend/src/components/Header.js
Normal file
@@ -0,0 +1,284 @@
|
||||
import React, { useRef } from 'react';
|
||||
import styled from 'styled-components';
|
||||
import { getGlassOpacity } from '../config/background';
|
||||
import { setAdminToken, adminGetWorks } from '../services/adminApi';
|
||||
|
||||
const glassOpacity = getGlassOpacity();
|
||||
|
||||
const HeaderContainer = styled.header`
|
||||
/* 顶部整体背景完全透明,仅保留内部内容样式 */
|
||||
background: transparent;
|
||||
background-color: transparent;
|
||||
color: #1b5e20; /* 深绿色文字 */
|
||||
padding: 25px 0; /* 上下内边距 */
|
||||
box-shadow: 0 8px 32px rgba(27, 94, 32, 0.15); /* 深绿色阴影效果 */
|
||||
position: relative; /* 相对定位,为伪元素提供定位基准 */
|
||||
overflow: hidden; /* 隐藏溢出内容,确保动画效果不会超出边界 */
|
||||
transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1); /* 平滑过渡动画 */
|
||||
border-radius: 0 0 25px 25px; /* 底部圆角,营造圆润效果 */
|
||||
margin-bottom: 10px; /* 与下方内容的间距 */
|
||||
|
||||
/* 光泽动画效果:从左到右的白色光泽扫过 */
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: -100%; /* 初始位置在左侧外部 */
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
/* 半透明白色渐变,中间较亮 */
|
||||
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.15), transparent);
|
||||
animation: shimmer 4s infinite; /* 4秒循环的光泽动画 */
|
||||
}
|
||||
|
||||
/* 底部流动边框:彩色边框从左到右流动 */
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 3px; /* 边框高度 */
|
||||
/* 绿色系渐变边框 */
|
||||
background: linear-gradient(90deg,rgb(21, 221, 31),rgb(2, 233, 14),rgb(0, 161, 5),rgb(0, 25rgb(12, 221, 23)#66bb6a);
|
||||
background-size: 200% 100%; /* 背景尺寸为200%,用于动画效果 */
|
||||
animation: flowingBorder 3s ease-in-out infinite; /* 3秒循环的流动动画 */
|
||||
}
|
||||
|
||||
/* 光泽扫过动画:从左侧移动到右侧 */
|
||||
@keyframes shimmer {
|
||||
0% { left: -100%; } /* 开始位置:左侧外部 */
|
||||
100% { left: 100%; } /* 结束位置:右侧外部 */
|
||||
}
|
||||
|
||||
/* 边框流动动画:背景位置左右移动 */
|
||||
@keyframes flowingBorder {
|
||||
0%, 100% { background-position: 0% 50%; } /* 起始和结束位置 */
|
||||
50% { background-position: 100% 50%; } /* 中间位置 */
|
||||
}
|
||||
|
||||
/* 悬停效果:增强阴影和轻微上移 */
|
||||
&:hover {
|
||||
box-shadow: 0 12px 40px rgba(27, 94, 32, 0.2); /* 更深的阴影 */
|
||||
transform: translateY(-2px); /* 向上移动2像素 */
|
||||
}
|
||||
`;
|
||||
|
||||
const HeaderContent = styled.div`
|
||||
max-width: 1200px; /* 最大宽度限制 */
|
||||
margin: 0 auto; /* 水平居中 */
|
||||
padding: 0 20px; /* 左右内边距 */
|
||||
text-align: center; /* 文字居中对齐 */
|
||||
display: flex; /* 弹性布局 */
|
||||
flex-direction: column; /* 垂直排列 */
|
||||
align-items: center; /* 子元素居中对齐 */
|
||||
|
||||
/* 移动端响应式:减少左右内边距 */
|
||||
@media (max-width: 768px) {
|
||||
padding: 0 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
const LogoContainer = styled.div`
|
||||
margin-bottom: 15px; /* 底部间距 */
|
||||
animation: fadeInUp 0.8s ease-out; /* 淡入向上动画 */
|
||||
|
||||
/* Logo淡入动画:从下方淡入 */
|
||||
@keyframes fadeInUp {
|
||||
from {
|
||||
opacity: 0; /* 初始透明 */
|
||||
transform: translateY(20px); /* 初始向下偏移 */
|
||||
}
|
||||
to {
|
||||
opacity: 1; /* 最终不透明 */
|
||||
transform: translateY(0); /* 最终正常位置 */
|
||||
}
|
||||
}
|
||||
|
||||
/* 移动端响应式:减少底部间距 */
|
||||
@media (max-width: 768px) {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
const Logo = styled.img`
|
||||
height: 80px; /* Logo高度 */
|
||||
width: auto; /* 宽度自适应,保持比例 */
|
||||
border-radius: 12px; /* 圆角效果 */
|
||||
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); /* 平滑过渡动画 */
|
||||
filter: drop-shadow(0 2px 8px rgba(46, 93, 49, 0.15)); /* 投影效果 */
|
||||
cursor: pointer;
|
||||
|
||||
/* Logo悬停效果:放大并轻微旋转 */
|
||||
&:hover {
|
||||
transform: scale(1.05) rotate(2deg); /* 放大105%并旋转2度 */
|
||||
filter: drop-shadow(0 4px 12px rgba(46, 93, 49, 0.25)); /* 增强投影 */
|
||||
}
|
||||
|
||||
/* 移动端响应式:减小Logo尺寸 */
|
||||
@media (max-width: 768px) {
|
||||
height: 60px;
|
||||
}
|
||||
`;
|
||||
|
||||
const Title = styled.h1`
|
||||
font-size: 3rem; /* 标题字体大小 */
|
||||
margin-bottom: 10px; /* 底部间距 */
|
||||
font-weight: 700; /* 字体粗细 */
|
||||
position: relative; /* 相对定位,为伪元素提供基准 */
|
||||
|
||||
/* 文字颜色:纯白色,保持清晰可读 */
|
||||
color: #ffffff;
|
||||
|
||||
/* 金色描边效果:使用-webkit-text-stroke创建外描边 */
|
||||
-webkit-text-stroke: 2px #ffd700; /* 2像素金色描边 */
|
||||
text-stroke: 2px #ffd700; /* 标准属性 */
|
||||
|
||||
/* 外围辐射金光:只在外围产生光晕,不影响文字内部 */
|
||||
filter: drop-shadow(0 0 4px #ffd700)
|
||||
drop-shadow(0 0 8px #ffd700)
|
||||
drop-shadow(0 0 12px #ffed4e);
|
||||
|
||||
/* 底部立体阴影 */
|
||||
text-shadow: 0 3px 6px rgba(0,0,0,0.3);
|
||||
|
||||
/* 淡入向上动画 + 金光闪烁效果 */
|
||||
animation:
|
||||
fadeInUp 0.8s ease-out 0.2s both, /* 淡入向上动画 */
|
||||
goldGlow 3s ease-in-out infinite; /* 金光闪烁效果 */
|
||||
|
||||
|
||||
|
||||
/* 淡入向上动画 */
|
||||
@keyframes fadeInUp {
|
||||
from {
|
||||
opacity: 0; /* 初始透明 */
|
||||
transform: translateY(20px); /* 初始位置向下偏移 */
|
||||
}
|
||||
to {
|
||||
opacity: 1; /* 最终不透明 */
|
||||
transform: translateY(0); /* 最终位置正常 */
|
||||
}
|
||||
}
|
||||
|
||||
/* 响应式设计:移动端字体大小调整 */
|
||||
@media (max-width: 768px) {
|
||||
font-size: 2.5rem; /* 移动端较小字体 */
|
||||
-webkit-text-stroke: 1.5px #ffd700; /* 移动端较细描边 */
|
||||
|
||||
/* 移动端减弱光晕效果,避免性能问题 */
|
||||
filter: drop-shadow(0 0 6px #ffd700)
|
||||
drop-shadow(0 0 12px #ffed4e);
|
||||
}
|
||||
`;
|
||||
|
||||
const Description = styled.p`
|
||||
font-size: 1.1rem; /* 描述文字大小 */
|
||||
color: rgba(255, 255, 255, 0.9); /* 半透明白色文字 */
|
||||
text-shadow: 0 2px 8px rgba(27, 94, 32, 0.3); /* 绿色文字阴影 */
|
||||
margin-bottom: 5px; /* 底部间距 */
|
||||
animation: fadeInUp 0.8s ease-out 0.4s both; /* 延迟0.4秒的淡入动画 */
|
||||
transition: all 0.3s ease; /* 平滑过渡效果 */
|
||||
|
||||
/* 描述文字悬停效果:变为完全不透明并上移 */
|
||||
&:hover {
|
||||
color: rgba(255, 255, 255, 1); /* 完全不透明的白色 */
|
||||
transform: translateY(-2px); /* 向上移动2像素 */
|
||||
}
|
||||
|
||||
/* 移动端响应式:减小字体大小 */
|
||||
@media (max-width: 768px) {
|
||||
font-size: 1rem;
|
||||
}
|
||||
`;
|
||||
|
||||
const Author = styled.p`
|
||||
font-size: 0.9rem; /* 作者信息字体大小 */
|
||||
color: rgba(255, 255, 255, 0.8); /* 更透明的白色文字 */
|
||||
text-shadow: 0 2px 8px rgba(27, 94, 32, 0.3); /* 绿色文字阴影 */
|
||||
animation: fadeInUp 0.8s ease-out 0.6s both; /* 延迟0.6秒的淡入动画 */
|
||||
transition: all 0.3s ease; /* 平滑过渡效果 */
|
||||
|
||||
/* 作者信息悬停效果:变为完全不透明并上移 */
|
||||
&:hover {
|
||||
color: rgba(255, 255, 255, 1); /* 完全不透明的白色 */
|
||||
transform: translateY(-2px); /* 向上移动2像素 */
|
||||
}
|
||||
`;
|
||||
|
||||
const DEFAULT_LOGO = `${process.env.PUBLIC_URL || ''}/assets/logo.png`;
|
||||
const DEFAULT_FAVICON = `${process.env.PUBLIC_URL || ''}/assets/icon.png`;
|
||||
|
||||
const Header = ({ settings }) => {
|
||||
// 隐藏入口:点击 Logo 5 次后触发管理员口令输入
|
||||
const logoClickCountRef = useRef(0);
|
||||
const lastClickTimeRef = useRef(0);
|
||||
|
||||
// 动态设置 favicon:优先使用后端配置的网站 logo,否则使用前端默认 icon
|
||||
React.useEffect(() => {
|
||||
const iconHref = settings.网站logo || DEFAULT_FAVICON;
|
||||
const existing = document.querySelector('link[rel="icon"]');
|
||||
if (existing) {
|
||||
existing.href = iconHref;
|
||||
} else {
|
||||
const link = document.createElement('link');
|
||||
link.rel = 'icon';
|
||||
link.href = iconHref;
|
||||
document.head.appendChild(link);
|
||||
}
|
||||
}, [settings.网站logo]);
|
||||
|
||||
const handleLogoSecretClick = () => {
|
||||
const now = Date.now();
|
||||
const interval = now - lastClickTimeRef.current;
|
||||
|
||||
// 超过 2 秒则重新计数,避免误触
|
||||
if (interval > 2000) {
|
||||
logoClickCountRef.current = 0;
|
||||
}
|
||||
|
||||
lastClickTimeRef.current = now;
|
||||
logoClickCountRef.current += 1;
|
||||
|
||||
if (logoClickCountRef.current >= 5) {
|
||||
logoClickCountRef.current = 0;
|
||||
const tokenInput = window.prompt('请输入管理员口令进入后台:');
|
||||
if (!tokenInput) return;
|
||||
|
||||
const token = tokenInput.trim();
|
||||
setAdminToken(token);
|
||||
|
||||
// 简单校验:尝试拉取一次后台作品列表
|
||||
adminGetWorks()
|
||||
.then(() => {
|
||||
window.location.hash = '#/admin';
|
||||
})
|
||||
.catch(() => {
|
||||
// eslint-disable-next-line no-alert
|
||||
alert('口令错误或无权限,请重试。');
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<HeaderContainer>
|
||||
<HeaderContent>
|
||||
<LogoContainer>
|
||||
<Logo
|
||||
src={settings.网站logo || DEFAULT_LOGO}
|
||||
alt={settings.网站名字 || '树萌芽の作品集'}
|
||||
onClick={handleLogoSecretClick}
|
||||
onError={(e) => {
|
||||
e.target.style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
</LogoContainer>
|
||||
<Title>{settings.网站名字 || '树萌芽の作品集'}</Title>
|
||||
<Description>{settings.网站描述 || '展示我的创意作品和项目'}</Description>
|
||||
<Author>{settings.站长 || '树萌芽'}</Author>
|
||||
</HeaderContent>
|
||||
</HeaderContainer>
|
||||
);
|
||||
};
|
||||
|
||||
export default Header;
|
||||
150
SproutWorkCollect-Frontend/src/components/LoadingSpinner.js
Normal file
150
SproutWorkCollect-Frontend/src/components/LoadingSpinner.js
Normal file
@@ -0,0 +1,150 @@
|
||||
import React from 'react';
|
||||
import styled, { keyframes } from 'styled-components';
|
||||
|
||||
// 背景柔和脉冲动画(亮度轻微变化)
|
||||
const bgPulse = keyframes`
|
||||
0%, 100% { opacity: 1; }
|
||||
50% { opacity: 0.96; }
|
||||
`;
|
||||
|
||||
// Logo 轻微上下浮动
|
||||
const float = keyframes`
|
||||
0%, 100% { transform: translateY(0); }
|
||||
50% { transform: translateY(-8px); }
|
||||
`;
|
||||
|
||||
// 扩散圆环动画
|
||||
const ringPulse = keyframes`
|
||||
0% {
|
||||
transform: scale(0.8);
|
||||
opacity: 0.6;
|
||||
}
|
||||
70% {
|
||||
transform: scale(1.4);
|
||||
opacity: 0;
|
||||
}
|
||||
100% {
|
||||
transform: scale(1.4);
|
||||
opacity: 0;
|
||||
}
|
||||
`;
|
||||
|
||||
// 底部三个圆点缩放动画
|
||||
const dotPulse = keyframes`
|
||||
0%, 80%, 100% { transform: scale(0.6); opacity: 0.4; }
|
||||
40% { transform: scale(1); opacity: 1; }
|
||||
`;
|
||||
|
||||
const SplashWrapper = styled.div`
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 9999;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: radial-gradient(circle at top left, rgba(232, 245, 233, 0.9), rgba(200, 230, 201, 0.9)),
|
||||
radial-gradient(circle at bottom right, rgba(255, 255, 224, 0.8), rgba(240, 255, 240, 0.9));
|
||||
animation: ${bgPulse} 6s ease-in-out infinite;
|
||||
`;
|
||||
|
||||
const SplashInner = styled.div`
|
||||
position: relative;
|
||||
text-align: center;
|
||||
padding: 32px 40px 28px;
|
||||
border-radius: 24px;
|
||||
background: rgba(255, 255, 255, 0.28);
|
||||
box-shadow:
|
||||
0 18px 45px rgba(129, 199, 132, 0.35),
|
||||
0 0 40px rgba(129, 199, 132, 0.25);
|
||||
backdrop-filter: blur(12px);
|
||||
`;
|
||||
|
||||
const LogoWrapper = styled.div`
|
||||
position: relative;
|
||||
width: 112px;
|
||||
height: 112px;
|
||||
margin: 0 auto 18px;
|
||||
border-radius: 28px;
|
||||
background: radial-gradient(circle at 30% 20%, #ffffff, #e8f5e9);
|
||||
box-shadow:
|
||||
0 10px 26px rgba(67, 160, 71, 0.35),
|
||||
0 0 25px rgba(129, 199, 132, 0.45);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
animation: ${float} 3s ease-in-out infinite;
|
||||
overflow: hidden;
|
||||
`;
|
||||
|
||||
const LogoImage = styled.img`
|
||||
width: 76px;
|
||||
height: 76px;
|
||||
border-radius: 22px;
|
||||
object-fit: cover;
|
||||
`;
|
||||
|
||||
const Ring = styled.div`
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: 999px;
|
||||
border: 2px solid rgba(129, 199, 132, 0.7);
|
||||
animation: ${ringPulse} 2.6s ease-out infinite;
|
||||
animation-delay: ${({ $delay }) => $delay || '0s'};
|
||||
`;
|
||||
|
||||
const Title = styled.h2`
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
color: #2e7d32;
|
||||
margin-bottom: 6px;
|
||||
letter-spacing: 0.06em;
|
||||
text-shadow: 0 2px 6px rgba(76, 175, 80, 0.35);
|
||||
`;
|
||||
|
||||
const Subtitle = styled.p`
|
||||
font-size: 0.95rem;
|
||||
color: #4caf50;
|
||||
margin-bottom: 16px;
|
||||
`;
|
||||
|
||||
const Dots = styled.div`
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
margin-top: 2px;
|
||||
`;
|
||||
|
||||
const Dot = styled.span`
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: #66bb6a;
|
||||
animation: ${dotPulse} 1.4s ease-in-out infinite;
|
||||
animation-delay: ${({ $delay }) => $delay || '0s'};
|
||||
`;
|
||||
|
||||
const LOGO_SRC = `${process.env.PUBLIC_URL || ''}/assets/icon.png`;
|
||||
|
||||
const LoadingSpinner = ({ text = '加载中...' }) => {
|
||||
return (
|
||||
<SplashWrapper>
|
||||
<SplashInner>
|
||||
<LogoWrapper>
|
||||
<Ring $delay="0s" />
|
||||
<Ring $delay="0.5s" />
|
||||
<Ring $delay="1s" />
|
||||
<LogoImage src={LOGO_SRC} alt="萌芽作品集 Logo" />
|
||||
</LogoWrapper>
|
||||
<Title>✨ 萌芽作品集 ✨</Title>
|
||||
<Subtitle>{text}</Subtitle>
|
||||
<Dots>
|
||||
<Dot $delay="0s" />
|
||||
<Dot $delay="0.15s" />
|
||||
<Dot $delay="0.3s" />
|
||||
</Dots>
|
||||
</SplashInner>
|
||||
</SplashWrapper>
|
||||
);
|
||||
};
|
||||
|
||||
export default LoadingSpinner;
|
||||
161
SproutWorkCollect-Frontend/src/components/Pagination.js
Normal file
161
SproutWorkCollect-Frontend/src/components/Pagination.js
Normal file
@@ -0,0 +1,161 @@
|
||||
import React from 'react';
|
||||
import styled from 'styled-components';
|
||||
|
||||
const PaginationContainer = styled.div`
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
margin: 30px 0;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
`;
|
||||
|
||||
const PaginationButton = styled.button`
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #81c784;
|
||||
background: ${props => props.active ? '#81c784' : 'rgba(255, 255, 255, 0.9)'};
|
||||
color: ${props => props.active ? 'white' : '#2e7d32'};
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
transition: all 0.3s ease;
|
||||
min-width: 40px;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: ${props => props.active ? '#66bb6a' : '#e8f5e8'};
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 2px 8px rgba(129, 199, 132, 0.3);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 6px 10px;
|
||||
font-size: 12px;
|
||||
min-width: 35px;
|
||||
}
|
||||
`;
|
||||
|
||||
const PageInfo = styled.div`
|
||||
color: #666;
|
||||
font-size: 14px;
|
||||
margin: 0 10px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
font-size: 12px;
|
||||
margin: 0 5px;
|
||||
}
|
||||
`;
|
||||
|
||||
const Ellipsis = styled.span`
|
||||
color: #666;
|
||||
padding: 0 5px;
|
||||
font-weight: bold;
|
||||
`;
|
||||
|
||||
const Pagination = ({
|
||||
currentPage,
|
||||
totalPages,
|
||||
totalItems,
|
||||
itemsPerPage,
|
||||
onPageChange
|
||||
}) => {
|
||||
if (totalPages <= 1) return null;
|
||||
|
||||
const getPageNumbers = () => {
|
||||
const pages = [];
|
||||
const maxVisiblePages = 7; // 最多显示7个页码按钮
|
||||
|
||||
if (totalPages <= maxVisiblePages) {
|
||||
// 如果总页数小于等于最大显示页数,显示所有页码
|
||||
for (let i = 1; i <= totalPages; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
} else {
|
||||
// 复杂的分页逻辑
|
||||
if (currentPage <= 4) {
|
||||
// 当前页在前面
|
||||
for (let i = 1; i <= 5; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
pages.push('...');
|
||||
pages.push(totalPages);
|
||||
} else if (currentPage >= totalPages - 3) {
|
||||
// 当前页在后面
|
||||
pages.push(1);
|
||||
pages.push('...');
|
||||
for (let i = totalPages - 4; i <= totalPages; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
} else {
|
||||
// 当前页在中间
|
||||
pages.push(1);
|
||||
pages.push('...');
|
||||
for (let i = currentPage - 1; i <= currentPage + 1; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
pages.push('...');
|
||||
pages.push(totalPages);
|
||||
}
|
||||
}
|
||||
|
||||
return pages;
|
||||
};
|
||||
|
||||
const handlePageClick = (page) => {
|
||||
if (page !== '...' && page !== currentPage && page >= 1 && page <= totalPages) {
|
||||
onPageChange(page);
|
||||
}
|
||||
};
|
||||
|
||||
const startItem = (currentPage - 1) * itemsPerPage + 1;
|
||||
const endItem = Math.min(currentPage * itemsPerPage, totalItems);
|
||||
|
||||
return (
|
||||
<PaginationContainer>
|
||||
{/* 上一页按钮 */}
|
||||
<PaginationButton
|
||||
onClick={() => handlePageClick(currentPage - 1)}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
← 上一页
|
||||
</PaginationButton>
|
||||
|
||||
{/* 页码按钮 */}
|
||||
{getPageNumbers().map((page, index) => (
|
||||
page === '...' ? (
|
||||
<Ellipsis key={`ellipsis-${index}`}>...</Ellipsis>
|
||||
) : (
|
||||
<PaginationButton
|
||||
key={page}
|
||||
active={page === currentPage}
|
||||
onClick={() => handlePageClick(page)}
|
||||
>
|
||||
{page}
|
||||
</PaginationButton>
|
||||
)
|
||||
))}
|
||||
|
||||
{/* 下一页按钮 */}
|
||||
<PaginationButton
|
||||
onClick={() => handlePageClick(currentPage + 1)}
|
||||
disabled={currentPage === totalPages}
|
||||
>
|
||||
下一页 →
|
||||
</PaginationButton>
|
||||
|
||||
{/* 页面信息 */}
|
||||
<PageInfo>
|
||||
第 {startItem}-{endItem} 项,共 {totalItems} 项
|
||||
</PageInfo>
|
||||
</PaginationContainer>
|
||||
);
|
||||
};
|
||||
|
||||
export default Pagination;
|
||||
103
SproutWorkCollect-Frontend/src/components/SearchBar.js
Normal file
103
SproutWorkCollect-Frontend/src/components/SearchBar.js
Normal file
@@ -0,0 +1,103 @@
|
||||
import React, { useState } from 'react';
|
||||
import styled from 'styled-components';
|
||||
import { getGlassOpacity } from '../config/background';
|
||||
|
||||
const glassOpacity = getGlassOpacity();
|
||||
|
||||
const SearchContainer = styled.div`
|
||||
position: relative;
|
||||
flex: 1;
|
||||
max-width: 400px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
max-width: 100%;
|
||||
}
|
||||
`;
|
||||
|
||||
const SearchInput = styled.input`
|
||||
width: 100%;
|
||||
padding: 12px 45px 12px 15px;
|
||||
border: 2px solid #e0e0e0;
|
||||
border-radius: 25px;
|
||||
font-size: 16px;
|
||||
outline: none;
|
||||
transition: all 0.3s ease;
|
||||
background: rgba(255, 255, 255, ${glassOpacity});
|
||||
|
||||
&:focus {
|
||||
border-color: #81c784;
|
||||
box-shadow: 0 0 0 3px rgba(129, 199, 132, 0.1);
|
||||
}
|
||||
|
||||
&::placeholder {
|
||||
color: #999;
|
||||
}
|
||||
`;
|
||||
|
||||
const SearchButton = styled.button`
|
||||
position: absolute;
|
||||
right: 5px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
background: #81c784;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
width: 35px;
|
||||
height: 35px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
transition: background 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
background: #66bb6a;
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: translateY(-50%) scale(0.95);
|
||||
}
|
||||
`;
|
||||
|
||||
const SearchIcon = styled.span`
|
||||
color: white;
|
||||
font-size: 16px;
|
||||
`;
|
||||
|
||||
const SearchBar = ({ onSearch }) => {
|
||||
const [query, setQuery] = useState('');
|
||||
|
||||
const handleSubmit = (e) => {
|
||||
e.preventDefault();
|
||||
onSearch(query.trim());
|
||||
};
|
||||
|
||||
const handleInputChange = (e) => {
|
||||
setQuery(e.target.value);
|
||||
};
|
||||
|
||||
const handleKeyPress = (e) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleSubmit(e);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<SearchContainer>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<SearchInput
|
||||
type="text"
|
||||
placeholder="搜索作品名称、描述或标签..."
|
||||
value={query}
|
||||
onChange={handleInputChange}
|
||||
onKeyPress={handleKeyPress}
|
||||
/>
|
||||
<SearchButton type="submit">
|
||||
<SearchIcon>🔍</SearchIcon>
|
||||
</SearchButton>
|
||||
</form>
|
||||
</SearchContainer>
|
||||
);
|
||||
};
|
||||
|
||||
export default SearchBar;
|
||||
369
SproutWorkCollect-Frontend/src/components/UploadProgressModal.js
Normal file
369
SproutWorkCollect-Frontend/src/components/UploadProgressModal.js
Normal file
@@ -0,0 +1,369 @@
|
||||
import React from 'react';
|
||||
import styled, { keyframes } from 'styled-components';
|
||||
|
||||
const fadeIn = keyframes`
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: scale(0.9);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
`;
|
||||
|
||||
const ModalOverlay = styled.div`
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 9999;
|
||||
backdrop-filter: blur(5px);
|
||||
`;
|
||||
|
||||
const ModalContent = styled.div`
|
||||
background: white;
|
||||
border-radius: 20px;
|
||||
padding: 30px;
|
||||
min-width: 400px;
|
||||
max-width: 90vw;
|
||||
max-height: 80vh;
|
||||
overflow-y: auto;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
|
||||
animation: ${fadeIn} 0.3s ease-out;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
min-width: 300px;
|
||||
padding: 20px;
|
||||
margin: 20px;
|
||||
}
|
||||
`;
|
||||
|
||||
const ModalHeader = styled.div`
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 25px;
|
||||
padding-bottom: 15px;
|
||||
border-bottom: 2px solid #e8f5e8;
|
||||
`;
|
||||
|
||||
const ModalTitle = styled.h2`
|
||||
color: #2e7d32;
|
||||
font-size: 1.5rem;
|
||||
margin: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
`;
|
||||
|
||||
const CloseButton = styled.button`
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 1.5rem;
|
||||
color: #666;
|
||||
cursor: pointer;
|
||||
padding: 5px;
|
||||
border-radius: 50%;
|
||||
transition: all 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
background: #f0f0f0;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
`;
|
||||
|
||||
const UploadList = styled.div`
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
`;
|
||||
|
||||
const UploadItem = styled.div`
|
||||
margin-bottom: 20px;
|
||||
padding: 15px;
|
||||
background: #f8f9fa;
|
||||
border-radius: 12px;
|
||||
border-left: 4px solid #81c784;
|
||||
|
||||
&:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
`;
|
||||
|
||||
const FileInfo = styled.div`
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 10px;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
`;
|
||||
|
||||
const FileName = styled.div`
|
||||
font-weight: 500;
|
||||
color: #333;
|
||||
word-break: break-all;
|
||||
flex: 1;
|
||||
`;
|
||||
|
||||
const FileSize = styled.div`
|
||||
font-size: 0.9rem;
|
||||
color: #666;
|
||||
background: #e0e0e0;
|
||||
padding: 2px 8px;
|
||||
border-radius: 12px;
|
||||
`;
|
||||
|
||||
const ProgressInfo = styled.div`
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 8px;
|
||||
font-size: 0.9rem;
|
||||
`;
|
||||
|
||||
const ProgressText = styled.span`
|
||||
color: #2e7d32;
|
||||
font-weight: 500;
|
||||
`;
|
||||
|
||||
const ProgressPercentage = styled.span`
|
||||
color: #666;
|
||||
font-weight: bold;
|
||||
`;
|
||||
|
||||
const ProgressBarContainer = styled.div`
|
||||
width: 100%;
|
||||
height: 12px;
|
||||
background: #e0e0e0;
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 5px;
|
||||
`;
|
||||
|
||||
const ProgressBar = styled.div`
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, #4caf50, #81c784);
|
||||
transition: width 0.3s ease;
|
||||
width: ${props => props.progress}%;
|
||||
border-radius: 6px;
|
||||
position: relative;
|
||||
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
transparent,
|
||||
rgba(255, 255, 255, 0.3),
|
||||
transparent
|
||||
);
|
||||
animation: shimmer 2s infinite;
|
||||
}
|
||||
|
||||
@keyframes shimmer {
|
||||
0% { transform: translateX(-100%); }
|
||||
100% { transform: translateX(100%); }
|
||||
}
|
||||
`;
|
||||
|
||||
const SpeedInfo = styled.div`
|
||||
font-size: 0.8rem;
|
||||
color: #999;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
`;
|
||||
|
||||
const StatusIcon = styled.span`
|
||||
font-size: 1.2rem;
|
||||
margin-right: 5px;
|
||||
`;
|
||||
|
||||
const RetryInfo = styled.div`
|
||||
font-size: 0.8rem;
|
||||
color: #ff9800;
|
||||
margin-bottom: 5px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
`;
|
||||
|
||||
const ErrorMessage = styled.div`
|
||||
font-size: 0.8rem;
|
||||
color: #f44336;
|
||||
margin-top: 5px;
|
||||
padding: 5px 8px;
|
||||
background: #ffebee;
|
||||
border-radius: 4px;
|
||||
border-left: 3px solid #f44336;
|
||||
`;
|
||||
|
||||
const EmptyState = styled.div`
|
||||
text-align: center;
|
||||
padding: 40px 20px;
|
||||
color: #666;
|
||||
font-size: 1.1rem;
|
||||
`;
|
||||
|
||||
const formatFileSize = (bytes) => {
|
||||
if (bytes === 0) return '0 B';
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
|
||||
};
|
||||
|
||||
const formatSpeed = (bytesPerSecond) => {
|
||||
return formatFileSize(bytesPerSecond) + '/s';
|
||||
};
|
||||
|
||||
const formatETA = (seconds) => {
|
||||
if (!seconds || seconds <= 0) return '计算中...';
|
||||
if (seconds < 60) return `${seconds}秒`;
|
||||
if (seconds < 3600) return `${Math.round(seconds / 60)}分钟`;
|
||||
return `${Math.round(seconds / 3600)}小时`;
|
||||
};
|
||||
|
||||
const calculateETA = (uploaded, total, speed) => {
|
||||
if (speed === 0 || uploaded >= total) return '完成';
|
||||
const remaining = total - uploaded;
|
||||
const seconds = Math.round(remaining / speed);
|
||||
return formatETA(seconds);
|
||||
};
|
||||
|
||||
const UploadProgressModal = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
uploadItems,
|
||||
canClose = true
|
||||
}) => {
|
||||
if (!isOpen) return null;
|
||||
|
||||
const hasActiveUploads = Object.keys(uploadItems).length > 0;
|
||||
|
||||
return (
|
||||
<ModalOverlay onClick={canClose ? onClose : undefined}>
|
||||
<ModalContent onClick={(e) => e.stopPropagation()}>
|
||||
<ModalHeader>
|
||||
<ModalTitle>
|
||||
<StatusIcon>📤</StatusIcon>
|
||||
文件上传进度
|
||||
{hasActiveUploads && <span style={{ color: '#81c784' }}>({Object.keys(uploadItems).length})</span>}
|
||||
</ModalTitle>
|
||||
<CloseButton
|
||||
onClick={onClose}
|
||||
disabled={!canClose}
|
||||
title={canClose ? '关闭' : '上传中,无法关闭'}
|
||||
>
|
||||
×
|
||||
</CloseButton>
|
||||
</ModalHeader>
|
||||
|
||||
<UploadList>
|
||||
{!hasActiveUploads ? (
|
||||
<EmptyState>
|
||||
<StatusIcon>✅</StatusIcon>
|
||||
当前没有文件上传任务
|
||||
</EmptyState>
|
||||
) : (
|
||||
Object.entries(uploadItems).map(([fileKey, uploadInfo]) => {
|
||||
const {
|
||||
fileName,
|
||||
fileSize,
|
||||
progress,
|
||||
uploaded,
|
||||
speed,
|
||||
status,
|
||||
retryCount,
|
||||
eta,
|
||||
error
|
||||
} = uploadInfo;
|
||||
|
||||
const isCompleted = status === 'completed' || progress >= 100;
|
||||
const isFailed = status === 'error';
|
||||
const isRetrying = status === 'retrying';
|
||||
const isUploading = status === 'uploading' || (!status && progress < 100);
|
||||
|
||||
return (
|
||||
<UploadItem key={fileKey}>
|
||||
<FileInfo>
|
||||
<FileName>
|
||||
{isCompleted && <StatusIcon>✅</StatusIcon>}
|
||||
{isFailed && <StatusIcon>❌</StatusIcon>}
|
||||
{isRetrying && <StatusIcon>🔄</StatusIcon>}
|
||||
{isUploading && <StatusIcon>📤</StatusIcon>}
|
||||
{fileName}
|
||||
</FileName>
|
||||
<FileSize>{formatFileSize(fileSize)}</FileSize>
|
||||
</FileInfo>
|
||||
|
||||
{/* 重试信息 */}
|
||||
{(isRetrying || (retryCount > 0 && !isCompleted)) && (
|
||||
<RetryInfo>
|
||||
<span>🔄</span>
|
||||
{isRetrying ? '重试中...' : `已重试 ${retryCount} 次`}
|
||||
</RetryInfo>
|
||||
)}
|
||||
|
||||
<ProgressInfo>
|
||||
<ProgressText>
|
||||
{isFailed ? '上传失败' :
|
||||
isCompleted ? '上传完成' :
|
||||
isRetrying ? '重试中...' : '上传中...'}
|
||||
</ProgressText>
|
||||
<ProgressPercentage>{progress}%</ProgressPercentage>
|
||||
</ProgressInfo>
|
||||
|
||||
<ProgressBarContainer>
|
||||
<ProgressBar progress={progress} />
|
||||
</ProgressBarContainer>
|
||||
|
||||
<SpeedInfo>
|
||||
<span>
|
||||
{formatFileSize(uploaded || 0)} / {formatFileSize(fileSize)}
|
||||
</span>
|
||||
{(isUploading || isRetrying) && (
|
||||
<span>
|
||||
{speed > 0 && (
|
||||
<>
|
||||
{formatSpeed(speed)}
|
||||
{eta > 0 ? ` • 剩余 ${formatETA(eta)}` :
|
||||
speed > 0 ? ` • 剩余 ${calculateETA(uploaded || 0, fileSize, speed)}` : ''}
|
||||
</>
|
||||
)}
|
||||
{speed === 0 && !isRetrying && '计算速度中...'}
|
||||
</span>
|
||||
)}
|
||||
</SpeedInfo>
|
||||
|
||||
{/* 错误信息 */}
|
||||
{(isFailed || error) && (
|
||||
<ErrorMessage>
|
||||
{error || '上传失败,请重试'}
|
||||
</ErrorMessage>
|
||||
)}
|
||||
</UploadItem>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</UploadList>
|
||||
</ModalContent>
|
||||
</ModalOverlay>
|
||||
);
|
||||
};
|
||||
|
||||
export default UploadProgressModal;
|
||||
254
SproutWorkCollect-Frontend/src/components/WorkCard.js
Normal file
254
SproutWorkCollect-Frontend/src/components/WorkCard.js
Normal file
@@ -0,0 +1,254 @@
|
||||
import React from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import styled from 'styled-components';
|
||||
import { getApiOrigin } from '../config/apiBase';
|
||||
import { getGlassOpacity } from '../config/background';
|
||||
|
||||
const glassOpacity = getGlassOpacity();
|
||||
|
||||
const Card = styled.div`
|
||||
background: linear-gradient(145deg, rgba(255, 255, 255, ${0.7 + glassOpacity * 0.3}), rgba(248, 255, 248, ${0.7 + glassOpacity * 0.3}));
|
||||
border-radius: 15px;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
|
||||
overflow: hidden;
|
||||
transition: all 0.3s ease;
|
||||
cursor: pointer;
|
||||
border: 1px solid rgba(129, 199, 132, 0.2);
|
||||
|
||||
&:hover {
|
||||
transform: translateY(-5px);
|
||||
box-shadow: 0 8px 30px rgba(129, 199, 132, 0.2);
|
||||
border-color: rgba(129, 199, 132, 0.4);
|
||||
}
|
||||
`;
|
||||
|
||||
const ImageContainer = styled.div`
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 200px;
|
||||
overflow: hidden;
|
||||
background: #f5f5f5;
|
||||
`;
|
||||
|
||||
const WorkImage = styled.img`
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
transition: transform 0.3s ease;
|
||||
|
||||
${Card}:hover & {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
`;
|
||||
|
||||
const ImagePlaceholder = styled.div`
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: linear-gradient(135deg, #e8f5e8 0%, #f1f8e9 100%);
|
||||
color: #81c784;
|
||||
font-size: 3rem;
|
||||
`;
|
||||
|
||||
const CardContent = styled.div`
|
||||
padding: 20px;
|
||||
`;
|
||||
|
||||
const WorkTitle = styled.h3`
|
||||
font-size: 1.3rem;
|
||||
color: #2e7d32;
|
||||
margin-bottom: 8px;
|
||||
font-weight: 600;
|
||||
`;
|
||||
|
||||
const WorkDescription = styled.p`
|
||||
color: #666;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.5;
|
||||
margin-bottom: 15px;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
`;
|
||||
|
||||
const TagsContainer = styled.div`
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-bottom: 15px;
|
||||
`;
|
||||
|
||||
const Tag = styled.span`
|
||||
background: #e8f5e8;
|
||||
color: #2e7d32;
|
||||
padding: 4px 8px;
|
||||
border-radius: 12px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
`;
|
||||
|
||||
const InfoRow = styled.div`
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 10px;
|
||||
font-size: 0.85rem;
|
||||
color: #666;
|
||||
`;
|
||||
|
||||
const PlatformsContainer = styled.div`
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-bottom: 10px;
|
||||
`;
|
||||
|
||||
const Platform = styled.span`
|
||||
background: #81c784;
|
||||
color: white;
|
||||
padding: 4px 8px;
|
||||
border-radius: 8px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
`;
|
||||
|
||||
const StatsContainer = styled.div`
|
||||
display: flex;
|
||||
justify-content: space-around;
|
||||
align-items: center;
|
||||
padding: 8px 0;
|
||||
border-top: 1px solid #eee;
|
||||
margin-top: 10px;
|
||||
font-size: 0.75rem;
|
||||
color: #666;
|
||||
`;
|
||||
|
||||
const StatItem = styled.div`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
`;
|
||||
|
||||
const StatIcon = styled.span`
|
||||
font-size: 0.9rem;
|
||||
`;
|
||||
|
||||
const StatValue = styled.span`
|
||||
font-weight: 500;
|
||||
color: #2e7d32;
|
||||
`;
|
||||
|
||||
const ViewDetailText = styled.div`
|
||||
text-align: center;
|
||||
color: #81c784;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
padding: 6px 0;
|
||||
border-top: 1px solid #eee;
|
||||
margin-top: 8px;
|
||||
`;
|
||||
|
||||
const WorkCard = ({ work }) => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const formatDate = (dateString) => {
|
||||
if (!dateString) return '';
|
||||
return new Date(dateString).toLocaleDateString('zh-CN');
|
||||
};
|
||||
|
||||
const getCoverImage = () => {
|
||||
if (work.作品封面 && work.图片链接) {
|
||||
const coverIndex = work.作品截图?.indexOf(work.作品封面);
|
||||
if (coverIndex >= 0 && work.图片链接[coverIndex]) {
|
||||
return `${getApiOrigin()}${work.图片链接[coverIndex]}`;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const handleCardClick = () => {
|
||||
navigate(`/work/${work.作品ID}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<Card onClick={handleCardClick}>
|
||||
<ImageContainer>
|
||||
{getCoverImage() ? (
|
||||
<WorkImage
|
||||
src={getCoverImage()}
|
||||
alt={work.作品作品}
|
||||
onError={(e) => {
|
||||
e.target.style.display = 'none';
|
||||
e.target.nextSibling.style.display = 'flex';
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<ImagePlaceholder style={{ display: getCoverImage() ? 'none' : 'flex' }}>
|
||||
🎨
|
||||
</ImagePlaceholder>
|
||||
</ImageContainer>
|
||||
|
||||
<CardContent>
|
||||
<WorkTitle>{work.作品作品}</WorkTitle>
|
||||
<WorkDescription>{work.作品描述}</WorkDescription>
|
||||
|
||||
{work.作品标签 && work.作品标签.length > 0 && (
|
||||
<TagsContainer>
|
||||
{work.作品标签.slice(0, 3).map((tag, index) => (
|
||||
<Tag key={index}>{tag}</Tag>
|
||||
))}
|
||||
{work.作品标签.length > 3 && (
|
||||
<Tag>+{work.作品标签.length - 3}</Tag>
|
||||
)}
|
||||
</TagsContainer>
|
||||
)}
|
||||
|
||||
<InfoRow>
|
||||
<span>👨💻 作者: {work.作者}</span>
|
||||
<span>🏷️ v{work.作品版本号}</span>
|
||||
</InfoRow>
|
||||
|
||||
<InfoRow>
|
||||
<span>📂 分类: {work.作品分类}</span>
|
||||
<span>📅 {formatDate(work.更新时间)}</span>
|
||||
</InfoRow>
|
||||
|
||||
{work.支持平台 && work.支持平台.length > 0 && (
|
||||
<PlatformsContainer>
|
||||
{work.支持平台.map((platform, index) => (
|
||||
<Platform key={index}>{platform}</Platform>
|
||||
))}
|
||||
</PlatformsContainer>
|
||||
)}
|
||||
|
||||
<StatsContainer>
|
||||
<StatItem>
|
||||
<StatIcon>👀</StatIcon>
|
||||
<StatValue>{work.作品浏览量 || 0}</StatValue>
|
||||
</StatItem>
|
||||
<StatItem>
|
||||
<StatIcon>📥</StatIcon>
|
||||
<StatValue>{work.作品下载量 || 0}</StatValue>
|
||||
</StatItem>
|
||||
<StatItem>
|
||||
<StatIcon>💖</StatIcon>
|
||||
<StatValue>{work.作品点赞量 || 0}</StatValue>
|
||||
</StatItem>
|
||||
<StatItem>
|
||||
<StatIcon>🔄</StatIcon>
|
||||
<StatValue>{work.作品更新次数 || 0}</StatValue>
|
||||
</StatItem>
|
||||
</StatsContainer>
|
||||
|
||||
<ViewDetailText>
|
||||
🌟 点击查看详情 →
|
||||
</ViewDetailText>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default WorkCard;
|
||||
872
SproutWorkCollect-Frontend/src/components/WorkDetail.js
Normal file
872
SproutWorkCollect-Frontend/src/components/WorkDetail.js
Normal file
@@ -0,0 +1,872 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useParams, useNavigate } from 'react-router-dom';
|
||||
import styled from 'styled-components';
|
||||
import LoadingSpinner from './LoadingSpinner';
|
||||
import { getWorkDetail, likeWork } from '../services/api';
|
||||
import { getApiOrigin } from '../config/apiBase';
|
||||
|
||||
const DetailContainer = styled.div`
|
||||
max-width: 1000px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
min-height: 100vh;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
const BackButton = styled.button`
|
||||
background: linear-gradient(45deg, #81c784, #66bb6a);
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 10px 20px;
|
||||
border-radius: 25px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
margin-bottom: 20px;
|
||||
transition: all 0.3s ease;
|
||||
box-shadow: 0 4px 15px rgba(129, 199, 132, 0.3);
|
||||
|
||||
&:before {
|
||||
content: '🏠 ';
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background: linear-gradient(45deg, #66bb6a, #4caf50);
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 20px rgba(129, 199, 132, 0.4);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 8px 16px;
|
||||
font-size: 13px;
|
||||
}
|
||||
`;
|
||||
|
||||
const WorkHeader = styled.div`
|
||||
background: white;
|
||||
border-radius: 15px;
|
||||
padding: 30px;
|
||||
margin-bottom: 20px;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 20px;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
`;
|
||||
|
||||
const WorkTitle = styled.h1`
|
||||
font-size: 2.2rem;
|
||||
color: #2e7d32;
|
||||
margin-bottom: 15px;
|
||||
font-weight: 700;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
font-size: 1.8rem;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
`;
|
||||
|
||||
const WorkMeta = styled.div`
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 15px;
|
||||
margin-bottom: 20px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
const MetaItem = styled.div`
|
||||
display: flex;
|
||||
align-items: center;
|
||||
font-size: 0.9rem;
|
||||
color: #666;
|
||||
|
||||
strong {
|
||||
color: #2e7d32;
|
||||
margin-right: 8px;
|
||||
}
|
||||
`;
|
||||
|
||||
const WorkDescription = styled.p`
|
||||
font-size: 1.1rem;
|
||||
line-height: 1.6;
|
||||
color: #444;
|
||||
margin-bottom: 20px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
font-size: 1rem;
|
||||
}
|
||||
`;
|
||||
|
||||
const TagsContainer = styled.div`
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-bottom: 20px;
|
||||
`;
|
||||
|
||||
const Tag = styled.span`
|
||||
background: #e8f5e8;
|
||||
color: #2e7d32;
|
||||
padding: 6px 12px;
|
||||
border-radius: 15px;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
`;
|
||||
|
||||
const PlatformsContainer = styled.div`
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
margin-bottom: 20px;
|
||||
`;
|
||||
|
||||
const Platform = styled.span`
|
||||
background: #81c784;
|
||||
color: white;
|
||||
padding: 8px 16px;
|
||||
border-radius: 10px;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
`;
|
||||
|
||||
const ContentSection = styled.div`
|
||||
background: white;
|
||||
border-radius: 15px;
|
||||
padding: 30px;
|
||||
margin-bottom: 20px;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 20px;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
`;
|
||||
|
||||
const SectionTitle = styled.h2`
|
||||
font-size: 1.5rem;
|
||||
color: #2e7d32;
|
||||
margin-bottom: 20px;
|
||||
font-weight: 600;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
font-size: 1.3rem;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
`;
|
||||
|
||||
const ImageGallery = styled.div`
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
||||
gap: 15px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
const WorkImage = styled.img`
|
||||
width: 100%;
|
||||
height: 200px;
|
||||
object-fit: cover;
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
transition: transform 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.02);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
height: 180px;
|
||||
}
|
||||
`;
|
||||
|
||||
const DownloadSection = styled.div`
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
||||
gap: 20px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 15px;
|
||||
}
|
||||
`;
|
||||
|
||||
const PlatformDownload = styled.div`
|
||||
background: #f8f9fa;
|
||||
border-radius: 10px;
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 15px;
|
||||
}
|
||||
`;
|
||||
|
||||
const PlatformTitle = styled.h3`
|
||||
font-size: 1.2rem;
|
||||
color: #2e7d32;
|
||||
margin-bottom: 15px;
|
||||
font-weight: 600;
|
||||
`;
|
||||
|
||||
const DownloadButton = styled.a`
|
||||
display: inline-block;
|
||||
background: #81c784;
|
||||
color: white;
|
||||
padding: 12px 24px;
|
||||
border-radius: 8px;
|
||||
text-decoration: none;
|
||||
font-size: 1rem;
|
||||
font-weight: 500;
|
||||
margin: 5px;
|
||||
transition: background 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
background: #66bb6a;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 10px 20px;
|
||||
font-size: 0.9rem;
|
||||
display: block;
|
||||
margin: 8px 0;
|
||||
}
|
||||
`;
|
||||
|
||||
const VideoContainer = styled.div`
|
||||
margin-bottom: 15px;
|
||||
`;
|
||||
|
||||
const VideoPlayer = styled.video`
|
||||
width: 100%;
|
||||
max-height: 400px;
|
||||
border-radius: 10px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
max-height: 250px;
|
||||
}
|
||||
`;
|
||||
|
||||
const StatsSection = styled.div`
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
|
||||
gap: 15px;
|
||||
margin: 20px 0;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: space-between;
|
||||
flex-wrap: nowrap;
|
||||
overflow-x: auto;
|
||||
gap: 10px;
|
||||
padding-bottom: 5px;
|
||||
|
||||
/* 添加滚动条样式 */
|
||||
&::-webkit-scrollbar {
|
||||
height: 4px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: #f1f1f1;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: #81c784;
|
||||
border-radius: 10px;
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const StatCard = styled.div`
|
||||
background: #f8f9fa;
|
||||
border-radius: 12px;
|
||||
padding: 15px;
|
||||
text-align: center;
|
||||
border: 2px solid transparent;
|
||||
transition: all 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
border-color: #81c784;
|
||||
background: #f0f8f0;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 12px;
|
||||
min-width: 80px;
|
||||
flex: 1 0 auto;
|
||||
margin-right: 2px;
|
||||
}
|
||||
`;
|
||||
|
||||
const StatIcon = styled.div`
|
||||
font-size: 1.5rem;
|
||||
margin-bottom: 8px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
font-size: 1.2rem;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
`;
|
||||
|
||||
const StatValue = styled.div`
|
||||
font-size: 1.4rem;
|
||||
font-weight: 700;
|
||||
color: #2e7d32;
|
||||
margin-bottom: 4px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
`;
|
||||
|
||||
const StatLabel = styled.div`
|
||||
font-size: 0.8rem;
|
||||
color: #666;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
`;
|
||||
|
||||
const LikeButton = styled.button`
|
||||
background: linear-gradient(
|
||||
45deg,
|
||||
rgba(255, 107, 107, 0.8),
|
||||
rgba(255, 165, 0, 0.8),
|
||||
rgba(255, 255, 0, 0.7),
|
||||
rgba(50, 205, 50, 0.8),
|
||||
rgba(0, 191, 255, 0.8),
|
||||
rgba(65, 105, 225, 0.8),
|
||||
rgba(147, 112, 219, 0.8)
|
||||
);
|
||||
background-size: 300% 300%;
|
||||
animation: buttonRainbow 12s ease infinite;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
padding: 15px;
|
||||
font-size: 1rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
|
||||
|
||||
&:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
background: #ccc;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
animation: none;
|
||||
}
|
||||
|
||||
@keyframes buttonRainbow {
|
||||
0%, 100% {
|
||||
background-position: 0% 50%;
|
||||
}
|
||||
50% {
|
||||
background-position: 100% 50%;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 12px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
`;
|
||||
|
||||
const ErrorMessage = styled.div`
|
||||
text-align: center;
|
||||
padding: 40px 20px;
|
||||
color: #e53e3e;
|
||||
font-size: 18px;
|
||||
background: white;
|
||||
border-radius: 15px;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
|
||||
`;
|
||||
|
||||
// 模态框样式
|
||||
const ModalOverlay = styled.div`
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.8);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
padding: 20px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
const ModalContent = styled.div`
|
||||
position: relative;
|
||||
max-width: 90vw;
|
||||
max-height: 90vh;
|
||||
background: white;
|
||||
border-radius: 15px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
|
||||
`;
|
||||
|
||||
const ModalImage = styled.img`
|
||||
width: 100%;
|
||||
height: auto;
|
||||
max-height: 85vh;
|
||||
object-fit: contain;
|
||||
display: block;
|
||||
`;
|
||||
|
||||
const ModalVideo = styled.video`
|
||||
width: 100%;
|
||||
height: auto;
|
||||
max-height: 85vh;
|
||||
display: block;
|
||||
`;
|
||||
|
||||
const CloseButton = styled.button`
|
||||
position: absolute;
|
||||
top: 15px;
|
||||
right: 15px;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
font-size: 20px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1001;
|
||||
transition: background 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
background: rgba(0, 0, 0, 0.9);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
width: 35px;
|
||||
height: 35px;
|
||||
font-size: 18px;
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
const ModalTitle = styled.div`
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
|
||||
color: white;
|
||||
padding: 20px;
|
||||
font-size: 16px;
|
||||
z-index: 1001;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 15px;
|
||||
font-size: 14px;
|
||||
}
|
||||
`;
|
||||
|
||||
const WorkDetail = () => {
|
||||
const { workId } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const [work, setWork] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
const [liking, setLiking] = useState(false);
|
||||
const [likeMessage, setLikeMessage] = useState('');
|
||||
|
||||
// 模态框状态
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [modalType, setModalType] = useState(''); // 'image' 或 'video'
|
||||
const [modalSrc, setModalSrc] = useState('');
|
||||
const [modalTitle, setModalTitle] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
loadWorkDetail();
|
||||
}, [workId]);
|
||||
|
||||
const loadWorkDetail = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const response = await getWorkDetail(workId);
|
||||
if (response.success) {
|
||||
setWork(response.data);
|
||||
} else {
|
||||
setError(response.message || '作品不存在');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载作品详情失败:', error);
|
||||
setError('加载失败,请稍后重试');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const formatDate = (dateString) => {
|
||||
if (!dateString) return '';
|
||||
return new Date(dateString).toLocaleDateString('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric'
|
||||
});
|
||||
};
|
||||
|
||||
// 打开图片模态框
|
||||
const handleImageClick = (imageUrl, index) => {
|
||||
setModalType('image');
|
||||
setModalSrc(`${getApiOrigin()}${imageUrl}`);
|
||||
setModalTitle(`${work.作品作品} - 截图 ${index + 1}`);
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
// 打开视频模态框
|
||||
const handleVideoClick = (videoUrl, index) => {
|
||||
setModalType('video');
|
||||
setModalSrc(`${getApiOrigin()}${videoUrl}`);
|
||||
setModalTitle(`${work.作品作品} - 视频 ${index + 1}`);
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
// 关闭模态框
|
||||
const closeModal = () => {
|
||||
setModalOpen(false);
|
||||
setModalType('');
|
||||
setModalSrc('');
|
||||
setModalTitle('');
|
||||
};
|
||||
|
||||
// 处理模态框背景点击
|
||||
const handleModalOverlayClick = (e) => {
|
||||
if (e.target === e.currentTarget) {
|
||||
closeModal();
|
||||
}
|
||||
};
|
||||
|
||||
// 处理键盘事件
|
||||
useEffect(() => {
|
||||
const handleKeyPress = (e) => {
|
||||
if (e.key === 'Escape' && modalOpen) {
|
||||
closeModal();
|
||||
}
|
||||
};
|
||||
|
||||
if (modalOpen) {
|
||||
document.addEventListener('keydown', handleKeyPress);
|
||||
document.body.style.overflow = 'hidden'; // 防止背景滚动
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleKeyPress);
|
||||
document.body.style.overflow = 'unset';
|
||||
};
|
||||
}, [modalOpen]);
|
||||
|
||||
const handleLike = async () => {
|
||||
if (liking) return;
|
||||
|
||||
setLiking(true);
|
||||
setLikeMessage('');
|
||||
|
||||
try {
|
||||
const response = await likeWork(workId);
|
||||
if (response.success) {
|
||||
setLikeMessage('点赞成功!');
|
||||
// 更新本地作品数据
|
||||
setWork(prev => ({
|
||||
...prev,
|
||||
作品点赞量: response.likes
|
||||
}));
|
||||
} else {
|
||||
setLikeMessage(response.message || '点赞失败');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('点赞失败:', error);
|
||||
if (error.response?.status === 429) {
|
||||
setLikeMessage('操作太频繁,请稍后再试');
|
||||
} else {
|
||||
setLikeMessage('点赞失败,请稍后重试');
|
||||
}
|
||||
} finally {
|
||||
setLiking(false);
|
||||
// 3秒后清除消息
|
||||
setTimeout(() => setLikeMessage(''), 3000);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return <LoadingSpinner text="加载作品详情中..." />;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<DetailContainer>
|
||||
<BackButton onClick={() => navigate('/')}>
|
||||
返回首页
|
||||
</BackButton>
|
||||
<ErrorMessage>{error}</ErrorMessage>
|
||||
</DetailContainer>
|
||||
);
|
||||
}
|
||||
|
||||
if (!work) {
|
||||
return (
|
||||
<DetailContainer>
|
||||
<BackButton onClick={() => navigate('/')}>
|
||||
返回首页
|
||||
</BackButton>
|
||||
<ErrorMessage>作品不存在</ErrorMessage>
|
||||
</DetailContainer>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DetailContainer>
|
||||
<BackButton onClick={() => navigate('/')}>
|
||||
← 返回首页
|
||||
</BackButton>
|
||||
|
||||
<WorkHeader>
|
||||
<WorkTitle>{work.作品作品}</WorkTitle>
|
||||
|
||||
<WorkMeta>
|
||||
<MetaItem>
|
||||
<strong>👨💻 作者:</strong> {work.作者}
|
||||
</MetaItem>
|
||||
<MetaItem>
|
||||
<strong>🏷️ 版本:</strong> {work.作品版本号}
|
||||
</MetaItem>
|
||||
<MetaItem>
|
||||
<strong>📂 分类:</strong> {work.作品分类}
|
||||
</MetaItem>
|
||||
<MetaItem>
|
||||
<strong>📅 上传时间:</strong> {formatDate(work.上传时间)}
|
||||
</MetaItem>
|
||||
<MetaItem>
|
||||
<strong>🔄 更新时间:</strong> {formatDate(work.更新时间)}
|
||||
</MetaItem>
|
||||
</WorkMeta>
|
||||
|
||||
<WorkDescription>{work.作品描述}</WorkDescription>
|
||||
|
||||
{work.作品标签 && work.作品标签.length > 0 && (
|
||||
<TagsContainer>
|
||||
{work.作品标签.map((tag, index) => (
|
||||
<Tag key={index}>{tag}</Tag>
|
||||
))}
|
||||
</TagsContainer>
|
||||
)}
|
||||
|
||||
{work.支持平台 && work.支持平台.length > 0 && (
|
||||
<PlatformsContainer>
|
||||
{work.支持平台.map((platform, index) => (
|
||||
<Platform key={index}>{platform}</Platform>
|
||||
))}
|
||||
</PlatformsContainer>
|
||||
)}
|
||||
|
||||
{/* 统计数据 */}
|
||||
<StatsSection>
|
||||
<StatCard>
|
||||
<StatIcon>👁️🗨️</StatIcon>
|
||||
<StatValue>{work.作品浏览量 || 0}</StatValue>
|
||||
<StatLabel>浏览量</StatLabel>
|
||||
</StatCard>
|
||||
<StatCard>
|
||||
<StatIcon>📥</StatIcon>
|
||||
<StatValue>{work.作品下载量 || 0}</StatValue>
|
||||
<StatLabel>下载量</StatLabel>
|
||||
</StatCard>
|
||||
<StatCard>
|
||||
<StatIcon>💖</StatIcon>
|
||||
<StatValue>{work.作品点赞量 || 0}</StatValue>
|
||||
<StatLabel>点赞量</StatLabel>
|
||||
</StatCard>
|
||||
<StatCard>
|
||||
<StatIcon>🔄</StatIcon>
|
||||
<StatValue>{work.作品更新次数 || 0}</StatValue>
|
||||
<StatLabel>更新次数</StatLabel>
|
||||
</StatCard>
|
||||
</StatsSection>
|
||||
|
||||
{/* 点赞按钮 */}
|
||||
<LikeButton
|
||||
onClick={handleLike}
|
||||
disabled={liking}
|
||||
style={{
|
||||
width: '100%',
|
||||
marginTop: '15px',
|
||||
position: 'relative'
|
||||
}}
|
||||
>
|
||||
<span>💖</span>
|
||||
{liking ? '💫 点赞中...' : '点赞作品'}
|
||||
{likeMessage && (
|
||||
<div style={{
|
||||
position: 'absolute',
|
||||
top: '-35px',
|
||||
left: '50%',
|
||||
transform: 'translateX(-50%)',
|
||||
background: likeMessage.includes('成功') ? '#4caf50' : '#f44336',
|
||||
color: 'white',
|
||||
padding: '4px 8px',
|
||||
borderRadius: '4px',
|
||||
fontSize: '0.8rem',
|
||||
whiteSpace: 'nowrap'
|
||||
}}>
|
||||
{likeMessage}
|
||||
</div>
|
||||
)}
|
||||
</LikeButton>
|
||||
</WorkHeader>
|
||||
|
||||
{work.视频链接 && work.视频链接.length > 0 && (
|
||||
<ContentSection>
|
||||
<SectionTitle>🎬 作品视频</SectionTitle>
|
||||
{work.视频链接.map((videoUrl, index) => (
|
||||
<VideoContainer key={index}>
|
||||
<VideoPlayer
|
||||
controls
|
||||
onClick={() => handleVideoClick(videoUrl, index)}
|
||||
style={{ cursor: 'pointer' }}
|
||||
>
|
||||
<source src={`${getApiOrigin()}${videoUrl}`} type="video/mp4" />
|
||||
您的浏览器不支持视频播放
|
||||
</VideoPlayer>
|
||||
</VideoContainer>
|
||||
))}
|
||||
</ContentSection>
|
||||
)}
|
||||
|
||||
{(work.下载资源 && Object.keys(work.下载资源).length > 0) && (
|
||||
<ContentSection>
|
||||
<SectionTitle>📦 下载作品</SectionTitle>
|
||||
<DownloadSection>
|
||||
{Object.entries(work.下载资源).map(([platform, resources]) => (
|
||||
<PlatformDownload key={platform}>
|
||||
<PlatformTitle>{platform}</PlatformTitle>
|
||||
{resources.map((res, index) => {
|
||||
const isExternal = res.类型 === 'external';
|
||||
const href = isExternal ? res.链接 : `${getApiOrigin()}${res.链接}`;
|
||||
return (
|
||||
<DownloadButton
|
||||
key={index}
|
||||
href={href}
|
||||
target={isExternal ? '_blank' : undefined}
|
||||
rel={isExternal ? 'noreferrer' : undefined}
|
||||
download={isExternal ? undefined : true}
|
||||
>
|
||||
📥 {res.别名 || `下载 ${platform} 版本`}
|
||||
</DownloadButton>
|
||||
);
|
||||
})}
|
||||
</PlatformDownload>
|
||||
))}
|
||||
</DownloadSection>
|
||||
</ContentSection>
|
||||
)}
|
||||
|
||||
{/* 兼容旧后端:仅返回“下载链接”时依旧可用 */}
|
||||
{(!work.下载资源 || Object.keys(work.下载资源).length === 0) &&
|
||||
work.下载链接 &&
|
||||
Object.keys(work.下载链接).length > 0 && (
|
||||
<ContentSection>
|
||||
<SectionTitle>📦 下载作品</SectionTitle>
|
||||
<DownloadSection>
|
||||
{Object.entries(work.下载链接).map(([platform, links]) => (
|
||||
<PlatformDownload key={platform}>
|
||||
<PlatformTitle>{platform}</PlatformTitle>
|
||||
{links.map((link, index) => (
|
||||
<DownloadButton key={index} href={`${getApiOrigin()}${link}`} download>
|
||||
📥 下载 {platform} 版本
|
||||
</DownloadButton>
|
||||
))}
|
||||
</PlatformDownload>
|
||||
))}
|
||||
</DownloadSection>
|
||||
</ContentSection>
|
||||
)}
|
||||
|
||||
{work.图片链接 && work.图片链接.length > 0 && (
|
||||
<ContentSection>
|
||||
<SectionTitle>🖼️ 作品截图</SectionTitle>
|
||||
<ImageGallery>
|
||||
{work.图片链接.map((imageUrl, index) => (
|
||||
<WorkImage
|
||||
key={index}
|
||||
src={`${getApiOrigin()}${imageUrl}`}
|
||||
alt={`${work.作品作品} 截图 ${index + 1}`}
|
||||
onClick={() => handleImageClick(imageUrl, index)}
|
||||
onError={(e) => {
|
||||
e.target.style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</ImageGallery>
|
||||
</ContentSection>
|
||||
)}
|
||||
|
||||
{/* 模态框 */}
|
||||
{modalOpen && (
|
||||
<ModalOverlay onClick={handleModalOverlayClick}>
|
||||
<ModalContent>
|
||||
<CloseButton onClick={closeModal}>×</CloseButton>
|
||||
{modalType === 'image' ? (
|
||||
<ModalImage
|
||||
src={modalSrc}
|
||||
alt={modalTitle}
|
||||
onError={(e) => {
|
||||
console.error('图片加载失败:', modalSrc);
|
||||
}}
|
||||
/>
|
||||
) : modalType === 'video' ? (
|
||||
<ModalVideo
|
||||
src={modalSrc}
|
||||
controls
|
||||
autoPlay
|
||||
onError={(e) => {
|
||||
console.error('视频加载失败:', modalSrc);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<ModalTitle>{modalTitle}</ModalTitle>
|
||||
</ModalContent>
|
||||
</ModalOverlay>
|
||||
)}
|
||||
</DetailContainer>
|
||||
);
|
||||
};
|
||||
|
||||
export default WorkDetail;
|
||||
1049
SproutWorkCollect-Frontend/src/components/WorkEditor.js
Normal file
1049
SproutWorkCollect-Frontend/src/components/WorkEditor.js
Normal file
File diff suppressed because it is too large
Load Diff
38
SproutWorkCollect-Frontend/src/config/apiBase.js
Normal file
38
SproutWorkCollect-Frontend/src/config/apiBase.js
Normal file
@@ -0,0 +1,38 @@
|
||||
const DEFAULT_PROD_API_ORIGIN = 'https://work.api.shumengya.top';
|
||||
|
||||
const stripTrailingSlashes = (value) => value.replace(/\/+$/, '');
|
||||
|
||||
const stripApiSuffix = (value) => value.replace(/\/api\/?$/, '');
|
||||
|
||||
const hasHttpProtocol = (value) => /^https?:\/\//i.test(value);
|
||||
|
||||
export const getApiBaseUrl = () => {
|
||||
const envUrl = process.env.REACT_APP_API_URL;
|
||||
if (envUrl) {
|
||||
const normalized = stripTrailingSlashes(envUrl);
|
||||
|
||||
// 避免生产环境错误使用相对路径(例如 /api),导致请求打到前端自身域名
|
||||
if (normalized.startsWith('/')) {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn(
|
||||
`[SproutWorkCollect] REACT_APP_API_URL=${normalized} 是相对路径,已忽略并回退到默认后端:${DEFAULT_PROD_API_ORIGIN}/api`,
|
||||
);
|
||||
return `${DEFAULT_PROD_API_ORIGIN}/api`;
|
||||
}
|
||||
|
||||
return normalized.endsWith('/api') ? normalized : `${normalized}/api`;
|
||||
}
|
||||
|
||||
const absolute = hasHttpProtocol(normalized) ? normalized : `https://${normalized}`;
|
||||
return absolute.endsWith('/api') ? absolute : `${absolute}/api`;
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
return `${DEFAULT_PROD_API_ORIGIN}/api`;
|
||||
}
|
||||
|
||||
return 'http://localhost:5000/api';
|
||||
};
|
||||
|
||||
export const getApiOrigin = () => stripApiSuffix(getApiBaseUrl());
|
||||
59
SproutWorkCollect-Frontend/src/config/background.js
Normal file
59
SproutWorkCollect-Frontend/src/config/background.js
Normal file
@@ -0,0 +1,59 @@
|
||||
// 网站背景图配置(前端可配,不需要改代码)。
|
||||
// - 手机端用 mobileImages,电脑端用 desktopImages(按视口宽度 768px 区分)
|
||||
// - blur.enabled 控制是否启用高斯模糊遮罩
|
||||
// - blur.amount 是模糊强度,建议 4px~10px
|
||||
// - blur.overlayOpacity 是白色蒙层透明度,0~1,建议 0.2~0.5
|
||||
|
||||
const mobileImages = [
|
||||
'https://image.smyhub.com/file/手机壁纸/女生/1772108123232_VJ86r.jpg',
|
||||
'https://image.smyhub.com/file/手机壁纸/女生/1772108022800_f945774e0a45f7a4afdc3da2b112025f.png',
|
||||
'https://image.smyhub.com/file/手机壁纸/女生/1772108024006_3f9030ba77e355869115bc90fe019d53.png',
|
||||
'https://image.smyhub.com/file/手机壁纸/女生/1772108030393_159bbf61f88b38475ee9144a2e8e4956.png',
|
||||
'https://image.smyhub.com/file/手机壁纸/女生/1772108021977_8020902a0c8788538eee1cd06e784c6a.png',
|
||||
'https://image.smyhub.com/file/手机壁纸/女生/1772108021881_44374ab6c1daa54e0204bca48ac382f2.png',
|
||||
];
|
||||
|
||||
const desktopImages = [
|
||||
'https://image.smyhub.com/file/电脑壁纸/女生/cuSpSkq4.webp',
|
||||
'https://image.smyhub.com/file/电脑壁纸/女生/5CrdoShv.webp',
|
||||
'https://image.smyhub.com/file/电脑壁纸/女生/xTsVkCli.webp',
|
||||
'https://image.smyhub.com/file/电脑壁纸/女生/ItOJOHST.webp',
|
||||
'https://image.smyhub.com/file/电脑壁纸/女生/cUDkKiOf.webp',
|
||||
'https://image.smyhub.com/file/电脑壁纸/女生/c2HxMuGK.webp',
|
||||
'https://image.smyhub.com/file/电脑壁纸/女生/L0nQHehz.webp',
|
||||
'https://image.smyhub.com/file/电脑壁纸/女生/hj64Cqxn.webp',
|
||||
];
|
||||
|
||||
// 内容区块(搜索框、分类块、内容卡片、顶栏和底栏)的半透明背景透明度,0=全透明 1=不透明,可自行修改
|
||||
window.SITE_GLASS_OPACITY = 0.3;
|
||||
|
||||
export const getGlassOpacity = () => {
|
||||
if (typeof window !== 'undefined' && typeof window.SITE_GLASS_OPACITY === 'number') {
|
||||
return window.SITE_GLASS_OPACITY;
|
||||
}
|
||||
return 0.3;
|
||||
};
|
||||
|
||||
export const BACKGROUND_CONFIG = {
|
||||
mobileImages,
|
||||
desktopImages,
|
||||
blur: {
|
||||
enabled: true,
|
||||
amount: '6px',
|
||||
overlayOpacity: 0.35,
|
||||
},
|
||||
};
|
||||
|
||||
export const pickBackgroundImage = (isMobile) => {
|
||||
const list = isMobile ? BACKGROUND_CONFIG.mobileImages : BACKGROUND_CONFIG.desktopImages;
|
||||
if (!Array.isArray(list) || list.length === 0) return null;
|
||||
const index = Math.floor(Math.random() * list.length);
|
||||
return list[index];
|
||||
};
|
||||
|
||||
// 同时挂到 window 上,方便在控制台调试或以后用纯 script 标签引入时访问。
|
||||
if (typeof window !== 'undefined') {
|
||||
window.SITE_MOBILE_BACKGROUND_IMAGES = mobileImages;
|
||||
window.SITE_DESKTOP_BACKGROUND_IMAGES = desktopImages;
|
||||
window.SITE_BACKGROUND_BLUR = BACKGROUND_CONFIG.blur;
|
||||
}
|
||||
14
SproutWorkCollect-Frontend/src/index.js
Normal file
14
SproutWorkCollect-Frontend/src/index.js
Normal file
@@ -0,0 +1,14 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import App from './App';
|
||||
import { registerServiceWorker } from './serviceWorkerRegistration';
|
||||
|
||||
const root = ReactDOM.createRoot(document.getElementById('root'));
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
);
|
||||
|
||||
// 注册自定义 Service Worker,使应用具备 PWA 能力
|
||||
registerServiceWorker();
|
||||
60
SproutWorkCollect-Frontend/src/service-worker.js
Normal file
60
SproutWorkCollect-Frontend/src/service-worker.js
Normal file
@@ -0,0 +1,60 @@
|
||||
/* eslint-disable no-restricted-globals */
|
||||
/* 简易 PWA Service Worker(兼容 CRA 的 Workbox 注入机制):
|
||||
* - 使用 Workbox 预缓存构建产物(precacheAndRoute(self.__WB_MANIFEST))
|
||||
* - 额外对首页等关键路径做手动预缓存
|
||||
* - 对同源的 GET 请求走 cache-first 策略
|
||||
*/
|
||||
|
||||
import { precacheAndRoute } from 'workbox-precaching';
|
||||
|
||||
// 由 react-scripts 在构建时注入实际的资源清单
|
||||
precacheAndRoute(self.__WB_MANIFEST || []);
|
||||
|
||||
const CACHE_NAME = 'sproutworkcollect-cache-v1';
|
||||
const PRECACHE_URLS = ['/', '/index.html'];
|
||||
|
||||
self.addEventListener('install', (event) => {
|
||||
event.waitUntil(
|
||||
caches.open(CACHE_NAME).then((cache) => cache.addAll(PRECACHE_URLS)),
|
||||
);
|
||||
self.skipWaiting();
|
||||
});
|
||||
|
||||
self.addEventListener('activate', (event) => {
|
||||
event.waitUntil(
|
||||
caches.keys().then((keys) =>
|
||||
Promise.all(
|
||||
keys.map((key) => {
|
||||
if (key !== CACHE_NAME) {
|
||||
return caches.delete(key);
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
self.clients.claim();
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', (event) => {
|
||||
const { request } = event;
|
||||
|
||||
// 只对 GET 请求、同源请求做缓存处理,其它直接放行
|
||||
if (request.method !== 'GET' || new URL(request.url).origin !== self.location.origin) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.respondWith(
|
||||
caches.match(request).then((cached) => {
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
return fetch(request).then((response) => {
|
||||
const responseClone = response.clone();
|
||||
caches.open(CACHE_NAME).then((cache) => cache.put(request, responseClone));
|
||||
return response;
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
16
SproutWorkCollect-Frontend/src/serviceWorkerRegistration.js
Normal file
16
SproutWorkCollect-Frontend/src/serviceWorkerRegistration.js
Normal file
@@ -0,0 +1,16 @@
|
||||
// 在浏览器加载完成后注册自定义 Service Worker,使应用成为 PWA。
|
||||
// 生产环境和开发环境都可以注册,方便本地调试。
|
||||
|
||||
export function registerServiceWorker() {
|
||||
if ('serviceWorker' in navigator) {
|
||||
window.addEventListener('load', () => {
|
||||
navigator.serviceWorker
|
||||
.register('/service-worker.js')
|
||||
.catch((error) => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('[PWA] Service Worker 注册失败:', error);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
240
SproutWorkCollect-Frontend/src/services/adminApi.js
Normal file
240
SproutWorkCollect-Frontend/src/services/adminApi.js
Normal file
@@ -0,0 +1,240 @@
|
||||
import axios from 'axios';
|
||||
import { getApiBaseUrl } from '../config/apiBase';
|
||||
|
||||
const API_BASE_URL = getApiBaseUrl();
|
||||
|
||||
const adminApi = axios.create({
|
||||
baseURL: API_BASE_URL,
|
||||
timeout: 30000,
|
||||
});
|
||||
|
||||
adminApi.interceptors.response.use(
|
||||
(response) => {
|
||||
const contentType = response?.headers?.['content-type'] || '';
|
||||
if (typeof response.data === 'string') {
|
||||
const trimmed = response.data.trim().toLowerCase();
|
||||
const looksLikeHtml =
|
||||
contentType.includes('text/html') ||
|
||||
trimmed.startsWith('<!doctype') ||
|
||||
trimmed.startsWith('<html');
|
||||
|
||||
if (looksLikeHtml) {
|
||||
throw new Error(
|
||||
`API 返回了 HTML(疑似请求打到了前端自身域名/SPA重写),请检查 Cloudflare Pages 环境变量 REACT_APP_API_URL。当前 baseURL: ${API_BASE_URL}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return response;
|
||||
},
|
||||
(error) => Promise.reject(error)
|
||||
);
|
||||
|
||||
// 管理员token
|
||||
let adminToken = null;
|
||||
|
||||
export const setAdminToken = (token) => {
|
||||
adminToken = token;
|
||||
adminApi.defaults.headers.common['Authorization'] = token;
|
||||
};
|
||||
|
||||
export const getAdminToken = () => adminToken;
|
||||
|
||||
// 管理员获取所有作品
|
||||
export const adminGetWorks = async () => {
|
||||
const response = await adminApi.get('/admin/works', {
|
||||
params: { token: adminToken }
|
||||
});
|
||||
return response.data;
|
||||
};
|
||||
|
||||
// 管理员创建作品
|
||||
export const adminCreateWork = async (workData) => {
|
||||
const response = await adminApi.post('/admin/works', workData, {
|
||||
params: { token: adminToken }
|
||||
});
|
||||
return response.data;
|
||||
};
|
||||
|
||||
// 管理员更新作品
|
||||
export const adminUpdateWork = async (workId, workData) => {
|
||||
const response = await adminApi.put(`/admin/works/${workId}`, workData, {
|
||||
params: { token: adminToken }
|
||||
});
|
||||
return response.data;
|
||||
};
|
||||
|
||||
// 管理员删除作品
|
||||
export const adminDeleteWork = async (workId) => {
|
||||
const response = await adminApi.delete(`/admin/works/${workId}`, {
|
||||
params: { token: adminToken }
|
||||
});
|
||||
return response.data;
|
||||
};
|
||||
|
||||
// 管理员上传文件 (支持大文件和详细进度回调,增强错误处理和重试机制)
|
||||
export const adminUploadFile = async (workId, fileType, file, platform = null, onProgress = null, maxRetries = 3) => {
|
||||
// 检查文件大小 (前端预检查)
|
||||
const maxSize = 5000 * 1024 * 1024; // 5000MB
|
||||
if (file.size > maxSize) {
|
||||
throw new Error(`文件太大,最大支持 ${maxSize / (1024 * 1024)}MB,当前文件大小:${(file.size / (1024 * 1024)).toFixed(1)}MB`);
|
||||
}
|
||||
|
||||
console.log(`开始上传文件: ${file.name}, 大小: ${(file.size / (1024 * 1024)).toFixed(1)}MB, 作品ID: ${workId}, 类型: ${fileType}, 平台: ${platform}`);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
if (platform) {
|
||||
formData.append('platform', platform);
|
||||
}
|
||||
|
||||
let startTime = Date.now();
|
||||
let lastLoaded = 0;
|
||||
let lastTime = startTime;
|
||||
let retryCount = 0;
|
||||
|
||||
// 根据文件大小动态调整超时时间
|
||||
const getTimeoutForFileSize = (fileSize) => {
|
||||
const fileSizeMB = fileSize / (1024 * 1024);
|
||||
if (fileSizeMB < 10) return 5 * 60 * 1000; // 小于10MB: 5分钟
|
||||
if (fileSizeMB < 100) return 15 * 60 * 1000; // 小于100MB: 15分钟
|
||||
if (fileSizeMB < 500) return 30 * 60 * 1000; // 小于500MB: 30分钟
|
||||
return 60 * 60 * 1000; // 大于500MB: 60分钟
|
||||
};
|
||||
|
||||
const uploadAttempt = async () => {
|
||||
try {
|
||||
console.log(`上传尝试 ${retryCount + 1}/${maxRetries + 1}`);
|
||||
|
||||
const timeout = getTimeoutForFileSize(file.size);
|
||||
console.log(`设置超时时间: ${timeout / 1000}秒`);
|
||||
|
||||
const response = await adminApi.post(`/admin/upload/${workId}/${fileType}`, formData, {
|
||||
params: { token: adminToken },
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
},
|
||||
timeout: timeout,
|
||||
onUploadProgress: (progressEvent) => {
|
||||
if (onProgress && progressEvent.total) {
|
||||
const currentTime = Date.now();
|
||||
const currentLoaded = progressEvent.loaded;
|
||||
|
||||
// 计算上传速度
|
||||
const timeDiff = (currentTime - lastTime) / 1000;
|
||||
const loadedDiff = currentLoaded - lastLoaded;
|
||||
const speed = timeDiff > 0 ? loadedDiff / timeDiff : 0;
|
||||
|
||||
const percentCompleted = Math.round((currentLoaded * 100) / progressEvent.total);
|
||||
|
||||
// 计算剩余时间
|
||||
const remainingBytes = progressEvent.total - currentLoaded;
|
||||
const eta = speed > 0 ? Math.round(remainingBytes / speed) : 0;
|
||||
|
||||
onProgress({
|
||||
progress: percentCompleted,
|
||||
uploaded: currentLoaded,
|
||||
total: progressEvent.total,
|
||||
speed: speed,
|
||||
fileName: file.name,
|
||||
fileSize: file.size,
|
||||
eta: eta,
|
||||
retryCount: retryCount
|
||||
});
|
||||
|
||||
lastLoaded = currentLoaded;
|
||||
lastTime = currentTime;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
console.log(`文件上传成功: ${file.name}`);
|
||||
return response.data;
|
||||
|
||||
} catch (error) {
|
||||
console.error(`上传尝试 ${retryCount + 1} 失败:`, error);
|
||||
|
||||
// 分析错误类型
|
||||
const isRetryableError = (error) => {
|
||||
if (!error.response) {
|
||||
// 网络错误或超时,可重试
|
||||
return true;
|
||||
}
|
||||
|
||||
const status = error.response.status;
|
||||
// 5xx服务器错误可重试,4xx客户端错误通常不可重试
|
||||
if (status >= 500) return true;
|
||||
if (status === 408 || status === 429) return true; // 超时或限流可重试
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
const errorMessage = error.response?.data?.message || error.message || '未知错误';
|
||||
|
||||
// 如果是可重试的错误且还有重试次数
|
||||
if (isRetryableError(error) && retryCount < maxRetries) {
|
||||
retryCount++;
|
||||
const delayMs = Math.min(1000 * Math.pow(2, retryCount - 1), 10000); // 指数退避,最大10秒
|
||||
|
||||
console.log(`${delayMs}ms后进行第${retryCount}次重试...`);
|
||||
|
||||
// 通知前端正在重试
|
||||
if (onProgress) {
|
||||
onProgress({
|
||||
progress: 0,
|
||||
uploaded: 0,
|
||||
total: file.size,
|
||||
speed: 0,
|
||||
fileName: file.name,
|
||||
fileSize: file.size,
|
||||
eta: 0,
|
||||
retryCount: retryCount,
|
||||
status: 'retrying',
|
||||
error: `上传失败,${delayMs/1000}秒后重试: ${errorMessage}`
|
||||
});
|
||||
}
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, delayMs));
|
||||
return uploadAttempt(); // 递归重试
|
||||
}
|
||||
|
||||
// 不可重试或重试次数用完
|
||||
console.error(`文件上传最终失败: ${file.name}, 错误: ${errorMessage}`);
|
||||
|
||||
// 增强错误信息
|
||||
let enhancedError = new Error(errorMessage);
|
||||
enhancedError.originalError = error;
|
||||
enhancedError.retryCount = retryCount;
|
||||
enhancedError.fileName = file.name;
|
||||
enhancedError.fileSize = file.size;
|
||||
|
||||
// 根据错误类型提供更好的用户提示
|
||||
if (error.code === 'ECONNABORTED' || errorMessage.includes('timeout')) {
|
||||
enhancedError.message = `文件上传超时,请检查网络连接或尝试上传更小的文件。文件: ${file.name}`;
|
||||
} else if (error.response?.status === 413) {
|
||||
enhancedError.message = `文件太大无法上传: ${file.name} (${(file.size / (1024 * 1024)).toFixed(1)}MB)`;
|
||||
} else if (error.response?.status >= 500) {
|
||||
enhancedError.message = `服务器错误,请稍后重试。文件: ${file.name}`;
|
||||
}
|
||||
|
||||
throw enhancedError;
|
||||
}
|
||||
};
|
||||
|
||||
return uploadAttempt();
|
||||
};
|
||||
|
||||
// 管理员删除文件
|
||||
export const adminDeleteFile = async (workId, fileType, filename, platform = null) => {
|
||||
const params = { token: adminToken };
|
||||
if (platform) {
|
||||
params.platform = platform;
|
||||
}
|
||||
|
||||
const response = await adminApi.delete(`/admin/delete-file/${workId}/${fileType}/${filename}`, {
|
||||
params
|
||||
});
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export default adminApi;
|
||||
73
SproutWorkCollect-Frontend/src/services/api.js
Normal file
73
SproutWorkCollect-Frontend/src/services/api.js
Normal file
@@ -0,0 +1,73 @@
|
||||
import axios from 'axios';
|
||||
import { getApiBaseUrl } from '../config/apiBase';
|
||||
|
||||
const API_BASE_URL = getApiBaseUrl();
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: API_BASE_URL,
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
api.interceptors.response.use(
|
||||
(response) => {
|
||||
const contentType = response?.headers?.['content-type'] || '';
|
||||
if (typeof response.data === 'string') {
|
||||
const trimmed = response.data.trim().toLowerCase();
|
||||
const looksLikeHtml =
|
||||
contentType.includes('text/html') ||
|
||||
trimmed.startsWith('<!doctype') ||
|
||||
trimmed.startsWith('<html');
|
||||
|
||||
if (looksLikeHtml) {
|
||||
throw new Error(
|
||||
`API 返回了 HTML(疑似请求打到了前端自身域名/SPA重写),请检查 Cloudflare Pages 环境变量 REACT_APP_API_URL。当前 baseURL: ${API_BASE_URL}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return response;
|
||||
},
|
||||
(error) => Promise.reject(error)
|
||||
);
|
||||
|
||||
// 获取网站设置
|
||||
export const getSettings = async () => {
|
||||
const response = await api.get('/settings');
|
||||
return response.data;
|
||||
};
|
||||
|
||||
// 获取所有作品
|
||||
export const getWorks = async () => {
|
||||
const response = await api.get('/works');
|
||||
return response.data;
|
||||
};
|
||||
|
||||
// 获取单个作品详情
|
||||
export const getWorkDetail = async (workId) => {
|
||||
const response = await api.get(`/works/${workId}`);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
// 搜索作品
|
||||
export const searchWorks = async (query = '', category = '') => {
|
||||
const params = new URLSearchParams();
|
||||
if (query) params.append('q', query);
|
||||
if (category) params.append('category', category);
|
||||
|
||||
const response = await api.get(`/search?${params.toString()}`);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
// 获取所有分类
|
||||
export const getCategories = async () => {
|
||||
const response = await api.get('/categories');
|
||||
return response.data;
|
||||
};
|
||||
|
||||
// 点赞作品
|
||||
export const likeWork = async (workId) => {
|
||||
const response = await api.post(`/like/${workId}`);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export default api;
|
||||
192
SproutWorkCollect-Frontend/test/background.css
Normal file
192
SproutWorkCollect-Frontend/test/background.css
Normal file
@@ -0,0 +1,192 @@
|
||||
/* 彩虹渐变背景样式 */
|
||||
|
||||
/* 主背景渐变 */
|
||||
body {
|
||||
background: linear-gradient(
|
||||
135deg,
|
||||
rgba(255, 107, 107, 0.3) 0%,
|
||||
rgba(255, 165, 0, 0.3) 14.28%,
|
||||
rgba(255, 255, 0, 0.25) 28.56%,
|
||||
rgba(50, 205, 50, 0.3) 42.84%,
|
||||
rgba(0, 191, 255, 0.3) 57.12%,
|
||||
rgba(65, 105, 225, 0.3) 71.4%,
|
||||
rgba(147, 112, 219, 0.3) 85.68%,
|
||||
rgba(255, 105, 180, 0.3) 100%
|
||||
);
|
||||
background-size: 400% 400%;
|
||||
animation: rainbowShift 20s ease infinite;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
/* 彩虹渐变动画 */
|
||||
@keyframes rainbowShift {
|
||||
0% {
|
||||
background-position: 0% 50%;
|
||||
}
|
||||
50% {
|
||||
background-position: 100% 50%;
|
||||
}
|
||||
100% {
|
||||
background-position: 0% 50%;
|
||||
}
|
||||
}
|
||||
|
||||
/* 半透明覆盖层,增强可读性 */
|
||||
body::before {
|
||||
content: '';
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(255, 255, 255, 0.4);
|
||||
backdrop-filter: blur(2px);
|
||||
z-index: -1;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* 搜索按钮彩虹渐变 */
|
||||
.search-btn {
|
||||
background: linear-gradient(
|
||||
45deg,
|
||||
rgba(255, 107, 107, 0.8),
|
||||
rgba(255, 165, 0, 0.8),
|
||||
rgba(255, 255, 0, 0.7),
|
||||
rgba(50, 205, 50, 0.8),
|
||||
rgba(0, 191, 255, 0.8),
|
||||
rgba(65, 105, 225, 0.8),
|
||||
rgba(147, 112, 219, 0.8)
|
||||
);
|
||||
background-size: 300% 300%;
|
||||
animation: buttonRainbow 12s ease infinite;
|
||||
}
|
||||
|
||||
@keyframes buttonRainbow {
|
||||
0%, 100% {
|
||||
background-position: 0% 50%;
|
||||
}
|
||||
50% {
|
||||
background-position: 100% 50%;
|
||||
}
|
||||
}
|
||||
|
||||
/* 结果卡片边框彩虹渐变 */
|
||||
.result-card {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.result-card::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -2px;
|
||||
left: -2px;
|
||||
right: -2px;
|
||||
bottom: -2px;
|
||||
background: linear-gradient(
|
||||
45deg,
|
||||
rgba(255, 107, 107, 0.4),
|
||||
rgba(255, 165, 0, 0.4),
|
||||
rgba(255, 255, 0, 0.3),
|
||||
rgba(50, 205, 50, 0.4),
|
||||
rgba(0, 191, 255, 0.4),
|
||||
rgba(65, 105, 225, 0.4),
|
||||
rgba(147, 112, 219, 0.4),
|
||||
rgba(255, 107, 107, 0.4)
|
||||
);
|
||||
background-size: 400% 400%;
|
||||
animation: borderRainbow 15s linear infinite;
|
||||
border-radius: inherit;
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
@keyframes borderRainbow {
|
||||
0% {
|
||||
background-position: 0% 50%;
|
||||
}
|
||||
100% {
|
||||
background-position: 400% 50%;
|
||||
}
|
||||
}
|
||||
|
||||
/* 加载动画彩虹效果 */
|
||||
.loading-spinner {
|
||||
border: 4px solid rgba(255, 255, 255, 0.3);
|
||||
border-top: 4px solid transparent;
|
||||
border-image: linear-gradient(
|
||||
45deg,
|
||||
#ff6b6b,
|
||||
#ffa500,
|
||||
#ffff00,
|
||||
#32cd32,
|
||||
#00bfff,
|
||||
#4169e1,
|
||||
#9370db
|
||||
) 1;
|
||||
animation: spin 1s linear infinite, colorShift 3s ease infinite;
|
||||
}
|
||||
|
||||
@keyframes colorShift {
|
||||
0%, 100% {
|
||||
filter: hue-rotate(0deg);
|
||||
}
|
||||
50% {
|
||||
filter: hue-rotate(180deg);
|
||||
}
|
||||
}
|
||||
|
||||
/* 链接悬停彩虹效果 */
|
||||
.result-link:hover {
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
rgba(255, 107, 107, 0.7),
|
||||
rgba(255, 165, 0, 0.7),
|
||||
rgba(255, 255, 0, 0.6),
|
||||
rgba(50, 205, 50, 0.7),
|
||||
rgba(0, 191, 255, 0.7),
|
||||
rgba(65, 105, 225, 0.7),
|
||||
rgba(147, 112, 219, 0.7)
|
||||
);
|
||||
background-size: 200% 200%;
|
||||
animation: linkRainbow 3s ease infinite;
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
}
|
||||
|
||||
@keyframes linkRainbow {
|
||||
0%, 100% {
|
||||
background-position: 0% 50%;
|
||||
}
|
||||
50% {
|
||||
background-position: 100% 50%;
|
||||
}
|
||||
}
|
||||
|
||||
/* 标题彩虹文字效果 */
|
||||
.title {
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
rgba(255, 107, 107, 0.8),
|
||||
rgba(255, 165, 0, 0.8),
|
||||
rgba(255, 255, 0, 0.7),
|
||||
rgba(50, 205, 50, 0.8),
|
||||
rgba(0, 191, 255, 0.8),
|
||||
rgba(65, 105, 225, 0.8),
|
||||
rgba(147, 112, 219, 0.8)
|
||||
);
|
||||
background-size: 200% 200%;
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
animation: titleRainbow 8s ease infinite;
|
||||
}
|
||||
|
||||
@keyframes titleRainbow {
|
||||
0%, 100% {
|
||||
background-position: 0% 50%;
|
||||
}
|
||||
50% {
|
||||
background-position: 100% 50%;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user