Compare commits

..

4 Commits

@ -1,140 +0,0 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace OMS.NET.Common
{
public class UserInfo
{
public string? Name { get; set; }
public string? Email { get; set; }
public string? Color { get; set; }
}
public class ActiveDataElement
{
public string EID { get; set; }
public UserInfo? Pick { get; set; }
public UserInfo? Select { get; set; }
public ActiveDataElement(string id)
{
EID = "E" + id;
}
}
public class ActiveDataElementConverter : JsonConverter<ActiveDataElement>
{
public override ActiveDataElement Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartObject)
{
throw new JsonException();
}
reader.Read();
string? eid = (reader.GetString()?[1..]) ?? throw new JsonException(); // Removing 'E' prefix to get the ID
var element = new ActiveDataElement(eid);
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject)
{
break;
}
if (reader.TokenType == JsonTokenType.StartObject)
{
continue;
}
if (reader.TokenType != JsonTokenType.PropertyName)
{
throw new JsonException();
}
string? propertyName = reader.GetString();
reader.Read();
switch (propertyName)
{
case "pick":
element.Pick = DeserializeUserInfo(ref reader);
break;
case "select":
element.Select = DeserializeUserInfo(ref reader);
break;
default:
reader.Skip(); // Skip unknown properties
break;
}
}
//reader.CurrentDepth = 0;
reader.Read();
//还需要读取一次因为之前有过一次读取跳过了一个token最后一个token也要读一次
return element;
}
public override void Write(Utf8JsonWriter writer, ActiveDataElement value, JsonSerializerOptions options)
{
writer.WriteStartObject();
writer.WritePropertyName(value.EID);
writer.WriteStartObject();
if (value.Pick != null) { WriteUserInfo(writer, "pick", value.Pick); }
if (value.Select != null) { WriteUserInfo(writer, "select", value.Select); }
writer.WriteEndObject();
writer.WriteEndObject();
}
private static void WriteUserInfo(Utf8JsonWriter writer, string propertyName, UserInfo userInfo)
{
writer.WriteStartObject(propertyName);
if (userInfo != null)
{
writer.WriteString("name", userInfo.Name);
writer.WriteString("email", userInfo.Email);
writer.WriteString("color", userInfo.Color);
}
writer.WriteEndObject();
}
private static UserInfo DeserializeUserInfo(ref Utf8JsonReader reader)
{
if (reader.TokenType != JsonTokenType.StartObject)
{
throw new JsonException();
}
string? name = null;
string? email = null;
string? color = null;
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject)
{
break;
}
if (reader.TokenType != JsonTokenType.PropertyName)
{
throw new JsonException();
}
string? propertyName = reader.GetString();
reader.Read();
switch (propertyName)
{
case "name":
name = reader.GetString();
break;
case "email":
email = reader.GetString();
break;
case "color":
color = reader.GetString();
break;
default:
reader.Skip(); // Skip unknown properties
break;
}
}
return new UserInfo { Name = name, Email = email, Color = color };
}
}
}

@ -1,11 +1,8 @@
using System.Net; using System.Net;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using System.Text.Json;
using OMS.NET.Common;
using OMS.NET.DbClass;
namespace OMS.NET namespace OMS.NET.Common
{ {
class GlobalArea class GlobalArea
{ {
@ -250,107 +247,5 @@ namespace OMS.NET
#endregion #endregion
#region 缓存与活动数据
private static readonly List<AccountData> _AccountDataList = new();
private static readonly object _AccountDataListLock = new();
/// <summary>
/// 缓存已查询用户数据,如果已存在则替换,需要在数据更新后调用
/// </summary>
public static void AddLoginAccountData(AccountData? accountData)
{
if (accountData == null) return;
lock (_AccountDataListLock)
{
int index = _AccountDataList.FindIndex(u => u.UserEmail == accountData.UserEmail);
if (index == -1)
{
_AccountDataList.Add(accountData);
}
else
{
_AccountDataList[index] = accountData;
}
}
}
/// <summary>
/// 提供一个简单获取登录数据的方法,而不需要重复进行数据库查询
/// </summary>
public static AccountData? GetLoginAccountData(string? email)
{
if (email == null) return null;
lock (_AccountDataListLock)
{
return _AccountDataList.Find(u => u.UserEmail == email);
}
}
private static readonly List<LayerData> _LayerDataList = new();
private static readonly object _LayerDataListLock = new();
/// <summary>
/// 从数据库中构建layerid 和 templateid的对应关系
/// </summary>
public static void BuildLayerData()
{
List<MapLayer> mapLayer = MapLayer.GetMapLayerList();
lock (_LayerDataListLock)
{
foreach (MapLayer layer in mapLayer)
{
LayerData layerData = new(null, layer);
if (layerData.Type != "order")
{
string temId = layerData.Structure!.AsArray().ElementAt(1)!["template"]!["id"]!.GetValue<string>();
layerData.TemplateId = temId;
}
_LayerDataList.Add(layerData);
Console.WriteLine($"{layerData.TemplateId}--{layerData.LayerId}");
}
}
}
public static LayerData? GetLayerDataByTemplateId(string templateId)
{
lock (_LayerDataListLock)
{
try
{
return _LayerDataList.Where(x => x.TemplateId == templateId).First();
}
catch
{
Log.Warn("通过模板id未获取到图层数据");
return null;
}
}
}
#endregion
/// <summary>
/// 默认loglevel为3发布版本需要改成2
/// </summary>
private static Logger _Logger = new(3);
private static readonly object _LoggerLock = new();
public static Logger Log
{
get
{
lock (_LoggerLock)
{
return _Logger;
}
}
}
public static string GetCurrentTime()
{
string format = "yyyy-MM-dd HH:mm:ss";
return DateTime.Now.ToString(format);
}
} }
} }

@ -1,63 +0,0 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using OMS.NET.DbClass;
namespace OMS.NET.Common
{
public class LayerData
{
public string? TemplateId { get; set; }
public long LayerId { get; set; }
public bool HasChange { get; set; } = false;
public string Type { get; set; }
public JsonNode? Members { get; set; }
public JsonNode? Structure { get; set; }
public int Phase { get; set; } = 1;
public LayerData(long layerId, string type)
{
LayerId = layerId;
Type = type;
}
public LayerData(string? templateId, MapLayer layer)
{
TemplateId = templateId;
LayerId = layer.Id;
Type = layer.Type;
Members = (layer.Type == "order") ? JsonNode.Parse(layer.Members) : JsonNode.Parse(Util.Base64ToJson(layer.Members));
Structure = string.IsNullOrEmpty(layer.Structure) ? null : JsonNode.Parse(Util.Base64ToJson(layer.Structure));
Phase = layer.Phase;
}
public void AppendElement(long itemId, string ItemType)
{
if (this.Type == "order")
{
GlobalArea.Log.Error($"order图层不能添加{ItemType}元素");
return;
}
if (this.Members![itemId.ToString()] == null)
{
this.Members![itemId.ToString()] = ItemType;
this.Structure!.AsArray().Add(itemId);
this.HasChange = true;
//上传图层到数据库
MapLayer mapLayer = ConvertToMapLayer();
MapLayer.Update(mapLayer);
}
}
public MapLayer ConvertToMapLayer()
{
return new MapLayer()
{
Id = this.LayerId,
Type = this.Type,
Members = (this.Type == "order") ? this.Members!.ToString() : Util.JsonToBase64(this.Members!.ToString()),
Structure = (this.Structure == null) ? "" : Util.JsonToBase64(this.Structure!.ToString()),
Phase = this.Phase
};
}
}
}

@ -1,30 +1,24 @@
namespace OMS.NET.Common namespace OMS.NET.Common
{ {
public class Logger public class Log
{ {
private readonly int _logLevel; private static readonly int _logLevel = 3; //debug
private int logCount; private static int logCount = 0;
private string logPath; private static string logPath = GetNewLogFile();
private static readonly object LogLock = new(); private static readonly object LogLock = new();
private void WriteLog(string message) private static void WriteLogToFile(string message)
{ {
lock (LogLock) lock (LogLock)
{ {
using var writer = new StreamWriter(this.logPath, true); using var writer = new StreamWriter(logPath, true);
writer.WriteLine(message); writer.WriteLine(message);
} }
} }
public Logger(int level) private static string GetNewLogFile()
{ {
_logLevel = level; logCount = 0;
this.logPath = GetNewLogFile();
}
private string GetNewLogFile()
{
this.logCount = 0;
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log", $"{DateTime.Now:yyyy-MM-dd-HH-mm-ss}.log"); string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log", $"{DateTime.Now:yyyy-MM-dd-HH-mm-ss}.log");
if (!Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log"))) if (!Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log")))
{ {
@ -34,16 +28,16 @@ namespace OMS.NET.Common
return path; return path;
} }
private void Log(string message, int level) private static void Go(string message, int level)
{ {
if (level <= this._logLevel) if (level <= _logLevel)
{ {
string logtime = DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss]"); string logtime = DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss]");
string leveltext = level switch string leveltext = level switch
{ {
0 => "[ERROR]", 0 => "[ERROR]",
1 => "[WARN]", 1 => "[WARN] ",
2 => "[INFO]", 2 => "[INFO] ",
3 => "[DEBUG]", 3 => "[DEBUG]",
_ => level.ToString(), _ => level.ToString(),
}; };
@ -51,31 +45,32 @@ namespace OMS.NET.Common
Console.WriteLine(logtext); Console.WriteLine(logtext);
if (logCount > 100000) if (logCount > 100000)
{ {
this.logPath = GetNewLogFile(); logPath = GetNewLogFile();
} }
//File.AppendAllTextAsync(this.logPath, logtext); //File.AppendAllTextAsync(this.logPath, logtext);
WriteLog(logtext); WriteLogToFile(logtext);
logCount++; logCount++;
} }
} }
public void Error(string message)
public static void Error(string message)
{ {
Log(message, 0); Go(message, 0);
} }
public void Warn(string message) public static void Warn(string message)
{ {
Log(message, 1); Go(message, 1);
} }
public void Info(string message) public static void Info(string message)
{ {
Log(message, 2); Go(message, 2);
} }
public void Debug(string message) public static void Debug(string message)
{ {
Log(message, 3); Go(message, 3);
} }
} }
} }

