commit d99ccbbb0ccdc4d8c9d41f5dbf37ee6fa9c0a048 Author: milimoe Date: Fri Aug 28 19:44:46 2026 +0800 first commit diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..52784b3 --- /dev/null +++ b/.gitignore @@ -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 diff --git a/.workbuddy/memory/2026-08-22.md b/.workbuddy/memory/2026-08-22.md new file mode 100644 index 0000000..5d845b9 --- /dev/null +++ b/.workbuddy/memory/2026-08-22.md @@ -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` 先试无参构造,失败退化 `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(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(module_name, file_name)` → `EntityModuleConfig` 从 **`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 加 `` 随构建复制到 bin(运行时 BaseDirectory 可读)。 +- `OshimaItemModule.BuildEntities` 先 `Factory.GetGameModuleInstances("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)。 + diff --git a/.workbuddy/memory/2026-08-26.md b/.workbuddy/memory/2026-08-26.md new file mode 100644 index 0000000..7377410 --- /dev/null +++ b/.workbuddy/memory/2026-08-26.md @@ -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),待用户确认后开工。 diff --git a/.workbuddy/memory/2026-08-27.md b/.workbuddy/memory/2026-08-27.md new file mode 100644 index 0000000..0aeac15 --- /dev/null +++ b/.workbuddy/memory/2026-08-27.md @@ -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)。 diff --git a/.workbuddy/memory/MEMORY.md b/.workbuddy/memory/MEMORY.md new file mode 100644 index 0000000..05ecc02 --- /dev/null +++ b/.workbuddy/memory/MEMORY.md @@ -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 可用。 diff --git a/FunGame.Server-v3.slnx b/FunGame.Server-v3.slnx new file mode 100644 index 0000000..2228773 --- /dev/null +++ b/FunGame.Server-v3.slnx @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..df856ef --- /dev/null +++ b/LICENSE.txt @@ -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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..9467c33 --- /dev/null +++ b/README.md @@ -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`:每张表派生控制器即得 分页列表/详情/创建/更新/删除 | +| 负载模型 | WebSocket `MessageEnvelope`(t/i/ok/error/d/ts,替代 SocketObject);REST `ApiResponse` | +| 插件系统 | **始终热重载**:`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 --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 架构定稿(开发依据)** diff --git a/docs/01-v2-功能总结.md b/docs/01-v2-功能总结.md new file mode 100644 index 0000000..60cf125 --- /dev/null +++ b/docs/01-v2-功能总结.md @@ -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`) + +- 人数上限检查(`ConnectingPlayerCount + OnlinePlayerCount > MaxPlayers` 拒绝) +- IP 黑名单检查(`BannedList`,按 `ip:port` 拆分比较) +- 客户端参数验证(`OnValidateClientParameters`): + - Desktop 参数 1:客户端模组列表,与服务器 `GameModuleSupported` 对比,缺失则拒绝 + - Desktop 参数 2:客户端是否开启开发者模式(`isDebugMode`,开发者模式部分功能禁用) + - 可挂载 `ValidateClientParameters` 事件由插件扩展校验 +- 握手回复 `Connect` 消息(成功/失败原因),携带服务器名与公告 +- 连接成功回调插件事件:`OnBeforeConnectEvent` / `OnAfterConnectEvent` + +### 3.2 客户端会话(`ServerModel` : IServerModel) + +每个连接对应一个 `ServerModel` 或 `ServerModel`: + +- **消息分发** `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` 是业务核心,按 `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 ` | `-a` / `-r` | 添加/移除 IP 黑名单 | +| `reload ` | `-a/-m/-p/-sp/-wp` | 热重载加载项 | + +- 命令解析支持引号与转义(`ParseCommandLine`) +- 未知指令广播给插件处理 + +--- + +## 12. WebAPI(RESTful)接口清单 + +统一返回 `PayloadModel`(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` 形式直接调用数据请求(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、日志工具等。 diff --git a/docs/02-v3-Core-变更分析.md b/docs/02-v3-Core-变更分析.md new file mode 100644 index 0000000..7551ec0 --- /dev/null +++ b/docs/02-v3-Core-变更分析.md @@ -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` / `GetInstance(id, name, args)`(按 id/name 动态实例化 Character/Skill/Effect/Item/Inventory/Room/User),`GetGameModuleInstances(module_name, file_name)` 从**模块配置文件**批量实例化,`CreateGameModuleEntityConfig` 生成模块实体配置 +- `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 可以在它之上叠加网络/账号/房间层,或者完全另起架构。 diff --git a/docs/03-Server-v3-开发规划.md b/docs/03-Server-v3-开发规划.md new file mode 100644 index 0000000..c05dda5 --- /dev/null +++ b/docs/03-Server-v3-开发规划.md @@ -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` 实例化。参考 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) +│ ├── 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 的成熟业务代码可迁移复用,但底层基础设施(网络、数据库、配置、日志)需要在新项目里重建。 diff --git a/docs/04-架构设计.md b/docs/04-架构设计.md new file mode 100644 index 0000000..3cf0c3d --- /dev/null +++ b/docs/04-架构设计.md @@ -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`: + +``` +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`;权限用 `[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`(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`) + +### 4.2 负载信封(替代 SocketObject) + +```jsonc +// 客户端 → 服务器(请求) +{ + "t": "room.create", // 消息类型(点分字符串,替代 SocketMessageType 枚举) + "i": 1, // 请求序号(客户端生成,用于响应关联) + "d": { ... } // 负载(Dictionary,实体用 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` 生成/读取 JSON 配置;`Factory.GetGameModuleInstances(module, file)` 实例化实体 +- WebUI 提供"实体模组管理"页:查看/编辑/重新加载 JSON 配置(不重启进程改游戏内容) + +### 5.4 服务器插件接口(Contracts) + +```csharp +public interface IServerPlugin : IPluginBase +{ + // 注册 HTTP 端点(挂载 /plugin/{name}/{path},注册表 + 单一路由分发,可热移除) + // 与 WebSocket 消息处理器(随插件热卸载自动注销) + void ConfigureEndpoints(IPluginHttpHandlerRegistry http, IMessageHandlerRegistry messages); + // 对局模式逻辑(可选):局内消息转发到模式插件 + Task?> HandleGamingMessage(IGameSession session, string type, Dictionary 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 的迁移与部署验证 diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..c4af91d --- /dev/null +++ b/docs/README.md @@ -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)。 diff --git a/dotnet-tools.json b/dotnet-tools.json new file mode 100644 index 0000000..6030b24 --- /dev/null +++ b/dotnet-tools.json @@ -0,0 +1,13 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "dotnet-ef": { + "version": "10.0.11", + "commands": [ + "dotnet-ef" + ], + "rollForward": false + } + } +} \ No newline at end of file diff --git a/modules/FunGame.Server.Modules.Example/Characters/ExampleCharacters.cs b/modules/FunGame.Server.Modules.Example/Characters/ExampleCharacters.cs new file mode 100644 index 0000000..576ca24 --- /dev/null +++ b/modules/FunGame.Server.Modules.Example/Characters/ExampleCharacters.cs @@ -0,0 +1,54 @@ +using FunGame.Core.Entity; +using FunGame.Core.Library.Constant; + +namespace FunGame.Server.Modules.Example; + +/// 示例角色:战士(力量型近战) +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; + } +} + +/// 示例角色:法师(智力型远程) +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; + } +} diff --git a/modules/FunGame.Server.Modules.Example/ExampleModules.cs b/modules/FunGame.Server.Modules.Example/ExampleModules.cs new file mode 100644 index 0000000..c69d108 --- /dev/null +++ b/modules/FunGame.Server.Modules.Example/ExampleModules.cs @@ -0,0 +1,136 @@ +using FunGame.Core.Api; +using FunGame.Core.Entity; +using FunGame.Server.Contracts.Plugins; + +namespace FunGame.Server.Modules.Example; + +/// +/// 示例角色模组:注册工厂(工厂注册保持模块化)+ 提供实体集合 +/// 通过工厂注册后,实体 JSON 配置(EntityModuleConfig)通道也能实例化本模组的角色 +/// +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? _entities; + + public IReadOnlyDictionary Entities + { + get + { + _entities ??= new Dictionary + { + ["example_warrior"] = new ExampleWarrior(), + ["example_mage"] = new ExampleMage() + }; + return _entities; + } + } + + public void OnLoad(IServiceProvider services) + { + // 工厂注册:id -> 构造函数,供 Factory.GetInstance / GetGameModuleInstances 使用 + Factory.OpenFactory.RegisterFactory((id, name, args) => id switch + { + 90001 => new ExampleWarrior(), + 90002 => new ExampleMage(), + _ => null + }); + } + + public void OnUnload() + { + // 从工厂注销(保持工厂可被热重载模组替换) + Factory.OpenFactory.UnRegisterFactory((id, name, args) => id switch + { + 90001 => new ExampleWarrior(), + 90002 => new ExampleMage(), + _ => null + }); + } +} + +/// 示例技能模组 +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? _entities; + + public IReadOnlyDictionary Entities + { + get + { + _entities ??= new Dictionary + { + ["example_strike"] = new ExampleStrike() + }; + return _entities; + } + } + + public void OnLoad(IServiceProvider services) + { + Factory.OpenFactory.RegisterFactory((id, name, args) => id switch + { + 91001 => new ExampleStrike(), + _ => null + }); + } + + public void OnUnload() + { + Factory.OpenFactory.UnRegisterFactory((id, name, args) => id switch + { + 91001 => new ExampleStrike(), + _ => null + }); + } +} + +/// 示例物品模组 +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? _entities; + + public IReadOnlyDictionary Entities + { + get + { + _entities ??= new Dictionary + { + ["example_potion"] = new ExamplePotion() + }; + return _entities; + } + } + + public void OnLoad(IServiceProvider services) + { + Factory.OpenFactory.RegisterFactory((id, name, args) => id switch + { + 92001 => new ExamplePotion(), + _ => null + }); + } + + public void OnUnload() + { + Factory.OpenFactory.UnRegisterFactory((id, name, args) => id switch + { + 92001 => new ExamplePotion(), + _ => null + }); + } +} diff --git a/modules/FunGame.Server.Modules.Example/FunGame.Server.Modules.Example.csproj b/modules/FunGame.Server.Modules.Example/FunGame.Server.Modules.Example.csproj new file mode 100644 index 0000000..188e243 --- /dev/null +++ b/modules/FunGame.Server.Modules.Example/FunGame.Server.Modules.Example.csproj @@ -0,0 +1,26 @@ + + + + net10.0 + enable + enable + FunGame.Server.Modules.Example + + + + + + + + + + + + + + + + + + + diff --git a/modules/FunGame.Server.Modules.Example/Items/ExampleItems.cs b/modules/FunGame.Server.Modules.Example/Items/ExampleItems.cs new file mode 100644 index 0000000..1111bf3 --- /dev/null +++ b/modules/FunGame.Server.Modules.Example/Items/ExampleItems.cs @@ -0,0 +1,20 @@ +using FunGame.Core.Entity; +using FunGame.Core.Library.Constant; + +namespace FunGame.Server.Modules.Example; + +/// 示例物品:回复药剂(使用后回复生命值) +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 点生命值。"; + } +} diff --git a/modules/FunGame.Server.Modules.Example/Skills/ExampleSkills.cs b/modules/FunGame.Server.Modules.Example/Skills/ExampleSkills.cs new file mode 100644 index 0000000..a21ec7e --- /dev/null +++ b/modules/FunGame.Server.Modules.Example/Skills/ExampleSkills.cs @@ -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; + +/// 示例技能:强力打击(物理伤害 + 小幅度生命回复) +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)); + } +} + +/// 示例特效:基于攻击力的物理伤害 +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); + } + } + } +} diff --git a/modules/FunGame.Server.Modules.Melee/FunGame.Server.Modules.Melee.csproj b/modules/FunGame.Server.Modules.Melee/FunGame.Server.Modules.Melee.csproj new file mode 100644 index 0000000..47add01 --- /dev/null +++ b/modules/FunGame.Server.Modules.Melee/FunGame.Server.Modules.Melee.csproj @@ -0,0 +1,24 @@ + + + + net10.0 + enable + enable + FunGame.Server.Modules.Melee + + + + + + + + + + + + + + + + + diff --git a/modules/FunGame.Server.Modules.Melee/MeleeGameModuleServer.cs b/modules/FunGame.Server.Modules.Melee/MeleeGameModuleServer.cs new file mode 100644 index 0000000..8e53d1d --- /dev/null +++ b/modules/FunGame.Server.Modules.Melee/MeleeGameModuleServer.cs @@ -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; + +/// +/// 标准近战 GameModule(游戏模式模组):封装网络层在 MixGamingQueue 之上 +/// 参考 v2 ExampleGameModuleServer:单例模组、按房间建 Worker(GamingObject 对应物)、 +/// GamingType switch-case 处理玩家行动;内容层(角色/技能/物品/Effect)经 GameModuleDepend 声明依赖。 +/// 当前为 Phase 0:建房(StartGameAsync)+ 连接确认 + 选角;Attack/Skill/Item 等玩家局内决策后续接入。 +/// +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; + + /// 房间工作区:游戏 Id ->(角色池 / 已连接用户 / 用户角色选择) + private sealed record Worker(List Characters, HashSet ConnectedUsers, Dictionary UserCharacters); + + private readonly ConcurrentDictionary _workers = new(); + + public void OnLoad(IServiceProvider services) + { + _logger = services.GetService()?.CreateLogger("GameModule.melee"); + _logger?.LogInformation("MeleeGameModuleServer v{Version} 已加载", Version); + } + + public void OnUnload() + { + _logger?.LogInformation("MeleeGameModuleServer 即将卸载(活跃对局 {Count})", _workers.Count); + _workers.Clear(); + } + + /// 建房:创建 MixGamingQueue(沿用宿主当前淘汰/复活=1 配置),登记房间工作区 + public Task StartGameAsync(IGameSession session, params object[] args) + { + List characters = args.Length > 0 && args[0] is List 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(queue); + } + + /// 处理客户端局内消息(switch-case GamingType,参考 v2) + public Task?> HandleGamingMessageAsync(IGameSession session, IClientSession client, GamingType type, Dictionary data) + { + if (!_workers.TryGetValue(session.Id, out Worker? worker)) + { + return Task.FromResult?>(new Dictionary { ["error"] = "对局工作区不存在" }); + } + + long userId = client.UserId ?? client.SessionId; + switch (type) + { + case GamingType.Connect: + worker.ConnectedUsers.Add(userId); + return Task.FromResult?>(new Dictionary + { + ["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?>(new Dictionary { ["error"] = $"角色不存在:{id}" }); + } + worker.UserCharacters[userId] = character; + return Task.FromResult?>(new Dictionary + { + ["msg"] = $"已选择角色:{character.NickName ?? character.Name}", + ["id"] = character.Id + }); + } + + case GamingType.Surrender: + _ = session.EndGameAsync(); + return Task.FromResult?>(new Dictionary { ["msg"] = "对局已结束" }); + + default: + // Attack/Skill/Item/Move/Magic/Buy/... 玩家局内决策接入后续里程碑实现 + return Task.FromResult?>(new Dictionary + { + ["msg"] = $"已收到 {type}(玩家局内决策接入后续实现)", + ["round"] = session.Queue.TotalRound + }); + } + } + + private static long GetLong(Dictionary data, string key) + => data.TryGetValue(key, out object? value) && long.TryParse(value?.ToString(), out long result) ? result : 0; +} diff --git a/modules/FunGame.Server.Modules.Oshima/FunGame.Server.Modules.Oshima.csproj b/modules/FunGame.Server.Modules.Oshima/FunGame.Server.Modules.Oshima.csproj new file mode 100644 index 0000000..4cfd07d --- /dev/null +++ b/modules/FunGame.Server.Modules.Oshima/FunGame.Server.Modules.Oshima.csproj @@ -0,0 +1,29 @@ + + + + net10.0 + enable + enable + FunGame.Server.Modules.Oshima + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/FunGame.Server.Modules.Oshima/OshimaGameModuleConstant.cs b/modules/FunGame.Server.Modules.Oshima/OshimaGameModuleConstant.cs new file mode 100644 index 0000000..2f4790a --- /dev/null +++ b/modules/FunGame.Server.Modules.Oshima/OshimaGameModuleConstant.cs @@ -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"; + } +} diff --git a/modules/FunGame.Server.Modules.Oshima/OshimaServerModules.cs b/modules/FunGame.Server.Modules.Oshima/OshimaServerModules.cs new file mode 100644 index 0000000..8500bc8 --- /dev/null +++ b/modules/FunGame.Server.Modules.Oshima/OshimaServerModules.cs @@ -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; + +/// +/// 创建实体新实例:优先无参构造;无无参构造时退化为 (Character? = null) 风格的构造(技能类惯例) +/// 工厂委托必须返回新实例而非 Copy(),避免 Skill.Copy 内部调用 Factory.GetInstance 造成无限递归 +/// +internal static class ModuleEntityFactory +{ + public static T? Create(Type type) where T : class + { + try + { + return (T)Activator.CreateInstance(type)!; + } + catch (MissingMethodException) + { + return (T)Activator.CreateInstance(type, (object?[]?)[null])!; + } + } +} + +/// +/// Oshima Studios 角色模组:Testing-v3(FunGameSimulation)同源内容,供 Server 加载 +/// 18 名角色(大島シヤ / 心音 / 阳 / 南甘雨 …),与 Testing-v3 的 Oshima CharacterModule 工厂(id 1-18)一一对应 +/// +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? _entities; + + public IReadOnlyDictionary Entities + { + get + { + _entities ??= new Dictionary + { + ["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((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((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 + }); + } +} + +/// +/// Oshima 技能模组:基础战技 / 爆发技 / 被动 / 通用被动 / 通用爆发 / 魔法 全量注册 +/// +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? _entities; + + public IReadOnlyDictionary Entities + { + get + { + _entities ??= BuildEntities(); + return _entities; + } + } + + private static IReadOnlyDictionary BuildEntities() + { + Dictionary 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((id, name, args) => skill.Id == id ? ModuleEntityFactory.Create(skill.GetType()) : null); + } + } + + public void OnUnload() + { + foreach (Skill skill in Entities.Values) + { + Factory.OpenFactory.UnRegisterFactory((id, name, args) => skill.Id == id ? ModuleEntityFactory.Create(skill.GetType()) : null); + } + } +} + +/// +/// Oshima 物品模组:装备(武器/防具/鞋子/饰品)+ 消耗品 + 收藏品 全量注册 +/// +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)"; + + /// JSON 配置物品数量(modules/oshima-studios/oshima.fungame.items.json) + public static int JsonItemCount { get; private set; } + + private IReadOnlyDictionary? _entities; + + public IReadOnlyDictionary Entities + { + get + { + _entities ??= BuildEntities(); + return _entities; + } + } + + private static IReadOnlyDictionary BuildEntities() + { + Dictionary items = new(); + + // ===== JSON 配置物品(EntityModuleConfig 通道:modules/oshima-studios/oshima.fungame.items.json)===== + try + { + Dictionary jsonItems = Factory.GetGameModuleInstances(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((id, name, args) => item.Id == id ? ModuleEntityFactory.Create(item.GetType()) : null); + } + } + + public void OnUnload() + { + foreach (Item item in Entities.Values) + { + Factory.OpenFactory.UnRegisterFactory((id, name, args) => item.Id == id ? ModuleEntityFactory.Create(item.GetType()) : null); + } + } +} diff --git a/plugins/FunGame.Server.Plugins.Example/ExamplePlugin.cs b/plugins/FunGame.Server.Plugins.Example/ExamplePlugin.cs new file mode 100644 index 0000000..e1c8356 --- /dev/null +++ b/plugins/FunGame.Server.Plugins.Example/ExamplePlugin.cs @@ -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; + +/// +/// 示例服务器插件(合并 v2 的 WebAPIPlugin 与 GameModuleServer) +/// - HTTP 端点:GET /plugin/example/hello +/// - WS 消息处理器:example.echo +/// - 对局模式:HandleGamingMessage(example.cheer) +/// +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()?.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?> HandleGamingMessage(IGameSession session, string type, Dictionary data) + { + if (type == "example.cheer") + { + return Task.FromResult?>(new Dictionary + { + ["message"] = $"插件 {Name} 收到对局消息(对局 {session.Id},回合 {session.Queue.TotalRound})" + }); + } + return Task.FromResult?>(null); + } +} diff --git a/plugins/FunGame.Server.Plugins.Example/FunGame.Server.Plugins.Example.csproj b/plugins/FunGame.Server.Plugins.Example/FunGame.Server.Plugins.Example.csproj new file mode 100644 index 0000000..a894ac1 --- /dev/null +++ b/plugins/FunGame.Server.Plugins.Example/FunGame.Server.Plugins.Example.csproj @@ -0,0 +1,25 @@ + + + + net10.0 + enable + enable + FunGame.Server.Plugins.Example + + + + + + + + + + + + + + + + + + diff --git a/src/FunGame.Server.Contracts/Constants/ServerConstants.cs b/src/FunGame.Server.Contracts/Constants/ServerConstants.cs new file mode 100644 index 0000000..1ce59e8 --- /dev/null +++ b/src/FunGame.Server.Contracts/Constants/ServerConstants.cs @@ -0,0 +1,58 @@ +namespace FunGame.Server.Contracts.Constants; + +/// +/// 插件/模组/记录目录约定 +/// +public static class PluginConstants +{ + /// 服务器插件目录 + public const string PluginsDirectory = "plugins"; + + /// 角色模组目录 + public const string CharacterModulesDirectory = "modules/characters"; + + /// 技能模组目录 + public const string SkillModulesDirectory = "modules/skills"; + + /// 物品模组目录 + public const string ItemModulesDirectory = "modules/items"; + + /// 游戏模式模组(GameModule)目录 + public const string GameModuleDirectory = "modules/games"; + + /// 回合记录归档目录 + public const string RecordsDirectory = "records"; + + /// SQLite 数据目录 + public const string DataDirectory = "Data"; +} + +/// +/// 权限点(细粒度 RBAC;JWT Claim:perm) +/// +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"; + + /// 全部权限点:Code -> 说明 + public static IReadOnlyDictionary All { get; } = new Dictionary + { + [UsersRead] = "查看用户", + [UsersWrite] = "管理用户(增删改、角色分配、会话管理)", + [RolesManage] = "管理角色", + [PermissionsManage] = "管理权限点", + [PluginsManage] = "管理插件与模组(热重载)", + [GamesManage] = "管理对局(强制结束等)", + [LogsRead] = "查看服务器日志", + [ConfigManage] = "管理系统配置", + [TokensManage] = "管理 API 令牌" + }; +} diff --git a/src/FunGame.Server.Contracts/FunGame.Server.Contracts.csproj b/src/FunGame.Server.Contracts/FunGame.Server.Contracts.csproj new file mode 100644 index 0000000..e9d9ba4 --- /dev/null +++ b/src/FunGame.Server.Contracts/FunGame.Server.Contracts.csproj @@ -0,0 +1,18 @@ + + + + net10.0 + enable + enable + FunGame.Server.Contracts + + + + + + + + + + + diff --git a/src/FunGame.Server.Contracts/Gaming/GameModuleDepend.cs b/src/FunGame.Server.Contracts/Gaming/GameModuleDepend.cs new file mode 100644 index 0000000..974ae7d --- /dev/null +++ b/src/FunGame.Server.Contracts/Gaming/GameModuleDepend.cs @@ -0,0 +1,36 @@ +namespace FunGame.Server.Contracts.Gaming; + +/// +/// 游戏模式模组(GameModule)的内容依赖声明 +/// 参考 v2 GameModuleDepend:声明该模式依赖的地图/角色/技能/物品内容前缀(如 "example"、"oshima") +/// 宿主建房装配角色时只从声明允许的内容模组族取;空数组 = 不限制 +/// +public class GameModuleDepend +{ + /// 依赖的地图前缀(如 "fungame.example.gamemap") + public string[] MapsDepend { get; init; } = []; + + /// 依赖的角色内容前缀(如 "oshima" → oshima.characters) + public string[] CharactersDepend { get; init; } = []; + + /// 依赖的技能内容前缀(如 "oshima" → oshima.skills) + public string[] SkillsDepend { get; init; } = []; + + /// 依赖的物品内容前缀(如 "oshima" → oshima.items) + 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; + } + + /// 不限制内容(宿主按房间 ContentModule 装配) + public static GameModuleDepend All { get; } = new([], [], [], []); +} diff --git a/src/FunGame.Server.Contracts/Gaming/IGameSession.cs b/src/FunGame.Server.Contracts/Gaming/IGameSession.cs new file mode 100644 index 0000000..686bdce --- /dev/null +++ b/src/FunGame.Server.Contracts/Gaming/IGameSession.cs @@ -0,0 +1,39 @@ +using FunGame.Core.Entity; +using FunGame.Core.Model.Queue; +using FunGame.Server.Contracts.Networking; + +namespace FunGame.Server.Contracts.Gaming; + +/// +/// 对局会话(宿主维护,暴露给游戏模式模组 GameModuleServer) +/// 模组能力:读参与角色 / 广播局内事件 / 结束对局 +/// +public interface IGameSession +{ + /// 对局唯一标识 + Guid Id { get; } + + /// 战斗引擎队列(模组建房时创建) + GamingQueue Queue { get; } + + /// 游戏模式(GameModule 名 / 服务器插件名) + string Mode { get; } + + /// 用户 Id -> 客户端会话(本局参与者) + IReadOnlyDictionary Clients { get; } + + /// 对局是否仍在运行 + bool Running { get; } + + /// 自定义数据(模组私有状态) + Dictionary CustomData { get; } + + /// 本局参与角色(宿主装配,供模组取用) + IReadOnlyList Characters { get; } + + /// 广播消息给本局全部用户(userIds 为空)或指定用户 + Task BroadcastAsync(string messageType, Dictionary data, params long[] userIds); + + /// 结束对局(宿主负责归档回合记录与广播结算) + Task EndGameAsync(bool aborted = false); +} diff --git a/src/FunGame.Server.Contracts/Networking/IClientSession.cs b/src/FunGame.Server.Contracts/Networking/IClientSession.cs new file mode 100644 index 0000000..3141638 --- /dev/null +++ b/src/FunGame.Server.Contracts/Networking/IClientSession.cs @@ -0,0 +1,25 @@ +using FunGame.Server.Contracts.Payloads; + +namespace FunGame.Server.Contracts.Networking; + +/// +/// 客户端会话抽象(WebSocket 连接;替代 v2 的 IServerModel) +/// 由宿主实现,供业务层与插件层使用 +/// +public interface IClientSession +{ + long SessionId { get; } + long? UserId { get; } + string? Username { get; } + IReadOnlyCollection Permissions { get; } + bool IsAuthenticated { get; } + DateTime ConnectedAt { get; } + DateTime LastActiveAt { get; } + string RemoteAddress { get; } + + /// 发送消息 + Task SendAsync(MessageEnvelope message, CancellationToken cancellationToken = default); + + /// 关闭连接 + Task CloseAsync(string reason, CancellationToken cancellationToken = default); +} diff --git a/src/FunGame.Server.Contracts/Payloads/ApiResponse.cs b/src/FunGame.Server.Contracts/Payloads/ApiResponse.cs new file mode 100644 index 0000000..0d0103d --- /dev/null +++ b/src/FunGame.Server.Contracts/Payloads/ApiResponse.cs @@ -0,0 +1,47 @@ +namespace FunGame.Server.Contracts.Payloads; + +/// +/// REST API 统一响应包装(与 WebSocket 信封对齐) +/// +public class ApiResponse +{ + 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 Success(T? data, string? message = null) => new() + { + Ok = true, + Code = 0, + Data = data, + Message = message + }; + + public static ApiResponse Fail(int code, string message) => new() + { + Ok = false, + Code = code, + Message = message + }; +} + +public static class ApiResponse +{ + public static ApiResponse Success(T? data, string? message = null) => ApiResponse.Success(data, message); + public static ApiResponse Fail(int code, string message) => ApiResponse.Fail(code, message); + public static ApiResponse Success(object? data, string? message = null) => Success(data, message); + public static ApiResponse Fail(int code, string message) => Fail(code, message); +} + +/// +/// 分页数据包装(列表类 CRUD 接口统一返回) +/// +public class PagedData +{ + public int Page { get; set; } + public int PageSize { get; set; } + public long Total { get; set; } + public List Items { get; set; } = []; +} diff --git a/src/FunGame.Server.Contracts/Payloads/MessageEnvelope.cs b/src/FunGame.Server.Contracts/Payloads/MessageEnvelope.cs new file mode 100644 index 0000000..0ac67ec --- /dev/null +++ b/src/FunGame.Server.Contracts/Payloads/MessageEnvelope.cs @@ -0,0 +1,59 @@ +using System.Text.Json.Serialization; + +namespace FunGame.Server.Contracts.Payloads; + +/// +/// WebSocket 负载信封(替代 v2 的 SocketObject) +/// 字段:t=消息类型(点分字符串)、i=请求序号(客户端生成,用于响应关联)、ok=是否成功、error=错误信息、d=负载字典、ts=时间戳 +/// +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 Data { get; set; } = []; + + [JsonPropertyName("ts")] + public long Timestamp { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + + /// + /// 依据请求生成响应信封(类型与序号回显) + /// + public static MessageEnvelope Reply(MessageEnvelope request, Dictionary? data = null, bool ok = true, MessageError? error = null) => new() + { + Type = request.Type, + Id = request.Id, + Ok = ok, + Error = error, + Data = data ?? [] + }; + + /// + /// 构造服务器主动广播信封(i=0 表示无关联请求) + /// + public static MessageEnvelope Broadcast(string type, Dictionary? 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; } = ""; +} diff --git a/src/FunGame.Server.Contracts/Payloads/MessageTypes.cs b/src/FunGame.Server.Contracts/Payloads/MessageTypes.cs new file mode 100644 index 0000000..043afc4 --- /dev/null +++ b/src/FunGame.Server.Contracts/Payloads/MessageTypes.cs @@ -0,0 +1,63 @@ +namespace FunGame.Server.Contracts.Payloads; + +/// +/// WebSocket 消息类型注册表(替代 v2 的 SocketMessageType 枚举) +/// 命名约定:小写点分(域.动作);服务器响应使用同类型信封 + ok/error 字段 +/// +public static class MessageTypes +{ + // ===== 系统 ===== + /// 心跳请求 + public const string Ping = "system.ping"; + /// 心跳响应 + public const string Pong = "system.pong"; + /// 服务器公告 + public const string Notice = "system.notice"; + /// 系统消息(弹窗/提示) + public const string System = "system.message"; + /// 被踢下线 + public const string Kick = "system.kick"; + /// 服务器信息 + 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"; + /// 对端信息(登录成功后服务器下发用户/权限快照) + 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"; + /// 房间内广播(加入/离开/房主变更) + 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"; + /// 局内决策(决策点:技能/物品/移动) + public const string GamingAction = "gaming.action"; + /// 局内断线重连 + public const string GamingReconnect = "gaming.reconnect"; + /// 主动结束对局 + public const string GamingEnd = "gaming.end"; + /// 游戏结束结算广播 + public const string GamingOver = "gaming.over"; + /// 回合记录推送(观战/直播,来源:回合记录外发) + public const string GamingRound = "gaming.round"; + /// 行动顺序表推送 + public const string GamingQueue = "gaming.queue"; +} diff --git a/src/FunGame.Server.Contracts/Plugins/IGameModuleServer.cs b/src/FunGame.Server.Contracts/Plugins/IGameModuleServer.cs new file mode 100644 index 0000000..d063e80 --- /dev/null +++ b/src/FunGame.Server.Contracts/Plugins/IGameModuleServer.cs @@ -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; + +/// +/// 游戏模式模组(GameModule 服务器侧):封装网络层在 GamingQueue 之上的"游戏模式" +/// 参考 v2 IGameModuleServer/GameModuleServer:模组为单例,为每个房间建工作区(玩家/角色/状态), +/// 用 switch-case 处理 (Connect/PickCharacter/Skill/Item/...),并广播局内事件。 +/// 内容模组(ICharacterModule/ISkillModule/IItemModule)只是其依赖的内容层。 +/// +public interface IGameModuleServer : IPluginBase +{ + /// 游戏模式名(= 房间 GameModule 字段,如 "melee") + string Id { get; } + + /// 内容依赖声明(地图/角色/技能/物品前缀) + GameModuleDepend Dependencies { get; } + + /// 默认地图(可空) + string DefaultMap { get; } + + /// 适用房间模式(Mix/Team/...) + RoomType RoomType { get; } + + /// 模组容纳人数 + int MaxUsers { get; } + + /// + /// 建房:由宿主创建对局会话后调用,模组在此创建并返回 GamingQueue(装配角色、连接确认、启动流程) + /// args[0] = 宿主装配好的参与角色 List<Character>;args[1] = 可选 GameMap + /// + Task StartGameAsync(IGameSession session, params object[] args); + + /// + /// 处理客户端局内消息(switch-case ) + /// 返回的字典由宿主原样回复给发起客户端;返回 null 表示不处理 + /// + Task?> HandleGamingMessageAsync(IGameSession session, IClientSession client, GamingType type, Dictionary data); +} diff --git a/src/FunGame.Server.Contracts/Plugins/PluginInterfaces.cs b/src/FunGame.Server.Contracts/Plugins/PluginInterfaces.cs new file mode 100644 index 0000000..f67bf13 --- /dev/null +++ b/src/FunGame.Server.Contracts/Plugins/PluginInterfaces.cs @@ -0,0 +1,60 @@ +using FunGame.Core.Entity; +using FunGame.Core.Model.Queue; +using FunGame.Server.Contracts.Gaming; + +namespace FunGame.Server.Contracts.Plugins; + +/// +/// 所有加载项(服务器插件 / 角色·技能·物品模组)的公共基接口 +/// +public interface IPluginBase +{ + string Name { get; } + string Version { get; } + string Author { get; } + string Description { get; } + + /// 加载:接收宿主服务(可取得日志、配置、数据库等) + void OnLoad(IServiceProvider services); + + /// 卸载:释放资源(随后框架会卸载其 AssemblyLoadContext) + void OnUnload(); +} + +/// +/// 服务器插件(合并 v2 的 WebAPIPlugin 与 GameModuleServer) +/// - HTTP:通过 注册动态端点(挂载在 /plugin/{name}/ 下,支持热卸载) +/// - WebSocket:通过 注册消息处理器 +/// - 对局:实现 作为游戏模式参与对局逻辑 +/// +public interface IServerPlugin : IPluginBase +{ + /// 注册 HTTP 端点与 WebSocket 消息处理器 + void ConfigureEndpoints(IPluginHttpHandlerRegistry http, IMessageHandlerRegistry messages); + + /// + /// 对局消息处理(游戏模式插件实现) + /// 当宿主为对局选择此插件为模式时,局内客户端消息会转发到这里; + /// 返回 null 表示插件不处理该消息。 + /// + Task?> HandleGamingMessage(IGameSession session, string type, Dictionary data); +} + +/// +/// 实体模组(角色/技能/物品):DLL 热重载通道的加载项接口 +/// 与实体 JSON 配置(EntityModuleConfig)通道平行;实体以工厂注册方式保持模块化 +/// +public interface IEntityModule : IPluginBase where T : BaseEntity +{ + /// 模组提供的实体集合(key 为实体唯一名,供宿主/工厂使用) + IReadOnlyDictionary Entities { get; } +} + +/// 角色模组 +public interface ICharacterModule : IEntityModule; + +/// 技能模组 +public interface ISkillModule : IEntityModule; + +/// 物品模组 +public interface IItemModule : IEntityModule; diff --git a/src/FunGame.Server.Contracts/Plugins/PluginRegistries.cs b/src/FunGame.Server.Contracts/Plugins/PluginRegistries.cs new file mode 100644 index 0000000..0370bef --- /dev/null +++ b/src/FunGame.Server.Contracts/Plugins/PluginRegistries.cs @@ -0,0 +1,32 @@ +using FunGame.Server.Contracts.Networking; +using FunGame.Server.Contracts.Payloads; +using Microsoft.AspNetCore.Http; + +namespace FunGame.Server.Contracts.Plugins; + +/// WebSocket 消息处理器 +public delegate Task MessageHandler(IClientSession client, MessageEnvelope message); + +/// +/// WebSocket 消息处理器注册表(插件热卸载时按 owner 移除全部注册) +/// +public interface IMessageHandlerRegistry +{ + void Register(string messageType, object owner, MessageHandler handler); + void UnregisterAll(object owner); +} + +/// 插件 HTTP 端点处理器(直接操作 HttpContext,实现完全自定义) +public delegate Task PluginHttpHandler(HttpContext context); + +/// +/// 插件 HTTP 端点注册表(挂载在 /plugin/{name}/{path} 下) +/// 采用注册表 + 单一路由分发,保证端点可热添加/热移除 +/// +public interface IPluginHttpHandlerRegistry +{ + /// HTTP 方法(GET/POST/...,大小写不敏感) + /// 相对插件的路径(如 "hello"),匹配 /plugin/{name}/hello + void Register(string method, string path, object owner, PluginHttpHandler handler); + void UnregisterAll(object owner); +} diff --git a/src/FunGame.Server.Host/Auth/AuthService.cs b/src/FunGame.Server.Host/Auth/AuthService.cs new file mode 100644 index 0000000..4cc21ac --- /dev/null +++ b/src/FunGame.Server.Host/Auth/AuthService.cs @@ -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; + +/// 认证结果 +public record AuthResult(bool Success, string? Message = null, long? UserId = null, string? AccessToken = null, string? RefreshToken = null); + +/// +/// 认证服务:注册 / 登录 / 刷新 / 登出 +/// - 密码 PBKDF2(PasswordHasher) +/// - 刷新令牌散列入库、支持撤销与设备维度 +/// - 多端统一:WebUI / WebAPI / WebSocket 均通过本服务登录 +/// +public class AuthService( + AppDbContext db, + JwtService jwtService, + PasswordHasher passwordHasher, + IConfiguration configuration, + ILogger logger) +{ + private readonly int _refreshTokenDays = int.TryParse(configuration["Jwt:RefreshTokenDays"], out int days) ? days : 14; + + /// 注册 + public async Task 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); + } + + /// 登录 + public async Task 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 LoginCoreAsync(User user, string ipAddress, string userAgent, string device, string endpoint) + { + (IReadOnlyCollection roles, IReadOnlyCollection 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); + } + + /// 刷新令牌(旋转:旧令牌立即撤销) + public async Task 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 roles, IReadOnlyCollection 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); + } + + /// 登出(撤销刷新令牌) + public async Task 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; + } + + /// 用户角色与权限聚合 + public async Task<(IReadOnlyCollection Roles, IReadOnlyCollection Permissions)> GetRoleAndPermissionsAsync(long userId) + { + List roles = await db.UserRoles + .Where(ur => ur.UserId == userId) + .Select(ur => ur.Role!.Code) + .ToListAsync(); + + List roleIds = await db.UserRoles + .Where(ur => ur.UserId == userId) + .Select(ur => ur.RoleId) + .ToListAsync(); + + List permissions = await db.RolePermissions + .Where(rp => roleIds.Contains(rp.RoleId)) + .Select(rp => rp.Permission!.Code) + .Distinct() + .ToListAsync(); + + return (roles, permissions); + } + + /// 校验 API 令牌(外部服务接入,散列比对) + public async Task 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(); +} diff --git a/src/FunGame.Server.Host/Auth/JwtService.cs b/src/FunGame.Server.Host/Auth/JwtService.cs new file mode 100644 index 0000000..5cf7a13 --- /dev/null +++ b/src/FunGame.Server.Host/Auth/JwtService.cs @@ -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; + +/// +/// JWT 服务:多端统一验证的基础(WebUI / WebAPI / WebSocket 共用同一套签发与校验) +/// +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) + }; + + /// + /// 签发 AccessToken(claims:sub=用户Id、name=用户名、role=角色、perm=权限点、jti=令牌Id) + /// + public string CreateAccessToken(long userId, string username, IEnumerable roles, IEnumerable permissions, string? jti = null) + { + jti ??= Guid.NewGuid().ToString("N"); + List 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); + } + + /// 校验 AccessToken,返回主体(无效返回 null) + public ClaimsPrincipal? Validate(string token) + { + try + { + return new JwtSecurityTokenHandler().ValidateToken(token, TokenValidationParameters, out _); + } + catch + { + return null; + } + } + + /// 从主体读取用户 Id + public static long? GetUserId(ClaimsPrincipal principal) + { + string? value = principal.FindFirstValue(ClaimTypes.NameIdentifier); + return long.TryParse(value, out long id) ? id : null; + } + + /// 从主体读取权限点集合 + public static IReadOnlyCollection GetPermissions(ClaimsPrincipal principal) + => principal.FindAll("perm").Select(c => c.Value).ToHashSet(); +} diff --git a/src/FunGame.Server.Host/Auth/PermissionFilter.cs b/src/FunGame.Server.Host/Auth/PermissionFilter.cs new file mode 100644 index 0000000..e5cd6b9 --- /dev/null +++ b/src/FunGame.Server.Host/Auth/PermissionFilter.cs @@ -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; + +/// +/// 权限校验特性:标注在控制器或动作上,多个标注为 AND 关系 +/// +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)] +public class PermissionAttribute(string code) : Attribute +{ + public string Code { get; } = code; +} + +/// +/// 权限过滤器:校验 JWT 中的 perm Claim(配合 [Permission("code")]) +/// +public class PermissionFilter : IAsyncAuthorizationFilter +{ + public Task OnAuthorizationAsync(AuthorizationFilterContext context) + { + // [AllowAnonymous] 端点直接放行(登录/注册等) + if (context.ActionDescriptor.EndpointMetadata.OfType().Any()) + { + return Task.CompletedTask; + } + + if (context.HttpContext.User.Identity?.IsAuthenticated != true) + { + context.Result = new UnauthorizedResult(); + return Task.CompletedTask; + } + + string[] required = context.ActionDescriptor.EndpointMetadata + .OfType() + .Select(a => a.Code) + .Distinct() + .ToArray(); + + if (required.Length > 0) + { + HashSet 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; + } +} diff --git a/src/FunGame.Server.Host/Controllers/AdminControllers.cs b/src/FunGame.Server.Host/Controllers/AdminControllers.cs new file mode 100644 index 0000000..f3ae809 --- /dev/null +++ b/src/FunGame.Server.Host/Controllers/AdminControllers.cs @@ -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; + +/// +/// 插件与模组管理(始终热重载) +/// +[Route("api/admin/plugins")] +[Permission(PermissionCodes.PluginsManage)] +public class PluginController(PluginManager pluginManager) : ControllerBase +{ + /// GET /api/admin/plugins + [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)); + } + + /// POST /api/admin/plugins/{name}/reload + [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)); + } + } + + /// POST /api/admin/plugins/{name}/unload + [HttpPost("{name}/unload")] + public IActionResult Unload(string name) + { + try + { + pluginManager.Unload(name); + return Ok(ApiResponse.Success(null, $"加载项 {name} 已卸载。")); + } + catch (Exception e) + { + return Conflict(ApiResponse.Fail(409, e.Message)); + } + } + + /// POST /api/admin/plugins/reload-all + [HttpPost("reload-all")] + public IActionResult ReloadAll() + { + pluginManager.ReloadAll(); + return Ok(ApiResponse.Success(null, "已触发全部加载项热重载。")); + } +} + +/// +/// 服务器管理(仪表盘数据:会话/对局/概览) +/// +[Route("api/admin/server")] +[Permission(PermissionCodes.UsersRead)] +public class ServerController( + SessionManager sessions, + GameHostService gameHost, + FunGame.Server.Infrastructure.Data.AppDbContext db) : ControllerBase +{ + /// GET /api/admin/server/overview + [HttpGet("overview")] + public async Task 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 + })); + } + + /// GET /api/admin/server/sessions + [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)); + } + + /// POST /api/admin/server/sessions/{sessionId}/kick + [HttpPost("sessions/{sessionId:long}/kick")] + [Permission(PermissionCodes.UsersWrite)] + public async Task 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 { ["reason"] = "已被管理员踢出。" })); + await session.CloseAsync("kicked by admin"); + return Ok(ApiResponse.Success(null, "已踢出会话。")); + } + + /// GET /api/admin/server/games + [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)); + } + + /// POST /api/admin/server/games/{id}/end + [HttpPost("games/{id:guid}/end")] + [Permission(PermissionCodes.GamesManage)] + public async Task EndGame(Guid id) + { + bool result = await gameHost.EndGameAsync(id, aborted: true); + return result + ? Ok(ApiResponse.Success(null, "对局已强制结束。")) + : NotFound(ApiResponse.Fail(404, $"对局 {id} 不存在。")); + } + + /// POST /api/admin/server/games/{id}/pause —— 暂停对局(下一回合边界挂起) + [HttpPost("games/{id:guid}/pause")] + [Permission(PermissionCodes.GamesManage)] + public IActionResult PauseGame(Guid id) + { + bool result = gameHost.PauseGame(id); + return result + ? Ok(ApiResponse.Success(null, "对局已暂停。")) + : NotFound(ApiResponse.Fail(404, $"对局 {id} 不存在或已结束。")); + } + + /// POST /api/admin/server/games/{id}/resume —— 恢复对局 + [HttpPost("games/{id:guid}/resume")] + [Permission(PermissionCodes.GamesManage)] + public IActionResult ResumeGame(Guid id) + { + bool result = gameHost.ResumeGame(id); + return result + ? Ok(ApiResponse.Success(null, "对局已恢复。")) + : NotFound(ApiResponse.Fail(404, $"对局 {id} 不存在。")); + } +} diff --git a/src/FunGame.Server.Host/Controllers/AuthController.cs b/src/FunGame.Server.Host/Controllers/AuthController.cs new file mode 100644 index 0000000..db7bafa --- /dev/null +++ b/src/FunGame.Server.Host/Controllers/AuthController.cs @@ -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); + +/// +/// 认证端点(多端统一验证:WebUI / WebAPI / WebSocket 客户端均使用) +/// +[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(); + + /// POST /api/auth/register + [HttpPost("register")] + [AllowAnonymous] + public async Task 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))); + } + + /// POST /api/auth/login + [HttpPost("login")] + [AllowAnonymous] + public async Task 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))); + } + + /// POST /api/auth/refresh + [HttpPost("refresh")] + [AllowAnonymous] + public async Task 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))); + } + + /// POST /api/auth/logout + [HttpPost("logout")] + [Authorize] + public async Task 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(null, "已登出。")); + } + + /// GET /api/auth/me + [HttpGet("me")] + [Authorize] + public async Task Me() + { + long userId = JwtService.GetUserId(User) ?? 0; + if (userId == 0) + { + return Unauthorized(ApiResponse.Fail(401, "未登录。")); + } + (IReadOnlyCollection roles, IReadOnlyCollection permissions) = await authService.GetRoleAndPermissionsAsync(userId); + return Ok(ApiResponse.Success(new + { + UserId = userId, + Username = User.Identity?.Name, + Roles = roles, + Permissions = permissions + })); + } + + private async Task BuildTokenResponse(AuthResult result) + { + string username = ""; + string[] permissions = []; + string[] roles = []; + if (result.UserId is long userId) + { + (IReadOnlyCollection roleList, IReadOnlyCollection permList) = await authService.GetRoleAndPermissionsAsync(userId); + roles = [.. roleList]; + permissions = [.. permList]; + username = HttpContext.RequestServices.GetRequiredService() + .Users.Where(u => u.Id == userId).Select(u => u.Username).FirstOrDefault() ?? ""; + } + return new AuthTokenResponse( + result.AccessToken ?? "", + result.RefreshToken ?? "", + result.UserId ?? 0, + username, + permissions, + roles); + } +} diff --git a/src/FunGame.Server.Host/Controllers/CrudControllerBase.cs b/src/FunGame.Server.Host/Controllers/CrudControllerBase.cs new file mode 100644 index 0000000..6c91d8e --- /dev/null +++ b/src/FunGame.Server.Host/Controllers/CrudControllerBase.cs @@ -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; + +/// +/// 通用 CRUD 控制器基类(每张数据表派生一个控制器即可获得完整 CRUD 接口) +/// 约定:GET 列表(分页/排序)、GET 详情、POST 创建、PUT 更新、DELETE 删除 +/// +[ApiController] +public abstract class CrudControllerBase : ControllerBase where TEntity : class +{ + protected AppDbContext Db => HttpContext.RequestServices.GetRequiredService(); + + private DbSet Set => Db.Set(); + + /// 派生类可覆写:默认排序属性 + protected virtual string DefaultSort => "Id"; + + /// 派生类可覆写:查询前置过滤(如软删除、权限过滤) + protected virtual IQueryable ApplyQueryFilters(IQueryable query) => query; + + // ===== 查询 ===== + + /// GET /api/{resource}?page=1&pageSize=20&sort=Id&desc=false + [HttpGet] + public virtual async Task 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 query = ApplyQueryFilters(Set.AsNoTracking()); + long total = await query.LongCountAsync(); + + query = ApplySort(query, sort ?? DefaultSort, desc); + List items = await query.Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(); + + return Ok(ApiResponse.Success(new PagedData + { + Page = page, + PageSize = pageSize, + Total = total, + Items = items + })); + } + + /// GET /api/{resource}/{id} + [HttpGet("{id}")] + public virtual async Task 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)); + } + + // ===== 写入 ===== + + /// POST /api/{resource} + [HttpPost] + public virtual async Task Create([FromBody] TEntity entity) + { + if (entity == null) + { + return BadRequest(ApiResponse.Fail(400, "请求体不能为空。")); + } + Set.Add(entity); + await Db.SaveChangesAsync(); + return Ok(ApiResponse.Success(entity, "创建成功。")); + } + + /// PUT /api/{resource}/{id} + [HttpPut("{id}")] + public virtual async Task 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, "更新成功。")); + } + + /// DELETE /api/{resource}/{id} + [HttpDelete("{id}")] + public virtual async Task 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(null, "删除成功。")); + } + + // ===== 辅助 ===== + + private static IQueryable ApplySort(IQueryable 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)generic.Invoke(null, [query, lambda])!; + } +} diff --git a/src/FunGame.Server.Host/Controllers/EconomyControllers.cs b/src/FunGame.Server.Host/Controllers/EconomyControllers.cs new file mode 100644 index 0000000..710046d --- /dev/null +++ b/src/FunGame.Server.Host/Controllers/EconomyControllers.cs @@ -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; + +/// 商店 CRUD +[Route("api/stores")] +[Permission(PermissionCodes.ConfigManage)] +public class StoresController : CrudControllerBase; + +/// 商品 CRUD +[Route("api/goods")] +[Permission(PermissionCodes.ConfigManage)] +public class GoodsController : CrudControllerBase; + +/// 商品价格 CRUD +[Route("api/goodsprices")] +[Permission(PermissionCodes.ConfigManage)] +public class GoodsPricesController : CrudControllerBase; + +/// 商店-商品关联 CRUD(复合主键连接表) +[Route("api/storegoods")] +[Permission(PermissionCodes.ConfigManage)] +public class StoreGoodsController : ControllerBase +{ + private FunGame.Server.Infrastructure.Data.AppDbContext Db => HttpContext.RequestServices.GetRequiredService(); + + /// GET /api/storegoods + [HttpGet] + public async Task List() => Ok(ApiResponse.Success(await Db.StoreGoods.AsNoTracking().ToListAsync())); + + /// GET /api/storegoods/{storeId}/{goodsId} + [HttpGet("{storeId:long}/{goodsId:long}")] + public async Task Get(long storeId, long goodsId) + { + StoreGoods? item = await Db.StoreGoods.FindAsync([storeId, goodsId]); + return item == null ? NotFound(ApiResponse.Fail(404, "关联不存在。")) : Ok(ApiResponse.Success(item)); + } + + /// POST /api/storegoods + [HttpPost] + public async Task 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, "创建成功。")); + } + + /// PUT /api/storegoods/{storeId}/{goodsId} + [HttpPut("{storeId:long}/{goodsId:long}")] + public async Task 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, "更新成功。")); + } + + /// DELETE /api/storegoods/{storeId}/{goodsId} + [HttpDelete("{storeId:long}/{goodsId:long}")] + public async Task 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(null, "删除成功。")); + } +} + +/// 市场寄售 CRUD +[Route("api/marketitems")] +[Permission(PermissionCodes.ConfigManage)] +public class MarketItemsController : CrudControllerBase; + +/// 交易报价 CRUD +[Route("api/offers")] +[Permission(PermissionCodes.ConfigManage)] +public class OffersController : CrudControllerBase; + +/// 报价条目 CRUD +[Route("api/offeritems")] +[Permission(PermissionCodes.ConfigManage)] +public class OfferItemsController : CrudControllerBase; diff --git a/src/FunGame.Server.Host/Controllers/GameControllers.cs b/src/FunGame.Server.Host/Controllers/GameControllers.cs new file mode 100644 index 0000000..08bbbb7 --- /dev/null +++ b/src/FunGame.Server.Host/Controllers/GameControllers.cs @@ -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; + +/// 房间 CRUD +[Route("api/rooms")] +[Permission(PermissionCodes.UsersRead)] +public class RoomsController : CrudControllerBase +{ + protected override string DefaultSort => "CreatedAt"; +} + +/// 玩家角色库 CRUD +[Route("api/usercharacters")] +[Permission(PermissionCodes.UsersRead)] +public class UserCharactersController : CrudControllerBase; + +/// 玩家物品 CRUD +[Route("api/useritems")] +[Permission(PermissionCodes.UsersRead)] +public class UserItemsController : CrudControllerBase; + +/// 库存 CRUD +[Route("api/inventories")] +[Permission(PermissionCodes.UsersRead)] +public class InventoriesController : CrudControllerBase; + +/// 对局记录 CRUD(回放索引) +[Route("api/gamerecords")] +[Permission(PermissionCodes.LogsRead)] +public class GameRecordsController : CrudControllerBase +{ + protected override string DefaultSort => "StartedAt"; +} + +/// 回合记录 CRUD +[Route("api/roundrecords")] +[Permission(PermissionCodes.LogsRead)] +public class RoundRecordsController : CrudControllerBase +{ + protected override string DefaultSort => "Round"; +} diff --git a/src/FunGame.Server.Host/Controllers/GameModulesController.cs b/src/FunGame.Server.Host/Controllers/GameModulesController.cs new file mode 100644 index 0000000..a5bae0a --- /dev/null +++ b/src/FunGame.Server.Host/Controllers/GameModulesController.cs @@ -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; + +/// +/// 模组 / 游戏模式目录:供客户端(测试客户端、未来游戏客户端)创建房间时自选模组 +/// 公开接口,无需登录;数据来自 PluginManager 实时加载项(随热重载自动更新) +/// +[ApiController] +[Route("api/game-modules")] +public class GameModulesController(PluginManager plugins) : ControllerBase +{ + /// GET /api/game-modules —— 可用游戏模式(ServerPlugin)与内容模组(实体模组)列表 + [HttpGet] + [AllowAnonymous] + public IActionResult List() + { + List 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); diff --git a/src/FunGame.Server.Host/Controllers/ReplayController.cs b/src/FunGame.Server.Host/Controllers/ReplayController.cs new file mode 100644 index 0000000..dafbeb3 --- /dev/null +++ b/src/FunGame.Server.Host/Controllers/ReplayController.cs @@ -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; + +/// +/// 回放中心:对局记录、回合摘要、单回合详情、最终统计 +/// 数据来源:GameRoundRecordSink 归档(records/*.zip)+ game_records / round_records 表 +/// +[Route("api/games")] +[Permission(PermissionCodes.LogsRead)] +public class ReplayController(ReplayArchiveService replay) : ControllerBase +{ + /// GET /api/games/{id}/meta —— 对局元信息(含全角色清单与队伍) + [HttpGet("{id:guid}/meta")] + public async Task Meta(Guid id) + { + GameRecord? record = await replay.GetGameRecordAsync(id); + if (record == null) + { + return NotFound(ApiResponse.Fail(404, $"对局 {id} 不存在。")); + } + Dictionary? 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 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() + })); + } + + /// GET /api/games/{id}/rounds/summary?from=&to= —— 回合摘要列表(供时间轴) + [HttpGet("{id:guid}/rounds/summary")] + public async Task 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? 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 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)); + } + + /// GET /api/games/{id}/rounds/{n} —— 单回合完整数据(与归档一致的 JSON) + [HttpGet("{id:guid}/rounds/{n:int}")] + public async Task Round(Guid id, int n) + { + GameRecord? record = await replay.GetGameRecordAsync(id); + if (record == null) + { + return NotFound(ApiResponse.Fail(404, $"对局 {id} 不存在。")); + } + Dictionary? 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); + } + + /// GET /api/games/{id}/statistics —— 最终统计(Rating 排行 + 队伍结果) + [HttpGet("{id:guid}/statistics")] + public async Task Statistics(Guid id) + { + GameRecord? record = await replay.GetGameRecordAsync(id); + if (record == null) + { + return NotFound(ApiResponse.Fail(404, $"对局 {id} 不存在。")); + } + Dictionary? 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? statsByGuid = replay.ReadStatistics(record); + Dictionary teamMap = last.TeamMap ?? []; + Dictionary charactersByGuid = rounds.Values + .SelectMany(r => r.AllCharacters) + .GroupBy(c => c.Guid) + .ToDictionary(g => g.Key, g => g.First()); + + List 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); +} diff --git a/src/FunGame.Server.Host/Controllers/SystemControllers.cs b/src/FunGame.Server.Host/Controllers/SystemControllers.cs new file mode 100644 index 0000000..30686ad --- /dev/null +++ b/src/FunGame.Server.Host/Controllers/SystemControllers.cs @@ -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; + +/// 服务器日志 CRUD +[Route("api/serverlogs")] +[Permission(PermissionCodes.LogsRead)] +public class ServerLogsController : CrudControllerBase +{ + protected override string DefaultSort => "CreatedAt"; +} + +/// 系统配置 CRUD(Key 为主键) +[Route("api/systemconfigs")] +[Permission(PermissionCodes.ConfigManage)] +public class SystemConfigsController : CrudControllerBase +{ + protected override string DefaultSort => "Key"; +} + +/// 验证码 CRUD +[Route("api/verifycodes")] +[Permission(PermissionCodes.UsersWrite)] +public class VerifyCodesController : CrudControllerBase; + +/// 每日签到 CRUD +[Route("api/usersignins")] +[Permission(PermissionCodes.UsersRead)] +public class UserSignInsController : CrudControllerBase; + +/// +/// API 令牌管理(创建时生成原始令牌仅返回一次,散列入库) +/// +[Route("api/apitokens")] +[Permission(PermissionCodes.TokensManage)] +public class ApiTokensController : CrudControllerBase +{ + public override async Task 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 }, "创建成功,原始令牌仅显示一次,请妥善保管。")); + } +} diff --git a/src/FunGame.Server.Host/Controllers/UserCenterControllers.cs b/src/FunGame.Server.Host/Controllers/UserCenterControllers.cs new file mode 100644 index 0000000..1e1e161 --- /dev/null +++ b/src/FunGame.Server.Host/Controllers/UserCenterControllers.cs @@ -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; + +/// +/// 用户管理(CRUD + 角色分配 + 会话管理) +/// +[Route("api/users")] +[Permission(PermissionCodes.UsersRead)] +public class UsersController : CrudControllerBase +{ + private readonly PasswordHasher _hasher = new(); + + public override async Task 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 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 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(null, "删除成功。")); + } + + /// GET /api/users/{id}/roles + [HttpGet("{id:long}/roles")] + public async Task GetRoles(long id) + { + List roles = await Db.UserRoles.Where(ur => ur.UserId == id).Select(ur => ur.Role!).ToListAsync(); + return Ok(ApiResponse.Success(roles)); + } + + /// PUT /api/users/{id}/roles(body: 角色 Id 数组) + [HttpPut("{id:long}/roles")] + [Permission(PermissionCodes.UsersWrite)] + public async Task 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(null, "角色已更新。")); + } + + /// GET /api/users/{id}/sessions + [HttpGet("{id:long}/sessions")] + public async Task GetSessions(long id) + { + List sessions = await Db.UserSessions.Where(s => s.UserId == id).OrderByDescending(s => s.ConnectedAt).ToListAsync(); + return Ok(ApiResponse.Success(sessions)); + } +} + +/// 用户资料 CRUD +[Route("api/userprofiles")] +[Permission(PermissionCodes.UsersRead)] +public class UserProfilesController : CrudControllerBase; + +/// 用户会话 CRUD +[Route("api/usersessions")] +[Permission(PermissionCodes.UsersRead)] +public class UserSessionsController : CrudControllerBase; + +/// 登录日志 CRUD +[Route("api/loginlogs")] +[Permission(PermissionCodes.LogsRead)] +public class LoginLogsController : CrudControllerBase; + +/// 刷新令牌 CRUD +[Route("api/refreshtokens")] +[Permission(PermissionCodes.UsersWrite)] +public class RefreshTokensController : CrudControllerBase; + +/// 角色管理(CRUD + 权限分配) +[Route("api/roles")] +[Permission(PermissionCodes.RolesManage)] +public class RolesController : CrudControllerBase +{ + public override async Task 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(null, "删除成功。")); + } + + /// GET /api/roles/{id}/permissions + [HttpGet("{id:long}/permissions")] + public async Task GetPermissions(long id) + { + List permissions = await Db.RolePermissions.Where(rp => rp.RoleId == id).Select(rp => rp.Permission!).ToListAsync(); + return Ok(ApiResponse.Success(permissions)); + } + + /// PUT /api/roles/{id}/permissions(body: 权限点 Code 数组) + [HttpPut("{id:long}/permissions")] + public async Task SetPermissions(long id, [FromBody] string[] permissionCodes) + { + if (!await Db.Roles.AnyAsync(r => r.Id == id)) + { + return NotFound(ApiResponse.Fail(404, $"角色 {id} 不存在。")); + } + List 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(null, "权限已更新。")); + } +} + +/// 权限点管理(CRUD) +[Route("api/permissions")] +[Permission(PermissionCodes.PermissionsManage)] +public class PermissionsController : CrudControllerBase; diff --git a/src/FunGame.Server.Host/FunGame.Server.Host.csproj b/src/FunGame.Server.Host/FunGame.Server.Host.csproj new file mode 100644 index 0000000..2bfc4e6 --- /dev/null +++ b/src/FunGame.Server.Host/FunGame.Server.Host.csproj @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + net10.0 + enable + enable + + + diff --git a/src/FunGame.Server.Host/JsonHub.cs b/src/FunGame.Server.Host/JsonHub.cs new file mode 100644 index 0000000..ffa0da6 --- /dev/null +++ b/src/FunGame.Server.Host/JsonHub.cs @@ -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; + +/// +/// 宿主 JSON 中心:复用 Core v3 的 JsonService 转换器(实体/回合记录均可直接序列化) +/// +public static class JsonHub +{ + /// WebSocket 与 REST 负载序列化选项(紧凑、保留 Core 转换器) + public static JsonSerializerOptions Options { get; } = new(JsonService.GeneralOptions) + { + WriteIndented = false, + PropertyNameCaseInsensitive = true + }; + + public static string Serialize(T value) => JsonSerializer.Serialize(value, Options); + + public static T? Deserialize(string json) => JsonSerializer.Deserialize(json, Options); + + public static byte[] SerializeToUtf8Bytes(T value) => JsonSerializer.SerializeToUtf8Bytes(value, Options); + + /// 把 Core 转换器与循环引用策略应用到指定选项(MVC / Minimal API 配置) + 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); + } + } + + /// 从信封数据字典中取参数 + public static T? Get(MessageEnvelope message, string key) + => message.Data.TryGetValue(key, out object? value) && value is JsonElement element + ? element.Deserialize(Options) + : value is T typed ? typed : default; + + public static string? GetString(MessageEnvelope message, string key) => Get(message, key); +} diff --git a/src/FunGame.Server.Host/Logging/ServerLogsLoggerProvider.cs b/src/FunGame.Server.Host/Logging/ServerLogsLoggerProvider.cs new file mode 100644 index 0000000..2f98ed3 --- /dev/null +++ b/src/FunGame.Server.Host/Logging/ServerLogsLoggerProvider.cs @@ -0,0 +1,105 @@ +using FunGame.Server.Infrastructure.Data; +using FunGame.Server.Infrastructure.Entities.System; + +namespace FunGame.Server.Host.Logging; + +/// +/// 服务器日志通道:把 ILogger 输出(Information 及以上)写入 server_logs 表,供 WebUI 查看 +/// 宿主构建完成后通过 绑定真正的 IServiceScopeFactory(延迟绑定避免重复容器) +/// +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 state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Information; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func 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(); + 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"; + } +} diff --git a/src/FunGame.Server.Host/Networking/BuiltInMessageHandlers.cs b/src/FunGame.Server.Host/Networking/BuiltInMessageHandlers.cs new file mode 100644 index 0000000..6afab4b --- /dev/null +++ b/src/FunGame.Server.Host/Networking/BuiltInMessageHandlers.cs @@ -0,0 +1,39 @@ +using FunGame.Server.Contracts.Networking; +using FunGame.Server.Contracts.Payloads; + +namespace FunGame.Server.Host.Networking; + +/// +/// 宿主内置 WebSocket 消息处理器(system.ping / system.info / auth.logout) +/// +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 { ["time"] = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }); + }); + + dispatcher.Register(MessageTypes.ServerInfo, Owner, async (client, message) => + { + return MessageEnvelope.Reply(message, new Dictionary + { + ["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 { ["message"] = "已登出,请关闭连接。" }); + }); + } +} diff --git a/src/FunGame.Server.Host/Networking/ClientSession.cs b/src/FunGame.Server.Host/Networking/ClientSession.cs new file mode 100644 index 0000000..953eaf3 --- /dev/null +++ b/src/FunGame.Server.Host/Networking/ClientSession.cs @@ -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; + +/// +/// WebSocket 客户端会话(替代 v2 的 ServerModel<T>) +/// +public sealed class ClientSession : IClientSession, IAsyncDisposable +{ + private static long _sessionCounter; + private readonly WebSocket _socket; + private readonly SemaphoreSlim _sendLock = new(1, 1); + private readonly ILogger _logger; + private bool _closed; + + public ClientSession(WebSocket socket, ClaimsPrincipal? principal, string remoteAddress, ILogger 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 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; + + /// 是否已通过 WS 登录(连接时仅凭 JWT 判定;匿名连接可通过 auth.login 消息登录后由宿主提升会话) + public bool WebSocketAuthenticated { get; set; } + + public async Task 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); + } + } + + /// 接收一条完整消息(返回 null 表示连接关闭) + public async Task 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(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; + } +} diff --git a/src/FunGame.Server.Host/Networking/MessageDispatcher.cs b/src/FunGame.Server.Host/Networking/MessageDispatcher.cs new file mode 100644 index 0000000..19f1db9 --- /dev/null +++ b/src/FunGame.Server.Host/Networking/MessageDispatcher.cs @@ -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; + +/// +/// 消息分发中心:WebSocket 消息处理器注册表 + 插件 HTTP 端点注册表 +/// - 内置处理器与插件处理器合并,后者随插件热卸载自动移除 +/// - 插件 HTTP 端点统一挂载在 /plugin/{name}/{path},由单一路由分发(支持热添加/移除) +/// +public class MessageDispatcher : IMessageHandlerRegistry, IPluginHttpHandlerRegistry +{ + private readonly ConcurrentDictionary _messageHandlers = new(StringComparer.OrdinalIgnoreCase); + private readonly ConcurrentDictionary<(string Method, string Plugin, string Path), (object Owner, PluginHttpHandler Handler)> _httpHandlers = new(); + private readonly ILogger _logger; + + public MessageDispatcher(ILogger 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 _); + } + } + } + + /// 分发 WS 消息(无处理器返回 null) + public async Task 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 _); + } + } + } + + /// 分发插件 HTTP 请求(/plugin/{plugin}/{**path}) + public async Task 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(); +} diff --git a/src/FunGame.Server.Host/Networking/RoomMessageHandlers.cs b/src/FunGame.Server.Host/Networking/RoomMessageHandlers.cs new file mode 100644 index 0000000..4c893dc --- /dev/null +++ b/src/FunGame.Server.Host/Networking/RoomMessageHandlers.cs @@ -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; + +/// +/// 房间 / 匹配 / 聊天 的 WebSocket 业务处理器(新负载模型 MessageEnvelope) +/// +public static class RoomMessageHandlers +{ + public static readonly object Owner = new(); + + public static void Register(MessageDispatcher dispatcher, IServiceProvider services) + { + SessionManager sessions = services.GetRequiredService(); + RoomService rooms = services.GetRequiredService(); + GameHostService games = services.GetRequiredService(); + EntityCatalog catalog = services.GetRequiredService(); + CharacterBuildService builder = services.GetRequiredService(); + PluginManager plugins = services.GetRequiredService(); + ILogger logger = services.GetRequiredService().CreateLogger("RoomHandlers"); + + // ===== 房间列表 ===== + dispatcher.Register(MessageTypes.RoomList, Owner, async (client, message) => + { + List list = await rooms.ListRoomsAsync(); + Dictionary 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(message, "maxUsers"); + bool isRank = JsonHub.Get(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 { ["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 { ["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 { ["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 + { + ["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 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 characters = []; + List 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 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 + { + ["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 { ["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(message, "count"), 2, 10); + // 参考 FunGameSimulation:随机角色 + 完整技能装配(专属被动/大招、战技、通用被动/大招);内容模组指定时只从该模组族取 + List 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 + { + ["gameId"] = game.Id, + ["mode"] = mode, + ["contentModule"] = contentModule, + ["characters"] = count + }); + }); + + // ===== 取消匹配(当前快速匹配立即成局,无需取消) ===== + dispatcher.Register(MessageTypes.MatchCancel, Owner, async (client, message) => + { + return MessageEnvelope.Reply(message, new Dictionary { ["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(action, true, out GamingType type)) + { + return MessageEnvelope.Reply(message, ok: false, error: new MessageError { Code = "unknown_action", Message = $"未知的局内动作:{action}" }); + } + Dictionary? 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 + { + ["roomId"] = roomId, + ["type"] = type, + ["user"] = client.Username ?? "匿名", + ["members"] = rooms.GetMembers(roomId).Count + }); + foreach (ClientSession member in rooms.GetMembers(roomId)) + { + await member.SendAsync(roomEvent); + } + } +} diff --git a/src/FunGame.Server.Host/Networking/SessionManager.cs b/src/FunGame.Server.Host/Networking/SessionManager.cs new file mode 100644 index 0000000..82f8cbc --- /dev/null +++ b/src/FunGame.Server.Host/Networking/SessionManager.cs @@ -0,0 +1,69 @@ +using System.Collections.Concurrent; +using FunGame.Server.Contracts.Payloads; + +namespace FunGame.Server.Host.Networking; + +/// +/// WebSocket 会话管理器(在线连接 / 按用户分组 / 广播) +/// +public class SessionManager +{ + private readonly ConcurrentDictionary _sessions = new(); + private readonly ILogger _logger; + + public SessionManager(ILogger logger) + { + _logger = logger; + } + + public IEnumerable Sessions => _sessions.Values.ToArray(); + + public int Count => _sessions.Count; + + public ClientSession? Get(long sessionId) => _sessions.TryGetValue(sessionId, out ClientSession? session) ? session : null; + + public IReadOnlyCollection 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); + } + } + + /// 广播给所有会话 + public async Task BroadcastAsync(MessageEnvelope message, CancellationToken cancellationToken = default) + { + foreach (ClientSession session in _sessions.Values) + { + await session.SendAsync(message, cancellationToken); + } + } + + /// 广播给指定用户(多端全部收到) + public async Task SendToUserAsync(long userId, MessageEnvelope message, CancellationToken cancellationToken = default) + { + foreach (ClientSession session in GetByUser(userId)) + { + await session.SendAsync(message, cancellationToken); + } + } + + /// 踢出某用户的全部连接 + public async Task KickUserAsync(long userId, string reason) + { + foreach (ClientSession session in GetByUser(userId)) + { + await session.SendAsync(MessageEnvelope.Broadcast(MessageTypes.Kick, new Dictionary { ["reason"] = reason })); + await session.CloseAsync(reason); + } + } +} diff --git a/src/FunGame.Server.Host/Networking/WebSocketEndpoints.cs b/src/FunGame.Server.Host/Networking/WebSocketEndpoints.cs new file mode 100644 index 0000000..70b4472 --- /dev/null +++ b/src/FunGame.Server.Host/Networking/WebSocketEndpoints.cs @@ -0,0 +1,110 @@ +using System.Security.Claims; +using FunGame.Server.Contracts.Payloads; +using Microsoft.Extensions.Primitives; + +namespace FunGame.Server.Host.Networking; + +/// +/// WebSocket 接入端点与连接循环 +/// 认证:/ws?access_token={jwt} 或 Authorization: Bearer 头(与 WebAPI/WebUI 同一 JWT,多端统一验证) +/// +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(); + 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(); + SessionManager sessions = context.RequestServices.GetRequiredService(); + Auth.JwtService jwtService = context.RequestServices.GetRequiredService(); + + // 提取 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()); + sessions.Add(session); + + try + { + if (session.IsAuthenticated) + { + await session.SendAsync(MessageEnvelope.Broadcast(MessageTypes.Notice, new Dictionary + { + ["message"] = $"欢迎回来,{session.Username}!" + })); + } + else + { + await session.SendAsync(MessageEnvelope.Reply(new MessageEnvelope { Type = MessageTypes.Notice }, new Dictionary + { + ["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(); + } + } +} diff --git a/src/FunGame.Server.Host/Program.cs b/src/FunGame.Server.Host/Program.cs new file mode 100644 index 0000000..ec77fbe --- /dev/null +++ b/src/FunGame.Server.Host/Program.cs @@ -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>(); +builder.Services.AddScoped(); +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(); +builder.Services.AddSingleton(sp => sp.GetRequiredService()); +builder.Services.AddSingleton(sp => sp.GetRequiredService()); +builder.Services.AddSingleton(); + +// ===== 插件系统(始终热重载) ===== +builder.Services.AddSingleton(); + +// ===== 对局宿主与回合记录外发 ===== +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +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(); +}).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() + ?? ["http://localhost:5173", "http://127.0.0.1:5173"]; + policy.WithOrigins(allowedOrigins).AllowAnyHeader().AllowAnyMethod().AllowCredentials(); + }); +}); + +WebApplication app = builder.Build(); + +// 绑定日志通道的真实作用域工厂(延迟绑定) +serverLogsProvider.Attach(app.Services.GetRequiredService()); + +// ===== 目录初始化 ===== +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(); + 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(), builder.Configuration); +RoomMessageHandlers.Register(app.Services.GetRequiredService(), 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(); + app.Logger.LogInformation("正在应用数据库迁移(Provider: {Provider})…", builder.Configuration["Database:Provider"] ?? "Sqlite"); + await db.Database.MigrateAsync(); + + DbSeedService seedService = scope.ServiceProvider.GetRequiredService(); + await seedService.SeedAsync(); +} + +PluginManager pluginManager = app.Services.GetRequiredService(); +pluginManager.LoadAll(); +if (builder.Configuration.GetValue("Plugins:Watch", true)) +{ + pluginManager.EnableFileWatcher(); +} + +app.Logger.LogInformation("{Name} 启动完成,开始监听 …", builder.Configuration["Server:Name"]); + +app.Run(); diff --git a/src/FunGame.Server.Host/Properties/launchSettings.json b/src/FunGame.Server.Host/Properties/launchSettings.json new file mode 100644 index 0000000..6e7e794 --- /dev/null +++ b/src/FunGame.Server.Host/Properties/launchSettings.json @@ -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" + } + } + } +} diff --git a/src/FunGame.Server.Host/Services/CharacterBuildService.cs b/src/FunGame.Server.Host/Services/CharacterBuildService.cs new file mode 100644 index 0000000..61e6e77 --- /dev/null +++ b/src/FunGame.Server.Host/Services/CharacterBuildService.cs @@ -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; + +/// +/// 角色构建服务:参考 Testing-v3 的 FunGameSimulation / FunGameService.AddCharacterSkills 生成对局角色 +/// 与模组解耦:技能通过 EntityCatalog(模组注册的技能实体)按 Name 匹配,随模组热重载自动生效 +/// +public class CharacterBuildService(EntityCatalog catalog, ILogger logger) +{ + /// 角色专属技能映射(角色 Id -> 专属被动, 专属大招),与 FunGameService.AddCharacterSkills 一致 + private static readonly Dictionary ExclusiveSkills = new() + { + [1] = ("META马", "熵灭极诣"), + [2] = ("心灵之弦", "千羽瞬华"), + [3] = ("蚀魂震击", "咒怨洪流"), + [4] = ("灵能反射", "三相灵枢"), + [5] = ("双生流转", "变幻之心"), + [6] = ("零式崩解", "零式灭杀"), + [7] = ("少女绮想", "绝对领域"), + [8] = ("暗香疏影", "残香凋零"), + [9] = ("破釜沉舟", "宿命时律"), + [10] = ("累积之压", "极寒渴望"), + [11] = ("银隼之赐", "身心一境"), + [12] = ("弱者猎手", "饕餮盛宴"), + [13] = ("开宫", "放监"), + [14] = ("八卦阵", "归元环"), + [15] = ("深海之戟", "海王星的野望"), + [16] = ("雇佣兵团", "全军出击"), + [17] = ("不息之流", "宿命之潮"), + [18] = ("概念之骰", "神之因果") + }; + + private IReadOnlyList _skills = []; + + private IReadOnlyList Skills => _skills.Count > 0 ? _skills : (_skills = catalog.GetSkills()); + + /// + /// 参考 FunGameSimulation 生成一局对局角色:随机角色 + 等级/普攻等级 + 专属被动与大招 + 随机战技/通用被动/通用大招 + /// 返回的角色副本已绑定技能,可直接传入 GamingQueue + /// + /// 角色数量(≤10) + /// 内容模组前缀(如 "oshima"):角色与技能只从该模组族产生;空/null 则使用全量模组 + /// 角色等级(默认 10,与 FunGameSimulation 一致) + /// 战技/大招等级(默认 2) + public List BuildSimulationCharacters(int count, string? modulePrefix = null, int level = 10, int skillLevel = 2) + { + List templates = [.. string.IsNullOrWhiteSpace(modulePrefix) ? catalog.GetCharacters() : catalog.GetCharacters(modulePrefix)]; + List 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; + } + + /// + /// 装配单个角色(参考 FunGameService.AddCharacterSkills + FunGameSimulation 的随机技能分配) + /// 复制模板 → 设等级/普攻等级 → 专属被动与大招 → 随机战技/通用被动/通用大招 + /// + /// 内容模组前缀:专属技能/战技/通用技能只从该模组族匹配;空/null 则全量 + 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 pool = string.IsNullOrWhiteSpace(modulePrefix) ? Skills : catalog.GetSkills(modulePrefix); + + // 专属技能名(随机池排除,避免重复/跨角色专属;与 FunGameSimulation 的"通用技能"语义一致) + HashSet 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 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; + } + + /// 向角色添加指定技能(按名称从技能池匹配,复制后绑定角色) + private void AddSkill(Character character, IReadOnlyList 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); + } + + /// 复制技能并绑定到角色 + private static void AddSkill(Character character, Skill skill, int level) + { + Skill copy = skill.Copy(); + copy.Character = character; + copy.Level = level; + character.Skills.Add(copy); + } + + /// 模组缺失时的基础角色兜底(与 EntityCatalog 一致) + 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; + } +} diff --git a/src/FunGame.Server.Host/Services/EntityCatalog.cs b/src/FunGame.Server.Host/Services/EntityCatalog.cs new file mode 100644 index 0000000..46a3c87 --- /dev/null +++ b/src/FunGame.Server.Host/Services/EntityCatalog.cs @@ -0,0 +1,63 @@ +using FunGame.Core.Entity; +using FunGame.Server.PluginHost; + +namespace FunGame.Server.Host.Services; + +/// +/// 实体目录:聚合全部已加载实体模组(角色/技能/物品)供业务层取用 +/// 随模组热重载自动反映最新内容(PluginManager 实时查询) +/// +public class EntityCatalog(PluginManager pluginManager) +{ + public IReadOnlyList GetCharacters() => pluginManager.GetModuleEntities().ToList(); + + public IReadOnlyList GetSkills() => pluginManager.GetModuleEntities().ToList(); + + public IReadOnlyList GetItems() => pluginManager.GetModuleEntities().ToList(); + + /// 按模组前缀获取角色(如 "oshima" → oshima.characters) + public IReadOnlyList GetCharacters(string modulePrefix) => pluginManager.GetModuleEntities(modulePrefix).ToList(); + + /// 按模组前缀获取技能(如 "oshima" → oshima.skills) + public IReadOnlyList GetSkills(string modulePrefix) => pluginManager.GetModuleEntities(modulePrefix).ToList(); + + /// 按模组前缀获取物品(如 "oshima" → oshima.items) + public IReadOnlyList GetItems(string modulePrefix) => pluginManager.GetModuleEntities(modulePrefix).ToList(); + + /// 随机取 n 个角色副本(不足时重复填充) + public List GetRandomCharacters(int count, int level = 5) + { + IReadOnlyList source = GetCharacters(); + List 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; + } +} diff --git a/src/FunGame.Server.Host/Services/GameHostService.cs b/src/FunGame.Server.Host/Services/GameHostService.cs new file mode 100644 index 0000000..15fb421 --- /dev/null +++ b/src/FunGame.Server.Host/Services/GameHostService.cs @@ -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; + +/// +/// 对局宿主:GamingQueue 生命周期管理、AI 对局循环、回合记录外发接线与 WS 实时推送 +/// +public class GameHostService +{ + private readonly ConcurrentDictionary _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 _logger; + + public GameHostService( + IServiceScopeFactory scopeFactory, + PluginManager plugins, + SessionManager sessions, + IConfiguration configuration, + ILoggerFactory loggerFactory, + ILogger logger) + { + _scopeFactory = scopeFactory; + _plugins = plugins; + _sessions = sessions; + _configuration = configuration; + _loggerFactory = loggerFactory; + _logger = logger; + } + + public IEnumerable Games => _games.Values; + + public HostedGame? GetGame(Guid id) => _games.TryGetValue(id, out HostedGame? game) ? game : null; + + /// + /// 创建对局:mode 为服务器插件名(游戏模式);characters 为参与者;map 可空 + /// 创建后立即启动 AI 对局循环(人类玩家的局内决策接入在后续里程碑接入) + /// + public HostedGame CreateGame(string mode, List 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()); + + // 混战队列(淘汰制,最多复活 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; + } + + /// + /// 创建对局(GameModule 路径):由游戏模式模组建房并返回队列 + /// 模组负责创建/装配 GamingQueue 与房间工作区,宿主负责回合记录外发、实时广播与对局循环 + /// + public async Task CreateGameFromModule(IGameModuleServer module, List 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()); + 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; + } + + /// 按客户端会话查找所在对局(用于 gaming.* 消息路由到该局 GameModule) + public HostedGame? GetGameOfClient(long sessionId) + => _games.Values.FirstOrDefault(g => g.Clients.Values.Any(c => c.SessionId == sessionId)); + + /// AI 对局循环(参考 Testing-v3 的模拟循环:行动顺序 → ProcessTurn → TimeLapse) + 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 + { + ["gameId"] = game.Id, + ["round"] = element + }); + + foreach (ClientSession session in game.Clients.Values) + { + _ = session.SendAsync(message); + } + } + + /// 暂停对局(对局循环在下一个回合边界挂起) + 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; + } + + /// 恢复对局 + public bool ResumeGame(Guid id) + { + if (!_games.TryGetValue(id, out HostedGame? game)) + { + return false; + } + game.Paused = false; + _logger.LogInformation("恢复对局:{GameId}", id); + return true; + } + + /// 结束对局(正常/中止):归档回合记录、广播结算、释放插件引用 + public async Task 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 + { + ["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; + } + + /// 重连对局:把会话重新绑定到对局(用户 Id -> 会话) + public bool Reconnect(Guid gameId, long userId, ClientSession session) + { + if (_games.TryGetValue(gameId, out HostedGame? game)) + { + game.Clients[userId] = session; + return true; + } + return false; + } +} + +/// +/// 已托管的对局(实现 IGameSession,暴露给游戏模式模组 / 服务器插件) +/// +public class HostedGame : IGameSession +{ + private readonly GameRoundRecordSink _sink; + private readonly Func _endGame; + + public HostedGame(Guid id, string mode, GamingQueue? queue, GameRoundRecordSink sink, IGameModuleServer? module = null, Func? 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 Clients { get; } = []; + + IReadOnlyDictionary IGameSession.Clients => Clients.ToDictionary(kv => kv.Key, kv => (IClientSession)kv.Value); + + public Dictionary CustomData { get; } = []; + + public IReadOnlyList Characters => Queue.AllCharacters; + + public GameRoundRecordSink Sink => _sink; + + public void End(bool aborted) + { + Running = false; + _sink.End(); + } + + /// 广播消息给本局全部用户(userIds 为空)或指定用户(供 GameModule 使用) + public async Task BroadcastAsync(string messageType, Dictionary 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); + } + } + } + + /// 结束对局(宿主负责归档与广播结算) + public Task EndGameAsync(bool aborted = false) => _endGame(Id, aborted); + + /// 等待对局结束并复位房间(供房间开始对局流程使用) + 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); + } +} diff --git a/src/FunGame.Server.Host/Services/GameRoundRecordSink.cs b/src/FunGame.Server.Host/Services/GameRoundRecordSink.cs new file mode 100644 index 0000000..c752dcf --- /dev/null +++ b/src/FunGame.Server.Host/Services/GameRoundRecordSink.cs @@ -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; + +/// +/// 回合记录外发实现(Core v3 IRoundRecordSink) +/// - 本地归档:records/{gameId}.zip(rounds_data.json,与 Testing-v3 回放格式兼容)+ RoundRecords 表行 +/// - 远程转发:配置 RoundRecordSink:PostUrl 时内部包装 Core 的 DefaultRoundRecordSink 即时 POST +/// +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 _logger; + private readonly DefaultRoundRecordSink? _remote; + private readonly Lock _lock = new(); + + private readonly Dictionary _rounds = []; + private Dictionary? _statistics; + private List? _characters; + private List? _teams; + private Guid _queueId; + private bool _ended; + + public GameRoundRecordSink(Guid gameId, string mode, IServiceScopeFactory scopeFactory, IConfiguration configuration, ILogger 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() ?? ["0", "1", "2", "3", "4", "5", "6", "7", "8"]; + _remote = new DefaultRoundRecordSink(postUrl, intents) + { + AccessToken = configuration["RoundRecordSink:AccessToken"] ?? "", + Secret = configuration["RoundRecordSink:Secret"] ?? "" + }; + } + } + + /// 回合记录更新事件(供宿主做 WS 实时推送) + public event Action? 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(); + 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); + } + }); + } + + /// 归档最终化任务(End 后可用 await 等待归档完成) + 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 statistics) + { + lock (_lock) + { + _statistics = statistics; + } + _remote?.SendCharacterStatistics(statistics); + } + + public void SendCharacters(IEnumerable characters) + { + lock (_lock) + { + _characters = [.. characters]; + } + _remote?.SendCharacters(characters); + } + + public void SendTeams(IEnumerable teams) + { + lock (_lock) + { + _teams = [.. teams]; + } + _remote?.SendTeams(teams); + } + + public void SendQueueData(Dictionary queueData) + { + _remote?.SendQueueData(queueData); + } + + public void SendEliminatedCharacters(IEnumerable characterGuids) + { + _remote?.SendEliminatedCharacters(characterGuids); + } + + public void SendEliminatedTeams(IEnumerable teamNames) + { + _remote?.SendEliminatedTeams(teamNames); + } + + // ===== 归档 ===== + + private string ArchiveFileName => $"{_gameId:N}.zip"; + + private string ArchiveFilePath => Path.Combine(_archiveDirectory, ArchiveFileName); + + private void FinalizeArchive() + { + try + { + Dictionary rounds; + Dictionary? statistics; + List? characters; + List? teams; + lock (_lock) + { + rounds = new Dictionary(_rounds); + statistics = _statistics != null ? new Dictionary(_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(); + 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 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); + } +} diff --git a/src/FunGame.Server.Host/Services/ReplayArchiveService.cs b/src/FunGame.Server.Host/Services/ReplayArchiveService.cs new file mode 100644 index 0000000..902d6df --- /dev/null +++ b/src/FunGame.Server.Host/Services/ReplayArchiveService.cs @@ -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; + +/// +/// 回放归档服务:读取 GameRoundRecordSink 归档的 records/{gameId}.zip(rounds_data.json) +/// 格式与 Testing-v3 兼容:zip 内含 rounds_data.json = Dictionary<int, RoundRecord> +/// +public class ReplayArchiveService(IServiceScopeFactory scopeFactory, IConfiguration configuration, ILogger logger) +{ + private readonly string _archiveDirectory = configuration["RoundRecordSink:ArchiveDirectory"] ?? "records"; + + /// 取对局记录(GameRecords 行) + public async Task GetGameRecordAsync(Guid id) + { + using IServiceScope scope = scopeFactory.CreateScope(); + AppDbContext db = scope.ServiceProvider.GetRequiredService(); + return await db.GameRecords.AsNoTracking().FirstOrDefaultAsync(g => g.Id == id); + } + + /// 读取全部回合 + public Dictionary? 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>(entryStream, JsonService.GeneralOptions); + } + catch (Exception e) + { + logger.LogError(e, "读取对局归档失败:{Path}", path); + return null; + } + } + + public string GetArchivePath(GameRecord record) => Path.Combine(_archiveDirectory, record.ArchivePath); + + /// 读取归档中的最终角色统计(statistics.json) + public Dictionary? 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>(entryStream, JsonService.GeneralOptions); + } + catch (Exception e) + { + logger.LogError(e, "读取对局统计归档失败:{Path}", path); + return null; + } + } +} diff --git a/src/FunGame.Server.Host/Services/RoomService.cs b/src/FunGame.Server.Host/Services/RoomService.cs new file mode 100644 index 0000000..a91d9b1 --- /dev/null +++ b/src/FunGame.Server.Host/Services/RoomService.cs @@ -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; + +/// +/// 房间服务:房间持久化(EF)+ 内存成员表 + 聊天/开始对局 +/// +public class RoomService(IServiceScopeFactory scopeFactory, ILogger logger) +{ + /// 房间号 -> (会话Id -> 会话) + private readonly ConcurrentDictionary> _members = new(); + + /// 获取客户端所在房间号 + public string? GetRoomOfClient(long sessionId) + => _members.FirstOrDefault(kv => kv.Value.ContainsKey(sessionId)).Key; + + public IReadOnlyCollection GetMembers(string roomId) + => _members.TryGetValue(roomId, out ConcurrentDictionary? members) + ? members.Values.ToArray() + : []; + + public async Task GetRoomAsync(string roomId) + { + using IServiceScope scope = scopeFactory.CreateScope(); + AppDbContext db = scope.ServiceProvider.GetRequiredService(); + return await db.Rooms.AsNoTracking().FirstOrDefaultAsync(r => r.RoomId == roomId); + } + + public async Task> ListRoomsAsync() + { + using IServiceScope scope = scopeFactory.CreateScope(); + AppDbContext db = scope.ServiceProvider.GetRequiredService(); + return await db.Rooms.AsNoTracking().Where(r => r.State != RoomStateEntity.Gaming).OrderByDescending(r => r.CreatedAt).Take(50).ToListAsync(); + } + + public async Task 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(); + + 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; + } + + /// 进入房间 + 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 members = _members.GetOrAdd(room.RoomId, _ => new()); + if (members.Count >= room.MaxUsers && !members.ContainsKey(client.SessionId)) + { + return (false, "房间人数已满。"); + } + members[client.SessionId] = client; + return (true, ""); + } + + /// 退出房间(返回剩余人数) + public async Task QuitAsync(string roomId, ClientSession client) + { + if (_members.TryGetValue(roomId, out ConcurrentDictionary? members)) + { + members.TryRemove(client.SessionId, out _); + if (members.IsEmpty) + { + _members.TryRemove(roomId, out _); + return 0; + } + return members.Count; + } + return 0; + } + + /// 对局结束后复位房间 + public async Task ResetRoomAsync(string roomId) + { + using IServiceScope scope = scopeFactory.CreateScope(); + AppDbContext db = scope.ServiceProvider.GetRequiredService(); + 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(); + RoomEntity? room = await db.Rooms.FirstOrDefaultAsync(r => r.RoomId == roomId); + if (room != null) + { + room.State = RoomStateEntity.Gaming; + room.UpdatedAt = DateTime.Now; + await db.SaveChangesAsync(); + } + } + + /// 7 位大写随机房间号(防重复) + 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(); + if (!db.Rooms.Any(r => r.RoomId == id)) + { + return id; + } + } + } +} diff --git a/src/FunGame.Server.Host/appsettings.Development.json b/src/FunGame.Server.Host/appsettings.Development.json new file mode 100644 index 0000000..34f00ef --- /dev/null +++ b/src/FunGame.Server.Host/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "Microsoft.AspNetCore": "Information" + } + } +} diff --git a/src/FunGame.Server.Host/appsettings.json b/src/FunGame.Server.Host/appsettings.json new file mode 100644 index 0000000..431632c --- /dev/null +++ b/src/FunGame.Server.Host/appsettings.json @@ -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" + } + } +} diff --git a/src/FunGame.Server.Infrastructure/Data/AppDbContext.cs b/src/FunGame.Server.Infrastructure/Data/AppDbContext.cs new file mode 100644 index 0000000..c9eb099 --- /dev/null +++ b/src/FunGame.Server.Infrastructure/Data/AppDbContext.cs @@ -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 options) : DbContext(options) +{ + // ===== 认证与用户中心 ===== + public DbSet Users => Set(); + public DbSet UserProfiles => Set(); + public DbSet Roles => Set(); + public DbSet Permissions => Set(); + public DbSet UserRoles => Set(); + public DbSet RolePermissions => Set(); + public DbSet RefreshTokens => Set(); + public DbSet UserSessions => Set(); + public DbSet LoginLogs => Set(); + public DbSet ApiTokens => Set(); + + // ===== 游戏业务 ===== + public DbSet Rooms => Set(); + public DbSet UserCharacters => Set(); + public DbSet UserItems => Set(); + public DbSet Inventories => Set(); + public DbSet GameRecords => Set(); + public DbSet RoundRecords => Set(); + + // ===== 经济 ===== + public DbSet Stores => Set(); + public DbSet StoreGoods => Set(); + public DbSet Goods => Set(); + public DbSet GoodsPrices => Set(); + public DbSet MarketItems => Set(); + public DbSet Offers => Set(); + public DbSet OfferItems => Set(); + + // ===== 系统 ===== + public DbSet ServerLogs => Set(); + public DbSet SystemConfigs => Set(); + public DbSet VerifyCodes => Set(); + public DbSet UserSignIns => Set(); + + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); + + // ===== Users ===== + builder.Entity(e => + { + e.ToTable("users"); + e.HasIndex(u => u.Username).IsUnique(); + e.HasIndex(u => u.Email); + e.Property(u => u.Id).ValueGeneratedOnAdd(); + }); + + builder.Entity(e => + { + e.ToTable("user_profiles"); + e.HasOne(p => p.User).WithOne(u => u.Profile).HasForeignKey(p => p.UserId).OnDelete(DeleteBehavior.Cascade); + }); + + builder.Entity(e => + { + e.ToTable("roles"); + e.HasIndex(r => r.Code).IsUnique(); + }); + + builder.Entity(e => + { + e.ToTable("permissions"); + e.HasIndex(p => p.Code).IsUnique(); + }); + + builder.Entity(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(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(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(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(e => + { + e.ToTable("login_logs"); + e.HasIndex(l => new { l.UserId, l.CreatedAt }); + }); + + builder.Entity(e => + { + e.ToTable("api_tokens"); + e.HasIndex(t => t.TokenId).IsUnique(); + }); + + // ===== 游戏 ===== + builder.Entity(e => + { + e.ToTable("rooms"); + e.HasKey(r => r.RoomId); + e.HasIndex(r => r.State); + }); + + builder.Entity(e => + { + e.ToTable("user_characters"); + e.HasIndex(c => c.UserId); + }); + + builder.Entity(e => + { + e.ToTable("user_items"); + e.HasIndex(i => i.UserId); + }); + + builder.Entity(e => + { + e.ToTable("inventories"); + e.HasKey(i => i.UserId); + }); + + builder.Entity(e => + { + e.ToTable("game_records"); + e.HasIndex(g => g.QueueId).IsUnique(); + e.HasIndex(g => g.StartedAt); + }); + + builder.Entity(e => + { + e.ToTable("round_records"); + e.HasIndex(r => new { r.GameId, r.Round }).IsUnique(); + }); + + // ===== 经济 ===== + builder.Entity(e => + { + e.ToTable("stores"); + }); + + builder.Entity(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(e => + { + e.ToTable("goods"); + }); + + builder.Entity(e => + { + e.ToTable("goods_prices"); + e.HasOne(p => p.Goods).WithMany(g => g.Prices).HasForeignKey(p => p.GoodsId).OnDelete(DeleteBehavior.Cascade); + }); + + builder.Entity(e => + { + e.ToTable("market_items"); + e.HasIndex(m => m.ItemGuid); + e.HasIndex(m => m.SellerUserId); + }); + + builder.Entity(e => + { + e.ToTable("offers"); + e.HasIndex(o => new { o.OfferorUserId, o.OffereeUserId }); + }); + + builder.Entity(e => + { + e.ToTable("offer_items"); + e.HasOne(i => i.Offer).WithMany(o => o.Items).HasForeignKey(i => i.OfferId).OnDelete(DeleteBehavior.Cascade); + }); + + // ===== 系统 ===== + builder.Entity(e => + { + e.ToTable("server_logs"); + e.HasIndex(l => l.CreatedAt); + e.HasIndex(l => l.Level); + }); + + builder.Entity(e => + { + e.ToTable("system_configs"); + e.HasKey(c => c.Key); + }); + + builder.Entity(e => + { + e.ToTable("verify_codes"); + e.HasIndex(v => new { v.Purpose, v.Username }); + }); + + builder.Entity(e => + { + e.ToTable("user_sign_ins"); + e.HasIndex(s => s.UserId).IsUnique(); + }); + } +} diff --git a/src/FunGame.Server.Infrastructure/Data/AppDbContextFactory.cs b/src/FunGame.Server.Infrastructure/Data/AppDbContextFactory.cs new file mode 100644 index 0000000..4096c45 --- /dev/null +++ b/src/FunGame.Server.Infrastructure/Data/AppDbContextFactory.cs @@ -0,0 +1,45 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; +using Microsoft.Extensions.Configuration; + +namespace FunGame.Server.Infrastructure.Data; + +/// +/// 设计时工厂(dotnet-ef 迁移使用) +/// 依次向上查找 appsettings.json(优先 Host 项目的配置),未找到时回退到默认 SQLite +/// +public class AppDbContextFactory : IDesignTimeDbContextFactory +{ + 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 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"); + } +} diff --git a/src/FunGame.Server.Infrastructure/Data/DbContextOptionsFactory.cs b/src/FunGame.Server.Infrastructure/Data/DbContextOptionsFactory.cs new file mode 100644 index 0000000..696f486 --- /dev/null +++ b/src/FunGame.Server.Infrastructure/Data/DbContextOptionsFactory.cs @@ -0,0 +1,46 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; + +namespace FunGame.Server.Infrastructure.Data; + +/// +/// AppDbContext 选项工厂:按 Database:Provider 切换 SQLite / MySQL +/// +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 Create(IConfiguration configuration) + { + DbContextOptionsBuilder builder = new(); + Configure(builder, configuration); + return builder.Options; + } +} diff --git a/src/FunGame.Server.Infrastructure/Data/DbSeedService.cs b/src/FunGame.Server.Infrastructure/Data/DbSeedService.cs new file mode 100644 index 0000000..6051aad --- /dev/null +++ b/src/FunGame.Server.Infrastructure/Data/DbSeedService.cs @@ -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; + +/// +/// 数据库种子服务:权限点、系统角色、初始管理员(仅首次启动) +/// +public class DbSeedService(AppDbContext db, ILogger logger, IConfiguration configuration) +{ + /// 系统角色代码 + 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 existing = await db.Permissions.ToListAsync(ct); + HashSet 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 allPermissions = await db.Permissions.ToListAsync(ct); + Dictionary 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 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); + } +} diff --git a/src/FunGame.Server.Infrastructure/Entities/Economy/Economy.cs b/src/FunGame.Server.Infrastructure/Entities/Economy/Economy.cs new file mode 100644 index 0000000..1437cdb --- /dev/null +++ b/src/FunGame.Server.Infrastructure/Entities/Economy/Economy.cs @@ -0,0 +1,136 @@ +using System.ComponentModel.DataAnnotations; + +namespace FunGame.Server.Infrastructure.Entities.Economy; + +/// 商店 +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 { get; set; } = []; +} + +/// 商店-商品(多对多连接表) +public class StoreGoods +{ + public long StoreId { get; set; } + public Store? Store { get; set; } + public long GoodsId { get; set; } + public Goods? Goods { get; set; } +} + +/// 商品(物品实体以 Core JSON 存储) +public class Goods +{ + public long Id { get; set; } + + [MaxLength(64)] + public string Name { get; set; } = ""; + + /// Core Item 实体的 JSON + public string ItemJson { get; set; } = ""; + + /// 库存(-1 表示无限) + public int Stock { get; set; } = -1; + + public bool IsEnabled { get; set; } = true; + + public DateTime CreatedAt { get; set; } = DateTime.Now; + + public List Prices { get; set; } = []; + public List StoreGoods { get; set; } = []; +} + +/// 商品价格(双货币) +public class GoodsPrice +{ + public long Id { get; set; } + public long GoodsId { get; set; } + public Goods? Goods { get; set; } + + /// 货币:credits / materials + [MaxLength(16)] + public string Currency { get; set; } = "credits"; + + public double Price { get; set; } +} + +/// 市场寄售状态 +public enum MarketItemStateEntity +{ + Listed = 0, + Sold = 1, + Delisted = 2 +} + +/// 市场寄售 +public class MarketItem +{ + public long Id { get; set; } + + /// 寄售物品的 Guid(对应玩家库存中物品) + 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; +} + +/// 交易报价状态 +public enum OfferStateEntity +{ + Created = 0, + Sent = 1, + Negotiating = 2, + Completed = 3, + Rejected = 4, + Cancelled = 5, + Expired = 6 +} + +/// 交易报价(v2 offers 迁移) +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; + + /// 已协商次数(上限 3) + public int NegotiatedTimes { get; set; } + + public DateTime CreatedAt { get; set; } = DateTime.Now; + public DateTime? FinishedAt { get; set; } + + public List Items { get; set; } = []; +} + +/// 报价条目 +public class OfferItem +{ + public long Id { get; set; } + public long OfferId { get; set; } + public Offer? Offer { get; set; } + + /// 归属方:offeror / offeree + [MaxLength(16)] + public string Side { get; set; } = "offeror"; + + public Guid ItemGuid { get; set; } +} diff --git a/src/FunGame.Server.Infrastructure/Entities/Game/Game.cs b/src/FunGame.Server.Infrastructure/Entities/Game/Game.cs new file mode 100644 index 0000000..930903a --- /dev/null +++ b/src/FunGame.Server.Infrastructure/Entities/Game/Game.cs @@ -0,0 +1,175 @@ +using System.ComponentModel.DataAnnotations; + +namespace FunGame.Server.Infrastructure.Entities.Game; + +/// 房间状态 +public enum RoomStateEntity +{ + Created = 0, + Matching = 1, + Gaming = 2 +} + +/// +/// 房间(v2 rooms 表迁移) +/// +public class RoomEntity +{ + /// 房间号(7 位大写随机) + [MaxLength(16)] + public string RoomId { get; set; } = ""; + + public long? MasterUserId { get; set; } + + [MaxLength(64)] + public string GameModule { get; set; } = ""; + + /// 内容模组前缀(如 "oshima"):该房间对局的角色/技能/物品只从该模组族产生;空 = 全量模组 + [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; +} + +/// +/// 玩家角色库(v2 user_characters 迁移:角色实体以 Core JSON 存储,关键字段列冗余) +/// +public class UserCharacter +{ + public long Id { get; set; } + public long UserId { get; set; } + + [MaxLength(64)] + public string Name { get; set; } = ""; + + /// Core Character 实体的 JSON(JsonService 序列化) + public string CharacterJson { get; set; } = ""; + + public bool IsDefault { get; set; } + + public DateTime CreatedAt { get; set; } = DateTime.Now; + public DateTime UpdatedAt { get; set; } = DateTime.Now; +} + +/// +/// 玩家物品(v2 user_items 迁移) +/// +public class UserItem +{ + public long Id { get; set; } + public long UserId { get; set; } + + [MaxLength(64)] + public string Name { get; set; } = ""; + + /// Core Item 实体的 JSON + 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; +} + +/// +/// 库存(v2 inventories:货币与材料) +/// +public class Inventory +{ + public long UserId { get; set; } + + /// 游戏币 + public double Credits { get; set; } + + /// 材料 + public double Materials { get; set; } + + public DateTime UpdatedAt { get; set; } = DateTime.Now; +} + +/// 对局状态 +public enum GameState +{ + Running = 0, + Finished = 1, + Aborted = 2 +} + +/// +/// 对局记录索引(回合记录归档的元信息) +/// +public class GameRecord +{ + public Guid Id { get; set; } = Guid.NewGuid(); + + /// GamingQueue 的 Guid + public Guid QueueId { get; set; } + + /// 游戏模式(服务器插件名) + [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; } + + /// 回合记录归档文件路径(相对记录目录) + [MaxLength(256)] + public string ArchivePath { get; set; } = ""; + + public DateTime CreatedAt { get; set; } = DateTime.Now; +} + +/// +/// 回合记录行(与归档文件并存;JSON 列存储单回合数据,便于按回合检索) +/// +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; } + + /// Core RoundRecord 的 JSON(含行动流/特效/快照) + public string RecordJson { get; set; } = ""; + + /// 是否为检查点回合(含全角色状态快照) + public bool IsCheckpoint { get; set; } + + public DateTime CreatedAt { get; set; } = DateTime.Now; +} diff --git a/src/FunGame.Server.Infrastructure/Entities/Identity/Identity.cs b/src/FunGame.Server.Infrastructure/Entities/Identity/Identity.cs new file mode 100644 index 0000000..97e78dc --- /dev/null +++ b/src/FunGame.Server.Infrastructure/Entities/Identity/Identity.cs @@ -0,0 +1,134 @@ +using System.ComponentModel.DataAnnotations; + +namespace FunGame.Server.Infrastructure.Entities.Identity; + +/// 用户状态 +public enum UserStatus +{ + Active = 0, + Banned = 1, + Disabled = 2 +} + +/// +/// 用户(v2 users 重构:PBKDF2 密码散列、邮箱验证、状态管理) +/// +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; + + /// 系统内置账号(不可删除,如机器人账号) + 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 UserRoles { get; set; } = []; + public UserProfile? Profile { get; set; } + public List RefreshTokens { get; set; } = []; + public List Sessions { get; set; } = []; +} + +/// 用户资料(v2 user_profiles) +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; } = ""; + + /// 偏好设置(JSON) + public string PreferencesJson { get; set; } = "{}"; + + public DateTime UpdatedAt { get; set; } = DateTime.Now; +} + +/// 角色(RBAC) +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; } = ""; + + /// 系统内置角色(不可删除) + public bool IsSystem { get; set; } + + public DateTime CreatedAt { get; set; } = DateTime.Now; + + public List UserRoles { get; set; } = []; + public List RolePermissions { get; set; } = []; +} + +/// 权限点(细粒度) +public class Permission +{ + public long Id { get; set; } + + [MaxLength(64)] + public string Code { get; set; } = ""; + + [MaxLength(64)] + public string Name { get; set; } = ""; + + /// 权限分组(如 users / plugins / games) + [MaxLength(32)] + public string Group { get; set; } = ""; + + [MaxLength(256)] + public string Description { get; set; } = ""; + + public List RolePermissions { get; set; } = []; +} + +/// 用户-角色(多对多连接表) +public class UserRole +{ + public long UserId { get; set; } + public User? User { get; set; } + public long RoleId { get; set; } + public Role? Role { get; set; } +} + +/// 角色-权限(多对多连接表) +public class RolePermission +{ + public long RoleId { get; set; } + public Role? Role { get; set; } + public long PermissionId { get; set; } + public Permission? Permission { get; set; } +} diff --git a/src/FunGame.Server.Infrastructure/Entities/Identity/Tokens.cs b/src/FunGame.Server.Infrastructure/Entities/Identity/Tokens.cs new file mode 100644 index 0000000..8b7dc30 --- /dev/null +++ b/src/FunGame.Server.Infrastructure/Entities/Identity/Tokens.cs @@ -0,0 +1,125 @@ +using System.ComponentModel.DataAnnotations; + +namespace FunGame.Server.Infrastructure.Entities.Identity; + +/// +/// 刷新令牌(多端统一验证:散列存储,支持撤销/设备维度) +/// +public class RefreshToken +{ + public long Id { get; set; } + public long UserId { get; set; } + public User? User { get; set; } + + /// 令牌散列(原始令牌仅返回客户端一次) + [MaxLength(128)] + public string TokenHash { get; set; } = ""; + + /// 签发端:web / api / ws + [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; +} + +/// +/// 在线会话(每端一条,支持多端管理与同端互踢) +/// +public class UserSession +{ + public long Id { get; set; } + public long UserId { get; set; } + public User? User { get; set; } + + /// 会话端:web / api / ws + [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; } = ""; + + /// 本次 AccessToken 的 JTI + [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; +} + +/// 登录日志 +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; +} + +/// +/// API 访问令牌(外部服务接入,如回放服务器) +/// +public class ApiToken +{ + public long Id { get; set; } + + /// 令牌 ID(如 fungame_web_api) + [MaxLength(64)] + public string TokenId { get; set; } = ""; + + /// 令牌散列 + [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; } = ""; +} diff --git a/src/FunGame.Server.Infrastructure/Entities/System/System.cs b/src/FunGame.Server.Infrastructure/Entities/System/System.cs new file mode 100644 index 0000000..109f162 --- /dev/null +++ b/src/FunGame.Server.Infrastructure/Entities/System/System.cs @@ -0,0 +1,96 @@ +using System.ComponentModel.DataAnnotations; + +namespace FunGame.Server.Infrastructure.Entities.System; + +/// 日志级别 +public enum LogLevelEntity +{ + Trace = 0, + Debug = 1, + Info = 2, + Warning = 3, + Error = 4, + Critical = 5 +} + +/// +/// 服务器日志(供 WebUI 查看;可在 Host 用 Serilog/自定义 Provider 写入) +/// +public class ServerLog +{ + public long Id { get; set; } + + public LogLevelEntity Level { get; set; } = LogLevelEntity.Info; + + /// 来源(Host / Plugin / Module / Game ...) + [MaxLength(32)] + public string Source { get; set; } = "Host"; + + /// 分类(如 Auth / Room / PluginManager) + [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; +} + +/// 系统配置键值(v2 configs 迁移:公告、开关等) +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; +} + +/// 验证码用途 +public enum VerifyCodePurpose +{ + Register = 0, + ForgetPassword = 1 +} + +/// 验证码(v2 reg_verify_codes + forget_verify_codes 合并) +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; +} + +/// 每日签到 +public class UserSignIn +{ + public long Id { get; set; } + public long UserId { get; set; } + + /// 连续签到天数 + public int Days { get; set; } + + /// 是否已签到(当天) + public bool IsSigned { get; set; } + + public DateTime LastTime { get; set; } +} diff --git a/src/FunGame.Server.Infrastructure/FunGame.Server.Infrastructure.csproj b/src/FunGame.Server.Infrastructure/FunGame.Server.Infrastructure.csproj new file mode 100644 index 0000000..e9ef9cf --- /dev/null +++ b/src/FunGame.Server.Infrastructure/FunGame.Server.Infrastructure.csproj @@ -0,0 +1,22 @@ + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + net10.0 + enable + enable + + + diff --git a/src/FunGame.Server.Infrastructure/InfrastructureServiceCollectionExtensions.cs b/src/FunGame.Server.Infrastructure/InfrastructureServiceCollectionExtensions.cs new file mode 100644 index 0000000..471847a --- /dev/null +++ b/src/FunGame.Server.Infrastructure/InfrastructureServiceCollectionExtensions.cs @@ -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 +{ + /// + /// 注册 EF Core 数据层(SQLite/MySQL 按配置切换) + /// + public static IServiceCollection AddServerInfrastructure(this IServiceCollection services, IConfiguration configuration) + { + services.AddDbContext((serviceProvider, options) => + { + IConfiguration config = serviceProvider.GetRequiredService(); + DbContextOptionsFactory.Configure(options, config); + }); + + services.AddScoped(); + + return services; + } +} diff --git a/src/FunGame.Server.Infrastructure/Migrations/Sqlite/20260816155339_InitialCreate.Designer.cs b/src/FunGame.Server.Infrastructure/Migrations/Sqlite/20260816155339_InitialCreate.Designer.cs new file mode 100644 index 0000000..f9b6d48 --- /dev/null +++ b/src/FunGame.Server.Infrastructure/Migrations/Sqlite/20260816155339_InitialCreate.Designer.cs @@ -0,0 +1,1117 @@ +// +using System; +using FunGame.Server.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace FunGame.Server.Infrastructure.Migrations.Sqlite +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260816155339_InitialCreate")] + partial class InitialCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.Goods", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("IsEnabled") + .HasColumnType("INTEGER"); + + b.Property("ItemJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Stock") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.ToTable("goods", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.GoodsPrice", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("GoodsId") + .HasColumnType("INTEGER"); + + b.Property("Price") + .HasColumnType("REAL"); + + b.HasKey("Id"); + + b.HasIndex("GoodsId"); + + b.ToTable("goods_prices", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.MarketItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("ItemGuid") + .HasColumnType("TEXT"); + + b.Property("Price") + .HasColumnType("REAL"); + + b.Property("SellerUserId") + .HasColumnType("INTEGER"); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("Stock") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ItemGuid"); + + b.HasIndex("SellerUserId"); + + b.ToTable("market_items", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.Offer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("FinishedAt") + .HasColumnType("TEXT"); + + b.Property("NegotiatedTimes") + .HasColumnType("INTEGER"); + + b.Property("OffereeUserId") + .HasColumnType("INTEGER"); + + b.Property("OfferorUserId") + .HasColumnType("INTEGER"); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("OfferorUserId", "OffereeUserId"); + + b.ToTable("offers", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.OfferItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ItemGuid") + .HasColumnType("TEXT"); + + b.Property("OfferId") + .HasColumnType("INTEGER"); + + b.Property("Side") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("OfferId"); + + b.ToTable("offer_items", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.Store", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsEnabled") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("stores", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.StoreGoods", b => + { + b.Property("StoreId") + .HasColumnType("INTEGER"); + + b.Property("GoodsId") + .HasColumnType("INTEGER"); + + b.HasKey("StoreId", "GoodsId"); + + b.HasIndex("GoodsId"); + + b.ToTable("store_goods", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Game.GameRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ArchivePath") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("EndedAt") + .HasColumnType("TEXT"); + + b.Property("Map") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("MatchType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Mode") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("QueueId") + .HasColumnType("TEXT"); + + b.Property("StartedAt") + .HasColumnType("TEXT"); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("TotalRounds") + .HasColumnType("INTEGER"); + + b.Property("Winner") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("QueueId") + .IsUnique(); + + b.HasIndex("StartedAt"); + + b.ToTable("game_records", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Game.Inventory", b => + { + b.Property("UserId") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Credits") + .HasColumnType("REAL"); + + b.Property("Materials") + .HasColumnType("REAL"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("UserId"); + + b.ToTable("inventories", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Game.RoomEntity", b => + { + b.Property("RoomId") + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("GameMap") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("GameModule") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("IsRank") + .HasColumnType("INTEGER"); + + b.Property("MasterUserId") + .HasColumnType("INTEGER"); + + b.Property("MaxUsers") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("RoomId"); + + b.HasIndex("State"); + + b.ToTable("rooms", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Game.RoundRecordEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ActorGuid") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ActorName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("GameId") + .HasColumnType("TEXT"); + + b.Property("HasKill") + .HasColumnType("INTEGER"); + + b.Property("IsCheckpoint") + .HasColumnType("INTEGER"); + + b.Property("RecordJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Round") + .HasColumnType("INTEGER"); + + b.Property("TotalDamage") + .HasColumnType("REAL"); + + b.Property("TotalHeal") + .HasColumnType("REAL"); + + b.HasKey("Id"); + + b.HasIndex("GameId", "Round") + .IsUnique(); + + b.ToTable("round_records", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Game.UserCharacter", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CharacterJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("IsDefault") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_characters", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Game.UserItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Count") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("ItemJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_items", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.ApiToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("ExpiresAt") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reference1") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Reference2") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RevokedAt") + .HasColumnType("TEXT"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("TokenId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TokenId") + .IsUnique(); + + b.ToTable("api_tokens", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.LoginLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Device") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Success") + .HasColumnType("INTEGER"); + + b.Property("UserAgent") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "CreatedAt"); + + b.ToTable("login_logs", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.Permission", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Group") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Code") + .IsUnique(); + + b.ToTable("permissions", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.RefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Device") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Endpoint") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ExpiresAt") + .HasColumnType("TEXT"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RevokedAt") + .HasColumnType("TEXT"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("UserAgent") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("refresh_tokens", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.Role", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsSystem") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Code") + .IsUnique(); + + b.ToTable("roles", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.RolePermission", b => + { + b.Property("RoleId") + .HasColumnType("INTEGER"); + + b.Property("PermissionId") + .HasColumnType("INTEGER"); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.ToTable("role_permissions", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Avatar") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("EmailVerified") + .HasColumnType("INTEGER"); + + b.Property("IsSystem") + .HasColumnType("INTEGER"); + + b.Property("LastLoginAt") + .HasColumnType("TEXT"); + + b.Property("LastLoginIp") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Nickname") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Status") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Email"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("users", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.UserProfile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PreferencesJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Signature") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("user_profiles", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.UserRole", b => + { + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.Property("RoleId") + .HasColumnType("INTEGER"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.UserSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AccessTokenId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ConnectedAt") + .HasColumnType("TEXT"); + + b.Property("Device") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("DisconnectedAt") + .HasColumnType("TEXT"); + + b.Property("Endpoint") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("LastActiveAt") + .HasColumnType("TEXT"); + + b.Property("UserAgent") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "Endpoint"); + + b.ToTable("user_sessions", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.System.ServerLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Exception") + .HasColumnType("TEXT"); + + b.Property("Level") + .HasColumnType("INTEGER"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("Level"); + + b.ToTable("server_logs", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.System.SystemConfig", b => + { + b.Property("Key") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("Value") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("system_configs", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.System.UserSignIn", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Days") + .HasColumnType("INTEGER"); + + b.Property("IsSigned") + .HasColumnType("INTEGER"); + + b.Property("LastTime") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("user_sign_ins", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.System.VerifyCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ExpiresAt") + .HasColumnType("TEXT"); + + b.Property("Purpose") + .HasColumnType("INTEGER"); + + b.Property("UsedAt") + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Purpose", "Username"); + + b.ToTable("verify_codes", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.GoodsPrice", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Economy.Goods", "Goods") + .WithMany("Prices") + .HasForeignKey("GoodsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Goods"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.OfferItem", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Economy.Offer", "Offer") + .WithMany("Items") + .HasForeignKey("OfferId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Offer"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.StoreGoods", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Economy.Goods", "Goods") + .WithMany("StoreGoods") + .HasForeignKey("GoodsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FunGame.Server.Infrastructure.Entities.Economy.Store", "Store") + .WithMany("StoreGoods") + .HasForeignKey("StoreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Goods"); + + b.Navigation("Store"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.RefreshToken", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.User", "User") + .WithMany("RefreshTokens") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.RolePermission", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.Permission", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.Role", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.UserProfile", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.User", "User") + .WithOne("Profile") + .HasForeignKey("FunGame.Server.Infrastructure.Entities.Identity.UserProfile", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.UserRole", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.Role", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.User", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.UserSession", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.User", "User") + .WithMany("Sessions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.Goods", b => + { + b.Navigation("Prices"); + + b.Navigation("StoreGoods"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.Offer", b => + { + b.Navigation("Items"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.Store", b => + { + b.Navigation("StoreGoods"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.Permission", b => + { + b.Navigation("RolePermissions"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.Role", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.User", b => + { + b.Navigation("Profile"); + + b.Navigation("RefreshTokens"); + + b.Navigation("Sessions"); + + b.Navigation("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/FunGame.Server.Infrastructure/Migrations/Sqlite/20260816155339_InitialCreate.cs b/src/FunGame.Server.Infrastructure/Migrations/Sqlite/20260816155339_InitialCreate.cs new file mode 100644 index 0000000..62c7511 --- /dev/null +++ b/src/FunGame.Server.Infrastructure/Migrations/Sqlite/20260816155339_InitialCreate.cs @@ -0,0 +1,788 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace FunGame.Server.Infrastructure.Migrations.Sqlite +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "api_tokens", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + TokenId = table.Column(type: "TEXT", maxLength: 64, nullable: false), + TokenHash = table.Column(type: "TEXT", maxLength: 128, nullable: false), + Name = table.Column(type: "TEXT", maxLength: 64, nullable: false), + ExpiresAt = table.Column(type: "TEXT", nullable: true), + RevokedAt = table.Column(type: "TEXT", nullable: true), + CreatedAt = table.Column(type: "TEXT", nullable: false), + Reference1 = table.Column(type: "TEXT", maxLength: 128, nullable: false), + Reference2 = table.Column(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(type: "TEXT", nullable: false), + QueueId = table.Column(type: "TEXT", nullable: false), + Mode = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Map = table.Column(type: "TEXT", maxLength: 64, nullable: true), + MatchType = table.Column(type: "TEXT", maxLength: 32, nullable: false), + State = table.Column(type: "INTEGER", nullable: false), + StartedAt = table.Column(type: "TEXT", nullable: false), + EndedAt = table.Column(type: "TEXT", nullable: true), + TotalRounds = table.Column(type: "INTEGER", nullable: false), + Winner = table.Column(type: "TEXT", maxLength: 64, nullable: true), + ArchivePath = table.Column(type: "TEXT", maxLength: 256, nullable: false), + CreatedAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_game_records", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "goods", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Name = table.Column(type: "TEXT", maxLength: 64, nullable: false), + ItemJson = table.Column(type: "TEXT", nullable: false), + Stock = table.Column(type: "INTEGER", nullable: false), + IsEnabled = table.Column(type: "INTEGER", nullable: false), + CreatedAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_goods", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "inventories", + columns: table => new + { + UserId = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Credits = table.Column(type: "REAL", nullable: false), + Materials = table.Column(type: "REAL", nullable: false), + UpdatedAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_inventories", x => x.UserId); + }); + + migrationBuilder.CreateTable( + name: "login_logs", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + UserId = table.Column(type: "INTEGER", nullable: true), + Username = table.Column(type: "TEXT", maxLength: 32, nullable: false), + Success = table.Column(type: "INTEGER", nullable: false), + Reason = table.Column(type: "TEXT", maxLength: 256, nullable: true), + IpAddress = table.Column(type: "TEXT", maxLength: 64, nullable: false), + UserAgent = table.Column(type: "TEXT", maxLength: 256, nullable: false), + Device = table.Column(type: "TEXT", maxLength: 64, nullable: false), + CreatedAt = table.Column(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(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + ItemGuid = table.Column(type: "TEXT", nullable: false), + SellerUserId = table.Column(type: "INTEGER", nullable: false), + Price = table.Column(type: "REAL", nullable: false), + Stock = table.Column(type: "INTEGER", nullable: false), + State = table.Column(type: "INTEGER", nullable: false), + CreatedAt = table.Column(type: "TEXT", nullable: false), + UpdatedAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_market_items", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "offers", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + OfferorUserId = table.Column(type: "INTEGER", nullable: false), + OffereeUserId = table.Column(type: "INTEGER", nullable: false), + State = table.Column(type: "INTEGER", nullable: false), + NegotiatedTimes = table.Column(type: "INTEGER", nullable: false), + CreatedAt = table.Column(type: "TEXT", nullable: false), + FinishedAt = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_offers", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "permissions", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Code = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Name = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Group = table.Column(type: "TEXT", maxLength: 32, nullable: false), + Description = table.Column(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(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Code = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Name = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Description = table.Column(type: "TEXT", maxLength: 256, nullable: false), + IsSystem = table.Column(type: "INTEGER", nullable: false), + CreatedAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_roles", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "rooms", + columns: table => new + { + RoomId = table.Column(type: "TEXT", maxLength: 16, nullable: false), + MasterUserId = table.Column(type: "INTEGER", nullable: true), + GameModule = table.Column(type: "TEXT", maxLength: 64, nullable: false), + GameMap = table.Column(type: "TEXT", maxLength: 64, nullable: false), + PasswordHash = table.Column(type: "TEXT", maxLength: 128, nullable: true), + MaxUsers = table.Column(type: "INTEGER", nullable: false), + State = table.Column(type: "INTEGER", nullable: false), + IsRank = table.Column(type: "INTEGER", nullable: false), + CreatedAt = table.Column(type: "TEXT", nullable: false), + UpdatedAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_rooms", x => x.RoomId); + }); + + migrationBuilder.CreateTable( + name: "round_records", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + GameId = table.Column(type: "TEXT", nullable: false), + Round = table.Column(type: "INTEGER", nullable: false), + ActorGuid = table.Column(type: "TEXT", maxLength: 64, nullable: false), + ActorName = table.Column(type: "TEXT", maxLength: 64, nullable: false), + HasKill = table.Column(type: "INTEGER", nullable: false), + TotalDamage = table.Column(type: "REAL", nullable: false), + TotalHeal = table.Column(type: "REAL", nullable: false), + RecordJson = table.Column(type: "TEXT", nullable: false), + IsCheckpoint = table.Column(type: "INTEGER", nullable: false), + CreatedAt = table.Column(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(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Level = table.Column(type: "INTEGER", nullable: false), + Source = table.Column(type: "TEXT", maxLength: 32, nullable: false), + Category = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Message = table.Column(type: "TEXT", maxLength: 1024, nullable: false), + Exception = table.Column(type: "TEXT", nullable: true), + CreatedAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_server_logs", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "stores", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Name = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Description = table.Column(type: "TEXT", maxLength: 256, nullable: false), + IsEnabled = table.Column(type: "INTEGER", nullable: false), + CreatedAt = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_stores", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "system_configs", + columns: table => new + { + Key = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Value = table.Column(type: "TEXT", nullable: false), + Description = table.Column(type: "TEXT", maxLength: 64, nullable: true), + UpdatedAt = table.Column(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(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + UserId = table.Column(type: "INTEGER", nullable: false), + Name = table.Column(type: "TEXT", maxLength: 64, nullable: false), + CharacterJson = table.Column(type: "TEXT", nullable: false), + IsDefault = table.Column(type: "INTEGER", nullable: false), + CreatedAt = table.Column(type: "TEXT", nullable: false), + UpdatedAt = table.Column(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(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + UserId = table.Column(type: "INTEGER", nullable: false), + Name = table.Column(type: "TEXT", maxLength: 64, nullable: false), + ItemJson = table.Column(type: "TEXT", nullable: false), + Count = table.Column(type: "INTEGER", nullable: false), + CreatedAt = table.Column(type: "TEXT", nullable: false), + UpdatedAt = table.Column(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(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + UserId = table.Column(type: "INTEGER", nullable: false), + Days = table.Column(type: "INTEGER", nullable: false), + IsSigned = table.Column(type: "INTEGER", nullable: false), + LastTime = table.Column(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(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Username = table.Column(type: "TEXT", maxLength: 32, nullable: false), + PasswordHash = table.Column(type: "TEXT", maxLength: 256, nullable: false), + Email = table.Column(type: "TEXT", maxLength: 128, nullable: false), + EmailVerified = table.Column(type: "INTEGER", nullable: false), + Nickname = table.Column(type: "TEXT", maxLength: 64, nullable: false), + Avatar = table.Column(type: "TEXT", maxLength: 256, nullable: false), + Status = table.Column(type: "INTEGER", nullable: false), + IsSystem = table.Column(type: "INTEGER", nullable: false), + CreatedAt = table.Column(type: "TEXT", nullable: false), + UpdatedAt = table.Column(type: "TEXT", nullable: false), + LastLoginAt = table.Column(type: "TEXT", nullable: true), + LastLoginIp = table.Column(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(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Purpose = table.Column(type: "INTEGER", nullable: false), + Username = table.Column(type: "TEXT", maxLength: 32, nullable: false), + Email = table.Column(type: "TEXT", maxLength: 128, nullable: false), + Code = table.Column(type: "TEXT", maxLength: 16, nullable: false), + ExpiresAt = table.Column(type: "TEXT", nullable: false), + UsedAt = table.Column(type: "TEXT", nullable: true), + CreatedAt = table.Column(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(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + GoodsId = table.Column(type: "INTEGER", nullable: false), + Currency = table.Column(type: "TEXT", maxLength: 16, nullable: false), + Price = table.Column(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(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + OfferId = table.Column(type: "INTEGER", nullable: false), + Side = table.Column(type: "TEXT", maxLength: 16, nullable: false), + ItemGuid = table.Column(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(type: "INTEGER", nullable: false), + PermissionId = table.Column(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(type: "INTEGER", nullable: false), + GoodsId = table.Column(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(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + UserId = table.Column(type: "INTEGER", nullable: false), + TokenHash = table.Column(type: "TEXT", maxLength: 128, nullable: false), + Endpoint = table.Column(type: "TEXT", maxLength: 16, nullable: false), + Device = table.Column(type: "TEXT", maxLength: 64, nullable: false), + IpAddress = table.Column(type: "TEXT", maxLength: 64, nullable: false), + UserAgent = table.Column(type: "TEXT", maxLength: 256, nullable: false), + ExpiresAt = table.Column(type: "TEXT", nullable: false), + RevokedAt = table.Column(type: "TEXT", nullable: true), + CreatedAt = table.Column(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(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + UserId = table.Column(type: "INTEGER", nullable: false), + Signature = table.Column(type: "TEXT", maxLength: 256, nullable: false), + PreferencesJson = table.Column(type: "TEXT", nullable: false), + UpdatedAt = table.Column(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(type: "INTEGER", nullable: false), + RoleId = table.Column(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(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + UserId = table.Column(type: "INTEGER", nullable: false), + Endpoint = table.Column(type: "TEXT", maxLength: 16, nullable: false), + Device = table.Column(type: "TEXT", maxLength: 64, nullable: false), + IpAddress = table.Column(type: "TEXT", maxLength: 64, nullable: false), + UserAgent = table.Column(type: "TEXT", maxLength: 256, nullable: false), + AccessTokenId = table.Column(type: "TEXT", maxLength: 64, nullable: false), + ConnectedAt = table.Column(type: "TEXT", nullable: false), + LastActiveAt = table.Column(type: "TEXT", nullable: false), + DisconnectedAt = table.Column(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" }); + } + + /// + 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"); + } + } +} diff --git a/src/FunGame.Server.Infrastructure/Migrations/Sqlite/20260822050723_AddContentModule.Designer.cs b/src/FunGame.Server.Infrastructure/Migrations/Sqlite/20260822050723_AddContentModule.Designer.cs new file mode 100644 index 0000000..13d9557 --- /dev/null +++ b/src/FunGame.Server.Infrastructure/Migrations/Sqlite/20260822050723_AddContentModule.Designer.cs @@ -0,0 +1,1122 @@ +// +using System; +using FunGame.Server.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace FunGame.Server.Infrastructure.Migrations.Sqlite +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260822050723_AddContentModule")] + partial class AddContentModule + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.Goods", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("IsEnabled") + .HasColumnType("INTEGER"); + + b.Property("ItemJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Stock") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.ToTable("goods", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.GoodsPrice", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("GoodsId") + .HasColumnType("INTEGER"); + + b.Property("Price") + .HasColumnType("REAL"); + + b.HasKey("Id"); + + b.HasIndex("GoodsId"); + + b.ToTable("goods_prices", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.MarketItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("ItemGuid") + .HasColumnType("TEXT"); + + b.Property("Price") + .HasColumnType("REAL"); + + b.Property("SellerUserId") + .HasColumnType("INTEGER"); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("Stock") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ItemGuid"); + + b.HasIndex("SellerUserId"); + + b.ToTable("market_items", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.Offer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("FinishedAt") + .HasColumnType("TEXT"); + + b.Property("NegotiatedTimes") + .HasColumnType("INTEGER"); + + b.Property("OffereeUserId") + .HasColumnType("INTEGER"); + + b.Property("OfferorUserId") + .HasColumnType("INTEGER"); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("OfferorUserId", "OffereeUserId"); + + b.ToTable("offers", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.OfferItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ItemGuid") + .HasColumnType("TEXT"); + + b.Property("OfferId") + .HasColumnType("INTEGER"); + + b.Property("Side") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("OfferId"); + + b.ToTable("offer_items", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.Store", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsEnabled") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("stores", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.StoreGoods", b => + { + b.Property("StoreId") + .HasColumnType("INTEGER"); + + b.Property("GoodsId") + .HasColumnType("INTEGER"); + + b.HasKey("StoreId", "GoodsId"); + + b.HasIndex("GoodsId"); + + b.ToTable("store_goods", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Game.GameRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ArchivePath") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("EndedAt") + .HasColumnType("TEXT"); + + b.Property("Map") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("MatchType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Mode") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("QueueId") + .HasColumnType("TEXT"); + + b.Property("StartedAt") + .HasColumnType("TEXT"); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("TotalRounds") + .HasColumnType("INTEGER"); + + b.Property("Winner") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("QueueId") + .IsUnique(); + + b.HasIndex("StartedAt"); + + b.ToTable("game_records", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Game.Inventory", b => + { + b.Property("UserId") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Credits") + .HasColumnType("REAL"); + + b.Property("Materials") + .HasColumnType("REAL"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("UserId"); + + b.ToTable("inventories", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Game.RoomEntity", b => + { + b.Property("RoomId") + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ContentModule") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("GameMap") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("GameModule") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("IsRank") + .HasColumnType("INTEGER"); + + b.Property("MasterUserId") + .HasColumnType("INTEGER"); + + b.Property("MaxUsers") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("RoomId"); + + b.HasIndex("State"); + + b.ToTable("rooms", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Game.RoundRecordEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ActorGuid") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ActorName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("GameId") + .HasColumnType("TEXT"); + + b.Property("HasKill") + .HasColumnType("INTEGER"); + + b.Property("IsCheckpoint") + .HasColumnType("INTEGER"); + + b.Property("RecordJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Round") + .HasColumnType("INTEGER"); + + b.Property("TotalDamage") + .HasColumnType("REAL"); + + b.Property("TotalHeal") + .HasColumnType("REAL"); + + b.HasKey("Id"); + + b.HasIndex("GameId", "Round") + .IsUnique(); + + b.ToTable("round_records", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Game.UserCharacter", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CharacterJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("IsDefault") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_characters", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Game.UserItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Count") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("ItemJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_items", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.ApiToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("ExpiresAt") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reference1") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Reference2") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RevokedAt") + .HasColumnType("TEXT"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("TokenId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TokenId") + .IsUnique(); + + b.ToTable("api_tokens", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.LoginLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Device") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Success") + .HasColumnType("INTEGER"); + + b.Property("UserAgent") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "CreatedAt"); + + b.ToTable("login_logs", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.Permission", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Group") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Code") + .IsUnique(); + + b.ToTable("permissions", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.RefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Device") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Endpoint") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ExpiresAt") + .HasColumnType("TEXT"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RevokedAt") + .HasColumnType("TEXT"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("UserAgent") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("refresh_tokens", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.Role", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsSystem") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Code") + .IsUnique(); + + b.ToTable("roles", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.RolePermission", b => + { + b.Property("RoleId") + .HasColumnType("INTEGER"); + + b.Property("PermissionId") + .HasColumnType("INTEGER"); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.ToTable("role_permissions", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Avatar") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("EmailVerified") + .HasColumnType("INTEGER"); + + b.Property("IsSystem") + .HasColumnType("INTEGER"); + + b.Property("LastLoginAt") + .HasColumnType("TEXT"); + + b.Property("LastLoginIp") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Nickname") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Status") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Email"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("users", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.UserProfile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PreferencesJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Signature") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("user_profiles", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.UserRole", b => + { + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.Property("RoleId") + .HasColumnType("INTEGER"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.UserSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AccessTokenId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ConnectedAt") + .HasColumnType("TEXT"); + + b.Property("Device") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("DisconnectedAt") + .HasColumnType("TEXT"); + + b.Property("Endpoint") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("LastActiveAt") + .HasColumnType("TEXT"); + + b.Property("UserAgent") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "Endpoint"); + + b.ToTable("user_sessions", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.System.ServerLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Exception") + .HasColumnType("TEXT"); + + b.Property("Level") + .HasColumnType("INTEGER"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("Level"); + + b.ToTable("server_logs", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.System.SystemConfig", b => + { + b.Property("Key") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("Value") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("system_configs", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.System.UserSignIn", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Days") + .HasColumnType("INTEGER"); + + b.Property("IsSigned") + .HasColumnType("INTEGER"); + + b.Property("LastTime") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("user_sign_ins", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.System.VerifyCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ExpiresAt") + .HasColumnType("TEXT"); + + b.Property("Purpose") + .HasColumnType("INTEGER"); + + b.Property("UsedAt") + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Purpose", "Username"); + + b.ToTable("verify_codes", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.GoodsPrice", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Economy.Goods", "Goods") + .WithMany("Prices") + .HasForeignKey("GoodsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Goods"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.OfferItem", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Economy.Offer", "Offer") + .WithMany("Items") + .HasForeignKey("OfferId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Offer"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.StoreGoods", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Economy.Goods", "Goods") + .WithMany("StoreGoods") + .HasForeignKey("GoodsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FunGame.Server.Infrastructure.Entities.Economy.Store", "Store") + .WithMany("StoreGoods") + .HasForeignKey("StoreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Goods"); + + b.Navigation("Store"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.RefreshToken", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.User", "User") + .WithMany("RefreshTokens") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.RolePermission", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.Permission", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.Role", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.UserProfile", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.User", "User") + .WithOne("Profile") + .HasForeignKey("FunGame.Server.Infrastructure.Entities.Identity.UserProfile", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.UserRole", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.Role", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.User", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.UserSession", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.User", "User") + .WithMany("Sessions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.Goods", b => + { + b.Navigation("Prices"); + + b.Navigation("StoreGoods"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.Offer", b => + { + b.Navigation("Items"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.Store", b => + { + b.Navigation("StoreGoods"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.Permission", b => + { + b.Navigation("RolePermissions"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.Role", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.User", b => + { + b.Navigation("Profile"); + + b.Navigation("RefreshTokens"); + + b.Navigation("Sessions"); + + b.Navigation("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/FunGame.Server.Infrastructure/Migrations/Sqlite/20260822050723_AddContentModule.cs b/src/FunGame.Server.Infrastructure/Migrations/Sqlite/20260822050723_AddContentModule.cs new file mode 100644 index 0000000..54f734f --- /dev/null +++ b/src/FunGame.Server.Infrastructure/Migrations/Sqlite/20260822050723_AddContentModule.cs @@ -0,0 +1,30 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace FunGame.Server.Infrastructure.Migrations.Sqlite +{ + /// + public partial class AddContentModule : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ContentModule", + table: "rooms", + type: "TEXT", + maxLength: 64, + nullable: false, + defaultValue: ""); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "ContentModule", + table: "rooms"); + } + } +} diff --git a/src/FunGame.Server.Infrastructure/Migrations/Sqlite/AppDbContextModelSnapshot.cs b/src/FunGame.Server.Infrastructure/Migrations/Sqlite/AppDbContextModelSnapshot.cs new file mode 100644 index 0000000..8c43a7c --- /dev/null +++ b/src/FunGame.Server.Infrastructure/Migrations/Sqlite/AppDbContextModelSnapshot.cs @@ -0,0 +1,1119 @@ +// +using System; +using FunGame.Server.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace FunGame.Server.Infrastructure.Migrations.Sqlite +{ + [DbContext(typeof(AppDbContext))] + partial class AppDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.Goods", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("IsEnabled") + .HasColumnType("INTEGER"); + + b.Property("ItemJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Stock") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.ToTable("goods", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.GoodsPrice", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("GoodsId") + .HasColumnType("INTEGER"); + + b.Property("Price") + .HasColumnType("REAL"); + + b.HasKey("Id"); + + b.HasIndex("GoodsId"); + + b.ToTable("goods_prices", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.MarketItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("ItemGuid") + .HasColumnType("TEXT"); + + b.Property("Price") + .HasColumnType("REAL"); + + b.Property("SellerUserId") + .HasColumnType("INTEGER"); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("Stock") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ItemGuid"); + + b.HasIndex("SellerUserId"); + + b.ToTable("market_items", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.Offer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("FinishedAt") + .HasColumnType("TEXT"); + + b.Property("NegotiatedTimes") + .HasColumnType("INTEGER"); + + b.Property("OffereeUserId") + .HasColumnType("INTEGER"); + + b.Property("OfferorUserId") + .HasColumnType("INTEGER"); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("OfferorUserId", "OffereeUserId"); + + b.ToTable("offers", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.OfferItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ItemGuid") + .HasColumnType("TEXT"); + + b.Property("OfferId") + .HasColumnType("INTEGER"); + + b.Property("Side") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("OfferId"); + + b.ToTable("offer_items", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.Store", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsEnabled") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("stores", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.StoreGoods", b => + { + b.Property("StoreId") + .HasColumnType("INTEGER"); + + b.Property("GoodsId") + .HasColumnType("INTEGER"); + + b.HasKey("StoreId", "GoodsId"); + + b.HasIndex("GoodsId"); + + b.ToTable("store_goods", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Game.GameRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ArchivePath") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("EndedAt") + .HasColumnType("TEXT"); + + b.Property("Map") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("MatchType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Mode") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("QueueId") + .HasColumnType("TEXT"); + + b.Property("StartedAt") + .HasColumnType("TEXT"); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("TotalRounds") + .HasColumnType("INTEGER"); + + b.Property("Winner") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("QueueId") + .IsUnique(); + + b.HasIndex("StartedAt"); + + b.ToTable("game_records", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Game.Inventory", b => + { + b.Property("UserId") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Credits") + .HasColumnType("REAL"); + + b.Property("Materials") + .HasColumnType("REAL"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("UserId"); + + b.ToTable("inventories", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Game.RoomEntity", b => + { + b.Property("RoomId") + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ContentModule") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("GameMap") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("GameModule") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("IsRank") + .HasColumnType("INTEGER"); + + b.Property("MasterUserId") + .HasColumnType("INTEGER"); + + b.Property("MaxUsers") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("State") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("RoomId"); + + b.HasIndex("State"); + + b.ToTable("rooms", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Game.RoundRecordEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ActorGuid") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ActorName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("GameId") + .HasColumnType("TEXT"); + + b.Property("HasKill") + .HasColumnType("INTEGER"); + + b.Property("IsCheckpoint") + .HasColumnType("INTEGER"); + + b.Property("RecordJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Round") + .HasColumnType("INTEGER"); + + b.Property("TotalDamage") + .HasColumnType("REAL"); + + b.Property("TotalHeal") + .HasColumnType("REAL"); + + b.HasKey("Id"); + + b.HasIndex("GameId", "Round") + .IsUnique(); + + b.ToTable("round_records", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Game.UserCharacter", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CharacterJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("IsDefault") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_characters", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Game.UserItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Count") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("ItemJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_items", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.ApiToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("ExpiresAt") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reference1") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Reference2") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("RevokedAt") + .HasColumnType("TEXT"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("TokenId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TokenId") + .IsUnique(); + + b.ToTable("api_tokens", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.LoginLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Device") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Reason") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Success") + .HasColumnType("INTEGER"); + + b.Property("UserAgent") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "CreatedAt"); + + b.ToTable("login_logs", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.Permission", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Group") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Code") + .IsUnique(); + + b.ToTable("permissions", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.RefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Device") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Endpoint") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("ExpiresAt") + .HasColumnType("TEXT"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("RevokedAt") + .HasColumnType("TEXT"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("UserAgent") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("refresh_tokens", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.Role", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("IsSystem") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Code") + .IsUnique(); + + b.ToTable("roles", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.RolePermission", b => + { + b.Property("RoleId") + .HasColumnType("INTEGER"); + + b.Property("PermissionId") + .HasColumnType("INTEGER"); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.ToTable("role_permissions", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Avatar") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("EmailVerified") + .HasColumnType("INTEGER"); + + b.Property("IsSystem") + .HasColumnType("INTEGER"); + + b.Property("LastLoginAt") + .HasColumnType("TEXT"); + + b.Property("LastLoginIp") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Nickname") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Status") + .HasColumnType("INTEGER"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Email"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("users", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.UserProfile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("PreferencesJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Signature") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("user_profiles", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.UserRole", b => + { + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.Property("RoleId") + .HasColumnType("INTEGER"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.UserSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AccessTokenId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("ConnectedAt") + .HasColumnType("TEXT"); + + b.Property("Device") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("DisconnectedAt") + .HasColumnType("TEXT"); + + b.Property("Endpoint") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("LastActiveAt") + .HasColumnType("TEXT"); + + b.Property("UserAgent") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "Endpoint"); + + b.ToTable("user_sessions", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.System.ServerLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Exception") + .HasColumnType("TEXT"); + + b.Property("Level") + .HasColumnType("INTEGER"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("TEXT"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("Level"); + + b.ToTable("server_logs", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.System.SystemConfig", b => + { + b.Property("Key") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Description") + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.Property("Value") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("system_configs", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.System.UserSignIn", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Days") + .HasColumnType("INTEGER"); + + b.Property("IsSigned") + .HasColumnType("INTEGER"); + + b.Property("LastTime") + .HasColumnType("TEXT"); + + b.Property("UserId") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("user_sign_ins", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.System.VerifyCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ExpiresAt") + .HasColumnType("TEXT"); + + b.Property("Purpose") + .HasColumnType("INTEGER"); + + b.Property("UsedAt") + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Purpose", "Username"); + + b.ToTable("verify_codes", (string)null); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.GoodsPrice", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Economy.Goods", "Goods") + .WithMany("Prices") + .HasForeignKey("GoodsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Goods"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.OfferItem", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Economy.Offer", "Offer") + .WithMany("Items") + .HasForeignKey("OfferId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Offer"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.StoreGoods", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Economy.Goods", "Goods") + .WithMany("StoreGoods") + .HasForeignKey("GoodsId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FunGame.Server.Infrastructure.Entities.Economy.Store", "Store") + .WithMany("StoreGoods") + .HasForeignKey("StoreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Goods"); + + b.Navigation("Store"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.RefreshToken", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.User", "User") + .WithMany("RefreshTokens") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.RolePermission", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.Permission", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.Role", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.UserProfile", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.User", "User") + .WithOne("Profile") + .HasForeignKey("FunGame.Server.Infrastructure.Entities.Identity.UserProfile", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.UserRole", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.Role", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.User", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.UserSession", b => + { + b.HasOne("FunGame.Server.Infrastructure.Entities.Identity.User", "User") + .WithMany("Sessions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.Goods", b => + { + b.Navigation("Prices"); + + b.Navigation("StoreGoods"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.Offer", b => + { + b.Navigation("Items"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Economy.Store", b => + { + b.Navigation("StoreGoods"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.Permission", b => + { + b.Navigation("RolePermissions"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.Role", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("FunGame.Server.Infrastructure.Entities.Identity.User", b => + { + b.Navigation("Profile"); + + b.Navigation("RefreshTokens"); + + b.Navigation("Sessions"); + + b.Navigation("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/FunGame.Server.PluginHost/FunGame.Server.PluginHost.csproj b/src/FunGame.Server.PluginHost/FunGame.Server.PluginHost.csproj new file mode 100644 index 0000000..e1e9544 --- /dev/null +++ b/src/FunGame.Server.PluginHost/FunGame.Server.PluginHost.csproj @@ -0,0 +1,18 @@ + + + + + + + + net10.0 + enable + enable + FunGame.Server.PluginHost + + + + + + + diff --git a/src/FunGame.Server.PluginHost/PluginDescriptor.cs b/src/FunGame.Server.PluginHost/PluginDescriptor.cs new file mode 100644 index 0000000..0c3f75a --- /dev/null +++ b/src/FunGame.Server.PluginHost/PluginDescriptor.cs @@ -0,0 +1,58 @@ +using FunGame.Server.Contracts.Plugins; + +namespace FunGame.Server.PluginHost; + +/// 加载项类型 +public enum PluginKind +{ + ServerPlugin, + CharacterModule, + SkillModule, + ItemModule, + GameModuleServer +} + +/// 加载项状态 +public enum PluginStatus +{ + Unloaded, + Loading, + Loaded, + Unloading, + Failed +} + +/// +/// 加载项描述(插件/模组的运行时清单) +/// +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; } + + /// 加载上下文(卸载后置空) + public PluginLoadContext? LoadContext { get; set; } + + /// 影子副本路径(实际加载的程序集;卸载后可安全删除) + public string? ShadowPath { get; set; } + + /// 加载项实例 + public IPluginBase? Instance { get; set; } + + /// 用于确认上下文可回收 + public WeakReference? InstanceWeakReference { get; set; } + + /// 活跃对局引用计数(大于 0 时禁止卸载);字段以便 Interlocked 原子操作 + public int ActiveGames; + + /// 是否为实体模组(ICharacterModule/ISkillModule/IItemModule) + public bool IsEntityModule => Kind is PluginKind.CharacterModule or PluginKind.SkillModule or PluginKind.ItemModule; +} diff --git a/src/FunGame.Server.PluginHost/PluginLoadContext.cs b/src/FunGame.Server.PluginHost/PluginLoadContext.cs new file mode 100644 index 0000000..ab80da8 --- /dev/null +++ b/src/FunGame.Server.PluginHost/PluginLoadContext.cs @@ -0,0 +1,64 @@ +using System.Reflection; +using System.Runtime.Loader; + +namespace FunGame.Server.PluginHost; + +/// +/// 插件专用可回收加载上下文(每个加载项一个实例,热重载时整体卸载) +/// 共享程序集(FunGame.Core / Contracts / Infrastructure / PluginHost / ASP.NET Core)回退到默认上下文解析, +/// 插件自有依赖从插件所在目录解析。 +/// +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; + } +} diff --git a/src/FunGame.Server.PluginHost/PluginManager.cs b/src/FunGame.Server.PluginHost/PluginManager.cs new file mode 100644 index 0000000..6f8b52a --- /dev/null +++ b/src/FunGame.Server.PluginHost/PluginManager.cs @@ -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; + +/// +/// 加载项管理器:始终热重载的插件/模组加载系统 +/// - 服务器插件(IServerPlugin)从 plugins/ 加载 +/// - 角色/技能/物品模组(ICharacterModule/ISkillModule/IItemModule)从 modules/ 对应子目录加载 +/// - 每个 DLL 一个可回收 AssemblyLoadContext;同一 DLL 可包含多个加载项类型(各成一个加载项) +/// - 支持手动/文件监视自动热重载;活跃对局引用的插件禁止卸载(引用计数) +/// +public sealed class PluginManager : IDisposable +{ + private readonly ILogger _logger; + private readonly IServiceProvider _services; + private readonly IWebHostEnvironment _environment; + private readonly IMessageHandlerRegistry _messageRegistry; + private readonly IPluginHttpHandlerRegistry _httpRegistry; + + private readonly ConcurrentDictionary _items = new(StringComparer.OrdinalIgnoreCase); + private readonly ConcurrentDictionary> _contextNames = []; + private readonly object _sync = new(); + private readonly Dictionary _handledWrites = []; + private FileSystemWatcher? _watcher; + private System.Threading.Timer? _reloadDebounce; + private readonly HashSet _pendingReloads = []; + private bool _disposed; + + public PluginManager( + IServiceProvider services, + IWebHostEnvironment environment, + IMessageHandlerRegistry messageRegistry, + IPluginHttpHandlerRegistry httpRegistry, + ILogger 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 Items => _items.Values; + + public PluginDescriptor? GetPlugin(string name) => _items.TryGetValue(name, out PluginDescriptor? descriptor) ? descriptor : null; + + /// 按模式名查找服务器插件 + public IServerPlugin? GetServerPlugin(string name) + => _items.TryGetValue(name, out PluginDescriptor? descriptor) && descriptor.Instance is IServerPlugin plugin ? plugin : null; + + /// 按游戏模式名查找游戏模式模组(GameModuleServer) + public IGameModuleServer? GetGameModule(string name) + => _items.TryGetValue(name, out PluginDescriptor? descriptor) && descriptor.Instance is IGameModuleServer module ? module : null; + + /// 聚合全部已加载实体模组提供的实体(供对局准备使用) + public IEnumerable GetModuleEntities() where T : BaseEntity + => _items.Values + .Where(d => d.Status == PluginStatus.Loaded && d.Instance is IEntityModule) + .SelectMany(d => ((IEntityModule)d.Instance!).Entities.Values); + + /// + /// 按模组名前缀获取实体(如 "oshima" 匹配 oshima.characters / oshima.skills / oshima.items) + /// 用于"所选模组创建对局":角色/技能/物品只从指定模组族产生 + /// + public IEnumerable GetModuleEntities(string modulePrefix) where T : BaseEntity + => _items.Values + .Where(d => d.Status == PluginStatus.Loaded && d.Instance is IEntityModule + && d.Name.StartsWith($"{modulePrefix}.", StringComparison.OrdinalIgnoreCase)) + .SelectMany(d => ((IEntityModule)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); + } + + /// 启动时把暂存区文件提升到正式目录(覆盖),随后正常扫描加载 + 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); + } + } + } + + /// 加载一个 DLL 中指定 kind 的全部加载项类型(影子加载:正式文件不锁定,可热替换) + public IReadOnlyList LoadDll(string assemblyPath, PluginKind kind) + { + lock (_sync) + { + List 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 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? names) && names.Count == 0) + { + _contextNames.TryRemove(context, out _); + context.Unload(); + TryDelete(shadowPath); + } + + return loaded; + } + } + + /// 创建影子副本(_loaded/{name}.{guid}.dll),返回影子路径;失败返回空串 + 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; + } + + // ===== 卸载 / 重载 ===== + + /// 卸载(被活跃对局引用时抛出) + 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? 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); + } + } + + /// 热重载指定加载项 + 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,宿主原子热替换) ===== + + /// 暂存区目录名 + 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); + } + } + } + + /// + /// 处理暂存区新文件:卸载同名已加载项(释放文件锁)→ 原子替换正式目录 → 重新加载 + /// + 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 FindPluginTypes(Assembly assembly, PluginKind kind) + { + Type[] types; + try + { + types = assembly.GetTypes(); + } + catch (ReflectionTypeLoadException e) + { + types = e.Types.Where(t => t != null).Cast().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); + } + } +} diff --git a/webui/.gitignore b/webui/.gitignore new file mode 100644 index 0000000..a547bf3 --- /dev/null +++ b/webui/.gitignore @@ -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? diff --git a/webui/.oxlintrc.json b/webui/.oxlintrc.json new file mode 100644 index 0000000..6fa991d --- /dev/null +++ b/webui/.oxlintrc.json @@ -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 }] + } +} diff --git a/webui/README.md b/webui/README.md new file mode 100644 index 0000000..d6af7e3 --- /dev/null +++ b/webui/README.md @@ -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. diff --git a/webui/Web.config b/webui/Web.config new file mode 100644 index 0000000..9704c86 --- /dev/null +++ b/webui/Web.config @@ -0,0 +1,15 @@ + + + + + + + + \ No newline at end of file diff --git a/webui/index.html b/webui/index.html new file mode 100644 index 0000000..72d8b06 --- /dev/null +++ b/webui/index.html @@ -0,0 +1,13 @@ + + + + + + + FunGame Server v3 管理控制台 + + +
+ + + diff --git a/webui/package-lock.json b/webui/package-lock.json new file mode 100644 index 0000000..c82c51c --- /dev/null +++ b/webui/package-lock.json @@ -0,0 +1,1921 @@ +{ + "name": "webui", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "webui", + "version": "0.0.0", + "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" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmmirror.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmmirror.com/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmmirror.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmmirror.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmmirror.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.144.0", + "resolved": "https://registry.npmmirror.com/@oxc-project/types/-/types-0.144.0.tgz", + "integrity": "sha512-nuhZIOLuI6TFQ32I/WnUx+SCPY7SdSKwgnFHydAuoS1+Z4BRcaP+RRJmGzl9lw+0OFF7UmaESf7KQRXaNLHypg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/Boshen" + } + }, + "node_modules/@oxlint/binding-android-arm-eabi": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.78.0.tgz", + "integrity": "sha512-Bu819lmAfZMUHErrpe0cEWj3iaefuUODHSU8+UbXy67V/r7/7f4K3FL0NmbD85E+wiFLDYuhP8Zlv0XnVeXshw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-android-arm64": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-android-arm64/-/binding-android-arm64-1.78.0.tgz", + "integrity": "sha512-CDfxZgB61B7buRdY2FJoAYYPPXCZ1EoC1LKscnC5dg3kjobdxiconvAvvN1BmHyW4PyFT3jRLDag/BY/roSNBQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-darwin-arm64": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.78.0.tgz", + "integrity": "sha512-2Y2U9Ahrz+OO0Ej88f9SJYq51/jUBp1Mc7iZu0ukrbeeZ3gpRGfzIFnoqfHDY96xr0GEfNrPUBFEy0nN5aD7HA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-darwin-x64": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.78.0.tgz", + "integrity": "sha512-rpych6eJq6m9jDRypTEaPD1xysaEW5h9+xuxhGK/QhOg+/xaqPZrCrTNoIl/f3nEjuJeCEmstNDlrE9rJi/3/g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-freebsd-x64": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.78.0.tgz", + "integrity": "sha512-IcMGrQT3QizkOESUJd5et+rOhVqSkNDfNik1cvrKDqIbzqx9KMtRswpFgkCuNTSwylCFLKhGUu8KmqY1ZnC0Dg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm-gnueabihf": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.78.0.tgz", + "integrity": "sha512-/uLdoJ0IXE6vo/0f0LKjinQAp+re+VMaCWaNT8ENIv2EOCkSsc8SGaflXAuW0Jua2dq5+GLVWm1NQK7P3UFSNQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm-musleabihf": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.78.0.tgz", + "integrity": "sha512-7xi4Wb/O8NRJhLoUXmDJMUVpNYvB5kefdhFU1Jb8rtae4QoXlTiLwI14X4YvAXVZLNZChP8m5qO9SQAlWQTbkQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm64-gnu": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.78.0.tgz", + "integrity": "sha512-4hFW0+fVXa3OIh1Y4A5SPkmvI4wuuBSrCVKzOyE7PTjhc7yEqZ1pmvEEeS5Lj/MaqvegFxXyF33N+6jkehxdyg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm64-musl": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.78.0.tgz", + "integrity": "sha512-oC0mvsgBJjlMijSDEhx9KuvR9zYeHXceA9MjbuXB1F8NSR78Yj2unOBrstEvTVaq+pko+kuue6DajC00eqvTdg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-ppc64-gnu": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.78.0.tgz", + "integrity": "sha512-XAllT5SUZS+ohjuZ3/5S0cwe0r7eboiuigeStCZ5DXRYx/2KVM2UvQXvAfyzXEimtQjAB7cDQ2YxDe2Zl2WNQQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-riscv64-gnu": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.78.0.tgz", + "integrity": "sha512-trucMER/0QtecoXvc1y/UVqE3kwJipDwrx4oHfj+nNm3dq2zjP44WT0CfHNDPM3G1DXIkx/gY6lAD21NSCZVhA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-riscv64-musl": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.78.0.tgz", + "integrity": "sha512-cm3O4F/HQbdzOUX5mKHqG5KDL6E5w0pnlZ+fbBy2rmLryPOowkuLagFHTopQsEIpjcaZoPOrL+BmmAytAG9HFg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-s390x-gnu": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.78.0.tgz", + "integrity": "sha512-33wRf6HqGNsybJ3qX4cGaQN2ODPxNmc1rMa0mrTmx3eFq1VzOnvQooi9bIGVYakW8a/wmqVx1mgsUm8R2xfTiw==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-x64-gnu": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.78.0.tgz", + "integrity": "sha512-rRdISSYegj6VganMZ9tjRjijowfHJ09IZU01i0toBAqr6n5LEtwHq2IeS4FjW2RoskOHlb6efB26H5izYb3GEQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-x64-musl": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.78.0.tgz", + "integrity": "sha512-GmsP4rW0xTL6u5CVdcDsaN5Fbc7hBc382Wmar1kttbnwSEviM+rSINKOMQ+UQ6iH+AGwC+8gaAiwu134Tgh6Lg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-openharmony-arm64": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.78.0.tgz", + "integrity": "sha512-sy9yeYuADc8a+n4TLBayzMCZiHPW78DcIFVpOXTmdKHWQeM9xe5uzkqIIZmi326D5hY9XVwacipEB1p7tQjPAg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-win32-arm64-msvc": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.78.0.tgz", + "integrity": "sha512-rjc2hF1KfMi8fZj1X/m3AmnHbdsF3rL0v6KQg0Uc880Yb2khjz+3U14sfdZ7jWTpRnN1m1NQa/TT7uU9lJWPrA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-win32-ia32-msvc": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.78.0.tgz", + "integrity": "sha512-zcuXFVrEFHIafRfkCQT8w/Xe41o07ozl/vwHq7p94vB29xVzsB0sZGYORU1jhcYKv3Lr0J3HbJ2T4fHH5rWmvA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-win32-x64-msvc": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.78.0.tgz", + "integrity": "sha512-Sb5ocmLSuYeOuXd+CFOToGKp/gjXUEWDnvIGwhnh8aq8wY4TMmEnKnvbogSW7RdMZv77JSARduS7/gv+khYEjA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.4.tgz", + "integrity": "sha512-jHC2cnyKz5xU2fhECtFl8OZ83cYNt13GZQD+0uMJ/X3o+ijmd56okHhTUwxVSHPx1IRVIJEZ1/1pPzeLCU6XKA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.4.tgz", + "integrity": "sha512-Dc5mPD8F5F/FS8i01syd7FTF6yB2fVthH/TRkjwJkzUK6EpoxHtqvZQP5Zwq80/5z19TWYHIg1KOHboCgVx/aQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.4.tgz", + "integrity": "sha512-fpDm4oBo6SqLvWUYCmFhdde3U9KH2fRNNMeAnAPAIwxRL345xutL0EtEUcuoxsoazdJGv/MuDBQHlCDrtbvqOg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.4.tgz", + "integrity": "sha512-rSJoreDE/HoIzoaib6MTp5jQtCTdMHKIvItAKT/ImS6Y6Ww76oUaeMyp4Vc/fAgd/ehji068IxetHXAnqUwN9A==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.4", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.4.tgz", + "integrity": "sha512-/jm8OGHgn7oGaJu3i/qZI9spUGcJ+y/lk43ttQ/iO1tOd9NissG6o97bighBCiL+BKRngmcDuR6ikfwYdJmVuQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.4", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.4.tgz", + "integrity": "sha512-tIP06BeD9EqvECBrPZ+sqdPlYrT+aYaAiu1wYziVx5elRK/ftm33JxVDy2bXGbr6J0CrtirCkR87/X5a2euEng==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.4", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.4.tgz", + "integrity": "sha512-Ql1Q0EQqVThvn9VAVlwNzsUvbSFtCMGjLpRRi4pk5i7NZZ4n5ISiLMjHYtus4VQ2PvkSw24zyaCVsiS+sXPj1w==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.4", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.4.tgz", + "integrity": "sha512-GjbjXD4XXfN19D0LZNbmiCBUoDiRACsYHr0yaIbbn8aFsXjHZifcYqu/W5Er5X2X990WjHXFrxarn5chzItorQ==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.4", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.4.tgz", + "integrity": "sha512-p5WR0NOwaRmJ/B1b6IjEFLLivwEsf3PrdBIhRbhTCQisbo2SvHHpG4ELB/+FgQNnB88LTOF86upmJmbvZdQ2lw==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.4", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.4.tgz", + "integrity": "sha512-4/GyVjmhR+Tc6HLJvwc1sOhPqAZtySiSMesOZyX6JQ5XBxoTDEMKQzvo07NIK6nTon/SivlZqvhzvuVBNQhObQ==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.4", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.4.tgz", + "integrity": "sha512-l9eeLsCNvPpmSXUej0etw/J1eqV0Jj1D5G/xG6YTijmE6dkv6E2QezgWbTfQk63v952DPqrjOCoiqxq7Bw0YUQ==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.4.tgz", + "integrity": "sha512-e0F355MSTMm3+UOqtV3L24gFUp2N5m1f8L/7d56deik6va+AXdrt9F8LbzGpeWGWRbZEDq4m8NVnJDeBtf9DZg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.4", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.4.tgz", + "integrity": "sha512-AWLi0uBRYh6QlE7OKhiz+phZC0qwtij2QZmhmOdsLdFn64m7oMpooE9ICE3lhm9xMb4SpDo2WbHcxX1iFLFtqw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.4", + "resolved": "https://registry.npmmirror.com/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.4.tgz", + "integrity": "sha512-UwSDJOg3dqCAejWdxclJjCsh3Qq4vLYMDxmyHqo1btz3stK2VqgwNd3mm5tuIwzSlGIQ/1H9Hr+Zn09mrezNqQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "license": "MIT" + }, + "node_modules/@tailwindcss/node": { + "version": "4.3.3", + "resolved": "https://registry.npmmirror.com/@tailwindcss/node/-/node-4.3.3.tgz", + "integrity": "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg==", + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "^5.24.1", + "jiti": "^2.7.0", + "lightningcss": "1.32.0", + "magic-string": "^0.30.21", + "source-map-js": "^1.2.1", + "tailwindcss": "4.3.3" + } + }, + "node_modules/@tailwindcss/node/node_modules/lightningcss": { + "version": "1.32.0", + "resolved": "https://registry.npmmirror.com/lightningcss/-/lightningcss-1.32.0.tgz", + "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.32.0", + "lightningcss-darwin-arm64": "1.32.0", + "lightningcss-darwin-x64": "1.32.0", + "lightningcss-freebsd-x64": "1.32.0", + "lightningcss-linux-arm-gnueabihf": "1.32.0", + "lightningcss-linux-arm64-gnu": "1.32.0", + "lightningcss-linux-arm64-musl": "1.32.0", + "lightningcss-linux-x64-gnu": "1.32.0", + "lightningcss-linux-x64-musl": "1.32.0", + "lightningcss-win32-arm64-msvc": "1.32.0", + "lightningcss-win32-x64-msvc": "1.32.0" + } + }, + "node_modules/@tailwindcss/node/node_modules/lightningcss-android-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmmirror.com/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", + "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/node/node_modules/lightningcss-darwin-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmmirror.com/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", + "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/node/node_modules/lightningcss-darwin-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmmirror.com/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", + "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/node/node_modules/lightningcss-freebsd-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmmirror.com/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", + "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/node/node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.32.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", + "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", + "cpu": [ + "arm" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/node/node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", + "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/node/node_modules/lightningcss-linux-arm64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", + "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/node/node_modules/lightningcss-linux-x64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", + "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/node/node_modules/lightningcss-linux-x64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", + "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/node/node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmmirror.com/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", + "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/node/node_modules/lightningcss-win32-x64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmmirror.com/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", + "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.3.3", + "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide/-/oxide-4.3.3.tgz", + "integrity": "sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA==", + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.3.3", + "@tailwindcss/oxide-darwin-arm64": "4.3.3", + "@tailwindcss/oxide-darwin-x64": "4.3.3", + "@tailwindcss/oxide-freebsd-x64": "4.3.3", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.3", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.3", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.3", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.3", + "@tailwindcss/oxide-linux-x64-musl": "4.3.3", + "@tailwindcss/oxide-wasm32-wasi": "4.3.3", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.3", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.3" + } + }, + "node_modules/@tailwindcss/oxide-android-arm64": { + "version": "4.3.3", + "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.3.tgz", + "integrity": "sha512-Y85A2gmPSkl5Ve5qR86GL4HT509cFqQh1aes9p3sSkyTPwt0Pppf3GkwGe4JPACcRYjgJIEhQgM6dBClnr0NYw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-arm64": { + "version": "4.3.3", + "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.3.tgz", + "integrity": "sha512-BiaWatpBcERQFDlOjRDpIVXuFK5PJez5SA4JMg6VYZdBYU+qKfV/vqjcIs+IYmtitf1xYQZTwXvU/8y4lfZUGw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-x64": { + "version": "4.3.3", + "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.3.tgz", + "integrity": "sha512-fAeUqfV5ndhxRwai8cXGzdLvul9utWOmeTkv69unv4ZXixjn61Z+p9lCWdwOwA3TYboG3BwdVuN/RDjhBRl0mw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-freebsd-x64": { + "version": "4.3.3", + "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.3.tgz", + "integrity": "sha512-iyf5bV6+wnAlflVeEy7R25dupxTNECZN5QMI0qNT6eT+EgaGdZcKhGkr5SdoaWiLJ3spLqIY9VCeSGrwmtg4kw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.3.3", + "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.3.tgz", + "integrity": "sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.3.3", + "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.3.tgz", + "integrity": "sha512-nDxldcEENOxZRzC2uu9jrutZdAAQtb+8WWDCSnWL1zvBk1+FN+x6MtDViPB5AJMfttVCUhehGWus3XBPgatM/w==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.3.3", + "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.3.tgz", + "integrity": "sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.3.3", + "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.3.tgz", + "integrity": "sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-musl": { + "version": "4.3.3", + "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.3.tgz", + "integrity": "sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.3.3", + "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.3.tgz", + "integrity": "sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ==", + "bundleDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ], + "cpu": [ + "wasm32" + ], + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.11.1", + "@emnapi/runtime": "^1.11.1", + "@emnapi/wasi-threads": "^1.2.2", + "@napi-rs/wasm-runtime": "^1.1.4", + "@tybys/wasm-util": "^0.10.2", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.3.3", + "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz", + "integrity": "sha512-3rc292Ca2ceK6Ulcc/bAVnTs/3nDtoPhyEKlgPv+yQJQi/JS/AMJlqzxvlDacL1nekbrcf6bTqp/jV4qgnPxNQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.3.3", + "resolved": "https://registry.npmmirror.com/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.3.tgz", + "integrity": "sha512-yJ0pwIVc/nYeGoV02WtsN8KYyLQv7kyI2wDnkezyJlGGjkd4QLwDGAwl47YpPJeuI0M0ObaXGSPjvWDPeTPggw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/vite": { + "version": "4.3.3", + "resolved": "https://registry.npmmirror.com/@tailwindcss/vite/-/vite-4.3.3.tgz", + "integrity": "sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw==", + "license": "MIT", + "dependencies": { + "@tailwindcss/node": "4.3.3", + "@tailwindcss/oxide": "4.3.3", + "tailwindcss": "4.3.3" + }, + "peerDependencies": { + "vite": "^5.2.0 || ^6 || ^7 || ^8" + } + }, + "node_modules/@types/node": { + "version": "24.13.3", + "resolved": "https://registry.npmmirror.com/@types/node/-/node-24.13.3.tgz", + "integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.18.0" + } + }, + "node_modules/@types/react": { + "version": "19.2.18", + "resolved": "https://registry.npmmirror.com/@types/react/-/react-19.2.18.tgz", + "integrity": "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.2.4", + "resolved": "https://registry.npmmirror.com/@types/react-dom/-/react-dom-19.2.4.tgz", + "integrity": "sha512-Bsc+QHgp+P/F02XDzNCY9jnZNCUuLki36KT7VKrTXXLdHf+vHMNZnW1rVu5DNW/rCK+fya3DATySbLM4yhtKUw==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.2.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "6.0.5", + "resolved": "https://registry.npmmirror.com/@vitejs/plugin-react/-/plugin-react-6.0.5.tgz", + "integrity": "sha512-BOVzne/NL162sMdResB25mUv+vWMF5NoAjNf09TeGlE7ZpszZWSD3winycicLJw72yeVsoCn/2kOhEuCvEShMA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", + "babel-plugin-react-compiler": "^1.0.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + } + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmmirror.com/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/enhanced-resolve": { + "version": "5.24.5", + "resolved": "https://registry.npmmirror.com/enhanced-resolve/-/enhanced-resolve-5.24.5.tgz", + "integrity": "sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A==", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmmirror.com/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmmirror.com/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC" + }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmmirror.com/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmmirror.com/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmmirror.com/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/nanoid": { + "version": "3.3.18", + "resolved": "https://registry.npmmirror.com/nanoid/-/nanoid-3.3.18.tgz", + "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/oxlint": { + "version": "1.78.0", + "resolved": "https://registry.npmmirror.com/oxlint/-/oxlint-1.78.0.tgz", + "integrity": "sha512-QgQePuxIqKOzo1KSjG2EnITEeWvWnKAm77eq8nrMtf6AGoA+zyGc4PFYtDNJSD25g/ibOwfQ851hZ4/SPkMVoA==", + "dev": true, + "license": "MIT", + "bin": { + "oxlint": "bin/oxlint" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/Boshen" + }, + "optionalDependencies": { + "@oxlint/binding-android-arm-eabi": "1.78.0", + "@oxlint/binding-android-arm64": "1.78.0", + "@oxlint/binding-darwin-arm64": "1.78.0", + "@oxlint/binding-darwin-x64": "1.78.0", + "@oxlint/binding-freebsd-x64": "1.78.0", + "@oxlint/binding-linux-arm-gnueabihf": "1.78.0", + "@oxlint/binding-linux-arm-musleabihf": "1.78.0", + "@oxlint/binding-linux-arm64-gnu": "1.78.0", + "@oxlint/binding-linux-arm64-musl": "1.78.0", + "@oxlint/binding-linux-ppc64-gnu": "1.78.0", + "@oxlint/binding-linux-riscv64-gnu": "1.78.0", + "@oxlint/binding-linux-riscv64-musl": "1.78.0", + "@oxlint/binding-linux-s390x-gnu": "1.78.0", + "@oxlint/binding-linux-x64-gnu": "1.78.0", + "@oxlint/binding-linux-x64-musl": "1.78.0", + "@oxlint/binding-openharmony-arm64": "1.78.0", + "@oxlint/binding-win32-arm64-msvc": "1.78.0", + "@oxlint/binding-win32-ia32-msvc": "1.78.0", + "@oxlint/binding-win32-x64-msvc": "1.78.0" + }, + "peerDependencies": { + "oxlint-tsgolint": ">=7.0.2001", + "vite-plus": "*" + }, + "peerDependenciesMeta": { + "oxlint-tsgolint": { + "optional": true + }, + "vite-plus": { + "optional": true + } + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.5", + "resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-4.0.5.tgz", + "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.26", + "resolved": "https://registry.npmmirror.com/postcss/-/postcss-8.5.26.tgz", + "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.17", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "19.2.8", + "resolved": "https://registry.npmmirror.com/react/-/react-19.2.8.tgz", + "integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.2.8", + "resolved": "https://registry.npmmirror.com/react-dom/-/react-dom-19.2.8.tgz", + "integrity": "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.27.0" + }, + "peerDependencies": { + "react": "^19.2.8" + } + }, + "node_modules/rolldown": { + "version": "1.2.4", + "resolved": "https://registry.npmmirror.com/rolldown/-/rolldown-1.2.4.tgz", + "integrity": "sha512-rSr7irW0K7QRWzjdJXqZowkcRdDtjRduh43rBltnVKd0VFq839l1lJoDvGJb6gl7+4rTTCrPWu+YfujUL8Ug7w==", + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.144.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm64": "1.2.4", + "@rolldown/binding-darwin-arm64": "1.2.4", + "@rolldown/binding-darwin-x64": "1.2.4", + "@rolldown/binding-freebsd-x64": "1.2.4", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.4", + "@rolldown/binding-linux-arm64-gnu": "1.2.4", + "@rolldown/binding-linux-arm64-musl": "1.2.4", + "@rolldown/binding-linux-ppc64-gnu": "1.2.4", + "@rolldown/binding-linux-s390x-gnu": "1.2.4", + "@rolldown/binding-linux-x64-gnu": "1.2.4", + "@rolldown/binding-linux-x64-musl": "1.2.4", + "@rolldown/binding-openharmony-arm64": "1.2.4", + "@rolldown/binding-win32-arm64-msvc": "1.2.4", + "@rolldown/binding-win32-x64-msvc": "1.2.4" + } + }, + "node_modules/scheduler": { + "version": "0.27.0", + "resolved": "https://registry.npmmirror.com/scheduler/-/scheduler-0.27.0.tgz", + "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", + "license": "MIT" + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tailwindcss": { + "version": "4.3.3", + "resolved": "https://registry.npmmirror.com/tailwindcss/-/tailwindcss-4.3.3.tgz", + "integrity": "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==", + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.3.3", + "resolved": "https://registry.npmmirror.com/tapable/-/tapable-2.3.3.tgz", + "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==", + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmmirror.com/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "6.0.3", + "resolved": "https://registry.npmmirror.com/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.18.2", + "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-7.18.2.tgz", + "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "8.2.1", + "resolved": "https://registry.npmmirror.com/vite/-/vite-8.2.1.tgz", + "integrity": "sha512-EU/eS7BH3XROHh2YnBefjM6DBKA6ZeMZEYQbj7NLWg5wHYlhB8B/Mayd5XsgWq+NFYccDOTemRpdETWR6Ka/lw==", + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.5", + "postcss": "^8.5.25", + "rolldown": "~1.2.1", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.4.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + } + } +} diff --git a/webui/package.json b/webui/package.json new file mode 100644 index 0000000..418c874 --- /dev/null +++ b/webui/package.json @@ -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" + } +} diff --git a/webui/public/favicon.svg b/webui/public/favicon.svg new file mode 100644 index 0000000..6893eb1 --- /dev/null +++ b/webui/public/favicon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/webui/public/icons.svg b/webui/public/icons.svg new file mode 100644 index 0000000..e952219 --- /dev/null +++ b/webui/public/icons.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/webui/src/App.tsx b/webui/src/App.tsx new file mode 100644 index 0000000..377c3db --- /dev/null +++ b/webui/src/App.tsx @@ -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(null) + const [page, setPage] = useState('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 + } + + 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 ( +
+ +
+
+

+ {nav.find((n) => n.key === page)?.label} +

+
+ {session.username} + {session.permissions.length} 项权限 +
+
+ {page === 'dashboard' && } + {page === 'users' && } + {page === 'plugins' && } + {page === 'games' && } + {page === 'replay' && } + {page === 'logs' && } +
+
+ ) +} diff --git a/webui/src/api.ts b/webui/src/api.ts new file mode 100644 index 0000000..e3d32a7 --- /dev/null +++ b/webui/src/api.ts @@ -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 { + 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(path: string, options: RequestInit = {}, retry = true): Promise> { + 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(path, options, false) + } + if (res.status === 401 && !getToken()) { + clearTokens() + window.dispatchEvent(new Event('fungame:unauthorized')) + } + const body = (await res.json().catch(() => null)) as ApiResponse | 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 = (path: string) => api(path) +export const post = (path: string, body?: unknown) => api(path, { method: 'POST', body: JSON.stringify(body ?? {}) }) +export const put = (path: string, body?: unknown) => api(path, { method: 'PUT', body: JSON.stringify(body ?? {}) }) +export const del = (path: string) => api(path, { method: 'DELETE' }) diff --git a/webui/src/index.css b/webui/src/index.css new file mode 100644 index 0000000..f1d8c73 --- /dev/null +++ b/webui/src/index.css @@ -0,0 +1 @@ +@import "tailwindcss"; diff --git a/webui/src/main.tsx b/webui/src/main.tsx new file mode 100644 index 0000000..bef5202 --- /dev/null +++ b/webui/src/main.tsx @@ -0,0 +1,10 @@ +import { StrictMode } from 'react' +import { createRoot } from 'react-dom/client' +import './index.css' +import App from './App.tsx' + +createRoot(document.getElementById('root')!).render( + + + , +) diff --git a/webui/src/pages/Dashboard.tsx b/webui/src/pages/Dashboard.tsx new file mode 100644 index 0000000..c58cd7d --- /dev/null +++ b/webui/src/pages/Dashboard.tsx @@ -0,0 +1,77 @@ +import { useEffect, useState } from 'react' +import { get, getToken } from '../api' +import type { Overview } from '../types' + +// ===== 仪表盘:概览 + WebSocket 连通性检测 ===== + +export default function Dashboard() { + const [overview, setOverview] = useState(null) + const [wsStatus, setWsStatus] = useState<'connecting' | 'ok' | 'failed'>('connecting') + const [error, setError] = useState('') + + useEffect(() => { + get('/api/admin/server/overview').then((res) => { + if (res.ok) setOverview(res.data) + else setError(res.message ?? '加载失败') + }) + }, []) + + useEffect(() => { + const token = getToken() + if (!token) { + setWsStatus('failed') + return + } + const ws = new WebSocket(`${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/ws?access_token=${token}`) + ws.onopen = () => { + setWsStatus('ok') + ws.send(JSON.stringify({ t: 'system.ping', i: Date.now(), d: {} })) + } + ws.onerror = () => setWsStatus('failed') + ws.onclose = () => setWsStatus('failed') + return () => ws.close() + }, []) + + const cards = [ + { label: '在线连接', value: overview?.connections ?? '—', color: 'text-sky-400' }, + { label: '已认证连接', value: overview?.authenticated ?? '—', color: 'text-emerald-400' }, + { label: '注册用户', value: overview?.userCount ?? '—', color: 'text-indigo-400' }, + { label: '对局总数', value: overview?.gameCount ?? '—', color: 'text-amber-400' }, + { label: '进行中对局', value: overview?.runningGames ?? '—', color: 'text-rose-400' }, + ] + + return ( +
+

仪表盘

+ {error &&
{error}
} +
+ {cards.map((card) => ( +
+
{card.value}
+
{card.label}
+
+ ))} +
+
+
+ WebSocket 通道(/ws?access_token) + + + {wsStatus === 'ok' ? '已连接' : wsStatus === 'connecting' ? '连接中' : '不可用'} + +
+

+ WebUI / WebAPI / WebSocket 使用同一 JWT 认证体系(多端统一验证);令牌过期后通过 /api/auth/refresh 自动续期。 +

+
+
+ ) +} diff --git a/webui/src/pages/GamesPage.tsx b/webui/src/pages/GamesPage.tsx new file mode 100644 index 0000000..ba69b35 --- /dev/null +++ b/webui/src/pages/GamesPage.tsx @@ -0,0 +1,72 @@ +import { useEffect, useState } from 'react' +import { get, post } from '../api' +import type { GameInfo } from '../types' + +// ===== 对局管理:进行中对局监控与强制结束 ===== + +export default function GamesPage() { + const [games, setGames] = useState([]) + const [message, setMessage] = useState('') + + const load = () => { + get('/api/admin/server/games').then((res) => { + if (res.ok) setGames(res.data) + else setMessage(res.message ?? '加载失败') + }) + } + + useEffect(load, []) + + async function endGame(id: string) { + if (!confirm('确定强制结束此对局?')) return + const res = await post(`/api/admin/server/games/${id}/end`) + setMessage(res.ok ? '对局已结束。' : (res.message ?? '操作失败')) + load() + } + + return ( +
+

