using Newtonsoft.Json.Linq;
using Serein.Library;
using Serein.Library.Api;
using Serein.Library.Network.WebSocketCommunication;
using Serein.Library.Network.WebSocketCommunication.Handle;
using Serein.Library.Utils;
using System.Diagnostics.CodeAnalysis;
namespace Serein.NodeFlow.Env
{
///
/// 服务端的消息管理(用于处理客户端的请求)
///
[AutoSocketModule(ThemeKey = LocalFlowEnvironment.ThemeKey,
DataKey = LocalFlowEnvironment.DataKey,
MsgIdKey = LocalFlowEnvironment.MsgIdKey)]
public class MsgControllerOfServer : ISocketHandleModule
{
///
/// 受控环境
///
public IFlowEnvironment environment;
///
/// WebSocket处理
///
public Guid HandleGuid { get; } = new Guid();
///
/// 表示是否正在控制远程
/// Local control remote env
///
public bool IsLcR { get; set; }
///
/// 表示是否受到远程控制
/// Remote control local env
///
public bool IsRcL { get; set; }
///
/// 流程环境远程管理服务
///
private WebSocketServer FlowEnvRemoteWebSocket;
///
/// 启动不带Token验证的远程服务
///
public MsgControllerOfServer(IFlowEnvironment environment)
{
this.environment = environment;
FlowEnvRemoteWebSocket ??= new WebSocketServer();
}
///
/// 启动带token验证的远程服务
///
///
///
public MsgControllerOfServer(IFlowEnvironment environment, string token)
{
if (string.IsNullOrEmpty(token))
{
SereinEnv.WriteLine(InfoType.WARN, "当前没有设置token,但使用了token验证的服务端");
}
this.environment = environment;
FlowEnvRemoteWebSocket ??= new WebSocketServer(token, OnInspectionAuthorized);
}
#region 基本方法
///
/// 启动远程
///
///
///
public async Task StartRemoteServerAsync(int port = 7525)
{
FlowEnvRemoteWebSocket.MsgHandleHelper.AddModule(this,
(ex, send) =>
{
send(new
{
code = 400,
ex = ex.Message
});
});
var url = $"http://*:{port}/";
try
{
await FlowEnvRemoteWebSocket.StartAsync(url);
}
catch (Exception ex)
{
FlowEnvRemoteWebSocket.MsgHandleHelper.RemoveModule(this);
SereinEnv.WriteLine(InfoType.ERROR, "打开远程管理异常:" + ex);
}
}
///
/// 结束远程管理
///
[AutoSocketHandle]
public void StopRemoteServer()
{
try
{
FlowEnvRemoteWebSocket.Stop();
}
catch (Exception ex)
{
SereinEnv.WriteLine(InfoType.ERROR, "结束远程管理异常:" + ex);
}
}
///
/// 验证远程token
///
///
///
private async Task OnInspectionAuthorized(dynamic token)
{
if (IsLcR)
{
return false; // 正在远程控制远程环境时,禁止其它客户端远程控制
}
if (IsRcL)
{
return false; // 正在受到远程控制时,禁止其它客户端远程控制
}
await Task.Delay(0);
var tokenValue = token.ToString();
if ("123456".Equals(tokenValue))
{
// 同时切换远程环境
return true;
}
else
{
return false;
}
}
///
/// 获取发送消息的委托
///
///
private void OnResultSendMsgFunc(Func SendAsync)
{
// 从受控环境向主控环境发送消息。
Func func = async (theme, data) =>
{
JObject sendJson = new JObject
{
[LocalFlowEnvironment.ThemeKey] = theme,
[LocalFlowEnvironment.DataKey] = JObject.FromObject(data),
};
var msg = sendJson.ToString();
await SendAsync(msg);
};
// var remoteEnv = new RemoteFlowEnvironment(func); // 创建一个远程环境
// OnSwitchedEnvironment.Invoke(remoteEnv); // 通知前台切换到了远程环境
}
#endregion
///
/// 异步运行
///
///
[AutoSocketHandle(ThemeValue = EnvMsgTheme.StartFlow)]
private async Task