Compare commits

..

18 Commits
master ... dev

@ -12,14 +12,39 @@ namespace OMS.NET.Common
public class ActiveDataElement
{
public static readonly JsonSerializerOptions options = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // 属性名为小写
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, // 忽略 null 值,
WriteIndented = true, // 美化输出
Converters = { new ActiveDataElementConverter() }
};
public string EID { get; set; }
public UserInfo? Pick { get; set; }
public UserInfo? Select { get; set; }
public ActiveDataElement(string id)
public ActiveDataElement(long id)
{
EID = "E" + id;
}
public string ToJsonString()
{
return JsonSerializer.Serialize(this, options);
}
public static ActiveDataElement? JsonParse(string json)
{
try
{
return JsonSerializer.Deserialize<ActiveDataElement>(json, options);
}
catch (Exception ex)
{
GlobalArea.Log.Error(ex.Message);
return null;
}
}
}
public class ActiveDataElementConverter : JsonConverter<ActiveDataElement>
@ -32,7 +57,7 @@ namespace OMS.NET.Common
}
reader.Read();
string? eid = (reader.GetString()?[1..]) ?? throw new JsonException(); // Removing 'E' prefix to get the ID
var element = new ActiveDataElement(eid);
var element = new ActiveDataElement(Convert.ToInt64(eid));
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject)

@ -0,0 +1,31 @@
using System.Text.Json;
using System.Text.Json.Nodes;
namespace OMS.NET.Common
{
public static class Extensions
{
public static int FindElementIndex(this JsonArray jsonArray, long elementToFind)
{
for (int i = 0; i < jsonArray.Count; i++)
{
JsonNode node = jsonArray.ElementAt(i)!;
if (node.GetValueKind() == JsonValueKind.Number &&
node.GetValue<long>() == elementToFind)
{
return i;
}
}
return -1; // 未找到目标元素,返回 -1
}
public static void RemoveAll(this JsonArray jsonArray, Func<JsonNode?, bool> predicate)
{
var itemsToRemove = jsonArray.Where(predicate).ToList();
foreach (var item in itemsToRemove)
{
jsonArray.Remove(item);
}
}
}
}

@ -13,6 +13,13 @@ namespace OMS.NET.Common
public JsonNode? Members { get; set; }
public JsonNode? Structure { get; set; }
public int Phase { get; set; } = 1;
public string? Name
{
get
{
return Structure?.AsArray().ElementAt(0)?.GetValue<string>();
}
}
public LayerData(long layerId, string type)
{
@ -30,33 +37,156 @@ namespace OMS.NET.Common
Phase = layer.Phase;
}
public void AppendElement(long itemId, string ItemType)
public void AppendElement(long elementId, string elementType)
{
if (this.Type == "order")
if (Type == "order")
{
GlobalArea.Log.Error($"order图层不能添加{ItemType}元素");
GlobalArea.Log.Error($"order图层不能添加{elementType}元素");
return;
}
if (this.Members![itemId.ToString()] == null)
if (Members![elementId.ToString()] == null)
{
Members![elementId.ToString()] = elementType switch {
"point" => 1,
"line" => 2,
"area" => 3,
"curve" => 4,
_ => throw new Exception("图层添加:不支持的元素类型"),
};
Structure!.AsArray().Add(elementId);
HasChange = true;
UpdateToDb();
}
}
public void DeleteElement(long elementId)
{
if (Type == "order")
{
GlobalArea.Log.Error($"order图层不能移除Element元素");
return;
}
Members!.AsObject().Remove(elementId.ToString());
//移除structure中的值
int index = Structure!.AsArray().FindElementIndex(elementId);
if (index != -1)
{
Structure!.AsArray().RemoveAt(index);
}
UpdateToDb();
}
public void UpdateToDb()
{
this.Members![itemId.ToString()] = ItemType;
this.Structure!.AsArray().Add(itemId);
this.HasChange = true;
//上传图层到数据库
MapLayer mapLayer = ConvertToMapLayer();
MapLayer.Update(mapLayer);
}
public void AdjustABOrder(long a, long b, string method)
{
JsonArray arr = Structure!.AsArray();
int indexA = arr.FindElementIndex(a);
int indexB = arr.FindElementIndex(b);
switch (method)
{
case "up":
{
if (indexA > indexB)
{
arr.RemoveAt(indexA);
arr.Insert(indexB, a);
HasChange = true;
UpdateToDb();
}
break;
}
case "down":
{
if (indexA < indexB)
{
arr.RemoveAt(indexA);
indexB = arr.FindElementIndex(b);
arr.Insert(indexB + 1, a);
HasChange = true;
UpdateToDb();
}
break;
}
case "join"://donothing
break;
default:
throw new Exception($"LayerData.AdjustABOrder不支持的method类型:{method}");
}
}
public void AdjustOrderLayer(long layerAId, long layerBId, string type)
{
if (Type == "order")
{
JsonArray array = Members!.AsArray();
int indexA = array.FindElementIndex(layerAId);
int indexB = array.FindElementIndex(layerBId);
if (type == "up")
{
array.RemoveAt(indexA);
array.Insert(indexB, layerAId);
}
if (type == "down")
{
array.RemoveAt(indexA);
indexB = array.FindElementIndex(layerBId);
array.Insert(indexB + 1, layerAId);
}
UpdateToDb();
}
}
public void OrderAddGroupLayer(long layerId)
{
if (Type == "order")
{
Members?.AsArray().Add(layerId);
UpdateToDb();
}
}
public void OrderDeleteGroupLayer(long layerId)
{
if (Type == "order")
{
int index = Members!.AsArray().FindElementIndex(layerId);
Members!.AsArray().RemoveAt(index);
UpdateToDb();
}
}
public void Reset()
{
if (Type == "group")
{
Members = new JsonObject();
Members.AsObject()["0"] = 0;
int Count = Structure!.AsArray().Count;
for (int i = Count - 1; i <= 1; i--)
{
Structure!.AsArray().RemoveAt(i);
}
UpdateToDb();
}
}
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
Id = LayerId,
Type = Type,
Members = (Type == "order") ? Members!.ToString() : Util.JsonToBase64(Members!.ToString()),
Structure = (Structure == null) ? "" : Util.JsonToBase64(Structure!.ToString()),
Phase = Phase
};
}
}