对局管理

+ {message &&
{message}
} + {games.length === 0 ? ( +
+ 当前没有进行中的对局。 +
+ ) : ( +
+ + + + + + + + + + + + + + {games.map((g) => ( + + + + + + + + + + ))} + +
对局 ID模式状态回合时长角色/会话操作
{g.id}{g.mode}{g.running ? 进行中 : 已结束}{g.totalRound}{g.totalTime.toFixed(1)}s{g.characters} / {g.clients} + {g.running && ( + + )} +
+
+ )} +

对局结束后,回合记录将归档到 records/ 并写入 game_records / round_records 表,可在回放中心查看。

+
+ ) +} diff --git a/webui/src/pages/LoginPage.tsx b/webui/src/pages/LoginPage.tsx new file mode 100644 index 0000000..5db2eb6 --- /dev/null +++ b/webui/src/pages/LoginPage.tsx @@ -0,0 +1,76 @@ +import { useEffect, useState } from 'react' +import { post, setTokens } from '../api' +import type { AuthTokenResponse } from '../types' + +// ===== 登录页(多端统一验证:与 WebAPI/WebSocket 共用 JWT) ===== + +export default function LoginPage({ onLogin }: { onLogin: (info: { username: string; permissions: string[] }) => void }) { + const [username, setUsername] = useState('admin') + const [password, setPassword] = useState('') + const [error, setError] = useState('') + const [busy, setBusy] = useState(false) + + useEffect(() => { + const handler = () => setError('登录已过期,请重新登录。') + window.addEventListener('fungame:unauthorized', handler) + return () => window.removeEventListener('fungame:unauthorized', handler) + }, []) + + async function submit(e: React.FormEvent) { + e.preventDefault() + setBusy(true) + setError('') + try { + const res = await post('/api/auth/login', { username, password, device: 'webui' }) + if (res.ok) { + setTokens(res.data.accessToken, res.data.refreshToken) + onLogin({ username: res.data.username, permissions: res.data.permissions }) + } else { + setError(res.message ?? '登录失败。') + } + } catch { + setError('无法连接到服务器。') + } finally { + setBusy(false) + } + } + + return ( +
+
+