@ -1,6 +1,4 @@
using System.Reflection;
using System.Text; using System.Text;
using System.Text.Json;
namespace OMS.NET.Common namespace OMS.NET.Common
{ {
@ -36,38 +34,6 @@ namespace OMS.NET.Common
? value ? value
: "false"; : "false";
/// <summary>
/// 地图的背景图片位置图像尺寸为220px * 165px 最大为60kb 支持PNG和jpg类型的图片格式
/// default ./map_img.png
/// </summary>
public string Img => _config.TryGetValue("ServerConfigImg", out string? value)
? value
: "./map_img.png";
/// <summary>
/// key是唯一的,长度不限格式k[a-Z0-9]是客户端采用https://name.com/ + m/key 的方式快捷访问地图服务器的
/// default k0
/// </summary>
public string Key => _config.TryGetValue("ServerConfigKey", out string? value)
? value
: "k0";
/// <summary>
/// 服务器websocket链接的地址
/// default 'ws://0.0.0.0:8080'
/// </summary>
public string Url => _config.TryGetValue("ServerConfigUrl", out string? value)
? value
: "ws://0.0.0.0:8080";
/// <summary>
/// 服务器名称
/// default 地图名称
/// </summary>
public string Name => _config.TryGetValue("ServerConfigName", out string? value)
? value
: "地图名称";
/// <summary> /// <summary>
/// 服务器最大在线人数 /// 服务器最大在线人数
/// default 20 /// default 20
@ -76,172 +42,6 @@ namespace OMS.NET.Common
? value ? value
: "20"; : "20";
/// <summary>
/// 最大高度
/// default 10000
/// </summary>
public string MaxHeight => _config.TryGetValue("ServerConfigMaxHeight", out string? value)
? value
: "10000";
/// <summary>
/// 最小高度
/// default -10000
/// </summary>
public string MinHeight => _config.TryGetValue("ServerConfigMinHeight", out string? value)
? value
: "-10000";
/// <summary>
/// 最大宽度
/// default 10000
/// </summary>
public string MaxWidth => _config.TryGetValue("ServerConfigMaxWidth", out string? value)
? value
: "10000";
/// <summary>
/// 最小宽度
/// default -10000
/// </summary>
public string MinWidth => _config.TryGetValue("ServerConfigMinWidth", out string? value)
? value
: "-10000";
/// <summary>
/// 区域内横轴和纵轴的最小层级下layer0每像素移动量单位 纵轴单位
/// default 1
/// </summary>
public string Unit1Y => _config.TryGetValue("ServerConfigUnit1Y", out string? value)
? value
: "1";
/// <summary>
/// 区域内横轴和纵轴的最小层级下layer0每像素移动量单位 横轴单位
/// default 1
/// </summary>
public string Unit1X => _config.TryGetValue("ServerConfigUnit1X", out string? value)
? value
: "1";
/// <summary>
/// 打开地图时的默认中心点 x
/// default 0
/// </summary>
public string P0X => _config.TryGetValue("ServerConfigP0X", out string? value)
? value
: "0";
/// <summary>
/// 打开地图时的默认中心点 y
/// default 0
/// </summary>
public string P0Y => _config.TryGetValue("ServerConfigP0Y", out string? value)
? value
: "0";
/// <summary>
/// 最大层级
/// default 5
/// </summary>
public string MaxLayer => _config.TryGetValue("ServerConfigMaxLayer", out string? value)
? value
: "default";
/// <summary>
/// 最小层级
/// default 0
/// </summary>
public string MinLayer => _config.TryGetValue("ServerConfigMinLayer", out string? value)
? value
: "default";
/// <summary>
/// 默认层级
/// default 0
/// </summary>
public string DefaultLayer => _config.TryGetValue("ServerConfigDefaultLayer", out string? value)
? value
: "0";
/// <summary>
/// 默认缩放比例
/// default 1
/// </summary>
public string ZoomAdd => _config.TryGetValue("ServerConfigZoomAdd", out string? value)
? value
: "1";
/// <summary>
/// 表示是否启用额外的底图服务
/// default false
/// </summary>
public string EnableBase => _config.TryGetValue("ServerConfigEnableBase", out string? value)
? value
: "false";
/// <summary>
/// 默认x
/// default 0
/// </summary>
public string DefaultX => _config.TryGetValue("ServerConfigDefaultX", out string? value)
? value
: "0";
/// <summary>
/// 默认y
/// default 0
/// </summary>
public string DefaultY => _config.TryGetValue("ServerConfigDefaultY", out string? value)
? value
: "0";
/// <summary>
/// 屏幕默认分辨率x
/// default 1920
/// </summary>
public string ResolutionX => _config.TryGetValue("ServerConfigResolutionX", out string? value)
? value
: "1920";
/// <summary>
/// 屏幕默认分辨率y
/// default 980
/// </summary>
public string ResolutionY => _config.TryGetValue("ServerConfigResolutionY", out string? value)
? value
: "980";
/// <summary>
/// 最大底图缩放等级
/// default 0
/// </summary>
public string MaxZoom => _config.TryGetValue("ServerConfigMaxZoom", out string? value)
? value
: "0";
/// <summary>
/// 最小底图缩放等级
/// default 0
/// </summary>
public string MinZoom => _config.TryGetValue("ServerConfigMinZoom", out string? value)
? value
: "0";
/// <summary>
/// 默认底图缩放等级
/// default 0
/// </summary>
public string DefaultZoom => _config.TryGetValue("ServerConfigDefaultZoom", out string? value)
? value
: "0";
/// <summary>
/// 底图服务的服务器URL
/// default empty
/// </summary>
public string BaseMapUrl => _config.TryGetValue("ServerConfigBaseMapUrl", out string? value)
? value
: "";
public ServerConfig() public ServerConfig()
{ {
//do nothing,everything default //do nothing,everything default

@ -22,11 +22,4 @@ namespace OMS.NET.Common
this.UserEndPoint = UserEndPoint; this.UserEndPoint = UserEndPoint;
} }
} }
// public class UserData
// {
// public string UserEmail { get; set; }
// public string UserName { get; set; }
// public int Map_Layer { get; set; }
// }
} }

@ -1,71 +0,0 @@
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
namespace OMS.NET.Common
{
public class Point
{
public double X { get; set; }
public double Y { get; set; }
}
public class Util
{
public static readonly JsonSerializerOptions options = new()
{
ReadCommentHandling = JsonCommentHandling.Skip, //允许注释
AllowTrailingCommas = true,//允许尾随逗号
//PropertyNamingPolicy = new InstructNamingPolicy(), // 属性名为定制转换
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, // 忽略 null 值
WriteIndented = true, // 美化输出
PropertyNameCaseInsensitive = true,//属性名忽略大小写
};
public static string ObjToBase64(object obj)
{
string utf8 = JsonSerializer.Serialize(obj, options);
return Convert.ToBase64String(Encoding.UTF8.GetBytes(utf8));
}
public static string JsonToBase64(string json)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(json));
}
public static string Base64ToJson(string base64)
{
return Encoding.UTF8.GetString(Convert.FromBase64String(base64));
}
// public static JsonNode? JsonNodeFromJson(string json)
// {
// return JsonNode.Parse(json);
// }
//===========================================================
public static List<Point> PointsFromBase64(string base64)
{
string utf8 = Base64ToJson(base64);
return PointsFromJson(utf8);
}
public static List<Point> PointsFromJson(string json)
{
return JsonSerializer.Deserialize<List<Point>>(json, options) ?? new List<Point>();
}
public static Point PointFromBase64(string base64)
{
string utf8 = Base64ToJson(base64);
return PointFromJson(utf8);
}
public static Point PointFromJson(string json)
{
return JsonSerializer.Deserialize<Point>(json, options) ?? throw new Exception("转化point类型失败:" + json);
}
}
}

@ -1,19 +0,0 @@
using System.Text.RegularExpressions;
namespace OMS.NET.Common
{
public static class Validations
{
/// <summary>
/// 验证颜色值是否有效
/// </summary>
/// <param name="color"></param>
/// <returns></returns>
public static bool IsHexColor(string color)
{
// Regex for hex color code (with or without #)
var hexColorRegex = new Regex(@"^#?[0-9A-Fa-f]{6}$");
return hexColorRegex.IsMatch(color);
}
}
}

