Exemplo n.º 1
0
        /// <summary>Adds a message to the in-game display</summary>
        /// <param name="message">The message to add</param>
        internal static void AddMessage(AbstractMessage message)
        {
            if (TrainManager.PlayerTrain.StationState == TrainStopState.Jumping)
            {
                //Ignore messages triggered during a jump
                return;
            }
            if (message is MarkerImage || message is TextureMessage)
            {
                for (int i = 0; i < ImageMessages.Count; i++)
                {
                    if (ImageMessages[i] == message)
                    {
                        return;
                    }
                }
                message.AddMessage(Game.SecondsSinceMidnight);
                ImageMessages.Add(message);
                return;
            }

            for (int i = 0; i < TextualMessages.Count; i++)
            {
                if (TextualMessages[i] == message)
                {
                    //Other messages display one per message
                    return;
                }
            }
            //Prep: May be needed to trigger text replacement etc.
            message.AddMessage(Game.SecondsSinceMidnight);
            //Add to the start of the list
            TextualMessages.Insert(0, message);
        }
Exemplo n.º 2
0
 public virtual void SendAsync(AbstractMessage message)
 {
     this.sendDone.WaitOne();
     byte[] buffer = message.GetEnvelope();
     Trace.WriteLine(string.Format("Sending asynch message {0} len {1}", message.MessageUID, message.MessageLength));
     this.socket.BeginSend(buffer, this, SendCallback);
 }
Exemplo n.º 3
0
        private void C_OmemoSessionBuildError(XMPPClient client, OmemoSessionBuildErrorEventArgs args)
        {
            Task.Run(() =>
            {
                ChatTable chat = ChatDBManager.INSTANCE.getChat(ChatTable.generateId(args.CHAT_JID, client.getXMPPAccount().getBareJid()));
                if (!(chat is null))
                {
                    // Add an error chat message:
                    ChatMessageTable msg = new ChatMessageTable()
                    {
                        id       = ChatMessageTable.generateErrorMessageId(AbstractMessage.getRandomId(), chat.id),
                        chatId   = chat.id,
                        date     = DateTime.Now,
                        fromUser = args.CHAT_JID,
                        isImage  = false,
                        message  = "Failed to encrypt and send " + args.MESSAGES.Count + " OMEMO message(s) with:\n" + args.ERROR,
                        state    = MessageState.UNREAD,
                        type     = MessageMessage.TYPE_ERROR
                    };
                    ChatDBManager.INSTANCE.setChatMessage(msg, true, false);

                    // Set chat messages to encrypted failed:
                    setOmemoChatMessagesSendFailed(args.MESSAGES, chat);
                }
            });
        }
Exemplo n.º 4
0
 public void SendToAll(AbstractMessage message)
 {
     foreach (Player player in Controller.GetInstance().GetPlayers())
     {
         SendData(player.IPAddress, message);
     }
 }
Exemplo n.º 5
0
        public void SendData(IPAddress address, AbstractMessage message)
        {
            try
            {
                byte[] data, len;

                message.Guid = guid;

                MemoryStream    memoryStream    = new MemoryStream();
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(memoryStream, message);
                memoryStream.Close();

                len  = new byte[Core.RECEIVE_BUFFER_SIZE];
                data = memoryStream.ToArray();
                Encoding.ASCII.GetBytes(data.Length.ToString()).CopyTo(len, 0);

                Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sock.Connect(address, clientPort);
                sock.Send(len);
                sock.Send(data);
                sock.Close();
            }
            catch
            {
                ConnectionLost(Controller.GetInstance().GetPlayer(address));
            }
        }
