/// <summary>
        /// Настройка обработчика команд
        /// </summary>
        private static void SetupCommands(CommandHandler commandHandler)
        {
            commandHandler.Add(new Command("set_protocol", (string[] args) =>
            {
                var networkService   = Toolbox.GetTool <INetworkService>();
                IPAddress recieverIp = null;
                int recieverPort     = -1;
                int listenerPort     = -1;

                if (networkService != null)
                {
                    recieverIp   = networkService.RecieverIp;
                    recieverPort = networkService.RecieverPort;
                    listenerPort = networkService.ListenerPort;

                    networkService.Dispose();
                    Toolbox.Remove(networkService);
                }
                else
                {
                    recieverIp = IPAddress.Loopback;
                }

                if (args.Length > 0)
                {
                    switch (args[0])
                    {
                    case "udp":
                        var udpService = new UdpService();
                        udpService.SetRecieverInfo(recieverIp.ToString(), recieverPort);

                        if (listenerPort >= 0)
                        {
                            udpService.SetListenerPort(listenerPort);
                        }

                        Toolbox.Add(udpService);
                        Print.Log("Установлен протокол UDP", Color.DarkBlue);
                        break;

                    case "tcp":
                        Print.Log("Установлен протокол TCP", Color.DarkBlue);
                        var tcpService = new TcpService();
                        tcpService.SetRecieverInfo(recieverIp.ToString(), recieverPort);

                        if (listenerPort >= 0)
                        {
                            tcpService.SetListenerPort(listenerPort);
                        }

                        Toolbox.Add(tcpService);
                        break;

                    default:
                        var udpServiceDefault = new UdpService();
                        udpServiceDefault.SetRecieverInfo(recieverIp.ToString(), recieverPort);

                        if (listenerPort >= 0)
                        {
                            udpServiceDefault.SetListenerPort(listenerPort);
                        }

                        Toolbox.Add(udpServiceDefault);
                        Print.LogWarning("По умолчанию выбран протокол UDP");
                        break;
                    }
                }
                else
                {
                    var udpServiceDefault = new UdpService();
                    udpServiceDefault.SetRecieverInfo(recieverIp.ToString(), recieverPort);

                    if (listenerPort >= 0)
                    {
                        udpServiceDefault.SetListenerPort(listenerPort);
                    }

                    Toolbox.Add(udpServiceDefault);
                    Print.LogWarning("По умолчанию выбран протокол UDP");
                }
            })).Invoke(new string[] { "tcp" });

            commandHandler.Add(new Command("set_reciever_ip", (string[] args) =>
            {
                var networkService = Toolbox.GetTool <INetworkService>();

                if (networkService == null)
                {
                    Print.LogWarning("Протокол не установлен!");
                    return;
                }

                if (args.Length > 0)
                {
                    networkService.SetRecieverIp(args[0]);
                    return;
                }

                Print.LogError("Отсутствует аргумент адреса!");
            }));

            commandHandler.Add(new Command("set_reciever_port", (string[] args) =>
            {
                var networkService = Toolbox.GetTool <INetworkService>();

                if (networkService == null)
                {
                    Print.LogWarning("Протокол не установлен!");
                    return;
                }

                if (args.Length > 0)
                {
                    var numList = CommandsExtensions.ParseInt(args);

                    if (numList.Count > 0)
                    {
                        networkService.SetRecieverPort(numList[0]);
                        return;
                    }
                }

                Print.LogError("Отсутствует аргумент порта!");
            }));

            commandHandler.Add(new Command("set_listener_port", (string[] args) =>
            {
                var networkService = Toolbox.GetTool <INetworkService>();

                if (networkService == null)
                {
                    Print.LogWarning("Протокол не установлен!");
                    return;
                }

                if (args.Length > 0)
                {
                    var numList = CommandsExtensions.ParseInt(args);

                    if (numList.Count > 0)
                    {
                        networkService.SetListenerPort(numList[0]);
                        return;
                    }
                }

                Print.LogError("Отсутствует аргумент порта!");
            }));

            commandHandler.Add(new Command("send_ping", (string[] args) =>
            {
                var networkService = Toolbox.GetTool <INetworkService>();

                if (networkService == null)
                {
                    Print.LogWarning("Протокол не установлен!");
                    return;
                }

                networkService.Send($"ping from {Process.GetCurrentProcess().Id}");
            }));

            commandHandler.Add(new Command("show_msbuf", (string[] args) =>
            {
                var msbuf = Toolbox.GetTool <MessageBuffer>();

                if (msbuf == null)
                {
                    Print.LogError("Буфер сообщений отсутствует.");
                    return;
                }

                if (msbuf.Messages.Count == 0)
                {
                    Print.Log("Сообщений нет.", Color.DarkBlue);
                    return;
                }

                foreach (var str in msbuf.QueryQueue())
                {
                    Print.Log(str, Color.Blue);
                }
            }));

            commandHandler.Handle("set_reciever_port : 7777");
            commandHandler.Handle("set_listener_port : 7777");
        }
Example #2
0
        public HttpResponseMessage PostNotification(NotifyRequest request)
        {
            HttpResponseMessage responseMessage;
            var commandHandler = new CommandHandler();

            try
            {
                var tempString = Parser.SplitOnFirstWord(request.Item.message.message).Item2;
                if (string.IsNullOrEmpty(tempString))
                {
                    throw new Exception("no email distribution alias provided");
                }

                // parse message
                var parsedMessage = Parser.SplitOnFirstWord(tempString);

                //get command
                var     commandString = parsedMessage.Item1.Trim();
                Command command;
                var     commandResult = Enum.TryParse(commandString, true, out command);

                //get message
                var message = parsedMessage.Item2;
                var result  = "";

                if (commandResult)
                {
                    switch (command)
                    {
                    case Command.Add:
                        commandHandler.Add(message);
                        result = "Added Successfully";
                        break;

                    case Command.Update:
                        result = commandHandler.Update(message);
                        break;
                    }
                }
                else
                {
                    var isHtml     = false;
                    var parsedbody = Parser.SplitOnFirstWord(message);
                    var regex      = new Regex(@"^\^(\d)*");
                    var match      = regex.Match(parsedbody.Item1);
                    if (match.Success)
                    {
                        var regexDigits = new Regex(@"(\d)+");
                        var matchDigits = regexDigits.Match(parsedbody.Item1);
                        if (matchDigits.Success)
                        {
                            var roomHistory = new RoomHistory(request.Item.room.name);

                            isHtml  = false;
                            message = roomHistory.GetRoomMessageHistory(int.Parse(matchDigits.Value) + 1).GetEmailMessage();
                        }
                    }
                    var senderName    = request.Item.message.from.name;
                    var senderMention = request.Item.message.from.mention_name;
                    result = commandHandler.Email(senderName, senderMention, commandString, message, isHtml);
                }

                if (result == null)
                {
                    throw new Exception("error");
                }


                // Notify Hipchat
                var responseBody = new NotifyResponse
                {
                    color          = "green",
                    message        = result,
                    message_format = "text",
                    notify         = "false"
                };
                responseMessage = this.Request.CreateResponse(HttpStatusCode.OK, responseBody);
            }
            catch (Exception ex)
            {
                commandHandler.Dispose();
                var responseBody = new NotifyResponse
                {
                    color          = "green",
                    message        = ex.Message,
                    message_format = "text",
                    notify         = "false"
                };
                responseMessage = this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, JsonConvert.SerializeObject(responseBody));
            }
            return(responseMessage);
        }