public void ProcessMessageReceived(IIncomingMessage incomingMessage)
 {
     //This will be done on the worker thread of the background queue.
     Logger.Info(this, String.Format("Received response on {0} from sender {1} with correlation id {2}",
         incomingMessage.Topic,
         incomingMessage.Sender,
         incomingMessage.CorrelationId)); 
     Action<IIncomingMessage> responseHandler;
     _responseHandlerDict.TryGetValue(incomingMessage.CorrelationId, out responseHandler);
     if (responseHandler != null)
     {
         _stopwatch.Start();
         responseHandler(incomingMessage);
         _stopwatch.Stop();
         Logger.Info(this, String.Format("Processed response on {0} from sender {1} with correlation id {2}.  Time since arrival = {3}. Processing time = {4}",
             incomingMessage.Topic,
             incomingMessage.Sender,
             incomingMessage.CorrelationId,
             (DateTime.UtcNow - incomingMessage.TimeOfArrival).ToString(),
             _stopwatch.Elapsed.ToString()));
         _stopwatch.Reset();
         
     }
     else
     {
         //This should not happen.  You should not receive a message on the unique response topic
         //if it is not an expected response.  DO SOMETHING!!
         Logger.Warn(this, String.Format("Was not expecting a response for correlation id = {0}",
             incomingMessage.CorrelationId));
     }
 }
Exemple #2
0
        protected virtual void OnChatMessageHandler(IIncomingMessage message)
        {
            var chatUser = message.Peer.GetExtension <ChatUserPeerExtension>();

            string responseMsg;

            if (chatUser == null)
            {
                responseMsg = "Chat cannot identify you";

                logger.Error(responseMsg);

                message.Respond(responseMsg, ResponseStatus.Unauthorized);
                return;
            }

            var packet = message.Deserialize(new ChatMessagePacket());

            if (!TryHandleChatMessage(packet, chatUser, message))
            {
                responseMsg = "Invalid message";

                logger.Error(responseMsg);

                // If message was not handled
                message.Respond(responseMsg, ResponseStatus.NotHandled);
                return;
            }
        }
Exemple #3
0
        /// <summary>
        /// Implementazione esecuzione comando di richiesta lista plctags sotoscritti
        /// </summary>
        /// <param name="Message">Dati messaggio ricevuto</param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool GetSubscribedPLCTags(IIncomingMessage Message)
        {
            bool RetValue = true;
            var  tagslist = new List <PLCTag>();

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as MsgData;

            Logger.InfoFormat("{0}", Message.SourceApplicationName);

            // gestione subscriptions
            if (!_Subs.ContainsKey(Message.SourceApplicationName))
            {
                Logger.WarnFormat("[{0}] has no subscriptions", Message.SourceApplicationName);
                RetValue = false;
            }
            else
            {
                // costruisco la lista da inviare come risposta
                foreach (var sub in _Subs[Message.SourceApplicationName].ToList())
                {
                    var tag = new PLCTag()
                    {
                        PLCName = sub.PLCName, Address = sub.TagAddress, Validation = true
                    };
                    tagslist.Add(tag);
                }
            }

            // invio messaggio di risposta generica
            return(SendResponse(Message, MsgCodes.SubscribedPLCTags, new PLCTagsData()
            {
                MsgCode = MsgCodes.SubscribedPLCTags, Tags = tagslist
            }, RetValue));
        }
Exemple #4
0
        protected virtual void GetRoomAccessRequestHandler(IIncomingMessage message)
        {
            var data = message.Deserialize(new RoomAccessRequestPacket());

            // Let's find a room by Id which the player wants to join
            if (!roomsList.TryGetValue(data.RoomId, out RegisteredRoom room))
            {
                message.Respond("Room does not exist", ResponseStatus.Failed);
                return;
            }

            // If room requires the password and given password is not valid
            if (!string.IsNullOrEmpty(room.Options.Password) && room.Options.Password != data.Password)
            {
                message.Respond("Invalid password", ResponseStatus.Unauthorized);
                return;
            }

            // Send room access request to peer who owns it
            room.GetAccess(message.Peer, data.CustomOptions, (packet, error) =>
            {
                if (packet == null)
                {
                    message.Respond(error, ResponseStatus.Unauthorized);
                    return;
                }

                message.Respond(packet, ResponseStatus.Success);
            });
        }