Exemplo n.º 6
0
        //--------------------------------------------------------Events:---------------------------------------------------------------------\\
        #region --Events--
        private void OnOmemoSessionBuildError(XMPPClient xmppClient, OmemoSessionBuildErrorEventArgs args)
        {
            Task.Run(async() =>
            {
                ChatModel chat;
                using (SemaLock semaLock = DataCache.INSTANCE.NewChatSemaLock())
                {
                    chat = DataCache.INSTANCE.GetChat(xmppClient.getXMPPAccount().getBareJid(), args.CHAT_JID, semaLock);
                }
                if (!(chat is null))
                {
                    // Add an error chat message:
                    ChatMessageModel msg = new ChatMessageModel()
                    {
                        chatId         = chat.id,
                        date           = DateTime.Now,
                        fromBareJid    = args.CHAT_JID,
                        isCC           = false,
                        isDummyMessage = false,
                        isEncrypted    = false,
                        isFavorite     = false,
                        isImage        = false,
                        message        = "Failed to encrypt and send " + args.MESSAGES.Count + " OMEMO message(s) with:\n" + args.ERROR,
                        stableId       = AbstractMessage.getRandomId(),
                        state          = MessageState.UNREAD,
                        type           = MessageMessage.TYPE_ERROR
                    };
                    await DataCache.INSTANCE.AddChatMessageAsync(msg, chat);

                    // Set chat messages to encrypted failed:
                    SetOmemoChatMessagesSendFailed(args.MESSAGES, chat);
                }
            });
        }
Exemplo n.º 7
0
        /// <summary>
        /// Création d'un message vierge.
        /// </summary>
        /// <param name="eventType">Code de l'événement (A28, A01, ...).</param>
        /// <param name="eventOperator">Informations de la personne à l'origine de l'événement.</param>
        /// <returns></returns>
        public AbstractMessage CreateMessage(string eventType, object eventOperator)
        {
            AbstractMessage msgHL7 = null;

            if (string.IsNullOrWhiteSpace(eventType))
            {
                throw new ArgumentNullException(nameof(eventType));
            }

            if (!EventType.Description.ContainsKey(eventType))
            {
                throw new EncodingException($"L'événement '{eventType}' n'est pas implémenté par '{TypeUtil.GetTypeName(this)}'.");
            }

            switch (eventType)
            {
            case EventType.A28:
            {
                msgHL7 = new ADT_A28(this._options.EncodingChars, eventOperator);
                break;
            }

            default:
            {
                throw new EncodingException($"L'événement '{eventType}' n'est pas implémenté par '{TypeUtil.GetTypeName(this)}'.");
            }
            }

            return(msgHL7);
        }
Exemplo n.º 8
0
        protected override async Task processMessageAsync(NewValidMessageEventArgs args)
        {
            if (!STREAM_MANAGEMENT_ENABLED)
            {
                return;
            }

            AbstractMessage msg = args.MESSAGE;

            switch (state)
            {
            case SMState.DISABLED:
                if (msg is StreamFeaturesMessage || msg is OpenStreamAnswerMessage)
                {
                    StreamFeaturesMessage features = null;
                    if (msg is OpenStreamAnswerMessage)
                    {
                        features = (msg as OpenStreamAnswerMessage).getStreamFeaturesMessage();
                    }
                    else
                    {
                        features = msg as StreamFeaturesMessage;
                    }

                    if (features == null)
                    {
                        return;
                    }
                    if (features.containsFeature("sm"))
                    {
                        setMessageProcessed(args);
                        SMEnableMessage enableMsg = new SMEnableMessage();
                        await XMPP_CONNECTION.sendAsync(enableMsg, false, true);

                        serverSMEnabled = true;
                        state           = SMState.REQUESTED;
                    }
                }
                break;

            case SMState.REQUESTED:
                if (msg is SMEnableMessage enableAnswMsg)
                {
                    setMessageProcessed(args);
                    // Update connection information:
                    state           = SMState.ENABLED;
                    clientSMEnabled = true;
                    stopListeningForMessages();
                }
                else if (msg is SMFailedMessage failedMsg)
                {
                    setMessageProcessed(args);

                    // Handle errors:
                    state = SMState.ERROR;
                    stopListeningForMessages();
                }
                break;
            }
        }