FunGame Server v3

+

服务器管理控制台

+
+
+ + setUsername(e.target.value)} + autoComplete="username" + /> +
+
+ + setPassword(e.target.value)} + autoComplete="current-password" + /> +
+ {error &&
{error}
} + +
+

初始管理员账号由服务器首次启动时的 Bootstrap:Admin 配置创建

+
+
+ ) +} diff --git a/webui/src/pages/LogsPage.tsx b/webui/src/pages/LogsPage.tsx new file mode 100644 index 0000000..257a7ea --- /dev/null +++ b/webui/src/pages/LogsPage.tsx @@ -0,0 +1,65 @@ +import { useEffect, useState } from 'react' +import { get } from '../api' +import type { PagedData, ServerLog } from '../types' + +const levelText = ['TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRIT'] +const levelColor = ['text-slate-400', 'text-slate-400', 'text-sky-400', 'text-amber-400', 'text-red-400', 'text-rose-400'] + +// ===== 服务器日志(server_logs 表;结构化日志通道在 M7 接入) ===== + +export default function LogsPage() { + const [data, setData] = useState | null>(null) + const [page, setPage] = useState(1) + const [message, setMessage] = useState('') + + useEffect(() => { + get>(`/api/serverlogs?page=${page}&pageSize=20&desc=true`).then((res) => { + if (res.ok) setData(res.data) + else setMessage(res.message ?? '加载失败') + }) + }, [page]) + + return ( +
+