Exemple #5
0
        public async Task processBestMemeAsync(IIncomingMessage message, GetMemesMemes bestMeme, List <string> memeText)
        {
            try
            {
                _logger.Log(NLog.LogLevel.Info, $"processBestMemeAsync for peer_id: {message.peer_id}");


                var memeUrl = await imgflipService.imgFlipCaptionImage(bestMeme.id, memeText, _imgFlipUsername, _imgFlipPassword);

                var photoId = await vkService.savePhotoByUrl(memeUrl, message.peer_id, _token, _apiVersion);

                var outgoingMessage = new OutgoingMessage()
                {
                    peer_id = message.peer_id,
                    //message = text,
                    attachment = photoId,
                    //group_id = message.
                };
                await SendMessageAsync(outgoingMessage);
            }
            catch (Exception ex)
            {
                _logger.Log(NLog.LogLevel.Error, ex, "getMessagesUploadServer Error");
            }
        }
Exemple #6
0
        /// <summary>
        /// Implementazione esecuzione comando di disconnessione di un client sottoscrittore
        /// </summary>
        /// <param name="Message">Dati messaggio ricevuto</param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool DisconnectSubscriber(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as MsgData;

            Logger.InfoFormat("{1} da {0}", Message.SourceApplicationName, MsgData.MsgCode);

            // gestione subscriptions
            if (_Subs.ContainsKey(Message.SourceApplicationName))
            {
                foreach (var sub in _Subs[Message.SourceApplicationName].ToList())
                {
                    RemovePLCTag(Message.SourceApplicationName, new PLCTag()
                    {
                        PLCName = sub.PLCName, Address = sub.TagAddress
                    });
                }
                _Subs.Remove(Message.SourceApplicationName);
            }
            else
            {
                // non esiste !
                Logger.WarnFormat("{0} non sottoscritto!", Message.SourceApplicationName);
                RetValue = false;
            }

            /* invio messaggio di risposta generica */
            return(SendResponse(Message, MsgCodes.ResultDisconnectSubscriber, MsgData, RetValue));
        }
        public void ProcessMessageReceived(IIncomingMessage incomingMessage)
        {
            Logger.Info(this, String.Format("Received command on {0} from sender {1} using correlation id {2}",
                incomingMessage.Topic,
                incomingMessage.Sender,
                incomingMessage.CorrelationId));

            Action<IIncomingMessage> allHandlers = _messageHandlers;
            if (allHandlers != null)
            {
                _stopwatch.Start();
                HandleMessageReceived(incomingMessage, allHandlers);
                _stopwatch.Stop();

                Logger.Info(this,
                            String.Format(
                                "Executed command on {0} from sender {1} using correlation id {2}.  Time since arrival = {3}. Processing time = {4}",
                                incomingMessage.Topic,
                                incomingMessage.Sender,
                                incomingMessage.CorrelationId,
                                (DateTime.UtcNow - incomingMessage.TimeOfArrival).ToString(),    
                                _stopwatch.Elapsed.ToString()));
                _stopwatch.Reset();
            }
        }
Exemple #8
0
        /// <summary>
        /// Handles a message from spawned process. Spawned process send this message
        /// to notify server that it was started
        /// </summary>
        /// <param name="message"></param>
        protected virtual void RegisterSpawnedProcessRequestHandler(IIncomingMessage message)
        {
            var data = message.Deserialize(new RegisterSpawnedProcessPacket());

            // Try get psawn task by ID
            if (!spawnTasksList.TryGetValue(data.SpawnId, out SpawnTask task))
            {
                message.Respond("Invalid spawn task", ResponseStatus.Failed);
                logger.Error("Process tried to register to an unknown task");
                return;
            }

            // Check spawn task unique code
            if (task.UniqueCode != data.SpawnCode)
            {
                message.Respond("Unauthorized", ResponseStatus.Unauthorized);
                logger.Error("Spawned process tried to register, but failed due to mismaching unique code");
                return;
            }

            // Set task as registered
            task.OnRegistered(message.Peer);

            // Invoke event
            OnSpawnedProcessRegisteredEvent?.Invoke(task, message.Peer);

            // Respon to requester
            message.Respond(task.Options.ToDictionary().ToBytes(), ResponseStatus.Success);
        }