@ -11,7 +11,7 @@ namespace OMS.NET.Common
{
lock (LogLock)
{
using var writer = new StreamWriter(this.logPath, true);
using var writer = new StreamWriter(logPath, true);
writer.WriteLine(message);
}
}
@ -19,12 +19,12 @@ namespace OMS.NET.Common
public Logger(int level)
{
_logLevel = level;
this.logPath = GetNewLogFile();
logPath = GetNewLogFile();
}
private string GetNewLogFile()
{
this.logCount = 0;
logCount = 0;
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")))
{
@ -36,7 +36,7 @@ namespace OMS.NET.Common
private void Log(string message, int level)
{
if (level <= this._logLevel)
if (level <= _logLevel)
{
string logtime = DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss]");
string leveltext = level switch
@ -51,7 +51,7 @@ namespace OMS.NET.Common
Console.WriteLine(logtext);
if (logCount > 100000)
{
this.logPath = GetNewLogFile();
logPath = GetNewLogFile();
}
//File.AppendAllTextAsync(this.logPath, logtext);
WriteLog(logtext);

@ -242,6 +242,14 @@ namespace OMS.NET.Common
? value
: "";
/// <summary>
/// 底图的默认类型
/// default empty
/// </summary>
public string ServerConfigBaseMapType => _config.TryGetValue("ServerConfigBaseMapType", out string? value)
? value
: "realistic";
public ServerConfig()
{
//do nothing,everything default

@ -67,5 +67,71 @@ namespace OMS.NET.Common
{
return JsonSerializer.Deserialize<Point>(json, options) ?? throw new Exception("转化point类型失败:" + json);
}
//==================================================================================
/// <summary>
/// 麻烦的键值操作
/// </summary>
public static void DetailsTransform(JsonArray details, JsonArray detailsRule)
{
var originalKeys = details.Select(d => d!["key"]?.GetValue<string>())
.Where(k => k != null).ToList();
//好像可以直接拷贝一个新的detail模板然后继承原有属性即可顺序可直接继承模板不用再调整
JsonArray newDetails = new();
foreach (var rule in detailsRule)
{
var key = rule!["name"]?.GetValue<string>()!;
var value = rule["default"];
JsonValueKind newType = rule["default"]!.GetValueKind();
if (originalKeys.Contains(key))
{
int index = originalKeys.IndexOf(key);
JsonValueKind oldType = details.ElementAt(index)!["value"]!.GetValueKind();
//如果模板类型会有变化原设计中对应的value需要调整下格式
//这里直接放弃旧值,转化来转化去,太麻烦且没必要
if (oldType == newType)
{
value = details.ElementAt(index)!["value"];
}
}
var newDetail = new JsonObject
{
["key"] = key,
["value"] = value
};
newDetails.Add(newDetail);
}
details = newDetails;
}
/// <summary>
/// 生成 100000 到 999999 之间的随机整数
/// </summary>
public static int GetRandomNumber6()
{
Random random = new();
int minValue = 100000;
int maxValue = 999999;
return random.Next(minValue, maxValue + 1);
}
/// <summary>
/// 创建模板id
/// </summary>
public static string CreateTemplateId()
{
// 定义有效字符集
const string validChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random random = new();
int length = random.Next(8, 15);
string result = "";
for (int i = 0; i < length; i++)
{
int byteValue = random.Next(0, 256);
result += validChars[byteValue % validChars.Length];
}
return result;
}
}
}

@ -19,11 +19,11 @@ namespace OMS.NET.DbClass
public AccountData()
{
this.UserEmail = "";
this.UserName = "";
this.Password = "";
this.Mode = 1;
this.Phase = 1;
UserEmail = "";
UserName = "";
Password = "";
Mode = 1;
Phase = 1;
//this.Custom = "";
}
#endregion

@ -13,7 +13,7 @@ namespace OMS.NET.DbClass
public int Phase { get; set; }
public int? Width { get; set; }
public string? ChildRelations { get; set; }
public string? FatherRelations { get; set; }
public string? FatherRelation { get; set; }
public string? ChildNodes { get; set; }
public string? FatherNode { get; set; }
public string? Details { get; set; }
@ -21,11 +21,11 @@ namespace OMS.NET.DbClass
public MapData()
{
this.Id = -1;
this.Type = "";
this.Points = "";
this.Point = "";
this.Phase = 1;
Id = -1;
Type = "";
Points = "";
Point = "";
Phase = 1;
}
#endregion
@ -33,8 +33,8 @@ namespace OMS.NET.DbClass
{
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)";
var query = @"INSERT INTO map_0_data (type, points, point, color, phase, width, child_relations, father_relation, child_nodes, father_node, details, custom)
VALUES (@Type, @Points, @Point, @Color, @Phase, @Width, @ChildRelations, @FatherRelation, @ChildNodes, @FatherNode, @Details, @Custom)";
using MySqlCommand command = new(query, connection);
command.Parameters.AddWithValue("@Type", mapData.Type);
command.Parameters.AddWithValue("@Points", mapData.Points);
@ -43,7 +43,7 @@ namespace OMS.NET.DbClass
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("@FatherRelation", mapData.FatherRelation ?? (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);
@ -57,7 +57,7 @@ namespace OMS.NET.DbClass
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,
child_relations = @ChildRelations, father_relation = @FatherRelation, 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);
@ -68,7 +68,7 @@ namespace OMS.NET.DbClass
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("@FatherRelation", mapData.FatherRelation ?? (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);
@ -90,7 +90,7 @@ namespace OMS.NET.DbClass
{
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
var query = @"SELECT id, type, points, point, color, phase, width, child_relations, father_relation, child_nodes, father_node, details, custom
FROM map_0_data WHERE id = @Id";
using MySqlCommand command = new(query, connection);
command.Parameters.AddWithValue("@Id", id);
@ -107,7 +107,7 @@ namespace OMS.NET.DbClass
Phase = reader.GetInt32("phase"),
Width = reader["width"] as int?,
ChildRelations = reader["child_relations"] as string,
FatherRelations = reader["father_relations"] as string,
FatherRelation = reader["father_relation"] as string,
ChildNodes = reader["child_nodes"] as string,
FatherNode = reader["father_node"] as string,
Details = reader["details"] as string,
@ -139,7 +139,7 @@ namespace OMS.NET.DbClass
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"),
FatherRelation = reader.IsDBNull(reader.GetOrdinal("father_relation")) ? null : reader.GetString("father_relation"),
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"),

@ -13,11 +13,11 @@ namespace OMS.NET.DbClass
public MapLayer()
{
this.Id = 0;
this.Type = "";
this.Members = "";
this.Structure = "";
this.Phase = 1;
Id = 0;
Type = "";
Members = "";
Structure = "";
Phase = 1;
}
public MapLayer(long id, string type, string members, string structure, int phase)
{

@ -2,8 +2,11 @@ using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using K4os.Compression.LZ4.Internal;
using OMS.NET.Common;
using OMS.NET.DbClass;
using OMS.NET.Instructs;
namespace OMS.NET
{
@ -287,9 +290,59 @@ namespace OMS.NET
}
}
private static readonly List<LayerData> _LayerDataList = new();
private static List<LayerData> _LayerDataList = new();
private static readonly object _LayerDataListLock = new();
private static readonly List<ActiveDataElement> _ActiveDataList = new();
private static readonly object _ActiveDataListLock = new();
public static List<ActiveDataElement> GetActiveDataList
{
get
{
lock (_ActiveDataListLock)
{
return _ActiveDataList.Where(x => x.Pick != null || x.Select != null).ToList();
}
}
}
public static bool IsElementExit(long elementId)
{
lock (_ActiveDataListLock)
{
ActiveDataElement? ad = _ActiveDataList.Find(u => u.EID == ("E" + elementId));
return ad != null;
}
}
public static ActiveDataElement? GetActiveDataElement(long elementId)
{
lock (_ActiveDataListLock)
{
return _ActiveDataList.Find(u => u.EID == ("E" + elementId));
}
}
public static void AddActiveDataElement(ActiveDataElement activeDataElement)
{
lock (_ActiveDataListLock)
{
_ActiveDataList.Add(activeDataElement);
}
}
/// <summary>
/// 移除活动数据,调用前必需确保对象已存在
/// </summary>
public static void RemoveActiveDataElement(long elementId)
{
lock (_ActiveDataListLock)
{
_ActiveDataList.Remove(GetActiveDataElement(elementId)!);
}
}
/// <summary>
/// 从数据库中构建layerid 和 templateid的对应关系
/// </summary>
@ -298,7 +351,7 @@ namespace OMS.NET
List<MapLayer> mapLayer = MapLayer.GetMapLayerList();
lock (_LayerDataListLock)
{
foreach (MapLayer layer in mapLayer)
foreach (MapLayer layer in mapLayer.Where(x => x.Phase == 1))
{
LayerData layerData = new(null, layer);
if (layerData.Type != "order")
@ -327,12 +380,189 @@ namespace OMS.NET
}
}
}
public static LayerData? GetLayerDataByLayerId(long layerId)
{
lock (_LayerDataListLock)
{
try
{
return _LayerDataList.Where(x => x.LayerId == layerId).First();
}
catch
{
Log.Warn("通过图层id未获取到图层数据");
return null;
}
}
}
public static LayerData GetOrderLayerData()
{
lock (_LayerDataListLock)
{
return _LayerDataList.Where(x => x.Type == "order").First()!;
}
}
/// <summary>
/// 移除已经标记删除的图层模板映射
/// </summary>
public static void RemoveDeletedLayerData()
{
lock (_LayerDataListLock)
{
_LayerDataList = _LayerDataList.Where(x => x.Phase == 1).ToList();
}
}
public static dynamic AdjustElementOrder(long elementAId, long elementBId, string templateA, string templateB, string method)
{
lock (_LayerDataListLock)
{
dynamic result = new object();
List<LayerData> layers = new();
result.layers = layers;
LayerData layerA = GetLayerDataByTemplateId(templateA)!;
LayerData layerB = GetLayerDataByTemplateId(templateB)!;
if (layerA.LayerId == layerB.LayerId)
{
layerA.AdjustABOrder(elementAId, elementBId, method);
layers.Add(layerA);
}
else
{
MapData mapDataA = MapData.Get(elementAId)!;
JsonNode bTemplateData = layerB.Structure!.AsArray().ElementAt(1)!["template"]!;
if (bTemplateData["typeRule"]![mapDataA.Type]!.GetValue<bool>() == true)
{
JsonArray aDetail = JsonObject.Parse(Util.Base64ToJson(mapDataA.Details!))!.AsArray();
JsonNode aCustom = JsonObject.Parse(Util.Base64ToJson(mapDataA.Custom!))!;
Util.DetailsTransform(aDetail, bTemplateData.AsArray());
aCustom["tmpId"] = templateB;
mapDataA.Details = Util.JsonToBase64(aDetail.ToString());
mapDataA.Custom = Util.JsonToBase64(aCustom.ToString());
if (MapData.Update(mapDataA) == -1) throw new Exception("数据库修改失败");
result.element = mapDataA;
}
layerA.DeleteElement(elementAId);
layerB.AppendElement(elementAId, mapDataA.Type);
layerB.AdjustABOrder(elementAId, elementBId, method);//丢在一起,再调整顺序
layers.Add(layerA);
layers.Add(layerB);
}
return result;
}
}
public static LayerData CreateGroupLayer(string creator)
{
lock (_LayerDataListLock)
{
//int max = _LayerDataList.Count;
LayerData layer = new(-1, "group")
{
Members = new JsonObject(),
TemplateId = CreateGroupLayerTemplateId()
};
layer.Members.AsObject()["0"] = 0;
string time = GetCurrentTime();
layer.Structure = new JsonArray();
layer.Structure.AsArray().Add(CreateGroupLayerName());
layer.Structure.AsArray().Add(new
{
template = new
{
id = layer.TemplateId,
name = "template",
creator = creator,
modify = time,
locked = false,
explain = "none",
typeRule = new
{
point = true,
line = true,
area = true,
curve = true
},
detailsRule = new List<object>
{
new {
set = false,
name = "name",
@default = "default",
type = "text"
}
},
colorRule = new
{
basis = "",
type = "",
condition = new List<object>()
},
widthRule = new
{
basis = "",
type = "",
condition = new List<object>()
}
}
});
MapLayer mapLayer = layer.ConvertToMapLayer();
MapLayer.Add(mapLayer);
if (mapLayer.Id != -1)
{
LayerData order = GetOrderLayerData();
order.OrderAddGroupLayer(mapLayer.Id);
layer.HasChange = true;
layer.LayerId = mapLayer.Id;
_LayerDataList.Add(layer);
}
return layer;
}
}
private static string CreateGroupLayerName()
{
lock (_LayerDataListLock)
{
string name = "layer " + Util.GetRandomNumber6();
while (_LayerDataList.Any(x => x.Name == name))
{
name = "layer " + Util.GetRandomNumber6();
}
return name;
}
}
public static bool IsLayerNameRepeat(string name)
{
lock (_LayerDataListLock)
{
return _LayerDataList.Any(x => x.Name == name);
}
}
private static string CreateGroupLayerTemplateId()
{
lock (_LayerDataListLock)
{
string tmpId = Util.CreateTemplateId();
while (_LayerDataList.Any(x => x.TemplateId == tmpId))
{
tmpId = Util.CreateTemplateId();
}
return tmpId;
}
}
#endregion
/// <summary>
/// 默认loglevel为3发布版本需要改成2
/// </summary>
private static Logger _Logger = new(3);
private static readonly Logger _Logger = new(3);
private static readonly object _LoggerLock = new();
public static Logger Log

@ -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,
},
});
}
}
}
});
}
}
}