服务器日志

+ {message &&
{message}
} + {data && data.items.length === 0 ? ( +
+ 暂无日志记录。宿主结构化日志写入 server_logs 表的功能将在后续里程碑接入。 +
+ ) : ( +
+ + + + + + + + + + + + {data?.items.map((log) => ( + + + + + + + + ))} + +
时间级别来源分类消息
{new Date(log.createdAt).toLocaleString()}{levelText[log.level] ?? log.level}{log.source}{log.category}{log.message}
+
+ )} +
+ 共 {data?.total ?? 0} 条 +
+ + +
+
+
+ ) +} diff --git a/webui/src/pages/PluginsPage.tsx b/webui/src/pages/PluginsPage.tsx new file mode 100644 index 0000000..77bc33c --- /dev/null +++ b/webui/src/pages/PluginsPage.tsx @@ -0,0 +1,101 @@ +import { useEffect, useState } from 'react' +import { get, post } from '../api' +import type { PluginDescriptor } from '../types' + +// ===== 插件/模组管理:清单 + 热重载/卸载(始终热重载的加载项系统) ===== + +const kindText: Record = { + ServerPlugin: '服务器插件', + CharacterModule: '角色模组', + SkillModule: '技能模组', + ItemModule: '物品模组', +} + +export default function PluginsPage() { + const [items, setItems] = useState([]) + const [message, setMessage] = useState('') + + const load = () => { + get('/api/admin/plugins').then((res) => { + if (res.ok) setItems(res.data) + else setMessage(res.message ?? '加载失败') + }) + } + + useEffect(load, []) + + async function reload(name: string) { + setMessage('') + const res = await post(`/api/admin/plugins/${encodeURIComponent(name)}/reload`) + setMessage(res.ok ? `已热重载:${name}` : (res.message ?? '热重载失败')) + load() + } + + async function unload(name: string) { + if (!confirm(`确定卸载加载项 ${name}?`)) return + setMessage('') + const res = await post(`/api/admin/plugins/${encodeURIComponent(name)}/unload`) + setMessage(res.ok ? `已卸载:${name}` : (res.message ?? '卸载失败')) + load() + } + + async function reloadAll() { + setMessage('') + const res = await post('/api/admin/plugins/reload-all') + setMessage(res.ok ? '已触发全部加载项热重载。' : (res.message ?? '失败')) + load() + } + + return ( +
+
+