@ -1,112 +0,0 @@
using MySql.Data.MySqlClient;
namespace OMS.NET.DbClass
{
public class AccountData
{
#region base
public string UserEmail { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public int? MapLayer { get; set; }
public string? DefaultA1 { get; set; }
public string? SavePoint { get; set; }
public string? UserQQ { get; set; }
public string? HeadColor { get; set; }
public int Mode { get; set; }
public int Phase { get; set; }
public string? Custom { get; set; }
public AccountData()
{
this.UserEmail = "";
this.UserName = "";
this.Password = "";
this.Mode = 1;
this.Phase = 1;
//this.Custom = "";
}
#endregion
public static void Add(AccountData accountData)
{
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open();
var query = @"INSERT INTO account_data (user_email, user_name, pass_word, map_layer, default_a1, save_point, user_qq, head_color, mode, phase, custom)
VALUES (@UserEmail, @UserName, @Password, @MapLayer, @DefaultA1, @SavePoint, @UserQQ, @HeadColor, @Mode, @Phase, @Custom)";
using var command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@UserEmail", accountData.UserEmail);
command.Parameters.AddWithValue("@UserName", accountData.UserName);
command.Parameters.AddWithValue("@Password", accountData.Password);
command.Parameters.AddWithValue("@MapLayer", accountData.MapLayer ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@DefaultA1", accountData.DefaultA1 ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@SavePoint", accountData.SavePoint ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@UserQQ", accountData.UserQQ ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@HeadColor", accountData.HeadColor ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@Mode", accountData.Mode);
command.Parameters.AddWithValue("@Phase", accountData.Phase);
command.Parameters.AddWithValue("@Custom", accountData.Custom ?? (object)DBNull.Value);
command.ExecuteNonQuery();
}
public static void Update(AccountData accountData)
{
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open();
var query = @"UPDATE account_data SET user_name = @UserName, pass_word = @Password, map_layer = @MapLayer, default_a1 = @DefaultA1, save_point = @SavePoint, user_qq = @UserQQ, head_color = @HeadColor, mode = @Mode, phase = @Phase, custom = @Custom
WHERE user_email = @UserEmail";
using var command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@UserEmail", accountData.UserEmail);
command.Parameters.AddWithValue("@UserName", accountData.UserName);
command.Parameters.AddWithValue("@Password", accountData.Password);
command.Parameters.AddWithValue("@MapLayer", accountData.MapLayer ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@DefaultA1", accountData.DefaultA1 ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@SavePoint", accountData.SavePoint ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@UserQQ", accountData.UserQQ ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@HeadColor", accountData.HeadColor ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@Mode", accountData.Mode);
command.Parameters.AddWithValue("@Phase", accountData.Phase);
command.Parameters.AddWithValue("@Custom", accountData.Custom ?? (object)DBNull.Value);
command.ExecuteNonQuery();
}
public static void Delete(string userEmail)
{
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open();
var query = @"DELETE FROM account_data WHERE user_email = @UserEmail";
using var command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@UserEmail", userEmail);
command.ExecuteNonQuery();
}
public static AccountData? Get(string userEmail)
{
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open();
var query = @"SELECT user_email, user_name, pass_word, map_layer, default_a1, save_point, user_qq, head_color, mode, phase, custom
FROM account_data WHERE user_email = @UserEmail";
using var command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@UserEmail", userEmail);
using var reader = command.ExecuteReader();
if (reader.Read())
{
return new AccountData
{
UserEmail = reader.GetString("user_email"),
UserName = reader.GetString("user_name"),
Password = reader.GetString("pass_word"),
MapLayer = reader["map_layer"] as int?,
DefaultA1 = reader["default_a1"] as string,
SavePoint = reader["save_point"] as string,
UserQQ = reader["user_qq"] as string,
HeadColor = reader["head_color"] as string,
Mode = reader.GetInt32("mode"),
Phase = reader.GetInt32("phase"),
Custom = reader["custom"] as string,
};
}
return null;
}
}
}

@ -0,0 +1,28 @@
namespace OMS.NET.DbClass
{
[Table("map_data")]
public class Map : SqlTable
{
[Column("id", true)] // Primary Key and Identity false
public string Id { get; set; }
[Column("name")]
public string Name { get; set; }
[Column("description")]
public string Description { get; set; }
public Map()
{
Id = "";
Name = "";
Description = "";
}
public Map(string key, string name, string description)
{
Id = key;
Name = name;
Description = description;
}
}
}

@ -1,155 +0,0 @@
using MySql.Data.MySqlClient;
namespace OMS.NET.DbClass
{
public class MapData
{
#region base
public long Id { get; set; }
public string Type { get; set; }
public string Points { get; set; }
public string Point { get; set; }
public string? Color { get; set; }
public int Phase { get; set; }
public int? Width { get; set; }
public string? ChildRelations { get; set; }
public string? FatherRelations { get; set; }
public string? ChildNodes { get; set; }
public string? FatherNode { get; set; }
public string? Details { get; set; }
public string? Custom { get; set; }
public MapData()
{
this.Id = -1;
this.Type = "";
this.Points = "";
this.Point = "";
this.Phase = 1;
}
#endregion
public static void Add(MapData mapData)
{
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open();
var query = @"INSERT INTO map_0_data (type, points, point, color, phase, width, child_relations, father_relations, child_nodes, father_node, details, custom)
VALUES (@Type, @Points, @Point, @Color, @Phase, @Width, @ChildRelations, @FatherRelations, @ChildNodes, @FatherNode, @Details, @Custom)";
using MySqlCommand command = new(query, connection);
command.Parameters.AddWithValue("@Type", mapData.Type);
command.Parameters.AddWithValue("@Points", mapData.Points);
command.Parameters.AddWithValue("@Point", mapData.Point);
command.Parameters.AddWithValue("@Color", mapData.Color ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@Phase", mapData.Phase);
command.Parameters.AddWithValue("@Width", mapData.Width ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@ChildRelations", mapData.ChildRelations ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@FatherRelations", mapData.FatherRelations ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@ChildNodes", mapData.ChildNodes ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@FatherNode", mapData.FatherNode ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@Details", mapData.Details ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@Custom", mapData.Custom ?? (object)DBNull.Value);
command.ExecuteNonQuery();
mapData.Id = command.LastInsertedId;
}
public static int Update(MapData mapData)
{
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open();
var query = @"UPDATE map_0_data SET type = @Type, points = @Points, point = @Point, color = @Color, phase = @Phase, width = @Width,
child_relations = @ChildRelations, father_relations = @FatherRelations, child_nodes = @ChildNodes, father_node = @FatherNode,
details = @Details, custom = @Custom WHERE id = @Id";
using MySqlCommand command = new(query, connection);
command.Parameters.AddWithValue("@Id", mapData.Id);
command.Parameters.AddWithValue("@Type", mapData.Type);
command.Parameters.AddWithValue("@Points", mapData.Points);
command.Parameters.AddWithValue("@Point", mapData.Point);
command.Parameters.AddWithValue("@Color", mapData.Color ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@Phase", mapData.Phase);
command.Parameters.AddWithValue("@Width", mapData.Width ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@ChildRelations", mapData.ChildRelations ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@FatherRelations", mapData.FatherRelations ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@ChildNodes", mapData.ChildNodes ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@FatherNode", mapData.FatherNode ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@Details", mapData.Details ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@Custom", mapData.Custom ?? (object)DBNull.Value);
return command.ExecuteNonQuery();
}
public static void Delete(long id)
{
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open();
var query = @"DELETE FROM map_0_data WHERE id = @Id";
using MySqlCommand command = new(query, connection);
command.Parameters.AddWithValue("@Id", id);
command.ExecuteNonQuery();
}
public static MapData? Get(long id)
{
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open();
var query = @"SELECT id, type, points, point, color, phase, width, child_relations, father_relations, child_nodes, father_node, details, custom
FROM map_0_data WHERE id = @Id";
using MySqlCommand command = new(query, connection);
command.Parameters.AddWithValue("@Id", id);
using MySqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
return new MapData
{
Id = reader.GetInt64("id"),
Type = reader.GetString("type"),
Points = reader.GetString("points"),
Point = reader.GetString("point"),
Color = reader["color"] as string,
Phase = reader.GetInt32("phase"),
Width = reader["width"] as int?,
ChildRelations = reader["child_relations"] as string,
FatherRelations = reader["father_relations"] as string,
ChildNodes = reader["child_nodes"] as string,
FatherNode = reader["father_node"] as string,
Details = reader["details"] as string,
Custom = reader["custom"] as string
};
}
return null;
}
public static List<MapData> GetMapDataList()
{
List<MapData> mapDataList = new();
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open();
var query = @"SELECT * FROM map_0_data";
using var command = new MySqlCommand(query, connection);
using var reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
var mapData = new MapData
{
Id = reader.GetInt64("id"),
Type = reader.GetString("type"),
Points = reader.GetString("points"),
Point = reader.GetString("point"),
Color = reader.IsDBNull(reader.GetOrdinal("color")) ? null : reader.GetString("color"),
Phase = reader.GetInt32("phase"),
Width = reader.IsDBNull(reader.GetOrdinal("width")) ? (int?)null : reader.GetInt32("width"),
ChildRelations = reader.IsDBNull(reader.GetOrdinal("child_relations")) ? null : reader.GetString("child_relations"),
FatherRelations = reader.IsDBNull(reader.GetOrdinal("father_relations")) ? null : reader.GetString("father_relations"),
ChildNodes = reader.IsDBNull(reader.GetOrdinal("child_nodes")) ? null : reader.GetString("child_nodes"),
FatherNode = reader.IsDBNull(reader.GetOrdinal("father_node")) ? null : reader.GetString("father_node"),
Details = reader.IsDBNull(reader.GetOrdinal("details")) ? null : reader.GetString("details"),
Custom = reader.IsDBNull(reader.GetOrdinal("custom")) ? null : reader.GetString("custom")
};
mapDataList.Add(mapData);
}
}
return mapDataList;
}
}
}

@ -1,142 +0,0 @@
using MySql.Data.MySqlClient;
namespace OMS.NET.DbClass
{
public class MapLayer
{
#region base
public long Id { get; set; }
public string Type { get; set; }
public string Members { get; set; }
public string Structure { get; set; }
public int Phase { get; set; }
public MapLayer()
{
this.Id = 0;
this.Type = "";
this.Members = "";
this.Structure = "";
this.Phase = 1;
}
public MapLayer(long id, string type, string members, string structure, int phase)
{
Id = id;
Type = type;
Members = members;
Structure = structure;
Phase = phase;
}
#endregion
public static void Add(MapLayer mapLayer)
{
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open();
var query = @"INSERT INTO map_0_layer (type, members, structure, phase)
VALUES (@Type, @Members, @Structure, @Phase)";
using var command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@Type", mapLayer.Type);
command.Parameters.AddWithValue("@Members", mapLayer.Members);
command.Parameters.AddWithValue("@Structure", mapLayer.Structure);
command.Parameters.AddWithValue("@Phase", mapLayer.Phase);
command.ExecuteNonQuery();
mapLayer.Id = command.LastInsertedId;
}
public static void Update(MapLayer mapLayer)
{
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open();
var query = @"UPDATE map_0_layer SET type = @Type, members = @Members, structure = @Structure, phase = @Phase
WHERE id = @Id";
using var command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@Id", mapLayer.Id);
command.Parameters.AddWithValue("@Type", mapLayer.Type);
command.Parameters.AddWithValue("@Members", mapLayer.Members);
command.Parameters.AddWithValue("@Structure", mapLayer.Structure);
command.Parameters.AddWithValue("@Phase", mapLayer.Phase);
command.ExecuteNonQuery();
}
public static void Delete(long id)
{
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open();
var query = @"DELETE FROM map_0_layer WHERE id = @Id";
using var command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@Id", id);
command.ExecuteNonQuery();
}
public static MapLayer? Get(long id)
{
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open();
var query = @"SELECT id, type, members, structure, phase FROM map_0_layer WHERE id = @Id";
using var command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@Id", id);
using var reader = command.ExecuteReader();
if (reader.Read())
{
return new MapLayer
{
Id = reader.GetInt64("id"),
Type = reader.GetString("type"),
Members = reader.GetString("members"),
Structure = reader.GetString("structure"),
Phase = reader.GetInt32("phase")
};
}
return null;
}
/// <summary>
/// 获取所有MapLayer数据
/// </summary>
/// <returns></returns>
public static List<MapLayer> GetMapLayerList()
{
List<MapLayer> mapLayerList = new();
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open();
string query = "SELECT * FROM map_0_layer";
using var command = new MySqlCommand(query, connection);
using var reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
var mapLayer = new MapLayer
{
Id = reader.GetInt64("id"),
Type = reader.GetString("type"),
Members = reader.GetString("members"),
Structure = reader.GetString("structure"),
Phase = reader.GetInt32("phase")
};
mapLayerList.Add(mapLayer);
}
}
return mapLayerList;
}
/// <summary>
/// 指定是否将指定字段编码成base64格式 ???
/// </summary>
public static void ProcessMapLayers(List<MapLayer> mapLayers, bool encode = false)
{
mapLayers.ForEach(mapLayer =>
{
if (encode)
{
}
else
{
}
});
}
}
}

