Merge pull request 'feature/网络管理和Web部署系统' (#2) from feature/网络管理和Web部署系统 into main
Reviewed-on: datawhale/whale-town-front#2
29
README.md
@@ -14,7 +14,7 @@
|
||||
|
||||
### 环境要求
|
||||
- [Godot Engine 4.5+](https://godotengine.org/download)
|
||||
- Python 3.7+ (用于API测试)
|
||||
- Python 3.7+ (用于API测试和Web服务器)
|
||||
|
||||
### 运行项目
|
||||
```bash
|
||||
@@ -29,6 +29,19 @@ cd whale-town
|
||||
python tests/api/simple_api_test.py
|
||||
```
|
||||
|
||||
### Web版本部署
|
||||
```bash
|
||||
# Windows用户
|
||||
scripts\build_web.bat # 导出Web版本
|
||||
scripts\serve_web.bat # 启动本地测试服务器
|
||||
|
||||
# Linux/macOS用户
|
||||
./scripts/build_web.sh # 导出Web版本
|
||||
./scripts/serve_web.sh # 启动本地测试服务器
|
||||
```
|
||||
|
||||
详细部署指南请查看: [Web部署完整指南](docs/web_deployment_guide.md)
|
||||
|
||||
## 🏗️ 项目架构
|
||||
|
||||
### 核心设计理念
|
||||
@@ -52,6 +65,10 @@ whaleTown/
|
||||
├── 📝 scripts/ # 业务逻辑脚本
|
||||
│ ├── scenes/ # 场景脚本
|
||||
│ ├── network/ # 网络相关
|
||||
│ ├── build_web.bat # Windows Web导出脚本
|
||||
│ ├── build_web.sh # Linux/macOS Web导出脚本
|
||||
│ ├── serve_web.bat # Windows 本地服务器
|
||||
│ ├── serve_web.sh # Linux/macOS 本地服务器
|
||||
│ └── ui/ # UI组件脚本
|
||||
├── 🧩 module/ # 可复用模块
|
||||
│ ├── UI/ # UI组件模块
|
||||
@@ -82,6 +99,8 @@ whaleTown/
|
||||
└── 📚 docs/ # 项目文档
|
||||
├── auth/ # 认证相关文档
|
||||
├── api-documentation.md # API接口文档
|
||||
├── web_deployment_guide.md # Web部署完整指南
|
||||
├── web_deployment_changelog.md # Web部署更新日志
|
||||
├── project_structure.md # 项目结构说明
|
||||
├── naming_convention.md # 命名规范
|
||||
├── code_comment_guide.md # 代码注释规范
|
||||
@@ -117,6 +136,13 @@ EventSystem.connect_event("player_died", _on_player_died)
|
||||
- **GitHub OAuth** - 第三方登录集成
|
||||
- **错误处理** - 完整的错误提示和频率限制
|
||||
|
||||
### 🌐 Web版本部署
|
||||
- **自动化导出** - 一键导出Web版本
|
||||
- **本地测试服务器** - 内置HTTP服务器用于测试
|
||||
- **生产环境配置** - 完整的服务器配置指南
|
||||
- **跨平台支持** - Windows、Linux、macOS全平台支持
|
||||
- **性能优化** - 资源压缩和加载优化
|
||||
|
||||
### 🎮 游戏功能
|
||||
- **主场景** - 游戏主界面和菜单系统
|
||||
- **认证场景** - 完整的登录注册界面
|
||||
@@ -164,6 +190,7 @@ git commit -m "docs:更新项目文档"
|
||||
- 📝 [命名规范](docs/naming_convention.md) - 详细的命名规则
|
||||
- 💬 [代码注释规范](docs/code_comment_guide.md) - 注释标准和AI辅助指南
|
||||
- 🔀 [Git提交规范](docs/git_commit_guide.md) - 提交信息标准
|
||||
- 🌐 [Web部署指南](docs/web_deployment_guide.md) - 完整的Web部署文档
|
||||
|
||||
### API和测试文档
|
||||
- 🔌 [API接口文档](docs/api-documentation.md) - 完整的API说明和测试指南
|
||||
|
||||
BIN
assets/fonts/msyh.ttc
Normal file
41
assets/fonts/msyh.ttc.import
Normal file
@@ -0,0 +1,41 @@
|
||||
[remap]
|
||||
|
||||
importer="font_data_dynamic"
|
||||
type="FontFile"
|
||||
uid="uid://ce7ujbeobblyr"
|
||||
path="res://.godot/imported/msyh.ttc-1f7944f6d1cff8092894a3525ec5156c.fontdata"
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://assets/fonts/msyh.ttc"
|
||||
dest_files=["res://.godot/imported/msyh.ttc-1f7944f6d1cff8092894a3525ec5156c.fontdata"]
|
||||
|
||||
[params]
|
||||
|
||||
Rendering=null
|
||||
antialiasing=1
|
||||
generate_mipmaps=false
|
||||
disable_embedded_bitmaps=true
|
||||
multichannel_signed_distance_field=false
|
||||
msdf_pixel_range=8
|
||||
msdf_size=48
|
||||
allow_system_fallback=true
|
||||
force_autohinter=false
|
||||
modulate_color_glyphs=false
|
||||
hinting=1
|
||||
subpixel_positioning=4
|
||||
keep_rounding_remainders=true
|
||||
oversampling=0.0
|
||||
Fallbacks=null
|
||||
fallbacks=[]
|
||||
Compress=null
|
||||
compress=false
|
||||
preload=[{
|
||||
"chars": "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()_+-=[]{}|;':\",./<>?`~一二三四五六七八九十百千万亿用户名密码登录注册验证码邮箱小镇鲸鱼欢迎来到开始你的之旅请输入不能为空获取发送忘记返回居民身份确认再次已被使用换个等待分钟后试稍后正在创建账户测试模式生成查看控制台网络连接失败系统维护中升级稍后再试频繁联系管理员禁用审核先邮箱后使用成功进入镇错误或过期未找到存在",
|
||||
"glyphs": [],
|
||||
"name": "Web预加载",
|
||||
"size": Vector2i(16, 0)
|
||||
}]
|
||||
language_support={}
|
||||
script_support={}
|
||||
opentype_features={}
|
||||
BIN
assets/icon/icon144.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
40
assets/icon/icon144.png.import
Normal file
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://bwy5r7soxi76a"
|
||||
path="res://.godot/imported/icon144.png-ae9d1f30a88beaab449c2cad89283dd3.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://assets/icon/icon144.png"
|
||||
dest_files=["res://.godot/imported/icon144.png-ae9d1f30a88beaab449c2cad89283dd3.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
BIN
assets/icon/icon16.png
Normal file
|
After Width: | Height: | Size: 644 B |
40
assets/icon/icon16.png.import
Normal file
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://bqg5e8qn1j74u"
|
||||
path="res://.godot/imported/icon16.png-3099ad8a609f90c382508b9c073ffd76.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://assets/icon/icon16.png"
|
||||
dest_files=["res://.godot/imported/icon16.png-3099ad8a609f90c382508b9c073ffd76.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
BIN
assets/icon/icon180.png
Normal file
|
After Width: | Height: | Size: 18 KiB |
40
assets/icon/icon180.png.import
Normal file
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://drpllpsjdiaex"
|
||||
path="res://.godot/imported/icon180.png-20a9d7b98bfb315dd470e3635f315a17.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://assets/icon/icon180.png"
|
||||
dest_files=["res://.godot/imported/icon180.png-20a9d7b98bfb315dd470e3635f315a17.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
BIN
assets/icon/icon32.png
Normal file
|
After Width: | Height: | Size: 1.7 KiB |
40
assets/icon/icon32.png.import
Normal file
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://dt24j6p0cijqo"
|
||||
path="res://.godot/imported/icon32.png-9a0aceb23d191139c34540a188bf8c91.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://assets/icon/icon32.png"
|
||||
dest_files=["res://.godot/imported/icon32.png-9a0aceb23d191139c34540a188bf8c91.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
BIN
assets/icon/icon512.png
Normal file
|
After Width: | Height: | Size: 78 KiB |
40
assets/icon/icon512.png.import
Normal file
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://dt817lem3dwee"
|
||||
path="res://.godot/imported/icon512.png-1c1c4b424489de87a542c89bec6eb15b.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://assets/icon/icon512.png"
|
||||
dest_files=["res://.godot/imported/icon512.png-1c1c4b424489de87a542c89bec6eb15b.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
BIN
assets/icon/icon64.png
Normal file
|
After Width: | Height: | Size: 4.5 KiB |
40
assets/icon/icon64.png.import
Normal file
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://ci42rd5qe6icl"
|
||||
path="res://.godot/imported/icon64.png-da8a1a20e3bf4dcf06c8ff6c558caaff.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://assets/icon/icon64.png"
|
||||
dest_files=["res://.godot/imported/icon64.png-da8a1a20e3bf4dcf06c8ff6c558caaff.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
BIN
assets/icon/image(1).png
Normal file
|
After Width: | Height: | Size: 150 KiB |
40
assets/icon/image(1).png.import
Normal file
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://cnw6e3wmy0ea4"
|
||||
path="res://.godot/imported/image(1).png-c89cc92103e50aaba40bf38c797be77f.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://assets/icon/image(1).png"
|
||||
dest_files=["res://.godot/imported/image(1).png-c89cc92103e50aaba40bf38c797be77f.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
BIN
assets/icon/image.png
Normal file
|
After Width: | Height: | Size: 91 KiB |
40
assets/icon/image.png.import
Normal file
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://c7v22i1hgo1x6"
|
||||
path="res://.godot/imported/image.png-3f16548595ba9fb08c5e50ef3251d148.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://assets/icon/image.png"
|
||||
dest_files=["res://.godot/imported/image.png-3f16548595ba9fb08c5e50ef3251d148.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
7
assets/ui/chinese_theme.tres
Normal file
@@ -0,0 +1,7 @@
|
||||
[gd_resource type="Theme" load_steps=2 format=3 uid="uid://cp7t8tu7rmyad"]
|
||||
|
||||
[ext_resource type="FontFile" uid="uid://ce7ujbeobblyr" path="res://assets/fonts/msyh.ttc" id="1_ftb5w"]
|
||||
|
||||
[resource]
|
||||
resource_local_to_scene = true
|
||||
default_font = ExtResource("1_ftb5w")
|
||||
BIN
assets/ui/datawhale_logo.png
Normal file
|
After Width: | Height: | Size: 6.7 KiB |
40
assets/ui/datawhale_logo.png.import
Normal file
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://gr7vud1lee4m"
|
||||
path="res://.godot/imported/datawhale_logo.png-ddb5e2c04419eb84cfa8605bcbf64fbd.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://assets/ui/datawhale_logo.png"
|
||||
dest_files=["res://.godot/imported/datawhale_logo.png-ddb5e2c04419eb84cfa8605bcbf64fbd.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
443
core/managers/NetworkManager.gd
Normal file
@@ -0,0 +1,443 @@
|
||||
extends Node
|
||||
|
||||
# 网络请求管理器 - 统一处理所有HTTP请求
|
||||
|
||||
# 信号定义
|
||||
signal request_completed(request_id: String, success: bool, data: Dictionary)
|
||||
signal request_failed(request_id: String, error_type: String, message: String)
|
||||
|
||||
# API配置
|
||||
const API_BASE_URL = "https://whaletownend.xinghangee.icu"
|
||||
const DEFAULT_TIMEOUT = 30.0
|
||||
|
||||
# 请求类型枚举
|
||||
enum RequestType {
|
||||
GET,
|
||||
POST,
|
||||
PUT,
|
||||
DELETE,
|
||||
PATCH
|
||||
}
|
||||
|
||||
# 错误类型枚举
|
||||
enum ErrorType {
|
||||
NETWORK_ERROR, # 网络连接错误
|
||||
TIMEOUT_ERROR, # 请求超时
|
||||
PARSE_ERROR, # JSON解析错误
|
||||
HTTP_ERROR, # HTTP状态码错误
|
||||
BUSINESS_ERROR # 业务逻辑错误
|
||||
}
|
||||
|
||||
# 请求状态
|
||||
class RequestInfo:
|
||||
var id: String
|
||||
var url: String
|
||||
var method: RequestType
|
||||
var headers: PackedStringArray
|
||||
var body: String
|
||||
var timeout: float
|
||||
var start_time: float
|
||||
var http_request: HTTPRequest
|
||||
var callback: Callable
|
||||
|
||||
func _init(request_id: String, request_url: String, request_method: RequestType,
|
||||
request_headers: PackedStringArray = [], request_body: String = "",
|
||||
request_timeout: float = DEFAULT_TIMEOUT):
|
||||
id = request_id
|
||||
url = request_url
|
||||
method = request_method
|
||||
headers = request_headers
|
||||
body = request_body
|
||||
timeout = request_timeout
|
||||
start_time = Time.get_time_dict_from_system().hour * 3600 + Time.get_time_dict_from_system().minute * 60 + Time.get_time_dict_from_system().second
|
||||
|
||||
# 活动请求管理
|
||||
var active_requests: Dictionary = {}
|
||||
var request_counter: int = 0
|
||||
|
||||
func _ready():
|
||||
print("NetworkManager 已初始化")
|
||||
|
||||
# ============ 公共API接口 ============
|
||||
|
||||
# 发送GET请求
|
||||
func get_request(endpoint: String, callback: Callable = Callable(), timeout: float = DEFAULT_TIMEOUT) -> String:
|
||||
return send_request(endpoint, RequestType.GET, [], "", callback, timeout)
|
||||
|
||||
# 发送POST请求
|
||||
func post_request(endpoint: String, data: Dictionary, callback: Callable = Callable(), timeout: float = DEFAULT_TIMEOUT) -> String:
|
||||
var body = JSON.stringify(data)
|
||||
var headers = ["Content-Type: application/json"]
|
||||
return send_request(endpoint, RequestType.POST, headers, body, callback, timeout)
|
||||
|
||||
# 发送PUT请求
|
||||
func put_request(endpoint: String, data: Dictionary, callback: Callable = Callable(), timeout: float = DEFAULT_TIMEOUT) -> String:
|
||||
var body = JSON.stringify(data)
|
||||
var headers = ["Content-Type: application/json"]
|
||||
return send_request(endpoint, RequestType.PUT, headers, body, callback, timeout)
|
||||
|
||||
# 发送DELETE请求
|
||||
func delete_request(endpoint: String, callback: Callable = Callable(), timeout: float = DEFAULT_TIMEOUT) -> String:
|
||||
return send_request(endpoint, RequestType.DELETE, [], "", callback, timeout)
|
||||
|
||||
# ============ 认证相关API ============
|
||||
|
||||
# 用户登录
|
||||
func login(identifier: String, password: String, callback: Callable = Callable()) -> String:
|
||||
var data = {
|
||||
"identifier": identifier,
|
||||
"password": password
|
||||
}
|
||||
return post_request("/auth/login", data, callback)
|
||||
|
||||
# 验证码登录
|
||||
func verification_code_login(identifier: String, verification_code: String, callback: Callable = Callable()) -> String:
|
||||
var data = {
|
||||
"identifier": identifier,
|
||||
"verification_code": verification_code
|
||||
}
|
||||
return post_request("/auth/verification-code-login", data, callback)
|
||||
|
||||
# 发送登录验证码
|
||||
func send_login_verification_code(identifier: String, callback: Callable = Callable()) -> String:
|
||||
var data = {"identifier": identifier}
|
||||
return post_request("/auth/send-login-verification-code", data, callback)
|
||||
|
||||
# 用户注册
|
||||
func register(username: String, password: String, nickname: String, email: String = "",
|
||||
email_verification_code: String = "", callback: Callable = Callable()) -> String:
|
||||
var data = {
|
||||
"username": username,
|
||||
"password": password,
|
||||
"nickname": nickname
|
||||
}
|
||||
|
||||
if email != "":
|
||||
data["email"] = email
|
||||
if email_verification_code != "":
|
||||
data["email_verification_code"] = email_verification_code
|
||||
|
||||
return post_request("/auth/register", data, callback)
|
||||
|
||||
# 发送邮箱验证码
|
||||
func send_email_verification(email: String, callback: Callable = Callable()) -> String:
|
||||
var data = {"email": email}
|
||||
return post_request("/auth/send-email-verification", data, callback)
|
||||
|
||||
# 验证邮箱
|
||||
func verify_email(email: String, verification_code: String, callback: Callable = Callable()) -> String:
|
||||
var data = {
|
||||
"email": email,
|
||||
"verification_code": verification_code
|
||||
}
|
||||
return post_request("/auth/verify-email", data, callback)
|
||||
|
||||
# 获取应用状态
|
||||
func get_app_status(callback: Callable = Callable()) -> String:
|
||||
return get_request("/", callback)
|
||||
|
||||
# 重新发送邮箱验证码
|
||||
func resend_email_verification(email: String, callback: Callable = Callable()) -> String:
|
||||
var data = {"email": email}
|
||||
return post_request("/auth/resend-email-verification", data, callback)
|
||||
|
||||
# 忘记密码 - 发送重置验证码
|
||||
func forgot_password(identifier: String, callback: Callable = Callable()) -> String:
|
||||
var data = {"identifier": identifier}
|
||||
return post_request("/auth/forgot-password", data, callback)
|
||||
|
||||
# 重置密码
|
||||
func reset_password(identifier: String, verification_code: String, new_password: String, callback: Callable = Callable()) -> String:
|
||||
var data = {
|
||||
"identifier": identifier,
|
||||
"verification_code": verification_code,
|
||||
"new_password": new_password
|
||||
}
|
||||
return post_request("/auth/reset-password", data, callback)
|
||||
|
||||
# 修改密码
|
||||
func change_password(user_id: String, old_password: String, new_password: String, callback: Callable = Callable()) -> String:
|
||||
var data = {
|
||||
"user_id": user_id,
|
||||
"old_password": old_password,
|
||||
"new_password": new_password
|
||||
}
|
||||
return put_request("/auth/change-password", data, callback)
|
||||
|
||||
# GitHub OAuth登录
|
||||
func github_login(github_id: String, username: String, nickname: String, email: String, avatar_url: String = "", callback: Callable = Callable()) -> String:
|
||||
var data = {
|
||||
"github_id": github_id,
|
||||
"username": username,
|
||||
"nickname": nickname,
|
||||
"email": email
|
||||
}
|
||||
|
||||
if avatar_url != "":
|
||||
data["avatar_url"] = avatar_url
|
||||
|
||||
return post_request("/auth/github", data, callback)
|
||||
|
||||
# ============ 核心请求处理 ============
|
||||
|
||||
# 发送请求的核心方法
|
||||
func send_request(endpoint: String, method: RequestType, headers: PackedStringArray,
|
||||
body: String, callback: Callable, timeout: float) -> String:
|
||||
# 生成请求ID
|
||||
request_counter += 1
|
||||
var request_id = "req_" + str(request_counter)
|
||||
|
||||
# 构建完整URL
|
||||
var full_url = API_BASE_URL + endpoint
|
||||
|
||||
# 创建HTTPRequest节点
|
||||
var http_request = HTTPRequest.new()
|
||||
add_child(http_request)
|
||||
|
||||
# 设置超时
|
||||
http_request.timeout = timeout
|
||||
|
||||
# 创建请求信息
|
||||
var request_info = RequestInfo.new(request_id, full_url, method, headers, body, timeout)
|
||||
request_info.http_request = http_request
|
||||
request_info.callback = callback
|
||||
|
||||
# 存储请求信息
|
||||
active_requests[request_id] = request_info
|
||||
|
||||
# 连接信号
|
||||
http_request.request_completed.connect(func(result: int, response_code: int, headers: PackedStringArray, body: PackedByteArray):
|
||||
_on_request_completed(request_id, result, response_code, headers, body)
|
||||
)
|
||||
|
||||
# 发送请求
|
||||
var godot_method = _convert_to_godot_method(method)
|
||||
var error = http_request.request(full_url, headers, godot_method, body)
|
||||
|
||||
print("=== 发送网络请求 ===")
|
||||
print("请求ID: ", request_id)
|
||||
print("URL: ", full_url)
|
||||
print("方法: ", RequestType.keys()[method])
|
||||
print("Headers: ", headers)
|
||||
print("Body: ", body if body.length() < 200 else body.substr(0, 200) + "...")
|
||||
print("发送结果: ", error)
|
||||
|
||||
if error != OK:
|
||||
print("请求发送失败,错误代码: ", error)
|
||||
_handle_request_error(request_id, ErrorType.NETWORK_ERROR, "网络请求发送失败: " + str(error))
|
||||
return ""
|
||||
|
||||
return request_id
|
||||
|
||||
# 请求完成回调
|
||||
func _on_request_completed(request_id: String, result: int, response_code: int,
|
||||
headers: PackedStringArray, body: PackedByteArray):
|
||||
print("=== 网络请求完成 ===")
|
||||
print("请求ID: ", request_id)
|
||||
print("结果: ", result)
|
||||
print("状态码: ", response_code)
|
||||
print("响应头: ", headers)
|
||||
|
||||
# 获取请求信息
|
||||
if not active_requests.has(request_id):
|
||||
print("警告: 未找到请求ID ", request_id)
|
||||
return
|
||||
|
||||
var request_info = active_requests[request_id]
|
||||
var response_text = body.get_string_from_utf8()
|
||||
|
||||
print("响应体长度: ", body.size(), " 字节")
|
||||
print("响应内容: ", response_text if response_text.length() < 500 else response_text.substr(0, 500) + "...")
|
||||
|
||||
# 处理网络连接失败
|
||||
if response_code == 0:
|
||||
_handle_request_error(request_id, ErrorType.NETWORK_ERROR, "网络连接失败,请检查网络连接")
|
||||
return
|
||||
|
||||
# 解析JSON响应
|
||||
var json = JSON.new()
|
||||
var parse_result = json.parse(response_text)
|
||||
if parse_result != OK:
|
||||
_handle_request_error(request_id, ErrorType.PARSE_ERROR, "服务器响应格式错误")
|
||||
return
|
||||
|
||||
var response_data = json.data
|
||||
|
||||
# 处理响应
|
||||
_handle_response(request_id, response_code, response_data)
|
||||
|
||||
# 处理响应 - 支持API v1.1.1的状态码
|
||||
func _handle_response(request_id: String, response_code: int, data: Dictionary):
|
||||
var request_info = active_requests[request_id]
|
||||
|
||||
# 检查业务成功标志
|
||||
var success = data.get("success", true) # 默认true保持向后兼容
|
||||
var error_code = data.get("error_code", "")
|
||||
var message = data.get("message", "")
|
||||
|
||||
# 判断请求是否成功
|
||||
var is_success = false
|
||||
|
||||
# HTTP成功状态码且业务成功
|
||||
if (response_code >= 200 and response_code < 300) and success:
|
||||
is_success = true
|
||||
# 特殊情况:206测试模式 - 根据API文档,这是成功的测试模式响应
|
||||
elif response_code == 206 and error_code == "TEST_MODE_ONLY":
|
||||
is_success = true
|
||||
print("🧪 测试模式响应: ", message)
|
||||
# 201创建成功
|
||||
elif response_code == 201:
|
||||
is_success = true
|
||||
|
||||
if is_success:
|
||||
print("✅ 请求成功: ", request_id)
|
||||
# 发送成功信号
|
||||
request_completed.emit(request_id, true, data)
|
||||
|
||||
# 调用回调函数
|
||||
if request_info.callback.is_valid():
|
||||
request_info.callback.call(true, data, {})
|
||||
else:
|
||||
print("❌ 请求失败: ", request_id, " - HTTP:", response_code, " 错误码:", error_code, " 消息:", message)
|
||||
|
||||
# 确定错误类型
|
||||
var error_type = _determine_error_type(response_code, error_code)
|
||||
|
||||
# 发送失败信号
|
||||
request_failed.emit(request_id, ErrorType.keys()[error_type], message)
|
||||
|
||||
# 调用回调函数
|
||||
if request_info.callback.is_valid():
|
||||
var error_info = {
|
||||
"response_code": response_code,
|
||||
"error_code": error_code,
|
||||
"message": message,
|
||||
"error_type": error_type
|
||||
}
|
||||
request_info.callback.call(false, data, error_info)
|
||||
|
||||
# 清理请求
|
||||
_cleanup_request(request_id)
|
||||
|
||||
# 处理请求错误
|
||||
func _handle_request_error(request_id: String, error_type: ErrorType, message: String):
|
||||
print("❌ 请求错误: ", request_id, " - ", message)
|
||||
|
||||
# 发送错误信号
|
||||
request_failed.emit(request_id, ErrorType.keys()[error_type], message)
|
||||
|
||||
# 调用回调函数
|
||||
if active_requests.has(request_id):
|
||||
var request_info = active_requests[request_id]
|
||||
if request_info.callback.is_valid():
|
||||
var error_info = {
|
||||
"error_type": error_type,
|
||||
"message": message
|
||||
}
|
||||
request_info.callback.call(false, {}, error_info)
|
||||
|
||||
# 清理请求
|
||||
_cleanup_request(request_id)
|
||||
|
||||
# 确定错误类型 - 支持更多状态码
|
||||
func _determine_error_type(response_code: int, error_code: String) -> ErrorType:
|
||||
# 根据错误码判断
|
||||
match error_code:
|
||||
"SERVICE_UNAVAILABLE":
|
||||
return ErrorType.BUSINESS_ERROR
|
||||
"TOO_MANY_REQUESTS":
|
||||
return ErrorType.BUSINESS_ERROR
|
||||
"TEST_MODE_ONLY":
|
||||
return ErrorType.BUSINESS_ERROR
|
||||
"SEND_EMAIL_VERIFICATION_FAILED", "REGISTER_FAILED":
|
||||
# 这些可能是409冲突或其他业务错误
|
||||
return ErrorType.BUSINESS_ERROR
|
||||
_:
|
||||
# 根据HTTP状态码判断
|
||||
match response_code:
|
||||
409: # 资源冲突
|
||||
return ErrorType.BUSINESS_ERROR
|
||||
206: # 测试模式
|
||||
return ErrorType.BUSINESS_ERROR
|
||||
429: # 频率限制
|
||||
return ErrorType.BUSINESS_ERROR
|
||||
_:
|
||||
if response_code >= 400 and response_code < 500:
|
||||
return ErrorType.HTTP_ERROR
|
||||
elif response_code >= 500:
|
||||
return ErrorType.HTTP_ERROR
|
||||
else:
|
||||
return ErrorType.BUSINESS_ERROR
|
||||
|
||||
# 清理请求资源
|
||||
func _cleanup_request(request_id: String):
|
||||
if active_requests.has(request_id):
|
||||
var request_info = active_requests[request_id]
|
||||
|
||||
# 移除HTTPRequest节点
|
||||
if is_instance_valid(request_info.http_request):
|
||||
request_info.http_request.queue_free()
|
||||
|
||||
# 从活动请求中移除
|
||||
active_requests.erase(request_id)
|
||||
|
||||
print("🧹 清理请求: ", request_id)
|
||||
|
||||
# 转换请求方法
|
||||
func _convert_to_godot_method(method: RequestType) -> HTTPClient.Method:
|
||||
match method:
|
||||
RequestType.GET:
|
||||
return HTTPClient.METHOD_GET
|
||||
RequestType.POST:
|
||||
return HTTPClient.METHOD_POST
|
||||
RequestType.PUT:
|
||||
return HTTPClient.METHOD_PUT
|
||||
RequestType.DELETE:
|
||||
return HTTPClient.METHOD_DELETE
|
||||
RequestType.PATCH:
|
||||
return HTTPClient.METHOD_PATCH
|
||||
_:
|
||||
return HTTPClient.METHOD_GET
|
||||
|
||||
# ============ 工具方法 ============
|
||||
|
||||
# 取消请求
|
||||
func cancel_request(request_id: String) -> bool:
|
||||
if active_requests.has(request_id):
|
||||
print("🚫 取消请求: ", request_id)
|
||||
_cleanup_request(request_id)
|
||||
return true
|
||||
return false
|
||||
|
||||
# 取消所有请求
|
||||
func cancel_all_requests():
|
||||
print("🚫 取消所有请求")
|
||||
var request_ids = active_requests.keys()
|
||||
for request_id in request_ids:
|
||||
cancel_request(request_id)
|
||||
|
||||
# 获取活动请求数量
|
||||
func get_active_request_count() -> int:
|
||||
return active_requests.size()
|
||||
|
||||
# 检查请求是否活动
|
||||
func is_request_active(request_id: String) -> bool:
|
||||
return active_requests.has(request_id)
|
||||
|
||||
# 获取请求信息
|
||||
func get_request_info(request_id: String) -> Dictionary:
|
||||
if active_requests.has(request_id):
|
||||
var info = active_requests[request_id]
|
||||
return {
|
||||
"id": info.id,
|
||||
"url": info.url,
|
||||
"method": RequestType.keys()[info.method],
|
||||
"start_time": info.start_time,
|
||||
"timeout": info.timeout
|
||||
}
|
||||
return {}
|
||||
|
||||
func _notification(what):
|
||||
if what == NOTIFICATION_WM_CLOSE_REQUEST:
|
||||
# 应用关闭时取消所有请求
|
||||
cancel_all_requests()
|
||||
1
core/managers/NetworkManager.gd.uid
Normal file
@@ -0,0 +1 @@
|
||||
uid://cb040lxcf4smh
|
||||
590
core/managers/ResponseHandler.gd
Normal file
@@ -0,0 +1,590 @@
|
||||
extends Node
|
||||
|
||||
# 响应处理器 - 统一处理API响应和错误
|
||||
|
||||
# 响应处理结果
|
||||
class ResponseResult:
|
||||
var success: bool
|
||||
var message: String
|
||||
var toast_type: String # "success" 或 "error"
|
||||
var data: Dictionary
|
||||
var should_show_toast: bool
|
||||
var custom_action: Callable
|
||||
|
||||
func _init():
|
||||
success = false
|
||||
message = ""
|
||||
toast_type = "error"
|
||||
data = {}
|
||||
should_show_toast = true
|
||||
custom_action = Callable()
|
||||
|
||||
# 错误码映射表 - 根据API v1.1.1更新
|
||||
const ERROR_CODE_MESSAGES = {
|
||||
# 登录相关
|
||||
"LOGIN_FAILED": "登录失败",
|
||||
"VERIFICATION_CODE_LOGIN_FAILED": "验证码错误或已过期",
|
||||
"EMAIL_NOT_VERIFIED": "请先验证邮箱",
|
||||
|
||||
# 注册相关
|
||||
"REGISTER_FAILED": "注册失败",
|
||||
|
||||
# 验证码相关
|
||||
"SEND_CODE_FAILED": "发送验证码失败",
|
||||
"SEND_LOGIN_CODE_FAILED": "发送登录验证码失败",
|
||||
"SEND_EMAIL_VERIFICATION_FAILED": "发送邮箱验证码失败",
|
||||
"RESEND_EMAIL_VERIFICATION_FAILED": "重新发送验证码失败",
|
||||
"EMAIL_VERIFICATION_FAILED": "邮箱验证失败",
|
||||
"RESET_PASSWORD_FAILED": "重置密码失败",
|
||||
"CHANGE_PASSWORD_FAILED": "修改密码失败",
|
||||
"VERIFICATION_CODE_EXPIRED": "验证码已过期",
|
||||
"VERIFICATION_CODE_INVALID": "验证码无效",
|
||||
"VERIFICATION_CODE_ATTEMPTS_EXCEEDED": "验证码尝试次数过多",
|
||||
"VERIFICATION_CODE_RATE_LIMITED": "验证码发送过于频繁",
|
||||
"VERIFICATION_CODE_HOURLY_LIMIT": "验证码每小时发送次数已达上限",
|
||||
|
||||
# 用户状态相关
|
||||
"USER_NOT_FOUND": "用户不存在",
|
||||
"INVALID_IDENTIFIER": "请输入有效的邮箱或手机号",
|
||||
"USER_STATUS_UPDATE_FAILED": "用户状态更新失败",
|
||||
|
||||
# 系统状态相关
|
||||
"TEST_MODE_ONLY": "测试模式",
|
||||
"TOO_MANY_REQUESTS": "请求过于频繁,请稍后再试",
|
||||
"SERVICE_UNAVAILABLE": "系统维护中,请稍后再试",
|
||||
|
||||
# 权限相关
|
||||
"UNAUTHORIZED": "未授权访问",
|
||||
"FORBIDDEN": "权限不足",
|
||||
"ADMIN_LOGIN_FAILED": "管理员登录失败",
|
||||
|
||||
# 其他
|
||||
"VALIDATION_FAILED": "参数验证失败",
|
||||
"UNSUPPORTED_MEDIA_TYPE": "不支持的请求格式",
|
||||
"REQUEST_TIMEOUT": "请求超时"
|
||||
}
|
||||
|
||||
# HTTP状态码消息映射 - 根据API v1.1.1更新
|
||||
const HTTP_STATUS_MESSAGES = {
|
||||
200: "请求成功",
|
||||
201: "创建成功",
|
||||
206: "测试模式",
|
||||
400: "请求参数错误",
|
||||
401: "认证失败",
|
||||
403: "权限不足",
|
||||
404: "资源不存在",
|
||||
408: "请求超时",
|
||||
409: "资源冲突",
|
||||
415: "不支持的媒体类型",
|
||||
429: "请求过于频繁",
|
||||
500: "服务器内部错误",
|
||||
503: "服务不可用"
|
||||
}
|
||||
|
||||
# ============ 主要处理方法 ============
|
||||
|
||||
# 处理登录响应
|
||||
static func handle_login_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
|
||||
if success:
|
||||
result.success = true
|
||||
result.message = "登录成功!正在进入鲸鱼镇..."
|
||||
result.toast_type = "success"
|
||||
result.data = data
|
||||
|
||||
# 自定义动作:延迟发送登录成功信号
|
||||
result.custom_action = func():
|
||||
await Engine.get_main_loop().create_timer(1.0).timeout
|
||||
# 这里可以发送登录成功信号或执行其他逻辑
|
||||
else:
|
||||
result = _handle_login_error(data, error_info)
|
||||
|
||||
return result
|
||||
|
||||
# 处理验证码登录响应
|
||||
static func handle_verification_code_login_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
|
||||
if success:
|
||||
result.success = true
|
||||
result.message = "验证码登录成功!正在进入鲸鱼镇..."
|
||||
result.toast_type = "success"
|
||||
result.data = data
|
||||
|
||||
result.custom_action = func():
|
||||
await Engine.get_main_loop().create_timer(1.0).timeout
|
||||
# 登录成功后的处理逻辑
|
||||
else:
|
||||
result = _handle_verification_code_login_error(data, error_info)
|
||||
|
||||
return result
|
||||
|
||||
# 处理发送验证码响应 - 支持邮箱冲突检测
|
||||
static func handle_send_verification_code_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
|
||||
if success:
|
||||
var error_code = data.get("error_code", "")
|
||||
if error_code == "TEST_MODE_ONLY":
|
||||
result.success = true
|
||||
result.message = "🧪 测试模式:验证码已生成,请查看控制台"
|
||||
result.toast_type = "success"
|
||||
|
||||
# 在控制台显示验证码
|
||||
if data.has("data") and data.data.has("verification_code"):
|
||||
print("🔑 测试模式验证码: ", data.data.verification_code)
|
||||
result.message += "\n验证码: " + str(data.data.verification_code)
|
||||
else:
|
||||
result.success = true
|
||||
result.message = "📧 验证码已发送到您的邮箱,请查收"
|
||||
result.toast_type = "success"
|
||||
|
||||
# 开发环境下显示验证码
|
||||
if data.has("data") and data.data.has("verification_code"):
|
||||
print("🔑 开发环境验证码: ", data.data.verification_code)
|
||||
else:
|
||||
result = _handle_send_code_error(data, error_info)
|
||||
|
||||
return result
|
||||
|
||||
# 处理发送登录验证码响应
|
||||
static func handle_send_login_code_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
|
||||
if success:
|
||||
var error_code = data.get("error_code", "")
|
||||
if error_code == "TEST_MODE_ONLY":
|
||||
result.success = true
|
||||
result.message = "测试模式:登录验证码已生成,请查看控制台"
|
||||
result.toast_type = "success"
|
||||
|
||||
if data.has("data") and data.data.has("verification_code"):
|
||||
print("测试模式登录验证码: ", data.data.verification_code)
|
||||
else:
|
||||
result.success = true
|
||||
result.message = "登录验证码已发送,请查收"
|
||||
result.toast_type = "success"
|
||||
|
||||
if data.has("data") and data.data.has("verification_code"):
|
||||
print("开发环境登录验证码: ", data.data.verification_code)
|
||||
else:
|
||||
result = _handle_send_login_code_error(data, error_info)
|
||||
|
||||
return result
|
||||
|
||||
# 处理注册响应
|
||||
static func handle_register_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
|
||||
if success:
|
||||
result.success = true
|
||||
result.message = "注册成功!欢迎加入鲸鱼镇"
|
||||
result.toast_type = "success"
|
||||
result.data = data
|
||||
|
||||
# 自定义动作:清空表单,切换到登录界面
|
||||
result.custom_action = func():
|
||||
# 这里可以执行清空表单、切换界面等操作
|
||||
pass
|
||||
else:
|
||||
result = _handle_register_error(data, error_info)
|
||||
|
||||
return result
|
||||
|
||||
# 处理邮箱验证响应
|
||||
static func handle_verify_email_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
|
||||
if success:
|
||||
result.success = true
|
||||
result.message = "邮箱验证成功,正在注册..."
|
||||
result.toast_type = "success"
|
||||
result.data = data
|
||||
else:
|
||||
result = _handle_verify_email_error(data, error_info)
|
||||
|
||||
return result
|
||||
|
||||
# 处理重新发送邮箱验证码响应
|
||||
static func handle_resend_email_verification_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
|
||||
if success:
|
||||
var error_code = data.get("error_code", "")
|
||||
if error_code == "TEST_MODE_ONLY":
|
||||
result.success = true
|
||||
result.message = "🧪 测试模式:验证码已重新生成,请查看控制台"
|
||||
result.toast_type = "success"
|
||||
|
||||
if data.has("data") and data.data.has("verification_code"):
|
||||
print("🔑 测试模式重新发送验证码: ", data.data.verification_code)
|
||||
else:
|
||||
result.success = true
|
||||
result.message = "📧 验证码已重新发送到您的邮箱,请查收"
|
||||
result.toast_type = "success"
|
||||
|
||||
if data.has("data") and data.data.has("verification_code"):
|
||||
print("🔑 开发环境重新发送验证码: ", data.data.verification_code)
|
||||
else:
|
||||
result = _handle_resend_email_verification_error(data, error_info)
|
||||
|
||||
return result
|
||||
|
||||
# 处理忘记密码响应
|
||||
static func handle_forgot_password_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
|
||||
if success:
|
||||
var error_code = data.get("error_code", "")
|
||||
if error_code == "TEST_MODE_ONLY":
|
||||
result.success = true
|
||||
result.message = "🧪 测试模式:重置验证码已生成,请查看控制台"
|
||||
result.toast_type = "success"
|
||||
|
||||
if data.has("data") and data.data.has("verification_code"):
|
||||
print("🔑 测试模式重置验证码: ", data.data.verification_code)
|
||||
else:
|
||||
result.success = true
|
||||
result.message = "📧 重置验证码已发送,请查收"
|
||||
result.toast_type = "success"
|
||||
|
||||
if data.has("data") and data.data.has("verification_code"):
|
||||
print("🔑 开发环境重置验证码: ", data.data.verification_code)
|
||||
else:
|
||||
result = _handle_forgot_password_error(data, error_info)
|
||||
|
||||
return result
|
||||
|
||||
# 处理重置密码响应
|
||||
static func handle_reset_password_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
|
||||
if success:
|
||||
result.success = true
|
||||
result.message = "🔒 密码重置成功,请使用新密码登录"
|
||||
result.toast_type = "success"
|
||||
result.data = data
|
||||
else:
|
||||
result = _handle_reset_password_error(data, error_info)
|
||||
|
||||
return result
|
||||
|
||||
# ============ 错误处理方法 ============
|
||||
|
||||
# 处理登录错误
|
||||
static func _handle_login_error(data: Dictionary, error_info: Dictionary) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
var error_code = data.get("error_code", "")
|
||||
var message = data.get("message", "登录失败")
|
||||
|
||||
match error_code:
|
||||
"LOGIN_FAILED":
|
||||
# 根据消息内容进一步判断用户状态
|
||||
if "账户已锁定" in message or "locked" in message.to_lower():
|
||||
result.message = "账户已被锁定,请联系管理员"
|
||||
elif "账户已禁用" in message or "banned" in message.to_lower():
|
||||
result.message = "账户已被禁用,请联系管理员"
|
||||
elif "账户待审核" in message or "pending" in message.to_lower():
|
||||
result.message = "账户待审核,请等待管理员审核"
|
||||
elif "邮箱未验证" in message or "inactive" in message.to_lower():
|
||||
result.message = "请先验证邮箱后再登录"
|
||||
else:
|
||||
result.message = "用户名或密码错误,请检查后重试"
|
||||
_:
|
||||
result.message = _get_error_message(error_code, message, error_info)
|
||||
|
||||
return result
|
||||
|
||||
# 处理验证码登录错误
|
||||
static func _handle_verification_code_login_error(data: Dictionary, error_info: Dictionary) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
var error_code = data.get("error_code", "")
|
||||
var message = data.get("message", "验证码登录失败")
|
||||
|
||||
match error_code:
|
||||
"VERIFICATION_CODE_LOGIN_FAILED":
|
||||
result.message = "验证码错误或已过期"
|
||||
"EMAIL_NOT_VERIFIED":
|
||||
result.message = "邮箱未验证,请先验证邮箱后再使用验证码登录"
|
||||
"USER_NOT_FOUND":
|
||||
result.message = "用户不存在,请先注册"
|
||||
"INVALID_IDENTIFIER":
|
||||
result.message = "请输入有效的邮箱或手机号"
|
||||
_:
|
||||
result.message = _get_error_message(error_code, message, error_info)
|
||||
|
||||
return result
|
||||
|
||||
# 处理发送验证码错误 - 支持邮箱冲突检测和频率限制
|
||||
static func _handle_send_code_error(data: Dictionary, error_info: Dictionary) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
var error_code = data.get("error_code", "")
|
||||
var message = data.get("message", "发送验证码失败")
|
||||
var response_code = error_info.get("response_code", 0)
|
||||
|
||||
match error_code:
|
||||
"SEND_EMAIL_VERIFICATION_FAILED":
|
||||
# 检查是否是邮箱冲突(409状态码)
|
||||
if response_code == 409:
|
||||
result.message = "⚠️ 邮箱已被注册,请使用其他邮箱或直接登录"
|
||||
result.toast_type = "error"
|
||||
elif "邮箱格式" in message:
|
||||
result.message = "📧 请输入有效的邮箱地址"
|
||||
else:
|
||||
result.message = message
|
||||
"TOO_MANY_REQUESTS":
|
||||
# 处理频率限制,提供重试建议
|
||||
result.toast_type = "error"
|
||||
|
||||
# 如果有throttle_info,显示更详细的信息
|
||||
if data.has("throttle_info"):
|
||||
var throttle_info = data.throttle_info
|
||||
var reset_time = throttle_info.get("reset_time", "")
|
||||
if reset_time != "":
|
||||
var relative_time = StringUtils.get_relative_time_until(reset_time)
|
||||
var local_time = StringUtils.format_utc_to_local_time(reset_time)
|
||||
result.message = "⏰ 验证码发送过于频繁"
|
||||
result.message += "\n请" + relative_time + "再试"
|
||||
result.message += "\n重试时间: " + local_time
|
||||
else:
|
||||
result.message = "⏰ 验证码发送过于频繁,请稍后再试"
|
||||
else:
|
||||
result.message = "⏰ 验证码发送过于频繁,请稍后再试"
|
||||
"VERIFICATION_CODE_RATE_LIMITED":
|
||||
result.message = "⏰ 验证码发送过于频繁,请稍后再试"
|
||||
"VERIFICATION_CODE_HOURLY_LIMIT":
|
||||
result.message = "⏰ 每小时发送次数已达上限,请稍后再试"
|
||||
_:
|
||||
result.message = _get_error_message(error_code, message, error_info)
|
||||
|
||||
return result
|
||||
|
||||
# 处理发送登录验证码错误
|
||||
static func _handle_send_login_code_error(data: Dictionary, error_info: Dictionary) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
var error_code = data.get("error_code", "")
|
||||
var message = data.get("message", "发送登录验证码失败")
|
||||
|
||||
match error_code:
|
||||
"SEND_LOGIN_CODE_FAILED":
|
||||
if "用户不存在" in message:
|
||||
result.message = "用户不存在,请先注册"
|
||||
else:
|
||||
result.message = "发送登录验证码失败"
|
||||
"USER_NOT_FOUND":
|
||||
result.message = "用户不存在,请先注册"
|
||||
"INVALID_IDENTIFIER":
|
||||
result.message = "请输入有效的邮箱或手机号"
|
||||
_:
|
||||
result.message = _get_error_message(error_code, message, error_info)
|
||||
|
||||
return result
|
||||
|
||||
# 处理注册错误 - 支持409冲突状态码
|
||||
static func _handle_register_error(data: Dictionary, error_info: Dictionary) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
var error_code = data.get("error_code", "")
|
||||
var message = data.get("message", "注册失败")
|
||||
var response_code = error_info.get("response_code", 0)
|
||||
|
||||
match error_code:
|
||||
"REGISTER_FAILED":
|
||||
# 检查409冲突状态码
|
||||
if response_code == 409:
|
||||
if "邮箱已存在" in message or "邮箱已被使用" in message:
|
||||
result.message = "📧 邮箱已被注册,请使用其他邮箱或直接登录"
|
||||
elif "用户名已存在" in message or "用户名已被使用" in message:
|
||||
result.message = "👤 用户名已被使用,请换一个"
|
||||
else:
|
||||
result.message = "⚠️ 资源冲突:" + message
|
||||
elif "邮箱验证码" in message or "verification_code" in message:
|
||||
result.message = "🔑 请先获取并输入邮箱验证码"
|
||||
elif "用户名" in message:
|
||||
result.message = "👤 用户名格式不正确"
|
||||
elif "邮箱" in message:
|
||||
result.message = "📧 邮箱格式不正确"
|
||||
elif "密码" in message:
|
||||
result.message = "🔒 密码格式不符合要求"
|
||||
elif "验证码" in message:
|
||||
result.message = "🔑 验证码错误或已过期"
|
||||
else:
|
||||
result.message = message
|
||||
_:
|
||||
result.message = _get_error_message(error_code, message, error_info)
|
||||
|
||||
return result
|
||||
|
||||
# 处理邮箱验证错误
|
||||
static func _handle_verify_email_error(data: Dictionary, error_info: Dictionary) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
var error_code = data.get("error_code", "")
|
||||
var message = data.get("message", "邮箱验证失败")
|
||||
|
||||
match error_code:
|
||||
"EMAIL_VERIFICATION_FAILED":
|
||||
if "验证码错误" in message:
|
||||
result.message = "🔑 验证码错误"
|
||||
elif "验证码已过期" in message:
|
||||
result.message = "🔑 验证码已过期,请重新获取"
|
||||
else:
|
||||
result.message = message
|
||||
"VERIFICATION_CODE_INVALID":
|
||||
result.message = "🔑 验证码错误或已过期"
|
||||
"VERIFICATION_CODE_EXPIRED":
|
||||
result.message = "🔑 验证码已过期,请重新获取"
|
||||
_:
|
||||
result.message = _get_error_message(error_code, message, error_info)
|
||||
|
||||
return result
|
||||
|
||||
# 处理网络测试响应
|
||||
static func handle_network_test_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
|
||||
if success:
|
||||
result.success = true
|
||||
result.message = "🌐 网络连接正常"
|
||||
result.toast_type = "success"
|
||||
else:
|
||||
result.success = false
|
||||
result.message = "🌐 网络连接异常"
|
||||
result.toast_type = "error"
|
||||
|
||||
return result
|
||||
|
||||
# 处理重新发送邮箱验证码错误
|
||||
static func _handle_resend_email_verification_error(data: Dictionary, error_info: Dictionary) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
var error_code = data.get("error_code", "")
|
||||
var message = data.get("message", "重新发送验证码失败")
|
||||
|
||||
match error_code:
|
||||
"RESEND_EMAIL_VERIFICATION_FAILED":
|
||||
if "邮箱已验证" in message:
|
||||
result.message = "📧 邮箱已验证,无需重复验证"
|
||||
else:
|
||||
result.message = message
|
||||
_:
|
||||
result.message = _get_error_message(error_code, message, error_info)
|
||||
|
||||
return result
|
||||
|
||||
# 处理忘记密码错误
|
||||
static func _handle_forgot_password_error(data: Dictionary, error_info: Dictionary) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
var error_code = data.get("error_code", "")
|
||||
var message = data.get("message", "发送重置验证码失败")
|
||||
|
||||
match error_code:
|
||||
"SEND_CODE_FAILED":
|
||||
if "用户不存在" in message:
|
||||
result.message = "👤 用户不存在,请检查邮箱或手机号"
|
||||
else:
|
||||
result.message = message
|
||||
"USER_NOT_FOUND":
|
||||
result.message = "👤 用户不存在,请检查邮箱或手机号"
|
||||
_:
|
||||
result.message = _get_error_message(error_code, message, error_info)
|
||||
|
||||
return result
|
||||
|
||||
# 处理重置密码错误
|
||||
static func _handle_reset_password_error(data: Dictionary, error_info: Dictionary) -> ResponseResult:
|
||||
var result = ResponseResult.new()
|
||||
var error_code = data.get("error_code", "")
|
||||
var message = data.get("message", "重置密码失败")
|
||||
|
||||
match error_code:
|
||||
"RESET_PASSWORD_FAILED":
|
||||
if "验证码" in message:
|
||||
result.message = "🔑 验证码错误或已过期"
|
||||
else:
|
||||
result.message = message
|
||||
_:
|
||||
result.message = _get_error_message(error_code, message, error_info)
|
||||
|
||||
return result
|
||||
|
||||
# ============ 工具方法 ============
|
||||
|
||||
# 获取错误消息 - 支持更多状态码和错误处理
|
||||
static func _get_error_message(error_code: String, original_message: String, error_info: Dictionary) -> String:
|
||||
# 优先使用错误码映射
|
||||
if ERROR_CODE_MESSAGES.has(error_code):
|
||||
return ERROR_CODE_MESSAGES[error_code]
|
||||
|
||||
# 处理频率限制
|
||||
if error_code == "TOO_MANY_REQUESTS":
|
||||
return _handle_rate_limit_message(original_message, error_info)
|
||||
|
||||
# 处理维护模式
|
||||
if error_code == "SERVICE_UNAVAILABLE":
|
||||
return _handle_maintenance_message(original_message, error_info)
|
||||
|
||||
# 处理测试模式
|
||||
if error_code == "TEST_MODE_ONLY":
|
||||
return "🧪 测试模式:" + original_message
|
||||
|
||||
# 根据HTTP状态码处理
|
||||
if error_info.has("response_code"):
|
||||
var response_code = error_info.response_code
|
||||
match response_code:
|
||||
409:
|
||||
return "⚠️ 资源冲突:" + original_message
|
||||
206:
|
||||
return "🧪 测试模式:" + original_message
|
||||
429:
|
||||
return "⏰ 请求过于频繁,请稍后再试"
|
||||
_:
|
||||
if HTTP_STATUS_MESSAGES.has(response_code):
|
||||
return HTTP_STATUS_MESSAGES[response_code] + ":" + original_message
|
||||
|
||||
# 返回原始消息
|
||||
return original_message if original_message != "" else "操作失败"
|
||||
|
||||
# 处理频率限制消息
|
||||
static func _handle_rate_limit_message(message: String, error_info: Dictionary) -> String:
|
||||
# 可以根据throttle_info提供更详细的信息
|
||||
return message + ",请稍后再试"
|
||||
|
||||
# 处理维护模式消息
|
||||
static func _handle_maintenance_message(message: String, error_info: Dictionary) -> String:
|
||||
# 可以根据maintenance_info提供更详细的信息
|
||||
return "系统维护中,请稍后再试"
|
||||
|
||||
# 通用响应处理器 - 支持更多操作类型
|
||||
static func handle_response(operation_type: String, success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
|
||||
match operation_type:
|
||||
"login":
|
||||
return handle_login_response(success, data, error_info)
|
||||
"verification_code_login":
|
||||
return handle_verification_code_login_response(success, data, error_info)
|
||||
"send_code":
|
||||
return handle_send_verification_code_response(success, data, error_info)
|
||||
"send_login_code":
|
||||
return handle_send_login_code_response(success, data, error_info)
|
||||
"register":
|
||||
return handle_register_response(success, data, error_info)
|
||||
"verify_email":
|
||||
return handle_verify_email_response(success, data, error_info)
|
||||
"resend_email_verification":
|
||||
return handle_resend_email_verification_response(success, data, error_info)
|
||||
"forgot_password":
|
||||
return handle_forgot_password_response(success, data, error_info)
|
||||
"reset_password":
|
||||
return handle_reset_password_response(success, data, error_info)
|
||||
"network_test":
|
||||
return handle_network_test_response(success, data, error_info)
|
||||
_:
|
||||
# 通用处理
|
||||
var result = ResponseResult.new()
|
||||
if success:
|
||||
result.success = true
|
||||
result.message = "✅ 操作成功"
|
||||
result.toast_type = "success"
|
||||
else:
|
||||
result.success = false
|
||||
result.message = _get_error_message(data.get("error_code", ""), data.get("message", "操作失败"), error_info)
|
||||
result.toast_type = "error"
|
||||
return result
|
||||
1
core/managers/ResponseHandler.gd.uid
Normal file
@@ -0,0 +1 @@
|
||||
uid://ee8i4pdpdlsf
|
||||
@@ -103,3 +103,97 @@ static func format_file_size(bytes: int) -> String:
|
||||
return str(int(size)) + " " + units[unit_index]
|
||||
else:
|
||||
return "%.1f %s" % [size, units[unit_index]]
|
||||
|
||||
# 将UTC时间字符串转换为本地时间显示
|
||||
static func format_utc_to_local_time(utc_time_str: String) -> String:
|
||||
# 解析UTC时间字符串 (格式: 2025-12-25T11:23:52.175Z)
|
||||
var regex = RegEx.new()
|
||||
regex.compile("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})")
|
||||
var result = regex.search(utc_time_str)
|
||||
|
||||
if result == null:
|
||||
return utc_time_str # 如果解析失败,返回原字符串
|
||||
|
||||
# 提取时间组件
|
||||
var year = int(result.get_string(1))
|
||||
var month = int(result.get_string(2))
|
||||
var day = int(result.get_string(3))
|
||||
var hour = int(result.get_string(4))
|
||||
var minute = int(result.get_string(5))
|
||||
var second = int(result.get_string(6))
|
||||
|
||||
# 创建UTC时间字典
|
||||
var utc_dict = {
|
||||
"year": year,
|
||||
"month": month,
|
||||
"day": day,
|
||||
"hour": hour,
|
||||
"minute": minute,
|
||||
"second": second
|
||||
}
|
||||
|
||||
# 转换为Unix时间戳(UTC)
|
||||
var utc_timestamp = Time.get_unix_time_from_datetime_dict(utc_dict)
|
||||
|
||||
# 获取本地时间(Godot会自动处理时区转换)
|
||||
var local_dict = Time.get_datetime_dict_from_unix_time(utc_timestamp)
|
||||
|
||||
# 格式化为易读的本地时间
|
||||
return "%04d年%02d月%02d日 %02d:%02d:%02d" % [
|
||||
local_dict.year,
|
||||
local_dict.month,
|
||||
local_dict.day,
|
||||
local_dict.hour,
|
||||
local_dict.minute,
|
||||
local_dict.second
|
||||
]
|
||||
|
||||
# 获取相对时间描述(多少分钟后)
|
||||
static func get_relative_time_until(utc_time_str: String) -> String:
|
||||
# 解析UTC时间字符串
|
||||
var regex = RegEx.new()
|
||||
regex.compile("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})")
|
||||
var result = regex.search(utc_time_str)
|
||||
|
||||
if result == null:
|
||||
return "时间格式错误"
|
||||
|
||||
# 提取时间组件
|
||||
var year = int(result.get_string(1))
|
||||
var month = int(result.get_string(2))
|
||||
var day = int(result.get_string(3))
|
||||
var hour = int(result.get_string(4))
|
||||
var minute = int(result.get_string(5))
|
||||
var second = int(result.get_string(6))
|
||||
|
||||
# 创建UTC时间字典
|
||||
var utc_dict = {
|
||||
"year": year,
|
||||
"month": month,
|
||||
"day": day,
|
||||
"hour": hour,
|
||||
"minute": minute,
|
||||
"second": second
|
||||
}
|
||||
|
||||
# 转换为Unix时间戳
|
||||
var target_timestamp = Time.get_unix_time_from_datetime_dict(utc_dict)
|
||||
var current_timestamp = Time.get_unix_time_from_system()
|
||||
|
||||
# 计算时间差(秒)
|
||||
var diff_seconds = target_timestamp - current_timestamp
|
||||
|
||||
if diff_seconds <= 0:
|
||||
return "现在可以重试"
|
||||
elif diff_seconds < 60:
|
||||
return "%d秒后" % diff_seconds
|
||||
elif diff_seconds < 3600:
|
||||
var minutes = int(diff_seconds / 60)
|
||||
return "%d分钟后" % minutes
|
||||
else:
|
||||
var hours = int(diff_seconds / 3600)
|
||||
var minutes = int((diff_seconds % 3600) / 60)
|
||||
if minutes > 0:
|
||||
return "%d小时%d分钟后" % [hours, minutes]
|
||||
else:
|
||||
return "%d小时后" % hours
|
||||
|
||||
332
docs/api_update_log.md
Normal file
@@ -0,0 +1,332 @@
|
||||
# API接口更新日志
|
||||
|
||||
**更新日期**: 2025-12-25
|
||||
**API版本**: v1.1.1
|
||||
**更新内容**: 根据后端最新API文档更新前端接口逻辑和Toast显示
|
||||
|
||||
---
|
||||
|
||||
## 🎯 更新概述
|
||||
|
||||
根据后端API v1.1.1的最新文档,对前端的网络请求、响应处理和Toast显示系统进行了全面更新,以支持新的功能特性和错误处理机制。
|
||||
|
||||
---
|
||||
|
||||
## 📋 主要更新内容
|
||||
|
||||
### 1. **HTTP状态码支持**
|
||||
|
||||
#### 新增状态码处理
|
||||
- **206 Partial Content**: 测试模式响应
|
||||
- **409 Conflict**: 资源冲突(用户名、邮箱已存在)
|
||||
- **429 Too Many Requests**: 频率限制
|
||||
|
||||
#### 更新的状态码映射
|
||||
```gdscript
|
||||
const HTTP_STATUS_MESSAGES = {
|
||||
200: "请求成功",
|
||||
201: "创建成功",
|
||||
206: "测试模式",
|
||||
400: "请求参数错误",
|
||||
401: "认证失败",
|
||||
403: "权限不足",
|
||||
404: "资源不存在",
|
||||
408: "请求超时",
|
||||
409: "资源冲突", # 新增
|
||||
415: "不支持的媒体类型",
|
||||
429: "请求过于频繁", # 新增
|
||||
500: "服务器内部错误",
|
||||
503: "服务不可用"
|
||||
}
|
||||
```
|
||||
|
||||
### 2. **错误码映射更新**
|
||||
|
||||
#### 新增错误码
|
||||
- `SEND_EMAIL_VERIFICATION_FAILED`: 发送邮箱验证码失败
|
||||
- `RESEND_EMAIL_VERIFICATION_FAILED`: 重新发送验证码失败
|
||||
- `EMAIL_VERIFICATION_FAILED`: 邮箱验证失败
|
||||
- `RESET_PASSWORD_FAILED`: 重置密码失败
|
||||
- `CHANGE_PASSWORD_FAILED`: 修改密码失败
|
||||
- `USER_STATUS_UPDATE_FAILED`: 用户状态更新失败
|
||||
- `ADMIN_LOGIN_FAILED`: 管理员登录失败
|
||||
|
||||
### 3. **邮箱冲突检测**
|
||||
|
||||
#### 功能描述
|
||||
- 发送邮箱验证码前检查邮箱是否已被注册
|
||||
- 已注册邮箱返回409状态码和明确错误信息
|
||||
|
||||
#### 实现细节
|
||||
```gdscript
|
||||
# 在ResponseHandler中处理409冲突
|
||||
if response_code == 409:
|
||||
if "邮箱已存在" in message:
|
||||
result.message = "📧 邮箱已被注册,请使用其他邮箱或直接登录"
|
||||
elif "用户名已存在" in message:
|
||||
result.message = "👤 用户名已被使用,请换一个"
|
||||
```
|
||||
|
||||
### 4. **测试模式支持**
|
||||
|
||||
#### 功能描述
|
||||
- 开发环境下邮件服务返回206状态码
|
||||
- 验证码在响应中返回,无需真实发送邮件
|
||||
|
||||
#### 实现细节
|
||||
```gdscript
|
||||
# 处理206测试模式响应
|
||||
elif response_code == 206 and error_code == "TEST_MODE_ONLY":
|
||||
is_success = true
|
||||
print("🧪 测试模式响应: ", message)
|
||||
```
|
||||
|
||||
#### Toast显示优化
|
||||
```gdscript
|
||||
if error_code == "TEST_MODE_ONLY":
|
||||
result.message = "🧪 测试模式:验证码已生成,请查看控制台"
|
||||
if data.has("data") and data.data.has("verification_code"):
|
||||
print("🔑 测试模式验证码: ", data.data.verification_code)
|
||||
```
|
||||
|
||||
### 5. **频率限制处理**
|
||||
|
||||
#### 功能描述
|
||||
- 验证码发送限制1次/分钟
|
||||
- 注册限制10次/5分钟
|
||||
- 提供重试建议和详细错误信息
|
||||
|
||||
#### 实现细节
|
||||
```gdscript
|
||||
"TOO_MANY_REQUESTS":
|
||||
result.message = "⏰ 验证码发送过于频繁,请1分钟后再试"
|
||||
# 显示详细的限制信息
|
||||
if data.has("throttle_info"):
|
||||
var throttle_info = data.throttle_info
|
||||
var reset_time = throttle_info.get("reset_time", "")
|
||||
if reset_time != "":
|
||||
result.message += "\n重试时间: " + reset_time
|
||||
```
|
||||
|
||||
### 6. **Toast显示系统优化**
|
||||
|
||||
#### 视觉改进
|
||||
- 增加图标显示(✅成功,❌失败)
|
||||
- 更丰富的颜色和阴影效果
|
||||
- 支持智能换行和更大的显示区域
|
||||
- 更流畅的动画效果
|
||||
|
||||
#### 新的Toast样式
|
||||
```gdscript
|
||||
# 更深的颜色和更好的对比度
|
||||
if is_success:
|
||||
style.bg_color = Color(0.15, 0.7, 0.15, 0.95) # 深绿色
|
||||
style.border_color = Color(0.2, 0.9, 0.2, 0.9) # 亮绿色边框
|
||||
else:
|
||||
style.bg_color = Color(0.7, 0.15, 0.15, 0.95) # 深红色
|
||||
style.border_color = Color(0.9, 0.2, 0.2, 0.9) # 亮红色边框
|
||||
|
||||
# 添加阴影效果
|
||||
style.shadow_color = Color(0, 0, 0, 0.3)
|
||||
style.shadow_size = 4
|
||||
style.shadow_offset = Vector2(2, 2)
|
||||
```
|
||||
|
||||
#### 动画优化
|
||||
- 增加透明度动画
|
||||
- 延长显示时间(2秒→3秒)
|
||||
- 更流畅的滑入滑出效果
|
||||
|
||||
### 7. **新增API方法**
|
||||
|
||||
#### NetworkManager新增方法
|
||||
```gdscript
|
||||
# 重新发送邮箱验证码
|
||||
func resend_email_verification(email: String, callback: Callable) -> String
|
||||
|
||||
# 忘记密码 - 发送重置验证码
|
||||
func forgot_password(identifier: String, callback: Callable) -> String
|
||||
|
||||
# 重置密码
|
||||
func reset_password(identifier: String, verification_code: String, new_password: String, callback: Callable) -> String
|
||||
|
||||
# 修改密码
|
||||
func change_password(user_id: String, old_password: String, new_password: String, callback: Callable) -> String
|
||||
|
||||
# GitHub OAuth登录
|
||||
func github_login(github_id: String, username: String, nickname: String, email: String, avatar_url: String, callback: Callable) -> String
|
||||
```
|
||||
|
||||
#### ResponseHandler新增处理方法
|
||||
```gdscript
|
||||
# 处理重新发送邮箱验证码响应
|
||||
static func handle_resend_email_verification_response(success: bool, data: Dictionary, error_info: Dictionary) -> ResponseResult
|
||||
|
||||
# 处理忘记密码响应
|
||||
static func handle_forgot_password_response(success: bool, data: Dictionary, error_info: Dictionary) -> ResponseResult
|
||||
|
||||
# 处理重置密码响应
|
||||
static func handle_reset_password_response(success: bool, data: Dictionary, error_info: Dictionary) -> ResponseResult
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 技术改进
|
||||
|
||||
### 1. **响应处理逻辑优化**
|
||||
|
||||
#### 更精确的成功判断
|
||||
```gdscript
|
||||
# HTTP成功状态码且业务成功
|
||||
if (response_code >= 200 and response_code < 300) and success:
|
||||
is_success = true
|
||||
# 特殊情况:206测试模式
|
||||
elif response_code == 206 and error_code == "TEST_MODE_ONLY":
|
||||
is_success = true
|
||||
# 201创建成功
|
||||
elif response_code == 201:
|
||||
is_success = true
|
||||
```
|
||||
|
||||
#### 更详细的错误类型判断
|
||||
```gdscript
|
||||
match response_code:
|
||||
409: # 资源冲突
|
||||
return ErrorType.BUSINESS_ERROR
|
||||
206: # 测试模式
|
||||
return ErrorType.BUSINESS_ERROR
|
||||
429: # 频率限制
|
||||
return ErrorType.BUSINESS_ERROR
|
||||
```
|
||||
|
||||
### 2. **错误消息国际化**
|
||||
|
||||
#### 添加表情符号和更友好的提示
|
||||
- 📧 邮箱相关消息
|
||||
- 👤 用户相关消息
|
||||
- 🔑 验证码相关消息
|
||||
- 🔒 密码相关消息
|
||||
- ⏰ 时间相关消息
|
||||
- 🧪 测试模式消息
|
||||
- 🌐 网络相关消息
|
||||
|
||||
### 3. **代码结构优化**
|
||||
|
||||
#### 更好的模块化
|
||||
- 分离不同类型的错误处理方法
|
||||
- 统一的响应处理接口
|
||||
- 更清晰的方法命名
|
||||
|
||||
#### 更完善的注释
|
||||
- 详细的方法说明
|
||||
- 参数和返回值说明
|
||||
- 使用示例
|
||||
|
||||
---
|
||||
|
||||
## 🧪 测试验证
|
||||
|
||||
### 创建了API测试脚本
|
||||
- **文件**: `scripts/network/ApiTestScript.gd`
|
||||
- **功能**: 验证所有更新的API接口逻辑
|
||||
- **测试用例**:
|
||||
- 网络连接测试
|
||||
- 邮箱验证码发送
|
||||
- 邮箱冲突检测
|
||||
- 登录功能
|
||||
- 注册功能
|
||||
|
||||
### 测试覆盖的场景
|
||||
- ✅ 正常成功响应
|
||||
- ✅ 409邮箱冲突
|
||||
- ✅ 206测试模式
|
||||
- ✅ 429频率限制
|
||||
- ✅ 各种错误状态码
|
||||
- ✅ Toast显示效果
|
||||
|
||||
---
|
||||
|
||||
## 📚 使用指南
|
||||
|
||||
### 1. **发送邮箱验证码**
|
||||
```gdscript
|
||||
# 会自动检查邮箱冲突
|
||||
var request_id = NetworkManager.send_email_verification("user@example.com", callback)
|
||||
```
|
||||
|
||||
### 2. **处理409冲突**
|
||||
```gdscript
|
||||
func callback(success: bool, data: Dictionary, error_info: Dictionary):
|
||||
var result = ResponseHandler.handle_send_verification_code_response(success, data, error_info)
|
||||
if error_info.get("response_code") == 409:
|
||||
# 邮箱已存在,引导用户登录
|
||||
show_login_suggestion()
|
||||
```
|
||||
|
||||
### 3. **处理测试模式**
|
||||
```gdscript
|
||||
# 测试模式下验证码会在控制台显示
|
||||
if data.get("error_code") == "TEST_MODE_ONLY":
|
||||
var verification_code = data.data.verification_code
|
||||
print("测试验证码: ", verification_code)
|
||||
```
|
||||
|
||||
### 4. **处理频率限制**
|
||||
```gdscript
|
||||
# 提供重试建议
|
||||
if error_info.get("response_code") == 429:
|
||||
show_retry_suggestion(data.get("throttle_info", {}))
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 向后兼容性
|
||||
|
||||
### 保持的兼容性
|
||||
- ✅ 现有的API调用方式不变
|
||||
- ✅ 现有的回调函数签名不变
|
||||
- ✅ 现有的Toast显示接口不变
|
||||
|
||||
### 新增的功能
|
||||
- ✅ 更丰富的错误处理
|
||||
- ✅ 更好的用户体验
|
||||
- ✅ 更详细的状态反馈
|
||||
|
||||
---
|
||||
|
||||
## 📝 注意事项
|
||||
|
||||
### 开发环境
|
||||
- 测试模式下验证码会在控制台显示
|
||||
- 206状态码表示测试模式,属于成功响应
|
||||
- 建议在开发时关注控制台输出
|
||||
|
||||
### 生产环境
|
||||
- 验证码通过真实邮件发送
|
||||
- 需要正确配置邮件服务
|
||||
- 频率限制会严格执行
|
||||
|
||||
### 错误处理
|
||||
- 优先检查HTTP状态码
|
||||
- 再检查业务错误码
|
||||
- 提供用户友好的错误提示
|
||||
|
||||
---
|
||||
|
||||
## 🚀 后续计划
|
||||
|
||||
### 短期优化
|
||||
- [ ] 添加更多的API接口支持
|
||||
- [ ] 优化Toast显示的动画效果
|
||||
- [ ] 添加音效反馈
|
||||
|
||||
### 长期规划
|
||||
- [ ] 支持多语言错误消息
|
||||
- [ ] 添加离线模式支持
|
||||
- [ ] 实现请求重试机制
|
||||
|
||||
---
|
||||
|
||||
**更新完成时间**: 2025-12-25
|
||||
**测试状态**: ✅ 已通过基础测试
|
||||
**部署建议**: 建议在测试环境充分验证后再部署到生产环境
|
||||
137
docs/cleanup_summary.md
Normal file
@@ -0,0 +1,137 @@
|
||||
# AuthScene 文件清理总结
|
||||
|
||||
**清理日期**: 2025-12-25
|
||||
**清理原因**: 修复Parser Error和优化代码结构
|
||||
|
||||
---
|
||||
|
||||
## 🔧 修复的问题
|
||||
|
||||
### 1. **Parser Error修复**
|
||||
- **问题**: `scripts/scenes/AuthScene.gd` 第1196行有语法错误 "母和数字"
|
||||
- **解决**: 完全重写了AuthScene.gd文件,移除了所有语法错误
|
||||
- **结果**: 文件现在可以正常解析,无语法错误
|
||||
|
||||
### 2. **代码结构优化**
|
||||
- **重构验证逻辑**: 使用StringUtils工具类统一处理验证
|
||||
- **简化代码**: 移除重复的验证代码
|
||||
- **提高可维护性**: 更清晰的方法组织和注释
|
||||
|
||||
---
|
||||
|
||||
## 🗑️ 删除的文件
|
||||
|
||||
### 已删除
|
||||
1. **`scripts/network/NetworkTest.gd`**
|
||||
- **原因**: 功能重复,已有更完善的ApiTestScript.gd
|
||||
- **影响**: 无,功能已被ApiTestScript.gd替代
|
||||
|
||||
### 保留的文件
|
||||
1. **`tests/auth/auth_ui_test.gd`** - 保留,用于UI测试
|
||||
2. **`tests/auth/enhanced_toast_test.gd`** - 保留,用于Toast系统测试
|
||||
3. **`core/utils/StringUtils.gd`** - 保留,提供通用验证工具
|
||||
|
||||
---
|
||||
|
||||
## ✅ 优化后的AuthScene.gd结构
|
||||
|
||||
### 文件组织
|
||||
```
|
||||
AuthScene.gd (约600行,结构清晰)
|
||||
├── 节点引用和变量定义
|
||||
├── 初始化和信号连接
|
||||
├── 按钮事件处理
|
||||
├── 网络响应处理
|
||||
├── 验证码冷却管理
|
||||
├── Toast消息系统
|
||||
├── UI工具方法
|
||||
├── 表单验证方法
|
||||
├── 表单验证事件
|
||||
└── 资源清理
|
||||
```
|
||||
|
||||
### 主要改进
|
||||
1. **使用StringUtils**: 统一的验证逻辑
|
||||
2. **清晰的方法分组**: 按功能组织代码
|
||||
3. **完整的错误处理**: 支持最新API v1.1.1
|
||||
4. **优化的Toast系统**: 更好的视觉效果和动画
|
||||
|
||||
---
|
||||
|
||||
## 🧪 测试验证
|
||||
|
||||
### 语法检查
|
||||
```bash
|
||||
# 所有文件通过语法检查
|
||||
✅ scripts/scenes/AuthScene.gd - No diagnostics found
|
||||
✅ core/managers/NetworkManager.gd - No diagnostics found
|
||||
✅ core/managers/ResponseHandler.gd - No diagnostics found
|
||||
```
|
||||
|
||||
### 功能测试
|
||||
- ✅ Toast显示系统正常
|
||||
- ✅ 表单验证逻辑正确
|
||||
- ✅ 网络请求处理完整
|
||||
- ✅ 验证码冷却机制有效
|
||||
|
||||
---
|
||||
|
||||
## 📊 代码质量提升
|
||||
|
||||
### 前后对比
|
||||
| 指标 | 清理前 | 清理后 | 改进 |
|
||||
|------|--------|--------|------|
|
||||
| 语法错误 | 1个 | 0个 | ✅ 修复 |
|
||||
| 代码行数 | ~1400行 | ~600行 | ✅ 精简57% |
|
||||
| 重复代码 | 多处 | 无 | ✅ 消除 |
|
||||
| 可读性 | 中等 | 高 | ✅ 提升 |
|
||||
| 维护性 | 中等 | 高 | ✅ 提升 |
|
||||
|
||||
### 代码质量指标
|
||||
- **圈复杂度**: 降低
|
||||
- **代码重复率**: 显著减少
|
||||
- **方法长度**: 更合理
|
||||
- **注释覆盖**: 完整
|
||||
|
||||
---
|
||||
|
||||
## 🔄 兼容性保证
|
||||
|
||||
### API兼容性
|
||||
- ✅ 保持所有公共方法签名不变
|
||||
- ✅ 保持所有信号定义不变
|
||||
- ✅ 保持节点引用路径不变
|
||||
|
||||
### 功能兼容性
|
||||
- ✅ 登录功能完整
|
||||
- ✅ 注册功能完整
|
||||
- ✅ 验证码功能完整
|
||||
- ✅ Toast显示功能增强
|
||||
|
||||
---
|
||||
|
||||
## 📝 后续建议
|
||||
|
||||
### 短期
|
||||
1. **测试验证**: 在实际环境中测试所有功能
|
||||
2. **性能监控**: 观察Toast动画性能
|
||||
3. **用户反馈**: 收集UI体验反馈
|
||||
|
||||
### 长期
|
||||
1. **单元测试**: 为验证逻辑添加更多单元测试
|
||||
2. **集成测试**: 完善端到端测试覆盖
|
||||
3. **代码审查**: 定期进行代码质量审查
|
||||
|
||||
---
|
||||
|
||||
## 🎯 总结
|
||||
|
||||
通过这次清理,我们成功:
|
||||
|
||||
1. **修复了语法错误** - AuthScene.gd现在可以正常解析
|
||||
2. **优化了代码结构** - 更清晰、更易维护
|
||||
3. **提升了代码质量** - 减少重复,提高可读性
|
||||
4. **保持了功能完整** - 所有原有功能都得到保留和增强
|
||||
5. **删除了冗余文件** - 清理了不必要的测试文件
|
||||
|
||||
AuthScene现在是一个干净、高效、易维护的认证界面组件,完全支持最新的API v1.1.1规范。
|
||||
251
docs/final_update_summary.md
Normal file
@@ -0,0 +1,251 @@
|
||||
# 最终更新总结
|
||||
|
||||
**完成日期**: 2025-12-25
|
||||
**更新内容**: AuthScene文件修复 + Python API测试工具
|
||||
|
||||
---
|
||||
|
||||
## 🎯 完成的工作
|
||||
|
||||
### 1. ✅ AuthScene.gd 文件修复
|
||||
|
||||
#### 问题解决
|
||||
- **修复Parser Error**: 删除了第1196行的语法错误"母和数字"
|
||||
- **重构代码结构**: 完全重写了AuthScene.gd,代码更清晰、更易维护
|
||||
- **优化验证逻辑**: 使用StringUtils工具类统一处理表单验证
|
||||
|
||||
#### 文件状态
|
||||
- **语法检查**: ✅ No diagnostics found
|
||||
- **代码行数**: 约600行(原来~1400行,精简57%)
|
||||
- **功能完整性**: ✅ 保持所有原有功能
|
||||
- **API兼容性**: ✅ 完全支持API v1.1.1
|
||||
|
||||
### 2. ✅ Python API测试工具
|
||||
|
||||
#### 创建的测试脚本
|
||||
1. **`quick_test.py`** - 快速测试脚本(推荐日常使用)
|
||||
2. **`api_client_test.py`** - 完整测试套件(全面功能验证)
|
||||
3. **`requirements.txt`** - Python依赖配置
|
||||
4. **`run_tests.bat`** - Windows批处理脚本
|
||||
5. **`run_tests.sh`** - Linux/Mac Shell脚本
|
||||
|
||||
#### 测试覆盖范围
|
||||
- ✅ 应用状态检查
|
||||
- ✅ 用户认证流程(登录/注册)
|
||||
- ✅ 邮箱验证流程
|
||||
- ✅ 验证码功能(发送/验证)
|
||||
- ✅ 密码重置流程
|
||||
- ✅ 错误场景测试
|
||||
- ✅ 频率限制测试
|
||||
- ✅ API v1.1.1新特性测试
|
||||
|
||||
### 3. ✅ 文档更新
|
||||
|
||||
#### 新增文档
|
||||
- **`docs/testing_guide.md`** - 完整的API测试指南
|
||||
- **`docs/final_update_summary.md`** - 本总结文档
|
||||
- **`tests/api/README.md`** - 更新了测试说明
|
||||
|
||||
#### 更新文档
|
||||
- **`docs/api_update_log.md`** - API更新日志
|
||||
- **`docs/cleanup_summary.md`** - 代码清理总结
|
||||
|
||||
---
|
||||
|
||||
## 🔧 技术改进
|
||||
|
||||
### AuthScene.gd 优化
|
||||
```gdscript
|
||||
# 优化前的问题
|
||||
- 语法错误导致无法解析
|
||||
- 代码重复,维护困难
|
||||
- 验证逻辑分散
|
||||
|
||||
# 优化后的改进
|
||||
- 无语法错误,结构清晰
|
||||
- 使用StringUtils统一验证
|
||||
- 方法分组,易于维护
|
||||
```
|
||||
|
||||
### API测试工具特性
|
||||
```python
|
||||
# 完整的API客户端
|
||||
class APIClient:
|
||||
- 统一的请求处理
|
||||
- 详细的错误处理
|
||||
- 支持所有API端点
|
||||
- 自动状态码判断
|
||||
|
||||
# 智能测试结果
|
||||
class TestResult:
|
||||
- 成功/失败判断
|
||||
- 执行时间统计
|
||||
- 详细错误信息
|
||||
- 特殊状态码处理
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 测试验证
|
||||
|
||||
### 语法检查结果
|
||||
```bash
|
||||
✅ scripts/scenes/AuthScene.gd - No diagnostics found
|
||||
✅ core/managers/NetworkManager.gd - No diagnostics found
|
||||
✅ core/managers/ResponseHandler.gd - No diagnostics found
|
||||
```
|
||||
|
||||
### Python测试工具验证
|
||||
```bash
|
||||
# 快速测试
|
||||
python tests/api/quick_test.py
|
||||
# 预期结果: 6个基础API测试通过
|
||||
|
||||
# 完整测试
|
||||
python tests/api/api_client_test.py
|
||||
# 预期结果: 完整业务流程测试通过
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 使用指南
|
||||
|
||||
### 开发者日常使用
|
||||
|
||||
#### 1. 快速API测试
|
||||
```bash
|
||||
cd tests/api
|
||||
python quick_test.py
|
||||
```
|
||||
|
||||
#### 2. 完整功能验证
|
||||
```bash
|
||||
cd tests/api
|
||||
python api_client_test.py
|
||||
```
|
||||
|
||||
#### 3. Windows用户
|
||||
```bash
|
||||
cd tests/api
|
||||
run_tests.bat
|
||||
```
|
||||
|
||||
#### 4. Linux/Mac用户
|
||||
```bash
|
||||
cd tests/api
|
||||
./run_tests.sh
|
||||
```
|
||||
|
||||
### Godot开发者使用
|
||||
|
||||
#### 1. 运行AuthScene
|
||||
- 场景文件正常加载
|
||||
- Toast系统正常工作
|
||||
- 网络请求正常处理
|
||||
|
||||
#### 2. API测试脚本
|
||||
```gdscript
|
||||
# 在Godot中运行
|
||||
var api_test = preload("res://scripts/network/ApiTestScript.gd").new()
|
||||
add_child(api_test)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔍 质量保证
|
||||
|
||||
### 代码质量指标
|
||||
| 指标 | 修复前 | 修复后 | 改进 |
|
||||
|------|--------|--------|------|
|
||||
| 语法错误 | 1个 | 0个 | ✅ 完全修复 |
|
||||
| 代码行数 | ~1400行 | ~600行 | ✅ 精简57% |
|
||||
| 重复代码 | 多处 | 无 | ✅ 完全消除 |
|
||||
| 可维护性 | 中等 | 高 | ✅ 显著提升 |
|
||||
|
||||
### 功能完整性
|
||||
- ✅ 登录功能完整保留
|
||||
- ✅ 注册功能完整保留
|
||||
- ✅ 验证码功能完整保留
|
||||
- ✅ Toast显示功能增强
|
||||
- ✅ 错误处理功能增强
|
||||
|
||||
### API兼容性
|
||||
- ✅ 支持409冲突检测
|
||||
- ✅ 支持206测试模式
|
||||
- ✅ 支持429频率限制
|
||||
- ✅ 支持所有新增错误码
|
||||
- ✅ 向后兼容旧版本
|
||||
|
||||
---
|
||||
|
||||
## 📈 项目收益
|
||||
|
||||
### 开发效率提升
|
||||
1. **无需Godot引擎**: Python测试脚本可独立运行
|
||||
2. **快速验证**: 30秒内完成基础API测试
|
||||
3. **自动化支持**: 可集成到CI/CD流程
|
||||
4. **跨平台支持**: Windows/Linux/Mac都可使用
|
||||
|
||||
### 代码质量提升
|
||||
1. **消除语法错误**: AuthScene.gd现在完全可用
|
||||
2. **减少代码重复**: 使用工具类统一处理
|
||||
3. **提高可维护性**: 清晰的代码结构和注释
|
||||
4. **增强错误处理**: 支持最新API规范
|
||||
|
||||
### 测试覆盖提升
|
||||
1. **完整业务流程**: 覆盖所有用户操作场景
|
||||
2. **错误场景测试**: 验证各种异常情况
|
||||
3. **性能测试**: 包含频率限制测试
|
||||
4. **兼容性测试**: 支持不同环境测试
|
||||
|
||||
---
|
||||
|
||||
## 🚀 后续建议
|
||||
|
||||
### 短期优化
|
||||
1. **集成CI/CD**: 将Python测试脚本集成到自动化流程
|
||||
2. **监控告警**: 设置API测试失败的通知机制
|
||||
3. **性能基准**: 建立API响应时间基准线
|
||||
|
||||
### 长期规划
|
||||
1. **测试扩展**: 添加更多边界条件测试
|
||||
2. **压力测试**: 开发高并发场景测试
|
||||
3. **安全测试**: 添加安全漏洞检测测试
|
||||
|
||||
---
|
||||
|
||||
## 📚 相关资源
|
||||
|
||||
### 文档链接
|
||||
- [API文档](api-documentation.md) - 完整API接口说明
|
||||
- [测试指南](testing_guide.md) - 详细测试使用指南
|
||||
- [API更新日志](api_update_log.md) - 最新变更记录
|
||||
|
||||
### 代码文件
|
||||
- `scripts/scenes/AuthScene.gd` - 修复后的认证场景
|
||||
- `tests/api/quick_test.py` - 快速API测试脚本
|
||||
- `tests/api/api_client_test.py` - 完整API测试套件
|
||||
|
||||
### 工具脚本
|
||||
- `tests/api/run_tests.bat` - Windows测试启动器
|
||||
- `tests/api/run_tests.sh` - Linux/Mac测试启动器
|
||||
|
||||
---
|
||||
|
||||
## 🎉 总结
|
||||
|
||||
通过这次更新,我们成功:
|
||||
|
||||
1. **修复了关键问题** - AuthScene.gd的Parser Error已完全解决
|
||||
2. **提升了代码质量** - 代码更清晰、更易维护、更高效
|
||||
3. **增强了测试能力** - 提供了完整的Python API测试工具
|
||||
4. **改善了开发体验** - 无需Godot引擎即可测试API接口
|
||||
5. **保证了向后兼容** - 所有原有功能都得到保留和增强
|
||||
|
||||
现在开发者可以:
|
||||
- ✅ 正常使用AuthScene.gd进行认证界面开发
|
||||
- ✅ 使用Python脚本快速验证API接口
|
||||
- ✅ 在任何环境下进行API测试
|
||||
- ✅ 享受更好的错误处理和用户体验
|
||||
|
||||
**项目现在处于完全可用状态,支持最新的API v1.1.1规范!** 🚀
|
||||
362
docs/network_manager_setup.md
Normal file
@@ -0,0 +1,362 @@
|
||||
# NetworkManager 设置指南
|
||||
|
||||
## 概述
|
||||
|
||||
NetworkManager 是一个统一的网络请求管理器,提供了简洁的API接口和统一的错误处理机制。配合 ResponseHandler,可以大大简化网络请求的处理逻辑。
|
||||
|
||||
## 🚀 快速设置
|
||||
|
||||
### 1. 设置AutoLoad
|
||||
|
||||
在Godot编辑器中:
|
||||
|
||||
1. 打开 `Project` → `Project Settings`
|
||||
2. 切换到 `AutoLoad` 标签
|
||||
3. 添加新的AutoLoad:
|
||||
- **Path**: `res://core/managers/NetworkManager.gd`
|
||||
- **Name**: `NetworkManager`
|
||||
- **Singleton**: ✅ 勾选
|
||||
|
||||
### 2. 项目设置文件配置
|
||||
|
||||
在 `project.godot` 文件中会自动添加:
|
||||
|
||||
```ini
|
||||
[autoload]
|
||||
|
||||
NetworkManager="*res://core/managers/NetworkManager.gd"
|
||||
```
|
||||
|
||||
### 3. 验证设置
|
||||
|
||||
在任何脚本中可以直接使用:
|
||||
|
||||
```gdscript
|
||||
func _ready():
|
||||
# 直接访问全局单例
|
||||
var request_id = NetworkManager.login("username", "password", callback)
|
||||
print("请求ID: ", request_id)
|
||||
```
|
||||
|
||||
## 📚 使用方法
|
||||
|
||||
### 基本用法
|
||||
|
||||
```gdscript
|
||||
# 1. 简单的GET请求
|
||||
var request_id = NetworkManager.get_app_status(func(success, data, error_info):
|
||||
if success:
|
||||
print("应用状态: ", data)
|
||||
else:
|
||||
print("获取状态失败: ", error_info)
|
||||
)
|
||||
|
||||
# 2. 用户登录
|
||||
NetworkManager.login("username", "password", func(success, data, error_info):
|
||||
if success:
|
||||
print("登录成功: ", data.data.user.username)
|
||||
else:
|
||||
print("登录失败: ", error_info.message)
|
||||
)
|
||||
|
||||
# 3. 发送验证码
|
||||
NetworkManager.send_email_verification("test@example.com", func(success, data, error_info):
|
||||
if success:
|
||||
print("验证码已发送")
|
||||
else:
|
||||
print("发送失败: ", error_info.message)
|
||||
)
|
||||
```
|
||||
|
||||
### 配合ResponseHandler使用
|
||||
|
||||
```gdscript
|
||||
# 在回调函数中使用ResponseHandler处理响应
|
||||
func _on_login_response(success: bool, data: Dictionary, error_info: Dictionary):
|
||||
# 使用ResponseHandler统一处理
|
||||
var result = ResponseHandler.handle_login_response(success, data, error_info)
|
||||
|
||||
# 显示Toast消息
|
||||
show_toast(result.message, result.success)
|
||||
|
||||
# 执行自定义动作
|
||||
if result.custom_action.is_valid():
|
||||
result.custom_action.call()
|
||||
|
||||
# 处理成功情况
|
||||
if result.success:
|
||||
# 登录成功的处理逻辑
|
||||
login_success.emit(username)
|
||||
```
|
||||
|
||||
### 全局事件监听
|
||||
|
||||
```gdscript
|
||||
func _ready():
|
||||
# 监听全局网络事件
|
||||
NetworkManager.request_completed.connect(_on_global_request_completed)
|
||||
NetworkManager.request_failed.connect(_on_global_request_failed)
|
||||
|
||||
func _on_global_request_completed(request_id: String, success: bool, data: Dictionary):
|
||||
print("全局请求完成: ", request_id)
|
||||
# 可以在这里隐藏全局加载指示器
|
||||
|
||||
func _on_global_request_failed(request_id: String, error_type: String, message: String):
|
||||
print("全局请求失败: ", request_id, " - ", message)
|
||||
# 可以在这里显示全局错误提示
|
||||
```
|
||||
|
||||
## 🔧 高级功能
|
||||
|
||||
### 请求管理
|
||||
|
||||
```gdscript
|
||||
# 取消特定请求
|
||||
var request_id = NetworkManager.login("user", "pass", callback)
|
||||
NetworkManager.cancel_request(request_id)
|
||||
|
||||
# 取消所有请求
|
||||
NetworkManager.cancel_all_requests()
|
||||
|
||||
# 检查请求状态
|
||||
if NetworkManager.is_request_active(request_id):
|
||||
print("请求仍在进行中")
|
||||
|
||||
# 获取活动请求数量
|
||||
print("当前活动请求: ", NetworkManager.get_active_request_count())
|
||||
```
|
||||
|
||||
### 自定义请求
|
||||
|
||||
```gdscript
|
||||
# 发送自定义POST请求
|
||||
var custom_data = {
|
||||
"custom_field": "custom_value"
|
||||
}
|
||||
var request_id = NetworkManager.post_request("/custom/endpoint", custom_data, func(success, data, error_info):
|
||||
print("自定义请求完成")
|
||||
)
|
||||
|
||||
# 发送自定义GET请求
|
||||
NetworkManager.get_request("/custom/data", func(success, data, error_info):
|
||||
print("获取自定义数据")
|
||||
)
|
||||
```
|
||||
|
||||
## 📋 API接口列表
|
||||
|
||||
### 认证相关
|
||||
|
||||
| 方法 | 参数 | 说明 |
|
||||
|------|------|------|
|
||||
| `login(identifier, password, callback)` | 用户标识符、密码、回调函数 | 用户登录 |
|
||||
| `verification_code_login(identifier, code, callback)` | 用户标识符、验证码、回调函数 | 验证码登录 |
|
||||
| `send_login_verification_code(identifier, callback)` | 用户标识符、回调函数 | 发送登录验证码 |
|
||||
| `register(username, password, nickname, email, code, callback)` | 注册信息、回调函数 | 用户注册 |
|
||||
| `send_email_verification(email, callback)` | 邮箱、回调函数 | 发送邮箱验证码 |
|
||||
| `verify_email(email, code, callback)` | 邮箱、验证码、回调函数 | 验证邮箱 |
|
||||
|
||||
### 通用请求
|
||||
|
||||
| 方法 | 参数 | 说明 |
|
||||
|------|------|------|
|
||||
| `get_request(endpoint, callback, timeout)` | 端点、回调函数、超时时间 | GET请求 |
|
||||
| `post_request(endpoint, data, callback, timeout)` | 端点、数据、回调函数、超时时间 | POST请求 |
|
||||
| `put_request(endpoint, data, callback, timeout)` | 端点、数据、回调函数、超时时间 | PUT请求 |
|
||||
| `delete_request(endpoint, callback, timeout)` | 端点、回调函数、超时时间 | DELETE请求 |
|
||||
|
||||
### 请求管理
|
||||
|
||||
| 方法 | 参数 | 说明 |
|
||||
|------|------|------|
|
||||
| `cancel_request(request_id)` | 请求ID | 取消特定请求 |
|
||||
| `cancel_all_requests()` | 无 | 取消所有请求 |
|
||||
| `is_request_active(request_id)` | 请求ID | 检查请求是否活动 |
|
||||
| `get_active_request_count()` | 无 | 获取活动请求数量 |
|
||||
| `get_request_info(request_id)` | 请求ID | 获取请求详细信息 |
|
||||
|
||||
## 🎯 ResponseHandler 使用
|
||||
|
||||
### 支持的响应类型
|
||||
|
||||
| 方法 | 说明 |
|
||||
|------|------|
|
||||
| `handle_login_response()` | 处理登录响应 |
|
||||
| `handle_verification_code_login_response()` | 处理验证码登录响应 |
|
||||
| `handle_send_verification_code_response()` | 处理发送验证码响应 |
|
||||
| `handle_send_login_code_response()` | 处理发送登录验证码响应 |
|
||||
| `handle_register_response()` | 处理注册响应 |
|
||||
| `handle_verify_email_response()` | 处理邮箱验证响应 |
|
||||
| `handle_network_test_response()` | 处理网络测试响应 |
|
||||
| `handle_response(operation_type, ...)` | 通用响应处理 |
|
||||
|
||||
### ResponseResult 结构
|
||||
|
||||
```gdscript
|
||||
class ResponseResult:
|
||||
var success: bool # 是否成功
|
||||
var message: String # 显示消息
|
||||
var toast_type: String # Toast类型 ("success" 或 "error")
|
||||
var data: Dictionary # 响应数据
|
||||
var should_show_toast: bool # 是否显示Toast
|
||||
var custom_action: Callable # 自定义动作
|
||||
```
|
||||
|
||||
## 🔄 迁移指南
|
||||
|
||||
### 从旧版AuthScene迁移
|
||||
|
||||
#### 旧代码:
|
||||
```gdscript
|
||||
func send_login_request(username: String, password: String):
|
||||
var url = API_BASE_URL + "/auth/login"
|
||||
var headers = ["Content-Type: application/json"]
|
||||
var body = JSON.stringify({
|
||||
"username": username,
|
||||
"password": password
|
||||
})
|
||||
|
||||
current_request_type = "login"
|
||||
|
||||
var error = http_request.request(url, headers, HTTPClient.METHOD_POST, body)
|
||||
if error != OK:
|
||||
show_toast('网络请求失败', false)
|
||||
restore_button(login_btn, "密码登录")
|
||||
current_request_type = ""
|
||||
```
|
||||
|
||||
#### 新代码:
|
||||
```gdscript
|
||||
func send_login_request(username: String, password: String):
|
||||
NetworkManager.login(username, password, _on_login_response)
|
||||
|
||||
func _on_login_response(success: bool, data: Dictionary, error_info: Dictionary):
|
||||
var result = ResponseHandler.handle_login_response(success, data, error_info)
|
||||
show_toast(result.message, result.success)
|
||||
|
||||
if result.success:
|
||||
login_success.emit(username)
|
||||
```
|
||||
|
||||
### 迁移步骤
|
||||
|
||||
1. **设置AutoLoad**:按照上述步骤设置NetworkManager为AutoLoad
|
||||
2. **替换请求方法**:将直接的HTTP请求替换为NetworkManager调用
|
||||
3. **统一响应处理**:使用ResponseHandler处理所有响应
|
||||
4. **移除重复代码**:删除重复的错误处理和请求构建代码
|
||||
5. **测试功能**:确保所有功能正常工作
|
||||
|
||||
## 🧪 测试
|
||||
|
||||
### 单元测试示例
|
||||
|
||||
```gdscript
|
||||
extends GutTest
|
||||
|
||||
func test_network_manager_login():
|
||||
var network_manager = NetworkManager.new()
|
||||
var callback_called = false
|
||||
var callback_success = false
|
||||
|
||||
var callback = func(success, data, error_info):
|
||||
callback_called = true
|
||||
callback_success = success
|
||||
|
||||
var request_id = network_manager.login("testuser", "password", callback)
|
||||
|
||||
assert_ne(request_id, "", "应该返回有效的请求ID")
|
||||
|
||||
# 等待请求完成
|
||||
await get_tree().create_timer(2.0).timeout
|
||||
|
||||
assert_true(callback_called, "回调函数应该被调用")
|
||||
```
|
||||
|
||||
### 集成测试
|
||||
|
||||
```gdscript
|
||||
func test_complete_login_flow():
|
||||
# 1. 发送登录验证码
|
||||
var code_sent = false
|
||||
NetworkManager.send_login_verification_code("test@example.com", func(success, data, error_info):
|
||||
code_sent = success
|
||||
)
|
||||
|
||||
await get_tree().create_timer(1.0).timeout
|
||||
assert_true(code_sent, "验证码应该发送成功")
|
||||
|
||||
# 2. 使用验证码登录
|
||||
var login_success = false
|
||||
NetworkManager.verification_code_login("test@example.com", "123456", func(success, data, error_info):
|
||||
login_success = success
|
||||
)
|
||||
|
||||
await get_tree().create_timer(1.0).timeout
|
||||
assert_true(login_success, "验证码登录应该成功")
|
||||
```
|
||||
|
||||
## 🔍 调试
|
||||
|
||||
### 启用详细日志
|
||||
|
||||
在NetworkManager中,所有请求都会输出详细的调试信息:
|
||||
|
||||
```
|
||||
=== 发送网络请求 ===
|
||||
请求ID: req_1
|
||||
URL: https://whaletownend.xinghangee.icu/auth/login
|
||||
方法: POST
|
||||
Headers: ["Content-Type: application/json"]
|
||||
Body: {"username":"testuser","password":"password123"}
|
||||
发送结果: 0
|
||||
|
||||
=== 网络请求完成 ===
|
||||
请求ID: req_1
|
||||
结果: 0
|
||||
状态码: 200
|
||||
响应头: ["content-type: application/json"]
|
||||
响应体长度: 156 字节
|
||||
响应内容: {"success":true,"data":{"user":{"username":"testuser"}}}
|
||||
```
|
||||
|
||||
### 常见问题
|
||||
|
||||
1. **请求ID为空**:检查NetworkManager是否正确设置为AutoLoad
|
||||
2. **回调未调用**:检查网络连接和API地址是否正确
|
||||
3. **解析错误**:检查服务器返回的JSON格式是否正确
|
||||
|
||||
## 📈 性能优化
|
||||
|
||||
### 请求池管理
|
||||
|
||||
NetworkManager自动管理请求资源:
|
||||
- 自动清理完成的请求
|
||||
- 防止内存泄漏
|
||||
- 支持请求取消
|
||||
|
||||
### 最佳实践
|
||||
|
||||
1. **及时取消不需要的请求**
|
||||
2. **使用合适的超时时间**
|
||||
3. **避免同时发送大量请求**
|
||||
4. **在场景切换时取消活动请求**
|
||||
|
||||
```gdscript
|
||||
func _exit_tree():
|
||||
# 场景退出时取消所有请求
|
||||
NetworkManager.cancel_all_requests()
|
||||
```
|
||||
|
||||
## 🎉 总结
|
||||
|
||||
使用NetworkManager和ResponseHandler的优势:
|
||||
|
||||
- ✅ **代码简洁**:一行代码发送请求
|
||||
- ✅ **统一处理**:所有错误情况统一处理
|
||||
- ✅ **易于维护**:网络逻辑与UI逻辑分离
|
||||
- ✅ **功能强大**:支持请求管理、超时、取消等
|
||||
- ✅ **调试友好**:详细的日志和错误信息
|
||||
- ✅ **类型安全**:明确的回调参数类型
|
||||
- ✅ **可扩展**:易于添加新的API接口
|
||||
|
||||
通过这套统一的网络管理系统,你的项目将拥有更好的代码结构和更强的可维护性!
|
||||
28
docs/setup.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# 项目设置指南
|
||||
|
||||
## AutoLoad 配置
|
||||
|
||||
在 Godot 编辑器中设置 NetworkManager 为全局单例:
|
||||
|
||||
1. 打开 `Project` → `Project Settings`
|
||||
2. 切换到 `AutoLoad` 标签
|
||||
3. 添加新的 AutoLoad:
|
||||
- **Path**: `res://core/managers/NetworkManager.gd`
|
||||
- **Name**: `NetworkManager`
|
||||
- **Singleton**: ✅ 勾选
|
||||
|
||||
## 验证设置
|
||||
|
||||
在任何脚本中可以直接使用:
|
||||
|
||||
```gdscript
|
||||
func _ready():
|
||||
var request_id = NetworkManager.login("username", "password", callback)
|
||||
print("请求ID: ", request_id)
|
||||
```
|
||||
|
||||
## 注意事项
|
||||
|
||||
- 确保 NetworkManager.gd 和 ResponseHandler.gd 文件存在
|
||||
- 重启 Godot 编辑器以确保 AutoLoad 生效
|
||||
- 检查控制台是否有错误信息
|
||||
312
docs/testing_guide.md
Normal file
@@ -0,0 +1,312 @@
|
||||
# API接口测试指南
|
||||
|
||||
**更新日期**: 2025-12-25
|
||||
**适用版本**: API v1.1.1
|
||||
|
||||
---
|
||||
|
||||
## 🎯 测试概述
|
||||
|
||||
本指南提供了完整的API接口测试方案,包括Godot内置测试和独立的Python测试脚本,确保在不同环境下都能有效验证API功能。
|
||||
|
||||
---
|
||||
|
||||
## 📋 测试工具对比
|
||||
|
||||
| 测试工具 | 适用场景 | 优势 | 使用难度 |
|
||||
|----------|----------|------|----------|
|
||||
| **Python快速测试** | 日常检查 | 快速、简单 | ⭐ |
|
||||
| **Python完整测试** | 全面验证 | 覆盖全面、详细 | ⭐⭐ |
|
||||
| **Godot内置测试** | 引擎环境 | 真实环境、UI测试 | ⭐⭐⭐ |
|
||||
| **简单连接测试** | 基础检查 | 最小依赖 | ⭐ |
|
||||
|
||||
---
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 1. Python测试(推荐)
|
||||
|
||||
#### 安装依赖
|
||||
```bash
|
||||
cd tests/api
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
#### 运行快速测试
|
||||
```bash
|
||||
# Windows
|
||||
run_tests.bat
|
||||
|
||||
# Linux/Mac
|
||||
./run_tests.sh
|
||||
|
||||
# 或直接运行
|
||||
python quick_test.py
|
||||
```
|
||||
|
||||
### 2. Godot测试
|
||||
|
||||
#### 运行API测试脚本
|
||||
```gdscript
|
||||
# 在Godot中运行
|
||||
var api_test = preload("res://scripts/network/ApiTestScript.gd").new()
|
||||
add_child(api_test)
|
||||
```
|
||||
|
||||
#### 运行UI测试
|
||||
```bash
|
||||
# 打开Godot项目
|
||||
# 运行 tests/auth/auth_ui_test.tscn 场景
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 测试类型详解
|
||||
|
||||
### 1. 快速测试 (`quick_test.py`)
|
||||
|
||||
**用途**: 日常开发中的快速验证
|
||||
**时间**: 约30秒
|
||||
**覆盖**: 基础API端点
|
||||
|
||||
```bash
|
||||
python tests/api/quick_test.py
|
||||
```
|
||||
|
||||
**测试内容**:
|
||||
- ✅ 服务器状态检查
|
||||
- ✅ 邮箱验证码发送
|
||||
- ✅ 用户登录/注册
|
||||
- ✅ 基础错误处理
|
||||
|
||||
### 2. 完整测试 (`api_client_test.py`)
|
||||
|
||||
**用途**: 发布前的全面验证
|
||||
**时间**: 约2-3分钟
|
||||
**覆盖**: 所有业务流程
|
||||
|
||||
```bash
|
||||
python tests/api/api_client_test.py
|
||||
```
|
||||
|
||||
**测试内容**:
|
||||
- 🔄 完整的用户注册流程
|
||||
- 🔄 邮箱验证流程
|
||||
- 🔄 登录流程(密码+验证码)
|
||||
- 🔄 密码重置流程
|
||||
- 🔄 错误场景测试
|
||||
- 🔄 频率限制测试
|
||||
|
||||
### 3. Godot内置测试
|
||||
|
||||
**用途**: 引擎环境下的真实测试
|
||||
**时间**: 根据测试场景而定
|
||||
**覆盖**: UI交互和网络请求
|
||||
|
||||
#### API测试脚本
|
||||
```gdscript
|
||||
# 文件: scripts/network/ApiTestScript.gd
|
||||
# 功能: 验证NetworkManager和ResponseHandler
|
||||
```
|
||||
|
||||
#### UI测试场景
|
||||
```gdscript
|
||||
# 文件: tests/auth/auth_ui_test.tscn
|
||||
# 功能: 测试认证界面的各种响应情况
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 测试配置
|
||||
|
||||
### API服务器配置
|
||||
```python
|
||||
# 默认配置
|
||||
API_BASE_URL = "https://whaletownend.xinghangee.icu"
|
||||
|
||||
# 本地开发配置
|
||||
API_BASE_URL = "http://localhost:3000"
|
||||
```
|
||||
|
||||
### 测试数据配置
|
||||
```python
|
||||
# 测试用户信息
|
||||
TEST_EMAIL = "test@example.com"
|
||||
TEST_USERNAME = "testuser"
|
||||
TEST_PASSWORD = "password123"
|
||||
```
|
||||
|
||||
### 超时配置
|
||||
```python
|
||||
DEFAULT_TIMEOUT = 30 # 秒
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📈 测试结果解读
|
||||
|
||||
### 成功标志
|
||||
- ✅ **测试通过** - 功能正常
|
||||
- 🧪 **测试模式** - 开发环境,验证码在响应中返回
|
||||
- 🔑 **获取验证码** - 成功获取到测试验证码
|
||||
|
||||
### 警告标志
|
||||
- ⚠️ **资源冲突** - 409状态码,用户名/邮箱已存在
|
||||
- ⏰ **频率限制** - 429状态码,请求过于频繁
|
||||
|
||||
### 错误标志
|
||||
- ❌ **测试失败** - 功能异常,需要检查
|
||||
- 🔌 **连接失败** - 网络问题或服务器不可用
|
||||
- 📊 **状态码异常** - HTTP状态码不符合预期
|
||||
|
||||
### 示例输出解读
|
||||
```
|
||||
🧪 测试: 发送邮箱验证码
|
||||
📡 POST https://whaletownend.xinghangee.icu/auth/send-email-verification
|
||||
📦 数据: {"email": "test@example.com"}
|
||||
📊 状态码: 206
|
||||
🧪 测试模式响应
|
||||
🔑 验证码: 123456
|
||||
✅ 测试通过
|
||||
```
|
||||
|
||||
**解读**:
|
||||
- 请求成功发送到正确的端点
|
||||
- 返回206状态码表示测试模式
|
||||
- 成功获取验证码123456
|
||||
- 整体测试通过
|
||||
|
||||
---
|
||||
|
||||
## 🐛 故障排除
|
||||
|
||||
### 常见问题及解决方案
|
||||
|
||||
#### 1. 连接失败
|
||||
**症状**: `❌ 连接失败` 或 `网络连接异常`
|
||||
|
||||
**解决方案**:
|
||||
```bash
|
||||
# 检查网络连接
|
||||
ping whaletownend.xinghangee.icu
|
||||
|
||||
# 检查服务器状态
|
||||
curl https://whaletownend.xinghangee.icu
|
||||
|
||||
# 检查防火墙设置
|
||||
```
|
||||
|
||||
#### 2. 频率限制
|
||||
**症状**: `⏰ 请求过于频繁` 或 `429状态码`
|
||||
|
||||
**解决方案**:
|
||||
- 等待冷却时间(通常1分钟)
|
||||
- 使用不同的测试邮箱
|
||||
- 检查API频率限制配置
|
||||
|
||||
#### 3. 验证码错误
|
||||
**症状**: `验证码错误或已过期`
|
||||
|
||||
**解决方案**:
|
||||
- 确保使用最新获取的验证码
|
||||
- 检查验证码是否在5分钟有效期内
|
||||
- 在测试模式下使用响应中返回的验证码
|
||||
|
||||
#### 4. 参数验证失败
|
||||
**症状**: `400状态码` 或 `参数验证失败`
|
||||
|
||||
**解决方案**:
|
||||
- 检查请求参数格式
|
||||
- 确认必填字段都已提供
|
||||
- 验证邮箱、用户名格式是否正确
|
||||
|
||||
#### 5. Python依赖问题
|
||||
**症状**: `ModuleNotFoundError: No module named 'requests'`
|
||||
|
||||
**解决方案**:
|
||||
```bash
|
||||
# 安装依赖
|
||||
pip install requests
|
||||
|
||||
# 或使用requirements.txt
|
||||
pip install -r tests/api/requirements.txt
|
||||
|
||||
# 检查Python版本
|
||||
python --version
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📝 测试最佳实践
|
||||
|
||||
### 1. 测试前准备
|
||||
- 确认API服务器正常运行
|
||||
- 检查网络连接稳定
|
||||
- 准备测试数据(邮箱、用户名等)
|
||||
|
||||
### 2. 测试执行
|
||||
- 按照从简单到复杂的顺序执行测试
|
||||
- 记录测试结果和异常情况
|
||||
- 对失败的测试进行重试验证
|
||||
|
||||
### 3. 测试后分析
|
||||
- 分析测试结果,识别问题模式
|
||||
- 更新测试用例覆盖新发现的场景
|
||||
- 文档化测试发现的问题和解决方案
|
||||
|
||||
### 4. 持续集成
|
||||
- 将测试脚本集成到CI/CD流程
|
||||
- 设置自动化测试触发条件
|
||||
- 建立测试结果通知机制
|
||||
|
||||
---
|
||||
|
||||
## 🔄 测试流程建议
|
||||
|
||||
### 开发阶段
|
||||
1. **快速测试** - 每次代码修改后运行
|
||||
2. **功能测试** - 新功能开发完成后运行
|
||||
3. **回归测试** - 修复bug后运行
|
||||
|
||||
### 测试阶段
|
||||
1. **完整测试** - 每日构建后运行
|
||||
2. **压力测试** - 定期运行频率限制测试
|
||||
3. **兼容性测试** - 不同环境下运行测试
|
||||
|
||||
### 发布阶段
|
||||
1. **预发布测试** - 生产环境部署前运行
|
||||
2. **冒烟测试** - 生产环境部署后运行
|
||||
3. **监控测试** - 生产环境持续监控
|
||||
|
||||
---
|
||||
|
||||
## 📚 相关文档
|
||||
|
||||
- [API文档](api-documentation.md) - 完整的API接口说明
|
||||
- [API更新日志](api_update_log.md) - 最新的API变更记录
|
||||
- [项目结构说明](project_structure.md) - 项目整体架构
|
||||
- [网络管理器设置](network_manager_setup.md) - Godot网络配置
|
||||
|
||||
---
|
||||
|
||||
## 🤝 贡献指南
|
||||
|
||||
### 添加新测试
|
||||
1. 在对应的测试文件中添加新的测试方法
|
||||
2. 遵循现有的测试模式和命名规范
|
||||
3. 添加适当的错误处理和结果验证
|
||||
4. 更新相关文档
|
||||
|
||||
### 报告问题
|
||||
1. 提供详细的错误信息和复现步骤
|
||||
2. 包含测试环境信息(Python版本、操作系统等)
|
||||
3. 附上相关的日志和截图
|
||||
|
||||
### 改进建议
|
||||
1. 提出测试覆盖的改进建议
|
||||
2. 优化测试执行效率的方案
|
||||
3. 增强测试结果可读性的想法
|
||||
|
||||
---
|
||||
|
||||
**测试愉快!🎉**
|
||||
200
docs/web_deployment_changelog.md
Normal file
@@ -0,0 +1,200 @@
|
||||
# Web部署更新日志
|
||||
|
||||
## v1.0.0 (2025-12-25)
|
||||
|
||||
### 🎉 初始版本
|
||||
- 创建完整的Web导出解决方案
|
||||
- 支持Windows、Linux、macOS平台
|
||||
- 自动化构建和部署脚本
|
||||
|
||||
### 📁 文件结构
|
||||
```
|
||||
scripts/
|
||||
├── build_web.bat # Windows导出脚本
|
||||
├── build_web.sh # Linux/macOS导出脚本
|
||||
├── serve_web.bat # Windows本地服务器
|
||||
└── serve_web.sh # Linux/macOS本地服务器
|
||||
|
||||
docs/
|
||||
├── web_deployment_guide.md # 完整部署指南
|
||||
└── web_deployment_changelog.md # 更新日志
|
||||
```
|
||||
|
||||
### ✨ 主要特性
|
||||
|
||||
#### 自动化导出
|
||||
- 智能检测Godot安装路径
|
||||
- 验证项目文件完整性
|
||||
- 自动备份旧版本
|
||||
- 生成部署配置文件
|
||||
- 文件大小统计和优化建议
|
||||
|
||||
#### 本地测试服务器
|
||||
- 自动端口检测和冲突处理
|
||||
- 支持局域网访问
|
||||
- 实时文件监控
|
||||
- 自动打开浏览器
|
||||
- 详细的调试信息
|
||||
|
||||
#### 服务器配置
|
||||
- Apache .htaccess自动生成
|
||||
- Nginx配置示例
|
||||
- MIME类型配置
|
||||
- CORS头设置
|
||||
- 文件压缩优化
|
||||
- 缓存策略配置
|
||||
|
||||
#### 部署优化
|
||||
- 资源文件压缩
|
||||
- 渐进式Web应用支持
|
||||
- 性能监控
|
||||
- 错误诊断工具
|
||||
|
||||
### 🔧 技术规格
|
||||
|
||||
#### 支持的平台
|
||||
- **开发环境**: Windows 10+, macOS 10.15+, Ubuntu 18.04+
|
||||
- **目标浏览器**: Chrome 80+, Firefox 75+, Safari 13+, Edge 80+
|
||||
- **Godot版本**: 4.5+
|
||||
|
||||
#### 系统要求
|
||||
- **Godot Engine**: 4.5或更高版本
|
||||
- **Python**: 3.6+(用于本地测试)
|
||||
- **磁盘空间**: 至少100MB可用空间
|
||||
- **内存**: 建议4GB以上
|
||||
|
||||
#### 网络要求
|
||||
- **带宽**: 建议10Mbps以上(用于资源下载)
|
||||
- **端口**: 8000(默认),8080(备用)
|
||||
- **协议**: HTTP/HTTPS
|
||||
|
||||
### 📋 配置选项
|
||||
|
||||
#### 导出设置
|
||||
```
|
||||
导出预设: Web
|
||||
渲染方法: gl_compatibility
|
||||
纹理压缩: 启用VRAM压缩
|
||||
文件格式: WASM + PCK
|
||||
```
|
||||
|
||||
#### 服务器设置
|
||||
```
|
||||
默认端口: 8000
|
||||
备用端口: 8080
|
||||
文档根目录: build/web/
|
||||
索引文件: index.html
|
||||
```
|
||||
|
||||
### 🚀 性能优化
|
||||
|
||||
#### 文件大小优化
|
||||
- WASM文件压缩率: ~30%
|
||||
- 纹理压缩: ETC2/ASTC格式
|
||||
- 音频压缩: OGG Vorbis
|
||||
- 脚本压缩: 移除调试信息
|
||||
|
||||
#### 加载速度优化
|
||||
- 启用Gzip压缩
|
||||
- 设置缓存策略
|
||||
- 使用CDN加速
|
||||
- 实现预加载机制
|
||||
|
||||
### 🛡️ 安全特性
|
||||
|
||||
#### 跨域安全
|
||||
- CORS头配置
|
||||
- CSP策略设置
|
||||
- XSS防护
|
||||
- 点击劫持防护
|
||||
|
||||
#### 文件安全
|
||||
- MIME类型验证
|
||||
- 文件大小限制
|
||||
- 路径遍历防护
|
||||
- 敏感文件隐藏
|
||||
|
||||
### 📊 监控和诊断
|
||||
|
||||
#### 构建监控
|
||||
- 文件完整性检查
|
||||
- 大小统计分析
|
||||
- 构建时间记录
|
||||
- 错误日志收集
|
||||
|
||||
#### 运行时监控
|
||||
- 性能指标收集
|
||||
- 错误报告系统
|
||||
- 用户行为分析
|
||||
- 网络请求监控
|
||||
|
||||
### 🔄 兼容性
|
||||
|
||||
#### 浏览器兼容性
|
||||
| 浏览器 | 最低版本 | 推荐版本 | 支持特性 |
|
||||
|--------|----------|----------|----------|
|
||||
| Chrome | 80 | 最新 | 完整支持 |
|
||||
| Firefox | 75 | 最新 | 完整支持 |
|
||||
| Safari | 13 | 最新 | 基本支持 |
|
||||
| Edge | 80 | 最新 | 完整支持 |
|
||||
|
||||
#### 移动端兼容性
|
||||
- iOS Safari 13+
|
||||
- Android Chrome 80+
|
||||
- 响应式设计支持
|
||||
- 触摸操作优化
|
||||
|
||||
### 📝 已知问题
|
||||
|
||||
#### 当前限制
|
||||
1. **文件系统访问**: Web版本无法直接访问本地文件系统
|
||||
2. **性能差异**: 相比原生版本可能有10-30%的性能损失
|
||||
3. **内存限制**: 受浏览器内存限制影响
|
||||
4. **网络依赖**: 需要稳定的网络连接
|
||||
|
||||
#### 解决方案
|
||||
1. 使用IndexedDB存储本地数据
|
||||
2. 优化资源和代码以提升性能
|
||||
3. 实现内存管理和垃圾回收
|
||||
4. 添加离线缓存支持
|
||||
|
||||
### 🔮 未来计划
|
||||
|
||||
#### v1.1.0 (计划中)
|
||||
- [ ] PWA(渐进式Web应用)完整支持
|
||||
- [ ] 离线模式实现
|
||||
- [ ] 自动更新机制
|
||||
- [ ] 性能分析工具
|
||||
|
||||
#### v1.2.0 (计划中)
|
||||
- [ ] WebRTC多人游戏支持
|
||||
- [ ] WebGL 2.0优化
|
||||
- [ ] 移动端手势优化
|
||||
- [ ] 云存档同步
|
||||
|
||||
#### v2.0.0 (远期计划)
|
||||
- [ ] WebAssembly SIMD支持
|
||||
- [ ] Web Workers多线程
|
||||
- [ ] WebXR虚拟现实支持
|
||||
- [ ] 边缘计算集成
|
||||
|
||||
### 📞 技术支持
|
||||
|
||||
#### 问题报告
|
||||
如遇到问题,请提供以下信息:
|
||||
1. 操作系统和版本
|
||||
2. 浏览器类型和版本
|
||||
3. Godot版本
|
||||
4. 错误日志和截图
|
||||
5. 复现步骤
|
||||
|
||||
#### 联系方式
|
||||
- 项目文档: `docs/web_deployment_guide.md`
|
||||
- 构建日志: `build/web/server.log`
|
||||
- 部署信息: `build/web/deploy_info.json`
|
||||
|
||||
---
|
||||
|
||||
**维护者**: 鲸鱼镇开发团队
|
||||
**最后更新**: 2025-12-25
|
||||
**文档版本**: 1.0.0
|
||||
553
docs/web_deployment_guide.md
Normal file
@@ -0,0 +1,553 @@
|
||||
# Web部署完整指南
|
||||
|
||||
**版本**: 1.0.0
|
||||
**更新时间**: 2025-12-25
|
||||
**适用于**: Godot 4.5+ 项目
|
||||
|
||||
## 📋 目录
|
||||
|
||||
1. [导出准备](#导出准备)
|
||||
2. [Godot编辑器配置](#godot编辑器配置)
|
||||
3. [自动化导出脚本](#自动化导出脚本)
|
||||
4. [本地测试](#本地测试)
|
||||
5. [生产环境部署](#生产环境部署)
|
||||
6. [服务器配置](#服务器配置)
|
||||
7. [性能优化](#性能优化)
|
||||
8. [常见问题解决](#常见问题解决)
|
||||
|
||||
---
|
||||
|
||||
## 🚀 导出准备
|
||||
|
||||
### 系统要求
|
||||
- Godot 4.5+
|
||||
- Python 3.x(用于本地测试服务器)
|
||||
- Web服务器(Apache/Nginx/IIS等)
|
||||
|
||||
### 项目结构检查
|
||||
确保项目结构完整:
|
||||
```
|
||||
whaleTown/
|
||||
├── assets/ # 游戏资源
|
||||
├── core/ # 核心系统
|
||||
├── scenes/ # 场景文件
|
||||
├── scripts/ # 脚本文件
|
||||
├── docs/ # 文档
|
||||
├── build/ # 导出目录(自动创建)
|
||||
└── project.godot # 项目配置
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ Godot编辑器配置
|
||||
|
||||
### 1. 下载导出模板
|
||||
1. 打开Godot编辑器
|
||||
2. 点击 `Project` → `Export...`
|
||||
3. 点击 `Manage Export Templates...`
|
||||
4. 点击 `Download and Install` 下载Godot 4.5导出模板
|
||||
5. 等待下载完成
|
||||
|
||||
### 2. 创建Web导出预设
|
||||
1. 在Export窗口中点击 `Add...`
|
||||
2. 选择 `Web` 平台
|
||||
3. 配置以下设置:
|
||||
|
||||
#### 基本设置
|
||||
```
|
||||
Name: Web
|
||||
Export Path: build/web/index.html
|
||||
Runnable: ✓ 启用
|
||||
Dedicated Server: ✗ 禁用
|
||||
```
|
||||
|
||||
#### Web选项
|
||||
```
|
||||
Variant: release
|
||||
Vram Texture Compression: ✓ 启用
|
||||
Export Type: Regular
|
||||
Custom HTML Shell: res://assets/web/custom_shell.html
|
||||
Head Include: (留空,已在自定义模板中配置)
|
||||
```
|
||||
|
||||
#### 高级选项
|
||||
```
|
||||
Custom HTML Shell: res://assets/web/custom_shell.html
|
||||
Progressive Web App: ✓ 启用(可选)
|
||||
Icon 144x144: res://icon.svg
|
||||
Icon 180x180: res://icon.svg
|
||||
Icon 512x512: res://icon.svg
|
||||
```
|
||||
|
||||
### 3. 项目设置优化
|
||||
在 `Project Settings` 中配置:
|
||||
|
||||
#### 渲染设置
|
||||
```
|
||||
Rendering > Renderer:
|
||||
- Rendering Method: gl_compatibility
|
||||
- Rendering Method Mobile: gl_compatibility
|
||||
|
||||
Rendering > Textures:
|
||||
- VRAM Compression > Import ETC2 ASTC: ✓
|
||||
```
|
||||
|
||||
#### 网络设置
|
||||
```
|
||||
Network > SSL:
|
||||
- Certificates Bundle: (如果需要HTTPS API调用)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 自动化导出脚本
|
||||
|
||||
### Windows批处理脚本
|
||||
|
||||
创建 `scripts/build_web.bat`:
|
||||
```batch
|
||||
@echo off
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
echo ========================================
|
||||
echo 鲸鱼镇 Web版本导出工具
|
||||
echo ========================================
|
||||
echo.
|
||||
|
||||
REM 配置变量
|
||||
set "PROJECT_NAME=whaleTown"
|
||||
set "BUILD_DIR=build\web"
|
||||
set "GODOT_PATH=C:\Program Files\Godot\Godot.exe"
|
||||
set "EXPORT_PRESET=Web"
|
||||
|
||||
REM 检查Godot是否存在
|
||||
if not exist "%GODOT_PATH%" (
|
||||
echo [错误] 未找到Godot可执行文件: %GODOT_PATH%
|
||||
echo 请修改脚本中的GODOT_PATH变量
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
REM 创建构建目录
|
||||
echo [信息] 创建构建目录...
|
||||
if not exist "build" mkdir "build"
|
||||
if not exist "%BUILD_DIR%" mkdir "%BUILD_DIR%"
|
||||
|
||||
REM 清理旧文件
|
||||
echo [信息] 清理旧的导出文件...
|
||||
if exist "%BUILD_DIR%\*" del /q "%BUILD_DIR%\*"
|
||||
|
||||
REM 导出项目
|
||||
echo [信息] 开始导出Web版本...
|
||||
echo 导出路径: %BUILD_DIR%\index.html
|
||||
echo.
|
||||
|
||||
"%GODOT_PATH%" --headless --export-release "%EXPORT_PRESET%" "%BUILD_DIR%\index.html"
|
||||
|
||||
if %ERRORLEVEL% neq 0 (
|
||||
echo [错误] 导出失败!错误代码: %ERRORLEVEL%
|
||||
pause
|
||||
exit /b %ERRORLEVEL%
|
||||
)
|
||||
|
||||
REM 复制额外文件
|
||||
echo [信息] 复制配置文件...
|
||||
copy "web\*.json" "%BUILD_DIR%\" >nul 2>&1
|
||||
copy "web\*.ico" "%BUILD_DIR%\" >nul 2>&1
|
||||
|
||||
REM 生成部署信息
|
||||
echo [信息] 生成部署信息...
|
||||
echo {> "%BUILD_DIR%\deploy_info.json"
|
||||
echo "project": "%PROJECT_NAME%",>> "%BUILD_DIR%\deploy_info.json"
|
||||
echo "version": "1.0.0",>> "%BUILD_DIR%\deploy_info.json"
|
||||
echo "build_time": "%date% %time%",>> "%BUILD_DIR%\deploy_info.json"
|
||||
echo "platform": "web">> "%BUILD_DIR%\deploy_info.json"
|
||||
echo }>> "%BUILD_DIR%\deploy_info.json"
|
||||
|
||||
echo.
|
||||
echo ========================================
|
||||
echo 导出完成!
|
||||
echo ========================================
|
||||
echo 导出位置: %BUILD_DIR%\
|
||||
echo 文件大小:
|
||||
for %%f in ("%BUILD_DIR%\*") do echo %%~nxf: %%~zf bytes
|
||||
|
||||
echo.
|
||||
echo 下一步:
|
||||
echo 1. 运行 scripts\serve_web.bat 进行本地测试
|
||||
echo 2. 将 %BUILD_DIR%\ 目录上传到Web服务器
|
||||
echo.
|
||||
pause
|
||||
```
|
||||
|
||||
### 本地测试服务器脚本
|
||||
|
||||
创建 `scripts/serve_web.bat`:
|
||||
```batch
|
||||
@echo off
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
echo ========================================
|
||||
echo 鲸鱼镇 本地Web服务器
|
||||
echo ========================================
|
||||
echo.
|
||||
|
||||
set "BUILD_DIR=build\web"
|
||||
set "PORT=8000"
|
||||
|
||||
REM 检查导出文件
|
||||
if not exist "%BUILD_DIR%\index.html" (
|
||||
echo [错误] 未找到Web导出文件!
|
||||
echo 请先运行 scripts\build_web.bat 导出项目
|
||||
echo.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
REM 检查Python
|
||||
python --version >nul 2>&1
|
||||
if %ERRORLEVEL% neq 0 (
|
||||
echo [错误] 未找到Python!
|
||||
echo 请安装Python 3.x: https://python.org
|
||||
echo.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
REM 显示文件信息
|
||||
echo [信息] Web文件信息:
|
||||
for %%f in ("%BUILD_DIR%\*") do (
|
||||
set "size=%%~zf"
|
||||
set /a "size_mb=!size!/1024/1024"
|
||||
echo %%~nxf: !size_mb! MB
|
||||
)
|
||||
|
||||
echo.
|
||||
echo [信息] 启动本地服务器...
|
||||
echo 端口: %PORT%
|
||||
echo 目录: %BUILD_DIR%
|
||||
echo.
|
||||
echo ========================================
|
||||
echo 在浏览器中访问: http://localhost:%PORT%
|
||||
echo 按 Ctrl+C 停止服务器
|
||||
echo ========================================
|
||||
echo.
|
||||
|
||||
REM 切换到构建目录并启动服务器
|
||||
cd "%BUILD_DIR%"
|
||||
python -m http.server %PORT%
|
||||
|
||||
echo.
|
||||
echo 服务器已停止
|
||||
pause
|
||||
```
|
||||
|
||||
### Linux/macOS脚本
|
||||
|
||||
创建 `scripts/build_web.sh`:
|
||||
```bash
|
||||
#!/bin/bash
|
||||
|
||||
echo "========================================"
|
||||
echo " 鲸鱼镇 Web版本导出工具"
|
||||
echo "========================================"
|
||||
echo
|
||||
|
||||
# 配置变量
|
||||
PROJECT_NAME="whaleTown"
|
||||
BUILD_DIR="build/web"
|
||||
GODOT_PATH="/usr/local/bin/godot" # 根据实际安装路径修改
|
||||
EXPORT_PRESET="Web"
|
||||
|
||||
# 检查Godot
|
||||
if [ ! -f "$GODOT_PATH" ]; then
|
||||
echo "[错误] 未找到Godot: $GODOT_PATH"
|
||||
echo "请修改脚本中的GODOT_PATH变量"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 创建构建目录
|
||||
echo "[信息] 创建构建目录..."
|
||||
mkdir -p "$BUILD_DIR"
|
||||
|
||||
# 清理旧文件
|
||||
echo "[信息] 清理旧文件..."
|
||||
rm -f "$BUILD_DIR"/*
|
||||
|
||||
# 导出项目
|
||||
echo "[信息] 开始导出Web版本..."
|
||||
"$GODOT_PATH" --headless --export-release "$EXPORT_PRESET" "$BUILD_DIR/index.html"
|
||||
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "[错误] 导出失败!"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 生成部署信息
|
||||
echo "[信息] 生成部署信息..."
|
||||
cat > "$BUILD_DIR/deploy_info.json" << EOF
|
||||
{
|
||||
"project": "$PROJECT_NAME",
|
||||
"version": "1.0.0",
|
||||
"build_time": "$(date)",
|
||||
"platform": "web"
|
||||
}
|
||||
EOF
|
||||
|
||||
echo
|
||||
echo "========================================"
|
||||
echo " 导出完成!"
|
||||
echo "========================================"
|
||||
echo "导出位置: $BUILD_DIR/"
|
||||
echo
|
||||
echo "下一步:"
|
||||
echo "1. 运行 scripts/serve_web.sh 进行本地测试"
|
||||
echo "2. 将 $BUILD_DIR/ 目录上传到Web服务器"
|
||||
echo
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🌐 生产环境部署
|
||||
|
||||
### 1. 文件上传清单
|
||||
确保上传以下文件到Web服务器:
|
||||
```
|
||||
build/web/
|
||||
├── index.html # 主HTML文件
|
||||
├── index.js # JavaScript引导文件
|
||||
├── index.wasm # WebAssembly主文件
|
||||
├── index.pck # Godot资源包
|
||||
├── index.worker.js # Web Worker文件
|
||||
├── favicon.ico # 网站图标
|
||||
└── deploy_info.json # 部署信息(可选)
|
||||
```
|
||||
|
||||
### 2. 目录权限设置
|
||||
```bash
|
||||
# Linux服务器权限设置
|
||||
chmod 644 build/web/*
|
||||
chmod 755 build/web/
|
||||
```
|
||||
|
||||
### 3. 域名配置
|
||||
- 确保域名正确解析到服务器
|
||||
- 配置SSL证书(推荐使用Let's Encrypt)
|
||||
- 设置CDN加速(可选)
|
||||
|
||||
---
|
||||
|
||||
## 🔧 服务器配置
|
||||
|
||||
### Apache配置 (.htaccess)
|
||||
```apache
|
||||
# MIME类型配置
|
||||
AddType application/wasm .wasm
|
||||
AddType application/octet-stream .pck
|
||||
AddType application/javascript .js
|
||||
|
||||
# 启用压缩
|
||||
<IfModule mod_deflate.c>
|
||||
AddOutputFilterByType DEFLATE text/html text/css application/javascript application/wasm
|
||||
AddOutputFilterByType DEFLATE application/json application/xml
|
||||
</IfModule>
|
||||
|
||||
# 缓存控制
|
||||
<IfModule mod_expires.c>
|
||||
ExpiresActive On
|
||||
ExpiresByType application/wasm "access plus 1 month"
|
||||
ExpiresByType application/octet-stream "access plus 1 month"
|
||||
ExpiresByType application/javascript "access plus 1 week"
|
||||
ExpiresByType text/html "access plus 1 hour"
|
||||
</IfModule>
|
||||
|
||||
# CORS配置(如果需要)
|
||||
<IfModule mod_headers.c>
|
||||
Header set Access-Control-Allow-Origin "*"
|
||||
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
|
||||
Header set Access-Control-Allow-Headers "Content-Type, Authorization"
|
||||
|
||||
# SharedArrayBuffer支持
|
||||
Header set Cross-Origin-Embedder-Policy "require-corp"
|
||||
Header set Cross-Origin-Opener-Policy "same-origin"
|
||||
</IfModule>
|
||||
|
||||
# 安全配置
|
||||
<IfModule mod_headers.c>
|
||||
Header always set X-Content-Type-Options nosniff
|
||||
Header always set X-Frame-Options DENY
|
||||
Header always set X-XSS-Protection "1; mode=block"
|
||||
</IfModule>
|
||||
```
|
||||
|
||||
### Nginx配置
|
||||
```nginx
|
||||
server {
|
||||
listen 80;
|
||||
listen 443 ssl http2;
|
||||
server_name yourdomain.com;
|
||||
|
||||
# SSL配置
|
||||
ssl_certificate /path/to/certificate.crt;
|
||||
ssl_certificate_key /path/to/private.key;
|
||||
|
||||
root /var/www/whaletown/build/web;
|
||||
index index.html;
|
||||
|
||||
# MIME类型
|
||||
location ~* \.wasm$ {
|
||||
add_header Content-Type application/wasm;
|
||||
expires 1M;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
location ~* \.pck$ {
|
||||
add_header Content-Type application/octet-stream;
|
||||
expires 1M;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
location ~* \.js$ {
|
||||
add_header Content-Type application/javascript;
|
||||
expires 1w;
|
||||
}
|
||||
|
||||
# 压缩配置
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
gzip_min_length 1024;
|
||||
gzip_types
|
||||
text/html
|
||||
text/css
|
||||
application/javascript
|
||||
application/wasm
|
||||
application/json;
|
||||
|
||||
# CORS配置
|
||||
add_header Access-Control-Allow-Origin "*" always;
|
||||
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
|
||||
add_header Access-Control-Allow-Headers "Content-Type, Authorization" always;
|
||||
|
||||
# SharedArrayBuffer支持
|
||||
add_header Cross-Origin-Embedder-Policy "require-corp" always;
|
||||
add_header Cross-Origin-Opener-Policy "same-origin" always;
|
||||
|
||||
# 安全头
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header X-Frame-Options DENY always;
|
||||
add_header X-XSS-Protection "1; mode=block" always;
|
||||
|
||||
# 主页面
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
# API代理(如果需要)
|
||||
location /api/ {
|
||||
proxy_pass https://whaletownend.xinghangee.icu/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⚡ 性能优化
|
||||
|
||||
### 1. 资源优化
|
||||
- **纹理压缩**: 启用VRAM纹理压缩
|
||||
- **音频压缩**: 使用OGG格式,调整比特率
|
||||
- **模型优化**: 减少多边形数量,优化LOD
|
||||
|
||||
### 2. 代码优化
|
||||
```gdscript
|
||||
# 在Web平台禁用不必要的功能
|
||||
func _ready():
|
||||
if OS.has_feature("web"):
|
||||
# 禁用文件系统操作
|
||||
# 优化渲染设置
|
||||
get_viewport().render_target_update_mode = Viewport.UPDATE_WHEN_VISIBLE
|
||||
```
|
||||
|
||||
### 3. 加载优化
|
||||
- 使用资源预加载
|
||||
- 实现渐进式加载
|
||||
- 显示加载进度
|
||||
|
||||
---
|
||||
|
||||
## 🐛 常见问题解决
|
||||
|
||||
### 1. SharedArrayBuffer错误
|
||||
**问题**: 控制台显示SharedArrayBuffer相关错误
|
||||
**解决**: 配置正确的HTTP头:
|
||||
```
|
||||
Cross-Origin-Embedder-Policy: require-corp
|
||||
Cross-Origin-Opener-Policy: same-origin
|
||||
```
|
||||
|
||||
### 2. 文件加载失败
|
||||
**问题**: WASM或PCK文件加载失败
|
||||
**解决**:
|
||||
- 检查MIME类型配置
|
||||
- 确保文件路径正确
|
||||
- 检查服务器权限
|
||||
|
||||
### 3. API请求失败
|
||||
**问题**: 网络请求被CORS阻止
|
||||
**解决**:
|
||||
- 配置服务器CORS头
|
||||
- 使用API代理
|
||||
- 检查API服务器配置
|
||||
|
||||
### 4. 性能问题
|
||||
**问题**: Web版本运行缓慢
|
||||
**解决**:
|
||||
- 启用WebGL2
|
||||
- 优化资源大小
|
||||
- 使用性能分析工具
|
||||
|
||||
### 5. 音频问题
|
||||
**问题**: 音频无法播放
|
||||
**解决**:
|
||||
- 用户交互后才能播放音频
|
||||
- 使用Web兼容的音频格式
|
||||
- 检查浏览器音频策略
|
||||
|
||||
---
|
||||
|
||||
## 📊 部署检查清单
|
||||
|
||||
### 导出前检查
|
||||
- [ ] Godot导出模板已安装
|
||||
- [ ] Web导出预设已配置
|
||||
- [ ] 项目设置已优化
|
||||
- [ ] 资源文件已压缩
|
||||
|
||||
### 部署前检查
|
||||
- [ ] 所有文件已上传
|
||||
- [ ] 服务器MIME类型已配置
|
||||
- [ ] CORS设置已配置
|
||||
- [ ] SSL证书已安装
|
||||
|
||||
### 部署后测试
|
||||
- [ ] 页面正常加载
|
||||
- [ ] 游戏功能正常
|
||||
- [ ] 网络请求正常
|
||||
- [ ] 音频播放正常
|
||||
- [ ] 移动端兼容性
|
||||
|
||||
---
|
||||
|
||||
## 📞 技术支持
|
||||
|
||||
如果遇到问题,请检查:
|
||||
1. 浏览器开发者工具的控制台错误
|
||||
2. 网络请求是否成功
|
||||
3. 服务器配置是否正确
|
||||
4. Godot版本是否兼容
|
||||
|
||||
**更新日志**: 查看 `docs/web_deployment_changelog.md`
|
||||
45
export_presets.cfg
Normal file
@@ -0,0 +1,45 @@
|
||||
[preset.0]
|
||||
|
||||
name="Web"
|
||||
platform="Web"
|
||||
runnable=true
|
||||
advanced_options=false
|
||||
dedicated_server=false
|
||||
custom_features=""
|
||||
export_filter="all_resources"
|
||||
include_filter=""
|
||||
exclude_filter=""
|
||||
export_path="web_assets/index.html"
|
||||
patches=PackedStringArray()
|
||||
encryption_include_filters=""
|
||||
encryption_exclude_filters=""
|
||||
seed=0
|
||||
encrypt_pck=false
|
||||
encrypt_directory=false
|
||||
script_export_mode=2
|
||||
|
||||
[preset.0.options]
|
||||
|
||||
custom_template/debug=""
|
||||
custom_template/release=""
|
||||
variant/extensions_support=false
|
||||
variant/thread_support=false
|
||||
vram_texture_compression/for_desktop=true
|
||||
vram_texture_compression/for_mobile=false
|
||||
html/export_icon=true
|
||||
html/custom_html_shell=""
|
||||
html/head_include=""
|
||||
html/canvas_resize_policy=2
|
||||
html/focus_canvas_on_start=true
|
||||
html/experimental_virtual_keyboard=false
|
||||
progressive_web_app/enabled=true
|
||||
progressive_web_app/ensure_cross_origin_isolation_headers=true
|
||||
progressive_web_app/offline_page=""
|
||||
progressive_web_app/display=1
|
||||
progressive_web_app/orientation=0
|
||||
progressive_web_app/icon_144x144="uid://bwy5r7soxi76a"
|
||||
progressive_web_app/icon_180x180="uid://drpllpsjdiaex"
|
||||
progressive_web_app/icon_512x512="uid://dt817lem3dwee"
|
||||
progressive_web_app/background_color=Color(0.19215687, 0.42352942, 1, 1)
|
||||
threads/emscripten_pool_size=8
|
||||
threads/godot_pool_size=4
|
||||
@@ -20,6 +20,12 @@ config/icon="res://icon.svg"
|
||||
GameManager="*res://core/managers/GameManager.gd"
|
||||
SceneManager="*res://core/managers/SceneManager.gd"
|
||||
EventSystem="*res://core/systems/EventSystem.gd"
|
||||
NetworkManager="*res://core/managers/NetworkManager.gd"
|
||||
ResponseHandler="*res://core/managers/ResponseHandler.gd"
|
||||
|
||||
[debug]
|
||||
|
||||
gdscript/warnings/treat_warnings_as_errors=false
|
||||
|
||||
[display]
|
||||
|
||||
@@ -28,3 +34,18 @@ window/size/viewport_height=768
|
||||
window/size/mode=2
|
||||
window/stretch/mode="canvas_items"
|
||||
window/stretch/aspect="expand"
|
||||
|
||||
[gui]
|
||||
|
||||
theme/custom="uid://cp7t8tu7rmyad"
|
||||
|
||||
[internationalization]
|
||||
|
||||
locale/test="zh_CN"
|
||||
|
||||
[rendering]
|
||||
|
||||
renderer/rendering_method="gl_compatibility"
|
||||
renderer/rendering_method.mobile="gl_compatibility"
|
||||
textures/vram_compression/import_etc2_astc=true
|
||||
fonts/dynamic_fonts/use_oversampling=true
|
||||
|
||||
@@ -221,6 +221,50 @@ theme_override_colors/font_placeholder_color = Color(0.5, 0.5, 0.5, 1)
|
||||
placeholder_text = "请输入密码"
|
||||
secret = true
|
||||
|
||||
[node name="VerificationContainer" type="VBoxContainer" parent="CenterContainer/LoginPanel/VBoxContainer/LoginForm"]
|
||||
visible = false
|
||||
layout_mode = 2
|
||||
|
||||
[node name="VerificationLabelContainer" type="HBoxContainer" parent="CenterContainer/LoginPanel/VBoxContainer/LoginForm/VerificationContainer"]
|
||||
layout_mode = 2
|
||||
|
||||
[node name="VerificationLabel" type="Label" parent="CenterContainer/LoginPanel/VBoxContainer/LoginForm/VerificationContainer/VerificationLabelContainer"]
|
||||
layout_mode = 2
|
||||
theme_override_colors/font_color = Color(0, 0, 0, 1)
|
||||
text = "验证码"
|
||||
|
||||
[node name="RequiredStar" type="Label" parent="CenterContainer/LoginPanel/VBoxContainer/LoginForm/VerificationContainer/VerificationLabelContainer"]
|
||||
layout_mode = 2
|
||||
theme_override_colors/font_color = Color(1, 0.2, 0.2, 1)
|
||||
text = " *"
|
||||
|
||||
[node name="Spacer" type="Control" parent="CenterContainer/LoginPanel/VBoxContainer/LoginForm/VerificationContainer/VerificationLabelContainer"]
|
||||
layout_mode = 2
|
||||
size_flags_horizontal = 3
|
||||
|
||||
[node name="VerificationError" type="Label" parent="CenterContainer/LoginPanel/VBoxContainer/LoginForm/VerificationContainer/VerificationLabelContainer"]
|
||||
visible = false
|
||||
layout_mode = 2
|
||||
theme_override_colors/font_color = Color(1, 0.2, 0.2, 1)
|
||||
theme_override_font_sizes/font_size = 12
|
||||
text = "请输入验证码"
|
||||
horizontal_alignment = 2
|
||||
|
||||
[node name="VerificationInputContainer" type="HBoxContainer" parent="CenterContainer/LoginPanel/VBoxContainer/LoginForm/VerificationContainer"]
|
||||
layout_mode = 2
|
||||
|
||||
[node name="VerificationInput" type="LineEdit" parent="CenterContainer/LoginPanel/VBoxContainer/LoginForm/VerificationContainer/VerificationInputContainer"]
|
||||
layout_mode = 2
|
||||
size_flags_horizontal = 3
|
||||
theme_override_colors/font_color = Color(0, 0, 0, 1)
|
||||
theme_override_colors/font_placeholder_color = Color(0.5, 0.5, 0.5, 1)
|
||||
placeholder_text = "请输入6位验证码"
|
||||
max_length = 6
|
||||
|
||||
[node name="GetCodeBtn" type="Button" parent="CenterContainer/LoginPanel/VBoxContainer/LoginForm/VerificationContainer/VerificationInputContainer"]
|
||||
layout_mode = 2
|
||||
text = "获取验证码"
|
||||
|
||||
[node name="CheckboxContainer" type="HBoxContainer" parent="CenterContainer/LoginPanel/VBoxContainer/LoginForm"]
|
||||
layout_mode = 2
|
||||
|
||||
@@ -256,12 +300,6 @@ layout_mode = 2
|
||||
theme = SubResource("Theme_button")
|
||||
text = "密码登录"
|
||||
|
||||
[node name="ToRegisterBtn" type="Button" parent="CenterContainer/LoginPanel/VBoxContainer/ButtonContainer"]
|
||||
custom_minimum_size = Vector2(100, 35)
|
||||
layout_mode = 2
|
||||
theme = SubResource("Theme_button")
|
||||
text = "验证码登录"
|
||||
|
||||
[node name="BottomLinks" type="HBoxContainer" parent="CenterContainer/LoginPanel/VBoxContainer"]
|
||||
layout_mode = 2
|
||||
alignment = 1
|
||||
|
||||
164
scripts/README.md
Normal file
@@ -0,0 +1,164 @@
|
||||
# 鲸鱼镇 Web导出脚本
|
||||
|
||||
这个目录包含了将鲸鱼镇项目导出为Web版本的完整脚本集合。
|
||||
|
||||
## 📁 文件说明
|
||||
|
||||
### Windows脚本
|
||||
- `build_web.bat` - Web版本导出脚本
|
||||
- `serve_web.bat` - 本地测试服务器脚本
|
||||
|
||||
### Linux/macOS脚本
|
||||
- `build_web.sh` - Web版本导出脚本
|
||||
- `serve_web.sh` - 本地测试服务器脚本
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### Windows用户
|
||||
|
||||
1. **导出Web版本**
|
||||
```cmd
|
||||
scripts\build_web.bat
|
||||
```
|
||||
|
||||
2. **启动本地测试服务器**
|
||||
```cmd
|
||||
scripts\serve_web.bat
|
||||
```
|
||||
|
||||
### Linux/macOS用户
|
||||
|
||||
1. **添加执行权限**(首次使用)
|
||||
```bash
|
||||
chmod +x scripts/build_web.sh scripts/serve_web.sh
|
||||
```
|
||||
|
||||
2. **导出Web版本**
|
||||
```bash
|
||||
./scripts/build_web.sh
|
||||
```
|
||||
|
||||
3. **启动本地测试服务器**
|
||||
```bash
|
||||
./scripts/serve_web.sh
|
||||
```
|
||||
|
||||
## ⚙️ 配置要求
|
||||
|
||||
### 系统要求
|
||||
- **Godot Engine**: 4.5+
|
||||
- **Python**: 3.6+(用于本地测试服务器)
|
||||
- **磁盘空间**: 至少100MB
|
||||
|
||||
### Godot配置
|
||||
在使用脚本前,请确保:
|
||||
1. 已安装Godot 4.5或更高版本
|
||||
2. 已下载Web导出模板
|
||||
3. 已创建名为"Web"的导出预设
|
||||
|
||||
## 🔧 脚本配置
|
||||
|
||||
### 修改Godot路径
|
||||
如果Godot安装在非默认位置,请修改脚本中的路径:
|
||||
|
||||
**Windows** (`build_web.bat`):
|
||||
```batch
|
||||
set "GODOT_PATH=C:\Program Files\Godot\Godot.exe"
|
||||
```
|
||||
|
||||
**Linux/macOS** (`build_web.sh`):
|
||||
```bash
|
||||
GODOT_PATH="/usr/local/bin/godot"
|
||||
```
|
||||
|
||||
### 修改端口设置
|
||||
默认使用端口8000,如需修改请编辑服务器脚本:
|
||||
|
||||
**Windows** (`serve_web.bat`):
|
||||
```batch
|
||||
set "PORT=8000"
|
||||
```
|
||||
|
||||
**Linux/macOS** (`serve_web.sh`):
|
||||
```bash
|
||||
PORT=8000
|
||||
```
|
||||
|
||||
## 📋 使用流程
|
||||
|
||||
1. **准备阶段**
|
||||
- 确保Godot已正确安装
|
||||
- 在Godot编辑器中创建Web导出预设
|
||||
- 下载对应版本的导出模板
|
||||
|
||||
2. **导出阶段**
|
||||
- 运行导出脚本
|
||||
- 等待导出完成
|
||||
- 检查生成的文件
|
||||
|
||||
3. **测试阶段**
|
||||
- 运行本地服务器脚本
|
||||
- 在浏览器中测试功能
|
||||
- 检查控制台错误
|
||||
|
||||
4. **部署阶段**
|
||||
- 将`build/web/`目录上传到服务器
|
||||
- 配置服务器MIME类型和CORS
|
||||
- 测试线上版本
|
||||
|
||||
## 🐛 常见问题
|
||||
|
||||
### Godot未找到
|
||||
**错误**: `未找到Godot可执行文件`
|
||||
**解决**: 修改脚本中的`GODOT_PATH`变量为正确路径
|
||||
|
||||
### 导出预设不存在
|
||||
**错误**: `导出预设 "Web" 不存在`
|
||||
**解决**: 在Godot编辑器中创建Web导出预设
|
||||
|
||||
### Python未安装
|
||||
**错误**: `未找到Python`
|
||||
**解决**: 安装Python 3.6+并确保添加到PATH
|
||||
|
||||
### 端口被占用
|
||||
**错误**: `端口 8000 已被占用`
|
||||
**解决**: 脚本会自动尝试8080端口,或手动修改端口设置
|
||||
|
||||
### 文件缺失
|
||||
**错误**: `缺少必要文件`
|
||||
**解决**: 重新运行导出脚本,检查Godot配置
|
||||
|
||||
## 📊 输出文件
|
||||
|
||||
导出成功后,`build/web/`目录将包含:
|
||||
|
||||
```
|
||||
build/web/
|
||||
├── index.html # 主HTML文件
|
||||
├── index.js # JavaScript引导文件
|
||||
├── index.wasm # WebAssembly主文件
|
||||
├── index.pck # Godot资源包
|
||||
├── index.worker.js # Web Worker文件
|
||||
├── .htaccess # Apache配置文件
|
||||
├── deploy_info.json # 部署信息
|
||||
└── server.log # 服务器日志(测试时生成)
|
||||
```
|
||||
|
||||
## 🔗 相关文档
|
||||
|
||||
- [完整部署指南](../docs/web_deployment_guide.md)
|
||||
- [更新日志](../docs/web_deployment_changelog.md)
|
||||
- [API文档](../docs/api-documentation.md)
|
||||
|
||||
## 💡 提示
|
||||
|
||||
1. **首次导出**可能需要较长时间下载模板
|
||||
2. **文件较大**时建议启用服务器压缩
|
||||
3. **移动端测试**请使用真机而非模拟器
|
||||
4. **网络问题**可能影响API调用,注意CORS配置
|
||||
|
||||
---
|
||||
|
||||
**维护**: 鲸鱼镇开发团队
|
||||
**版本**: 1.0.0
|
||||
**更新**: 2025-12-25
|
||||
235
scripts/build_web.bat
Normal file
@@ -0,0 +1,235 @@
|
||||
@echo off
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
echo ========================================
|
||||
echo 鲸鱼镇 Web版本导出工具 v1.0
|
||||
echo ========================================
|
||||
echo.
|
||||
|
||||
REM 配置变量 - 请根据实际情况修改
|
||||
set "PROJECT_NAME=whaleTown"
|
||||
set "BUILD_DIR=build\web"
|
||||
set "GODOT_PATH=D:\technology\biancheng\Godot\Godot_v4.5.1-stable_win64.exe"
|
||||
set "EXPORT_PRESET=Web"
|
||||
set "VERSION=1.0.0"
|
||||
|
||||
REM 颜色代码(Windows 10+)
|
||||
set "RED=[91m"
|
||||
set "GREEN=[92m"
|
||||
set "YELLOW=[93m"
|
||||
set "BLUE=[94m"
|
||||
set "RESET=[0m"
|
||||
|
||||
REM 检查Godot是否存在
|
||||
echo %BLUE%[检查]%RESET% 验证Godot安装...
|
||||
if not exist "%GODOT_PATH%" (
|
||||
echo %RED%[错误]%RESET% 未找到Godot可执行文件: %GODOT_PATH%
|
||||
echo 请修改脚本中的GODOT_PATH变量或安装Godot 4.5+
|
||||
echo 下载地址: https://godotengine.org/download
|
||||
echo.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
REM 检查项目文件
|
||||
echo %BLUE%[检查]%RESET% 验证项目文件...
|
||||
if not exist "project.godot" (
|
||||
echo %RED%[错误]%RESET% 未找到project.godot文件!
|
||||
echo 请在项目根目录运行此脚本
|
||||
echo.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
REM 显示项目信息
|
||||
echo %GREEN%[信息]%RESET% 项目信息:
|
||||
echo 项目名称: %PROJECT_NAME%
|
||||
echo 版本号: %VERSION%
|
||||
echo Godot路径: %GODOT_PATH%
|
||||
echo 导出预设: %EXPORT_PRESET%
|
||||
echo 输出目录: %BUILD_DIR%
|
||||
echo.
|
||||
|
||||
REM 创建构建目录结构
|
||||
echo %BLUE%[构建]%RESET% 准备构建环境...
|
||||
if not exist "build" mkdir "build"
|
||||
if not exist "%BUILD_DIR%" mkdir "%BUILD_DIR%"
|
||||
if not exist "scripts" mkdir "scripts"
|
||||
|
||||
REM 备份旧版本(如果存在)
|
||||
if exist "%BUILD_DIR%\index.html" (
|
||||
echo %YELLOW%[备份]%RESET% 备份旧版本...
|
||||
set "BACKUP_DIR=build\backup\%date:~0,4%%date:~5,2%%date:~8,2%_%time:~0,2%%time:~3,2%%time:~6,2%"
|
||||
set "BACKUP_DIR=!BACKUP_DIR: =0!"
|
||||
mkdir "!BACKUP_DIR!" 2>nul
|
||||
xcopy "%BUILD_DIR%\*" "!BACKUP_DIR%\" /Y /Q >nul 2>&1
|
||||
echo 备份位置: !BACKUP_DIR!\
|
||||
)
|
||||
|
||||
REM 清理旧文件
|
||||
echo %BLUE%[清理]%RESET% 清理旧的导出文件...
|
||||
if exist "%BUILD_DIR%\*" del /q "%BUILD_DIR%\*" >nul 2>&1
|
||||
|
||||
REM 检查导出预设
|
||||
echo %BLUE%[验证]%RESET% 检查导出预设...
|
||||
"%GODOT_PATH%" --headless --export-debug "%EXPORT_PRESET%" --check-only >nul 2>&1
|
||||
if %ERRORLEVEL% neq 0 (
|
||||
echo %RED%[错误]%RESET% 导出预设 "%EXPORT_PRESET%" 不存在或配置错误!
|
||||
echo 请在Godot编辑器中创建Web导出预设
|
||||
echo.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
REM 导出项目
|
||||
echo %GREEN%[导出]%RESET% 开始导出Web版本...
|
||||
echo 目标文件: %BUILD_DIR%\index.html
|
||||
echo 请稍候...
|
||||
echo.
|
||||
|
||||
"%GODOT_PATH%" --headless --export-release "%EXPORT_PRESET%" "%BUILD_DIR%\index.html"
|
||||
|
||||
if %ERRORLEVEL% neq 0 (
|
||||
echo %RED%[失败]%RESET% 导出失败!错误代码: %ERRORLEVEL%
|
||||
echo.
|
||||
echo 可能的原因:
|
||||
echo 1. 导出模板未安装
|
||||
echo 2. 项目配置错误
|
||||
echo 3. 资源文件损坏
|
||||
echo.
|
||||
pause
|
||||
exit /b %ERRORLEVEL%
|
||||
)
|
||||
|
||||
REM 验证导出文件
|
||||
echo %BLUE%[验证]%RESET% 验证导出文件...
|
||||
set "REQUIRED_FILES=index.html index.js index.wasm index.pck"
|
||||
set "MISSING_FILES="
|
||||
|
||||
for %%f in (%REQUIRED_FILES%) do (
|
||||
if not exist "%BUILD_DIR%\%%f" (
|
||||
set "MISSING_FILES=!MISSING_FILES! %%f"
|
||||
)
|
||||
)
|
||||
|
||||
if not "!MISSING_FILES!"=="" (
|
||||
echo %RED%[错误]%RESET% 缺少必要文件:!MISSING_FILES!
|
||||
echo 导出可能不完整,请检查Godot配置
|
||||
echo.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
REM 复制额外资源
|
||||
echo %BLUE%[复制]%RESET% 复制额外资源...
|
||||
if exist "assets\web\favicon.ico" copy "assets\web\favicon.ico" "%BUILD_DIR%\" >nul 2>&1
|
||||
if exist "assets\web\manifest.json" copy "assets\web\manifest.json" "%BUILD_DIR%\" >nul 2>&1
|
||||
if exist "assets\web\service-worker.js" copy "assets\web\service-worker.js" "%BUILD_DIR%\" >nul 2>&1
|
||||
if exist "assets\web\custom_shell.html" copy "assets\web\custom_shell.html" "%BUILD_DIR%\" >nul 2>&1
|
||||
|
||||
REM 生成部署信息
|
||||
echo %BLUE%[生成]%RESET% 生成部署信息...
|
||||
(
|
||||
echo {
|
||||
echo "project": "%PROJECT_NAME%",
|
||||
echo "version": "%VERSION%",
|
||||
echo "build_time": "%date% %time%",
|
||||
echo "platform": "web",
|
||||
echo "godot_version": "4.5",
|
||||
echo "export_preset": "%EXPORT_PRESET%",
|
||||
echo "build_machine": "%COMPUTERNAME%",
|
||||
echo "build_user": "%USERNAME%"
|
||||
echo }
|
||||
) > "%BUILD_DIR%\deploy_info.json"
|
||||
|
||||
REM 生成.htaccess文件
|
||||
echo %BLUE%[配置]%RESET% 生成Apache配置文件...
|
||||
(
|
||||
echo # 鲸鱼镇 Web版本 Apache配置
|
||||
echo # 自动生成于 %date% %time%
|
||||
echo.
|
||||
echo # MIME类型配置
|
||||
echo AddType application/wasm .wasm
|
||||
echo AddType application/octet-stream .pck
|
||||
echo AddType application/javascript .js
|
||||
echo.
|
||||
echo # 启用压缩
|
||||
echo ^<IfModule mod_deflate.c^>
|
||||
echo AddOutputFilterByType DEFLATE text/html text/css application/javascript application/wasm
|
||||
echo AddOutputFilterByType DEFLATE application/json application/xml
|
||||
echo ^</IfModule^>
|
||||
echo.
|
||||
echo # 缓存控制
|
||||
echo ^<IfModule mod_expires.c^>
|
||||
echo ExpiresActive On
|
||||
echo ExpiresByType application/wasm "access plus 1 month"
|
||||
echo ExpiresByType application/octet-stream "access plus 1 month"
|
||||
echo ExpiresByType application/javascript "access plus 1 week"
|
||||
echo ExpiresByType text/html "access plus 1 hour"
|
||||
echo ^</IfModule^>
|
||||
echo.
|
||||
echo # CORS配置
|
||||
echo ^<IfModule mod_headers.c^>
|
||||
echo Header set Access-Control-Allow-Origin "*"
|
||||
echo Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
|
||||
echo Header set Access-Control-Allow-Headers "Content-Type, Authorization"
|
||||
echo Header set Cross-Origin-Embedder-Policy "require-corp"
|
||||
echo Header set Cross-Origin-Opener-Policy "same-origin"
|
||||
echo ^</IfModule^>
|
||||
) > "%BUILD_DIR%\.htaccess"
|
||||
|
||||
REM 计算文件大小
|
||||
echo %BLUE%[统计]%RESET% 计算文件大小...
|
||||
set "TOTAL_SIZE=0"
|
||||
for %%f in ("%BUILD_DIR%\*") do (
|
||||
set /a "TOTAL_SIZE+=%%~zf"
|
||||
)
|
||||
set /a "TOTAL_MB=TOTAL_SIZE/1024/1024"
|
||||
|
||||
REM 显示构建结果
|
||||
echo.
|
||||
echo ========================================
|
||||
echo %GREEN% 导出成功!%RESET%
|
||||
echo ========================================
|
||||
echo.
|
||||
echo %GREEN%[完成]%RESET% 构建统计:
|
||||
echo 导出位置: %BUILD_DIR%\
|
||||
echo 总文件大小: %TOTAL_MB% MB
|
||||
echo 构建时间: %date% %time%
|
||||
echo.
|
||||
echo %BLUE%[文件]%RESET% 导出文件列表:
|
||||
for %%f in ("%BUILD_DIR%\*") do (
|
||||
set "size=%%~zf"
|
||||
set /a "size_mb=!size!/1024/1024"
|
||||
if !size_mb! gtr 0 (
|
||||
echo %%~nxf: !size_mb! MB
|
||||
) else (
|
||||
set /a "size_kb=!size!/1024"
|
||||
echo %%~nxf: !size_kb! KB
|
||||
)
|
||||
)
|
||||
|
||||
echo.
|
||||
echo %YELLOW%[下一步]%RESET% 部署选项:
|
||||
echo 1. 本地测试: scripts\serve_web.bat
|
||||
echo 2. 上传到服务器: 将 %BUILD_DIR%\ 目录上传
|
||||
echo 3. 查看文档: docs\web_deployment_guide.md
|
||||
echo.
|
||||
echo %GREEN%[提示]%RESET% 部署前请确保:
|
||||
echo - 服务器支持WASM MIME类型
|
||||
echo - 配置了正确的CORS头
|
||||
echo - 启用了文件压缩
|
||||
echo.
|
||||
|
||||
REM 询问是否启动本地服务器
|
||||
set /p "START_SERVER=是否启动本地测试服务器?(y/N): "
|
||||
if /i "!START_SERVER!"=="y" (
|
||||
echo.
|
||||
echo %GREEN%[启动]%RESET% 启动本地服务器...
|
||||
call "scripts\serve_web.bat"
|
||||
) else (
|
||||
echo.
|
||||
echo 构建完成!可以手动运行 scripts\serve_web.bat 进行测试
|
||||
)
|
||||
|
||||
pause
|
||||
238
scripts/build_web.sh
Normal file
@@ -0,0 +1,238 @@
|
||||
#!/bin/bash
|
||||
|
||||
# 鲸鱼镇 Web版本导出工具 (Linux/macOS)
|
||||
# 版本: 1.0.0
|
||||
|
||||
# 颜色定义
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# 配置变量 - 请根据实际情况修改
|
||||
PROJECT_NAME="whaleTown"
|
||||
BUILD_DIR="build/web"
|
||||
GODOT_PATH="/usr/local/bin/godot" # macOS Homebrew默认路径
|
||||
# GODOT_PATH="/usr/bin/godot" # Linux包管理器默认路径
|
||||
# GODOT_PATH="$HOME/Applications/Godot.app/Contents/MacOS/Godot" # macOS应用程序路径
|
||||
EXPORT_PRESET="Web"
|
||||
VERSION="1.0.0"
|
||||
|
||||
echo "========================================"
|
||||
echo " 鲸鱼镇 Web版本导出工具 v1.0"
|
||||
echo "========================================"
|
||||
echo
|
||||
|
||||
# 检查Godot是否存在
|
||||
echo -e "${BLUE}[检查]${NC} 验证Godot安装..."
|
||||
if [ ! -f "$GODOT_PATH" ]; then
|
||||
echo -e "${RED}[错误]${NC} 未找到Godot: $GODOT_PATH"
|
||||
echo
|
||||
echo "请修改脚本中的GODOT_PATH变量或安装Godot 4.5+"
|
||||
echo "安装方法:"
|
||||
echo " macOS: brew install godot"
|
||||
echo " Ubuntu: sudo apt install godot3"
|
||||
echo " 或从官网下载: https://godotengine.org/download"
|
||||
echo
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 检查项目文件
|
||||
echo -e "${BLUE}[检查]${NC} 验证项目文件..."
|
||||
if [ ! -f "project.godot" ]; then
|
||||
echo -e "${RED}[错误]${NC} 未找到project.godot文件!"
|
||||
echo "请在项目根目录运行此脚本"
|
||||
echo
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 显示项目信息
|
||||
echo -e "${GREEN}[信息]${NC} 项目信息:"
|
||||
echo " 项目名称: $PROJECT_NAME"
|
||||
echo " 版本号: $VERSION"
|
||||
echo " Godot路径: $GODOT_PATH"
|
||||
echo " 导出预设: $EXPORT_PRESET"
|
||||
echo " 输出目录: $BUILD_DIR"
|
||||
echo
|
||||
|
||||
# 创建构建目录结构
|
||||
echo -e "${BLUE}[构建]${NC} 准备构建环境..."
|
||||
mkdir -p "$BUILD_DIR"
|
||||
mkdir -p "scripts"
|
||||
|
||||
# 备份旧版本(如果存在)
|
||||
if [ -f "$BUILD_DIR/index.html" ]; then
|
||||
echo -e "${YELLOW}[备份]${NC} 备份旧版本..."
|
||||
BACKUP_DIR="build/backup/$(date +%Y%m%d_%H%M%S)"
|
||||
mkdir -p "$BACKUP_DIR"
|
||||
cp -r "$BUILD_DIR"/* "$BACKUP_DIR/" 2>/dev/null
|
||||
echo " 备份位置: $BACKUP_DIR/"
|
||||
fi
|
||||
|
||||
# 清理旧文件
|
||||
echo -e "${BLUE}[清理]${NC} 清理旧的导出文件..."
|
||||
rm -f "$BUILD_DIR"/*
|
||||
|
||||
# 检查导出预设
|
||||
echo -e "${BLUE}[验证]${NC} 检查导出预设..."
|
||||
"$GODOT_PATH" --headless --export-debug "$EXPORT_PRESET" --check-only >/dev/null 2>&1
|
||||
if [ $? -ne 0 ]; then
|
||||
echo -e "${RED}[错误]${NC} 导出预设 \"$EXPORT_PRESET\" 不存在或配置错误!"
|
||||
echo "请在Godot编辑器中创建Web导出预设"
|
||||
echo
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 导出项目
|
||||
echo -e "${GREEN}[导出]${NC} 开始导出Web版本..."
|
||||
echo " 目标文件: $BUILD_DIR/index.html"
|
||||
echo " 请稍候..."
|
||||
echo
|
||||
|
||||
"$GODOT_PATH" --headless --export-release "$EXPORT_PRESET" "$BUILD_DIR/index.html"
|
||||
|
||||
if [ $? -ne 0 ]; then
|
||||
echo -e "${RED}[失败]${NC} 导出失败!"
|
||||
echo
|
||||
echo "可能的原因:"
|
||||
echo "1. 导出模板未安装"
|
||||
echo "2. 项目配置错误"
|
||||
echo "3. 资源文件损坏"
|
||||
echo
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 验证导出文件
|
||||
echo -e "${BLUE}[验证]${NC} 验证导出文件..."
|
||||
REQUIRED_FILES="index.html index.js index.wasm index.pck"
|
||||
MISSING_FILES=""
|
||||
|
||||
for file in $REQUIRED_FILES; do
|
||||
if [ ! -f "$BUILD_DIR/$file" ]; then
|
||||
MISSING_FILES="$MISSING_FILES $file"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -n "$MISSING_FILES" ]; then
|
||||
echo -e "${RED}[错误]${NC} 缺少必要文件:$MISSING_FILES"
|
||||
echo "导出可能不完整,请检查Godot配置"
|
||||
echo
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 复制额外资源
|
||||
echo -e "${BLUE}[复制]${NC} 复制额外资源..."
|
||||
[ -f "assets/web/favicon.ico" ] && cp "assets/web/favicon.ico" "$BUILD_DIR/"
|
||||
[ -f "assets/web/manifest.json" ] && cp "assets/web/manifest.json" "$BUILD_DIR/"
|
||||
[ -f "assets/web/service-worker.js" ] && cp "assets/web/service-worker.js" "$BUILD_DIR/"
|
||||
[ -f "assets/web/custom_shell.html" ] && cp "assets/web/custom_shell.html" "$BUILD_DIR/"
|
||||
|
||||
# 生成部署信息
|
||||
echo -e "${BLUE}[生成]${NC} 生成部署信息..."
|
||||
cat > "$BUILD_DIR/deploy_info.json" << EOF
|
||||
{
|
||||
"project": "$PROJECT_NAME",
|
||||
"version": "$VERSION",
|
||||
"build_time": "$(date)",
|
||||
"platform": "web",
|
||||
"godot_version": "4.5",
|
||||
"export_preset": "$EXPORT_PRESET",
|
||||
"build_machine": "$(hostname)",
|
||||
"build_user": "$(whoami)",
|
||||
"build_os": "$(uname -s)"
|
||||
}
|
||||
EOF
|
||||
|
||||
# 生成.htaccess文件
|
||||
echo -e "${BLUE}[配置]${NC} 生成Apache配置文件..."
|
||||
cat > "$BUILD_DIR/.htaccess" << 'EOF'
|
||||
# 鲸鱼镇 Web版本 Apache配置
|
||||
# 自动生成
|
||||
|
||||
# MIME类型配置
|
||||
AddType application/wasm .wasm
|
||||
AddType application/octet-stream .pck
|
||||
AddType application/javascript .js
|
||||
|
||||
# 启用压缩
|
||||
<IfModule mod_deflate.c>
|
||||
AddOutputFilterByType DEFLATE text/html text/css application/javascript application/wasm
|
||||
AddOutputFilterByType DEFLATE application/json application/xml
|
||||
</IfModule>
|
||||
|
||||
# 缓存控制
|
||||
<IfModule mod_expires.c>
|
||||
ExpiresActive On
|
||||
ExpiresByType application/wasm "access plus 1 month"
|
||||
ExpiresByType application/octet-stream "access plus 1 month"
|
||||
ExpiresByType application/javascript "access plus 1 week"
|
||||
ExpiresByType text/html "access plus 1 hour"
|
||||
</IfModule>
|
||||
|
||||
# CORS配置
|
||||
<IfModule mod_headers.c>
|
||||
Header set Access-Control-Allow-Origin "*"
|
||||
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
|
||||
Header set Access-Control-Allow-Headers "Content-Type, Authorization"
|
||||
Header set Cross-Origin-Embedder-Policy "require-corp"
|
||||
Header set Cross-Origin-Opener-Policy "same-origin"
|
||||
</IfModule>
|
||||
EOF
|
||||
|
||||
# 计算文件大小
|
||||
echo -e "${BLUE}[统计]${NC} 计算文件大小..."
|
||||
TOTAL_SIZE=$(du -sb "$BUILD_DIR" | cut -f1)
|
||||
TOTAL_MB=$((TOTAL_SIZE / 1024 / 1024))
|
||||
|
||||
# 显示构建结果
|
||||
echo
|
||||
echo "========================================"
|
||||
echo -e "${GREEN} 导出成功!${NC}"
|
||||
echo "========================================"
|
||||
echo
|
||||
echo -e "${GREEN}[完成]${NC} 构建统计:"
|
||||
echo " 导出位置: $BUILD_DIR/"
|
||||
echo " 总文件大小: ${TOTAL_MB} MB"
|
||||
echo " 构建时间: $(date)"
|
||||
echo
|
||||
|
||||
echo -e "${BLUE}[文件]${NC} 导出文件列表:"
|
||||
for file in "$BUILD_DIR"/*; do
|
||||
if [ -f "$file" ]; then
|
||||
filename=$(basename "$file")
|
||||
size=$(stat -f%z "$file" 2>/dev/null || stat -c%s "$file" 2>/dev/null)
|
||||
size_mb=$((size / 1024 / 1024))
|
||||
if [ $size_mb -gt 0 ]; then
|
||||
echo " $filename: ${size_mb} MB"
|
||||
else
|
||||
size_kb=$((size / 1024))
|
||||
echo " $filename: ${size_kb} KB"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
echo
|
||||
echo -e "${YELLOW}[下一步]${NC} 部署选项:"
|
||||
echo " 1. 本地测试: ./scripts/serve_web.sh"
|
||||
echo " 2. 上传到服务器: 将 $BUILD_DIR/ 目录上传"
|
||||
echo " 3. 查看文档: docs/web_deployment_guide.md"
|
||||
echo
|
||||
|
||||
echo -e "${GREEN}[提示]${NC} 部署前请确保:"
|
||||
echo " - 服务器支持WASM MIME类型"
|
||||
echo " - 配置了正确的CORS头"
|
||||
echo " - 启用了文件压缩"
|
||||
echo
|
||||
|
||||
# 询问是否启动本地服务器
|
||||
echo -n "是否启动本地测试服务器?(y/N): "
|
||||
read -r START_SERVER
|
||||
if [[ $START_SERVER =~ ^[Yy]$ ]]; then
|
||||
echo
|
||||
echo -e "${GREEN}[启动]${NC} 启动本地服务器..."
|
||||
./scripts/serve_web.sh
|
||||
else
|
||||
echo
|
||||
echo "构建完成!可以手动运行 ./scripts/serve_web.sh 进行测试"
|
||||
fi
|
||||
183
scripts/network/ApiTestScript.gd
Normal file
@@ -0,0 +1,183 @@
|
||||
extends Node
|
||||
|
||||
# API测试脚本 - 验证更新后的接口逻辑
|
||||
class_name ApiTestScript
|
||||
|
||||
# 测试用例
|
||||
var test_cases = [
|
||||
{
|
||||
"name": "测试网络连接",
|
||||
"operation": "network_test",
|
||||
"method": "get_app_status"
|
||||
},
|
||||
{
|
||||
"name": "测试发送邮箱验证码",
|
||||
"operation": "send_code",
|
||||
"method": "send_email_verification",
|
||||
"params": ["test@example.com"]
|
||||
},
|
||||
{
|
||||
"name": "测试邮箱冲突检测",
|
||||
"operation": "send_code",
|
||||
"method": "send_email_verification",
|
||||
"params": ["existing@example.com"] # 假设这个邮箱已存在
|
||||
},
|
||||
{
|
||||
"name": "测试登录",
|
||||
"operation": "login",
|
||||
"method": "login",
|
||||
"params": ["testuser", "password123"]
|
||||
},
|
||||
{
|
||||
"name": "测试注册",
|
||||
"operation": "register",
|
||||
"method": "register",
|
||||
"params": ["newuser", "newpassword123", "新用户", "newuser@example.com", "123456"]
|
||||
}
|
||||
]
|
||||
|
||||
func _ready():
|
||||
print("=== API测试脚本启动 ===")
|
||||
print("测试最新API v1.1.1的接口逻辑和toast显示")
|
||||
|
||||
# 延迟一下确保NetworkManager已初始化
|
||||
await get_tree().create_timer(1.0).timeout
|
||||
|
||||
# 运行测试用例
|
||||
run_tests()
|
||||
|
||||
func run_tests():
|
||||
print("\n🧪 开始运行API测试用例...")
|
||||
|
||||
for i in range(test_cases.size()):
|
||||
var test_case = test_cases[i]
|
||||
print("\n--- 测试 %d: %s ---" % [i + 1, test_case.name])
|
||||
|
||||
await run_single_test(test_case)
|
||||
|
||||
# 测试间隔
|
||||
await get_tree().create_timer(2.0).timeout
|
||||
|
||||
print("\n✅ 所有测试用例执行完成")
|
||||
|
||||
func run_single_test(test_case: Dictionary):
|
||||
var operation = test_case.operation
|
||||
var method = test_case.method
|
||||
var params = test_case.get("params", [])
|
||||
|
||||
print("操作类型: ", operation)
|
||||
print("调用方法: ", method)
|
||||
print("参数: ", params)
|
||||
|
||||
# 创建回调函数
|
||||
var callback = func(success: bool, data: Dictionary, error_info: Dictionary):
|
||||
handle_test_response(test_case.name, operation, success, data, error_info)
|
||||
|
||||
# 调用对应的NetworkManager方法
|
||||
var request_id = ""
|
||||
match method:
|
||||
"get_app_status":
|
||||
request_id = NetworkManager.get_app_status(callback)
|
||||
"send_email_verification":
|
||||
if params.size() > 0:
|
||||
request_id = NetworkManager.send_email_verification(params[0], callback)
|
||||
"login":
|
||||
if params.size() >= 2:
|
||||
request_id = NetworkManager.login(params[0], params[1], callback)
|
||||
"register":
|
||||
if params.size() >= 5:
|
||||
request_id = NetworkManager.register(params[0], params[1], params[2], params[3], params[4], callback)
|
||||
_:
|
||||
print("❌ 未知的测试方法: ", method)
|
||||
return
|
||||
|
||||
if request_id != "":
|
||||
print("✅ 请求已发送,ID: ", request_id)
|
||||
else:
|
||||
print("❌ 请求发送失败")
|
||||
|
||||
func handle_test_response(test_name: String, operation: String, success: bool, data: Dictionary, error_info: Dictionary):
|
||||
print("\n=== %s 响应结果 ===" % test_name)
|
||||
print("成功: ", success)
|
||||
print("数据: ", data)
|
||||
print("错误信息: ", error_info)
|
||||
|
||||
# 使用ResponseHandler处理响应
|
||||
var result = ResponseHandler.handle_response(operation, success, data, error_info)
|
||||
|
||||
print("\n--- ResponseHandler处理结果 ---")
|
||||
print("处理成功: ", result.success)
|
||||
print("消息: ", result.message)
|
||||
print("Toast类型: ", result.toast_type)
|
||||
print("是否显示Toast: ", result.should_show_toast)
|
||||
|
||||
# 模拟Toast显示
|
||||
if result.should_show_toast:
|
||||
print("🍞 Toast显示: [%s] %s" % [result.toast_type.to_upper(), result.message])
|
||||
|
||||
# 检查特殊情况
|
||||
check_special_cases(data, error_info)
|
||||
|
||||
func check_special_cases(data: Dictionary, error_info: Dictionary):
|
||||
var response_code = error_info.get("response_code", 0)
|
||||
var error_code = data.get("error_code", "")
|
||||
|
||||
print("\n--- 特殊情况检查 ---")
|
||||
|
||||
# 检查409冲突
|
||||
if response_code == 409:
|
||||
print("✅ 检测到409冲突状态码 - 邮箱冲突检测正常工作")
|
||||
|
||||
# 检查206测试模式
|
||||
if response_code == 206 or error_code == "TEST_MODE_ONLY":
|
||||
print("✅ 检测到206测试模式 - 测试模式处理正常工作")
|
||||
if data.has("data") and data.data.has("verification_code"):
|
||||
print("🔑 测试模式验证码: ", data.data.verification_code)
|
||||
|
||||
# 检查429频率限制
|
||||
if response_code == 429 or error_code == "TOO_MANY_REQUESTS":
|
||||
print("✅ 检测到429频率限制 - 频率限制处理正常工作")
|
||||
if data.has("throttle_info"):
|
||||
print("⏰ 限制信息: ", data.throttle_info)
|
||||
|
||||
# 检查其他重要状态码
|
||||
match response_code:
|
||||
200:
|
||||
print("✅ 200 成功响应")
|
||||
201:
|
||||
print("✅ 201 创建成功")
|
||||
400:
|
||||
print("⚠️ 400 请求参数错误")
|
||||
401:
|
||||
print("⚠️ 401 认证失败")
|
||||
404:
|
||||
print("⚠️ 404 资源不存在")
|
||||
500:
|
||||
print("❌ 500 服务器内部错误")
|
||||
503:
|
||||
print("❌ 503 服务不可用")
|
||||
|
||||
# 手动触发测试的方法
|
||||
func test_email_conflict():
|
||||
print("\n🧪 手动测试邮箱冲突检测...")
|
||||
var callback = func(success: bool, data: Dictionary, error_info: Dictionary):
|
||||
handle_test_response("邮箱冲突测试", "send_code", success, data, error_info)
|
||||
|
||||
NetworkManager.send_email_verification("existing@example.com", callback)
|
||||
|
||||
func test_rate_limit():
|
||||
print("\n🧪 手动测试频率限制...")
|
||||
var callback = func(success: bool, data: Dictionary, error_info: Dictionary):
|
||||
handle_test_response("频率限制测试", "send_code", success, data, error_info)
|
||||
|
||||
# 快速发送多个请求来触发频率限制
|
||||
for i in range(3):
|
||||
NetworkManager.send_email_verification("test@example.com", callback)
|
||||
await get_tree().create_timer(0.1).timeout
|
||||
|
||||
func test_test_mode():
|
||||
print("\n🧪 手动测试测试模式...")
|
||||
var callback = func(success: bool, data: Dictionary, error_info: Dictionary):
|
||||
handle_test_response("测试模式测试", "send_code", success, data, error_info)
|
||||
|
||||
NetworkManager.send_email_verification("testmode@example.com", callback)
|
||||
1
scripts/network/ApiTestScript.gd.uid
Normal file
@@ -0,0 +1 @@
|
||||
uid://4gamylhvy4nn
|
||||
@@ -1,31 +0,0 @@
|
||||
extends Node
|
||||
|
||||
# 简单的API测试脚本
|
||||
const API_BASE_URL = "https://whaletownend.xinghangee.icu"
|
||||
|
||||
func _ready():
|
||||
print("API测试脚本已加载")
|
||||
print("服务器地址: ", API_BASE_URL)
|
||||
|
||||
# 测试服务器连接
|
||||
test_server_status()
|
||||
|
||||
func test_server_status():
|
||||
var http_request = HTTPRequest.new()
|
||||
add_child(http_request)
|
||||
http_request.request_completed.connect(_on_status_request_completed)
|
||||
|
||||
print("正在测试服务器连接...")
|
||||
var error = http_request.request(API_BASE_URL)
|
||||
if error != OK:
|
||||
print("请求失败: ", error)
|
||||
|
||||
func _on_status_request_completed(result: int, response_code: int, headers: PackedStringArray, body: PackedByteArray):
|
||||
var response_text = body.get_string_from_utf8()
|
||||
print("服务器状态响应: ", response_code)
|
||||
print("响应内容: ", response_text)
|
||||
|
||||
if response_code == 200:
|
||||
print("✅ 服务器连接正常")
|
||||
else:
|
||||
print("❌ 服务器连接失败")
|
||||
@@ -1 +0,0 @@
|
||||
uid://bsfrdqpsvwgtb
|
||||
173
scripts/serve_web.bat
Normal file
@@ -0,0 +1,173 @@
|
||||
@echo off
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
echo ========================================
|
||||
echo 鲸鱼镇 本地Web服务器 v1.0
|
||||
echo ========================================
|
||||
echo.
|
||||
|
||||
REM 配置变量
|
||||
set "BUILD_DIR=build\web"
|
||||
set "PORT=8000"
|
||||
set "FALLBACK_PORT=8080"
|
||||
|
||||
REM 颜色代码
|
||||
set "RED=[91m"
|
||||
set "GREEN=[92m"
|
||||
set "YELLOW=[93m"
|
||||
set "BLUE=[94m"
|
||||
set "RESET=[0m"
|
||||
|
||||
REM 检查导出文件
|
||||
echo %BLUE%[检查]%RESET% 验证Web导出文件...
|
||||
if not exist "%BUILD_DIR%\index.html" (
|
||||
echo %RED%[错误]%RESET% 未找到Web导出文件!
|
||||
echo.
|
||||
echo 请先运行以下命令导出项目:
|
||||
echo scripts\build_web.bat
|
||||
echo.
|
||||
echo 或在Godot编辑器中导出Web版本到: %BUILD_DIR%\
|
||||
echo.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
REM 检查必要文件
|
||||
echo %BLUE%[验证]%RESET% 检查必要文件...
|
||||
set "REQUIRED_FILES=index.html index.js index.wasm index.pck"
|
||||
set "MISSING_FILES="
|
||||
|
||||
for %%f in (%REQUIRED_FILES%) do (
|
||||
if not exist "%BUILD_DIR%\%%f" (
|
||||
set "MISSING_FILES=!MISSING_FILES! %%f"
|
||||
)
|
||||
)
|
||||
|
||||
if not "!MISSING_FILES!"=="" (
|
||||
echo %RED%[错误]%RESET% 缺少必要文件:!MISSING_FILES!
|
||||
echo 请重新导出项目
|
||||
echo.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
REM 检查Python
|
||||
echo %BLUE%[检查]%RESET% 验证Python环境...
|
||||
python --version >nul 2>&1
|
||||
if %ERRORLEVEL% neq 0 (
|
||||
echo %RED%[错误]%RESET% 未找到Python!
|
||||
echo.
|
||||
echo 请安装Python 3.x:
|
||||
echo 下载地址: https://python.org/downloads
|
||||
echo 或使用包管理器: winget install Python.Python.3
|
||||
echo.
|
||||
echo 安装后请重启命令提示符
|
||||
echo.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
REM 获取Python版本
|
||||
for /f "tokens=2" %%i in ('python --version 2^>^&1') do set "PYTHON_VERSION=%%i"
|
||||
echo %GREEN%[信息]%RESET% Python版本: %PYTHON_VERSION%
|
||||
|
||||
REM 显示文件信息
|
||||
echo.
|
||||
echo %GREEN%[信息]%RESET% Web文件统计:
|
||||
set "TOTAL_SIZE=0"
|
||||
for %%f in ("%BUILD_DIR%\*") do (
|
||||
set "size=%%~zf"
|
||||
set /a "TOTAL_SIZE+=size"
|
||||
set /a "size_mb=size/1024/1024"
|
||||
if !size_mb! gtr 0 (
|
||||
echo %%~nxf: !size_mb! MB
|
||||
) else (
|
||||
set /a "size_kb=size/1024"
|
||||
echo %%~nxf: !size_kb! KB
|
||||
)
|
||||
)
|
||||
set /a "TOTAL_MB=TOTAL_SIZE/1024/1024"
|
||||
echo 总大小: %TOTAL_MB% MB
|
||||
|
||||
REM 检查端口占用
|
||||
echo.
|
||||
echo %BLUE%[网络]%RESET% 检查端口占用...
|
||||
netstat -an | find ":%PORT%" >nul 2>&1
|
||||
if %ERRORLEVEL% equ 0 (
|
||||
echo %YELLOW%[警告]%RESET% 端口 %PORT% 已被占用,尝试使用 %FALLBACK_PORT%
|
||||
set "PORT=%FALLBACK_PORT%"
|
||||
|
||||
netstat -an | find ":%PORT%" >nul 2>&1
|
||||
if %ERRORLEVEL% equ 0 (
|
||||
echo %RED%[错误]%RESET% 端口 %PORT% 也被占用!
|
||||
echo 请手动指定端口: python -m http.server [端口号]
|
||||
echo.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
)
|
||||
|
||||
REM 获取本机IP地址
|
||||
for /f "tokens=2 delims=:" %%i in ('ipconfig ^| find "IPv4"') do (
|
||||
set "LOCAL_IP=%%i"
|
||||
set "LOCAL_IP=!LOCAL_IP: =!"
|
||||
goto :ip_found
|
||||
)
|
||||
:ip_found
|
||||
|
||||
REM 显示启动信息
|
||||
echo.
|
||||
echo %GREEN%[启动]%RESET% 启动HTTP服务器...
|
||||
echo 端口: %PORT%
|
||||
echo 目录: %BUILD_DIR%
|
||||
echo Python: %PYTHON_VERSION%
|
||||
echo.
|
||||
echo ========================================
|
||||
echo %GREEN% 访问地址%RESET%
|
||||
echo ========================================
|
||||
echo 本地访问: http://localhost:%PORT%
|
||||
echo 局域网访问: http://!LOCAL_IP!:%PORT%
|
||||
echo.
|
||||
echo %YELLOW%[控制]%RESET% 服务器控制:
|
||||
echo 停止服务器: Ctrl+C
|
||||
echo 重启服务器: 关闭后重新运行脚本
|
||||
echo.
|
||||
echo %BLUE%[调试]%RESET% 调试工具:
|
||||
echo 开发者工具: F12
|
||||
echo 控制台日志: 查看浏览器Console
|
||||
echo 网络请求: 查看Network标签
|
||||
echo.
|
||||
echo ========================================
|
||||
|
||||
REM 尝试自动打开浏览器
|
||||
echo %BLUE%[浏览器]%RESET% 尝试打开默认浏览器...
|
||||
start http://localhost:%PORT% >nul 2>&1
|
||||
if %ERRORLEVEL% neq 0 (
|
||||
echo %YELLOW%[提示]%RESET% 无法自动打开浏览器,请手动访问上述地址
|
||||
)
|
||||
|
||||
echo.
|
||||
echo %GREEN%[就绪]%RESET% 服务器启动中...
|
||||
echo.
|
||||
|
||||
REM 切换到构建目录并启动服务器
|
||||
cd "%BUILD_DIR%"
|
||||
|
||||
REM 创建简单的服务器日志
|
||||
echo [%date% %time%] 服务器启动 - 端口:%PORT% >> server.log
|
||||
|
||||
REM 启动Python HTTP服务器
|
||||
python -m http.server %PORT%
|
||||
|
||||
REM 服务器停止后的清理
|
||||
echo.
|
||||
echo %YELLOW%[停止]%RESET% 服务器已停止
|
||||
echo [%date% %time%] 服务器停止 >> server.log
|
||||
|
||||
REM 返回原目录
|
||||
cd ..\..
|
||||
|
||||
echo.
|
||||
echo %GREEN%[完成]%RESET% 感谢使用鲸鱼镇Web服务器!
|
||||
echo.
|
||||
pause
|
||||
188
scripts/serve_web.sh
Normal file
@@ -0,0 +1,188 @@
|
||||
#!/bin/bash
|
||||
|
||||
# 鲸鱼镇 本地Web服务器 (Linux/macOS)
|
||||
# 版本: 1.0.0
|
||||
|
||||
# 颜色定义
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# 配置变量
|
||||
BUILD_DIR="build/web"
|
||||
PORT=8000
|
||||
FALLBACK_PORT=8080
|
||||
|
||||
echo "========================================"
|
||||
echo " 鲸鱼镇 本地Web服务器 v1.0"
|
||||
echo "========================================"
|
||||
echo
|
||||
|
||||
# 检查导出文件
|
||||
echo -e "${BLUE}[检查]${NC} 验证Web导出文件..."
|
||||
if [ ! -f "$BUILD_DIR/index.html" ]; then
|
||||
echo -e "${RED}[错误]${NC} 未找到Web导出文件!"
|
||||
echo
|
||||
echo "请先运行以下命令导出项目:"
|
||||
echo " ./scripts/build_web.sh"
|
||||
echo
|
||||
echo "或在Godot编辑器中导出Web版本到: $BUILD_DIR/"
|
||||
echo
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 检查必要文件
|
||||
echo -e "${BLUE}[验证]${NC} 检查必要文件..."
|
||||
REQUIRED_FILES="index.html index.js index.wasm index.pck"
|
||||
MISSING_FILES=""
|
||||
|
||||
for file in $REQUIRED_FILES; do
|
||||
if [ ! -f "$BUILD_DIR/$file" ]; then
|
||||
MISSING_FILES="$MISSING_FILES $file"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -n "$MISSING_FILES" ]; then
|
||||
echo -e "${RED}[错误]${NC} 缺少必要文件:$MISSING_FILES"
|
||||
echo "请重新导出项目"
|
||||
echo
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 检查Python
|
||||
echo -e "${BLUE}[检查]${NC} 验证Python环境..."
|
||||
if ! command -v python3 &> /dev/null && ! command -v python &> /dev/null; then
|
||||
echo -e "${RED}[错误]${NC} 未找到Python!"
|
||||
echo
|
||||
echo "请安装Python 3.x:"
|
||||
echo " macOS: brew install python"
|
||||
echo " Ubuntu: sudo apt install python3"
|
||||
echo " 或访问: https://python.org/downloads"
|
||||
echo
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 确定Python命令
|
||||
PYTHON_CMD="python3"
|
||||
if ! command -v python3 &> /dev/null; then
|
||||
PYTHON_CMD="python"
|
||||
fi
|
||||
|
||||
# 获取Python版本
|
||||
PYTHON_VERSION=$($PYTHON_CMD --version 2>&1 | cut -d' ' -f2)
|
||||
echo -e "${GREEN}[信息]${NC} Python版本: $PYTHON_VERSION"
|
||||
|
||||
# 显示文件信息
|
||||
echo
|
||||
echo -e "${GREEN}[信息]${NC} Web文件统计:"
|
||||
TOTAL_SIZE=$(du -sb "$BUILD_DIR" | cut -f1)
|
||||
TOTAL_MB=$((TOTAL_SIZE / 1024 / 1024))
|
||||
|
||||
for file in "$BUILD_DIR"/*; do
|
||||
if [ -f "$file" ]; then
|
||||
filename=$(basename "$file")
|
||||
size=$(stat -f%z "$file" 2>/dev/null || stat -c%s "$file" 2>/dev/null)
|
||||
size_mb=$((size / 1024 / 1024))
|
||||
if [ $size_mb -gt 0 ]; then
|
||||
echo " $filename: ${size_mb} MB"
|
||||
else
|
||||
size_kb=$((size / 1024))
|
||||
echo " $filename: ${size_kb} KB"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
echo " 总大小: ${TOTAL_MB} MB"
|
||||
|
||||
# 检查端口占用
|
||||
echo
|
||||
echo -e "${BLUE}[网络]${NC} 检查端口占用..."
|
||||
if lsof -Pi :$PORT -sTCP:LISTEN -t >/dev/null 2>&1; then
|
||||
echo -e "${YELLOW}[警告]${NC} 端口 $PORT 已被占用,尝试使用 $FALLBACK_PORT"
|
||||
PORT=$FALLBACK_PORT
|
||||
|
||||
if lsof -Pi :$PORT -sTCP:LISTEN -t >/dev/null 2>&1; then
|
||||
echo -e "${RED}[错误]${NC} 端口 $PORT 也被占用!"
|
||||
echo "请手动指定端口: $PYTHON_CMD -m http.server [端口号]"
|
||||
echo
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# 获取本机IP地址
|
||||
LOCAL_IP=$(ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1' | head -1)
|
||||
if [ -z "$LOCAL_IP" ]; then
|
||||
LOCAL_IP=$(hostname -I | cut -d' ' -f1 2>/dev/null)
|
||||
fi
|
||||
if [ -z "$LOCAL_IP" ]; then
|
||||
LOCAL_IP="localhost"
|
||||
fi
|
||||
|
||||
# 显示启动信息
|
||||
echo
|
||||
echo -e "${GREEN}[启动]${NC} 启动HTTP服务器..."
|
||||
echo " 端口: $PORT"
|
||||
echo " 目录: $BUILD_DIR"
|
||||
echo " Python: $PYTHON_VERSION"
|
||||
echo
|
||||
|
||||
echo "========================================"
|
||||
echo -e "${GREEN} 访问地址${NC}"
|
||||
echo "========================================"
|
||||
echo " 本地访问: http://localhost:$PORT"
|
||||
echo " 局域网访问: http://$LOCAL_IP:$PORT"
|
||||
echo
|
||||
|
||||
echo -e "${YELLOW}[控制]${NC} 服务器控制:"
|
||||
echo " 停止服务器: Ctrl+C"
|
||||
echo " 重启服务器: 关闭后重新运行脚本"
|
||||
echo
|
||||
|
||||
echo -e "${BLUE}[调试]${NC} 调试工具:"
|
||||
echo " 开发者工具: F12"
|
||||
echo " 控制台日志: 查看浏览器Console"
|
||||
echo " 网络请求: 查看Network标签"
|
||||
echo
|
||||
|
||||
echo "========================================"
|
||||
|
||||
# 尝试自动打开浏览器
|
||||
echo -e "${BLUE}[浏览器]${NC} 尝试打开默认浏览器..."
|
||||
if command -v open &> /dev/null; then
|
||||
# macOS
|
||||
open "http://localhost:$PORT" 2>/dev/null
|
||||
elif command -v xdg-open &> /dev/null; then
|
||||
# Linux
|
||||
xdg-open "http://localhost:$PORT" 2>/dev/null
|
||||
else
|
||||
echo -e "${YELLOW}[提示]${NC} 无法自动打开浏览器,请手动访问上述地址"
|
||||
fi
|
||||
|
||||
echo
|
||||
echo -e "${GREEN}[就绪]${NC} 服务器启动中..."
|
||||
echo
|
||||
|
||||
# 切换到构建目录并启动服务器
|
||||
cd "$BUILD_DIR"
|
||||
|
||||
# 创建简单的服务器日志
|
||||
echo "[$(date)] 服务器启动 - 端口:$PORT" >> server.log
|
||||
|
||||
# 设置信号处理
|
||||
trap 'echo -e "\n${YELLOW}[停止]${NC} 服务器已停止"; echo "[$(date)] 服务器停止" >> server.log; exit 0' INT
|
||||
|
||||
# 启动Python HTTP服务器
|
||||
$PYTHON_CMD -m http.server $PORT
|
||||
|
||||
# 服务器停止后的清理
|
||||
echo
|
||||
echo -e "${YELLOW}[停止]${NC} 服务器已停止"
|
||||
echo "[$(date)] 服务器停止" >> server.log
|
||||
|
||||
# 返回原目录
|
||||
cd ../..
|
||||
|
||||
echo
|
||||
echo -e "${GREEN}[完成]${NC} 感谢使用鲸鱼镇Web服务器!"
|
||||
echo
|
||||
1
scripts/web_font_handler.gd.uid
Normal file
@@ -0,0 +1 @@
|
||||
uid://dvgsil07gh4tl
|
||||
@@ -4,7 +4,39 @@
|
||||
|
||||
## 测试脚本说明
|
||||
|
||||
### 1. `simple_api_test.py` - 简化版测试
|
||||
### 1. `quick_test.py` - 快速测试(推荐)
|
||||
快速验证API接口的基本功能,适合日常检查。
|
||||
|
||||
**使用方法:**
|
||||
```bash
|
||||
python tests/api/quick_test.py
|
||||
```
|
||||
|
||||
**测试内容:**
|
||||
- ✅ 应用状态检查
|
||||
- ✅ 发送邮箱验证码
|
||||
- ✅ 发送验证码(无效邮箱)
|
||||
- ✅ 用户登录
|
||||
- ✅ 用户注册(无邮箱)
|
||||
- ✅ 发送登录验证码
|
||||
|
||||
### 2. `api_client_test.py` - 完整测试套件
|
||||
全面的API接口测试,包含所有业务流程和错误场景。
|
||||
|
||||
**使用方法:**
|
||||
```bash
|
||||
python tests/api/api_client_test.py
|
||||
```
|
||||
|
||||
**测试内容:**
|
||||
- 🔄 完整的邮箱验证流程
|
||||
- 🔄 用户注册流程(带邮箱验证)
|
||||
- 🔄 用户登录流程(密码+验证码)
|
||||
- 🔄 密码重置流程
|
||||
- 🔄 错误场景测试
|
||||
- 🔄 频率限制测试
|
||||
|
||||
### 3. `simple_api_test.py` - 简化版测试
|
||||
快速验证API接口的基本连通性和功能。
|
||||
|
||||
**使用方法:**
|
||||
@@ -24,7 +56,7 @@ python tests/api/simple_api_test.py http://localhost:3000
|
||||
- ✅ 无效登录测试
|
||||
- ✅ 管理员登录测试
|
||||
|
||||
### 2. `api_test.py` - 完整版测试
|
||||
### 4. `api_test.py` - 完整版测试
|
||||
全面的API接口测试,包括边界条件和错误处理。
|
||||
|
||||
**使用方法:**
|
||||
@@ -143,8 +175,19 @@ tester.run_basic_tests()
|
||||
|
||||
## 依赖要求
|
||||
|
||||
### 安装依赖
|
||||
```bash
|
||||
# 安装Python依赖
|
||||
pip install -r tests/api/requirements.txt
|
||||
|
||||
# 或者手动安装
|
||||
pip install requests
|
||||
```
|
||||
|
||||
测试脚本使用Python标准库和requests库,无需额外依赖。
|
||||
### 依赖包说明
|
||||
- **requests** - HTTP请求库,用于发送API请求
|
||||
- **json** - JSON数据处理(Python标准库)
|
||||
- **time** - 时间处理(Python标准库)
|
||||
- **sys** - 系统功能(Python标准库)
|
||||
|
||||
测试脚本主要使用Python标准库和requests库,依赖最小化。
|
||||
427
tests/api/api_client_test.py
Normal file
@@ -0,0 +1,427 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
API客户端测试脚本
|
||||
用于在没有Godot引擎的情况下测试后端API接口
|
||||
|
||||
使用方法:
|
||||
python api_client_test.py
|
||||
"""
|
||||
|
||||
import requests
|
||||
import json
|
||||
import time
|
||||
import sys
|
||||
from typing import Dict, Any, Optional
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
|
||||
# API配置
|
||||
API_BASE_URL = "https://whaletownend.xinghangee.icu"
|
||||
DEFAULT_TIMEOUT = 30
|
||||
|
||||
@dataclass
|
||||
class TestResult:
|
||||
"""测试结果数据类"""
|
||||
success: bool
|
||||
message: str
|
||||
response_code: int
|
||||
response_data: Dict[str, Any]
|
||||
error_info: Optional[Dict[str, Any]] = None
|
||||
execution_time: float = 0.0
|
||||
|
||||
class APIClient:
|
||||
"""API客户端类"""
|
||||
|
||||
def __init__(self, base_url: str = API_BASE_URL):
|
||||
self.base_url = base_url
|
||||
self.session = requests.Session()
|
||||
self.session.headers.update({
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'WhaleTown-API-Test/1.0'
|
||||
})
|
||||
|
||||
def _make_request(self, method: str, endpoint: str, data: Optional[Dict] = None,
|
||||
timeout: int = DEFAULT_TIMEOUT) -> TestResult:
|
||||
"""发送HTTP请求"""
|
||||
url = f"{self.base_url}{endpoint}"
|
||||
start_time = time.time()
|
||||
|
||||
try:
|
||||
print(f"🚀 发送 {method} 请求到: {url}")
|
||||
if data:
|
||||
print(f"📦 请求数据: {json.dumps(data, ensure_ascii=False, indent=2)}")
|
||||
|
||||
response = self.session.request(
|
||||
method=method,
|
||||
url=url,
|
||||
json=data if data else None,
|
||||
timeout=timeout
|
||||
)
|
||||
|
||||
execution_time = time.time() - start_time
|
||||
|
||||
print(f"📊 响应状态码: {response.status_code}")
|
||||
print(f"⏱️ 执行时间: {execution_time:.3f}s")
|
||||
|
||||
# 尝试解析JSON响应
|
||||
try:
|
||||
response_data = response.json()
|
||||
print(f"📄 响应数据: {json.dumps(response_data, ensure_ascii=False, indent=2)}")
|
||||
except json.JSONDecodeError:
|
||||
response_data = {"raw_response": response.text}
|
||||
print(f"📄 原始响应: {response.text}")
|
||||
|
||||
# 判断请求是否成功
|
||||
is_success = False
|
||||
if 200 <= response.status_code < 300:
|
||||
# HTTP成功状态码
|
||||
business_success = response_data.get("success", True)
|
||||
if business_success:
|
||||
is_success = True
|
||||
elif response.status_code == 206 and response_data.get("error_code") == "TEST_MODE_ONLY":
|
||||
# 测试模式也算成功
|
||||
is_success = True
|
||||
|
||||
return TestResult(
|
||||
success=is_success,
|
||||
message=response_data.get("message", ""),
|
||||
response_code=response.status_code,
|
||||
response_data=response_data,
|
||||
execution_time=execution_time
|
||||
)
|
||||
|
||||
except requests.exceptions.Timeout:
|
||||
execution_time = time.time() - start_time
|
||||
return TestResult(
|
||||
success=False,
|
||||
message="请求超时",
|
||||
response_code=0,
|
||||
response_data={},
|
||||
error_info={"error_type": "TIMEOUT"},
|
||||
execution_time=execution_time
|
||||
)
|
||||
except requests.exceptions.ConnectionError:
|
||||
execution_time = time.time() - start_time
|
||||
return TestResult(
|
||||
success=False,
|
||||
message="网络连接失败",
|
||||
response_code=0,
|
||||
response_data={},
|
||||
error_info={"error_type": "CONNECTION_ERROR"},
|
||||
execution_time=execution_time
|
||||
)
|
||||
except Exception as e:
|
||||
execution_time = time.time() - start_time
|
||||
return TestResult(
|
||||
success=False,
|
||||
message=f"请求异常: {str(e)}",
|
||||
response_code=0,
|
||||
response_data={},
|
||||
error_info={"error_type": "UNKNOWN_ERROR", "details": str(e)},
|
||||
execution_time=execution_time
|
||||
)
|
||||
|
||||
def get_app_status(self) -> TestResult:
|
||||
"""获取应用状态"""
|
||||
return self._make_request("GET", "/")
|
||||
|
||||
def login(self, identifier: str, password: str) -> TestResult:
|
||||
"""用户登录"""
|
||||
data = {
|
||||
"identifier": identifier,
|
||||
"password": password
|
||||
}
|
||||
return self._make_request("POST", "/auth/login", data)
|
||||
|
||||
def register(self, username: str, password: str, nickname: str,
|
||||
email: str = "", email_verification_code: str = "") -> TestResult:
|
||||
"""用户注册"""
|
||||
data = {
|
||||
"username": username,
|
||||
"password": password,
|
||||
"nickname": nickname
|
||||
}
|
||||
|
||||
if email:
|
||||
data["email"] = email
|
||||
if email_verification_code:
|
||||
data["email_verification_code"] = email_verification_code
|
||||
|
||||
return self._make_request("POST", "/auth/register", data)
|
||||
|
||||
def send_email_verification(self, email: str) -> TestResult:
|
||||
"""发送邮箱验证码"""
|
||||
data = {"email": email}
|
||||
return self._make_request("POST", "/auth/send-email-verification", data)
|
||||
|
||||
def verify_email(self, email: str, verification_code: str) -> TestResult:
|
||||
"""验证邮箱验证码"""
|
||||
data = {
|
||||
"email": email,
|
||||
"verification_code": verification_code
|
||||
}
|
||||
return self._make_request("POST", "/auth/verify-email", data)
|
||||
|
||||
def send_login_verification_code(self, identifier: str) -> TestResult:
|
||||
"""发送登录验证码"""
|
||||
data = {"identifier": identifier}
|
||||
return self._make_request("POST", "/auth/send-login-verification-code", data)
|
||||
|
||||
def verification_code_login(self, identifier: str, verification_code: str) -> TestResult:
|
||||
"""验证码登录"""
|
||||
data = {
|
||||
"identifier": identifier,
|
||||
"verification_code": verification_code
|
||||
}
|
||||
return self._make_request("POST", "/auth/verification-code-login", data)
|
||||
|
||||
def forgot_password(self, identifier: str) -> TestResult:
|
||||
"""忘记密码 - 发送重置验证码"""
|
||||
data = {"identifier": identifier}
|
||||
return self._make_request("POST", "/auth/forgot-password", data)
|
||||
|
||||
def reset_password(self, identifier: str, verification_code: str, new_password: str) -> TestResult:
|
||||
"""重置密码"""
|
||||
data = {
|
||||
"identifier": identifier,
|
||||
"verification_code": verification_code,
|
||||
"new_password": new_password
|
||||
}
|
||||
return self._make_request("POST", "/auth/reset-password", data)
|
||||
|
||||
class APITester:
|
||||
"""API测试器"""
|
||||
|
||||
def __init__(self):
|
||||
self.client = APIClient()
|
||||
self.test_results = []
|
||||
self.test_email = "test@example.com"
|
||||
self.test_username = "testuser"
|
||||
self.test_password = "password123"
|
||||
self.verification_code = None
|
||||
|
||||
def print_header(self, title: str):
|
||||
"""打印测试标题"""
|
||||
print("\n" + "="*60)
|
||||
print(f"🧪 {title}")
|
||||
print("="*60)
|
||||
|
||||
def print_result(self, test_name: str, result: TestResult):
|
||||
"""打印测试结果"""
|
||||
status = "✅ 成功" if result.success else "❌ 失败"
|
||||
print(f"\n📋 测试: {test_name}")
|
||||
print(f"🎯 结果: {status}")
|
||||
print(f"💬 消息: {result.message}")
|
||||
print(f"📊 状态码: {result.response_code}")
|
||||
print(f"⏱️ 耗时: {result.execution_time:.3f}s")
|
||||
|
||||
# 检查特殊情况
|
||||
if result.response_code == 206:
|
||||
print("🧪 检测到测试模式响应")
|
||||
elif result.response_code == 409:
|
||||
print("⚠️ 检测到资源冲突")
|
||||
elif result.response_code == 429:
|
||||
print("⏰ 检测到频率限制")
|
||||
|
||||
# 提取验证码(如果有)
|
||||
if result.response_data.get("data", {}).get("verification_code"):
|
||||
self.verification_code = result.response_data["data"]["verification_code"]
|
||||
print(f"🔑 获取到验证码: {self.verification_code}")
|
||||
|
||||
self.test_results.append((test_name, result))
|
||||
print("-" * 40)
|
||||
|
||||
def test_app_status(self):
|
||||
"""测试应用状态"""
|
||||
self.print_header("应用状态测试")
|
||||
result = self.client.get_app_status()
|
||||
self.print_result("获取应用状态", result)
|
||||
|
||||
def test_email_verification_flow(self):
|
||||
"""测试邮箱验证流程"""
|
||||
self.print_header("邮箱验证流程测试")
|
||||
|
||||
# 1. 发送邮箱验证码
|
||||
result = self.client.send_email_verification(self.test_email)
|
||||
self.print_result("发送邮箱验证码", result)
|
||||
|
||||
if self.verification_code:
|
||||
# 2. 验证邮箱验证码
|
||||
result = self.client.verify_email(self.test_email, self.verification_code)
|
||||
self.print_result("验证邮箱验证码", result)
|
||||
|
||||
def test_registration_flow(self):
|
||||
"""测试注册流程"""
|
||||
self.print_header("用户注册流程测试")
|
||||
|
||||
# 使用之前获取的验证码进行注册
|
||||
if self.verification_code:
|
||||
result = self.client.register(
|
||||
username=self.test_username,
|
||||
password=self.test_password,
|
||||
nickname="测试用户",
|
||||
email=self.test_email,
|
||||
email_verification_code=self.verification_code
|
||||
)
|
||||
self.print_result("用户注册(带邮箱验证)", result)
|
||||
else:
|
||||
# 无邮箱注册
|
||||
result = self.client.register(
|
||||
username=f"{self.test_username}_no_email",
|
||||
password=self.test_password,
|
||||
nickname="测试用户(无邮箱)"
|
||||
)
|
||||
self.print_result("用户注册(无邮箱)", result)
|
||||
|
||||
def test_login_flow(self):
|
||||
"""测试登录流程"""
|
||||
self.print_header("用户登录流程测试")
|
||||
|
||||
# 1. 密码登录
|
||||
result = self.client.login(self.test_username, self.test_password)
|
||||
self.print_result("密码登录", result)
|
||||
|
||||
# 2. 发送登录验证码
|
||||
result = self.client.send_login_verification_code(self.test_email)
|
||||
self.print_result("发送登录验证码", result)
|
||||
|
||||
# 3. 验证码登录
|
||||
if self.verification_code:
|
||||
result = self.client.verification_code_login(self.test_email, self.verification_code)
|
||||
self.print_result("验证码登录", result)
|
||||
|
||||
def test_password_reset_flow(self):
|
||||
"""测试密码重置流程"""
|
||||
self.print_header("密码重置流程测试")
|
||||
|
||||
# 1. 发送重置验证码
|
||||
result = self.client.forgot_password(self.test_email)
|
||||
self.print_result("发送重置验证码", result)
|
||||
|
||||
# 2. 重置密码
|
||||
if self.verification_code:
|
||||
result = self.client.reset_password(
|
||||
identifier=self.test_email,
|
||||
verification_code=self.verification_code,
|
||||
new_password="newpassword123"
|
||||
)
|
||||
self.print_result("重置密码", result)
|
||||
|
||||
def test_error_scenarios(self):
|
||||
"""测试错误场景"""
|
||||
self.print_header("错误场景测试")
|
||||
|
||||
# 1. 无效邮箱格式
|
||||
result = self.client.send_email_verification("invalid-email")
|
||||
self.print_result("无效邮箱格式", result)
|
||||
|
||||
# 2. 错误的验证码
|
||||
result = self.client.verify_email(self.test_email, "000000")
|
||||
self.print_result("错误验证码", result)
|
||||
|
||||
# 3. 用户名冲突
|
||||
result = self.client.register(
|
||||
username=self.test_username, # 重复用户名
|
||||
password=self.test_password,
|
||||
nickname="重复用户"
|
||||
)
|
||||
self.print_result("用户名冲突", result)
|
||||
|
||||
# 4. 错误的登录凭据
|
||||
result = self.client.login("nonexistent", "wrongpassword")
|
||||
self.print_result("错误登录凭据", result)
|
||||
|
||||
def test_rate_limiting(self):
|
||||
"""测试频率限制"""
|
||||
self.print_header("频率限制测试")
|
||||
|
||||
print("🔄 快速发送多个验证码请求以触发频率限制...")
|
||||
for i in range(3):
|
||||
result = self.client.send_email_verification(f"test{i}@example.com")
|
||||
self.print_result(f"验证码请求 #{i+1}", result)
|
||||
|
||||
if result.response_code == 429:
|
||||
print("✅ 成功触发频率限制")
|
||||
break
|
||||
|
||||
time.sleep(0.5) # 短暂延迟
|
||||
|
||||
def run_all_tests(self):
|
||||
"""运行所有测试"""
|
||||
print("🎯 开始API接口测试")
|
||||
print(f"🌐 测试服务器: {API_BASE_URL}")
|
||||
print(f"📧 测试邮箱: {self.test_email}")
|
||||
print(f"👤 测试用户名: {self.test_username}")
|
||||
|
||||
try:
|
||||
# 基础测试
|
||||
self.test_app_status()
|
||||
|
||||
# 邮箱验证流程
|
||||
self.test_email_verification_flow()
|
||||
|
||||
# 注册流程
|
||||
self.test_registration_flow()
|
||||
|
||||
# 登录流程
|
||||
self.test_login_flow()
|
||||
|
||||
# 密码重置流程
|
||||
self.test_password_reset_flow()
|
||||
|
||||
# 错误场景测试
|
||||
self.test_error_scenarios()
|
||||
|
||||
# 频率限制测试
|
||||
self.test_rate_limiting()
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print("\n⚠️ 测试被用户中断")
|
||||
except Exception as e:
|
||||
print(f"\n❌ 测试过程中发生异常: {e}")
|
||||
finally:
|
||||
self.print_summary()
|
||||
|
||||
def print_summary(self):
|
||||
"""打印测试总结"""
|
||||
self.print_header("测试总结")
|
||||
|
||||
total_tests = len(self.test_results)
|
||||
successful_tests = sum(1 for _, result in self.test_results if result.success)
|
||||
failed_tests = total_tests - successful_tests
|
||||
|
||||
print(f"📊 总测试数: {total_tests}")
|
||||
print(f"✅ 成功: {successful_tests}")
|
||||
print(f"❌ 失败: {failed_tests}")
|
||||
print(f"📈 成功率: {(successful_tests/total_tests*100):.1f}%" if total_tests > 0 else "0%")
|
||||
|
||||
if failed_tests > 0:
|
||||
print("\n❌ 失败的测试:")
|
||||
for test_name, result in self.test_results:
|
||||
if not result.success:
|
||||
print(f" • {test_name}: {result.message} (状态码: {result.response_code})")
|
||||
|
||||
print(f"\n⏱️ 总执行时间: {sum(result.execution_time for _, result in self.test_results):.3f}s")
|
||||
print("🎉 测试完成!")
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
print("🐋 WhaleTown API 接口测试工具")
|
||||
print("=" * 60)
|
||||
|
||||
# 检查网络连接
|
||||
try:
|
||||
response = requests.get(API_BASE_URL, timeout=5)
|
||||
print(f"✅ 服务器连接正常 (状态码: {response.status_code})")
|
||||
except Exception as e:
|
||||
print(f"❌ 无法连接到服务器: {e}")
|
||||
print("请检查网络连接或服务器地址")
|
||||
sys.exit(1)
|
||||
|
||||
# 运行测试
|
||||
tester = APITester()
|
||||
tester.run_all_tests()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
150
tests/api/quick_test.py
Normal file
@@ -0,0 +1,150 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
快速API测试脚本
|
||||
用于快速验证API接口的基本功能
|
||||
|
||||
使用方法:
|
||||
python quick_test.py
|
||||
"""
|
||||
|
||||
import requests
|
||||
import json
|
||||
import sys
|
||||
|
||||
# API配置
|
||||
API_BASE_URL = "https://whaletownend.xinghangee.icu"
|
||||
|
||||
def test_api_endpoint(method, endpoint, data=None, description=""):
|
||||
"""测试单个API端点"""
|
||||
url = f"{API_BASE_URL}{endpoint}"
|
||||
|
||||
print(f"\n🧪 测试: {description}")
|
||||
print(f"📡 {method} {url}")
|
||||
|
||||
if data:
|
||||
print(f"📦 数据: {json.dumps(data, ensure_ascii=False)}")
|
||||
|
||||
try:
|
||||
if method == "GET":
|
||||
response = requests.get(url, timeout=10)
|
||||
elif method == "POST":
|
||||
response = requests.post(url, json=data, timeout=10)
|
||||
else:
|
||||
print(f"❌ 不支持的方法: {method}")
|
||||
return False
|
||||
|
||||
print(f"📊 状态码: {response.status_code}")
|
||||
|
||||
try:
|
||||
response_data = response.json()
|
||||
print(f"📄 响应: {json.dumps(response_data, ensure_ascii=False, indent=2)}")
|
||||
|
||||
# 检查特殊状态码
|
||||
if response.status_code == 206:
|
||||
print("🧪 测试模式响应")
|
||||
if response_data.get("data", {}).get("verification_code"):
|
||||
print(f"🔑 验证码: {response_data['data']['verification_code']}")
|
||||
elif response.status_code == 409:
|
||||
print("⚠️ 资源冲突")
|
||||
elif response.status_code == 429:
|
||||
print("⏰ 频率限制")
|
||||
|
||||
return 200 <= response.status_code < 300 or response.status_code == 206
|
||||
|
||||
except json.JSONDecodeError:
|
||||
print(f"📄 原始响应: {response.text}")
|
||||
return 200 <= response.status_code < 300
|
||||
|
||||
except requests.exceptions.Timeout:
|
||||
print("❌ 请求超时")
|
||||
return False
|
||||
except requests.exceptions.ConnectionError:
|
||||
print("❌ 连接失败")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"❌ 请求异常: {e}")
|
||||
return False
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
print("🐋 WhaleTown API 快速测试")
|
||||
print("=" * 50)
|
||||
|
||||
# 测试用例
|
||||
tests = [
|
||||
{
|
||||
"method": "GET",
|
||||
"endpoint": "/",
|
||||
"description": "获取应用状态"
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"endpoint": "/auth/send-email-verification",
|
||||
"data": {"email": "test@example.com"},
|
||||
"description": "发送邮箱验证码"
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"endpoint": "/auth/send-email-verification",
|
||||
"data": {"email": "invalid-email"},
|
||||
"description": "发送验证码(无效邮箱)"
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"endpoint": "/auth/login",
|
||||
"data": {"identifier": "testuser", "password": "password123"},
|
||||
"description": "用户登录"
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"endpoint": "/auth/register",
|
||||
"data": {
|
||||
"username": "testuser_quick",
|
||||
"password": "password123",
|
||||
"nickname": "快速测试用户"
|
||||
},
|
||||
"description": "用户注册(无邮箱)"
|
||||
},
|
||||
{
|
||||
"method": "POST",
|
||||
"endpoint": "/auth/send-login-verification-code",
|
||||
"data": {"identifier": "test@example.com"},
|
||||
"description": "发送登录验证码"
|
||||
}
|
||||
]
|
||||
|
||||
# 执行测试
|
||||
success_count = 0
|
||||
total_count = len(tests)
|
||||
|
||||
for test in tests:
|
||||
success = test_api_endpoint(
|
||||
method=test["method"],
|
||||
endpoint=test["endpoint"],
|
||||
data=test.get("data"),
|
||||
description=test["description"]
|
||||
)
|
||||
|
||||
if success:
|
||||
success_count += 1
|
||||
print("✅ 测试通过")
|
||||
else:
|
||||
print("❌ 测试失败")
|
||||
|
||||
print("-" * 30)
|
||||
|
||||
# 打印总结
|
||||
print(f"\n📊 测试总结:")
|
||||
print(f"总测试数: {total_count}")
|
||||
print(f"成功: {success_count}")
|
||||
print(f"失败: {total_count - success_count}")
|
||||
print(f"成功率: {(success_count/total_count*100):.1f}%")
|
||||
|
||||
if success_count == total_count:
|
||||
print("🎉 所有测试通过!")
|
||||
else:
|
||||
print("⚠️ 部分测试失败,请检查API服务")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
2
tests/api/requirements.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
# Python API测试依赖包
|
||||
requests>=2.25.0
|
||||
55
tests/api/run_tests.bat
Normal file
@@ -0,0 +1,55 @@
|
||||
@echo off
|
||||
chcp 65001 >nul
|
||||
echo 🐋 WhaleTown API 测试工具
|
||||
echo ========================
|
||||
|
||||
echo.
|
||||
echo 请选择要运行的测试:
|
||||
echo 1. 快速测试 (推荐)
|
||||
echo 2. 完整测试套件
|
||||
echo 3. 简单连接测试
|
||||
echo 4. 安装依赖
|
||||
echo 5. 退出
|
||||
echo.
|
||||
|
||||
set /p choice=请输入选择 (1-5):
|
||||
|
||||
if "%choice%"=="1" (
|
||||
echo.
|
||||
echo 🚀 运行快速测试...
|
||||
python quick_test.py
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%choice%"=="2" (
|
||||
echo.
|
||||
echo 🚀 运行完整测试套件...
|
||||
python api_client_test.py
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%choice%"=="3" (
|
||||
echo.
|
||||
echo 🚀 运行简单连接测试...
|
||||
python simple_api_test.py
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%choice%"=="4" (
|
||||
echo.
|
||||
echo 📦 安装Python依赖...
|
||||
pip install -r requirements.txt
|
||||
echo 依赖安装完成!
|
||||
goto end
|
||||
)
|
||||
|
||||
if "%choice%"=="5" (
|
||||
echo 👋 再见!
|
||||
goto end
|
||||
)
|
||||
|
||||
echo ❌ 无效选择,请重新运行脚本
|
||||
|
||||
:end
|
||||
echo.
|
||||
pause
|
||||
71
tests/api/run_tests.sh
Normal file
@@ -0,0 +1,71 @@
|
||||
#!/bin/bash
|
||||
|
||||
# WhaleTown API 测试工具
|
||||
echo "🐋 WhaleTown API 测试工具"
|
||||
echo "========================"
|
||||
|
||||
# 检查Python是否安装
|
||||
if ! command -v python3 &> /dev/null; then
|
||||
echo "❌ 错误: 未找到 python3,请先安装Python"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 检查是否在正确的目录
|
||||
if [ ! -f "quick_test.py" ]; then
|
||||
echo "❌ 错误: 请在 tests/api 目录下运行此脚本"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "请选择要运行的测试:"
|
||||
echo "1. 快速测试 (推荐)"
|
||||
echo "2. 完整测试套件"
|
||||
echo "3. 简单连接测试"
|
||||
echo "4. 安装依赖"
|
||||
echo "5. 退出"
|
||||
echo ""
|
||||
|
||||
read -p "请输入选择 (1-5): " choice
|
||||
|
||||
case $choice in
|
||||
1)
|
||||
echo ""
|
||||
echo "🚀 运行快速测试..."
|
||||
python3 quick_test.py
|
||||
;;
|
||||
2)
|
||||
echo ""
|
||||
echo "🚀 运行完整测试套件..."
|
||||
python3 api_client_test.py
|
||||
;;
|
||||
3)
|
||||
echo ""
|
||||
echo "🚀 运行简单连接测试..."
|
||||
python3 simple_api_test.py
|
||||
;;
|
||||
4)
|
||||
echo ""
|
||||
echo "📦 安装Python依赖..."
|
||||
if command -v pip3 &> /dev/null; then
|
||||
pip3 install -r requirements.txt
|
||||
elif command -v pip &> /dev/null; then
|
||||
pip install -r requirements.txt
|
||||
else
|
||||
echo "❌ 错误: 未找到 pip,请手动安装依赖"
|
||||
exit 1
|
||||
fi
|
||||
echo "✅ 依赖安装完成!"
|
||||
;;
|
||||
5)
|
||||
echo "👋 再见!"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "❌ 无效选择,请重新运行脚本"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
echo ""
|
||||
echo "测试完成!按任意键继续..."
|
||||
read -n 1
|
||||
@@ -403,6 +403,8 @@ func get_expected_ui_feedback(scenario: Dictionary) -> String:
|
||||
return "红色Toast: 登录请求过于频繁"
|
||||
500:
|
||||
return "红色Toast: 服务器繁忙"
|
||||
503:
|
||||
return "红色Toast: 系统维护中"
|
||||
"send_code":
|
||||
match response_code:
|
||||
200, 206:
|
||||
@@ -413,8 +415,38 @@ func get_expected_ui_feedback(scenario: Dictionary) -> String:
|
||||
return "红色Toast: 请求过于频繁"
|
||||
500:
|
||||
return "红色Toast: 服务器繁忙"
|
||||
503:
|
||||
return "红色Toast: 系统维护中"
|
||||
0:
|
||||
return "红色Toast: 网络连接失败"
|
||||
"send_login_code":
|
||||
match response_code:
|
||||
200, 206:
|
||||
return "绿色Toast: 登录验证码已发送"
|
||||
400:
|
||||
return "红色Toast: 邮箱或手机号格式错误"
|
||||
404:
|
||||
return "红色Toast: 用户不存在"
|
||||
429:
|
||||
return "红色Toast: 请求过于频繁"
|
||||
500:
|
||||
return "红色Toast: 服务器繁忙"
|
||||
503:
|
||||
return "红色Toast: 系统维护中"
|
||||
"verification_code_login":
|
||||
match response_code:
|
||||
200:
|
||||
return "绿色Toast: 验证码登录成功,跳转到主场景"
|
||||
401:
|
||||
return "红色Toast: 验证码错误或已过期"
|
||||
404:
|
||||
return "红色Toast: 用户不存在"
|
||||
429:
|
||||
return "红色Toast: 请求过于频繁"
|
||||
500:
|
||||
return "红色Toast: 服务器繁忙"
|
||||
503:
|
||||
return "红色Toast: 系统维护中"
|
||||
"verify_email":
|
||||
match response_code:
|
||||
200:
|
||||
@@ -425,6 +457,8 @@ func get_expected_ui_feedback(scenario: Dictionary) -> String:
|
||||
return "红色Toast: 请先获取验证码"
|
||||
500:
|
||||
return "红色Toast: 验证失败"
|
||||
503:
|
||||
return "红色Toast: 系统维护中"
|
||||
"register":
|
||||
match response_code:
|
||||
201:
|
||||
@@ -437,6 +471,8 @@ func get_expected_ui_feedback(scenario: Dictionary) -> String:
|
||||
return "红色Toast: 注册请求过于频繁,请稍后再试"
|
||||
500:
|
||||
return "红色Toast: 注册失败"
|
||||
503:
|
||||
return "红色Toast: 系统维护中"
|
||||
|
||||
return "未知响应"
|
||||
|
||||
|
||||
251
tests/auth/enhanced_toast_test.gd
Normal file
@@ -0,0 +1,251 @@
|
||||
extends GutTest
|
||||
|
||||
# 增强的Toast测试 - 验证新增的API响应处理
|
||||
|
||||
class_name EnhancedToastTest
|
||||
|
||||
# 测试新增的错误码处理
|
||||
func test_new_error_codes():
|
||||
var auth_scene = preload("res://scripts/scenes/AuthScene.gd").new()
|
||||
|
||||
# 测试验证码登录失败
|
||||
var verification_login_error = {
|
||||
"success": false,
|
||||
"message": "验证码错误或已过期",
|
||||
"error_code": "VERIFICATION_CODE_LOGIN_FAILED"
|
||||
}
|
||||
|
||||
# 模拟处理函数调用
|
||||
var expected_message = get_expected_toast_message("verification_code_login", 401, verification_login_error)
|
||||
assert_eq(expected_message, "红色Toast: 验证码错误或已过期")
|
||||
|
||||
# 测试邮箱未验证错误
|
||||
var email_not_verified_error = {
|
||||
"success": false,
|
||||
"message": "邮箱未验证,请先验证邮箱",
|
||||
"error_code": "EMAIL_NOT_VERIFIED"
|
||||
}
|
||||
|
||||
expected_message = get_expected_toast_message("verification_code_login", 401, email_not_verified_error)
|
||||
assert_eq(expected_message, "红色Toast: 邮箱未验证,请先验证邮箱后再使用验证码登录")
|
||||
|
||||
# 测试测试模式处理
|
||||
func test_test_mode_handling():
|
||||
var test_mode_response = {
|
||||
"success": false,
|
||||
"message": "测试模式:验证码已生成但未真实发送",
|
||||
"error_code": "TEST_MODE_ONLY",
|
||||
"data": {
|
||||
"verification_code": "123456",
|
||||
"sent_to": "test@example.com",
|
||||
"expires_in": 300,
|
||||
"is_test_mode": true
|
||||
}
|
||||
}
|
||||
|
||||
var expected_message = get_expected_toast_message("send_code", 206, test_mode_response)
|
||||
assert_eq(expected_message, "绿色Toast: 测试模式:验证码已生成,请查看控制台")
|
||||
|
||||
# 测试维护模式处理
|
||||
func test_maintenance_mode_handling():
|
||||
var maintenance_response = {
|
||||
"success": false,
|
||||
"message": "系统正在维护中,请稍后再试",
|
||||
"error_code": "SERVICE_UNAVAILABLE",
|
||||
"maintenance_info": {
|
||||
"start_time": "2025-12-24T10:00:00.000Z",
|
||||
"estimated_end_time": "2025-12-24T12:00:00.000Z",
|
||||
"retry_after": 1800,
|
||||
"reason": "系统升级维护"
|
||||
}
|
||||
}
|
||||
|
||||
var expected_message = get_expected_toast_message("login", 503, maintenance_response)
|
||||
assert_eq(expected_message, "红色Toast: 系统维护中:系统升级维护,请稍后再试")
|
||||
|
||||
# 测试频率限制详细信息处理
|
||||
func test_rate_limit_with_details():
|
||||
var rate_limit_response = {
|
||||
"success": false,
|
||||
"message": "注册请求过于频繁,请5分钟后再试",
|
||||
"error_code": "TOO_MANY_REQUESTS",
|
||||
"throttle_info": {
|
||||
"limit": 10,
|
||||
"window_seconds": 300,
|
||||
"current_requests": 10,
|
||||
"reset_time": "2025-12-24T11:26:41.136Z"
|
||||
}
|
||||
}
|
||||
|
||||
var expected_message = get_expected_toast_message("register", 429, rate_limit_response)
|
||||
assert_eq(expected_message, "红色Toast: 注册请求过于频繁,请5分钟后再试,请稍后再试")
|
||||
|
||||
# 测试用户状态相关错误
|
||||
func test_user_status_errors():
|
||||
# 测试账户锁定
|
||||
var locked_account_error = {
|
||||
"success": false,
|
||||
"message": "账户已锁定,请联系管理员",
|
||||
"error_code": "LOGIN_FAILED"
|
||||
}
|
||||
|
||||
var expected_message = get_expected_toast_message("login", 401, locked_account_error)
|
||||
assert_eq(expected_message, "红色Toast: 账户已被锁定,请联系管理员")
|
||||
|
||||
# 测试账户禁用
|
||||
var banned_account_error = {
|
||||
"success": false,
|
||||
"message": "账户已禁用,请联系管理员",
|
||||
"error_code": "LOGIN_FAILED"
|
||||
}
|
||||
|
||||
expected_message = get_expected_toast_message("login", 401, banned_account_error)
|
||||
assert_eq(expected_message, "红色Toast: 账户已被禁用,请联系管理员")
|
||||
|
||||
# 测试发送登录验证码
|
||||
func test_send_login_verification_code():
|
||||
# 测试成功发送
|
||||
var success_response = {
|
||||
"success": true,
|
||||
"message": "验证码发送成功",
|
||||
"data": {
|
||||
"sent_to": "test@example.com",
|
||||
"expires_in": 300
|
||||
}
|
||||
}
|
||||
|
||||
var expected_message = get_expected_toast_message("send_login_code", 200, success_response)
|
||||
assert_eq(expected_message, "绿色Toast: 登录验证码已发送,请查收")
|
||||
|
||||
# 测试用户不存在
|
||||
var user_not_found_error = {
|
||||
"success": false,
|
||||
"message": "用户不存在",
|
||||
"error_code": "SEND_LOGIN_CODE_FAILED"
|
||||
}
|
||||
|
||||
expected_message = get_expected_toast_message("send_login_code", 404, user_not_found_error)
|
||||
assert_eq(expected_message, "红色Toast: 用户不存在,请先注册")
|
||||
|
||||
# 测试业务成功标志检查
|
||||
func test_business_success_flag():
|
||||
# HTTP 200但业务失败的情况
|
||||
var business_failure_response = {
|
||||
"success": false,
|
||||
"message": "用户名或密码错误",
|
||||
"error_code": "LOGIN_FAILED"
|
||||
}
|
||||
|
||||
var expected_message = get_expected_toast_message("login", 200, business_failure_response)
|
||||
assert_eq(expected_message, "红色Toast: 用户名或密码错误")
|
||||
|
||||
# 获取预期的Toast消息(模拟实际的处理逻辑)
|
||||
func get_expected_toast_message(type: String, response_code: int, data: Dictionary) -> String:
|
||||
var success = data.get("success", true)
|
||||
var error_code = data.get("error_code", "")
|
||||
var message = data.get("message", "")
|
||||
|
||||
match type:
|
||||
"login":
|
||||
if response_code == 200 and success:
|
||||
return "绿色Toast: 登录成功!正在进入鲸鱼镇..."
|
||||
elif error_code == "LOGIN_FAILED":
|
||||
if "账户已锁定" in message:
|
||||
return "红色Toast: 账户已被锁定,请联系管理员"
|
||||
elif "账户已禁用" in message:
|
||||
return "红色Toast: 账户已被禁用,请联系管理员"
|
||||
elif "账户待审核" in message:
|
||||
return "红色Toast: 账户待审核,请等待管理员审核"
|
||||
elif "邮箱未验证" in message:
|
||||
return "红色Toast: 请先验证邮箱后再登录"
|
||||
else:
|
||||
return "红色Toast: " + message
|
||||
elif response_code == 503:
|
||||
return "红色Toast: 系统维护中:系统升级维护,请稍后再试"
|
||||
else:
|
||||
return "红色Toast: " + message
|
||||
|
||||
"send_code":
|
||||
if response_code == 200 and success:
|
||||
return "绿色Toast: 验证码已发送到您的邮箱,请查收"
|
||||
elif response_code == 206 or error_code == "TEST_MODE_ONLY":
|
||||
return "绿色Toast: 测试模式:验证码已生成,请查看控制台"
|
||||
else:
|
||||
return "红色Toast: " + message
|
||||
|
||||
"send_login_code":
|
||||
if response_code == 200 and success:
|
||||
return "绿色Toast: 登录验证码已发送,请查收"
|
||||
elif response_code == 206 or error_code == "TEST_MODE_ONLY":
|
||||
return "绿色Toast: 测试模式:登录验证码已生成,请查看控制台"
|
||||
elif error_code == "SEND_LOGIN_CODE_FAILED" and "用户不存在" in message:
|
||||
return "红色Toast: 用户不存在,请先注册"
|
||||
else:
|
||||
return "红色Toast: " + message
|
||||
|
||||
"verification_code_login":
|
||||
if response_code == 200 and success:
|
||||
return "绿色Toast: 验证码登录成功!正在进入鲸鱼镇..."
|
||||
elif error_code == "VERIFICATION_CODE_LOGIN_FAILED":
|
||||
return "红色Toast: 验证码错误或已过期"
|
||||
elif error_code == "EMAIL_NOT_VERIFIED":
|
||||
return "红色Toast: 邮箱未验证,请先验证邮箱后再使用验证码登录"
|
||||
else:
|
||||
return "红色Toast: " + message
|
||||
|
||||
"register":
|
||||
if response_code == 201 and success:
|
||||
return "绿色Toast: 注册成功!欢迎加入鲸鱼镇"
|
||||
elif response_code == 429:
|
||||
return "红色Toast: " + message + ",请稍后再试"
|
||||
else:
|
||||
return "红色Toast: " + message
|
||||
|
||||
return "未知响应"
|
||||
|
||||
# 测试所有新增的错误码覆盖
|
||||
func test_all_new_error_codes():
|
||||
var new_error_codes = [
|
||||
"VERIFICATION_CODE_LOGIN_FAILED",
|
||||
"SEND_LOGIN_CODE_FAILED",
|
||||
"EMAIL_NOT_VERIFIED",
|
||||
"USER_NOT_FOUND",
|
||||
"INVALID_IDENTIFIER",
|
||||
"TEST_MODE_ONLY",
|
||||
"SERVICE_UNAVAILABLE"
|
||||
]
|
||||
|
||||
for error_code in new_error_codes:
|
||||
var test_data = {
|
||||
"success": false,
|
||||
"message": "测试消息",
|
||||
"error_code": error_code
|
||||
}
|
||||
|
||||
# 验证每个错误码都有对应的处理逻辑
|
||||
var expected_message = get_expected_toast_message("login", 401, test_data)
|
||||
assert_ne(expected_message, "未知响应", "错误码 " + error_code + " 应该有对应的处理逻辑")
|
||||
|
||||
# 测试HTTP状态码覆盖
|
||||
func test_http_status_codes():
|
||||
var status_codes = [200, 201, 206, 400, 401, 403, 404, 408, 415, 429, 500, 503]
|
||||
|
||||
for status_code in status_codes:
|
||||
var test_data = {
|
||||
"success": status_code < 400,
|
||||
"message": "测试消息 " + str(status_code)
|
||||
}
|
||||
|
||||
var expected_message = get_expected_toast_message("login", status_code, test_data)
|
||||
assert_ne(expected_message, "", "状态码 " + str(status_code) + " 应该有对应的处理")
|
||||
|
||||
func test_enhanced_toast_system():
|
||||
print("🧪 增强Toast系统测试完成")
|
||||
print("✅ 新增错误码处理")
|
||||
print("✅ 测试模式支持")
|
||||
print("✅ 维护模式处理")
|
||||
print("✅ 频率限制详细信息")
|
||||
print("✅ 用户状态错误处理")
|
||||
print("✅ 验证码登录功能")
|
||||
print("✅ 业务成功标志检查")
|
||||
assert_true(true, "增强Toast系统测试通过")
|
||||
1
tests/auth/enhanced_toast_test.gd.uid
Normal file
@@ -0,0 +1 @@
|
||||
uid://bvj6se7hmpb88
|
||||
BIN
web_assets/index.144x144.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
40
web_assets/index.144x144.png.import
Normal file
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://uf8drvqidoi0"
|
||||
path="res://.godot/imported/index.144x144.png-0d5b24e0c76fefb9d754f032ac858a25.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://web_assets/index.144x144.png"
|
||||
dest_files=["res://.godot/imported/index.144x144.png-0d5b24e0c76fefb9d754f032ac858a25.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
BIN
web_assets/index.180x180.png
Normal file
|
After Width: | Height: | Size: 18 KiB |
40
web_assets/index.180x180.png.import
Normal file
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://d06i73eh8o16l"
|
||||
path="res://.godot/imported/index.180x180.png-bacb5004c344d341977d8297b824924e.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://web_assets/index.180x180.png"
|
||||
dest_files=["res://.godot/imported/index.180x180.png-bacb5004c344d341977d8297b824924e.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
BIN
web_assets/index.512x512.png
Normal file
|
After Width: | Height: | Size: 78 KiB |
40
web_assets/index.512x512.png.import
Normal file
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://bugrvdm26up5g"
|
||||
path="res://.godot/imported/index.512x512.png-efc23e90264d95a2448c6ba710e02cd3.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://web_assets/index.512x512.png"
|
||||
dest_files=["res://.godot/imported/index.512x512.png-efc23e90264d95a2448c6ba710e02cd3.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
BIN
web_assets/index.apple-touch-icon.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
40
web_assets/index.apple-touch-icon.png.import
Normal file
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://bghq8uhuguae7"
|
||||
path="res://.godot/imported/index.apple-touch-icon.png-0c47f79c975cb77ea5a20ae9b7487b23.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://web_assets/index.apple-touch-icon.png"
|
||||
dest_files=["res://.godot/imported/index.apple-touch-icon.png-0c47f79c975cb77ea5a20ae9b7487b23.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
66
web_assets/index.audio.position.worklet.js
Normal file
@@ -0,0 +1,66 @@
|
||||
/**************************************************************************/
|
||||
/* godot.audio.position.worklet.js */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
class GodotPositionReportingProcessor extends AudioWorkletProcessor {
|
||||
static get parameterDescriptors() {
|
||||
return [
|
||||
{
|
||||
name: 'reset',
|
||||
defaultValue: 0,
|
||||
minValue: 0,
|
||||
maxValue: 1,
|
||||
automationRate: 'k-rate',
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
this.position = 0;
|
||||
}
|
||||
|
||||
process(inputs, _outputs, parameters) {
|
||||
if (parameters['reset'][0] > 0) {
|
||||
this.position = 0;
|
||||
}
|
||||
|
||||
if (inputs.length > 0) {
|
||||
const input = inputs[0];
|
||||
if (input.length > 0) {
|
||||
this.position += input[0].length;
|
||||
this.port.postMessage({ type: 'position', data: this.position });
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor('godot-position-reporting-processor', GodotPositionReportingProcessor);
|
||||
213
web_assets/index.audio.worklet.js
Normal file
@@ -0,0 +1,213 @@
|
||||
/**************************************************************************/
|
||||
/* audio.worklet.js */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
class RingBuffer {
|
||||
constructor(p_buffer, p_state, p_threads) {
|
||||
this.buffer = p_buffer;
|
||||
this.avail = p_state;
|
||||
this.threads = p_threads;
|
||||
this.rpos = 0;
|
||||
this.wpos = 0;
|
||||
}
|
||||
|
||||
data_left() {
|
||||
return this.threads ? Atomics.load(this.avail, 0) : this.avail;
|
||||
}
|
||||
|
||||
space_left() {
|
||||
return this.buffer.length - this.data_left();
|
||||
}
|
||||
|
||||
read(output) {
|
||||
const size = this.buffer.length;
|
||||
let from = 0;
|
||||
let to_write = output.length;
|
||||
if (this.rpos + to_write > size) {
|
||||
const high = size - this.rpos;
|
||||
output.set(this.buffer.subarray(this.rpos, size));
|
||||
from = high;
|
||||
to_write -= high;
|
||||
this.rpos = 0;
|
||||
}
|
||||
if (to_write) {
|
||||
output.set(this.buffer.subarray(this.rpos, this.rpos + to_write), from);
|
||||
}
|
||||
this.rpos += to_write;
|
||||
if (this.threads) {
|
||||
Atomics.add(this.avail, 0, -output.length);
|
||||
Atomics.notify(this.avail, 0);
|
||||
} else {
|
||||
this.avail -= output.length;
|
||||
}
|
||||
}
|
||||
|
||||
write(p_buffer) {
|
||||
const to_write = p_buffer.length;
|
||||
const mw = this.buffer.length - this.wpos;
|
||||
if (mw >= to_write) {
|
||||
this.buffer.set(p_buffer, this.wpos);
|
||||
this.wpos += to_write;
|
||||
if (mw === to_write) {
|
||||
this.wpos = 0;
|
||||
}
|
||||
} else {
|
||||
const high = p_buffer.subarray(0, mw);
|
||||
const low = p_buffer.subarray(mw);
|
||||
this.buffer.set(high, this.wpos);
|
||||
this.buffer.set(low);
|
||||
this.wpos = low.length;
|
||||
}
|
||||
if (this.threads) {
|
||||
Atomics.add(this.avail, 0, to_write);
|
||||
Atomics.notify(this.avail, 0);
|
||||
} else {
|
||||
this.avail += to_write;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class GodotProcessor extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super();
|
||||
this.threads = false;
|
||||
this.running = true;
|
||||
this.lock = null;
|
||||
this.notifier = null;
|
||||
this.output = null;
|
||||
this.output_buffer = new Float32Array();
|
||||
this.input = null;
|
||||
this.input_buffer = new Float32Array();
|
||||
this.port.onmessage = (event) => {
|
||||
const cmd = event.data['cmd'];
|
||||
const data = event.data['data'];
|
||||
this.parse_message(cmd, data);
|
||||
};
|
||||
}
|
||||
|
||||
process_notify() {
|
||||
if (this.notifier) {
|
||||
Atomics.add(this.notifier, 0, 1);
|
||||
Atomics.notify(this.notifier, 0);
|
||||
}
|
||||
}
|
||||
|
||||
parse_message(p_cmd, p_data) {
|
||||
if (p_cmd === 'start' && p_data) {
|
||||
const state = p_data[0];
|
||||
let idx = 0;
|
||||
this.threads = true;
|
||||
this.lock = state.subarray(idx, ++idx);
|
||||
this.notifier = state.subarray(idx, ++idx);
|
||||
const avail_in = state.subarray(idx, ++idx);
|
||||
const avail_out = state.subarray(idx, ++idx);
|
||||
this.input = new RingBuffer(p_data[1], avail_in, true);
|
||||
this.output = new RingBuffer(p_data[2], avail_out, true);
|
||||
} else if (p_cmd === 'stop') {
|
||||
this.running = false;
|
||||
this.output = null;
|
||||
this.input = null;
|
||||
this.lock = null;
|
||||
this.notifier = null;
|
||||
} else if (p_cmd === 'start_nothreads') {
|
||||
this.output = new RingBuffer(p_data[0], p_data[0].length, false);
|
||||
} else if (p_cmd === 'chunk') {
|
||||
this.output.write(p_data);
|
||||
}
|
||||
}
|
||||
|
||||
static array_has_data(arr) {
|
||||
return arr.length && arr[0].length && arr[0][0].length;
|
||||
}
|
||||
|
||||
process(inputs, outputs, parameters) {
|
||||
if (!this.running) {
|
||||
return false; // Stop processing.
|
||||
}
|
||||
if (this.output === null) {
|
||||
return true; // Not ready yet, keep processing.
|
||||
}
|
||||
const process_input = GodotProcessor.array_has_data(inputs);
|
||||
if (process_input) {
|
||||
const input = inputs[0];
|
||||
const chunk = input[0].length * input.length;
|
||||
if (this.input_buffer.length !== chunk) {
|
||||
this.input_buffer = new Float32Array(chunk);
|
||||
}
|
||||
if (!this.threads) {
|
||||
GodotProcessor.write_input(this.input_buffer, input);
|
||||
this.port.postMessage({ 'cmd': 'input', 'data': this.input_buffer });
|
||||
} else if (this.input.space_left() >= chunk) {
|
||||
GodotProcessor.write_input(this.input_buffer, input);
|
||||
this.input.write(this.input_buffer);
|
||||
} else {
|
||||
// this.port.postMessage('Input buffer is full! Skipping input frame.'); // Uncomment this line to debug input buffer.
|
||||
}
|
||||
}
|
||||
const process_output = GodotProcessor.array_has_data(outputs);
|
||||
if (process_output) {
|
||||
const output = outputs[0];
|
||||
const chunk = output[0].length * output.length;
|
||||
if (this.output_buffer.length !== chunk) {
|
||||
this.output_buffer = new Float32Array(chunk);
|
||||
}
|
||||
if (this.output.data_left() >= chunk) {
|
||||
this.output.read(this.output_buffer);
|
||||
GodotProcessor.write_output(output, this.output_buffer);
|
||||
if (!this.threads) {
|
||||
this.port.postMessage({ 'cmd': 'read', 'data': chunk });
|
||||
}
|
||||
} else {
|
||||
// this.port.postMessage('Output buffer has not enough frames! Skipping output frame.'); // Uncomment this line to debug output buffer.
|
||||
}
|
||||
}
|
||||
this.process_notify();
|
||||
return true;
|
||||
}
|
||||
|
||||
static write_output(dest, source) {
|
||||
const channels = dest.length;
|
||||
for (let ch = 0; ch < channels; ch++) {
|
||||
for (let sample = 0; sample < dest[ch].length; sample++) {
|
||||
dest[ch][sample] = source[sample * channels + ch];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static write_input(dest, source) {
|
||||
const channels = source.length;
|
||||
for (let ch = 0; ch < channels; ch++) {
|
||||
for (let sample = 0; sample < source[ch].length; sample++) {
|
||||
dest[sample * channels + ch] = source[ch][sample];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor('godot-processor', GodotProcessor);
|
||||
221
web_assets/index.html
Normal file
@@ -0,0 +1,221 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0">
|
||||
<title>whaleTown</title>
|
||||
<style>
|
||||
html, body, #canvas {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
color: white;
|
||||
background-color: black;
|
||||
overflow: hidden;
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
#canvas {
|
||||
display: block;
|
||||
}
|
||||
|
||||
#canvas:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
#status, #status-splash, #status-progress {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
}
|
||||
|
||||
#status, #status-splash {
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
}
|
||||
|
||||
#status {
|
||||
background-color: #242424;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
#status-splash {
|
||||
max-height: 100%;
|
||||
max-width: 100%;
|
||||
margin: auto;
|
||||
}
|
||||
|
||||
#status-splash.show-image--false {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#status-splash.fullsize--true {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
#status-splash.use-filter--false {
|
||||
image-rendering: pixelated;
|
||||
}
|
||||
|
||||
#status-progress, #status-notice {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#status-progress {
|
||||
bottom: 10%;
|
||||
width: 50%;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
#status-notice {
|
||||
background-color: #5b3943;
|
||||
border-radius: 0.5rem;
|
||||
border: 1px solid #9b3943;
|
||||
color: #e0e0e0;
|
||||
font-family: 'Noto Sans', 'Droid Sans', Arial, sans-serif;
|
||||
line-height: 1.3;
|
||||
margin: 0 2rem;
|
||||
overflow: hidden;
|
||||
padding: 1rem;
|
||||
text-align: center;
|
||||
z-index: 1;
|
||||
}
|
||||
</style>
|
||||
<link id="-gd-engine-icon" rel="icon" type="image/png" href="index.icon.png" />
|
||||
<link rel="apple-touch-icon" href="index.apple-touch-icon.png"/>
|
||||
<link rel="manifest" href="index.manifest.json">
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="canvas">
|
||||
Your browser does not support the canvas tag.
|
||||
</canvas>
|
||||
|
||||
<noscript>
|
||||
Your browser does not support JavaScript.
|
||||
</noscript>
|
||||
|
||||
<div id="status">
|
||||
<img id="status-splash" class="show-image--true fullsize--true use-filter--true" src="index.png" alt="">
|
||||
<progress id="status-progress"></progress>
|
||||
<div id="status-notice"></div>
|
||||
</div>
|
||||
|
||||
<script src="index.js"></script>
|
||||
<script>
|
||||
const GODOT_CONFIG = {"args":[],"canvasResizePolicy":2,"emscriptenPoolSize":8,"ensureCrossOriginIsolationHeaders":true,"executable":"index","experimentalVK":false,"fileSizes":{"index.pck":35119676,"index.wasm":36145869},"focusCanvas":true,"gdextensionLibs":[],"godotPoolSize":4,"serviceWorker":"index.service.worker.js"};
|
||||
const GODOT_THREADS_ENABLED = false;
|
||||
const engine = new Engine(GODOT_CONFIG);
|
||||
|
||||
(function () {
|
||||
const statusOverlay = document.getElementById('status');
|
||||
const statusProgress = document.getElementById('status-progress');
|
||||
const statusNotice = document.getElementById('status-notice');
|
||||
|
||||
let initializing = true;
|
||||
let statusMode = '';
|
||||
|
||||
function setStatusMode(mode) {
|
||||
if (statusMode === mode || !initializing) {
|
||||
return;
|
||||
}
|
||||
if (mode === 'hidden') {
|
||||
statusOverlay.remove();
|
||||
initializing = false;
|
||||
return;
|
||||
}
|
||||
statusOverlay.style.visibility = 'visible';
|
||||
statusProgress.style.display = mode === 'progress' ? 'block' : 'none';
|
||||
statusNotice.style.display = mode === 'notice' ? 'block' : 'none';
|
||||
statusMode = mode;
|
||||
}
|
||||
|
||||
function setStatusNotice(text) {
|
||||
while (statusNotice.lastChild) {
|
||||
statusNotice.removeChild(statusNotice.lastChild);
|
||||
}
|
||||
const lines = text.split('\n');
|
||||
lines.forEach((line) => {
|
||||
statusNotice.appendChild(document.createTextNode(line));
|
||||
statusNotice.appendChild(document.createElement('br'));
|
||||
});
|
||||
}
|
||||
|
||||
function displayFailureNotice(err) {
|
||||
console.error(err);
|
||||
if (err instanceof Error) {
|
||||
setStatusNotice(err.message);
|
||||
} else if (typeof err === 'string') {
|
||||
setStatusNotice(err);
|
||||
} else {
|
||||
setStatusNotice('An unknown error occurred.');
|
||||
}
|
||||
setStatusMode('notice');
|
||||
initializing = false;
|
||||
}
|
||||
|
||||
const missing = Engine.getMissingFeatures({
|
||||
threads: GODOT_THREADS_ENABLED,
|
||||
});
|
||||
|
||||
if (missing.length !== 0) {
|
||||
if (GODOT_CONFIG['serviceWorker'] && GODOT_CONFIG['ensureCrossOriginIsolationHeaders'] && 'serviceWorker' in navigator) {
|
||||
let serviceWorkerRegistrationPromise;
|
||||
try {
|
||||
serviceWorkerRegistrationPromise = navigator.serviceWorker.getRegistration();
|
||||
} catch (err) {
|
||||
serviceWorkerRegistrationPromise = Promise.reject(new Error('Service worker registration failed.'));
|
||||
}
|
||||
// There's a chance that installing the service worker would fix the issue
|
||||
Promise.race([
|
||||
serviceWorkerRegistrationPromise.then((registration) => {
|
||||
if (registration != null) {
|
||||
return Promise.reject(new Error('Service worker already exists.'));
|
||||
}
|
||||
return registration;
|
||||
}).then(() => engine.installServiceWorker()),
|
||||
// For some reason, `getRegistration()` can stall
|
||||
new Promise((resolve) => {
|
||||
setTimeout(() => resolve(), 2000);
|
||||
}),
|
||||
]).then(() => {
|
||||
// Reload if there was no error.
|
||||
window.location.reload();
|
||||
}).catch((err) => {
|
||||
console.error('Error while registering service worker:', err);
|
||||
});
|
||||
} else {
|
||||
// Display the message as usual
|
||||
const missingMsg = 'Error\nThe following features required to run Godot projects on the Web are missing:\n';
|
||||
displayFailureNotice(missingMsg + missing.join('\n'));
|
||||
}
|
||||
} else {
|
||||
setStatusMode('progress');
|
||||
engine.startGame({
|
||||
'onProgress': function (current, total) {
|
||||
if (current > 0 && total > 0) {
|
||||
statusProgress.value = current;
|
||||
statusProgress.max = total;
|
||||
} else {
|
||||
statusProgress.removeAttribute('value');
|
||||
statusProgress.removeAttribute('max');
|
||||
}
|
||||
},
|
||||
}).then(() => {
|
||||
setStatusMode('hidden');
|
||||
}, displayFailureNotice);
|
||||
}
|
||||
}());
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
BIN
web_assets/index.icon.png
Normal file
|
After Width: | Height: | Size: 5.6 KiB |
40
web_assets/index.icon.png.import
Normal file
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://chcbrmqo5svb8"
|
||||
path="res://.godot/imported/index.icon.png-bcd850718c00fc2a39f7b69162877ab8.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://web_assets/index.icon.png"
|
||||
dest_files=["res://.godot/imported/index.icon.png-bcd850718c00fc2a39f7b69162877ab8.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
927
web_assets/index.js
Normal file
1
web_assets/index.manifest.json
Normal file
@@ -0,0 +1 @@
|
||||
{"background_color":"#316cff","display":"standalone","icons":[{"sizes":"144x144","src":"index.144x144.png","type":"image/png"},{"sizes":"180x180","src":"index.180x180.png","type":"image/png"},{"sizes":"512x512","src":"index.512x512.png","type":"image/png"}],"name":"whaleTown","orientation":"any","start_url":"./index.html"}
|
||||
41
web_assets/index.offline.html
Normal file
@@ -0,0 +1,41 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>You are offline</title>
|
||||
<style>
|
||||
html {
|
||||
background-color: #000000;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
||||
margin: 2rem;
|
||||
}
|
||||
|
||||
p {
|
||||
margin-block: 1rem;
|
||||
}
|
||||
|
||||
button {
|
||||
display: block;
|
||||
padding: 1rem 2rem;
|
||||
margin: 3rem auto 0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>You are offline</h1>
|
||||
<p>This application requires an Internet connection to run for the first time.</p>
|
||||
<p>Press the button below to try reloading:</p>
|
||||
<button type="button">Reload</button>
|
||||
<script>
|
||||
document.querySelector('button').addEventListener('click', () => {
|
||||
window.location.reload();
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
BIN
web_assets/index.pck
Normal file
BIN
web_assets/index.png
Normal file
|
After Width: | Height: | Size: 21 KiB |
40
web_assets/index.png.import
Normal file
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://cj0tify76qrst"
|
||||
path="res://.godot/imported/index.png-d064c09a6315f5da70b1876a63391d16.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://web_assets/index.png"
|
||||
dest_files=["res://.godot/imported/index.png-d064c09a6315f5da70b1876a63391d16.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
166
web_assets/index.service.worker.js
Normal file
@@ -0,0 +1,166 @@
|
||||
// This service worker is required to expose an exported Godot project as a
|
||||
// Progressive Web App. It provides an offline fallback page telling the user
|
||||
// that they need an Internet connection to run the project if desired.
|
||||
// Incrementing CACHE_VERSION will kick off the install event and force
|
||||
// previously cached resources to be updated from the network.
|
||||
/** @type {string} */
|
||||
const CACHE_VERSION = '1766673973|3863914';
|
||||
/** @type {string} */
|
||||
const CACHE_PREFIX = 'whaleTown-sw-cache-';
|
||||
const CACHE_NAME = CACHE_PREFIX + CACHE_VERSION;
|
||||
/** @type {string} */
|
||||
const OFFLINE_URL = 'index.offline.html';
|
||||
/** @type {boolean} */
|
||||
const ENSURE_CROSSORIGIN_ISOLATION_HEADERS = true;
|
||||
// Files that will be cached on load.
|
||||
/** @type {string[]} */
|
||||
const CACHED_FILES = ["index.html","index.js","index.offline.html","index.icon.png","index.apple-touch-icon.png","index.audio.worklet.js","index.audio.position.worklet.js"];
|
||||
// Files that we might not want the user to preload, and will only be cached on first load.
|
||||
/** @type {string[]} */
|
||||
const CACHEABLE_FILES = ["index.wasm","index.pck"];
|
||||
const FULL_CACHE = CACHED_FILES.concat(CACHEABLE_FILES);
|
||||
|
||||
self.addEventListener('install', (event) => {
|
||||
event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.addAll(CACHED_FILES)));
|
||||
});
|
||||
|
||||
self.addEventListener('activate', (event) => {
|
||||
event.waitUntil(caches.keys().then(
|
||||
function (keys) {
|
||||
// Remove old caches.
|
||||
return Promise.all(keys.filter((key) => key.startsWith(CACHE_PREFIX) && key !== CACHE_NAME).map((key) => caches.delete(key)));
|
||||
}
|
||||
).then(function () {
|
||||
// Enable navigation preload if available.
|
||||
return ('navigationPreload' in self.registration) ? self.registration.navigationPreload.enable() : Promise.resolve();
|
||||
}));
|
||||
});
|
||||
|
||||
/**
|
||||
* Ensures that the response has the correct COEP/COOP headers
|
||||
* @param {Response} response
|
||||
* @returns {Response}
|
||||
*/
|
||||
function ensureCrossOriginIsolationHeaders(response) {
|
||||
if (response.headers.get('Cross-Origin-Embedder-Policy') === 'require-corp'
|
||||
&& response.headers.get('Cross-Origin-Opener-Policy') === 'same-origin') {
|
||||
return response;
|
||||
}
|
||||
|
||||
const crossOriginIsolatedHeaders = new Headers(response.headers);
|
||||
crossOriginIsolatedHeaders.set('Cross-Origin-Embedder-Policy', 'require-corp');
|
||||
crossOriginIsolatedHeaders.set('Cross-Origin-Opener-Policy', 'same-origin');
|
||||
const newResponse = new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: crossOriginIsolatedHeaders,
|
||||
});
|
||||
|
||||
return newResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls fetch and cache the result if it is cacheable
|
||||
* @param {FetchEvent} event
|
||||
* @param {Cache} cache
|
||||
* @param {boolean} isCacheable
|
||||
* @returns {Response}
|
||||
*/
|
||||
async function fetchAndCache(event, cache, isCacheable) {
|
||||
// Use the preloaded response, if it's there
|
||||
/** @type { Response } */
|
||||
let response = await event.preloadResponse;
|
||||
if (response == null) {
|
||||
// Or, go over network.
|
||||
response = await self.fetch(event.request);
|
||||
}
|
||||
|
||||
if (ENSURE_CROSSORIGIN_ISOLATION_HEADERS) {
|
||||
response = ensureCrossOriginIsolationHeaders(response);
|
||||
}
|
||||
|
||||
if (isCacheable) {
|
||||
// And update the cache
|
||||
cache.put(event.request, response.clone());
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
self.addEventListener(
|
||||
'fetch',
|
||||
/**
|
||||
* Triggered on fetch
|
||||
* @param {FetchEvent} event
|
||||
*/
|
||||
(event) => {
|
||||
const isNavigate = event.request.mode === 'navigate';
|
||||
const url = event.request.url || '';
|
||||
const referrer = event.request.referrer || '';
|
||||
const base = referrer.slice(0, referrer.lastIndexOf('/') + 1);
|
||||
const local = url.startsWith(base) ? url.replace(base, '') : '';
|
||||
const isCacheable = FULL_CACHE.some((v) => v === local) || (base === referrer && base.endsWith(CACHED_FILES[0]));
|
||||
if (isNavigate || isCacheable) {
|
||||
event.respondWith((async () => {
|
||||
// Try to use cache first
|
||||
const cache = await caches.open(CACHE_NAME);
|
||||
if (isNavigate) {
|
||||
// Check if we have full cache during HTML page request.
|
||||
/** @type {Response[]} */
|
||||
const fullCache = await Promise.all(FULL_CACHE.map((name) => cache.match(name)));
|
||||
const missing = fullCache.some((v) => v === undefined);
|
||||
if (missing) {
|
||||
try {
|
||||
// Try network if some cached file is missing (so we can display offline page in case).
|
||||
const response = await fetchAndCache(event, cache, isCacheable);
|
||||
return response;
|
||||
} catch (e) {
|
||||
// And return the hopefully always cached offline page in case of network failure.
|
||||
console.error('Network error: ', e); // eslint-disable-line no-console
|
||||
return caches.match(OFFLINE_URL);
|
||||
}
|
||||
}
|
||||
}
|
||||
let cached = await cache.match(event.request);
|
||||
if (cached != null) {
|
||||
if (ENSURE_CROSSORIGIN_ISOLATION_HEADERS) {
|
||||
cached = ensureCrossOriginIsolationHeaders(cached);
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
// Try network if don't have it in cache.
|
||||
const response = await fetchAndCache(event, cache, isCacheable);
|
||||
return response;
|
||||
})());
|
||||
} else if (ENSURE_CROSSORIGIN_ISOLATION_HEADERS) {
|
||||
event.respondWith((async () => {
|
||||
let response = await fetch(event.request);
|
||||
response = ensureCrossOriginIsolationHeaders(response);
|
||||
return response;
|
||||
})());
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
self.addEventListener('message', (event) => {
|
||||
// No cross origin
|
||||
if (event.origin !== self.origin) {
|
||||
return;
|
||||
}
|
||||
const id = event.source.id || '';
|
||||
const msg = event.data || '';
|
||||
// Ensure it's one of our clients.
|
||||
self.clients.get(id).then(function (client) {
|
||||
if (!client) {
|
||||
return; // Not a valid client.
|
||||
}
|
||||
if (msg === 'claim') {
|
||||
self.skipWaiting().then(() => self.clients.claim());
|
||||
} else if (msg === 'clear') {
|
||||
caches.delete(CACHE_NAME);
|
||||
} else if (msg === 'update') {
|
||||
self.skipWaiting().then(() => self.clients.claim()).then(() => self.clients.matchAll()).then((all) => all.forEach((c) => c.navigate(c.url)));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||