mirror of
https://github.com/project-redbud/FunGame-Server.git
synced 2025-12-05 08:09:03 +00:00
Compare commits
16 Commits
1.0.0-rc.1
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 449cb1df9b | |||
|
|
ffa839e9f1 | ||
| ca27d7776d | |||
| 744df60653 | |||
| 11ce293021 | |||
| 9e1c68042d | |||
| c32188e0f5 | |||
| 1823e00669 | |||
| 620a398f47 | |||
| 5c002a40a8 | |||
| a989b8b56d | |||
| a641e8ce6f | |||
| 60307b4bcc | |||
| 301c66baa5 | |||
| d3cf91e014 | |||
| 0e361b5be9 |
@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>..\bin</BaseOutputPath>
|
||||
|
||||
@ -154,11 +154,8 @@ namespace Milimoe.FunGame.Server.Controller
|
||||
}
|
||||
}
|
||||
|
||||
if (ValidateClientParameters is null)
|
||||
if (ValidateClientParameters != null)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
|
||||
foreach (Func<SocketObject, string> handler in ValidateClientParameters.GetInvocationList().Cast<Func<SocketObject, string>>())
|
||||
{
|
||||
string msg = handler(obj);
|
||||
@ -168,6 +165,8 @@ namespace Milimoe.FunGame.Server.Controller
|
||||
ServerHelper.WriteLine(msg, InvokeMessageType.Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return builder.ToString().Trim();
|
||||
}
|
||||
}
|
||||
|
||||
@ -315,7 +315,7 @@ namespace Milimoe.FunGame.Server.Controller
|
||||
if (SQLHelper.Result == SQLResult.Success)
|
||||
{
|
||||
ServerHelper.WriteLine("[CreateRoom] Master: " + user.Username + " RoomID: " + roomid);
|
||||
DataRow? dr = SQLHelper.ExecuteDataRow(RoomQuery.Select_IsExistRoom(SQLHelper, roomid));
|
||||
DataRow? dr = SQLHelper.ExecuteDataRow(RoomQuery.Select_RoomByRoomId(SQLHelper, roomid));
|
||||
if (dr != null)
|
||||
{
|
||||
room = Factory.GetRoom(dr, user);
|
||||
@ -355,7 +355,7 @@ namespace Milimoe.FunGame.Server.Controller
|
||||
string roomid = DataRequest.GetDictionaryJsonObject<string>(requestData, "roomid") ?? "-1";
|
||||
bool isMaster = DataRequest.GetDictionaryJsonObject<bool>(requestData, "isMaster");
|
||||
|
||||
if (roomid != "-1" && FunGameSystem.RoomList.IsExist(roomid))
|
||||
if (roomid != "-1" && FunGameSystem.RoomList.Exists(roomid))
|
||||
{
|
||||
Room room = FunGameSystem.RoomList[roomid];
|
||||
RoomEventArgs eventArgs = new(room);
|
||||
@ -403,7 +403,7 @@ namespace Milimoe.FunGame.Server.Controller
|
||||
}
|
||||
else if (SQLHelper != null)
|
||||
{
|
||||
SQLHelper.ExecuteDataSet(RoomQuery.Select_IsExistRoom(SQLHelper, roomid));
|
||||
SQLHelper.ExecuteDataSet(RoomQuery.Select_RoomByRoomId(SQLHelper, roomid));
|
||||
if (SQLHelper.Success)
|
||||
{
|
||||
FunGameSystem.RoomList.IntoRoom(roomid, Server.User);
|
||||
@ -897,7 +897,7 @@ namespace Milimoe.FunGame.Server.Controller
|
||||
string newModule = DataRequest.GetDictionaryJsonObject<string>(requestData, "module") ?? "";
|
||||
string newMap = DataRequest.GetDictionaryJsonObject<string>(requestData, "map") ?? "";
|
||||
User user = Server.User;
|
||||
if (roomid != "-1" && FunGameSystem.RoomList.IsExist(roomid))
|
||||
if (roomid != "-1" && FunGameSystem.RoomList.Exists(roomid))
|
||||
{
|
||||
Room room = FunGameSystem.RoomList[roomid];
|
||||
RoomEventArgs eventArgs = new(room);
|
||||
@ -973,7 +973,7 @@ namespace Milimoe.FunGame.Server.Controller
|
||||
string roomid = DataRequest.GetDictionaryJsonObject<string>(requestData, "roomid") ?? "-1";
|
||||
User newMaster = DataRequest.GetDictionaryJsonObject<User>(requestData, "newMaster") ?? Factory.GetUser();
|
||||
|
||||
if (roomid != "-1" && FunGameSystem.RoomList.IsExist(roomid) && newMaster.Id != 0)
|
||||
if (roomid != "-1" && FunGameSystem.RoomList.Exists(roomid) && newMaster.Id != 0)
|
||||
{
|
||||
Room room = FunGameSystem.RoomList[roomid];
|
||||
RoomEventArgs eventArgs = new(room);
|
||||
@ -1393,7 +1393,7 @@ namespace Milimoe.FunGame.Server.Controller
|
||||
{
|
||||
Goods goods = store.Goods[goodsId];
|
||||
int count = counts[goodsId];
|
||||
if (count > goods.Stock)
|
||||
if (goods.Stock != -1 && count > goods.Stock)
|
||||
{
|
||||
result = false;
|
||||
buyResult.Add($"购买失败,原因:库存不足,当前库存为:{goods.Stock},购买数量:{count}。");
|
||||
@ -1421,11 +1421,11 @@ namespace Milimoe.FunGame.Server.Controller
|
||||
else
|
||||
{
|
||||
subResult = false;
|
||||
buyResult.Add($"购买失败,原因:需要花费 {totalPrice} {General.GameplayEquilibriumConstant.InGameMaterial},但是您只有 {user.Inventory.Credits} {General.GameplayEquilibriumConstant.InGameMaterial}。");
|
||||
buyResult.Add($"购买失败,原因:需要花费 {totalPrice} {General.GameplayEquilibriumConstant.InGameMaterial},但是您只有 {user.Inventory.Materials} {General.GameplayEquilibriumConstant.InGameMaterial}。");
|
||||
}
|
||||
if (subResult)
|
||||
{
|
||||
goods.Stock -= count;
|
||||
if (goods.Stock != -1) goods.Stock -= count;
|
||||
totalCost += totalPrice;
|
||||
ProcessStoreBuy(goods, useCredits, price, count, user);
|
||||
buyResult.Add($"成功消费:{totalPrice} {currency},购买了 {count} 个 {goods.Name}。");
|
||||
@ -1524,7 +1524,7 @@ namespace Milimoe.FunGame.Server.Controller
|
||||
try
|
||||
{
|
||||
User? buyer = SQLHelper.GetUserById(userid, true);
|
||||
User? itemUser = SQLHelper.GetUserById(marketItem.User.Id, true);
|
||||
User? itemUser = SQLHelper.GetUserById(marketItem.User, true);
|
||||
if (itemUser != null && buyer != null && itemUser.Inventory.Items.FirstOrDefault(i => i.Guid == itemGuid) is Item item)
|
||||
{
|
||||
if (buyer.Inventory.Credits >= price)
|
||||
@ -1631,7 +1631,7 @@ namespace Milimoe.FunGame.Server.Controller
|
||||
Guid itemGuid = DataRequest.GetDictionaryJsonObject<Guid>(requestData, "itemGuid");
|
||||
long userid = DataRequest.GetDictionaryJsonObject<long>(requestData, "userid");
|
||||
Character[] targets = DataRequest.GetDictionaryJsonObject<Character[]>(requestData, "targets") ?? [];
|
||||
long useCount = DataRequest.GetDictionaryJsonObject<long>(requestData, "useCount");
|
||||
int useCount = DataRequest.GetDictionaryJsonObject<int>(requestData, "useCount");
|
||||
|
||||
GeneralEventArgs eventArgs = new(itemGuid, userid, targets, useCount);
|
||||
FunGameSystem.ServerPluginLoader?.OnBeforeUseItemEvent(this, eventArgs);
|
||||
@ -1646,16 +1646,16 @@ namespace Milimoe.FunGame.Server.Controller
|
||||
User? user = SQLHelper.GetUserById(userid, true);
|
||||
if (user != null && user.Inventory.Items.FirstOrDefault(i => i.Guid == itemGuid) is Item item)
|
||||
{
|
||||
// 暂定标准实现是传这两个参数,作用目标和使用数量
|
||||
// 暂定标准实现是传这个参数,作用目标
|
||||
Dictionary<string, object> args = new()
|
||||
{
|
||||
{ "targets", targets },
|
||||
{ "useCount", useCount }
|
||||
{ "targets", targets }
|
||||
};
|
||||
bool used = item.UseItem(args);
|
||||
bool used = item.UseItem(user, useCount, args);
|
||||
if (used)
|
||||
{
|
||||
SQLHelper.UpdateInventory(user.Inventory);
|
||||
result = true;
|
||||
}
|
||||
}
|
||||
if (result)
|
||||
@ -1698,6 +1698,7 @@ namespace Milimoe.FunGame.Server.Controller
|
||||
user.Inventory.Credits += reward;
|
||||
item.EntityState = EntityState.Deleted;
|
||||
SQLHelper.UpdateInventory(user.Inventory);
|
||||
result = true;
|
||||
}
|
||||
}
|
||||
if (result)
|
||||
@ -1721,6 +1722,7 @@ namespace Milimoe.FunGame.Server.Controller
|
||||
Guid itemGuid = DataRequest.GetDictionaryJsonObject<Guid>(requestData, "itemGuid");
|
||||
long userid = DataRequest.GetDictionaryJsonObject<long>(requestData, "userid");
|
||||
double price = DataRequest.GetDictionaryJsonObject<double>(requestData, "price");
|
||||
int stock = DataRequest.GetDictionaryJsonObject<int>(requestData, "stock");
|
||||
User? user = SQLHelper?.GetUserById(userid, true);
|
||||
if (user != null && user.Inventory.Items.FirstOrDefault(i => i.Guid == itemGuid) is Item item)
|
||||
{
|
||||
@ -1730,7 +1732,7 @@ namespace Milimoe.FunGame.Server.Controller
|
||||
}
|
||||
else
|
||||
{
|
||||
SQLHelper?.AddMarketItem(itemGuid, userid, price);
|
||||
SQLHelper?.AddMarketItem(itemGuid, userid, price, stock);
|
||||
if (SQLHelper?.Success ?? false)
|
||||
{
|
||||
msg = "";
|
||||
@ -2017,14 +2019,13 @@ namespace Milimoe.FunGame.Server.Controller
|
||||
}
|
||||
}
|
||||
|
||||
if (msg != "")
|
||||
if (msg == "")
|
||||
{
|
||||
offer = SQLHelper.GetOffer(offerId);
|
||||
if (offer != null)
|
||||
{
|
||||
SQLHelper.Commit();
|
||||
resultData.Add("offer", offer);
|
||||
msg = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>..\bin</BaseOutputPath>
|
||||
@ -39,9 +39,8 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="9.0.4" />
|
||||
<PackageReference Include="MySql.Data" Version="9.3.0" />
|
||||
<PackageReference Include="System.Text.Json" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.0" />
|
||||
<PackageReference Include="MySql.Data" Version="9.5.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@ -16,7 +16,7 @@ HTTPListener? WebSocketListener = null;
|
||||
ServerHelper.WriteLine("正在读取配置文件并初始化服务 . . .");
|
||||
|
||||
// 检查是否存在配置文件
|
||||
if (!INIHelper.ExistINIFile())
|
||||
if (!INIHelper.INIFileExists())
|
||||
{
|
||||
ServerHelper.WriteLine("未检测到配置文件,将自动创建配置文件 . . .");
|
||||
INIHelper.Init(Config.FunGameType);
|
||||
|
||||
@ -20,7 +20,7 @@ namespace Milimoe.FunGame.Server.Models
|
||||
{
|
||||
if (Name == "" && DataSource == "" && Port == "" && DataBase == "" && User == "" && Password == "")
|
||||
{
|
||||
if (INIHelper.ExistINIFile())
|
||||
if (INIHelper.INIFileExists())
|
||||
{
|
||||
DataSource = INIHelper.ReadINI("MySQL", "DBServer");
|
||||
Port = INIHelper.ReadINI("MySQL", "DBPort");
|
||||
@ -41,7 +41,7 @@ namespace Milimoe.FunGame.Server.Models
|
||||
{
|
||||
if (DataSource == "")
|
||||
{
|
||||
if (INIHelper.ExistINIFile())
|
||||
if (INIHelper.INIFileExists())
|
||||
{
|
||||
DataSource = INIHelper.ReadINI("SQLite", "DataSource");
|
||||
}
|
||||
|
||||
@ -73,7 +73,7 @@ namespace Milimoe.FunGame.Server.Services
|
||||
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));
|
||||
sqlHelper.ExecuteDataSet(UserQuery.Select_UserByUsername(sqlHelper, username));
|
||||
if (sqlHelper.Result == SQLResult.Success)
|
||||
{
|
||||
ServerHelper.WriteLine(clientName + " 账号已被注册");
|
||||
@ -81,7 +81,7 @@ namespace Milimoe.FunGame.Server.Services
|
||||
}
|
||||
|
||||
// 检查邮箱是否重复
|
||||
sqlHelper.ExecuteDataSet(UserQuery.Select_IsExistEmail(sqlHelper, email));
|
||||
sqlHelper.ExecuteDataSet(UserQuery.Select_UserByEmail(sqlHelper, email));
|
||||
if (sqlHelper.Result == SQLResult.Success)
|
||||
{
|
||||
ServerHelper.WriteLine(clientName + " 邮箱已被注册");
|
||||
|
||||
@ -142,7 +142,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
||||
|
||||
OpenConnection();
|
||||
Script = script;
|
||||
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api);
|
||||
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api, LogLevel.Debug);
|
||||
using MySqlCommand command = new(script, _connection);
|
||||
command.CommandType = CommandType;
|
||||
foreach (KeyValuePair<string, object> param in Parameters)
|
||||
@ -206,7 +206,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
||||
|
||||
OpenConnection();
|
||||
Script = script;
|
||||
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api);
|
||||
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api, LogLevel.Debug);
|
||||
using MySqlCommand command = new(script, _connection);
|
||||
command.CommandType = CommandType;
|
||||
foreach (KeyValuePair<string, object> param in Parameters)
|
||||
@ -270,7 +270,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
||||
|
||||
OpenConnection();
|
||||
Script = script;
|
||||
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api);
|
||||
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api, LogLevel.Debug);
|
||||
|
||||
using MySqlCommand command = new(script, _connection)
|
||||
{
|
||||
@ -287,7 +287,6 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
||||
{
|
||||
SelectCommand = command
|
||||
};
|
||||
_dataSet = new();
|
||||
_affectedRows = adapter.Fill(_dataSet);
|
||||
|
||||
if (localTransaction) Commit();
|
||||
@ -335,7 +334,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
||||
|
||||
OpenConnection();
|
||||
Script = script;
|
||||
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api);
|
||||
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api, LogLevel.Debug);
|
||||
|
||||
using MySqlCommand command = new(script, _connection)
|
||||
{
|
||||
@ -352,7 +351,6 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
||||
{
|
||||
SelectCommand = command
|
||||
};
|
||||
_dataSet = new();
|
||||
_affectedRows = await adapter.FillAsync(_dataSet);
|
||||
|
||||
if (localTransaction) Commit();
|
||||
@ -482,7 +480,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
||||
_result = SQLResult.NotFound;
|
||||
_affectedRows = 0;
|
||||
_lastInsertId = 0;
|
||||
DataSet.Clear();
|
||||
_dataSet = new();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -140,7 +140,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
||||
|
||||
OpenConnection();
|
||||
Script = script;
|
||||
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api);
|
||||
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api, LogLevel.Debug);
|
||||
using SqliteCommand command = new(script, _connection);
|
||||
command.CommandType = CommandType;
|
||||
foreach (KeyValuePair<string, object> param in Parameters)
|
||||
@ -206,7 +206,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
||||
|
||||
OpenConnection();
|
||||
Script = script;
|
||||
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api);
|
||||
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api, LogLevel.Debug);
|
||||
using SqliteCommand command = new(script, _connection);
|
||||
command.CommandType = CommandType;
|
||||
foreach (KeyValuePair<string, object> param in Parameters)
|
||||
@ -272,7 +272,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
||||
|
||||
OpenConnection();
|
||||
Script = script;
|
||||
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api);
|
||||
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api, LogLevel.Debug);
|
||||
using SqliteCommand command = new(script, _connection)
|
||||
{
|
||||
CommandType = CommandType
|
||||
@ -285,7 +285,6 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
||||
|
||||
ReSet();
|
||||
using SqliteDataReader reader = command.ExecuteReader();
|
||||
_dataSet = new();
|
||||
do
|
||||
{
|
||||
DataTable table = new();
|
||||
@ -338,7 +337,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
||||
|
||||
OpenConnection();
|
||||
Script = script;
|
||||
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api);
|
||||
ServerHelper.WriteLine("SQLQuery -> " + script, InvokeMessageType.Api, LogLevel.Debug);
|
||||
using SqliteCommand command = new(script, _connection)
|
||||
{
|
||||
CommandType = CommandType
|
||||
@ -351,7 +350,6 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
||||
|
||||
ReSet();
|
||||
using SqliteDataReader reader = await command.ExecuteReaderAsync();
|
||||
_dataSet = new();
|
||||
do
|
||||
{
|
||||
DataTable table = new();
|
||||
@ -486,7 +484,7 @@ namespace Milimoe.FunGame.Server.Services.DataUtility
|
||||
_result = SQLResult.NotFound;
|
||||
_affectedRows = 0;
|
||||
_lastInsertId = 0;
|
||||
DataSet.Clear();
|
||||
_dataSet = new();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -85,7 +85,7 @@ namespace Milimoe.FunGame.Server.Services
|
||||
SQLMode.SQLite => new SQLiteHelper(),
|
||||
_ => null,
|
||||
});
|
||||
if (INIHelper.ExistINIFile())
|
||||
if (INIHelper.INIFileExists())
|
||||
{
|
||||
string useMySQL = INIHelper.ReadINI("MySQL", "UseMySQL").Trim();
|
||||
string useSQLite = INIHelper.ReadINI("SQLite", "UseSQLite").Trim();
|
||||
@ -239,6 +239,21 @@ namespace Milimoe.FunGame.Server.Services
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Web API 启动完成回调
|
||||
/// </summary>
|
||||
public static void OnWebAPIStarted(params object[] objs)
|
||||
{
|
||||
try
|
||||
{
|
||||
WebAPIPluginLoader?.OnWebAPIStarted(objs);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
ServerHelper.Error(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 服务器启动登记
|
||||
/// </summary>
|
||||
|
||||
@ -72,10 +72,12 @@ namespace Milimoe.FunGame.Server.Services
|
||||
{
|
||||
Console.WriteLine("\r" + GetPrefix(InvokeMessageType.Error, LogLevel.Error) + e.Message + "\n" + e.StackTrace);
|
||||
Type();
|
||||
TXTHelper.AppendErrorLog(e);
|
||||
}
|
||||
|
||||
public static void Write(string msg, InvokeMessageType type = InvokeMessageType.System, LogLevel level = LogLevel.Info, bool useLevel = true)
|
||||
{
|
||||
if (msg.Trim() == "") return;
|
||||
if (type == InvokeMessageType.Warning)
|
||||
{
|
||||
level = LogLevel.Warning;
|
||||
@ -86,14 +88,14 @@ namespace Milimoe.FunGame.Server.Services
|
||||
}
|
||||
if (!useLevel || (useLevel && (int)level >= (int)Config.LogLevelValue))
|
||||
{
|
||||
if (msg.Trim() != "") Console.Write("\r" + GetPrefix(type, level) + msg + "> ");
|
||||
Console.Write("\r" + GetPrefix(type, level) + msg + "> ");
|
||||
Console.ResetColor();
|
||||
}
|
||||
else Type();
|
||||
}
|
||||
|
||||
public static void WriteLine(string msg, InvokeMessageType type = InvokeMessageType.System, LogLevel level = LogLevel.Info, bool useLevel = true)
|
||||
{
|
||||
if (msg.Trim() == "") return;
|
||||
if (type == InvokeMessageType.Warning)
|
||||
{
|
||||
level = LogLevel.Warning;
|
||||
@ -104,13 +106,14 @@ namespace Milimoe.FunGame.Server.Services
|
||||
}
|
||||
if (!useLevel || ((int)level >= (int)Config.LogLevelValue))
|
||||
{
|
||||
if (msg.Trim() != "") Console.WriteLine("\r" + GetPrefix(type, level) + msg);
|
||||
}
|
||||
Console.WriteLine("\r" + GetPrefix(type, level) + msg);
|
||||
Type();
|
||||
}
|
||||
}
|
||||
|
||||
public static void WriteLine_Addons(string addon, string msg, InvokeMessageType type = InvokeMessageType.System, LogLevel level = LogLevel.Info, bool useLevel = true)
|
||||
{
|
||||
if (msg.Trim() == "") return;
|
||||
if (type == InvokeMessageType.Warning)
|
||||
{
|
||||
level = LogLevel.Warning;
|
||||
@ -121,10 +124,10 @@ namespace Milimoe.FunGame.Server.Services
|
||||
}
|
||||
if (!useLevel || ((int)level >= (int)Config.LogLevelValue))
|
||||
{
|
||||
if (msg.Trim() != "") Console.WriteLine("\r" + GetPrefix(type, level, addon) + msg);
|
||||
}
|
||||
Console.WriteLine("\r" + GetPrefix(type, level, addon) + msg);
|
||||
Type();
|
||||
}
|
||||
}
|
||||
|
||||
public static void Type()
|
||||
{
|
||||
@ -145,7 +148,7 @@ namespace Milimoe.FunGame.Server.Services
|
||||
private static Hashtable GetServerSettingHashtable()
|
||||
{
|
||||
Hashtable settings = [];
|
||||
if (INIHelper.ExistINIFile())
|
||||
if (INIHelper.INIFileExists())
|
||||
{
|
||||
settings.Add("LogLevel", INIHelper.ReadINI("Console", "LogLevel"));
|
||||
settings.Add("Name", INIHelper.ReadINI("Server", "Name"));
|
||||
@ -257,7 +260,7 @@ namespace Milimoe.FunGame.Server.Services
|
||||
{
|
||||
if (SenderMailAddress == "" && SenderName == "" && SenderPassword == "" && SmtpHost == "")
|
||||
{
|
||||
if (INIHelper.ExistINIFile())
|
||||
if (INIHelper.INIFileExists())
|
||||
{
|
||||
if (bool.TryParse(INIHelper.ReadINI("Mailer", "UseMailSender").ToLower(), out bool use))
|
||||
{
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
using Milimoe.FunGame.WebAPI.Services;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Milimoe.FunGame.WebAPI.Services;
|
||||
|
||||
namespace Milimoe.FunGame.WebAPI.Architecture
|
||||
{
|
||||
@ -11,12 +12,33 @@ namespace Milimoe.FunGame.WebAPI.Architecture
|
||||
// 获取 JWT Token
|
||||
string token = context.Request.Headers.Authorization.ToString().Replace("Bearer ", "");
|
||||
|
||||
if (token == "")
|
||||
{
|
||||
await next(context);
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果存在 Authorize 属性且指定了 CustomBearer 认证方案,跳过 JWT 吊销检查
|
||||
Endpoint? endpoint = context.GetEndpoint();
|
||||
IReadOnlyList<AuthorizeAttribute>? authorizeAttributes = endpoint?.Metadata.GetOrderedMetadata<AuthorizeAttribute>();
|
||||
if (authorizeAttributes != null)
|
||||
{
|
||||
foreach (AuthorizeAttribute authorizeAttribute in authorizeAttributes)
|
||||
{
|
||||
if (authorizeAttribute.AuthenticationSchemes == "APIBearer" || authorizeAttribute.AuthenticationSchemes == "CustomBearer")
|
||||
{
|
||||
await next(context);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 检查 JWT 是否被吊销
|
||||
if (jwtService.IsTokenRevoked(token))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
context.Response.ContentType = "application/json";
|
||||
await context.Response.WriteAsync("{\"message\":\"此 Token 已吊销,请重新登录以获取 Token。\"}");
|
||||
await context.Response.WriteAsync("{\"message\":\"此 Token 无效或已吊销,请重新登录以获取 Token。\"}");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@ -1,38 +1,44 @@
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using Microsoft.OpenApi;
|
||||
|
||||
namespace Milimoe.FunGame.WebAPI.Architecture
|
||||
{
|
||||
public class SecurityDocumentTransformer : IOpenApiDocumentTransformer
|
||||
public class SecurityDocumentTransformer(IAuthenticationSchemeProvider authenticationSchemeProvider) : IOpenApiDocumentTransformer
|
||||
{
|
||||
public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
document.Components ??= new OpenApiComponents();
|
||||
document.Components.SecuritySchemes = new Dictionary<string, OpenApiSecurityScheme>
|
||||
IEnumerable<AuthenticationScheme> authenticationSchemes = await authenticationSchemeProvider.GetAllSchemesAsync();
|
||||
if (authenticationSchemes.Any(authScheme => authScheme.Name == "Bearer"))
|
||||
{
|
||||
Dictionary<string, IOpenApiSecurityScheme> securitySchemes = new()
|
||||
{
|
||||
"Bearer", new OpenApiSecurityScheme
|
||||
["Bearer"] = new OpenApiSecurityScheme
|
||||
{
|
||||
Type = SecuritySchemeType.Http,
|
||||
Scheme = "bearer",
|
||||
BearerFormat = "JWT",
|
||||
Description = "BearerToken"
|
||||
}
|
||||
In = ParameterLocation.Header
|
||||
}
|
||||
};
|
||||
document.SecurityRequirements = [
|
||||
new()
|
||||
document.Components ??= new OpenApiComponents();
|
||||
document.Components.SecuritySchemes = securitySchemes;
|
||||
|
||||
foreach (KeyValuePair<HttpMethod, OpenApiOperation> operation in document.Paths.Values.SelectMany(path => path.Operations!))
|
||||
{
|
||||
operation.Value.Security ??= [];
|
||||
operation.Value.Security.Add(new OpenApiSecurityRequirement
|
||||
{
|
||||
new OpenApiSecurityScheme
|
||||
{
|
||||
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
|
||||
},
|
||||
Array.Empty<string>()
|
||||
[new OpenApiSecuritySchemeReference("Bearer", document)] = []
|
||||
});
|
||||
}
|
||||
}
|
||||
];
|
||||
await Task.CompletedTask;
|
||||
document.Info = new()
|
||||
{
|
||||
Title = "FunGame Web API",
|
||||
Version = "v1",
|
||||
Description = "Welcome to FunGame Web API document."
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<RootNamespace>Milimoe.$(MSBuildProjectName.Replace(" ", "_"))</RootNamespace>
|
||||
@ -24,10 +24,9 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.4" />
|
||||
<PackageReference Include="Scalar.AspNetCore" Version="2.2.1" />
|
||||
<PackageReference Include="System.Text.Json" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.0" />
|
||||
<PackageReference Include="Scalar.AspNetCore" Version="2.10.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
@FunGame.WebAPI_HostAddress = http://localhost:5117
|
||||
|
||||
GET {{FunGame.WebAPI_HostAddress}}/weatherforecast/
|
||||
GET {{FunGame.WebAPI_HostAddress}}/Room/GetRoomList/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
|
||||
@ -37,7 +37,7 @@ try
|
||||
ServerHelper.WriteLine("正在读取配置文件并初始化服务 . . .");
|
||||
|
||||
// 检查是否存在配置文件
|
||||
if (!INIHelper.ExistINIFile())
|
||||
if (!INIHelper.INIFileExists())
|
||||
{
|
||||
ServerHelper.WriteLine("未检测到配置文件,将自动创建配置文件 . . .");
|
||||
INIHelper.Init(Config.FunGameType);
|
||||
@ -94,6 +94,17 @@ try
|
||||
ServerHelper.WriteLine("正在启动 Web API 监听 . . .");
|
||||
Console.WriteLine("\r ");
|
||||
|
||||
// 添加 JSON 转换器
|
||||
builder.Services.AddControllers().AddJsonOptions(options =>
|
||||
{
|
||||
options.JsonSerializerOptions.WriteIndented = true;
|
||||
options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
|
||||
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
|
||||
foreach (JsonConverter converter in JsonTool.JsonSerializerOptions.Converters)
|
||||
{
|
||||
options.JsonSerializerOptions.Converters.Add(converter);
|
||||
}
|
||||
});
|
||||
// 读取扩展控制器
|
||||
if (FunGameSystem.WebAPIPluginLoader != null)
|
||||
{
|
||||
@ -108,23 +119,11 @@ try
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 添加 JSON 转换器
|
||||
builder.Services.AddControllers().AddJsonOptions(options =>
|
||||
{
|
||||
options.JsonSerializerOptions.WriteIndented = true;
|
||||
options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
|
||||
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
|
||||
foreach (JsonConverter converter in JsonTool.JsonSerializerOptions.Converters)
|
||||
{
|
||||
options.JsonSerializerOptions.Converters.Add(converter);
|
||||
}
|
||||
});
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
// 添加 OpenAPI 文档
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddOpenApi(options =>
|
||||
{
|
||||
options.AddDocumentTransformer(new SecurityDocumentTransformer());
|
||||
options.AddDocumentTransformer<SecurityDocumentTransformer>();
|
||||
});
|
||||
// 添加 CORS 服务
|
||||
builder.Services.AddCors(options =>
|
||||
@ -259,6 +258,9 @@ try
|
||||
|
||||
Task order = Task.Factory.StartNew(GetConsoleOrder);
|
||||
|
||||
otherobjs = [app, listener];
|
||||
FunGameSystem.OnWebAPIStarted(otherobjs);
|
||||
|
||||
app.Run();
|
||||
}
|
||||
catch (Exception e)
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Logging.Console;
|
||||
using Milimoe.FunGame.Core.Api.Utility;
|
||||
|
||||
namespace Milimoe.FunGame.WebAPI.Services
|
||||
{
|
||||
@ -20,6 +21,11 @@ namespace Milimoe.FunGame.WebAPI.Services
|
||||
textWriter.WriteLine($"{colorLevel}{timestamp} {level}/[{category}] {message}");
|
||||
}
|
||||
textWriter.Write("\x1b[0m\r> ");
|
||||
|
||||
if (logEntry.Exception != null)
|
||||
{
|
||||
TXTHelper.AppendErrorLog(logEntry.Exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetColorCode(LogLevel logLevel)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user