@ -0,0 +1,196 @@
using System.Reflection;
using MySql.Data.MySqlClient;
using OMS.NET.Common;
namespace OMS.NET.DbClass
{
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class TableAttribute : Attribute
{
public string TableName { get; }
public TableAttribute(string tableName)
{
TableName = tableName;
}
}
[AttributeUsage(AttributeTargets.Property, Inherited = false)]
public class ColumnAttribute : Attribute
{
public string ColumnName { get; }
public bool IsPrimaryKey { get; }
public bool IsIdentity { get; } // 是否自增列
public ColumnAttribute(string columnName, bool isPrimaryKey = false, bool isIdentity = false)
{
ColumnName = columnName;
IsPrimaryKey = isPrimaryKey;
IsIdentity = isIdentity;
}
}
public class SqlHelper
{
public static string GetTableName(Type type)
{
var attr = type.GetCustomAttribute<TableAttribute>();
return attr?.TableName ?? throw new Exception($"{type.Name} 没有指定数据表");
}
public static bool IsIdentity(Type type)
{
var primaryKey = GetPrimaryKeyProperties(type);
return primaryKey.GetCustomAttribute<ColumnAttribute>()!.IsIdentity;
}
public static IEnumerable<PropertyInfo> GetProperties(Type type)
{
return type.GetProperties()
.Where(p => p.GetCustomAttribute<ColumnAttribute>() != null);
}
private static PropertyInfo GetPrimaryKeyProperties(Type type)
{
var primaryKeyProperties = GetProperties(type)
.Where(p => p.GetCustomAttribute<ColumnAttribute>()?.IsPrimaryKey == true)
.ToList();
if (primaryKeyProperties.Count == 0)
{
throw new InvalidOperationException("No primary key defined for the class.");
}
if (primaryKeyProperties.Count != 1)
{
throw new InvalidOperationException("Multiple primary keys defined for the class. Only one primary key is allowed.");
}
return primaryKeyProperties.First();
}
private static IEnumerable<PropertyInfo> GetNonKeyProperties(Type type)
{
return GetProperties(type)
.Where(p => p.GetCustomAttribute<ColumnAttribute>()?.IsPrimaryKey == false);
}
private static PropertyInfo? GetIdentityKeyProperty(Type type)
{
var primaryKey = GetPrimaryKeyProperties(type);
return (primaryKey.GetCustomAttribute<ColumnAttribute>()!.IsIdentity == true) ? null : primaryKey;
}
public static string GetInsertSql(Type type)
{
var tableName = GetTableName(type);
var identityKey = GetIdentityKeyProperty(type);
var columns = GetNonKeyProperties(type)
.Select(p => p.GetCustomAttribute<ColumnAttribute>()!.ColumnName).ToList();
var values = GetNonKeyProperties(type)
.Select(p => "@" + p.Name).ToList();
if (identityKey != null)
{
// Exclude the identity key from columns and values for insert statement
columns.Add(identityKey.GetCustomAttribute<ColumnAttribute>()!.ColumnName);
values.Add("@" + identityKey.Name);
}
return $"INSERT INTO {tableName} ({string.Join(", ", columns)}) VALUES ({string.Join(", ", values)})";
}
public static string GetUpdateSql(Type type)
{
var tableName = GetTableName(type);
var setClause = string.Join(", ",
GetNonKeyProperties(type)
.Select(p => $"{p.GetCustomAttribute<ColumnAttribute>()!.ColumnName} = @{p.Name}"));
var primaryKey = GetPrimaryKeyProperties(type);
var whereClause = $"{primaryKey.GetCustomAttribute<ColumnAttribute>()!.ColumnName} = @{primaryKey.Name}";
return $"UPDATE {tableName} SET {setClause} WHERE {whereClause}";
}
public static string GetDeleteSql(Type type)
{
var tableName = GetTableName(type);
var primaryKey = GetPrimaryKeyProperties(type);
var whereClause = $"{primaryKey.GetCustomAttribute<ColumnAttribute>()!.ColumnName} = @{primaryKey.Name}";
return $"DELETE FROM {tableName} WHERE {whereClause}";
}
public static string GetSelectSql(Type type)
{
var tableName = GetTableName(type);
var columns = string.Join(", ",
GetProperties(type)
.Select(p => p.GetCustomAttribute<ColumnAttribute>()!.ColumnName));
return $"SELECT {columns} FROM {tableName}";
}
public static string GetSelectSqlWithPrimaryKey(Type type)
{
var tableName = GetTableName(type);
var columns = string.Join(", ",
GetProperties(type)
.Select(p => p.GetCustomAttribute<ColumnAttribute>()!.ColumnName));
var primaryKey = GetPrimaryKeyProperties(type);
var whereClause = $"{primaryKey.GetCustomAttribute<ColumnAttribute>()!.ColumnName} = @{primaryKey.Name}";
return $"SELECT {columns} FROM {tableName} WHERE {whereClause}";
}
public static IEnumerable<T> SelectAll<T>() where T : SqlTable, new()
{
var type = typeof(T);
var selectSql = GetSelectSql(type);
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open(); // 确保在执行命令之前打开连接
using var command = new MySqlCommand(selectSql, connection);
using var reader = command.ExecuteReader();
var results = new List<T>();
while (reader.Read())
{
var item = new T();
PopulateObject(reader, item);
results.Add(item);
}
return results;
}
private static void PopulateObject(MySqlDataReader reader, SqlTable obj)
{
var type = obj.GetType();
foreach (var property in GetProperties(type))
{
var columnAttr = property.GetCustomAttribute<ColumnAttribute>()!;
var value = reader[columnAttr.ColumnName];
if (value != DBNull.Value)
{
property.SetValue(obj, Convert.ChangeType(value, property.PropertyType));
}
}
}
public static T? Get<T>(object key) where T : SqlTable, new()
{
var type = typeof(T);
var selectSql = GetSelectSqlWithPrimaryKey(type);
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open(); // 确保在执行命令之前打开连接
using var command = new MySqlCommand(selectSql, connection);
var primaryKey = GetPrimaryKeyProperties(type);
command.Parameters.AddWithValue("@" + primaryKey.GetCustomAttribute<ColumnAttribute>()!.ColumnName, key);
using var reader = command.ExecuteReader();
while (reader.Read())
{
var item = new T();
PopulateObject(reader, item);
return item;
}
return null;
}
}
}