插件与模组管理

+ +
+ {message &&
{message}
} +

+ plugins/ 与 modules/ 目录受文件监视,DLL 更新后自动热重载;实体 JSON 配置(EntityModuleConfig)与 DLL 加载为两条平行通道。 +

+ {items.length === 0 ? ( +
+ 暂无加载项 —— 将服务器插件 DLL 放入 plugins/,将角色/技能/物品模组 DLL 放入 modules/ 对应子目录。 +
+ ) : ( +
+ {items.map((item) => ( +
+
+
+
+ {item.name} v{item.version} +
+
+ {kindText[item.kind] ?? item.kind} · {item.author || '未知作者'} +
+
+ + {item.status} + +
+ {item.description &&
{item.description}
} + {item.error &&
{item.error}
} +
+ + + {item.activeGames > 0 && 被 {item.activeGames} 个对局引用} +
+
+ ))} +
+ )} +
+ ) +} diff --git a/webui/src/pages/ReplayPage.tsx b/webui/src/pages/ReplayPage.tsx new file mode 100644 index 0000000..f7e9e5e --- /dev/null +++ b/webui/src/pages/ReplayPage.tsx @@ -0,0 +1,189 @@ +import { useEffect, useState } from 'react' +import { get } from '../api' +import type { PagedData } from '../types' + +interface GameRecord { + id: string + mode: string + state: number + startedAt: string + endedAt: string | null + totalRounds: number + winner: string | null + archivePath: string +} + +interface RoundSummary { + round: number + actorGuid: string + actorName: string + hasKill: boolean + damageTotal: number + healTotal: number + actionCount: number + effectCount: number + hasCheckpoint: boolean + totalTime: number +} + +interface StatRow { + guid: string + name: string + nickName: string + rating: number + kills: number + deaths: number + assists: number + totalDamage: number + totalHeal: number +} + +// ===== 回放中心:对局记录 → 回合摘要 → 单回合详情 / 最终统计 ===== + +export default function ReplayPage() { + const [games, setGames] = useState | null>(null) + const [page, setPage] = useState(1) + const [selected, setSelected] = useState(null) + const [summaries, setSummaries] = useState(null) + const [stats, setStats] = useState(null) + const [roundJson, setRoundJson] = useState(null) + const [message, setMessage] = useState('') + + const loadGames = () => { + get>(`/api/gamerecords?page=${page}&pageSize=10&desc=true`).then((res) => { + if (res.ok) setGames(res.data) + else setMessage(res.message ?? '加载失败') + }) + } + useEffect(loadGames, [page]) + + function openGame(game: GameRecord) { + setSelected(game) + setSummaries(null) + setStats(null) + setRoundJson(null) + get(`/api/games/${game.id}/rounds/summary`).then((res) => { + if (res.ok) setSummaries(res.data) + else setMessage(res.message ?? '回合加载失败(对局可能仍在进行中)') + }) + get<{ rows: StatRow[] }>(`/api/games/${game.id}/statistics`).then((res) => { + if (res.ok && res.data.rows.length > 0) setStats(res.data.rows) + }) + } + + function openRound(round: number) { + if (!selected) return + get(`/api/games/${selected.id}/rounds/${round}`).then((res) => { + if (res.ok) setRoundJson(JSON.stringify(res.data, null, 2)) + }) + } + + return ( +
+