Exemplo n.º 9
0
 private bool updateDevicesIfNeededMsg(AbstractMessage msg)
 {
     if (msg is IQErrorMessage errMsg)
     {
         Logger.Error("[OMEMO HELPER](" + CONNECTION.account.getIdAndDomain() + ") Failed to set OMEMO device list to: " + CONNECTION.account.user.domain + "\n" + errMsg.ERROR_OBJ.ToString());
         setState(OmemoHelperState.ERROR);
         return(true);
     }
     else if (msg is IQMessage)
     {
         Logger.Info("[OMEMO HELPER](" + CONNECTION.account.getIdAndDomain() + ") Device list updated.");
         if (CONNECTION.account.omemoDeviceId == 0)
         {
             CONNECTION.account.omemoDeviceId = tmpDeviceId;
             CONNECTION.account.onPropertyChanged(nameof(CONNECTION.account.omemoDeviceId));
         }
         if (!CONNECTION.account.omemoBundleInfoAnnounced)
         {
             announceBundleInfo();
         }
         else
         {
             setState(OmemoHelperState.ENABLED);
         }
         return(true);
     }
     return(false);
 }
Exemplo n.º 10
0
            public override void Print(AbstractMessage msg, bool showFullPath)
            {
                var line   = 0;
                var column = 0;

                try
                {
                    line   = msg.Location.Row;
                    column = msg.Location.Column;
                }
                catch
                {
                    //Log (ex);
                }
                var m = new EvalMessage
                {
                    MessageType = msg.MessageType,
                    Text        = msg.Text,
                    Line        = line,
                    Column      = column,
                };

                Messages.Add(m);

                //
                // Print it to the console if there's an error
                //
                if (msg.MessageType == "error")
                {
                    var tm = msg.Text;
                    System.Threading.ThreadPool.QueueUserWorkItem(_ =>
                                                                  Console.WriteLine("ERROR: {0}", tm));
                }
            }
Exemplo n.º 11
0
        private async Task ParseAndShowNotificationAsync(string s, ToastNotification progressToast, BindableString statusText)
        {
            UpdateProgress(progressToast, statusText, "Started");
            if (string.IsNullOrEmpty(s))
            {
                Logger.Warn("Received an empty push notification...");
                return;
            }
            Logger.Trace(s);

            AbstractMessage msg = MessageParser.Parse(s);

            if (msg is null)
            {
                Logger.Warn("Invalid push message received: " + s);
                return;
            }
            UpdateProgress(progressToast, statusText, "Parsed");

            if (msg is TestPushMessage)
            {
                ToastHelper.ShowSimpleToast("Here is your test push message. It got successfully received from the push server!🎉");
                Logger.Info("Test push message received.");
                return;
            }
            else if (msg is PushMessage pushMsg)
            {
                await HandelPushMessageAsync(pushMsg, progressToast, statusText);
            }
            else
            {
                Logger.Warn("Invalid push message action received: " + msg.action);
                return;
            }
        }
Exemplo n.º 12
0
        public MessageDecoderResult Decode(IoSession session, IoBuffer input, IProtocolDecoderOutput output)
        {
            // Try to skip header if not read.
            if (!_readHeader)
            {
                input.GetInt16();               // Skip 'type'.
                _sequence   = input.GetInt32(); // Get 'sequence'.
                _readHeader = true;
            }

            // Try to decode body
            AbstractMessage m = DecodeBody(session, input);

            // Return NEED_DATA if the body is not fully read.
            if (m == null)
            {
                return(MessageDecoderResult.NeedData);
            }
            else
            {
                _readHeader = false; // reset readHeader for the next decode
            }
            m.Sequence = _sequence;
            output.Write(m);

            return(MessageDecoderResult.OK);
        }
Exemplo n.º 13
0
 public MarkerEndEvent(double TrackPositionDelta, AbstractMessage Message, HostInterface Host)
 {
     this.TrackPositionDelta = TrackPositionDelta;
     DontTriggerAnymore      = false;
     message     = Message;
     currentHost = Host;
 }
