public void Process(TextMessageReceived @event) { _repositoryForReceivedMessage.Insert(new ReceivedMessage { Id = @event.Id, Sender = @event.Sender, Text = @event.Text, Received = @event.Received, }); }
/// <inheritdoc/> public NotificationParsingResult Parse(TextMessageReceived notification) { var content = notification.Text; var fragments = content.Replace(" ", string.Empty).Split(Separators).Select(s => new NotificationFragment(s)); var result = new NotificationParsingResult(fragments); return(result); }
//TODO: Add a test that ensure that the right count is put in the right property //TODO: This should possibly be process once, since it should only happen the first time a text message is recieved public void Process(TextMessageReceived @event) { //TODO: Handle if parsing fails and send TextMessageParseFailed event var caseReportContent = TextMessageContentParser.Parse(@event.Message); var dataCollector = _dataCollectors.GetByPhoneNumber(@event.OriginNumber); if (caseReportContent.GetType() == typeof(SingleCaseReportContent)) { var singlecaseReport = caseReportContent as SingleCaseReportContent; _eventEmitter.Emit(Feature, new CaseReportReceived { Id = Guid.NewGuid(), DataCollectorId = dataCollector?.Id, HealthRiskId = _healthRisks.GetByReadableId(caseReportContent.HealthRiskId).Id, NumberOfFemalesUnder5 = singlecaseReport.Age <= 5 && singlecaseReport.Sex == Sex.Female ? 1 : 0, NumberOfFemalesOver5 = singlecaseReport.Age > 5 && singlecaseReport.Sex == Sex.Female ? 1 : 0, NumberOfMalesUnder5 = singlecaseReport.Age <= 5 && singlecaseReport.Sex == Sex.Male ? 1 : 0, NumberOfMalesOver5 = singlecaseReport.Age > 5 && singlecaseReport.Sex == Sex.Male ? 1 : 0, Latitude = @event.Latitude, Longitude = @event.Longitude, Timestamp = @event.Sent }); } else { var report = caseReportContent as MultipleCaseReportContent; _eventEmitter.Emit(Feature, new CaseReportReceived { Id = Guid.NewGuid(), DataCollectorId = dataCollector?.Id, HealthRiskId = _healthRisks.GetByReadableId(caseReportContent.HealthRiskId).Id, NumberOfFemalesUnder5 = report.FemalesUnder5, NumberOfFemalesOver5 = report.FemalesOver5, NumberOfMalesUnder5 = report.MalesUnder5, NumberOfMalesOver5 = report.MalesOver5, Latitude = @event.Latitude, Longitude = @event.Longitude, Timestamp = @event.Sent }); } //TODO: emit AnonymousCaseReportRecieved //Or should both events be emitted? //if (dataCollector == null) //{ // return; //} }
//TODO: Add test that sends TextMessageReceived events and verifies that the correct events are emitted public void Process(TextMessageReceived @event) { var message = _receivedTextMessages.GetById(@event.Id) ?? new ReceivedTextMessage(@event.Id); message.Keyword = @event.Keyword; message.Message = @event.Message; message.OriginNumber = @event.OriginNumber; message.ReceivedAtGatewayNumber = @event.ReceivedAtGatewayNumber; message.Sent = @event.Sent; message.Latitude = @event.Latitude; message.Longitude = @event.Longitude; _receivedTextMessages.Save(message); }
private void ClientOnOnMessageReceived(NewMessage obj) { try { _client.ConversationLookup.TryGetValue(obj.channel, out var conversation); _client.UserLookup.TryGetValue(obj.user, out var user); var chatType = BotChatType.Channel; var chatId = obj.channel; var chatName = obj.channel; if (conversation is Channel cnn) { chatType = cnn.is_group ? BotChatType.Group : BotChatType.Channel; chatName = cnn.name; } else if (conversation is DirectMessageConversation dmc) { chatType = BotChatType.Private; if (_client.UserLookup.TryGetValue(dmc.user, out var privateUser)) { chatName = privateUser.name; } else { chatName = dmc.user; } } var message = new BotTextMessage { Id = obj.id.ToString(), Date = obj.ts, Text = obj.text, Chat = new BotChat { ChatType = chatType, Id = chatId, Name = chatName }, User = new SlackBotUser { Id = user?.id ?? obj.user, Name = user?.name ?? obj.user, Color = user?.color, Presence = user?.presence, Email = user?.profile?.email, FirstName = user?.profile?.first_name, LastName = user?.profile?.last_name, RealName = user?.profile?.real_name, Skype = user?.profile?.skype, Phone = user?.profile?.phone } }; TextMessageReceived?.Invoke(this, new EventArgs <BotTextMessage>(message)); } catch (Exception ex) { Core.Log.Write(ex); } }
private void MessageLoop() { var packet = new List <byte>(); var messageOpcode = 0x0; using (var messageBuffer = new MemoryStream()) { while (_client.Connected) { packet.Clear(); var ab = _client.Available; if (ab == 0) { continue; } packet.Add((byte)_clientStream.ReadByte()); var fin = (packet[0] & (1 << 7)) != 0; var rsv1 = (packet[0] & (1 << 6)) != 0; var rsv2 = (packet[0] & (1 << 5)) != 0; var rsv3 = (packet[0] & (1 << 4)) != 0; // Must error if is set. //if (rsv1 || rsv2 || rsv3) // return; var opcode = packet[0] & ((1 << 4) - 1); switch (opcode) { case 0x0: // Continuation Frame break; case 0x1: // Text case 0x2: // Binary case 0x8: // Connection Close messageOpcode = opcode; break; case 0x9: continue; // Ping case 0xA: continue; // Pong default: continue; // Reserved } packet.Add((byte)_clientStream.ReadByte()); var masked = IsMasking = (packet[1] & (1 << 7)) != 0; var pseudoLength = packet[1] - (masked ? 128 : 0); ulong actualLength = 0; if (pseudoLength > 0 && pseudoLength < 125) { actualLength = (ulong)pseudoLength; } else if (pseudoLength == 126) { var length = new byte[2]; _clientStream.Read(length, 0, length.Length); packet.AddRange(length); Array.Reverse(length); actualLength = BitConverter.ToUInt16(length, 0); } else if (pseudoLength == 127) { var length = new byte[8]; _clientStream.Read(length, 0, length.Length); packet.AddRange(length); Array.Reverse(length); actualLength = BitConverter.ToUInt64(length, 0); } var mask = new byte[4]; if (masked) { _clientStream.Read(mask, 0, mask.Length); packet.AddRange(mask); } if (actualLength > 0) { var data = new byte[actualLength]; _clientStream.Read(data, 0, data.Length); packet.AddRange(data); if (masked) { data = ApplyMask(data, mask); } messageBuffer.Write(data, 0, data.Length); } LogRequest?.Invoke(this, new LogEventArgs($@"RECV: {BitConverter.ToString(packet.ToArray())}")); if (!fin) { continue; } var message = messageBuffer.ToArray(); switch (messageOpcode) { case 0x1: AnyMessageReceived?.Invoke(this, message); TextMessageReceived?.Invoke(this, Encoding.UTF8.GetString(message)); break; case 0x2: AnyMessageReceived?.Invoke(this, message); BinaryMessageReceived?.Invoke(this, Encoding.UTF8.GetString(message)); break; case 0x8: Close(); break; default: throw new Exception("Invalid opcode: " + messageOpcode); } messageBuffer.SetLength(0); } } }
private async void Bot_OnMessage(object sender, TBot.Args.MessageEventArgs e) { try { if (e.Message is null) { return; } switch (e.Message.Type) { case TBot.Types.Enums.MessageType.Text: if (string.IsNullOrWhiteSpace(e.Message.Text)) { return; } var message = new BotTextMessage { Id = e.Message.MessageId.ToString(), Date = e.Message.Date, Text = e.Message.Text, Chat = new TelegramBotChat { Id = e.Message.Chat.Id.ToString(), ChatType = (BotChatType)e.Message.Chat.Type, Name = e.Message.Chat.Title, Title = e.Message.Chat.Title, Username = e.Message.Chat.Username, FirstName = e.Message.Chat.FirstName, LastName = e.Message.Chat.LastName }, User = new TelegramBotUser { Id = e.Message.From.Id.ToString(), Name = e.Message.From.Username, FirstName = e.Message.From.FirstName, LastName = e.Message.From.LastName } }; TextMessageReceived?.Invoke(this, new EventArgs <BotTextMessage>(message)); break; case TBot.Types.Enums.MessageType.Photo: foreach (var photo in e.Message.Photo) { var photoFileInfo = await _bot.GetFileAsync(photo.FileId); var photoMessage = new BotPhotoMessage { Id = e.Message.MessageId.ToString(), Date = e.Message.Date, PhotoWidth = photo.Width, PhotoHeight = photo.Height, PhotoId = photo.FileId, PhotoSize = photo.FileSize, PhotoName = photoFileInfo.FilePath, PhotoStream = new Lazy <Stream>(() => { var ms = new MemoryStream(); _bot.DownloadFileAsync(photoFileInfo.FilePath, ms).WaitAsync(); return(ms); }), Chat = new TelegramBotChat { Id = e.Message.Chat.Id.ToString(), ChatType = (BotChatType)e.Message.Chat.Type, Name = e.Message.Chat.Title, Title = e.Message.Chat.Title, Username = e.Message.Chat.Username, FirstName = e.Message.Chat.FirstName, LastName = e.Message.Chat.LastName }, User = new TelegramBotUser { Id = e.Message.From.Id.ToString(), Name = e.Message.From.Username, FirstName = e.Message.From.FirstName, LastName = e.Message.From.LastName } }; PhotoMessageReceived?.Invoke(this, new EventArgs <BotPhotoMessage>(photoMessage)); } break; } } catch (Exception ex) { Core.Log.Write(ex); } }
//TODO: Add a test that ensure that the right count is put in the right property //TODO: This should possibly be process once, since it should only happen the first time a text message is recieved public void Process(TextMessageReceived @event) { var caseReportContent = TextMessageContentParser.Parse(@event.Message); var dataCollector = _dataCollectors.GetByPhoneNumber(@event.OriginNumber); if (caseReportContent.GetType() == typeof(InvalidCaseReportContent)) { //TODO: Handle if datacollector is unknown also. Different event? var invalidCaseReport = caseReportContent as InvalidCaseReportContent; _eventEmitter.Emit(Feature, new TextMessageParsingFailed { Id = Guid.NewGuid(), DataCollectorId = dataCollector.Id, Message = @event.Message, ParsingErrorMessage = invalidCaseReport.ErrorMessage }); } else if (caseReportContent.GetType() == typeof(SingleCaseReportContent)) { var singlecaseReport = caseReportContent as SingleCaseReportContent; var healthRisk = _healthRisks.GetByReadableId(singlecaseReport.HealthRiskId); if (dataCollector == null) { _eventEmitter.Emit(Feature, new AnonymousCaseReportRecieved { Id = Guid.NewGuid(), PhoneNumber = @event.OriginNumber, HealthRiskId = healthRisk.Id, NumberOfFemalesUnder5 = singlecaseReport.Age <= 5 && singlecaseReport.Sex == Sex.Female ? 1 : 0, NumberOfFemalesOver5 = singlecaseReport.Age > 5 && singlecaseReport.Sex == Sex.Female ? 1 : 0, NumberOfMalesUnder5 = singlecaseReport.Age <= 5 && singlecaseReport.Sex == Sex.Male ? 1 : 0, NumberOfMalesOver5 = singlecaseReport.Age > 5 && singlecaseReport.Sex == Sex.Male ? 1 : 0, Latitude = @event.Latitude, Longitude = @event.Longitude, Timestamp = @event.Sent }); return; } _eventEmitter.Emit(Feature, new CaseReportReceived { Id = Guid.NewGuid(), DataCollectorId = dataCollector.Id, HealthRiskId = healthRisk.Id, NumberOfFemalesUnder5 = singlecaseReport.Age <= 5 && singlecaseReport.Sex == Sex.Female ? 1 : 0, NumberOfFemalesOver5 = singlecaseReport.Age > 5 && singlecaseReport.Sex == Sex.Female ? 1 : 0, NumberOfMalesUnder5 = singlecaseReport.Age <= 5 && singlecaseReport.Sex == Sex.Male ? 1 : 0, NumberOfMalesOver5 = singlecaseReport.Age > 5 && singlecaseReport.Sex == Sex.Male ? 1 : 0, Latitude = @event.Latitude, Longitude = @event.Longitude, Timestamp = @event.Sent }); } else { var report = caseReportContent as MultipleCaseReportContent; var healthRisk = _healthRisks.GetByReadableId(report.HealthRiskId); if (dataCollector == null) { _eventEmitter.Emit(Feature, new AnonymousCaseReportRecieved { Id = Guid.NewGuid(), PhoneNumber = @event.OriginNumber, HealthRiskId = healthRisk.Id, NumberOfFemalesUnder5 = report.FemalesUnder5, NumberOfFemalesOver5 = report.FemalesOver5, NumberOfMalesUnder5 = report.MalesUnder5, NumberOfMalesOver5 = report.MalesOver5, Latitude = @event.Latitude, Longitude = @event.Longitude, Timestamp = @event.Sent }); return; } _eventEmitter.Emit(Feature, new CaseReportReceived { Id = Guid.NewGuid(), DataCollectorId = dataCollector.Id, HealthRiskId = healthRisk.Id, NumberOfFemalesUnder5 = report.FemalesUnder5, NumberOfFemalesOver5 = report.FemalesOver5, NumberOfMalesUnder5 = report.MalesUnder5, NumberOfMalesOver5 = report.MalesOver5, Latitude = @event.Latitude, Longitude = @event.Longitude, Timestamp = @event.Sent }); } }
public void Process(TextMessageReceived @event) { _logger.Warning($"TextMessageReceieved in VolunteerReporting. Add some action here :)"); }
public void Process(TextMessageReceived notification) { var transaction = _commandContextManager.EstablishForCommand(new Dolittle.Runtime.Commands.CommandRequest(Guid.NewGuid(), Guid.NewGuid(), 1, new Dictionary <string, object>())); var parsingResult = _textMessageParser.Parse(notification); // var filter = Builders<DataCollector>.Filter.AnyEq(c => c.PhoneNumbers, (PhoneNumber)phoneNumber); var isTextMessageFormatValid = parsingResult.IsValid; var dataCollector = _dataCollectors.Query.Where(_ => _.PhoneNumbers.Contains(new Concepts.DataCollectors.PhoneNumber() { Value = notification.Sender })).FirstOrDefault(); var unknownDataCollector = dataCollector == null; var caseReportId = Guid.NewGuid(); var caseReporting = _caseReportingRepository.Get(caseReportId); if (!isTextMessageFormatValid && unknownDataCollector) { caseReporting.ReportInvalidReportFromUnknownDataCollector( notification.Sender, notification.Text, parsingResult.ErrorMessages, notification.Received); transaction.Commit(); return; } if (!isTextMessageFormatValid && !unknownDataCollector) { caseReporting.ReportInvalidReport( dataCollector.Id, notification.Sender, notification.Text, dataCollector.Location.Longitude, dataCollector.Location.Latitude, parsingResult.ErrorMessages, notification.Received); transaction.Commit(); return; } var healthRiskReadableId = parsingResult.HealthRiskReadableId; var healthRiskId = _healthRisks.Query.Where(i => i.ReadableId == healthRiskReadableId).FirstOrDefault()?.Id; if (healthRiskId == null || healthRiskId == HealthRiskId.NotSet) { var errorMessages = new List <string> { $"Unable to find health risk, since there are no health risks with a readable id of {healthRiskReadableId}" }; if (unknownDataCollector) { caseReporting.ReportInvalidReportFromUnknownDataCollector( notification.Sender, notification.Text, errorMessages, notification.Received); transaction.Commit(); return; } caseReporting.ReportInvalidReport( dataCollector.Id, notification.Sender, notification.Text, dataCollector.Location.Longitude, dataCollector.Location.Latitude, errorMessages, notification.Received); transaction.Commit(); return; } if (unknownDataCollector) { caseReporting.ReportFromUnknownDataCollector( notification.Sender, healthRiskId.Value, parsingResult.MalesUnder5, parsingResult.MalesAged5AndOlder, parsingResult.FemalesUnder5, parsingResult.FemalesAged5AndOlder, notification.Received, notification.Text ); transaction.Commit(); return; } caseReporting.Report( dataCollector.Id, healthRiskId.Value, notification.Sender, parsingResult.MalesUnder5, parsingResult.MalesAged5AndOlder, parsingResult.FemalesUnder5, parsingResult.FemalesAged5AndOlder, dataCollector.Location.Longitude, dataCollector.Location.Latitude, notification.Received, notification.Text ); transaction.Commit(); }
public void OnTextMessage(TextMessageReceived handler) { textReceived = handler; CPP.Add("QObject::connect($q, &QWebSocket::textMessageReceived, [=] (QString msg) {this->SlotTextMessageReceived(new Qt::Core::String(msg));});"); }
private void MessageLoop() { WebSocketSession session = this; TcpClient client = session.Client; Stream stream = session.ClientStream; List <byte> packet = new List <byte>(); int messageOpcode = 0x0; using (MemoryStream messageBuffer = new MemoryStream()) while (client.Connected) { packet.Clear(); int ab = client.Available; if (ab == 0) { continue; } packet.Add((byte)stream.ReadByte()); bool fin = (packet[0] & (1 << 7)) != 0; bool rsv1 = (packet[0] & (1 << 6)) != 0; bool rsv2 = (packet[0] & (1 << 5)) != 0; bool rsv3 = (packet[0] & (1 << 4)) != 0; // Must error if is set. //if (rsv1 || rsv2 || rsv3) // return; int opcode = packet[0] & ((1 << 4) - 1); switch (opcode) { case 0x0: // Continuation Frame break; case 0x1: // Text case 0x2: // Binary case 0x8: // Connection Close messageOpcode = opcode; break; case 0x9: continue; // Ping case 0xA: continue; // Pong default: continue; // Reserved } packet.Add((byte)stream.ReadByte()); bool masked = (packet[1] & (1 << 7)) != 0; int pseudoLength = packet[1] - (masked ? 128 : 0); ulong actualLength = 0; if (pseudoLength > 0 && pseudoLength < 125) { actualLength = (ulong)pseudoLength; } else if (pseudoLength == 126) { byte[] length = new byte[2]; stream.Read(length, 0, length.Length); packet.AddRange(length); Array.Reverse(length); actualLength = BitConverter.ToUInt16(length, 0); } else if (pseudoLength == 127) { byte[] length = new byte[8]; stream.Read(length, 0, length.Length); packet.AddRange(length); Array.Reverse(length); actualLength = BitConverter.ToUInt64(length, 0); } byte[] mask = new byte[4]; if (masked) { stream.Read(mask, 0, mask.Length); packet.AddRange(mask); } if (actualLength > 0) { byte[] data = new byte[actualLength]; stream.Read(data, 0, data.Length); packet.AddRange(data); if (masked) { data = ApplyMask(data, mask); } messageBuffer.Write(data, 0, data.Length); } Console.WriteLine($@"RECV: {BitConverter.ToString(packet.ToArray())}"); if (!fin) { continue; } byte[] message = messageBuffer.ToArray(); switch (messageOpcode) { case 0x1: AnyMessageReceived?.Invoke(session, message); TextMessageReceived?.Invoke(session, Encoding.UTF8.GetString(message)); break; case 0x2: AnyMessageReceived?.Invoke(session, message); BinaryMessageReceived?.Invoke(session, Encoding.UTF8.GetString(message)); break; case 0x8: Close(); break; default: throw new Exception("Invalid opcode: " + messageOpcode); } messageBuffer.SetLength(0); } }
private void Bot_OnMessage(object sender, TBot.Args.MessageEventArgs e) { if (e.Message == null) { return; } switch (e.Message.Type) { case TBot.Types.Enums.MessageType.TextMessage: if (string.IsNullOrWhiteSpace(e.Message.Text)) { return; } var message = new BotTextMessage { Id = e.Message.MessageId.ToString(), Date = e.Message.Date, Text = e.Message.Text, Chat = new TelegramBotChat { Id = e.Message.Chat.Id.ToString(), ChatType = (BotChatType)e.Message.Chat.Type, Name = e.Message.Chat.Title, Title = e.Message.Chat.Title, Username = e.Message.Chat.Username, FirstName = e.Message.Chat.FirstName, LastName = e.Message.Chat.LastName }, User = new TelegramBotUser { Id = e.Message.From.Id.ToString(), Name = e.Message.From.Username, FirstName = e.Message.From.FirstName, LastName = e.Message.From.LastName } }; TextMessageReceived?.Invoke(this, new EventArgs <BotTextMessage>(message)); break; case TBot.Types.Enums.MessageType.PhotoMessage: foreach (var photo in e.Message.Photo) { var photoMessage = new BotPhotoMessage { Id = e.Message.MessageId.ToString(), Date = e.Message.Date, PhotoWidth = photo.Width, PhotoHeight = photo.Height, PhotoId = photo.FileId, PhotoSize = photo.FileSize, PhotoName = photo.FilePath, PhotoStream = new Lazy <Stream>(() => { var file = _bot.GetFileAsync(photo.FileId).WaitAndResults(); return(file.FileStream); }), Chat = new TelegramBotChat { Id = e.Message.Chat.Id.ToString(), ChatType = (BotChatType)e.Message.Chat.Type, Name = e.Message.Chat.Title, Title = e.Message.Chat.Title, Username = e.Message.Chat.Username, FirstName = e.Message.Chat.FirstName, LastName = e.Message.Chat.LastName }, User = new TelegramBotUser { Id = e.Message.From.Id.ToString(), Name = e.Message.From.Username, FirstName = e.Message.From.FirstName, LastName = e.Message.From.LastName } }; PhotoMessageReceived?.Invoke(this, new EventArgs <BotPhotoMessage>(photoMessage)); } break; } }