回放中心

+ {message &&
{message}
} + +
+
+
对局记录(game_records 表)
+
+ + + + + + + + + + + + {games?.items.map((g) => ( + + + + + + + + ))} + {games && games.items.length === 0 && ( + + )} + +
时间模式回合胜者
{new Date(g.startedAt).toLocaleString()}{g.mode}{g.state === 1 ? g.totalRounds : '进行中'}{g.winner ?? '—'} + +
暂无对局记录
+
+
+ + + 共 {games?.total ?? 0} 局 +
+ + {selected && stats && stats.length > 0 && ( +
+
最终统计(statistics.json)
+ + + + + + {stats.map((s) => ( + + + + + + + + ))} + +
角色RatingK/D/A伤害治疗
{s.nickName || s.name}{s.rating.toFixed(2)}{s.kills}/{s.deaths}/{s.assists}{s.totalDamage.toFixed(0)}{s.totalHeal.toFixed(0)}
+
+ )} +
+ +
+ {selected && ( + <> +
回合列表({selected.id.slice(0, 8)}…)
+
+ + + + + + + + + + + + {summaries?.map((s) => ( + + + + + + + + ))} + {summaries && summaries.length === 0 && ( + + )} + +
回合行动者伤害击杀
{s.round}{s.actorName}{s.damageTotal.toFixed(0)}{s.hasKill ? 击杀 : '—'} + +
暂无回合
+
+ {roundJson && ( +
{roundJson}
+ )} + + )} +
+
+
+ ) +} diff --git a/webui/src/pages/UsersPage.tsx b/webui/src/pages/UsersPage.tsx new file mode 100644 index 0000000..bb9ed41 --- /dev/null +++ b/webui/src/pages/UsersPage.tsx @@ -0,0 +1,102 @@ +import { useEffect, useState } from 'react' +import { get, del, post } from '../api' +import type { PagedData, User } from '../types' + +// ===== 用户管理:分页列表 + 创建 + 删除(对应 /api/users CRUD) ===== + +export default function UsersPage() { + const [data, setData] = useState | null>(null) + const [page, setPage] = useState(1) + const [showCreate, setShowCreate] = useState(false) + const [form, setForm] = useState({ username: '', password: '', nickname: '', email: '' }) + const [message, setMessage] = useState('') + + const load = () => { + get>(`/api/users?page=${page}&pageSize=10`).then((res) => { + if (res.ok) setData(res.data) + else setMessage(res.message ?? '加载失败') + }) + } + + useEffect(load, [page]) + + async function create(e: React.FormEvent) { + e.preventDefault() + const res = await post('/api/users', { ...form, passwordHash: form.password, status: 0 }) + setMessage(res.ok ? '创建成功。' : (res.message ?? '创建失败。')) + if (res.ok) { + setShowCreate(false) + setForm({ username: '', password: '', nickname: '', email: '' }) + load() + } + } + + async function remove(id: number) { + if (!confirm(`确定删除用户 #${id}?此操作不可恢复。`)) return + const res = await del(`/api/users/${id}`) + setMessage(res.ok ? '已删除。' : (res.message ?? '删除失败。')) + load() + } + + return ( +
+
+