Exemplo n.º 14
0
        public void CheckKilledOtherRegex_KilledOtherMessageWithHeadshotPenetratedAsInput_ExpectedCorrectConstructionOfObject()
        {
            string input = "\"WeedMonkey<67><STEAM_1:1:84194999><TERRORIST>\" [341 -429 96] killed other \"chicken<194>\" [344 -451 96] with \"knife_t\" (headshot penetrated)";

            var             regex           = new KilledOtherRegex();
            AbstractMessage abstractMessage = regex.Parse(input);

            Assert.NotNull(abstractMessage);
            var killedOtherMessage = (KilledOtherMessage)abstractMessage;

            Assert.Equal("WeedMonkey", killedOtherMessage.UserName);
            Assert.Equal("67", killedOtherMessage.UserID);
            Assert.Equal("STEAM_1:1:84194999", killedOtherMessage.UserSteamID);
            Assert.Equal("TERRORIST", killedOtherMessage.UserTeam);
            Assert.Equal(341, killedOtherMessage.UserPosX);
            Assert.Equal(-429, killedOtherMessage.UserPosY);
            Assert.Equal(96, killedOtherMessage.UserPosZ);
            Assert.Equal("chicken", killedOtherMessage.KilledOtherName);
            Assert.Equal("194", killedOtherMessage.KilledOtherID);
            Assert.Equal(344, killedOtherMessage.KilledUserPosX);
            Assert.Equal(-451, killedOtherMessage.KilledUserPosY);
            Assert.Equal(96, killedOtherMessage.KilledUserPosZ);
            Assert.Equal("knife_t", killedOtherMessage.Weapon);
            Assert.True(killedOtherMessage.IsHeadshot);
            Assert.True(killedOtherMessage.IsPenetrated);
        }
Exemplo n.º 15
0
 public void DataArrival(String address, AbstractMessage message)
 {
     if (message is SelectServerMessage)
     {
         HandleSelectServerMessage(address, message);
     }
     else if (message is CharacterSelectionMessage)
     {
         HandleCharacterSelectionMessage(address, message);
     }
     else if (message is WaitingOponentMessage)
     {
         HandleWaitingOponentMessage(address, message);
     }
     else if (message is StartGameMessage)
     {
         HandleStartGameMessage(address, message);
     }
     else if (message is CharacterPositionMessage)
     {
         HandleCharacterPositionMessage(address, message);
     }
     else if (message is StartBattleMessage)
     {
         HandleStartBattleMessage(address, message);
     }
     else if (message is UpdateMessage)
     {
         HandleUpdateMessage(address, message);
     }
     else if (message is TurnMessage)
     {
         HandleTurnMessage(address, message);
     }
     else if (message is AffectsMessage)
     {
         HandleAffectsMessage(address, message);
     }
     else if (message is ChatMessage)
     {
         HandleChatMessage(address, message);
     }
     else if (message is EndGameMessage)
     {
         HandleEndGameMessage(address, message);
     }
     else if (message is PingMessage)
     {
         HandlePingMessage(address, message);
     }
     else if (message is InvalidGuidMessage)
     {
         HandleInvalidGuidMessage(address, message);
     }
     else if (message is LeaveMessage)
     {
         HandleLeaveMessage(address, message);
     }
 }
Exemplo n.º 16
0
 /// <summary>
 /// Send a message
 /// </summary>
 /// <param name="message">The message to send</param>
 /// <returns>True if the message has been sent, otherwise false</returns>
 public bool Send(AbstractMessage message)
 {
     if (handler == null)
     {
         return(false);
     }
     return(handler.Send(message));
 }
        /// <summary>
        /// Send a buffer. It's a synchronous operation. The previous send has to be completed.
        /// You can define a timeout on the previous send and skip this one in case of time out.
        /// </summary>
        /// <param name="message">The message to send</param>
        /// <param name="previousSendTimeout">Timeout on the previous send in ms</param>
        /// <returns>True if the message has been sent, otherwise false</returns>
        internal bool SendMessage(AbstractMessage message, int previousSendTimeout)
        {
            byte[] buffer = message.GetEnvelope();
            Trace.WriteLine(string.Format("Sending message, len {0}", message.MessageLength));
            bool r = SendBuffer(this, buffer, previousSendTimeout);

            return(r);
        }