Exemple #9
0
        protected virtual void OnChatMessageHandler(IIncomingMessage message)
        {
            try
            {
                var chatUser = message.Peer.GetExtension <ChatUserPeerExtension>();

                // If peer has no user
                if (chatUser == null)
                {
                    throw new MstMessageHandlerException("Chat cannot identify you", ResponseStatus.Unauthorized);
                }

                var packet = message.Deserialize(new ChatMessagePacket());

                if (!TryHandleChatMessage(packet, chatUser, message))
                {
                    throw new MstMessageHandlerException("Invalid message", ResponseStatus.NotHandled);
                }
            }
            // If we got system exception
            catch (MstMessageHandlerException e)
            {
                logger.Error(e.Message);
                message.Respond(e.Message, e.Status);
            }
            // If we got another exception
            catch (Exception e)
            {
                logger.Error(e.Message);
                message.Respond(e.Message, ResponseStatus.Error);
            }
        }
Exemple #10
0
        protected virtual void GetCompletionDataRequestHandler(IIncomingMessage message)
        {
            var spawnId = message.AsInt();

            if (!spawnTasksList.TryGetValue(spawnId, out SpawnTask task))
            {
                message.Respond("Invalid request", ResponseStatus.Failed);
                return;
            }

            if (task.Requester != message.Peer)
            {
                message.Respond("You're not the requester", ResponseStatus.Unauthorized);
                return;
            }

            if (task.FinalizationPacket == null)
            {
                message.Respond("Task has no completion data", ResponseStatus.Failed);
                return;
            }

            // Respond with data (dictionary of strings)
            message.Respond(task.FinalizationPacket.FinalizationData.ToBytes(), ResponseStatus.Success);
        }
Exemple #11
0
        /// <summary>
        /// Implementazione esecuzione comando di rimozione della sottoscrizione di una lista di plctags
        /// </summary>
        /// <param name="Message">Dati messaggio ricevuto</param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool RemovePLCTags(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData  = GeneralHelper.DeserializeObject(Message.MessageData) as PLCTagsData;
            var tagslist = MsgData.Tags;

            Logger.InfoFormat("{0}", Message.SourceApplicationName);

            for (int i = 0; i < tagslist.Count; i++)
            {
                var tag = tagslist[i];

                if (!RemovePLCTag(Message.SourceApplicationName, tag))
                {
                    tag.Validation = false;
                    RetValue       = false;
                }
                else
                {
                    tag.Validation = true;
                }
            }

            // invio messaggio di risposta generica
            return(SendResponse(Message, MsgCodes.ResultRemovePLCTags, MsgData, RetValue));
        }
Exemple #12
0
        private bool PLCTagChanged(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PLCTagData;

            Logger.InfoFormat("Ricevuto Messaggio {1}/{2}:{3} da {0}", Message.SourceApplicationName, MsgData.Tag.PLCName, MsgData.Tag.Address, MsgData.Tag.Value);

            var tag = model.ListTagItems.FirstOrDefault(item => item.Address == MsgData.Tag.Address);

            if (tag != null)
            {
                // funzionano entrambe, la Invoke esegue in modo bloccante, la BeginInvoke esegue in parallelo

                //Application.Current.Dispatcher.Invoke(new Action(() =>
                //{
                //    tag.Value = MsgData.Tag.Value.ToString();
                //}));

                Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                {
                    tag.Value = MsgData.Tag.Value.ToString();
                }));
            }
            else
            {
                Logger.InfoFormat("Tag {0}/{1} non trovato", tag.PLCName, tag.Address);
                RetValue = false;
            }

            return(RetValue);
        }
Exemple #13
0
        /// <summary>
        /// Handles a request from user to join a lobby
        /// </summary>
        /// <param name="message"></param>
        protected virtual void JoinLobbyHandler(IIncomingMessage message)
        {
            var lobbyUser = GetOrCreateLobbyUserPeerExtension(message.Peer);

            if (lobbyUser.CurrentLobby != null)
            {
                message.Respond("You're already in a lobby", ResponseStatus.Failed);
                return;
            }

            var lobbyId = message.AsInt();

            lobbies.TryGetValue(lobbyId, out ILobby lobby);

            if (lobby == null)
            {
                message.Respond("Lobby was not found", ResponseStatus.Failed);
                return;
            }

            if (!lobby.AddPlayer(lobbyUser, out string error))
            {
                message.Respond(error ?? "Failed to add player to lobby", ResponseStatus.Failed);
                return;
            }

            var data = lobby.GenerateLobbyData(lobbyUser);

            message.Respond(data, ResponseStatus.Success);
        }