@ -0,0 +1,131 @@
using System.Text;
using System.Text.Json;
using OMS.NET.Common;
using OMS.NET.DbClass;
namespace OMS.NET.Instructs
{
public class AddElementInstruct : Instruct
{
public AddElementInstruct()
{
Type = "broadcast";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查,不通过则直接退出
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
try
{
char[] charsToTrim = { '"' };
long id = Data.GetProperty("id").GetInt64();
string type = Data.GetProperty("type").GetRawText().Trim(charsToTrim);
string points = Data.GetProperty("points").GetRawText();
string point = Data.GetProperty("point").GetRawText().Trim(charsToTrim);
string? color = Data.GetProperty("color").GetRawText().Trim(charsToTrim);
int? width = Data.GetProperty("width").GetInt32();
// string? childRelations = Data.GetProperty("childRelations").GetString();
// string? fatherRelation = Data.GetProperty("fatherRelation").GetString();
// string? childNodes = Data.GetProperty("childNodes").GetString();
// string? fatherNode = Data.GetProperty("fatherNode").GetString();
string? details = Data.GetProperty("details").GetRawText().Trim(charsToTrim);
string? custom = Data.GetProperty("custom").GetRawText().Trim(charsToTrim);
//validations todo
//假设所有数据均合法
MapData mapData = new()
{
Type = type,
Points = Util.JsonToBase64(points),
Point = Util.JsonToBase64(point),
Color = color,
Width = width,
// ChildRelations = childRelations,
// FatherRelation = fatherRelation,
// 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 Instruct()
{
IsBroadcast = true,
Type = "broadcast",
Class = Class,
Conveyor = conveyor,
Time = time,
Data = mapData,
});
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsBroadcast = true,
Type = "broadcast",
Class = "updateLayerData",
Conveyor = conveyor,
Time = time,
Data = new
{
id = layer.LayerId,
members = layer.Members!.ToString(),
structure = layer.Structure!.ToString(),
}
});
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsResponse = true,
Type = "send_correct",
Class = "upload",
Conveyor = conveyor,
Time = time,
Data = new
{
vid = id,
rid = mapData.Id
}
});
}
}
else
{
throw new Exception("未找到 tmpId");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsResponse = true,
Type = "send_error",
Class = "upload",
Conveyor = GlobalArea.GetLoginEmailByID(wsid),
Time = GlobalArea.GetCurrentTime(),
Data = new
{
source = Data,
message = ex.Message
}
});
}
});
}
}
}