@ -0,0 +1,81 @@
using System.Reflection;
using MySql.Data.MySqlClient;
using OMS.NET.Common;
namespace OMS.NET.DbClass
{
public class SqlTable
{
public void Test()
{
Console.WriteLine("===========this is a test area=================");
Console.WriteLine(SqlHelper.GetInsertSql(GetType()));
Console.WriteLine(SqlHelper.GetDeleteSql(GetType()));
Console.WriteLine(SqlHelper.GetUpdateSql(GetType()));
Console.WriteLine(SqlHelper.GetSelectSql(GetType()));
Console.WriteLine(SqlHelper.GetSelectSqlWithPrimaryKey(GetType()));
Console.WriteLine("===========this is a test area=================");
}
/// <summary>
/// 将对象本身插入到数据库中
/// </summary>
public virtual void Insert()
{
var type = GetType();
var insertSql = SqlHelper.GetInsertSql(GetType());
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open(); //确保在执行命令之前打开连接
using var command = new MySqlCommand(insertSql, connection);
AddParameters(command);
Console.WriteLine($"SQL: {command.CommandText}");
foreach (MySqlParameter param in command.Parameters)
{
Console.WriteLine($"Parameter: {param.ParameterName}, Value: {param.Value}");
}
command.ExecuteNonQuery();
Log.Info($"{SqlHelper.GetTableName(type)}数据表插入({string.Join(',', ShowDetail())})");
}
public virtual void Update()
{
var type = GetType();
var updateSql = SqlHelper.GetUpdateSql(GetType());
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open();
using var command = new MySqlCommand(updateSql, connection);
AddParameters(command);
command.ExecuteNonQuery();
Log.Info($"{SqlHelper.GetTableName(type)}数据表修改({string.Join(',', ShowDetail())})");
}
public virtual void Delete()
{
var deleteSql = SqlHelper.GetDeleteSql(GetType());
using MySqlConnection connection = new(GlobalArea.ConnectionStringWithDbName);
connection.Open();
using var command = new MySqlCommand(deleteSql, connection);
AddParameters(command);
command.ExecuteNonQuery();
Log.Info($"{SqlHelper.GetTableName(GetType())}数据表删除({string.Join(',', ShowDetail())})");
}
private void AddParameters(MySqlCommand command)
{
//bool IsIdentity = SqlHelper.IsIdentity(GetType());
foreach (var property in SqlHelper.GetProperties(GetType()))
{
if (property.GetCustomAttribute<ColumnAttribute>()!.IsIdentity)
{
continue;
}
command.Parameters.AddWithValue("@" + property.Name, property.GetValue(this));
}
}
public IEnumerable<string> ShowDetail()
{
return SqlHelper.GetProperties(GetType()).Select(p => $"{p.Name}={p.GetValue(this)}");
}
}
}

@ -1,134 +0,0 @@
using System.Text;
using System.Text.Json;
using OMS.NET.Common;
using OMS.NET.DbClass;
namespace OMS.NET.Instructs
{
public class AddElementBroadcastInstruct : BroadcastInstuct
{
public AddElementBroadcastInstruct()
{
Type = "broadcast";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (GlobalArea.LoginCheckByID(wsid))
{
//从Data中解析数据收到的是json文本类型
if (Data?.GetType() == typeof(JsonElement))
{
try
{
long id = Data.GetProperty("id").GetInt64();
string type = Data.GetProperty("type").GetString();
string points = Data.GetProperty("points").GetString();
string point = Data.GetProperty("point").GetString();
string? color = Data.GetProperty("color").GetString();
int? width = Data.GetProperty("width").GetInt32();
string? childRelations = Data.GetProperty("childRelations").GetString();
string? fatherRelations = Data.GetProperty("fatherRelations").GetString();
string? childNodes = Data.GetProperty("childNodes").GetString();
string? fatherNode = Data.GetProperty("fatherNode").GetString();
string? details = Data.GetProperty("details").GetString();
string? custom = Data.GetProperty("custom").GetString();
//validations todo
//假设所有数据均合法
MapData mapData = new()
{
Type = type,
Points = Util.JsonToBase64(points),
Point = Util.JsonToBase64(point),
Color = color,
Width = width,
ChildRelations = childRelations,
FatherRelations = fatherRelations,
ChildNodes = childNodes,
FatherNode = fatherNode,
Details = Util.JsonToBase64(details),
Custom = Util.JsonToBase64(custom)
};
//保存点到数据库
MapData.Add(mapData);
//获取图层id
if (Data.GetProperty("custom").TryGetProperty("tmpId", out JsonElement tmpIdNode))
{
string tmpId = tmpIdNode.GetString() ?? throw new Exception("tmpId不能为空");
LayerData? layer = GlobalArea.GetLayerDataByTemplateId(tmpId);
if (layer != null && mapData.Id != -1)
{
layer.AppendElement(mapData.Id, mapData.Type);//包括数据库操作
//准备回复广播
string conveyor = GlobalArea.GetLoginEmailByID(wsid);
string time = GlobalArea.GetCurrentTime();
ResponseOrBroadcastInstructs.Add(new BroadcastInstuct()
{
IsBroadcast = true,
Class = this.Class,
Conveyor = conveyor,
Time = time,
Data = mapData,
});
ResponseOrBroadcastInstructs.Add(new BroadcastInstuct()
{
IsBroadcast = true,
Class = "updateLayerData",
Conveyor = conveyor,
Time = time,
Data = new
{
id = layer.LayerId,
members = layer.Members!.ToString(),
structure = layer.Structure!.ToString(),
}
});
ResponseOrBroadcastInstructs.Add(new SendErrorInstuct()
{
IsResponse = true,
Class = "upload",
Conveyor = conveyor,
Time = time,
Data = new Dictionary<string, object>()
{
{"vid",id},
{"rid",mapData.Id}
},
});
}
}
else
{
throw new Exception("未找到 tmpId");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
ResponseOrBroadcastInstructs.Add(new SendErrorInstuct()
{
IsResponse = true,
Class = "upload",
Conveyor = GlobalArea.GetLoginEmailByID(wsid),
Time = GlobalArea.GetCurrentTime(),
Data = new
{
source = Data,
message = ex.Message,
},
});
}
}
}
});
}
}
}

@ -1,31 +0,0 @@
using System.Text.Json;
namespace OMS.NET.Instructs
{
/// <summary>
/// 广播指令的基类
/// </summary>
public class BroadcastInstuct : Instruct
{
public BroadcastInstuct()
{
this.Type = "broadcast";
}
}
public class SendCorrectInstuct : Instruct
{
public SendCorrectInstuct()
{
this.Type = "send_error";
}
}
public class SendErrorInstuct : Instruct
{
public SendErrorInstuct()
{
this.Type = "send_correct";
}
}
}

@ -1,4 +1,4 @@
using OMS.NET.DbClass; using OMS.NET.Common;
namespace OMS.NET.Instructs namespace OMS.NET.Instructs
{ {
@ -6,7 +6,7 @@ namespace OMS.NET.Instructs
{ {
public GetMapDataInstruct() public GetMapDataInstruct()
{ {
this.Type = "get_mapData"; Type = "get_mapData";
} }
public override Task Handler(string wsid) public override Task Handler(string wsid)
@ -15,12 +15,7 @@ namespace OMS.NET.Instructs
{ {
if (GlobalArea.LoginCheckByID(wsid)) if (GlobalArea.LoginCheckByID(wsid))
{ {
List<MapData> mapDatas = MapData.GetMapDataList().Where(m => m.Phase != 2).ToList();
this.ResponseOrBroadcastInstructs.Add(new SendMapDataInstruct()
{
IsResponse = true,
Data = mapDatas
});
} }
}); });
} }
@ -30,7 +25,7 @@ namespace OMS.NET.Instructs
{ {
public SendMapDataInstruct() public SendMapDataInstruct()
{ {
this.Type = "send_mapData"; Type = "send_mapData";
} }
} }
} }

@ -1,4 +1,4 @@
using OMS.NET.DbClass; using OMS.NET.Common;
namespace OMS.NET.Instructs namespace OMS.NET.Instructs
{ {
@ -6,7 +6,7 @@ namespace OMS.NET.Instructs
{ {
public GetMapLayerInstruct() public GetMapLayerInstruct()
{ {
this.Type = "get_mapLayer"; Type = "get_mapLayer";
} }
public override Task Handler(string wsid) public override Task Handler(string wsid)
@ -15,12 +15,7 @@ namespace OMS.NET.Instructs
{ {
if (GlobalArea.LoginCheckByID(wsid)) if (GlobalArea.LoginCheckByID(wsid))
{ {
List<MapLayer> mapLayers = MapLayer.GetMapLayerList().Where(m => m.Phase != 2).ToList();
this.ResponseOrBroadcastInstructs.Add(new SendMapLayerInstruct()
{
IsResponse = true,
Data = mapLayers
});
} }
}); });
} }
@ -30,7 +25,7 @@ namespace OMS.NET.Instructs
{ {
public SendMapLayerInstruct() public SendMapLayerInstruct()
{ {
this.Type = "send_mapLayer"; Type = "send_mapLayer";
} }
} }
} }

@ -1,52 +0,0 @@
using OMS.NET.DbClass;
namespace OMS.NET.Instructs
{
public class GetPresenceInstruct : Instruct
{
public GetPresenceInstruct()
{
this.Type = "get_presence";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (GlobalArea.LoginCheckByID(wsid))
{
//获取所有在线用户,移除重复
List<string?> emails = GlobalArea.UserConnects.Where(u => u.UserEmail != null)
.Select(u => u.UserEmail).Distinct().ToList();
List<dynamic> allLoginUsers = new();
emails.ForEach(email =>
{
AccountData accountData = GlobalArea.GetLoginAccountData(email)!;
//由于是已登录用户,默认都能查询到值
allLoginUsers.Add(new
{
userEmail = accountData.UserEmail,
userQq = accountData.UserQQ,
userName = accountData.UserName,
headColor = accountData.HeadColor,
});
});
this.ResponseOrBroadcastInstructs.Add(new SendPresenceInstruct()
{
IsResponse = true,
Data = allLoginUsers,
});
}
});
}
}
public class SendPresenceInstruct : Instruct
{
public SendPresenceInstruct()
{
this.Type = "send_presence";
}
}
}