Exemple #14
0
        protected virtual void SetLobbyPropertiesMessageHandler(IIncomingMessage message)
        {
            var data = message.Deserialize(new LobbyPropertiesSetPacket());

            lobbies.TryGetValue(data.LobbyId, out ILobby lobby);

            if (lobby == null)
            {
                message.Respond("Lobby was not found", ResponseStatus.Failed);
                return;
            }

            var lobbiesExt = GetOrCreateLobbyUserPeerExtension(message.Peer);

            foreach (var dataProperty in data.Properties.ToDictionary())
            {
                if (!lobby.SetProperty(lobbiesExt, dataProperty.Key, dataProperty.Value))
                {
                    message.Respond("Failed to set the property: " + dataProperty.Key,
                                    ResponseStatus.Failed);
                    return;
                }
            }

            message.Respond(ResponseStatus.Success);
        }
Exemple #15
0
        private void AbortSpawnRequestHandler(IIncomingMessage message)
        {
            var prevRequest = message.Peer.GetProperty((int)MstPeerPropertyCodes.ClientSpawnRequest) as SpawnTask;

            if (prevRequest == null)
            {
                message.Respond("There's nothing to abort", ResponseStatus.Failed);
                return;
            }

            if (prevRequest.Status >= SpawnStatus.Finalized)
            {
                message.Respond("You can't abort a completed request", ResponseStatus.Failed);
                return;
            }

            if (prevRequest.Status <= SpawnStatus.None)
            {
                message.Respond("Already aborting", ResponseStatus.Success);
                return;
            }

            logger.Debug($"Client [{message.Peer.Id}] requested to terminate process [{prevRequest.Id}]");

            prevRequest.Abort();

            message.Respond(ResponseStatus.Success);
        }
Exemple #16
0
        private bool PLCStatus(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PLCStatusData;

            Logger.InfoFormat("Ricevuto Messaggio {1}:{2} da {0}", Message.SourceApplicationName, MsgData.PLCName, MsgData.Status, MsgData.validation);

            RetValue = MsgData.validation;

            if (MsgData.validation)
            {
                var plc = model.ListPLCItems.FirstOrDefault(item => item.Name == MsgData.PLCName);
                if (plc != null)
                {
                    plc.ConnectionStatus = MsgData.Status;
                }
                else
                {
                    RetValue = false;
                }
            }

            return(RetValue);
        }
Exemple #17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="message"></param>
        protected virtual void PermissionLevelRequestHandler(IIncomingMessage message)
        {
            var key = message.AsString();

            var extension = message.Peer.GetExtension <SecurityInfoPeerExtension>();

            var currentLevel = extension.PermissionLevel;
            var newLevel     = currentLevel;

            var permissionClaimed = false;

            foreach (var entry in permissions)
            {
                if (entry.key == key)
                {
                    newLevel          = entry.permissionLevel;
                    permissionClaimed = true;
                }
            }

            extension.PermissionLevel = newLevel;

            if (!permissionClaimed && !string.IsNullOrEmpty(key))
            {
                // If we didn't claim a permission
                message.Respond("Invalid permission key", ResponseStatus.Unauthorized);
                return;
            }

            message.Respond(newLevel, ResponseStatus.Success);
        }
Exemple #18
0
        private bool ResultSubscribePLCTag(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PLCTagData;

            Logger.InfoFormat("Ricevuto Messaggio {1}/{2}:{3} da {0}", Message.SourceApplicationName, MsgData.Tag.PLCName, MsgData.Tag.Address, MsgData.Tag.Value);

            TagItem tag = new TagItem()
            {
                PLCName = MsgData.Tag.PLCName, Address = MsgData.Tag.Address
            };

            if (tag != null)
            {
                Logger.InfoFormat("Aggiunto {0}/{1}", tag.PLCName, tag.Address);

                if (GuiContext != null)
                {
                    GuiContext.Send((o) => { model.ListTagItems.Add(tag); }, null);
                }
                else
                {
                    Logger.InfoFormat("GuiContext NULL");
                    Debug.Assert(false);
                }
            }
            return(RetValue);
        }