@ -0,0 +1,75 @@
using System.Text.Json;
using OMS.NET.Common;
using OMS.NET.DbClass;
namespace OMS.NET.Instructs
{
public class AdjustElementOrderInstuct : Instruct
{
public AdjustElementOrderInstuct()
{
Type = "broadcast";
Class = "adjustElementOrder";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查不通过则直接退出
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
string conveyor = GlobalArea.GetLoginEmailByID(wsid);
try
{
long elementA = Data.GetProperty("elementA").GetInt64();
long elementB = Data.GetProperty("elementB").GetInt64();
string templateA = Data.GetProperty("templateA").GetString();
string templateB = Data.GetProperty("templateB").GetString();
string method = Data.GetProperty("method").GetString();
dynamic result = GlobalArea.AdjustElementOrder(elementA, elementB, templateA, templateB, method);
List<dynamic> list = new();
foreach (LayerData layerData in result.layers)
{
list.Add(new
{
id = layerData.LayerId,
members = layerData.Members,
structure = layerData.Structure,
});
}
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsBroadcast = true,
Type = "broadcast",
Class = "batchUpdateLayerData",
Conveyor = conveyor,
Time = GlobalArea.GetCurrentTime(),
Data = list
});
if (result.element != null && result.element.GetType() != typeof(MapData))
{
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsBroadcast = true,
Type = "broadcast",
Class = "updateElement",
Conveyor = conveyor,
Time = GlobalArea.GetCurrentTime(),
Data = new
{
id = result.element.ID,
type = result.element.Type,
details = result.element.Details,
custom = result.element.Custom
}
});
}
}
catch (Exception ex)
{
GlobalArea.Log.Warn($"处理{Class}广播指令出错:" + ex.Message);
}
});
}
}
}

@ -0,0 +1,32 @@
using System.Text.Json;
namespace OMS.NET.Instructs
{
public class BatchDeleteElementInstruct : Instruct
{
public BatchDeleteElementInstruct()
{
Type = "broadcast";
Class = "batchDeleteElement";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查不通过则直接退出
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
try
{
//string conveyor = GlobalArea.GetLoginEmailByID(wsid);
//string time = GlobalArea.GetCurrentTime();
throw new NotImplementedException("这个也不想搞了");
}
catch (Exception ex)
{
GlobalArea.Log.Warn($"处理{Class}广播指令出错:" + 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";
}
}
}

@ -0,0 +1,56 @@
using System.Text.Json;
using OMS.NET.Common;
using OMS.NET.DbClass;
namespace OMS.NET.Instructs
{
public class CreateGroupLayerInstruct : Instruct
{
public CreateGroupLayerInstruct()
{
Type = "broadcast";
Class = "createGroupLayer";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查不通过则直接退出
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
try
{
string conveyor = GlobalArea.GetLoginEmailByID(wsid);
AccountData accountData = GlobalArea.GetLoginAccountData(conveyor)!;
string creator = $"{accountData.UserName}({conveyor})";
LayerData newGroupLayer = GlobalArea.CreateGroupLayer(creator);
string time = GlobalArea.GetCurrentTime();
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsBroadcast = true,
Type = "broadcast",
Class = "createGroupLayer",
Conveyor = conveyor,
Time = time,
Data = newGroupLayer
});
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsBroadcast = true,
Type = "broadcast",
Class = "updateLayerOrder",
Conveyor = conveyor,
Time = time,
Data = new{
member = GlobalArea.GetOrderLayerData().Members
}
});
}
catch (Exception ex)
{
GlobalArea.Log.Warn($"处理{Class}广播指令出错:" + ex.Message);
}
});
}
}
}

@ -0,0 +1,110 @@
using System.Text.Json;
using OMS.NET.Common;
using OMS.NET.DbClass;
namespace OMS.NET.Instructs
{
public class DeleteElementInstruct : Instruct
{
public DeleteElementInstruct()
{
Type = "broadcast";
Class = "deleteElement";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查不通过则直接退出
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
string conveyor = GlobalArea.GetLoginEmailByID(wsid);
try
{
//解析id和tmpId
long id = Data.GetProperty("id").GetInt64();
string tmpId = Data.GetProperty("tmpId").GetString();
//需要先实现activeData相关
MapData mapData = MapData.Get(id) ?? throw new Exception($"Element{id}不存在");
mapData.Phase = 2;
int row = MapData.Update(mapData);
if (row == -1) throw new Exception("数据库修改失败");
if (GlobalArea.IsElementExit(id))
{
GlobalArea.RemoveActiveDataElement(id);
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsBroadcast = true,
Type = "broadcast",
Class = "pickSelectEndElements",
Conveyor = conveyor,
Time = GlobalArea.GetCurrentTime(),
Data = new
{
id = id
}
});
}
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsResponse = true,
Type = "send_correct",
Class = "delete",
Conveyor = conveyor,
Time = GlobalArea.GetCurrentTime(),
Data = new
{
rid = id
}
});
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsBroadcast = true,
Type = "broadcast",
Class = "deleteElement",
Conveyor = conveyor,
Time = GlobalArea.GetCurrentTime(),
Data = new
{
id = id
}
});
LayerData layer = GlobalArea.GetLayerDataByTemplateId(tmpId)!;
layer.DeleteElement(id);
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsBroadcast = true,
Type = "broadcast",
Class = "updateLayerData",
Conveyor = conveyor,
Time = GlobalArea.GetCurrentTime(),
Data = new
{
id = layer.LayerId,
members = layer.Members!.ToString(),
structure = layer.Structure!.ToString(),
}
});
}
catch (Exception ex)
{
GlobalArea.Log.Warn($"处理{Class}广播指令出错:" + ex.Message);
//ResponseOrBroadcastInstructs.Clear();
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsResponse = true,
Type = "send_error",
Class = "delete",
Conveyor = conveyor,
Time = GlobalArea.GetCurrentTime(),
Data = new
{
source = Data,
message = ex.Message
}
});
}
});
}
}
}

@ -0,0 +1,68 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using OMS.NET.Common;
using OMS.NET.DbClass;
namespace OMS.NET.Instructs
{
public class DeleteLayerAndMembersInstuct : Instruct
{
public DeleteLayerAndMembersInstuct()
{
Type = "broadcast";
Class = "deleteLayerAndMembers";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查不通过则直接退出
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
try
{
long id = Data.GetProperty("id").GetInt64();
LayerData layer = GlobalArea.GetLayerDataByLayerId(id)!;
if (layer.Type == "order") throw new Exception("Order Layer不能删");
layer.Phase = 2;
layer.Reset();//本身移除member和structure内的elementId引用然后更新到数据库
layer.HasChange = true;
LayerData order = GlobalArea.GetOrderLayerData();
order.OrderDeleteGroupLayer(id);
GlobalArea.RemoveDeletedLayerData();//更新图层模板映射
string conveyor = GlobalArea.GetLoginEmailByID(wsid);
string time = GlobalArea.GetCurrentTime();
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsBroadcast = true,
Type = "broadcast",
Class = "updateLayerOrder",
Conveyor = conveyor,
Time = time,
Data = new
{
member = order.Members
}
});
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsBroadcast = true,
Type = "broadcast",
Class = "deleteLayerAndMembers",
Conveyor = conveyor,
Time = time,
Data = new
{
id = id,
member = layer.Members
}
});
}
catch (Exception ex)
{
GlobalArea.Log.Warn($"处理{Class}广播指令出错:" + ex.Message);
}
});
}
}
}

@ -0,0 +1,31 @@
using System.Text.Json;
namespace OMS.NET.Instructs
{
public class ForceUpdateDataInstruct : Instruct
{
public ForceUpdateDataInstruct()
{
Type = "broadcast";
Class = "forceUpdate";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查不通过则直接退出
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
try
{
//string conveyor = GlobalArea.GetLoginEmailByID(wsid);
string time = GlobalArea.GetCurrentTime();
}
catch (Exception ex)
{
GlobalArea.Log.Warn($"处理{Class}广播指令出错:" + ex.Message);
}
});
}
}
}

