mirror of
https://github.com/project-redbud/FunGame-Server.git
synced 2025-12-16 21:38:21 +00:00
服务器补全 API 实现 (#48)
* PayloadModel 添加 event 属性,添加 Room,Main 的 API 控制器 * 实现 SQLHelper 的自增 ID、异步版本功能 * 填充一些请求控制器的方法 * 添加报价的核心操作 * 涉及库存的物品获取应该使用 Guid 而不是 ItemId * 添加 InventoryController * 添加更新房间设置和用户房间的状态管理 * 优化 API Token 秘钥管理;修复服务器统一报错信息 BUG * 优雅的关闭服务器;补全了所有数据请求实现;API Token 加密方式修改;添加了服务器初始化时创建管理员账号的必要步骤 * 完善 Web API 控制器 --------- Co-authored-by: yeziuku <yezi@wrss.org>
This commit is contained in:
parent
47d29ced5e
commit
8aec496fcb
File diff suppressed because it is too large
Load Diff
@ -5,8 +5,6 @@
|
|||||||
<TargetFramework>net9.0</TargetFramework>
|
<TargetFramework>net9.0</TargetFramework>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ApplicationIcon>logo.ico</ApplicationIcon>
|
|
||||||
<PackageIcon>logo.ico</PackageIcon>
|
|
||||||
<BaseOutputPath>..\bin</BaseOutputPath>
|
<BaseOutputPath>..\bin</BaseOutputPath>
|
||||||
<Title>FunGameServer</Title>
|
<Title>FunGameServer</Title>
|
||||||
<Company>Milimoe</Company>
|
<Company>Milimoe</Company>
|
||||||
@ -17,6 +15,7 @@
|
|||||||
<AssemblyName>FunGameServer</AssemblyName>
|
<AssemblyName>FunGameServer</AssemblyName>
|
||||||
<RootNamespace>Milimoe.$(MSBuildProjectName.Replace(" ", "_"))</RootNamespace>
|
<RootNamespace>Milimoe.$(MSBuildProjectName.Replace(" ", "_"))</RootNamespace>
|
||||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||||
|
<ApplicationIcon>logo.ico</ApplicationIcon>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||||
@ -47,14 +46,8 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\..\FunGame.Core\FunGame.Core.csproj" />
|
<ProjectReference Include="..\..\FunGame.Core\FunGame.Core.csproj" />
|
||||||
|
<ProjectReference Include="..\..\FunGame.Extension\FunGame.SQLQueryExtension\FunGame.SQLQueryExtension.csproj" />
|
||||||
<ProjectReference Include="..\FunGame.Implement\FunGame.Implement.csproj" />
|
<ProjectReference Include="..\FunGame.Implement\FunGame.Implement.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<None Update="Images\logo.ico">
|
|
||||||
<Pack>True</Pack>
|
|
||||||
<PackagePath>\</PackagePath>
|
|
||||||
</None>
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 17 KiB |
@ -1,5 +1,4 @@
|
|||||||
using Milimoe.FunGame;
|
using Milimoe.FunGame.Core.Api.Utility;
|
||||||
using Milimoe.FunGame.Core.Api.Utility;
|
|
||||||
using Milimoe.FunGame.Core.Library.Common.Network;
|
using Milimoe.FunGame.Core.Library.Common.Network;
|
||||||
using Milimoe.FunGame.Core.Library.Constant;
|
using Milimoe.FunGame.Core.Library.Constant;
|
||||||
using Milimoe.FunGame.Server.Controller;
|
using Milimoe.FunGame.Server.Controller;
|
||||||
@ -23,6 +22,28 @@ Console.CancelKeyPress += (sender, e) =>
|
|||||||
Environment.Exit(0); // 退出程序
|
Environment.Exit(0); // 退出程序
|
||||||
};
|
};
|
||||||
|
|
||||||
|
FunGameSystem.CloseListener += async () =>
|
||||||
|
{
|
||||||
|
if (SocketListener != null)
|
||||||
|
{
|
||||||
|
foreach (ServerModel<ServerSocket> model in SocketListener.ClientList.Cast<ServerModel<ServerSocket>>())
|
||||||
|
{
|
||||||
|
await model.Kick("服务器正在关闭。");
|
||||||
|
}
|
||||||
|
SocketListener.Close();
|
||||||
|
SocketListener = null;
|
||||||
|
}
|
||||||
|
if (WebSocketListener != null)
|
||||||
|
{
|
||||||
|
foreach (ServerModel<ServerWebSocket> model in WebSocketListener.ClientList.Cast<ServerModel<ServerWebSocket>>())
|
||||||
|
{
|
||||||
|
await model.Kick("服务器正在关闭。");
|
||||||
|
}
|
||||||
|
WebSocketListener.Close();
|
||||||
|
WebSocketListener = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
while (Running)
|
while (Running)
|
||||||
{
|
{
|
||||||
string order = Console.ReadLine() ?? "";
|
string order = Console.ReadLine() ?? "";
|
||||||
@ -30,21 +51,23 @@ while (Running)
|
|||||||
if (order != "" && Running)
|
if (order != "" && Running)
|
||||||
{
|
{
|
||||||
order = order.ToLower();
|
order = order.ToLower();
|
||||||
|
if (FunGameSystem.OrderList.TryGetValue(order, out Action<string>? action) && action != null)
|
||||||
|
{
|
||||||
|
action(order);
|
||||||
|
}
|
||||||
switch (order)
|
switch (order)
|
||||||
{
|
{
|
||||||
case OrderDictionary.Quit:
|
case OrderDictionary.Quit:
|
||||||
case OrderDictionary.Exit:
|
case OrderDictionary.Exit:
|
||||||
case OrderDictionary.Close:
|
case OrderDictionary.Close:
|
||||||
Running = false;
|
|
||||||
CloseServer();
|
CloseServer();
|
||||||
break;
|
break;
|
||||||
case OrderDictionary.Restart:
|
case OrderDictionary.Restart:
|
||||||
if (SocketListener is null || WebSocketListener is null)
|
if (SocketListener is null || WebSocketListener is null)
|
||||||
{
|
{
|
||||||
ServerHelper.WriteLine("重启服务器");
|
|
||||||
StartServer();
|
StartServer();
|
||||||
}
|
}
|
||||||
else ServerHelper.WriteLine("服务器正在运行,拒绝重启!");
|
else ServerHelper.WriteLine("服务器正在运行,请手动结束服务器进程再启动!");
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
if (SocketListener != null)
|
if (SocketListener != null)
|
||||||
@ -60,9 +83,6 @@ while (Running)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ServerHelper.WriteLine("服务器已关闭,按任意键退出程序。");
|
|
||||||
Console.ReadKey();
|
|
||||||
|
|
||||||
void StartServer()
|
void StartServer()
|
||||||
{
|
{
|
||||||
TaskUtility.NewTask(async () =>
|
TaskUtility.NewTask(async () =>
|
||||||
@ -105,8 +125,8 @@ void StartServer()
|
|||||||
|
|
||||||
ServerHelper.WriteLine("请输入 help 来获取帮助,按下 Ctrl+C 关闭服务器。");
|
ServerHelper.WriteLine("请输入 help 来获取帮助,按下 Ctrl+C 关闭服务器。");
|
||||||
|
|
||||||
// 初始化用户密钥列表
|
// 初始化服务器其他配置文件
|
||||||
FunGameSystem.InitUserKeys();
|
FunGameSystem.InitOtherConfig();
|
||||||
|
|
||||||
ServerHelper.PrintFunGameTitle();
|
ServerHelper.PrintFunGameTitle();
|
||||||
|
|
||||||
@ -246,38 +266,18 @@ void StartServer()
|
|||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
if (e.Message.Equals(new ServerErrorException().Message))
|
|
||||||
{
|
|
||||||
if (SocketListener != null)
|
|
||||||
{
|
|
||||||
SocketListener.Close();
|
|
||||||
SocketListener = null;
|
|
||||||
}
|
|
||||||
if (WebSocketListener != null)
|
|
||||||
{
|
|
||||||
WebSocketListener.Close();
|
|
||||||
WebSocketListener = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ServerHelper.Error(e);
|
ServerHelper.Error(e);
|
||||||
|
CloseServer();
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
if (SocketListener != null)
|
CloseServer();
|
||||||
{
|
|
||||||
SocketListener.Close();
|
|
||||||
SocketListener = null;
|
|
||||||
}
|
|
||||||
if (WebSocketListener != null)
|
|
||||||
{
|
|
||||||
WebSocketListener.Close();
|
|
||||||
WebSocketListener = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
void CloseServer()
|
void CloseServer()
|
||||||
{
|
{
|
||||||
|
Running = false;
|
||||||
FunGameSystem.CloseServer();
|
FunGameSystem.CloseServer();
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +1,13 @@
|
|||||||
using Milimoe.FunGame.Core.Interface.Base;
|
using System.Text;
|
||||||
|
using Milimoe.FunGame.Core.Api.Transmittal;
|
||||||
|
using Milimoe.FunGame.Core.Api.Utility;
|
||||||
|
using Milimoe.FunGame.Core.Entity;
|
||||||
|
using Milimoe.FunGame.Core.Interface.Base;
|
||||||
using Milimoe.FunGame.Core.Library.Common.Addon;
|
using Milimoe.FunGame.Core.Library.Common.Addon;
|
||||||
|
using Milimoe.FunGame.Core.Library.Constant;
|
||||||
using Milimoe.FunGame.Server.Others;
|
using Milimoe.FunGame.Server.Others;
|
||||||
using Milimoe.FunGame.Server.Services;
|
using Milimoe.FunGame.Server.Services;
|
||||||
|
using ProjectRedbud.FunGame.SQLQueryExtension;
|
||||||
|
|
||||||
namespace Milimoe.FunGame.Server.Model
|
namespace Milimoe.FunGame.Server.Model
|
||||||
{
|
{
|
||||||
@ -45,9 +51,6 @@ namespace Milimoe.FunGame.Server.Model
|
|||||||
case OrderDictionary.ShowUsers2:
|
case OrderDictionary.ShowUsers2:
|
||||||
ShowUsers(server);
|
ShowUsers(server);
|
||||||
break;
|
break;
|
||||||
case OrderDictionary.Help:
|
|
||||||
ShowHelp();
|
|
||||||
break;
|
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@ -109,9 +112,90 @@ namespace Milimoe.FunGame.Server.Model
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void ShowHelp()
|
public static void FirstRunRegAdmin()
|
||||||
{
|
{
|
||||||
ServerHelper.WriteLine("Milimoe -> 帮助");
|
using SQLHelper? sql = Factory.OpenFactory.GetSQLHelper() ?? throw new SQLServiceException();
|
||||||
|
ServerHelper.WriteLine("首次启动需要注册管理员账号,请按提示输入信息!", InvokeMessageType.Core);
|
||||||
|
string username, password, email;
|
||||||
|
ServerHelper.Write("请输入管理员用户名:", InvokeMessageType.Core);
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
username = Console.ReadLine() ?? "";
|
||||||
|
int usernameLength = NetworkUtility.GetUserNameLength(username);
|
||||||
|
if (usernameLength < 3 || usernameLength > 12)
|
||||||
|
{
|
||||||
|
ServerHelper.WriteLine("账号名长度不符合要求:3~12个字符数(一个中文2个字符)", InvokeMessageType.Error);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ServerHelper.Write("请输入管理员邮箱:", InvokeMessageType.Core);
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
email = Console.ReadLine() ?? "";
|
||||||
|
if (!NetworkUtility.IsEmail(email))
|
||||||
|
{
|
||||||
|
ServerHelper.WriteLine("这不是一个邮箱地址!", InvokeMessageType.Error);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ServerHelper.Write("请输入管理员密码:", InvokeMessageType.Core);
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
StringBuilder passwordBuilder = new();
|
||||||
|
ConsoleKeyInfo key;
|
||||||
|
|
||||||
|
do
|
||||||
|
{
|
||||||
|
key = Console.ReadKey(true);
|
||||||
|
|
||||||
|
if (key.Key == ConsoleKey.Enter)
|
||||||
|
{
|
||||||
|
Console.WriteLine();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
else if (key.Key == ConsoleKey.Backspace)
|
||||||
|
{
|
||||||
|
if (passwordBuilder.Length > 0)
|
||||||
|
{
|
||||||
|
passwordBuilder.Remove(passwordBuilder.Length - 1, 1);
|
||||||
|
Console.Write("\b \b");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (!char.IsControl(key.KeyChar))
|
||||||
|
{
|
||||||
|
passwordBuilder.Append(key.KeyChar);
|
||||||
|
Console.Write("*");
|
||||||
|
}
|
||||||
|
} while (true);
|
||||||
|
|
||||||
|
password = passwordBuilder.ToString();
|
||||||
|
|
||||||
|
if (password.Length < 6 || password.Length > 15)
|
||||||
|
{
|
||||||
|
ServerHelper.WriteLine("密码长度不符合要求:6~15个字符数", InvokeMessageType.Error);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(string msg, RegInvokeType type, bool success) = DataRequestService.RegisterUser(sql, username, password, email, "localhost");
|
||||||
|
ServerHelper.WriteLine(msg, InvokeMessageType.Core);
|
||||||
|
if (success)
|
||||||
|
{
|
||||||
|
User? user = sql.GetUserByUsernameAndEmail(username, email);
|
||||||
|
if (user != null)
|
||||||
|
{
|
||||||
|
user.IsAdmin = true;
|
||||||
|
sql.UpdateUser(user);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -11,6 +11,7 @@ using Milimoe.FunGame.Core.Library.SQLScript.Entity;
|
|||||||
using Milimoe.FunGame.Server.Controller;
|
using Milimoe.FunGame.Server.Controller;
|
||||||
using Milimoe.FunGame.Server.Others;
|
using Milimoe.FunGame.Server.Others;
|
||||||
using Milimoe.FunGame.Server.Services;
|
using Milimoe.FunGame.Server.Services;
|
||||||
|
using ProjectRedbud.FunGame.SQLQueryExtension;
|
||||||
|
|
||||||
namespace Milimoe.FunGame.Server.Model
|
namespace Milimoe.FunGame.Server.Model
|
||||||
{
|
{
|
||||||
@ -82,6 +83,8 @@ namespace Milimoe.FunGame.Server.Model
|
|||||||
NowGamingServer.CloseAnonymousServer(this);
|
NowGamingServer.CloseAnonymousServer(this);
|
||||||
}
|
}
|
||||||
NowGamingServer = null;
|
NowGamingServer = null;
|
||||||
|
User.OnlineState = OnlineState.InRoom;
|
||||||
|
if (User.Id == InRoom.RoomMaster.Id) InRoom.RoomState = RoomState.Created;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -382,44 +385,47 @@ namespace Milimoe.FunGame.Server.Model
|
|||||||
public async Task<bool> QuitRoom(string roomid, bool isMaster)
|
public async Task<bool> QuitRoom(string roomid, bool isMaster)
|
||||||
{
|
{
|
||||||
bool result;
|
bool result;
|
||||||
|
SQLHelper?.NewTransaction();
|
||||||
|
|
||||||
FunGameSystem.RoomList.CancelReady(roomid, User);
|
FunGameSystem.RoomList.CancelReady(roomid, User);
|
||||||
FunGameSystem.RoomList.QuitRoom(roomid, User);
|
FunGameSystem.RoomList.QuitRoom(roomid, User);
|
||||||
Room Room = FunGameSystem.RoomList[roomid] ?? General.HallInstance;
|
Room Room = FunGameSystem.RoomList[roomid] ?? General.HallInstance;
|
||||||
|
User.OnlineState = OnlineState.Online;
|
||||||
// 是否是房主
|
// 是否是房主
|
||||||
if (isMaster)
|
if (isMaster && Room.Roomid != "-1")
|
||||||
{
|
{
|
||||||
List<User> users = [.. FunGameSystem.RoomList[roomid].UserAndIsReady.Keys];
|
List<User> users = [.. FunGameSystem.RoomList[roomid].UserAndIsReady.Keys];
|
||||||
if (users.Count > 0) // 如果此时房间还有人,更新房主
|
User? newRoomMaster = null;
|
||||||
|
if (users.Count > 0) newRoomMaster = users[0];
|
||||||
|
SQLHelper?.QuitRoomByRoomMaster(roomid, User.Id, newRoomMaster?.Id);
|
||||||
|
if (newRoomMaster != null)
|
||||||
{
|
{
|
||||||
User NewMaster = users[0];
|
Room.RoomMaster = users[0];
|
||||||
Room.RoomMaster = NewMaster;
|
ServerHelper.WriteLine("[ " + GetClientName() + " ] 退出了房间 " + roomid + ",并更新房主为:" + newRoomMaster);
|
||||||
SQLHelper?.Execute(RoomQuery.Update_QuitRoom(SQLHelper, roomid, User.Id, NewMaster.Id));
|
await NotifyQuitRoom(Room, true);
|
||||||
this.InRoom = General.HallInstance;
|
|
||||||
await UpdateRoomMaster(Room, true);
|
|
||||||
result = true;
|
|
||||||
}
|
}
|
||||||
else // 没人了就解散房间
|
else
|
||||||
{
|
{
|
||||||
FunGameSystem.RoomList.RemoveRoom(roomid);
|
FunGameSystem.RoomList.RemoveRoom(roomid);
|
||||||
SQLHelper?.Execute(RoomQuery.Delete_QuitRoom(SQLHelper, roomid, User.Id));
|
|
||||||
this.InRoom = General.HallInstance;
|
|
||||||
ServerHelper.WriteLine("[ " + GetClientName() + " ] 解散了房间 " + roomid);
|
ServerHelper.WriteLine("[ " + GetClientName() + " ] 解散了房间 " + roomid);
|
||||||
result = true;
|
|
||||||
}
|
}
|
||||||
|
InRoom = General.HallInstance;
|
||||||
|
result = true;
|
||||||
}
|
}
|
||||||
// 不是房主直接退出房间
|
// 不是房主直接退出房间
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
this.InRoom = General.HallInstance;
|
this.InRoom = General.HallInstance;
|
||||||
await UpdateRoomMaster(Room);
|
await NotifyQuitRoom(Room);
|
||||||
result = true;
|
result = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
SQLHelper?.Commit();
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task UpdateRoomMaster(Room room, bool isUpdateRoomMaster = false)
|
public async Task NotifyQuitRoom(Room room, bool isUpdateRoomMaster = false)
|
||||||
{
|
{
|
||||||
foreach (IServerModel Client in Listener.ClientList.Where(c => c != null && c.User.Id != 0 && room.Roomid == c.InRoom?.Roomid))
|
foreach (IServerModel Client in Listener.ClientList.Where(c => c != null && c.User.Id != 0 && room.Roomid == c.InRoom?.Roomid))
|
||||||
{
|
{
|
||||||
@ -473,6 +479,11 @@ namespace Milimoe.FunGame.Server.Model
|
|||||||
{
|
{
|
||||||
// 创建User对象
|
// 创建User对象
|
||||||
User = Factory.GetUser(_dsUser);
|
User = Factory.GetUser(_dsUser);
|
||||||
|
if (SQLHelper?.GetUserById(User.Id, true, true) is User real)
|
||||||
|
{
|
||||||
|
User = real;
|
||||||
|
}
|
||||||
|
User.OnlineState = OnlineState.Online;
|
||||||
// 检查有没有重复登录的情况
|
// 检查有没有重复登录的情况
|
||||||
await ForceLogOutDuplicateLogonUser();
|
await ForceLogOutDuplicateLogonUser();
|
||||||
// 添加至玩家列表
|
// 添加至玩家列表
|
||||||
@ -499,6 +510,7 @@ namespace Milimoe.FunGame.Server.Model
|
|||||||
{
|
{
|
||||||
if (User.Id != 0 && this != null)
|
if (User.Id != 0 && this != null)
|
||||||
{
|
{
|
||||||
|
User.OnlineState = OnlineState.Offline;
|
||||||
_checkLoginKey = Guid.Empty;
|
_checkLoginKey = Guid.Empty;
|
||||||
_logoutTime = DateTime.Now.Ticks;
|
_logoutTime = DateTime.Now.Ticks;
|
||||||
int TotalMinutes = Convert.ToInt32((new DateTime(_logoutTime) - new DateTime(_loginTime)).TotalMinutes);
|
int TotalMinutes = Convert.ToInt32((new DateTime(_logoutTime) - new DateTime(_loginTime)).TotalMinutes);
|
||||||
|
|||||||
@ -6,14 +6,25 @@ using Milimoe.FunGame.Core.Library.Constant;
|
|||||||
using Milimoe.FunGame.Core.Library.SQLScript.Common;
|
using Milimoe.FunGame.Core.Library.SQLScript.Common;
|
||||||
using Milimoe.FunGame.Core.Library.SQLScript.Entity;
|
using Milimoe.FunGame.Core.Library.SQLScript.Entity;
|
||||||
using Milimoe.FunGame.Server.Others;
|
using Milimoe.FunGame.Server.Others;
|
||||||
|
using ProjectRedbud.FunGame.SQLQueryExtension;
|
||||||
|
|
||||||
namespace Milimoe.FunGame.Server.Services
|
namespace Milimoe.FunGame.Server.Services
|
||||||
{
|
{
|
||||||
public class DataRequestService
|
public class DataRequestService
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 获取插件取消请求的原因
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="type"></param>
|
||||||
|
/// <param name="e"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private static string GetPluginCancelString(DataRequestType type, GeneralEventArgs e) => $"{DataRequestSet.GetTypeString(type)} 请求已取消。{(e.EventMsg != "" ? $"原因:{e.EventMsg}" : "")}";
|
||||||
|
|
||||||
|
#region Register
|
||||||
|
|
||||||
public static (string Msg, RegInvokeType RegInvokeType, bool Success) Reg(object sender, string username, string password, string email, string verifyCode, string clientIP = "")
|
public static (string Msg, RegInvokeType RegInvokeType, bool Success) Reg(object sender, string username, string password, string email, string verifyCode, string clientIP = "")
|
||||||
{
|
{
|
||||||
string msg = "";
|
string msg;
|
||||||
RegInvokeType type = RegInvokeType.None;
|
RegInvokeType type = RegInvokeType.None;
|
||||||
bool success = false;
|
bool success = false;
|
||||||
string clientName = ServerHelper.MakeClientName(clientIP);
|
string clientName = ServerHelper.MakeClientName(clientIP);
|
||||||
@ -23,131 +34,21 @@ namespace Milimoe.FunGame.Server.Services
|
|||||||
FunGameSystem.WebAPIPluginLoader?.OnBeforeRegEvent(sender, eventArgs);
|
FunGameSystem.WebAPIPluginLoader?.OnBeforeRegEvent(sender, eventArgs);
|
||||||
if (eventArgs.Cancel)
|
if (eventArgs.Cancel)
|
||||||
{
|
{
|
||||||
msg = $"{DataRequestSet.GetTypeString(DataRequestType.Reg_Reg)} 请求已取消。{(eventArgs.EventMsg != "" ? $"原因:{eventArgs.EventMsg}" : "")}";
|
msg = GetPluginCancelString(DataRequestType.Reg_Reg, eventArgs);
|
||||||
ServerHelper.WriteLine(msg, InvokeMessageType.DataRequest, LogLevel.Warning);
|
ServerHelper.WriteLine(msg, InvokeMessageType.DataRequest, LogLevel.Warning);
|
||||||
return (eventArgs.EventMsg, RegInvokeType.None, false);
|
return (eventArgs.EventMsg, RegInvokeType.None, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
using SQLHelper? sqlHelper = Factory.OpenFactory.GetSQLHelper();
|
using SQLHelper? sqlHelper = Factory.OpenFactory.GetSQLHelper();
|
||||||
using MailSender? mailSender = Factory.OpenFactory.GetMailSender();
|
using MailSender? mailSender = Factory.OpenFactory.GetMailSender();
|
||||||
|
|
||||||
if (sqlHelper != null)
|
if (sqlHelper != null)
|
||||||
{
|
{
|
||||||
// 如果没发验证码,就生成验证码
|
(msg, type, success) = ProcessRegistration(sqlHelper, mailSender, username, password, email, verifyCode, clientIP, clientName);
|
||||||
if (verifyCode.Trim() == "")
|
}
|
||||||
{
|
else
|
||||||
// 先检查账号是否重复
|
{
|
||||||
sqlHelper.ExecuteDataSet(UserQuery.Select_IsExistUsername(sqlHelper, username));
|
msg = "服务器无法处理您的注册,注册失败!";
|
||||||
if (sqlHelper.Result == SQLResult.Success)
|
|
||||||
{
|
|
||||||
ServerHelper.WriteLine(clientName + " 账号已被注册");
|
|
||||||
msg = "此账号名已被使用!";
|
|
||||||
type = RegInvokeType.DuplicateUserName;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
// 检查邮箱是否重复
|
|
||||||
sqlHelper.ExecuteDataSet(UserQuery.Select_IsExistEmail(sqlHelper, email));
|
|
||||||
if (sqlHelper.Result == SQLResult.Success)
|
|
||||||
{
|
|
||||||
ServerHelper.WriteLine(clientName + " 邮箱已被注册");
|
|
||||||
msg = "此邮箱已被注册!";
|
|
||||||
type = RegInvokeType.DuplicateEmail;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
// 检查验证码是否发送过
|
|
||||||
sqlHelper.ExecuteDataSet(RegVerifyCodes.Select_HasSentRegVerifyCode(sqlHelper, username, email));
|
|
||||||
if (sqlHelper.Result == SQLResult.Success && DateTime.TryParse(sqlHelper.DataSet.Tables[0].Rows[0][RegVerifyCodes.Column_RegTime].ToString(), out DateTime RegTime) && (DateTime.Now - RegTime).TotalMinutes < 10)
|
|
||||||
{
|
|
||||||
string RegVerifyCode = sqlHelper.DataSet.Tables[0].Rows[0][RegVerifyCodes.Column_RegVerifyCode].ToString() ?? "";
|
|
||||||
ServerHelper.WriteLine(clientName + $" 十分钟内已向{email}发送过验证码:{RegVerifyCode}");
|
|
||||||
type = RegInvokeType.InputVerifyCode;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
// 发送验证码,需要先删除之前过期的验证码
|
|
||||||
sqlHelper.NewTransaction();
|
|
||||||
sqlHelper.Execute(RegVerifyCodes.Delete_RegVerifyCode(sqlHelper, username, email));
|
|
||||||
string regVerify = Verification.CreateVerifyCode(VerifyCodeType.NumberVerifyCode, 6);
|
|
||||||
sqlHelper.Execute(RegVerifyCodes.Insert_RegVerifyCode(sqlHelper, username, email, regVerify));
|
|
||||||
if (sqlHelper.Result == SQLResult.Success)
|
|
||||||
{
|
|
||||||
sqlHelper.Commit();
|
|
||||||
if (mailSender != null)
|
|
||||||
{
|
|
||||||
// 发送验证码
|
|
||||||
string ServerName = Config.ServerName;
|
|
||||||
string Subject = $"[{ServerName}] FunGame 注册验证码";
|
|
||||||
string Body = $"亲爱的 {username}, <br/> 感谢您注册[{ServerName}],您的验证码是 {regVerify} ,10分钟内有效,请及时输入!<br/><br/>{ServerName}<br/>{DateTimeUtility.GetDateTimeToString(TimeType.LongDateOnly)}";
|
|
||||||
string[] To = [email];
|
|
||||||
if (mailSender.Send(mailSender.CreateMail(Subject, Body, System.Net.Mail.MailPriority.Normal, true, To)) == MailSendResult.Success)
|
|
||||||
{
|
|
||||||
ServerHelper.WriteLine(clientName + $" 已向{email}发送验证码:{regVerify}");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
ServerHelper.WriteLine(clientName + " 无法发送验证码", InvokeMessageType.Error);
|
|
||||||
ServerHelper.WriteLine(mailSender.ErrorMsg, InvokeMessageType.Error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else // 不使用MailSender的情况
|
|
||||||
{
|
|
||||||
ServerHelper.WriteLine(clientName + $" 验证码为:{regVerify},请服务器管理员告知此用户");
|
|
||||||
}
|
|
||||||
type = RegInvokeType.InputVerifyCode;
|
|
||||||
}
|
|
||||||
else sqlHelper.Rollback();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
// 先检查验证码
|
|
||||||
sqlHelper.ExecuteDataSet(RegVerifyCodes.Select_RegVerifyCode(sqlHelper, username, email, verifyCode));
|
|
||||||
if (sqlHelper.Result == SQLResult.Success)
|
|
||||||
{
|
|
||||||
if (!DateTime.TryParse(sqlHelper.DataSet.Tables[0].Rows[0][RegVerifyCodes.Column_RegTime].ToString(), out DateTime RegTime))
|
|
||||||
{
|
|
||||||
RegTime = General.DefaultTime;
|
|
||||||
}
|
|
||||||
// 检查验证码是否过期
|
|
||||||
if ((DateTime.Now - RegTime).TotalMinutes >= 10)
|
|
||||||
{
|
|
||||||
ServerHelper.WriteLine(clientName + " 验证码已过期");
|
|
||||||
msg = "此验证码已过期,请重新注册。";
|
|
||||||
sqlHelper.Execute(RegVerifyCodes.Delete_RegVerifyCode(sqlHelper, username, email));
|
|
||||||
type = RegInvokeType.None;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
// 注册
|
|
||||||
if (verifyCode.Equals(sqlHelper.DataSet.Tables[0].Rows[0][RegVerifyCodes.Column_RegVerifyCode]))
|
|
||||||
{
|
|
||||||
sqlHelper.NewTransaction();
|
|
||||||
ServerHelper.WriteLine("[Reg] Username: " + username + " Email: " + email);
|
|
||||||
FunGameSystem.UpdateUserKey(username);
|
|
||||||
password = password.Encrypt(FunGameSystem.GetUserKey(username));
|
|
||||||
sqlHelper.Execute(UserQuery.Insert_Register(sqlHelper, username, password, email, clientIP));
|
|
||||||
if (sqlHelper.Result == SQLResult.Success)
|
|
||||||
{
|
|
||||||
success = true;
|
|
||||||
msg = "注册成功!请牢记您的账号与密码!";
|
|
||||||
sqlHelper.Execute(RegVerifyCodes.Delete_RegVerifyCode(sqlHelper, username, email));
|
|
||||||
sqlHelper.Commit();
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
sqlHelper.Rollback();
|
|
||||||
msg = "服务器无法处理您的注册,注册失败!";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else msg = "验证码不正确,请重新输入!";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (sqlHelper.Result == SQLResult.NotFound) msg = "验证码不正确,请重新输入!";
|
|
||||||
else msg = "服务器无法处理您的注册,注册失败!";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
eventArgs.Success = success;
|
eventArgs.Success = success;
|
||||||
@ -157,11 +58,152 @@ namespace Milimoe.FunGame.Server.Services
|
|||||||
return (msg, type, success);
|
return (msg, type, success);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal static (string Msg, RegInvokeType Type, bool Success) ProcessRegistration(SQLHelper sqlHelper, MailSender? mailSender, string username, string password, string email, string verifyCode, string clientIP, string clientName)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(verifyCode))
|
||||||
|
{
|
||||||
|
return HandleNoVerifyCode(sqlHelper, mailSender, username, email, clientName);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
return HandleWithVerifyCode(sqlHelper, username, password, email, verifyCode, clientIP, clientName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static (string Msg, RegInvokeType Type, bool Success) HandleNoVerifyCode(SQLHelper sqlHelper, MailSender? mailSender, string username, string email, string clientName)
|
||||||
|
{
|
||||||
|
// 先检查账号是否重复
|
||||||
|
sqlHelper.ExecuteDataSet(UserQuery.Select_IsExistUsername(sqlHelper, username));
|
||||||
|
if (sqlHelper.Result == SQLResult.Success)
|
||||||
|
{
|
||||||
|
ServerHelper.WriteLine(clientName + " 账号已被注册");
|
||||||
|
return ("此账号名已被使用!", RegInvokeType.DuplicateUserName, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查邮箱是否重复
|
||||||
|
sqlHelper.ExecuteDataSet(UserQuery.Select_IsExistEmail(sqlHelper, email));
|
||||||
|
if (sqlHelper.Result == SQLResult.Success)
|
||||||
|
{
|
||||||
|
ServerHelper.WriteLine(clientName + " 邮箱已被注册");
|
||||||
|
return ("此邮箱已被注册!", RegInvokeType.DuplicateEmail, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查验证码是否发送过
|
||||||
|
sqlHelper.ExecuteDataSet(RegVerifyCodes.Select_HasSentRegVerifyCode(sqlHelper, username, email));
|
||||||
|
if (sqlHelper.Result == SQLResult.Success && DateTime.TryParse(sqlHelper.DataSet.Tables[0].Rows[0][RegVerifyCodes.Column_RegTime].ToString(), out DateTime RegTime) && (DateTime.Now - RegTime).TotalMinutes < 10)
|
||||||
|
{
|
||||||
|
string RegVerifyCode = sqlHelper.DataSet.Tables[0].Rows[0][RegVerifyCodes.Column_RegVerifyCode].ToString() ?? "";
|
||||||
|
ServerHelper.WriteLine(clientName + $" 十分钟内已向{email}发送过验证码:{RegVerifyCode}");
|
||||||
|
return ("", RegInvokeType.InputVerifyCode, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 发送验证码
|
||||||
|
return SendVerificationCode(sqlHelper, mailSender, username, email, clientName);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static (string Msg, RegInvokeType Type, bool Success) SendVerificationCode(SQLHelper sqlHelper, MailSender? mailSender, string username, string email, string clientName)
|
||||||
|
{
|
||||||
|
sqlHelper.NewTransaction();
|
||||||
|
sqlHelper.Execute(RegVerifyCodes.Delete_RegVerifyCode(sqlHelper, username, email));
|
||||||
|
string regVerify = Verification.CreateVerifyCode(VerifyCodeType.NumberVerifyCode, 6);
|
||||||
|
sqlHelper.Execute(RegVerifyCodes.Insert_RegVerifyCode(sqlHelper, username, email, regVerify));
|
||||||
|
|
||||||
|
if (sqlHelper.Result == SQLResult.Success)
|
||||||
|
{
|
||||||
|
sqlHelper.Commit();
|
||||||
|
|
||||||
|
if (mailSender != null)
|
||||||
|
{
|
||||||
|
// 发送验证码
|
||||||
|
string ServerName = Config.ServerName;
|
||||||
|
string Subject = $"[{ServerName}] 注册验证码";
|
||||||
|
string Body = $"亲爱的 {username}, <br/> 感谢您注册 [{ServerName}],您的验证码是 {regVerify} ,10分钟内有效,请及时输入!<br/><br/>{ServerName}<br/>{DateTimeUtility.GetDateTimeToString(TimeType.LongDateOnly)}";
|
||||||
|
string[] To = [email];
|
||||||
|
if (mailSender.Send(mailSender.CreateMail(Subject, Body, System.Net.Mail.MailPriority.Normal, true, To)) == MailSendResult.Success)
|
||||||
|
{
|
||||||
|
ServerHelper.WriteLine(clientName + $" 已向{email}发送验证码:{regVerify}");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ServerHelper.WriteLine(clientName + " 无法发送验证码", InvokeMessageType.Error);
|
||||||
|
ServerHelper.WriteLine(mailSender.ErrorMsg, InvokeMessageType.Error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else // 不使用MailSender的情况
|
||||||
|
{
|
||||||
|
ServerHelper.WriteLine(clientName + $" 验证码为:{regVerify},请服务器管理员告知此用户");
|
||||||
|
}
|
||||||
|
return ("", RegInvokeType.InputVerifyCode, false);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
sqlHelper.Rollback();
|
||||||
|
return ("发送验证码失败!", RegInvokeType.None, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static (string Msg, RegInvokeType Type, bool Success) HandleWithVerifyCode(SQLHelper sqlHelper, string username, string password, string email, string verifyCode, string clientIP, string clientName)
|
||||||
|
{
|
||||||
|
// 先检查验证码
|
||||||
|
sqlHelper.ExecuteDataSet(RegVerifyCodes.Select_RegVerifyCode(sqlHelper, username, email, verifyCode));
|
||||||
|
if (sqlHelper.Result == SQLResult.Success)
|
||||||
|
{
|
||||||
|
if (!DateTime.TryParse(sqlHelper.DataSet.Tables[0].Rows[0][RegVerifyCodes.Column_RegTime].ToString(), out DateTime RegTime))
|
||||||
|
{
|
||||||
|
RegTime = General.DefaultTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查验证码是否过期
|
||||||
|
if ((DateTime.Now - RegTime).TotalMinutes >= 10)
|
||||||
|
{
|
||||||
|
ServerHelper.WriteLine(clientName + " 验证码已过期");
|
||||||
|
sqlHelper.Execute(RegVerifyCodes.Delete_RegVerifyCode(sqlHelper, username, email));
|
||||||
|
return ("此验证码已过期,请重新注册。", RegInvokeType.None, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 注册
|
||||||
|
return RegisterUser(sqlHelper, username, password, email, clientIP);
|
||||||
|
}
|
||||||
|
else if (sqlHelper.Result == SQLResult.NotFound)
|
||||||
|
{
|
||||||
|
return ("验证码不正确,请重新输入!", RegInvokeType.None, false);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
return ("服务器无法处理您的注册,注册失败!", RegInvokeType.None, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static (string Msg, RegInvokeType Type, bool Success) RegisterUser(SQLHelper sqlHelper, string username, string password, string email, string clientIP)
|
||||||
|
{
|
||||||
|
sqlHelper.NewTransaction();
|
||||||
|
ServerHelper.WriteLine("[Reg] Username: " + username + " Email: " + email);
|
||||||
|
FunGameSystem.UpdateUserKey(username);
|
||||||
|
password = password.Encrypt(FunGameSystem.GetUserKey(username));
|
||||||
|
sqlHelper.RegisterUser(username, password, email, clientIP);
|
||||||
|
|
||||||
|
if (sqlHelper.Result == SQLResult.Success)
|
||||||
|
{
|
||||||
|
sqlHelper.Execute(RegVerifyCodes.Delete_RegVerifyCode(sqlHelper, username, email));
|
||||||
|
sqlHelper.Commit();
|
||||||
|
return ("注册成功!请牢记您的账号与密码!", RegInvokeType.None, true);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
sqlHelper.Rollback();
|
||||||
|
return ("服务器无法处理您的注册,注册失败!", RegInvokeType.None, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Login
|
||||||
|
|
||||||
public static (bool Success, DataSet DataSet, string Msg, Guid Key) PreLogin(object sender, string username, string password, string autokey = "")
|
public static (bool Success, DataSet DataSet, string Msg, Guid Key) PreLogin(object sender, string username, string password, string autokey = "")
|
||||||
{
|
{
|
||||||
bool success = false;
|
bool success = false;
|
||||||
DataSet dsUser = new();
|
DataSet dsUser = new();
|
||||||
string msg = "用户名或密码不正确。";
|
string msg;
|
||||||
Guid key = Guid.Empty;
|
Guid key = Guid.Empty;
|
||||||
|
|
||||||
LoginEventArgs eventArgs = new(username, password, autokey);
|
LoginEventArgs eventArgs = new(username, password, autokey);
|
||||||
@ -169,43 +211,12 @@ namespace Milimoe.FunGame.Server.Services
|
|||||||
FunGameSystem.WebAPIPluginLoader?.OnBeforeLoginEvent(sender, eventArgs);
|
FunGameSystem.WebAPIPluginLoader?.OnBeforeLoginEvent(sender, eventArgs);
|
||||||
if (eventArgs.Cancel)
|
if (eventArgs.Cancel)
|
||||||
{
|
{
|
||||||
msg = $"{DataRequestSet.GetTypeString(DataRequestType.Login_Login)} 请求已取消。{(eventArgs.EventMsg != "" ? $"原因:{eventArgs.EventMsg}" : "")}";
|
msg = GetPluginCancelString(DataRequestType.Login_Login, eventArgs);
|
||||||
ServerHelper.WriteLine(msg, InvokeMessageType.DataRequest, LogLevel.Warning);
|
ServerHelper.WriteLine(msg, InvokeMessageType.DataRequest, LogLevel.Warning);
|
||||||
return (success, dsUser, eventArgs.EventMsg, key);
|
return (success, dsUser, eventArgs.EventMsg, key);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 验证登录
|
(success, dsUser, msg, key) = ProcessLogin(username, password, autokey);
|
||||||
if (username != "" && password != "")
|
|
||||||
{
|
|
||||||
password = password.Encrypt(FunGameSystem.GetUserKey(username));
|
|
||||||
ServerHelper.WriteLine("[" + DataRequestSet.GetTypeString(DataRequestType.Login_Login) + "] Username: " + username);
|
|
||||||
using SQLHelper? sqlHelper = Factory.OpenFactory.GetSQLHelper();
|
|
||||||
if (sqlHelper != null)
|
|
||||||
{
|
|
||||||
sqlHelper.ExecuteDataSet(UserQuery.Select_Users_LoginQuery(sqlHelper, username, password));
|
|
||||||
if (sqlHelper.Result == SQLResult.Success)
|
|
||||||
{
|
|
||||||
dsUser = sqlHelper.DataSet;
|
|
||||||
key = Guid.NewGuid();
|
|
||||||
success = true;
|
|
||||||
msg = "";
|
|
||||||
if (autokey.Trim() != "")
|
|
||||||
{
|
|
||||||
sqlHelper.ExecuteDataSet(UserQuery.Select_CheckAutoKey(sqlHelper, username, autokey));
|
|
||||||
if (sqlHelper.Result == SQLResult.Success)
|
|
||||||
{
|
|
||||||
ServerHelper.WriteLine("[" + DataRequestSet.GetTypeString(DataRequestType.Login_Login) + "] AutoKey: 已确认");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
success = false;
|
|
||||||
msg = "AutoKey 不正确,拒绝自动登录!";
|
|
||||||
ServerHelper.WriteLine("[" + DataRequestSet.GetTypeString(DataRequestType.Login_Login) + "] " + msg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
eventArgs.Success = success;
|
eventArgs.Success = success;
|
||||||
FunGameSystem.ServerPluginLoader?.OnAfterLoginEvent(sender, eventArgs);
|
FunGameSystem.ServerPluginLoader?.OnAfterLoginEvent(sender, eventArgs);
|
||||||
@ -214,5 +225,72 @@ namespace Milimoe.FunGame.Server.Services
|
|||||||
ServerHelper.WriteLine(msg, InvokeMessageType.Core);
|
ServerHelper.WriteLine(msg, InvokeMessageType.Core);
|
||||||
return (success, dsUser, msg, key);
|
return (success, dsUser, msg, key);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal static (bool Success, DataSet DataSet, string Msg, Guid Key) ProcessLogin(string username, string password, string autokey)
|
||||||
|
{
|
||||||
|
bool success = false;
|
||||||
|
DataSet dsUser = new();
|
||||||
|
string msg = "用户名或密码不正确。";
|
||||||
|
Guid key = Guid.Empty;
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
|
||||||
|
{
|
||||||
|
password = password.Encrypt(FunGameSystem.GetUserKey(username));
|
||||||
|
ServerHelper.WriteLine("[" + DataRequestSet.GetTypeString(DataRequestType.Login_Login) + "] Username: " + username);
|
||||||
|
|
||||||
|
using SQLHelper? sqlHelper = Factory.OpenFactory.GetSQLHelper();
|
||||||
|
if (sqlHelper != null)
|
||||||
|
{
|
||||||
|
(success, dsUser, msg, key) = ValidateLogin(sqlHelper, username, password, autokey);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
msg = "无法连接到数据库,登录失败!";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (success, dsUser, msg, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static (bool Success, DataSet DataSet, string Msg, Guid Key) ValidateLogin(SQLHelper sqlHelper, string username, string password, string autokey)
|
||||||
|
{
|
||||||
|
bool success = false;
|
||||||
|
DataSet dsUser = new();
|
||||||
|
string msg = "用户名或密码不正确。";
|
||||||
|
Guid key = Guid.NewGuid();
|
||||||
|
|
||||||
|
sqlHelper.ExecuteDataSet(UserQuery.Select_Users_LoginQuery(sqlHelper, username, password));
|
||||||
|
if (sqlHelper.Result == SQLResult.Success)
|
||||||
|
{
|
||||||
|
dsUser = sqlHelper.DataSet;
|
||||||
|
success = true;
|
||||||
|
msg = "";
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(autokey))
|
||||||
|
{
|
||||||
|
(success, msg) = CheckAutoKey(sqlHelper, username, autokey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (success, dsUser, msg, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static (bool Success, string Msg) CheckAutoKey(SQLHelper sqlHelper, string username, string autokey)
|
||||||
|
{
|
||||||
|
sqlHelper.ExecuteDataSet(UserQuery.Select_CheckAutoKey(sqlHelper, username, autokey));
|
||||||
|
if (sqlHelper.Result == SQLResult.Success)
|
||||||
|
{
|
||||||
|
ServerHelper.WriteLine("[" + DataRequestSet.GetTypeString(DataRequestType.Login_Login) + "] AutoKey: 已确认");
|
||||||
|
return (true, "");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
string msg = "AutoKey 不正确,拒绝自动登录!";
|
||||||
|
ServerHelper.WriteLine("[" + DataRequestSet.GetTypeString(DataRequestType.Login_Login) + "] " + msg);
|
||||||
|
return (false, msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,4 +1,5 @@
|
|||||||
using System.Data;
|
using System.Data;
|
||||||
|
using System.Data.Common;
|
||||||
using Milimoe.FunGame.Core.Api.Transmittal;
|
using Milimoe.FunGame.Core.Api.Transmittal;
|
||||||
using Milimoe.FunGame.Core.Library.Constant;
|
using Milimoe.FunGame.Core.Library.Constant;
|
||||||
using Milimoe.FunGame.Core.Model;
|
using Milimoe.FunGame.Core.Model;
|
||||||
@ -9,14 +10,59 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
{
|
{
|
||||||
public class MySQLHelper : SQLHelper
|
public class MySQLHelper : SQLHelper
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// FunGame 类型
|
||||||
|
/// </summary>
|
||||||
public override FunGameInfo.FunGame FunGameType { get; } = FunGameInfo.FunGame.FunGame_Server;
|
public override FunGameInfo.FunGame FunGameType { get; } = FunGameInfo.FunGame.FunGame_Server;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 使用的数据库类型
|
||||||
|
/// </summary>
|
||||||
public override SQLMode Mode { get; } = SQLMode.MySQL;
|
public override SQLMode Mode { get; } = SQLMode.MySQL;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// SQL 脚本
|
||||||
|
/// </summary>
|
||||||
public override string Script { get; set; } = "";
|
public override string Script { get; set; } = "";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 命令类型
|
||||||
|
/// </summary>
|
||||||
public override CommandType CommandType { get; set; } = CommandType.Text;
|
public override CommandType CommandType { get; set; } = CommandType.Text;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 数据库事务
|
||||||
|
/// </summary>
|
||||||
|
public override DbTransaction? Transaction => _transaction;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 执行结果
|
||||||
|
/// </summary>
|
||||||
public override SQLResult Result => _result;
|
public override SQLResult Result => _result;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// SQL 服务器信息
|
||||||
|
/// </summary>
|
||||||
public override SQLServerInfo ServerInfo => _serverInfo ?? SQLServerInfo.Create();
|
public override SQLServerInfo ServerInfo => _serverInfo ?? SQLServerInfo.Create();
|
||||||
public override int UpdateRows => _updateRows;
|
|
||||||
|
/// <summary>
|
||||||
|
/// 上一次执行命令影响的行数
|
||||||
|
/// </summary>
|
||||||
|
public override int AffectedRows => _affectedRows;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 上一次执行的命令是 Insert 时,返回的自增 ID,大于 0 有效
|
||||||
|
/// </summary>
|
||||||
|
public override long LastInsertId => _lastInsertId;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 上一次执行命令的查询结果集
|
||||||
|
/// </summary>
|
||||||
public override DataSet DataSet => _dataSet;
|
public override DataSet DataSet => _dataSet;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// SQL 语句参数
|
||||||
|
/// </summary>
|
||||||
public override Dictionary<string, object> Parameters { get; } = [];
|
public override Dictionary<string, object> Parameters { get; } = [];
|
||||||
|
|
||||||
private readonly string _connectionString = "";
|
private readonly string _connectionString = "";
|
||||||
@ -25,7 +71,8 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
private DataSet _dataSet = new();
|
private DataSet _dataSet = new();
|
||||||
private SQLResult _result = SQLResult.NotFound;
|
private SQLResult _result = SQLResult.NotFound;
|
||||||
private readonly SQLServerInfo? _serverInfo;
|
private readonly SQLServerInfo? _serverInfo;
|
||||||
private int _updateRows = 0;
|
private int _affectedRows = 0;
|
||||||
|
private long _lastInsertId = 0;
|
||||||
|
|
||||||
public MySQLHelper(string script = "", CommandType type = CommandType.Text)
|
public MySQLHelper(string script = "", CommandType type = CommandType.Text)
|
||||||
{
|
{
|
||||||
@ -69,7 +116,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 执行一个命令
|
/// 执行现有命令(<see cref="Script"/>)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public override int Execute()
|
public override int Execute()
|
||||||
@ -104,14 +151,24 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
}
|
}
|
||||||
if (_transaction != null) command.Transaction = _transaction;
|
if (_transaction != null) command.Transaction = _transaction;
|
||||||
|
|
||||||
_updateRows = command.ExecuteNonQuery();
|
ReSet();
|
||||||
_result = SQLResult.Success;
|
_affectedRows = command.ExecuteNonQuery();
|
||||||
|
if (_affectedRows > 0)
|
||||||
|
{
|
||||||
|
_result = SQLResult.Success;
|
||||||
|
if (script.Contains(Core.Library.SQLScript.Constant.Command_Insert, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
_lastInsertId = command.LastInsertedId;
|
||||||
|
if (_lastInsertId < 0) _lastInsertId = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else _result = SQLResult.Fail;
|
||||||
if (localTransaction) Commit();
|
if (localTransaction) Commit();
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
if (localTransaction) Rollback();
|
if (localTransaction) Rollback();
|
||||||
_result = SQLResult.Fail;
|
_result = SQLResult.SQLError;
|
||||||
ServerHelper.Error(e);
|
ServerHelper.Error(e);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
@ -119,11 +176,75 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
if (localTransaction) Close();
|
if (localTransaction) Close();
|
||||||
if (ClearParametersAfterExecute) Parameters.Clear();
|
if (ClearParametersAfterExecute) Parameters.Clear();
|
||||||
}
|
}
|
||||||
return UpdateRows;
|
return AffectedRows;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 查询DataSet
|
/// 异步执行现有命令(<see cref="Script"/>)
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
public override async Task<int> ExecuteAsync()
|
||||||
|
{
|
||||||
|
return await ExecuteAsync(Script);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 异步执行一个指定的命令
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="script"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public override async Task<int> ExecuteAsync(string script)
|
||||||
|
{
|
||||||
|
bool localTransaction = _transaction == null;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (localTransaction)
|
||||||
|
{
|
||||||
|
NewTransaction();
|
||||||
|
}
|
||||||
|
|
||||||
|
OpenConnection();
|
||||||
|
Script = script;
|
||||||
|
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api);
|
||||||
|
using MySqlCommand command = new(script, _connection);
|
||||||
|
command.CommandType = CommandType;
|
||||||
|
foreach (KeyValuePair<string, object> param in Parameters)
|
||||||
|
{
|
||||||
|
command.Parameters.AddWithValue(param.Key, param.Value);
|
||||||
|
}
|
||||||
|
if (_transaction != null) command.Transaction = _transaction;
|
||||||
|
|
||||||
|
ReSet();
|
||||||
|
_affectedRows = await command.ExecuteNonQueryAsync();
|
||||||
|
if (_affectedRows > 0)
|
||||||
|
{
|
||||||
|
_result = SQLResult.Success;
|
||||||
|
if (script.Contains(Core.Library.SQLScript.Constant.Command_Insert, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
_lastInsertId = command.LastInsertedId;
|
||||||
|
if (_lastInsertId < 0) _lastInsertId = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else _result = SQLResult.Fail;
|
||||||
|
if (localTransaction) Commit();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
if (localTransaction) Rollback();
|
||||||
|
_result = SQLResult.SQLError;
|
||||||
|
ServerHelper.Error(e);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (localTransaction) Close();
|
||||||
|
if (ClearParametersAfterExecute) Parameters.Clear();
|
||||||
|
}
|
||||||
|
return AffectedRows;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 执行现有命令(<see cref="Script"/>)查询 DataSet
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public override DataSet ExecuteDataSet()
|
public override DataSet ExecuteDataSet()
|
||||||
@ -132,7 +253,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 执行指定的命令查询DataSet
|
/// 执行指定的命令查询 DataSet
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="script"></param>
|
/// <param name="script"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
@ -161,12 +282,13 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
}
|
}
|
||||||
if (_transaction != null) command.Transaction = _transaction;
|
if (_transaction != null) command.Transaction = _transaction;
|
||||||
|
|
||||||
|
ReSet();
|
||||||
MySqlDataAdapter adapter = new()
|
MySqlDataAdapter adapter = new()
|
||||||
{
|
{
|
||||||
SelectCommand = command
|
SelectCommand = command
|
||||||
};
|
};
|
||||||
_dataSet = new();
|
_dataSet = new();
|
||||||
adapter.Fill(_dataSet);
|
_affectedRows = adapter.Fill(_dataSet);
|
||||||
|
|
||||||
if (localTransaction) Commit();
|
if (localTransaction) Commit();
|
||||||
|
|
||||||
@ -175,7 +297,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
if (localTransaction) Rollback();
|
if (localTransaction) Rollback();
|
||||||
_result = SQLResult.Fail;
|
_result = SQLResult.SQLError;
|
||||||
ServerHelper.Error(e);
|
ServerHelper.Error(e);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
@ -187,26 +309,68 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 检查数据库是否存在
|
/// 异步执行现有命令(<see cref="Script"/>)查询 DataSet
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public override bool DatabaseExists()
|
public override async Task<DataSet> ExecuteDataSetAsync()
|
||||||
{
|
{
|
||||||
|
return await ExecuteDataSetAsync(Script);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 异步执行指定的命令查询 DataSet
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="script"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public override async Task<DataSet> ExecuteDataSetAsync(string script)
|
||||||
|
{
|
||||||
|
bool localTransaction = _transaction == null;
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
ExecuteDataSet(Core.Library.SQLScript.Common.Configs.Select_GetConfig(this, "Initialization"));
|
if (localTransaction)
|
||||||
return Success;
|
{
|
||||||
|
NewTransaction();
|
||||||
|
}
|
||||||
|
|
||||||
|
OpenConnection();
|
||||||
|
Script = script;
|
||||||
|
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api);
|
||||||
|
|
||||||
|
using MySqlCommand command = new(script, _connection)
|
||||||
|
{
|
||||||
|
CommandType = CommandType
|
||||||
|
};
|
||||||
|
foreach (KeyValuePair<string, object> param in Parameters)
|
||||||
|
{
|
||||||
|
command.Parameters.AddWithValue(param.Key, param.Value);
|
||||||
|
}
|
||||||
|
if (_transaction != null) command.Transaction = _transaction;
|
||||||
|
|
||||||
|
ReSet();
|
||||||
|
MySqlDataAdapter adapter = new()
|
||||||
|
{
|
||||||
|
SelectCommand = command
|
||||||
|
};
|
||||||
|
_dataSet = new();
|
||||||
|
_affectedRows = await adapter.FillAsync(_dataSet);
|
||||||
|
|
||||||
|
if (localTransaction) Commit();
|
||||||
|
|
||||||
|
_result = _dataSet.Tables.Cast<DataTable>().Any(table => table.Rows.Count > 0) ? SQLResult.Success : SQLResult.NotFound;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
|
if (localTransaction) Rollback();
|
||||||
|
_result = SQLResult.SQLError;
|
||||||
ServerHelper.Error(e);
|
ServerHelper.Error(e);
|
||||||
_result = SQLResult.Fail;
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
Close();
|
if (localTransaction) Close();
|
||||||
|
if (ClearParametersAfterExecute) Parameters.Clear();
|
||||||
}
|
}
|
||||||
|
return _dataSet;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -233,7 +397,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
_result = SQLResult.Fail;
|
_result = SQLResult.SQLError;
|
||||||
ServerHelper.Error(e);
|
ServerHelper.Error(e);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
@ -254,7 +418,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
_result = SQLResult.Fail;
|
_result = SQLResult.SQLError;
|
||||||
ServerHelper.Error(e);
|
ServerHelper.Error(e);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
@ -263,12 +427,35 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 检查数据库是否存在
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
public override bool DatabaseExists()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ExecuteDataSet(Core.Library.SQLScript.Common.Configs.Select_GetConfig(this, "Initialization"));
|
||||||
|
return Success;
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
ServerHelper.Error(e);
|
||||||
|
_result = SQLResult.SQLError;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private bool _isDisposed = false;
|
private bool _isDisposed = false;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 资源清理
|
/// 资源清理
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public void Dispose(bool disposing)
|
private void Dispose(bool disposing)
|
||||||
{
|
{
|
||||||
if (!_isDisposed)
|
if (!_isDisposed)
|
||||||
{
|
{
|
||||||
@ -289,5 +476,13 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
Dispose(true);
|
Dispose(true);
|
||||||
GC.SuppressFinalize(this);
|
GC.SuppressFinalize(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void ReSet()
|
||||||
|
{
|
||||||
|
_result = SQLResult.NotFound;
|
||||||
|
_affectedRows = 0;
|
||||||
|
_lastInsertId = 0;
|
||||||
|
DataSet.Clear();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,4 +1,5 @@
|
|||||||
using System.Data;
|
using System.Data;
|
||||||
|
using System.Data.Common;
|
||||||
using Microsoft.Data.Sqlite;
|
using Microsoft.Data.Sqlite;
|
||||||
using Milimoe.FunGame.Core.Api.Transmittal;
|
using Milimoe.FunGame.Core.Api.Transmittal;
|
||||||
using Milimoe.FunGame.Core.Library.Constant;
|
using Milimoe.FunGame.Core.Library.Constant;
|
||||||
@ -9,14 +10,59 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
{
|
{
|
||||||
public class SQLiteHelper : SQLHelper
|
public class SQLiteHelper : SQLHelper
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// FunGame 类型
|
||||||
|
/// </summary>
|
||||||
public override FunGameInfo.FunGame FunGameType { get; } = FunGameInfo.FunGame.FunGame_Server;
|
public override FunGameInfo.FunGame FunGameType { get; } = FunGameInfo.FunGame.FunGame_Server;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 使用的数据库类型
|
||||||
|
/// </summary>
|
||||||
public override SQLMode Mode { get; } = SQLMode.SQLite;
|
public override SQLMode Mode { get; } = SQLMode.SQLite;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// SQL 脚本
|
||||||
|
/// </summary>
|
||||||
public override string Script { get; set; } = "";
|
public override string Script { get; set; } = "";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 命令类型
|
||||||
|
/// </summary>
|
||||||
public override CommandType CommandType { get; set; } = CommandType.Text;
|
public override CommandType CommandType { get; set; } = CommandType.Text;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 数据库事务
|
||||||
|
/// </summary>
|
||||||
|
public override DbTransaction? Transaction => _transaction;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 执行结果
|
||||||
|
/// </summary>
|
||||||
public override SQLResult Result => _result;
|
public override SQLResult Result => _result;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// SQL 服务器信息
|
||||||
|
/// </summary>
|
||||||
public override SQLServerInfo ServerInfo => _serverInfo ?? SQLServerInfo.Create();
|
public override SQLServerInfo ServerInfo => _serverInfo ?? SQLServerInfo.Create();
|
||||||
public override int UpdateRows => _updateRows;
|
|
||||||
|
/// <summary>
|
||||||
|
/// 上一次执行命令影响的行数
|
||||||
|
/// </summary>
|
||||||
|
public override int AffectedRows => _affectedRows;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 上一次执行的命令是 Insert 时,返回的自增 ID,大于 0 有效
|
||||||
|
/// </summary>
|
||||||
|
public override long LastInsertId => _lastInsertId;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 上一次执行命令的查询结果集
|
||||||
|
/// </summary>
|
||||||
public override DataSet DataSet => _dataSet;
|
public override DataSet DataSet => _dataSet;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// SQL 语句参数
|
||||||
|
/// </summary>
|
||||||
public override Dictionary<string, object> Parameters { get; } = [];
|
public override Dictionary<string, object> Parameters { get; } = [];
|
||||||
|
|
||||||
private readonly string _connectionString = "";
|
private readonly string _connectionString = "";
|
||||||
@ -25,7 +71,8 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
private DataSet _dataSet = new();
|
private DataSet _dataSet = new();
|
||||||
private SQLResult _result = SQLResult.NotFound;
|
private SQLResult _result = SQLResult.NotFound;
|
||||||
private readonly SQLServerInfo? _serverInfo;
|
private readonly SQLServerInfo? _serverInfo;
|
||||||
private int _updateRows = 0;
|
private int _affectedRows = 0;
|
||||||
|
private long _lastInsertId = 0;
|
||||||
|
|
||||||
public SQLiteHelper(string script = "", CommandType type = CommandType.Text)
|
public SQLiteHelper(string script = "", CommandType type = CommandType.Text)
|
||||||
{
|
{
|
||||||
@ -67,7 +114,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 执行一个命令
|
/// 执行现有命令(<see cref="Script"/>)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public override int Execute()
|
public override int Execute()
|
||||||
@ -102,14 +149,26 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
}
|
}
|
||||||
if (_transaction != null) command.Transaction = _transaction;
|
if (_transaction != null) command.Transaction = _transaction;
|
||||||
|
|
||||||
_updateRows = command.ExecuteNonQuery();
|
ReSet();
|
||||||
_result = SQLResult.Success;
|
_affectedRows = command.ExecuteNonQuery();
|
||||||
|
if (_affectedRows > 0)
|
||||||
|
{
|
||||||
|
_result = SQLResult.Success;
|
||||||
|
if (script.Contains(Core.Library.SQLScript.Constant.Command_Insert, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
using SqliteCommand idCommand = new("SELECT last_insert_rowid()", _connection);
|
||||||
|
if (_transaction != null) idCommand.Transaction = _transaction;
|
||||||
|
_lastInsertId = (long?)idCommand.ExecuteScalar() ?? 0;
|
||||||
|
if (_lastInsertId < 0) _lastInsertId = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else _result = SQLResult.Fail;
|
||||||
if (localTransaction) Commit();
|
if (localTransaction) Commit();
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
if (localTransaction) Rollback();
|
if (localTransaction) Rollback();
|
||||||
_result = SQLResult.Fail;
|
_result = SQLResult.SQLError;
|
||||||
ServerHelper.Error(e);
|
ServerHelper.Error(e);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
@ -117,11 +176,77 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
if (localTransaction) Close();
|
if (localTransaction) Close();
|
||||||
if (ClearParametersAfterExecute) Parameters.Clear();
|
if (ClearParametersAfterExecute) Parameters.Clear();
|
||||||
}
|
}
|
||||||
return UpdateRows;
|
return AffectedRows;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 查询DataSet
|
/// 异步执行现有命令(<see cref="Script"/>)
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
public override async Task<int> ExecuteAsync()
|
||||||
|
{
|
||||||
|
return await ExecuteAsync(Script);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 异步执行一个指定的命令
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="script"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public override async Task<int> ExecuteAsync(string script)
|
||||||
|
{
|
||||||
|
bool localTransaction = _transaction == null;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (localTransaction)
|
||||||
|
{
|
||||||
|
NewTransaction();
|
||||||
|
}
|
||||||
|
|
||||||
|
OpenConnection();
|
||||||
|
Script = script;
|
||||||
|
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api);
|
||||||
|
using SqliteCommand command = new(script, _connection);
|
||||||
|
command.CommandType = CommandType;
|
||||||
|
foreach (KeyValuePair<string, object> param in Parameters)
|
||||||
|
{
|
||||||
|
command.Parameters.AddWithValue(param.Key, param.Value);
|
||||||
|
}
|
||||||
|
if (_transaction != null) command.Transaction = _transaction;
|
||||||
|
|
||||||
|
ReSet();
|
||||||
|
_affectedRows = await command.ExecuteNonQueryAsync();
|
||||||
|
if (_affectedRows > 0)
|
||||||
|
{
|
||||||
|
_result = SQLResult.Success;
|
||||||
|
if (script.Contains(Core.Library.SQLScript.Constant.Command_Insert, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
using SqliteCommand idCommand = new("SELECT last_insert_rowid()", _connection);
|
||||||
|
if (_transaction != null) idCommand.Transaction = _transaction;
|
||||||
|
_lastInsertId = (long?)await idCommand.ExecuteScalarAsync() ?? 0;
|
||||||
|
if (_lastInsertId < 0) _lastInsertId = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else _result = SQLResult.Fail;
|
||||||
|
if (localTransaction) Commit();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
if (localTransaction) Rollback();
|
||||||
|
_result = SQLResult.SQLError;
|
||||||
|
ServerHelper.Error(e);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (localTransaction) Close();
|
||||||
|
if (ClearParametersAfterExecute) Parameters.Clear();
|
||||||
|
}
|
||||||
|
return AffectedRows;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 执行现有命令(<see cref="Script"/>)查询 DataSet
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public override DataSet ExecuteDataSet()
|
public override DataSet ExecuteDataSet()
|
||||||
@ -130,7 +255,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 执行指定的命令查询DataSet
|
/// 执行指定的命令查询 DataSet
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="script"></param>
|
/// <param name="script"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
@ -158,6 +283,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
}
|
}
|
||||||
if (_transaction != null) command.Transaction = _transaction;
|
if (_transaction != null) command.Transaction = _transaction;
|
||||||
|
|
||||||
|
ReSet();
|
||||||
using SqliteDataReader reader = command.ExecuteReader();
|
using SqliteDataReader reader = command.ExecuteReader();
|
||||||
_dataSet = new();
|
_dataSet = new();
|
||||||
do
|
do
|
||||||
@ -174,7 +300,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
if (localTransaction) Rollback();
|
if (localTransaction) Rollback();
|
||||||
_result = SQLResult.Fail;
|
_result = SQLResult.SQLError;
|
||||||
ServerHelper.Error(e);
|
ServerHelper.Error(e);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
@ -186,7 +312,73 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 创建一个SQL事务
|
/// 异步执行现有命令(<see cref="Script"/>)查询 DataSet
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
public override async Task<DataSet> ExecuteDataSetAsync()
|
||||||
|
{
|
||||||
|
return await ExecuteDataSetAsync(Script);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 异步执行指定的命令查询 DataSet
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="script"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public override async Task<DataSet> ExecuteDataSetAsync(string script)
|
||||||
|
{
|
||||||
|
bool localTransaction = _transaction == null;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (localTransaction)
|
||||||
|
{
|
||||||
|
NewTransaction();
|
||||||
|
}
|
||||||
|
|
||||||
|
OpenConnection();
|
||||||
|
Script = script;
|
||||||
|
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api);
|
||||||
|
using SqliteCommand command = new(script, _connection)
|
||||||
|
{
|
||||||
|
CommandType = CommandType
|
||||||
|
};
|
||||||
|
foreach (KeyValuePair<string, object> param in Parameters)
|
||||||
|
{
|
||||||
|
command.Parameters.AddWithValue(param.Key, param.Value);
|
||||||
|
}
|
||||||
|
if (_transaction != null) command.Transaction = _transaction;
|
||||||
|
|
||||||
|
ReSet();
|
||||||
|
using SqliteDataReader reader = await command.ExecuteReaderAsync();
|
||||||
|
_dataSet = new();
|
||||||
|
do
|
||||||
|
{
|
||||||
|
DataTable table = new();
|
||||||
|
table.Load(reader);
|
||||||
|
_dataSet.Tables.Add(table);
|
||||||
|
} while (!reader.IsClosed && reader.NextResult());
|
||||||
|
|
||||||
|
if (localTransaction) Commit();
|
||||||
|
|
||||||
|
_result = _dataSet.Tables.Cast<DataTable>().Any(table => table.Rows.Count > 0) ? SQLResult.Success : SQLResult.NotFound;
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
if (localTransaction) Rollback();
|
||||||
|
_result = SQLResult.SQLError;
|
||||||
|
ServerHelper.Error(e);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (localTransaction) Close();
|
||||||
|
if (ClearParametersAfterExecute) Parameters.Clear();
|
||||||
|
}
|
||||||
|
return _dataSet;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建一个 SQL 事务
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public override void NewTransaction()
|
public override void NewTransaction()
|
||||||
{
|
{
|
||||||
@ -209,7 +401,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
_result = SQLResult.Fail;
|
_result = SQLResult.SQLError;
|
||||||
ServerHelper.Error(e);
|
ServerHelper.Error(e);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
@ -230,7 +422,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
_result = SQLResult.Fail;
|
_result = SQLResult.SQLError;
|
||||||
ServerHelper.Error(e);
|
ServerHelper.Error(e);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
@ -253,7 +445,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
ServerHelper.Error(e);
|
ServerHelper.Error(e);
|
||||||
_result = SQLResult.Fail;
|
_result = SQLResult.SQLError;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
@ -267,7 +459,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// 资源清理
|
/// 资源清理
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public void Dispose(bool disposing)
|
private void Dispose(bool disposing)
|
||||||
{
|
{
|
||||||
if (!_isDisposed)
|
if (!_isDisposed)
|
||||||
{
|
{
|
||||||
@ -288,5 +480,13 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
|||||||
Dispose(true);
|
Dispose(true);
|
||||||
GC.SuppressFinalize(this);
|
GC.SuppressFinalize(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void ReSet()
|
||||||
|
{
|
||||||
|
_result = SQLResult.NotFound;
|
||||||
|
_affectedRows = 0;
|
||||||
|
_lastInsertId = 0;
|
||||||
|
DataSet.Clear();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,11 +1,11 @@
|
|||||||
using System.Collections;
|
using Milimoe.FunGame.Core.Api.Transmittal;
|
||||||
using Milimoe.FunGame.Core.Api.Transmittal;
|
|
||||||
using Milimoe.FunGame.Core.Api.Utility;
|
using Milimoe.FunGame.Core.Api.Utility;
|
||||||
using Milimoe.FunGame.Core.Library.Common.Addon;
|
using Milimoe.FunGame.Core.Library.Common.Addon;
|
||||||
using Milimoe.FunGame.Core.Library.Constant;
|
using Milimoe.FunGame.Core.Library.Constant;
|
||||||
using Milimoe.FunGame.Core.Library.SQLScript.Common;
|
using Milimoe.FunGame.Core.Library.SQLScript.Common;
|
||||||
using Milimoe.FunGame.Core.Library.SQLScript.Entity;
|
using Milimoe.FunGame.Core.Library.SQLScript.Entity;
|
||||||
using Milimoe.FunGame.Core.Model;
|
using Milimoe.FunGame.Core.Model;
|
||||||
|
using Milimoe.FunGame.Server.Model;
|
||||||
using Milimoe.FunGame.Server.Others;
|
using Milimoe.FunGame.Server.Others;
|
||||||
using Milimoe.FunGame.Server.Services.DataUtility;
|
using Milimoe.FunGame.Server.Services.DataUtility;
|
||||||
|
|
||||||
@ -13,10 +13,13 @@ namespace Milimoe.FunGame.Server.Services
|
|||||||
{
|
{
|
||||||
public class FunGameSystem
|
public class FunGameSystem
|
||||||
{
|
{
|
||||||
|
public delegate Task CloseListenerHandler();
|
||||||
|
public static event CloseListenerHandler? CloseListener;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 服务器指令列表
|
/// 服务器指令列表
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static Hashtable OrderList { get; } = [];
|
public static Dictionary<string, Action<string>> OrderList { get; } = [];
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 在线房间列表
|
/// 在线房间列表
|
||||||
@ -46,6 +49,11 @@ namespace Milimoe.FunGame.Server.Services
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// 服务器配置
|
/// 服务器配置
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
public static PluginConfig LocalConfig { get; set; } = new("system", "local");
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 数据库配置
|
||||||
|
/// </summary>
|
||||||
public static PluginConfig SQLConfig { get; set; } = new("system", "sqlconfig");
|
public static PluginConfig SQLConfig { get; set; } = new("system", "sqlconfig");
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -53,6 +61,11 @@ namespace Milimoe.FunGame.Server.Services
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public const string FunGameWebAPITokenID = "fungame_web_api";
|
public const string FunGameWebAPITokenID = "fungame_web_api";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// API Secret 文件名
|
||||||
|
/// </summary>
|
||||||
|
public const string APISecretFileName = ".apisecret";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 初始化数据库连接器
|
/// 初始化数据库连接器
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@ -225,7 +238,7 @@ namespace Milimoe.FunGame.Server.Services
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public static void ServerLogin(SQLHelper sqlHelper)
|
public static void ServerLogin(SQLHelper sqlHelper)
|
||||||
{
|
{
|
||||||
sqlHelper.Execute(ServerLoginLogs.Insert_ServerLoginLogs(sqlHelper, Config.ServerName, Config.ServerKey));
|
sqlHelper.Execute(ServerLoginLogs.Insert_ServerLoginLog(sqlHelper, Config.ServerName, Config.ServerKey));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -237,10 +250,12 @@ namespace Milimoe.FunGame.Server.Services
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 初始化用户密钥列表
|
/// 初始化服务器其他配置文件
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static void InitUserKeys()
|
public static void InitOtherConfig()
|
||||||
{
|
{
|
||||||
|
LocalConfig.LoadConfig();
|
||||||
|
LocalConfig.SaveConfig();
|
||||||
UserKeys.LoadConfig();
|
UserKeys.LoadConfig();
|
||||||
UserKeys.SaveConfig();
|
UserKeys.SaveConfig();
|
||||||
}
|
}
|
||||||
@ -274,11 +289,12 @@ namespace Milimoe.FunGame.Server.Services
|
|||||||
/// 检查是否存在 API Secret Key
|
/// 检查是否存在 API Secret Key
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="key"></param>
|
/// <param name="key"></param>
|
||||||
public static bool IsAPISecretKeyExist(string key)
|
public static bool APISecretKeyExists(string key)
|
||||||
{
|
{
|
||||||
using SQLHelper? sql = Factory.OpenFactory.GetSQLHelper();
|
using SQLHelper? sql = Factory.OpenFactory.GetSQLHelper();
|
||||||
if (sql != null)
|
if (sql != null)
|
||||||
{
|
{
|
||||||
|
key = Encryption.HmacSha256(key, Encryption.FileSha256(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, APISecretFileName)));
|
||||||
sql.ExecuteDataSet(ApiTokens.Select_GetAPISecretKey(sql, key));
|
sql.ExecuteDataSet(ApiTokens.Select_GetAPISecretKey(sql, key));
|
||||||
if (sql.Result == SQLResult.Success)
|
if (sql.Result == SQLResult.Success)
|
||||||
{
|
{
|
||||||
@ -289,54 +305,42 @@ namespace Milimoe.FunGame.Server.Services
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 获取 API Secret Key
|
/// 创建 API Secret Key
|
||||||
/// </summary>
|
|
||||||
/// <param name="token"></param>
|
|
||||||
public static string GetAPISecretKey(string token)
|
|
||||||
{
|
|
||||||
using SQLHelper? sql = Factory.OpenFactory.GetSQLHelper();
|
|
||||||
if (sql != null)
|
|
||||||
{
|
|
||||||
sql.ExecuteDataSet(ApiTokens.Select_GetAPIToken(sql, token));
|
|
||||||
if (sql.Result == SQLResult.Success)
|
|
||||||
{
|
|
||||||
return sql.DataSet.Tables[0].Rows[0][ApiTokens.Column_SecretKey].ToString() ?? "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 设置 API Secret Key
|
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="token"></param>
|
/// <param name="token"></param>
|
||||||
/// <param name="reference1"></param>
|
/// <param name="reference1"></param>
|
||||||
/// <param name="reference2"></param>
|
/// <param name="reference2"></param>
|
||||||
public static void SetAPISecretKey(string token, string reference1 = "", string reference2 = "", SQLHelper? sqlHelper = null)
|
public static string CreateAPISecretKey(string token, string reference1 = "", string reference2 = "", SQLHelper? sqlHelper = null)
|
||||||
{
|
{
|
||||||
bool useSQLHelper = sqlHelper != null;
|
bool useSQLHelper = sqlHelper != null;
|
||||||
sqlHelper ??= Factory.OpenFactory.GetSQLHelper();
|
sqlHelper ??= Factory.OpenFactory.GetSQLHelper();
|
||||||
string key = Encryption.GenerateRandomString();
|
string key = Encryption.GenerateRandomString();
|
||||||
if (sqlHelper != null)
|
string enKey = Encryption.HmacSha256(key, Encryption.FileSha256(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, APISecretFileName)));
|
||||||
|
if (sqlHelper != null && enKey != "")
|
||||||
{
|
{
|
||||||
sqlHelper.ExecuteDataSet(ApiTokens.Select_GetAPIToken(sqlHelper, token));
|
sqlHelper.ExecuteDataSet(ApiTokens.Select_GetAPIToken(sqlHelper, token));
|
||||||
if (sqlHelper.Success)
|
if (sqlHelper.Success)
|
||||||
{
|
{
|
||||||
sqlHelper.Execute(ApiTokens.Update_APIToken(sqlHelper, token, key, reference1, reference2));
|
sqlHelper.Execute(ApiTokens.Update_APIToken(sqlHelper, token, enKey, reference1, reference2));
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
sqlHelper.Execute(ApiTokens.Insert_APIToken(sqlHelper, token, key, reference1, reference2));
|
sqlHelper.Execute(ApiTokens.Insert_APIToken(sqlHelper, token, enKey, reference1, reference2));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ServerHelper.WriteLine($"API Secret Key '{token}' 创建失败,未连接到数据库或者找不到加密秘钥。", InvokeMessageType.Error);
|
||||||
|
}
|
||||||
if (!useSQLHelper)
|
if (!useSQLHelper)
|
||||||
{
|
{
|
||||||
sqlHelper?.Dispose();
|
sqlHelper?.Dispose();
|
||||||
}
|
}
|
||||||
|
return key;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 创建 SQL 服务后需要做的事
|
/// 创建 SQL 服务后需要做的事,包括数据库初始化,API 初始化,首次建立管理员账户等等
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="sqlHelper"></param>
|
/// <param name="sqlHelper"></param>
|
||||||
public static void AfterCreateSQLService(SQLHelper sqlHelper)
|
public static void AfterCreateSQLService(SQLHelper sqlHelper)
|
||||||
@ -354,7 +358,12 @@ namespace Milimoe.FunGame.Server.Services
|
|||||||
{
|
{
|
||||||
mysqlHelper.ExecuteSqlFile(AppDomain.CurrentDomain.BaseDirectory + "fungame.sql");
|
mysqlHelper.ExecuteSqlFile(AppDomain.CurrentDomain.BaseDirectory + "fungame.sql");
|
||||||
}
|
}
|
||||||
SetAPISecretKey(FunGameWebAPITokenID, sqlHelper: sqlHelper);
|
ConsoleModel.FirstRunRegAdmin();
|
||||||
|
using StreamWriter sw = File.CreateText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, APISecretFileName));
|
||||||
|
sw.WriteLine(Encryption.GenerateRandomString());
|
||||||
|
sw.Flush();
|
||||||
|
sw.Close();
|
||||||
|
ServerHelper.WriteLine($"已生成一个默认的 API Token,Token ID: {FunGameWebAPITokenID}, Secret Key: 【{CreateAPISecretKey(FunGameWebAPITokenID, sqlHelper: sqlHelper)}】,请妥善保管方括号内的内容,仅显示一次。如遗忘需要使用管理员账号重置。");
|
||||||
sqlHelper.Execute(Configs.Insert_Config(sqlHelper, "Initialization", FunGameInfo.FunGame_Version, "SQL Service Installed."));
|
sqlHelper.Execute(Configs.Insert_Config(sqlHelper, "Initialization", FunGameInfo.FunGame_Version, "SQL Service Installed."));
|
||||||
SQLConfig.Clear();
|
SQLConfig.Clear();
|
||||||
SQLConfig.Add("Initialized", true);
|
SQLConfig.Add("Initialized", true);
|
||||||
@ -367,6 +376,10 @@ namespace Milimoe.FunGame.Server.Services
|
|||||||
sqlHelper.Dispose();
|
sqlHelper.Dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 数据库是否存在
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
public static bool DatabaseExists()
|
public static bool DatabaseExists()
|
||||||
{
|
{
|
||||||
SQLConfig.LoadConfig();
|
SQLConfig.LoadConfig();
|
||||||
@ -403,6 +416,8 @@ namespace Milimoe.FunGame.Server.Services
|
|||||||
plugin.Controller.Close();
|
plugin.Controller.Close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 停止所有正在运行的监听
|
||||||
|
CloseListener?.Invoke();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -234,11 +234,11 @@ namespace Milimoe.FunGame.Server.Services
|
|||||||
public static void InitOrderList()
|
public static void InitOrderList()
|
||||||
{
|
{
|
||||||
FunGameSystem.OrderList.Clear();
|
FunGameSystem.OrderList.Clear();
|
||||||
FunGameSystem.OrderList.Add(OrderDictionary.Help, "Milimoe -> 帮助");
|
FunGameSystem.OrderList.Add(OrderDictionary.Help, s => WriteLine("Milimoe -> 帮助"));
|
||||||
FunGameSystem.OrderList.Add(OrderDictionary.Quit, "关闭服务器");
|
FunGameSystem.OrderList.Add(OrderDictionary.Quit, s => WriteLine("关闭服务器"));
|
||||||
FunGameSystem.OrderList.Add(OrderDictionary.Exit, "关闭服务器");
|
FunGameSystem.OrderList.Add(OrderDictionary.Exit, s => WriteLine("关闭服务器"));
|
||||||
FunGameSystem.OrderList.Add(OrderDictionary.Close, "关闭服务器");
|
FunGameSystem.OrderList.Add(OrderDictionary.Close, s => WriteLine("关闭服务器"));
|
||||||
FunGameSystem.OrderList.Add(OrderDictionary.Restart, "重启服务器");
|
FunGameSystem.OrderList.Add(OrderDictionary.Restart, s => WriteLine("重启服务器"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 66 KiB |
@ -19,6 +19,7 @@ namespace Milimoe.FunGame.WebAPI.Controllers
|
|||||||
{
|
{
|
||||||
PayloadModel<DataRequestType> response = new()
|
PayloadModel<DataRequestType> response = new()
|
||||||
{
|
{
|
||||||
|
Event = "data_request",
|
||||||
RequestType = payload.RequestType
|
RequestType = payload.RequestType
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@ -19,6 +19,7 @@ namespace Milimoe.FunGame.WebAPI.Controllers
|
|||||||
{
|
{
|
||||||
PayloadModel<GamingType> response = new()
|
PayloadModel<GamingType> response = new()
|
||||||
{
|
{
|
||||||
|
Event = "gaming_request",
|
||||||
RequestType = payload.RequestType
|
RequestType = payload.RequestType
|
||||||
};
|
};
|
||||||
if (model.RequestID == Guid.Empty)
|
if (model.RequestID == Guid.Empty)
|
||||||
|
|||||||
437
FunGame.WebAPI/Controllers/InventoryController.cs
Normal file
437
FunGame.WebAPI/Controllers/InventoryController.cs
Normal file
@ -0,0 +1,437 @@
|
|||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Milimoe.FunGame.Core.Library.Constant;
|
||||||
|
using Milimoe.FunGame.Core.Library.SQLScript.Entity;
|
||||||
|
using Milimoe.FunGame.WebAPI.Models;
|
||||||
|
|
||||||
|
namespace Milimoe.FunGame.WebAPI.Controllers
|
||||||
|
{
|
||||||
|
[ApiController]
|
||||||
|
[Route("[controller]")]
|
||||||
|
[Authorize]
|
||||||
|
public class InventoryController(RESTfulAPIModel model, ILogger<InventoryController> logger) : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly ILogger<InventoryController> _logger = logger;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取商店内容
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("getstore")]
|
||||||
|
public async Task<IActionResult> GetStore(long[] ids)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "inventory_getstore",
|
||||||
|
RequestType = DataRequestType.Inventory_GetStore
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> data = new()
|
||||||
|
{
|
||||||
|
{ "ids", ids }
|
||||||
|
};
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Inventory_GetStore, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取市场内容
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("getmarket")]
|
||||||
|
public async Task<IActionResult> GetMarket(long[]? users = null, MarketItemState state = MarketItemState.Listed, long[]? items = null)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "inventory_getmarket",
|
||||||
|
RequestType = DataRequestType.Inventory_GetMarket
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> data = new()
|
||||||
|
{
|
||||||
|
{ "users", users ?? [] },
|
||||||
|
{ "state", state },
|
||||||
|
{ "items", items ?? [] }
|
||||||
|
};
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Inventory_GetMarket, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 商店购买物品
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("storebuy")]
|
||||||
|
public async Task<IActionResult> StoreBuy([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "inventory_storebuy",
|
||||||
|
RequestType = DataRequestType.Inventory_StoreBuy
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Inventory_StoreBuy, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 市场购买物品
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("marketbuy")]
|
||||||
|
public async Task<IActionResult> MarketBuy([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "inventory_marketbuy",
|
||||||
|
RequestType = DataRequestType.Inventory_MarketBuy
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Inventory_MarketBuy, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 更新库存
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("updateinventory")]
|
||||||
|
public async Task<IActionResult> UpdateInventory([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "inventory_updateinventory",
|
||||||
|
RequestType = DataRequestType.Inventory_UpdateInventory
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Inventory_UpdateInventory, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 使用库存物品
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("useitem")]
|
||||||
|
public async Task<IActionResult> Use([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "inventory_use",
|
||||||
|
RequestType = DataRequestType.Inventory_Use
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Inventory_Use, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 商店出售物品
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("storesell")]
|
||||||
|
public async Task<IActionResult> StoreSell([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "inventory_storesell",
|
||||||
|
RequestType = DataRequestType.Inventory_StoreSell
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Inventory_StoreSell, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 市场出售物品
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("marketsell")]
|
||||||
|
public async Task<IActionResult> MarketSell([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "inventory_marketsell",
|
||||||
|
RequestType = DataRequestType.Inventory_MarketSell
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Inventory_MarketSell, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 下架市场物品
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("marketdelist")]
|
||||||
|
public async Task<IActionResult> MarketDelist([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "inventory_marketdelist",
|
||||||
|
RequestType = DataRequestType.Inventory_MarketDelist
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Inventory_MarketDelist, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 更新市场价格
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("updatemarketprice")]
|
||||||
|
public async Task<IActionResult> UpdateMarketPrice([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "inventory_updatemarketprice",
|
||||||
|
RequestType = DataRequestType.Inventory_UpdateMarketPrice
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Inventory_UpdateMarketPrice, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取交易报价
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("getoffer")]
|
||||||
|
public async Task<IActionResult> GetOffer([FromQuery] long offerId)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "inventory_getoffer",
|
||||||
|
RequestType = DataRequestType.Inventory_GetOffer
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> data = new()
|
||||||
|
{
|
||||||
|
{ OffersQuery.Column_Id, offerId },
|
||||||
|
{ "apiQuery", true }
|
||||||
|
};
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Inventory_GetOffer, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建交易报价
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("makeoffer")]
|
||||||
|
public async Task<IActionResult> MakeOffer([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "inventory_makeoffer",
|
||||||
|
RequestType = DataRequestType.Inventory_MakeOffer
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Inventory_MakeOffer, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 修改交易报价
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("reviseoffer")]
|
||||||
|
public async Task<IActionResult> ReviseOffer([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "inventory_reviseoffer",
|
||||||
|
RequestType = DataRequestType.Inventory_ReviseOffer
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Inventory_ReviseOffer, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 回应交易报价
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("respondoffer")]
|
||||||
|
public async Task<IActionResult> RespondOffer([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "inventory_respondoffer",
|
||||||
|
RequestType = DataRequestType.Inventory_RespondOffer
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Inventory_RespondOffer, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
73
FunGame.WebAPI/Controllers/MainController.cs
Normal file
73
FunGame.WebAPI/Controllers/MainController.cs
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Milimoe.FunGame.Core.Library.Constant;
|
||||||
|
using Milimoe.FunGame.WebAPI.Models;
|
||||||
|
|
||||||
|
namespace Milimoe.FunGame.WebAPI.Controllers
|
||||||
|
{
|
||||||
|
[ApiController]
|
||||||
|
[Route("[controller]")]
|
||||||
|
[Authorize]
|
||||||
|
public class MainController(RESTfulAPIModel model, ILogger<MainController> logger) : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly ILogger<MainController> _logger = logger;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取公告
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("notice")]
|
||||||
|
public async Task<IActionResult> GetNotice()
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "main_getnotice",
|
||||||
|
RequestType = DataRequestType.Main_GetNotice
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Main_GetNotice, []);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 发送聊天消息
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("chat")]
|
||||||
|
public async Task<IActionResult> Chat([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "main_chat",
|
||||||
|
RequestType = DataRequestType.Main_Chat
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Main_Chat, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
340
FunGame.WebAPI/Controllers/RoomController.cs
Normal file
340
FunGame.WebAPI/Controllers/RoomController.cs
Normal file
@ -0,0 +1,340 @@
|
|||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Milimoe.FunGame.Core.Entity;
|
||||||
|
using Milimoe.FunGame.Core.Library.Constant;
|
||||||
|
using Milimoe.FunGame.WebAPI.Models;
|
||||||
|
|
||||||
|
namespace Milimoe.FunGame.WebAPI.Controllers
|
||||||
|
{
|
||||||
|
[ApiController]
|
||||||
|
[Route("[controller]")]
|
||||||
|
[Authorize]
|
||||||
|
public class RoomController(RESTfulAPIModel model, ILogger<RoomController> logger) : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly ILogger<RoomController> _logger = logger;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建房间
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("create")]
|
||||||
|
public async Task<IActionResult> CreateRoom([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
string msg = "服务器暂时无法处理此请求。";
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "room_create",
|
||||||
|
RequestType = DataRequestType.Main_CreateRoom
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Main_CreateRoom, data);
|
||||||
|
if (result.TryGetValue("room", out object? value) && value is Room room && room.Roomid != "-1")
|
||||||
|
{
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
msg = "创建房间失败!";
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = msg;
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取/更新房间列表
|
||||||
|
/// </summary>
|
||||||
|
[HttpGet("list")]
|
||||||
|
public async Task<IActionResult> GetRoomList()
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "room_list",
|
||||||
|
RequestType = DataRequestType.Main_UpdateRoom
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Main_UpdateRoom, []);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 进入房间
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("join")]
|
||||||
|
public async Task<IActionResult> IntoRoom([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "room_join",
|
||||||
|
RequestType = DataRequestType.Main_IntoRoom
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Main_IntoRoom, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 退出房间
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("quit")]
|
||||||
|
public async Task<IActionResult> QuitRoom([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "room_quit",
|
||||||
|
RequestType = DataRequestType.Main_QuitRoom
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Main_QuitRoom, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 匹配房间
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("match")]
|
||||||
|
public async Task<IActionResult> MatchRoom([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "room_match",
|
||||||
|
RequestType = DataRequestType.Main_MatchRoom
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Main_MatchRoom, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 设置准备状态
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("ready")]
|
||||||
|
public async Task<IActionResult> SetReady([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "room_ready",
|
||||||
|
RequestType = DataRequestType.Main_Ready
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Main_Ready, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 取消准备状态
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("cancelready")]
|
||||||
|
public async Task<IActionResult> CancelReady([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "room_cancelready",
|
||||||
|
RequestType = DataRequestType.Main_CancelReady
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Main_CancelReady, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 开始游戏
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("start")]
|
||||||
|
public async Task<IActionResult> StartGame([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "room_start",
|
||||||
|
RequestType = DataRequestType.Main_StartGame
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Main_StartGame, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 更新房间设置
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("updateroomsettings")]
|
||||||
|
public async Task<IActionResult> UpdateRoomSettings([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "room_updatesettings",
|
||||||
|
RequestType = DataRequestType.Room_UpdateRoomSettings
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Room_UpdateRoomSettings, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取房间内玩家数量
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("playercount")]
|
||||||
|
public async Task<IActionResult> GetRoomPlayerCount([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "room_playercount",
|
||||||
|
RequestType = DataRequestType.Room_GetRoomPlayerCount
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Room_GetRoomPlayerCount, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 更新房主
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("updatemaster")]
|
||||||
|
public async Task<IActionResult> UpdateRoomMaster([FromBody] Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "room_updatemaster",
|
||||||
|
RequestType = DataRequestType.Room_UpdateRoomMaster
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.Room_UpdateRoomMaster, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
104
FunGame.WebAPI/Controllers/UserCenterController.cs
Normal file
104
FunGame.WebAPI/Controllers/UserCenterController.cs
Normal file
@ -0,0 +1,104 @@
|
|||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Milimoe.FunGame.Core.Library.Constant;
|
||||||
|
using Milimoe.FunGame.Core.Library.SQLScript.Entity;
|
||||||
|
using Milimoe.FunGame.WebAPI.Models;
|
||||||
|
using static System.Runtime.InteropServices.JavaScript.JSType;
|
||||||
|
|
||||||
|
namespace Milimoe.FunGame.WebAPI.Controllers
|
||||||
|
{
|
||||||
|
[ApiController]
|
||||||
|
[Route("[controller]")]
|
||||||
|
[Authorize]
|
||||||
|
public class UserCenterController(RESTfulAPIModel model, ILogger<UserCenterController> logger) : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly ILogger<UserCenterController> _logger = logger;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 更新用户
|
||||||
|
/// </summary>
|
||||||
|
[HttpPut("updateuser")]
|
||||||
|
public async Task<IActionResult> UpdateUser(Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "user_update",
|
||||||
|
RequestType = DataRequestType.UserCenter_UpdateUser
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.UserCenter_UpdateUser, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 更新密码
|
||||||
|
/// </summary>
|
||||||
|
[HttpPut("updatepassword")]
|
||||||
|
public async Task<IActionResult> UpdatePassword(Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "user_updatepassword",
|
||||||
|
RequestType = DataRequestType.UserCenter_UpdatePassword
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.UserCenter_UpdatePassword, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 每日签到
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("dailysignin")]
|
||||||
|
public async Task<IActionResult> DailySignIn(Dictionary<string, object> data)
|
||||||
|
{
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "user_dailysignin",
|
||||||
|
RequestType = DataRequestType.UserCenter_DailySignIn
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Dictionary<string, object> result = await model.DataRequestController.GetResultData(DataRequestType.UserCenter_DailySignIn, data);
|
||||||
|
response.StatusCode = 200;
|
||||||
|
response.Data = result;
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError("Error: {e}", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = "服务器暂时无法处理此请求。";
|
||||||
|
return StatusCode(500, response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -28,6 +28,13 @@ namespace Milimoe.FunGame.WebAPI.Controllers
|
|||||||
[Authorize(AuthenticationSchemes = "APIBearer")]
|
[Authorize(AuthenticationSchemes = "APIBearer")]
|
||||||
public IActionResult Register([FromBody] RegDTO dto)
|
public IActionResult Register([FromBody] RegDTO dto)
|
||||||
{
|
{
|
||||||
|
string msg = "服务器暂时无法处理注册请求。";
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "user_register",
|
||||||
|
RequestType = DataRequestType.Reg_Reg
|
||||||
|
};
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
string clientIP = HttpContext.Connection.RemoteIpAddress?.ToString() + ":" + HttpContext.Connection.RemotePort;
|
string clientIP = HttpContext.Connection.RemoteIpAddress?.ToString() + ":" + HttpContext.Connection.RemotePort;
|
||||||
@ -37,39 +44,40 @@ namespace Milimoe.FunGame.WebAPI.Controllers
|
|||||||
string email = dto.Email;
|
string email = dto.Email;
|
||||||
string verifycode = dto.VerifyCode;
|
string verifycode = dto.VerifyCode;
|
||||||
|
|
||||||
(string msg, RegInvokeType type, bool success) = DataRequestService.Reg(apiListener, username, password, email, verifycode, clientIP);
|
(msg, RegInvokeType type, bool success) = DataRequestService.Reg(apiListener, username, password, email, verifycode, clientIP);
|
||||||
|
|
||||||
return Ok(new PayloadModel<DataRequestType>()
|
response.StatusCode = 200;
|
||||||
|
response.Message = msg;
|
||||||
|
response.Data = new()
|
||||||
{
|
{
|
||||||
RequestType = DataRequestType.Reg_Reg,
|
{ "success", success },
|
||||||
StatusCode = 200,
|
{ "type", type }
|
||||||
Message = msg,
|
};
|
||||||
Data = new()
|
return Ok(response);
|
||||||
{
|
|
||||||
{ "success", success },
|
|
||||||
{ "type", type }
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
logger.LogError("Error: {e}", e);
|
logger.LogError("Error: {e}", e);
|
||||||
}
|
}
|
||||||
return BadRequest("服务器暂时无法处理注册请求。");
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = msg;
|
||||||
|
return StatusCode(500, response);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("login")]
|
[HttpPost("login")]
|
||||||
public async Task<IActionResult> Login([FromBody] LoginDTO dto)
|
public async Task<IActionResult> Login([FromBody] LoginDTO dto)
|
||||||
{
|
{
|
||||||
|
string msg = "服务器暂时无法处理登录请求。";
|
||||||
Config.ConnectingPlayerCount++;
|
Config.ConnectingPlayerCount++;
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "user_login",
|
||||||
|
RequestType = DataRequestType.Login_Login
|
||||||
|
};
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
PayloadModel<DataRequestType> response = new()
|
|
||||||
{
|
|
||||||
RequestType = DataRequestType.Login_Login
|
|
||||||
};
|
|
||||||
string msg = "服务器暂时无法处理登录请求。";
|
|
||||||
|
|
||||||
string clientIP = HttpContext.Connection.RemoteIpAddress?.ToString() + ":" + HttpContext.Connection.RemotePort;
|
string clientIP = HttpContext.Connection.RemoteIpAddress?.ToString() + ":" + HttpContext.Connection.RemotePort;
|
||||||
ServerHelper.WriteLine(ServerHelper.MakeClientName(clientIP) + " 通过 RESTful API 连接至服务器,正在登录 . . .", InvokeMessageType.Core);
|
ServerHelper.WriteLine(ServerHelper.MakeClientName(clientIP) + " 通过 RESTful API 连接至服务器,正在登录 . . .", InvokeMessageType.Core);
|
||||||
string username = dto.Username;
|
string username = dto.Username;
|
||||||
@ -109,21 +117,26 @@ namespace Milimoe.FunGame.WebAPI.Controllers
|
|||||||
Config.ConnectingPlayerCount--;
|
Config.ConnectingPlayerCount--;
|
||||||
logger.LogError("Error: {e}", e);
|
logger.LogError("Error: {e}", e);
|
||||||
}
|
}
|
||||||
return BadRequest();
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = msg;
|
||||||
|
return StatusCode(500, response);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("logout")]
|
[HttpPost("logout")]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
public async Task<IActionResult> LogOut()
|
public async Task<IActionResult> LogOut()
|
||||||
{
|
{
|
||||||
|
string msg = "退出登录失败!服务器可能暂时无法处理此请求。";
|
||||||
|
PayloadModel<DataRequestType> response = new()
|
||||||
|
{
|
||||||
|
Event = "user_logout",
|
||||||
|
RequestType = DataRequestType.RunTime_Logout
|
||||||
|
};
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
PayloadModel<DataRequestType> response = new()
|
|
||||||
{
|
|
||||||
RequestType = DataRequestType.RunTime_Logout
|
|
||||||
};
|
|
||||||
string username = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "";
|
string username = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "";
|
||||||
|
|
||||||
if (apiListener.UserList.ContainsKey(username))
|
if (apiListener.UserList.ContainsKey(username))
|
||||||
{
|
{
|
||||||
RESTfulAPIModel model = (RESTfulAPIModel)apiListener.UserList[username];
|
RESTfulAPIModel model = (RESTfulAPIModel)apiListener.UserList[username];
|
||||||
@ -134,16 +147,15 @@ namespace Milimoe.FunGame.WebAPI.Controllers
|
|||||||
response.StatusCode = 200;
|
response.StatusCode = 200;
|
||||||
return Ok(response);
|
return Ok(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
response.Message = "退出登录失败!";
|
|
||||||
response.StatusCode = 400;
|
|
||||||
return BadRequest(response);
|
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
logger.LogError("Error: {e}", e);
|
logger.LogError("Error: {e}", e);
|
||||||
}
|
}
|
||||||
return BadRequest();
|
|
||||||
|
response.StatusCode = 500;
|
||||||
|
response.Message = msg;
|
||||||
|
return StatusCode(500, response);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("refresh")]
|
[HttpPost("refresh")]
|
||||||
@ -163,7 +175,7 @@ namespace Milimoe.FunGame.WebAPI.Controllers
|
|||||||
{
|
{
|
||||||
logger.LogError("Error: {e}", e);
|
logger.LogError("Error: {e}", e);
|
||||||
}
|
}
|
||||||
return BadRequest();
|
return StatusCode(500);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<RESTfulAPIModel?> CheckConnection(string username, string clientIP)
|
private async Task<RESTfulAPIModel?> CheckConnection(string username, string clientIP)
|
||||||
|
|||||||
@ -7,8 +7,8 @@
|
|||||||
<RootNamespace>Milimoe.$(MSBuildProjectName.Replace(" ", "_"))</RootNamespace>
|
<RootNamespace>Milimoe.$(MSBuildProjectName.Replace(" ", "_"))</RootNamespace>
|
||||||
<BaseOutputPath>..\bin\</BaseOutputPath>
|
<BaseOutputPath>..\bin\</BaseOutputPath>
|
||||||
<AssemblyName>FunGameWebAPI</AssemblyName>
|
<AssemblyName>FunGameWebAPI</AssemblyName>
|
||||||
<ApplicationIcon>Images\logo.ico</ApplicationIcon>
|
|
||||||
<Authors>Milimoe</Authors>
|
<Authors>Milimoe</Authors>
|
||||||
|
<ApplicationIcon>logo.ico</ApplicationIcon>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||||
@ -20,7 +20,7 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Content Include="Images\logo.ico" />
|
<Content Include="logo.ico" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
@ -32,17 +32,11 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\..\FunGame.Core\FunGame.Core.csproj" />
|
<ProjectReference Include="..\..\FunGame.Core\FunGame.Core.csproj" />
|
||||||
|
<ProjectReference Include="..\..\FunGame.Extension\FunGame.SQLQueryExtension\FunGame.SQLQueryExtension.csproj" />
|
||||||
<ProjectReference Include="..\FunGame.Implement\FunGame.Implement.csproj" />
|
<ProjectReference Include="..\FunGame.Implement\FunGame.Implement.csproj" />
|
||||||
<ProjectReference Include="..\FunGame.Server\FunGame.Server.csproj" />
|
<ProjectReference Include="..\FunGame.Server\FunGame.Server.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<None Update="Images\logo.ico">
|
|
||||||
<PackagePath>\</PackagePath>
|
|
||||||
<Pack>True</Pack>
|
|
||||||
</None>
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Folder Include="wwwroot\" />
|
<Folder Include="wwwroot\" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 17 KiB |
@ -2,6 +2,11 @@
|
|||||||
{
|
{
|
||||||
public class PayloadModel<T> where T : struct, Enum
|
public class PayloadModel<T> where T : struct, Enum
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 业务事件
|
||||||
|
/// </summary>
|
||||||
|
public string Event { get; set; } = "";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 请求类型
|
/// 请求类型
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@ -62,8 +62,8 @@ try
|
|||||||
// 读取 Server 插件
|
// 读取 Server 插件
|
||||||
FunGameSystem.GetServerPlugins();
|
FunGameSystem.GetServerPlugins();
|
||||||
|
|
||||||
// 初始化用户密钥列表
|
// 初始化服务器其他配置文件
|
||||||
FunGameSystem.InitUserKeys();
|
FunGameSystem.InitOtherConfig();
|
||||||
|
|
||||||
// Add services to the container.
|
// Add services to the container.
|
||||||
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
|
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
|
||||||
@ -215,12 +215,17 @@ try
|
|||||||
IExceptionHandlerFeature? contextFeature = context.Features.Get<IExceptionHandlerFeature>();
|
IExceptionHandlerFeature? contextFeature = context.Features.Get<IExceptionHandlerFeature>();
|
||||||
if (contextFeature != null)
|
if (contextFeature != null)
|
||||||
{
|
{
|
||||||
await context.Response.WriteAsync(new
|
await context.Response.WriteAsync(NetworkUtility.JsonSerialize(new PayloadModel<DataRequestType>()
|
||||||
{
|
{
|
||||||
context.Response.StatusCode,
|
Event = "system_error",
|
||||||
|
RequestType = DataRequestType.UnKnown,
|
||||||
|
StatusCode = context.Response.StatusCode,
|
||||||
Message = "Internal Server Error.",
|
Message = "Internal Server Error.",
|
||||||
Detailed = contextFeature.Error.Message
|
Data = new()
|
||||||
}.ToString() ?? "");
|
{
|
||||||
|
{ "msg", contextFeature.Error.Message }
|
||||||
|
}
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@ -242,6 +247,16 @@ try
|
|||||||
// 开始监听连接
|
// 开始监听连接
|
||||||
listener.BannedList.AddRange(Config.ServerBannedList);
|
listener.BannedList.AddRange(Config.ServerBannedList);
|
||||||
|
|
||||||
|
FunGameSystem.CloseListener += async () =>
|
||||||
|
{
|
||||||
|
foreach (ServerModel<ServerWebSocket> model in listener.ClientList.Cast<ServerModel<ServerWebSocket>>())
|
||||||
|
{
|
||||||
|
await model.Kick("服务器正在关闭。");
|
||||||
|
}
|
||||||
|
listener.Close();
|
||||||
|
await app.StopAsync();
|
||||||
|
};
|
||||||
|
|
||||||
Task order = Task.Factory.StartNew(GetConsoleOrder);
|
Task order = Task.Factory.StartNew(GetConsoleOrder);
|
||||||
|
|
||||||
app.Run();
|
app.Run();
|
||||||
@ -260,8 +275,20 @@ async Task GetConsoleOrder()
|
|||||||
if (order != "")
|
if (order != "")
|
||||||
{
|
{
|
||||||
order = order.ToLower();
|
order = order.ToLower();
|
||||||
|
if (FunGameSystem.OrderList.TryGetValue(order, out Action<string>? action) && action != null)
|
||||||
|
{
|
||||||
|
action(order);
|
||||||
|
}
|
||||||
switch (order)
|
switch (order)
|
||||||
{
|
{
|
||||||
|
case OrderDictionary.Quit:
|
||||||
|
case OrderDictionary.Exit:
|
||||||
|
case OrderDictionary.Close:
|
||||||
|
CloseServer();
|
||||||
|
break;
|
||||||
|
case OrderDictionary.Restart:
|
||||||
|
ServerHelper.WriteLine("服务器正在运行,请手动结束服务器进程再启动!");
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
await ConsoleModel.Order(listener, order);
|
await ConsoleModel.Order(listener, order);
|
||||||
break;
|
break;
|
||||||
|
|||||||
@ -25,7 +25,7 @@ namespace Milimoe.FunGame.WebAPI.Services
|
|||||||
string key = authorizationHeader["Bearer ".Length..].Trim();
|
string key = authorizationHeader["Bearer ".Length..].Trim();
|
||||||
|
|
||||||
// 验证 API Bearer Token
|
// 验证 API Bearer Token
|
||||||
if (key == "" || !FunGameSystem.IsAPISecretKeyExist(key))
|
if (key == "" || !FunGameSystem.APISecretKeyExists(key))
|
||||||
{
|
{
|
||||||
await Task.CompletedTask;
|
await Task.CompletedTask;
|
||||||
return AuthenticateResult.Fail("Invalid Token.");
|
return AuthenticateResult.Fail("Invalid Token.");
|
||||||
|
|||||||
BIN
FunGame.WebAPI/logo.ico
Normal file
BIN
FunGame.WebAPI/logo.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 66 KiB |
@ -11,6 +11,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FunGame.WebAPI", "FunGame.W
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FunGame.Core", "..\FunGame.Core\FunGame.Core.csproj", "{33CAC80F-8394-41DB-B5AF-5E91123E6C84}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FunGame.Core", "..\FunGame.Core\FunGame.Core.csproj", "{33CAC80F-8394-41DB-B5AF-5E91123E6C84}"
|
||||||
EndProject
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FunGame.SQLQueryExtension", "..\FunGame.Extension\FunGame.SQLQueryExtension\FunGame.SQLQueryExtension.csproj", "{9EEB3474-B9A1-4E5E-BEF0-14F30D81873C}"
|
||||||
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
@ -33,6 +35,10 @@ Global
|
|||||||
{33CAC80F-8394-41DB-B5AF-5E91123E6C84}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{33CAC80F-8394-41DB-B5AF-5E91123E6C84}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{33CAC80F-8394-41DB-B5AF-5E91123E6C84}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{33CAC80F-8394-41DB-B5AF-5E91123E6C84}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{33CAC80F-8394-41DB-B5AF-5E91123E6C84}.Release|Any CPU.Build.0 = Release|Any CPU
|
{33CAC80F-8394-41DB-B5AF-5E91123E6C84}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{9EEB3474-B9A1-4E5E-BEF0-14F30D81873C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{9EEB3474-B9A1-4E5E-BEF0-14F30D81873C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{9EEB3474-B9A1-4E5E-BEF0-14F30D81873C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{9EEB3474-B9A1-4E5E-BEF0-14F30D81873C}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user