@ -1,17 +1,19 @@
using OMS.NET.Common;
namespace OMS.NET.Instructs namespace OMS.NET.Instructs
{ {
public class GetPublickeyInstruct : Instruct public class GetPublickeyInstruct : Instruct
{ {
public GetPublickeyInstruct() public GetPublickeyInstruct()
{ {
this.Type = "get_publickey"; Type = "get_publickey";
} }
public override Task Handler(string wsid) public override Task Handler(string wsid)
{ {
return Task.Run(() => return Task.Run(() =>
{ {
this.ResponseOrBroadcastInstructs.Add(new PublickeyInstruct() ResponseOrBroadcastInstructs.Add(new PublickeyInstruct()
{ {
Data = GlobalArea.GetRsaPublickKey(), Data = GlobalArea.GetRsaPublickKey(),
IsResponse = true IsResponse = true
@ -25,7 +27,7 @@ namespace OMS.NET.Instructs
{ {
public PublickeyInstruct() public PublickeyInstruct()
{ {
this.Type = "publickey"; Type = "publickey";
} }
} }

@ -1,47 +0,0 @@
namespace OMS.NET.Instructs
{
public class GetServerConfigInstruct : Instruct
{
public GetServerConfigInstruct()
{
this.Type = "get_serverConfig";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
this.ResponseOrBroadcastInstructs.Add(new SendServerConfigInstruct
{
IsResponse = true,
Data = new
{
anonymous_login = bool.TryParse(GlobalArea.ServerConfig.AnonymousLogin, out bool booleanValue) && booleanValue,
key = GlobalArea.ServerConfig.Key,
url = GlobalArea.ServerConfig.Url,
name = GlobalArea.ServerConfig.Name,
online_number = GlobalArea.ConnectClientsCount,
max_online = GlobalArea.ServerConfig.MaxUser,
default_x = GlobalArea.ServerConfig.DefaultX,
default_y = GlobalArea.ServerConfig.DefaultY,
//以下在0.7会删除
enable_base_map = GlobalArea.ServerConfig.EnableBase,
//base_map_type= GlobalArea.ServerConfig.ServerConfigEnableBase,
max_zoom = GlobalArea.ServerConfig.MaxZoom,
min_zoom = GlobalArea.ServerConfig.MinZoom,
default_zoom = GlobalArea.ServerConfig.DefaultZoom,
base_map_url = GlobalArea.ServerConfig.BaseMapUrl
}
});
});
}
}
public class SendServerConfigInstruct : Instruct
{
public SendServerConfigInstruct()
{
this.Type = "send_serverConfig";
}
}
}

@ -1,84 +0,0 @@
using System.Globalization;
using WebSocketSharp;
namespace OMS.NET.Instructs
{
public class GetServerImgInstruct : Instruct
{
public GetServerImgInstruct()
{
this.Type = "get_serverImg";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (this.Time != null)
{
//时间解析
string format = "yyyy-MM-dd HH:mm:ss";
DateTime clientDateTime = DateTime.ParseExact(this.Time, format, CultureInfo.InvariantCulture);
//Console.WriteLine("Converted DateTime: " + clientDateTime);
string serverImgPath = GlobalArea.ServerConfig.Img;
if (File.Exists(serverImgPath))
{
DateTime serverImgLastModified = File.GetLastWriteTime(serverImgPath);
Instruct res = new SendServerConfigInstruct
{
IsResponse = true
};
if (serverImgLastModified > clientDateTime)
{
byte[] imageBytes = File.ReadAllBytes(serverImgPath);
string imageFileType = GetImageFileType(imageBytes);
string base64String = $"data:image/{imageFileType};base64," + Convert.ToBase64String(imageBytes);
//Console.WriteLine("Base64 Encoded Image: " + base64String);
res.Data = new
{
@string = base64String,
time = serverImgLastModified.ToString(format),
};
}
else
{
res.Data = new
{
@string = ""
};
}
this.ResponseOrBroadcastInstructs.Add(res);
}
}
});
}
static string GetImageFileType(byte[] imageBytes)
{
byte[] fileHeader = imageBytes.SubArray(0, 8);
// PNG 文件的文件头字节为 89 50 4E 47 0D 0A 1A 0A
if (fileHeader[0] == 0x89 && fileHeader[1] == 0x50 && fileHeader[2] == 0x4E && fileHeader[3] == 0x47 &&
fileHeader[4] == 0x0D && fileHeader[5] == 0x0A && fileHeader[6] == 0x1A && fileHeader[7] == 0x0A)
{
return "png";
}
// JPEG 文件的文件头字节为 FF D8 FF
if (fileHeader[0] == 0xFF && fileHeader[1] == 0xD8 && fileHeader[2] == 0xFF)
{
return "jpeg";
}
return "unknown";
}
}
public class SendServerImgInstruct : Instruct
{
public SendServerImgInstruct()
{
this.Type = "send_serverImg";
}
}
}

@ -1,4 +1,4 @@
using OMS.NET.DbClass; using OMS.NET.Common;
namespace OMS.NET.Instructs namespace OMS.NET.Instructs
{ {
@ -6,7 +6,7 @@ namespace OMS.NET.Instructs
{ {
public GetUserDataInstruct() public GetUserDataInstruct()
{ {
this.Type = "get_userData"; Type = "get_userData";
} }
public override Task Handler(string wsid) public override Task Handler(string wsid)
@ -16,23 +16,6 @@ namespace OMS.NET.Instructs
if (GlobalArea.LoginCheckByID(wsid)) if (GlobalArea.LoginCheckByID(wsid))
{ {
string userEmail = GlobalArea.UserConnects.First(u => u.ID == wsid).UserEmail!; string userEmail = GlobalArea.UserConnects.First(u => u.ID == wsid).UserEmail!;
AccountData accountData = GlobalArea.GetLoginAccountData(userEmail)!;
this.ResponseOrBroadcastInstructs.Add(new SendUserDataInstruct()
{
IsResponse = true,
Data = new
{
user_email = accountData.UserEmail,
user_name = accountData.UserName,
map_layer = accountData.MapLayer,
default_a1 = accountData.DefaultA1,
save_point = accountData.SavePoint,
head_color = accountData.HeadColor,
mode = accountData.Mode,
phase = accountData.Phase,
custom = accountData.Custom,
}
});
} }
}); });
} }
@ -42,7 +25,7 @@ namespace OMS.NET.Instructs
{ {
public SendUserDataInstruct() public SendUserDataInstruct()
{ {
this.Type = "send_userData"; Type = "send_userData";
} }
} }
} }

@ -1,7 +1,7 @@
using System.Diagnostics; using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using OMS.NET.Common;
namespace OMS.NET.Instructs namespace OMS.NET.Instructs
{ {
@ -44,29 +44,14 @@ namespace OMS.NET.Instructs
{ {
//实现新指令需在这里添加反序列化类型,限定为客户端发过来的指令类型 //实现新指令需在这里添加反序列化类型,限定为客户端发过来的指令类型
"get_publickey" => JsonSerializer.Deserialize<GetPublickeyInstruct>(root.GetRawText(), options), "get_publickey" => JsonSerializer.Deserialize<GetPublickeyInstruct>(root.GetRawText(), options),
"get_serverImg" => JsonSerializer.Deserialize<GetServerImgInstruct>(root.GetRawText(), options),
"get_serverConfig" => JsonSerializer.Deserialize<GetServerConfigInstruct>(root.GetRawText(), options),
"login" => JsonSerializer.Deserialize<LoginInstruct>(root.GetRawText(), options), "login" => JsonSerializer.Deserialize<LoginInstruct>(root.GetRawText(), options),
"test" => JsonSerializer.Deserialize<TestInstruct>(root.GetRawText(), options), "test" => JsonSerializer.Deserialize<TestInstruct>(root.GetRawText(), options),
"get_userData" => JsonSerializer.Deserialize<GetUserDataInstruct>(root.GetRawText(), options), "get_userData" => JsonSerializer.Deserialize<GetUserDataInstruct>(root.GetRawText(), options),
"get_presence" => JsonSerializer.Deserialize<GetPresenceInstruct>(root.GetRawText(), options),
"get_mapData" => JsonSerializer.Deserialize<GetMapDataInstruct>(root.GetRawText(), options), "get_mapData" => JsonSerializer.Deserialize<GetMapDataInstruct>(root.GetRawText(), options),
"get_mapLayer" => JsonSerializer.Deserialize<GetMapLayerInstruct>(root.GetRawText(), options), "get_mapLayer" => JsonSerializer.Deserialize<GetMapLayerInstruct>(root.GetRawText(), options),
"ping" => JsonSerializer.Deserialize<PingInstuct>(root.GetRawText(), options),
//广播指令
"broadcast" => classValue switch
{
//广播指令继承结构
"point" => JsonSerializer.Deserialize<AddElementBroadcastInstruct>(root.GetRawText(), options),
"line" => JsonSerializer.Deserialize<AddElementBroadcastInstruct>(root.GetRawText(), options),
"area" => JsonSerializer.Deserialize<AddElementBroadcastInstruct>(root.GetRawText(), options),
"curve" => JsonSerializer.Deserialize<AddElementBroadcastInstruct>(root.GetRawText(), options),
_ => JsonSerializer.Deserialize<Instruct>(root.GetRawText(), options)
},
_ => null _ => null
} ?? throw new JsonException($"{typeValue} 反序列化失败"); };
return instruct; return instruct ?? throw new JsonException($"{typeValue} 反序列化失败");
} }
else else
{ {
@ -127,7 +112,7 @@ namespace OMS.NET.Instructs
public Instruct() public Instruct()
{ {
this.Type = ""; Type = "";
} }
/// <summary> /// <summary>
@ -145,7 +130,7 @@ namespace OMS.NET.Instructs
stopWatch.Start(); stopWatch.Start();
await Handler(wsid); await Handler(wsid);
stopWatch.Stop(); stopWatch.Stop();
GlobalArea.Log.Debug($"处理{this.GetType()}耗时:{stopWatch.ElapsedMilliseconds}ms"); Log.Debug($"处理{GetType()}耗时:{stopWatch.ElapsedMilliseconds}ms");
} }
public string ToJsonString() public string ToJsonString()
@ -161,7 +146,7 @@ namespace OMS.NET.Instructs
} }
catch (Exception ex) catch (Exception ex)
{ {
GlobalArea.Log.Error(ex.Message); Log.Error(ex.Message);
return null; return null;
} }
} }

@ -1,6 +1,6 @@
using System.Text.Json; using System.Text.Json;
using OMS.NET.DbClass; using OMS.NET.Common;
namespace OMS.NET.Instructs namespace OMS.NET.Instructs
{ {
@ -11,60 +11,22 @@ namespace OMS.NET.Instructs
{ {
public LoginInstruct() public LoginInstruct()
{ {
this.Type = "login"; Type = "login";
} }
public override Task Handler(string wsid) public override Task Handler(string wsid)
{ {
return Task.Run(() => return Task.Run(() =>
{ {
if (this.Data?.GetType() == typeof(JsonElement)) if (Data?.GetType() == typeof(JsonElement))
{ {
string email = this.Data.GetProperty("email").GetString(); string email = Data.GetProperty("email").GetString();
string password = this.Data.GetProperty("password").GetString(); string password = Data.GetProperty("password").GetString();
if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password)) if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
{ {
GlobalArea.Log.Warn("登录信息不能为空!"); Log.Warn("登录信息不能为空!");
return; return;
} }
//能够获取到则说明客户端有发送数据过来
Instruct res1 = new LoginStatusInstuct
{
Data = false,
IsResponse = true
};//默认为false
//Console.WriteLine($"已获取到{email}:{password},解密测试{GlobalArea.DecryptFromBase64String(password)}");
AccountData? accountData = AccountData.Get(email);
GlobalArea.AddLoginAccountData(accountData);
if (accountData != null)
{
//只能原文比较,密文每次都不一样,涉及随机性填充
if (accountData.Password == GlobalArea.DecryptFromBase64String(password))
{
res1.Data = true;//登录成功则修改为true
this.ResponseOrBroadcastInstructs.Add(res1);
GlobalArea.Log.Info($"{accountData.UserEmail}:登录成功");
GlobalArea.Login(wsid, accountData.UserEmail);
GlobalArea.Log.Info($"当前登录用户数量: {GlobalArea.LoginUserCount}");
this.ResponseOrBroadcastInstructs.Add(new Instruct
{
Type = "broadcast",
Class = "logIn",
Data = new
{
userEmail = accountData.UserEmail,
userName = accountData.UserName,
headColor = accountData.HeadColor,
userQq = accountData.UserQQ,
},
IsBroadcast = true
});
}
else
{
this.ResponseOrBroadcastInstructs.Add(res1);
}
}
} }
}); });
} }
@ -74,7 +36,7 @@ namespace OMS.NET.Instructs
{ {
public LoginStatusInstuct() public LoginStatusInstuct()
{ {
this.Type = "loginStatus"; Type = "loginStatus";
} }
} }
} }

@ -1,32 +0,0 @@
namespace OMS.NET.Instructs
{
/// <summary>
/// 用于测试和代码复制
/// </summary>
public class PingInstuct : Instruct
{
public PingInstuct()
{
this.Type = "ping";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
this.ResponseOrBroadcastInstructs.Add(new PongInstuct()
{
IsResponse = true
});
});
}
}
public class PongInstuct : Instruct
{
public PongInstuct()
{
this.Type = "pong";
}
}
}

