/// <summary> /// 上传控制指令 /// </summary> /// <param name="entity"></param> /// <param name="transport"></param> /// <param name="facilitySerialnum"></param> /// <returns></returns> public dynamic UploadControlResult(AwEntity entity, IApiTransport transport, ControlResult controlResult) { if (transport == null) { throw new ArgumentNullException(nameof(transport)); } //if (controlResult.FacilityCode.IsNullOrWhiteSpace()) throw new ArgumentNullException("facilitySerialnum"); Guard(entity); entity.Description = "上传控制指令"; entity.DataBlockObject.DataContentRequest.ControlDataBlock = new ControlDataBlock() { ControlResults = new[] { new ControlResult() { Serialnum = controlResult.Serialnum, Result = controlResult.Result, Time = controlResult.Time } }.ToList() }; var response = transport.Process(entity); //if (response.Success == ErrorType.NoError) //{ // if (response.Data != null && response.Data != null) // return response.Data; //} //return null; return(response.Success == ErrorType.NoError); }
protected override void OnUIGenerated(ControlResult ui) { base.OnUIGenerated(ui); var listView = this.ListView; //默认发起一次查询。 var queryView = listView.ConditionQueryView; if (queryView != null) { queryView.TryExecuteQuery(); } listView.IsReadOnly = ReadOnlyStatus.ReadOnly; //列表双击时,弹出查看窗口 listView.Control.MouseDoubleClick += (o, e) => { var cmd = listView.Commands.Find <ShowBill>(); if (cmd != null) { cmd.TryExecute(); } }; }
/// <summary> /// 子类重写此方法实现自己的弹窝逻辑。 /// </summary> /// <param name="ui"></param> /// <returns></returns> protected virtual WindowButton PopupSelectionWindow(ControlResult ui) { return(App.Windows.ShowDialog(ui.Control, w => { w.Title = this.Meta.Label.Translate(); })); }
/// <summary> /// 上传控制指令 /// </summary> /// <returns></returns> private void UploadControlCommand(ControlResult controlResult, Facility fac) { #if DEBUG var sw = new Stopwatch(); var accessResult = false; sw.Start(); #endif try { var entity = AwEntityHelper.GetEntity(fac.Farm.Code1); var result = _facilityApi.UploadControlResult(entity, _transport, controlResult); LogHelper.Debug("上传控制结果成功 " + (result ? "成功" : "失败")); accessResult = result; } catch (Exception ex) { LogHelper.Debug("上传控制结果失败," + ex.Message); } #if DEBUG sw.Stop(); var apiAccesslog = new ApiAccessLog { ApiName = "上传控制结果", Result = accessResult, CreateTime = DateTime.Now, CostTime = Convert.ToInt32(sw.ElapsedMilliseconds) }; apiAccesslog.Save(); LogHelper.Debug("控制结果上传耗时:" + sw.ElapsedMilliseconds + "ms"); #endif //return true; }
private void TryArrangeCommandsContainer(ControlResult toolBar) { if (toolBar != null) { toolBarContainer.Content = toolBar.Control; } }
private RemotePlayContext SendInitControlMessages(Socket udpClient) { /******** Initial control message 1 ********/ byte[] controlMessage1Payload = HexUtil.Unhexlify("0064006400004823"); ushort initialControlMessage1PayloadSize = (ushort)(12 + controlMessage1Payload.Length); ControlMessage initialMessage1 = new ControlMessage(0, 0, 0, 0, 1, 0, initialControlMessage1PayloadSize, 0x4823, 0x19000); initialMessage1.UnParsedPayload = controlMessage1Payload; byte[] initialControlMessage1Data = GetByteArrayForControlMessage(initialMessage1); ControlResult initControlResult1 = SendControlDataAndWaitForAnswer(udpClient, initialControlMessage1Data, 1, "Send Init Control message 1"); if (!initControlResult1.WasSuccessful) { return(null); } ControlMessage initialAnswer1 = initControlResult1.ControlMessages[0]; /******** Initial control message 2 ********/ byte[] initialAnswer1Payload = initialAnswer1.UnParsedPayload; MemoryStream memoryBuffer = new MemoryStream(initialAnswer1Payload) { Position = 8 }; byte[] funcIncrBuffer = new byte[4]; memoryBuffer.Read(funcIncrBuffer, 0, funcIncrBuffer.Length); uint funcIncrValue = ByteUtil.ByteArrayToUInt(funcIncrBuffer); memoryBuffer.Position = 28; byte[] lastAnswerPart = new byte[memoryBuffer.Length - memoryBuffer.Position]; memoryBuffer.Read(lastAnswerPart, 0, lastAnswerPart.Length); byte[] funcIncr = ByteUtil.UIntToByteArray(initialAnswer1.FuncIncr); byte[] classValue = ByteUtil.UIntToByteArray(initialAnswer1.ClassValue); byte[] controlMessage2Payload = ByteUtil.ConcatenateArrays(funcIncr, classValue, funcIncr, lastAnswerPart); ushort initialControlMessage2PayloadSize = (ushort)(12 + controlMessage2Payload.Length); ControlMessage controlMessage2 = new ControlMessage(0, initialAnswer1.FuncIncr, 0, 0, 10, 0, initialControlMessage2PayloadSize, funcIncrValue, initialAnswer1.ReceiverId); controlMessage2.UnParsedPayload = controlMessage2Payload; byte[] initialControlMessage2Data = GetByteArrayForControlMessage(controlMessage2); ControlResult initControlResult2 = SendControlDataAndWaitForAnswer(udpClient, initialControlMessage2Data, 1, "Send Init Control message 2"); if (!initControlResult2.WasSuccessful) { return(null); } RemotePlayContext remotePlayContext = new RemotePlayContext() { ReceiverId = initialAnswer1.FuncIncr, FuncIncr = initialMessage1.FuncIncr }; return(remotePlayContext); }
protected override WindowButton PopupSelectionWindow(ControlResult ui) { return(App.Windows.ShowDialog(ui.Control, w => { w.Title = this.Meta.Label.Translate(); w.Width = 600; w.Height = 300; })); }
private void TryArrangeCommandsContainer(ControlResult toolBar) { if (toolBar != null) { toolBarContainer.Content = toolBar.Control; } else { toolBarContainer.RemoveFromParent(false); } }
private void TryArrangeCommandsContainer(ControlResult toolBar) { if (toolBar != null) { toolBarContainer.Content = toolBar.Control; } else { toolBarContainer.RemoveFromParent(false); } }
private void TryArrangeMain(ControlResult control) { if (control != null) { main.Content = control.Control; } else { main.RemoveFromParent(false); } }
private void TryArrangeDetail(ControlResult control) { if (control != null) { detailRegion.Content = control.Control; } else { detailRegion.RemoveFromParent(); } }
private void TryArrangeNavigation(ControlResult control) { if (control != null) { navigate.Content = control.Control; } else { navigate.RemoveFromParent(false); } }
private void TryArrangeCondition(ControlResult control) { if (control != null) { condition.Content = control.Control; } else { condition.RemoveFromParent(); } }
private void TryArrangeMain(ControlResult control) { if (control != null) { listRegion.Content = control.Control; } else { listRegion.RemoveFromParent(); } }
private void TryArrangeCondition(ControlResult control) { if (control != null) { condition.Content = control.Control; } else { condition.RemoveFromParent(); } }
private static void BanUserForPositiveControl(Message message, ControlResult result) { int limitTime = 3; Models.Group.ConfigurationParameter configValue = CacheData.GroupConfigs[message.Chat.Id] .Where(x => x.ConfigurationParameterId == "SpamActionLimitTime") .SingleOrDefault(); if (configValue != null) { int.TryParse(configValue.Value, out limitTime); } RemoveMessageForPositiveControl(message, result); Bot.Manager.BotClient.KickChatMemberAsync(message.Chat.Id, message.From.Id, DateTime.UtcNow.AddMinutes(-5)); UserTools.AddPenalty(message.Chat.Id, message.From.Id, Models.TrustFactorLog.TrustFactorAction.ban, Bot.Manager.MyId); string author = message.From.Username == null ? message.From.FirstName + " " + message.From.LastName : "@" + message.From.Username; string logMessage = String.Format( "*[Report]*\n" + "User banned as per group _Spam Action_ preference.\n" + "⚠ do not open links you don't know ⚠\n" + "\nControl: `{0}`" + "\nChat: `{1}`" + "\nAuthor: `{2}`" + "\nUserId: `{3}`" + "\n\n*hash_code:* #UB{4}-{5}", result.CheckName, message.Chat.Title, author, message.From.Id, message.Chat.Id.ToString().Replace("-", ""), Guid.NewGuid()); MessageQueueManager.EnqueueLog(new ChatMessage() { ParseMode = ParseMode.Markdown, Text = logMessage }); LogTools.AddActionLog(new ActionLog() { GroupId = CacheData.Groups[message.Chat.Id].GroupId, UtcDate = DateTime.UtcNow, ActionTypeId = "autoBan", Parameters = logMessage, }); }
public Region(string name, ControlResult control) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException("name"); } if (control == null) { throw new ArgumentNullException("control"); } this.Name = name; this.ControlResult = control; }
// GET api/<controller> public IEnumerable <ControlResult> Get() { List <ControlResult> controls = new List <ControlResult>(); List <Chemical> chemicals = db.Chemicals.ToList(); foreach (var chemical in chemicals) { ControlResult control = new ControlResult() { Control = "Chemical", Description = chemical.Name }; controls.Add(control); } return(controls); }
protected override void OnUIGenerated(ControlResult ui) { base.OnUIGenerated(ui); this._planView = ui.MainView as ListLogicalView; this._taskView = this._planView.GetChildView(typeof(TaskOrCategory)) as ListLogicalView; this._weekCompletionView = this._taskView.GetChildView(typeof(WeekCompletion)) as ListLogicalView; var weekNoteView = this._planView.GetChildView(typeof(WeekNote)) as ListLogicalView; MPHelper.ModifyRowStyle(this._taskView, "TaskViewRowStyle"); MPHelper.ModifyRowStyle(this._weekCompletionView, "CurrentWeekRowStyle"); MPHelper.ModifyRowStyle(weekNoteView, "CurrentWeekRowStyle"); this.ChangeTaskCompletionVisibility(); this.AddWeekNotesOnPlan(); }
protected override void OnUIGenerated(ControlResult ui) { base.OnUIGenerated(ui); var itemView = ui.MainView.GetChildView(typeof(StorageInBillItem)); var treeGrid = itemView.Control.CastTo <RafyTreeGrid>(); var column = treeGrid.FindColumnByProperty(StorageInBillItem.UnitPriceProperty); if (column != null) { column.Meta.Readonly(); column.Meta.Label = "订单单价";//注意,此行代码将会无效 } //只能把该按钮隐藏 itemView.Commands[typeof(BarcodeSelectProduct)].IsVisible = false; }
private ControlResult SendControlDataAndWaitForAnswer(Socket udpClient, byte[] data, int expectedPackets, string info) { const int retry = 3; ControlResult controlResult = null; for (int i = 1; i <= retry; i++) { Task <ControlResult> controlResultFuture = WaitForControlMessage(udpClient, expectedPackets, info); SendData(udpClient, data); controlResult = controlResultFuture.Result; if (controlResult.WasSuccessful) { break; } } return(controlResult); }
//protected override void OnItemCreated(Entity entity) //{ // base.OnItemCreated(entity); // var log = entity as FinanceLog; // log.Date = DateTime.Today; //} protected override void OnUIGenerated(ControlResult ui) { var defaultPersons = RF.Find <Person>().GetAll().Cast <Person>() .Where(t => t.IsDefault).Select(t => t.Name).ToArray(); var defaultTags = RF.Find <Tag>().GetAll().Cast <Tag>() .Where(t => !t.NotUsed && t.IsDefault).Select(t => t.Name).ToArray(); var log = new FinanceLog { Users = string.Join(",", defaultPersons), Tags = string.Join(",", defaultTags) }; var main = ui.MainView as DetailLogicalView; main.Current = log; main.Control.Loaded += (s, e) => (main.PropertyEditors[0].Control as FrameworkElement).Focus(); //暂时通过以下方式为按钮添加键盘事件。 main.Control.KeyDown += (s, e) => { if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.Enter) { //移除焦点,提交更改 var element = Keyboard.FocusedElement as FrameworkElement; if (element != null) { element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); } main.Commands[typeof(ContinueAddFinanceLog)].TryExecute(); } }; var listView = main.Relations["list"] as ListLogicalView; listView.DataLoader.LoadDataAsync(); listView.IsReadOnly = ReadOnlyStatus.ReadOnly; base.OnUIGenerated(ui); }
// 系统参数设置 public static void SetSystemSettingParaService(CmsSystemSetting obj) { var channel = new Channel(GrpcChannelAddress, ChannelCredentials.Insecure); var client = new gRPCClient(channel); foreach (PropertyInfo p in obj.GetType().GetProperties()) { object value = p.GetValue(obj); // 处理是否 if (value != null && p.PropertyType == typeof(string)) { if (value.ToString().Equals("是")) { value = 1; } else if (value.ToString().Equals("否")) { value = 0; } SystemPara systemPara = new SystemPara(); systemPara.ParaName = p.Name; systemPara.ParaValue = value.ToString(); ControlResult result = client.setSystemSettingPara(systemPara); // 日志输出 if (result.Result.Equals("1")) { log.Info($"参数设置成功:{systemPara.ParaName},{systemPara.ParaValue}"); } else { log.Info($"参数设置失败:{systemPara.ParaName},{systemPara.ParaValue}"); } } } }
private static void RemoveMessageForPositiveControl(Message message, ControlResult result) { try { Bot.Manager.BotClient.DeleteMessageAsync(message.Chat.Id, message.MessageId); string author = message.From.Username == null ? message.From.FirstName + " " + message.From.LastName : "@" + message.From.Username; string logMessage = String.Format( "*[Report]*\n" + "Message deleted due to control *{0}*.\n" + "⚠ do not open links you don't know ⚠\n" + "\nChat: `{1}`" + "\nAuthor: `{3}`" + "\nUserId: `{4}`" + "\nOriginal message:\n```{2}```" + "\n\n*hash_code:* #UB{5}-{6}", result.CheckName, message.Chat.Title, message.Text, author, message.From.Id, message.Chat.Id.ToString().Replace("-", ""), Guid.NewGuid()); MessageQueueManager.EnqueueLog(new ChatMessage() { ParseMode = ParseMode.Markdown, Text = logMessage }); LogTools.AddActionLog(new ActionLog() { GroupId = CacheData.Groups[message.Chat.Id].GroupId, UtcDate = DateTime.UtcNow, ActionTypeId = "autoDelete", Parameters = logMessage, }); } catch (Exception ex) { Data.Utils.Logging.AddLog(new SystemLog() { LoggerName = CacheData.LoggerName, Date = DateTime.Now, Function = "Unifiedban.Terminal.Controls.Manager.RemoveMessageForPositiveControl", Level = SystemLog.Levels.Error, Message = ex.Message, UserId = -1 }); if (ex.InnerException != null) { Data.Utils.Logging.AddLog(new SystemLog() { LoggerName = CacheData.LoggerName, Date = DateTime.Now, Function = "Unifiedban.Terminal.Controls.Manager.RemoveMessageForPositiveControl", Level = SystemLog.Levels.Error, Message = ex.InnerException.Message, UserId = -1 }); } } }
private void TryArrangeMain(ControlResult control) { if (control != null) { main.Content = control.Control; } else { main.RemoveFromParent(false); } }
/// <summary> /// 控制设备 /// </summary> /// <param name="deviceId">控制设备ID</param> /// <param name="status">设备状态</param> private void Control(int deviceId, int status) { const bool result = false; List <FacilityControlDeviceUnit> fac = FacilityControlDeviceUnit.FindAllByControlDeviceUnitGroupNum(deviceId); if (fac == null || !fac.Any()) { return; } var device = ControlDeviceUnit.FindByID(deviceId); if (device == null) { return; } string reason = null; TransportTypeEnum type; if ( !Enum.TryParse(device.ModularDevice.CommunicateDevice.CommunicateDeviceTypeName, true, out type)) { type = TransportTypeEnum.Unknow; } var host = device.ModularDevice.CommunicateDevice.Args1; var e = Convert.ToInt32(device.ModularDevice.CommunicateDevice.Args2); var timeout = Convert.ToInt32(device.ModularDevice.CommunicateDevice.Args3); //获取Transport var transport = TransportFactory.GetTransport(type, host, e, timeout); var modbusControlDevice = new ModbusControlDevice(transport, Convert.ToByte(device.ModularDevice.Address)); try { //待编写控制指令 //if (device.IsComposite) //三态设备 正转 反转 停止 //{ // if (status == -1) // { // result = modbusControlDevice.Write(device.RegisterAddress1, true); // } // else if (status == 0) // { // result = modbusControlDevice.Write(device.RegisterAddress1, false); // result = modbusControlDevice.Write(device.RegisterAddress2, false); // } // else if (status == 1) // { // result = modbusControlDevice.Write(device.RegisterAddress2, true); // } //} //else //两态设备 开 关 //{ // result = modbusControlDevice.Write(device.RegisterAddress1, status == 1 ? true : false); //} } catch (Exception ex) { reason = ex.ToString(); } LogHelper.Debug("指令执行" + (result ? "成功" : "失败")); DeviceControlCommand.FindAllByControlDeviceUnitID(deviceId).ToList().ForEach(deviceControlCommand => { var controlResult = new ControlResult { Serialnum = deviceControlCommand.Code1, //Command = status, //FacilityCode = fac[0].Facility.Code1, //DeviceCode = fac[0].Code1, //ContinueTime = 5, Time = DateTime.Now, Result = result, FailReason = reason }; var devControlLog = new DeviceControlLog { Code1 = deviceControlCommand.Code1, ControlDeviceUnitID = deviceControlCommand.ControlDeviceUnitGroupNum, ControlResult = result, CreateTime = DateTime.Now, DeviceControlCommand = deviceControlCommand, DeviceControlCommandID = deviceControlCommand.ID, DeviceValue = Convert.ToInt32(CalcControlDeviceValue.CalcProcessValue(fac[0])), ShowValue = CalcControlDeviceValue.CalcOriginal(fac[0]).ToString(), FailReason = reason }; devControlLog.Save(); UploadControlCommand(controlResult, fac[0].Facility); //上传控制指令 Thread.Sleep(50); }); }
private bool ShouldExtractFieldValue(ControlResult field) { return FieldNamesForExtraction.Contains(field.FieldName); }
// 设备指令发送 public static ControlResult DeviceControlService(ControlModel model) { ControlResult result = new ControlResult(); var channel = new Channel(GrpcChannelAddress, ChannelCredentials.Insecure); var client = new gRPCClient(channel); switch (model.Name) { case "TurnOnLoopValve01": result = client.TurnOnLoopValve01(model.WriteCommand); break; case "TurnOffLoopValve01": result = client.TurnOffLoopValve01(model.WriteCommand); break; case "TurnOnLoopValve02": result = client.TurnOnLoopValve02(model.WriteCommand); break; case "TurnOffLoopValve02": result = client.TurnOffLoopValve02(model.WriteCommand); break; case "TurnOnOutValve01": result = client.TurnOnOutValve01(model.WriteCommand); break; case "TurnOffOutValve01": result = client.TurnOffOutValve01(model.WriteCommand); break; case "TurnOnOutValve02": result = client.TurnOnOutValve02(model.WriteCommand); break; case "TurnOffOutValve02": result = client.TurnOffOutValve02(model.WriteCommand); break; case "TurnOnPump01": result = client.TurnOnPump01(model.WriteCommand); break; case "TurnOffPump01": result = client.TurnOffPump01(model.WriteCommand); break; case "TurnOnPump02": result = client.TurnOnPump02(model.WriteCommand); break; case "TurnOffPump02": result = client.TurnOffPump02(model.WriteCommand); break; case "OperateDevice": result = client.OperateDevice(model.WriteCommand); break; default: break; } return(result); }
private RemotePlayContext SendStreamInfo(Socket udpClient, Session session, RemotePlayContext remotePlayContext) { /******** Stream info receive ********/ ControlResult resolutionInfoPayload = WaitForControlMessage(udpClient, 1, "Wait for stream info payload").Result; if (!resolutionInfoPayload.WasSuccessful) { if (remotePlayContext.LastSentMessage.Length > 0) { resolutionInfoPayload = SendControlDataAndWaitForAnswer(udpClient, remotePlayContext.LastSentMessage, 1, "Resend bang ack control message and wait for stream info payload"); if (!resolutionInfoPayload.WasSuccessful) { return(null); } } else { return(null); } } ControlMessage resolutionInfoControlMessage = resolutionInfoPayload.ControlMessages[0]; TakionMessage resolutionPayload = Serializer.Deserialize <TakionMessage>(new MemoryStream(resolutionInfoControlMessage.UnParsedPayload)); if (resolutionPayload.streamInfoPayload == null) { return(null); } remotePlayContext.StreamInfoPayload = resolutionPayload.streamInfoPayload; byte[] ackResolutionInfoPayload = HexUtil.Unhexlify("00000000"); ushort ackResolutionInfoSize = (ushort)(12 + ackResolutionInfoPayload.Length); ControlMessage ackResolutionInfoControlMessage = new ControlMessage((byte)0, remotePlayContext.ReceiverId, 0, 0, 3, 0, ackResolutionInfoSize, resolutionInfoControlMessage.FuncIncr, 0x19000); ackResolutionInfoControlMessage.UnParsedPayload = ackResolutionInfoPayload; byte[] ackResolutionInfoControlMessageData = GetByteArrayForControlMessage(ackResolutionInfoControlMessage); remotePlayContext.LastSentMessage = ackResolutionInfoControlMessageData; SendCryptedControlMessage(ackResolutionInfoControlMessage, remotePlayContext, udpClient); // ToDo handle when there is no further response and and resolution info is sent again //SendData(udpClient, ackResolutionInfoControlMessageData); /******** Stream info ack send ********/ remotePlayContext.LastSentMessage = new byte[0]; byte[] streamInfoAckPayload = HexUtil.Unhexlify("00080e"); ushort streamInfoAckPayloadSize = (ushort)(12 + streamInfoAckPayload.Length); ControlMessage streamInfoAckControlMessage = new ControlMessage((byte)0, remotePlayContext.ReceiverId, 0, 0, 0, 1, streamInfoAckPayloadSize, remotePlayContext.FuncIncr, 0x90000); streamInfoAckControlMessage.UnParsedPayload = streamInfoAckPayload; ControlResult controlResult = SendCryptedControlMessageAndWaitForAnswer(streamInfoAckControlMessage, remotePlayContext, udpClient, 1, "Sending stream info ack message" + Environment.NewLine); if (!controlResult.WasSuccessful) { const int retry = 0; for (int i = 0; i < retry; i++) { SendData(udpClient, remotePlayContext.LastSentMessage); controlResult = SendCryptedControlMessageAndWaitForAnswer(streamInfoAckControlMessage, remotePlayContext, udpClient, 1, "Resend stream info ack message" + Environment.NewLine); if (controlResult.WasSuccessful) { break; } } } if (!controlResult.WasSuccessful) { return(null); } return(remotePlayContext); }
private static ControlResult CreateNewControlResultWithEmptyValue(ControlResult field) { ControlResult controlResult = new ControlResult(field.FieldName, string.Empty, string.Empty); controlResult.FieldID = field.FieldID; return controlResult; }
private void TryArrangeDetail(ControlResult control) { if (control != null) { detailRegion.Content = control.Control; } else { detailRegion.RemoveFromParent(); } }
private void TryArrangeMain(ControlResult control) { if (control != null) { listRegion.Content = control.Control; } else { listRegion.RemoveFromParent(); } }
private void TryArrangeNavigation(ControlResult control) { if (control != null) { dcNavigate.Content = control.Control; } else { dcNavigate.RemoveFromParent(); } }
public Region(string name, string childrenLabel, ControlResult control) : this(name, control) { this.ChildrenLabel = childrenLabel; }
public static void DoCheck(Message message) { foreach (var plugin in CacheData.PreControlsPlugins) { if (!plugin.Execute(message, MessageQueueManager.EnqueueMessage, Bot.Manager.BotClient)) { return; } } foreach (IControl control in controls) { ControlResult result = control.DoCheck(message); if (result.Result == IControl.ControlResultType.positive) { var actionToTake = CacheData.GroupConfigs[message.Chat.Id] .SingleOrDefault(x => x.ConfigurationParameterId == "SpamAction"); if (actionToTake == null) { RemoveMessageForPositiveControl(message, result); return; } switch (actionToTake.Value) { case "delete": RemoveMessageForPositiveControl(message, result); break; case "limit": LimitUserForPositiveControl(message, result); break; case "ban": BanUserForPositiveControl(message, result); break; } return; } } foreach (var plugin in CacheData.PostControlsPlugins) { if (!plugin.Execute(message, MessageQueueManager.EnqueueMessage, Bot.Manager.BotClient)) { return; } } foreach (var plugin in CacheData.PreFiltersPlugins) { if (!plugin.Execute(message, MessageQueueManager.EnqueueMessage, Bot.Manager.BotClient)) { return; } } foreach (Filters.IFilter filter in filters) { Filters.FilterResult result = filter.DoCheck(message); if (result.Result == Filters.IFilter.FilterResultType.positive) { var actionToTake = CacheData.GroupConfigs[message.Chat.Id] .SingleOrDefault(x => x.ConfigurationParameterId == "SpamAction"); if (actionToTake == null) { RemoveMessageForPositiveFilter(message, result); return; } switch (actionToTake.Value) { case "delete": RemoveMessageForPositiveFilter(message, result); break; case "limit": LimitUserForPositiveFilter(message, result); break; case "ban": BanUserForPositiveFilter(message, result); break; } return; } } foreach (var plugin in CacheData.PostFiltersPlugins) { if (!plugin.Execute(message, MessageQueueManager.EnqueueMessage, Bot.Manager.BotClient)) { return; } } }
private static void LimitUserForPositiveControl(Message message, ControlResult result) { int limitTime = 3; Models.Group.ConfigurationParameter configValue = CacheData.GroupConfigs[message.Chat.Id] .Where(x => x.ConfigurationParameterId == "SpamActionLimitTime") .SingleOrDefault(); if (configValue != null) { int.TryParse(configValue.Value, out limitTime); } RemoveMessageForPositiveControl(message, result); Bot.Manager.BotClient.RestrictChatMemberAsync( message.Chat.Id, message.From.Id, new ChatPermissions() { CanSendMessages = false, CanAddWebPagePreviews = false, CanChangeInfo = false, CanInviteUsers = false, CanPinMessages = false, CanSendMediaMessages = false, CanSendOtherMessages = false, CanSendPolls = false }, DateTime.UtcNow.AddMinutes(limitTime)); string author = message.From.Username == null ? message.From.FirstName + " " + message.From.LastName : "@" + message.From.Username; string logMessage = String.Format( "*[Report]*\n" + "User limited as per group _Spam Action_ preference.\n" + "⚠ do not open links you don't know ⚠\n" + "\nControl: `{0}`" + "\nChat: `{1}`" + "\nAuthor: `{2}`" + "\nUserId: `{3}`" + "\n\n*hash_code:* #UB{4}-{5}", result.CheckName, message.Chat.Title, author, message.From.Id, message.Chat.Id.ToString().Replace("-", ""), Guid.NewGuid()); MessageQueueManager.EnqueueLog(new ChatMessage() { ParseMode = ParseMode.Markdown, Text = logMessage }); LogTools.AddActionLog(new ActionLog() { GroupId = CacheData.Groups[message.Chat.Id].GroupId, UtcDate = DateTime.UtcNow, ActionTypeId = "autoLimit", Parameters = logMessage, }); }
private AdaptedControlResult GetControlResult(string fieldValue, FieldItem fieldItem) { //Populate fields with values ControlResult controlResult = new ControlResult(fieldItem.Name, HttpUtility.UrlDecode(fieldValue), string.Empty) { FieldID = fieldItem.ID.ToString(), FieldName = fieldItem.Name, Value = HttpUtility.UrlDecode(fieldValue), Parameters = string.Empty }; return new AdaptedControlResult(controlResult, true); }
private void TryArrangeCommandsContainer(ControlResult toolBar) { if (toolBar != null) { toolBarContainer.Content = toolBar.Control; } }
private RemotePlayContext SendBigBangMessages(Socket udpClient, Session session, RemotePlayContext remotePlayContext) { /******** Big Payload send ********/ // Generate random handshake key, for ECDH pubkey signature calculation byte[] handshakeKey = new byte[16]; new Random().NextBytes(handshakeKey); // Generate ECDH keypair var ecdhKeyPair = CryptoService.GenerateEcdhKeyPair(); // Get public key bytes var ownPublicKey = Session.GetPublicKeyBytesFromKeyPair(ecdhKeyPair); // Calculate ECDH pubkey signature var ecdhSignature = Session.CalculateHMAC(handshakeKey, ownPublicKey); int unixTimestamp = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; string timestampUnix = unixTimestamp.ToString(); string sessionKey = timestampUnix + CryptoService.GetUniqueKey(64); LaunchSpecification launchSpecs = LaunchSpecification.GetStandardSpecs("sessionId123", handshakeKey); byte[] launchSpecBuffer = Encoding.UTF8.GetBytes(launchSpecs.Serialize()); byte[] cryptoBuffer = new byte[launchSpecBuffer.Length]; cryptoBuffer = session.Encrypt(cryptoBuffer, 0); byte[] newLaunchSpec = new byte[launchSpecBuffer.Length]; for (int i = 0; i < launchSpecBuffer.Length; i++) { newLaunchSpec[i] = (byte)(launchSpecBuffer[i] ^ cryptoBuffer[i]); } TakionMessage takionBigPayloadMessage = new TakionMessage { Type = TakionMessage.PayloadType.Big, bigPayload = new BigPayload { clientVersion = 9, sessionKey = sessionKey, launchSpec = Convert.ToBase64String(newLaunchSpec), encryptedKey = new byte[] { 0, 0, 0, 0 }, ecdhPubKey = ownPublicKey, ecdhSig = ecdhSignature } }; MemoryStream bigPayloadStream = new MemoryStream(); Serializer.Serialize(bigPayloadStream, takionBigPayloadMessage); byte[] bigPayloadBuffer = ByteUtil.ConcatenateArrays(new byte[1], bigPayloadStream.ToArray()); // Padding byte + BigPayload ushort bigPayloadSize = (ushort)(12 + bigPayloadBuffer.Length); ControlMessage controlMessageBigPayload = new ControlMessage(0, remotePlayContext.ReceiverId, 0, 0, 0, 1, bigPayloadSize, remotePlayContext.FuncIncr, 0x10000); controlMessageBigPayload.UnParsedPayload = bigPayloadBuffer; byte[] initialControlMessage2Data = GetByteArrayForControlMessage(controlMessageBigPayload); OnPs4LogInfo?.Invoke(this, Environment.NewLine + "Sending big payload:"); OnPs4LogInfo?.Invoke(this, "ECDH pubkey: " + HexUtil.Hexlify(takionBigPayloadMessage.bigPayload.ecdhPubKey)); OnPs4LogInfo?.Invoke(this, "ECDH sig: " + HexUtil.Hexlify(takionBigPayloadMessage.bigPayload.ecdhSig)); OnPs4LogInfo?.Invoke(this, "Session key: " + takionBigPayloadMessage.bigPayload.sessionKey + Environment.NewLine); ControlResult bigPayloadResult = SendControlDataAndWaitForAnswer(udpClient, initialControlMessage2Data, 2, "Send BigPayload"); if (!bigPayloadResult.WasSuccessful) { return(null); } /******** Bang Payload receive ********/ ControlMessage answerPacket1 = bigPayloadResult.ControlMessages[0]; ControlMessage answerPacket2 = bigPayloadResult.ControlMessages[1]; if (answerPacket1.ProtoBuffFlag != 1 && answerPacket2.ProtoBuffFlag != 1) { return(null); } TakionMessage bangPayload = answerPacket1.ProtoBuffFlag == 1 ? Serializer.Deserialize <TakionMessage>(new MemoryStream(answerPacket1.UnParsedPayload)) : Serializer.Deserialize <TakionMessage>(new MemoryStream(answerPacket2.UnParsedPayload)); if (bangPayload.bangPayload == null) { return(null); } ControlMessage bangPayloadControl = answerPacket1.ProtoBuffFlag == 1 ? answerPacket1 : answerPacket2; OnPs4LogInfo?.Invoke(this, Environment.NewLine + "Received bang payload:"); OnPs4LogInfo?.Invoke(this, "ECDH pubkey: " + HexUtil.Hexlify(bangPayload.bangPayload.ecdhPubKey)); OnPs4LogInfo?.Invoke(this, "ECDH sig: " + HexUtil.Hexlify(bangPayload.bangPayload.ecdhSig)); OnPs4LogInfo?.Invoke(this, "Session key: " + bangPayload.bangPayload.sessionKey); /* Derive ECDH shared secret */ var foreignPubkeyParams = Session.ConvertPubkeyBytesToCipherParams(bangPayload.bangPayload.ecdhPubKey); remotePlayContext.SharedSecret = Session.GenerateSharedSecret(ecdhKeyPair.Private, foreignPubkeyParams); remotePlayContext.LocalGmacInfo = CryptoService.SetUpGmac(2, handshakeKey, remotePlayContext.SharedSecret); remotePlayContext.RemoteGmacInfo = CryptoService.SetUpGmac(3, handshakeKey, remotePlayContext.SharedSecret); OnPs4LogInfo?.Invoke(this, "HANDSHAKE KEY: " + HexUtil.Hexlify(handshakeKey)); OnPs4LogInfo?.Invoke(this, "SHARED SECRET: " + HexUtil.Hexlify(remotePlayContext.SharedSecret)); byte[] ackBangPayload = HexUtil.Unhexlify("00000000"); ushort ackBangPayloadSize = (ushort)(12 + ackBangPayload.Length); ControlMessage ackBangPayloadMessage = new ControlMessage(0, bangPayloadControl.FuncIncr, 0, 0, 3, 0, ackBangPayloadSize, bangPayloadControl.FuncIncr, 0x19000); ackBangPayloadMessage.UnParsedPayload = ackBangPayload; byte[] ackBangPayloadMessageData = GetByteArrayForControlMessage(ackBangPayloadMessage); remotePlayContext.LastSentMessage = ackBangPayloadMessageData; SendData(udpClient, ackBangPayloadMessageData); return(remotePlayContext); }
protected override void OnUIGenerated(ControlResult ui) { ui.MainView.CastTo <QueryLogicalView>().TryExecuteQuery(); base.OnUIGenerated(ui); }
private static AdaptedControlResult GetExtractedValueField(ControlResult field) { return new AdaptedControlResult(CreateNewControlResultWithEmptyValue(field), true); }