Exemple #19
0
        protected virtual void OnGetUsersInChannelRequestHandler(IIncomingMessage message)
        {
            string responseMsg = string.Empty;

            var chatUser = message.Peer.GetExtension <ChatUserPeerExtension>();

            if (chatUser == null)
            {
                responseMsg = "Chat cannot identify you";

                logger.Error(responseMsg);

                message.Respond(responseMsg, ResponseStatus.Unauthorized);
                return;
            }

            var channelName = message.AsString();
            var channel     = GetOrCreateChannel(channelName);

            if (channel == null)
            {
                responseMsg = "This channel is forbidden";

                logger.Error(responseMsg);

                // There's no such channel
                message.Respond(responseMsg, ResponseStatus.Failed);
                return;
            }

            var users = channel.Users.Select(u => u.Username);

            message.Respond(users.ToBytes(), ResponseStatus.Success);
        }
Exemple #20
0
        protected virtual void GetLobbyRoomAccessMessageHandler(IIncomingMessage message)
        {
            var lobbiesExt = GetOrCreateLobbyUserPeerExtension(message.Peer);
            var lobby      = lobbiesExt.CurrentLobby;

            lobby.GameAccessRequestHandler(message);
        }
Exemple #21
0
        private bool SubscribeProperty(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PropertyData;
            var prop    = MsgData.Prop;

            Logger.InfoFormat("{1} da {0}", Message.SourceApplicationName, prop.ObjPath);


            RetValue = SubscribeProperty(Message.SourceApplicationName, prop);

            /* invio messaggio di risposta */
            RetValue = SendResponse(Message, MsgCodes.ResultSubscribeProperty, MsgData, RetValue);

            // all'atto della sottoscrizione invio valore attuale della property
            if (RetValue)
            {
                PropertyNotifyToSubscriber(Message.SourceApplicationName, prop);
            }


            return(RetValue);
        }
Exemple #22
0
        private bool RemoveProperties(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PropertiesData;
            var props   = MsgData.Props;

            Logger.InfoFormat("{0}", Message.SourceApplicationName);

            for (int i = 0; i < props.Count(); i++)
            {
                var prop = props[i];
                if (!RemoveProperty(Message.SourceApplicationName, prop))
                {
                    RetValue        = false;
                    prop.Validation = false;
                }
                else
                {
                    prop.Validation = true;
                }
            }

            /* invio messaggio di risposta */
            return(SendResponse(Message, MsgCodes.ResultRemoveProperties, MsgData, RetValue));
        }
Exemple #23
0
        private bool DisconnectSubscriber(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data (not useful for now)
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as MsgData;

            Logger.InfoFormat("{1} da {0}", Message.SourceApplicationName, MsgData.MsgCode);

            // gestione subscriptions
            if (ListSubscriptions.ContainsKey(Message.SourceApplicationName))
            {
                foreach (var sub in ListSubscriptions[Message.SourceApplicationName].ToList())
                {
                    RemoveProperty(Message.SourceApplicationName, new Property()
                    {
                        ObjPath = sub.ObjPath
                    });
                }
                ListSubscriptions.Remove(Message.SourceApplicationName);
            }
            else
            {
                // non esiste !
                Logger.WarnFormat("{0} non sottoscritto!", Message.SourceApplicationName);
                RetValue = false;
            }

            /* invio messaggio di risposta */
            return(SendResponse(Message, MsgCodes.ResultDisconnectSubscriber, MsgData, RetValue));
        }
Exemple #24
0
        private bool PLCTagsChanged(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PLCTagsData;
            var plctags = MsgData.Tags;

            Logger.InfoFormat("Ricevuto Messaggio da {0}", Message.SourceApplicationName);

            foreach (var plctag in plctags)
            {
                bool bOK = true;

                // trova il tag corrispondente (uno solo) all'indirizzo sottoscritto
                TagItem tag = ListTagItems.FirstOrDefault(item => item.PLCName == plctag.PLCName && item.Address == plctag.Address);

                if (tag != null)
                {
                    //
                    try
                    {
                        tag.Value = plctag.Value;
                        Logger.InfoFormat("Cambiato Tag {0} : {1}/{2}:{3} -> {4}", tag.Name, tag.PLCName, tag.Address, tag.Type, tag.Value);
                    }
                    catch (Exception exc)
                    {
                        Logger.WarnFormat("Errore in cambio Tag value {0} : {1}/{2}:{3} -> {4} {5}", tag.Name, tag.PLCName, tag.Address, tag.Type, tag.Value, exc.Message);
                    }

                    // recuperare la lista delle properties dell'impianto
                    List <MariniProperty> props = mariniImpiantoTree.MariniImpianto.GetObjectListByType(typeof(MariniProperty)).Cast <MariniProperty>().ToList();
                    // trova la property associata e cambia il valore
                    MariniProperty property = props.FirstOrDefault(prp => prp.bind == tag.Name);

                    if (property != null)
                    {
                        try
                        {
                            property.value = tag.Value;
                        }
                        catch (Exception exc)
                        {
                            Logger.WarnFormat("Errore in cambio valore property {0}:{1} {2}", property.name, tag.Value, exc.Message);
                            bOK = false;
                        }
                    }
                }
                else
                {
                    Logger.InfoFormat("Tag associato a : {0}/{1} non trovato", plctag.PLCName, plctag.Address);
                    bOK = false;
                }
                if (bOK == false)
                {
                    RetValue = bOK;
                }
            }
            return(RetValue);
        }