@ -0,0 +1,24 @@
namespace OMS.NET.Instructs
{
public class GetActiveDataInstruct : Instruct
{
public GetActiveDataInstruct()
{
Type = "get_activeData";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查,不通过则直接退出
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsResponse = true,
Type = "send_activeData",
Data = GlobalArea.GetActiveDataList
});
});
}
}
}

@ -6,31 +6,22 @@ namespace OMS.NET.Instructs
{
public GetMapDataInstruct()
{
this.Type = "get_mapData";
Type = "get_mapData";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (GlobalArea.LoginCheckByID(wsid))
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查,不通过则直接退出
List<MapData> mapDatas = MapData.GetMapDataList().Where(m => m.Phase != 2).ToList();
this.ResponseOrBroadcastInstructs.Add(new SendMapDataInstruct()
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsResponse = true,
Type = "send_mapData",
Data = mapDatas
});
}
});
}
}
public class SendMapDataInstruct : Instruct
{
public SendMapDataInstruct()
{
this.Type = "send_mapData";
}
}
}

@ -6,31 +6,22 @@ namespace OMS.NET.Instructs
{
public GetMapLayerInstruct()
{
this.Type = "get_mapLayer";
Type = "get_mapLayer";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (GlobalArea.LoginCheckByID(wsid))
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查,不通过则直接退出
List<MapLayer> mapLayers = MapLayer.GetMapLayerList().Where(m => m.Phase != 2).ToList();
this.ResponseOrBroadcastInstructs.Add(new SendMapLayerInstruct()
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsResponse = true,
Type = "send_mapLayer",
Data = mapLayers
});
}
});
}
}
public class SendMapLayerInstruct : Instruct
{
public SendMapLayerInstruct()
{
this.Type = "send_mapLayer";
}
}
}

@ -6,15 +6,14 @@ namespace OMS.NET.Instructs
{
public GetPresenceInstruct()
{
this.Type = "get_presence";
Type = "get_presence";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (GlobalArea.LoginCheckByID(wsid))
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查,不通过则直接退出
//获取所有在线用户,移除重复
List<string?> emails = GlobalArea.UserConnects.Where(u => u.UserEmail != null)
.Select(u => u.UserEmail).Distinct().ToList();
@ -31,22 +30,13 @@ namespace OMS.NET.Instructs
headColor = accountData.HeadColor,
});
});
this.ResponseOrBroadcastInstructs.Add(new SendPresenceInstruct()
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsResponse = true,
Type = "send_presence",
Data = allLoginUsers,
});
}
});
}
}
public class SendPresenceInstruct : Instruct
{
public SendPresenceInstruct()
{
this.Type = "send_presence";
}
}
}

@ -4,29 +4,21 @@ namespace OMS.NET.Instructs
{
public GetPublickeyInstruct()
{
this.Type = "get_publickey";
Type = "get_publickey";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
this.ResponseOrBroadcastInstructs.Add(new PublickeyInstruct()
ResponseOrBroadcastInstructs.Add(new Instruct()
{
Data = GlobalArea.GetRsaPublickKey(),
IsResponse = true
IsResponse = true,
Type = "publickey",
Data = GlobalArea.GetRsaPublickKey()
});
//Thread.Sleep(9000);//模拟耗时操作
});
}
}
public class PublickeyInstruct : Instruct
{
public PublickeyInstruct()
{
this.Type = "publickey";
}
}
}

@ -4,16 +4,17 @@ namespace OMS.NET.Instructs
{
public GetServerConfigInstruct()
{
this.Type = "get_serverConfig";
Type = "get_serverConfig";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
this.ResponseOrBroadcastInstructs.Add(new SendServerConfigInstruct
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsResponse = true,
Type = "send_serverConfig",
Data = new
{
anonymous_login = bool.TryParse(GlobalArea.ServerConfig.AnonymousLogin, out bool booleanValue) && booleanValue,
@ -30,18 +31,11 @@ namespace OMS.NET.Instructs
max_zoom = GlobalArea.ServerConfig.MaxZoom,
min_zoom = GlobalArea.ServerConfig.MinZoom,
default_zoom = GlobalArea.ServerConfig.DefaultZoom,
base_map_url = GlobalArea.ServerConfig.BaseMapUrl
base_map_url = GlobalArea.ServerConfig.BaseMapUrl,
base_map_type = GlobalArea.ServerConfig.ServerConfigBaseMapType
}
});
});
}
}
public class SendServerConfigInstruct : Instruct
{
public SendServerConfigInstruct()
{
this.Type = "send_serverConfig";
}
}
}

@ -1,4 +1,5 @@
using System.Globalization;
using System.Text.Json;
using WebSocketSharp;
namespace OMS.NET.Instructs
@ -7,33 +8,37 @@ namespace OMS.NET.Instructs
{
public GetServerImgInstruct()
{
this.Type = "get_serverImg";
Type = "get_serverImg";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (this.Time != null)
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
try
{
string time = Data.GetProperty("time").GetString();
if (time != null)
{
//时间解析
string format = "yyyy-MM-dd HH:mm:ss";
DateTime clientDateTime = DateTime.ParseExact(this.Time, format, CultureInfo.InvariantCulture);
DateTime clientDateTime = DateTime.ParseExact(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
Instruct res = new()
{
IsResponse = true
IsResponse = true,
Type = "send_serverImg"
};
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,
@ -47,9 +52,15 @@ namespace OMS.NET.Instructs
@string = ""
};
}
this.ResponseOrBroadcastInstructs.Add(res);
ResponseOrBroadcastInstructs.Add(res);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
});
}
@ -73,12 +84,4 @@ namespace OMS.NET.Instructs
return "unknown";
}
}
public class SendServerImgInstruct : Instruct
{
public SendServerImgInstruct()
{
this.Type = "send_serverImg";
}
}
}

@ -6,20 +6,20 @@ namespace OMS.NET.Instructs
{
public GetUserDataInstruct()
{
this.Type = "get_userData";
Type = "get_userData";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (GlobalArea.LoginCheckByID(wsid))
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查,不通过则直接退出
string userEmail = GlobalArea.UserConnects.First(u => u.ID == wsid).UserEmail!;
AccountData accountData = GlobalArea.GetLoginAccountData(userEmail)!;
this.ResponseOrBroadcastInstructs.Add(new SendUserDataInstruct()
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsResponse = true,
Type = "send_userData",
Data = new
{
user_email = accountData.UserEmail,
@ -33,16 +33,7 @@ namespace OMS.NET.Instructs
custom = accountData.Custom,
}
});
}
});
}
}
public class SendUserDataInstruct : Instruct
{
public SendUserDataInstruct()
{
this.Type = "send_userData";
}
}
}