@ -1,3 +1,8 @@
using System.Text.Json;
using OMS.NET.Common;
using OMS.NET.DbClass;
using ZstdSharp.Unsafe;
namespace OMS.NET.Instructs namespace OMS.NET.Instructs
{ {
/// <summary> /// <summary>
@ -7,7 +12,7 @@ namespace OMS.NET.Instructs
{ {
public TestInstruct() public TestInstruct()
{ {
this.Type = "test"; Type = "test";
} }
public override Task Handler(string wsid) public override Task Handler(string wsid)
@ -15,8 +20,47 @@ namespace OMS.NET.Instructs
return Task.Run(() => return Task.Run(() =>
{ {
//GlobalArea.UserConnects.Where(x => x.ID == wsid).First().UserEmail = "xxx@xx.com";//login //GlobalArea.UserConnects.Where(x => x.ID == wsid).First().UserEmail = "xxx@xx.com";//login
GlobalArea.Log.Info("当前客户端连接数:" + GlobalArea.ConnectClientsCount); // Log.Info("当前客户端连接数:" + GlobalArea.ConnectClientsCount);
GlobalArea.Log.Info("当前登录用户数:" + GlobalArea.LoginUserCount); // Log.Info("当前登录用户数:" + GlobalArea.LoginUserCount);
//测试数据表连接
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
try
{
int op = Data.GetInt32();
Map map = new()
{
Id = "map1",
Name = "test",
Description = "haksjhdkasd"
};
switch (op)
{
case 0:
map.Test();
break;
case 1:
map.Insert();
Log.Debug($"插入测试成功,新的id为{map.Id}");
break;
case 2:
Log.Debug(string.Join(',', map.ShowDetail()));
break;
case 3:
map.Description = "随便写一个有意义的字符串";
map.Update();
break;
case 4:
map.Delete();
Log.Debug($"删除测试成功");
break;
default:
throw new Exception("do nothing");
}
}
catch (Exception ex)
{
Log.Warn($"处理{Type}指令出错:" + ex.Message);
}
}); });
} }
} }

@ -1,6 +1,5 @@
using System.Net; using System.Net;
using System.Text; using OMS.NET.Common;
using System.Text.Unicode;
using OMS.NET.Instructs; using OMS.NET.Instructs;
using WebSocketSharp; using WebSocketSharp;
using WebSocketSharp.Server; using WebSocketSharp.Server;
@ -12,11 +11,11 @@ namespace OMS.NET
private IPEndPoint iPEndPoint = new(IPAddress.Any, 0); private IPEndPoint iPEndPoint = new(IPAddress.Any, 0);
protected override async void OnMessage(MessageEventArgs e) protected override async void OnMessage(MessageEventArgs e)
{ {
GlobalArea.Log.Debug(this.ID + " " + this.Context.UserEndPoint.ToString() + ":" + e.Data); Log.Debug(ID + " " + Context.UserEndPoint.ToString() + ":" + e.Data);
Instruct? instruct = Instruct.JsonStringParse(e.Data); Instruct? instruct = Instruct.JsonStringParse(e.Data);
if (instruct != null) if (instruct != null)
{ {
await instruct.HandlerAndMeasure(this.ID);//传递ws连接的id为某些需要判断ws连接状态的处理逻辑准备 await instruct.HandlerAndMeasure(ID);
if (instruct.ResponseOrBroadcastInstructs.Count > 0) if (instruct.ResponseOrBroadcastInstructs.Count > 0)
{ {
instruct.ResponseOrBroadcastInstructs.ForEach(res => instruct.ResponseOrBroadcastInstructs.ForEach(res =>
@ -25,12 +24,11 @@ namespace OMS.NET
{ {
string str = res.ToJsonString(); string str = res.ToJsonString();
Send(str); Send(str);
//GlobalArea.Log.Debug("已发送回复 " + str);
} }
if (res.IsBroadcast) if (res.IsBroadcast)
{ {
string str = res.ToJsonString(); string str = res.ToJsonString();
foreach (IWebSocketSession session in this.Sessions.Sessions) foreach (IWebSocketSession session in Sessions.Sessions)
{ {
//看起来只有登录后的连接才能收到广播,这里添加下过滤 //看起来只有登录后的连接才能收到广播,这里添加下过滤
if (GlobalArea.LoginCheckByID(session.ID)) if (GlobalArea.LoginCheckByID(session.ID))
@ -38,7 +36,6 @@ namespace OMS.NET
session.Context.WebSocket.Send(str); session.Context.WebSocket.Send(str);
} }
} }
//GlobalArea.Log.Debug("已发送广播 " + str);
} }
}); });
} }
@ -47,24 +44,24 @@ namespace OMS.NET
protected override void OnOpen() protected override void OnOpen()
{ {
this.iPEndPoint = this.Context.UserEndPoint; iPEndPoint = Context.UserEndPoint;
GlobalArea.AddUserConnect(this.ID, this.iPEndPoint); GlobalArea.AddUserConnect(ID, iPEndPoint);
Console.WriteLine(this.ID + " " + this.iPEndPoint.ToString() + " Conection Open"); Log.Info(ID + " " + iPEndPoint.ToString() + " Conection Open");
Console.WriteLine($"当前连接客户端数量: {GlobalArea.ConnectClientsCount}"); // Console.WriteLine($"当前连接客户端数量: {GlobalArea.ConnectClientsCount}");
} }
protected override void OnClose(CloseEventArgs e) protected override void OnClose(CloseEventArgs e)
{ {
GlobalArea.RemoveUserConnectByID(this.ID); GlobalArea.RemoveUserConnectByID(ID);
Console.WriteLine(this.ID + " " + this.iPEndPoint.ToString() + " Conection Close" + e.Reason); Log.Info(this.ID + " " + this.iPEndPoint.ToString() + " Conection Close" + e.Reason);
Console.WriteLine($"当前连接客户端数量: {GlobalArea.ConnectClientsCount}"); // Console.WriteLine($"当前连接客户端数量: {GlobalArea.ConnectClientsCount}");
} }
protected override void OnError(ErrorEventArgs e) protected override void OnError(ErrorEventArgs e)
{ {
GlobalArea.RemoveUserConnectByID(this.ID); GlobalArea.RemoveUserConnectByID(ID);
Console.WriteLine(this.ID + " " + this.iPEndPoint.ToString() + " Conection Error Close" + e.Message); Log.Info(this.ID + " " + this.iPEndPoint.ToString() + " Conection Error Close" + e.Message);
Console.WriteLine($"当前连接客户端数量: {GlobalArea.ConnectClientsCount}"); // Console.WriteLine($"当前连接客户端数量: {GlobalArea.ConnectClientsCount}");
} }
} }
} }

