初始化提交
This commit is contained in:
107
.gitignore
vendored
107
.gitignore
vendored
@@ -1,12 +1,8 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
@@ -20,15 +16,12 @@ parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
@@ -39,17 +32,14 @@ pip-delete-this-directory.txt
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
@@ -59,7 +49,6 @@ cover/
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
@@ -72,57 +61,16 @@ instance/
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
.python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# UV
|
||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
#uv.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
||||
.pdm.toml
|
||||
.pdm-python
|
||||
.pdm-build/
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
# celery beat schedule file
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
@@ -151,31 +99,32 @@ venv.bak/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
# OS
|
||||
.DS_Store
|
||||
.DS_Store?
|
||||
._*
|
||||
.Spotlight-V100
|
||||
.Trashes
|
||||
ehthumbs.db
|
||||
Thumbs.db
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
# 项目特定
|
||||
uploads/
|
||||
temp/
|
||||
*.tmp
|
||||
*.bak
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
# 日志文件
|
||||
*.log
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
|
||||
# Cursor
|
||||
# Cursor is an AI-powered code editor.`.cursorignore` specifies files/directories to
|
||||
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
||||
# refer to https://docs.cursor.com/context/ignore-files
|
||||
.cursorignore
|
||||
.cursorindexingignore
|
||||
#作品
|
||||
works/
|
||||
frontend/build/
|
||||
frontend/node_modules/
|
||||
54
API_CONFIG.md
Normal file
54
API_CONFIG.md
Normal file
@@ -0,0 +1,54 @@
|
||||
# API配置说明
|
||||
|
||||
## 开发环境
|
||||
开发环境下,前端会自动连接到 `http://localhost:5000/api`,无需额外配置。
|
||||
|
||||
## 生产环境配置
|
||||
|
||||
### 方式1: 前后端同域名部署
|
||||
如果前端和后端部署在同一服务器的同一域名下,使用默认配置即可。
|
||||
前端会使用相对路径 `/api` 访问后端。
|
||||
|
||||
### 方式2: 后端独立部署
|
||||
如果后端部署在不同的服务器或域名,需要设置环境变量:
|
||||
|
||||
1. 在 `frontend` 目录下创建 `.env.local` 文件
|
||||
2. 添加以下内容:
|
||||
```
|
||||
REACT_APP_API_URL=http://your-backend-domain.com:5000/api
|
||||
```
|
||||
|
||||
### 方式3: 修改源代码
|
||||
如果不想使用环境变量,可以直接修改 `src/services/api.js` 和 `src/services/adminApi.js` 文件中的配置。
|
||||
|
||||
## 后端CORS设置
|
||||
确保后端允许前端域名的跨域请求。在 `backend/app.py` 中:
|
||||
|
||||
```python
|
||||
from flask_cors import CORS
|
||||
|
||||
app = Flask(__name__)
|
||||
CORS(app, origins=['http://your-frontend-domain.com']) # 指定允许的域名
|
||||
```
|
||||
|
||||
## 常见问题
|
||||
|
||||
1. **构建后无法访问API**: 检查API_URL配置是否正确
|
||||
2. **跨域错误**: 检查后端CORS设置
|
||||
3. **连接超时**: 检查后端服务是否正常运行,防火墙是否开放端口
|
||||
|
||||
## 部署建议
|
||||
|
||||
### 同域名部署 (推荐)
|
||||
```
|
||||
your-domain.com/ -> 前端静态文件
|
||||
your-domain.com/api/ -> 后端API
|
||||
```
|
||||
|
||||
### 不同域名部署
|
||||
```
|
||||
frontend.your-domain.com -> 前端
|
||||
api.your-domain.com -> 后端
|
||||
```
|
||||
|
||||
需要在前端设置 `REACT_APP_API_URL=https://api.your-domain.com/api`
|
||||
209
README.md
Normal file
209
README.md
Normal file
@@ -0,0 +1,209 @@
|
||||
# 树萌芽の作品集
|
||||
|
||||
一个展示创意作品和项目的现代化网站,采用React + Flask架构开发。
|
||||
|
||||
## 功能特点
|
||||
|
||||
- 🎨 清新可爱的淡绿色配色方案
|
||||
- 📱 完全响应式设计,优先适配手机端
|
||||
- 🔍 作品搜索和分类筛选功能
|
||||
- 📦 多平台作品下载支持(Windows/Android/Linux)
|
||||
- 🖼️ 作品截图和视频展示
|
||||
- 📄 详细的作品信息页面
|
||||
- 🏷️ 网站logo、备案号、页尾配置支持
|
||||
- 👑 管理员后台界面,支持作品增删改
|
||||
- 📁 文件上传管理功能
|
||||
- 📊 作品统计功能:浏览量、下载量、点赞量、更新次数
|
||||
- 🛡️ 防刷机制:基于用户指纹的智能防刷保护
|
||||
- 👍 互动功能:支持作品点赞
|
||||
- 🔄 自动统计:管理员编辑作品自动增加更新次数
|
||||
- ⚡ 模块化架构,易于扩展维护
|
||||
|
||||
## 技术栈
|
||||
|
||||
### 前端
|
||||
- React 18.2.0
|
||||
- Styled Components
|
||||
- Axios
|
||||
- React Router DOM
|
||||
|
||||
### 后端
|
||||
- Python 3.13.2
|
||||
- Flask 3.0.0
|
||||
- Flask-CORS
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 方式一:使用批处理文件(Windows)
|
||||
|
||||
1. **启动后端服务**
|
||||
```
|
||||
双击运行 start_backend.bat
|
||||
```
|
||||
|
||||
2. **启动前端服务**(新开一个命令窗口)
|
||||
```
|
||||
双击运行 start_frontend.bat
|
||||
```
|
||||
|
||||
### 方式二:手动启动
|
||||
|
||||
1. **启动后端服务**
|
||||
```bash
|
||||
cd backend
|
||||
pip install -r requirements.txt
|
||||
python app.py
|
||||
```
|
||||
|
||||
2. **启动前端服务**(新开一个终端)
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
npm start
|
||||
```
|
||||
|
||||
## 访问地址
|
||||
|
||||
- 前端页面: http://localhost:3000
|
||||
- 后端API: http://localhost:5000
|
||||
- 管理员界面: http://localhost:3000/admin?token=shumengya520
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
树萌芽の作品集/
|
||||
├── backend/ # Flask后端
|
||||
│ ├── app.py # 主应用文件
|
||||
│ └── requirements.txt # Python依赖
|
||||
├── frontend/ # React前端
|
||||
│ ├── public/ # 静态文件
|
||||
│ ├── src/ # 源代码
|
||||
│ │ ├── components/ # React组件
|
||||
│ │ ├── services/ # API服务
|
||||
│ │ ├── App.js # 主应用组件
|
||||
│ │ └── index.js # 入口文件
|
||||
│ └── package.json # Node.js依赖
|
||||
├── config/ # 配置文件
|
||||
│ └── settings.json # 网站基础配置(包含logo、备案号、页尾等)
|
||||
├── works/ # 作品目录
|
||||
│ ├── aicodevartool/ # AI代码变量工具
|
||||
│ ├── mengyafarm/ # 萌芽农场
|
||||
│ └── mml_cgj2025/ # MML创意游戏大赛2025
|
||||
└── README.md # 项目说明
|
||||
```
|
||||
|
||||
## 作品配置格式
|
||||
|
||||
每个作品需要在 `works/{作品ID}/` 目录下包含:
|
||||
|
||||
- `work_config.json` - 作品配置文件
|
||||
- `image/` - 作品截图目录
|
||||
- `platform/` - 各平台文件目录
|
||||
- `Windows/` - Windows版本文件
|
||||
- `Android/` - Android版本文件
|
||||
- `Linux/` - Linux版本文件
|
||||
|
||||
### work_config.json 示例
|
||||
|
||||
```json
|
||||
{
|
||||
"作品ID": "example",
|
||||
"作品作品": "示例作品",
|
||||
"作品描述": "这是一个示例作品的描述",
|
||||
"作者": "树萌芽",
|
||||
"作品版本号": "1.0.0",
|
||||
"作品分类": "工具",
|
||||
"作品标签": ["示例", "工具"],
|
||||
"上传时间": "2025-01-01T00:00:00",
|
||||
"更新时间": "2025-01-01T00:00:00",
|
||||
"支持平台": ["Windows", "Android"],
|
||||
"文件名称": {
|
||||
"Windows": ["example_windows.zip"],
|
||||
"Android": ["example_android.apk"]
|
||||
},
|
||||
"作品截图": ["image1.jpg", "image2.jpg"],
|
||||
"作品视频": [],
|
||||
"作品封面": "image1.jpg"
|
||||
}
|
||||
```
|
||||
|
||||
## API接口
|
||||
|
||||
- `GET /api/settings` - 获取网站设置
|
||||
- `GET /api/works` - 获取所有作品列表
|
||||
- `GET /api/works/{work_id}` - 获取单个作品详情
|
||||
- `GET /api/search?q={query}&category={category}` - 搜索作品
|
||||
- `GET /api/categories` - 获取所有分类
|
||||
- `GET /api/image/{work_id}/{filename}` - 获取作品图片
|
||||
- `GET /api/download/{work_id}/{platform}/{filename}` - 下载作品文件
|
||||
- `POST /api/like/{work_id}` - 点赞作品
|
||||
|
||||
### 管理员API接口
|
||||
|
||||
- `GET /api/admin/works?token=shumengya520` - 管理员获取所有作品
|
||||
- `POST /api/admin/works?token=shumengya520` - 管理员创建新作品
|
||||
- `PUT /api/admin/works/{work_id}?token=shumengya520` - 管理员更新作品
|
||||
- `DELETE /api/admin/works/{work_id}?token=shumengya520` - 管理员删除作品
|
||||
- `POST /api/admin/upload/{work_id}/{file_type}?token=shumengya520` - 管理员上传文件
|
||||
- `DELETE /api/admin/delete-file/{work_id}/{file_type}/{filename}?token=shumengya520` - 管理员删除文件
|
||||
|
||||
## 管理员功能使用说明
|
||||
|
||||
### 访问管理员界面
|
||||
|
||||
1. 确保后端和前端服务都已启动
|
||||
2. 访问: http://localhost:3000/admin?token=shumengya520
|
||||
3. 正确的token是 `shumengya520`
|
||||
|
||||
### 管理员功能
|
||||
|
||||
1. **查看作品列表**: 显示所有作品的基本信息和操作按钮
|
||||
2. **添加新作品**:
|
||||
- 点击"添加新作品"按钮
|
||||
- 填写作品基本信息(作品ID、名称、描述等)
|
||||
- 选择支持的平台
|
||||
- 保存后可以上传文件
|
||||
3. **编辑作品**:
|
||||
- 点击作品旁的"编辑"按钮
|
||||
- 修改作品信息
|
||||
- 管理作品文件(上传、删除)
|
||||
4. **删除作品**:
|
||||
- 点击作品旁的"删除"按钮
|
||||
- 确认删除(将删除整个作品目录)
|
||||
|
||||
### 文件管理
|
||||
|
||||
- **作品截图**: 支持PNG、JPG、JPEG、GIF格式,支持批量上传
|
||||
- **作品视频**: 支持MP4、AVI、MOV格式
|
||||
- **平台文件**: 支持ZIP、RAR、APK、EXE、DMG等格式
|
||||
- **自动命名**: 图片自动命名为image1.jpg、image2.png等,视频命名为video1.mp4等,平台文件命名为作品ID_平台.扩展名
|
||||
- **封面选择**: 可以从已上传的图片中点击选择封面图
|
||||
- **拖拽上传**: 支持拖拽文件到上传区域
|
||||
- 支持批量上传和单独删除
|
||||
|
||||
### 统计功能说明
|
||||
|
||||
#### 防刷机制
|
||||
- **用户识别**: 基于IP地址和User-Agent生成用户指纹
|
||||
- **时间限制**:
|
||||
- 浏览量:同一用户1分钟内对同一作品只计数一次
|
||||
- 下载量:同一用户5分钟内对同一作品只计数一次
|
||||
- 点赞量:同一用户1小时内对同一作品只计数一次
|
||||
- **自动更新**: 管理员编辑作品时自动增加更新次数
|
||||
|
||||
#### 统计展示
|
||||
- **作品卡片**: 显示浏览、下载、点赞、更新次数的简洁图标统计
|
||||
- **详情页面**: 显示详细的统计卡片和互动点赞按钮
|
||||
- **实时更新**: 点赞后立即更新显示数据
|
||||
|
||||
## 开发说明
|
||||
|
||||
- 前端采用模块化架构,组件分离,便于维护
|
||||
- 响应式设计优先考虑手机端体验
|
||||
- 后端提供RESTful API接口
|
||||
- 支持作品搜索和分类筛选
|
||||
- 自动解析works目录下的作品配置
|
||||
|
||||
## 作者
|
||||
|
||||
树萌芽 - 3205788256@qq.com
|
||||
181
ShuMengyaWorks-Web/.gitignore
vendored
Normal file
181
ShuMengyaWorks-Web/.gitignore
vendored
Normal file
@@ -0,0 +1,181 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# UV
|
||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
#uv.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
||||
.pdm.toml
|
||||
.pdm-python
|
||||
.pdm-build/
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
|
||||
# Cursor
|
||||
# Cursor is an AI-powered code editor.`.cursorignore` specifies files/directories to
|
||||
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
||||
# refer to https://docs.cursor.com/context/ignore-files
|
||||
.cursorignore
|
||||
.cursorindexingignore
|
||||
704
backend/app.py
Normal file
704
backend/app.py
Normal file
@@ -0,0 +1,704 @@
|
||||
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
|
||||
|
||||
# 配置日志
|
||||
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.dirname(os.path.abspath(__file__)))
|
||||
WORKS_DIR = os.path.join(BASE_DIR, 'works')
|
||||
CONFIG_DIR = os.path.join(BASE_DIR, 'config')
|
||||
|
||||
# 管理员token
|
||||
ADMIN_TOKEN = "shumengya520"
|
||||
|
||||
# 允许的文件扩展名
|
||||
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 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 {
|
||||
"网站名字": "树萌芽の作品集",
|
||||
"网站描述": "展示我的创意作品和项目",
|
||||
"站长": "树萌芽",
|
||||
"联系邮箱": "3205788256@qq.com",
|
||||
"主题颜色": "#81c784",
|
||||
"每页作品数量": 12,
|
||||
"启用搜索": True,
|
||||
"启用分类": True
|
||||
}
|
||||
|
||||
#加载单个作品配置
|
||||
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 = secure_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
|
||||
|
||||
file_extension = original_filename.rsplit('.', 1)[1].lower()
|
||||
|
||||
# 读取现有配置来生成新文件名
|
||||
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('作品截图', [])
|
||||
image_number = len(existing_images) + 1
|
||||
filename = f"image{image_number}.{file_extension}"
|
||||
elif file_type == 'video':
|
||||
save_dir = os.path.join(work_dir, 'video')
|
||||
existing_videos = config.get('作品视频', [])
|
||||
video_number = len(existing_videos) + 1
|
||||
filename = f"video{video_number}.{file_extension}"
|
||||
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)
|
||||
filename = f"{work_id}_{platform.lower()}.{file_extension}"
|
||||
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)
|
||||
if not config.get('作品封面'):
|
||||
config['作品封面'] = filename
|
||||
elif file_type == 'video':
|
||||
if filename not in config.get('作品视频', []):
|
||||
config.setdefault('作品视频', []).append(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['更新时间'] = 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 config.get('作品封面') == filename:
|
||||
config['作品封面'] = config['作品截图'][0] if config['作品截图'] else ''
|
||||
elif file_type == 'video':
|
||||
if filename in config.get('作品视频', []):
|
||||
config['作品视频'].remove(filename)
|
||||
elif file_type == 'platform':
|
||||
platform = request.args.get('platform')
|
||||
if platform in config.get('文件名称', {}):
|
||||
if filename in config['文件名称'][platform]:
|
||||
config['文件名称'][platform].remove(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__':
|
||||
app.run(debug=True, host='0.0.0.0', port=5000)
|
||||
8
backend/requirements.txt
Normal file
8
backend/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
backend/后端返回接口.json
Normal file
167
backend/后端返回接口.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
|
||||
}
|
||||
5
build_frontend.bat
Normal file
5
build_frontend.bat
Normal file
@@ -0,0 +1,5 @@
|
||||
@echo off
|
||||
echo 正在构建树萌芽の作品集网站前端
|
||||
cd frontend
|
||||
npm run build
|
||||
pause
|
||||
13
config/settings.json
Normal file
13
config/settings.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"网站名字": "树萌芽の作品集",
|
||||
"网站描述": "展示个人制作的一些小创意和小项目,欢迎交流讨论",
|
||||
"站长": "by-树萌芽",
|
||||
"联系邮箱": "3205788256@qq.com",
|
||||
"主题颜色": "#81c784",
|
||||
"每页作品数量": 9,
|
||||
"启用搜索": true,
|
||||
"启用分类": true,
|
||||
"备案号": "蜀ICP备2025151694号",
|
||||
"网站页尾": "树萌芽の作品集 | Copyright © 2025-2025 smy",
|
||||
"网站logo": "assets/logo.png"
|
||||
}
|
||||
1
frontend/.env.local
Normal file
1
frontend/.env.local
Normal file
@@ -0,0 +1 @@
|
||||
REACT_APP_API_URL=http://127.0.0.1:5000/api
|
||||
20651
frontend/package-lock.json
generated
Normal file
20651
frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
42
frontend/package.json
Normal file
42
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",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-scripts": "5.0.1",
|
||||
"axios": "^1.4.0",
|
||||
"react-router-dom": "^6.8.0",
|
||||
"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
frontend/public/.htaccess
Normal file
15
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
frontend/public/_redirects
Normal file
2
frontend/public/_redirects
Normal file
@@ -0,0 +1,2 @@
|
||||
# Netlify redirects for SPA
|
||||
/* /index.html 200
|
||||
BIN
frontend/public/assets/logo.png
Normal file
BIN
frontend/public/assets/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.2 MiB |
26
frontend/public/assets/logo.svg
Normal file
26
frontend/public/assets/logo.svg
Normal file
@@ -0,0 +1,26 @@
|
||||
<svg width="120" height="60" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<linearGradient id="logoGradient" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
<stop offset="0%" style="stop-color:#81c784;stop-opacity:1" />
|
||||
<stop offset="100%" style="stop-color:#66bb6a;stop-opacity:1" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<!-- 背景圆角矩形 -->
|
||||
<rect x="0" y="0" width="120" height="60" rx="10" ry="10" fill="url(#logoGradient)"/>
|
||||
|
||||
<!-- 树的主干 -->
|
||||
<rect x="55" y="35" width="10" height="20" fill="#4a4a4a"/>
|
||||
|
||||
<!-- 树叶/树冠 -->
|
||||
<circle cx="45" cy="25" r="12" fill="#2e7d32"/>
|
||||
<circle cx="60" cy="20" r="15" fill="#388e3c"/>
|
||||
<circle cx="75" cy="25" r="12" fill="#2e7d32"/>
|
||||
|
||||
<!-- 萌芽 -->
|
||||
<circle cx="35" cy="30" r="4" fill="#a5d6a7"/>
|
||||
<circle cx="85" cy="28" r="4" fill="#a5d6a7"/>
|
||||
|
||||
<!-- 文字 -->
|
||||
<text x="60" y="52" text-anchor="middle" font-family="Arial, sans-serif" font-size="8" fill="white" font-weight="bold">树萌芽</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 994 B |
32
frontend/public/index.html
Normal file
32
frontend/public/index.html
Normal file
@@ -0,0 +1,32 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<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>
|
||||
176
frontend/src/App.js
Normal file
176
frontend/src/App.js
Normal file
@@ -0,0 +1,176 @@
|
||||
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 { getWorks, getSettings, getCategories, searchWorks } from './services/api';
|
||||
|
||||
const AppContainer = styled.div`
|
||||
min-height: 100vh;
|
||||
background: linear-gradient(135deg, #e8f5e8 0%, #f1f8e9 100%);
|
||||
`;
|
||||
|
||||
const MainContent = styled.main`
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
const WorksGrid = styled.div`
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
|
||||
gap: 20px;
|
||||
margin-top: 20px;
|
||||
|
||||
@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 = () => {
|
||||
const [works, setWorks] = useState([]);
|
||||
const [categories, setCategories] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [selectedCategory, setSelectedCategory] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
loadInitialData();
|
||||
}, []);
|
||||
|
||||
const loadInitialData = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const [worksData, categoriesData] = await Promise.all([
|
||||
getWorks(),
|
||||
getCategories()
|
||||
]);
|
||||
|
||||
setWorks(worksData.data || []);
|
||||
setCategories(categoriesData.data || []);
|
||||
} 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);
|
||||
setWorks(searchData.data || []);
|
||||
} else {
|
||||
const worksData = await getWorks();
|
||||
setWorks(worksData.data || []);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('搜索失败:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<MainContent>
|
||||
<FilterSection>
|
||||
<SearchBar onSearch={handleSearch} />
|
||||
<CategoryFilter
|
||||
categories={categories}
|
||||
selectedCategory={selectedCategory}
|
||||
onCategoryChange={handleCategoryChange}
|
||||
/>
|
||||
</FilterSection>
|
||||
|
||||
{loading ? (
|
||||
<LoadingSpinner />
|
||||
) : works.length > 0 ? (
|
||||
<WorksGrid>
|
||||
{works.map((work) => (
|
||||
<WorkCard key={work.作品ID} work={work} />
|
||||
))}
|
||||
</WorksGrid>
|
||||
) : (
|
||||
<NoResults>
|
||||
{searchQuery || selectedCategory ? '没有找到匹配的作品' : '暂无作品'}
|
||||
</NoResults>
|
||||
)}
|
||||
</MainContent>
|
||||
);
|
||||
};
|
||||
|
||||
function App() {
|
||||
const [settings, setSettings] = useState({});
|
||||
|
||||
useEffect(() => {
|
||||
loadSettings();
|
||||
}, []);
|
||||
|
||||
const loadSettings = async () => {
|
||||
try {
|
||||
const settingsData = await getSettings();
|
||||
setSettings(settingsData);
|
||||
} catch (error) {
|
||||
console.error('加载设置失败:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Router>
|
||||
<AppContainer>
|
||||
<Header settings={settings} />
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/work/:workId" element={<WorkDetail />} />
|
||||
<Route path="/admin" element={<AdminPanel />} />
|
||||
</Routes>
|
||||
<Footer settings={settings} />
|
||||
</AppContainer>
|
||||
</Router>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
317
frontend/src/components/AdminPanel.js
Normal file
317
frontend/src/components/AdminPanel.js
Normal file
@@ -0,0 +1,317 @@
|
||||
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 } 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 token = searchParams.get('token');
|
||||
if (token !== 'shumengya520') {
|
||||
navigate('/');
|
||||
return;
|
||||
}
|
||||
|
||||
setAdminToken(token);
|
||||
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;
|
||||
77
frontend/src/components/CategoryFilter.js
Normal file
77
frontend/src/components/CategoryFilter.js
Normal file
@@ -0,0 +1,77 @@
|
||||
import React from 'react';
|
||||
import styled from 'styled-components';
|
||||
|
||||
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: white;
|
||||
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;
|
||||
101
frontend/src/components/Footer.js
Normal file
101
frontend/src/components/Footer.js
Normal file
@@ -0,0 +1,101 @@
|
||||
import React from 'react';
|
||||
import styled from 'styled-components';
|
||||
|
||||
const FooterContainer = styled.footer`
|
||||
background: linear-gradient(135deg, #2e7d32 0%, #388e3c 100%);
|
||||
color: white;
|
||||
padding: 30px 0 20px;
|
||||
margin-top: 40px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 20px 0 15px;
|
||||
margin-top: 30px;
|
||||
}
|
||||
`;
|
||||
|
||||
const FooterContent = styled.div`
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 0 20px;
|
||||
text-align: center;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 0 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
const FooterText = styled.p`
|
||||
font-size: 0.9rem;
|
||||
opacity: 0.9;
|
||||
margin-bottom: 10px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
font-size: 0.8rem;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
`;
|
||||
|
||||
const ContactInfo = styled.div`
|
||||
margin-bottom: 15px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
`;
|
||||
|
||||
const ContactLink = styled.a`
|
||||
color: white;
|
||||
text-decoration: none;
|
||||
opacity: 0.9;
|
||||
transition: opacity 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
opacity: 1;
|
||||
text-decoration: underline;
|
||||
}
|
||||
`;
|
||||
|
||||
const RecordNumber = styled.p`
|
||||
font-size: 0.8rem;
|
||||
opacity: 0.7;
|
||||
margin-bottom: 5px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
`;
|
||||
|
||||
const Copyright = styled.p`
|
||||
font-size: 0.8rem;
|
||||
opacity: 0.7;
|
||||
|
||||
@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;
|
||||
108
frontend/src/components/Header.js
Normal file
108
frontend/src/components/Header.js
Normal file
@@ -0,0 +1,108 @@
|
||||
import React from 'react';
|
||||
import styled from 'styled-components';
|
||||
|
||||
const HeaderContainer = styled.header`
|
||||
background: linear-gradient(135deg, #81c784 0%, #a5d6a7 100%);
|
||||
color: white;
|
||||
padding: 20px 0;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
`;
|
||||
|
||||
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;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
const Logo = styled.img`
|
||||
height: 60px;
|
||||
width: auto;
|
||||
border-radius: 8px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
height: 50px;
|
||||
}
|
||||
`;
|
||||
|
||||
const Title = styled.h1`
|
||||
font-size: 2.5rem;
|
||||
margin-bottom: 10px;
|
||||
font-weight: 700;
|
||||
text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
|
||||
|
||||
@media (max-width: 768px) {
|
||||
font-size: 2rem;
|
||||
}
|
||||
`;
|
||||
|
||||
const Description = styled.p`
|
||||
font-size: 1.1rem;
|
||||
opacity: 0.9;
|
||||
margin-bottom: 5px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
font-size: 1rem;
|
||||
}
|
||||
`;
|
||||
|
||||
const Author = styled.p`
|
||||
font-size: 0.9rem;
|
||||
opacity: 0.8;
|
||||
`;
|
||||
|
||||
const Header = ({ settings }) => {
|
||||
// 动态设置favicon
|
||||
React.useEffect(() => {
|
||||
if (settings.网站logo) {
|
||||
const favicon = document.querySelector('link[rel="icon"]');
|
||||
if (favicon) {
|
||||
favicon.href = settings.网站logo;
|
||||
} else {
|
||||
// 如果没有favicon链接,创建一个
|
||||
const newFavicon = document.createElement('link');
|
||||
newFavicon.rel = 'icon';
|
||||
newFavicon.href = settings.网站logo;
|
||||
document.head.appendChild(newFavicon);
|
||||
}
|
||||
}
|
||||
}, [settings.网站logo]);
|
||||
|
||||
return (
|
||||
<HeaderContainer>
|
||||
<HeaderContent>
|
||||
{settings.网站logo && (
|
||||
<LogoContainer>
|
||||
<Logo
|
||||
src={settings.网站logo}
|
||||
alt={settings.网站名字 || '树萌芽の作品集'}
|
||||
onError={(e) => {
|
||||
e.target.style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
</LogoContainer>
|
||||
)}
|
||||
<Title>{settings.网站名字 || '树萌芽の作品集'}</Title>
|
||||
<Description>{settings.网站描述 || '展示我的创意作品和项目'}</Description>
|
||||
<Author>{settings.站长 || '树萌芽'}</Author>
|
||||
</HeaderContent>
|
||||
</HeaderContainer>
|
||||
);
|
||||
};
|
||||
|
||||
export default Header;
|
||||
41
frontend/src/components/LoadingSpinner.js
Normal file
41
frontend/src/components/LoadingSpinner.js
Normal file
@@ -0,0 +1,41 @@
|
||||
import React from 'react';
|
||||
import styled, { keyframes } from 'styled-components';
|
||||
|
||||
const spin = keyframes`
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
`;
|
||||
|
||||
const SpinnerContainer = styled.div`
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 40px;
|
||||
min-height: 200px;
|
||||
`;
|
||||
|
||||
const Spinner = styled.div`
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border: 4px solid #e8f5e8;
|
||||
border-top: 4px solid #81c784;
|
||||
border-radius: 50%;
|
||||
animation: ${spin} 1s linear infinite;
|
||||
`;
|
||||
|
||||
const LoadingText = styled.p`
|
||||
margin-left: 15px;
|
||||
color: #666;
|
||||
font-size: 16px;
|
||||
`;
|
||||
|
||||
const LoadingSpinner = ({ text = '加载中...' }) => {
|
||||
return (
|
||||
<SpinnerContainer>
|
||||
<Spinner />
|
||||
<LoadingText>{text}</LoadingText>
|
||||
</SpinnerContainer>
|
||||
);
|
||||
};
|
||||
|
||||
export default LoadingSpinner;
|
||||
100
frontend/src/components/SearchBar.js
Normal file
100
frontend/src/components/SearchBar.js
Normal file
@@ -0,0 +1,100 @@
|
||||
import React, { useState } from 'react';
|
||||
import styled from 'styled-components';
|
||||
|
||||
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: white;
|
||||
|
||||
&: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
frontend/src/components/UploadProgressModal.js
Normal file
369
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;
|
||||
259
frontend/src/components/WorkCard.js
Normal file
259
frontend/src/components/WorkCard.js
Normal file
@@ -0,0 +1,259 @@
|
||||
import React from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import styled from 'styled-components';
|
||||
|
||||
// 获取API基础URL
|
||||
const getApiBaseUrl = () => {
|
||||
if (process.env.REACT_APP_API_URL) {
|
||||
return process.env.REACT_APP_API_URL.replace('/api', '');
|
||||
}
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
return '';
|
||||
}
|
||||
return 'http://localhost:5000';
|
||||
};
|
||||
|
||||
const Card = styled.div`
|
||||
background: white;
|
||||
border-radius: 15px;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
|
||||
overflow: hidden;
|
||||
transition: all 0.3s ease;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
transform: translateY(-5px);
|
||||
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
`;
|
||||
|
||||
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 `${getApiBaseUrl()}${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;
|
||||
626
frontend/src/components/WorkDetail.js
Normal file
626
frontend/src/components/WorkDetail.js
Normal file
@@ -0,0 +1,626 @@
|
||||
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';
|
||||
|
||||
// 获取API基础URL
|
||||
const getApiBaseUrl = () => {
|
||||
if (process.env.REACT_APP_API_URL) {
|
||||
return process.env.REACT_APP_API_URL.replace('/api', '');
|
||||
}
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
return '';
|
||||
}
|
||||
return 'http://localhost:5000';
|
||||
};
|
||||
|
||||
const DetailContainer = styled.div`
|
||||
max-width: 1000px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
const BackButton = styled.button`
|
||||
background: #81c784;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 10px 20px;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
margin-bottom: 20px;
|
||||
transition: background 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
background: #66bb6a;
|
||||
}
|
||||
|
||||
@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) {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 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;
|
||||
}
|
||||
`;
|
||||
|
||||
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: ${props => props.liked ? '#4caf50' : '#81c784'};
|
||||
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;
|
||||
|
||||
&:hover {
|
||||
background: ${props => props.liked ? '#45a049' : '#66bb6a'};
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
background: #ccc;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
@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 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('');
|
||||
|
||||
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) => {
|
||||
window.open(`${getApiBaseUrl()}${imageUrl}`, '_blank');
|
||||
};
|
||||
|
||||
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>
|
||||
<source src={`${getApiBaseUrl()}${videoUrl}`} type="video/mp4" />
|
||||
您的浏览器不支持视频播放
|
||||
</VideoPlayer>
|
||||
</VideoContainer>
|
||||
))}
|
||||
</ContentSection>
|
||||
)}
|
||||
|
||||
{work.图片链接 && work.图片链接.length > 0 && (
|
||||
<ContentSection>
|
||||
<SectionTitle>作品截图</SectionTitle>
|
||||
<ImageGallery>
|
||||
{work.图片链接.map((imageUrl, index) => (
|
||||
<WorkImage
|
||||
key={index}
|
||||
src={`${getApiBaseUrl()}${imageUrl}`}
|
||||
alt={`${work.作品作品} 截图 ${index + 1}`}
|
||||
onClick={() => handleImageClick(imageUrl)}
|
||||
onError={(e) => {
|
||||
e.target.style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</ImageGallery>
|
||||
</ContentSection>
|
||||
)}
|
||||
|
||||
{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={`${getApiBaseUrl()}${link}`}
|
||||
download
|
||||
>
|
||||
下载 {platform} 版本
|
||||
</DownloadButton>
|
||||
))}
|
||||
</PlatformDownload>
|
||||
))}
|
||||
</DownloadSection>
|
||||
</ContentSection>
|
||||
)}
|
||||
</DetailContainer>
|
||||
);
|
||||
};
|
||||
|
||||
export default WorkDetail;
|
||||
997
frontend/src/components/WorkEditor.js
Normal file
997
frontend/src/components/WorkEditor.js
Normal file
@@ -0,0 +1,997 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import styled from 'styled-components';
|
||||
import { adminCreateWork, adminUpdateWork, adminUploadFile, adminDeleteFile } from '../services/adminApi';
|
||||
import UploadProgressModal from './UploadProgressModal';
|
||||
|
||||
// 获取API基础URL
|
||||
const getApiBaseUrl = () => {
|
||||
if (process.env.REACT_APP_API_URL) {
|
||||
return process.env.REACT_APP_API_URL.replace('/api', '');
|
||||
}
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
return '';
|
||||
}
|
||||
return 'http://localhost:5000';
|
||||
};
|
||||
|
||||
const EditorContainer = styled.div`
|
||||
max-width: 1000px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 10px;
|
||||
}
|
||||
`;
|
||||
|
||||
const EditorHeader = 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;
|
||||
}
|
||||
`;
|
||||
|
||||
const EditorTitle = styled.h1`
|
||||
color: #2e7d32;
|
||||
font-size: 1.8rem;
|
||||
margin: 0;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
font-size: 1.5rem;
|
||||
text-align: center;
|
||||
}
|
||||
`;
|
||||
|
||||
const ButtonGroup = styled.div`
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
}
|
||||
`;
|
||||
|
||||
const Button = styled.button`
|
||||
background: ${props => {
|
||||
if (props.variant === 'success') return '#4caf50';
|
||||
if (props.variant === 'danger') return '#f44336';
|
||||
return '#81c784';
|
||||
}};
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 10px 20px;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
transition: background 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
background: ${props => {
|
||||
if (props.variant === 'success') return '#45a049';
|
||||
if (props.variant === 'danger') return '#d32f2f';
|
||||
return '#66bb6a';
|
||||
}};
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
background: #ccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 12px 16px;
|
||||
width: 100%;
|
||||
}
|
||||
`;
|
||||
|
||||
const FormSection = styled.div`
|
||||
background: white;
|
||||
border-radius: 15px;
|
||||
padding: 25px;
|
||||
margin-bottom: 20px;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 20px;
|
||||
}
|
||||
`;
|
||||
|
||||
const SectionTitle = styled.h2`
|
||||
color: #2e7d32;
|
||||
font-size: 1.3rem;
|
||||
margin-bottom: 20px;
|
||||
border-bottom: 2px solid #e8f5e8;
|
||||
padding-bottom: 10px;
|
||||
`;
|
||||
|
||||
const FormGrid = styled.div`
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
|
||||
gap: 20px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 15px;
|
||||
}
|
||||
`;
|
||||
|
||||
const FormGroup = styled.div`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
`;
|
||||
|
||||
const Label = styled.label`
|
||||
font-weight: 500;
|
||||
color: #2e7d32;
|
||||
margin-bottom: 8px;
|
||||
font-size: 0.9rem;
|
||||
`;
|
||||
|
||||
const Input = styled.input`
|
||||
padding: 10px 12px;
|
||||
border: 2px solid #e0e0e0;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
outline: none;
|
||||
transition: border-color 0.3s ease;
|
||||
|
||||
&:focus {
|
||||
border-color: #81c784;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 12px;
|
||||
font-size: 16px; /* 防止iOS缩放 */
|
||||
}
|
||||
`;
|
||||
|
||||
const TextArea = styled.textarea`
|
||||
padding: 10px 12px;
|
||||
border: 2px solid #e0e0e0;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
outline: none;
|
||||
transition: border-color 0.3s ease;
|
||||
resize: vertical;
|
||||
min-height: 80px;
|
||||
font-family: inherit;
|
||||
|
||||
&:focus {
|
||||
border-color: #81c784;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 12px;
|
||||
font-size: 16px;
|
||||
}
|
||||
`;
|
||||
|
||||
const Select = styled.select`
|
||||
padding: 10px 12px;
|
||||
border: 2px solid #e0e0e0;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
outline: none;
|
||||
background: white;
|
||||
cursor: pointer;
|
||||
|
||||
&:focus {
|
||||
border-color: #81c784;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 12px;
|
||||
font-size: 16px;
|
||||
}
|
||||
`;
|
||||
|
||||
const TagsInput = styled.div`
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
padding: 8px;
|
||||
border: 2px solid #e0e0e0;
|
||||
border-radius: 8px;
|
||||
min-height: 45px;
|
||||
align-items: center;
|
||||
|
||||
&:focus-within {
|
||||
border-color: #81c784;
|
||||
}
|
||||
`;
|
||||
|
||||
const Tag = styled.span`
|
||||
background: #e8f5e8;
|
||||
color: #2e7d32;
|
||||
padding: 4px 8px;
|
||||
border-radius: 12px;
|
||||
font-size: 0.8rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
`;
|
||||
|
||||
const TagRemove = styled.button`
|
||||
background: none;
|
||||
border: none;
|
||||
color: #2e7d32;
|
||||
cursor: pointer;
|
||||
font-size: 0.8rem;
|
||||
padding: 0;
|
||||
|
||||
&:hover {
|
||||
color: #f44336;
|
||||
}
|
||||
`;
|
||||
|
||||
const TagInput = styled.input`
|
||||
border: none;
|
||||
outline: none;
|
||||
flex: 1;
|
||||
min-width: 100px;
|
||||
padding: 4px;
|
||||
font-size: 14px;
|
||||
`;
|
||||
|
||||
const PlatformSelector = styled.div`
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
`;
|
||||
|
||||
const PlatformCheckbox = styled.label`
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
padding: 8px 12px;
|
||||
border: 2px solid #e0e0e0;
|
||||
border-radius: 8px;
|
||||
transition: all 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
border-color: #81c784;
|
||||
background: #f8f9fa;
|
||||
}
|
||||
|
||||
input:checked + & {
|
||||
border-color: #81c784;
|
||||
background: #e8f5e8;
|
||||
}
|
||||
`;
|
||||
|
||||
const FileUploadSection = styled.div`
|
||||
border: 2px dashed #e0e0e0;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
transition: border-color 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
border-color: #81c784;
|
||||
}
|
||||
|
||||
&.dragover {
|
||||
border-color: #81c784;
|
||||
background: #f8f9fa;
|
||||
}
|
||||
`;
|
||||
|
||||
const FileInput = styled.input`
|
||||
display: none;
|
||||
`;
|
||||
|
||||
const FileList = styled.div`
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
|
||||
gap: 10px;
|
||||
margin-top: 15px;
|
||||
`;
|
||||
|
||||
const FileItem = styled.div`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 10px;
|
||||
border: 1px solid #e0e0e0;
|
||||
border-radius: 8px;
|
||||
position: relative;
|
||||
cursor: ${props => props.selectable ? 'pointer' : 'default'};
|
||||
|
||||
${props => props.isCover && `
|
||||
border: 2px solid #81c784;
|
||||
background: #f8f9fa;
|
||||
`}
|
||||
|
||||
&:hover {
|
||||
${props => props.selectable && `
|
||||
border-color: #81c784;
|
||||
background: #f8f9fa;
|
||||
`}
|
||||
}
|
||||
`;
|
||||
|
||||
const FilePreview = styled.img`
|
||||
width: 100%;
|
||||
height: 80px;
|
||||
object-fit: cover;
|
||||
border-radius: 4px;
|
||||
margin-bottom: 8px;
|
||||
`;
|
||||
|
||||
const FileName = styled.span`
|
||||
font-size: 0.8rem;
|
||||
color: #666;
|
||||
text-align: center;
|
||||
word-break: break-all;
|
||||
`;
|
||||
|
||||
const FileDeleteButton = styled.button`
|
||||
position: absolute;
|
||||
top: 5px;
|
||||
right: 5px;
|
||||
background: #f44336;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
`;
|
||||
|
||||
const ErrorMessage = styled.div`
|
||||
background: #ffebee;
|
||||
color: #c62828;
|
||||
padding: 15px;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 20px;
|
||||
`;
|
||||
|
||||
const SuccessMessage = styled.div`
|
||||
background: #e8f5e8;
|
||||
color: #2e7d32;
|
||||
padding: 15px;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 20px;
|
||||
`;
|
||||
|
||||
|
||||
|
||||
const WorkEditor = ({ work, onClose }) => {
|
||||
const [formData, setFormData] = useState({
|
||||
作品ID: '',
|
||||
作品作品: '',
|
||||
作品描述: '',
|
||||
作者: '树萌芽',
|
||||
作品版本号: '1.0.0',
|
||||
作品分类: '其他',
|
||||
作品标签: [],
|
||||
支持平台: [],
|
||||
作品截图: [],
|
||||
作品视频: [],
|
||||
作品封面: '',
|
||||
文件名称: {}
|
||||
});
|
||||
|
||||
const [newTag, setNewTag] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState(null);
|
||||
const [success, setSuccess] = useState(null);
|
||||
const [uploadItems, setUploadItems] = useState({});
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [showUploadModal, setShowUploadModal] = useState(false);
|
||||
|
||||
const platforms = ['Windows', 'Android', 'Linux', 'iOS', 'macOS'];
|
||||
const categories = ['游戏', '工具', '应用', '网站', '其他'];
|
||||
|
||||
useEffect(() => {
|
||||
if (work) {
|
||||
setFormData({
|
||||
...work,
|
||||
作品标签: work.作品标签 || [],
|
||||
支持平台: work.支持平台 || [],
|
||||
作品截图: work.作品截图 || [],
|
||||
作品视频: work.作品视频 || [],
|
||||
文件名称: work.文件名称 || {}
|
||||
});
|
||||
}
|
||||
}, [work]);
|
||||
|
||||
const handleInputChange = (field, value) => {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[field]: value
|
||||
}));
|
||||
setError(null);
|
||||
setSuccess(null);
|
||||
};
|
||||
|
||||
const handleTagAdd = (e) => {
|
||||
if (e.key === 'Enter' && newTag.trim()) {
|
||||
e.preventDefault();
|
||||
if (!formData.作品标签.includes(newTag.trim())) {
|
||||
handleInputChange('作品标签', [...formData.作品标签, newTag.trim()]);
|
||||
}
|
||||
setNewTag('');
|
||||
}
|
||||
};
|
||||
|
||||
const handleTagRemove = (tagToRemove) => {
|
||||
handleInputChange('作品标签', formData.作品标签.filter(tag => tag !== tagToRemove));
|
||||
};
|
||||
|
||||
const handlePlatformChange = (platform, checked) => {
|
||||
if (checked) {
|
||||
handleInputChange('支持平台', [...formData.支持平台, platform]);
|
||||
} else {
|
||||
handleInputChange('支持平台', formData.支持平台.filter(p => p !== platform));
|
||||
// 移除该平台的文件名称
|
||||
const newFileNames = { ...formData.文件名称 };
|
||||
delete newFileNames[platform];
|
||||
handleInputChange('文件名称', newFileNames);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileUpload = async (files, fileType, platform = null) => {
|
||||
if (!formData.作品ID) {
|
||||
setError('请先保存作品基本信息后再上传文件');
|
||||
return;
|
||||
}
|
||||
|
||||
setUploading(true);
|
||||
setError(null);
|
||||
setUploadItems({});
|
||||
setShowUploadModal(true);
|
||||
|
||||
try {
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const file = files[i];
|
||||
console.log(`上传文件: ${file.name}, 作品ID: ${formData.作品ID}, 文件类型: ${fileType}, 平台: ${platform}`);
|
||||
|
||||
// 显示文件大小
|
||||
const fileSizeMB = (file.size / (1024 * 1024)).toFixed(1);
|
||||
console.log(`文件大小: ${fileSizeMB}MB`);
|
||||
|
||||
// 设置当前文件的进度信息
|
||||
const fileKey = `${file.name}_${i}`;
|
||||
|
||||
// 初始化上传项目
|
||||
setUploadItems(prev => ({
|
||||
...prev,
|
||||
[fileKey]: {
|
||||
fileName: file.name,
|
||||
fileSize: file.size,
|
||||
progress: 0,
|
||||
uploaded: 0,
|
||||
speed: 0,
|
||||
status: 'uploading'
|
||||
}
|
||||
}));
|
||||
|
||||
const response = await adminUploadFile(
|
||||
formData.作品ID,
|
||||
fileType,
|
||||
file,
|
||||
platform,
|
||||
(progressInfo) => {
|
||||
setUploadItems(prev => ({
|
||||
...prev,
|
||||
[fileKey]: {
|
||||
...prev[fileKey],
|
||||
...progressInfo,
|
||||
status: 'uploading'
|
||||
}
|
||||
}));
|
||||
}
|
||||
);
|
||||
console.log('上传响应:', response);
|
||||
|
||||
if (response.success) {
|
||||
// 更新文件列表
|
||||
if (fileType === 'image') {
|
||||
const newImages = [...formData.作品截图, response.filename];
|
||||
handleInputChange('作品截图', newImages);
|
||||
if (!formData.作品封面) {
|
||||
handleInputChange('作品封面', response.filename);
|
||||
}
|
||||
} else if (fileType === 'video') {
|
||||
handleInputChange('作品视频', [...formData.作品视频, response.filename]);
|
||||
} else if (fileType === 'platform' && platform) {
|
||||
const newFileNames = { ...formData.文件名称 };
|
||||
newFileNames[platform] = newFileNames[platform] || [];
|
||||
newFileNames[platform].push(response.filename);
|
||||
handleInputChange('文件名称', newFileNames);
|
||||
}
|
||||
setSuccess(`文件上传成功: ${response.filename} (${fileSizeMB}MB)`);
|
||||
|
||||
// 标记该文件上传完成
|
||||
setUploadItems(prev => ({
|
||||
...prev,
|
||||
[fileKey]: {
|
||||
...prev[fileKey],
|
||||
progress: 100,
|
||||
status: 'completed'
|
||||
}
|
||||
}));
|
||||
} else {
|
||||
setError(`文件上传失败: ${response.message}`);
|
||||
|
||||
// 标记该文件上传失败
|
||||
setUploadItems(prev => ({
|
||||
...prev,
|
||||
[fileKey]: {
|
||||
...prev[fileKey],
|
||||
status: 'error'
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('文件上传失败:', error);
|
||||
|
||||
// 标记所有上传项目为失败
|
||||
setUploadItems(prev => {
|
||||
const updated = { ...prev };
|
||||
Object.keys(updated).forEach(key => {
|
||||
if (updated[key].status === 'uploading') {
|
||||
updated[key].status = 'error';
|
||||
}
|
||||
});
|
||||
return updated;
|
||||
});
|
||||
|
||||
if (error.response) {
|
||||
setError(`文件上传失败: ${error.response.data?.message || error.response.statusText}`);
|
||||
} else {
|
||||
setError(`文件上传失败: ${error.message}`);
|
||||
}
|
||||
} finally {
|
||||
setUploading(false);
|
||||
|
||||
// 3秒后自动清理完成的上传项目
|
||||
setTimeout(() => {
|
||||
setUploadItems(prev => {
|
||||
const filtered = {};
|
||||
Object.entries(prev).forEach(([key, item]) => {
|
||||
if (item.status === 'uploading' || item.status === 'error') {
|
||||
filtered[key] = item;
|
||||
}
|
||||
});
|
||||
return filtered;
|
||||
});
|
||||
}, 3000);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileDelete = async (filename, fileType, platform = null) => {
|
||||
if (!window.confirm(`确定要删除文件 ${filename} 吗?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await adminDeleteFile(formData.作品ID, fileType, filename, platform);
|
||||
if (response.success) {
|
||||
// 更新文件列表
|
||||
if (fileType === 'image') {
|
||||
const newImages = formData.作品截图.filter(img => img !== filename);
|
||||
handleInputChange('作品截图', newImages);
|
||||
if (formData.作品封面 === filename) {
|
||||
handleInputChange('作品封面', newImages[0] || '');
|
||||
}
|
||||
} else if (fileType === 'video') {
|
||||
handleInputChange('作品视频', formData.作品视频.filter(video => video !== filename));
|
||||
} else if (fileType === 'platform' && platform) {
|
||||
const newFileNames = { ...formData.文件名称 };
|
||||
newFileNames[platform] = newFileNames[platform].filter(file => file !== filename);
|
||||
handleInputChange('文件名称', newFileNames);
|
||||
}
|
||||
setSuccess(`文件删除成功: ${filename}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('文件删除失败:', error);
|
||||
setError('文件删除失败,请稍后重试');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSetCover = (filename) => {
|
||||
handleInputChange('作品封面', filename);
|
||||
setSuccess(`封面设置成功: ${filename}`);
|
||||
};
|
||||
|
||||
const handleDragOver = (e) => {
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = 'copy';
|
||||
};
|
||||
|
||||
const handleDrop = (e, fileType, platform = null) => {
|
||||
e.preventDefault();
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
if (files.length > 0) {
|
||||
handleFileUpload(files, fileType, platform);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!formData.作品ID || !formData.作品作品) {
|
||||
setError('作品ID和作品名称不能为空');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
let response;
|
||||
if (work) {
|
||||
// 更新现有作品
|
||||
response = await adminUpdateWork(formData.作品ID, formData);
|
||||
} else {
|
||||
// 创建新作品
|
||||
response = await adminCreateWork(formData);
|
||||
}
|
||||
|
||||
if (response.success) {
|
||||
setSuccess(work ? '作品更新成功' : '作品创建成功');
|
||||
// 如果是创建新作品,不要自动关闭,让用户可以继续上传文件
|
||||
if (work) {
|
||||
setTimeout(() => {
|
||||
onClose();
|
||||
}, 1500);
|
||||
}
|
||||
} else {
|
||||
setError(response.message);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('保存失败:', error);
|
||||
setError('保存失败,请稍后重试');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<EditorContainer>
|
||||
<EditorHeader>
|
||||
<EditorTitle>{work ? '编辑作品' : '添加新作品'}</EditorTitle>
|
||||
<ButtonGroup>
|
||||
<Button variant="success" onClick={handleSave} disabled={loading || uploading}>
|
||||
{loading ? '保存中...' : '保存'}
|
||||
</Button>
|
||||
<Button onClick={onClose} disabled={uploading}>
|
||||
返回
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
</EditorHeader>
|
||||
|
||||
{error && <ErrorMessage>{error}</ErrorMessage>}
|
||||
{success && <SuccessMessage>{success}</SuccessMessage>}
|
||||
|
||||
|
||||
|
||||
{/* 基本信息 */}
|
||||
<FormSection>
|
||||
<SectionTitle>基本信息</SectionTitle>
|
||||
<FormGrid>
|
||||
<FormGroup>
|
||||
<Label htmlFor="workId">作品ID *</Label>
|
||||
<Input
|
||||
id="workId"
|
||||
type="text"
|
||||
value={formData.作品ID}
|
||||
onChange={(e) => handleInputChange('作品ID', e.target.value)}
|
||||
placeholder="唯一标识符,只能包含字母、数字、下划线"
|
||||
disabled={!!work} // 编辑时不能修改ID
|
||||
/>
|
||||
</FormGroup>
|
||||
|
||||
<FormGroup>
|
||||
<Label htmlFor="workName">作品名称 *</Label>
|
||||
<Input
|
||||
id="workName"
|
||||
type="text"
|
||||
value={formData.作品作品}
|
||||
onChange={(e) => handleInputChange('作品作品', e.target.value)}
|
||||
placeholder="作品的显示名称"
|
||||
/>
|
||||
</FormGroup>
|
||||
|
||||
<FormGroup>
|
||||
<Label htmlFor="author">作者</Label>
|
||||
<Input
|
||||
id="author"
|
||||
type="text"
|
||||
value={formData.作者}
|
||||
onChange={(e) => handleInputChange('作者', e.target.value)}
|
||||
placeholder="作者名称"
|
||||
/>
|
||||
</FormGroup>
|
||||
|
||||
<FormGroup>
|
||||
<Label htmlFor="version">版本号</Label>
|
||||
<Input
|
||||
id="version"
|
||||
type="text"
|
||||
value={formData.作品版本号}
|
||||
onChange={(e) => handleInputChange('作品版本号', e.target.value)}
|
||||
placeholder="如: 1.0.0"
|
||||
/>
|
||||
</FormGroup>
|
||||
|
||||
<FormGroup>
|
||||
<Label htmlFor="category">分类</Label>
|
||||
<Select
|
||||
id="category"
|
||||
value={formData.作品分类}
|
||||
onChange={(e) => handleInputChange('作品分类', e.target.value)}
|
||||
>
|
||||
{categories.map(cat => (
|
||||
<option key={cat} value={cat}>{cat}</option>
|
||||
))}
|
||||
</Select>
|
||||
</FormGroup>
|
||||
</FormGrid>
|
||||
|
||||
<FormGroup style={{ marginTop: '20px' }}>
|
||||
<Label htmlFor="description">作品描述</Label>
|
||||
<TextArea
|
||||
id="description"
|
||||
value={formData.作品描述}
|
||||
onChange={(e) => handleInputChange('作品描述', e.target.value)}
|
||||
placeholder="详细描述作品的功能和特点"
|
||||
rows={4}
|
||||
/>
|
||||
</FormGroup>
|
||||
|
||||
<FormGroup style={{ marginTop: '20px' }}>
|
||||
<Label>作品标签</Label>
|
||||
<TagsInput>
|
||||
{formData.作品标签.map((tag, index) => (
|
||||
<Tag key={index}>
|
||||
{tag}
|
||||
<TagRemove onClick={() => handleTagRemove(tag)}>×</TagRemove>
|
||||
</Tag>
|
||||
))}
|
||||
<TagInput
|
||||
value={newTag}
|
||||
onChange={(e) => setNewTag(e.target.value)}
|
||||
onKeyDown={handleTagAdd}
|
||||
placeholder="输入标签,按回车添加"
|
||||
/>
|
||||
</TagsInput>
|
||||
</FormGroup>
|
||||
|
||||
<FormGroup style={{ marginTop: '20px' }}>
|
||||
<Label>支持平台</Label>
|
||||
<PlatformSelector>
|
||||
{platforms.map(platform => (
|
||||
<PlatformCheckbox key={platform}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={formData.支持平台.includes(platform)}
|
||||
onChange={(e) => handlePlatformChange(platform, e.target.checked)}
|
||||
/>
|
||||
{platform}
|
||||
</PlatformCheckbox>
|
||||
))}
|
||||
</PlatformSelector>
|
||||
</FormGroup>
|
||||
</FormSection>
|
||||
|
||||
{/* 文件管理 */}
|
||||
{formData.作品ID && (
|
||||
<>
|
||||
{/* 作品截图 */}
|
||||
<FormSection>
|
||||
<SectionTitle>作品截图</SectionTitle>
|
||||
<FileUploadSection
|
||||
onDragOver={handleDragOver}
|
||||
onDrop={(e) => handleDrop(e, 'image')}
|
||||
>
|
||||
<p>拖拽图片文件到这里或点击选择文件</p>
|
||||
<p style={{ fontSize: '0.8rem', color: '#666', marginTop: '8px' }}>
|
||||
支持 PNG、JPG、JPEG、GIF 格式,支持批量选择多张图片
|
||||
</p>
|
||||
<p style={{ fontSize: '0.7rem', color: '#999', marginTop: '4px' }}>
|
||||
单个文件最大支持 5000MB (5GB)
|
||||
</p>
|
||||
<FileInput
|
||||
id="imageUpload"
|
||||
type="file"
|
||||
multiple
|
||||
accept="image/*"
|
||||
onChange={(e) => handleFileUpload(Array.from(e.target.files), 'image')}
|
||||
/>
|
||||
<Button
|
||||
onClick={() => document.getElementById('imageUpload').click()}
|
||||
style={{ marginTop: '10px' }}
|
||||
disabled={uploading}
|
||||
>
|
||||
{uploading ? '上传中...' : '选择图片 (支持多选)'}
|
||||
</Button>
|
||||
</FileUploadSection>
|
||||
|
||||
{formData.作品截图.length > 0 && (
|
||||
<div>
|
||||
<h4 style={{ marginBottom: '10px', color: '#2e7d32' }}>
|
||||
已上传图片 (点击图片设置为封面)
|
||||
</h4>
|
||||
<FileList>
|
||||
{formData.作品截图.map((image, index) => (
|
||||
<FileItem
|
||||
key={index}
|
||||
selectable={true}
|
||||
isCover={formData.作品封面 === image}
|
||||
onClick={() => handleSetCover(image)}
|
||||
>
|
||||
<FileDeleteButton onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleFileDelete(image, 'image');
|
||||
}}>
|
||||
×
|
||||
</FileDeleteButton>
|
||||
<FilePreview
|
||||
src={`${getApiBaseUrl()}/api/image/${formData.作品ID}/${image}`}
|
||||
alt={image}
|
||||
onError={(e) => {
|
||||
e.target.style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
<FileName>{image}</FileName>
|
||||
{formData.作品封面 === image && (
|
||||
<span style={{
|
||||
fontSize: '0.7rem',
|
||||
color: '#4caf50',
|
||||
fontWeight: 'bold',
|
||||
marginTop: '4px',
|
||||
padding: '2px 6px',
|
||||
background: '#e8f5e8',
|
||||
borderRadius: '4px'
|
||||
}}>
|
||||
当前封面
|
||||
</span>
|
||||
)}
|
||||
</FileItem>
|
||||
))}
|
||||
</FileList>
|
||||
</div>
|
||||
)}
|
||||
</FormSection>
|
||||
|
||||
{/* 作品视频 */}
|
||||
<FormSection>
|
||||
<SectionTitle>作品视频</SectionTitle>
|
||||
<FileUploadSection>
|
||||
<p>上传作品演示视频</p>
|
||||
<p style={{ fontSize: '0.8rem', color: '#666', marginTop: '8px' }}>
|
||||
支持 MP4、AVI、MOV 格式
|
||||
</p>
|
||||
<p style={{ fontSize: '0.7rem', color: '#999', marginTop: '4px' }}>
|
||||
单个文件最大支持 5000MB (5GB)
|
||||
</p>
|
||||
<FileInput
|
||||
id="videoUpload"
|
||||
type="file"
|
||||
multiple
|
||||
accept="video/*"
|
||||
onChange={(e) => handleFileUpload(Array.from(e.target.files), 'video')}
|
||||
/>
|
||||
<Button
|
||||
onClick={() => document.getElementById('videoUpload').click()}
|
||||
style={{ marginTop: '10px' }}
|
||||
disabled={uploading}
|
||||
>
|
||||
{uploading ? '上传中...' : '选择视频'}
|
||||
</Button>
|
||||
</FileUploadSection>
|
||||
|
||||
{formData.作品视频.length > 0 && (
|
||||
<FileList>
|
||||
{formData.作品视频.map((video, index) => (
|
||||
<FileItem key={index}>
|
||||
<FileDeleteButton onClick={() => handleFileDelete(video, 'video')}>
|
||||
×
|
||||
</FileDeleteButton>
|
||||
<div style={{
|
||||
width: '100%',
|
||||
height: '80px',
|
||||
background: '#f0f0f0',
|
||||
borderRadius: '4px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
marginBottom: '8px'
|
||||
}}>
|
||||
🎬
|
||||
</div>
|
||||
<FileName>{video}</FileName>
|
||||
</FileItem>
|
||||
))}
|
||||
</FileList>
|
||||
)}
|
||||
</FormSection>
|
||||
|
||||
{/* 平台文件 */}
|
||||
{formData.支持平台.map(platform => (
|
||||
<FormSection key={platform}>
|
||||
<SectionTitle>{platform} 平台文件</SectionTitle>
|
||||
<FileUploadSection>
|
||||
<p>上传 {platform} 平台的应用文件</p>
|
||||
<p style={{ fontSize: '0.8rem', color: '#666', marginTop: '8px' }}>
|
||||
支持 ZIP、RAR、APK、EXE、DMG 等格式
|
||||
</p>
|
||||
<p style={{ fontSize: '0.7rem', color: '#999', marginTop: '4px' }}>
|
||||
单个文件最大支持 5000MB (5GB)
|
||||
</p>
|
||||
<FileInput
|
||||
id={`${platform}Upload`}
|
||||
type="file"
|
||||
multiple
|
||||
onChange={(e) => handleFileUpload(Array.from(e.target.files), 'platform', platform)}
|
||||
/>
|
||||
<Button
|
||||
onClick={() => document.getElementById(`${platform}Upload`).click()}
|
||||
style={{ marginTop: '10px' }}
|
||||
disabled={uploading}
|
||||
>
|
||||
{uploading ? '上传中...' : '选择文件'}
|
||||
</Button>
|
||||
</FileUploadSection>
|
||||
|
||||
{formData.文件名称[platform] && formData.文件名称[platform].length > 0 && (
|
||||
<FileList>
|
||||
{formData.文件名称[platform].map((file, index) => (
|
||||
<FileItem key={index}>
|
||||
<FileDeleteButton onClick={() => handleFileDelete(file, 'platform', platform)}>
|
||||
×
|
||||
</FileDeleteButton>
|
||||
<div style={{
|
||||
width: '100%',
|
||||
height: '80px',
|
||||
background: '#f0f0f0',
|
||||
borderRadius: '4px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
marginBottom: '8px'
|
||||
}}>
|
||||
📦
|
||||
</div>
|
||||
<FileName>{file}</FileName>
|
||||
</FileItem>
|
||||
))}
|
||||
</FileList>
|
||||
)}
|
||||
</FormSection>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* 上传进度弹窗 */}
|
||||
<UploadProgressModal
|
||||
isOpen={showUploadModal}
|
||||
onClose={() => setShowUploadModal(false)}
|
||||
uploadItems={uploadItems}
|
||||
canClose={!uploading}
|
||||
/>
|
||||
</EditorContainer>
|
||||
);
|
||||
};
|
||||
|
||||
export default WorkEditor;
|
||||
10
frontend/src/index.js
Normal file
10
frontend/src/index.js
Normal file
@@ -0,0 +1,10 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import App from './App';
|
||||
|
||||
const root = ReactDOM.createRoot(document.getElementById('root'));
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
);
|
||||
236
frontend/src/services/adminApi.js
Normal file
236
frontend/src/services/adminApi.js
Normal file
@@ -0,0 +1,236 @@
|
||||
import axios from 'axios';
|
||||
|
||||
// 配置API基础URL
|
||||
const getApiBaseUrl = () => {
|
||||
// 如果设置了环境变量,优先使用
|
||||
if (process.env.REACT_APP_API_URL) {
|
||||
return process.env.REACT_APP_API_URL;
|
||||
}
|
||||
|
||||
// 生产环境使用相对路径(需要代理)或绝对路径
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
// 如果前后端部署在同一域名下,使用相对路径
|
||||
return '/api';
|
||||
// 如果后端部署在不同地址,请修改为后端的完整URL
|
||||
// return 'http://your-backend-domain.com:5000/api';
|
||||
}
|
||||
|
||||
// 开发环境使用localhost
|
||||
return 'http://localhost:5000/api';
|
||||
};
|
||||
|
||||
const API_BASE_URL = getApiBaseUrl();
|
||||
|
||||
const adminApi = axios.create({
|
||||
baseURL: API_BASE_URL,
|
||||
timeout: 30000,
|
||||
});
|
||||
|
||||
// 管理员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;
|
||||
69
frontend/src/services/api.js
Normal file
69
frontend/src/services/api.js
Normal file
@@ -0,0 +1,69 @@
|
||||
import axios from 'axios';
|
||||
|
||||
// 配置API基础URL
|
||||
const getApiBaseUrl = () => {
|
||||
// 如果设置了环境变量,优先使用
|
||||
if (process.env.REACT_APP_API_URL) {
|
||||
return process.env.REACT_APP_API_URL;
|
||||
}
|
||||
|
||||
// 生产环境使用相对路径(需要代理)或绝对路径
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
// 如果前后端部署在同一域名下,使用相对路径
|
||||
return '/api';
|
||||
// 如果后端部署在不同地址,请修改为后端的完整URL
|
||||
// return 'http://your-backend-domain.com:5000/api';
|
||||
}
|
||||
|
||||
// 开发环境使用localhost
|
||||
return 'http://localhost:5000/api';
|
||||
};
|
||||
|
||||
const API_BASE_URL = getApiBaseUrl();
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: API_BASE_URL,
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
// 获取网站设置
|
||||
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;
|
||||
6
start_backend.bat
Normal file
6
start_backend.bat
Normal file
@@ -0,0 +1,6 @@
|
||||
@echo off
|
||||
echo 启动树萌芽の作品集后端服务...
|
||||
cd backend
|
||||
python app.py
|
||||
pause
|
||||
python -m pip install -r requirements.txt
|
||||
6
start_frontend.bat
Normal file
6
start_frontend.bat
Normal file
@@ -0,0 +1,6 @@
|
||||
@echo off
|
||||
echo 启动树萌芽の作品集前端服务...
|
||||
cd frontend
|
||||
npm start
|
||||
pause
|
||||
npm install
|
||||
8
vercel.json
Normal file
8
vercel.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"rewrites": [
|
||||
{
|
||||
"source": "/(.*)",
|
||||
"destination": "/index.html"
|
||||
}
|
||||
]
|
||||
}
|
||||
41
初始要求.md
Normal file
41
初始要求.md
Normal file
@@ -0,0 +1,41 @@
|
||||
开发一个名为 树萌芽の作品集 网站,具体要求如下:
|
||||
|
||||
1. 前端架构:
|
||||
- 采用模块化架构避免单个文件过大,使用React最新版开发 放在frontend目录
|
||||
- 确保代码结构清晰,便于后期扩展维护
|
||||
- 先保证简单展示就可以了
|
||||
|
||||
2. 响应式设计:
|
||||
- 分别编写手机端和电脑端的专用代码
|
||||
- 优先保证手机端用户体验
|
||||
|
||||
3. 后端开发:
|
||||
- 使用Python 3.13.2开发
|
||||
- 后端代码集中存放在独立文件夹backend目录
|
||||
- 先保证能正确读取解析已有的作品,完成最核心的作品下载功能
|
||||
|
||||
4. 后台管理系统:
|
||||
- 开发简洁但功能完整的作品管理界面
|
||||
- 功能包括:
|
||||
* 上传多平台作品文件(Windows/Android/Linux)
|
||||
* 设置作品元数据:名称、版本号、唯一ID
|
||||
* 上传作品图片(可选)并设置首页展示图
|
||||
* 上传作品视频(可选)
|
||||
* 编辑作品信息:作者、标签、分类、介绍
|
||||
|
||||
5. 数据存储:
|
||||
- 创建setting.json存储网站基础配置
|
||||
- 使用work_config.json单独存储每个作品的信息
|
||||
|
||||
6. 前端设计:
|
||||
- 采用淡绿色清新可爱的配色方案
|
||||
- 首页展示作品卡片包含:
|
||||
* 作品名称(标题)
|
||||
* 简短介绍
|
||||
* 标签分类
|
||||
* 上传/更新时间
|
||||
* 支持平台
|
||||
* 版本信息
|
||||
* 作者信息
|
||||
* 作品截图
|
||||
- 实现作品搜索功能@config/ @settings.json @works/ @aicodevartool/ @Windows/ @style.css @主题配色参考/
|
||||
112
生产环境前端nginx配置_修复版.txt
Normal file
112
生产环境前端nginx配置_修复版.txt
Normal file
@@ -0,0 +1,112 @@
|
||||
server
|
||||
{
|
||||
listen 80;
|
||||
listen 443 ssl;
|
||||
listen 443 quic;
|
||||
http2 on;
|
||||
server_name work.shumengya.top;
|
||||
index index.html index.htm default.htm default.html;
|
||||
root /shumengya/树萌芽的作品集网站/frontend/build;
|
||||
|
||||
# 大文件上传支持
|
||||
client_max_body_size 500M;
|
||||
client_body_timeout 300s;
|
||||
client_header_timeout 300s;
|
||||
send_timeout 300s;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
#CERT-APPLY-CHECK--START
|
||||
# 用于SSL证书申请时的文件验证相关配置 -- 请勿删除并保持这段设置在优先级高的位置
|
||||
include /www/server/panel/vhost/nginx/well-known/work.shumengya.top.conf;
|
||||
#CERT-APPLY-CHECK--END
|
||||
|
||||
#SSL-START SSL相关配置,请勿删除或修改下一行带注释的404规则
|
||||
#error_page 404/404.html;
|
||||
#HTTP_TO_HTTPS_START
|
||||
set $isRedcert 1;
|
||||
if ($server_port != 443) {
|
||||
set $isRedcert 2;
|
||||
}
|
||||
if ( $uri ~ /\.well-known/ ) {
|
||||
set $isRedcert 1;
|
||||
}
|
||||
if ($isRedcert != 1) {
|
||||
rewrite ^(/.*)$ https://$host$1 permanent;
|
||||
}
|
||||
#HTTP_TO_HTTPS_END
|
||||
ssl_certificate /www/server/panel/vhost/cert/work.shumengya.top/fullchain.pem;
|
||||
ssl_certificate_key /www/server/panel/vhost/cert/work.shumengya.top/privkey.pem;
|
||||
ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
|
||||
ssl_prefer_server_ciphers on;
|
||||
ssl_session_tickets on;
|
||||
ssl_session_cache shared:SSL:10m;
|
||||
ssl_session_timeout 10m;
|
||||
add_header Strict-Transport-Security "max-age=31536000";
|
||||
add_header Alt-Svc 'quic=":443"; h3=":443"; h3-29=":443"; h3-27=":443";h3-25=":443"; h3-T050=":443"; h3-Q050=":443";h3-Q049=":443";h3-Q048=":443"; h3-Q046=":443"; h3-Q043=":443"';
|
||||
error_page 497 https://$host$request_uri;
|
||||
|
||||
#SSL-END
|
||||
|
||||
#ERROR-PAGE-START 错误页配置,可以注释、删除或修改
|
||||
#error_page 404 /404.html;
|
||||
#error_page 502 /502.html;
|
||||
#ERROR-PAGE-END
|
||||
|
||||
#REWRITE-START URL重写规则引用,修改后将导致面板设置的伪静态规则失效
|
||||
include /www/server/panel/vhost/rewrite/html_work.shumengya.top.conf;
|
||||
#REWRITE-END
|
||||
|
||||
#禁止访问的文件或目录
|
||||
location ~ ^/(\.user.ini|\.htaccess|\.git|\.env|\.svn|\.project|LICENSE|README.md)
|
||||
{
|
||||
return 404;
|
||||
}
|
||||
|
||||
#一键申请SSL证书验证目录相关设置
|
||||
location ~ \.well-known{
|
||||
allow all;
|
||||
}
|
||||
|
||||
#禁止在证书验证目录放入敏感文件
|
||||
if ( $uri ~ "^/\.well-known/.*\.(php|jsp|py|js|css|lua|ts|go|zip|tar\.gz|rar|7z|sql|bak)$" ) {
|
||||
return 403;
|
||||
}
|
||||
|
||||
# SPA路由支持 - 关键添加部分
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
|
||||
# 添加安全头
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-XSS-Protection "1; mode=block" always;
|
||||
|
||||
# 处理预检请求
|
||||
if ($request_method = 'OPTIONS') {
|
||||
add_header 'Access-Control-Allow-Origin' '*';
|
||||
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
|
||||
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
|
||||
add_header 'Access-Control-Max-Age' 86400;
|
||||
add_header 'Content-Type' 'text/plain charset=UTF-8';
|
||||
add_header 'Content-Length' 0;
|
||||
return 204;
|
||||
}
|
||||
}
|
||||
|
||||
location ~ .*\\.(gif|jpg|jpeg|png|bmp|swf)$
|
||||
{
|
||||
expires 30d;
|
||||
error_log /dev/null;
|
||||
access_log /dev/null;
|
||||
}
|
||||
|
||||
location ~ .*\\.(js|css)?$
|
||||
{
|
||||
expires 12h;
|
||||
error_log /dev/null;
|
||||
access_log /dev/null;
|
||||
}
|
||||
access_log /www/wwwlogs/work.shumengya.top.log;
|
||||
error_log /www/wwwlogs/work.shumengya.top.error.log;
|
||||
}
|
||||
Reference in New Issue
Block a user