Exemplo n.º 18
0
 public virtual void SendMessage(List <Guid> userList, AbstractMessage resp = null)
 {
     if (resp == null)
     {
         resp = this.response;
     }
     sender.SendMessage(userList, resp);
 }
Exemplo n.º 19
0
        private static string GetFormattedLogMessage(AbstractMessage message)
        {
            var path   = GetSourcePath(message);
            var row    = message.Location.Row;
            var column = message.Location.Column;

            return(string.Format("{0} ({1},{2}): {3}", path.FullPath, row, column, message.Text));
        }
Exemplo n.º 20
0
    private void handleHCUpdate(AbstractMessage message)
    {
        HCMessage hcMessage = message as HCMessage;

        gameModel.User.HC += hcMessage.Amount;
        Messenger.Dispatch(HCMessage.UPDATED);
        updateView();
    }
Exemplo n.º 21
0
 /// <summary>
 /// Send asynchronous message
 /// </summary>
 /// <param name="message">The message to send</param>
 public void SendAsync(AbstractMessage message)
 {
     if (handler == null)
     {
         return;
     }
     handler.SendAsync(message);
 }
Exemplo n.º 22
0
 public override void Print(AbstractMessage msg, bool showFullPath)
 {
     if (msg.MessageType != "error")
     {
         return;
     }
     AddMessage(msg.MessageType, msg.Text, msg.Location.Row, msg.Location.Column);
 }
Exemplo n.º 23
0
        /// <summary>
        /// Sends the given message to the server or stores it until there is a connection to the server.
        /// </summary>
        /// <param name="msg">The message to send.</param>
        /// <param name="cacheIfNotConnected">Cache the message if the connection state does not equals 'CONNECTED', to ensure the message doesn't get lost.</param>
        /// <param name="sendIfNotConnected">Sends the message if the underlaying TCP connection is connected to the server and ignores the connection state of the XMPPConnection.</param>
        public async Task sendAsync(AbstractMessage msg, bool cacheIfNotConnected, bool sendIfNotConnected)
        {
            if (state == ConnectionState.CONNECTING)
            {
                resetConnectionTimer();
            }

            if (state != ConnectionState.CONNECTED && !sendIfNotConnected)
            {
                if (Logger.logLevel >= LogLevel.DEBUG)
                {
                    Logger.Warn("Did not send message, due to connection state is " + state + "\n" + msg.toXmlString());
                }
                else
                {
                    Logger.Warn("Did not send message, due to connection state is " + state);
                }

                if ((cacheIfNotConnected || msg.shouldSaveUntilSend()))
                {
                    MessageCacheDBManager.INSTANCE.addMessage(account.getIdAndDomain(), msg);
                }
                if (!sendIfNotConnected)
                {
                    return;
                }
            }

            if (msg is IQMessage && msg.ID != null)
            {
                messageIdCache.addTimed(msg.ID);
            }
            try
            {
                if (await TCP_CONNECTION.sendAsync(msg.toXmlString()))
                {
                    // Only trigger onMessageSend(...) for chat messages:
                    if (msg is MessageMessage m)
                    {
                        onMessageSend(msg.ID, m.chatMessageId, false);
                        return;
                    }
                }
                else
                {
                    Logger.Error("Error during sending message for account: " + account.getIdAndDomain());
                }
            }
            catch (Exception e)
            {
                Logger.Error("Error during sending message for account: " + account.getIdAndDomain(), e);
            }

            if ((cacheIfNotConnected || msg.shouldSaveUntilSend()))
            {
                MessageCacheDBManager.INSTANCE.addMessage(account.getIdAndDomain(), msg);
            }
        }
        protected override void OnReceive(AbstractMessage message)
        {
            TypeSwitch.On(message)
            .Case((ClearMessage clearMessage) =>
            {
                // Reset partition and send sync message
                clear();
                clearMessage.Sender.SendMe(new EstimateRefinedMessage(this));
            })
            .Case((RefineMessage refineMessage) =>
            {
                // Perform local refine step
                refine();
                refineMessage.Sender.SendMe(new EstimateRefinedMessage(this));
            })
            .Case((CountMessage countMessage) =>
            {
                var blocks = new HashSet <int>();
                foreach (var node in ownerInverted[this])
                {
                    if (!blocks.Contains(partition[node]))
                    {
                        blocks.Add(partition[node]);
                    }
                }

                countMessage.Sender.SendMe(new CountedMessage(this, blocks));
            })
            .Case((ShareMessage shareMessage) =>
            {
                // Share changes
                foreach (var worker in ownerInverted.Keys)
                {
                    if (worker != this)
                    {
                        var changedNodesOfInterest = partition.Where(kvp => interestedIn[worker].Contains(kvp.Key) && changed[kvp.Key]);

                        if (changedNodesOfInterest.Any())
                        {
                            worker.SendMe(new UpdatePartitionMessage <TNode>(this, changedNodesOfInterest));
                        }
                    }
                }

                shareMessage.Sender.SendMe(new SharedMessage(this));
            })
            .Case((UpdatePartitionMessage <TNode> updatePartitionMessage) =>
            {
                foreach (var change in updatePartitionMessage.Changes)
                {
                    partition[change.Key] = change.Value;
                }
            })
            .Case((SegmentRequestMessage segmentRequestMessage) =>
            {
                segmentRequestMessage.Sender.SendMe(new SegmentResponseMessage <TNode>(this, partition.Where(kvp => owner[kvp.Key] == this)));
            });
        }