Exemple #25
0
        private bool ResultDisconnectPLC(IIncomingMessage Message)
        {
            bool RetValue = true;

            // get msg application data
            var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PLCData;

            Logger.InfoFormat("Ricevuto Messaggio {1} da {0}", Message.SourceApplicationName, MsgData.PLCName);

            RetValue = MsgData.validation;

            if (MsgData.validation)
            {
                var plc = model.ListPLCItems.FirstOrDefault(item => item.Name == MsgData.PLCName);
                if (plc != null)
                {
                    // reentrant... approfondire
                    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                    {
                        model.ListPLCItems.Remove(plc);
                    }));
                }
            }

            return(RetValue);
        }
Exemple #26
0
        private void SetMyPropertiesMessageHandler(IIncomingMessage message)
        {
            // Get lobby user peer extension
            var lobbyUser = GetOrCreateLobbyUserPeerExtension(message.Peer);

            // Get current lobby this user joined in
            var lobby = lobbyUser.CurrentLobby;

            if (lobby == null)
            {
                message.Respond("Lobby was not found", ResponseStatus.Failed);
                return;
            }

            // Properties to be changed
            var properties = new Dictionary <string, string>().FromBytes(message.AsBytes());

            // Get member of lobby by its lobby user extension
            var member = lobby.GetMemberByExtension(lobbyUser);

            foreach (var dataProperty in properties)
            {
                // We don't change properties directly,
                // because we want to allow an implementation of lobby
                // to do "sanity" checking
                if (!lobby.SetPlayerProperty(member, dataProperty.Key, dataProperty.Value))
                {
                    message.Respond("Failed to set property: " + dataProperty.Key, ResponseStatus.Failed);
                    return;
                }
            }

            message.Respond(ResponseStatus.Success);
        }
Exemple #27
0
 public async Task <bool> getChatHistory(IIncomingMessage message)
 {
     try
     {
         //var uri = new Uri(url);
         //_logger.Log(NLog.LogLevel.Info, uri);
         var request = new VkontakteBot.Services.VKService.HistoryRequest
         {
             offset           = 0,
             count            = 200,
             user_id          = "1556462",
             peer_id          = message.peer_id,
             start_message_id = "0",
             rev = "1",
             //extended =
             //fields =
             group_id = _groupId,
         };
         await vkService.messagesGetHistory(request, _token, _apiVersion);
     }
     catch (Exception ex)
     {
         _logger.Log(NLog.LogLevel.Error, ex, "audioToText Error");
     }
     return(false);
 }
Exemple #28
0
        protected virtual void JoinLobbyTeamMessageHandler(IIncomingMessage message)
        {
            var data = message.Deserialize(new LobbyJoinTeamPacket());

            var lobbiesExt = GetOrCreateLobbyUserPeerExtension(message.Peer);
            var lobby      = lobbiesExt.CurrentLobby;

            if (lobby == null)
            {
                message.Respond("You're not in a lobby", ResponseStatus.Failed);
                return;
            }

            var player = lobby.GetMemberByExtension(lobbiesExt);

            if (player == null)
            {
                message.Respond("Invalid request", ResponseStatus.Failed);
                return;
            }

            if (!lobby.TryJoinTeam(data.TeamName, player))
            {
                message.Respond("Failed to join a team: " + data.TeamName, ResponseStatus.Failed);
                return;
            }

            message.Respond(ResponseStatus.Success);
        }