用户管理

+ +
+ {message &&
{message}
} + {showCreate && ( +
+ setForm({ ...form, username: e.target.value })} /> + setForm({ ...form, password: e.target.value })} /> + setForm({ ...form, nickname: e.target.value })} /> + setForm({ ...form, email: e.target.value })} /> + +
+ )} +
+ + + + + + + + + + + + + + {data?.items.map((u) => ( + + + + + + + + + + ))} + +
ID用户名昵称邮箱状态最后登录操作
{u.id}{u.username}{u.isSystem && 系统}{u.nickname}{u.email || '—'} + {u.status === 0 ? '正常' : u.status === 1 ? '封禁' : '禁用'} + {u.lastLoginAt ? new Date(u.lastLoginAt).toLocaleString() : '从未登录'} + {!u.isSystem && ( + + )} +
+
+
+ 共 {data?.total ?? 0} 个用户 +
+ + +
+
+
+ ) +} diff --git a/webui/src/types.ts b/webui/src/types.ts new file mode 100644 index 0000000..9a9fe93 --- /dev/null +++ b/webui/src/types.ts @@ -0,0 +1,97 @@ +// ===== 服务器 API 响应类型(与 Contracts 对齐) ===== + +export interface ApiResponse { + ok: boolean + code: number + message: string | null + data: T + timestamp: string +} + +export interface PagedData { + page: number + pageSize: number + total: number + items: T[] +} + +export interface AuthTokenResponse { + accessToken: string + refreshToken: string + userId: number + username: string + permissions: string[] + roles: string[] +} + +export interface User { + id: number + username: string + email: string + emailVerified: boolean + nickname: string + avatar: string + status: number + isSystem: boolean + createdAt: string + updatedAt: string + lastLoginAt: string | null + lastLoginIp: string | null +} + +export interface Role { + id: number + code: string + name: string + description: string + isSystem: boolean +} + +export interface Permission { + id: number + code: string + name: string + group: string + description: string +} + +export interface PluginDescriptor { + name: string + version: string + author: string + description: string + kind: string + status: string + error: string | null + loadedAt: string | null + activeGames: number + assemblyPath: string +} + +export interface GameInfo { + id: string + mode: string + running: boolean + totalRound: number + totalTime: number + characters: number + clients: number +} + +export interface ServerLog { + id: number + level: number + source: string + category: string + message: string + exception: string | null + createdAt: string +} + +export interface Overview { + connections: number + authenticated: number + userCount: number + gameCount: number + runningGames: number +} diff --git a/webui/tsconfig.app.json b/webui/tsconfig.app.json new file mode 100644 index 0000000..6830b6f --- /dev/null +++ b/webui/tsconfig.app.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", + "target": "es2023", + "lib": ["ES2023", "DOM"], + "module": "esnext", + "types": ["vite/client"], + "allowArbitraryExtensions": true, + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "moduleDetection": "force", + "noEmit": true, + "jsx": "react-jsx", + + /* Linting */ + "noUnusedLocals": true, + "noUnusedParameters": true, + "erasableSyntaxOnly": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["src"] +} diff --git a/webui/tsconfig.json b/webui/tsconfig.json new file mode 100644 index 0000000..1ffef60 --- /dev/null +++ b/webui/tsconfig.json @@ -0,0 +1,7 @@ +{ + "files": [], + "references": [ + { "path": "./tsconfig.app.json" }, + { "path": "./tsconfig.node.json" } + ] +} diff --git a/webui/tsconfig.node.json b/webui/tsconfig.node.json new file mode 100644 index 0000000..8455dcb --- /dev/null +++ b/webui/tsconfig.node.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", + "target": "es2023", + "lib": ["ES2023"], + "types": ["node"], + "skipLibCheck": true, + + /* Bundler mode */ + "module": "nodenext", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "moduleDetection": "force", + "noEmit": true, + + /* Linting */ + "noUnusedLocals": true, + "noUnusedParameters": true, + "erasableSyntaxOnly": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["vite.config.ts"] +} diff --git a/webui/vite.config.ts b/webui/vite.config.ts new file mode 100644 index 0000000..59a1ff7 --- /dev/null +++ b/webui/vite.config.ts @@ -0,0 +1,25 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' + +// https://vite.dev/config/ +export default defineConfig({ + plugins: [react(), tailwindcss()], + server: { + port: 5173, + proxy: { + '/api': { + target: 'http://localhost:5000', + changeOrigin: true, + }, + '/ws': { + target: 'ws://localhost:5000', + ws: true, + }, + '/plugin': { + target: 'http://localhost:5000', + changeOrigin: true, + }, + }, + }, +})