@ -2,6 +2,7 @@ using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using OMS.NET.Common;
namespace OMS.NET.Instructs
{
@ -52,16 +53,32 @@ namespace OMS.NET.Instructs
"get_presence" => JsonSerializer.Deserialize<GetPresenceInstruct>(root.GetRawText(), options),
"get_mapData" => JsonSerializer.Deserialize<GetMapDataInstruct>(root.GetRawText(), options),
"get_mapLayer" => JsonSerializer.Deserialize<GetMapLayerInstruct>(root.GetRawText(), options),
"get_activeData" => JsonSerializer.Deserialize<GetActiveDataInstruct>(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),
"point" => JsonSerializer.Deserialize<AddElementInstruct>(root.GetRawText(), options),
"line" => JsonSerializer.Deserialize<AddElementInstruct>(root.GetRawText(), options),
"area" => JsonSerializer.Deserialize<AddElementInstruct>(root.GetRawText(), options),
"curve" => JsonSerializer.Deserialize<AddElementInstruct>(root.GetRawText(), options),
"deleteElement" => JsonSerializer.Deserialize<DeleteElementInstruct>(root.GetRawText(), options),
"textMessage" => JsonSerializer.Deserialize<TextMessageInstruct>(root.GetRawText(), options),
"updateElement" => JsonSerializer.Deserialize<UpdateElementInstuct>(root.GetRawText(), options),
"updateElementNode" => JsonSerializer.Deserialize<UpdateElementNodeInstuct>(root.GetRawText(), options),
"selectIngElement" => JsonSerializer.Deserialize<SelectIngElementInstruct>(root.GetRawText(), options),
"selectEndElement" => JsonSerializer.Deserialize<SelectEndElementInstruct>(root.GetRawText(), options),
"pickIngElement" => JsonSerializer.Deserialize<PickIngElementInstruct>(root.GetRawText(), options),
"pickEndElement" => JsonSerializer.Deserialize<PickEndElementInstruct>(root.GetRawText(), options),
"restoreElement" => JsonSerializer.Deserialize<RestoreElementInstruct>(root.GetRawText(), options),
"adjustElementOrder" => JsonSerializer.Deserialize<AdjustElementOrderInstuct>(root.GetRawText(), options),
"updateLayerOrder" => JsonSerializer.Deserialize<UpdateLayerOrderInstruct>(root.GetRawText(), options),
"createGroupLayer" => JsonSerializer.Deserialize<CreateGroupLayerInstruct>(root.GetRawText(), options),
"deleteLayerAndMembers" => JsonSerializer.Deserialize<DeleteLayerAndMembersInstuct>(root.GetRawText(), options),
"batchDeleteElement" => JsonSerializer.Deserialize<BatchDeleteElementInstruct>(root.GetRawText(), options),
"renameLayer" => JsonSerializer.Deserialize<RenameLayerInstruct>(root.GetRawText(), options),
"updateTemplateData" => JsonSerializer.Deserialize<UpdateTemplateDataInstruct>(root.GetRawText(), options),
_ => JsonSerializer.Deserialize<Instruct>(root.GetRawText(), options)
},
_ => null
@ -78,24 +95,31 @@ namespace OMS.NET.Instructs
{
//JsonSerializer.Serialize(writer, (object)value, options); 这个在Data是对象时导致了无限递归调用
writer.WriteStartObject();
writer.WriteString(InstructNamingPolicy.Convert(nameof(Instruct.Type)), value.Type);
writer.WriteString("type", value.Type);
if (value.Class != null)
{
writer.WriteString(InstructNamingPolicy.Convert(nameof(Instruct.Class)), value.Class);
writer.WriteString("class", value.Class);
}
if (value.Conveyor != null)
{
writer.WriteString(InstructNamingPolicy.Convert(nameof(Instruct.Conveyor)), value.Conveyor);
writer.WriteString("conveyor", value.Conveyor);
}
if (value.Time != null)
{
writer.WriteString(InstructNamingPolicy.Convert(nameof(Instruct.Time)), value.Time);
writer.WriteString("time", value.Time);
}
if (value.Data != null)
{
writer.WritePropertyName(InstructNamingPolicy.Convert(nameof(Instruct.Data)));
writer.WritePropertyName("data");
if (value.Data.GetType() == typeof(List<ActiveDataElement>))
{
JsonSerializer.Serialize(writer, value.Data, value.Data.GetType(), ActiveDataElement.options);
}
else
{
JsonSerializer.Serialize(writer, value.Data, value.Data.GetType(), options);
}
}
writer.WriteEndObject();
}
}
@ -106,10 +130,10 @@ namespace OMS.NET.Instructs
{
ReadCommentHandling = JsonCommentHandling.Skip, //允许注释
AllowTrailingCommas = true,//允许尾随逗号
PropertyNamingPolicy = new InstructNamingPolicy(), // 属性名为定制转换
PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // 属性名为定制转换
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, // 忽略 null 值
WriteIndented = true, // 美化输出
//PropertyNameCaseInsensitive = true,//属性名忽略大小写
PropertyNameCaseInsensitive = true,//属性名忽略大小写
Converters = { new InstructConverter() },
};
public string Type { get; set; }
@ -127,7 +151,7 @@ namespace OMS.NET.Instructs
public Instruct()
{
this.Type = "";
Type = "";
}
/// <summary>
@ -145,7 +169,7 @@ namespace OMS.NET.Instructs
stopWatch.Start();
await Handler(wsid);
stopWatch.Stop();
GlobalArea.Log.Debug($"处理{this.GetType()}耗时:{stopWatch.ElapsedMilliseconds}ms");
GlobalArea.Log.Debug($"处理{GetType()}耗时:{stopWatch.ElapsedMilliseconds}ms");
}
public string ToJsonString()

@ -11,42 +11,41 @@ namespace OMS.NET.Instructs
{
public LoginInstruct()
{
this.Type = "login";
Type = "login";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (this.Data?.GetType() == typeof(JsonElement))
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
try
{
string email = this.Data.GetProperty("email").GetString();
string password = this.Data.GetProperty("password").GetString();
string email = Data.GetProperty("email").GetString();
string password = Data.GetProperty("password").GetString();
if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
{
GlobalArea.Log.Warn("登录信息不能为空!");
return;
throw new Exception("登录信息不能为空");
}
//能够获取到则说明客户端有发送数据过来
Instruct res1 = new LoginStatusInstuct
Instruct res1 = new()
{
Data = false,
IsResponse = true
IsResponse = true,
Type = "loginStatus",
Data = false
};//默认为false
//Console.WriteLine($"已获取到{email}:{password},解密测试{GlobalArea.DecryptFromBase64String(password)}");
AccountData? accountData = AccountData.Get(email);
AccountData accountData = AccountData.Get(email) ?? throw new Exception($"数据库中不包含用户{email}");
GlobalArea.AddLoginAccountData(accountData);
if (accountData != null)
{
ResponseOrBroadcastInstructs.Add(res1);
//只能原文比较,密文每次都不一样,涉及随机性填充
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
ResponseOrBroadcastInstructs.Add(new Instruct
{
Type = "broadcast",
Class = "logIn",
@ -60,21 +59,13 @@ namespace OMS.NET.Instructs
IsBroadcast = true
});
}
else
{
this.ResponseOrBroadcastInstructs.Add(res1);
}
}
catch (Exception ex)
{
GlobalArea.Log.Warn($"处理{Type}广播指令出错:" + ex.Message);
}
});
}
}
public class LoginStatusInstuct : Instruct
{
public LoginStatusInstuct()
{
this.Type = "loginStatus";
}
}
}

@ -0,0 +1,50 @@
using System.Text.Json;
using OMS.NET.Common;
using OMS.NET.DbClass;
namespace OMS.NET.Instructs
{
public class PickEndElementInstruct : Instruct
{
public PickEndElementInstruct()
{
Type = "broadcast";
Class = "pickEndElement";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查,不通过则直接退出
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
try
{
long id = Data.GetInt64();
string conveyor = GlobalArea.GetLoginEmailByID(wsid);
if (GlobalArea.IsElementExit(id))//已存在activedata项
{
ActiveDataElement activeDataElement = GlobalArea.GetActiveDataElement(id)!;
if (activeDataElement.Pick?.Email == conveyor)
{
activeDataElement.Pick = null;
string time = GlobalArea.GetCurrentTime();
ResponseOrBroadcastInstructs.Add(new PickEndElementInstruct()
{
IsBroadcast = true,
Conveyor = conveyor,
Time = time,
Data = id
});
}
}
}
catch (Exception ex)
{
GlobalArea.Log.Warn($"处理{Class}广播指令出错:" + ex.Message);
}
});
}
}
}