Exemple #29
0
        protected virtual void DestroyRoomRequestHandler(IIncomingMessage message)
        {
            var roomId = message.AsInt();

            logger.Debug($"Client {message.Peer.Id} requested to destroy room server with id {roomId}");

            if (!roomsList.TryGetValue(roomId, out RegisteredRoom room))
            {
                logger.Debug($"But this room does not exist");
                message.Respond("Room does not exist", ResponseStatus.Failed);
                return;
            }

            if (message.Peer != room.Peer)
            {
                logger.Debug($"But it is not the creator of the room");
                message.Respond("You're not the creator of the room", ResponseStatus.Unauthorized);
                return;
            }

            DestroyRoom(room);

            logger.Debug($"Room {roomId} has been successfully destroyed");

            message.Respond(ResponseStatus.Success);
        }
Exemple #30
0
        private void UpdateDisplayNameRequestHandler(IIncomingMessage message)
        {
            var userExtension = message.Peer.GetExtension <IUserPeerExtension>();

            if (userExtension == null || userExtension.Account == null)
            {
                message.Respond("Invalid session", ResponseStatus.Unauthorized);
                return;
            }

            var newProfileData = new Dictionary <string, string>().FromBytes(message.AsBytes());

            try
            {
                if (profilesList.TryGetValue(userExtension.Username, out ObservableServerProfile profile))
                {
                    profile.GetProperty <ObservableString>((short)ObservablePropertiyCodes.DisplayName).Set(newProfileData["displayName"]);
                    profile.GetProperty <ObservableString>((short)ObservablePropertiyCodes.Avatar).Set(newProfileData["avatarUrl"]);

                    message.Respond(ResponseStatus.Success);
                }
                else
                {
                    message.Respond("Invalid session", ResponseStatus.Unauthorized);
                }
            }
            catch (Exception e)
            {
                message.Respond($"Internal Server Error: {e}", ResponseStatus.Error);
            }
        }
