first commit
This commit is contained in:
@@ -0,0 +1,63 @@
|
|||||||
|
###############################################################################
|
||||||
|
# Set default behavior to automatically normalize line endings.
|
||||||
|
###############################################################################
|
||||||
|
* text=auto
|
||||||
|
|
||||||
|
###############################################################################
|
||||||
|
# Set default behavior for command prompt diff.
|
||||||
|
#
|
||||||
|
# This is need for earlier builds of msysgit that does not have it on by
|
||||||
|
# default for csharp files.
|
||||||
|
# Note: This is only used by command line
|
||||||
|
###############################################################################
|
||||||
|
#*.cs diff=csharp
|
||||||
|
|
||||||
|
###############################################################################
|
||||||
|
# Set the merge driver for project and solution files
|
||||||
|
#
|
||||||
|
# Merging from the command prompt will add diff markers to the files if there
|
||||||
|
# are conflicts (Merging from VS is not affected by the settings below, in VS
|
||||||
|
# the diff markers are never inserted). Diff markers may cause the following
|
||||||
|
# file extensions to fail to load in VS. An alternative would be to treat
|
||||||
|
# these files as binary and thus will always conflict and require user
|
||||||
|
# intervention with every merge. To do so, just uncomment the entries below
|
||||||
|
###############################################################################
|
||||||
|
#*.sln merge=binary
|
||||||
|
#*.csproj merge=binary
|
||||||
|
#*.vbproj merge=binary
|
||||||
|
#*.vcxproj merge=binary
|
||||||
|
#*.vcproj merge=binary
|
||||||
|
#*.dbproj merge=binary
|
||||||
|
#*.fsproj merge=binary
|
||||||
|
#*.lsproj merge=binary
|
||||||
|
#*.wixproj merge=binary
|
||||||
|
#*.modelproj merge=binary
|
||||||
|
#*.sqlproj merge=binary
|
||||||
|
#*.wwaproj merge=binary
|
||||||
|
|
||||||
|
###############################################################################
|
||||||
|
# behavior for image files
|
||||||
|
#
|
||||||
|
# image files are treated as binary by default.
|
||||||
|
###############################################################################
|
||||||
|
#*.jpg binary
|
||||||
|
#*.png binary
|
||||||
|
#*.gif binary
|
||||||
|
|
||||||
|
###############################################################################
|
||||||
|
# diff behavior for common document formats
|
||||||
|
#
|
||||||
|
# Convert binary document formats to text before diffing them. This feature
|
||||||
|
# is only available from the command line. Turn it on by uncommenting the
|
||||||
|
# entries below.
|
||||||
|
###############################################################################
|
||||||
|
#*.doc diff=astextplain
|
||||||
|
#*.DOC diff=astextplain
|
||||||
|
#*.docx diff=astextplain
|
||||||
|
#*.DOCX diff=astextplain
|
||||||
|
#*.dot diff=astextplain
|
||||||
|
#*.DOT diff=astextplain
|
||||||
|
#*.pdf diff=astextplain
|
||||||
|
#*.PDF diff=astextplain
|
||||||
|
#*.rtf diff=astextplain
|
||||||
|
#*.RTF diff=astextplain
|
||||||
+387
@@ -0,0 +1,387 @@
|
|||||||
|
## Ignore Visual Studio temporary files, build results, and
|
||||||
|
## files generated by popular Visual Studio add-ons.
|
||||||
|
##
|
||||||
|
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
|
||||||
|
|
||||||
|
# User-specific files
|
||||||
|
*.rsuser
|
||||||
|
*.suo
|
||||||
|
*.user
|
||||||
|
*.userosscache
|
||||||
|
*.sln.docstates
|
||||||
|
|
||||||
|
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||||
|
*.userprefs
|
||||||
|
|
||||||
|
# Mono auto generated files
|
||||||
|
mono_crash.*
|
||||||
|
|
||||||
|
# Build results
|
||||||
|
[Dd]ebug/
|
||||||
|
[Dd]ebugPublic/
|
||||||
|
[Rr]elease/
|
||||||
|
[Rr]eleases/
|
||||||
|
x64/
|
||||||
|
x86/
|
||||||
|
[Ww][Ii][Nn]32/
|
||||||
|
[Aa][Rr][Mm]/
|
||||||
|
[Aa][Rr][Mm]64/
|
||||||
|
bld/
|
||||||
|
[Bb]in/
|
||||||
|
[Oo]bj/
|
||||||
|
[Oo]ut/
|
||||||
|
[Ll]og/
|
||||||
|
[Ll]ogs/
|
||||||
|
|
||||||
|
# Visual Studio 2015/2017 cache/options directory
|
||||||
|
.vs/
|
||||||
|
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||||
|
#wwwroot/
|
||||||
|
|
||||||
|
# Visual Studio 2017 auto generated files
|
||||||
|
Generated\ Files/
|
||||||
|
|
||||||
|
# MSTest test Results
|
||||||
|
[Tt]est[Rr]esult*/
|
||||||
|
[Bb]uild[Ll]og.*
|
||||||
|
|
||||||
|
# NUnit
|
||||||
|
*.VisualState.xml
|
||||||
|
TestResult.xml
|
||||||
|
nunit-*.xml
|
||||||
|
|
||||||
|
# Build Results of an ATL Project
|
||||||
|
[Dd]ebugPS/
|
||||||
|
[Rr]eleasePS/
|
||||||
|
dlldata.c
|
||||||
|
|
||||||
|
# Benchmark Results
|
||||||
|
BenchmarkDotNet.Artifacts/
|
||||||
|
|
||||||
|
# .NET Core
|
||||||
|
project.lock.json
|
||||||
|
project.fragment.lock.json
|
||||||
|
artifacts/
|
||||||
|
|
||||||
|
# ASP.NET Scaffolding
|
||||||
|
ScaffoldingReadMe.txt
|
||||||
|
|
||||||
|
# StyleCop
|
||||||
|
StyleCopReport.xml
|
||||||
|
|
||||||
|
# Files built by Visual Studio
|
||||||
|
*_i.c
|
||||||
|
*_p.c
|
||||||
|
*_h.h
|
||||||
|
*.ilk
|
||||||
|
*.meta
|
||||||
|
*.obj
|
||||||
|
*.iobj
|
||||||
|
*.pch
|
||||||
|
*.pdb
|
||||||
|
*.ipdb
|
||||||
|
*.pgc
|
||||||
|
*.pgd
|
||||||
|
*.rsp
|
||||||
|
*.sbr
|
||||||
|
*.tlb
|
||||||
|
*.tli
|
||||||
|
*.tlh
|
||||||
|
*.tmp
|
||||||
|
*.tmp_proj
|
||||||
|
*_wpftmp.csproj
|
||||||
|
*.log
|
||||||
|
*.vspscc
|
||||||
|
*.vssscc
|
||||||
|
.builds
|
||||||
|
*.pidb
|
||||||
|
*.svclog
|
||||||
|
*.scc
|
||||||
|
|
||||||
|
# Chutzpah Test files
|
||||||
|
_Chutzpah*
|
||||||
|
|
||||||
|
# Visual C++ cache files
|
||||||
|
ipch/
|
||||||
|
*.aps
|
||||||
|
*.ncb
|
||||||
|
*.opendb
|
||||||
|
*.opensdf
|
||||||
|
*.sdf
|
||||||
|
*.cachefile
|
||||||
|
*.VC.db
|
||||||
|
*.VC.VC.opendb
|
||||||
|
|
||||||
|
# Visual Studio profiler
|
||||||
|
*.psess
|
||||||
|
*.vsp
|
||||||
|
*.vspx
|
||||||
|
*.sap
|
||||||
|
|
||||||
|
# Visual Studio Trace Files
|
||||||
|
*.e2e
|
||||||
|
|
||||||
|
# TFS 2012 Local Workspace
|
||||||
|
$tf/
|
||||||
|
|
||||||
|
# Guidance Automation Toolkit
|
||||||
|
*.gpState
|
||||||
|
|
||||||
|
# ReSharper is a .NET coding add-in
|
||||||
|
_ReSharper*/
|
||||||
|
*.[Rr]e[Ss]harper
|
||||||
|
*.DotSettings.user
|
||||||
|
|
||||||
|
# TeamCity is a build add-in
|
||||||
|
_TeamCity*
|
||||||
|
|
||||||
|
# DotCover is a Code Coverage Tool
|
||||||
|
*.dotCover
|
||||||
|
|
||||||
|
# AxoCover is a Code Coverage Tool
|
||||||
|
.axoCover/*
|
||||||
|
!.axoCover/settings.json
|
||||||
|
|
||||||
|
# Coverlet is a free, cross platform Code Coverage Tool
|
||||||
|
coverage*.json
|
||||||
|
coverage*.xml
|
||||||
|
coverage*.info
|
||||||
|
|
||||||
|
# Visual Studio code coverage results
|
||||||
|
*.coverage
|
||||||
|
*.coveragexml
|
||||||
|
|
||||||
|
# NCrunch
|
||||||
|
_NCrunch_*
|
||||||
|
.*crunch*.local.xml
|
||||||
|
nCrunchTemp_*
|
||||||
|
|
||||||
|
# MightyMoose
|
||||||
|
*.mm.*
|
||||||
|
AutoTest.Net/
|
||||||
|
|
||||||
|
# Web workbench (sass)
|
||||||
|
.sass-cache/
|
||||||
|
|
||||||
|
# Installshield output folder
|
||||||
|
[Ee]xpress/
|
||||||
|
|
||||||
|
# DocProject is a documentation generator add-in
|
||||||
|
DocProject/buildhelp/
|
||||||
|
DocProject/Help/*.HxT
|
||||||
|
DocProject/Help/*.HxC
|
||||||
|
DocProject/Help/*.hhc
|
||||||
|
DocProject/Help/*.hhk
|
||||||
|
DocProject/Help/*.hhp
|
||||||
|
DocProject/Help/Html2
|
||||||
|
DocProject/Help/html
|
||||||
|
|
||||||
|
# Click-Once directory
|
||||||
|
publish/
|
||||||
|
|
||||||
|
# Publish Web Output
|
||||||
|
*.[Pp]ublish.xml
|
||||||
|
*.azurePubxml
|
||||||
|
# Note: Comment the next line if you want to checkin your web deploy settings,
|
||||||
|
# but database connection strings (with potential passwords) will be unencrypted
|
||||||
|
*.pubxml
|
||||||
|
*.publishproj
|
||||||
|
|
||||||
|
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
||||||
|
# checkin your Azure Web App publish settings, but sensitive information contained
|
||||||
|
# in these scripts will be unencrypted
|
||||||
|
PublishScripts/
|
||||||
|
|
||||||
|
# NuGet Packages
|
||||||
|
*.nupkg
|
||||||
|
# NuGet Symbol Packages
|
||||||
|
*.snupkg
|
||||||
|
# The packages folder can be ignored because of Package Restore
|
||||||
|
**/[Pp]ackages/*
|
||||||
|
# except build/, which is used as an MSBuild target.
|
||||||
|
!**/[Pp]ackages/build/
|
||||||
|
# Uncomment if necessary however generally it will be regenerated when needed
|
||||||
|
#!**/[Pp]ackages/repositories.config
|
||||||
|
# NuGet v3's project.json files produces more ignorable files
|
||||||
|
*.nuget.props
|
||||||
|
*.nuget.targets
|
||||||
|
|
||||||
|
# Microsoft Azure Build Output
|
||||||
|
csx/
|
||||||
|
*.build.csdef
|
||||||
|
|
||||||
|
# Microsoft Azure Emulator
|
||||||
|
ecf/
|
||||||
|
rcf/
|
||||||
|
|
||||||
|
# Windows Store app package directories and files
|
||||||
|
AppPackages/
|
||||||
|
BundleArtifacts/
|
||||||
|
Package.StoreAssociation.xml
|
||||||
|
_pkginfo.txt
|
||||||
|
*.appx
|
||||||
|
*.appxbundle
|
||||||
|
*.appxupload
|
||||||
|
|
||||||
|
# Visual Studio cache files
|
||||||
|
# files ending in .cache can be ignored
|
||||||
|
*.[Cc]ache
|
||||||
|
# but keep track of directories ending in .cache
|
||||||
|
!?*.[Cc]ache/
|
||||||
|
|
||||||
|
# Others
|
||||||
|
ClientBin/
|
||||||
|
~$*
|
||||||
|
*~
|
||||||
|
*.dbmdl
|
||||||
|
*.dbproj.schemaview
|
||||||
|
*.jfm
|
||||||
|
*.pfx
|
||||||
|
*.publishsettings
|
||||||
|
orleans.codegen.cs
|
||||||
|
|
||||||
|
# Including strong name files can present a security risk
|
||||||
|
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
|
||||||
|
#*.snk
|
||||||
|
|
||||||
|
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||||
|
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
||||||
|
#bower_components/
|
||||||
|
|
||||||
|
# RIA/Silverlight projects
|
||||||
|
Generated_Code/
|
||||||
|
|
||||||
|
# Backup & report files from converting an old project file
|
||||||
|
# to a newer Visual Studio version. Backup files are not needed,
|
||||||
|
# because we have git ;-)
|
||||||
|
_UpgradeReport_Files/
|
||||||
|
Backup*/
|
||||||
|
UpgradeLog*.XML
|
||||||
|
UpgradeLog*.htm
|
||||||
|
ServiceFabricBackup/
|
||||||
|
*.rptproj.bak
|
||||||
|
|
||||||
|
# SQL Server files
|
||||||
|
*.mdf
|
||||||
|
*.ldf
|
||||||
|
*.ndf
|
||||||
|
|
||||||
|
# Business Intelligence projects
|
||||||
|
*.rdl.data
|
||||||
|
*.bim.layout
|
||||||
|
*.bim_*.settings
|
||||||
|
*.rptproj.rsuser
|
||||||
|
*- [Bb]ackup.rdl
|
||||||
|
*- [Bb]ackup ([0-9]).rdl
|
||||||
|
*- [Bb]ackup ([0-9][0-9]).rdl
|
||||||
|
|
||||||
|
# Microsoft Fakes
|
||||||
|
FakesAssemblies/
|
||||||
|
|
||||||
|
# GhostDoc plugin setting file
|
||||||
|
*.GhostDoc.xml
|
||||||
|
|
||||||
|
# Node.js Tools for Visual Studio
|
||||||
|
.ntvs_analysis.dat
|
||||||
|
node_modules/
|
||||||
|
|
||||||
|
# Visual Studio 6 build log
|
||||||
|
*.plg
|
||||||
|
|
||||||
|
# Visual Studio 6 workspace options file
|
||||||
|
*.opt
|
||||||
|
|
||||||
|
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||||
|
*.vbw
|
||||||
|
|
||||||
|
# Visual Studio LightSwitch build output
|
||||||
|
**/*.HTMLClient/GeneratedArtifacts
|
||||||
|
**/*.DesktopClient/GeneratedArtifacts
|
||||||
|
**/*.DesktopClient/ModelManifest.xml
|
||||||
|
**/*.Server/GeneratedArtifacts
|
||||||
|
**/*.Server/ModelManifest.xml
|
||||||
|
_Pvt_Extensions
|
||||||
|
|
||||||
|
# Paket dependency manager
|
||||||
|
.paket/paket.exe
|
||||||
|
paket-files/
|
||||||
|
|
||||||
|
# FAKE - F# Make
|
||||||
|
.fake/
|
||||||
|
|
||||||
|
# CodeRush personal settings
|
||||||
|
.cr/personal
|
||||||
|
|
||||||
|
# Python Tools for Visual Studio (PTVS)
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
|
||||||
|
# Cake - Uncomment if you are using it
|
||||||
|
# tools/**
|
||||||
|
# !tools/packages.config
|
||||||
|
|
||||||
|
# Tabs Studio
|
||||||
|
*.tss
|
||||||
|
|
||||||
|
# Telerik's JustMock configuration file
|
||||||
|
*.jmconfig
|
||||||
|
|
||||||
|
# BizTalk build output
|
||||||
|
*.btp.cs
|
||||||
|
*.btm.cs
|
||||||
|
*.odx.cs
|
||||||
|
*.xsd.cs
|
||||||
|
|
||||||
|
# OpenCover UI analysis results
|
||||||
|
OpenCover/
|
||||||
|
|
||||||
|
# Azure Stream Analytics local run output
|
||||||
|
ASALocalRun/
|
||||||
|
|
||||||
|
# MSBuild Binary and Structured Log
|
||||||
|
*.binlog
|
||||||
|
|
||||||
|
# NVidia Nsight GPU debugger configuration file
|
||||||
|
*.nvuser
|
||||||
|
|
||||||
|
# MFractors (Xamarin productivity tool) working folder
|
||||||
|
.mfractor/
|
||||||
|
|
||||||
|
# Local History for Visual Studio
|
||||||
|
.localhistory/
|
||||||
|
|
||||||
|
# BeatPulse healthcheck temp database
|
||||||
|
healthchecksdb
|
||||||
|
|
||||||
|
# Backup folder for Package Reference Convert tool in Visual Studio 2017
|
||||||
|
MigrationBackup/
|
||||||
|
|
||||||
|
# Ionide (cross platform F# VS Code tools) working folder
|
||||||
|
.ionide/
|
||||||
|
|
||||||
|
# Fody - auto-generated XML schema
|
||||||
|
FodyWeavers.xsd
|
||||||
|
|
||||||
|
#FunGame.Implement
|
||||||
|
FunGame.Implement/*.cs
|
||||||
|
FunGame.Implement/Implement/*.cs
|
||||||
|
/FunGame.WebAPI/wwwroot/*
|
||||||
|
/FunGame.WebAPI/.config
|
||||||
|
|
||||||
|
# ===== FunGame.Server-v3 专属 =====
|
||||||
|
|
||||||
|
# Node / WebUI
|
||||||
|
webui/node_modules/
|
||||||
|
webui/dist/
|
||||||
|
|
||||||
|
# 运行时数据
|
||||||
|
src/FunGame.Server.Host/Data/
|
||||||
|
src/FunGame.Server.Host/records/
|
||||||
|
src/FunGame.Server.Host/plugins/
|
||||||
|
src/FunGame.Server.Host/modules/
|
||||||
|
src/FunGame.Server.Host/logs/
|
||||||
|
|
||||||
|
# EF 迁移以外的生成物
|
||||||
|
*.db
|
||||||
|
*.db-shm
|
||||||
|
*.db-wal
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
# 2026-08-22
|
||||||
|
|
||||||
|
## 项目进度盘点(FunGame.Server-v3)
|
||||||
|
|
||||||
|
- 梳理三项目现状:FunGame.Core(net10.0 战斗引擎,v3 迭代中,最新 dev-0820,git 到 #170)、FunGame.Testing-v3(模拟器已并入单 WebAPI 项目,含 Tests/OshimaGameModules,已出 linux-x64/win-x64 发布)、FunGame.Server-v3(本工作区,4 项目 + webui)。
|
||||||
|
- Server-v3 里程碑对照 docs/04-架构设计.md:M0~M6 全部 ✅(骨架/数据层/认证/插件热重载/WebSocket/业务/WebUI),M7 加固发布 ⏳ 进行中。
|
||||||
|
- **修复阻断 bug**:`FunGame.Server-v3.slnx` 中误把 `webui/` 配置为 .NET Framework Website 项目(Type="Website"),导致 `dotnet build` 报 MSB4249 失败。已移除该条目,webui 由 npm 独立构建。
|
||||||
|
- M7 剩余候选:玩家局内决策接入(gaming.action 驱动 GamingQueue,当前 AI 自动循环)、Elo 扩圈匹配、单元/集成测试项目(参考 Testing-v3 Tests)、Linux 自包含发布、WebUI 权限/角色与系统配置页、MySQL Provider 部署验证。
|
||||||
|
|
||||||
|
## FunGame.Testing-v3 新增 webui-client(Server 测试客户端)
|
||||||
|
|
||||||
|
- 新建项目 `C:\milimoe\FunGame.Testing-v3\webui-client`,技术栈与 Testing-v3 现有 webui 回放台一致:React 19 + Vite 6 + Tailwind CSS v4(@tailwindcss/vite 插件),TypeScript 严格模式。
|
||||||
|
- 设计参照 `C:\milimoe\FunGame.Testing-v3\docs_internal\01-WebUI.txt` + `02-MobileUI.txt`(深蓝紫底 / 金色装饰 / 蓝红阵营 / 二次元幻想风),针对 FunGame.Core 战斗系统适配(5v5 → 5 人混战)。
|
||||||
|
- 端口 5174;vite proxy 配置 `/api` 与 `/ws` 代理到 FunGame.Server-v3(5000),解决 CORS。
|
||||||
|
- 三个主面板:测试中心(预设 30+ 用例 + 手动请求构造器,含 auth/用户中心/对局回放/经济/系统/管理/WebSocket/房间匹配组,结果卡片展示状态/耗时/错误/JSON)、战斗对局(顶部双队伍+金色回合计数器、中央角色战场 HP/MP/状态/阵营、底部开始行动/自动/×2 加速、对局事件流、结算横幅)、回放(对局记录列表 → meta → 回合时间轴 → RoundRecord JSON → statistics)。
|
||||||
|
- REST 客户端封装:ApiResponse 解包 + 耗时测量 + 错误归一化。WS 客户端:MessageEnvelope 信封、心跳 (system.ping)、响应关联(按 i 字段)、超时控制。
|
||||||
|
- React Context 全局状态(ServerProvider):连接配置 / 认证 (JWT) / WS 实例 / 测试记录 / 对局事件 / 战斗状态。
|
||||||
|
- 支持深链:`#tab=test|battle|replay` 直接进入对应面板(顺手增强)。
|
||||||
|
- `npm run build` 成功(240KB JS / 35KB CSS gzip 后 73KB/6.5KB),共 2026 行 TS/TSX,0 错误 0 警告。
|
||||||
|
- 验收截图(Chrome headless):桌面测试中心、移动端 390x844、战斗对局、回放加载中,4 张存于 `webui-client/shots/`。
|
||||||
|
- Chrome headless `--virtual-time-budget` 会干扰 fetch 调度导致 "Failed to fetch"(已记录);agent-browser daemon 在本环境启动 Chrome 一直 exit 3(已记录),改用 Chrome headless 直接 --screenshot 验收。
|
||||||
|
- 项目已写 README.md(启动步骤 + 代理说明 + 测试流程指引 + 协议速查)。
|
||||||
|
|
||||||
|
## CORS 修复(5174 直连放行)
|
||||||
|
|
||||||
|
- 现象:客户端(5174)顶部直连 `http://localhost:5000` 时 Server 日志报 `CORS policy execution failed`,浏览器拦截 401 响应。
|
||||||
|
- 修复:`FunGame.Server-v3/src/FunGame.Server.Host/appsettings.json` 的 `AllowOrigins` 增加 `http://localhost:5174` 与 `http://127.0.0.1:5174`。
|
||||||
|
- 验证:curl 带 `Origin: http://localhost:5174` 返回 401 + `Access-Control-Allow-Origin: http://localhost:5174`;未放行 Origin 无 CORS 头。
|
||||||
|
- 注意:Git Bash 下 `taskkill //F //PID` 无效(// 转义问题),需用 PowerShell `Stop-Process` 或 `cmd //c`;遗留 dotnet 进程会占用 5000 导致重启失败(AddressInUse)。
|
||||||
|
|
||||||
|
## 对局暂停/恢复 + Oshima 模组移植
|
||||||
|
|
||||||
|
### 1. Server 对局控制(暂停/恢复/强制结束)
|
||||||
|
- `GameHostService` 新增 `PauseGame(Guid)` / `ResumeGame(Guid)`;`HostedGame` 增加 `volatile bool Paused`;`RunGameLoopAsync` 循环内暂停检测(暂停时等待 100ms 直到恢复/结束)。
|
||||||
|
- `AdminControllers` 新增 `POST /api/admin/server/games/{id}/pause|resume`(GamesManage 权限);强制结束 `.../end` 原本已有。
|
||||||
|
- webui-client `BattleView` 操作区新增「⏸ 暂停/▶ 继续」「⏹ 强制结束」(confirm 确认),走 REST 管理端;`BattleState` 增加 `paused` 字段(gaming.over 时复位)。
|
||||||
|
|
||||||
|
### 2. Oshima 模组(FunGameSimulation 内容移植给 Server)
|
||||||
|
- 新建 `modules/FunGame.Server.Modules.Oshima/`:复制 Testing-v3 OshimaGameModules 源码(Characters/Effects/Items/Skills/Units 281 cs)+ `Others/OshimaGameModuleConstant.cs` + configs;命名空间保持 `Milimoe.FunGameTesting.OshimaGameModules.*`。
|
||||||
|
- 唯一外部依赖 `FunGameService.GenerateRandomChineseName`(雇佣兵团.cs 用到)→ 新建 `Others/RandomNames.cs` 自包含工具类并改写引用。
|
||||||
|
- 新建 `OshimaServerModules.cs`:`OshimaCharacterModule`(18 角色,工厂 id 1-18)/ `OshimaSkillModule`(基础+爆发+被动+通用+魔法全量)/ `OshimaItemModule`(武器/防具/鞋子/饰品/消耗品),实现 Server 的 `ICharacterModule/ISkillModule/IItemModule`,OnLoad 注册 Factory。
|
||||||
|
- csproj 仿 ExampleModules(含 CopyModulesToHost 复制到 Host/modules/*/_staging 热替换);已加入 slnx。
|
||||||
|
- 模组一次编译通过(0 错 0 警);Server 启动后 /api/admin/plugins 显示 oshima.characters/skills/items 三个 Loaded。
|
||||||
|
- 端到端验证(临时脚本 `webui-client/e2e-battle-check.mjs`,Node 原生 WS):match.start → 回合含 Oshima 角色(大島シヤ)→ pause 后 1s 0 新回合 → resume 后 32 新回合 → gaming.over → 强制结束 OK。
|
||||||
|
|
||||||
|
### 3.5 参考 FunGameSimulation 生成对局(角色技能装配)
|
||||||
|
- 新建 `src/FunGame.Server.Host/Services/CharacterBuildService.cs`:参考 FunGameSimulation + FunGameService.AddCharacterSkills 装配对局角色。
|
||||||
|
- `BuildSimulationCharacters(count, level=10, skillLevel=2)`:随机角色 + `BuildCharacter` 逐角色装配。
|
||||||
|
- `BuildCharacter(template)`:Copy → Level=10 / NormalAttack.Level=2 → 专属被动+大招(id 1-18 映射表,如 1→META马/熵灭极诣、18→概念之骰/神之因果)→ 随机 3 基础战技(排除疾走)→ 3 通用被动(等级1)→ 3 通用大招 → 清理模板被动特效。
|
||||||
|
- 与模组解耦:技能通过 `catalog.GetSkills()` 按 Name 匹配。
|
||||||
|
- 接入:Program.cs 注册;RoomMessageHandlers 的 match.start 用 `BuildSimulationCharacters`、room.start 玩家/AI 角色用 `BuildCharacter`。
|
||||||
|
- **关键踩坑(模组工厂注册)**:OshimaSkillModule/ItemModule OnLoad 工厂委托原用 `skill.Copy()`,但 `Skill.Copy()` 内部调 `Factory.GetInstance` → 委托又 Copy → **无限递归**。修复:工厂委托必须返回**新实例**(`Activator.CreateInstance(type)`),不能 Copy。
|
||||||
|
- **坑 2**:部分技能(如 闪现)只有 `(Character? character = null)` 构造,`Activator.CreateInstance(Type)` 不应用可选参数 → MissingMethodException。修复:`ModuleEntityFactory.Create<T>` 先试无参构造,失败退化 `CreateInstance(type, [null])`。
|
||||||
|
- 验证:装配日志 K神(Id=18)11 技能(概念之骰/神之因果/3战技/3通用被动/3通用大招)、男甘雨(Id=4)专属灵能反射/三相灵枢;被动不出现于行动记录、大招需条件触发,以装配日志为准。
|
||||||
|
- 日志级别:Server:Debug=False 时 LogDebug 不可见,装配日志用 LogInformation。
|
||||||
|
|
||||||
|
## 房间自选模组(Server 提供列表 → 客户端渲染选择)
|
||||||
|
|
||||||
|
### Server 端
|
||||||
|
- 新增 `src/FunGame.Server.Host/Controllers/GameModulesController.cs`:`GET /api/game-modules`(`[AllowAnonymous]`,公开),返回 `{ modes, modules }`:
|
||||||
|
- `modes`:从 `PluginManager.Items` 过滤 `Kind=ServerPlugin && Status=Loaded`(可作为房间 GameModule 的游戏模式,如 example)
|
||||||
|
- `modules`:过滤 `Kind=CharacterModule/SkillModule/ItemModule && Status=Loaded`(内容模组,影响角色/技能/物品池)
|
||||||
|
- 数据实时反映热重载。
|
||||||
|
|
||||||
|
### 客户端(webui-client)
|
||||||
|
- `types.ts` 加 `ModuleInfoDto` / `GameModulesDto`;`api.ts` 加 `fetchGameModules(baseUrl)`。
|
||||||
|
- 新增 `src/components/RoomPanel.tsx`:
|
||||||
|
- 挂载时 `GET /api/game-modules` 拉取列表,渲染游戏模式选项卡(含版本/作者/描述)。
|
||||||
|
- 房间参数:模组(必选)、最大人数(2-10)、是否排位、密码(可选)。
|
||||||
|
- 「创建房间」→ WS `room.create`(`{module, map, maxUsers, isRank, password}`)→ 返回 `roomId`。
|
||||||
|
- 创建后显示「▶ 开始对局(房主)」→ WS `room.start`(`{roomId}`)→ 收到 `gaming.start` 后提示用户切到「战斗对局」面板,battle.gameId 也被 patchBattle 同步。
|
||||||
|
- 错误/提示:WS 未连接、token 缺失、result.error 全部 inline 展示。
|
||||||
|
- `App.tsx` 新增 Tab「🚪 房间」(`#room` 深链)。
|
||||||
|
- 端到端:room-e2e.mjs 验证模组列表正确、自选 example 创建房间 UXJWPBF、开始对局成功。
|
||||||
|
- 截图:headless `--virtual-time-budget=8000 --screenshot` 触发 React 完整渲染(普通 `--screenshot` 截不到 fetch 完成态;此参数对 fetch 有干扰但 8s 足够完成初次加载),存 `webui-client/shots/05-room.png`。
|
||||||
|
- 已知行为:room.start 按内容模组池全量随机抽角色,**未按"内容模组"过滤**——若需"只选 Oshima 角色"可后续扩展 GameHostService 的角色源支持 contentModule 参数。
|
||||||
|
|
||||||
|
## 创建游戏只从所选模组取内容(角色/技能/物品)
|
||||||
|
|
||||||
|
- **PluginManager**:新增 `GetModuleEntities<T>(string modulePrefix)` —— 按 `{prefix}.` 前缀过滤已加载实体模组。
|
||||||
|
- **EntityCatalog**:新增 `GetCharacters/GetSkills/GetItems(string modulePrefix)`。
|
||||||
|
- **CharacterBuildService**:`BuildSimulationCharacters/BuildCharacter` 增加 `modulePrefix` 参数——角色模板池与技能池均只从该模组族取;技能装配改为**按 SkillType 分类自适应**(战技 Skill / 被动 Passive / 爆发 SuperSkill 各随机 3,排除专属技能名避免重复与跨角色专属;候选不足回退)。`SkillType` 枚举在 `FunGame.Core.Library.Constant`。
|
||||||
|
- **RoomEntity**:新增 `ContentModule` 字段(EF 迁移 `20260822050723_AddContentModule`,README 命令不带 --startup-project,因 Host 缺 EF Design 包)。`CreateRoomAsync` 加参数;`room.create` 接收 `contentModule`;`room.start` 用它过滤角色池;`match.start` 也支持可选 `contentModule`;`room.list` 响应带出 `contentModule`。
|
||||||
|
- **客户端 RoomPanel**:新增"内容模组"单选(全量 / 模组名前缀去重:example、oshima),room.create 传 `contentModule`。
|
||||||
|
- 验证(cm-e2e.mjs):oshima → 大島シヤ 10 技能(META马+战技+通用被动/爆发,无重复);example → 示例战士 1 技能(示例打击,example.skills 唯一技能);全量 → 混合角色 + 专属。
|
||||||
|
- 教训:硬编码技能名池只对 oshima 有效,example 模组会装配 0 技能 → 必须按类型从所选模组实际技能中选取。
|
||||||
|
|
||||||
|
### 3. Oshima JSON 配置物品部署
|
||||||
|
- 需求:把 `Testing-v3/WebAPI/OshimaGameModules/configs/oshima-studios/oshima.fungame.items.json`(108KB,147 件武器/防具/收藏品配置)部署到 Server Host。
|
||||||
|
- 加载机制确认:`Factory.GetGameModuleInstances<Item>(module_name, file_name)` → `EntityModuleConfig<T>` 从 **`AppDomain.CurrentDomain.BaseDirectory/modules/{ModuleName}/{FileName}.json`** 读取(默认 ModuleDirectory="modules"),JSON 物品经 OpenItemAdapter 适配。
|
||||||
|
- 部署:JSON 复制到 `src/FunGame.Server.Host/modules/oshima-studios/oshima.fungame.items.json`;Host.csproj 加 `<None Include="modules/oshima-studios/**" CopyToOutputDirectory="PreserveNewest"/>` 随构建复制到 bin(运行时 BaseDirectory 可读)。
|
||||||
|
- `OshimaItemModule.BuildEntities` 先 `Factory.GetGameModuleInstances<Item>("oshima-studios","oshima.fungame.items")` 合并 JSON 物品(key 前缀 `oshima_json_`,JsonItemCount 静态计数),再合并代码物品;OnLoad 统一注册 Factory。
|
||||||
|
- 验证:启动日志 `Oshima 物品模组加载:代码物品 51 件 + JSON 配置物品 147 件`(共 198 件)。
|
||||||
|
- 踩坑:`IReadOnlyDictionary.Values` 是 `IEnumerable`,没有 `.Count` 属性(只有 LINQ `Count()` 扩展)→ 用 `Entities.Count`;模组项目需 `using Microsoft.Extensions.Logging` 才能用 ILogger(DI 扩展需单独 using)。
|
||||||
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# 2026-08-26
|
||||||
|
|
||||||
|
## 「一切皆模组」架构设计讨论
|
||||||
|
- 用户提出服务器模式重构方向:游戏逻辑由房间内生效的模组定义,服务器仅做核心队列计算与转发。
|
||||||
|
- 摸清 FunGame.Core 真实扩展点:规则=GamingQueue 虚钩子(AfterDeathCalculation/AfterCharacterAction/...),行为=Effect 钩子 + EventCenter.Stores;IGameEventHandler 局内事件当前未在对局循环派发。
|
||||||
|
- 与用户敲定三处分叉:规则形态=queue 子类、行为通道=Effect+Stores、热重载=规则开局锁定。
|
||||||
|
- 硬约束:只改 FunGame.Server-v3,不碰 FunGame.Core。
|
||||||
|
- 结论已写入 MEMORY.md(长期架构约定)。下一步:Phase 0 实现(Contracts 加 IRuleModule/RoomModuleSet + 标准近战规则模组 + 重构 CreateGame/RoomStart),待用户确认后开工。
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# 2026-08-27
|
||||||
|
|
||||||
|
## 「一切皆模组」设计理解修正(关键)
|
||||||
|
- 用户纠正方向:目标是**多玩家联机**,核心抽象是 **GameModule**(封装网络层在 GamingQueue 上的"游戏模式模组"),c/s/IModule 只是内容层。
|
||||||
|
- 研读参考:FunGame.Core **v2 分支**(IGameModule/IGameModuleServer/GameModule/GameModuleServer/GameModuleDepend/GamingObject/GameModuleLoader/ExampleGameModule)与旧版 **C:\milimoe\fungame.server**(ServerModel 把 SocketMessageType.Gaming 路由到 NowGamingServer.GamingMessageHandler,switch-case 处理 GamingType,结果 Send 回客户端)。
|
||||||
|
- 确认 v3 现状:IServerPlugin.HandleGamingMessage 是 v2 GamingMessageHandler 的薄版;gaming.action 未接路由;IGameSession 已暴露 Queue/Clients/CustomData。
|
||||||
|
|
||||||
|
## Phase 0 GameModule 落地(编译 0 错误,冒烟 OK)
|
||||||
|
- **Contracts**:新增 `IGameModuleServer`(Id/Dependencies/DefaultMap/RoomType/MaxUsers/StartGameAsync/HandleGamingMessageAsync,GamingType/RoomType 复用 Core `Library/Constant/TypeEnum`)、`GameModuleDepend`(内容依赖前缀);扩展 `IGameSession`(Characters/BroadcastAsync/EndGameAsync)。
|
||||||
|
- **modules/FunGame.Server.Modules.Melee**:`MeleeGameModuleServer` 复刻 v2 ExampleGameModuleServer——单例、按 session 建 Worker、StartGameAsync 建 `MixGamingQueue`(淘汰/复活=1)、HandleGamingMessage switch-case(Connect/PickCharacter/Surrender)。
|
||||||
|
- **Host 接线**:`PluginKind.GameModuleServer` + `modules/games` 目录;`GetGameModule`;`CreateGameFromModule`/`GetGameOfClient`;`gaming.action` 路由到房间 GameModule;`RoomStart` 优先走 GameModule(无则回退 IServerPlugin)。老 IServerPlugin 并存逐步退役。
|
||||||
|
|
||||||
|
## 核心约定:Oshima 引用不拷贝(用户拍板)
|
||||||
|
- **Testing-v3 最先适配 Core v3,Server-v3 不再维护 Oshima 内容拷贝**(Core #172/#173 把 Effect 钩子改成 Context 模式,拷贝会快速过期)。
|
||||||
|
- **已抽取独立库**:`C:\milimoe\FunGame.Testing-v3\OshimaGameModules\OshimaGameModules.csproj`(net10.0,281 cs:Characters/Effects/Skills/Items/Units + Others/RandomNames.cs + configs→输出 `modules/oshima-studios/`);Testing-v3 `WebAPI` 与 Server-v3 的 Oshima 包装层均 **ProjectReference** 它。
|
||||||
|
- Testing-v3 `WebAPI/OshimaGameModules/` 只留 `Modules/` 接线层(继承 Core IModule + JSON 加载);`雇佣兵团.cs` 的 `FunGameService.GenerateRandomChineseName()` → 库内自包含 `RandomNames`(`Milimoe.FunGameTesting.Others`)。
|
||||||
|
- **Server-v3 `FunGame.Server.Modules.Oshima` 只剩包装**:csproj(引用库,CopyModulesToHost 同时复制包装层 + `OshimaGameModules.dll` 到 modules/*/_staging)+ `OshimaServerModules.cs` + `OshimaGameModuleConstant.cs`;内容/配置/`Others/RandomNames.cs` 已删除。
|
||||||
|
- 插件 ALC 解析:被引用的库 DLL 与包装层同目录 → `PluginLoadContext` 第 3 步 fallback(`_pluginDirectory + name.dll`)命中;冒烟验证 oshima.* 全部加载。
|
||||||
|
- 顺带迁移(旧钩子→Context):`CharacterBuildService` `e.OnEffectLost(new HookContext(null, c))`;Example 模组 `OnSkillCasted(SkillCastContext)`。
|
||||||
|
- **约定**:以后 Oshima 内容改动只改 Testing-v3 库;Server-v3 重新 build 即自动跟随(复制目标同步库 DLL)。
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# 长期项目约定(FunGame.Server-v3)
|
||||||
|
|
||||||
|
## 架构方向:一切皆模组(Everything is a Module)
|
||||||
|
用户确定的设计理念:游戏逻辑由房间内生效的模组定义,服务器仅负责核心队列计算与转发。
|
||||||
|
**核心是"多玩家联机"**:GameModule 本质是封装网络层在 GamingQueue 之上的"游戏模式模组";c/s/IModule 那套只是内容层。
|
||||||
|
|
||||||
|
### 已敲定的分叉(2026-08-26 讨论,2026-08-27 修正)
|
||||||
|
- **GameModule = 游戏模式模组(核心抽象,参考 v2 设计)**:参考 FunGame.Core **v2 分支** `Interface/Base/Addons/IGameModule.cs`、`IGameModuleServer.cs`、`Library/Common/Addon/GameModule(Server).cs`、`ExampleGameModule.cs`、`GamingObject.cs`,及旧版 `C:\milimoe\fungame.server` 的 `ServerModel` 路由(`SocketMessageType.Gaming` → `NowGamingServer.GamingMessageHandler(this, type, data)` → 结果 `Send` 回客户端)。
|
||||||
|
- 服务器侧 `IGameModuleServer`:`GamingMessageHandler(model, type, data)` **switch-case 处理 GamingType**(Connect/PickCharacter/Skill/Item/...);`StartServer(GamingObject)` 建房即返回、为每房间建 Worker(玩家/角色/状态);`SendGamingMessage` 广播;模组为单例、`GamingObjects` 管所有进行中对局。
|
||||||
|
- 客户端侧 `IGameModule`:实现全部 `IGaming*EventHandler`(局内事件就是模组接口面)+ `StartGame(Gaming instance)` + `GameModuleDepend` 声明内容依赖 + `RoomType`/`MaxUsers`/`DefaultMap`。
|
||||||
|
- **内容层(c/s/IModule)= 纯内容**:角色/技能/物品/Effect 模组(`ICharacterModule` 等 + `Factory.OpenFactory` 显式注册,沿用 `SkillModule.Load()` 与 `EffectHookCache.ScanAllAssemblies()`),GameModule 通过 `GameModuleDepend` 依赖它们。
|
||||||
|
- **行为/跨模式逻辑**:后续事件订阅模组(全局 Effect / 房间事件总线),非本期重点。
|
||||||
|
- **热重载**:GameModule 逻辑开局锁定;内容模组可热重载。
|
||||||
|
- v3 现有 `IServerPlugin.HandleGamingMessage(IGameSession, string type, data)` = v2 `GamingMessageHandler` 的薄版;`gaming.action` 尚未接路由(M7 候选"玩家局内决策接入"即此)。
|
||||||
|
|
||||||
|
### 硬约束
|
||||||
|
- **只改 FunGame.Server-v3,不修改 FunGame.Core 源码**。
|
||||||
|
- 服务器核心收敛为:薄路由/转发 + 对局会话(`IGameSession`)+ 模组生命周期(解析房间 GameModule 并编排)。
|
||||||
|
|
||||||
|
### 迁移路线(绞杀者)
|
||||||
|
1. ✅ Contracts:`IGameModuleServer` + `GameModuleDepend`(GamingType/RoomType 复用 Core 枚举);扩展 `IGameSession`(Characters/BroadcastAsync/EndGameAsync)。
|
||||||
|
2. ✅ 标准近战 GameModule(`modules/FunGame.Server.Modules.Melee`):StartGameAsync 建 MixGamingQueue + HandleGamingMessage switch-case(Connect/PickCharacter/Surrender)。
|
||||||
|
3. ✅ Host:`PluginKind.GameModuleServer` + `modules/games` 目录;`GetGameModule`;`CreateGameFromModule`/`GetGameOfClient`;`gaming.action` 路由;RoomStart 优先 GameModule;GameModulesController modes 纳入。
|
||||||
|
4. ⏳ 玩家局内决策接入(Attack/Skill/Item/Move 驱动队列)、客户端侧 GameModule(webui)、老 `IServerPlugin` 退役。
|
||||||
|
|
||||||
|
### 引擎扩展点备忘(FunGame.Core,只读参考)
|
||||||
|
- Core 已到 #174:Effect 虚钩子为 **Context 模式**(`OnTurnStart(TurnContext)`/`OnEffectGained(HookContext)` 等),经 `GamingQueue.EffectDispatch.Trigger*` 分发(按角色/全队列);`GamingType`/`RoomType` 枚举在 `Library/Constant/TypeEnum.cs`。
|
||||||
|
- `MixGamingQueue`/`TeamGamingQueue` 是内置规则(死亡竞赛/组队)。
|
||||||
|
- `IGameEventHandler` 局内事件当前未在对局循环派发(v3);v2 中它是 GameModule 的接口面。
|
||||||
|
- `EventCenter` 是探索/活动系统(Stores 可复用为房间 KV)。
|
||||||
|
- **Oshima 引用不拷贝**:内容权威源 = Testing-v3 独立库 `C:\milimoe\FunGame.Testing-v3\OshimaGameModules\OshimaGameModules.csproj`(最先适配 Core v3);Server-v3 的 `FunGame.Server.Modules.Oshima` 只保留包装层并 ProjectReference 它(CopyModulesToHost 同时复制 `OshimaGameModules.dll` 到 modules/*/_staging)。内容改动只改 Testing-v3,Server 重新 build 即跟随。
|
||||||
|
- 本地可编译:dotnet 10.0.400 可用。
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<Solution>
|
||||||
|
<Folder Name="/modules/">
|
||||||
|
<Project Path="modules/FunGame.Server.Modules.Example/FunGame.Server.Modules.Example.csproj" />
|
||||||
|
<Project Path="modules/FunGame.Server.Modules.Melee/FunGame.Server.Modules.Melee.csproj" />
|
||||||
|
<Project Path="modules/FunGame.Server.Modules.Oshima/FunGame.Server.Modules.Oshima.csproj" />
|
||||||
|
</Folder>
|
||||||
|
<Folder Name="/plugins/">
|
||||||
|
<Project Path="plugins/FunGame.Server.Plugins.Example/FunGame.Server.Plugins.Example.csproj" />
|
||||||
|
</Folder>
|
||||||
|
<Folder Name="/src/">
|
||||||
|
<Project Path="src/FunGame.Server.Contracts/FunGame.Server.Contracts.csproj" />
|
||||||
|
<Project Path="src/FunGame.Server.Host/FunGame.Server.Host.csproj" />
|
||||||
|
<Project Path="src/FunGame.Server.Infrastructure/FunGame.Server.Infrastructure.csproj" />
|
||||||
|
<Project Path="src/FunGame.Server.PluginHost/FunGame.Server.PluginHost.csproj" />
|
||||||
|
</Folder>
|
||||||
|
</Solution>
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2022-present Milimoe, Project Redbud and Contributors.
|
||||||
|
|
||||||
|
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.
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
# FunGame.Server-v3
|
||||||
|
|
||||||
|
基于 **FunGame.Core v3**(net10.0)全新构建的服务器项目:EF Core 数据层、React/Tailwind WebUI 管理台、仅 WebSocket + WebAPI 启动、细粒度权限角色与多端统一验证、全表 CRUD REST API、始终热重载的插件系统、新负载模型与回合记录外发。
|
||||||
|
|
||||||
|
> 架构设计与规划文档见 [`docs/`](docs/),开发依据为 [docs/04-架构设计.md](docs/04-架构设计.md)。
|
||||||
|
|
||||||
|
## 解决方案结构
|
||||||
|
|
||||||
|
```
|
||||||
|
src/FunGame.Server.Contracts/ 共享契约:负载模型(MessageEnvelope/ApiResponse)、插件接口、权限点
|
||||||
|
src/FunGame.Server.Infrastructure/ EF Core 数据层:实体、AppDbContext、迁移、种子数据
|
||||||
|
src/FunGame.Server.PluginHost/ 始终热重载的插件/模组加载系统(可回收 AssemblyLoadContext + 文件监视)
|
||||||
|
src/FunGame.Server.Host/ ASP.NET Core 宿主:WebAPI + WebSocket + JWT 认证 + 对局宿主 + 回放归档
|
||||||
|
webui/ React + Vite + Tailwind 管理控制台
|
||||||
|
```
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# 1. 启动服务器(默认 http://localhost:5000,SQLite 自动建库并创建初始管理员)
|
||||||
|
dotnet run --project src/FunGame.Server.Host
|
||||||
|
|
||||||
|
# 2. 开发模式启动 WebUI(http://localhost:5173,代理 /api 与 /ws 到 5000)
|
||||||
|
cd webui
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
|
|
||||||
|
# 3. 生产模式:构建前端后由服务器托管
|
||||||
|
cd webui && npm run build
|
||||||
|
# 重启服务器后直接访问 http://localhost:5000
|
||||||
|
```
|
||||||
|
|
||||||
|
初始管理员账号由 `appsettings.json` 的 `Bootstrap:Admin` 配置(默认 `admin` / `admin123456`,仅首次启动生效,请尽快修改)。
|
||||||
|
|
||||||
|
## 核心特性
|
||||||
|
|
||||||
|
| 特性 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| 数据层 | EF Core 10,`Database:Provider` 切换 SQLite / MySQL(迁移:`Migrations/Sqlite`) |
|
||||||
|
| 认证 | JWT(WebUI/WebAPI/WebSocket 三端统一)+ 刷新令牌(散列入库/可撤销)+ PBKDF2 密码 |
|
||||||
|
| 权限 | RBAC + 权限点(`PermissionCodes`),`[Permission("code")]` 过滤,JWT `perm` Claim |
|
||||||
|
| CRUD | `CrudControllerBase<TEntity, TKey>`:每张表派生控制器即得 分页列表/详情/创建/更新/删除 |
|
||||||
|
| 负载模型 | WebSocket `MessageEnvelope`(t/i/ok/error/d/ts,替代 SocketObject);REST `ApiResponse<T>` |
|
||||||
|
| 插件系统 | **始终热重载**:`plugins/`(服务器插件)、`modules/{characters,skills,items}/`(实体模组);影子加载(正式文件不锁定)+ `_staging` 暂存区原子热替换 + 文件监视自动热重载 + 活跃对局引用计数保护 |
|
||||||
|
| 插件能力 | 服务器插件可注册 HTTP 端点(`/plugin/{name}/path`,可热移除)、WS 消息处理器(`example.echo` 等)、对局模式(`HandleGamingMessage`);实体模组经工厂注册(`Factory.RegisterFactory`)与实体 JSON 配置通道平行 |
|
||||||
|
| 回合记录 | 实现 Core v3 `IRoundRecordSink`:归档 `records/{gameId}.zip`(rounds_data.json + statistics.json + characters.json)+ `round_records` 表 + 可选远程 POST(`DefaultRoundRecordSink`) |
|
||||||
|
| 对局宿主 | `GameHostService`:MixGamingQueue 对战循环(AI 决策演示)、`gaming.round` 实时回合推送、`gaming.over` 结算广播、断线重连接口 |
|
||||||
|
| 回放 | `/api/games/{id}/meta|rounds/summary|rounds/{n}|statistics`(与 Testing-v3 归档格式兼容) |
|
||||||
|
| WebSocket | `/ws?access_token={jwt}`,内置 system.ping / system.info / auth.logout + room.*(创建/加入/退出/聊天/开始) + match.*(快速匹配) |
|
||||||
|
| 管理台 | 仪表盘(含 WS 连通性)、用户管理、插件与模组热重载、对局监控、回放中心、服务器日志(server_logs 结构化日志通道) |
|
||||||
|
|
||||||
|
## 示例加载项
|
||||||
|
|
||||||
|
- `plugins/FunGame.Server.Plugins.Example` —— 示例服务器插件(HTTP 端点 + WS echo + 对局模式),构建后自动进入 `_staging` 由宿主热替换
|
||||||
|
- `modules/FunGame.Server.Modules.Example` —— 示例角色/技能/物品模组(战士/法师/示例打击/回复药剂),演示工厂注册与热重载
|
||||||
|
|
||||||
|
## 常用命令
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# 构建
|
||||||
|
dotnet build FunGame.Server-v3.slnx
|
||||||
|
|
||||||
|
# EF 迁移(SQLite 为默认 Provider)
|
||||||
|
dotnet dotnet-ef migrations add <Name> --project src/FunGame.Server.Infrastructure --output-dir Migrations/Sqlite
|
||||||
|
|
||||||
|
# 清理开发数据库
|
||||||
|
Remove-Item src/FunGame.Server.Host/Data/fungame-server.db
|
||||||
|
```
|
||||||
|
|
||||||
|
## 文档
|
||||||
|
|
||||||
|
- [docs/01-v2-功能总结.md](docs/01-v2-功能总结.md) —— v2 服务器功能基线
|
||||||
|
- [docs/02-v3-Core-变更分析.md](docs/02-v3-Core-变更分析.md) —— Core v3 技术边界
|
||||||
|
- [docs/03-Server-v3-开发规划.md](docs/03-Server-v3-开发规划.md) —— 早期备选方案
|
||||||
|
- [docs/04-架构设计.md](docs/04-架构设计.md) —— **v3 架构定稿(开发依据)**
|
||||||
@@ -0,0 +1,376 @@
|
|||||||
|
# FunGame.Server v2 功能总结
|
||||||
|
|
||||||
|
> 分析对象:`C:\milimoe\FunGame.Server`(基于 FunGame.Core **v2 / 分支 v2 / 2.1.0**)
|
||||||
|
> 说明:本文基于 v2 服务器源码逐文件梳理,用于作为 v3 开发内容决策的基准。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 项目总览
|
||||||
|
|
||||||
|
v2 服务器仓库构建 **两个** 可执行程序 + 一个实现类库:
|
||||||
|
|
||||||
|
| 项目 | 类型 | 职责 |
|
||||||
|
|---|---|---|
|
||||||
|
| `FunGame.Server` (FunGameServer.exe) | .NET 控制台 (net10.0) | **Socket (TCP) 或 WebSocket 二选一** 的游戏服务器,带管理控制台 |
|
||||||
|
| `FunGame.WebAPI` (FunGameWebAPI.exe) | ASP.NET Core Web API (net10.0) | **WebSocket + RESTful API 共存**,共享同一套数据处理逻辑 |
|
||||||
|
| `FunGame.Implement` | 类库 | 实现 Core 的 `IServer` 接口(目前仅提供空 `SecretKey`) |
|
||||||
|
|
||||||
|
### 依赖(NuGet / 项目引用)
|
||||||
|
|
||||||
|
- `FunGame.Core` **2.1.0**(v2 核心库,含网络、SQLHelper、插件/模组加载器等全部服务器运行时)
|
||||||
|
- `FunGame.SQLQueryExtension` 2.0.0(SQLHelper 的查询扩展,全部 SQL 语句都来自这里)
|
||||||
|
- `MySql.Data`、`Microsoft.Data.Sqlite`
|
||||||
|
- `FunGame.Implement`(项目引用)
|
||||||
|
|
||||||
|
### v2 架构特征
|
||||||
|
|
||||||
|
v2 的架构是 **"Core 内置整套服务器运行时"**:网络监听、Socket 协议、数据库访问、SMTP 邮件、插件/模组加载器、任务调度、INI 配置……全部由 Core 提供,Server 项目只负责"接线"与业务逻辑(连接握手、数据请求分发、房间/用户/经济业务)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 启动流程(Main.cs / Program.cs)
|
||||||
|
|
||||||
|
### 2.1 FunGameServer(控制台)
|
||||||
|
|
||||||
|
1. 设置控制台标题、打印版本信息
|
||||||
|
2. 检查 `FunGame.ini` 配置文件,不存在则自动生成并退出
|
||||||
|
3. 读取配置(`ServerHelper.GetServerSettings()` → `Config`)
|
||||||
|
4. 解析启动参数:`--debug/-d`、`--allowanyorigin/-aao`
|
||||||
|
5. 初始化 SQLHelper(`FunGameSystem.InitSQLHelper`:MySQL/SQLite 二选一,首次运行自动建库)
|
||||||
|
6. 初始化 MailSender(SMTP)
|
||||||
|
7. 加载 Server 插件(`plugins/` 目录)
|
||||||
|
8. 加载游戏模组(`modules/` 目录,地图/角色/技能/物品/GameModuleServer 五项)
|
||||||
|
9. 初始化本地配置(`PluginConfig`:user_keys / local / sqlconfig)
|
||||||
|
10. 启动监听(Socket 或 WebSocket 二选一,`Config.UseWebSocket`)
|
||||||
|
11. 进入控制台命令循环
|
||||||
|
|
||||||
|
### 2.2 FunGameWebAPI(ASP.NET Core)
|
||||||
|
|
||||||
|
流程与上面类似,额外:
|
||||||
|
|
||||||
|
- 读取 Web API 插件(`WebAPIPlugin`,可在插件里注册 ASP.NET Controller)
|
||||||
|
- 搭建 ASP.NET Core:JWT 认证、CORS、OpenAPI + Scalar 文档、自定义 JSON 转换器、异常处理
|
||||||
|
- WebSocket 监听挂载在 `/ws` 路径
|
||||||
|
- 认证方案三种并存:`JwtBearer`、`APIBearer`(API Token)、`CustomBearer`
|
||||||
|
- 控制台命令循环在后台任务中运行
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 连接与会话管理
|
||||||
|
|
||||||
|
### 3.1 连接握手(`ConnectController.Connect<T>`)
|
||||||
|
|
||||||
|
- 人数上限检查(`ConnectingPlayerCount + OnlinePlayerCount > MaxPlayers` 拒绝)
|
||||||
|
- IP 黑名单检查(`BannedList`,按 `ip:port` 拆分比较)
|
||||||
|
- 客户端参数验证(`OnValidateClientParameters`):
|
||||||
|
- Desktop 参数 1:客户端模组列表,与服务器 `GameModuleSupported` 对比,缺失则拒绝
|
||||||
|
- Desktop 参数 2:客户端是否开启开发者模式(`isDebugMode`,开发者模式部分功能禁用)
|
||||||
|
- 可挂载 `ValidateClientParameters` 事件由插件扩展校验
|
||||||
|
- 握手回复 `Connect` 消息(成功/失败原因),携带服务器名与公告
|
||||||
|
- 连接成功回调插件事件:`OnBeforeConnectEvent` / `OnAfterConnectEvent`
|
||||||
|
|
||||||
|
### 3.2 客户端会话(`ServerModel<T>` : IServerModel)
|
||||||
|
|
||||||
|
每个连接对应一个 `ServerModel<ServerSocket>` 或 `ServerModel<ServerWebSocket>`:
|
||||||
|
|
||||||
|
- **消息分发** `SocketMessageHandler`:校验 Token(除 HeartBeat 外必须匹配)、处理 8 种消息类型
|
||||||
|
- **HeartBeat** 心跳(回显 probeId)
|
||||||
|
- **DataRequest** 数据请求(见第 4 节)
|
||||||
|
- **GamingRequest** / **Gaming** 对局请求与广播(转发给 `GameModuleServer`)
|
||||||
|
- **AnonymousGameServer** 匿名模组服务器(建立/断开)
|
||||||
|
- **ReconnectToGame** 断线重连对局(从 `NowGamingServers` 找回对局并重新下发 `StartGame`)
|
||||||
|
- **EndGame** 结束对局(清理 NowGamingServer,房间恢复 Created)
|
||||||
|
- **Disconnect** 断开连接
|
||||||
|
- 会话生命周期:`SetClientName`(加入 ClientList、在线数+1)→ `Start`(循环读取 + SQL 保活轮询)→ `Close`(移除、在线数-1)
|
||||||
|
- **失败计数**:连续读失败超过 `MaxConnectionFaileds`(默认 5)自动踢出
|
||||||
|
- **SQL 保活**:每 2 小时对 SQL 服务器做一次心跳查询
|
||||||
|
- 登录态:`PreLogin`(暂存 DataSet + 登录 key)→ `CheckLogin`(构造 User、重复登录检查、加入 UserList)
|
||||||
|
|
||||||
|
### 3.3 在线玩家管理
|
||||||
|
|
||||||
|
- `Listener.ClientList`(所有连接)/ `Listener.UserList`(已登录玩家)/ 全局 `FunGameSystem.UserList`
|
||||||
|
- `AddUser`:记录登录时间、更新最后登录 IP
|
||||||
|
- `RemoveUser`:记录下线时间、累计游戏时长(分钟)写入数据库
|
||||||
|
- 重复登录:`ForceLogOutDuplicateLogonUser` 强制旧连接下线
|
||||||
|
- 踢人/强制下线:`Kick` / `ForceLogOut`(会先退出房间)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 数据请求系统(DataRequest)
|
||||||
|
|
||||||
|
`DataRequestController<T>` 是业务核心,按 `DataRequestType` 分发,**全部请求类型**:
|
||||||
|
|
||||||
|
### RunTime
|
||||||
|
| 类型 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `RunTime_Logout` | 退出登录(插件可拦截) |
|
||||||
|
|
||||||
|
### Main(大厅/房间)
|
||||||
|
| 类型 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `Main_GetNotice` | 获取服务器公告 |
|
||||||
|
| `Main_CreateRoom` | 创建房间(7 位随机房间号、写库、插件事件) |
|
||||||
|
| `Main_UpdateRoom` | 拉取房间列表 |
|
||||||
|
| `Main_IntoRoom` | 进入房间(校验数据库存在、广播进入消息) |
|
||||||
|
| `Main_QuitRoom` | 退出房间(房主退出则移交/解散) |
|
||||||
|
| `Main_MatchRoom` | 开始/取消匹配 |
|
||||||
|
| `Main_Chat` | 房间聊天(广播同房间客户端) |
|
||||||
|
| `Main_Ready` / `Main_CancelReady` | 准备 / 取消准备 |
|
||||||
|
| `Main_StartGame` | 开始游戏(见 5.3) |
|
||||||
|
|
||||||
|
### Reg / Login(账号)
|
||||||
|
| 类型 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `Reg_Reg` | 注册(邮箱验证码流程) |
|
||||||
|
| `Login_Login` | 登录(密码或 autokey;check-login key 二次确认) |
|
||||||
|
| `Login_GetFindPasswordVerifyCode` | 找回密码验证码(10 分钟有效,SMTP 发送) |
|
||||||
|
| `Login_UpdatePassword` | 更新密码(换新用户密钥加密) |
|
||||||
|
|
||||||
|
### Room(房间管理)
|
||||||
|
| 类型 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `Room_UpdateRoomSettings` | 房主更新房间设置(类型/密码/人数/模组/地图,仅 Created 状态) |
|
||||||
|
| `Room_GetRoomPlayerCount` | 查询房间人数 |
|
||||||
|
| `Room_UpdateRoomMaster` | 转让房主(写库 + 广播) |
|
||||||
|
|
||||||
|
### UserCenter(个人中心)
|
||||||
|
| 类型 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `UserCenter_UpdateUser` | 更新用户资料 |
|
||||||
|
| `UserCenter_UpdatePassword` | 修改密码 |
|
||||||
|
| `UserCenter_DailySignIn` | 每日签到(连续签到天数,跨天重置) |
|
||||||
|
|
||||||
|
### Inventory(库存/经济)
|
||||||
|
| 类型 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `Inventory_GetStore` | 获取商店(按 store id + 商品) |
|
||||||
|
| `Inventory_GetMarket` | 获取市场(按用户或全局、状态过滤、按物品过滤) |
|
||||||
|
| `Inventory_StoreBuy` | 商店购买(双货币、库存扣减、事务) |
|
||||||
|
| `Inventory_MarketBuy` | 市场购买(15% 手续费、事务) |
|
||||||
|
| `Inventory_UpdateInventory` | 更新库存(全量/增量) |
|
||||||
|
| `Inventory_Use` | 使用物品(目标角色参数) |
|
||||||
|
| `Inventory_StoreSell` | 商店出售(按物品 Price 回收货币) |
|
||||||
|
| `Inventory_MarketSell` | 市场寄售(价格 + 库存) |
|
||||||
|
| `Inventory_MarketDelist` | 下架市场物品 |
|
||||||
|
| `Inventory_UpdateMarketPrice` | 修改寄售价 |
|
||||||
|
| `Inventory_GetOffer` | 查看交易报价(权限校验) |
|
||||||
|
| `Inventory_MakeOffer` | 发起交易报价 |
|
||||||
|
| `Inventory_ReviseOffer` | 修改报价(9 种状态机动作,见 7.4) |
|
||||||
|
| `Inventory_RespondOffer` | 回应报价(接受/拒绝) |
|
||||||
|
|
||||||
|
### Addon(扩展)
|
||||||
|
| 类型 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `Addon_Plugin` | 转发给 ServerPlugin / WebAPIPlugin 的 `HandleDataRequest`(支持指定目标插件) |
|
||||||
|
| `Addon_Module` | 转发给 GameModuleServer 的 `HandleDataRequest` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 房间与对局系统
|
||||||
|
|
||||||
|
### 5.1 房间模型
|
||||||
|
|
||||||
|
- `FunGameSystem.RoomList` 全局房间列表(内存)
|
||||||
|
- 房间属性:房间号(7 位随机大写)、房主、类型(`RoomType`)、密码、最大人数、模组(GameModule)、地图(GameMap)、是否排位、状态(Created/Matching/Gaming)
|
||||||
|
- 房间持久化在 `rooms` 表,服务器重启时清空房间表
|
||||||
|
|
||||||
|
### 5.2 匹配系统(Elo)
|
||||||
|
|
||||||
|
- 按 `RoomType` 过滤目标房间(`All` 匹配全部)
|
||||||
|
- 取房间玩家平均 Elo(`Statistics.EloStats[0]`),与玩家 Elo 差在 `300 * i` 内命中
|
||||||
|
- 每 10 秒扩大匹配范围(`i++` 并刷新房间列表),最长 50 秒后返回第一个房间
|
||||||
|
- 匹配过程在线程中轮询(100ms 间隔),可随时取消
|
||||||
|
|
||||||
|
### 5.3 开始游戏流程
|
||||||
|
|
||||||
|
- 房主触发:检查未准备玩家 → 提醒(15 秒 CD)→ 全部准备后发送"10 秒后开始"
|
||||||
|
- 玩家可请求房主开始(同样 15 秒 CD)
|
||||||
|
- 实际启动:`GameModuleLoader.GetServerMode(room.GameModule)` 获取 `GameModuleServer`,为房间所有玩家绑定该服务器、设置 `OnlineState.Gaming`、写入 `Listener.NowGamingServers[userId]`、构造 `GamingObject(room, users, master, all)`、调用 `StartServer(obj)` 后向玩家发送 `StartGame` 消息
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 账号系统(DataRequestService / Authenticator)
|
||||||
|
|
||||||
|
- **注册**:邮箱验证码(SMTP 发送 6 位数字码,10 分钟有效)→ 校验用户名/邮箱唯一 → 注册入库;首次注册管理员在数据库初始化时控制台交互完成
|
||||||
|
- **登录**:密码用"用户专属密钥"加密后比对(`FunGameSystem.GetUserKey(username)` 来自本地 `user_keys` 配置,改密时轮换密钥)→ 成功后下发 Guid 形式的 check-login key → 客户端凭 key 二次确认登录;支持 `autokey` 自动登录
|
||||||
|
- **找回密码**:邮箱匹配校验 → 验证码发送(10 分钟、限频)→ 验证通过后允许改密
|
||||||
|
- **2FA**:`Authenticator` / `TFA` 类已搭好骨架(继承 Core 的 `Authenticator` / `TwoFactorAuthenticator`),目前 `AfterAuthenticator` / `BeforeAuthenticator` / `IsAvailable` 均为空实现,预留接入点
|
||||||
|
- **安全细节**:密码加密使用每用户随机密钥(`Encryption.GenerateRandomString`);管理员 `IsAdmin` 标记;`NetworkUtility` 校验用户名长度(3~12,中文按 2 字符)、邮箱格式
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 经济系统
|
||||||
|
|
||||||
|
### 7.1 货币
|
||||||
|
|
||||||
|
- `Credits`(游戏币,InGameCurrency)与 `Materials`(材料,InGameMaterial)双货币
|
||||||
|
- 商店商品按货币分别定价(`Goods.GetPrice(currency)`)
|
||||||
|
|
||||||
|
### 7.2 商店
|
||||||
|
|
||||||
|
- 商店含商品(Goods)+ 价格表(GoodsPrices)+ 库存(Stock,-1 为无限)
|
||||||
|
- 购买:事务内扣货币、扣库存、生成物品(`IsTradable=false`、设定可交易时间、价格折算 35% / 7 倍)、支持 `ignore` 部分失败仍提交
|
||||||
|
- 出售:按物品 `Price` 回收货币,检查 `IsSellable` 与可出售时间
|
||||||
|
|
||||||
|
### 7.3 市场
|
||||||
|
|
||||||
|
- 寄售(价格 + 库存数量)、改价、下架、按用户/状态/物品查询
|
||||||
|
- 购买:15% 手续费(卖家实收 85%),事务内转移物品(买家获得的新物品有可交易冷却)
|
||||||
|
|
||||||
|
### 7.4 交易报价(Offer 状态机)
|
||||||
|
|
||||||
|
- 发起 → 协商(最多 3 轮)→ 确认 → 发送 → 接受/拒绝/取消/过期
|
||||||
|
- 9 种动作:`OfferorRevise / OfferorConfirm / OfferorSend / OfferorCancel / OfferorAccept / OffereeRevise / OffereeConfirm / OffereeSend / OffereeAccept / OffereeReject`
|
||||||
|
- 物品可交易性检查(`IsTradable` + `NextTradableTime`)、修改前备份(`BackupOfferItem`)、事务回滚
|
||||||
|
|
||||||
|
### 7.5 物品使用
|
||||||
|
|
||||||
|
- `item.UseItem(user, useCount, args)`,参数携带目标角色数组;使用后更新库存
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 数据库层
|
||||||
|
|
||||||
|
- **双数据库**:MySQL / SQLite,由 `FunGame.ini` 的 `[MySQL]` / `[SQLite]` 开关决定;抽象基类 `SQLHelper`,Server 侧实现 `MySQLHelper` / `SQLiteHelper`(连接、执行、事务、DataSet、参数化)
|
||||||
|
- **首次初始化**:执行 `fungame.sql` / `fungame_sqlite.sql` 建库脚本(Core v2 提供)→ 控制台创建管理员 → 生成 `.apisecret` 文件与默认 API Token(`fungame_web_api`,仅显示一次)→ 写 `Initialization` 配置标记
|
||||||
|
- **表结构(来自 SQLQueryExtension)**:users、user_profiles、user_characters、user_items、inventories、stores、goods、goods_prices、store_goods、market_items、offers、offer_items、rooms、reg_verify_codes、forget_verify_codes、user_sign_ins、api_tokens、configs、server_login_logs、user_logs 等
|
||||||
|
- 版本补丁脚本:`Library/SQLScript/PatchScript/{mysql,sqlite}/2.0.0.250728.sql`
|
||||||
|
- 服务器启动登记 `ServerLoginLogs`;每个会话有 2 小时 SQL 心跳保活
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 插件系统
|
||||||
|
|
||||||
|
### 9.1 ServerPlugin(`plugins/` 目录 DLL)
|
||||||
|
|
||||||
|
- 继承 Core 的 `ServerPlugin`,通过 `LoadPlugins` / `LoadPluginsByHotLoadMode` 加载(`UseHotLoadAddons` 开启热加载)
|
||||||
|
- 全流程事件钩子(在 DataRequestController / ServerModel / Main 中触发):
|
||||||
|
- 连接:`OnBefore/AfterConnectEvent`、`OnAfterDisconnectEvent`
|
||||||
|
- 登录:`OnBefore/AfterLoginEvent`、`OnBefore/AfterLogoutEvent`、`OnBeforeRegEvent`、`OnAfterRegEvent`
|
||||||
|
- 房间:`OnBefore/AfterCreateRoomEvent`、`IntoRoom`、`QuitRoom`、`ChangeRoomSetting`
|
||||||
|
- 对局:`OnBefore/AfterStartGameEvent`、`OnBefore/AfterEndGameEvent`、`OnBeforeStartMatchEvent`
|
||||||
|
- 行为:`OnBefore/AfterSendTalkEvent`、`OnBeforeChangeProfileEvent`、`OnBeforeChangeAccountSettingEvent`、`OnBefore/AfterSignInEvent`、`OnBefore/AfterBuyItemEvent`、`OnBefore/AfterUseItemEvent`、`OnBeforeOpenStoreEvent`、`OnBefore/AfterStartGameEvent`……
|
||||||
|
- 事件均支持 `Cancel` 拦截(返回 `GetPluginCancelString` 拒绝原因)
|
||||||
|
- 插件可响应控制台指令(`plugin.ProcessInput`)、处理自定义 DataRequest(`HandleDataRequest`)
|
||||||
|
|
||||||
|
### 9.2 WebAPIPlugin
|
||||||
|
|
||||||
|
- 类似 ServerPlugin + 可在插件程序集内注册 ASP.NET Controller(`AssemblyPart` 动态加入)
|
||||||
|
- 额外钩子:`OnWebAPIStarted`(拿到 `WebApplication` 与 listener 后回调)
|
||||||
|
|
||||||
|
### 9.3 热加载
|
||||||
|
|
||||||
|
- `reload addons/modules/plugins/serverplugins/webapiplugins` 控制台指令
|
||||||
|
- `TaskScheduler.StartCleanUnusedAddonContexts` 清理卸载的加载上下文
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. 模组系统
|
||||||
|
|
||||||
|
- `GameModuleLoader` 加载 `modules/` 目录:`GameMap`(地图)、`CharacterModule`(角色)、`SkillModule`(技能)、`ItemModule`(物品)、`GameModuleServer`(模组服务器)
|
||||||
|
- 加载校验:模组服务器必须有对应的 `DefaultMap` 地图,否则加载失败
|
||||||
|
- `GameModuleServer`:对局服务器实现(`StartServer(GamingObject)`、`GamingMessageHandler`、`HandleDataRequest`、`AnonymousGameServerHandler`、`Close`),由模组开发者在 DLL 中实现
|
||||||
|
- 热更新:`HotReloadGameModuleList`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. 控制台管理指令(FunGameServer / FunGameWebAPI 共用)
|
||||||
|
|
||||||
|
| 指令 | 别名 | 功能 |
|
||||||
|
|---|---|---|
|
||||||
|
| `help` | - | 列出可用指令及别名 |
|
||||||
|
| `quit` / `exit` / `close` | - | 关闭服务器 |
|
||||||
|
| `restart` | - | 重新启动监听(仅未运行时) |
|
||||||
|
| `kick <客户端名>` | - | 踢出客户端 |
|
||||||
|
| `logout <玩家名>` | - | 强制下线玩家 |
|
||||||
|
| `show [clients\|users\|-c\|-u]` | `clients` / `users` | 查看在线客户端/玩家列表 |
|
||||||
|
| `ban add\|remove <ip>` | `-a` / `-r` | 添加/移除 IP 黑名单 |
|
||||||
|
| `reload <addons\|modules\|plugins\|serverplugins\|webapiplugins>` | `-a/-m/-p/-sp/-wp` | 热重载加载项 |
|
||||||
|
|
||||||
|
- 命令解析支持引号与转义(`ParseCommandLine`)
|
||||||
|
- 未知指令广播给插件处理
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. WebAPI(RESTful)接口清单
|
||||||
|
|
||||||
|
统一返回 `PayloadModel<T>`(Event / RequestType / StatusCode / Message / Timestamp / Data)。
|
||||||
|
|
||||||
|
### 认证相关
|
||||||
|
| 端点 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `POST /User/register` | 注册(RegDTO) |
|
||||||
|
| `POST /User/login` | 登录(LoginDTO,签发 JWT) |
|
||||||
|
| `POST /User/logout` | 退出登录 |
|
||||||
|
| `POST /User/refresh` | 刷新 JWT |
|
||||||
|
|
||||||
|
### 大厅/房间
|
||||||
|
| 端点 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `GET /Main/notice` | 服务器公告 |
|
||||||
|
| `POST /Main/chat` | 聊天 |
|
||||||
|
| `POST /Room/create` / `list` / `join` / `quit` / `match` / `ready` / `cancelready` / `start` / `updateroomsettings` / `playercount` / `updatemaster` | 房间全流程 |
|
||||||
|
|
||||||
|
### 用户中心
|
||||||
|
| 端点 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `PUT /UserCenter/updateuser` / `updatepassword` | 资料/密码 |
|
||||||
|
| `POST /UserCenter/dailysignin` | 每日签到 |
|
||||||
|
|
||||||
|
### 库存/经济
|
||||||
|
| 端点 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `GET /Inventory/getstore`、`getmarketbyuser`、`getmarketbyitem`、`getoffer` | 查询类 |
|
||||||
|
| `POST /Inventory/storebuy`、`marketbuy`、`updateinventory`、`useitem`、`storesell`、`marketsell`、`marketdelist`、`updatemarketprice`、`makeoffer`、`reviseoffer`、`respondoffer` | 操作类 |
|
||||||
|
|
||||||
|
### 协议转发
|
||||||
|
| 端点 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `POST /DataRequest` | 客户端以 `PayloadModel<DataRequestType>` 形式直接调用数据请求(JWT 身份 → RESTfulAPIModel) |
|
||||||
|
| `POST /GamingRequest` | 对局请求转发 |
|
||||||
|
| `POST /Adapter` | 接收原始 `SocketObject`(供客户端协议适配) |
|
||||||
|
| `WS /ws` | WebSocket 接入点(完整游戏协议) |
|
||||||
|
|
||||||
|
### WebAPI 架构要点
|
||||||
|
|
||||||
|
- `RESTfulAPIListener` + `RESTfulAPIModel`:REST 请求通过 `IUserContext`(`HttpUserContext` 从 JWT 取用户名)关联在线玩家模型,与 WebSocket 玩家**共享同一套 ServerModel 逻辑**
|
||||||
|
- `JwtAuthenticationMiddleware`:JWT 与两种 Bearer 处理器(API Token / 自定义 Token)
|
||||||
|
- `JWTService`:签发/刷新 JWT
|
||||||
|
- OpenAPI + Scalar 文档(仅开发环境);CORS 白名单(默认 localhost:12099,`--allowanyorigin` 可全开)
|
||||||
|
- 静态文件托管 + 前端默认页
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 13. 配置(FunGame.ini)
|
||||||
|
|
||||||
|
| 节 | 键 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| `[Console]` | `LogLevel`、`UseHotLoadAddons` | 日志级别、热加载开关 |
|
||||||
|
| `[Server]` | `Name`、`Password`、`Description`、`Notice`、`Key`、`Status`、`BannedList`、`UseDesktopParameters` | 服务器信息与公告、社区注册 Key、黑名单 |
|
||||||
|
| `[ServerMail]` | `OfficialMail`、`SupportMail` | 官方/支持邮箱 |
|
||||||
|
| `[Socket]` | `Port`、`UseWebSocket`、`WebSocketAddress`、`WebSocketPort`、`WebSocketSubUrl`、`WebSocketSSL`、`MaxPlayer`、`MaxConnectFailed` | 监听与人数上限 |
|
||||||
|
| `[MySQL]` / `[SQLite]` | `UseMySQL` / `UseSQLite`、连接参数 | 数据库开关与连接串 |
|
||||||
|
| `[Mailer]` | `UseMailSender`、`MailAddress`、`Name`、`Password`、`Host`、`Port`、`SSL` | SMTP 邮件服务 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 14. 日志
|
||||||
|
|
||||||
|
- `ServerHelper` 分级彩色控制台输出:`[Core] [Error] [Api] [Warning] [Interface] [DataRequest] [Plugin] [GameModule] [System]`
|
||||||
|
- 时间戳 + 日志级别前缀(TRACE~CRIT,按 `Config.LogLevel` 过滤)
|
||||||
|
- 异常写 `error.log`(`TXTHelper.AppendErrorLog`)
|
||||||
|
- 插件/模组可通过委托 `WriteLine_Addons` 接入同一日志体系
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 15. 小结(v2 能力全景)
|
||||||
|
|
||||||
|
```
|
||||||
|
FunGameServer v2 = 连接层(Socket/WebSocket) + 会话层 + 业务层(房间/匹配/账号/经济)
|
||||||
|
+ 插件/模组扩展 + 控制台管理 + 双数据库 + SMTP + 日志
|
||||||
|
FunGameWebAPI v2 = WebSocket + REST(JWT) + 与游戏服务器共享的会话/业务模型
|
||||||
|
```
|
||||||
|
|
||||||
|
**v2 中属于"服务器自研"(迁移到 v3 需要保留/重写)**:连接握手、会话模型、DataRequest 分发、房间/匹配/账号/经济全部业务逻辑、控制台指令、数据库访问封装。
|
||||||
|
|
||||||
|
**v2 中由 Core v2 提供(v3 已删除,见 02 文档)**:网络监听与协议、SQLHelper 抽象、MailSender、插件/模组加载器、INI 读写、任务调度、Factory、日志工具等。
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
# FunGame.Core v3 变更分析(v2 → v3)
|
||||||
|
|
||||||
|
> 分析对象:`C:\milimoe\FunGame.Core`(master 分支,3.0.0-dev,net10.0)
|
||||||
|
> 对比基准:v2 分支(2.1.0 Release)
|
||||||
|
> 配套参考:`C:\milimoe\FunGame.Testing-v3`(v3 的测试项目,WebAPI + React 回放台)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 总体结论(先看这里)
|
||||||
|
|
||||||
|
**v3 把 Core 从"游戏服务器运行时框架"重构为"纯回合制战斗引擎库"。**
|
||||||
|
|
||||||
|
- v2:Core = 网络 + 数据库 + 插件 + 模组加载 + 邮件 + 任务调度 + 战斗引擎(一整包服务器运行时)
|
||||||
|
- v3:Core = 实体模型 + 战斗引擎(GamingQueue)+ 回合记录/回放基础设施 + 模块(数据驱动)机制。**网络、SQL、SMTP、插件加载器等全部从 Core 中移除**,由使用方(Server / WebAPI 等)自行实现。
|
||||||
|
|
||||||
|
v2→v3 共 10 个提交、280 个文件变更,+4816 / -18642 行——**删除远多于新增**,删除的正是"服务器运行时"那一层。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 版本与命名空间
|
||||||
|
|
||||||
|
| 项 | v2 | v3 |
|
||||||
|
|---|---|---|
|
||||||
|
| 版本 | 2.1.0 | 3.0.0-dev(每日版本后缀) |
|
||||||
|
| 目标框架 | net10.0(v2 分支后期已升级) | net10.0 |
|
||||||
|
| 根命名空间 | `Milimoe.FunGame.Core` | `FunGame.Core` |
|
||||||
|
| 打包 | NuGet `FunGame.Core` | 继续 NuGet 发布(新增自动发布工作流)+ slnx |
|
||||||
|
| 文档 | README.md | README.md + README_EN.md |
|
||||||
|
|
||||||
|
> ⚠️ **命名空间整体变更**:所有 v2 代码中的 `using Milimoe.FunGame.Core.*` 在 v3 都要改为 `using FunGame.Core.*`。这是迁移时最机械但覆盖面最广的改动。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 从 Core 中移除的内容(v3 不再提供)
|
||||||
|
|
||||||
|
> 这些能力在 v3 Server 项目中**必须自行实现**(或放弃)。
|
||||||
|
|
||||||
|
### 3.1 网络与协议层(全部移除)
|
||||||
|
|
||||||
|
| 移除项(v2 位置) | 功能 |
|
||||||
|
|---|---|
|
||||||
|
| `Service/SocketManager.cs` | Socket 服务管理 |
|
||||||
|
| `Library/Common/Network/Socket.cs`、`SocketObject.cs` | Socket 对象与消息协议(SocketMessageType 等) |
|
||||||
|
| `Library/Common/Network/ServerSocket.cs`、`ServerWebSocket.cs` | 服务端 Socket/WebSocket 实现 |
|
||||||
|
| `Library/Common/Network/SocketListener.cs`、`HTTPListener.cs` | 监听器(TCP / HTTP 前缀) |
|
||||||
|
| `Library/Common/Network/HTTPClient.cs` | HTTP 客户端封装 |
|
||||||
|
| `Interface/Base/ISocketListener`、`ISocketMessageProcessor`、`IBaseSocket`、`ISocketHeartBeat`、`ISocketHandler`、Sockets/* | 网络接口 |
|
||||||
|
| `Controller/SocketHandlerController.cs`、`Service/HTTPManager.cs` | 消息处理与 HTTP 管理 |
|
||||||
|
| `Library/Common/Architecture/HeartBeat.cs`、`AsyncAwaiter.cs`、`TaskAwaiter.cs`、`SyncAwaiter.cs`(部分) | 心跳与异步等待基建 |
|
||||||
|
|
||||||
|
### 3.2 数据访问层(移除)
|
||||||
|
|
||||||
|
| 移除项 | 功能 |
|
||||||
|
|---|---|
|
||||||
|
| `Api/Transmittal/SQLHelper.cs`、`Interface/Base/ISQLHelper.cs`、`Model/SQLServerInfo.cs` | SQLHelper 抽象 |
|
||||||
|
| `Library/SQLScript/**`(全部) | 全部 SQL 语句类(UserQuery、RoomQuery、OffersQuery……)与建库脚本 fungame.sql / fungame_sqlite.sql、补丁脚本 |
|
||||||
|
| `Library/Common/JsonConverter/DataSetConverter.cs`、`DataTableConverter.cs` | DataSet/DataTable 序列化(SQL 时代的遗留) |
|
||||||
|
|
||||||
|
### 3.3 通信协议与事务(移除)
|
||||||
|
|
||||||
|
| 移除项 | 功能 |
|
||||||
|
|---|---|
|
||||||
|
| `Api/Transmittal/DataRequest.cs` | DataRequestType 数据请求传输模型 |
|
||||||
|
| `Api/Transmittal/MailSender.cs`、`IMailSender`、`Model/SmtpClientInfo.cs`、`Library/Common/Network/MailObject.cs` | SMTP 邮件 |
|
||||||
|
| `Library/Common/Addon/AddonDataRequestEventArgs.cs` | 插件数据请求事件 |
|
||||||
|
|
||||||
|
### 3.4 插件 / 模组 / 加载器(移除或重构)
|
||||||
|
|
||||||
|
| 移除项 | 功能 |
|
||||||
|
|---|---|
|
||||||
|
| `Service/AddonManager.cs`、`HotLoadAddonManager.cs` | 插件管理、热加载上下文管理 |
|
||||||
|
| `Api/Utility/PluginLoader.cs`、`ServerPluginLoader.cs`、`WebAPIPluginLoader.cs`、`PluginConfig.cs` | 插件加载器与配置存储 |
|
||||||
|
| `Library/Common/Addon/Plugin.cs`、`ServerPlugin.cs`、`WebAPIPlugin.cs`、`GameModule.cs`、`GameModuleDepend.cs`、`GameModuleServer.cs`、`GamingObject.cs` | 插件/模组基类(**全部删除**) |
|
||||||
|
| `Api/Utility/GameModuleLoader.cs` | 模组 DLL 加载器 |
|
||||||
|
| `Controller/AddonController.cs`、`BaseAddonController.cs`、`ServerAddonController.cs`、`RunTimeController.cs` | 加载项控制器(事件分发中枢) |
|
||||||
|
| `Interface/Base/Addons/*`、`Interface/Base/HTTP/*`、`Interface/Base/IAddon.cs`→`IModule.cs` | 加载项接口(重构为模块接口) |
|
||||||
|
| `Api/Utility/TextReader.cs`(txt 资源读取)、`TwoFactorAuthenticator.cs`、`Singleton.cs`、`TaskScheduler.cs`、`ConcurrentFIFOQueue.cs`、`ConcurrentModelList.cs` | 工具类 |
|
||||||
|
|
||||||
|
### 3.5 服务器模型(移除)
|
||||||
|
|
||||||
|
| 移除项 | 功能 |
|
||||||
|
|---|---|
|
||||||
|
| `Interface/Base/IServerModel.cs` | 服务器客户端模型接口(v2 Server 的 ServerModel 实现它) |
|
||||||
|
| `Model/Gaming.cs`、`Model/RoomList.cs`、`Model/ActionQueue.cs`、`Model/RecurringTask.cs`、`Model/ScheduledTask.cs`、`Model/Session.cs`、`Model/FunGameConfig.cs` | 服务器状态模型 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. v3 新增 / 重构的内容
|
||||||
|
|
||||||
|
### 4.1 回合记录框架(Framework 模型,v3 核心新特性)
|
||||||
|
|
||||||
|
`Model/Framework/` 下新增,围绕"**可回放的对局记录**"设计:
|
||||||
|
|
||||||
|
| 类型 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `RoundRecord` | 单回合完整记录:行动流(Actions)、操作类型与目标、技能/物品及消耗、伤害/暴击/闪避/免疫/治疗字典、特效触发(Effects)与施加特效(ApplyEffects)、击杀/助攻、连杀、吟唱/硬直、复活、回合奖励、杂项消息、全角色清单、队伍归属映射、检查点快照、最终统计、游戏结果排名(`GameResult`)等;提供 `Snapshot()` 结构快照 |
|
||||||
|
| `ActionRecord` | 单次操作记录(决策点系统允许一回合多次操作,`ActionIndex` 从 1 开始),含伤害记录、特效记录、状态变更等 |
|
||||||
|
| `CharacterStateSnapshot` | 角色状态快照(HP/MP/EP、装备明细、物品、技能、状态栏特效) |
|
||||||
|
| `EquipmentStateSnapshot` | 装备状态快照 |
|
||||||
|
| `DamageRecord` / `DeathRelation` | 伤害记录 / 死亡关系 |
|
||||||
|
| `RankingEntry` | 游戏结束排名条目(角色或团队、胜者标记、KDA、得分、赚钱) |
|
||||||
|
| `RoundRecordPayload` | **外发数据包线协议**:紧凑字段 `g`(队列 Guid)/`t`(时间戳)/`e`(事件 id)/`d`(数据)/`s`(签名) |
|
||||||
|
| `GameMap`、`Grid` | 地图与格子(原 Addon 中移入 Framework 并重构) |
|
||||||
|
|
||||||
|
### 4.2 回合记录外发通道(v3 最重要新增特性)
|
||||||
|
|
||||||
|
- `Interface/Base/IRoundRecordSink`:**回合记录外发接口**,8+1 个事件:
|
||||||
|
- `SendAction`("0",每次角色操作后即时)、`SendRound`("1",每操作后当前回合全量)、`SendCheckpointRound`("2",检查点回合,带全角色状态快照)、`SendCharacterStatistics`("3")、`SendCharacters`("4")、`SendTeams`("5")、`SendQueueData`("6",行动顺序表)、`SendEliminatedCharacters`("7")、`SendEliminatedTeams`("8")
|
||||||
|
- 另有 `Attach(queueId)`、`End()` 生命周期方法
|
||||||
|
- `Api/DefaultRoundRecordSink`:默认实现——**即时主动 POST 外发**:把数据包 POST 到外部专用服务器(Bearer AccessToken 可选),支持 `Secret` 签名握手(事件 "13" 验证签名,失败每 60s 重试,成功前不外发其他事件),HttpClient 5 秒超时防挂起
|
||||||
|
- `Api/BattleStatePredictor`:**状态推算器**——从回合记录序列推算任意回合的全角色状态(基于检查点 + 行动记录),回放端无需完整状态即可展示
|
||||||
|
- `Api/RoundRecordRenderer`:回合记录文本渲染(`RenderRound` / `RenderAll` / `RenderCharacterActions`)
|
||||||
|
|
||||||
|
### 4.3 战斗引擎重构(GamingQueue)
|
||||||
|
|
||||||
|
- `Model/ActionQueue.cs` → `Model/Queue/GamingQueue.cs`(**+615 行重写**)
|
||||||
|
- `MixGamingQueue`(混战队列)、`TeamGamingQueue`(团队队列)重构
|
||||||
|
- 新增属性:`RoundRecordSink`(绑定外发通道)、`CheckpointInterval`(检查点间隔,默认 50 回合)、`Rounds`(全量回合记录)、`LastRound`、`GameOver`、`CustomData`、`EarnedMoney`、`CharacterDecisionPoints`、`MaxScoreToWin`、`MaxRespawnTimes` 等
|
||||||
|
- 战斗能力保留并强化:伤害计算(物理/魔法)、暴击/闪避/免疫、特效钩子(`EffectHookCache`)、决策点系统(DecisionPoints)、复活、回合奖励、商店(AddStoreItems/BuyItems)、物品使用、地图寻路与目标选择、AI 决策
|
||||||
|
- `Api/EffectHookCache.cs`:特效钩子缓存(配合 `Model/Framework/ActionRecord` 的"特效记录"重写,提交 #167"依靠检查方法重写以记录触发的特效")
|
||||||
|
|
||||||
|
### 4.4 实体工厂与模块配置(数据驱动)
|
||||||
|
|
||||||
|
- `Api/Factory.cs`:新实体工厂——`Factory.OpenFactory.RegisterFactory<T>` / `GetInstance<T>(id, name, args)`(按 id/name 动态实例化 Character/Skill/Effect/Item/Inventory/Room/User),`GetGameModuleInstances<T>(module_name, file_name)` 从**模块配置文件**批量实例化,`CreateGameModuleEntityConfig<T>` 生成模块实体配置
|
||||||
|
- `Api/EntityModuleConfig.cs`:实体模块配置文件(`modules/` 目录、可配置目录)
|
||||||
|
- `Library/Module/`:`IModule` + `CharacterModule` / `SkillModule` / `ItemModule`(`Load()` / `UnLoad()`),替代 v2 的 `Library/Common/Addon/GameModule` 体系;`Example/` 示例模块
|
||||||
|
- 意义:**模组内容 = 代码类 + 配置文件**,运行期按配置实例化,替代 v2 的"DLL 扫描加载"模式
|
||||||
|
|
||||||
|
### 4.5 JSON 序列化体系重构
|
||||||
|
|
||||||
|
- `Service/JsonManager.cs` → `Api/JsonService.cs`(全局 `JsonSerializerOptions`、`GeneralOptions`)
|
||||||
|
- `Library/Common/JsonConverter/` 大幅更新:新增 `ActionRecordConverter`、`CharacterStateSnapshotConverter`、`RankingEntryConverter`、`RoundRecordConverter`(重写)、`EntityRefHelper`(实体引用表,解决循环引用/共享引用)
|
||||||
|
- 移除 DataSet/DataTable 转换器(SQL 时代产物)
|
||||||
|
|
||||||
|
### 4.6 工具类整合
|
||||||
|
|
||||||
|
- `Api/General.cs`:合并 `NetworkUtility`(partial + RegexGenerator)、`Encryption`(HMAC/SHA/RSA/MD5/随机串)、`Verification`(验证码)、日期时间工具、数值工具(Round/PercentageCheck 等)、JSON 快捷方法
|
||||||
|
- `Api/Attribute.cs`、`LINQExtension.cs`、`SkillExtension.cs`、`OpenItemAdapter`/`OpenSkillAdapter`(开放实体适配)、`NovelConfig.cs`(剧情配置)
|
||||||
|
|
||||||
|
### 4.7 保留的内容(基本未动)
|
||||||
|
|
||||||
|
- `Entity/**`:Character / Skill / Effect / Item / Inventory / User / Room / Team / Store / Market / Offer / Goods / Club / Season / Explore(Region/Quest/Activity) / Statistics 等全部实体(局部字段调整:Item 构造公开、Skill 关联 Item、Equal 应用 Guid)
|
||||||
|
- `Library/Constant/`:TypeEnum(含战斗相关枚举)、StateEnum、ResultEnum、ConstantSet、FunGameInfo、General(经济平衡常量)
|
||||||
|
- `Library/Common/Event/`:事件参数(Connect/Login/Register/Room/SendTalk/General/Gaming/UserActivity 等,命名空间调整)
|
||||||
|
- `Interface/Event/`:事件处理器接口(IGamingConnectEventHandler、IGamingRoundEventHandler 等局内事件 + EventCenter 活动/商店中心)
|
||||||
|
- `Model/PrefabricatedEntity/`:预制技能/特效(灵魂绑定、魔法卡包等)
|
||||||
|
- `Library/Architecture/BaseEntityConverter.cs`:实体转换基类
|
||||||
|
- `Library/Exception/`:异常体系
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. FunGame.Testing-v3 参考(v3 的"服务器"长什么样)
|
||||||
|
|
||||||
|
Testing-v3 是 v3 Core 目前唯一的宿主参考实现,展示了 v3 时代的运行形态:
|
||||||
|
|
||||||
|
```
|
||||||
|
FunGame.Testing-v3/
|
||||||
|
├── WebAPI/ # ASP.NET Core Web API(net10.0,唯一项目)
|
||||||
|
│ ├── Program.cs # 入口:模块初始化 + 6 个 REST 端点 + 托管前端
|
||||||
|
│ ├── Services/ArchiveStore.cs # 读取 rounds_archive.zip(回合存档)
|
||||||
|
│ ├── Tests/FunGameService.cs # 角色/技能/物品注册表 + Rating 计算
|
||||||
|
│ ├── Tests/FunGameSimulation.cs # 进程内跑一局 AI 对战(GamingQueue)
|
||||||
|
│ ├── Tests/EffectAutoRecordTest.cs # 特效自动记录测试
|
||||||
|
│ ├── Tests/RoundRecordSinkTest.cs # RoundRecordSink 测试
|
||||||
|
│ └── OshimaGameModules/ # 模组代码(角色/技能/特效/物品,全部编译期引用)
|
||||||
|
├── webui/ # React + Vite + Tailwind 回放台(统计/回放/快照三面板)
|
||||||
|
└── rounds_archive.zip # 回合记录归档(rounds_data.json)
|
||||||
|
```
|
||||||
|
|
||||||
|
**关键模式**:
|
||||||
|
|
||||||
|
1. **进程内直接引用模组代码**(`characterModule.Load()` 等),不再有 DLL 插件/模组加载器
|
||||||
|
2. **`GamingQueue` 跑完一局 → `RoundRecord` 列表 → 压缩归档 `rounds_archive.zip`**
|
||||||
|
3. **WebAPI 提供回放端点**:`/api/meta`、`/api/rounds/summary`、`/api/rounds/{n}`、`/api/statistics`、`/api/reload`、`/api/simulate/team`
|
||||||
|
4. **无数据库、无账号、无网络协议**——纯战斗模拟与回放
|
||||||
|
5. 发布 Linux 自包含(publish-linux.sh)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. v2 → v3 变化对照总表
|
||||||
|
|
||||||
|
| 能力 | v2(Core 提供) | v3(Core 提供) | Server-v3 需要 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 回合制战斗引擎 | ✅ GamingQueue | ✅ 重构强化 + 回合记录 | 直接用 |
|
||||||
|
| 回合记录/回放 | ❌ | ✅ RoundRecord/ActionRecord/快照/渲染 | 直接用 |
|
||||||
|
| 记录外发(POST) | ❌ | ✅ IRoundRecordSink / DefaultRoundRecordSink | 配置 URL 或自定义实现 |
|
||||||
|
| 实体/模块 | Addon DLL 体系 | IModule + 实体配置 + Factory | 采用新模块方式 |
|
||||||
|
| 网络(Socket/WS) | ✅ | ❌ | **自研或引入第三方** |
|
||||||
|
| 消息协议(SocketObject/DataRequest) | ✅ | ❌ | **自研** |
|
||||||
|
| 数据库(SQLHelper + SQL 脚本) | ✅ | ❌ | **自研**(EF/ADO/Dapper…) |
|
||||||
|
| 邮件 SMTP | ✅ | ❌ | 自研或引入库 |
|
||||||
|
| 插件系统 + 热加载 | ✅ | ❌ | **自研**(或改为服务内模块) |
|
||||||
|
| 账号/注册/登录/2FA | 部分(Authenticator 骨架) | ❌ | 自研 |
|
||||||
|
| 房间/匹配/Elo | ❌(Server 层实现) | ❌ | 迁移 v2 Server 代码 |
|
||||||
|
| 商店/市场/报价经济 | ❌(Server 层实现) | ❌ | 迁移 v2 Server 代码 |
|
||||||
|
| 控制台管理 | 部分(Core 提供订单定义) | ❌ | 自研 |
|
||||||
|
| INI 配置 | ✅ | ❌ | 自研或引入库 |
|
||||||
|
| 日志 | ✅ TXTHelper/ServerHelper | ❌ | 自研或引入库(ILogger 等) |
|
||||||
|
| 事件体系 | 插件事件链 | 局内事件 + EventCenter | 自研服务事件 |
|
||||||
|
| 任务调度 | ✅ TaskScheduler | ❌ | 自研 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 对 Server-v3 开发的关键影响(决策输入)
|
||||||
|
|
||||||
|
1. **Core v3 不再是"开箱即用的服务器"**:v3 Server 需要自己补齐网络、数据库、认证、配置、日志五大基础设施。
|
||||||
|
2. **战斗与回放是 v3 的拳头能力**:`GamingQueue` + `RoundRecord` + `IRoundRecordSink`(即时 POST 外发)+ `BattleStatePredictor` + `RoundRecordRenderer` 构成完整的"对局产生 → 记录 → 外发 → 回放"链路,这是 v3 Server 应当优先围绕设计的核心。
|
||||||
|
3. **默认外发通道是 HTTP POST**(`DefaultRoundRecordSink`):说明 v3 的设计意图之一是"战斗服务器算、外部服务收"——Server-v3 天然适合做成 **WebAPI 形态**,自己既是战斗宿主又是记录接收方(或转发到数据服务)。
|
||||||
|
4. **模组体系变化**:从"DLL 热插拔"变为"代码引用 + 配置数据"。Server-v3 要么跟随(进程内引用模组)、要么自行实现 DLL 隔离加载(回到 v2 思路,Core 不再帮忙)。
|
||||||
|
5. **v2 Server 的业务代码(房间/匹配/账号/经济/控制台)仍然有效**,可以整体迁移,但要换掉所有 `Milimoe.FunGame.Core.*` 命名空间引用,并重写底层依赖(SQLHelper→自选数据层、DataRequest 传输→自定协议)。
|
||||||
|
6. **Testing-v3 不是"服务器"**:它是无账号无网络的对战模拟/回放台。Server-v3 可以在它之上叠加网络/账号/房间层,或者完全另起架构。
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
# Server-v3 开发规划(决策与建议)
|
||||||
|
|
||||||
|
> 目标:以 FunGame.Core **v3**(master)为基础,在 `C:\milimoe\FunGame.Server-v3` 重新构建服务器。
|
||||||
|
> 本文基于 `01-v2-功能总结.md` 与 `02-v3-Core-变更分析.md`,列出**必须做的决策**、**建议架构**与**开发路线**,供确定 v3 开发内容。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 先决决策(需要你拍板的 5 个问题)
|
||||||
|
|
||||||
|
### 决策 A:服务器形态
|
||||||
|
| 选项 | 说明 | 建议 |
|
||||||
|
|---|---|---|
|
||||||
|
| **A1. 单一 WebAPI 程序**(推荐) | 一个 ASP.NET Core 进程同时提供:WebSocket 游戏协议 + RESTful API + 回合记录回放端点。与 v3 的 `DefaultRoundRecordSink`(POST) 设计意图吻合,与 Testing-v3 一脉相承 | ✅ 推荐:维护面小、天然支持记录外发与回放、Linux 部署友好 |
|
||||||
|
| A2. 控制台 + WebAPI 双程序 | 沿用 v2:FunGameServer(控制台) + FunGameWebAPI 双进程 | 保留 v2 习惯,但两套入口重复维护 |
|
||||||
|
| A3. 控制台单程序 | 只有 Socket/WS 游戏服务 | 无法直接对接 v3 的 POST 外发/回放生态 |
|
||||||
|
|
||||||
|
### 决策 B:客户端传输协议
|
||||||
|
| 选项 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| B1. **WebSocket + JSON**(推荐) | 与 v3 回放/记录 JSON 体系一致;浏览器/Web/桌面端都能连;`/ws` 单端点 |
|
||||||
|
| B2. WebSocket + 二进制协议 | 性能更高,但需要重新设计序列化(v3 已无 SocketObject) |
|
||||||
|
| B3. TCP Socket 二进制 | v2 传统;客户端(FunGame.Desktop 等)需同步改造 |
|
||||||
|
| B4. 纯 REST + 轮询/SSE | 放弃实时长连接,最简但体验差 |
|
||||||
|
|
||||||
|
> 注意:v3 已无 `SocketObject`/`SocketMessageType`,**协议要自己定**。建议最小集:
|
||||||
|
> 连接握手(协议版本/模组清单/版本校验)→ 登录/注册 → 大厅/房间/匹配 → 局内指令(决策点/技能/移动)→ 心跳/断线重连。数据格式直接复用 v3 实体 JSON(JsonService 转换器已就绪)。
|
||||||
|
|
||||||
|
### 决策 C:数据层
|
||||||
|
| 选项 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| C1. **EF Core + SQLite/MySQL**(推荐) | 现代、迁移方便;v2 的 users/rooms/inventory 等表结构可迁移为 EF 模型 |
|
||||||
|
| C2. 保留 v2 的 SQLHelper 思路自研 | 可从 v2 Server 移植 `MySQLHelper`/`SQLiteHelper` + SQLQueryExtension(注意该包依赖 v2 Core 命名空间,需改) |
|
||||||
|
| C3. Dapper/ADO 手写 | 轻量但开发量大 |
|
||||||
|
|
||||||
|
> v3 需要的持久化比 v2 简单:**对局记录(RoundRecord)可以用 JSON 归档**(Testing-v3 已有 rounds_archive.zip 模式),数据库只存账号/房间/经济等"服务器业务数据"。
|
||||||
|
|
||||||
|
### 决策 D:模组加载方式
|
||||||
|
| 选项 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| D1. **编译期进程内引用**(推荐,跟随 v3 设计) | 模组 = 代码类 + `EntityModuleConfig` 配置;`CharacterModule.Load()` 后 `Factory.GetGameModuleInstances<T>` 实例化。参考 Testing-v3 的 OshimaGameModules |
|
||||||
|
| D2. DLL 插件加载器自研 | 保留 v2 的 plugins/modules 热插拔体验,但 Core v3 不再提供任何加载器,需要完整自研(隔离上下文、依赖解析、热卸载) |
|
||||||
|
| D3. 混合 | 核心模组编译期引用,扩展模组走 DLL |
|
||||||
|
|
||||||
|
### 决策 E:回合记录外发(v3 特色能力,强烈建议纳入)
|
||||||
|
| 选项 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| E1. **自收自发**(推荐) | 服务器自身实现 `IRoundRecordSink`,把 `RoundRecord` 写入自己的存储(JSON 归档/数据库),并提供回放 REST 端点(参考 Testing-v3 的 ArchiveStore + /api/rounds 系列) |
|
||||||
|
| E2. 使用 `DefaultRoundRecordSink` | 直接 POST 到外部数据服务(如独立的回放服务器),Server 只当生产者 |
|
||||||
|
| E3. 两者结合 | 本地归档 + 转发远端(最完整,实现也最简单:自定义 sink 内包一个 DefaultRoundRecordSink) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 建议架构(以 A1 + B1 + C1 + D1 + E1 为例)
|
||||||
|
|
||||||
|
```
|
||||||
|
FunGame.Server-v3/ (解决方案:FunGame.Server-v3.slnx)
|
||||||
|
├── docs/ # 本文档目录
|
||||||
|
├── Server/ # ASP.NET Core Web API(宿主)
|
||||||
|
│ ├── Program.cs # 入口:模块加载 + 服务注册 + 管道
|
||||||
|
│ ├── Networking/ # 协议层(自研,替代 v2 的 Core 网络)
|
||||||
|
│ │ ├── WebSocketHandler.cs # /ws 长连接接入
|
||||||
|
│ │ ├── Protocol/ # 消息帧/信封、消息类型枚举(替代 SocketObject)
|
||||||
|
│ │ └── ClientSession.cs # 会话模型(替代 ServerModel<T>)
|
||||||
|
│ ├── Controllers/ # RESTful:账号/房间/商店/回放……
|
||||||
|
│ ├── Services/ # 业务层
|
||||||
|
│ │ ├── UserService.cs # 注册/登录/签到/找回密码(迁移 v2 逻辑)
|
||||||
|
│ │ ├── RoomService.cs # 房间/匹配/Elo(迁移 v2 逻辑)
|
||||||
|
│ │ ├── EconomyService.cs # 商店/市场/报价(迁移 v2 逻辑)
|
||||||
|
│ │ ├── GameHostService.cs # 对局宿主:GamingQueue 生命周期管理
|
||||||
|
│ │ └── MatchService.cs # 匹配队列
|
||||||
|
│ ├── Data/ # EF Core:DbContext + 迁移(users/rooms/inventory…)
|
||||||
|
│ ├── Records/ # 回合记录
|
||||||
|
│ │ ├── RoundRecordSink.cs # 实现 IRoundRecordSink → 归档 + 可选转发
|
||||||
|
│ │ ├── ArchiveStore.cs # 存档读写(参考 Testing-v3,可改数据库存储)
|
||||||
|
│ │ └── ReplayController.cs # /api/replay 系列回放端点
|
||||||
|
│ ├── Modules/ # 模组(编译期引用,如 OshimaGameModules)
|
||||||
|
│ │ ├── CharacterModule.cs / SkillModule.cs / ItemModule.cs
|
||||||
|
│ │ └── GameMapModule.cs # 地图(Framework.GameMap)
|
||||||
|
│ ├── Console/ # 管理控制台(ILogger + 指令解析,迁移 v2 ConsoleModel)
|
||||||
|
│ └── appsettings.json # JWT/CORS/数据库/SMTP/回放存储配置
|
||||||
|
├── FunGame.Core (项目引用) # C:\milimoe\FunGame.Core 或 NuGet
|
||||||
|
└── WebUI/ (可选) # 管理后台/回放台(React,参考 Testing-v3 webui)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 核心运行时流程(一局对局)
|
||||||
|
|
||||||
|
```
|
||||||
|
玩家进房/匹配成功
|
||||||
|
→ GameHostService 创建 GamingQueue(角色列表, map)
|
||||||
|
→ queue.RoundRecordSink = RoundRecordSink(本服务实现)
|
||||||
|
→ 局内:玩家决策点指令 → queue.ProcessTurn / GamingMessageHandler 等价物
|
||||||
|
└── GamingQueue 内部自动:写 RoundRecord → 调 Sink(即时存档/转发)
|
||||||
|
→ 游戏结束 → 结算(RankingEntry/CharacterStatistics)→ 归档 → 通知客户端
|
||||||
|
→ 回放:ReplayController 读取归档;BattleStatePredictor 支撑"任意回合状态还原"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. v3 Server 必须重建的基础设施(对照 v2 清单)
|
||||||
|
|
||||||
|
| # | 模块 | v2 位置 | v3 方案 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1 | 网络监听与 WebSocket 会话 | Core 提供 | ASP.NET Core `UseWebSockets` + 自研会话模型 |
|
||||||
|
| 2 | 消息协议(信封/序列化) | SocketObject | 自研(推荐 JSON + 类型标记,复用 v3 JsonService) |
|
||||||
|
| 3 | 数据库访问 | SQLHelper + SQLQueryExtension | EF Core(或移植 v2 SQLHelper) |
|
||||||
|
| 4 | 配置系统 | INIHelper(Core) | `Microsoft.Extensions.Configuration`(JSON/appsettings) |
|
||||||
|
| 5 | 日志 | ServerHelper/TXTHelper(Server + Core) | `ILogger` + Serilog 等 |
|
||||||
|
| 6 | 邮件 | MailSender(Core) | 自研 SMTP 封装或 MailKit |
|
||||||
|
| 7 | 认证 | JWT + APIBearer(v2 WebAPI 已有) | 迁移 v2 WebAPI 认证架构 |
|
||||||
|
| 8 | 任务调度 | TaskScheduler(Core) | `BackgroundService` / `System.Threading.Timer` |
|
||||||
|
| 9 | 插件体系 | ServerPluginLoader/WebAPIPluginLoader(Core) | 按决策 D:模块化替代或自研加载器 |
|
||||||
|
| 10 | 控制台指令 | 迁移 v2 ConsoleModel | 指令字典 + ILogger(保留 ban/kick/logout/show/reload) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 可从 v2 直接迁移的业务代码(高复用)
|
||||||
|
|
||||||
|
以下逻辑与 Core 运行时解耦程度高,**迁移成本低**(主要是改命名空间 + 换数据访问 + 换传输参数):
|
||||||
|
|
||||||
|
- ✅ `ConnectController` 握手逻辑(人数/黑名单/参数校验)→ 适配新协议
|
||||||
|
- ✅ `DataRequestController` 的业务方法:房间创建/进入/退出/房主移交/设置、准备、开始游戏流程、聊天
|
||||||
|
- ✅ 匹配算法 `MatchingRoom`(Elo 扩圈)
|
||||||
|
- ✅ `DataRequestService`:注册流程、登录流程(含 autokey、check-login key 思路)、找回密码
|
||||||
|
- ✅ 每日签到、游戏时长统计、重复登录踢下线
|
||||||
|
- ✅ 商店/市场/报价/物品使用全套经济逻辑(事务化)
|
||||||
|
- ✅ `ConsoleModel` 指令解析与常用指令
|
||||||
|
- ✅ WebAPI 的 JWT/CORS/认证处理器架构、`PayloadModel` 包装
|
||||||
|
|
||||||
|
**需要重写/放弃的 v2 部分**:
|
||||||
|
- 所有 `Milimoe.FunGame.Core.*` 网络/传输引用(协议层)
|
||||||
|
- SQLHelper 调用点(改为 EF/新数据层)
|
||||||
|
- 插件事件链(v3 无 ServerPlugin)——如果保留插件需求,事件点要么自建事件总线,要么砍掉
|
||||||
|
- GameModuleServer 机制(v3 无此基类)——对局宿主改为直接驱动 GamingQueue
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 建议开发路线(里程碑)
|
||||||
|
|
||||||
|
### M0:地基(0.5~1 周)
|
||||||
|
- [ ] Server-v3 解决方案骨架(slnx + WebAPI 项目 + 项目引用 v3 Core)
|
||||||
|
- [ ] appsettings 配置体系、ILogger、统一响应模型 `PayloadModel`(迁移)
|
||||||
|
- [ ] 模块加载骨架:CharacterModule/SkillModule/ItemModule/地图模块 + `Factory.GetGameModuleInstances`
|
||||||
|
- [ ] 用 Testing-v3 的 OshimaGameModules(或精简示例模组)跑通:**进程内 GamingQueue 一局模拟 → RoundRecord → 归档 → 回放端点**(这是 v3 的核心价值验证)
|
||||||
|
|
||||||
|
### M1:网络与账号(1~2 周)
|
||||||
|
- [ ] WebSocket `/ws` 会话层 + 自研消息协议(握手/心跳/分发)
|
||||||
|
- [ ] EF Core + SQLite:users/profiles/rooms 迁移脚本
|
||||||
|
- [ ] 注册(邮箱验证码可选)、登录(密码加密 + 登录 key/autokey)、JWT
|
||||||
|
- [ ] 管理控制台指令框架(kick/logout/show/ban/reload)
|
||||||
|
|
||||||
|
### M2:房间与匹配(1~2 周)
|
||||||
|
- [ ] 房间 CRUD/进入退出/房主移交/设置/准备/开始流程(迁移 v2)
|
||||||
|
- [ ] 匹配队列 + Elo 扩圈匹配(迁移)
|
||||||
|
- [ ] 对局启动:GameHostService 创建 GamingQueue、绑定 IRoundRecordSink、局内指令转发
|
||||||
|
|
||||||
|
### M3:局内体验与回放(1~2 周)
|
||||||
|
- [ ] 局内指令协议:决策点(攻击/技能/物品/移动)、广播(Actions 实时推送,可基于 sink 事件)
|
||||||
|
- [ ] 断线重连(对局内重连,参考 v2 ReconnectToGame 思路)
|
||||||
|
- [ ] 回放台:`/api/replay/*` + 可选 React webui(可直接复用 Testing-v3 webui 改造)
|
||||||
|
|
||||||
|
### M4:经济与扩展(1~2 周)
|
||||||
|
- [ ] 商店/市场/报价/签到迁移(EF 数据层)
|
||||||
|
- [ ] SMTP 找回密码、每日签到、游戏时长统计
|
||||||
|
- [ ] 排位统计(Rating 计算可参考 Testing-v3 的 `CalculateRating`)
|
||||||
|
|
||||||
|
### M5:加固与发布(持续)
|
||||||
|
- [ ] 并发与事务正确性、压力测试
|
||||||
|
- [ ] Linux 自包含发布脚本(参考 Testing-v3 publish-linux.sh)
|
||||||
|
- [ ] 单元测试:迁移 Testing-v3 的 Tests(EffectAutoRecordTest / RoundRecordSinkTest)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 开放问题(建议尽早确认)
|
||||||
|
|
||||||
|
1. **客户端是谁?** FunGame.Desktop(v2 客户端)是否同步升级协议?若保留 v2 客户端,Server-v3 需要兼容 v2 的 SocketObject 协议——那网络层改动会大很多。
|
||||||
|
2. **回放数据存哪?** JSON 归档(简单、Testing-v3 模式)vs 数据库(可查询/统计)vs 远端 POST(DefaultRoundRecordSink)。
|
||||||
|
3. **要不要账号系统?** 如果 v3 服务器定位为"对战/回放服务",可以砍掉注册/邮箱,仅保留昵称 + JWT 匿名身份(大幅缩短开发)。
|
||||||
|
4. **插件生态是否保留?** 如果 Oshima 社区依赖 v2 的 ServerPlugin/WebAPIPlugin 插件,需要自研加载器;否则用"模块 + 服务内扩展点"替代。
|
||||||
|
5. **核心业务与 Testing-v3 的关系**:Testing-v3 的对战模拟/回放功能是直接并入 Server-v3(作为测试与演示能力),还是独立保留?
|
||||||
|
6. **Core v3 还在迭代**(3.0.0-dev):建议以 ProjectReference 或本地 NuGet 引用 master,跟随提交更新,并关注 nuget 自动发布工作流(正式版发布后可切 NuGet)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 一句话总结
|
||||||
|
|
||||||
|
> **v2 是"Core 给的服务器",v3 是"自己搭的服务器 + Core 给的战斗/回放引擎"。**
|
||||||
|
> Server-v3 的核心价值 = v3 战斗引擎(GamingQueue)+ 回合记录/即时外发(IRoundRecordSink)+ 回放(BattleStatePredictor/ArchiveStore),叠加自研的网络/账号/房间/经济层;v2 的成熟业务代码可迁移复用,但底层基础设施(网络、数据库、配置、日志)需要在新项目里重建。
|
||||||
+309
@@ -0,0 +1,309 @@
|
|||||||
|
# Server-v3 架构设计(已定稿,基于用户 8 项决策)
|
||||||
|
|
||||||
|
> 状态:**定稿**。本文为 `FunGame.Server-v3` 的开发规格说明书,取代 `03-Server-v3-开发规划.md` 中的备选方案。
|
||||||
|
> 所有实现以本文为准;01/02 文档作为功能与 Core v3 能力参考。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0. 总体决策摘要
|
||||||
|
|
||||||
|
| # | 决策 | 结论 |
|
||||||
|
|---|---|---|
|
||||||
|
| 1 | 数据层 | **EF Core**,Provider 可切换:SQLite(默认/开发)与 MySQL(生产,Pomelo) |
|
||||||
|
| 2 | 管理入口 | **废弃控制台输入**,提供 **WebUI(React + Tailwind)** 服务器管理 |
|
||||||
|
| 3 | 启动方式 | **仅 WebSocket + WebAPI**(单一 ASP.NET Core 进程,同旧版 FunGameWebAPI 形态),移除 TCP Socket |
|
||||||
|
| 4 | 用户中心 | 重构为**细粒度权限角色模型**(RBAC + 权限点),**多端统一验证**(WebUI / WebAPI / WebSocket 共用同一 JWT 认证体系 + 刷新令牌 + 会话表) |
|
||||||
|
| 5 | 数据库/API | 数据表优化 + 追加新表;**每张数据表都有对应 CRUD REST 接口**(通用 CRUD 基类派生) |
|
||||||
|
| 6 | 加载项 | **始终热重载**(无普通加载模式);WebAPI 插件与服务器模组**合并为单一"服务器插件"**;角色/技能/物品模组仍是**独立加载项**,工厂注册保持模块化;DLL 热重载与实体 JSON 配置加载为**两条平行通道** |
|
||||||
|
| 7 | 负载模型 | **弃用 SocketObject**,全新设计负载模型(WebSocket 信封 + REST 响应包装) |
|
||||||
|
| 8 | 回合记录 | 支持 Core v3 的 **IRoundRecordSink 回合记录外发**(本地归档 + 可配置远程 POST) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 解决方案结构
|
||||||
|
|
||||||
|
```
|
||||||
|
FunGame.Server-v3/
|
||||||
|
├── docs/ # 文档(01~04)
|
||||||
|
├── FunGame.Server-v3.slnx # 解决方案
|
||||||
|
├── src/
|
||||||
|
│ ├── FunGame.Server.Contracts/ # 共享契约:负载模型、插件接口、常量、事件参数
|
||||||
|
│ ├── FunGame.Server.Infrastructure/ # EF Core 数据层:实体、DbContext、迁移、种子数据
|
||||||
|
│ ├── FunGame.Server.PluginHost/ # 始终热重载的插件/模组加载系统
|
||||||
|
│ └── FunGame.Server.Host/ # 宿主:WebAPI + WebSocket + 认证 + 业务服务 + 对局宿主
|
||||||
|
├── plugins/ # 服务器插件示例(编译输出 → Host/plugins/)
|
||||||
|
├── modules/ # 角色/技能/物品模组示例(编译输出 → Host/modules/)
|
||||||
|
└── webui/ # React + Vite + Tailwind 管理台
|
||||||
|
```
|
||||||
|
|
||||||
|
**依赖方向(严格单向)**:
|
||||||
|
|
||||||
|
```
|
||||||
|
FunGame.Core (v3) ← Contracts ← Infrastructure ← PluginHost ← Host
|
||||||
|
↑ ↑
|
||||||
|
(共享程序集:插件 ALC 回退到默认上下文解析)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 数据层(决策 1/5)
|
||||||
|
|
||||||
|
### 2.1 Provider 切换
|
||||||
|
|
||||||
|
`appsettings.json`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"Database": {
|
||||||
|
"Provider": "Sqlite", // Sqlite | MySql
|
||||||
|
"ConnectionStrings": {
|
||||||
|
"Sqlite": "Data Source=Data/fungame-server.db",
|
||||||
|
"MySql": "Server=localhost;Port=3306;Database=fungame;User=root;Password=***;"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `AppDbContextFactory`(设计时)与 `AddDbContext`(运行时)都按 `Provider` 注册对应 Provider:
|
||||||
|
- SQLite → `Microsoft.EntityFrameworkCore.Sqlite`
|
||||||
|
- MySQL → `Pomelo.EntityFrameworkCore.MySql`
|
||||||
|
- 迁移目录按 Provider 拆分:`Migrations/Sqlite/` 与 `Migrations/MySql/`(`--output-dir` 指定)
|
||||||
|
- 首次启动自动 `Migrate()` + 种子数据(系统角色、权限点、初始管理员)
|
||||||
|
|
||||||
|
### 2.2 数据表规划(v2 表优化 + 新增)
|
||||||
|
|
||||||
|
**认证与用户中心(新增/重构,决策 4)**
|
||||||
|
|
||||||
|
| 表 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `Users` | 用户(v2 users 重构:密码散列 PBKDF2、邮箱验证、状态、昵称、头像、最后登录 IP/时间) |
|
||||||
|
| `UserProfiles` | 用户资料(v2 user_profiles 保留:个性签名、展示角色、偏好设置等) |
|
||||||
|
| `Roles` | 角色(Code/Name/是否系统内置) |
|
||||||
|
| `Permissions` | 权限点(Code/Name/分组,如 `users.read`、`plugins.reload`、`games.forceend`) |
|
||||||
|
| `UserRoles` | 用户-角色 多对多 |
|
||||||
|
| `RolePermissions` | 角色-权限 多对多 |
|
||||||
|
| `RefreshTokens` | 刷新令牌(散列存储、设备标识、过期/吊销;多端统一验证的基础) |
|
||||||
|
| `UserSessions` | 在线会话(每端一条:WebUI/WebAPI/WebSocket,登录挤下线/多端管理) |
|
||||||
|
| `LoginLogs` | 登录日志(v2 user_logs 细化:成功/失败、IP、UA、设备) |
|
||||||
|
| `ApiTokens` | API 访问令牌(v2 api_tokens 保留,供外部服务接入) |
|
||||||
|
|
||||||
|
**游戏业务(v2 表迁移/优化)**
|
||||||
|
|
||||||
|
| 表 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `Rooms` | 房间(v2 rooms 保留,去掉 SQL 运行时依赖) |
|
||||||
|
| `UserCharacters` | 玩家角色库(v2 user_characters;实体数据以 Core JSON 存储 + 关键字段列冗余便于查询) |
|
||||||
|
| `UserItems` | 玩家物品(v2 user_items) |
|
||||||
|
| `Inventories` | 库存(v2 inventories:货币/材料) |
|
||||||
|
| `Stores` / `Goods` / `GoodsPrices` / `StoreGoods` | 商店体系(v2 保留) |
|
||||||
|
| `MarketItems` | 市场寄售(v2 保留) |
|
||||||
|
| `Offers` / `OfferItems` | 交易报价(v2 保留) |
|
||||||
|
| `VerifyCodes` | 验证码(v2 reg_verify_codes + forget_verify_codes 合并,加 Purpose 字段) |
|
||||||
|
| `UserSignIns` | 签到(v2 保留) |
|
||||||
|
|
||||||
|
**对局记录与运维(新增,决策 8/2)**
|
||||||
|
|
||||||
|
| 表 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `GameRecords` | 对局记录索引(GamingQueue Guid、模式、起止时间、回合数、归档路径、胜者) |
|
||||||
|
| `RoundRecords` | 回合记录归档(可 JSON 列或归档文件路径;支持按回合查询回放) |
|
||||||
|
| `ServerLogs` | 服务器日志(供 WebUI 查看;结构化:级别/来源/分类/消息) |
|
||||||
|
| `SystemConfigs` | 系统配置键值(v2 configs 保留:动态公告、开关等) |
|
||||||
|
|
||||||
|
> 所有 `*Query` 静态 SQL 类(SQLQueryExtension)**废弃**,改为 EF LINQ。
|
||||||
|
|
||||||
|
### 2.3 CRUD API 约定(每表一套,决策 5)
|
||||||
|
|
||||||
|
通用基类 `CrudControllerBase<TEntity, TKey>`:
|
||||||
|
|
||||||
|
```
|
||||||
|
GET /api/{resource} 列表(分页 page/pageSize、排序 sort、过滤 filter=field:op:value)
|
||||||
|
GET /api/{resource}/{id} 详情
|
||||||
|
POST /api/{resource} 创建([Permission("{resource}.create")])
|
||||||
|
PUT /api/{resource}/{id} 整体更新
|
||||||
|
PATCH /api/{resource}/{id} 部分更新
|
||||||
|
DELETE /api/{resource}/{id} 删除
|
||||||
|
```
|
||||||
|
|
||||||
|
- 派生控制器:`UsersController`、`RolesController`、`PermissionsController`、`ApiTokensController`、`RoomsController`、`StoresController`、`GoodsController`、`MarketItemsController`、`OffersController`、`GameRecordsController`、`ServerLogsController`、`SystemConfigsController`……
|
||||||
|
- 关系表(UserRoles/RolePermissions)随主资源提供子路由:`GET/PUT /api/users/{id}/roles`、`GET/PUT /api/roles/{id}/permissions`
|
||||||
|
- 统一响应包装 `ApiResponse<T>`;权限用 `[Permission]` 授权过滤器校验
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 认证:多端统一验证(决策 4)
|
||||||
|
|
||||||
|
**一条认证体系,三端共用**:
|
||||||
|
|
||||||
|
```
|
||||||
|
登录 → POST /api/auth/login (用户名/密码 或 刷新令牌) → { accessToken, refreshToken }
|
||||||
|
WebUI : Axios 拦截器 → Authorization: Bearer {accessToken};401 → /api/auth/refresh → 重试;失败 → 登录页
|
||||||
|
WebAPI : 同上(外部服务可用 ApiTokens 走 X-API-Token)
|
||||||
|
WebSocket : /ws?access_token=… 握手时校验 JWT(过期可先 refresh 再连)
|
||||||
|
```
|
||||||
|
|
||||||
|
- JWT:AccessToken 短时效(默认 30 分钟),RefreshToken 长时效(默认 14 天,可配置),**散列入库**,支持撤销/设备维度("踢出该设备")
|
||||||
|
- `UserSessions`:每端登录产生会话;同用户可多端同时在线,重复登录可配置"同端互踢"
|
||||||
|
- 密码:`PasswordHasher<T>`(PBKDF2);v2 的每用户密钥加密方案**废弃**(简化 + 标准库)
|
||||||
|
- 权限模型:`Permission` 权限点字符串(`users.read` / `plugins.reload` …)→ 角色聚合 → JWT Claim `perm` 数组;`PermissionAttribute("code")` 服务端校验
|
||||||
|
- 首次启动种子:系统角色(Admin/Moderator/User)、全部权限点、初始管理员(用户名/密码由 appsettings `Bootstrap:Admin` 提供,仅首次生效)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. WebSocket 与负载模型(决策 3/7)
|
||||||
|
|
||||||
|
### 4.1 接入
|
||||||
|
|
||||||
|
- 端点:`GET /ws?access_token={jwt}`
|
||||||
|
- ASP.NET Core 原生 `UseWebSockets`;连接对象 `ClientSession`(会话模型,替代 v2 `ServerModel<T>`)
|
||||||
|
|
||||||
|
### 4.2 负载信封(替代 SocketObject)
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
// 客户端 → 服务器(请求)
|
||||||
|
{
|
||||||
|
"t": "room.create", // 消息类型(点分字符串,替代 SocketMessageType 枚举)
|
||||||
|
"i": 1, // 请求序号(客户端生成,用于响应关联)
|
||||||
|
"d": { ... } // 负载(Dictionary<string, object>,实体用 Core JsonService 序列化)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 服务器 → 客户端(响应 / 广播)
|
||||||
|
{
|
||||||
|
"t": "room.created", // 或原样回显请求类型 + ".ok"/".error"
|
||||||
|
"i": 1,
|
||||||
|
"ok": true,
|
||||||
|
"error": null, // { code, message }
|
||||||
|
"d": { ... },
|
||||||
|
"ts": 1750000000000
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- 消息类型注册表 `MessageTypes`(Contracts 常量类),覆盖:`auth.*`、`room.*`、`match.*`、`chat.*`、`gaming.*`(局内:`gaming.ready`、`gaming.action`、`gaming.sync`…)、`system.*`(公告/系统消息/踢人)
|
||||||
|
- 局内数据全部复用 **Core v3 实体 JSON**(JsonService.GeneralOptions 的转换器已支持 RoundRecord/ActionRecord/Character 等)
|
||||||
|
- `MessageDispatcher`:类型字符串 → 处理器注册表(业务服务 + 插件处理器合并)
|
||||||
|
- 心跳:`{ "t": "system.ping" }` ↔ `system.pong`;超时判定断线,断线重连(对局内重连保留 v2 思路,凭 `gameId` 重挂)
|
||||||
|
|
||||||
|
### 4.3 REST 响应包装(与 WS 对齐)
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
{ "ok": true, "code": 0, "message": null, "data": { ... }, "timestamp": "..." }
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 加载项系统(决策 6)—— 始终热重载
|
||||||
|
|
||||||
|
### 5.1 三类加载项(DLL 热重载通道)
|
||||||
|
|
||||||
|
| 类型 | 目录 | 接口 | 说明 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **服务器插件**(合并 v2 WebAPIPlugin + GameModuleServer) | `plugins/` | `IServerPlugin` | 生命周期 + REST 端点注册(MapGroup)+ WS 消息处理器 + 对局模式(GameModule) |
|
||||||
|
| 角色模组 | `modules/characters/` | `ICharacterModule` | 提供角色实体集合,`Load()` 时通过工厂注册 |
|
||||||
|
| 技能模组 | `modules/skills/` | `ISkillModule` | 同上(技能) |
|
||||||
|
| 物品模组 | `modules/items/` | `IItemModule` | 同上(物品) |
|
||||||
|
|
||||||
|
> 实体模组也可只提供 `EntityModuleConfig` JSON 文件(平行通道,见 5.3),DLL 与 JSON 两者可共存。
|
||||||
|
|
||||||
|
### 5.2 DLL 热重载机制(始终开启,无普通加载模式)
|
||||||
|
|
||||||
|
- 每个加载项一个**可回收 AssemblyLoadContext**(`PluginLoadContext`,`isCollectible: true`),按 `Name + Guid` 命名
|
||||||
|
- `PluginManager`:
|
||||||
|
- `LoadAll()` / `Load(string name)` / `Unload(string name)` / `Reload(string name)` / `ReloadAll()`
|
||||||
|
- `Plugins` / `Modules` 清单(名称、版本、状态、加载时间)
|
||||||
|
- 文件监视(`FileSystemWatcher`,去抖合并变更)→ 自动热重载;也可 `POST /api/admin/plugins/{name}/reload` 手动触发
|
||||||
|
- 卸载顺序:`OnUnload()` → 摘除端点/处理器 → `ALC.Unload()` → 弱引用等待 GC(必要时 `GC.Collect`)
|
||||||
|
- 共享程序集(FunGame.Core、Contracts、Infrastructure、PluginHost)**不随插件加载**:`PluginLoadContext.Load` 优先返回默认上下文已加载程序集;插件自有依赖从插件目录解析
|
||||||
|
- 插件端点用 **Minimal API `MapGroup`**(`plugin.ConfigureEndpoints(app)`),可热卸载(v2 的 Controller 程序集注册方式因无法热移除而弃用)
|
||||||
|
- 对局中途插件被卸载:`PluginManager` 拒绝卸载"仍被活跃对局引用"的插件(引用计数)
|
||||||
|
|
||||||
|
### 5.3 实体 JSON 通道(与 5.2 平行)
|
||||||
|
|
||||||
|
- `EntityModuleConfig<T>` 生成/读取 JSON 配置;`Factory.GetGameModuleInstances<T>(module, file)` 实例化实体
|
||||||
|
- WebUI 提供"实体模组管理"页:查看/编辑/重新加载 JSON 配置(不重启进程改游戏内容)
|
||||||
|
|
||||||
|
### 5.4 服务器插件接口(Contracts)
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
public interface IServerPlugin : IPluginBase
|
||||||
|
{
|
||||||
|
// 注册 HTTP 端点(挂载 /plugin/{name}/{path},注册表 + 单一路由分发,可热移除)
|
||||||
|
// 与 WebSocket 消息处理器(随插件热卸载自动注销)
|
||||||
|
void ConfigureEndpoints(IPluginHttpHandlerRegistry http, IMessageHandlerRegistry messages);
|
||||||
|
// 对局模式逻辑(可选):局内消息转发到模式插件
|
||||||
|
Task<Dictionary<string, object>?> HandleGamingMessage(IGameSession session, string type, Dictionary<string, object> data);
|
||||||
|
void OnLoad(IServiceProvider services); // 继承自 IPluginBase
|
||||||
|
void OnUnload(); // 继承自 IPluginBase
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
> 注:插件 HTTP 端点采用 **注册表 + 单一路由分发**(`/plugin/{name}/{path}`)而非动态注册 Controller/MapGroup——保证端点可随 ALC 热添加/热移除。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 对局宿主与回合记录外发(决策 8)
|
||||||
|
|
||||||
|
### 6.1 对局宿主 `GameHostService`
|
||||||
|
|
||||||
|
- 房间/匹配就绪 → 创建 `GamingQueue(characters, map)` → 绑定 `RoundRecordSink`
|
||||||
|
- 局内循环:行动顺序(`NextCharacter()`)→ 等待该角色决策(WS `gaming.action`)→ `ProcessTurn(character)`(或插件模式接管整回合逻辑)
|
||||||
|
- 维护 `gameId → GameSession`(队列、玩家会话映射、状态);断线重连、强制结束、观战
|
||||||
|
- 游戏结束:结算 `GameResult`/`CharacterStatistics` → 写 `GameRecords` → 通知各端
|
||||||
|
|
||||||
|
### 6.2 回合记录外发 `GameRoundRecordSink : IRoundRecordSink`
|
||||||
|
|
||||||
|
- 实现 Core v3 的 9 个外发事件(Action/Round/CheckpointRound/CharacterStatistics/Characters/Teams/QueueData/EliminatedCharacters/EliminatedTeams)
|
||||||
|
- **本地归档**:每局一个 `records/{gameId}.zip`(沿用 Testing-v3 的 rounds_data.json 格式)或按配置写入 `RoundRecords` 表
|
||||||
|
- **远程转发**(可选):配置 `RoundRecordSink:PostUrl` + `Secret` 时,内部包装 `DefaultRoundRecordSink` 转发(生产者/消费者都可)
|
||||||
|
- 回放 REST:`GET /api/games/{id}/rounds`、`GET /api/games/{id}/rounds/{n}`、`GET /api/games/{id}/statistics`(参考 Testing-v3 端点设计),配合 `BattleStatePredictor` 提供任意回合状态
|
||||||
|
- WS 实时推送:订阅 sink 事件 → 广播 `gaming.round` / `gaming.action`(观战/直播能力)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. WebUI 管理台(决策 2)
|
||||||
|
|
||||||
|
技术栈:**React 18 + Vite + TypeScript + Tailwind CSS v4**(与 Testing-v3 webui 同栈,可复用组件风格)。
|
||||||
|
|
||||||
|
| 页面 | 功能 |
|
||||||
|
|---|---|
|
||||||
|
| 登录 | 统一 JWT 登录(与 WebAPI/WS 同一认证) |
|
||||||
|
| 仪表盘 | 在线玩家/连接数、进行中对局、服务器状态、近期日志 |
|
||||||
|
| 玩家管理 | Users CRUD、资料、角色分配、会话管理(踢下线)、登录日志 |
|
||||||
|
| 权限管理 | Roles / Permissions CRUD、角色-权限配置 |
|
||||||
|
| 房间/对局 | 房间列表、对局监控、强制结束、观战入口 |
|
||||||
|
| 插件/模组管理 | 插件清单、热重载/卸载、实体模组 JSON 编辑与重载 |
|
||||||
|
| 数据管理 | 各业务表 CRUD 通用表格页(商店/市场/物品/系统配置…) |
|
||||||
|
| 回放中心 | 对局记录、回合回放(复用 Testing-v3 回放面板) |
|
||||||
|
| 日志 | ServerLogs 检索、级别过滤、实时尾巴 |
|
||||||
|
|
||||||
|
- 开发:`vite dev`(5173)代理 `/api`、`/ws` → 服务器(默认 5000)
|
||||||
|
- 生产:`npm run build` → `webui/dist` 由 Host 静态托管(同 Testing-v3 模式)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 目录与命名约定
|
||||||
|
|
||||||
|
- 根命名空间:`FunGame.Server.Contracts` / `FunGame.Server.Infrastructure` / `FunGame.Server.PluginHost` / `FunGame.Server.Host`;模组/插件可自定义(如 `FunGame.Server.Plugins.OfficialStandard`)
|
||||||
|
- REST 路由:`/api/{resource}`;管理端 `[Permission]` 保护
|
||||||
|
- WS 消息类型:小写点分(`room.create`、`gaming.action`)
|
||||||
|
- 配置:`appsettings.json`(分层:Database/Jwt/Auth/Server/RoundRecordSink/Bootstrap/Cors/Plugins)
|
||||||
|
- 日志:`ILogger` + ServerLogs 数据库通道(Serilog 可选接入)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 里程碑(对应实施顺序)
|
||||||
|
|
||||||
|
- **M0 骨架**:解决方案 + 4 个类库/宿主 + Core 引用 + 编译通过 ✅
|
||||||
|
- **M1 数据层**:实体、DbContext、双 Provider、迁移、种子数据、CRUD 基类 + 首批控制器 ✅
|
||||||
|
- **M2 认证**:JWT + 刷新令牌 + 会话 + 权限过滤 + WS 握手认证 ✅
|
||||||
|
- **M3 插件系统**:PluginHost 热重载 + 示例插件/模组 + 管理端点 ✅(影子加载 + _staging 热替换 + 文件监视)
|
||||||
|
- **M4 WebSocket**:ClientSession、信封、消息分发、心跳/断线 ✅
|
||||||
|
- **M5 业务**:房间/匹配/聊天/对局宿主 + 回合记录归档与外发 + 回放端点 ✅(AI 对局循环为演示实现,玩家局内决策接入待办)
|
||||||
|
- **M6 WebUI**:管理台全页面(登录/仪表盘/用户/插件/对局/回放/日志)✅
|
||||||
|
- **M7 加固发布**:测试、Linux 发布、文档 ⏳(进行中)
|
||||||
|
|
||||||
|
### M7 剩余事项
|
||||||
|
|
||||||
|
- 玩家局内决策接入(`gaming.action` 驱动 GamingQueue,当前为 AI 自动循环)
|
||||||
|
- 更完整的匹配队列(Elo 扩圈,当前为快速匹配演示)
|
||||||
|
- 单元/集成测试项目(参考 Testing-v3 的 Tests)
|
||||||
|
- Linux 自包含发布脚本(参考 Testing-v3 publish-linux.sh)
|
||||||
|
- WebUI 权限/角色管理页、系统配置页
|
||||||
|
- MySQL Provider 的迁移与部署验证
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
# Server-v3 文档索引
|
||||||
|
|
||||||
|
FunGame.Server-v3 规划与设计文档(基于 FunGame.Core v3 / master 分支)。
|
||||||
|
|
||||||
|
| 文档 | 内容 | 状态 |
|
||||||
|
|---|---|---|
|
||||||
|
| [01-v2-功能总结.md](01-v2-功能总结.md) | v2 FunGame.Server 全部功能梳理 | 参考 |
|
||||||
|
| [02-v3-Core-变更分析.md](02-v3-Core-变更分析.md) | v3 FunGame.Core 相对 v2 的变更与边界 | 参考 |
|
||||||
|
| [03-Server-v3-开发规划.md](03-Server-v3-开发规划.md) | v3 开发决策与备选方案(早期) | 已被 04 取代 |
|
||||||
|
| [04-架构设计.md](04-架构设计.md) | **v3 架构定稿**:数据层/认证/负载模型/插件系统/对局与回放/WebUI 规格 | **开发依据** |
|
||||||
|
|
||||||
|
实施顺序见 04 文档第 9 节里程碑(M0~M7)。
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"isRoot": true,
|
||||||
|
"tools": {
|
||||||
|
"dotnet-ef": {
|
||||||
|
"version": "10.0.11",
|
||||||
|
"commands": [
|
||||||
|
"dotnet-ef"
|
||||||
|
],
|
||||||
|
"rollForward": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
using FunGame.Core.Entity;
|
||||||
|
using FunGame.Core.Library.Constant;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Modules.Example;
|
||||||
|
|
||||||
|
/// <summary>示例角色:战士(力量型近战)</summary>
|
||||||
|
public class ExampleWarrior : Character
|
||||||
|
{
|
||||||
|
public ExampleWarrior() : base()
|
||||||
|
{
|
||||||
|
Id = 90001;
|
||||||
|
Name = "Example";
|
||||||
|
FirstName = "Warrior";
|
||||||
|
NickName = "示例战士";
|
||||||
|
PrimaryAttribute = PrimaryAttribute.STR;
|
||||||
|
InitialATK = 30;
|
||||||
|
InitialHP = 100;
|
||||||
|
InitialMP = 10;
|
||||||
|
InitialSTR = 32;
|
||||||
|
STRGrowth = 3;
|
||||||
|
InitialAGI = 0;
|
||||||
|
AGIGrowth = 0;
|
||||||
|
InitialINT = 0;
|
||||||
|
INTGrowth = 0;
|
||||||
|
InitialSPD = 300;
|
||||||
|
InitialHR = 4;
|
||||||
|
InitialMR = 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>示例角色:法师(智力型远程)</summary>
|
||||||
|
public class ExampleMage : Character
|
||||||
|
{
|
||||||
|
public ExampleMage() : base()
|
||||||
|
{
|
||||||
|
Id = 90002;
|
||||||
|
Name = "Example";
|
||||||
|
FirstName = "Mage";
|
||||||
|
NickName = "示例法师";
|
||||||
|
PrimaryAttribute = PrimaryAttribute.INT;
|
||||||
|
InitialATK = 18;
|
||||||
|
InitialHP = 75;
|
||||||
|
InitialMP = 50;
|
||||||
|
InitialSTR = 0;
|
||||||
|
STRGrowth = 0;
|
||||||
|
InitialAGI = 0;
|
||||||
|
AGIGrowth = 0;
|
||||||
|
InitialINT = 35;
|
||||||
|
INTGrowth = 3;
|
||||||
|
InitialSPD = 280;
|
||||||
|
InitialHR = 3;
|
||||||
|
InitialMR = 5;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
using FunGame.Core.Api;
|
||||||
|
using FunGame.Core.Entity;
|
||||||
|
using FunGame.Server.Contracts.Plugins;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Modules.Example;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 示例角色模组:注册工厂(工厂注册保持模块化)+ 提供实体集合<para/>
|
||||||
|
/// 通过工厂注册后,实体 JSON 配置(EntityModuleConfig)通道也能实例化本模组的角色
|
||||||
|
/// </summary>
|
||||||
|
public class ExampleCharacterModule : ICharacterModule
|
||||||
|
{
|
||||||
|
public string Name => "example.characters";
|
||||||
|
public string Version => "1.0.0";
|
||||||
|
public string Author => "FunGame.Server";
|
||||||
|
public string Description => "示例角色模组:战士 / 法师";
|
||||||
|
|
||||||
|
private IReadOnlyDictionary<string, Character>? _entities;
|
||||||
|
|
||||||
|
public IReadOnlyDictionary<string, Character> Entities
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
_entities ??= new Dictionary<string, Character>
|
||||||
|
{
|
||||||
|
["example_warrior"] = new ExampleWarrior(),
|
||||||
|
["example_mage"] = new ExampleMage()
|
||||||
|
};
|
||||||
|
return _entities;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnLoad(IServiceProvider services)
|
||||||
|
{
|
||||||
|
// 工厂注册:id -> 构造函数,供 Factory.GetInstance / GetGameModuleInstances 使用
|
||||||
|
Factory.OpenFactory.RegisterFactory<Character>((id, name, args) => id switch
|
||||||
|
{
|
||||||
|
90001 => new ExampleWarrior(),
|
||||||
|
90002 => new ExampleMage(),
|
||||||
|
_ => null
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnUnload()
|
||||||
|
{
|
||||||
|
// 从工厂注销(保持工厂可被热重载模组替换)
|
||||||
|
Factory.OpenFactory.UnRegisterFactory<Character>((id, name, args) => id switch
|
||||||
|
{
|
||||||
|
90001 => new ExampleWarrior(),
|
||||||
|
90002 => new ExampleMage(),
|
||||||
|
_ => null
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>示例技能模组</summary>
|
||||||
|
public class ExampleSkillModule : ISkillModule
|
||||||
|
{
|
||||||
|
public string Name => "example.skills";
|
||||||
|
public string Version => "1.0.0";
|
||||||
|
public string Author => "FunGame.Server";
|
||||||
|
public string Description => "示例技能模组:示例打击";
|
||||||
|
|
||||||
|
private IReadOnlyDictionary<string, Skill>? _entities;
|
||||||
|
|
||||||
|
public IReadOnlyDictionary<string, Skill> Entities
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
_entities ??= new Dictionary<string, Skill>
|
||||||
|
{
|
||||||
|
["example_strike"] = new ExampleStrike()
|
||||||
|
};
|
||||||
|
return _entities;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnLoad(IServiceProvider services)
|
||||||
|
{
|
||||||
|
Factory.OpenFactory.RegisterFactory<Skill>((id, name, args) => id switch
|
||||||
|
{
|
||||||
|
91001 => new ExampleStrike(),
|
||||||
|
_ => null
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnUnload()
|
||||||
|
{
|
||||||
|
Factory.OpenFactory.UnRegisterFactory<Skill>((id, name, args) => id switch
|
||||||
|
{
|
||||||
|
91001 => new ExampleStrike(),
|
||||||
|
_ => null
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>示例物品模组</summary>
|
||||||
|
public class ExampleItemModule : IItemModule
|
||||||
|
{
|
||||||
|
public string Name => "example.items";
|
||||||
|
public string Version => "1.0.0";
|
||||||
|
public string Author => "FunGame.Server";
|
||||||
|
public string Description => "示例物品模组:回复药剂";
|
||||||
|
|
||||||
|
private IReadOnlyDictionary<string, Item>? _entities;
|
||||||
|
|
||||||
|
public IReadOnlyDictionary<string, Item> Entities
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
_entities ??= new Dictionary<string, Item>
|
||||||
|
{
|
||||||
|
["example_potion"] = new ExamplePotion()
|
||||||
|
};
|
||||||
|
return _entities;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnLoad(IServiceProvider services)
|
||||||
|
{
|
||||||
|
Factory.OpenFactory.RegisterFactory<Item>((id, name, args) => id switch
|
||||||
|
{
|
||||||
|
92001 => new ExamplePotion(),
|
||||||
|
_ => null
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnUnload()
|
||||||
|
{
|
||||||
|
Factory.OpenFactory.UnRegisterFactory<Item>((id, name, args) => id switch
|
||||||
|
{
|
||||||
|
92001 => new ExamplePotion(),
|
||||||
|
_ => null
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>FunGame.Server.Modules.Example</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\..\src\FunGame.Server.Contracts\FunGame.Server.Contracts.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<!-- 构建后复制到宿主的三个实体模组暂存区(热重载:由宿主原子替换到正式目录) -->
|
||||||
|
<Target Name="CopyModulesToHost" AfterTargets="Build">
|
||||||
|
<ItemGroup>
|
||||||
|
<ModuleFiles Include="$(TargetDir)$(AssemblyName).dll;$(TargetDir)$(AssemblyName).pdb" />
|
||||||
|
</ItemGroup>
|
||||||
|
<MakeDir Directories="$(MSBuildThisFileDirectory)..\..\src\FunGame.Server.Host\modules\characters\_staging;$(MSBuildThisFileDirectory)..\..\src\FunGame.Server.Host\modules\skills\_staging;$(MSBuildThisFileDirectory)..\..\src\FunGame.Server.Host\modules\items\_staging" />
|
||||||
|
<Copy SourceFiles="@(ModuleFiles)" DestinationFolder="$(MSBuildThisFileDirectory)..\..\src\FunGame.Server.Host\modules\characters\_staging\" SkipUnchangedFiles="false" />
|
||||||
|
<Copy SourceFiles="@(ModuleFiles)" DestinationFolder="$(MSBuildThisFileDirectory)..\..\src\FunGame.Server.Host\modules\skills\_staging\" SkipUnchangedFiles="false" />
|
||||||
|
<Copy SourceFiles="@(ModuleFiles)" DestinationFolder="$(MSBuildThisFileDirectory)..\..\src\FunGame.Server.Host\modules\items\_staging\" SkipUnchangedFiles="false" />
|
||||||
|
<Message Text="实体模组已复制到 Host/modules/*/_staging:$(AssemblyName).dll(等待宿主热替换)" Importance="high" />
|
||||||
|
</Target>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
using FunGame.Core.Entity;
|
||||||
|
using FunGame.Core.Library.Constant;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Modules.Example;
|
||||||
|
|
||||||
|
/// <summary>示例物品:回复药剂(使用后回复生命值)</summary>
|
||||||
|
public class ExamplePotion : Item
|
||||||
|
{
|
||||||
|
public ExamplePotion() : base(ItemType.Consumable)
|
||||||
|
{
|
||||||
|
Id = 92001;
|
||||||
|
Name = "示例回复药剂";
|
||||||
|
QualityType = QualityType.Blue;
|
||||||
|
RemainUseTimes = 1;
|
||||||
|
IsSellable = true;
|
||||||
|
IsTradable = true;
|
||||||
|
Price = 50;
|
||||||
|
Description = "使用后立即回复 100 点生命值。";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
using FunGame.Core.Entity;
|
||||||
|
using FunGame.Core.Library.Constant;
|
||||||
|
using FunGame.Core.Model.EffectContext;
|
||||||
|
using FunGame.Core.Model.Framework;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Modules.Example;
|
||||||
|
|
||||||
|
/// <summary>示例技能:强力打击(物理伤害 + 小幅度生命回复)</summary>
|
||||||
|
public class ExampleStrike : Skill
|
||||||
|
{
|
||||||
|
public override long Id => 91001;
|
||||||
|
public override string Name => "示例打击";
|
||||||
|
public override string Description => Effects.Count > 0 ? Effects.First().Description : "";
|
||||||
|
public override double EPCost => 40;
|
||||||
|
public override double CD => 15;
|
||||||
|
public override double HardnessTime { get; set; } = 8;
|
||||||
|
public override int CanSelectTargetRange => 1;
|
||||||
|
|
||||||
|
public ExampleStrike(Character? character = null) : base(SkillType.Skill, character)
|
||||||
|
{
|
||||||
|
Effects.Add(new ExampleDamage(this, 90, 30, DamageType.Physical));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>示例特效:基于攻击力的物理伤害</summary>
|
||||||
|
public class ExampleDamage : Effect
|
||||||
|
{
|
||||||
|
public override long Id => Skill.Id;
|
||||||
|
public override string Name => Skill.Name;
|
||||||
|
public override string Description => $"对目标造成 {Damage:0.##} 点{CharacterSet.GetDamageTypeName(DamageType)}伤害。";
|
||||||
|
|
||||||
|
private double Damage => Skill.Level > 0 ? 基础伤害 + 等级成长 * (Skill.Level - 1) : 基础伤害;
|
||||||
|
private double 基础伤害 { get; set; } = 90;
|
||||||
|
private double 等级成长 { get; set; } = 30;
|
||||||
|
private DamageType DamageType { get; set; } = DamageType.Physical;
|
||||||
|
|
||||||
|
public ExampleDamage(Skill skill, double 基础伤害, double 等级成长, DamageType damageType) : base(skill)
|
||||||
|
{
|
||||||
|
GamingQueue = skill.GamingQueue;
|
||||||
|
this.基础伤害 = 基础伤害;
|
||||||
|
this.等级成长 = 等级成长;
|
||||||
|
DamageType = damageType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void OnSkillCasted(SkillCastContext ctx)
|
||||||
|
{
|
||||||
|
Character? caster = ctx.Actor;
|
||||||
|
foreach (Character enemy in ctx.Targets)
|
||||||
|
{
|
||||||
|
if (caster != null)
|
||||||
|
{
|
||||||
|
DamageToEnemy(caster, enemy, DamageType, MagicType.None, Damage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>FunGame.Server.Modules.Melee</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\..\src\FunGame.Server.Contracts\FunGame.Server.Contracts.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<!-- 构建后复制到宿主的游戏模式模组暂存区(热重载:由宿主原子替换到正式目录 modules/games) -->
|
||||||
|
<Target Name="CopyModulesToHost" AfterTargets="Build">
|
||||||
|
<ItemGroup>
|
||||||
|
<ModuleFiles Include="$(TargetDir)$(AssemblyName).dll;$(TargetDir)$(AssemblyName).pdb" />
|
||||||
|
</ItemGroup>
|
||||||
|
<MakeDir Directories="$(MSBuildThisFileDirectory)..\..\src\FunGame.Server.Host\modules\games\_staging" />
|
||||||
|
<Copy SourceFiles="@(ModuleFiles)" DestinationFolder="$(MSBuildThisFileDirectory)..\..\src\FunGame.Server.Host\modules\games\_staging\" SkipUnchangedFiles="false" />
|
||||||
|
<Message Text="GameModule 已复制到 Host/modules/games/_staging:$(AssemblyName).dll(等待宿主热替换)" Importance="high" />
|
||||||
|
</Target>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using FunGame.Core.Entity;
|
||||||
|
using FunGame.Core.Library.Constant;
|
||||||
|
using FunGame.Core.Model.Framework;
|
||||||
|
using FunGame.Core.Model.Queue;
|
||||||
|
using FunGame.Server.Contracts.Gaming;
|
||||||
|
using FunGame.Server.Contracts.Networking;
|
||||||
|
using FunGame.Server.Contracts.Plugins;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Modules.Melee;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 标准近战 GameModule(游戏模式模组):封装网络层在 MixGamingQueue 之上<para/>
|
||||||
|
/// 参考 v2 ExampleGameModuleServer:单例模组、按房间建 Worker(GamingObject 对应物)、
|
||||||
|
/// GamingType switch-case 处理玩家行动;内容层(角色/技能/物品/Effect)经 GameModuleDepend 声明依赖。<para/>
|
||||||
|
/// 当前为 Phase 0:建房(StartGameAsync)+ 连接确认 + 选角;Attack/Skill/Item 等玩家局内决策后续接入。
|
||||||
|
/// </summary>
|
||||||
|
public class MeleeGameModuleServer : IGameModuleServer
|
||||||
|
{
|
||||||
|
public string Name => "melee";
|
||||||
|
public string Version => "0.1.0";
|
||||||
|
public string Author => "FunGame.Server";
|
||||||
|
public string Description => "标准近战游戏模式:淘汰制死亡竞赛(最多复活 1 次),封装网络层在 MixGamingQueue 上";
|
||||||
|
|
||||||
|
public string Id => Name;
|
||||||
|
|
||||||
|
public GameModuleDepend Dependencies { get; } = new(
|
||||||
|
maps: [],
|
||||||
|
characters: ["example", "oshima"],
|
||||||
|
skills: ["example", "oshima"],
|
||||||
|
items: ["example", "oshima"]);
|
||||||
|
|
||||||
|
public string DefaultMap => "";
|
||||||
|
|
||||||
|
public RoomType RoomType => RoomType.Mix;
|
||||||
|
|
||||||
|
public int MaxUsers => 8;
|
||||||
|
|
||||||
|
private ILogger? _logger;
|
||||||
|
|
||||||
|
/// <summary>房间工作区:游戏 Id ->(角色池 / 已连接用户 / 用户角色选择)</summary>
|
||||||
|
private sealed record Worker(List<Character> Characters, HashSet<long> ConnectedUsers, Dictionary<long, Character> UserCharacters);
|
||||||
|
|
||||||
|
private readonly ConcurrentDictionary<Guid, Worker> _workers = new();
|
||||||
|
|
||||||
|
public void OnLoad(IServiceProvider services)
|
||||||
|
{
|
||||||
|
_logger = services.GetService<ILoggerFactory>()?.CreateLogger("GameModule.melee");
|
||||||
|
_logger?.LogInformation("MeleeGameModuleServer v{Version} 已加载", Version);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnUnload()
|
||||||
|
{
|
||||||
|
_logger?.LogInformation("MeleeGameModuleServer 即将卸载(活跃对局 {Count})", _workers.Count);
|
||||||
|
_workers.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>建房:创建 MixGamingQueue(沿用宿主当前淘汰/复活=1 配置),登记房间工作区</summary>
|
||||||
|
public Task<GamingQueue> StartGameAsync(IGameSession session, params object[] args)
|
||||||
|
{
|
||||||
|
List<Character> characters = args.Length > 0 && args[0] is List<Character> list ? list : [];
|
||||||
|
GameMap? map = args.Length > 1 ? args[1] as GameMap : null;
|
||||||
|
|
||||||
|
MixGamingQueue queue = new(characters, msg => _logger?.LogDebug("[Melee {GameId}] {Msg}", session.Id, msg))
|
||||||
|
{
|
||||||
|
IsDebug = false,
|
||||||
|
MaxRespawnTimes = 1
|
||||||
|
};
|
||||||
|
if (map != null)
|
||||||
|
{
|
||||||
|
queue.LoadGameMap(map);
|
||||||
|
}
|
||||||
|
queue.InitActionQueue();
|
||||||
|
|
||||||
|
_workers[session.Id] = new Worker(characters, [], []);
|
||||||
|
_logger?.LogInformation("Melee 对局 {GameId} 开始({Count} 名角色)", session.Id, characters.Count);
|
||||||
|
return Task.FromResult<GamingQueue>(queue);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>处理客户端局内消息(switch-case GamingType,参考 v2)</summary>
|
||||||
|
public Task<Dictionary<string, object>?> HandleGamingMessageAsync(IGameSession session, IClientSession client, GamingType type, Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
if (!_workers.TryGetValue(session.Id, out Worker? worker))
|
||||||
|
{
|
||||||
|
return Task.FromResult<Dictionary<string, object>?>(new Dictionary<string, object> { ["error"] = "对局工作区不存在" });
|
||||||
|
}
|
||||||
|
|
||||||
|
long userId = client.UserId ?? client.SessionId;
|
||||||
|
switch (type)
|
||||||
|
{
|
||||||
|
case GamingType.Connect:
|
||||||
|
worker.ConnectedUsers.Add(userId);
|
||||||
|
return Task.FromResult<Dictionary<string, object>?>(new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["msg"] = "连接确认成功",
|
||||||
|
["connected"] = worker.ConnectedUsers.Count,
|
||||||
|
["total"] = worker.Characters.Count
|
||||||
|
});
|
||||||
|
|
||||||
|
case GamingType.PickCharacter:
|
||||||
|
{
|
||||||
|
long id = GetLong(data, "id");
|
||||||
|
Character? character = worker.Characters.FirstOrDefault(c => c.Id == id);
|
||||||
|
if (character == null)
|
||||||
|
{
|
||||||
|
return Task.FromResult<Dictionary<string, object>?>(new Dictionary<string, object> { ["error"] = $"角色不存在:{id}" });
|
||||||
|
}
|
||||||
|
worker.UserCharacters[userId] = character;
|
||||||
|
return Task.FromResult<Dictionary<string, object>?>(new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["msg"] = $"已选择角色:{character.NickName ?? character.Name}",
|
||||||
|
["id"] = character.Id
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
case GamingType.Surrender:
|
||||||
|
_ = session.EndGameAsync();
|
||||||
|
return Task.FromResult<Dictionary<string, object>?>(new Dictionary<string, object> { ["msg"] = "对局已结束" });
|
||||||
|
|
||||||
|
default:
|
||||||
|
// Attack/Skill/Item/Move/Magic/Buy/... 玩家局内决策接入后续里程碑实现
|
||||||
|
return Task.FromResult<Dictionary<string, object>?>(new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["msg"] = $"已收到 {type}(玩家局内决策接入后续实现)",
|
||||||
|
["round"] = session.Queue.TotalRound
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long GetLong(Dictionary<string, object> data, string key)
|
||||||
|
=> data.TryGetValue(key, out object? value) && long.TryParse(value?.ToString(), out long result) ? result : 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>FunGame.Server.Modules.Oshima</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\..\src\FunGame.Server.Contracts\FunGame.Server.Contracts.csproj" />
|
||||||
|
<ProjectReference Include="..\..\..\FunGame.Core\FunGame.Core.csproj" />
|
||||||
|
<!-- Oshima 内容库:Testing-v3 维护(最先适配 Core v3),Server 只引用不拷贝 -->
|
||||||
|
<ProjectReference Include="..\..\..\FunGame.Testing-v3\OshimaGameModules\OshimaGameModules.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<!-- 构建后复制包装层 + 内容库 DLL 到宿主的三个实体模组暂存区(热重载:由宿主原子替换到正式目录) -->
|
||||||
|
<Target Name="CopyModulesToHost" AfterTargets="Build">
|
||||||
|
<ItemGroup>
|
||||||
|
<ModuleFiles Include="$(TargetDir)$(AssemblyName).dll;$(TargetDir)$(AssemblyName).pdb;$(TargetDir)OshimaGameModules.dll;$(TargetDir)OshimaGameModules.pdb" />
|
||||||
|
</ItemGroup>
|
||||||
|
<MakeDir Directories="$(MSBuildThisFileDirectory)..\..\src\FunGame.Server.Host\modules\characters\_staging;$(MSBuildThisFileDirectory)..\..\src\FunGame.Server.Host\modules\skills\_staging;$(MSBuildThisFileDirectory)..\..\src\FunGame.Server.Host\modules\items\_staging" />
|
||||||
|
<Copy SourceFiles="@(ModuleFiles)" DestinationFolder="$(MSBuildThisFileDirectory)..\..\src\FunGame.Server.Host\modules\characters\_staging\" SkipUnchangedFiles="false" />
|
||||||
|
<Copy SourceFiles="@(ModuleFiles)" DestinationFolder="$(MSBuildThisFileDirectory)..\..\src\FunGame.Server.Host\modules\skills\_staging\" SkipUnchangedFiles="false" />
|
||||||
|
<Copy SourceFiles="@(ModuleFiles)" DestinationFolder="$(MSBuildThisFileDirectory)..\..\src\FunGame.Server.Host\modules\items\_staging\" SkipUnchangedFiles="false" />
|
||||||
|
<Message Text="Oshima 包装层 + 内容库已复制到 Host/modules/*/_staging(等待宿主热替换)" Importance="high" />
|
||||||
|
</Target>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
namespace Milimoe.FunGameTesting.Others
|
||||||
|
{
|
||||||
|
public class OshimaGameModuleConstant
|
||||||
|
{
|
||||||
|
public const string General = "oshima-studios";
|
||||||
|
public const string WebAPI = "oshima.fungame.webapi";
|
||||||
|
public const string FastAuto = "oshima.fungame.fastauto";
|
||||||
|
public const string Character = "oshima.fungame.characters";
|
||||||
|
public const string Skill = "oshima.fungame.skills";
|
||||||
|
public const string Item = "oshima.fungame.items";
|
||||||
|
public const string Description = "Oshima Studios Presents";
|
||||||
|
public const string Version = "1.0.0";
|
||||||
|
public const string Author = "Oshima Studios";
|
||||||
|
public const string FastAutoMap = "oshima.fungame.fastauto.map";
|
||||||
|
public const string Anonymous = "oshima.fungame.anonymous";
|
||||||
|
public const string AnonymousMap = "oshima.fungame.anonymous.map";
|
||||||
|
public const string Server = "oshima.fungame.server";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,288 @@
|
|||||||
|
using FunGame.Core.Api;
|
||||||
|
using FunGame.Core.Entity;
|
||||||
|
using FunGame.Server.Contracts.Plugins;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Milimoe.FunGameTesting.Others;
|
||||||
|
using Milimoe.FunGameTesting.OshimaGameModules.Characters;
|
||||||
|
using Milimoe.FunGameTesting.OshimaGameModules.Items;
|
||||||
|
using Milimoe.FunGameTesting.OshimaGameModules.Skills;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Modules.Oshima;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建实体新实例:优先无参构造;无无参构造时退化为 (Character? = null) 风格的构造(技能类惯例)<para/>
|
||||||
|
/// 工厂委托必须返回新实例而非 Copy(),避免 Skill.Copy 内部调用 Factory.GetInstance 造成无限递归
|
||||||
|
/// </summary>
|
||||||
|
internal static class ModuleEntityFactory
|
||||||
|
{
|
||||||
|
public static T? Create<T>(Type type) where T : class
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return (T)Activator.CreateInstance(type)!;
|
||||||
|
}
|
||||||
|
catch (MissingMethodException)
|
||||||
|
{
|
||||||
|
return (T)Activator.CreateInstance(type, (object?[]?)[null])!;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Oshima Studios 角色模组:Testing-v3(FunGameSimulation)同源内容,供 Server 加载<para/>
|
||||||
|
/// 18 名角色(大島シヤ / 心音 / 阳 / 南甘雨 …),与 Testing-v3 的 Oshima CharacterModule 工厂(id 1-18)一一对应
|
||||||
|
/// </summary>
|
||||||
|
public class OshimaCharacterModule : ICharacterModule
|
||||||
|
{
|
||||||
|
public string Name => "oshima.characters";
|
||||||
|
public string Version => "1.0.0";
|
||||||
|
public string Author => "Oshima Studios";
|
||||||
|
public string Description => "Oshima 角色模组:18 名角色(移植自 FunGame.Testing-v3 / FunGameSimulation)";
|
||||||
|
|
||||||
|
private IReadOnlyDictionary<string, Character>? _entities;
|
||||||
|
|
||||||
|
public IReadOnlyDictionary<string, Character> Entities
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
_entities ??= new Dictionary<string, Character>
|
||||||
|
{
|
||||||
|
["oshima_shiya"] = new OshimaShiya(),
|
||||||
|
["xin_yin"] = new XinYin(),
|
||||||
|
["yang"] = new Yang(),
|
||||||
|
["nan_ganyu"] = new NanGanYu(),
|
||||||
|
["niu_nan"] = new NiuNan(),
|
||||||
|
["dokyo_mayor"] = new DokyoMayor(),
|
||||||
|
["magical_girl"] = new MagicalGirl(),
|
||||||
|
["qing_xiang"] = new QingXiang(),
|
||||||
|
["qwqaqw"] = new QWQAQW(),
|
||||||
|
["cold_blue"] = new ColdBlue(),
|
||||||
|
["dddovo"] = new Dddovo(),
|
||||||
|
["qu_duoduo"] = new Quduoduo(),
|
||||||
|
["shi_yu"] = new ShiYu(),
|
||||||
|
["xreouni"] = new XReouni(),
|
||||||
|
["neptune"] = new Neptune(),
|
||||||
|
["chaos"] = new CHAOS(),
|
||||||
|
["ryuko"] = new Ryuko(),
|
||||||
|
["the_god_k"] = new TheGodK()
|
||||||
|
};
|
||||||
|
return _entities;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnLoad(IServiceProvider services)
|
||||||
|
{
|
||||||
|
// 注册工厂(与 Oshima CharacterModule 工厂一致:id 1-18)
|
||||||
|
Factory.OpenFactory.RegisterFactory<Character>((id, name, args) => id switch
|
||||||
|
{
|
||||||
|
1 => new OshimaShiya(),
|
||||||
|
2 => new XinYin(),
|
||||||
|
3 => new Yang(),
|
||||||
|
4 => new NanGanYu(),
|
||||||
|
5 => new NiuNan(),
|
||||||
|
6 => new DokyoMayor(),
|
||||||
|
7 => new MagicalGirl(),
|
||||||
|
8 => new QingXiang(),
|
||||||
|
9 => new QWQAQW(),
|
||||||
|
10 => new ColdBlue(),
|
||||||
|
11 => new Dddovo(),
|
||||||
|
12 => new Quduoduo(),
|
||||||
|
13 => new ShiYu(),
|
||||||
|
14 => new XReouni(),
|
||||||
|
15 => new Neptune(),
|
||||||
|
16 => new CHAOS(),
|
||||||
|
17 => new Ryuko(),
|
||||||
|
18 => new TheGodK(),
|
||||||
|
_ => null
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnUnload()
|
||||||
|
{
|
||||||
|
Factory.OpenFactory.UnRegisterFactory<Character>((id, name, args) => id switch
|
||||||
|
{
|
||||||
|
1 => new OshimaShiya(),
|
||||||
|
2 => new XinYin(),
|
||||||
|
3 => new Yang(),
|
||||||
|
4 => new NanGanYu(),
|
||||||
|
5 => new NiuNan(),
|
||||||
|
6 => new DokyoMayor(),
|
||||||
|
7 => new MagicalGirl(),
|
||||||
|
8 => new QingXiang(),
|
||||||
|
9 => new QWQAQW(),
|
||||||
|
10 => new ColdBlue(),
|
||||||
|
11 => new Dddovo(),
|
||||||
|
12 => new Quduoduo(),
|
||||||
|
13 => new ShiYu(),
|
||||||
|
14 => new XReouni(),
|
||||||
|
15 => new Neptune(),
|
||||||
|
16 => new CHAOS(),
|
||||||
|
17 => new Ryuko(),
|
||||||
|
18 => new TheGodK(),
|
||||||
|
_ => null
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Oshima 技能模组:基础战技 / 爆发技 / 被动 / 通用被动 / 通用爆发 / 魔法 全量注册
|
||||||
|
/// </summary>
|
||||||
|
public class OshimaSkillModule : ISkillModule
|
||||||
|
{
|
||||||
|
public string Name => "oshima.skills";
|
||||||
|
public string Version => "1.0.0";
|
||||||
|
public string Author => "Oshima Studios";
|
||||||
|
public string Description => "Oshima 技能模组:基础技能 / 爆发技 / 被动 / 魔法(移植自 FunGame.Testing-v3)";
|
||||||
|
|
||||||
|
private IReadOnlyDictionary<string, Skill>? _entities;
|
||||||
|
|
||||||
|
public IReadOnlyDictionary<string, Skill> Entities
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
_entities ??= BuildEntities();
|
||||||
|
return _entities;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IReadOnlyDictionary<string, Skill> BuildEntities()
|
||||||
|
{
|
||||||
|
Dictionary<string, Skill> skills = new();
|
||||||
|
int seq = 0;
|
||||||
|
Skill[] all =
|
||||||
|
[
|
||||||
|
// ===== 基础战技 =====
|
||||||
|
new 疾风步(), new 助威(), new 挑拨(), new 绞丝棍(), new 金刚击(), new 旋风轮(), new 双连击(), new 绝影(), new 胧(), new 魔眼(),
|
||||||
|
new 天堂之吻(), new 回复弹(), new 养命功(), new 镜花水月(), new 剑风闪(), new 鲨鱼锚击(), new 疾走(), new 闪现(),
|
||||||
|
// ===== 爆发技 =====
|
||||||
|
new 极寒渴望(), new 身心一境(), new 绝对领域(), new 零式灭杀(), new 三相灵枢(), new 变幻之心(), new 熵灭极诣(), new 残香凋零(), new 饕餮盛宴(),
|
||||||
|
new 宿命时律(), new 千羽瞬华(), new 咒怨洪流(), new 放监(), new 归元环(), new 海王星的野望(), new 全军出击(), new 宿命之潮(), new 神之因果(),
|
||||||
|
// ===== 角色被动 =====
|
||||||
|
new META马(), new 心灵之弦(), new 蚀魂震击(), new 灵能反射(), new 双生流转(), new 零式崩解(), new 少女绮想(), new 暗香疏影(), new 破釜沉舟(),
|
||||||
|
new 累积之压(), new 银隼之赐(), new 弱者猎手(), new 开宫(), new 八卦阵(), new 深海之戟(), new 雇佣兵团(), new 不息之流(), new 概念之骰(),
|
||||||
|
// ===== 通用被动 =====
|
||||||
|
new 征服者(), new 致命节奏(), new 强攻(), new 电刑(), new 黑暗收割(), new 迅捷步法(), new 贪欲猎手(),
|
||||||
|
// ===== 通用爆发 =====
|
||||||
|
new 樱花无双击(), new 漆黑之牙(), new 女王之怒(), new 裁决塔罗(), new 光明之环(), new 圣星光旋(),
|
||||||
|
// ===== 魔法 =====
|
||||||
|
new 冰霜攻击(), new 火之矢(), new 水之矢(), new 风之轮(), new 石之锤(), new 心灵之霞(), new 次元上升(), new 暗物质(),
|
||||||
|
new 回复术(), new 治愈术(), new 复苏术(), new 圣灵术(), new 时间加速(), new 时间减速(), new 反魔法领域(), new 沉默十字(), new 虚弱领域(), new 混沌烙印(), new 凝胶稠絮(),
|
||||||
|
new 大地之墙(), new 盖亚之盾(), new 风之守护(), new 结晶防护(), new 强音之力(), new 神圣祝福(), new 根源屏障(), new 灾难冲击波(), new 银色荆棘(), new 等离子之波(),
|
||||||
|
new 地狱之门(), new 钻石星尘(), new 死亡咆哮(), new 鬼魅之痛(), new 导力停止(), new 冰狱冥嚎(), new 火山咆哮(), new 水蓝轰炸(), new 岩石之息(), new 弧形日珥(), new 苍白地狱(), new 破碎虚空(),
|
||||||
|
new 弧光消耗(), new 回复术改(), new 回复术复(), new 治愈术复(), new 风之守护复(), new 强音之力复(), new 结晶防护复(), new 神圣祝福复(), new 时间加速改(), new 时间减速改(), new 时间加速复(), new 时间减速复()
|
||||||
|
];
|
||||||
|
foreach (Skill skill in all)
|
||||||
|
{
|
||||||
|
skills[$"oshima_skill_{++seq}"] = skill;
|
||||||
|
}
|
||||||
|
return skills;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnLoad(IServiceProvider services)
|
||||||
|
{
|
||||||
|
// 注意:工厂委托必须返回“新实例”,不能用 skill.Copy()——Copy 内部会再调 Factory.GetInstance,形成无限递归
|
||||||
|
foreach (Skill skill in Entities.Values)
|
||||||
|
{
|
||||||
|
Factory.OpenFactory.RegisterFactory<Skill>((id, name, args) => skill.Id == id ? ModuleEntityFactory.Create<Skill>(skill.GetType()) : null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnUnload()
|
||||||
|
{
|
||||||
|
foreach (Skill skill in Entities.Values)
|
||||||
|
{
|
||||||
|
Factory.OpenFactory.UnRegisterFactory<Skill>((id, name, args) => skill.Id == id ? ModuleEntityFactory.Create<Skill>(skill.GetType()) : null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Oshima 物品模组:装备(武器/防具/鞋子/饰品)+ 消耗品 + 收藏品 全量注册
|
||||||
|
/// </summary>
|
||||||
|
public class OshimaItemModule : IItemModule
|
||||||
|
{
|
||||||
|
public string Name => "oshima.items";
|
||||||
|
public string Version => "1.0.0";
|
||||||
|
public string Author => "Oshima Studios";
|
||||||
|
public string Description => "Oshima 物品模组:装备 / 消耗品 / JSON 配置物品(移植自 FunGame.Testing-v3)";
|
||||||
|
|
||||||
|
/// <summary>JSON 配置物品数量(modules/oshima-studios/oshima.fungame.items.json)</summary>
|
||||||
|
public static int JsonItemCount { get; private set; }
|
||||||
|
|
||||||
|
private IReadOnlyDictionary<string, Item>? _entities;
|
||||||
|
|
||||||
|
public IReadOnlyDictionary<string, Item> Entities
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
_entities ??= BuildEntities();
|
||||||
|
return _entities;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IReadOnlyDictionary<string, Item> BuildEntities()
|
||||||
|
{
|
||||||
|
Dictionary<string, Item> items = new();
|
||||||
|
|
||||||
|
// ===== JSON 配置物品(EntityModuleConfig 通道:modules/oshima-studios/oshima.fungame.items.json)=====
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, Item> jsonItems = Factory.GetGameModuleInstances<Item>(OshimaGameModuleConstant.General, OshimaGameModuleConstant.Item);
|
||||||
|
foreach ((string key, Item item) in jsonItems)
|
||||||
|
{
|
||||||
|
items[$"oshima_json_{key}"] = item;
|
||||||
|
}
|
||||||
|
JsonItemCount = jsonItems.Count;
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
JsonItemCount = -1; // JSON 缺失或解析失败(代码物品仍可用)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 代码注册物品 =====
|
||||||
|
int seq = 0;
|
||||||
|
Item[] all =
|
||||||
|
[
|
||||||
|
// ===== 武器 =====
|
||||||
|
new 攻击之爪10(), new 攻击之爪25(), new 攻击之爪40(), new 攻击之爪55(), new 攻击之爪70(), new 攻击之爪85(), new 糖糖一周年纪念武器(),
|
||||||
|
// ===== 防具 =====
|
||||||
|
new 糖糖一周年纪念防具(),
|
||||||
|
// ===== 鞋子 =====
|
||||||
|
new 糖糖一周年纪念鞋子(),
|
||||||
|
// ===== 饰品 =====
|
||||||
|
new 糖糖一周年纪念饰品1(), new 糖糖一周年纪念饰品2(),
|
||||||
|
// ===== 消耗品 =====
|
||||||
|
new 小经验书(), new 中经验书(), new 大经验书(), new 升华之印(), new 流光之印(), new 永恒之印(), new 技能卷轴(), new 智慧之果(), new 奥术符文(), new 混沌之核(),
|
||||||
|
new 小回复药(), new 中回复药(), new 大回复药(), new 魔力填充剂1(), new 魔力填充剂2(), new 魔力填充剂3(), new 能量饮料1(), new 能量饮料2(), new 能量饮料3(), new 年夜饭(), new 蛇年大吉(), new 新春快乐(), new 毕业礼包(),
|
||||||
|
new 复苏药1(), new 复苏药2(), new 复苏药3(), new 全回复药(), new 魔法卡礼包(), new 奖券(), new 十连奖券(), new 改名卡(), new 原初之印(), new 创生之印(), new 法则精粹(), new 大师锻造券(),
|
||||||
|
new 一周年纪念礼包(), new 一周年纪念套装(), new 冬至快乐(), new 圣诞礼包(), new 元旦快乐()
|
||||||
|
];
|
||||||
|
foreach (Item item in all)
|
||||||
|
{
|
||||||
|
items[$"oshima_item_{++seq}"] = item;
|
||||||
|
}
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnLoad(IServiceProvider services)
|
||||||
|
{
|
||||||
|
ILoggerFactory? loggerFactory = services.GetService(typeof(ILoggerFactory)) as ILoggerFactory;
|
||||||
|
ILogger? logger = loggerFactory?.CreateLogger("OshimaItemModule");
|
||||||
|
int total = Entities.Count;
|
||||||
|
int jsonCount = Math.Max(JsonItemCount, 0);
|
||||||
|
logger?.LogInformation("Oshima 物品模组加载:代码物品 {CodeCount} 件 + JSON 配置物品 {JsonCount} 件", total - jsonCount, JsonItemCount);
|
||||||
|
foreach (Item item in Entities.Values)
|
||||||
|
{
|
||||||
|
// 注意:工厂委托必须返回“新实例”,不能用 item.Copy()——Copy 内部会再调 Factory.GetInstance,形成无限递归
|
||||||
|
Factory.OpenFactory.RegisterFactory<Item>((id, name, args) => item.Id == id ? ModuleEntityFactory.Create<Item>(item.GetType()) : null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnUnload()
|
||||||
|
{
|
||||||
|
foreach (Item item in Entities.Values)
|
||||||
|
{
|
||||||
|
Factory.OpenFactory.UnRegisterFactory<Item>((id, name, args) => item.Id == id ? ModuleEntityFactory.Create<Item>(item.GetType()) : null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
using FunGame.Server.Contracts.Gaming;
|
||||||
|
using FunGame.Server.Contracts.Networking;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
using FunGame.Server.Contracts.Plugins;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Plugins.Example;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 示例服务器插件(合并 v2 的 WebAPIPlugin 与 GameModuleServer)<para/>
|
||||||
|
/// - HTTP 端点:GET /plugin/example/hello<para/>
|
||||||
|
/// - WS 消息处理器:example.echo<para/>
|
||||||
|
/// - 对局模式:HandleGamingMessage(example.cheer)
|
||||||
|
/// </summary>
|
||||||
|
public class ExamplePlugin : IServerPlugin
|
||||||
|
{
|
||||||
|
private ILogger? _logger;
|
||||||
|
|
||||||
|
public string Name => "example";
|
||||||
|
public string Version => "1.2.0";
|
||||||
|
public string Author => "FunGame.Server";
|
||||||
|
public string Description => "示例服务器插件:演示 HTTP 端点、WS 消息处理器、对局模式与热重载";
|
||||||
|
|
||||||
|
public void OnLoad(IServiceProvider services)
|
||||||
|
{
|
||||||
|
_logger = services.GetService<ILoggerFactory>()?.CreateLogger("Plugin.example");
|
||||||
|
_logger?.LogInformation("ExamplePlugin v{Version} 已加载", Version);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnUnload()
|
||||||
|
{
|
||||||
|
_logger?.LogInformation("ExamplePlugin 即将卸载(端点与消息处理器随后注销)");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ConfigureEndpoints(IPluginHttpHandlerRegistry http, IMessageHandlerRegistry messages)
|
||||||
|
{
|
||||||
|
// GET /plugin/example/hello
|
||||||
|
http.Register("GET", "hello", this, async context =>
|
||||||
|
{
|
||||||
|
await context.Response.WriteAsJsonAsync(ApiResponse.Success(new
|
||||||
|
{
|
||||||
|
message = "来自示例插件的问候(热重载后 v1.2.0)",
|
||||||
|
plugin = Name,
|
||||||
|
version = Version,
|
||||||
|
time = DateTime.Now
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /plugin/example/info
|
||||||
|
http.Register("GET", "info", this, async context =>
|
||||||
|
{
|
||||||
|
await context.Response.WriteAsJsonAsync(ApiResponse.Success(new
|
||||||
|
{
|
||||||
|
name = Name,
|
||||||
|
version = Version,
|
||||||
|
author = Author,
|
||||||
|
description = Description
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
// WS:example.echo —— 原样回显负载
|
||||||
|
messages.Register("example.echo", this, async (client, message) =>
|
||||||
|
{
|
||||||
|
return MessageEnvelope.Reply(message, message.Data);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<Dictionary<string, object>?> HandleGamingMessage(IGameSession session, string type, Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
if (type == "example.cheer")
|
||||||
|
{
|
||||||
|
return Task.FromResult<Dictionary<string, object>?>(new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["message"] = $"插件 {Name} 收到对局消息(对局 {session.Id},回合 {session.Queue.TotalRound})"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Task.FromResult<Dictionary<string, object>?>(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>FunGame.Server.Plugins.Example</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||||
|
<ProjectReference Include="..\..\src\FunGame.Server.Contracts\FunGame.Server.Contracts.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<!-- 构建后复制到宿主 plugins/_staging(热重载暂存区,由宿主原子替换到正式目录) -->
|
||||||
|
<Target Name="CopyPluginToHost" AfterTargets="Build">
|
||||||
|
<ItemGroup>
|
||||||
|
<PluginFiles Include="$(TargetDir)$(AssemblyName).dll;$(TargetDir)$(AssemblyName).pdb" />
|
||||||
|
</ItemGroup>
|
||||||
|
<MakeDir Directories="$(MSBuildThisFileDirectory)..\..\src\FunGame.Server.Host\plugins\_staging\" />
|
||||||
|
<Copy SourceFiles="@(PluginFiles)" DestinationFolder="$(MSBuildThisFileDirectory)..\..\src\FunGame.Server.Host\plugins\_staging\" SkipUnchangedFiles="false" />
|
||||||
|
<Message Text="插件已复制到 Host/plugins/_staging:$(AssemblyName).dll(等待宿主热替换)" Importance="high" />
|
||||||
|
</Target>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
namespace FunGame.Server.Contracts.Constants;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 插件/模组/记录目录约定
|
||||||
|
/// </summary>
|
||||||
|
public static class PluginConstants
|
||||||
|
{
|
||||||
|
/// <summary>服务器插件目录</summary>
|
||||||
|
public const string PluginsDirectory = "plugins";
|
||||||
|
|
||||||
|
/// <summary>角色模组目录</summary>
|
||||||
|
public const string CharacterModulesDirectory = "modules/characters";
|
||||||
|
|
||||||
|
/// <summary>技能模组目录</summary>
|
||||||
|
public const string SkillModulesDirectory = "modules/skills";
|
||||||
|
|
||||||
|
/// <summary>物品模组目录</summary>
|
||||||
|
public const string ItemModulesDirectory = "modules/items";
|
||||||
|
|
||||||
|
/// <summary>游戏模式模组(GameModule)目录</summary>
|
||||||
|
public const string GameModuleDirectory = "modules/games";
|
||||||
|
|
||||||
|
/// <summary>回合记录归档目录</summary>
|
||||||
|
public const string RecordsDirectory = "records";
|
||||||
|
|
||||||
|
/// <summary>SQLite 数据目录</summary>
|
||||||
|
public const string DataDirectory = "Data";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 权限点(细粒度 RBAC;JWT Claim:perm)
|
||||||
|
/// </summary>
|
||||||
|
public static class PermissionCodes
|
||||||
|
{
|
||||||
|
public const string UsersRead = "users.read";
|
||||||
|
public const string UsersWrite = "users.write";
|
||||||
|
public const string RolesManage = "roles.manage";
|
||||||
|
public const string PermissionsManage = "permissions.manage";
|
||||||
|
public const string PluginsManage = "plugins.manage";
|
||||||
|
public const string GamesManage = "games.manage";
|
||||||
|
public const string LogsRead = "logs.read";
|
||||||
|
public const string ConfigManage = "config.manage";
|
||||||
|
public const string TokensManage = "tokens.manage";
|
||||||
|
|
||||||
|
/// <summary>全部权限点:Code -> 说明</summary>
|
||||||
|
public static IReadOnlyDictionary<string, string> All { get; } = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
[UsersRead] = "查看用户",
|
||||||
|
[UsersWrite] = "管理用户(增删改、角色分配、会话管理)",
|
||||||
|
[RolesManage] = "管理角色",
|
||||||
|
[PermissionsManage] = "管理权限点",
|
||||||
|
[PluginsManage] = "管理插件与模组(热重载)",
|
||||||
|
[GamesManage] = "管理对局(强制结束等)",
|
||||||
|
[LogsRead] = "查看服务器日志",
|
||||||
|
[ConfigManage] = "管理系统配置",
|
||||||
|
[TokensManage] = "管理 API 令牌"
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>FunGame.Server.Contracts</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\..\..\FunGame.Core\FunGame.Core.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
namespace FunGame.Server.Contracts.Gaming;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 游戏模式模组(GameModule)的内容依赖声明<para/>
|
||||||
|
/// 参考 v2 <c>GameModuleDepend</c>:声明该模式依赖的地图/角色/技能/物品内容前缀(如 "example"、"oshima")<para/>
|
||||||
|
/// 宿主建房装配角色时只从声明允许的内容模组族取;空数组 = 不限制
|
||||||
|
/// </summary>
|
||||||
|
public class GameModuleDepend
|
||||||
|
{
|
||||||
|
/// <summary>依赖的地图前缀(如 "fungame.example.gamemap")</summary>
|
||||||
|
public string[] MapsDepend { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>依赖的角色内容前缀(如 "oshima" → oshima.characters)</summary>
|
||||||
|
public string[] CharactersDepend { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>依赖的技能内容前缀(如 "oshima" → oshima.skills)</summary>
|
||||||
|
public string[] SkillsDepend { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>依赖的物品内容前缀(如 "oshima" → oshima.items)</summary>
|
||||||
|
public string[] ItemsDepend { get; init; } = [];
|
||||||
|
|
||||||
|
public GameModuleDepend()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public GameModuleDepend(string[] maps, string[] characters, string[] skills, string[] items)
|
||||||
|
{
|
||||||
|
MapsDepend = maps;
|
||||||
|
CharactersDepend = characters;
|
||||||
|
SkillsDepend = skills;
|
||||||
|
ItemsDepend = items;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>不限制内容(宿主按房间 ContentModule 装配)</summary>
|
||||||
|
public static GameModuleDepend All { get; } = new([], [], [], []);
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
using FunGame.Core.Entity;
|
||||||
|
using FunGame.Core.Model.Queue;
|
||||||
|
using FunGame.Server.Contracts.Networking;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Contracts.Gaming;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 对局会话(宿主维护,暴露给游戏模式模组 GameModuleServer)<para/>
|
||||||
|
/// 模组能力:读参与角色 / 广播局内事件 / 结束对局
|
||||||
|
/// </summary>
|
||||||
|
public interface IGameSession
|
||||||
|
{
|
||||||
|
/// <summary>对局唯一标识</summary>
|
||||||
|
Guid Id { get; }
|
||||||
|
|
||||||
|
/// <summary>战斗引擎队列(模组建房时创建)</summary>
|
||||||
|
GamingQueue Queue { get; }
|
||||||
|
|
||||||
|
/// <summary>游戏模式(GameModule 名 / 服务器插件名)</summary>
|
||||||
|
string Mode { get; }
|
||||||
|
|
||||||
|
/// <summary>用户 Id -> 客户端会话(本局参与者)</summary>
|
||||||
|
IReadOnlyDictionary<long, IClientSession> Clients { get; }
|
||||||
|
|
||||||
|
/// <summary>对局是否仍在运行</summary>
|
||||||
|
bool Running { get; }
|
||||||
|
|
||||||
|
/// <summary>自定义数据(模组私有状态)</summary>
|
||||||
|
Dictionary<string, object> CustomData { get; }
|
||||||
|
|
||||||
|
/// <summary>本局参与角色(宿主装配,供模组取用)</summary>
|
||||||
|
IReadOnlyList<Character> Characters { get; }
|
||||||
|
|
||||||
|
/// <summary>广播消息给本局全部用户(userIds 为空)或指定用户</summary>
|
||||||
|
Task BroadcastAsync(string messageType, Dictionary<string, object> data, params long[] userIds);
|
||||||
|
|
||||||
|
/// <summary>结束对局(宿主负责归档回合记录与广播结算)</summary>
|
||||||
|
Task EndGameAsync(bool aborted = false);
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Contracts.Networking;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 客户端会话抽象(WebSocket 连接;替代 v2 的 IServerModel)<para/>
|
||||||
|
/// 由宿主实现,供业务层与插件层使用
|
||||||
|
/// </summary>
|
||||||
|
public interface IClientSession
|
||||||
|
{
|
||||||
|
long SessionId { get; }
|
||||||
|
long? UserId { get; }
|
||||||
|
string? Username { get; }
|
||||||
|
IReadOnlyCollection<string> Permissions { get; }
|
||||||
|
bool IsAuthenticated { get; }
|
||||||
|
DateTime ConnectedAt { get; }
|
||||||
|
DateTime LastActiveAt { get; }
|
||||||
|
string RemoteAddress { get; }
|
||||||
|
|
||||||
|
/// <summary>发送消息</summary>
|
||||||
|
Task<bool> SendAsync(MessageEnvelope message, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
|
/// <summary>关闭连接</summary>
|
||||||
|
Task CloseAsync(string reason, CancellationToken cancellationToken = default);
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
namespace FunGame.Server.Contracts.Payloads;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// REST API 统一响应包装(与 WebSocket 信封对齐)
|
||||||
|
/// </summary>
|
||||||
|
public class ApiResponse<T>
|
||||||
|
{
|
||||||
|
public bool Ok { get; set; } = true;
|
||||||
|
public int Code { get; set; }
|
||||||
|
public string? Message { get; set; }
|
||||||
|
public T? Data { get; set; }
|
||||||
|
public DateTime Timestamp { get; set; } = DateTime.Now;
|
||||||
|
|
||||||
|
public static ApiResponse<T> Success(T? data, string? message = null) => new()
|
||||||
|
{
|
||||||
|
Ok = true,
|
||||||
|
Code = 0,
|
||||||
|
Data = data,
|
||||||
|
Message = message
|
||||||
|
};
|
||||||
|
|
||||||
|
public static ApiResponse<T> Fail(int code, string message) => new()
|
||||||
|
{
|
||||||
|
Ok = false,
|
||||||
|
Code = code,
|
||||||
|
Message = message
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class ApiResponse
|
||||||
|
{
|
||||||
|
public static ApiResponse<T> Success<T>(T? data, string? message = null) => ApiResponse<T>.Success(data, message);
|
||||||
|
public static ApiResponse<T> Fail<T>(int code, string message) => ApiResponse<T>.Fail(code, message);
|
||||||
|
public static ApiResponse<object?> Success(object? data, string? message = null) => Success<object?>(data, message);
|
||||||
|
public static ApiResponse<object?> Fail(int code, string message) => Fail<object?>(code, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 分页数据包装(列表类 CRUD 接口统一返回)
|
||||||
|
/// </summary>
|
||||||
|
public class PagedData<T>
|
||||||
|
{
|
||||||
|
public int Page { get; set; }
|
||||||
|
public int PageSize { get; set; }
|
||||||
|
public long Total { get; set; }
|
||||||
|
public List<T> Items { get; set; } = [];
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Contracts.Payloads;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// WebSocket 负载信封(替代 v2 的 SocketObject)<para/>
|
||||||
|
/// 字段:t=消息类型(点分字符串)、i=请求序号(客户端生成,用于响应关联)、ok=是否成功、error=错误信息、d=负载字典、ts=时间戳
|
||||||
|
/// </summary>
|
||||||
|
public class MessageEnvelope
|
||||||
|
{
|
||||||
|
[JsonPropertyName("t")]
|
||||||
|
public string Type { get; set; } = "";
|
||||||
|
|
||||||
|
[JsonPropertyName("i")]
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("ok")]
|
||||||
|
public bool Ok { get; set; } = true;
|
||||||
|
|
||||||
|
[JsonPropertyName("error")]
|
||||||
|
public MessageError? Error { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("d")]
|
||||||
|
public Dictionary<string, object> Data { get; set; } = [];
|
||||||
|
|
||||||
|
[JsonPropertyName("ts")]
|
||||||
|
public long Timestamp { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 依据请求生成响应信封(类型与序号回显)
|
||||||
|
/// </summary>
|
||||||
|
public static MessageEnvelope Reply(MessageEnvelope request, Dictionary<string, object>? data = null, bool ok = true, MessageError? error = null) => new()
|
||||||
|
{
|
||||||
|
Type = request.Type,
|
||||||
|
Id = request.Id,
|
||||||
|
Ok = ok,
|
||||||
|
Error = error,
|
||||||
|
Data = data ?? []
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 构造服务器主动广播信封(i=0 表示无关联请求)
|
||||||
|
/// </summary>
|
||||||
|
public static MessageEnvelope Broadcast(string type, Dictionary<string, object>? data = null) => new()
|
||||||
|
{
|
||||||
|
Type = type,
|
||||||
|
Id = 0,
|
||||||
|
Data = data ?? []
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public class MessageError
|
||||||
|
{
|
||||||
|
[JsonPropertyName("code")]
|
||||||
|
public string Code { get; set; } = "";
|
||||||
|
|
||||||
|
[JsonPropertyName("message")]
|
||||||
|
public string Message { get; set; } = "";
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
namespace FunGame.Server.Contracts.Payloads;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// WebSocket 消息类型注册表(替代 v2 的 SocketMessageType 枚举)<para/>
|
||||||
|
/// 命名约定:小写点分(域.动作);服务器响应使用同类型信封 + ok/error 字段
|
||||||
|
/// </summary>
|
||||||
|
public static class MessageTypes
|
||||||
|
{
|
||||||
|
// ===== 系统 =====
|
||||||
|
/// <summary>心跳请求</summary>
|
||||||
|
public const string Ping = "system.ping";
|
||||||
|
/// <summary>心跳响应</summary>
|
||||||
|
public const string Pong = "system.pong";
|
||||||
|
/// <summary>服务器公告</summary>
|
||||||
|
public const string Notice = "system.notice";
|
||||||
|
/// <summary>系统消息(弹窗/提示)</summary>
|
||||||
|
public const string System = "system.message";
|
||||||
|
/// <summary>被踢下线</summary>
|
||||||
|
public const string Kick = "system.kick";
|
||||||
|
/// <summary>服务器信息</summary>
|
||||||
|
public const string ServerInfo = "system.info";
|
||||||
|
|
||||||
|
// ===== 认证 =====
|
||||||
|
public const string AuthLogin = "auth.login";
|
||||||
|
public const string AuthRegister = "auth.register";
|
||||||
|
public const string AuthLogout = "auth.logout";
|
||||||
|
public const string AuthRefresh = "auth.refresh";
|
||||||
|
/// <summary>对端信息(登录成功后服务器下发用户/权限快照)</summary>
|
||||||
|
public const string AuthProfile = "auth.profile";
|
||||||
|
|
||||||
|
// ===== 房间 =====
|
||||||
|
public const string RoomList = "room.list";
|
||||||
|
public const string RoomCreate = "room.create";
|
||||||
|
public const string RoomJoin = "room.join";
|
||||||
|
public const string RoomQuit = "room.quit";
|
||||||
|
public const string RoomUpdate = "room.update";
|
||||||
|
public const string RoomReady = "room.ready";
|
||||||
|
public const string RoomCancelReady = "room.cancelready";
|
||||||
|
public const string RoomStart = "room.start";
|
||||||
|
public const string RoomChat = "room.chat";
|
||||||
|
/// <summary>房间内广播(加入/离开/房主变更)</summary>
|
||||||
|
public const string RoomEvent = "room.event";
|
||||||
|
|
||||||
|
// ===== 匹配 =====
|
||||||
|
public const string MatchStart = "match.start";
|
||||||
|
public const string MatchCancel = "match.cancel";
|
||||||
|
public const string MatchFound = "match.found";
|
||||||
|
|
||||||
|
// ===== 对局 =====
|
||||||
|
public const string GamingStart = "gaming.start";
|
||||||
|
/// <summary>局内决策(决策点:技能/物品/移动)</summary>
|
||||||
|
public const string GamingAction = "gaming.action";
|
||||||
|
/// <summary>局内断线重连</summary>
|
||||||
|
public const string GamingReconnect = "gaming.reconnect";
|
||||||
|
/// <summary>主动结束对局</summary>
|
||||||
|
public const string GamingEnd = "gaming.end";
|
||||||
|
/// <summary>游戏结束结算广播</summary>
|
||||||
|
public const string GamingOver = "gaming.over";
|
||||||
|
/// <summary>回合记录推送(观战/直播,来源:回合记录外发)</summary>
|
||||||
|
public const string GamingRound = "gaming.round";
|
||||||
|
/// <summary>行动顺序表推送</summary>
|
||||||
|
public const string GamingQueue = "gaming.queue";
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
using FunGame.Core.Library.Constant;
|
||||||
|
using FunGame.Core.Model.Queue;
|
||||||
|
using FunGame.Server.Contracts.Gaming;
|
||||||
|
using FunGame.Server.Contracts.Networking;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Contracts.Plugins;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 游戏模式模组(GameModule 服务器侧):封装网络层在 GamingQueue 之上的"游戏模式"<para/>
|
||||||
|
/// 参考 v2 <c>IGameModuleServer</c>/<c>GameModuleServer</c>:模组为单例,为每个房间建工作区(玩家/角色/状态),
|
||||||
|
/// 用 switch-case 处理 <see cref="GamingType"/>(Connect/PickCharacter/Skill/Item/...),并广播局内事件。<para/>
|
||||||
|
/// 内容模组(ICharacterModule/ISkillModule/IItemModule)只是其依赖的内容层。
|
||||||
|
/// </summary>
|
||||||
|
public interface IGameModuleServer : IPluginBase
|
||||||
|
{
|
||||||
|
/// <summary>游戏模式名(= 房间 GameModule 字段,如 "melee")</summary>
|
||||||
|
string Id { get; }
|
||||||
|
|
||||||
|
/// <summary>内容依赖声明(地图/角色/技能/物品前缀)</summary>
|
||||||
|
GameModuleDepend Dependencies { get; }
|
||||||
|
|
||||||
|
/// <summary>默认地图(可空)</summary>
|
||||||
|
string DefaultMap { get; }
|
||||||
|
|
||||||
|
/// <summary>适用房间模式(Mix/Team/...)</summary>
|
||||||
|
RoomType RoomType { get; }
|
||||||
|
|
||||||
|
/// <summary>模组容纳人数</summary>
|
||||||
|
int MaxUsers { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 建房:由宿主创建对局会话后调用,模组在此创建并返回 GamingQueue(装配角色、连接确认、启动流程)<para/>
|
||||||
|
/// args[0] = 宿主装配好的参与角色 List<Character>;args[1] = 可选 GameMap
|
||||||
|
/// </summary>
|
||||||
|
Task<GamingQueue> StartGameAsync(IGameSession session, params object[] args);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 处理客户端局内消息(switch-case <see cref="GamingType"/>)<para/>
|
||||||
|
/// 返回的字典由宿主原样回复给发起客户端;返回 null 表示不处理
|
||||||
|
/// </summary>
|
||||||
|
Task<Dictionary<string, object>?> HandleGamingMessageAsync(IGameSession session, IClientSession client, GamingType type, Dictionary<string, object> data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
using FunGame.Core.Entity;
|
||||||
|
using FunGame.Core.Model.Queue;
|
||||||
|
using FunGame.Server.Contracts.Gaming;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Contracts.Plugins;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 所有加载项(服务器插件 / 角色·技能·物品模组)的公共基接口
|
||||||
|
/// </summary>
|
||||||
|
public interface IPluginBase
|
||||||
|
{
|
||||||
|
string Name { get; }
|
||||||
|
string Version { get; }
|
||||||
|
string Author { get; }
|
||||||
|
string Description { get; }
|
||||||
|
|
||||||
|
/// <summary>加载:接收宿主服务(可取得日志、配置、数据库等)</summary>
|
||||||
|
void OnLoad(IServiceProvider services);
|
||||||
|
|
||||||
|
/// <summary>卸载:释放资源(随后框架会卸载其 AssemblyLoadContext)</summary>
|
||||||
|
void OnUnload();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 服务器插件(合并 v2 的 WebAPIPlugin 与 GameModuleServer)<para/>
|
||||||
|
/// - HTTP:通过 <see cref="IPluginHttpHandlerRegistry"/> 注册动态端点(挂载在 /plugin/{name}/ 下,支持热卸载)<para/>
|
||||||
|
/// - WebSocket:通过 <see cref="IMessageHandlerRegistry"/> 注册消息处理器<para/>
|
||||||
|
/// - 对局:实现 <see cref="HandleGamingMessage"/> 作为游戏模式参与对局逻辑
|
||||||
|
/// </summary>
|
||||||
|
public interface IServerPlugin : IPluginBase
|
||||||
|
{
|
||||||
|
/// <summary>注册 HTTP 端点与 WebSocket 消息处理器</summary>
|
||||||
|
void ConfigureEndpoints(IPluginHttpHandlerRegistry http, IMessageHandlerRegistry messages);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 对局消息处理(游戏模式插件实现)<para/>
|
||||||
|
/// 当宿主为对局选择此插件为模式时,局内客户端消息会转发到这里;
|
||||||
|
/// 返回 null 表示插件不处理该消息。
|
||||||
|
/// </summary>
|
||||||
|
Task<Dictionary<string, object>?> HandleGamingMessage(IGameSession session, string type, Dictionary<string, object> data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 实体模组(角色/技能/物品):DLL 热重载通道的加载项接口<para/>
|
||||||
|
/// 与实体 JSON 配置(EntityModuleConfig)通道平行;实体以工厂注册方式保持模块化
|
||||||
|
/// </summary>
|
||||||
|
public interface IEntityModule<T> : IPluginBase where T : BaseEntity
|
||||||
|
{
|
||||||
|
/// <summary>模组提供的实体集合(key 为实体唯一名,供宿主/工厂使用)</summary>
|
||||||
|
IReadOnlyDictionary<string, T> Entities { get; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>角色模组</summary>
|
||||||
|
public interface ICharacterModule : IEntityModule<Character>;
|
||||||
|
|
||||||
|
/// <summary>技能模组</summary>
|
||||||
|
public interface ISkillModule : IEntityModule<Skill>;
|
||||||
|
|
||||||
|
/// <summary>物品模组</summary>
|
||||||
|
public interface IItemModule : IEntityModule<Item>;
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
using FunGame.Server.Contracts.Networking;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Contracts.Plugins;
|
||||||
|
|
||||||
|
/// <summary>WebSocket 消息处理器</summary>
|
||||||
|
public delegate Task<MessageEnvelope?> MessageHandler(IClientSession client, MessageEnvelope message);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// WebSocket 消息处理器注册表(插件热卸载时按 owner 移除全部注册)
|
||||||
|
/// </summary>
|
||||||
|
public interface IMessageHandlerRegistry
|
||||||
|
{
|
||||||
|
void Register(string messageType, object owner, MessageHandler handler);
|
||||||
|
void UnregisterAll(object owner);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>插件 HTTP 端点处理器(直接操作 HttpContext,实现完全自定义)</summary>
|
||||||
|
public delegate Task PluginHttpHandler(HttpContext context);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 插件 HTTP 端点注册表(挂载在 /plugin/{name}/{path} 下)<para/>
|
||||||
|
/// 采用注册表 + 单一路由分发,保证端点可热添加/热移除
|
||||||
|
/// </summary>
|
||||||
|
public interface IPluginHttpHandlerRegistry
|
||||||
|
{
|
||||||
|
/// <param name="method">HTTP 方法(GET/POST/...,大小写不敏感)</param>
|
||||||
|
/// <param name="path">相对插件的路径(如 "hello"),匹配 /plugin/{name}/hello</param>
|
||||||
|
void Register(string method, string path, object owner, PluginHttpHandler handler);
|
||||||
|
void UnregisterAll(object owner);
|
||||||
|
}
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using FunGame.Server.Infrastructure.Data;
|
||||||
|
using FunGame.Server.Infrastructure.Entities.Identity;
|
||||||
|
using Microsoft.AspNetCore.Identity;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Auth;
|
||||||
|
|
||||||
|
/// <summary>认证结果</summary>
|
||||||
|
public record AuthResult(bool Success, string? Message = null, long? UserId = null, string? AccessToken = null, string? RefreshToken = null);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 认证服务:注册 / 登录 / 刷新 / 登出<para/>
|
||||||
|
/// - 密码 PBKDF2(PasswordHasher)<para/>
|
||||||
|
/// - 刷新令牌散列入库、支持撤销与设备维度<para/>
|
||||||
|
/// - 多端统一:WebUI / WebAPI / WebSocket 均通过本服务登录
|
||||||
|
/// </summary>
|
||||||
|
public class AuthService(
|
||||||
|
AppDbContext db,
|
||||||
|
JwtService jwtService,
|
||||||
|
PasswordHasher<User> passwordHasher,
|
||||||
|
IConfiguration configuration,
|
||||||
|
ILogger<AuthService> logger)
|
||||||
|
{
|
||||||
|
private readonly int _refreshTokenDays = int.TryParse(configuration["Jwt:RefreshTokenDays"], out int days) ? days : 14;
|
||||||
|
|
||||||
|
/// <summary>注册</summary>
|
||||||
|
public async Task<AuthResult> RegisterAsync(string username, string password, string email = "", string nickname = "", string ipAddress = "", string userAgent = "", string device = "", string endpoint = "api")
|
||||||
|
{
|
||||||
|
username = username.Trim();
|
||||||
|
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
|
||||||
|
{
|
||||||
|
return new(false, "用户名和密码不能为空。");
|
||||||
|
}
|
||||||
|
if (await db.Users.AnyAsync(u => u.Username == username))
|
||||||
|
{
|
||||||
|
return new(false, "此账号名已被使用!");
|
||||||
|
}
|
||||||
|
if (email != "" && await db.Users.AnyAsync(u => u.Email == email))
|
||||||
|
{
|
||||||
|
return new(false, "此邮箱已被注册!");
|
||||||
|
}
|
||||||
|
|
||||||
|
User user = new()
|
||||||
|
{
|
||||||
|
Username = username,
|
||||||
|
Email = email,
|
||||||
|
EmailVerified = email == "",
|
||||||
|
Nickname = nickname == "" ? username : nickname
|
||||||
|
};
|
||||||
|
user.PasswordHash = passwordHasher.HashPassword(user, password);
|
||||||
|
|
||||||
|
// 默认角色:user
|
||||||
|
Role? defaultRole = await db.Roles.FirstOrDefaultAsync(r => r.Code == DbSeedService.UserRoleCode);
|
||||||
|
if (defaultRole != null)
|
||||||
|
{
|
||||||
|
user.UserRoles.Add(new UserRole { RoleId = defaultRole.Id });
|
||||||
|
}
|
||||||
|
|
||||||
|
db.Users.Add(user);
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
|
||||||
|
await WriteLoginLogAsync(user.Id, username, true, null, ipAddress, userAgent, device);
|
||||||
|
return await LoginCoreAsync(user, ipAddress, userAgent, device, endpoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>登录</summary>
|
||||||
|
public async Task<AuthResult> LoginAsync(string username, string password, string ipAddress = "", string userAgent = "", string device = "", string endpoint = "api")
|
||||||
|
{
|
||||||
|
username = username.Trim();
|
||||||
|
User? user = await db.Users.FirstOrDefaultAsync(u => u.Username == username);
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
await WriteLoginLogAsync(null, username, false, "用户名或密码不正确", ipAddress, userAgent, device);
|
||||||
|
return new(false, "用户名或密码不正确。");
|
||||||
|
}
|
||||||
|
|
||||||
|
PasswordVerificationResult verifyResult = passwordHasher.VerifyHashedPassword(user, user.PasswordHash, password);
|
||||||
|
if (verifyResult == PasswordVerificationResult.Failed)
|
||||||
|
{
|
||||||
|
await WriteLoginLogAsync(user.Id, username, false, "用户名或密码不正确", ipAddress, userAgent, device);
|
||||||
|
return new(false, "用户名或密码不正确。");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user.Status != UserStatus.Active)
|
||||||
|
{
|
||||||
|
await WriteLoginLogAsync(user.Id, username, false, "账号已被封禁或禁用", ipAddress, userAgent, device);
|
||||||
|
return new(false, "账号已被封禁或禁用。");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 密码散列需要升级时自动重新散列
|
||||||
|
if (verifyResult == PasswordVerificationResult.SuccessRehashNeeded)
|
||||||
|
{
|
||||||
|
user.PasswordHash = passwordHasher.HashPassword(user, password);
|
||||||
|
}
|
||||||
|
|
||||||
|
await WriteLoginLogAsync(user.Id, username, true, null, ipAddress, userAgent, device);
|
||||||
|
return await LoginCoreAsync(user, ipAddress, userAgent, device, endpoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<AuthResult> LoginCoreAsync(User user, string ipAddress, string userAgent, string device, string endpoint)
|
||||||
|
{
|
||||||
|
(IReadOnlyCollection<string> roles, IReadOnlyCollection<string> permissions) = await GetRoleAndPermissionsAsync(user.Id);
|
||||||
|
|
||||||
|
string jti = Guid.NewGuid().ToString("N");
|
||||||
|
string accessToken = jwtService.CreateAccessToken(user.Id, user.Username, roles, permissions, jti);
|
||||||
|
string refreshToken = GenerateRefreshToken();
|
||||||
|
|
||||||
|
db.RefreshTokens.Add(new RefreshToken
|
||||||
|
{
|
||||||
|
UserId = user.Id,
|
||||||
|
TokenHash = HashToken(refreshToken),
|
||||||
|
Endpoint = endpoint,
|
||||||
|
Device = device,
|
||||||
|
IpAddress = ipAddress,
|
||||||
|
UserAgent = userAgent,
|
||||||
|
ExpiresAt = DateTime.Now.AddDays(_refreshTokenDays)
|
||||||
|
});
|
||||||
|
|
||||||
|
db.UserSessions.Add(new UserSession
|
||||||
|
{
|
||||||
|
UserId = user.Id,
|
||||||
|
Endpoint = endpoint,
|
||||||
|
Device = device,
|
||||||
|
IpAddress = ipAddress,
|
||||||
|
UserAgent = userAgent,
|
||||||
|
AccessTokenId = jti
|
||||||
|
});
|
||||||
|
|
||||||
|
user.LastLoginAt = DateTime.Now;
|
||||||
|
user.LastLoginIp = ipAddress;
|
||||||
|
user.UpdatedAt = DateTime.Now;
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
|
||||||
|
logger.LogInformation("用户登录成功:{Username}({Endpoint})", user.Username, endpoint);
|
||||||
|
return new(true, null, user.Id, accessToken, refreshToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>刷新令牌(旋转:旧令牌立即撤销)</summary>
|
||||||
|
public async Task<AuthResult> RefreshAsync(string refreshToken, string ipAddress = "", string userAgent = "", string device = "", string endpoint = "api")
|
||||||
|
{
|
||||||
|
string hash = HashToken(refreshToken);
|
||||||
|
RefreshToken? token = await db.RefreshTokens.FirstOrDefaultAsync(t => t.TokenHash == hash);
|
||||||
|
|
||||||
|
if (token == null || token.IsRevoked || token.IsExpired)
|
||||||
|
{
|
||||||
|
return new(false, "刷新令牌无效或已过期。");
|
||||||
|
}
|
||||||
|
|
||||||
|
User? user = await db.Users.FindAsync(token.UserId);
|
||||||
|
if (user == null || user.Status != UserStatus.Active)
|
||||||
|
{
|
||||||
|
return new(false, "账号不存在或已被禁用。");
|
||||||
|
}
|
||||||
|
|
||||||
|
token.RevokedAt = DateTime.Now;
|
||||||
|
|
||||||
|
(IReadOnlyCollection<string> roles, IReadOnlyCollection<string> permissions) = await GetRoleAndPermissionsAsync(user.Id);
|
||||||
|
|
||||||
|
string jti = Guid.NewGuid().ToString("N");
|
||||||
|
string accessToken = jwtService.CreateAccessToken(user.Id, user.Username, roles, permissions, jti);
|
||||||
|
string newRefreshToken = GenerateRefreshToken();
|
||||||
|
|
||||||
|
db.RefreshTokens.Add(new RefreshToken
|
||||||
|
{
|
||||||
|
UserId = user.Id,
|
||||||
|
TokenHash = HashToken(newRefreshToken),
|
||||||
|
Endpoint = endpoint,
|
||||||
|
Device = device,
|
||||||
|
IpAddress = ipAddress,
|
||||||
|
UserAgent = userAgent,
|
||||||
|
ExpiresAt = DateTime.Now.AddDays(_refreshTokenDays)
|
||||||
|
});
|
||||||
|
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
|
||||||
|
return new(true, null, user.Id, accessToken, newRefreshToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>登出(撤销刷新令牌)</summary>
|
||||||
|
public async Task<bool> LogoutAsync(long userId, string? refreshToken = null)
|
||||||
|
{
|
||||||
|
if (refreshToken != null)
|
||||||
|
{
|
||||||
|
string hash = HashToken(refreshToken);
|
||||||
|
RefreshToken? token = await db.RefreshTokens.FirstOrDefaultAsync(t => t.TokenHash == hash && t.UserId == userId);
|
||||||
|
if (token != null)
|
||||||
|
{
|
||||||
|
token.RevokedAt = DateTime.Now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>用户角色与权限聚合</summary>
|
||||||
|
public async Task<(IReadOnlyCollection<string> Roles, IReadOnlyCollection<string> Permissions)> GetRoleAndPermissionsAsync(long userId)
|
||||||
|
{
|
||||||
|
List<string> roles = await db.UserRoles
|
||||||
|
.Where(ur => ur.UserId == userId)
|
||||||
|
.Select(ur => ur.Role!.Code)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
List<long> roleIds = await db.UserRoles
|
||||||
|
.Where(ur => ur.UserId == userId)
|
||||||
|
.Select(ur => ur.RoleId)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
List<string> permissions = await db.RolePermissions
|
||||||
|
.Where(rp => roleIds.Contains(rp.RoleId))
|
||||||
|
.Select(rp => rp.Permission!.Code)
|
||||||
|
.Distinct()
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
return (roles, permissions);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>校验 API 令牌(外部服务接入,散列比对)</summary>
|
||||||
|
public async Task<bool> ValidateApiTokenAsync(string tokenId, string secretKey)
|
||||||
|
{
|
||||||
|
ApiToken? token = await db.ApiTokens.FirstOrDefaultAsync(t => t.TokenId == tokenId);
|
||||||
|
if (token == null || token.RevokedAt != null) return false;
|
||||||
|
if (token.ExpiresAt != null && token.ExpiresAt < DateTime.Now) return false;
|
||||||
|
return HashToken(secretKey) == token.TokenHash;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task WriteLoginLogAsync(long? userId, string username, bool success, string? reason, string ipAddress, string userAgent, string device)
|
||||||
|
{
|
||||||
|
db.LoginLogs.Add(new LoginLog
|
||||||
|
{
|
||||||
|
UserId = userId,
|
||||||
|
Username = username,
|
||||||
|
Success = success,
|
||||||
|
Reason = reason,
|
||||||
|
IpAddress = ipAddress,
|
||||||
|
UserAgent = userAgent,
|
||||||
|
Device = device
|
||||||
|
});
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string GenerateRefreshToken() => Convert.ToBase64String(RandomNumberGenerator.GetBytes(48));
|
||||||
|
|
||||||
|
private static string HashToken(string token) => Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(token))).ToLowerInvariant();
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
using System.IdentityModel.Tokens.Jwt;
|
||||||
|
using System.Security.Claims;
|
||||||
|
using System.Text;
|
||||||
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Auth;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// JWT 服务:多端统一验证的基础(WebUI / WebAPI / WebSocket 共用同一套签发与校验)
|
||||||
|
/// </summary>
|
||||||
|
public class JwtService(IConfiguration configuration)
|
||||||
|
{
|
||||||
|
private readonly string _key = configuration["Jwt:Key"] ?? throw new InvalidOperationException("未配置 Jwt:Key。");
|
||||||
|
private readonly string _issuer = configuration["Jwt:Issuer"] ?? "FunGame.Server";
|
||||||
|
private readonly string _audience = configuration["Jwt:Audience"] ?? "FunGame.Server.Clients";
|
||||||
|
private readonly int _accessTokenMinutes = int.TryParse(configuration["Jwt:AccessTokenMinutes"], out int minutes) ? minutes : 30;
|
||||||
|
|
||||||
|
public int AccessTokenMinutes => _accessTokenMinutes;
|
||||||
|
|
||||||
|
public TokenValidationParameters TokenValidationParameters => new()
|
||||||
|
{
|
||||||
|
ValidateIssuer = true,
|
||||||
|
ValidateAudience = true,
|
||||||
|
ValidateLifetime = true,
|
||||||
|
ValidateIssuerSigningKey = true,
|
||||||
|
ValidIssuer = _issuer,
|
||||||
|
ValidAudience = _audience,
|
||||||
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_key)),
|
||||||
|
NameClaimType = ClaimTypes.NameIdentifier,
|
||||||
|
ClockSkew = TimeSpan.FromMinutes(1)
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 签发 AccessToken(claims:sub=用户Id、name=用户名、role=角色、perm=权限点、jti=令牌Id)
|
||||||
|
/// </summary>
|
||||||
|
public string CreateAccessToken(long userId, string username, IEnumerable<string> roles, IEnumerable<string> permissions, string? jti = null)
|
||||||
|
{
|
||||||
|
jti ??= Guid.NewGuid().ToString("N");
|
||||||
|
List<Claim> claims =
|
||||||
|
[
|
||||||
|
new(ClaimTypes.NameIdentifier, userId.ToString()),
|
||||||
|
new(ClaimTypes.Name, username),
|
||||||
|
new(JwtRegisteredClaimNames.Jti, jti),
|
||||||
|
.. roles.Select(r => new Claim("role", r)),
|
||||||
|
.. permissions.Distinct().Select(p => new Claim("perm", p))
|
||||||
|
];
|
||||||
|
|
||||||
|
JwtSecurityToken token = new(
|
||||||
|
issuer: _issuer,
|
||||||
|
audience: _audience,
|
||||||
|
claims: claims,
|
||||||
|
notBefore: DateTime.UtcNow,
|
||||||
|
expires: DateTime.UtcNow.AddMinutes(_accessTokenMinutes),
|
||||||
|
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_key)), SecurityAlgorithms.HmacSha256));
|
||||||
|
|
||||||
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>校验 AccessToken,返回主体(无效返回 null)</summary>
|
||||||
|
public ClaimsPrincipal? Validate(string token)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return new JwtSecurityTokenHandler().ValidateToken(token, TokenValidationParameters, out _);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>从主体读取用户 Id</summary>
|
||||||
|
public static long? GetUserId(ClaimsPrincipal principal)
|
||||||
|
{
|
||||||
|
string? value = principal.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||||
|
return long.TryParse(value, out long id) ? id : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>从主体读取权限点集合</summary>
|
||||||
|
public static IReadOnlyCollection<string> GetPermissions(ClaimsPrincipal principal)
|
||||||
|
=> principal.FindAll("perm").Select(c => c.Value).ToHashSet();
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Filters;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Auth;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 权限校验特性:标注在控制器或动作上,多个标注为 AND 关系
|
||||||
|
/// </summary>
|
||||||
|
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
|
||||||
|
public class PermissionAttribute(string code) : Attribute
|
||||||
|
{
|
||||||
|
public string Code { get; } = code;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 权限过滤器:校验 JWT 中的 perm Claim(配合 [Permission("code")])
|
||||||
|
/// </summary>
|
||||||
|
public class PermissionFilter : IAsyncAuthorizationFilter
|
||||||
|
{
|
||||||
|
public Task OnAuthorizationAsync(AuthorizationFilterContext context)
|
||||||
|
{
|
||||||
|
// [AllowAnonymous] 端点直接放行(登录/注册等)
|
||||||
|
if (context.ActionDescriptor.EndpointMetadata.OfType<IAllowAnonymous>().Any())
|
||||||
|
{
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (context.HttpContext.User.Identity?.IsAuthenticated != true)
|
||||||
|
{
|
||||||
|
context.Result = new UnauthorizedResult();
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
string[] required = context.ActionDescriptor.EndpointMetadata
|
||||||
|
.OfType<PermissionAttribute>()
|
||||||
|
.Select(a => a.Code)
|
||||||
|
.Distinct()
|
||||||
|
.ToArray();
|
||||||
|
|
||||||
|
if (required.Length > 0)
|
||||||
|
{
|
||||||
|
HashSet<string> owned = context.HttpContext.User.FindAll("perm")
|
||||||
|
.Select(c => c.Value)
|
||||||
|
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
if (required.Any(code => !owned.Contains(code)))
|
||||||
|
{
|
||||||
|
context.Result = new ObjectResult(ApiResponse.Fail(403, $"缺少权限:{string.Join("、", required.Where(code => !owned.Contains(code)))}"))
|
||||||
|
{
|
||||||
|
StatusCode = StatusCodes.Status403Forbidden
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
using FunGame.Server.Contracts.Constants;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
using FunGame.Server.Host.Auth;
|
||||||
|
using FunGame.Server.Host.Networking;
|
||||||
|
using FunGame.Server.Host.Services;
|
||||||
|
using FunGame.Server.PluginHost;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Controllers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 插件与模组管理(始终热重载)
|
||||||
|
/// </summary>
|
||||||
|
[Route("api/admin/plugins")]
|
||||||
|
[Permission(PermissionCodes.PluginsManage)]
|
||||||
|
public class PluginController(PluginManager pluginManager) : ControllerBase
|
||||||
|
{
|
||||||
|
/// <summary>GET /api/admin/plugins</summary>
|
||||||
|
[HttpGet]
|
||||||
|
public IActionResult List()
|
||||||
|
{
|
||||||
|
var items = pluginManager.Items.Select(d => new
|
||||||
|
{
|
||||||
|
d.Name,
|
||||||
|
d.Version,
|
||||||
|
d.Author,
|
||||||
|
d.Description,
|
||||||
|
Kind = d.Kind.ToString(),
|
||||||
|
Status = d.Status.ToString(),
|
||||||
|
d.Error,
|
||||||
|
d.LoadedAt,
|
||||||
|
d.ActiveGames,
|
||||||
|
d.AssemblyPath
|
||||||
|
});
|
||||||
|
return Ok(ApiResponse.Success(items));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>POST /api/admin/plugins/{name}/reload</summary>
|
||||||
|
[HttpPost("{name}/reload")]
|
||||||
|
public IActionResult Reload(string name)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
PluginDescriptor? descriptor = pluginManager.Reload(name);
|
||||||
|
if (descriptor == null)
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, $"加载项 {name} 不存在。"));
|
||||||
|
}
|
||||||
|
return Ok(ApiResponse.Success(new
|
||||||
|
{
|
||||||
|
descriptor.Name,
|
||||||
|
descriptor.Version,
|
||||||
|
Status = descriptor.Status.ToString(),
|
||||||
|
descriptor.Error
|
||||||
|
}, $"加载项 {name} 已热重载。"));
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
return Conflict(ApiResponse.Fail(409, e.Message));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>POST /api/admin/plugins/{name}/unload</summary>
|
||||||
|
[HttpPost("{name}/unload")]
|
||||||
|
public IActionResult Unload(string name)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
pluginManager.Unload(name);
|
||||||
|
return Ok(ApiResponse.Success<object?>(null, $"加载项 {name} 已卸载。"));
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
return Conflict(ApiResponse.Fail(409, e.Message));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>POST /api/admin/plugins/reload-all</summary>
|
||||||
|
[HttpPost("reload-all")]
|
||||||
|
public IActionResult ReloadAll()
|
||||||
|
{
|
||||||
|
pluginManager.ReloadAll();
|
||||||
|
return Ok(ApiResponse.Success<object?>(null, "已触发全部加载项热重载。"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 服务器管理(仪表盘数据:会话/对局/概览)
|
||||||
|
/// </summary>
|
||||||
|
[Route("api/admin/server")]
|
||||||
|
[Permission(PermissionCodes.UsersRead)]
|
||||||
|
public class ServerController(
|
||||||
|
SessionManager sessions,
|
||||||
|
GameHostService gameHost,
|
||||||
|
FunGame.Server.Infrastructure.Data.AppDbContext db) : ControllerBase
|
||||||
|
{
|
||||||
|
/// <summary>GET /api/admin/server/overview</summary>
|
||||||
|
[HttpGet("overview")]
|
||||||
|
public async Task<IActionResult> Overview()
|
||||||
|
{
|
||||||
|
long userCount = await db.Users.LongCountAsync();
|
||||||
|
long gameCount = await db.GameRecords.LongCountAsync();
|
||||||
|
int runningGames = gameHost.Games.Count(g => g.Running);
|
||||||
|
|
||||||
|
return Ok(ApiResponse.Success(new
|
||||||
|
{
|
||||||
|
connections = sessions.Count,
|
||||||
|
authenticated = sessions.Sessions.Count(s => s.IsAuthenticated),
|
||||||
|
userCount,
|
||||||
|
gameCount,
|
||||||
|
runningGames
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>GET /api/admin/server/sessions</summary>
|
||||||
|
[HttpGet("sessions")]
|
||||||
|
public IActionResult Sessions()
|
||||||
|
{
|
||||||
|
var list = sessions.Sessions.Select(s => new
|
||||||
|
{
|
||||||
|
s.SessionId,
|
||||||
|
s.UserId,
|
||||||
|
s.Username,
|
||||||
|
s.RemoteAddress,
|
||||||
|
s.ConnectedAt,
|
||||||
|
s.LastActiveAt,
|
||||||
|
s.Permissions
|
||||||
|
});
|
||||||
|
return Ok(ApiResponse.Success(list));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>POST /api/admin/server/sessions/{sessionId}/kick</summary>
|
||||||
|
[HttpPost("sessions/{sessionId:long}/kick")]
|
||||||
|
[Permission(PermissionCodes.UsersWrite)]
|
||||||
|
public async Task<IActionResult> Kick(long sessionId)
|
||||||
|
{
|
||||||
|
ClientSession? session = sessions.Get(sessionId);
|
||||||
|
if (session == null)
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, $"会话 {sessionId} 不存在。"));
|
||||||
|
}
|
||||||
|
await session.SendAsync(MessageEnvelope.Broadcast(MessageTypes.Kick, new Dictionary<string, object> { ["reason"] = "已被管理员踢出。" }));
|
||||||
|
await session.CloseAsync("kicked by admin");
|
||||||
|
return Ok(ApiResponse.Success<object?>(null, "已踢出会话。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>GET /api/admin/server/games</summary>
|
||||||
|
[HttpGet("games")]
|
||||||
|
public IActionResult Games()
|
||||||
|
{
|
||||||
|
var list = gameHost.Games.Select(g => new
|
||||||
|
{
|
||||||
|
g.Id,
|
||||||
|
g.Mode,
|
||||||
|
g.Running,
|
||||||
|
TotalRound = g.Queue.TotalRound,
|
||||||
|
TotalTime = g.Queue.TotalTime,
|
||||||
|
Characters = g.Queue.AllCharacters.Count,
|
||||||
|
Clients = g.Clients.Count
|
||||||
|
});
|
||||||
|
return Ok(ApiResponse.Success(list));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>POST /api/admin/server/games/{id}/end</summary>
|
||||||
|
[HttpPost("games/{id:guid}/end")]
|
||||||
|
[Permission(PermissionCodes.GamesManage)]
|
||||||
|
public async Task<IActionResult> EndGame(Guid id)
|
||||||
|
{
|
||||||
|
bool result = await gameHost.EndGameAsync(id, aborted: true);
|
||||||
|
return result
|
||||||
|
? Ok(ApiResponse.Success<object?>(null, "对局已强制结束。"))
|
||||||
|
: NotFound(ApiResponse.Fail(404, $"对局 {id} 不存在。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>POST /api/admin/server/games/{id}/pause —— 暂停对局(下一回合边界挂起)</summary>
|
||||||
|
[HttpPost("games/{id:guid}/pause")]
|
||||||
|
[Permission(PermissionCodes.GamesManage)]
|
||||||
|
public IActionResult PauseGame(Guid id)
|
||||||
|
{
|
||||||
|
bool result = gameHost.PauseGame(id);
|
||||||
|
return result
|
||||||
|
? Ok(ApiResponse.Success<object?>(null, "对局已暂停。"))
|
||||||
|
: NotFound(ApiResponse.Fail(404, $"对局 {id} 不存在或已结束。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>POST /api/admin/server/games/{id}/resume —— 恢复对局</summary>
|
||||||
|
[HttpPost("games/{id:guid}/resume")]
|
||||||
|
[Permission(PermissionCodes.GamesManage)]
|
||||||
|
public IActionResult ResumeGame(Guid id)
|
||||||
|
{
|
||||||
|
bool result = gameHost.ResumeGame(id);
|
||||||
|
return result
|
||||||
|
? Ok(ApiResponse.Success<object?>(null, "对局已恢复。"))
|
||||||
|
: NotFound(ApiResponse.Fail(404, $"对局 {id} 不存在。"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
using FunGame.Server.Host.Auth;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Controllers;
|
||||||
|
|
||||||
|
public record RegisterRequest(string Username, string Password, string Email = "", string Nickname = "", string Device = "");
|
||||||
|
|
||||||
|
public record LoginRequest(string Username, string Password, string Device = "");
|
||||||
|
|
||||||
|
public record RefreshRequest(string RefreshToken, string Device = "");
|
||||||
|
|
||||||
|
public record LogoutRequest(string? RefreshToken = null);
|
||||||
|
|
||||||
|
public record AuthTokenResponse(string AccessToken, string RefreshToken, long UserId, string Username, string[] Permissions, string[] Roles);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 认证端点(多端统一验证:WebUI / WebAPI / WebSocket 客户端均使用)
|
||||||
|
/// </summary>
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/auth")]
|
||||||
|
public class AuthController(AuthService authService) : ControllerBase
|
||||||
|
{
|
||||||
|
private string ClientIp => HttpContext.Connection.RemoteIpAddress?.ToString() ?? "";
|
||||||
|
private string UserAgent => HttpContext.Request.Headers.UserAgent.ToString();
|
||||||
|
|
||||||
|
/// <summary>POST /api/auth/register</summary>
|
||||||
|
[HttpPost("register")]
|
||||||
|
[AllowAnonymous]
|
||||||
|
public async Task<IActionResult> Register([FromBody] RegisterRequest request)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(request.Username) || string.IsNullOrWhiteSpace(request.Password))
|
||||||
|
{
|
||||||
|
return BadRequest(ApiResponse.Fail(400, "用户名和密码不能为空。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
AuthResult result = await authService.RegisterAsync(
|
||||||
|
request.Username, request.Password, request.Email, request.Nickname,
|
||||||
|
ClientIp, UserAgent, request.Device, "api");
|
||||||
|
|
||||||
|
if (!result.Success)
|
||||||
|
{
|
||||||
|
return BadRequest(ApiResponse.Fail(400, result.Message ?? "注册失败。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(ApiResponse.Success(await BuildTokenResponse(result)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>POST /api/auth/login</summary>
|
||||||
|
[HttpPost("login")]
|
||||||
|
[AllowAnonymous]
|
||||||
|
public async Task<IActionResult> Login([FromBody] LoginRequest request)
|
||||||
|
{
|
||||||
|
AuthResult result = await authService.LoginAsync(
|
||||||
|
request.Username, request.Password,
|
||||||
|
ClientIp, UserAgent, request.Device, "api");
|
||||||
|
|
||||||
|
if (!result.Success)
|
||||||
|
{
|
||||||
|
return Unauthorized(ApiResponse.Fail(401, result.Message ?? "登录失败。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(ApiResponse.Success(await BuildTokenResponse(result)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>POST /api/auth/refresh</summary>
|
||||||
|
[HttpPost("refresh")]
|
||||||
|
[AllowAnonymous]
|
||||||
|
public async Task<IActionResult> Refresh([FromBody] RefreshRequest request)
|
||||||
|
{
|
||||||
|
AuthResult result = await authService.RefreshAsync(
|
||||||
|
request.RefreshToken, ClientIp, UserAgent, request.Device, "api");
|
||||||
|
|
||||||
|
if (!result.Success)
|
||||||
|
{
|
||||||
|
return Unauthorized(ApiResponse.Fail(401, result.Message ?? "刷新失败。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(ApiResponse.Success(await BuildTokenResponse(result)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>POST /api/auth/logout</summary>
|
||||||
|
[HttpPost("logout")]
|
||||||
|
[Authorize]
|
||||||
|
public async Task<IActionResult> Logout([FromBody] LogoutRequest? request)
|
||||||
|
{
|
||||||
|
long userId = JwtService.GetUserId(User) ?? 0;
|
||||||
|
if (userId == 0)
|
||||||
|
{
|
||||||
|
return Unauthorized(ApiResponse.Fail(401, "未登录。"));
|
||||||
|
}
|
||||||
|
await authService.LogoutAsync(userId, request?.RefreshToken);
|
||||||
|
return Ok(ApiResponse.Success<object?>(null, "已登出。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>GET /api/auth/me</summary>
|
||||||
|
[HttpGet("me")]
|
||||||
|
[Authorize]
|
||||||
|
public async Task<IActionResult> Me()
|
||||||
|
{
|
||||||
|
long userId = JwtService.GetUserId(User) ?? 0;
|
||||||
|
if (userId == 0)
|
||||||
|
{
|
||||||
|
return Unauthorized(ApiResponse.Fail(401, "未登录。"));
|
||||||
|
}
|
||||||
|
(IReadOnlyCollection<string> roles, IReadOnlyCollection<string> permissions) = await authService.GetRoleAndPermissionsAsync(userId);
|
||||||
|
return Ok(ApiResponse.Success(new
|
||||||
|
{
|
||||||
|
UserId = userId,
|
||||||
|
Username = User.Identity?.Name,
|
||||||
|
Roles = roles,
|
||||||
|
Permissions = permissions
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<AuthTokenResponse> BuildTokenResponse(AuthResult result)
|
||||||
|
{
|
||||||
|
string username = "";
|
||||||
|
string[] permissions = [];
|
||||||
|
string[] roles = [];
|
||||||
|
if (result.UserId is long userId)
|
||||||
|
{
|
||||||
|
(IReadOnlyCollection<string> roleList, IReadOnlyCollection<string> permList) = await authService.GetRoleAndPermissionsAsync(userId);
|
||||||
|
roles = [.. roleList];
|
||||||
|
permissions = [.. permList];
|
||||||
|
username = HttpContext.RequestServices.GetRequiredService<FunGame.Server.Infrastructure.Data.AppDbContext>()
|
||||||
|
.Users.Where(u => u.Id == userId).Select(u => u.Username).FirstOrDefault() ?? "";
|
||||||
|
}
|
||||||
|
return new AuthTokenResponse(
|
||||||
|
result.AccessToken ?? "",
|
||||||
|
result.RefreshToken ?? "",
|
||||||
|
result.UserId ?? 0,
|
||||||
|
username,
|
||||||
|
permissions,
|
||||||
|
roles);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
using System.Linq.Expressions;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
using FunGame.Server.Infrastructure.Data;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Controllers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 通用 CRUD 控制器基类(每张数据表派生一个控制器即可获得完整 CRUD 接口)<para/>
|
||||||
|
/// 约定:GET 列表(分页/排序)、GET 详情、POST 创建、PUT 更新、DELETE 删除
|
||||||
|
/// </summary>
|
||||||
|
[ApiController]
|
||||||
|
public abstract class CrudControllerBase<TEntity, TKey> : ControllerBase where TEntity : class
|
||||||
|
{
|
||||||
|
protected AppDbContext Db => HttpContext.RequestServices.GetRequiredService<AppDbContext>();
|
||||||
|
|
||||||
|
private DbSet<TEntity> Set => Db.Set<TEntity>();
|
||||||
|
|
||||||
|
/// <summary>派生类可覆写:默认排序属性</summary>
|
||||||
|
protected virtual string DefaultSort => "Id";
|
||||||
|
|
||||||
|
/// <summary>派生类可覆写:查询前置过滤(如软删除、权限过滤)</summary>
|
||||||
|
protected virtual IQueryable<TEntity> ApplyQueryFilters(IQueryable<TEntity> query) => query;
|
||||||
|
|
||||||
|
// ===== 查询 =====
|
||||||
|
|
||||||
|
/// <summary>GET /api/{resource}?page=1&pageSize=20&sort=Id&desc=false</summary>
|
||||||
|
[HttpGet]
|
||||||
|
public virtual async Task<IActionResult> List([FromQuery] int page = 1, [FromQuery] int pageSize = 20, [FromQuery] string? sort = null, [FromQuery] bool desc = false)
|
||||||
|
{
|
||||||
|
page = Math.Max(1, page);
|
||||||
|
pageSize = Math.Clamp(pageSize, 1, 200);
|
||||||
|
|
||||||
|
IQueryable<TEntity> query = ApplyQueryFilters(Set.AsNoTracking());
|
||||||
|
long total = await query.LongCountAsync();
|
||||||
|
|
||||||
|
query = ApplySort(query, sort ?? DefaultSort, desc);
|
||||||
|
List<TEntity> items = await query.Skip((page - 1) * pageSize).Take(pageSize).ToListAsync();
|
||||||
|
|
||||||
|
return Ok(ApiResponse.Success(new PagedData<TEntity>
|
||||||
|
{
|
||||||
|
Page = page,
|
||||||
|
PageSize = pageSize,
|
||||||
|
Total = total,
|
||||||
|
Items = items
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>GET /api/{resource}/{id}</summary>
|
||||||
|
[HttpGet("{id}")]
|
||||||
|
public virtual async Task<IActionResult> Get([FromRoute] TKey id)
|
||||||
|
{
|
||||||
|
TEntity? entity = await Set.FindAsync([id]);
|
||||||
|
if (entity == null)
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, $"{typeof(TEntity).Name} {id} 不存在。"));
|
||||||
|
}
|
||||||
|
return Ok(ApiResponse.Success(entity));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 写入 =====
|
||||||
|
|
||||||
|
/// <summary>POST /api/{resource}</summary>
|
||||||
|
[HttpPost]
|
||||||
|
public virtual async Task<IActionResult> Create([FromBody] TEntity entity)
|
||||||
|
{
|
||||||
|
if (entity == null)
|
||||||
|
{
|
||||||
|
return BadRequest(ApiResponse.Fail(400, "请求体不能为空。"));
|
||||||
|
}
|
||||||
|
Set.Add(entity);
|
||||||
|
await Db.SaveChangesAsync();
|
||||||
|
return Ok(ApiResponse.Success(entity, "创建成功。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>PUT /api/{resource}/{id}</summary>
|
||||||
|
[HttpPut("{id}")]
|
||||||
|
public virtual async Task<IActionResult> Update([FromRoute] TKey id, [FromBody] TEntity entity)
|
||||||
|
{
|
||||||
|
if (entity == null)
|
||||||
|
{
|
||||||
|
return BadRequest(ApiResponse.Fail(400, "请求体不能为空。"));
|
||||||
|
}
|
||||||
|
TEntity? existing = await Set.FindAsync([id]);
|
||||||
|
if (existing == null)
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, $"{typeof(TEntity).Name} {id} 不存在。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Db.Entry(existing).CurrentValues.SetValues(entity);
|
||||||
|
// 主键保持路由值(防篡改)
|
||||||
|
await Db.SaveChangesAsync();
|
||||||
|
return Ok(ApiResponse.Success(existing, "更新成功。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>DELETE /api/{resource}/{id}</summary>
|
||||||
|
[HttpDelete("{id}")]
|
||||||
|
public virtual async Task<IActionResult> Delete([FromRoute] TKey id)
|
||||||
|
{
|
||||||
|
TEntity? entity = await Set.FindAsync([id]);
|
||||||
|
if (entity == null)
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, $"{typeof(TEntity).Name} {id} 不存在。"));
|
||||||
|
}
|
||||||
|
Set.Remove(entity);
|
||||||
|
await Db.SaveChangesAsync();
|
||||||
|
return Ok(ApiResponse.Success<object?>(null, "删除成功。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 辅助 =====
|
||||||
|
|
||||||
|
private static IQueryable<TEntity> ApplySort(IQueryable<TEntity> query, string sort, bool desc)
|
||||||
|
{
|
||||||
|
System.Reflection.PropertyInfo? property = typeof(TEntity).GetProperty(sort,
|
||||||
|
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase);
|
||||||
|
|
||||||
|
if (property == null)
|
||||||
|
{
|
||||||
|
return query;
|
||||||
|
}
|
||||||
|
|
||||||
|
ParameterExpression parameter = Expression.Parameter(typeof(TEntity), "x");
|
||||||
|
MemberExpression member = Expression.Property(parameter, property);
|
||||||
|
LambdaExpression lambda = Expression.Lambda(member, parameter);
|
||||||
|
|
||||||
|
// 通过反射调用 Queryable.OrderBy/OrderByDescending 泛型方法(属性类型编译期未知)
|
||||||
|
string methodName = desc ? "OrderByDescending" : "OrderBy";
|
||||||
|
System.Reflection.MethodInfo method = typeof(Queryable).GetMethods()
|
||||||
|
.First(m => m.Name == methodName && m.IsGenericMethodDefinition && m.GetParameters().Length == 2);
|
||||||
|
System.Reflection.MethodInfo generic = method.MakeGenericMethod(typeof(TEntity), property.PropertyType);
|
||||||
|
return (IQueryable<TEntity>)generic.Invoke(null, [query, lambda])!;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
using FunGame.Server.Contracts.Constants;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
using FunGame.Server.Host.Auth;
|
||||||
|
using FunGame.Server.Infrastructure.Entities.Economy;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Controllers;
|
||||||
|
|
||||||
|
/// <summary>商店 CRUD</summary>
|
||||||
|
[Route("api/stores")]
|
||||||
|
[Permission(PermissionCodes.ConfigManage)]
|
||||||
|
public class StoresController : CrudControllerBase<Store, long>;
|
||||||
|
|
||||||
|
/// <summary>商品 CRUD</summary>
|
||||||
|
[Route("api/goods")]
|
||||||
|
[Permission(PermissionCodes.ConfigManage)]
|
||||||
|
public class GoodsController : CrudControllerBase<Goods, long>;
|
||||||
|
|
||||||
|
/// <summary>商品价格 CRUD</summary>
|
||||||
|
[Route("api/goodsprices")]
|
||||||
|
[Permission(PermissionCodes.ConfigManage)]
|
||||||
|
public class GoodsPricesController : CrudControllerBase<GoodsPrice, long>;
|
||||||
|
|
||||||
|
/// <summary>商店-商品关联 CRUD(复合主键连接表)</summary>
|
||||||
|
[Route("api/storegoods")]
|
||||||
|
[Permission(PermissionCodes.ConfigManage)]
|
||||||
|
public class StoreGoodsController : ControllerBase
|
||||||
|
{
|
||||||
|
private FunGame.Server.Infrastructure.Data.AppDbContext Db => HttpContext.RequestServices.GetRequiredService<FunGame.Server.Infrastructure.Data.AppDbContext>();
|
||||||
|
|
||||||
|
/// <summary>GET /api/storegoods</summary>
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<IActionResult> List() => Ok(ApiResponse.Success(await Db.StoreGoods.AsNoTracking().ToListAsync()));
|
||||||
|
|
||||||
|
/// <summary>GET /api/storegoods/{storeId}/{goodsId}</summary>
|
||||||
|
[HttpGet("{storeId:long}/{goodsId:long}")]
|
||||||
|
public async Task<IActionResult> Get(long storeId, long goodsId)
|
||||||
|
{
|
||||||
|
StoreGoods? item = await Db.StoreGoods.FindAsync([storeId, goodsId]);
|
||||||
|
return item == null ? NotFound(ApiResponse.Fail(404, "关联不存在。")) : Ok(ApiResponse.Success(item));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>POST /api/storegoods</summary>
|
||||||
|
[HttpPost]
|
||||||
|
public async Task<IActionResult> Create([FromBody] StoreGoods item)
|
||||||
|
{
|
||||||
|
if (await Db.StoreGoods.AnyAsync(sg => sg.StoreId == item.StoreId && sg.GoodsId == item.GoodsId))
|
||||||
|
{
|
||||||
|
return BadRequest(ApiResponse.Fail(400, "该关联已存在。"));
|
||||||
|
}
|
||||||
|
Db.StoreGoods.Add(item);
|
||||||
|
await Db.SaveChangesAsync();
|
||||||
|
return Ok(ApiResponse.Success(item, "创建成功。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>PUT /api/storegoods/{storeId}/{goodsId}</summary>
|
||||||
|
[HttpPut("{storeId:long}/{goodsId:long}")]
|
||||||
|
public async Task<IActionResult> Update(long storeId, long goodsId, [FromBody] StoreGoods item)
|
||||||
|
{
|
||||||
|
StoreGoods? existing = await Db.StoreGoods.FindAsync([storeId, goodsId]);
|
||||||
|
if (existing == null)
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, "关联不存在。"));
|
||||||
|
}
|
||||||
|
Db.StoreGoods.Remove(existing);
|
||||||
|
Db.StoreGoods.Add(item);
|
||||||
|
await Db.SaveChangesAsync();
|
||||||
|
return Ok(ApiResponse.Success(item, "更新成功。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>DELETE /api/storegoods/{storeId}/{goodsId}</summary>
|
||||||
|
[HttpDelete("{storeId:long}/{goodsId:long}")]
|
||||||
|
public async Task<IActionResult> Delete(long storeId, long goodsId)
|
||||||
|
{
|
||||||
|
StoreGoods? item = await Db.StoreGoods.FindAsync([storeId, goodsId]);
|
||||||
|
if (item == null)
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, "关联不存在。"));
|
||||||
|
}
|
||||||
|
Db.StoreGoods.Remove(item);
|
||||||
|
await Db.SaveChangesAsync();
|
||||||
|
return Ok(ApiResponse.Success<object?>(null, "删除成功。"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>市场寄售 CRUD</summary>
|
||||||
|
[Route("api/marketitems")]
|
||||||
|
[Permission(PermissionCodes.ConfigManage)]
|
||||||
|
public class MarketItemsController : CrudControllerBase<MarketItem, long>;
|
||||||
|
|
||||||
|
/// <summary>交易报价 CRUD</summary>
|
||||||
|
[Route("api/offers")]
|
||||||
|
[Permission(PermissionCodes.ConfigManage)]
|
||||||
|
public class OffersController : CrudControllerBase<Offer, long>;
|
||||||
|
|
||||||
|
/// <summary>报价条目 CRUD</summary>
|
||||||
|
[Route("api/offeritems")]
|
||||||
|
[Permission(PermissionCodes.ConfigManage)]
|
||||||
|
public class OfferItemsController : CrudControllerBase<OfferItem, long>;
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
using FunGame.Server.Contracts.Constants;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
using FunGame.Server.Host.Auth;
|
||||||
|
using FunGame.Server.Infrastructure.Entities.Game;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Controllers;
|
||||||
|
|
||||||
|
/// <summary>房间 CRUD</summary>
|
||||||
|
[Route("api/rooms")]
|
||||||
|
[Permission(PermissionCodes.UsersRead)]
|
||||||
|
public class RoomsController : CrudControllerBase<RoomEntity, string>
|
||||||
|
{
|
||||||
|
protected override string DefaultSort => "CreatedAt";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>玩家角色库 CRUD</summary>
|
||||||
|
[Route("api/usercharacters")]
|
||||||
|
[Permission(PermissionCodes.UsersRead)]
|
||||||
|
public class UserCharactersController : CrudControllerBase<UserCharacter, long>;
|
||||||
|
|
||||||
|
/// <summary>玩家物品 CRUD</summary>
|
||||||
|
[Route("api/useritems")]
|
||||||
|
[Permission(PermissionCodes.UsersRead)]
|
||||||
|
public class UserItemsController : CrudControllerBase<UserItem, long>;
|
||||||
|
|
||||||
|
/// <summary>库存 CRUD</summary>
|
||||||
|
[Route("api/inventories")]
|
||||||
|
[Permission(PermissionCodes.UsersRead)]
|
||||||
|
public class InventoriesController : CrudControllerBase<Inventory, long>;
|
||||||
|
|
||||||
|
/// <summary>对局记录 CRUD(回放索引)</summary>
|
||||||
|
[Route("api/gamerecords")]
|
||||||
|
[Permission(PermissionCodes.LogsRead)]
|
||||||
|
public class GameRecordsController : CrudControllerBase<GameRecord, Guid>
|
||||||
|
{
|
||||||
|
protected override string DefaultSort => "StartedAt";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>回合记录 CRUD</summary>
|
||||||
|
[Route("api/roundrecords")]
|
||||||
|
[Permission(PermissionCodes.LogsRead)]
|
||||||
|
public class RoundRecordsController : CrudControllerBase<RoundRecordEntity, long>
|
||||||
|
{
|
||||||
|
protected override string DefaultSort => "Round";
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
using FunGame.Server.PluginHost;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Controllers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 模组 / 游戏模式目录:供客户端(测试客户端、未来游戏客户端)创建房间时自选模组<para/>
|
||||||
|
/// 公开接口,无需登录;数据来自 PluginManager 实时加载项(随热重载自动更新)
|
||||||
|
/// </summary>
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/game-modules")]
|
||||||
|
public class GameModulesController(PluginManager plugins) : ControllerBase
|
||||||
|
{
|
||||||
|
/// <summary>GET /api/game-modules —— 可用游戏模式(ServerPlugin)与内容模组(实体模组)列表</summary>
|
||||||
|
[HttpGet]
|
||||||
|
[AllowAnonymous]
|
||||||
|
public IActionResult List()
|
||||||
|
{
|
||||||
|
List<PluginDescriptor> items = [.. plugins.Items];
|
||||||
|
|
||||||
|
// 游戏模式:游戏模式模组(GameModuleServer)或服务器插件(可创建对局的模式,如 melee / example)
|
||||||
|
var modes = items
|
||||||
|
.Where(i => (i.Kind == PluginKind.ServerPlugin || i.Kind == PluginKind.GameModuleServer) && i.Status == PluginStatus.Loaded)
|
||||||
|
.OrderBy(i => i.Name)
|
||||||
|
.Select(i => new ModuleInfoDto(i.Name, i.Version, i.Author, i.Description, i.Kind == PluginKind.GameModuleServer ? "GameModule" : null));
|
||||||
|
|
||||||
|
// 内容模组:角色/技能/物品模组(决定对局内容池,当前全量加载)
|
||||||
|
var modules = items
|
||||||
|
.Where(i => i.Kind != PluginKind.ServerPlugin && i.Status == PluginStatus.Loaded)
|
||||||
|
.OrderBy(i => i.Name)
|
||||||
|
.Select(i => new ModuleInfoDto(i.Name, i.Version, i.Author, i.Description, i.Kind.ToString()));
|
||||||
|
|
||||||
|
return Ok(ApiResponse.Success(new { modes, modules }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public record ModuleInfoDto(string Name, string Version, string Author, string Description, string? Kind);
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
using FunGame.Core.Entity;
|
||||||
|
using FunGame.Core.Model.Framework;
|
||||||
|
using FunGame.Server.Contracts.Constants;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
using FunGame.Server.Host.Auth;
|
||||||
|
using FunGame.Server.Host.Services;
|
||||||
|
using FunGame.Server.Infrastructure.Entities.Game;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Controllers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 回放中心:对局记录、回合摘要、单回合详情、最终统计<para/>
|
||||||
|
/// 数据来源:GameRoundRecordSink 归档(records/*.zip)+ game_records / round_records 表
|
||||||
|
/// </summary>
|
||||||
|
[Route("api/games")]
|
||||||
|
[Permission(PermissionCodes.LogsRead)]
|
||||||
|
public class ReplayController(ReplayArchiveService replay) : ControllerBase
|
||||||
|
{
|
||||||
|
/// <summary>GET /api/games/{id}/meta —— 对局元信息(含全角色清单与队伍)</summary>
|
||||||
|
[HttpGet("{id:guid}/meta")]
|
||||||
|
public async Task<IActionResult> Meta(Guid id)
|
||||||
|
{
|
||||||
|
GameRecord? record = await replay.GetGameRecordAsync(id);
|
||||||
|
if (record == null)
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, $"对局 {id} 不存在。"));
|
||||||
|
}
|
||||||
|
Dictionary<int, RoundRecord>? rounds = replay.ReadRounds(record);
|
||||||
|
if (rounds == null || rounds.Count == 0)
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, "该对局没有回合记录(可能仍在进行中或归档失败)。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
RoundRecord last = rounds.Values.OrderBy(r => r.Round).Last();
|
||||||
|
bool isTeam = last.GameResult.Any(e => e.IsTeam);
|
||||||
|
List<Character> characters = rounds.Values
|
||||||
|
.SelectMany(r => r.AllCharacters)
|
||||||
|
.GroupBy(c => c.Guid)
|
||||||
|
.Select(g => g.First())
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
return Ok(ApiResponse.Success(new
|
||||||
|
{
|
||||||
|
record.Id,
|
||||||
|
record.Mode,
|
||||||
|
record.State,
|
||||||
|
record.StartedAt,
|
||||||
|
record.EndedAt,
|
||||||
|
record.TotalRounds,
|
||||||
|
record.Winner,
|
||||||
|
roundCount = rounds.Count,
|
||||||
|
totalTime = last.TotalTime,
|
||||||
|
modeType = isTeam ? "团队" : "混战",
|
||||||
|
characters = characters.Select(c => new { guid = c.Guid, c.Name, c.NickName, c.Level }).ToList(),
|
||||||
|
teams = last.GameResult.Where(e => e.IsTeam && e.Team != null).Select(e => new { e.Team!.Name, e.Team.Score, e.Team.IsWinner }).ToList()
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>GET /api/games/{id}/rounds/summary?from=&to= —— 回合摘要列表(供时间轴)</summary>
|
||||||
|
[HttpGet("{id:guid}/rounds/summary")]
|
||||||
|
public async Task<IActionResult> Summary(Guid id, [FromQuery] int? from, [FromQuery] int? to)
|
||||||
|
{
|
||||||
|
GameRecord? record = await replay.GetGameRecordAsync(id);
|
||||||
|
if (record == null)
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, $"对局 {id} 不存在。"));
|
||||||
|
}
|
||||||
|
Dictionary<int, RoundRecord>? rounds = replay.ReadRounds(record);
|
||||||
|
if (rounds == null || rounds.Count == 0)
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, "该对局没有回合记录。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 回合号不连续(行动顺序驱动),按真实回合号排序后取区间
|
||||||
|
int[] keys = rounds.Keys.OrderBy(k => k).ToArray();
|
||||||
|
int fromN = Math.Clamp(from ?? 1, keys[0], keys[^1]);
|
||||||
|
int toN = Math.Clamp(to ?? keys[^1], fromN, keys[^1]);
|
||||||
|
|
||||||
|
List<object> list = [];
|
||||||
|
foreach (int n in keys.Where(k => k >= fromN && k <= toN))
|
||||||
|
{
|
||||||
|
RoundRecord r = rounds[n];
|
||||||
|
list.Add(new
|
||||||
|
{
|
||||||
|
r.Round,
|
||||||
|
actorGuid = r.Actor?.Guid.ToString() ?? "",
|
||||||
|
actorName = r.Actor?.NickName ?? r.Actor?.Name ?? "",
|
||||||
|
r.HasKill,
|
||||||
|
damageTotal = Math.Round(r.Damages.Values.Sum(), 2),
|
||||||
|
healTotal = Math.Round(r.Heals.Values.Sum(), 2),
|
||||||
|
actionCount = r.Actions.Count,
|
||||||
|
effectCount = r.Effects.Count + r.ApplyEffects.Count,
|
||||||
|
hasCheckpoint = r.Checkpoint is { Count: > 0 },
|
||||||
|
r.TotalTime
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Ok(ApiResponse.Success(list));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>GET /api/games/{id}/rounds/{n} —— 单回合完整数据(与归档一致的 JSON)</summary>
|
||||||
|
[HttpGet("{id:guid}/rounds/{n:int}")]
|
||||||
|
public async Task<IActionResult> Round(Guid id, int n)
|
||||||
|
{
|
||||||
|
GameRecord? record = await replay.GetGameRecordAsync(id);
|
||||||
|
if (record == null)
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, $"对局 {id} 不存在。"));
|
||||||
|
}
|
||||||
|
Dictionary<int, RoundRecord>? rounds = replay.ReadRounds(record);
|
||||||
|
if (rounds == null || !rounds.TryGetValue(n, out RoundRecord? round))
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, $"回合 {n} 不存在,有效范围 1 ~ {rounds?.Count ?? 0}。"));
|
||||||
|
}
|
||||||
|
return new JsonResult(round, JsonHub.Options);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>GET /api/games/{id}/statistics —— 最终统计(Rating 排行 + 队伍结果)</summary>
|
||||||
|
[HttpGet("{id:guid}/statistics")]
|
||||||
|
public async Task<IActionResult> Statistics(Guid id)
|
||||||
|
{
|
||||||
|
GameRecord? record = await replay.GetGameRecordAsync(id);
|
||||||
|
if (record == null)
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, $"对局 {id} 不存在。"));
|
||||||
|
}
|
||||||
|
Dictionary<int, RoundRecord>? rounds = replay.ReadRounds(record);
|
||||||
|
if (rounds == null || rounds.Count == 0)
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, "该对局没有回合记录。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
RoundRecord last = rounds.Values.OrderBy(r => r.Round).Last();
|
||||||
|
|
||||||
|
// 优先使用归档中的最终统计(statistics.json),回退到回合记录内嵌统计
|
||||||
|
Dictionary<Guid, CharacterStatistics>? statsByGuid = replay.ReadStatistics(record);
|
||||||
|
Dictionary<Guid, string> teamMap = last.TeamMap ?? [];
|
||||||
|
Dictionary<Guid, Character> charactersByGuid = rounds.Values
|
||||||
|
.SelectMany(r => r.AllCharacters)
|
||||||
|
.GroupBy(c => c.Guid)
|
||||||
|
.ToDictionary(g => g.Key, g => g.First());
|
||||||
|
|
||||||
|
List<StatRow> rows = [];
|
||||||
|
if (statsByGuid is { Count: > 0 })
|
||||||
|
{
|
||||||
|
foreach ((Guid guid, CharacterStatistics s) in statsByGuid)
|
||||||
|
{
|
||||||
|
charactersByGuid.TryGetValue(guid, out Character? character);
|
||||||
|
teamMap.TryGetValue(guid, out string? team);
|
||||||
|
rows.Add(ToStatRow(guid, character, team ?? "", s));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
foreach ((Character character, CharacterStatistics s) in last.CharacterStatistics ?? [])
|
||||||
|
{
|
||||||
|
teamMap.TryGetValue(character.Guid, out string? team);
|
||||||
|
rows.Add(ToStatRow(character.Guid, character, team ?? "", s));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows = [.. rows.OrderByDescending(r => r.Rating)];
|
||||||
|
|
||||||
|
return Ok(ApiResponse.Success(new
|
||||||
|
{
|
||||||
|
roundCount = rounds.Count,
|
||||||
|
totalTime = last.TotalTime,
|
||||||
|
winner = record.Winner,
|
||||||
|
gameResult = last.GameResult,
|
||||||
|
rows
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static StatRow ToStatRow(Guid guid, Character? character, string team, CharacterStatistics s) => new(
|
||||||
|
guid.ToString(),
|
||||||
|
character?.Name ?? "",
|
||||||
|
character?.NickName ?? "",
|
||||||
|
team,
|
||||||
|
s.Rating,
|
||||||
|
s.Kills,
|
||||||
|
s.Deaths,
|
||||||
|
s.Assists,
|
||||||
|
s.TotalDamage,
|
||||||
|
s.TotalHeal,
|
||||||
|
s.TotalShield,
|
||||||
|
s.Winrate,
|
||||||
|
s.MVPs,
|
||||||
|
s.LastRank,
|
||||||
|
s.AvgRank,
|
||||||
|
s.LiveRound,
|
||||||
|
s.TotalEarnedMoney,
|
||||||
|
s.DamagePerRound,
|
||||||
|
s.DamagePerSecond,
|
||||||
|
s.ControlTime);
|
||||||
|
|
||||||
|
private record StatRow(
|
||||||
|
string Guid, string Name, string NickName, string Team, double Rating,
|
||||||
|
int Kills, int Deaths, int Assists, double TotalDamage, double TotalHeal, double TotalShield,
|
||||||
|
double Winrate, int Mvps, int LastRank, double AvgRank, int LiveRound, int TotalEarnedMoney,
|
||||||
|
double DamagePerRound, double DamagePerSecond, double ControlTime);
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using FunGame.Server.Contracts.Constants;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
using FunGame.Server.Host.Auth;
|
||||||
|
using FunGame.Server.Infrastructure.Entities.Identity;
|
||||||
|
using FunGame.Server.Infrastructure.Entities.System;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Controllers;
|
||||||
|
|
||||||
|
/// <summary>服务器日志 CRUD</summary>
|
||||||
|
[Route("api/serverlogs")]
|
||||||
|
[Permission(PermissionCodes.LogsRead)]
|
||||||
|
public class ServerLogsController : CrudControllerBase<ServerLog, long>
|
||||||
|
{
|
||||||
|
protected override string DefaultSort => "CreatedAt";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>系统配置 CRUD(Key 为主键)</summary>
|
||||||
|
[Route("api/systemconfigs")]
|
||||||
|
[Permission(PermissionCodes.ConfigManage)]
|
||||||
|
public class SystemConfigsController : CrudControllerBase<SystemConfig, string>
|
||||||
|
{
|
||||||
|
protected override string DefaultSort => "Key";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>验证码 CRUD</summary>
|
||||||
|
[Route("api/verifycodes")]
|
||||||
|
[Permission(PermissionCodes.UsersWrite)]
|
||||||
|
public class VerifyCodesController : CrudControllerBase<VerifyCode, long>;
|
||||||
|
|
||||||
|
/// <summary>每日签到 CRUD</summary>
|
||||||
|
[Route("api/usersignins")]
|
||||||
|
[Permission(PermissionCodes.UsersRead)]
|
||||||
|
public class UserSignInsController : CrudControllerBase<UserSignIn, long>;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// API 令牌管理(创建时生成原始令牌仅返回一次,散列入库)
|
||||||
|
/// </summary>
|
||||||
|
[Route("api/apitokens")]
|
||||||
|
[Permission(PermissionCodes.TokensManage)]
|
||||||
|
public class ApiTokensController : CrudControllerBase<ApiToken, long>
|
||||||
|
{
|
||||||
|
public override async Task<IActionResult> Create([FromBody] ApiToken entity)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(entity.TokenId))
|
||||||
|
{
|
||||||
|
return BadRequest(ApiResponse.Fail(400, "TokenId 不能为空。"));
|
||||||
|
}
|
||||||
|
if (await Db.ApiTokens.AnyAsync(t => t.TokenId == entity.TokenId))
|
||||||
|
{
|
||||||
|
return BadRequest(ApiResponse.Fail(400, "TokenId 已存在。"));
|
||||||
|
}
|
||||||
|
string rawToken = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32));
|
||||||
|
entity.TokenHash = Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(rawToken))).ToLowerInvariant();
|
||||||
|
Db.ApiTokens.Add(entity);
|
||||||
|
await Db.SaveChangesAsync();
|
||||||
|
return Ok(ApiResponse.Success(new { entity, rawToken }, "创建成功,原始令牌仅显示一次,请妥善保管。"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
using FunGame.Server.Contracts.Constants;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
using FunGame.Server.Host.Auth;
|
||||||
|
using FunGame.Server.Infrastructure.Data;
|
||||||
|
using FunGame.Server.Infrastructure.Entities.Identity;
|
||||||
|
using Microsoft.AspNetCore.Identity;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Controllers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 用户管理(CRUD + 角色分配 + 会话管理)
|
||||||
|
/// </summary>
|
||||||
|
[Route("api/users")]
|
||||||
|
[Permission(PermissionCodes.UsersRead)]
|
||||||
|
public class UsersController : CrudControllerBase<User, long>
|
||||||
|
{
|
||||||
|
private readonly PasswordHasher<User> _hasher = new();
|
||||||
|
|
||||||
|
public override async Task<IActionResult> Create([FromBody] User entity)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(entity.Username) || string.IsNullOrWhiteSpace(entity.PasswordHash))
|
||||||
|
{
|
||||||
|
return BadRequest(ApiResponse.Fail(400, "用户名与密码不能为空(密码字段以明文传入,服务端散列存储)。"));
|
||||||
|
}
|
||||||
|
if (await Db.Users.AnyAsync(u => u.Username == entity.Username))
|
||||||
|
{
|
||||||
|
return BadRequest(ApiResponse.Fail(400, "此账号名已被使用!"));
|
||||||
|
}
|
||||||
|
entity.PasswordHash = _hasher.HashPassword(entity, entity.PasswordHash);
|
||||||
|
Db.Users.Add(entity);
|
||||||
|
await Db.SaveChangesAsync();
|
||||||
|
return Ok(ApiResponse.Success(entity, "创建成功。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task<IActionResult> Update(long id, [FromBody] User entity)
|
||||||
|
{
|
||||||
|
User? existing = await Db.Users.FindAsync([id]);
|
||||||
|
if (existing == null)
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, $"用户 {id} 不存在。"));
|
||||||
|
}
|
||||||
|
if (existing.IsSystem)
|
||||||
|
{
|
||||||
|
return BadRequest(ApiResponse.Fail(400, "系统内置账号不可通过此接口修改。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
string? newPassword = entity.PasswordHash;
|
||||||
|
entity.PasswordHash = existing.PasswordHash;
|
||||||
|
Db.Entry(existing).CurrentValues.SetValues(entity);
|
||||||
|
if (!string.IsNullOrWhiteSpace(newPassword))
|
||||||
|
{
|
||||||
|
existing.PasswordHash = _hasher.HashPassword(existing, newPassword);
|
||||||
|
}
|
||||||
|
existing.UpdatedAt = DateTime.Now;
|
||||||
|
await Db.SaveChangesAsync();
|
||||||
|
return Ok(ApiResponse.Success(existing, "更新成功。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task<IActionResult> Delete(long id)
|
||||||
|
{
|
||||||
|
User? user = await Db.Users.FindAsync([id]);
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, $"用户 {id} 不存在。"));
|
||||||
|
}
|
||||||
|
if (user.IsSystem)
|
||||||
|
{
|
||||||
|
return BadRequest(ApiResponse.Fail(400, "系统内置账号不可删除。"));
|
||||||
|
}
|
||||||
|
Db.Users.Remove(user);
|
||||||
|
await Db.SaveChangesAsync();
|
||||||
|
return Ok(ApiResponse.Success<object?>(null, "删除成功。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>GET /api/users/{id}/roles</summary>
|
||||||
|
[HttpGet("{id:long}/roles")]
|
||||||
|
public async Task<IActionResult> GetRoles(long id)
|
||||||
|
{
|
||||||
|
List<Role> roles = await Db.UserRoles.Where(ur => ur.UserId == id).Select(ur => ur.Role!).ToListAsync();
|
||||||
|
return Ok(ApiResponse.Success(roles));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>PUT /api/users/{id}/roles(body: 角色 Id 数组)</summary>
|
||||||
|
[HttpPut("{id:long}/roles")]
|
||||||
|
[Permission(PermissionCodes.UsersWrite)]
|
||||||
|
public async Task<IActionResult> SetRoles(long id, [FromBody] long[] roleIds)
|
||||||
|
{
|
||||||
|
if (!await Db.Users.AnyAsync(u => u.Id == id))
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, $"用户 {id} 不存在。"));
|
||||||
|
}
|
||||||
|
Db.UserRoles.RemoveRange(Db.UserRoles.Where(ur => ur.UserId == id));
|
||||||
|
foreach (long roleId in roleIds.Distinct())
|
||||||
|
{
|
||||||
|
Db.UserRoles.Add(new UserRole { UserId = id, RoleId = roleId });
|
||||||
|
}
|
||||||
|
await Db.SaveChangesAsync();
|
||||||
|
return Ok(ApiResponse.Success<object?>(null, "角色已更新。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>GET /api/users/{id}/sessions</summary>
|
||||||
|
[HttpGet("{id:long}/sessions")]
|
||||||
|
public async Task<IActionResult> GetSessions(long id)
|
||||||
|
{
|
||||||
|
List<UserSession> sessions = await Db.UserSessions.Where(s => s.UserId == id).OrderByDescending(s => s.ConnectedAt).ToListAsync();
|
||||||
|
return Ok(ApiResponse.Success(sessions));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>用户资料 CRUD</summary>
|
||||||
|
[Route("api/userprofiles")]
|
||||||
|
[Permission(PermissionCodes.UsersRead)]
|
||||||
|
public class UserProfilesController : CrudControllerBase<UserProfile, long>;
|
||||||
|
|
||||||
|
/// <summary>用户会话 CRUD</summary>
|
||||||
|
[Route("api/usersessions")]
|
||||||
|
[Permission(PermissionCodes.UsersRead)]
|
||||||
|
public class UserSessionsController : CrudControllerBase<UserSession, long>;
|
||||||
|
|
||||||
|
/// <summary>登录日志 CRUD</summary>
|
||||||
|
[Route("api/loginlogs")]
|
||||||
|
[Permission(PermissionCodes.LogsRead)]
|
||||||
|
public class LoginLogsController : CrudControllerBase<LoginLog, long>;
|
||||||
|
|
||||||
|
/// <summary>刷新令牌 CRUD</summary>
|
||||||
|
[Route("api/refreshtokens")]
|
||||||
|
[Permission(PermissionCodes.UsersWrite)]
|
||||||
|
public class RefreshTokensController : CrudControllerBase<RefreshToken, long>;
|
||||||
|
|
||||||
|
/// <summary>角色管理(CRUD + 权限分配)</summary>
|
||||||
|
[Route("api/roles")]
|
||||||
|
[Permission(PermissionCodes.RolesManage)]
|
||||||
|
public class RolesController : CrudControllerBase<Role, long>
|
||||||
|
{
|
||||||
|
public override async Task<IActionResult> Delete(long id)
|
||||||
|
{
|
||||||
|
Role? role = await Db.Roles.FindAsync([id]);
|
||||||
|
if (role == null)
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, $"角色 {id} 不存在。"));
|
||||||
|
}
|
||||||
|
if (role.IsSystem)
|
||||||
|
{
|
||||||
|
return BadRequest(ApiResponse.Fail(400, "系统内置角色不可删除。"));
|
||||||
|
}
|
||||||
|
Db.Roles.Remove(role);
|
||||||
|
await Db.SaveChangesAsync();
|
||||||
|
return Ok(ApiResponse.Success<object?>(null, "删除成功。"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>GET /api/roles/{id}/permissions</summary>
|
||||||
|
[HttpGet("{id:long}/permissions")]
|
||||||
|
public async Task<IActionResult> GetPermissions(long id)
|
||||||
|
{
|
||||||
|
List<Permission> permissions = await Db.RolePermissions.Where(rp => rp.RoleId == id).Select(rp => rp.Permission!).ToListAsync();
|
||||||
|
return Ok(ApiResponse.Success(permissions));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>PUT /api/roles/{id}/permissions(body: 权限点 Code 数组)</summary>
|
||||||
|
[HttpPut("{id:long}/permissions")]
|
||||||
|
public async Task<IActionResult> SetPermissions(long id, [FromBody] string[] permissionCodes)
|
||||||
|
{
|
||||||
|
if (!await Db.Roles.AnyAsync(r => r.Id == id))
|
||||||
|
{
|
||||||
|
return NotFound(ApiResponse.Fail(404, $"角色 {id} 不存在。"));
|
||||||
|
}
|
||||||
|
List<long> permissionIds = await Db.Permissions
|
||||||
|
.Where(p => permissionCodes.Contains(p.Code))
|
||||||
|
.Select(p => p.Id)
|
||||||
|
.ToListAsync();
|
||||||
|
Db.RolePermissions.RemoveRange(Db.RolePermissions.Where(rp => rp.RoleId == id));
|
||||||
|
foreach (long permissionId in permissionIds)
|
||||||
|
{
|
||||||
|
Db.RolePermissions.Add(new RolePermission { RoleId = id, PermissionId = permissionId });
|
||||||
|
}
|
||||||
|
await Db.SaveChangesAsync();
|
||||||
|
return Ok(ApiResponse.Success<object?>(null, "权限已更新。"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>权限点管理(CRUD)</summary>
|
||||||
|
[Route("api/permissions")]
|
||||||
|
[Permission(PermissionCodes.PermissionsManage)]
|
||||||
|
public class PermissionsController : CrudControllerBase<Permission, long>;
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\FunGame.Server.Contracts\FunGame.Server.Contracts.csproj" />
|
||||||
|
<ProjectReference Include="..\FunGame.Server.Infrastructure\FunGame.Server.Infrastructure.csproj" />
|
||||||
|
<ProjectReference Include="..\FunGame.Server.PluginHost\FunGame.Server.PluginHost.csproj" />
|
||||||
|
<ProjectReference Include="..\..\..\FunGame.Core\FunGame.Core.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.11" />
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.11" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<!-- 实体 JSON 配置(EntityModuleConfig 通道,如 oshima.fungame.items.json)随构建复制到输出目录,
|
||||||
|
使其在 AppDomain.BaseDirectory/modules/{ModuleName}/{FileName}.json 可被 Factory.GetGameModuleInstances 读取 -->
|
||||||
|
<ItemGroup>
|
||||||
|
<None Include="modules/oshima-studios/**" CopyToOutputDirectory="PreserveNewest" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
using FunGame.Core.Api;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 宿主 JSON 中心:复用 Core v3 的 JsonService 转换器(实体/回合记录均可直接序列化)
|
||||||
|
/// </summary>
|
||||||
|
public static class JsonHub
|
||||||
|
{
|
||||||
|
/// <summary>WebSocket 与 REST 负载序列化选项(紧凑、保留 Core 转换器)</summary>
|
||||||
|
public static JsonSerializerOptions Options { get; } = new(JsonService.GeneralOptions)
|
||||||
|
{
|
||||||
|
WriteIndented = false,
|
||||||
|
PropertyNameCaseInsensitive = true
|
||||||
|
};
|
||||||
|
|
||||||
|
public static string Serialize<T>(T value) => JsonSerializer.Serialize(value, Options);
|
||||||
|
|
||||||
|
public static T? Deserialize<T>(string json) => JsonSerializer.Deserialize<T>(json, Options);
|
||||||
|
|
||||||
|
public static byte[] SerializeToUtf8Bytes<T>(T value) => JsonSerializer.SerializeToUtf8Bytes(value, Options);
|
||||||
|
|
||||||
|
/// <summary>把 Core 转换器与循环引用策略应用到指定选项(MVC / Minimal API 配置)</summary>
|
||||||
|
public static void Configure(JsonSerializerOptions options)
|
||||||
|
{
|
||||||
|
options.PropertyNameCaseInsensitive = true;
|
||||||
|
options.ReferenceHandler = ReferenceHandler.IgnoreCycles;
|
||||||
|
options.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(System.Text.Unicode.UnicodeRanges.All);
|
||||||
|
foreach (JsonConverter converter in JsonService.GeneralOptions.Converters)
|
||||||
|
{
|
||||||
|
options.Converters.Add(converter);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>从信封数据字典中取参数</summary>
|
||||||
|
public static T? Get<T>(MessageEnvelope message, string key)
|
||||||
|
=> message.Data.TryGetValue(key, out object? value) && value is JsonElement element
|
||||||
|
? element.Deserialize<T>(Options)
|
||||||
|
: value is T typed ? typed : default;
|
||||||
|
|
||||||
|
public static string? GetString(MessageEnvelope message, string key) => Get<string>(message, key);
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
using FunGame.Server.Infrastructure.Data;
|
||||||
|
using FunGame.Server.Infrastructure.Entities.System;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Logging;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 服务器日志通道:把 ILogger 输出(Information 及以上)写入 server_logs 表,供 WebUI 查看<para/>
|
||||||
|
/// 宿主构建完成后通过 <see cref="Attach"/> 绑定真正的 IServiceScopeFactory(延迟绑定避免重复容器)
|
||||||
|
/// </summary>
|
||||||
|
public class ServerLogsLoggerProvider : ILoggerProvider
|
||||||
|
{
|
||||||
|
private IServiceScopeFactory? _scopeFactory;
|
||||||
|
private readonly Lock _lock = new();
|
||||||
|
|
||||||
|
public void Attach(IServiceScopeFactory scopeFactory)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
_scopeFactory = scopeFactory;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal IServiceScopeFactory? GetScopeFactory()
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
return _scopeFactory;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public ILogger CreateLogger(string categoryName) => new ServerLogsLogger(categoryName, this);
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ServerLogsLogger(string categoryName, ServerLogsLoggerProvider provider) : ILogger
|
||||||
|
{
|
||||||
|
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||||
|
|
||||||
|
public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Information;
|
||||||
|
|
||||||
|
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||||
|
{
|
||||||
|
if (!IsEnabled(logLevel))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
IServiceScopeFactory? scopeFactory = provider.GetScopeFactory();
|
||||||
|
if (scopeFactory == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
string message = formatter(state, exception);
|
||||||
|
if (string.IsNullOrWhiteSpace(message))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (message.Length > 1024)
|
||||||
|
{
|
||||||
|
message = message[..1024];
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using IServiceScope scope = scopeFactory.CreateScope();
|
||||||
|
AppDbContext db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||||
|
db.ServerLogs.Add(new ServerLog
|
||||||
|
{
|
||||||
|
Level = Map(logLevel),
|
||||||
|
Source = ResolveSource(categoryName),
|
||||||
|
Category = categoryName,
|
||||||
|
Message = message,
|
||||||
|
Exception = exception?.ToString()
|
||||||
|
});
|
||||||
|
db.SaveChanges();
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// 日志写入失败绝不能影响业务(如数据库不可用时)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LogLevelEntity Map(LogLevel level) => level switch
|
||||||
|
{
|
||||||
|
LogLevel.Trace => LogLevelEntity.Trace,
|
||||||
|
LogLevel.Debug => LogLevelEntity.Debug,
|
||||||
|
LogLevel.Information => LogLevelEntity.Info,
|
||||||
|
LogLevel.Warning => LogLevelEntity.Warning,
|
||||||
|
LogLevel.Error => LogLevelEntity.Error,
|
||||||
|
LogLevel.Critical => LogLevelEntity.Critical,
|
||||||
|
_ => LogLevelEntity.Info
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string ResolveSource(string category)
|
||||||
|
{
|
||||||
|
if (category.StartsWith("Plugin.")) return "Plugin";
|
||||||
|
if (category.Contains(".PluginHost.")) return "PluginHost";
|
||||||
|
if (category.Contains(".Host.")) return "Host";
|
||||||
|
if (category == "WebSocket") return "Host";
|
||||||
|
return "System";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
using FunGame.Server.Contracts.Networking;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Networking;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 宿主内置 WebSocket 消息处理器(system.ping / system.info / auth.logout)
|
||||||
|
/// </summary>
|
||||||
|
public static class BuiltInMessageHandlers
|
||||||
|
{
|
||||||
|
public static readonly object Owner = new();
|
||||||
|
|
||||||
|
public static void Register(MessageDispatcher dispatcher, IConfiguration configuration)
|
||||||
|
{
|
||||||
|
string serverName = configuration["Server:Name"] ?? "FunGame Server v3";
|
||||||
|
string notice = configuration["Server:Notice"] ?? "";
|
||||||
|
|
||||||
|
dispatcher.Register(MessageTypes.Ping, Owner, async (client, message) =>
|
||||||
|
{
|
||||||
|
return MessageEnvelope.Reply(message, new Dictionary<string, object> { ["time"] = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() });
|
||||||
|
});
|
||||||
|
|
||||||
|
dispatcher.Register(MessageTypes.ServerInfo, Owner, async (client, message) =>
|
||||||
|
{
|
||||||
|
return MessageEnvelope.Reply(message, new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["name"] = serverName,
|
||||||
|
["notice"] = notice,
|
||||||
|
["version"] = "3.0.0-dev"
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
dispatcher.Register(MessageTypes.AuthLogout, Owner, async (client, message) =>
|
||||||
|
{
|
||||||
|
// WS 会话随连接关闭失效;刷新令牌撤销由 REST /api/auth/logout 处理
|
||||||
|
return MessageEnvelope.Reply(message, new Dictionary<string, object> { ["message"] = "已登出,请关闭连接。" });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
using System.Net.WebSockets;
|
||||||
|
using System.Security.Claims;
|
||||||
|
using System.Text;
|
||||||
|
using FunGame.Server.Contracts.Networking;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Networking;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// WebSocket 客户端会话(替代 v2 的 ServerModel<T>)
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ClientSession : IClientSession, IAsyncDisposable
|
||||||
|
{
|
||||||
|
private static long _sessionCounter;
|
||||||
|
private readonly WebSocket _socket;
|
||||||
|
private readonly SemaphoreSlim _sendLock = new(1, 1);
|
||||||
|
private readonly ILogger<ClientSession> _logger;
|
||||||
|
private bool _closed;
|
||||||
|
|
||||||
|
public ClientSession(WebSocket socket, ClaimsPrincipal? principal, string remoteAddress, ILogger<ClientSession> logger)
|
||||||
|
{
|
||||||
|
_socket = socket;
|
||||||
|
_logger = logger;
|
||||||
|
SessionId = Interlocked.Increment(ref _sessionCounter);
|
||||||
|
RemoteAddress = remoteAddress;
|
||||||
|
ConnectedAt = DateTime.Now;
|
||||||
|
LastActiveAt = DateTime.Now;
|
||||||
|
|
||||||
|
if (principal?.Identity?.IsAuthenticated == true)
|
||||||
|
{
|
||||||
|
long? userId = Auth.JwtService.GetUserId(principal);
|
||||||
|
if (userId != null)
|
||||||
|
{
|
||||||
|
UserId = userId;
|
||||||
|
Username = principal.FindFirstValue(ClaimTypes.Name);
|
||||||
|
Permissions = principal.FindAll("perm").Select(c => c.Value).ToHashSet();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public long SessionId { get; }
|
||||||
|
public long? UserId { get; }
|
||||||
|
public string? Username { get; }
|
||||||
|
public IReadOnlyCollection<string> Permissions { get; } = [];
|
||||||
|
public bool IsAuthenticated => UserId != null;
|
||||||
|
public DateTime ConnectedAt { get; }
|
||||||
|
public DateTime LastActiveAt { get; private set; }
|
||||||
|
public string RemoteAddress { get; }
|
||||||
|
public WebSocketState State => _socket.State;
|
||||||
|
|
||||||
|
/// <summary>是否已通过 WS 登录(连接时仅凭 JWT 判定;匿名连接可通过 auth.login 消息登录后由宿主提升会话)</summary>
|
||||||
|
public bool WebSocketAuthenticated { get; set; }
|
||||||
|
|
||||||
|
public async Task<bool> SendAsync(MessageEnvelope message, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (_closed || _socket.State != WebSocketState.Open)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
try
|
||||||
|
{
|
||||||
|
byte[] bytes = JsonHub.SerializeToUtf8Bytes(message);
|
||||||
|
await _sendLock.WaitAsync(cancellationToken);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _socket.SendAsync(bytes, WebSocketMessageType.Text, true, cancellationToken);
|
||||||
|
LastActiveAt = DateTime.Now;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_sendLock.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogDebug(e, "发送消息失败:Session {SessionId}", SessionId);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task CloseAsync(string reason, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (_closed) return;
|
||||||
|
_closed = true;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_socket.State is WebSocketState.Open or WebSocketState.CloseReceived)
|
||||||
|
{
|
||||||
|
await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, reason, cancellationToken);
|
||||||
|
}
|
||||||
|
_socket.Dispose();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogDebug(e, "关闭连接异常:Session {SessionId}", SessionId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>接收一条完整消息(返回 null 表示连接关闭)</summary>
|
||||||
|
public async Task<MessageEnvelope?> ReceiveAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
using MemoryStream stream = new();
|
||||||
|
byte[] buffer = new byte[16 * 1024];
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
WebSocketReceiveResult result;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
result = await _socket.ReceiveAsync(buffer, cancellationToken);
|
||||||
|
}
|
||||||
|
catch (WebSocketException)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.MessageType == WebSocketMessageType.Close)
|
||||||
|
{
|
||||||
|
if (_socket.State == WebSocketState.CloseReceived && !_closed)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "closed", CancellationToken.None);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// 忽略关闭异常
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
await stream.WriteAsync(buffer.AsMemory(0, result.Count), cancellationToken);
|
||||||
|
|
||||||
|
if (result.EndOfMessage)
|
||||||
|
{
|
||||||
|
LastActiveAt = DateTime.Now;
|
||||||
|
string json = Encoding.UTF8.GetString(stream.ToArray());
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return JsonHub.Deserialize<MessageEnvelope>(json);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(e, "解析客户端消息失败:{Json}", json[..Math.Min(json.Length, 256)]);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
_closed = true;
|
||||||
|
_socket.Dispose();
|
||||||
|
_sendLock.Dispose();
|
||||||
|
return ValueTask.CompletedTask;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using FunGame.Server.Contracts.Networking;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
using FunGame.Server.Contracts.Plugins;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Networking;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 消息分发中心:WebSocket 消息处理器注册表 + 插件 HTTP 端点注册表<para/>
|
||||||
|
/// - 内置处理器与插件处理器合并,后者随插件热卸载自动移除<para/>
|
||||||
|
/// - 插件 HTTP 端点统一挂载在 /plugin/{name}/{path},由单一路由分发(支持热添加/移除)
|
||||||
|
/// </summary>
|
||||||
|
public class MessageDispatcher : IMessageHandlerRegistry, IPluginHttpHandlerRegistry
|
||||||
|
{
|
||||||
|
private readonly ConcurrentDictionary<string, (object Owner, MessageHandler Handler)> _messageHandlers = new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
private readonly ConcurrentDictionary<(string Method, string Plugin, string Path), (object Owner, PluginHttpHandler Handler)> _httpHandlers = new();
|
||||||
|
private readonly ILogger<MessageDispatcher> _logger;
|
||||||
|
|
||||||
|
public MessageDispatcher(ILogger<MessageDispatcher> logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== WebSocket 消息处理器 =====
|
||||||
|
|
||||||
|
public void Register(string messageType, object owner, MessageHandler handler)
|
||||||
|
{
|
||||||
|
_messageHandlers[messageType] = (owner, handler);
|
||||||
|
_logger.LogDebug("注册消息处理器:{Type}({Owner})", messageType, owner.GetType().Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
void IMessageHandlerRegistry.UnregisterAll(object owner)
|
||||||
|
{
|
||||||
|
foreach ((string type, (object Owner, MessageHandler Handler) entry) in _messageHandlers)
|
||||||
|
{
|
||||||
|
if (ReferenceEquals(entry.Owner, owner))
|
||||||
|
{
|
||||||
|
_messageHandlers.TryRemove(type, out _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>分发 WS 消息(无处理器返回 null)</summary>
|
||||||
|
public async Task<MessageEnvelope?> DispatchAsync(IClientSession client, MessageEnvelope message)
|
||||||
|
{
|
||||||
|
if (_messageHandlers.TryGetValue(message.Type, out (object Owner, MessageHandler Handler) entry))
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await entry.Handler(client, message);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError(e, "消息处理异常:{Type}({Owner})", message.Type, entry.Owner.GetType().Name);
|
||||||
|
return MessageEnvelope.Reply(message, ok: false, error: new MessageError { Code = "handler_error", Message = "服务器处理消息时发生异常。" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return MessageEnvelope.Reply(message, ok: false, error: new MessageError { Code = "unknown_type", Message = $"未知的消息类型:{message.Type}" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 插件 HTTP 端点 =====
|
||||||
|
|
||||||
|
public void Register(string method, string path, object owner, PluginHttpHandler handler)
|
||||||
|
{
|
||||||
|
string plugin = owner is Contracts.Plugins.IPluginBase pluginBase ? pluginBase.Name : owner.GetType().Name;
|
||||||
|
string normalized = NormalizePath(path);
|
||||||
|
_httpHandlers[(method.ToUpperInvariant(), plugin, normalized)] = (owner, handler);
|
||||||
|
_logger.LogDebug("注册插件端点:{Method} /plugin/{Plugin}/{Path}", method.ToUpperInvariant(), plugin, normalized);
|
||||||
|
}
|
||||||
|
|
||||||
|
void IPluginHttpHandlerRegistry.UnregisterAll(object owner)
|
||||||
|
{
|
||||||
|
foreach (((string Method, string Plugin, string Path) key, (object Owner, PluginHttpHandler Handler) entry) in _httpHandlers)
|
||||||
|
{
|
||||||
|
if (ReferenceEquals(entry.Owner, owner))
|
||||||
|
{
|
||||||
|
_httpHandlers.TryRemove(key, out _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>分发插件 HTTP 请求(/plugin/{plugin}/{**path})</summary>
|
||||||
|
public async Task<bool> DispatchHttpAsync(HttpContext context, string plugin, string path)
|
||||||
|
{
|
||||||
|
string method = context.Request.Method.ToUpperInvariant();
|
||||||
|
string normalized = NormalizePath(path);
|
||||||
|
|
||||||
|
if (_httpHandlers.TryGetValue((method, plugin, normalized), out (object Owner, PluginHttpHandler Handler) entry))
|
||||||
|
{
|
||||||
|
await entry.Handler(context);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
context.Response.StatusCode = StatusCodes.Status404NotFound;
|
||||||
|
await context.Response.WriteAsJsonAsync(ApiResponse.Fail(404, $"端点不存在:{method} /plugin/{plugin}/{normalized}"));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string NormalizePath(string path) => path.Trim('/').ToLowerInvariant();
|
||||||
|
}
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
using FunGame.Core.Entity;
|
||||||
|
using FunGame.Core.Library.Constant;
|
||||||
|
using FunGame.Server.Contracts.Networking;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
using FunGame.Server.Contracts.Plugins;
|
||||||
|
using FunGame.Server.Host.Services;
|
||||||
|
using FunGame.Server.Infrastructure.Entities.Game;
|
||||||
|
using FunGame.Server.PluginHost;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Networking;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 房间 / 匹配 / 聊天 的 WebSocket 业务处理器(新负载模型 MessageEnvelope)
|
||||||
|
/// </summary>
|
||||||
|
public static class RoomMessageHandlers
|
||||||
|
{
|
||||||
|
public static readonly object Owner = new();
|
||||||
|
|
||||||
|
public static void Register(MessageDispatcher dispatcher, IServiceProvider services)
|
||||||
|
{
|
||||||
|
SessionManager sessions = services.GetRequiredService<SessionManager>();
|
||||||
|
RoomService rooms = services.GetRequiredService<RoomService>();
|
||||||
|
GameHostService games = services.GetRequiredService<GameHostService>();
|
||||||
|
EntityCatalog catalog = services.GetRequiredService<EntityCatalog>();
|
||||||
|
CharacterBuildService builder = services.GetRequiredService<CharacterBuildService>();
|
||||||
|
PluginManager plugins = services.GetRequiredService<PluginManager>();
|
||||||
|
ILogger logger = services.GetRequiredService<ILoggerFactory>().CreateLogger("RoomHandlers");
|
||||||
|
|
||||||
|
// ===== 房间列表 =====
|
||||||
|
dispatcher.Register(MessageTypes.RoomList, Owner, async (client, message) =>
|
||||||
|
{
|
||||||
|
List<RoomEntity> list = await rooms.ListRoomsAsync();
|
||||||
|
Dictionary<string, object> data = new()
|
||||||
|
{
|
||||||
|
["rooms"] = list.Select(r => new
|
||||||
|
{
|
||||||
|
r.RoomId,
|
||||||
|
r.MasterUserId,
|
||||||
|
r.GameModule,
|
||||||
|
r.ContentModule,
|
||||||
|
r.GameMap,
|
||||||
|
r.MaxUsers,
|
||||||
|
r.State,
|
||||||
|
r.IsRank,
|
||||||
|
r.CreatedAt,
|
||||||
|
hasPassword = r.PasswordHash != null,
|
||||||
|
members = rooms.GetMembers(r.RoomId).Count
|
||||||
|
}).ToList()
|
||||||
|
};
|
||||||
|
return MessageEnvelope.Reply(message, data);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ===== 创建房间 =====
|
||||||
|
dispatcher.Register(MessageTypes.RoomCreate, Owner, async (client, message) =>
|
||||||
|
{
|
||||||
|
if (client.UserId == null)
|
||||||
|
{
|
||||||
|
return MessageEnvelope.Reply(message, ok: false, error: new MessageError { Code = "unauthorized", Message = "请先登录。" });
|
||||||
|
}
|
||||||
|
string module = JsonHub.GetString(message, "module") ?? "example";
|
||||||
|
string contentModule = JsonHub.GetString(message, "contentModule") ?? "";
|
||||||
|
string map = JsonHub.GetString(message, "map") ?? "";
|
||||||
|
int maxUsers = JsonHub.Get<int>(message, "maxUsers");
|
||||||
|
bool isRank = JsonHub.Get<bool>(message, "isRank");
|
||||||
|
string? password = JsonHub.GetString(message, "password");
|
||||||
|
|
||||||
|
RoomEntity room = await rooms.CreateRoomAsync(client.UserId.Value, module, contentModule, map, maxUsers, isRank, password);
|
||||||
|
(bool joined, _) = await rooms.JoinAsync(room, (ClientSession)client);
|
||||||
|
return MessageEnvelope.Reply(message, new Dictionary<string, object> { ["roomId"] = room.RoomId, ["joined"] = joined });
|
||||||
|
});
|
||||||
|
|
||||||
|
// ===== 进入房间 =====
|
||||||
|
dispatcher.Register(MessageTypes.RoomJoin, Owner, async (client, message) =>
|
||||||
|
{
|
||||||
|
string roomId = JsonHub.GetString(message, "roomId") ?? "";
|
||||||
|
RoomEntity? room = await rooms.GetRoomAsync(roomId);
|
||||||
|
if (room == null)
|
||||||
|
{
|
||||||
|
return MessageEnvelope.Reply(message, ok: false, error: new MessageError { Code = "room_not_found", Message = "房间不存在。" });
|
||||||
|
}
|
||||||
|
(bool success, string error) = await rooms.JoinAsync(room, (ClientSession)client, JsonHub.GetString(message, "password"));
|
||||||
|
if (!success)
|
||||||
|
{
|
||||||
|
return MessageEnvelope.Reply(message, ok: false, error: new MessageError { Code = "join_failed", Message = error });
|
||||||
|
}
|
||||||
|
await BroadcastRoomEvent(rooms, roomId, client, "join");
|
||||||
|
return MessageEnvelope.Reply(message, new Dictionary<string, object> { ["roomId"] = roomId });
|
||||||
|
});
|
||||||
|
|
||||||
|
// ===== 退出房间 =====
|
||||||
|
dispatcher.Register(MessageTypes.RoomQuit, Owner, async (client, message) =>
|
||||||
|
{
|
||||||
|
string roomId = JsonHub.GetString(message, "roomId") ?? "";
|
||||||
|
int left = await rooms.QuitAsync(roomId, (ClientSession)client);
|
||||||
|
await BroadcastRoomEvent(rooms, roomId, client, "quit");
|
||||||
|
return MessageEnvelope.Reply(message, new Dictionary<string, object> { ["roomId"] = roomId, ["members"] = left });
|
||||||
|
});
|
||||||
|
|
||||||
|
// ===== 房间聊天 =====
|
||||||
|
dispatcher.Register(MessageTypes.RoomChat, Owner, async (client, message) =>
|
||||||
|
{
|
||||||
|
string? roomId = rooms.GetRoomOfClient(client.SessionId);
|
||||||
|
if (roomId == null)
|
||||||
|
{
|
||||||
|
return MessageEnvelope.Reply(message, ok: false, error: new MessageError { Code = "not_in_room", Message = "你不在任何房间中。" });
|
||||||
|
}
|
||||||
|
string msg = JsonHub.GetString(message, "msg") ?? "";
|
||||||
|
if (msg.Trim() == "")
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
MessageEnvelope chat = MessageEnvelope.Broadcast(MessageTypes.RoomChat, new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["roomId"] = roomId,
|
||||||
|
["from"] = client.Username ?? "匿名",
|
||||||
|
["msg"] = msg,
|
||||||
|
["time"] = DateTime.Now
|
||||||
|
});
|
||||||
|
foreach (ClientSession member in rooms.GetMembers(roomId))
|
||||||
|
{
|
||||||
|
await member.SendAsync(chat);
|
||||||
|
}
|
||||||
|
return null; // 已广播,无需单独响应
|
||||||
|
});
|
||||||
|
|
||||||
|
// ===== 开始对局(房主触发;当前为 AI 对战演示,玩家决策接入在后续里程碑) =====
|
||||||
|
dispatcher.Register(MessageTypes.RoomStart, Owner, async (client, message) =>
|
||||||
|
{
|
||||||
|
string? roomId = rooms.GetRoomOfClient(client.SessionId);
|
||||||
|
if (roomId == null)
|
||||||
|
{
|
||||||
|
return MessageEnvelope.Reply(message, ok: false, error: new MessageError { Code = "not_in_room", Message = "你不在任何房间中。" });
|
||||||
|
}
|
||||||
|
RoomEntity? room = await rooms.GetRoomAsync(roomId);
|
||||||
|
if (room == null || room.MasterUserId != client.UserId)
|
||||||
|
{
|
||||||
|
return MessageEnvelope.Reply(message, ok: false, error: new MessageError { Code = "not_master", Message = "只有房主可以开始对局。" });
|
||||||
|
}
|
||||||
|
|
||||||
|
List<ClientSession> members = [.. rooms.GetMembers(roomId)];
|
||||||
|
if (members.Count < 1)
|
||||||
|
{
|
||||||
|
return MessageEnvelope.Reply(message, ok: false, error: new MessageError { Code = "no_players", Message = "房间内没有玩家。" });
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await rooms.SetGamingAsync(roomId);
|
||||||
|
|
||||||
|
// 为每名玩家分配角色(参考 FunGameSimulation 装配技能:专属被动/大招 + 随机战技/通用被动/通用大招);不足 2 人时补 AI 机器人,保证对局可分出胜负
|
||||||
|
// 内容模组:角色与技能只从 room.ContentModule 指定的模组族产生(空 = 全量模组)
|
||||||
|
string contentModule = room.ContentModule ?? "";
|
||||||
|
List<Character> characters = [];
|
||||||
|
List<Character> templates = [.. string.IsNullOrEmpty(contentModule) ? catalog.GetCharacters() : catalog.GetCharacters(contentModule)];
|
||||||
|
int index = 0;
|
||||||
|
foreach (ClientSession member in members)
|
||||||
|
{
|
||||||
|
Character character = templates.Count > 0
|
||||||
|
? builder.BuildCharacter(templates[index % templates.Count], contentModule)
|
||||||
|
: new Character { Id = 1000 + index, Name = "Base", FirstName = member.Username ?? "Player", NickName = member.Username ?? $"玩家{index + 1}", Level = 5 };
|
||||||
|
if (templates.Count == 0)
|
||||||
|
{
|
||||||
|
character.InitialATK = 20;
|
||||||
|
character.InitialHP = 80;
|
||||||
|
character.InitialSTR = 20;
|
||||||
|
character.InitialSPD = 300;
|
||||||
|
}
|
||||||
|
character.NickName = member.Username ?? character.NickName;
|
||||||
|
characters.Add(character);
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
int targetCount = Math.Max(2, members.Count);
|
||||||
|
while (characters.Count < targetCount)
|
||||||
|
{
|
||||||
|
List<Character> fill = string.IsNullOrEmpty(contentModule) ? catalog.GetRandomCharacters(1, 10) : [.. catalog.GetCharacters(contentModule).Take(1)];
|
||||||
|
if (fill.Count == 0)
|
||||||
|
{
|
||||||
|
fill = [catalog.GetRandomCharacters(1, 10)[0]];
|
||||||
|
}
|
||||||
|
Character bot = builder.BuildCharacter(fill[0], contentModule);
|
||||||
|
bot.NickName = $"AI机器人{characters.Count + 1}";
|
||||||
|
characters.Add(bot);
|
||||||
|
}
|
||||||
|
|
||||||
|
string mode = room.GameModule == "" ? "example" : room.GameModule;
|
||||||
|
// 优先走 GameModule(游戏模式模组建房);无对应模组时回退到旧服务器插件路径
|
||||||
|
IGameModuleServer? gameModule = plugins.GetGameModule(mode);
|
||||||
|
HostedGame game;
|
||||||
|
if (gameModule != null)
|
||||||
|
{
|
||||||
|
game = await games.CreateGameFromModule(gameModule, characters);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
game = games.CreateGame(mode, characters);
|
||||||
|
}
|
||||||
|
foreach (ClientSession member in members)
|
||||||
|
{
|
||||||
|
game.Clients[member.UserId ?? member.SessionId] = member;
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageEnvelope start = MessageEnvelope.Broadcast(MessageTypes.GamingStart, new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["gameId"] = game.Id,
|
||||||
|
["mode"] = mode,
|
||||||
|
["roomId"] = roomId,
|
||||||
|
["characters"] = characters.Count
|
||||||
|
});
|
||||||
|
foreach (ClientSession member in members)
|
||||||
|
{
|
||||||
|
await member.SendAsync(start);
|
||||||
|
}
|
||||||
|
_ = game.WaitGameOverAsync(rooms, roomId, logger);
|
||||||
|
|
||||||
|
return MessageEnvelope.Reply(message, new Dictionary<string, object> { ["gameId"] = game.Id, ["mode"] = mode });
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
logger.LogError(e, "开始对局失败:Room {RoomId}", roomId);
|
||||||
|
return MessageEnvelope.Reply(message, ok: false, error: new MessageError { Code = "start_failed", Message = e.Message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ===== 匹配(快速演示:立即创建一局 AI 对战并返回房间) =====
|
||||||
|
dispatcher.Register(MessageTypes.MatchStart, Owner, async (client, message) =>
|
||||||
|
{
|
||||||
|
string mode = JsonHub.GetString(message, "mode") ?? "example";
|
||||||
|
string contentModule = JsonHub.GetString(message, "contentModule") ?? "";
|
||||||
|
int count = Math.Clamp(JsonHub.Get<int>(message, "count"), 2, 10);
|
||||||
|
// 参考 FunGameSimulation:随机角色 + 完整技能装配(专属被动/大招、战技、通用被动/大招);内容模组指定时只从该模组族取
|
||||||
|
List<Character> characters = string.IsNullOrEmpty(contentModule)
|
||||||
|
? builder.BuildSimulationCharacters(count)
|
||||||
|
: builder.BuildSimulationCharacters(count, contentModule);
|
||||||
|
HostedGame game = games.CreateGame(mode, characters);
|
||||||
|
if (client.UserId != null)
|
||||||
|
{
|
||||||
|
game.Clients[client.UserId.Value] = (ClientSession)client;
|
||||||
|
}
|
||||||
|
return MessageEnvelope.Reply(message, new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["gameId"] = game.Id,
|
||||||
|
["mode"] = mode,
|
||||||
|
["contentModule"] = contentModule,
|
||||||
|
["characters"] = count
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ===== 取消匹配(当前快速匹配立即成局,无需取消) =====
|
||||||
|
dispatcher.Register(MessageTypes.MatchCancel, Owner, async (client, message) =>
|
||||||
|
{
|
||||||
|
return MessageEnvelope.Reply(message, new Dictionary<string, object> { ["message"] = "快速匹配模式无需取消。" });
|
||||||
|
});
|
||||||
|
|
||||||
|
// ===== 局内消息(GameModule 路由):玩家行动进入当前对局的游戏模式模组 =====
|
||||||
|
dispatcher.Register(MessageTypes.GamingAction, Owner, async (client, message) =>
|
||||||
|
{
|
||||||
|
HostedGame? game = games.GetGameOfClient(client.SessionId);
|
||||||
|
if (game == null || game.Module == null)
|
||||||
|
{
|
||||||
|
return MessageEnvelope.Reply(message, ok: false, error: new MessageError { Code = "not_in_game", Message = "你不在任何 GameModule 对局中。" });
|
||||||
|
}
|
||||||
|
string action = JsonHub.GetString(message, "action") ?? "";
|
||||||
|
if (!Enum.TryParse<GamingType>(action, true, out GamingType type))
|
||||||
|
{
|
||||||
|
return MessageEnvelope.Reply(message, ok: false, error: new MessageError { Code = "unknown_action", Message = $"未知的局内动作:{action}" });
|
||||||
|
}
|
||||||
|
Dictionary<string, object>? result = await game.Module.HandleGamingMessageAsync(game, client, type, message.Data);
|
||||||
|
return result == null ? null : MessageEnvelope.Reply(message, result);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task BroadcastRoomEvent(RoomService rooms, string roomId, IClientSession client, string type)
|
||||||
|
{
|
||||||
|
MessageEnvelope roomEvent = MessageEnvelope.Broadcast(MessageTypes.RoomEvent, new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["roomId"] = roomId,
|
||||||
|
["type"] = type,
|
||||||
|
["user"] = client.Username ?? "匿名",
|
||||||
|
["members"] = rooms.GetMembers(roomId).Count
|
||||||
|
});
|
||||||
|
foreach (ClientSession member in rooms.GetMembers(roomId))
|
||||||
|
{
|
||||||
|
await member.SendAsync(roomEvent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Networking;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// WebSocket 会话管理器(在线连接 / 按用户分组 / 广播)
|
||||||
|
/// </summary>
|
||||||
|
public class SessionManager
|
||||||
|
{
|
||||||
|
private readonly ConcurrentDictionary<long, ClientSession> _sessions = new();
|
||||||
|
private readonly ILogger<SessionManager> _logger;
|
||||||
|
|
||||||
|
public SessionManager(ILogger<SessionManager> logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IEnumerable<ClientSession> Sessions => _sessions.Values.ToArray();
|
||||||
|
|
||||||
|
public int Count => _sessions.Count;
|
||||||
|
|
||||||
|
public ClientSession? Get(long sessionId) => _sessions.TryGetValue(sessionId, out ClientSession? session) ? session : null;
|
||||||
|
|
||||||
|
public IReadOnlyCollection<ClientSession> GetByUser(long userId)
|
||||||
|
=> _sessions.Values.Where(s => s.UserId == userId).ToList();
|
||||||
|
|
||||||
|
public void Add(ClientSession session)
|
||||||
|
{
|
||||||
|
_sessions[session.SessionId] = session;
|
||||||
|
_logger.LogInformation("客户端接入:Session {SessionId}({Remote}),当前连接数:{Count}", session.SessionId, session.RemoteAddress, _sessions.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Remove(long sessionId)
|
||||||
|
{
|
||||||
|
if (_sessions.TryRemove(sessionId, out ClientSession? session))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("客户端断开:Session {SessionId},当前连接数:{Count}", sessionId, _sessions.Count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>广播给所有会话</summary>
|
||||||
|
public async Task BroadcastAsync(MessageEnvelope message, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
foreach (ClientSession session in _sessions.Values)
|
||||||
|
{
|
||||||
|
await session.SendAsync(message, cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>广播给指定用户(多端全部收到)</summary>
|
||||||
|
public async Task SendToUserAsync(long userId, MessageEnvelope message, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
foreach (ClientSession session in GetByUser(userId))
|
||||||
|
{
|
||||||
|
await session.SendAsync(message, cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>踢出某用户的全部连接</summary>
|
||||||
|
public async Task KickUserAsync(long userId, string reason)
|
||||||
|
{
|
||||||
|
foreach (ClientSession session in GetByUser(userId))
|
||||||
|
{
|
||||||
|
await session.SendAsync(MessageEnvelope.Broadcast(MessageTypes.Kick, new Dictionary<string, object> { ["reason"] = reason }));
|
||||||
|
await session.CloseAsync(reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
using System.Security.Claims;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
using Microsoft.Extensions.Primitives;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Networking;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// WebSocket 接入端点与连接循环<para/>
|
||||||
|
/// 认证:/ws?access_token={jwt} 或 Authorization: Bearer 头(与 WebAPI/WebUI 同一 JWT,多端统一验证)
|
||||||
|
/// </summary>
|
||||||
|
public static class WebSocketEndpoints
|
||||||
|
{
|
||||||
|
public static void MapWebSocket(this WebApplication app)
|
||||||
|
{
|
||||||
|
app.Map("/ws", HandleConnectionAsync);
|
||||||
|
|
||||||
|
// 插件 HTTP 端点分发(/plugin/{plugin}/{**path})
|
||||||
|
// 注意:lambda 必须返回 Task(不能返回 bool/值),否则 Minimal API 会把返回值写入响应体
|
||||||
|
app.Map("/plugin/{plugin}/{**path}", async (HttpContext context, string plugin, string? path, MessageDispatcher dispatcher) =>
|
||||||
|
{
|
||||||
|
await dispatcher.DispatchHttpAsync(context, plugin, path ?? "");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task HandleConnectionAsync(HttpContext context)
|
||||||
|
{
|
||||||
|
ILoggerFactory loggerFactory = context.RequestServices.GetRequiredService<ILoggerFactory>();
|
||||||
|
ILogger logger = loggerFactory.CreateLogger("WebSocket");
|
||||||
|
|
||||||
|
if (!context.WebSockets.IsWebSocketRequest)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||||
|
logger.LogWarning("非 WebSocket 握手请求被拒绝:Connection={Connection},Upgrade={Upgrade},SecWebSocketKey={Key}",
|
||||||
|
context.Request.Headers.Connection.ToString(),
|
||||||
|
context.Request.Headers.Upgrade.ToString(),
|
||||||
|
context.Request.Headers.SecWebSocketKey.ToString());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageDispatcher dispatcher = context.RequestServices.GetRequiredService<MessageDispatcher>();
|
||||||
|
SessionManager sessions = context.RequestServices.GetRequiredService<SessionManager>();
|
||||||
|
Auth.JwtService jwtService = context.RequestServices.GetRequiredService<Auth.JwtService>();
|
||||||
|
|
||||||
|
// 提取 JWT:query access_token > Authorization 头
|
||||||
|
string? token = null;
|
||||||
|
if (context.Request.Query.TryGetValue("access_token", out StringValues queryToken))
|
||||||
|
{
|
||||||
|
token = queryToken.ToString();
|
||||||
|
}
|
||||||
|
else if (context.Request.Headers.TryGetValue("Authorization", out StringValues authHeader))
|
||||||
|
{
|
||||||
|
string header = authHeader.ToString();
|
||||||
|
if (header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
token = header[7..];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ClaimsPrincipal? principal = token != null ? jwtService.Validate(token) : null;
|
||||||
|
string remote = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||||
|
|
||||||
|
System.Net.WebSockets.WebSocket socket = await context.WebSockets.AcceptWebSocketAsync();
|
||||||
|
ClientSession session = new(socket, principal, remote, loggerFactory.CreateLogger<ClientSession>());
|
||||||
|
sessions.Add(session);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (session.IsAuthenticated)
|
||||||
|
{
|
||||||
|
await session.SendAsync(MessageEnvelope.Broadcast(MessageTypes.Notice, new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["message"] = $"欢迎回来,{session.Username}!"
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await session.SendAsync(MessageEnvelope.Reply(new MessageEnvelope { Type = MessageTypes.Notice }, new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["message"] = "未认证连接:请先通过 /api/auth/login 获取 access_token,然后以 /ws?access_token=… 连接。"
|
||||||
|
}, ok: false, new MessageError { Code = "unauthorized", Message = "缺少有效的 access_token。" }));
|
||||||
|
await session.CloseAsync("unauthorized");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (session.State == System.Net.WebSockets.WebSocketState.Open)
|
||||||
|
{
|
||||||
|
MessageEnvelope? message = await session.ReceiveAsync(context.RequestAborted);
|
||||||
|
if (message == null)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
MessageEnvelope? reply = await dispatcher.DispatchAsync(session, message);
|
||||||
|
if (reply != null)
|
||||||
|
{
|
||||||
|
await session.SendAsync(reply, context.RequestAborted);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
logger.LogError(e, "WebSocket 连接异常:Session {SessionId}", session.SessionId);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
sessions.Remove(session.SessionId);
|
||||||
|
await session.DisposeAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
using FunGame.Core.Api;
|
||||||
|
using FunGame.Server.Contracts.Constants;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
using FunGame.Server.Contracts.Plugins;
|
||||||
|
using FunGame.Server.Host;
|
||||||
|
using FunGame.Server.Host.Auth;
|
||||||
|
using FunGame.Server.Host.Controllers;
|
||||||
|
using FunGame.Server.Host.Networking;
|
||||||
|
using FunGame.Server.Host.Services;
|
||||||
|
using FunGame.Server.Infrastructure;
|
||||||
|
using FunGame.Server.Infrastructure.Data;
|
||||||
|
using FunGame.Server.Infrastructure.Entities.Identity;
|
||||||
|
using FunGame.Server.PluginHost;
|
||||||
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||||
|
using Microsoft.AspNetCore.Diagnostics;
|
||||||
|
using Microsoft.AspNetCore.Identity;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.FileProviders;
|
||||||
|
|
||||||
|
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
|
// ===== 数据层(EF Core:SQLite / MySQL 按配置切换) =====
|
||||||
|
builder.Services.AddServerInfrastructure(builder.Configuration);
|
||||||
|
|
||||||
|
// ===== 认证:多端统一验证(JWT Bearer) =====
|
||||||
|
JwtService jwtService = new(builder.Configuration);
|
||||||
|
builder.Services.AddSingleton(jwtService);
|
||||||
|
builder.Services.AddSingleton<PasswordHasher<User>>();
|
||||||
|
builder.Services.AddScoped<AuthService>();
|
||||||
|
builder.Services.AddAuthentication(options =>
|
||||||
|
{
|
||||||
|
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||||
|
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||||
|
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||||
|
}).AddJwtBearer(options =>
|
||||||
|
{
|
||||||
|
options.TokenValidationParameters = jwtService.TokenValidationParameters;
|
||||||
|
});
|
||||||
|
builder.Services.AddAuthorization();
|
||||||
|
|
||||||
|
// ===== 网络层 =====
|
||||||
|
builder.Services.AddSingleton<MessageDispatcher>();
|
||||||
|
builder.Services.AddSingleton<IMessageHandlerRegistry>(sp => sp.GetRequiredService<MessageDispatcher>());
|
||||||
|
builder.Services.AddSingleton<IPluginHttpHandlerRegistry>(sp => sp.GetRequiredService<MessageDispatcher>());
|
||||||
|
builder.Services.AddSingleton<SessionManager>();
|
||||||
|
|
||||||
|
// ===== 插件系统(始终热重载) =====
|
||||||
|
builder.Services.AddSingleton<PluginManager>();
|
||||||
|
|
||||||
|
// ===== 对局宿主与回合记录外发 =====
|
||||||
|
builder.Services.AddSingleton<GameHostService>();
|
||||||
|
builder.Services.AddSingleton<EntityCatalog>();
|
||||||
|
builder.Services.AddSingleton<CharacterBuildService>();
|
||||||
|
builder.Services.AddSingleton<RoomService>();
|
||||||
|
builder.Services.AddSingleton<ReplayArchiveService>();
|
||||||
|
builder.Services.AddHttpClient();
|
||||||
|
|
||||||
|
// ===== 日志:结构化写入 server_logs 表(WebUI 日志页) =====
|
||||||
|
FunGame.Server.Host.Logging.ServerLogsLoggerProvider serverLogsProvider = new();
|
||||||
|
builder.Logging.AddProvider(serverLogsProvider);
|
||||||
|
|
||||||
|
// ===== 控制器与 JSON(复用 Core 转换器 + 循环引用策略) =====
|
||||||
|
builder.Services.AddControllers(options =>
|
||||||
|
{
|
||||||
|
options.Filters.Add<PermissionFilter>();
|
||||||
|
}).AddJsonOptions(options => JsonHub.Configure(options.JsonSerializerOptions));
|
||||||
|
builder.Services.ConfigureHttpJsonOptions(options => JsonHub.Configure(options.SerializerOptions));
|
||||||
|
builder.Services.AddEndpointsApiExplorer();
|
||||||
|
builder.Services.AddOpenApi();
|
||||||
|
|
||||||
|
// ===== CORS =====
|
||||||
|
builder.Services.AddCors(options =>
|
||||||
|
{
|
||||||
|
options.AddPolicy("AllowSpecificOrigin", policy =>
|
||||||
|
{
|
||||||
|
string[] allowedOrigins = builder.Configuration.GetSection("AllowOrigins").Get<string[]>()
|
||||||
|
?? ["http://localhost:5173", "http://127.0.0.1:5173"];
|
||||||
|
policy.WithOrigins(allowedOrigins).AllowAnyHeader().AllowAnyMethod().AllowCredentials();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
WebApplication app = builder.Build();
|
||||||
|
|
||||||
|
// 绑定日志通道的真实作用域工厂(延迟绑定)
|
||||||
|
serverLogsProvider.Attach(app.Services.GetRequiredService<IServiceScopeFactory>());
|
||||||
|
|
||||||
|
// ===== 目录初始化 =====
|
||||||
|
string contentRoot = app.Environment.ContentRootPath;
|
||||||
|
Directory.CreateDirectory(Path.Combine(contentRoot, PluginConstants.DataDirectory));
|
||||||
|
Directory.CreateDirectory(Path.Combine(contentRoot, PluginConstants.PluginsDirectory));
|
||||||
|
Directory.CreateDirectory(Path.Combine(contentRoot, PluginConstants.CharacterModulesDirectory));
|
||||||
|
Directory.CreateDirectory(Path.Combine(contentRoot, PluginConstants.SkillModulesDirectory));
|
||||||
|
Directory.CreateDirectory(Path.Combine(contentRoot, PluginConstants.ItemModulesDirectory));
|
||||||
|
Directory.CreateDirectory(Path.Combine(contentRoot, PluginConstants.GameModuleDirectory));
|
||||||
|
Directory.CreateDirectory(Path.Combine(contentRoot, PluginConstants.RecordsDirectory));
|
||||||
|
|
||||||
|
app.UseCors("AllowSpecificOrigin");
|
||||||
|
|
||||||
|
// ===== 异常处理(统一 ApiResponse 包装) =====
|
||||||
|
app.UseExceptionHandler(errorApp =>
|
||||||
|
{
|
||||||
|
errorApp.Run(async context =>
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
||||||
|
context.Response.ContentType = "application/json";
|
||||||
|
IExceptionHandlerFeature? feature = context.Features.Get<IExceptionHandlerFeature>();
|
||||||
|
await context.Response.WriteAsJsonAsync(ApiResponse.Fail(500, $"服务器内部错误:{feature?.Error.Message}"));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
if (app.Environment.IsDevelopment())
|
||||||
|
{
|
||||||
|
app.MapOpenApi();
|
||||||
|
}
|
||||||
|
|
||||||
|
app.UseAuthentication();
|
||||||
|
app.UseAuthorization();
|
||||||
|
|
||||||
|
app.MapControllers();
|
||||||
|
|
||||||
|
// ===== WebSocket(/ws)与插件 HTTP 端点(/plugin/**) =====
|
||||||
|
app.UseWebSockets(new WebSocketOptions
|
||||||
|
{
|
||||||
|
KeepAliveInterval = TimeSpan.FromMinutes(2)
|
||||||
|
});
|
||||||
|
app.MapWebSocket();
|
||||||
|
BuiltInMessageHandlers.Register(app.Services.GetRequiredService<MessageDispatcher>(), builder.Configuration);
|
||||||
|
RoomMessageHandlers.Register(app.Services.GetRequiredService<MessageDispatcher>(), app.Services);
|
||||||
|
|
||||||
|
// ===== 静态文件:生产环境托管 webui/dist =====
|
||||||
|
string? uiDist = null;
|
||||||
|
foreach (string candidate in new[]
|
||||||
|
{
|
||||||
|
Path.Combine(contentRoot, "webui", "dist"),
|
||||||
|
Path.Combine(contentRoot, "..", "webui", "dist"),
|
||||||
|
Path.Combine(contentRoot, "..", "..", "webui", "dist")
|
||||||
|
})
|
||||||
|
{
|
||||||
|
if (Directory.Exists(candidate))
|
||||||
|
{
|
||||||
|
uiDist = candidate;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (uiDist != null)
|
||||||
|
{
|
||||||
|
PhysicalFileProvider fileProvider = new(uiDist);
|
||||||
|
app.UseStaticFiles(new StaticFileOptions { FileProvider = fileProvider });
|
||||||
|
app.MapFallbackToFile("index.html", new StaticFileOptions { FileProvider = fileProvider });
|
||||||
|
app.Logger.LogInformation("已托管 WebUI 构建产物:{Path}", uiDist);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 服务器公开信息(根路径由 WebUI 静态托管占用)
|
||||||
|
app.MapGet("/api/server/info", () => Results.Ok(ApiResponse.Success(new
|
||||||
|
{
|
||||||
|
name = builder.Configuration["Server:Name"] ?? "FunGame Server v3",
|
||||||
|
version = "3.0.0-dev",
|
||||||
|
coreVersion = FunGame.Core.Library.Constant.FunGameInfo.FunGame_Version,
|
||||||
|
endpoints = new
|
||||||
|
{
|
||||||
|
rest = "/api",
|
||||||
|
websocket = "/ws?access_token={jwt}",
|
||||||
|
openapi = app.Environment.IsDevelopment() ? "/openapi/v1.json" : null
|
||||||
|
}
|
||||||
|
})));
|
||||||
|
|
||||||
|
// ===== 启动:数据库迁移 + 种子 + 插件加载 =====
|
||||||
|
using (IServiceScope scope = app.Services.CreateScope())
|
||||||
|
{
|
||||||
|
AppDbContext db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||||
|
app.Logger.LogInformation("正在应用数据库迁移(Provider: {Provider})…", builder.Configuration["Database:Provider"] ?? "Sqlite");
|
||||||
|
await db.Database.MigrateAsync();
|
||||||
|
|
||||||
|
DbSeedService seedService = scope.ServiceProvider.GetRequiredService<DbSeedService>();
|
||||||
|
await seedService.SeedAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
PluginManager pluginManager = app.Services.GetRequiredService<PluginManager>();
|
||||||
|
pluginManager.LoadAll();
|
||||||
|
if (builder.Configuration.GetValue("Plugins:Watch", true))
|
||||||
|
{
|
||||||
|
pluginManager.EnableFileWatcher();
|
||||||
|
}
|
||||||
|
|
||||||
|
app.Logger.LogInformation("{Name} 启动完成,开始监听 …", builder.Configuration["Server:Name"]);
|
||||||
|
|
||||||
|
app.Run();
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||||
|
"profiles": {
|
||||||
|
"http": {
|
||||||
|
"commandName": "Project",
|
||||||
|
"dotnetRunMessages": true,
|
||||||
|
"launchBrowser": true,
|
||||||
|
"applicationUrl": "http://localhost:5145",
|
||||||
|
"environmentVariables": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"https": {
|
||||||
|
"commandName": "Project",
|
||||||
|
"dotnetRunMessages": true,
|
||||||
|
"launchBrowser": true,
|
||||||
|
"applicationUrl": "https://localhost:7134;http://localhost:5145",
|
||||||
|
"environmentVariables": {
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
using FunGame.Core.Entity;
|
||||||
|
using FunGame.Core.Library.Constant;
|
||||||
|
using FunGame.Core.Model.EffectContext;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 角色构建服务:参考 Testing-v3 的 FunGameSimulation / FunGameService.AddCharacterSkills 生成对局角色<para/>
|
||||||
|
/// 与模组解耦:技能通过 EntityCatalog(模组注册的技能实体)按 Name 匹配,随模组热重载自动生效
|
||||||
|
/// </summary>
|
||||||
|
public class CharacterBuildService(EntityCatalog catalog, ILogger<CharacterBuildService> logger)
|
||||||
|
{
|
||||||
|
/// <summary>角色专属技能映射(角色 Id -> 专属被动, 专属大招),与 FunGameService.AddCharacterSkills 一致</summary>
|
||||||
|
private static readonly Dictionary<long, (string Passive, string Super)> ExclusiveSkills = new()
|
||||||
|
{
|
||||||
|
[1] = ("META马", "熵灭极诣"),
|
||||||
|
[2] = ("心灵之弦", "千羽瞬华"),
|
||||||
|
[3] = ("蚀魂震击", "咒怨洪流"),
|
||||||
|
[4] = ("灵能反射", "三相灵枢"),
|
||||||
|
[5] = ("双生流转", "变幻之心"),
|
||||||
|
[6] = ("零式崩解", "零式灭杀"),
|
||||||
|
[7] = ("少女绮想", "绝对领域"),
|
||||||
|
[8] = ("暗香疏影", "残香凋零"),
|
||||||
|
[9] = ("破釜沉舟", "宿命时律"),
|
||||||
|
[10] = ("累积之压", "极寒渴望"),
|
||||||
|
[11] = ("银隼之赐", "身心一境"),
|
||||||
|
[12] = ("弱者猎手", "饕餮盛宴"),
|
||||||
|
[13] = ("开宫", "放监"),
|
||||||
|
[14] = ("八卦阵", "归元环"),
|
||||||
|
[15] = ("深海之戟", "海王星的野望"),
|
||||||
|
[16] = ("雇佣兵团", "全军出击"),
|
||||||
|
[17] = ("不息之流", "宿命之潮"),
|
||||||
|
[18] = ("概念之骰", "神之因果")
|
||||||
|
};
|
||||||
|
|
||||||
|
private IReadOnlyList<Skill> _skills = [];
|
||||||
|
|
||||||
|
private IReadOnlyList<Skill> Skills => _skills.Count > 0 ? _skills : (_skills = catalog.GetSkills());
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 参考 FunGameSimulation 生成一局对局角色:随机角色 + 等级/普攻等级 + 专属被动与大招 + 随机战技/通用被动/通用大招<para/>
|
||||||
|
/// 返回的角色副本已绑定技能,可直接传入 GamingQueue
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="count">角色数量(≤10)</param>
|
||||||
|
/// <param name="modulePrefix">内容模组前缀(如 "oshima"):角色与技能只从该模组族产生;空/null 则使用全量模组</param>
|
||||||
|
/// <param name="level">角色等级(默认 10,与 FunGameSimulation 一致)</param>
|
||||||
|
/// <param name="skillLevel">战技/大招等级(默认 2)</param>
|
||||||
|
public List<Character> BuildSimulationCharacters(int count, string? modulePrefix = null, int level = 10, int skillLevel = 2)
|
||||||
|
{
|
||||||
|
List<Character> templates = [.. string.IsNullOrWhiteSpace(modulePrefix) ? catalog.GetCharacters() : catalog.GetCharacters(modulePrefix)];
|
||||||
|
List<Character> characters = [];
|
||||||
|
int total = Math.Clamp(count, 1, 10);
|
||||||
|
|
||||||
|
// 随机抽取角色模板(不足时允许重复填充)
|
||||||
|
for (int i = 0; i < total; i++)
|
||||||
|
{
|
||||||
|
Character template = templates.Count > 0
|
||||||
|
? templates[Random.Shared.Next(templates.Count)]
|
||||||
|
: CreateFallbackCharacter(i);
|
||||||
|
characters.Add(BuildCharacter(template, modulePrefix, level, skillLevel));
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.LogDebug("参考 FunGameSimulation 构建对局角色 {Count} 名(等级 {Level},模组 {Module})", characters.Count, level, string.IsNullOrWhiteSpace(modulePrefix) ? "all" : modulePrefix);
|
||||||
|
return characters;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 装配单个角色(参考 FunGameService.AddCharacterSkills + FunGameSimulation 的随机技能分配)<para/>
|
||||||
|
/// 复制模板 → 设等级/普攻等级 → 专属被动与大招 → 随机战技/通用被动/通用大招
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="modulePrefix">内容模组前缀:专属技能/战技/通用技能只从该模组族匹配;空/null 则全量</param>
|
||||||
|
public Character BuildCharacter(Character template, string? modulePrefix = null, int level = 10, int skillLevel = 2)
|
||||||
|
{
|
||||||
|
Character c = template.Copy();
|
||||||
|
c.Level = level;
|
||||||
|
c.NormalAttack.Level = 2;
|
||||||
|
|
||||||
|
// 技能池:限定模组前缀时只从该模组族匹配(否则全量)——角色/技能严格来自所选模组
|
||||||
|
IReadOnlyList<Skill> pool = string.IsNullOrWhiteSpace(modulePrefix) ? Skills : catalog.GetSkills(modulePrefix);
|
||||||
|
|
||||||
|
// 专属技能名(随机池排除,避免重复/跨角色专属;与 FunGameSimulation 的"通用技能"语义一致)
|
||||||
|
HashSet<string> exclusiveNames = ExclusiveSkills.Values.SelectMany(v => new[] { v.Passive, v.Super }).ToHashSet();
|
||||||
|
|
||||||
|
// 专属被动 + 专属大招(Oshima 角色 id 1-18 映射;其他模组角色无专属则跳过)
|
||||||
|
if (ExclusiveSkills.TryGetValue(c.Id, out (string Passive, string Super) exclusive))
|
||||||
|
{
|
||||||
|
AddSkill(c, pool, exclusive.Passive, 1);
|
||||||
|
AddSkill(c, pool, exclusive.Super, skillLevel);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 随机 3 个战技(按类型从所选模组技能池取;排除 疾走,与 FunGameSimulation 一致)
|
||||||
|
foreach (Skill s in pool.Where(s => s.SkillType == SkillType.Skill && s.Name != "疾走").OrderBy(_ => Random.Shared.Next()).Take(3))
|
||||||
|
{
|
||||||
|
AddSkill(c, s, skillLevel);
|
||||||
|
}
|
||||||
|
// 随机 3 个被动(等级 1;排除专属)
|
||||||
|
foreach (Skill s in pool.Where(s => s.SkillType == SkillType.Passive && !exclusiveNames.Contains(s.Name)).OrderBy(_ => Random.Shared.Next()).Take(3))
|
||||||
|
{
|
||||||
|
AddSkill(c, s, 1);
|
||||||
|
}
|
||||||
|
// 随机 3 个爆发技(排除专属;候选不足时回退到全部爆发技)
|
||||||
|
IEnumerable<Skill> supers = pool.Where(s => s.SkillType == SkillType.SuperSkill && !exclusiveNames.Contains(s.Name)).ToList();
|
||||||
|
if (!supers.Any()) supers = pool.Where(s => s.SkillType == SkillType.SuperSkill);
|
||||||
|
foreach (Skill s in supers.OrderBy(_ => Random.Shared.Next()).Take(3))
|
||||||
|
{
|
||||||
|
AddSkill(c, s, skillLevel);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 清理模板被动特效(与 FunGameSimulation 一致);局外场景 Queue 传 null
|
||||||
|
foreach (Effect e in c.Effects.ToList())
|
||||||
|
{
|
||||||
|
e.OnEffectLost(new HookContext(null, c));
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.LogInformation("角色装配完成:{NickName}(Id={Id})技能 {Count} 个:{Skills}", c.NickName, c.Id, c.Skills.Count, string.Join(" / ", c.Skills.Select(s => s.Name)));
|
||||||
|
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>向角色添加指定技能(按名称从技能池匹配,复制后绑定角色)</summary>
|
||||||
|
private void AddSkill(Character character, IReadOnlyList<Skill> pool, string skillName, int level)
|
||||||
|
{
|
||||||
|
Skill? skill = pool.FirstOrDefault(s => s.Name == skillName);
|
||||||
|
if (skill == null)
|
||||||
|
{
|
||||||
|
logger.LogDebug("技能未找到(模组未注册):{SkillName}", skillName);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
AddSkill(character, skill, level);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>复制技能并绑定到角色</summary>
|
||||||
|
private static void AddSkill(Character character, Skill skill, int level)
|
||||||
|
{
|
||||||
|
Skill copy = skill.Copy();
|
||||||
|
copy.Character = character;
|
||||||
|
copy.Level = level;
|
||||||
|
character.Skills.Add(copy);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>模组缺失时的基础角色兜底(与 EntityCatalog 一致)</summary>
|
||||||
|
private static Character CreateFallbackCharacter(int index)
|
||||||
|
{
|
||||||
|
Character fallback = new()
|
||||||
|
{
|
||||||
|
Id = 1000 + index,
|
||||||
|
Name = "Base",
|
||||||
|
FirstName = $"Bot{index + 1}",
|
||||||
|
NickName = $"基础机器人{index + 1}",
|
||||||
|
Level = 10
|
||||||
|
};
|
||||||
|
fallback.InitialATK = 20;
|
||||||
|
fallback.InitialHP = 80;
|
||||||
|
fallback.InitialSTR = 20;
|
||||||
|
fallback.STRGrowth = 2;
|
||||||
|
fallback.InitialSPD = 300;
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
using FunGame.Core.Entity;
|
||||||
|
using FunGame.Server.PluginHost;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 实体目录:聚合全部已加载实体模组(角色/技能/物品)供业务层取用<para/>
|
||||||
|
/// 随模组热重载自动反映最新内容(PluginManager 实时查询)
|
||||||
|
/// </summary>
|
||||||
|
public class EntityCatalog(PluginManager pluginManager)
|
||||||
|
{
|
||||||
|
public IReadOnlyList<Character> GetCharacters() => pluginManager.GetModuleEntities<Character>().ToList();
|
||||||
|
|
||||||
|
public IReadOnlyList<Skill> GetSkills() => pluginManager.GetModuleEntities<Skill>().ToList();
|
||||||
|
|
||||||
|
public IReadOnlyList<Item> GetItems() => pluginManager.GetModuleEntities<Item>().ToList();
|
||||||
|
|
||||||
|
/// <summary>按模组前缀获取角色(如 "oshima" → oshima.characters)</summary>
|
||||||
|
public IReadOnlyList<Character> GetCharacters(string modulePrefix) => pluginManager.GetModuleEntities<Character>(modulePrefix).ToList();
|
||||||
|
|
||||||
|
/// <summary>按模组前缀获取技能(如 "oshima" → oshima.skills)</summary>
|
||||||
|
public IReadOnlyList<Skill> GetSkills(string modulePrefix) => pluginManager.GetModuleEntities<Skill>(modulePrefix).ToList();
|
||||||
|
|
||||||
|
/// <summary>按模组前缀获取物品(如 "oshima" → oshima.items)</summary>
|
||||||
|
public IReadOnlyList<Item> GetItems(string modulePrefix) => pluginManager.GetModuleEntities<Item>(modulePrefix).ToList();
|
||||||
|
|
||||||
|
/// <summary>随机取 n 个角色副本(不足时重复填充)</summary>
|
||||||
|
public List<Character> GetRandomCharacters(int count, int level = 5)
|
||||||
|
{
|
||||||
|
IReadOnlyList<Character> source = GetCharacters();
|
||||||
|
List<Character> result = [];
|
||||||
|
if (source.Count == 0)
|
||||||
|
{
|
||||||
|
// 模组未安装时使用基础角色兜底
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
Character fallback = new()
|
||||||
|
{
|
||||||
|
Id = 1000 + i,
|
||||||
|
Name = "Base",
|
||||||
|
FirstName = $"Bot{i + 1}",
|
||||||
|
NickName = $"基础机器人{i + 1}",
|
||||||
|
Level = level
|
||||||
|
};
|
||||||
|
fallback.InitialATK = 20;
|
||||||
|
fallback.InitialHP = 80;
|
||||||
|
fallback.InitialSTR = 20;
|
||||||
|
fallback.STRGrowth = 2;
|
||||||
|
fallback.InitialSPD = 300;
|
||||||
|
result.Add(fallback);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
Character copy = source[Random.Shared.Next(source.Count)].Copy();
|
||||||
|
copy.Level = level;
|
||||||
|
copy.NickName = copy.NickName == "" ? $"玩家{i + 1}" : copy.NickName;
|
||||||
|
result.Add(copy);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,342 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Text.Json;
|
||||||
|
using FunGame.Core.Entity;
|
||||||
|
using FunGame.Core.Model.Framework;
|
||||||
|
using FunGame.Core.Model.Queue;
|
||||||
|
using FunGame.Server.Contracts.Gaming;
|
||||||
|
using FunGame.Server.Contracts.Networking;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
using FunGame.Server.Contracts.Plugins;
|
||||||
|
using FunGame.Server.Host.Networking;
|
||||||
|
using FunGame.Server.PluginHost;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 对局宿主:GamingQueue 生命周期管理、AI 对局循环、回合记录外发接线与 WS 实时推送
|
||||||
|
/// </summary>
|
||||||
|
public class GameHostService
|
||||||
|
{
|
||||||
|
private readonly ConcurrentDictionary<Guid, HostedGame> _games = new();
|
||||||
|
private readonly IServiceScopeFactory _scopeFactory;
|
||||||
|
private readonly PluginManager _plugins;
|
||||||
|
private readonly SessionManager _sessions;
|
||||||
|
private readonly IConfiguration _configuration;
|
||||||
|
private readonly ILoggerFactory _loggerFactory;
|
||||||
|
private readonly ILogger<GameHostService> _logger;
|
||||||
|
|
||||||
|
public GameHostService(
|
||||||
|
IServiceScopeFactory scopeFactory,
|
||||||
|
PluginManager plugins,
|
||||||
|
SessionManager sessions,
|
||||||
|
IConfiguration configuration,
|
||||||
|
ILoggerFactory loggerFactory,
|
||||||
|
ILogger<GameHostService> logger)
|
||||||
|
{
|
||||||
|
_scopeFactory = scopeFactory;
|
||||||
|
_plugins = plugins;
|
||||||
|
_sessions = sessions;
|
||||||
|
_configuration = configuration;
|
||||||
|
_loggerFactory = loggerFactory;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IEnumerable<HostedGame> Games => _games.Values;
|
||||||
|
|
||||||
|
public HostedGame? GetGame(Guid id) => _games.TryGetValue(id, out HostedGame? game) ? game : null;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建对局:mode 为服务器插件名(游戏模式);characters 为参与者;map 可空<para/>
|
||||||
|
/// 创建后立即启动 AI 对局循环(人类玩家的局内决策接入在后续里程碑接入)
|
||||||
|
/// </summary>
|
||||||
|
public HostedGame CreateGame(string mode, List<Character> characters, GameMap? map = null)
|
||||||
|
{
|
||||||
|
if (_plugins.GetServerPlugin(mode) == null)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"游戏模式插件不存在:{mode}");
|
||||||
|
}
|
||||||
|
|
||||||
|
Guid gameId = Guid.NewGuid();
|
||||||
|
_logger.LogInformation("创建对局:{GameId}(模式 {Mode},{Count} 名角色)", gameId, mode, characters.Count);
|
||||||
|
|
||||||
|
GameRoundRecordSink sink = new(gameId, mode, _scopeFactory, _configuration, _loggerFactory.CreateLogger<GameRoundRecordSink>());
|
||||||
|
|
||||||
|
// 混战队列(淘汰制,最多复活 1 次,保证对局可分出胜负)
|
||||||
|
MixGamingQueue queue = new(characters, msg => _logger.LogDebug("[Game {GameId}] {Msg}", gameId, msg))
|
||||||
|
{
|
||||||
|
IsDebug = _configuration.GetValue("Server:Debug", false),
|
||||||
|
MaxRespawnTimes = 1
|
||||||
|
};
|
||||||
|
if (map != null)
|
||||||
|
{
|
||||||
|
queue.LoadGameMap(map);
|
||||||
|
}
|
||||||
|
queue.RoundRecordSink = sink;
|
||||||
|
queue.InitActionQueue();
|
||||||
|
|
||||||
|
HostedGame game = new(gameId, mode, queue, sink, endGame: (id, aborted) => EndGameAsync(id, aborted));
|
||||||
|
_games[gameId] = game;
|
||||||
|
_plugins.Acquire(mode);
|
||||||
|
|
||||||
|
// 回合记录 → 实时广播(观战/直播)
|
||||||
|
sink.RoundRecorded += round => BroadcastRound(game, round);
|
||||||
|
|
||||||
|
// 启动对局循环
|
||||||
|
_ = Task.Run(() => RunGameLoopAsync(game));
|
||||||
|
return game;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建对局(GameModule 路径):由游戏模式模组建房并返回队列<para/>
|
||||||
|
/// 模组负责创建/装配 GamingQueue 与房间工作区,宿主负责回合记录外发、实时广播与对局循环
|
||||||
|
/// </summary>
|
||||||
|
public async Task<HostedGame> CreateGameFromModule(IGameModuleServer module, List<Character> characters, GameMap? map = null)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(module);
|
||||||
|
|
||||||
|
Guid gameId = Guid.NewGuid();
|
||||||
|
_logger.LogInformation("创建对局(GameModule):{GameId}(模式 {Mode},{Count} 名角色)", gameId, module.Id, characters.Count);
|
||||||
|
|
||||||
|
GameRoundRecordSink sink = new(gameId, module.Id, _scopeFactory, _configuration, _loggerFactory.CreateLogger<GameRoundRecordSink>());
|
||||||
|
HostedGame game = new(gameId, module.Id, null!, sink, module, (id, aborted) => EndGameAsync(id, aborted));
|
||||||
|
_games[gameId] = game;
|
||||||
|
|
||||||
|
// 模组建房(创建/装配队列),宿主随后接管回合记录与循环
|
||||||
|
GamingQueue queue = await module.StartGameAsync(game, characters, map!);
|
||||||
|
game.Queue = queue;
|
||||||
|
queue.RoundRecordSink = sink;
|
||||||
|
|
||||||
|
// 回合记录 → 实时广播(观战/直播)
|
||||||
|
sink.RoundRecorded += round => BroadcastRound(game, round);
|
||||||
|
|
||||||
|
_plugins.Acquire(module.Id);
|
||||||
|
|
||||||
|
// 启动对局循环
|
||||||
|
_ = Task.Run(() => RunGameLoopAsync(game));
|
||||||
|
return game;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>按客户端会话查找所在对局(用于 gaming.* 消息路由到该局 GameModule)</summary>
|
||||||
|
public HostedGame? GetGameOfClient(long sessionId)
|
||||||
|
=> _games.Values.FirstOrDefault(g => g.Clients.Values.Any(c => c.SessionId == sessionId));
|
||||||
|
|
||||||
|
/// <summary>AI 对局循环(参考 Testing-v3 的模拟循环:行动顺序 → ProcessTurn → TimeLapse)</summary>
|
||||||
|
private async Task RunGameLoopAsync(HostedGame game)
|
||||||
|
{
|
||||||
|
GamingQueue queue = game.Queue;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 全部角色由 AI 控制(玩家决策接入后,仅未连接的玩家角色走 AI)
|
||||||
|
queue.SetCharactersToAIControl(false, queue.AllCharacters);
|
||||||
|
|
||||||
|
int maxRounds = _configuration.GetValue("Server:MaxGameRounds", 3000);
|
||||||
|
int rounds = 0;
|
||||||
|
while (!queue.GameOver && game.Running && rounds < maxRounds)
|
||||||
|
{
|
||||||
|
// 暂停:等待恢复或对局结束(管理端可暂停/恢复)
|
||||||
|
while (game.Paused && game.Running && !queue.GameOver)
|
||||||
|
{
|
||||||
|
await Task.Delay(100);
|
||||||
|
}
|
||||||
|
if (!game.Running || queue.GameOver)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
Character? character = queue.NextCharacter();
|
||||||
|
if (character != null)
|
||||||
|
{
|
||||||
|
queue.ProcessTurn(character);
|
||||||
|
rounds++;
|
||||||
|
}
|
||||||
|
queue.TimeLapse();
|
||||||
|
await Task.Delay(20);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!queue.GameOver && game.Running)
|
||||||
|
{
|
||||||
|
_logger.LogWarning("对局 {GameId} 达到回合上限({Rounds}),强制结束", game.Id, rounds);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError(e, "对局循环异常:{GameId}", game.Id);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await EndGameAsync(game.Id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void BroadcastRound(HostedGame game, RoundRecord round)
|
||||||
|
{
|
||||||
|
JsonElement element = JsonSerializer.SerializeToElement(round, JsonHub.Options);
|
||||||
|
MessageEnvelope message = MessageEnvelope.Broadcast(MessageTypes.GamingRound, new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["gameId"] = game.Id,
|
||||||
|
["round"] = element
|
||||||
|
});
|
||||||
|
|
||||||
|
foreach (ClientSession session in game.Clients.Values)
|
||||||
|
{
|
||||||
|
_ = session.SendAsync(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>暂停对局(对局循环在下一个回合边界挂起)</summary>
|
||||||
|
public bool PauseGame(Guid id)
|
||||||
|
{
|
||||||
|
if (!_games.TryGetValue(id, out HostedGame? game) || !game.Running)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
game.Paused = true;
|
||||||
|
_logger.LogInformation("暂停对局:{GameId}", id);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>恢复对局</summary>
|
||||||
|
public bool ResumeGame(Guid id)
|
||||||
|
{
|
||||||
|
if (!_games.TryGetValue(id, out HostedGame? game))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
game.Paused = false;
|
||||||
|
_logger.LogInformation("恢复对局:{GameId}", id);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>结束对局(正常/中止):归档回合记录、广播结算、释放插件引用</summary>
|
||||||
|
public async Task<bool> EndGameAsync(Guid id, bool aborted = false)
|
||||||
|
{
|
||||||
|
if (!_games.TryGetValue(id, out HostedGame? game))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogInformation("结束对局:{GameId}({Reason})", id, aborted ? "中止" : "正常结束");
|
||||||
|
game.End(aborted);
|
||||||
|
_plugins.Release(game.Mode);
|
||||||
|
_games.TryRemove(id, out _);
|
||||||
|
|
||||||
|
// 等待回合记录归档完成(含最终统计落盘),确保客户端随后可立即回放
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await game.Sink.FinalizeTask.WaitAsync(TimeSpan.FromSeconds(10));
|
||||||
|
}
|
||||||
|
catch (TimeoutException)
|
||||||
|
{
|
||||||
|
_logger.LogWarning("对局 {GameId} 归档超时,仍继续广播结算", id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 广播结算
|
||||||
|
RoundRecord? last = game.Queue.Rounds.OrderByDescending(r => r.Round).FirstOrDefault();
|
||||||
|
JsonElement? resultElement = last?.GameResult.Count > 0
|
||||||
|
? JsonSerializer.SerializeToElement(last.GameResult, JsonHub.Options)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
MessageEnvelope over = MessageEnvelope.Broadcast(MessageTypes.GamingOver, new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
["gameId"] = game.Id,
|
||||||
|
["mode"] = game.Mode,
|
||||||
|
["totalRound"] = game.Queue.TotalRound,
|
||||||
|
["totalTime"] = game.Queue.TotalTime,
|
||||||
|
["gameResult"] = resultElement
|
||||||
|
});
|
||||||
|
foreach (ClientSession session in game.Clients.Values)
|
||||||
|
{
|
||||||
|
await session.SendAsync(over);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>重连对局:把会话重新绑定到对局(用户 Id -> 会话)</summary>
|
||||||
|
public bool Reconnect(Guid gameId, long userId, ClientSession session)
|
||||||
|
{
|
||||||
|
if (_games.TryGetValue(gameId, out HostedGame? game))
|
||||||
|
{
|
||||||
|
game.Clients[userId] = session;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 已托管的对局(实现 IGameSession,暴露给游戏模式模组 / 服务器插件)
|
||||||
|
/// </summary>
|
||||||
|
public class HostedGame : IGameSession
|
||||||
|
{
|
||||||
|
private readonly GameRoundRecordSink _sink;
|
||||||
|
private readonly Func<Guid, bool, Task> _endGame;
|
||||||
|
|
||||||
|
public HostedGame(Guid id, string mode, GamingQueue? queue, GameRoundRecordSink sink, IGameModuleServer? module = null, Func<Guid, bool, Task>? endGame = null)
|
||||||
|
{
|
||||||
|
Id = id;
|
||||||
|
Mode = mode;
|
||||||
|
Queue = queue!;
|
||||||
|
_sink = sink;
|
||||||
|
Module = module;
|
||||||
|
_endGame = endGame ?? ((_, _) => Task.CompletedTask);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Guid Id { get; }
|
||||||
|
public GamingQueue Queue { get; internal set; } = null!;
|
||||||
|
public string Mode { get; }
|
||||||
|
public IGameModuleServer? Module { get; }
|
||||||
|
public bool Running { get; private set; } = true;
|
||||||
|
public volatile bool Paused;
|
||||||
|
|
||||||
|
public ConcurrentDictionary<long, ClientSession> Clients { get; } = [];
|
||||||
|
|
||||||
|
IReadOnlyDictionary<long, IClientSession> IGameSession.Clients => Clients.ToDictionary(kv => kv.Key, kv => (IClientSession)kv.Value);
|
||||||
|
|
||||||
|
public Dictionary<string, object> CustomData { get; } = [];
|
||||||
|
|
||||||
|
public IReadOnlyList<Character> Characters => Queue.AllCharacters;
|
||||||
|
|
||||||
|
public GameRoundRecordSink Sink => _sink;
|
||||||
|
|
||||||
|
public void End(bool aborted)
|
||||||
|
{
|
||||||
|
Running = false;
|
||||||
|
_sink.End();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>广播消息给本局全部用户(userIds 为空)或指定用户(供 GameModule 使用)</summary>
|
||||||
|
public async Task BroadcastAsync(string messageType, Dictionary<string, object> data, params long[] userIds)
|
||||||
|
{
|
||||||
|
MessageEnvelope message = MessageEnvelope.Broadcast(messageType, data);
|
||||||
|
if (userIds.Length == 0)
|
||||||
|
{
|
||||||
|
foreach (ClientSession session in Clients.Values)
|
||||||
|
{
|
||||||
|
await session.SendAsync(message);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
foreach (long userId in userIds)
|
||||||
|
{
|
||||||
|
if (Clients.TryGetValue(userId, out ClientSession? session))
|
||||||
|
{
|
||||||
|
await session.SendAsync(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>结束对局(宿主负责归档与广播结算)</summary>
|
||||||
|
public Task EndGameAsync(bool aborted = false) => _endGame(Id, aborted);
|
||||||
|
|
||||||
|
/// <summary>等待对局结束并复位房间(供房间开始对局流程使用)</summary>
|
||||||
|
public async Task WaitGameOverAsync(RoomService rooms, string roomId, ILogger logger)
|
||||||
|
{
|
||||||
|
while (Running)
|
||||||
|
{
|
||||||
|
await Task.Delay(500);
|
||||||
|
}
|
||||||
|
await rooms.ResetRoomAsync(roomId);
|
||||||
|
logger.LogInformation("房间 {RoomId} 已复位(对局 {GameId} 结束)", roomId, Id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,291 @@
|
|||||||
|
using System.IO.Compression;
|
||||||
|
using System.Text.Json;
|
||||||
|
using FunGame.Core.Api;
|
||||||
|
using FunGame.Core.Entity;
|
||||||
|
using FunGame.Core.Interface.Base;
|
||||||
|
using FunGame.Core.Model.Framework;
|
||||||
|
using FunGame.Server.Infrastructure.Data;
|
||||||
|
using FunGame.Server.Infrastructure.Entities.Game;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 回合记录外发实现(Core v3 IRoundRecordSink)<para/>
|
||||||
|
/// - 本地归档:records/{gameId}.zip(rounds_data.json,与 Testing-v3 回放格式兼容)+ RoundRecords 表行<para/>
|
||||||
|
/// - 远程转发:配置 RoundRecordSink:PostUrl 时内部包装 Core 的 DefaultRoundRecordSink 即时 POST
|
||||||
|
/// </summary>
|
||||||
|
public sealed class GameRoundRecordSink : IRoundRecordSink, IDisposable
|
||||||
|
{
|
||||||
|
private readonly Guid _gameId;
|
||||||
|
private readonly string _mode;
|
||||||
|
private readonly string _archiveDirectory;
|
||||||
|
private readonly IServiceScopeFactory _scopeFactory;
|
||||||
|
private readonly ILogger<GameRoundRecordSink> _logger;
|
||||||
|
private readonly DefaultRoundRecordSink? _remote;
|
||||||
|
private readonly Lock _lock = new();
|
||||||
|
|
||||||
|
private readonly Dictionary<int, RoundRecord> _rounds = [];
|
||||||
|
private Dictionary<Guid, CharacterStatistics>? _statistics;
|
||||||
|
private List<Character>? _characters;
|
||||||
|
private List<Team>? _teams;
|
||||||
|
private Guid _queueId;
|
||||||
|
private bool _ended;
|
||||||
|
|
||||||
|
public GameRoundRecordSink(Guid gameId, string mode, IServiceScopeFactory scopeFactory, IConfiguration configuration, ILogger<GameRoundRecordSink> logger)
|
||||||
|
{
|
||||||
|
_gameId = gameId;
|
||||||
|
_mode = mode;
|
||||||
|
_scopeFactory = scopeFactory;
|
||||||
|
_logger = logger;
|
||||||
|
_archiveDirectory = configuration["RoundRecordSink:ArchiveDirectory"] ?? "records";
|
||||||
|
|
||||||
|
string? postUrl = configuration["RoundRecordSink:PostUrl"];
|
||||||
|
if (!string.IsNullOrWhiteSpace(postUrl))
|
||||||
|
{
|
||||||
|
string[] intents = configuration.GetSection("RoundRecordSink:Intents").Get<string[]>() ?? ["0", "1", "2", "3", "4", "5", "6", "7", "8"];
|
||||||
|
_remote = new DefaultRoundRecordSink(postUrl, intents)
|
||||||
|
{
|
||||||
|
AccessToken = configuration["RoundRecordSink:AccessToken"] ?? "",
|
||||||
|
Secret = configuration["RoundRecordSink:Secret"] ?? ""
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>回合记录更新事件(供宿主做 WS 实时推送)</summary>
|
||||||
|
public event Action<RoundRecord>? RoundRecorded;
|
||||||
|
|
||||||
|
public void Attach(Guid queueId)
|
||||||
|
{
|
||||||
|
_queueId = queueId;
|
||||||
|
_remote?.Attach(queueId);
|
||||||
|
// 登记对局记录索引
|
||||||
|
_ = Task.Run(async () =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using IServiceScope scope = _scopeFactory.CreateScope();
|
||||||
|
AppDbContext db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||||
|
db.GameRecords.Add(new GameRecord
|
||||||
|
{
|
||||||
|
Id = _gameId,
|
||||||
|
QueueId = queueId,
|
||||||
|
Mode = _mode,
|
||||||
|
State = GameState.Running,
|
||||||
|
ArchivePath = ArchiveFileName
|
||||||
|
});
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError(e, "登记对局记录失败:{GameId}", _gameId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>归档最终化任务(End 后可用 await 等待归档完成)</summary>
|
||||||
|
public Task FinalizeTask { get; private set; } = Task.CompletedTask;
|
||||||
|
|
||||||
|
public void End()
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (_ended) return;
|
||||||
|
_ended = true;
|
||||||
|
}
|
||||||
|
_remote?.End();
|
||||||
|
// 对局结束时队列还会外发最终统计/检查点事件,延迟归档以保证完整落盘
|
||||||
|
FinalizeTask = Task.Run(async () =>
|
||||||
|
{
|
||||||
|
await Task.Delay(1000);
|
||||||
|
FinalizeArchive();
|
||||||
|
_remote?.Dispose();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== IRoundRecordSink 事件 =====
|
||||||
|
|
||||||
|
public void SendAction(ActionRecord action)
|
||||||
|
{
|
||||||
|
_remote?.SendAction(action);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SendRound(RoundRecord round)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
_rounds[round.Round] = round;
|
||||||
|
}
|
||||||
|
_remote?.SendRound(round);
|
||||||
|
RoundRecorded?.Invoke(round);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SendCheckpointRound(RoundRecord round)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
_rounds[round.Round] = round;
|
||||||
|
}
|
||||||
|
_remote?.SendCheckpointRound(round);
|
||||||
|
RoundRecorded?.Invoke(round);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SendCharacterStatistics(Dictionary<Guid, CharacterStatistics> statistics)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
_statistics = statistics;
|
||||||
|
}
|
||||||
|
_remote?.SendCharacterStatistics(statistics);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SendCharacters(IEnumerable<Character> characters)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
_characters = [.. characters];
|
||||||
|
}
|
||||||
|
_remote?.SendCharacters(characters);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SendTeams(IEnumerable<Team> teams)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
_teams = [.. teams];
|
||||||
|
}
|
||||||
|
_remote?.SendTeams(teams);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SendQueueData(Dictionary<Guid, double> queueData)
|
||||||
|
{
|
||||||
|
_remote?.SendQueueData(queueData);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SendEliminatedCharacters(IEnumerable<string> characterGuids)
|
||||||
|
{
|
||||||
|
_remote?.SendEliminatedCharacters(characterGuids);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SendEliminatedTeams(IEnumerable<string> teamNames)
|
||||||
|
{
|
||||||
|
_remote?.SendEliminatedTeams(teamNames);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 归档 =====
|
||||||
|
|
||||||
|
private string ArchiveFileName => $"{_gameId:N}.zip";
|
||||||
|
|
||||||
|
private string ArchiveFilePath => Path.Combine(_archiveDirectory, ArchiveFileName);
|
||||||
|
|
||||||
|
private void FinalizeArchive()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<int, RoundRecord> rounds;
|
||||||
|
Dictionary<Guid, CharacterStatistics>? statistics;
|
||||||
|
List<Character>? characters;
|
||||||
|
List<Team>? teams;
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
rounds = new Dictionary<int, RoundRecord>(_rounds);
|
||||||
|
statistics = _statistics != null ? new Dictionary<Guid, CharacterStatistics>(_statistics) : null;
|
||||||
|
characters = _characters;
|
||||||
|
teams = _teams;
|
||||||
|
}
|
||||||
|
if (rounds.Count == 0)
|
||||||
|
{
|
||||||
|
_logger.LogWarning("对局 {GameId} 没有回合记录,跳过归档", _gameId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Directory.CreateDirectory(_archiveDirectory);
|
||||||
|
string path = ArchiveFilePath;
|
||||||
|
|
||||||
|
using (FileStream stream = new(path, FileMode.Create))
|
||||||
|
using (ZipArchive archive = new(stream, ZipArchiveMode.Create))
|
||||||
|
{
|
||||||
|
ZipArchiveEntry entry = archive.CreateEntry("rounds_data.json", CompressionLevel.Optimal);
|
||||||
|
using (Stream entryStream = entry.Open())
|
||||||
|
{
|
||||||
|
JsonSerializer.Serialize(entryStream, rounds, JsonService.GeneralOptions);
|
||||||
|
}
|
||||||
|
if (statistics is { Count: > 0 })
|
||||||
|
{
|
||||||
|
ZipArchiveEntry statsEntry = archive.CreateEntry("statistics.json", CompressionLevel.Optimal);
|
||||||
|
using Stream statsStream = statsEntry.Open();
|
||||||
|
JsonSerializer.Serialize(statsStream, statistics, JsonService.GeneralOptions);
|
||||||
|
}
|
||||||
|
if (characters is { Count: > 0 })
|
||||||
|
{
|
||||||
|
ZipArchiveEntry charactersEntry = archive.CreateEntry("characters.json", CompressionLevel.Optimal);
|
||||||
|
using Stream charactersStream = charactersEntry.Open();
|
||||||
|
JsonSerializer.Serialize(charactersStream, characters, JsonService.GeneralOptions);
|
||||||
|
}
|
||||||
|
if (teams is { Count: > 0 })
|
||||||
|
{
|
||||||
|
ZipArchiveEntry teamsEntry = archive.CreateEntry("teams.json", CompressionLevel.Optimal);
|
||||||
|
using Stream teamsStream = teamsEntry.Open();
|
||||||
|
JsonSerializer.Serialize(teamsStream, teams, JsonService.GeneralOptions);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogInformation("对局 {GameId} 回合记录已归档:{Path}({Rounds} 回合,统计 {Stats} 项)",
|
||||||
|
_gameId, path, rounds.Count, statistics?.Count ?? 0);
|
||||||
|
|
||||||
|
// 更新数据库
|
||||||
|
_ = Task.Run(async () =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using IServiceScope scope = _scopeFactory.CreateScope();
|
||||||
|
AppDbContext db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||||
|
GameRecord? record = await db.GameRecords.FirstOrDefaultAsync(g => g.Id == _gameId);
|
||||||
|
if (record != null)
|
||||||
|
{
|
||||||
|
record.State = GameState.Finished;
|
||||||
|
record.EndedAt = DateTime.Now;
|
||||||
|
record.TotalRounds = rounds.Count;
|
||||||
|
record.ArchivePath = ArchiveFileName;
|
||||||
|
|
||||||
|
RoundRecord? last = rounds.Values.OrderBy(r => r.Round).LastOrDefault();
|
||||||
|
RankingEntry? winner = last?.GameResult.FirstOrDefault(e => e.IsWinner);
|
||||||
|
record.Winner = winner?.IsTeam == true ? winner.Team?.Name : winner?.Character?.Name;
|
||||||
|
|
||||||
|
foreach (KeyValuePair<int, RoundRecord> kv in rounds)
|
||||||
|
{
|
||||||
|
db.RoundRecords.Add(new RoundRecordEntity
|
||||||
|
{
|
||||||
|
GameId = _gameId,
|
||||||
|
Round = kv.Key,
|
||||||
|
ActorGuid = kv.Value.Actor?.Guid.ToString() ?? "",
|
||||||
|
ActorName = kv.Value.Actor?.Name ?? "",
|
||||||
|
HasKill = kv.Value.HasKill,
|
||||||
|
TotalDamage = Math.Round(kv.Value.Damages.Values.Sum(), 2),
|
||||||
|
TotalHeal = Math.Round(kv.Value.Heals.Values.Sum(), 2),
|
||||||
|
RecordJson = JsonService.GetString(kv.Value),
|
||||||
|
IsCheckpoint = kv.Value.Checkpoint is { Count: > 0 },
|
||||||
|
CreatedAt = DateTime.Now
|
||||||
|
});
|
||||||
|
}
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError(e, "写入对局记录数据库失败:{GameId}", _gameId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError(e, "对局记录归档失败:{GameId}", _gameId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
End();
|
||||||
|
GC.SuppressFinalize(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
using System.IO.Compression;
|
||||||
|
using System.Text.Json;
|
||||||
|
using FunGame.Core.Api;
|
||||||
|
using FunGame.Core.Entity;
|
||||||
|
using FunGame.Core.Model.Framework;
|
||||||
|
using FunGame.Server.Infrastructure.Data;
|
||||||
|
using FunGame.Server.Infrastructure.Entities.Game;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 回放归档服务:读取 GameRoundRecordSink 归档的 records/{gameId}.zip(rounds_data.json)<para/>
|
||||||
|
/// 格式与 Testing-v3 兼容:zip 内含 rounds_data.json = Dictionary<int, RoundRecord>
|
||||||
|
/// </summary>
|
||||||
|
public class ReplayArchiveService(IServiceScopeFactory scopeFactory, IConfiguration configuration, ILogger<ReplayArchiveService> logger)
|
||||||
|
{
|
||||||
|
private readonly string _archiveDirectory = configuration["RoundRecordSink:ArchiveDirectory"] ?? "records";
|
||||||
|
|
||||||
|
/// <summary>取对局记录(GameRecords 行)</summary>
|
||||||
|
public async Task<GameRecord?> GetGameRecordAsync(Guid id)
|
||||||
|
{
|
||||||
|
using IServiceScope scope = scopeFactory.CreateScope();
|
||||||
|
AppDbContext db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||||
|
return await db.GameRecords.AsNoTracking().FirstOrDefaultAsync(g => g.Id == id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>读取全部回合</summary>
|
||||||
|
public Dictionary<int, RoundRecord>? ReadRounds(GameRecord record)
|
||||||
|
{
|
||||||
|
string path = GetArchivePath(record);
|
||||||
|
if (!File.Exists(path))
|
||||||
|
{
|
||||||
|
logger.LogWarning("对局 {GameId} 的归档文件不存在:{Path}", record.Id, path);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using FileStream stream = new(path, FileMode.Open);
|
||||||
|
using ZipArchive archive = new(stream, ZipArchiveMode.Read);
|
||||||
|
ZipArchiveEntry? entry = archive.GetEntry("rounds_data.json");
|
||||||
|
if (entry == null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
using Stream entryStream = entry.Open();
|
||||||
|
return JsonSerializer.Deserialize<Dictionary<int, RoundRecord>>(entryStream, JsonService.GeneralOptions);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
logger.LogError(e, "读取对局归档失败:{Path}", path);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public string GetArchivePath(GameRecord record) => Path.Combine(_archiveDirectory, record.ArchivePath);
|
||||||
|
|
||||||
|
/// <summary>读取归档中的最终角色统计(statistics.json)</summary>
|
||||||
|
public Dictionary<Guid, CharacterStatistics>? ReadStatistics(GameRecord record)
|
||||||
|
{
|
||||||
|
string path = GetArchivePath(record);
|
||||||
|
if (!File.Exists(path))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using FileStream stream = new(path, FileMode.Open);
|
||||||
|
using ZipArchive archive = new(stream, ZipArchiveMode.Read);
|
||||||
|
ZipArchiveEntry? entry = archive.GetEntry("statistics.json");
|
||||||
|
if (entry == null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
using Stream entryStream = entry.Open();
|
||||||
|
return JsonSerializer.Deserialize<Dictionary<Guid, CharacterStatistics>>(entryStream, JsonService.GeneralOptions);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
logger.LogError(e, "读取对局统计归档失败:{Path}", path);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using FunGame.Core.Entity;
|
||||||
|
using FunGame.Server.Contracts.Payloads;
|
||||||
|
using FunGame.Server.Host.Networking;
|
||||||
|
using FunGame.Server.Infrastructure.Data;
|
||||||
|
using FunGame.Server.Infrastructure.Entities.Game;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Host.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 房间服务:房间持久化(EF)+ 内存成员表 + 聊天/开始对局
|
||||||
|
/// </summary>
|
||||||
|
public class RoomService(IServiceScopeFactory scopeFactory, ILogger<RoomService> logger)
|
||||||
|
{
|
||||||
|
/// <summary>房间号 -> (会话Id -> 会话)</summary>
|
||||||
|
private readonly ConcurrentDictionary<string, ConcurrentDictionary<long, ClientSession>> _members = new();
|
||||||
|
|
||||||
|
/// <summary>获取客户端所在房间号</summary>
|
||||||
|
public string? GetRoomOfClient(long sessionId)
|
||||||
|
=> _members.FirstOrDefault(kv => kv.Value.ContainsKey(sessionId)).Key;
|
||||||
|
|
||||||
|
public IReadOnlyCollection<ClientSession> GetMembers(string roomId)
|
||||||
|
=> _members.TryGetValue(roomId, out ConcurrentDictionary<long, ClientSession>? members)
|
||||||
|
? members.Values.ToArray()
|
||||||
|
: [];
|
||||||
|
|
||||||
|
public async Task<RoomEntity?> GetRoomAsync(string roomId)
|
||||||
|
{
|
||||||
|
using IServiceScope scope = scopeFactory.CreateScope();
|
||||||
|
AppDbContext db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||||
|
return await db.Rooms.AsNoTracking().FirstOrDefaultAsync(r => r.RoomId == roomId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<List<RoomEntity>> ListRoomsAsync()
|
||||||
|
{
|
||||||
|
using IServiceScope scope = scopeFactory.CreateScope();
|
||||||
|
AppDbContext db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||||
|
return await db.Rooms.AsNoTracking().Where(r => r.State != RoomStateEntity.Gaming).OrderByDescending(r => r.CreatedAt).Take(50).ToListAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<RoomEntity> CreateRoomAsync(long masterUserId, string gameModule, string contentModule, string gameMap, int maxUsers, bool isRank, string? password)
|
||||||
|
{
|
||||||
|
string roomId = GenerateRoomId();
|
||||||
|
using IServiceScope scope = scopeFactory.CreateScope();
|
||||||
|
AppDbContext db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||||
|
|
||||||
|
RoomEntity room = new()
|
||||||
|
{
|
||||||
|
RoomId = roomId,
|
||||||
|
MasterUserId = masterUserId,
|
||||||
|
GameModule = gameModule,
|
||||||
|
ContentModule = contentModule,
|
||||||
|
GameMap = gameMap,
|
||||||
|
MaxUsers = Math.Clamp(maxUsers, 2, 20),
|
||||||
|
IsRank = isRank,
|
||||||
|
PasswordHash = string.IsNullOrEmpty(password) ? null : Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(password))),
|
||||||
|
State = RoomStateEntity.Created
|
||||||
|
};
|
||||||
|
db.Rooms.Add(room);
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
logger.LogInformation("房间创建:{RoomId}(游戏模式 {Module},内容模组 {ContentModule},地图 {Map})", roomId, gameModule, contentModule, gameMap);
|
||||||
|
return room;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>进入房间</summary>
|
||||||
|
public async Task<(bool Success, string Message)> JoinAsync(RoomEntity room, ClientSession client, string? password = null)
|
||||||
|
{
|
||||||
|
if (room.State != RoomStateEntity.Created)
|
||||||
|
{
|
||||||
|
return (false, "该房间状态不允许进入。");
|
||||||
|
}
|
||||||
|
if (room.PasswordHash != null)
|
||||||
|
{
|
||||||
|
string? input = password;
|
||||||
|
if (string.IsNullOrEmpty(input))
|
||||||
|
{
|
||||||
|
return (false, "该房间需要密码。");
|
||||||
|
}
|
||||||
|
string hash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(input)));
|
||||||
|
if (hash != room.PasswordHash)
|
||||||
|
{
|
||||||
|
return (false, "房间密码错误。");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ConcurrentDictionary<long, ClientSession> members = _members.GetOrAdd(room.RoomId, _ => new());
|
||||||
|
if (members.Count >= room.MaxUsers && !members.ContainsKey(client.SessionId))
|
||||||
|
{
|
||||||
|
return (false, "房间人数已满。");
|
||||||
|
}
|
||||||
|
members[client.SessionId] = client;
|
||||||
|
return (true, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>退出房间(返回剩余人数)</summary>
|
||||||
|
public async Task<int> QuitAsync(string roomId, ClientSession client)
|
||||||
|
{
|
||||||
|
if (_members.TryGetValue(roomId, out ConcurrentDictionary<long, ClientSession>? members))
|
||||||
|
{
|
||||||
|
members.TryRemove(client.SessionId, out _);
|
||||||
|
if (members.IsEmpty)
|
||||||
|
{
|
||||||
|
_members.TryRemove(roomId, out _);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return members.Count;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>对局结束后复位房间</summary>
|
||||||
|
public async Task ResetRoomAsync(string roomId)
|
||||||
|
{
|
||||||
|
using IServiceScope scope = scopeFactory.CreateScope();
|
||||||
|
AppDbContext db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||||
|
RoomEntity? room = await db.Rooms.FirstOrDefaultAsync(r => r.RoomId == roomId);
|
||||||
|
if (room != null)
|
||||||
|
{
|
||||||
|
room.State = RoomStateEntity.Created;
|
||||||
|
room.UpdatedAt = DateTime.Now;
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task SetGamingAsync(string roomId)
|
||||||
|
{
|
||||||
|
using IServiceScope scope = scopeFactory.CreateScope();
|
||||||
|
AppDbContext db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||||
|
RoomEntity? room = await db.Rooms.FirstOrDefaultAsync(r => r.RoomId == roomId);
|
||||||
|
if (room != null)
|
||||||
|
{
|
||||||
|
room.State = RoomStateEntity.Gaming;
|
||||||
|
room.UpdatedAt = DateTime.Now;
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>7 位大写随机房间号(防重复)</summary>
|
||||||
|
private string GenerateRoomId()
|
||||||
|
{
|
||||||
|
const string chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
string id = string.Create(7, Random.Shared, (span, r) =>
|
||||||
|
{
|
||||||
|
for (int i = 0; i < span.Length; i++)
|
||||||
|
{
|
||||||
|
span[i] = chars[r.Next(chars.Length)];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
using IServiceScope scope = scopeFactory.CreateScope();
|
||||||
|
AppDbContext db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||||
|
if (!db.Rooms.Any(r => r.RoomId == id))
|
||||||
|
{
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"Logging": {
|
||||||
|
"LogLevel": {
|
||||||
|
"Default": "Debug",
|
||||||
|
"Microsoft.AspNetCore": "Information"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
{
|
||||||
|
"Logging": {
|
||||||
|
"LogLevel": {
|
||||||
|
"Default": "Information",
|
||||||
|
"Microsoft.AspNetCore": "Warning",
|
||||||
|
"Microsoft.EntityFrameworkCore": "Warning"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"AllowedHosts": "*",
|
||||||
|
"Urls": "http://0.0.0.0:5000",
|
||||||
|
"AllowOrigins": [
|
||||||
|
"http://localhost:5173",
|
||||||
|
"http://127.0.0.1:5173",
|
||||||
|
"http://localhost:5174",
|
||||||
|
"http://127.0.0.1:5174"
|
||||||
|
],
|
||||||
|
"Database": {
|
||||||
|
"Provider": "Sqlite"
|
||||||
|
},
|
||||||
|
"ConnectionStrings": {
|
||||||
|
"Sqlite": "Data Source=Data/fungame-server.db",
|
||||||
|
"MySql": "Server=localhost;Port=3306;Database=fungame_server;User=root;Password=;SslMode=Preferred;CharSet=utf8mb4;"
|
||||||
|
},
|
||||||
|
"Jwt": {
|
||||||
|
"Key": "c73fca290ba9f9ad4b763586e6aede15997f1a127fc82e58df27a90ad24a18eb",
|
||||||
|
"Issuer": "FunGame.Server",
|
||||||
|
"Audience": "FunGame.Server.Clients",
|
||||||
|
"AccessTokenMinutes": 30,
|
||||||
|
"RefreshTokenDays": 14
|
||||||
|
},
|
||||||
|
"Server": {
|
||||||
|
"Name": "FunGame Server v3",
|
||||||
|
"Description": "基于 FunGame.Core v3 的服务器",
|
||||||
|
"Notice": "欢迎来到 FunGame Server v3!",
|
||||||
|
"MaxPlayers": 100,
|
||||||
|
"Debug": false,
|
||||||
|
"MaxGameRounds": 3000
|
||||||
|
},
|
||||||
|
"Plugins": {
|
||||||
|
"Directory": "plugins",
|
||||||
|
"Watch": true
|
||||||
|
},
|
||||||
|
"RoundRecordSink": {
|
||||||
|
"ArchiveDirectory": "records",
|
||||||
|
"PostUrl": "",
|
||||||
|
"AccessToken": "",
|
||||||
|
"Secret": "",
|
||||||
|
"Intents": []
|
||||||
|
},
|
||||||
|
"Bootstrap": {
|
||||||
|
"Admin": {
|
||||||
|
"Username": "admin",
|
||||||
|
"Password": "admin123456",
|
||||||
|
"Email": "admin@localhost",
|
||||||
|
"Nickname": "Administrator"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Kestrel": {
|
||||||
|
"EndpointDefaults": {
|
||||||
|
"Protocols": "Http1AndHttp2"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
using FunGame.Server.Infrastructure.Entities.Economy;
|
||||||
|
using FunGame.Server.Infrastructure.Entities.Game;
|
||||||
|
using FunGame.Server.Infrastructure.Entities.Identity;
|
||||||
|
using FunGame.Server.Infrastructure.Entities.System;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Infrastructure.Data;
|
||||||
|
|
||||||
|
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
|
||||||
|
{
|
||||||
|
// ===== 认证与用户中心 =====
|
||||||
|
public DbSet<User> Users => Set<User>();
|
||||||
|
public DbSet<UserProfile> UserProfiles => Set<UserProfile>();
|
||||||
|
public DbSet<Role> Roles => Set<Role>();
|
||||||
|
public DbSet<Permission> Permissions => Set<Permission>();
|
||||||
|
public DbSet<UserRole> UserRoles => Set<UserRole>();
|
||||||
|
public DbSet<RolePermission> RolePermissions => Set<RolePermission>();
|
||||||
|
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
|
||||||
|
public DbSet<UserSession> UserSessions => Set<UserSession>();
|
||||||
|
public DbSet<LoginLog> LoginLogs => Set<LoginLog>();
|
||||||
|
public DbSet<ApiToken> ApiTokens => Set<ApiToken>();
|
||||||
|
|
||||||
|
// ===== 游戏业务 =====
|
||||||
|
public DbSet<RoomEntity> Rooms => Set<RoomEntity>();
|
||||||
|
public DbSet<UserCharacter> UserCharacters => Set<UserCharacter>();
|
||||||
|
public DbSet<UserItem> UserItems => Set<UserItem>();
|
||||||
|
public DbSet<Inventory> Inventories => Set<Inventory>();
|
||||||
|
public DbSet<GameRecord> GameRecords => Set<GameRecord>();
|
||||||
|
public DbSet<RoundRecordEntity> RoundRecords => Set<RoundRecordEntity>();
|
||||||
|
|
||||||
|
// ===== 经济 =====
|
||||||
|
public DbSet<Store> Stores => Set<Store>();
|
||||||
|
public DbSet<StoreGoods> StoreGoods => Set<StoreGoods>();
|
||||||
|
public DbSet<Goods> Goods => Set<Goods>();
|
||||||
|
public DbSet<GoodsPrice> GoodsPrices => Set<GoodsPrice>();
|
||||||
|
public DbSet<MarketItem> MarketItems => Set<MarketItem>();
|
||||||
|
public DbSet<Offer> Offers => Set<Offer>();
|
||||||
|
public DbSet<OfferItem> OfferItems => Set<OfferItem>();
|
||||||
|
|
||||||
|
// ===== 系统 =====
|
||||||
|
public DbSet<ServerLog> ServerLogs => Set<ServerLog>();
|
||||||
|
public DbSet<SystemConfig> SystemConfigs => Set<SystemConfig>();
|
||||||
|
public DbSet<VerifyCode> VerifyCodes => Set<VerifyCode>();
|
||||||
|
public DbSet<UserSignIn> UserSignIns => Set<UserSignIn>();
|
||||||
|
|
||||||
|
protected override void OnModelCreating(ModelBuilder builder)
|
||||||
|
{
|
||||||
|
base.OnModelCreating(builder);
|
||||||
|
|
||||||
|
// ===== Users =====
|
||||||
|
builder.Entity<User>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("users");
|
||||||
|
e.HasIndex(u => u.Username).IsUnique();
|
||||||
|
e.HasIndex(u => u.Email);
|
||||||
|
e.Property(u => u.Id).ValueGeneratedOnAdd();
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<UserProfile>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("user_profiles");
|
||||||
|
e.HasOne(p => p.User).WithOne(u => u.Profile).HasForeignKey<UserProfile>(p => p.UserId).OnDelete(DeleteBehavior.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<Role>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("roles");
|
||||||
|
e.HasIndex(r => r.Code).IsUnique();
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<Permission>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("permissions");
|
||||||
|
e.HasIndex(p => p.Code).IsUnique();
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<UserRole>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("user_roles");
|
||||||
|
e.HasKey(ur => new { ur.UserId, ur.RoleId });
|
||||||
|
e.HasOne(ur => ur.User).WithMany(u => u.UserRoles).HasForeignKey(ur => ur.UserId).OnDelete(DeleteBehavior.Cascade);
|
||||||
|
e.HasOne(ur => ur.Role).WithMany(r => r.UserRoles).HasForeignKey(ur => ur.RoleId).OnDelete(DeleteBehavior.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<RolePermission>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("role_permissions");
|
||||||
|
e.HasKey(rp => new { rp.RoleId, rp.PermissionId });
|
||||||
|
e.HasOne(rp => rp.Role).WithMany(r => r.RolePermissions).HasForeignKey(rp => rp.RoleId).OnDelete(DeleteBehavior.Cascade);
|
||||||
|
e.HasOne(rp => rp.Permission).WithMany(p => p.RolePermissions).HasForeignKey(rp => rp.PermissionId).OnDelete(DeleteBehavior.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<RefreshToken>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("refresh_tokens");
|
||||||
|
e.HasIndex(t => t.TokenHash).IsUnique();
|
||||||
|
e.HasOne(t => t.User).WithMany(u => u.RefreshTokens).HasForeignKey(t => t.UserId).OnDelete(DeleteBehavior.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<UserSession>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("user_sessions");
|
||||||
|
e.HasIndex(s => new { s.UserId, s.Endpoint });
|
||||||
|
e.HasOne(s => s.User).WithMany(u => u.Sessions).HasForeignKey(s => s.UserId).OnDelete(DeleteBehavior.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<LoginLog>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("login_logs");
|
||||||
|
e.HasIndex(l => new { l.UserId, l.CreatedAt });
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<ApiToken>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("api_tokens");
|
||||||
|
e.HasIndex(t => t.TokenId).IsUnique();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ===== 游戏 =====
|
||||||
|
builder.Entity<RoomEntity>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("rooms");
|
||||||
|
e.HasKey(r => r.RoomId);
|
||||||
|
e.HasIndex(r => r.State);
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<UserCharacter>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("user_characters");
|
||||||
|
e.HasIndex(c => c.UserId);
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<UserItem>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("user_items");
|
||||||
|
e.HasIndex(i => i.UserId);
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<Inventory>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("inventories");
|
||||||
|
e.HasKey(i => i.UserId);
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<GameRecord>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("game_records");
|
||||||
|
e.HasIndex(g => g.QueueId).IsUnique();
|
||||||
|
e.HasIndex(g => g.StartedAt);
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<RoundRecordEntity>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("round_records");
|
||||||
|
e.HasIndex(r => new { r.GameId, r.Round }).IsUnique();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ===== 经济 =====
|
||||||
|
builder.Entity<Store>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("stores");
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<StoreGoods>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("store_goods");
|
||||||
|
e.HasKey(sg => new { sg.StoreId, sg.GoodsId });
|
||||||
|
e.HasOne(sg => sg.Store).WithMany(s => s.StoreGoods).HasForeignKey(sg => sg.StoreId).OnDelete(DeleteBehavior.Cascade);
|
||||||
|
e.HasOne(sg => sg.Goods).WithMany(g => g.StoreGoods).HasForeignKey(sg => sg.GoodsId).OnDelete(DeleteBehavior.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<Goods>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("goods");
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<GoodsPrice>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("goods_prices");
|
||||||
|
e.HasOne(p => p.Goods).WithMany(g => g.Prices).HasForeignKey(p => p.GoodsId).OnDelete(DeleteBehavior.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<MarketItem>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("market_items");
|
||||||
|
e.HasIndex(m => m.ItemGuid);
|
||||||
|
e.HasIndex(m => m.SellerUserId);
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<Offer>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("offers");
|
||||||
|
e.HasIndex(o => new { o.OfferorUserId, o.OffereeUserId });
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<OfferItem>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("offer_items");
|
||||||
|
e.HasOne(i => i.Offer).WithMany(o => o.Items).HasForeignKey(i => i.OfferId).OnDelete(DeleteBehavior.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ===== 系统 =====
|
||||||
|
builder.Entity<ServerLog>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("server_logs");
|
||||||
|
e.HasIndex(l => l.CreatedAt);
|
||||||
|
e.HasIndex(l => l.Level);
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<SystemConfig>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("system_configs");
|
||||||
|
e.HasKey(c => c.Key);
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<VerifyCode>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("verify_codes");
|
||||||
|
e.HasIndex(v => new { v.Purpose, v.Username });
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Entity<UserSignIn>(e =>
|
||||||
|
{
|
||||||
|
e.ToTable("user_sign_ins");
|
||||||
|
e.HasIndex(s => s.UserId).IsUnique();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Design;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Infrastructure.Data;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 设计时工厂(dotnet-ef 迁移使用)<para/>
|
||||||
|
/// 依次向上查找 appsettings.json(优先 Host 项目的配置),未找到时回退到默认 SQLite
|
||||||
|
/// </summary>
|
||||||
|
public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
|
||||||
|
{
|
||||||
|
public AppDbContext CreateDbContext(string[] args)
|
||||||
|
{
|
||||||
|
ConfigurationBuilder builder = new();
|
||||||
|
builder.SetBasePath(Directory.GetCurrentDirectory());
|
||||||
|
|
||||||
|
// 查找 appsettings.json:当前目录、Infrastructure 目录上两级(src/..)、repo 根、Host 目录
|
||||||
|
foreach (string candidate in EnumerateCandidateConfigPaths())
|
||||||
|
{
|
||||||
|
if (File.Exists(candidate))
|
||||||
|
{
|
||||||
|
builder.AddJsonFile(candidate, optional: false, reloadOnChange: false);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
IConfiguration configuration = builder.Build();
|
||||||
|
return new AppDbContext(DbContextOptionsFactory.Create(configuration));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IEnumerable<string> EnumerateCandidateConfigPaths()
|
||||||
|
{
|
||||||
|
yield return Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
|
||||||
|
string? baseDir = AppContext.BaseDirectory;
|
||||||
|
for (int i = 0; i < 6 && baseDir != null; i++)
|
||||||
|
{
|
||||||
|
baseDir = Directory.GetParent(baseDir)?.FullName;
|
||||||
|
if (baseDir == null) break;
|
||||||
|
yield return Path.Combine(baseDir, "src", "FunGame.Server.Host", "appsettings.json");
|
||||||
|
yield return Path.Combine(baseDir, "appsettings.json");
|
||||||
|
}
|
||||||
|
yield return Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "..", "FunGame.Server.Host", "appsettings.json");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Infrastructure.Data;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// AppDbContext 选项工厂:按 Database:Provider 切换 SQLite / MySQL
|
||||||
|
/// </summary>
|
||||||
|
public static class DbContextOptionsFactory
|
||||||
|
{
|
||||||
|
public const string ProviderSqlite = "Sqlite";
|
||||||
|
public const string ProviderMySql = "MySql";
|
||||||
|
|
||||||
|
public static void Configure(DbContextOptionsBuilder builder, IConfiguration configuration)
|
||||||
|
{
|
||||||
|
string provider = configuration["Database:Provider"] ?? ProviderSqlite;
|
||||||
|
|
||||||
|
if (provider.Equals(ProviderMySql, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
string connectionString = configuration.GetConnectionString(ProviderMySql)
|
||||||
|
?? configuration["Database:ConnectionStrings:MySql"]
|
||||||
|
?? throw new InvalidOperationException("未配置 MySQL 连接字符串(ConnectionStrings:MySql)。");
|
||||||
|
builder.UseMySQL(connectionString, options =>
|
||||||
|
{
|
||||||
|
options.MigrationsAssembly(typeof(AppDbContext).Assembly.FullName);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
string connectionString = configuration.GetConnectionString(ProviderSqlite)
|
||||||
|
?? configuration["Database:ConnectionStrings:Sqlite"]
|
||||||
|
?? "Data Source=Data/fungame-server.db";
|
||||||
|
builder.UseSqlite(connectionString, options =>
|
||||||
|
{
|
||||||
|
options.MigrationsAssembly(typeof(AppDbContext).Assembly.FullName);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static DbContextOptions<AppDbContext> Create(IConfiguration configuration)
|
||||||
|
{
|
||||||
|
DbContextOptionsBuilder<AppDbContext> builder = new();
|
||||||
|
Configure(builder, configuration);
|
||||||
|
return builder.Options;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
using FunGame.Server.Contracts.Constants;
|
||||||
|
using FunGame.Server.Infrastructure.Entities.Identity;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.AspNetCore.Identity;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Infrastructure.Data;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 数据库种子服务:权限点、系统角色、初始管理员(仅首次启动)
|
||||||
|
/// </summary>
|
||||||
|
public class DbSeedService(AppDbContext db, ILogger<DbSeedService> logger, IConfiguration configuration)
|
||||||
|
{
|
||||||
|
/// <summary>系统角色代码</summary>
|
||||||
|
public const string AdminRole = "admin";
|
||||||
|
public const string ModeratorRole = "moderator";
|
||||||
|
public const string UserRoleCode = "user";
|
||||||
|
|
||||||
|
public async Task SeedAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await SeedPermissionsAsync(cancellationToken);
|
||||||
|
await SeedRolesAsync(cancellationToken);
|
||||||
|
await SeedAdminAsync(cancellationToken);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
logger.LogError(e, "数据库种子数据初始化失败");
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SeedPermissionsAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
List<Permission> existing = await db.Permissions.ToListAsync(ct);
|
||||||
|
HashSet<string> codes = [.. existing.Select(p => p.Code)];
|
||||||
|
foreach ((string code, string description) in PermissionCodes.All)
|
||||||
|
{
|
||||||
|
if (codes.Contains(code)) continue;
|
||||||
|
string group = code.Split('.')[0];
|
||||||
|
string name = code.Split('.').Length > 1 ? char.ToUpper(code.Split('.')[1][0]) + code.Split('.')[1][1..] : code;
|
||||||
|
db.Permissions.Add(new Permission { Code = code, Name = name, Group = group, Description = description });
|
||||||
|
}
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
logger.LogInformation("权限点初始化完成({Count} 个)", PermissionCodes.All.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SeedRolesAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
List<Permission> allPermissions = await db.Permissions.ToListAsync(ct);
|
||||||
|
Dictionary<string, Permission> permMap = allPermissions.ToDictionary(p => p.Code);
|
||||||
|
|
||||||
|
Role? admin = await db.Roles.FirstOrDefaultAsync(r => r.Code == AdminRole, ct);
|
||||||
|
if (admin == null)
|
||||||
|
{
|
||||||
|
admin = new Role { Code = AdminRole, Name = "管理员", Description = "系统内置管理员角色(全部权限)", IsSystem = true };
|
||||||
|
db.Roles.Add(admin);
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
foreach (Permission permission in allPermissions)
|
||||||
|
{
|
||||||
|
db.RolePermissions.Add(new RolePermission { RoleId = admin.Id, PermissionId = permission.Id });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Role? user = await db.Roles.FirstOrDefaultAsync(r => r.Code == UserRoleCode, ct);
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
user = new Role { Code = UserRoleCode, Name = "普通用户", Description = "系统内置默认角色", IsSystem = true };
|
||||||
|
db.Roles.Add(user);
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
// 普通用户默认无管理权限
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
logger.LogInformation("系统角色初始化完成(admin / user)");
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SeedAdminAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (await db.Users.AnyAsync(ct))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
IConfigurationSection section = configuration.GetSection("Bootstrap:Admin");
|
||||||
|
string username = section["Username"] ?? "admin";
|
||||||
|
string password = section["Password"] ?? "admin123456";
|
||||||
|
string email = section["Email"] ?? "admin@localhost";
|
||||||
|
string nickname = section["Nickname"] ?? "Administrator";
|
||||||
|
|
||||||
|
PasswordHasher<User> hasher = new();
|
||||||
|
User adminUser = new()
|
||||||
|
{
|
||||||
|
Username = username,
|
||||||
|
Email = email,
|
||||||
|
EmailVerified = true,
|
||||||
|
Nickname = nickname,
|
||||||
|
IsSystem = true
|
||||||
|
};
|
||||||
|
adminUser.PasswordHash = hasher.HashPassword(adminUser, password);
|
||||||
|
db.Users.Add(adminUser);
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
|
||||||
|
Role? adminRole = await db.Roles.FirstOrDefaultAsync(r => r.Code == AdminRole, ct);
|
||||||
|
if (adminRole != null)
|
||||||
|
{
|
||||||
|
db.UserRoles.Add(new UserRole { UserId = adminUser.Id, RoleId = adminRole.Id });
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.LogWarning("已创建初始管理员账号:{Username}(密码来自 Bootstrap:Admin 配置,请尽快修改)", username);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Infrastructure.Entities.Economy;
|
||||||
|
|
||||||
|
/// <summary>商店</summary>
|
||||||
|
public class Store
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string Name { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(256)]
|
||||||
|
public string Description { get; set; } = "";
|
||||||
|
|
||||||
|
public bool IsEnabled { get; set; } = true;
|
||||||
|
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||||
|
|
||||||
|
public List<StoreGoods> StoreGoods { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>商店-商品(多对多连接表)</summary>
|
||||||
|
public class StoreGoods
|
||||||
|
{
|
||||||
|
public long StoreId { get; set; }
|
||||||
|
public Store? Store { get; set; }
|
||||||
|
public long GoodsId { get; set; }
|
||||||
|
public Goods? Goods { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>商品(物品实体以 Core JSON 存储)</summary>
|
||||||
|
public class Goods
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string Name { get; set; } = "";
|
||||||
|
|
||||||
|
/// <summary>Core Item 实体的 JSON</summary>
|
||||||
|
public string ItemJson { get; set; } = "";
|
||||||
|
|
||||||
|
/// <summary>库存(-1 表示无限)</summary>
|
||||||
|
public int Stock { get; set; } = -1;
|
||||||
|
|
||||||
|
public bool IsEnabled { get; set; } = true;
|
||||||
|
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||||
|
|
||||||
|
public List<GoodsPrice> Prices { get; set; } = [];
|
||||||
|
public List<StoreGoods> StoreGoods { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>商品价格(双货币)</summary>
|
||||||
|
public class GoodsPrice
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
public long GoodsId { get; set; }
|
||||||
|
public Goods? Goods { get; set; }
|
||||||
|
|
||||||
|
/// <summary>货币:credits / materials</summary>
|
||||||
|
[MaxLength(16)]
|
||||||
|
public string Currency { get; set; } = "credits";
|
||||||
|
|
||||||
|
public double Price { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>市场寄售状态</summary>
|
||||||
|
public enum MarketItemStateEntity
|
||||||
|
{
|
||||||
|
Listed = 0,
|
||||||
|
Sold = 1,
|
||||||
|
Delisted = 2
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>市场寄售</summary>
|
||||||
|
public class MarketItem
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>寄售物品的 Guid(对应玩家库存中物品)</summary>
|
||||||
|
public Guid ItemGuid { get; set; }
|
||||||
|
|
||||||
|
public long SellerUserId { get; set; }
|
||||||
|
public double Price { get; set; }
|
||||||
|
public int Stock { get; set; } = 1;
|
||||||
|
|
||||||
|
public MarketItemStateEntity State { get; set; } = MarketItemStateEntity.Listed;
|
||||||
|
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||||
|
public DateTime UpdatedAt { get; set; } = DateTime.Now;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>交易报价状态</summary>
|
||||||
|
public enum OfferStateEntity
|
||||||
|
{
|
||||||
|
Created = 0,
|
||||||
|
Sent = 1,
|
||||||
|
Negotiating = 2,
|
||||||
|
Completed = 3,
|
||||||
|
Rejected = 4,
|
||||||
|
Cancelled = 5,
|
||||||
|
Expired = 6
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>交易报价(v2 offers 迁移)</summary>
|
||||||
|
public class Offer
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
public long OfferorUserId { get; set; }
|
||||||
|
public long OffereeUserId { get; set; }
|
||||||
|
|
||||||
|
public OfferStateEntity State { get; set; } = OfferStateEntity.Created;
|
||||||
|
|
||||||
|
/// <summary>已协商次数(上限 3)</summary>
|
||||||
|
public int NegotiatedTimes { get; set; }
|
||||||
|
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||||
|
public DateTime? FinishedAt { get; set; }
|
||||||
|
|
||||||
|
public List<OfferItem> Items { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>报价条目</summary>
|
||||||
|
public class OfferItem
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
public long OfferId { get; set; }
|
||||||
|
public Offer? Offer { get; set; }
|
||||||
|
|
||||||
|
/// <summary>归属方:offeror / offeree</summary>
|
||||||
|
[MaxLength(16)]
|
||||||
|
public string Side { get; set; } = "offeror";
|
||||||
|
|
||||||
|
public Guid ItemGuid { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Infrastructure.Entities.Game;
|
||||||
|
|
||||||
|
/// <summary>房间状态</summary>
|
||||||
|
public enum RoomStateEntity
|
||||||
|
{
|
||||||
|
Created = 0,
|
||||||
|
Matching = 1,
|
||||||
|
Gaming = 2
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 房间(v2 rooms 表迁移)
|
||||||
|
/// </summary>
|
||||||
|
public class RoomEntity
|
||||||
|
{
|
||||||
|
/// <summary>房间号(7 位大写随机)</summary>
|
||||||
|
[MaxLength(16)]
|
||||||
|
public string RoomId { get; set; } = "";
|
||||||
|
|
||||||
|
public long? MasterUserId { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string GameModule { get; set; } = "";
|
||||||
|
|
||||||
|
/// <summary>内容模组前缀(如 "oshima"):该房间对局的角色/技能/物品只从该模组族产生;空 = 全量模组</summary>
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string ContentModule { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string GameMap { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(128)]
|
||||||
|
public string? PasswordHash { get; set; }
|
||||||
|
|
||||||
|
public int MaxUsers { get; set; } = 10;
|
||||||
|
|
||||||
|
public RoomStateEntity State { get; set; } = RoomStateEntity.Created;
|
||||||
|
|
||||||
|
public bool IsRank { get; set; }
|
||||||
|
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||||
|
public DateTime UpdatedAt { get; set; } = DateTime.Now;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 玩家角色库(v2 user_characters 迁移:角色实体以 Core JSON 存储,关键字段列冗余)
|
||||||
|
/// </summary>
|
||||||
|
public class UserCharacter
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
public long UserId { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string Name { get; set; } = "";
|
||||||
|
|
||||||
|
/// <summary>Core Character 实体的 JSON(JsonService 序列化)</summary>
|
||||||
|
public string CharacterJson { get; set; } = "";
|
||||||
|
|
||||||
|
public bool IsDefault { get; set; }
|
||||||
|
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||||
|
public DateTime UpdatedAt { get; set; } = DateTime.Now;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 玩家物品(v2 user_items 迁移)
|
||||||
|
/// </summary>
|
||||||
|
public class UserItem
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
public long UserId { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string Name { get; set; } = "";
|
||||||
|
|
||||||
|
/// <summary>Core Item 实体的 JSON</summary>
|
||||||
|
public string ItemJson { get; set; } = "";
|
||||||
|
|
||||||
|
public int Count { get; set; } = 1;
|
||||||
|
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||||
|
public DateTime UpdatedAt { get; set; } = DateTime.Now;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 库存(v2 inventories:货币与材料)
|
||||||
|
/// </summary>
|
||||||
|
public class Inventory
|
||||||
|
{
|
||||||
|
public long UserId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>游戏币</summary>
|
||||||
|
public double Credits { get; set; }
|
||||||
|
|
||||||
|
/// <summary>材料</summary>
|
||||||
|
public double Materials { get; set; }
|
||||||
|
|
||||||
|
public DateTime UpdatedAt { get; set; } = DateTime.Now;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>对局状态</summary>
|
||||||
|
public enum GameState
|
||||||
|
{
|
||||||
|
Running = 0,
|
||||||
|
Finished = 1,
|
||||||
|
Aborted = 2
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 对局记录索引(回合记录归档的元信息)
|
||||||
|
/// </summary>
|
||||||
|
public class GameRecord
|
||||||
|
{
|
||||||
|
public Guid Id { get; set; } = Guid.NewGuid();
|
||||||
|
|
||||||
|
/// <summary>GamingQueue 的 Guid</summary>
|
||||||
|
public Guid QueueId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>游戏模式(服务器插件名)</summary>
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string Mode { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string? Map { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(32)]
|
||||||
|
public string MatchType { get; set; } = "mix";
|
||||||
|
|
||||||
|
public GameState State { get; set; } = GameState.Running;
|
||||||
|
|
||||||
|
public DateTime StartedAt { get; set; } = DateTime.Now;
|
||||||
|
public DateTime? EndedAt { get; set; }
|
||||||
|
|
||||||
|
public int TotalRounds { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string? Winner { get; set; }
|
||||||
|
|
||||||
|
/// <summary>回合记录归档文件路径(相对记录目录)</summary>
|
||||||
|
[MaxLength(256)]
|
||||||
|
public string ArchivePath { get; set; } = "";
|
||||||
|
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 回合记录行(与归档文件并存;JSON 列存储单回合数据,便于按回合检索)
|
||||||
|
/// </summary>
|
||||||
|
public class RoundRecordEntity
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
public Guid GameId { get; set; }
|
||||||
|
|
||||||
|
public int Round { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string ActorGuid { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string ActorName { get; set; } = "";
|
||||||
|
|
||||||
|
public bool HasKill { get; set; }
|
||||||
|
public double TotalDamage { get; set; }
|
||||||
|
public double TotalHeal { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Core RoundRecord 的 JSON(含行动流/特效/快照)</summary>
|
||||||
|
public string RecordJson { get; set; } = "";
|
||||||
|
|
||||||
|
/// <summary>是否为检查点回合(含全角色状态快照)</summary>
|
||||||
|
public bool IsCheckpoint { get; set; }
|
||||||
|
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Infrastructure.Entities.Identity;
|
||||||
|
|
||||||
|
/// <summary>用户状态</summary>
|
||||||
|
public enum UserStatus
|
||||||
|
{
|
||||||
|
Active = 0,
|
||||||
|
Banned = 1,
|
||||||
|
Disabled = 2
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 用户(v2 users 重构:PBKDF2 密码散列、邮箱验证、状态管理)
|
||||||
|
/// </summary>
|
||||||
|
public class User
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(32)]
|
||||||
|
public string Username { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(256)]
|
||||||
|
public string PasswordHash { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(128)]
|
||||||
|
public string Email { get; set; } = "";
|
||||||
|
|
||||||
|
public bool EmailVerified { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string Nickname { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(256)]
|
||||||
|
public string Avatar { get; set; } = "";
|
||||||
|
|
||||||
|
public UserStatus Status { get; set; } = UserStatus.Active;
|
||||||
|
|
||||||
|
/// <summary>系统内置账号(不可删除,如机器人账号)</summary>
|
||||||
|
public bool IsSystem { get; set; }
|
||||||
|
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||||
|
|
||||||
|
public DateTime UpdatedAt { get; set; } = DateTime.Now;
|
||||||
|
|
||||||
|
public DateTime? LastLoginAt { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string? LastLoginIp { get; set; }
|
||||||
|
|
||||||
|
// ===== 导航 =====
|
||||||
|
public List<UserRole> UserRoles { get; set; } = [];
|
||||||
|
public UserProfile? Profile { get; set; }
|
||||||
|
public List<RefreshToken> RefreshTokens { get; set; } = [];
|
||||||
|
public List<UserSession> Sessions { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>用户资料(v2 user_profiles)</summary>
|
||||||
|
public class UserProfile
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
public long UserId { get; set; }
|
||||||
|
public User? User { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(256)]
|
||||||
|
public string Signature { get; set; } = "";
|
||||||
|
|
||||||
|
/// <summary>偏好设置(JSON)</summary>
|
||||||
|
public string PreferencesJson { get; set; } = "{}";
|
||||||
|
|
||||||
|
public DateTime UpdatedAt { get; set; } = DateTime.Now;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>角色(RBAC)</summary>
|
||||||
|
public class Role
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string Code { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string Name { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(256)]
|
||||||
|
public string Description { get; set; } = "";
|
||||||
|
|
||||||
|
/// <summary>系统内置角色(不可删除)</summary>
|
||||||
|
public bool IsSystem { get; set; }
|
||||||
|
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||||
|
|
||||||
|
public List<UserRole> UserRoles { get; set; } = [];
|
||||||
|
public List<RolePermission> RolePermissions { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>权限点(细粒度)</summary>
|
||||||
|
public class Permission
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string Code { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string Name { get; set; } = "";
|
||||||
|
|
||||||
|
/// <summary>权限分组(如 users / plugins / games)</summary>
|
||||||
|
[MaxLength(32)]
|
||||||
|
public string Group { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(256)]
|
||||||
|
public string Description { get; set; } = "";
|
||||||
|
|
||||||
|
public List<RolePermission> RolePermissions { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>用户-角色(多对多连接表)</summary>
|
||||||
|
public class UserRole
|
||||||
|
{
|
||||||
|
public long UserId { get; set; }
|
||||||
|
public User? User { get; set; }
|
||||||
|
public long RoleId { get; set; }
|
||||||
|
public Role? Role { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>角色-权限(多对多连接表)</summary>
|
||||||
|
public class RolePermission
|
||||||
|
{
|
||||||
|
public long RoleId { get; set; }
|
||||||
|
public Role? Role { get; set; }
|
||||||
|
public long PermissionId { get; set; }
|
||||||
|
public Permission? Permission { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Infrastructure.Entities.Identity;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 刷新令牌(多端统一验证:散列存储,支持撤销/设备维度)
|
||||||
|
/// </summary>
|
||||||
|
public class RefreshToken
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
public long UserId { get; set; }
|
||||||
|
public User? User { get; set; }
|
||||||
|
|
||||||
|
/// <summary>令牌散列(原始令牌仅返回客户端一次)</summary>
|
||||||
|
[MaxLength(128)]
|
||||||
|
public string TokenHash { get; set; } = "";
|
||||||
|
|
||||||
|
/// <summary>签发端:web / api / ws</summary>
|
||||||
|
[MaxLength(16)]
|
||||||
|
public string Endpoint { get; set; } = "web";
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string Device { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string IpAddress { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(256)]
|
||||||
|
public string UserAgent { get; set; } = "";
|
||||||
|
|
||||||
|
public DateTime ExpiresAt { get; set; }
|
||||||
|
public DateTime? RevokedAt { get; set; }
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||||
|
|
||||||
|
public bool IsRevoked => RevokedAt != null;
|
||||||
|
public bool IsExpired => DateTime.Now >= ExpiresAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 在线会话(每端一条,支持多端管理与同端互踢)
|
||||||
|
/// </summary>
|
||||||
|
public class UserSession
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
public long UserId { get; set; }
|
||||||
|
public User? User { get; set; }
|
||||||
|
|
||||||
|
/// <summary>会话端:web / api / ws</summary>
|
||||||
|
[MaxLength(16)]
|
||||||
|
public string Endpoint { get; set; } = "ws";
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string Device { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string IpAddress { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(256)]
|
||||||
|
public string UserAgent { get; set; } = "";
|
||||||
|
|
||||||
|
/// <summary>本次 AccessToken 的 JTI</summary>
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string AccessTokenId { get; set; } = "";
|
||||||
|
|
||||||
|
public DateTime ConnectedAt { get; set; } = DateTime.Now;
|
||||||
|
public DateTime LastActiveAt { get; set; } = DateTime.Now;
|
||||||
|
public DateTime? DisconnectedAt { get; set; }
|
||||||
|
|
||||||
|
public bool IsOnline => DisconnectedAt == null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>登录日志</summary>
|
||||||
|
public class LoginLog
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
public long? UserId { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(32)]
|
||||||
|
public string Username { get; set; } = "";
|
||||||
|
|
||||||
|
public bool Success { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(256)]
|
||||||
|
public string? Reason { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string IpAddress { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(256)]
|
||||||
|
public string UserAgent { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string Device { get; set; } = "";
|
||||||
|
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// API 访问令牌(外部服务接入,如回放服务器)
|
||||||
|
/// </summary>
|
||||||
|
public class ApiToken
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
/// <summary>令牌 ID(如 fungame_web_api)</summary>
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string TokenId { get; set; } = "";
|
||||||
|
|
||||||
|
/// <summary>令牌散列</summary>
|
||||||
|
[MaxLength(128)]
|
||||||
|
public string TokenHash { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string Name { get; set; } = "";
|
||||||
|
|
||||||
|
public DateTime? ExpiresAt { get; set; }
|
||||||
|
public DateTime? RevokedAt { get; set; }
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||||
|
|
||||||
|
[MaxLength(128)]
|
||||||
|
public string Reference1 { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(128)]
|
||||||
|
public string Reference2 { get; set; } = "";
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Infrastructure.Entities.System;
|
||||||
|
|
||||||
|
/// <summary>日志级别</summary>
|
||||||
|
public enum LogLevelEntity
|
||||||
|
{
|
||||||
|
Trace = 0,
|
||||||
|
Debug = 1,
|
||||||
|
Info = 2,
|
||||||
|
Warning = 3,
|
||||||
|
Error = 4,
|
||||||
|
Critical = 5
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 服务器日志(供 WebUI 查看;可在 Host 用 Serilog/自定义 Provider 写入)
|
||||||
|
/// </summary>
|
||||||
|
public class ServerLog
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
public LogLevelEntity Level { get; set; } = LogLevelEntity.Info;
|
||||||
|
|
||||||
|
/// <summary>来源(Host / Plugin / Module / Game ...)</summary>
|
||||||
|
[MaxLength(32)]
|
||||||
|
public string Source { get; set; } = "Host";
|
||||||
|
|
||||||
|
/// <summary>分类(如 Auth / Room / PluginManager)</summary>
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string Category { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(1024)]
|
||||||
|
public string Message { get; set; } = "";
|
||||||
|
|
||||||
|
public string? Exception { get; set; }
|
||||||
|
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>系统配置键值(v2 configs 迁移:公告、开关等)</summary>
|
||||||
|
public class SystemConfig
|
||||||
|
{
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string Key { get; set; } = "";
|
||||||
|
|
||||||
|
public string Value { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(64)]
|
||||||
|
public string? Description { get; set; }
|
||||||
|
|
||||||
|
public DateTime UpdatedAt { get; set; } = DateTime.Now;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>验证码用途</summary>
|
||||||
|
public enum VerifyCodePurpose
|
||||||
|
{
|
||||||
|
Register = 0,
|
||||||
|
ForgetPassword = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>验证码(v2 reg_verify_codes + forget_verify_codes 合并)</summary>
|
||||||
|
public class VerifyCode
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
|
||||||
|
public VerifyCodePurpose Purpose { get; set; }
|
||||||
|
|
||||||
|
[MaxLength(32)]
|
||||||
|
public string Username { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(128)]
|
||||||
|
public string Email { get; set; } = "";
|
||||||
|
|
||||||
|
[MaxLength(16)]
|
||||||
|
public string Code { get; set; } = "";
|
||||||
|
|
||||||
|
public DateTime ExpiresAt { get; set; }
|
||||||
|
public DateTime? UsedAt { get; set; }
|
||||||
|
public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>每日签到</summary>
|
||||||
|
public class UserSignIn
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
public long UserId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>连续签到天数</summary>
|
||||||
|
public int Days { get; set; }
|
||||||
|
|
||||||
|
/// <summary>是否已签到(当天)</summary>
|
||||||
|
public bool IsSigned { get; set; }
|
||||||
|
|
||||||
|
public DateTime LastTime { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\FunGame.Server.Contracts\FunGame.Server.Contracts.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.11">
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
</PackageReference>
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.11" />
|
||||||
|
<PackageReference Include="MySql.EntityFrameworkCore" Version="10.0.9" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
using FunGame.Server.Infrastructure.Data;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace FunGame.Server.Infrastructure;
|
||||||
|
|
||||||
|
public static class InfrastructureServiceCollectionExtensions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 注册 EF Core 数据层(SQLite/MySQL 按配置切换)
|
||||||
|
/// </summary>
|
||||||
|
public static IServiceCollection AddServerInfrastructure(this IServiceCollection services, IConfiguration configuration)
|
||||||
|
{
|
||||||
|
services.AddDbContext<AppDbContext>((serviceProvider, options) =>
|
||||||
|
{
|
||||||
|
IConfiguration config = serviceProvider.GetRequiredService<IConfiguration>();
|
||||||
|
DbContextOptionsFactory.Configure(options, config);
|
||||||
|
});
|
||||||
|
|
||||||
|
services.AddScoped<DbSeedService>();
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+1117
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,788 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace FunGame.Server.Infrastructure.Migrations.Sqlite
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class InitialCreate : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "api_tokens",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
TokenId = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
TokenHash = table.Column<string>(type: "TEXT", maxLength: 128, nullable: false),
|
||||||
|
Name = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
ExpiresAt = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||||
|
RevokedAt = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||||
|
Reference1 = table.Column<string>(type: "TEXT", maxLength: 128, nullable: false),
|
||||||
|
Reference2 = table.Column<string>(type: "TEXT", maxLength: 128, nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_api_tokens", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "game_records",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||||
|
QueueId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||||
|
Mode = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
Map = table.Column<string>(type: "TEXT", maxLength: 64, nullable: true),
|
||||||
|
MatchType = table.Column<string>(type: "TEXT", maxLength: 32, nullable: false),
|
||||||
|
State = table.Column<int>(type: "INTEGER", nullable: false),
|
||||||
|
StartedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||||
|
EndedAt = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||||
|
TotalRounds = table.Column<int>(type: "INTEGER", nullable: false),
|
||||||
|
Winner = table.Column<string>(type: "TEXT", maxLength: 64, nullable: true),
|
||||||
|
ArchivePath = table.Column<string>(type: "TEXT", maxLength: 256, nullable: false),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_game_records", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "goods",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
Name = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
ItemJson = table.Column<string>(type: "TEXT", nullable: false),
|
||||||
|
Stock = table.Column<int>(type: "INTEGER", nullable: false),
|
||||||
|
IsEnabled = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_goods", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "inventories",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
UserId = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
Credits = table.Column<double>(type: "REAL", nullable: false),
|
||||||
|
Materials = table.Column<double>(type: "REAL", nullable: false),
|
||||||
|
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_inventories", x => x.UserId);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "login_logs",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
UserId = table.Column<long>(type: "INTEGER", nullable: true),
|
||||||
|
Username = table.Column<string>(type: "TEXT", maxLength: 32, nullable: false),
|
||||||
|
Success = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||||
|
Reason = table.Column<string>(type: "TEXT", maxLength: 256, nullable: true),
|
||||||
|
IpAddress = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
UserAgent = table.Column<string>(type: "TEXT", maxLength: 256, nullable: false),
|
||||||
|
Device = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_login_logs", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "market_items",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
ItemGuid = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||||
|
SellerUserId = table.Column<long>(type: "INTEGER", nullable: false),
|
||||||
|
Price = table.Column<double>(type: "REAL", nullable: false),
|
||||||
|
Stock = table.Column<int>(type: "INTEGER", nullable: false),
|
||||||
|
State = table.Column<int>(type: "INTEGER", nullable: false),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||||
|
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_market_items", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "offers",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
OfferorUserId = table.Column<long>(type: "INTEGER", nullable: false),
|
||||||
|
OffereeUserId = table.Column<long>(type: "INTEGER", nullable: false),
|
||||||
|
State = table.Column<int>(type: "INTEGER", nullable: false),
|
||||||
|
NegotiatedTimes = table.Column<int>(type: "INTEGER", nullable: false),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||||
|
FinishedAt = table.Column<DateTime>(type: "TEXT", nullable: true)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_offers", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "permissions",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
Code = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
Name = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
Group = table.Column<string>(type: "TEXT", maxLength: 32, nullable: false),
|
||||||
|
Description = table.Column<string>(type: "TEXT", maxLength: 256, nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_permissions", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "roles",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
Code = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
Name = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
Description = table.Column<string>(type: "TEXT", maxLength: 256, nullable: false),
|
||||||
|
IsSystem = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_roles", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "rooms",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
RoomId = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
|
||||||
|
MasterUserId = table.Column<long>(type: "INTEGER", nullable: true),
|
||||||
|
GameModule = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
GameMap = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
PasswordHash = table.Column<string>(type: "TEXT", maxLength: 128, nullable: true),
|
||||||
|
MaxUsers = table.Column<int>(type: "INTEGER", nullable: false),
|
||||||
|
State = table.Column<int>(type: "INTEGER", nullable: false),
|
||||||
|
IsRank = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||||
|
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_rooms", x => x.RoomId);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "round_records",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
GameId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||||
|
Round = table.Column<int>(type: "INTEGER", nullable: false),
|
||||||
|
ActorGuid = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
ActorName = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
HasKill = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||||
|
TotalDamage = table.Column<double>(type: "REAL", nullable: false),
|
||||||
|
TotalHeal = table.Column<double>(type: "REAL", nullable: false),
|
||||||
|
RecordJson = table.Column<string>(type: "TEXT", nullable: false),
|
||||||
|
IsCheckpoint = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_round_records", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "server_logs",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
Level = table.Column<int>(type: "INTEGER", nullable: false),
|
||||||
|
Source = table.Column<string>(type: "TEXT", maxLength: 32, nullable: false),
|
||||||
|
Category = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
Message = table.Column<string>(type: "TEXT", maxLength: 1024, nullable: false),
|
||||||
|
Exception = table.Column<string>(type: "TEXT", nullable: true),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_server_logs", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "stores",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
Name = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
Description = table.Column<string>(type: "TEXT", maxLength: 256, nullable: false),
|
||||||
|
IsEnabled = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_stores", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "system_configs",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Key = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
Value = table.Column<string>(type: "TEXT", nullable: false),
|
||||||
|
Description = table.Column<string>(type: "TEXT", maxLength: 64, nullable: true),
|
||||||
|
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_system_configs", x => x.Key);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "user_characters",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
UserId = table.Column<long>(type: "INTEGER", nullable: false),
|
||||||
|
Name = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
CharacterJson = table.Column<string>(type: "TEXT", nullable: false),
|
||||||
|
IsDefault = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||||
|
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_user_characters", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "user_items",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
UserId = table.Column<long>(type: "INTEGER", nullable: false),
|
||||||
|
Name = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
ItemJson = table.Column<string>(type: "TEXT", nullable: false),
|
||||||
|
Count = table.Column<int>(type: "INTEGER", nullable: false),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||||
|
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_user_items", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "user_sign_ins",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
UserId = table.Column<long>(type: "INTEGER", nullable: false),
|
||||||
|
Days = table.Column<int>(type: "INTEGER", nullable: false),
|
||||||
|
IsSigned = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||||
|
LastTime = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_user_sign_ins", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "users",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
Username = table.Column<string>(type: "TEXT", maxLength: 32, nullable: false),
|
||||||
|
PasswordHash = table.Column<string>(type: "TEXT", maxLength: 256, nullable: false),
|
||||||
|
Email = table.Column<string>(type: "TEXT", maxLength: 128, nullable: false),
|
||||||
|
EmailVerified = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||||
|
Nickname = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
Avatar = table.Column<string>(type: "TEXT", maxLength: 256, nullable: false),
|
||||||
|
Status = table.Column<int>(type: "INTEGER", nullable: false),
|
||||||
|
IsSystem = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||||
|
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||||
|
LastLoginAt = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||||
|
LastLoginIp = table.Column<string>(type: "TEXT", maxLength: 64, nullable: true)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_users", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "verify_codes",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
Purpose = table.Column<int>(type: "INTEGER", nullable: false),
|
||||||
|
Username = table.Column<string>(type: "TEXT", maxLength: 32, nullable: false),
|
||||||
|
Email = table.Column<string>(type: "TEXT", maxLength: 128, nullable: false),
|
||||||
|
Code = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
|
||||||
|
ExpiresAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||||
|
UsedAt = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_verify_codes", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "goods_prices",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
GoodsId = table.Column<long>(type: "INTEGER", nullable: false),
|
||||||
|
Currency = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
|
||||||
|
Price = table.Column<double>(type: "REAL", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_goods_prices", x => x.Id);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_goods_prices_goods_GoodsId",
|
||||||
|
column: x => x.GoodsId,
|
||||||
|
principalTable: "goods",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "offer_items",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
OfferId = table.Column<long>(type: "INTEGER", nullable: false),
|
||||||
|
Side = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
|
||||||
|
ItemGuid = table.Column<Guid>(type: "TEXT", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_offer_items", x => x.Id);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_offer_items_offers_OfferId",
|
||||||
|
column: x => x.OfferId,
|
||||||
|
principalTable: "offers",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "role_permissions",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
RoleId = table.Column<long>(type: "INTEGER", nullable: false),
|
||||||
|
PermissionId = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_role_permissions", x => new { x.RoleId, x.PermissionId });
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_role_permissions_permissions_PermissionId",
|
||||||
|
column: x => x.PermissionId,
|
||||||
|
principalTable: "permissions",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_role_permissions_roles_RoleId",
|
||||||
|
column: x => x.RoleId,
|
||||||
|
principalTable: "roles",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "store_goods",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
StoreId = table.Column<long>(type: "INTEGER", nullable: false),
|
||||||
|
GoodsId = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_store_goods", x => new { x.StoreId, x.GoodsId });
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_store_goods_goods_GoodsId",
|
||||||
|
column: x => x.GoodsId,
|
||||||
|
principalTable: "goods",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_store_goods_stores_StoreId",
|
||||||
|
column: x => x.StoreId,
|
||||||
|
principalTable: "stores",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "refresh_tokens",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
UserId = table.Column<long>(type: "INTEGER", nullable: false),
|
||||||
|
TokenHash = table.Column<string>(type: "TEXT", maxLength: 128, nullable: false),
|
||||||
|
Endpoint = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
|
||||||
|
Device = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
IpAddress = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
UserAgent = table.Column<string>(type: "TEXT", maxLength: 256, nullable: false),
|
||||||
|
ExpiresAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||||
|
RevokedAt = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_refresh_tokens", x => x.Id);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_refresh_tokens_users_UserId",
|
||||||
|
column: x => x.UserId,
|
||||||
|
principalTable: "users",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "user_profiles",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
UserId = table.Column<long>(type: "INTEGER", nullable: false),
|
||||||
|
Signature = table.Column<string>(type: "TEXT", maxLength: 256, nullable: false),
|
||||||
|
PreferencesJson = table.Column<string>(type: "TEXT", nullable: false),
|
||||||
|
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_user_profiles", x => x.Id);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_user_profiles_users_UserId",
|
||||||
|
column: x => x.UserId,
|
||||||
|
principalTable: "users",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "user_roles",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
UserId = table.Column<long>(type: "INTEGER", nullable: false),
|
||||||
|
RoleId = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_user_roles", x => new { x.UserId, x.RoleId });
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_user_roles_roles_RoleId",
|
||||||
|
column: x => x.RoleId,
|
||||||
|
principalTable: "roles",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_user_roles_users_UserId",
|
||||||
|
column: x => x.UserId,
|
||||||
|
principalTable: "users",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "user_sessions",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<long>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
UserId = table.Column<long>(type: "INTEGER", nullable: false),
|
||||||
|
Endpoint = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
|
||||||
|
Device = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
IpAddress = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
UserAgent = table.Column<string>(type: "TEXT", maxLength: 256, nullable: false),
|
||||||
|
AccessTokenId = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
ConnectedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||||
|
LastActiveAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||||
|
DisconnectedAt = table.Column<DateTime>(type: "TEXT", nullable: true)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_user_sessions", x => x.Id);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_user_sessions_users_UserId",
|
||||||
|
column: x => x.UserId,
|
||||||
|
principalTable: "users",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_api_tokens_TokenId",
|
||||||
|
table: "api_tokens",
|
||||||
|
column: "TokenId",
|
||||||
|
unique: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_game_records_QueueId",
|
||||||
|
table: "game_records",
|
||||||
|
column: "QueueId",
|
||||||
|
unique: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_game_records_StartedAt",
|
||||||
|
table: "game_records",
|
||||||
|
column: "StartedAt");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_goods_prices_GoodsId",
|
||||||
|
table: "goods_prices",
|
||||||
|
column: "GoodsId");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_login_logs_UserId_CreatedAt",
|
||||||
|
table: "login_logs",
|
||||||
|
columns: new[] { "UserId", "CreatedAt" });
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_market_items_ItemGuid",
|
||||||
|
table: "market_items",
|
||||||
|
column: "ItemGuid");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_market_items_SellerUserId",
|
||||||
|
table: "market_items",
|
||||||
|
column: "SellerUserId");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_offer_items_OfferId",
|
||||||
|
table: "offer_items",
|
||||||
|
column: "OfferId");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_offers_OfferorUserId_OffereeUserId",
|
||||||
|
table: "offers",
|
||||||
|
columns: new[] { "OfferorUserId", "OffereeUserId" });
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_permissions_Code",
|
||||||
|
table: "permissions",
|
||||||
|
column: "Code",
|
||||||
|
unique: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_refresh_tokens_TokenHash",
|
||||||
|
table: "refresh_tokens",
|
||||||
|
column: "TokenHash",
|
||||||
|
unique: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_refresh_tokens_UserId",
|
||||||
|
table: "refresh_tokens",
|
||||||
|
column: "UserId");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_role_permissions_PermissionId",
|
||||||
|
table: "role_permissions",
|
||||||
|
column: "PermissionId");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_roles_Code",
|
||||||
|
table: "roles",
|
||||||
|
column: "Code",
|
||||||
|
unique: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_rooms_State",
|
||||||
|
table: "rooms",
|
||||||
|
column: "State");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_round_records_GameId_Round",
|
||||||
|
table: "round_records",
|
||||||
|
columns: new[] { "GameId", "Round" },
|
||||||
|
unique: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_server_logs_CreatedAt",
|
||||||
|
table: "server_logs",
|
||||||
|
column: "CreatedAt");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_server_logs_Level",
|
||||||
|
table: "server_logs",
|
||||||
|
column: "Level");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_store_goods_GoodsId",
|
||||||
|
table: "store_goods",
|
||||||
|
column: "GoodsId");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_user_characters_UserId",
|
||||||
|
table: "user_characters",
|
||||||
|
column: "UserId");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_user_items_UserId",
|
||||||
|
table: "user_items",
|
||||||
|
column: "UserId");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_user_profiles_UserId",
|
||||||
|
table: "user_profiles",
|
||||||
|
column: "UserId",
|
||||||
|
unique: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_user_roles_RoleId",
|
||||||
|
table: "user_roles",
|
||||||
|
column: "RoleId");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_user_sessions_UserId_Endpoint",
|
||||||
|
table: "user_sessions",
|
||||||
|
columns: new[] { "UserId", "Endpoint" });
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_user_sign_ins_UserId",
|
||||||
|
table: "user_sign_ins",
|
||||||
|
column: "UserId",
|
||||||
|
unique: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_users_Email",
|
||||||
|
table: "users",
|
||||||
|
column: "Email");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_users_Username",
|
||||||
|
table: "users",
|
||||||
|
column: "Username",
|
||||||
|
unique: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_verify_codes_Purpose_Username",
|
||||||
|
table: "verify_codes",
|
||||||
|
columns: new[] { "Purpose", "Username" });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "api_tokens");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "game_records");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "goods_prices");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "inventories");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "login_logs");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "market_items");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "offer_items");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "refresh_tokens");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "role_permissions");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "rooms");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "round_records");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "server_logs");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "store_goods");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "system_configs");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "user_characters");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "user_items");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "user_profiles");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "user_roles");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "user_sessions");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "user_sign_ins");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "verify_codes");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "offers");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "permissions");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "goods");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "stores");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "roles");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "users");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+1122
File diff suppressed because it is too large
Load Diff
+30
@@ -0,0 +1,30 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace FunGame.Server.Infrastructure.Migrations.Sqlite
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddContentModule : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "ContentModule",
|
||||||
|
table: "rooms",
|
||||||
|
type: "TEXT",
|
||||||
|
maxLength: 64,
|
||||||
|
nullable: false,
|
||||||
|
defaultValue: "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "ContentModule",
|
||||||
|
table: "rooms");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,18 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\FunGame.Server.Contracts\FunGame.Server.Contracts.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>FunGame.Server.PluginHost</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
using FunGame.Server.Contracts.Plugins;
|
||||||
|
|
||||||
|
namespace FunGame.Server.PluginHost;
|
||||||
|
|
||||||
|
/// <summary>加载项类型</summary>
|
||||||
|
public enum PluginKind
|
||||||
|
{
|
||||||
|
ServerPlugin,
|
||||||
|
CharacterModule,
|
||||||
|
SkillModule,
|
||||||
|
ItemModule,
|
||||||
|
GameModuleServer
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>加载项状态</summary>
|
||||||
|
public enum PluginStatus
|
||||||
|
{
|
||||||
|
Unloaded,
|
||||||
|
Loading,
|
||||||
|
Loaded,
|
||||||
|
Unloading,
|
||||||
|
Failed
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 加载项描述(插件/模组的运行时清单)
|
||||||
|
/// </summary>
|
||||||
|
public class PluginDescriptor
|
||||||
|
{
|
||||||
|
public required string Name { get; init; }
|
||||||
|
public string Version { get; init; } = "";
|
||||||
|
public string Author { get; init; } = "";
|
||||||
|
public string Description { get; init; } = "";
|
||||||
|
public PluginKind Kind { get; init; }
|
||||||
|
public required string AssemblyPath { get; init; }
|
||||||
|
|
||||||
|
public PluginStatus Status { get; set; } = PluginStatus.Unloaded;
|
||||||
|
public string? Error { get; set; }
|
||||||
|
public DateTime? LoadedAt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>加载上下文(卸载后置空)</summary>
|
||||||
|
public PluginLoadContext? LoadContext { get; set; }
|
||||||
|
|
||||||
|
/// <summary>影子副本路径(实际加载的程序集;卸载后可安全删除)</summary>
|
||||||
|
public string? ShadowPath { get; set; }
|
||||||
|
|
||||||
|
/// <summary>加载项实例</summary>
|
||||||
|
public IPluginBase? Instance { get; set; }
|
||||||
|
|
||||||
|
/// <summary>用于确认上下文可回收</summary>
|
||||||
|
public WeakReference? InstanceWeakReference { get; set; }
|
||||||
|
|
||||||
|
/// <summary>活跃对局引用计数(大于 0 时禁止卸载);字段以便 Interlocked 原子操作</summary>
|
||||||
|
public int ActiveGames;
|
||||||
|
|
||||||
|
/// <summary>是否为实体模组(ICharacterModule/ISkillModule/IItemModule)</summary>
|
||||||
|
public bool IsEntityModule => Kind is PluginKind.CharacterModule or PluginKind.SkillModule or PluginKind.ItemModule;
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
using System.Reflection;
|
||||||
|
using System.Runtime.Loader;
|
||||||
|
|
||||||
|
namespace FunGame.Server.PluginHost;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 插件专用可回收加载上下文(每个加载项一个实例,热重载时整体卸载)<para/>
|
||||||
|
/// 共享程序集(FunGame.Core / Contracts / Infrastructure / PluginHost / ASP.NET Core)回退到默认上下文解析,
|
||||||
|
/// 插件自有依赖从插件所在目录解析。
|
||||||
|
/// </summary>
|
||||||
|
public sealed class PluginLoadContext : AssemblyLoadContext
|
||||||
|
{
|
||||||
|
private readonly AssemblyDependencyResolver _resolver;
|
||||||
|
private readonly string _pluginDirectory;
|
||||||
|
|
||||||
|
public string PluginDirectory => _pluginDirectory;
|
||||||
|
|
||||||
|
public PluginLoadContext(string assemblyPath, string? dependencyDirectory = null)
|
||||||
|
: base($"FunGamePlugin-{Guid.NewGuid():N}", isCollectible: true)
|
||||||
|
{
|
||||||
|
// 依赖解析目录默认取程序集所在目录;影子加载时显式传正式目录(含插件自有依赖)
|
||||||
|
_pluginDirectory = dependencyDirectory ?? Path.GetDirectoryName(assemblyPath) ?? Directory.GetCurrentDirectory();
|
||||||
|
_resolver = new AssemblyDependencyResolver(assemblyPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override Assembly? Load(AssemblyName assemblyName)
|
||||||
|
{
|
||||||
|
// 1. 默认上下文已加载的共享程序集直接复用
|
||||||
|
foreach (Assembly assembly in Default.Assemblies)
|
||||||
|
{
|
||||||
|
if (AssemblyName.ReferenceMatchesDefinition(assembly.GetName(), assemblyName))
|
||||||
|
{
|
||||||
|
return assembly;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 插件目录内解析自有依赖
|
||||||
|
string? path = _resolver.ResolveAssemblyToPath(assemblyName);
|
||||||
|
if (path != null && File.Exists(path))
|
||||||
|
{
|
||||||
|
return LoadFromAssemblyPath(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 兜底:插件目录内同名 dll
|
||||||
|
string fallback = Path.Combine(_pluginDirectory, assemblyName.Name + ".dll");
|
||||||
|
if (File.Exists(fallback))
|
||||||
|
{
|
||||||
|
return LoadFromAssemblyPath(fallback);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override nint LoadUnmanagedDll(string unmanagedDllName)
|
||||||
|
{
|
||||||
|
string? path = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
|
||||||
|
if (path != null && File.Exists(path))
|
||||||
|
{
|
||||||
|
return LoadUnmanagedDllFromPath(path);
|
||||||
|
}
|
||||||
|
string fallback = Path.Combine(_pluginDirectory, unmanagedDllName);
|
||||||
|
return File.Exists(fallback) ? LoadUnmanagedDllFromPath(fallback) : nint.Zero;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,660 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Reflection;
|
||||||
|
using FunGame.Core.Entity;
|
||||||
|
using FunGame.Server.Contracts.Constants;
|
||||||
|
using FunGame.Server.Contracts.Plugins;
|
||||||
|
using Microsoft.AspNetCore.Hosting;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace FunGame.Server.PluginHost;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 加载项管理器:始终热重载的插件/模组加载系统<para/>
|
||||||
|
/// - 服务器插件(IServerPlugin)从 plugins/ 加载<para/>
|
||||||
|
/// - 角色/技能/物品模组(ICharacterModule/ISkillModule/IItemModule)从 modules/ 对应子目录加载<para/>
|
||||||
|
/// - 每个 DLL 一个可回收 AssemblyLoadContext;同一 DLL 可包含多个加载项类型(各成一个加载项)<para/>
|
||||||
|
/// - 支持手动/文件监视自动热重载;活跃对局引用的插件禁止卸载(引用计数)
|
||||||
|
/// </summary>
|
||||||
|
public sealed class PluginManager : IDisposable
|
||||||
|
{
|
||||||
|
private readonly ILogger<PluginManager> _logger;
|
||||||
|
private readonly IServiceProvider _services;
|
||||||
|
private readonly IWebHostEnvironment _environment;
|
||||||
|
private readonly IMessageHandlerRegistry _messageRegistry;
|
||||||
|
private readonly IPluginHttpHandlerRegistry _httpRegistry;
|
||||||
|
|
||||||
|
private readonly ConcurrentDictionary<string, PluginDescriptor> _items = new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
private readonly ConcurrentDictionary<PluginLoadContext, HashSet<string>> _contextNames = [];
|
||||||
|
private readonly object _sync = new();
|
||||||
|
private readonly Dictionary<string, DateTime> _handledWrites = [];
|
||||||
|
private FileSystemWatcher? _watcher;
|
||||||
|
private System.Threading.Timer? _reloadDebounce;
|
||||||
|
private readonly HashSet<string> _pendingReloads = [];
|
||||||
|
private bool _disposed;
|
||||||
|
|
||||||
|
public PluginManager(
|
||||||
|
IServiceProvider services,
|
||||||
|
IWebHostEnvironment environment,
|
||||||
|
IMessageHandlerRegistry messageRegistry,
|
||||||
|
IPluginHttpHandlerRegistry httpRegistry,
|
||||||
|
ILogger<PluginManager> logger)
|
||||||
|
{
|
||||||
|
_services = services;
|
||||||
|
_environment = environment;
|
||||||
|
_messageRegistry = messageRegistry;
|
||||||
|
_httpRegistry = httpRegistry;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 目录 =====
|
||||||
|
|
||||||
|
public string ContentRoot => _environment.ContentRootPath;
|
||||||
|
|
||||||
|
public string PluginsDirectory => Path.Combine(ContentRoot, PluginConstants.PluginsDirectory);
|
||||||
|
public string CharacterModulesDirectory => Path.Combine(ContentRoot, PluginConstants.CharacterModulesDirectory);
|
||||||
|
public string SkillModulesDirectory => Path.Combine(ContentRoot, PluginConstants.SkillModulesDirectory);
|
||||||
|
public string ItemModulesDirectory => Path.Combine(ContentRoot, PluginConstants.ItemModulesDirectory);
|
||||||
|
public string GameModuleDirectory => Path.Combine(ContentRoot, PluginConstants.GameModuleDirectory);
|
||||||
|
|
||||||
|
public IEnumerable<PluginDescriptor> Items => _items.Values;
|
||||||
|
|
||||||
|
public PluginDescriptor? GetPlugin(string name) => _items.TryGetValue(name, out PluginDescriptor? descriptor) ? descriptor : null;
|
||||||
|
|
||||||
|
/// <summary>按模式名查找服务器插件</summary>
|
||||||
|
public IServerPlugin? GetServerPlugin(string name)
|
||||||
|
=> _items.TryGetValue(name, out PluginDescriptor? descriptor) && descriptor.Instance is IServerPlugin plugin ? plugin : null;
|
||||||
|
|
||||||
|
/// <summary>按游戏模式名查找游戏模式模组(GameModuleServer)</summary>
|
||||||
|
public IGameModuleServer? GetGameModule(string name)
|
||||||
|
=> _items.TryGetValue(name, out PluginDescriptor? descriptor) && descriptor.Instance is IGameModuleServer module ? module : null;
|
||||||
|
|
||||||
|
/// <summary>聚合全部已加载实体模组提供的实体(供对局准备使用)</summary>
|
||||||
|
public IEnumerable<T> GetModuleEntities<T>() where T : BaseEntity
|
||||||
|
=> _items.Values
|
||||||
|
.Where(d => d.Status == PluginStatus.Loaded && d.Instance is IEntityModule<T>)
|
||||||
|
.SelectMany(d => ((IEntityModule<T>)d.Instance!).Entities.Values);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 按模组名前缀获取实体(如 "oshima" 匹配 oshima.characters / oshima.skills / oshima.items)<para/>
|
||||||
|
/// 用于"所选模组创建对局":角色/技能/物品只从指定模组族产生
|
||||||
|
/// </summary>
|
||||||
|
public IEnumerable<T> GetModuleEntities<T>(string modulePrefix) where T : BaseEntity
|
||||||
|
=> _items.Values
|
||||||
|
.Where(d => d.Status == PluginStatus.Loaded && d.Instance is IEntityModule<T>
|
||||||
|
&& d.Name.StartsWith($"{modulePrefix}.", StringComparison.OrdinalIgnoreCase))
|
||||||
|
.SelectMany(d => ((IEntityModule<T>)d.Instance!).Entities.Values);
|
||||||
|
|
||||||
|
// ===== 加载 =====
|
||||||
|
|
||||||
|
public void LoadAll()
|
||||||
|
{
|
||||||
|
EnsureDirectories();
|
||||||
|
PromoteAllStaging();
|
||||||
|
LoadFromDirectory(PluginsDirectory, PluginKind.ServerPlugin);
|
||||||
|
LoadFromDirectory(CharacterModulesDirectory, PluginKind.CharacterModule);
|
||||||
|
LoadFromDirectory(SkillModulesDirectory, PluginKind.SkillModule);
|
||||||
|
LoadFromDirectory(ItemModulesDirectory, PluginKind.ItemModule);
|
||||||
|
LoadFromDirectory(GameModuleDirectory, PluginKind.GameModuleServer);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>启动时把暂存区文件提升到正式目录(覆盖),随后正常扫描加载</summary>
|
||||||
|
private void PromoteAllStaging()
|
||||||
|
{
|
||||||
|
foreach ((string directory, _) in GetRootDirectories())
|
||||||
|
{
|
||||||
|
string staging = Path.Combine(directory, StagingDirectoryName);
|
||||||
|
if (!Directory.Exists(staging))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
foreach (string file in Directory.GetFiles(staging, "*", SearchOption.TopDirectoryOnly))
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.Move(file, Path.Combine(directory, Path.GetFileName(file)), true);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(e, "提升暂存文件失败:{File}", file);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void LoadFromDirectory(string directory, PluginKind kind)
|
||||||
|
{
|
||||||
|
if (!Directory.Exists(directory))
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(directory);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (string file in Directory.GetFiles(directory, "*.dll", SearchOption.TopDirectoryOnly))
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
LoadDll(file, kind);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError(e, "加载加载项失败:{File}", file);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>加载一个 DLL 中指定 kind 的全部加载项类型(影子加载:正式文件不锁定,可热替换)</summary>
|
||||||
|
public IReadOnlyList<PluginDescriptor> LoadDll(string assemblyPath, PluginKind kind)
|
||||||
|
{
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
List<PluginDescriptor> loaded = [];
|
||||||
|
string liveDir = Path.GetDirectoryName(assemblyPath) ?? Directory.GetCurrentDirectory();
|
||||||
|
|
||||||
|
// 影子加载:复制到 _loaded 目录并用唯一文件名加载,正式 DLL 不被进程锁定
|
||||||
|
string shadowPath = CreateShadowCopy(assemblyPath, liveDir);
|
||||||
|
if (shadowPath == "")
|
||||||
|
{
|
||||||
|
_logger.LogError("影子复制失败:{File}", assemblyPath);
|
||||||
|
return loaded;
|
||||||
|
}
|
||||||
|
|
||||||
|
PluginLoadContext context = new(shadowPath, liveDir);
|
||||||
|
Assembly assembly = context.LoadFromAssemblyPath(shadowPath);
|
||||||
|
|
||||||
|
List<Type> pluginTypes = FindPluginTypes(assembly, kind);
|
||||||
|
if (pluginTypes.Count == 0)
|
||||||
|
{
|
||||||
|
context.Unload();
|
||||||
|
TryDelete(shadowPath);
|
||||||
|
_logger.LogWarning("未在 {File} 中找到 {Kind} 类型,跳过", Path.GetFileName(assemblyPath), kind);
|
||||||
|
return loaded;
|
||||||
|
}
|
||||||
|
|
||||||
|
_contextNames[context] = [];
|
||||||
|
|
||||||
|
foreach (Type pluginType in pluginTypes)
|
||||||
|
{
|
||||||
|
PluginDescriptor descriptor = CreateDescriptor(assemblyPath, kind, pluginType, context, shadowPath);
|
||||||
|
loaded.Add(descriptor);
|
||||||
|
if (descriptor.Instance != null)
|
||||||
|
{
|
||||||
|
_contextNames[context].Add(descriptor.Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 没有任何一个实例化成功则回收上下文
|
||||||
|
if (_contextNames.TryGetValue(context, out HashSet<string>? names) && names.Count == 0)
|
||||||
|
{
|
||||||
|
_contextNames.TryRemove(context, out _);
|
||||||
|
context.Unload();
|
||||||
|
TryDelete(shadowPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
return loaded;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>创建影子副本(_loaded/{name}.{guid}.dll),返回影子路径;失败返回空串</summary>
|
||||||
|
private string CreateShadowCopy(string assemblyPath, string liveDir)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string shadowDir = Path.Combine(liveDir, StagingDirectoryName, "_loaded");
|
||||||
|
Directory.CreateDirectory(shadowDir);
|
||||||
|
string shadowPath = Path.Combine(shadowDir, $"{Path.GetFileNameWithoutExtension(assemblyPath)}.{Guid.NewGuid():N}.dll");
|
||||||
|
File.Copy(assemblyPath, shadowPath);
|
||||||
|
return shadowPath;
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError(e, "创建影子副本失败:{File}", assemblyPath);
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void TryDelete(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (File.Exists(path))
|
||||||
|
{
|
||||||
|
File.Delete(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// 影子副本可能仍被锁定(上下文未完全回收),忽略
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private PluginDescriptor CreateDescriptor(string assemblyPath, PluginKind kind, Type pluginType, PluginLoadContext context, string? shadowPath = null)
|
||||||
|
{
|
||||||
|
string fileKey = Path.GetFileNameWithoutExtension(assemblyPath);
|
||||||
|
PluginDescriptor descriptor = new()
|
||||||
|
{
|
||||||
|
Name = fileKey,
|
||||||
|
AssemblyPath = assemblyPath,
|
||||||
|
Kind = kind,
|
||||||
|
Status = PluginStatus.Failed,
|
||||||
|
Error = "实例化失败"
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (Activator.CreateInstance(pluginType) is not IPluginBase instance)
|
||||||
|
{
|
||||||
|
return descriptor;
|
||||||
|
}
|
||||||
|
|
||||||
|
descriptor = new PluginDescriptor
|
||||||
|
{
|
||||||
|
Name = instance.Name,
|
||||||
|
Version = instance.Version,
|
||||||
|
Author = instance.Author,
|
||||||
|
Description = instance.Description,
|
||||||
|
Kind = kind,
|
||||||
|
AssemblyPath = assemblyPath,
|
||||||
|
LoadContext = context,
|
||||||
|
ShadowPath = shadowPath,
|
||||||
|
Instance = instance,
|
||||||
|
InstanceWeakReference = new WeakReference(instance),
|
||||||
|
Status = PluginStatus.Loading
|
||||||
|
};
|
||||||
|
|
||||||
|
// 同名加载项已存在:先卸载旧的(热替换)
|
||||||
|
if (_items.TryGetValue(instance.Name, out PluginDescriptor? existing))
|
||||||
|
{
|
||||||
|
UnloadCore(existing, throwIfInUse: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
instance.OnLoad(_services);
|
||||||
|
|
||||||
|
if (kind == PluginKind.ServerPlugin && instance is IServerPlugin serverPlugin)
|
||||||
|
{
|
||||||
|
serverPlugin.ConfigureEndpoints(_httpRegistry, _messageRegistry);
|
||||||
|
}
|
||||||
|
|
||||||
|
descriptor.Status = PluginStatus.Loaded;
|
||||||
|
descriptor.LoadedAt = DateTime.Now;
|
||||||
|
_items[instance.Name] = descriptor;
|
||||||
|
_logger.LogInformation("加载项已加载:{Name} v{Version}({Kind})", instance.Name, instance.Version, kind);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
descriptor.Status = PluginStatus.Failed;
|
||||||
|
descriptor.Error = e.Message;
|
||||||
|
_logger.LogError(e, "加载项初始化失败:{Type}", pluginType.FullName);
|
||||||
|
}
|
||||||
|
|
||||||
|
return descriptor;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 卸载 / 重载 =====
|
||||||
|
|
||||||
|
/// <summary>卸载(被活跃对局引用时抛出)</summary>
|
||||||
|
public void Unload(string name)
|
||||||
|
{
|
||||||
|
if (_items.TryGetValue(name, out PluginDescriptor? descriptor))
|
||||||
|
{
|
||||||
|
UnloadCore(descriptor, throwIfInUse: true);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_logger.LogWarning("加载项不存在:{Name}", name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UnloadCore(PluginDescriptor descriptor, bool throwIfInUse)
|
||||||
|
{
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
if (descriptor.ActiveGames > 0)
|
||||||
|
{
|
||||||
|
string message = $"加载项 {descriptor.Name} 正被 {descriptor.ActiveGames} 个活跃对局引用,无法卸载";
|
||||||
|
if (throwIfInUse)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException(message);
|
||||||
|
}
|
||||||
|
_logger.LogWarning(message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (descriptor.Status != PluginStatus.Loaded && descriptor.Status != PluginStatus.Failed)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
descriptor.Status = PluginStatus.Unloading;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
descriptor.Instance?.OnUnload();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError(e, "加载项卸载回调异常:{Name}", descriptor.Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 移除注册(端点/消息处理器)
|
||||||
|
if (descriptor.Instance != null)
|
||||||
|
{
|
||||||
|
_httpRegistry.UnregisterAll(descriptor.Instance);
|
||||||
|
_messageRegistry.UnregisterAll(descriptor.Instance);
|
||||||
|
}
|
||||||
|
|
||||||
|
PluginLoadContext? context = descriptor.LoadContext;
|
||||||
|
WeakReference? weakReference = descriptor.InstanceWeakReference;
|
||||||
|
string? shadowPath = descriptor.ShadowPath;
|
||||||
|
descriptor.LoadContext = null;
|
||||||
|
descriptor.ShadowPath = null;
|
||||||
|
descriptor.Instance = null;
|
||||||
|
descriptor.InstanceWeakReference = null;
|
||||||
|
descriptor.Status = PluginStatus.Unloaded;
|
||||||
|
descriptor.LoadedAt = null;
|
||||||
|
_items.TryRemove(descriptor.Name, out _);
|
||||||
|
|
||||||
|
// 上下文名下不再有加载项时回收整个 ALC
|
||||||
|
bool unloadContext = true;
|
||||||
|
if (context != null && _contextNames.TryGetValue(context, out HashSet<string>? names))
|
||||||
|
{
|
||||||
|
names.Remove(descriptor.Name);
|
||||||
|
unloadContext = names.Count == 0;
|
||||||
|
if (unloadContext)
|
||||||
|
{
|
||||||
|
_contextNames.TryRemove(context, out _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (context != null && unloadContext)
|
||||||
|
{
|
||||||
|
context.Unload();
|
||||||
|
// 等待可回收上下文实际被 GC(上限 2 秒)
|
||||||
|
if (weakReference != null)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < 20 && weakReference.IsAlive; i++)
|
||||||
|
{
|
||||||
|
GC.Collect();
|
||||||
|
GC.WaitForPendingFinalizers();
|
||||||
|
Thread.Sleep(100);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 影子副本此时可安全删除(失败忽略)
|
||||||
|
if (shadowPath != null)
|
||||||
|
{
|
||||||
|
TryDelete(shadowPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogInformation("加载项已卸载:{Name}", descriptor.Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>热重载指定加载项</summary>
|
||||||
|
public PluginDescriptor? Reload(string name)
|
||||||
|
{
|
||||||
|
if (_items.TryGetValue(name, out PluginDescriptor? descriptor))
|
||||||
|
{
|
||||||
|
string path = descriptor.AssemblyPath;
|
||||||
|
PluginKind kind = descriptor.Kind;
|
||||||
|
UnloadCore(descriptor, throwIfInUse: true);
|
||||||
|
return LoadDll(path, kind).FirstOrDefault(d => d.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||||
|
}
|
||||||
|
_logger.LogWarning("加载项不存在:{Name}", name);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ReloadAll()
|
||||||
|
{
|
||||||
|
foreach (PluginDescriptor descriptor in _items.Values.ToArray())
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Reload(descriptor.Name);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError(e, "热重载失败:{Name}", descriptor.Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 对局引用计数 =====
|
||||||
|
|
||||||
|
public void Acquire(string name)
|
||||||
|
{
|
||||||
|
if (_items.TryGetValue(name, out PluginDescriptor? descriptor))
|
||||||
|
{
|
||||||
|
Interlocked.Increment(ref descriptor.ActiveGames);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Release(string name)
|
||||||
|
{
|
||||||
|
if (_items.TryGetValue(name, out PluginDescriptor? descriptor))
|
||||||
|
{
|
||||||
|
Interlocked.Decrement(ref descriptor.ActiveGames);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 文件监视(自动热重载:构建产物先入 _staging,宿主原子热替换) =====
|
||||||
|
|
||||||
|
/// <summary>暂存区目录名</summary>
|
||||||
|
public const string StagingDirectoryName = "_staging";
|
||||||
|
|
||||||
|
public void EnableFileWatcher()
|
||||||
|
{
|
||||||
|
EnsureDirectories();
|
||||||
|
_watcher = new FileSystemWatcher(ContentRoot)
|
||||||
|
{
|
||||||
|
IncludeSubdirectories = true,
|
||||||
|
NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.CreationTime,
|
||||||
|
EnableRaisingEvents = true
|
||||||
|
};
|
||||||
|
_watcher.Changed += OnPluginFileChanged;
|
||||||
|
_watcher.Created += OnPluginFileChanged;
|
||||||
|
_watcher.Renamed += OnPluginFileChanged;
|
||||||
|
_logger.LogInformation("加载项文件监视已启用(目录:{Dir})", ContentRoot);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnPluginFileChanged(object sender, FileSystemEventArgs e)
|
||||||
|
{
|
||||||
|
if (!IsPluginFile(e.FullPath))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
_pendingReloads.Add(e.FullPath);
|
||||||
|
_reloadDebounce?.Dispose();
|
||||||
|
_reloadDebounce = new System.Threading.Timer(_ => FlushPendingReloads(), null, TimeSpan.FromMilliseconds(600), Timeout.InfiniteTimeSpan);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void FlushPendingReloads()
|
||||||
|
{
|
||||||
|
string[] paths;
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
paths = [.. _pendingReloads];
|
||||||
|
_pendingReloads.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 只处理每个 DLL 的最新一次变更(按文件名去重;写时间相同的事件跳过,避免自我触发循环)
|
||||||
|
foreach (string path in paths
|
||||||
|
.Where(p => p.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
|
||||||
|
.GroupBy(Path.GetFileName)
|
||||||
|
.Select(g => g.OrderByDescending(p => p.Length).First()))
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string normalized = Path.GetFullPath(path);
|
||||||
|
if (!File.Exists(normalized))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
DateTime writeTime = File.GetLastWriteTimeUtc(normalized);
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
if (_handledWrites.TryGetValue(normalized, out DateTime handled) && handled == writeTime)
|
||||||
|
{
|
||||||
|
continue; // 同一文件状态已处理过(如热替换写入引发的二次事件)
|
||||||
|
}
|
||||||
|
_handledWrites[normalized] = writeTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (normalized.Contains(Path.DirectorySeparatorChar + StagingDirectoryName + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)
|
||||||
|
|| normalized.Contains('/' + StagingDirectoryName + '/', StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
ProcessStagingFile(normalized);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
PluginDescriptor? descriptor = _items.Values.FirstOrDefault(d =>
|
||||||
|
Path.GetFileName(d.AssemblyPath).Equals(Path.GetFileName(normalized), StringComparison.OrdinalIgnoreCase));
|
||||||
|
if (descriptor != null)
|
||||||
|
{
|
||||||
|
_logger.LogInformation("检测到加载项文件变化:{Name},执行热重载", descriptor.Name);
|
||||||
|
Reload(descriptor.Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError(e, "自动热重载失败:{Path}", path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 处理暂存区新文件:卸载同名已加载项(释放文件锁)→ 原子替换正式目录 → 重新加载
|
||||||
|
/// </summary>
|
||||||
|
private void ProcessStagingFile(string stagingPath)
|
||||||
|
{
|
||||||
|
string fileName = Path.GetFileName(stagingPath);
|
||||||
|
string stagingDir = Path.GetDirectoryName(stagingPath) ?? "";
|
||||||
|
string liveDir = Directory.GetParent(stagingDir)?.FullName ?? "";
|
||||||
|
string livePath = Path.Combine(liveDir, fileName);
|
||||||
|
PluginKind kind = GetKindForDirectory(liveDir);
|
||||||
|
|
||||||
|
if (!File.Exists(stagingPath))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. 卸载已加载的同名加载项,释放 DLL 文件锁
|
||||||
|
PluginDescriptor? existing = _items.Values.FirstOrDefault(d =>
|
||||||
|
Path.GetFileName(d.AssemblyPath).Equals(fileName, StringComparison.OrdinalIgnoreCase));
|
||||||
|
if (existing != null)
|
||||||
|
{
|
||||||
|
_logger.LogInformation("暂存区检测到 {File},先卸载 {Name} 以释放文件锁", fileName, existing.Name);
|
||||||
|
UnloadCore(existing, throwIfInUse: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 原子替换:移动暂存文件覆盖正式目录(失败则保留旧版继续运行)
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.Move(stagingPath, livePath, true);
|
||||||
|
string stagingPdb = Path.ChangeExtension(stagingPath, ".pdb");
|
||||||
|
if (File.Exists(stagingPdb))
|
||||||
|
{
|
||||||
|
File.Move(stagingPdb, Path.ChangeExtension(livePath, ".pdb"), true);
|
||||||
|
}
|
||||||
|
// 记录正式文件的新写时间,避免移动触发的监视事件重复处理
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
_handledWrites[Path.GetFullPath(livePath)] = File.GetLastWriteTimeUtc(livePath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (IOException ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "热替换失败(正式文件仍被锁定):{File}。可稍后重试或通过管理接口卸载后重新加载。", fileName);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 重新加载
|
||||||
|
_logger.LogInformation("热替换成功:{File},开始加载", fileName);
|
||||||
|
LoadDll(livePath, kind);
|
||||||
|
}
|
||||||
|
|
||||||
|
private PluginKind GetKindForDirectory(string directory)
|
||||||
|
{
|
||||||
|
string normalized = Path.GetFullPath(directory).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||||
|
if (normalized.StartsWith(Path.GetFullPath(PluginsDirectory) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) return PluginKind.ServerPlugin;
|
||||||
|
if (normalized.StartsWith(Path.GetFullPath(CharacterModulesDirectory) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) return PluginKind.CharacterModule;
|
||||||
|
if (normalized.StartsWith(Path.GetFullPath(SkillModulesDirectory) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) return PluginKind.SkillModule;
|
||||||
|
if (normalized.StartsWith(Path.GetFullPath(ItemModulesDirectory) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) return PluginKind.ItemModule;
|
||||||
|
if (normalized.StartsWith(Path.GetFullPath(GameModuleDirectory) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) return PluginKind.GameModuleServer;
|
||||||
|
return PluginKind.ServerPlugin;
|
||||||
|
}
|
||||||
|
|
||||||
|
private IEnumerable<(string Directory, PluginKind Kind)> GetRootDirectories()
|
||||||
|
{
|
||||||
|
yield return (PluginsDirectory, PluginKind.ServerPlugin);
|
||||||
|
yield return (CharacterModulesDirectory, PluginKind.CharacterModule);
|
||||||
|
yield return (SkillModulesDirectory, PluginKind.SkillModule);
|
||||||
|
yield return (ItemModulesDirectory, PluginKind.ItemModule);
|
||||||
|
yield return (GameModuleDirectory, PluginKind.GameModuleServer);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsPluginFile(string path)
|
||||||
|
{
|
||||||
|
string relative = path.Replace(Path.DirectorySeparatorChar, '/');
|
||||||
|
// 影子副本目录(_staging/_loaded)是宿主内部产物,不参与监视
|
||||||
|
if (relative.Contains($"/{StagingDirectoryName}/_loaded/", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return relative.Contains($"/{PluginConstants.PluginsDirectory}/", StringComparison.OrdinalIgnoreCase)
|
||||||
|
|| relative.Contains($"/{PluginConstants.CharacterModulesDirectory}/", StringComparison.OrdinalIgnoreCase)
|
||||||
|
|| relative.Contains($"/{PluginConstants.SkillModulesDirectory}/", StringComparison.OrdinalIgnoreCase)
|
||||||
|
|| relative.Contains($"/{PluginConstants.ItemModulesDirectory}/", StringComparison.OrdinalIgnoreCase)
|
||||||
|
|| relative.Contains($"/{PluginConstants.GameModuleDirectory}/", StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 辅助 =====
|
||||||
|
|
||||||
|
private void EnsureDirectories()
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(PluginsDirectory);
|
||||||
|
Directory.CreateDirectory(CharacterModulesDirectory);
|
||||||
|
Directory.CreateDirectory(SkillModulesDirectory);
|
||||||
|
Directory.CreateDirectory(ItemModulesDirectory);
|
||||||
|
Directory.CreateDirectory(GameModuleDirectory);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Type> FindPluginTypes(Assembly assembly, PluginKind kind)
|
||||||
|
{
|
||||||
|
Type[] types;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
types = assembly.GetTypes();
|
||||||
|
}
|
||||||
|
catch (ReflectionTypeLoadException e)
|
||||||
|
{
|
||||||
|
types = e.Types.Where(t => t != null).Cast<Type>().ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
Type target = kind switch
|
||||||
|
{
|
||||||
|
PluginKind.ServerPlugin => typeof(IServerPlugin),
|
||||||
|
PluginKind.CharacterModule => typeof(ICharacterModule),
|
||||||
|
PluginKind.SkillModule => typeof(ISkillModule),
|
||||||
|
PluginKind.ItemModule => typeof(IItemModule),
|
||||||
|
PluginKind.GameModuleServer => typeof(IGameModuleServer),
|
||||||
|
_ => typeof(IPluginBase)
|
||||||
|
};
|
||||||
|
|
||||||
|
return types.Where(t => t.IsClass && !t.IsAbstract && target.IsAssignableFrom(t)).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
if (_disposed) return;
|
||||||
|
_disposed = true;
|
||||||
|
_watcher?.Dispose();
|
||||||
|
_reloadDebounce?.Dispose();
|
||||||
|
foreach (PluginDescriptor descriptor in _items.Values.ToArray())
|
||||||
|
{
|
||||||
|
UnloadCore(descriptor, throwIfInUse: false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
.DS_Store
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||||
|
"plugins": ["react", "typescript", "oxc"],
|
||||||
|
"rules": {
|
||||||
|
"react/rules-of-hooks": "error",
|
||||||
|
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# React + TypeScript + Vite
|
||||||
|
|
||||||
|
This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
|
||||||
|
|
||||||
|
Currently, two official plugins are available:
|
||||||
|
|
||||||
|
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
||||||
|
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
||||||
|
|
||||||
|
## React Compiler
|
||||||
|
|
||||||
|
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||||
|
|
||||||
|
## Expanding the Oxlint configuration
|
||||||
|
|
||||||
|
If you are developing a production application, we recommend enabling type-aware lint rules by installing `oxlint-tsgolint` and editing `.oxlintrc.json`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||||
|
"plugins": ["react", "typescript", "oxc"],
|
||||||
|
"options": {
|
||||||
|
"typeAware": true
|
||||||
|
},
|
||||||
|
"rules": {
|
||||||
|
"react/rules-of-hooks": "error",
|
||||||
|
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
See the [Oxlint rules documentation](https://oxc.rs/docs/guide/usage/linter/rules) for the full list of rules and categories.
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<?xml version="1.0"?>
|
||||||
|
<configuration>
|
||||||
|
<!--
|
||||||
|
有关 web.config 更改的说明,请参见 http://go.microsoft.com/fwlink/?LinkId=235367。
|
||||||
|
|
||||||
|
可在 <httpRuntime> 标记上设置以下特性。
|
||||||
|
<system.Web>
|
||||||
|
<httpRuntime targetFramework="4.8" />
|
||||||
|
</system.Web>
|
||||||
|
-->
|
||||||
|
<system.web>
|
||||||
|
<compilation debug="false" targetFramework="4.8"/>
|
||||||
|
<pages controlRenderingCompatibilityVersion="4.0"/>
|
||||||
|
</system.web>
|
||||||
|
</configuration>
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>FunGame Server v3 管理控制台</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Generated
+1921
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"name": "webui",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc -b && vite build",
|
||||||
|
"lint": "oxlint",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@tailwindcss/vite": "^4.3.3",
|
||||||
|
"react": "^19.2.8",
|
||||||
|
"react-dom": "^19.2.8",
|
||||||
|
"tailwindcss": "^4.3.3"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^24.13.3",
|
||||||
|
"@types/react": "^19.2.17",
|
||||||
|
"@types/react-dom": "^19.2.3",
|
||||||
|
"@vitejs/plugin-react": "^6.0.4",
|
||||||
|
"oxlint": "^1.75.0",
|
||||||
|
"typescript": "~6.0.2",
|
||||||
|
"vite": "^8.2.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 9.3 KiB |
@@ -0,0 +1,24 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||||
|
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||||
|
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||||
|
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||||
|
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||||
|
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||||
|
</symbol>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,108 @@
|
|||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { get, getToken, clearTokens } from './api'
|
||||||
|
import LoginPage from './pages/LoginPage'
|
||||||
|
import Dashboard from './pages/Dashboard'
|
||||||
|
import UsersPage from './pages/UsersPage'
|
||||||
|
import PluginsPage from './pages/PluginsPage'
|
||||||
|
import GamesPage from './pages/GamesPage'
|
||||||
|
import ReplayPage from './pages/ReplayPage'
|
||||||
|
import LogsPage from './pages/LogsPage'
|
||||||
|
|
||||||
|
type PageKey = 'dashboard' | 'users' | 'plugins' | 'games' | 'replay' | 'logs'
|
||||||
|
|
||||||
|
interface Session {
|
||||||
|
username: string
|
||||||
|
permissions: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== FunGame.Server-v3 管理控制台(React + Tailwind) =====
|
||||||
|
|
||||||
|
export default function App() {
|
||||||
|
const [session, setSession] = useState<Session | null>(null)
|
||||||
|
const [page, setPage] = useState<PageKey>('dashboard')
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = () => {
|
||||||
|
clearTokens()
|
||||||
|
setSession(null)
|
||||||
|
}
|
||||||
|
window.addEventListener('fungame:unauthorized', handler)
|
||||||
|
return () => window.removeEventListener('fungame:unauthorized', handler)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
// 页面加载时若已有令牌则进入控制台(/api/auth/me 校验)
|
||||||
|
useEffect(() => {
|
||||||
|
if (getToken() && !session) {
|
||||||
|
get<{ username: string; permissions: string[] }>('/api/auth/me').then((res) => {
|
||||||
|
if (res.ok) setSession({ username: res.data.username, permissions: res.data.permissions })
|
||||||
|
else {
|
||||||
|
clearTokens()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}, [session])
|
||||||
|
|
||||||
|
if (!session) {
|
||||||
|
return <LoginPage onLogin={setSession} />
|
||||||
|
}
|
||||||
|
|
||||||
|
const nav: { key: PageKey; label: string }[] = [
|
||||||
|
{ key: 'dashboard', label: '仪表盘' },
|
||||||
|
{ key: 'users', label: '用户管理' },
|
||||||
|
{ key: 'plugins', label: '插件与模组' },
|
||||||
|
{ key: 'games', label: '对局管理' },
|
||||||
|
{ key: 'replay', label: '回放中心' },
|
||||||
|
{ key: 'logs', label: '服务器日志' },
|
||||||
|
]
|
||||||
|
|
||||||
|
function logout() {
|
||||||
|
clearTokens()
|
||||||
|
setSession(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen bg-slate-950 text-slate-200">
|
||||||
|
<aside className="w-52 shrink-0 border-r border-slate-800 bg-slate-900/60">
|
||||||
|
<div className="border-b border-slate-800 px-4 py-4">
|
||||||
|
<div className="font-bold text-white">FunGame Server</div>
|
||||||
|
<div className="text-xs text-indigo-400">v3 管理控制台</div>
|
||||||
|
</div>
|
||||||
|
<nav className="space-y-1 p-3">
|
||||||
|
{nav.map((item) => (
|
||||||
|
<button
|
||||||
|
key={item.key}
|
||||||
|
onClick={() => setPage(item.key)}
|
||||||
|
className={`block w-full rounded-lg px-3 py-2 text-left text-sm transition ${
|
||||||
|
page === item.key ? 'bg-indigo-950 text-indigo-300' : 'text-slate-400 hover:bg-slate-800 hover:text-white'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{item.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
<div className="p-3">
|
||||||
|
<button onClick={logout} className="w-full rounded-lg bg-slate-800 px-3 py-2 text-left text-sm text-slate-400 hover:bg-slate-700 hover:text-white">
|
||||||
|
← 退出登录
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
<main className="flex-1 overflow-y-auto p-6">
|
||||||
|
<header className="mb-6 flex items-center justify-between">
|
||||||
|
<h1 className="text-lg font-medium text-slate-300">
|
||||||
|
{nav.find((n) => n.key === page)?.label}
|
||||||
|
</h1>
|
||||||
|
<div className="text-sm text-slate-400">
|
||||||
|
<span className="text-white">{session.username}</span>
|
||||||
|
<span className="ml-2 rounded-full bg-slate-800 px-2 py-0.5 text-xs">{session.permissions.length} 项权限</span>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
{page === 'dashboard' && <Dashboard />}
|
||||||
|
{page === 'users' && <UsersPage />}
|
||||||
|
{page === 'plugins' && <PluginsPage />}
|
||||||
|
{page === 'games' && <GamesPage />}
|
||||||
|
{page === 'replay' && <ReplayPage />}
|
||||||
|
{page === 'logs' && <LogsPage />}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import type { ApiResponse } from './types'
|
||||||
|
|
||||||
|
// ===== API 客户端:统一 JWT 携带 + 401 自动刷新重试 =====
|
||||||
|
|
||||||
|
const TOKEN_KEY = 'fungame.accessToken'
|
||||||
|
const REFRESH_KEY = 'fungame.refreshToken'
|
||||||
|
|
||||||
|
export function getToken(): string | null {
|
||||||
|
return localStorage.getItem(TOKEN_KEY)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getRefreshToken(): string | null {
|
||||||
|
return localStorage.getItem(REFRESH_KEY)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setTokens(accessToken: string, refreshToken: string) {
|
||||||
|
localStorage.setItem(TOKEN_KEY, accessToken)
|
||||||
|
localStorage.setItem(REFRESH_KEY, refreshToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearTokens() {
|
||||||
|
localStorage.removeItem(TOKEN_KEY)
|
||||||
|
localStorage.removeItem(REFRESH_KEY)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshTokens(): Promise<boolean> {
|
||||||
|
const refreshToken = getRefreshToken()
|
||||||
|
if (!refreshToken) return false
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/auth/refresh', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ refreshToken, device: 'webui' }),
|
||||||
|
})
|
||||||
|
if (!res.ok) return false
|
||||||
|
const body = (await res.json()) as ApiResponse<{ accessToken: string; refreshToken: string }>
|
||||||
|
if (!body.ok) return false
|
||||||
|
setTokens(body.data.accessToken, body.data.refreshToken)
|
||||||
|
return true
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function api<T>(path: string, options: RequestInit = {}, retry = true): Promise<ApiResponse<T>> {
|
||||||
|
const headers = new Headers(options.headers)
|
||||||
|
headers.set('Content-Type', 'application/json')
|
||||||
|
const token = getToken()
|
||||||
|
if (token) headers.set('Authorization', `Bearer ${token}`)
|
||||||
|
|
||||||
|
const res = await fetch(path, { ...options, headers })
|
||||||
|
if (res.status === 401 && retry && (await refreshTokens())) {
|
||||||
|
return api<T>(path, options, false)
|
||||||
|
}
|
||||||
|
if (res.status === 401 && !getToken()) {
|
||||||
|
clearTokens()
|
||||||
|
window.dispatchEvent(new Event('fungame:unauthorized'))
|
||||||
|
}
|
||||||
|
const body = (await res.json().catch(() => null)) as ApiResponse<T> | null
|
||||||
|
if (!body) {
|
||||||
|
return { ok: false, code: res.status, message: `请求失败(${res.status})`, data: null as T, timestamp: new Date().toISOString() }
|
||||||
|
}
|
||||||
|
return body
|
||||||
|
}
|
||||||
|
|
||||||
|
export const get = <T>(path: string) => api<T>(path)
|
||||||
|
export const post = <T>(path: string, body?: unknown) => api<T>(path, { method: 'POST', body: JSON.stringify(body ?? {}) })
|
||||||
|
export const put = <T>(path: string, body?: unknown) => api<T>(path, { method: 'PUT', body: JSON.stringify(body ?? {}) })
|
||||||
|
export const del = <T>(path: string) => api<T>(path, { method: 'DELETE' })
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user