@ -0,0 +1,71 @@
using System.Text.Json;
using OMS.NET.Common;
using OMS.NET.DbClass;
namespace OMS.NET.Instructs
{
public class PickIngElementInstruct : Instruct
{
public PickIngElementInstruct()
{
Type = "broadcast";
Class = "pickIngElement";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查,不通过则直接退出
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
try
{
long id = Data.GetInt64();
string conveyor = GlobalArea.GetLoginEmailByID(wsid);
AccountData accountData = GlobalArea.GetLoginAccountData(conveyor)!;
UserInfo userInfo = new()
{
Email = conveyor,
Color = accountData.HeadColor,
Name = accountData.UserName,
};
if (GlobalArea.IsElementExit(id))//已存在activedata项
{
ActiveDataElement activeDataElement = GlobalArea.GetActiveDataElement(id)!;
if (activeDataElement.Pick == null)
{
activeDataElement.Pick = userInfo;
}
else
{
throw new Exception($"{id}已被{activeDataElement.Pick.Name}Pick");
}
}
else
{
GlobalArea.AddActiveDataElement(new ActiveDataElement(id)
{
Pick = userInfo
});
}
string time = GlobalArea.GetCurrentTime();
ResponseOrBroadcastInstructs.Add(new PickIngElementInstruct()
{
IsBroadcast = true,
Conveyor = conveyor,
Time = time,
Data = new
{
id = id,
color = accountData.HeadColor
}
});
}
catch (Exception ex)
{
GlobalArea.Log.Warn($"处理{Class}广播指令出错:" + ex.Message);
}
});
}
}
}

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

@ -0,0 +1,54 @@
using System.Text.Json;
using OMS.NET.Common;
namespace OMS.NET.Instructs
{
public class RenameLayerInstruct : Instruct
{
public RenameLayerInstruct()
{
Type = "broadcast";
Class = "renameLayer";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查不通过则直接退出
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
try
{
long id = Data.GetProperty("id").GetInt64();
string name = Data.GetProperty("name").GetString();
if (GlobalArea.IsLayerNameRepeat(name)) throw new Exception("存在名称重复");
LayerData layerData = GlobalArea.GetLayerDataByLayerId(id) ?? throw new Exception($"未找到MapLayer {id}");
layerData.Structure!.AsArray().RemoveAt(0);
layerData.Structure!.AsArray().Insert(0, name);
layerData.UpdateToDb();
string conveyor = GlobalArea.GetLoginEmailByID(wsid);
string time = GlobalArea.GetCurrentTime();
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsBroadcast = true,
Type = "broadcast",
Class = "renameLayer",
Conveyor = conveyor,
Time = time,
Data = new
{
id = id,
name = name,
}
});
}
catch (Exception ex)
{
GlobalArea.Log.Warn($"处理{Class}广播指令出错:" + ex.Message);
}
});
}
}
}

@ -0,0 +1,75 @@
using System.Text.Json;
using OMS.NET.Common;
using OMS.NET.DbClass;
namespace OMS.NET.Instructs
{
public class RestoreElementInstruct : Instruct
{
public RestoreElementInstruct()
{
Type = "broadcast";
Class = "restoreElement";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查不通过则直接退出
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
try
{
string conveyor = GlobalArea.GetLoginEmailByID(wsid);
long id = Data.GetProperty("id").GetInt64();
string tmpId = Data.GetProperty("tmpId").GetString();
MapData mapData = MapData.Get(id) ?? throw new Exception($"Element{id}不存在");
mapData.Phase = 1;
if (MapData.Update(mapData) == -1) throw new Exception("数据库修改失败");
LayerData layer = GlobalArea.GetLayerDataByTemplateId(tmpId)!;
layer.AppendElement(id, mapData.Type);
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsBroadcast = true,
Type = "broadcast",
Class = mapData.Type,
Conveyor = conveyor,
Time = GlobalArea.GetCurrentTime(),
Data = mapData
});
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsBroadcast = true,
Type = "broadcast",
Class = "updateLayerData",
Conveyor = conveyor,
Time = GlobalArea.GetCurrentTime(),
Data = new
{
id = layer.LayerId,
members = layer.Members!.ToString(),
structure = layer.Structure!.ToString(),
}
});
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsResponse = true,
Type = "send_correct",
Class = "upload",
Conveyor = conveyor,
Time = GlobalArea.GetCurrentTime(),
Data = new
{
rid = id,
vid = "restore"
}
});
}
catch (Exception ex)
{
GlobalArea.Log.Warn($"处理{Class}广播指令出错:" + ex.Message);
}
});
}
}
}

@ -0,0 +1,50 @@
using System.Text.Json;
using OMS.NET.Common;
using OMS.NET.DbClass;
namespace OMS.NET.Instructs
{
public class SelectEndElementInstruct : Instruct
{
public SelectEndElementInstruct()
{
Type = "broadcast";
Class = "selectEndElement";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查,不通过则直接退出
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
try
{
long id = Data.GetInt64();
string conveyor = GlobalArea.GetLoginEmailByID(wsid);
if (GlobalArea.IsElementExit(id))//已存在activedata项
{
ActiveDataElement activeDataElement = GlobalArea.GetActiveDataElement(id)!;
if (activeDataElement.Select?.Email == conveyor)
{
activeDataElement.Select = null;
string time = GlobalArea.GetCurrentTime();
ResponseOrBroadcastInstructs.Add(new SelectEndElementInstruct()
{
IsBroadcast = true,
Conveyor = conveyor,
Time = time,
Data = id
});
}
}
}
catch (Exception ex)
{
GlobalArea.Log.Warn($"处理{Class}广播指令出错:" + ex.Message);
}
});
}
}
}

@ -0,0 +1,71 @@
using System.Text.Json;
using OMS.NET.Common;
using OMS.NET.DbClass;
namespace OMS.NET.Instructs
{
public class SelectIngElementInstruct : Instruct
{
public SelectIngElementInstruct()
{
Type = "broadcast";
Class = "selectIngElement";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查,不通过则直接退出
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
try
{
long id = Data.GetInt64();
string conveyor = GlobalArea.GetLoginEmailByID(wsid);
AccountData accountData = GlobalArea.GetLoginAccountData(conveyor)!;
UserInfo userInfo = new()
{
Email = conveyor,
Color = accountData.HeadColor,
Name = accountData.UserName,
};
if (GlobalArea.IsElementExit(id))//已存在activedata项
{
ActiveDataElement activeDataElement = GlobalArea.GetActiveDataElement(id)!;
if (activeDataElement.Select == null)
{
activeDataElement.Select = userInfo;
}
else
{
throw new Exception($"{id}已被{activeDataElement.Select.Name}Select");
}
}
else
{
GlobalArea.AddActiveDataElement(new ActiveDataElement(id)
{
Select = userInfo
});
}
string time = GlobalArea.GetCurrentTime();
ResponseOrBroadcastInstructs.Add(new SelectIngElementInstruct()
{
IsBroadcast = true,
Conveyor = conveyor,
Time = time,
Data = new
{
id = id,
color = accountData.HeadColor
}
});
}
catch (Exception ex)
{
GlobalArea.Log.Warn($"处理{Class}广播指令出错:" + ex.Message);
}
});
}
}
}