Exemple #31
0
        /// <summary>
        /// Invio risposta a messaggi aventi messagedata di tipo <typeparamref name="MsgData"/>
        /// </summary>
        /// <param name="receivedMsg">Messaggio a cui viene inviata risposta</param>
        /// <param name="MsgCode">Codice messaggio di risposta</param>
        /// <param name="MessageData">Dato da inviare (contiene Validation)</param>
        /// <param name="Result">Risultato dell'operazione richiesta</param>
        /// <returns>true se tutto bene, altrimenti false</returns>
        private bool SendResponse(IIncomingMessage receivedMsg, MsgCodes MsgCode, MsgData MessageData, bool Result)
        {
            bool bOK     = true;
            var  message = mdsClient.CreateMessage();

            // Set message data
            MessageData.MsgCode    = MsgCode;
            MessageData.validation = Result;

            // Set message params
            message.MessageData = GeneralHelper.SerializeObject(MessageData);
            message.DestinationApplicationName = receivedMsg.SourceApplicationName;
            message.TransmitRule = MessageTransmitRules.NonPersistent;


            try
            {
                //Send message
                message.Send();
                Logger.InfoFormat("Inviato msg a {0}", message.DestinationApplicationName);
            }
            catch (Exception exc)
            {
                // non sono riuscito a inviare il messaggio
                Logger.WarnFormat("Messaggio non inviato - {0}", exc.Message);
                bOK = false;
            }

            return(bOK);
        }
        /// <summary>
        /// This version is used to forward an incoming request to a server
        /// </summary>
        public ServerRequestContext(
            IRequestContext requestContext,
            IPAddress serverIpAddress,
            ushort serverPort,
            Scheme scheme)
        {
            _log = requestContext.Log;

            _incoming = new IncomingMessage
            {
                Headers       = requestContext.Incoming.Headers,
                OnSendHeaders = requestContext.Incoming.OnSendHeaders,
                Content       = requestContext.Incoming.Content,
                ContentLength = requestContext.Incoming.ContentLength,

                Method        = requestContext.Incoming.Method,
                Scheme        = scheme,
                DomainName    = requestContext.Incoming.DomainName,
                Path          = requestContext.Incoming.Path,
                Query         = requestContext.Incoming.Query,
                SourceAddress = requestContext.Incoming.SourceAddress,
                SourcePort    = requestContext.Incoming.SourcePort,

                DestinationAddress = serverIpAddress,
                DestinationPort    = serverPort
            };

            _outgoing = requestContext.Outgoing;
        }
 private void ProcessIncomingMessage(IIncomingMessage next)
 {
     Logger.Debug(this, "Finding message processor for this topic.");
     if (!_knownMessageProcessors.ContainsKey(next.Topic))
     {
         Logger.Warn(this,
                     String.Format(
                         "Received message on topic {0} but could not find any registered handlers.  Ignoring this message.",
                         next.Topic));
         return;
     }
     var messageProcessor = _knownMessageProcessors[next.Topic];
     ProcessIncomingMessageCore(next, messageProcessor);
 }
        protected virtual void HandleMessageReceived(IIncomingMessage incomingMessage, Action<IIncomingMessage> messageHandlers)
        {
            //Delegate[] handlers = messageHandlers.GetInvocationList();
            //int totalHandlers = handlers.Count();
            //Logger.Debug(this, String.Format("Found {0} message handlers subscribing to this topic.", totalHandlers));
            
            messageHandlers(incomingMessage);
            
            //Logger.Debug(this, String.Format("Completed invoking {0} message handlers for this message.", totalHandlers));

            /*for (int i = 0; i < totalHandlers; i++)
            {
                handlers[i].DynamicInvoke(incomingMessage);
                Logger.Debug(this, String.Format("Completed invoking message handler: {0}.  {1} more to go...", i + 1,
                                                 totalHandlers - (i + 1)));
            }*/
            

        }
 /// <summary>
 /// Rejects a message.
 /// </summary>
 /// <param name="message">Message to reject</param>
 /// <param name="reason">Reject reason</param>
 private static void RejectMessage(IIncomingMessage message, string reason)
 {
     try
     {
         message.Reject(reason);
     }
     catch (Exception ex)
     {
         Logger.Error(ex.Message, ex);
     }
 }
        /// <summary>
        /// Sends return value to the remote application that invoked a service method.
        /// </summary>
        /// <param name="incomingMessage">Incoming invoke message from remote application</param>
        /// <param name="returnValue">Return value to send</param>
        private static void SendReturnValue(IIncomingMessage incomingMessage, object returnValue)
        {
            if (incomingMessage.TransmitRule != MessageTransmitRules.DirectlySend)
            {
                return;
            }

            try
            {
                //Create return message
                var returnMessage = new MDSRemoteInvokeReturnMessage { ReturnValue = returnValue };
                //Create response message and send
                var responseMessage = incomingMessage.CreateResponseMessage();
                responseMessage.MessageData = GeneralHelper.SerializeObject(returnMessage);
                responseMessage.Send();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
            }
        }
 /// <summary>
 /// Acknowledges a message.
 /// </summary>
 /// <param name="message">Message to acknowledge</param>
 private static void AcknowledgeMessage(IIncomingMessage message)
 {
     try
     {
         message.Acknowledge();
     }
     catch (Exception ex)
     {
         Logger.Error(ex.Message, ex);
     }
 }
 public void ReceiveResponse(IIncomingMessage incomingMessage)
 {
     Logger.Debug(this, "Handling incoming response...");
     lock (_syncRoot)
     {
         ReceivedResponseCorrelationId = incomingMessage.CorrelationId;
         ReceivedResponseMessage = incomingMessage.Content.ToString();
         ReceivedResponseTopic = incomingMessage.Topic.Address;
         HasResponseBeenReceived = true;
         Monitor.Pulse(_syncRoot);
     } 
 }
 protected virtual void ProcessIncomingMessageCore(IIncomingMessage next,
                                                   IProcessAnyMessage messageProcessor)
 {
     messageProcessor.ProcessMessageReceived(next);
 }
 /// <summary>
 /// This method is called by NGRID server to process the message, when a message is sent to this application.
 /// </summary>
 /// <param name="message">Message to process</param>
 public abstract void ProcessMessage(IIncomingMessage message);
 public void Receive(IIncomingMessage incomingMessage, CommunicatingPeer recipient)
 {
     Logger.Debug(this, "Handling incoming message...");
     lock (_syncRoot)
     {
         string incomingTopic = incomingMessage.Topic.ToString();
         HasMessageBeenReceived = true;
         ReceivedMessageTopic = incomingTopic;
         ReceivedMessage = incomingMessage.Content.ToString();
         ReceivedMsgCorrelationId = incomingMessage.CorrelationId;
         ReplyTo = incomingMessage.ReplyTo != null ? incomingMessage.ReplyTo.Address : String.Empty;
         Logger.Info(this, String.Format("{0} - Received message  on topic {1} from {2}",
             recipient.PeerName,
             incomingMessage.Topic.Address, incomingMessage.Sender));
         Monitor.Pulse(_syncRoot);
     }
 }