Exemplo n.º 25
0
    public static void Dispatch(string type, AbstractMessage message = null)
    {
        ObjUnityEvent thisEvent = null;

        if (instance.eventDictionary.TryGetValue(type, out thisEvent))
        {
            thisEvent.Invoke(message);
        }
    }
Exemplo n.º 26
0
 /// <summary>
 /// Build an acknowledge message.
 /// </summary>
 /// <param name="message">Incoming message.</param>
 static public AcknowledgeMessage BuildAcknowledgeMessage(AbstractMessage message)
 {
     return(new AcknowledgeMessage
     {
         MessageId = GenerateUuid(),
         CorrelationId = message.MessageId,
         Timestamp = GenerateTimestamp()
     });
 }
Exemplo n.º 27
0
        void OnMessage(AbstractMessage msg)
        {
            var m = _printer;

            if (m != null)
            {
                m(msg);
            }
        }
Exemplo n.º 28
0
 private void HandlePingMessage(String address, AbstractMessage message)
 {
     if (controller.Client.LastPing == default(DateTime))
     {
         Controller.GetInstance().Client.StartPing();
     }
     controller.Client.LastPing = DateTime.Now;
     controller.Client.SendData(message);
 }
Exemplo n.º 29
0
 /// <summary>
 /// Build an error message.
 /// </summary>
 /// <param name="message">Incoming message.</param>
 static public ErrorMessage BuildErrorMessage(AbstractMessage message)
 {
     return(new ErrorMessage
     {
         MessageId = GenerateUuid(),
         CorrelationId = message.MessageId,
         Timestamp = GenerateTimestamp()
     });
 }
Exemplo n.º 30
0
        /// <inheritdoc/>
        public Task MarkMessageAsPublishedAsync(string id, AbstractMessage message)
        {
            var entity = new DynamicTableEntity(id, message.Id, "*", new Dictionary <string, EntityProperty>
            {
                { IsPublishedColumnName, new EntityProperty(true) },
            });

            return(tableProxy.ExecuteAsync(TableOperation.Merge(entity)));
        }
 public void Receive(AbstractMessage message)
 {
     Console.WriteLine(this.GetType().ToString() + " => Sending Push Notification with content: " + message.GetBody());
 }