@ -7,7 +7,7 @@ namespace OMS.NET.Instructs
{
public TestInstruct()
{
this.Type = "test";
Type = "test";
}
public override Task Handler(string wsid)

@ -0,0 +1,45 @@
using System.Text.Json;
namespace OMS.NET.Instructs
{
public class TextMessageInstruct : Instruct
{
public TextMessageInstruct()
{
Type = "broadcast";
Class = "textMessage";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查不通过则直接退出
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
try
{
string message = Data.GetProperty("message").GetString();
string conveyor = GlobalArea.GetLoginEmailByID(wsid);
string time = GlobalArea.GetCurrentTime();
GlobalArea.Log.Info($"[{time}] {conveyor}:{message}");
ResponseOrBroadcastInstructs.Add(new TextMessageInstruct()
{
IsBroadcast = true,
Conveyor = conveyor,
Time = time,
Data = new
{
message,
headColor = Data.GetProperty("headColor").GetString(),
name = Data.GetProperty("name").GetString()
}
});
}
catch (Exception ex)
{
GlobalArea.Log.Warn("处理textMessage发生问题" + ex.Message);
}
});
}
}
}

@ -0,0 +1,91 @@
using System.Text.Json;
using OMS.NET.Common;
using OMS.NET.DbClass;
namespace OMS.NET.Instructs
{
public class UpdateElementInstuct : Instruct
{
public UpdateElementInstuct()
{
Type = "broadcast";
Class = "updateElement";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查不通过则直接退出
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
string conveyor = GlobalArea.GetLoginEmailByID(wsid);
try
{
long id = Data.GetProperty("id").GetInt64();
string updateId = Data.GetProperty("updateId").GetString();
if (Data.TryGetProperty("changes", out JsonElement changes))
{
MapData mapData = MapData.Get(id) ?? throw new Exception($"数据库中未能找到id为{id}的元素");
string color = changes.GetProperty("color").GetString()!;
if (changes.TryGetProperty("width", out JsonElement widthElement))
{
int width = widthElement.GetInt32();
mapData.Width = width;
}
if (changes.TryGetProperty("details", out JsonElement detailsElement))
{
string details = detailsElement.GetString()!;
mapData.Details = Util.JsonToBase64(details);
}
if (changes.TryGetProperty("custom", out JsonElement customElement))
{
string custom = customElement.GetString()!;
mapData.Custom = Util.JsonToBase64(custom);
}
if (MapData.Update(mapData) == -1) throw new Exception("数据库修改失败");
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsResponse = true,
Type = "send_correct",
Class = "updateElement",
Conveyor = conveyor,
Time = GlobalArea.GetCurrentTime(),
Data = new
{
vid = updateId,
rid = id
}
});
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsBroadcast = true,
Type = "broadcast",
Class = "updateElement",
Conveyor = conveyor,
Time = GlobalArea.GetCurrentTime(),
Data = mapData
});
}
}
catch (Exception ex)
{
GlobalArea.Log.Warn($"处理{Class}广播指令出错:" + ex.Message);
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsResponse = true,
Type = "send_error",
Class = "updateElement",
Conveyor = conveyor,
Time = GlobalArea.GetCurrentTime(),
Data = new
{
source = Data,
message = ex.Message
}
});
}
});
}
}
}

@ -0,0 +1,87 @@
using System.Text.Json;
using OMS.NET.Common;
using OMS.NET.DbClass;
namespace OMS.NET.Instructs
{
public class UpdateElementNodeInstuct : Instruct
{
public UpdateElementNodeInstuct()
{
Type = "broadcast";
Class = "updateElementNode";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查不通过则直接退出
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
string conveyor = GlobalArea.GetLoginEmailByID(wsid);
try
{
long id = Data.GetProperty("id").GetInt64();
string updateId = Data.GetProperty("updateId").GetString();
string points = Data.GetProperty("points").GetRawText();//todo
MapData mapData = MapData.Get(id) ?? throw new Exception($"数据库中未能找到id为{id}的元素");
mapData.Points = Util.JsonToBase64(points);
if (Data.TryGetProperty("point", out JsonElement pointNode))
{
mapData.Point = Util.JsonToBase64(pointNode.GetRawText());
}
if (MapData.Update(mapData) == -1) throw new Exception("数据库修改失败");
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsResponse = true,
Type = "send_correct",
Class = "updateNode",
Conveyor = conveyor,
Time = GlobalArea.GetCurrentTime(),
Data = new
{
vid = updateId,
rid = id
}
});
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsBroadcast = true,
Type = "broadcast",
Class = "updateElementNode",
Conveyor = conveyor,
Time = GlobalArea.GetCurrentTime(),
Data = new
{
id = mapData.Id,
type = mapData.Type,
point = mapData.Point,
points = mapData.Points
}
});
}
catch (Exception ex)
{
GlobalArea.Log.Warn($"处理{Class}广播指令出错:" + ex.Message);
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsResponse = true,
Type = "send_error",
Class = "updateNode",
Conveyor = conveyor,
Time = GlobalArea.GetCurrentTime(),
Data = new
{
source = Data,
message = ex.Message
}
});
}
});
}
}
}

@ -0,0 +1,50 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using OMS.NET.Common;
namespace OMS.NET.Instructs
{
public class UpdateLayerOrderInstruct : Instruct
{
public UpdateLayerOrderInstruct()
{
Type = "broadcast";
Class = "updateLayerOrder";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查不通过则直接退出
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
string conveyor = GlobalArea.GetLoginEmailByID(wsid);
try
{
long active = Data.GetProperty("active").GetInt64();
long passive = Data.GetProperty("passive").GetInt64();
string type = Data.GetProperty("type").GetString();
LayerData order = GlobalArea.GetOrderLayerData();
order.AdjustOrderLayer(active, passive, type);
ResponseOrBroadcastInstructs.Add(new Instruct()
{
IsBroadcast = true,
Type = "broadcast",
Class = "updateLayerOrder",
Conveyor = conveyor,
Time = GlobalArea.GetCurrentTime(),
Data = new
{
member = order.Members
}
});
}
catch (Exception ex)
{
GlobalArea.Log.Warn($"处理{Class}广播指令出错:" + ex.Message);
}
});
}
}
}

@ -0,0 +1,33 @@
using System.Text.Json;
namespace OMS.NET.Instructs
{
public class UpdateTemplateDataInstruct : Instruct
{
public UpdateTemplateDataInstruct()
{
Type = "broadcast";
Class = "updateTemplateData";
}
public override Task Handler(string wsid)
{
return Task.Run(() =>
{
if (!GlobalArea.LoginCheckByID(wsid)) return;//登录检查不通过则直接退出
if (Data?.GetType() != typeof(JsonElement)) return;//Data 非空和JsonElement类型检查
try
{
//string conveyor = GlobalArea.GetLoginEmailByID(wsid);
//string time = GlobalArea.GetCurrentTime();
//string template = Data.GetProperty("template").GetString();
throw new NotImplementedException("太难搞了,不干了");
}
catch (Exception ex)
{
GlobalArea.Log.Warn($"处理{Class}广播指令出错:" + ex.Message);
}
});
}
}
}

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

@ -7,7 +7,7 @@ CREATE TABLE IF NOT EXISTS map_0_data (
phase INT(1) NOT NULL,
width INT(11),
child_relations MEDIUMTEXT,
father_relations VARCHAR(255),
father_relation VARCHAR(255),
child_nodes MEDIUMTEXT,
father_node VARCHAR(255),
details MEDIUMTEXT,

Loading…
Cancel
Save