@ -19,8 +19,5 @@
<None Update="init.sql"> <None Update="init.sql">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None> </None>
<None Update="map_img.png">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup> </ItemGroup>
</Project> </Project>

@ -1,10 +1,7 @@
using WebSocketSharp.Server; using WebSocketSharp.Server;
using MySql.Data.MySqlClient; using MySql.Data.MySqlClient;
using System.Text; using OMS.NET.Common;
using System.Security.Cryptography; using OMS.NET.DbClass;
using OMS.NET.Instructs;
using System.Dynamic;
using System.Security.Cryptography.X509Certificates;
namespace OMS.NET namespace OMS.NET
{ {
@ -14,40 +11,11 @@ namespace OMS.NET
{ {
try try
{ {
GlobalArea.LoadServerConfig();//加载服务器配置 默认server.yaml MainLoop();
GlobalArea.LoadRsaPkey();//加载rsa私钥 默认.pkey
DbCheck();
//预加载一些数据以方便后面的处理
GlobalArea.BuildLayerData();
//开启ws监听
var wssv = new WebSocketServer(Convert.ToInt16(GlobalArea.ServerConfig.ListenPort), false);
//wssv.SslConfiguration.ServerCertificate = new X509Certificate2(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "server.pfx"));
wssv.AddWebSocketService<MapServer>("/");
wssv.Start();
Console.WriteLine("已开启ws监听, 端口: " + GlobalArea.ServerConfig.ListenPort);
Console.WriteLine("输入exit退出程序");
bool loopFlag = true;
while (loopFlag)
{
string input = Console.ReadLine() ?? "";
switch (input.Trim())
{
case "exit":
loopFlag = false;
break;
case "logins":
Console.WriteLine("当前登录用户 " + GlobalArea.LoginUserCount);
break;
default:
break;
}
}
wssv.Stop();
} }
catch (Exception e) catch (Exception e)
{ {
GlobalArea.Log.Error(e.Message); Log.Error(e.Message);
} }
} }
@ -63,7 +31,7 @@ namespace OMS.NET
{ {
using MySqlConnection connection = new(GlobalArea.ServerConfig.ConnectionString); using MySqlConnection connection = new(GlobalArea.ServerConfig.ConnectionString);
connection.Open(); connection.Open();
GlobalArea.Log.Info("dblock不存在连接到数据库服务进行检查"); Log.Info("dblock不存在连接到数据库服务进行检查");
//检查数据库是否存在,检查数据表是否 //检查数据库是否存在,检查数据表是否
// 检查数据库是否存在 // 检查数据库是否存在
string dbName = GlobalArea.ServerConfig.DataBaseName; string dbName = GlobalArea.ServerConfig.DataBaseName;
@ -77,7 +45,7 @@ namespace OMS.NET
string createDatabaseQuery = $"CREATE DATABASE {dbName} CHARACTER SET utf8mb4"; string createDatabaseQuery = $"CREATE DATABASE {dbName} CHARACTER SET utf8mb4";
MySqlCommand createDatabaseCmd = new(createDatabaseQuery, connection); MySqlCommand createDatabaseCmd = new(createDatabaseQuery, connection);
createDatabaseCmd.ExecuteNonQuery(); createDatabaseCmd.ExecuteNonQuery();
GlobalArea.Log.Info($"已创建数据库 {dbName}"); Log.Info($"已创建数据库 {dbName}");
} }
//创建默认数据表实现通用逻辑从init.sql读取创建相关表的sql语句,默认以分号结尾,忽略空行和换行 //创建默认数据表实现通用逻辑从init.sql读取创建相关表的sql语句,默认以分号结尾,忽略空行和换行
@ -95,15 +63,48 @@ namespace OMS.NET
{ {
MySqlCommand createDatabaseCmd = new(sql, connection); MySqlCommand createDatabaseCmd = new(sql, connection);
createDatabaseCmd.ExecuteNonQuery(); createDatabaseCmd.ExecuteNonQuery();
GlobalArea.Log.Info($"执行SQL成功 {sql}"); Log.Info($"执行SQL成功 {sql}");
}); });
} }
File.WriteAllText(dblockPath, ""); File.WriteAllText(dblockPath, "");
} }
else else
{ {
GlobalArea.Log.Info("满足预设条件,跳过数据库检查"); Log.Info("满足预设条件,跳过数据库检查");
}
}
static void MainLoop()
{
GlobalArea.LoadServerConfig();//加载服务器配置 默认server.yaml
GlobalArea.LoadRsaPkey();//加载rsa私钥 默认.pkey
DbCheck();
//开启ws监听
var wssv = new WebSocketServer(Convert.ToInt16(GlobalArea.ServerConfig.ListenPort), false);
//wssv.SslConfiguration.ServerCertificate = new X509Certificate2(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "server.pfx"));
wssv.AddWebSocketService<MapServer>("/");
wssv.Start();
Console.WriteLine("已开启ws监听, 端口: " + GlobalArea.ServerConfig.ListenPort);
Console.WriteLine("输入exit退出程序");
bool loopFlag = true;
while (loopFlag)
{
string input = Console.ReadLine() ?? "";
switch (input.Trim())
{
case "exit":
loopFlag = false;
break;
case "logins":
Console.WriteLine("当前登录用户 " + GlobalArea.LoginUserCount);
break;
default:
break;
}
} }
wssv.Stop();
} }
} }
} }

@ -1,6 +1,6 @@
# OMS.NET # OMSS.NET
OMS.NET为标准名称使用.NET 6开发语言使用C#。 OMSS.NET为标准名称使用.NET 6开发语言使用C#。
一个跨平台的OME服务端的.NET实现。 对数据库结构进行重新设计,简化服务器指令操作
## 先决条件 ## 先决条件
### 确保.NET开发环境已安装 ### 确保.NET开发环境已安装
@ -8,7 +8,7 @@ OMS.NET为标准名称使用.NET 6开发语言使用C#。
### 创建server.yaml ### 创建server.yaml
模板如下按情况修改user、pas、port 模板如下按情况修改user、pas、port
需准备默认的map_img.png
```yaml ```yaml
#连接字符串和默认监听端口 #连接字符串和默认监听端口
ConnectionString: server=localhost;port=3306;user=user;password=pas ConnectionString: server=localhost;port=3306;user=user;password=pas
@ -17,44 +17,7 @@ ListenPort: port
#匿名登录 #匿名登录
AnonymousLogin: false AnonymousLogin: false
#服务器基础信息 ServerConfigMaxUser: 20
#ServerConfigImg: ./map_img.png
#ServerConfigKey: k0
#ServerConfigUrl: ws://0.0.0.0:1080
#ServerConfigName: 地图名称
#ServerConfigMaxUser: 20
#以下四个常量规定了地图在什么区域内进行绘制
#ServerConfigMaxHeight: 10000
#ServerConfigMinHeight: -10000
#ServerConfigMaxWidth: 10000
#ServerConfigMinWidth: -10000
#以下两个常量决定了区域内横轴和纵轴的最小层级下layer0每像素移动量单位
#ServerConfigUnit1Y: 1
#ServerConfigUnit1X: 1
#打开地图时的默认中心点
#ServerConfigP0X: 0
#ServerConfigP0Y: 0
#层级为地图数据的缩放层级,可限制用户在高层级编辑地图导致严重误差
#ServerConfigMaxLayer: 5
#ServerConfigMinLayer: 0
#ServerConfigDefaultLayer: 0
#ServerConfigZoomAdd: 1
#底图配置
#缩放比为带有底图瓦图服务器的地图服务,可限制用户对底图缩放
#ServerConfigEnableBase: false
#ServerConfigDefaultX: 0
#ServerConfigDefaultY: 0
#ServerConfigResolutionX: 1920
#ServerConfigResolutionY: 980
#ServerConfigMaxZoom: 0
#ServerConfigMinZoom: 0
#ServerConfigDefaultZoom: 0
#ServerConfigBaseMapUrl: empty
``` ```

@ -1,40 +1,6 @@
CREATE TABLE IF NOT EXISTS map_0_data ( CREATE TABLE IF NOT EXISTS map_data (
id BIGINT(20) NOT NULL AUTO_INCREMENT, id VARCHAR(255) NOT NULL,
type VARCHAR(12) NOT NULL, name VARCHAR(255) NOT NULL,
points MEDIUMTEXT NOT NULL, description VARCHAR(255) NOT NULL,
point VARCHAR(255) NOT NULL,
color VARCHAR(255),
phase INT(1) NOT NULL,
width INT(11),
child_relations MEDIUMTEXT,
father_relations VARCHAR(255),
child_nodes MEDIUMTEXT,
father_node VARCHAR(255),
details MEDIUMTEXT,
custom MEDIUMTEXT,
PRIMARY KEY (id) PRIMARY KEY (id)
); );
CREATE TABLE IF NOT EXISTS map_0_layer (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
type VARCHAR(255) NOT NULL,
members MEDIUMTEXT NOT NULL,
structure MEDIUMTEXT NOT NULL,
phase INT(1) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS account_data (
user_email VARCHAR(255) NOT NULL,
user_name VARCHAR(255) NOT NULL,
pass_word VARCHAR(255) NOT NULL,
map_layer INT(11),
default_a1 VARCHAR(255),
save_point MEDIUMTEXT,
user_qq VARCHAR(255),
head_color VARCHAR(6),
mode INT(1) NOT NULL,
phase INT(1) NOT NULL,
custom MEDIUMTEXT,
PRIMARY KEY (user_email)
);
Loading…
Cancel
Save