public HttpResponseMessage Get() {
    if (HttpContext.Current.IsWebSocketRequest) {
       var wsHandler = new WebSocketHandler();
       wsHandler.ProcessRequest(HttpContext.Current);
       return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);
    }
    return new HttpResponseMessage(HttpStatusCode.OK);
 }
 public WebSocketManagerMiddleware(RequestDelegate next,
                                   WebSocketHandler webSocketHandler)
 {
     _next             = next;
     _webSocketHandler = webSocketHandler;
 }
Пример #3
0
 public static IApplicationBuilder MapWebSocketManager(this IApplicationBuilder app,
                                                       PathString path,
                                                       WebSocketHandler handler)
 {
     return(app.Map(path, (_app) => _app.UseMiddleware <WebSocketManagerMiddleware>(handler)));
 }
Пример #4
0
 public static void StopDiscordWebSocket()
 {
     webSocketHandler?.Dispose();
     webSocketHandler = null;
 }
 public WebSocketMiddleware(RequestDelegate next, WebSocketHandler handler)
 {
     _next      = next;
     _WSHandler = handler;
 }
 public async virtual void OnMessage(WebSocket socket, WebSocketHandler handler, JsonData message)
 {
 }
Пример #7
0
 public ChatConnection(WebSocketHandler handler, PostgresDbContext context) : base(handler)
 {
     //_vehiculoPosicionService = new  VehiculoPosicionService;
     _context = context;
 }
 public void ConnectWebsocketHandler(WebSocketHandler webSocketHandler)
 {
     ConnectedWebsocketHandlers.Add(webSocketHandler);
 }
Пример #9
0
        private async Task <(bool, string, Message)> RunRedirectAsync(Message nextMessage, User user, IConnectionService connectionService, WebSocketHandler webSocketHandler)
        {
            var nextCommandText = "220010";

            Message commandTemplate = _dialog.Templates.Where(t => t.CommandText == nextCommandText).FirstOrDefault();

            if (commandTemplate == null)
            {
                return(await RunErrorAsync(nextMessage, user, connectionService, webSocketHandler).ConfigureAwait(false));
            }

            var template = new Message
            {
                GUID        = Guid.NewGuid(),
                UserGuid    = nextMessage.UserGuid,
                ServiceGuid = nextMessage.ServiceGuid,
                Date        = nextMessage.Date,
                Command     = nextMessage.Command,
                Iid         = nextMessage.Iid,
                Body        = commandTemplate.Body,

                CommandText = commandTemplate?.CommandText,
                Commands    = commandTemplate?.Commands,
            };

            var messageRepository = new MessageRepository(connectionService, _cache);

            return(await messageRepository.PostAnswerAsync(webSocketHandler, template, user.Login).ConfigureAwait(false));
        }
Пример #10
0
        private async Task <(bool, string, Message)> RunErrorAsync(Message nextMessage, User user, IConnectionService connectionService, WebSocketHandler webSocketHandler)
        {
            nextMessage.Body     = _messageParams.CommandError;
            nextMessage.Commands = null;
            var messageRepository = new MessageRepository(connectionService, _cache);

            return(await messageRepository.PostAnswerAsync(webSocketHandler, nextMessage, user.Login).ConfigureAwait(false));
        }
Пример #11
0
        private async Task <(bool, string, Message)> RunNextAsync(Message nextMessage, User user, IConnectionService connectionService, WebSocketHandler webSocketHandler)
        {
            var service = ServiceItemRepository.GetServiceItems().
                          FirstOrDefault(s => s.GUID.Equals(nextMessage.ServiceGuid));

            var(hasQueue, userMessages) = _users.GetMessages(nextMessage.UserGuid, QueueType.information);
            if (!hasQueue || userMessages.Count == 0)
            { // end of queue
                if (service?.Id == 1)
                {
                    nextMessage.Command     = 6;
                    nextMessage.CommandText = "220099";
                    return(await RunTemplateAsync(nextMessage, user, connectionService, webSocketHandler));
                }

                // for service != PI no template ..
                return(await RunErrorAsync(nextMessage, user, connectionService, webSocketHandler).ConfigureAwait(false));
            }

            var answers = new List <Message>();

            for (int i = 0; i < 3; i++)
            {
                if (userMessages.Count == 0)
                {
                    break;
                }
                answers.Add(userMessages.Dequeue());
            }

            if (userMessages.Count != 0)
            {
                answers.Last().Commands = CommandRepository.GetNext();
            }
            if (service?.Id == 1)
            {
                answers.Last().Commands.Add(new CommandItem(6)
                {
                    CommandText = "200", Title = "В начало", Template = "Перехожу в начало"
                });
            }

            var now = DateTime.Now;

            foreach (var answer in answers)
            {
                var tiks = now.Ticks - answer.Created.Value.Ticks;
                answer.Date = answer.Date.AddTicks(tiks);

                var messageRepository = new MessageRepository(connectionService, _cache);
                var(success, error, _) = await messageRepository.PostAnswerAsync(webSocketHandler, answer, user.Login).ConfigureAwait(false);

                if (!success)
                {
                    return(false, error, null);
                }
                // log error
            }

            _users.SetLastMessageID(nextMessage.UserGuid);
            return(true, null, null);
        }
Пример #12
0
 public ChartConnection(WebSocketHandler handler) : base(handler)
 {
 }
Пример #13
0
        private async Task OpenWebsocketConnection(HttpContext context, WebSocket webSocket)
        {
            Console.WriteLine(DateTime.Now + " | Connected: " + context.Connection.RemoteIpAddress + ":" + context.Connection.RemotePort + " connected");
            var buffer = new byte[1024 * 4];
            WebSocketHandler webSocketHandler = new WebSocketHandler(webSocket);
            await webSocketHandler.Send(new Command("Connected", null));

            try
            {
                await webSocketHandler.ExtractCompleteMessage(buffer);

                if (webSocketHandler.ReceivedCommand.CommandName == "Login")
                {
                    await UserManager.HandleLogin(webSocketHandler);
                }
            }
            catch (OperationCanceledException ex)
            {
                await webSocketHandler.Send(new Command("LoginTimeout", null));

                Console.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.ToString());
            }

            try
            {
                if (webSocketHandler.ConnectedUserToken != "")
                {
                    await ServerSettingsHandler.RegisterUser(webSocketHandler.User, webSocketHandler.ConnectedUserToken);

                    await SDaysTDieServerHandler.RegisterUser(webSocketHandler.User, webSocketHandler.ConnectedUserToken);

                    while (!webSocketHandler.WebSocket.CloseStatus.HasValue)
                    {
                        await webSocketHandler.ExtractCompleteMessage(buffer);

                        if (webSocketHandler.ReceivedCommand?.CommandName == "GetUser")
                        {
                            await UserManager.GetUser(webSocketHandler);
                        }
                        else if (webSocketHandler.ReceivedCommand?.CommandName == "GetUsers")
                        {
                            await UserManager.GetUsers(webSocketHandler);
                        }
                        else if (webSocketHandler.ReceivedCommand?.CommandName == "ChangePassword")
                        {
                            await UserManager.ChangePassword(webSocketHandler);
                        }
                        else if (webSocketHandler.ReceivedCommand?.CommandName == "CreateUser")
                        {
                            await UserManager.CreateUser(webSocketHandler);
                        }
                        else if (webSocketHandler.ReceivedCommand?.CommandName == "EditUser")
                        {
                            await UserManager.EditUser(webSocketHandler);
                        }
                        else if (webSocketHandler.ReceivedCommand?.CommandName == "DeleteUser")
                        {
                            await UserManager.DeleteUser(webSocketHandler);
                        }
                        else if (webSocketHandler.ReceivedCommand?.CommandName == "LoggedInUserHasRights")
                        {
                            await UserManager.LoggedInUserHasRights(webSocketHandler);
                        }
                        else if (webSocketHandler.ReceivedCommand?.CommandName == "AddServerSetting")
                        {
                            await ServerSettingsHandler.AddServerSettings(webSocketHandler);
                        }
                        else if (webSocketHandler.ReceivedCommand?.CommandName == "EditServerSettings")
                        {
                            await ServerSettingsHandler.EditServerSettings(webSocketHandler);
                        }
                        else if (webSocketHandler.ReceivedCommand?.CommandName == "DeleteServerSettings")
                        {
                            await ServerSettingsHandler.DeleteServerSettings(webSocketHandler);
                        }
                        else if (webSocketHandler.ReceivedCommand?.CommandName == "GetServerSettingsOfLoggedInUser")
                        {
                            await ServerSettingsHandler.GetServerSettingsOfLoggedInUser(webSocketHandler);
                        }
                        else if (webSocketHandler.ReceivedCommand?.CommandName == "StartServer")
                        {
                            await SDaysTDieServerHandler.StartServer(webSocketHandler);
                        }
                        else if (webSocketHandler.ReceivedCommand?.CommandName == "StopServer")
                        {
                            await SDaysTDieServerHandler.StopServer(webSocketHandler);
                        }
                        else if (webSocketHandler.ReceivedCommand?.CommandName == "ConnectTelnet")
                        {
                            await SDaysTDieServerHandler.ConnectTelnet(webSocketHandler);
                        }
                    }
                }
            }
            catch (OperationCanceledException ex)
            {
                await webSocketHandler.Send(new Command("ConnectionTimeout", null));

                Console.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            try
            {
                await webSocketHandler.Send(new Command("Disconnected", null));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Could not send Disconnected message, Exception: " + ex.Message);
            }
            Console.WriteLine(DateTime.Now + " | " + context.Connection.RemoteIpAddress + ":" + context.Connection.RemotePort + " disconnected");
            await webSocket.CloseAsync(webSocketHandler.Result.CloseStatus.Value, webSocketHandler.Result.CloseStatusDescription, CancellationToken.None);
        }
Пример #14
0
 public MyWebSocketClient(WebSocketHandler socket)
 {
     Start();
     this.socket = socket;
 }
 public JsonRpcClientWebSocketConnection(WebSocketHandler client)
 {
     this.client = client ?? throw new ArgumentNullException(nameof(client));
     this.client.OnMessageReceive += Client_OnMessageReceive;
 }
Пример #16
0
 static void Main(string[] args)
 {
     Console.WriteLine("Start:");
     WebSocketHandler.WebServerInit();
     Console.ReadKey();
 }
Пример #17
0
        public async Task <(bool, string, Message)> RunHelloTemplateAsync(Message nextMessage, User user, ServiceItem service,
                                                                          IConnectionService connectionService, WebSocketHandler webSocketHandler)
        {
            if (service.Id == 1)
            {
                nextMessage.CommandText = "200";
            }
            else if (service.Id == 2)
            {
                nextMessage.CommandText = "100";
            }
            else if (service.Id == 3)
            {
                nextMessage.CommandText = "300";
            }
            else if (service.Id == 4)
            {
                nextMessage.CommandText = "400";
            }
            else
            {
                nextMessage.CommandText = "999";
            }

            return(await RunTemplateAsync(nextMessage, user, connectionService, webSocketHandler));
        }
Пример #18
0
 public DkHostedServiceChat(WebSocketHandler objWebSocketHandler)
 {
     _objWebSocketHandler = objWebSocketHandler;
 }
Пример #19
0
        private async Task <(bool, string, Message)> RunSetServiceAsync(Message nextMessage, User user,
                                                                        IConnectionService connectionService, WebSocketHandler webSocketHandler, AnswerService _answerService)
        {
            if (!Guid.TryParse(nextMessage.CommandText ?? "", out var serviceGuid))
            {
                return(await RunErrorAsync(nextMessage, user, connectionService, webSocketHandler).ConfigureAwait(false));
            }

            var service = ServiceItemRepository.GetServiceItems().
                          FirstOrDefault(s => s.GUID.Equals(serviceGuid) || s.GUID.Equals(nextMessage.ServiceGuid));

            if (service != null && service.Id != 1)
            {                                                                   // valid ServiceGuid (for service != PI) - say hello
                _users.ClearMessages(nextMessage.UserGuid, QueueType.category); // TODO if(!) {LOG}
                nextMessage.ServiceGuid = service.GUID;
                return(await RunHelloTemplateAsync(nextMessage, user, service, connectionService, webSocketHandler));
            }

            bool            hasQueue;
            Queue <Message> userMessages;
            var             messageRepository = new MessageRepository(connectionService, _cache);

            if (service is null)
            {
                LogAIResult(connectionService, nextMessage, "wrong serviceID");

                (hasQueue, userMessages) = _users.GetMessages(nextMessage.UserGuid, QueueType.service);
                if (!hasQueue || userMessages.Count == 0)
                {
                    LogAIResult(connectionService, nextMessage, "everything was wrong with serviceID");

                    nextMessage.Body        = _messageParams.NotFound;
                    nextMessage.CommandText = null;
                }
                else
                {
                    nextMessage = userMessages.Dequeue();
                }

                return(await messageRepository.PostAnswerAsync(webSocketHandler, nextMessage, user.Login).ConfigureAwait(false));
            }

            if (!nextMessage.ServiceGuid.HasValue)
            {
                LogAIResult(connectionService, nextMessage, $"let set serviceID={service.Id}");
            }

            // valid ServiceGuid (service == PI)
            nextMessage.ServiceGuid = service.GUID;

            _users.ClearMessages(nextMessage.UserGuid, QueueType.service);  // TODO if(!) {LOG}
            _users.ClearMessages(nextMessage.UserGuid, QueueType.category); // TODO if(!) {LOG}

            //(hasQueue, userMessages) = _users.GetMessages(nextMessage.UserGuid, QueueType.category);
            //if (!hasQueue || userMessages.Count == 0)
            //{
            //    LogAIResult(connectionService, nextMessage, "everything was wrong with QuestionCategory");

            //    nextMessage.Body = _messageParams.NotFound;
            //    nextMessage.CommandText = null;
            //}
            //else
            //{
            //    nextMessage = userMessages.Dequeue();
            //    _users.ClearMessages(nextMessage.UserGuid, QueueType.category); // TODO if(!) {LOG}
            //}

            if (!nextMessage.SourceId.HasValue)
            { // new empty context - say hello
                nextMessage.Command     = 6;
                nextMessage.CommandText = "200";
                return(await RunTemplateAsync(nextMessage, user, connectionService, webSocketHandler));
            }

            //else if(nextMessage.QuestionCategory == 2)
            // let ask AI question = body of old message (id=SourceId)
            var(isMessageFound, errorGettingMessage, messageWithQuestion) = await messageRepository.GetAsync((ulong)nextMessage.SourceId).ConfigureAwait(false);

            if (!isMessageFound)
            { // wrong source..
                nextMessage.Command     = 6;
                nextMessage.CommandText = "220099";
                return(await RunTemplateAsync(nextMessage, user, connectionService, webSocketHandler));
            }

            messageWithQuestion             = JsonSerializer.Deserialize <Message>(messageWithQuestion.JsonData, GPNJsonSerializer.Option());
            messageWithQuestion.ServiceGuid = service.GUID;

            var(successParce, queryType, iid) = PresetQuestionFilter.ParseQuestion(messageWithQuestion.Body);
            if (successParce && queryType == 5)
            {
                nextMessage.QuestionCategory = 3;
            }
            else
            {
                if (queryType > 0 && queryType < 5)
                {
                    nextMessage.QuestionCategory = 2;
                }
                else
                {
                    nextMessage.QuestionCategory = 1;
                }
            }


            if (nextMessage.QuestionCategory == 1)
            {
                nextMessage.Body        = "поиск..";
                nextMessage.CommandText = null;
                var(success, error, _)  = await messageRepository.PostAnswerAsync(webSocketHandler, nextMessage, user.Login).ConfigureAwait(false);

                success = await _answerService.GetSearch(messageWithQuestion, user, service.Id).ConfigureAwait(false);

                if (success)
                {
                    await RunNextAsync(nextMessage, user, connectionService, webSocketHandler);
                }
                return(success, error, null);
            }
            else if (nextMessage.QuestionCategory == 2)
            {
                await _answerService.GetAggregate(messageWithQuestion, user, service.Id);

                return(true, null, null);
            }
            else // nextMessage.QuestionCategory == 3
            {
                nextMessage.Command     = 6;
                nextMessage.CommandText = "220010";
                nextMessage.Iid         = iid;

                return(await RunTemplateAsync(nextMessage, user, connectionService, webSocketHandler));
            }
Пример #20
0
 public Client(WebSocketHandler socket)
 {
     this.Id     = Guid.NewGuid();
     this.Socket = socket;
 }
Пример #21
0
        private async Task <(bool, string, Message)> RunTemplateAsync(Message nextMessage, User user, IConnectionService connectionService, WebSocketHandler webSocketHandler)
        {
            var template = _dialog.Templates.Where(t => t.CommandText == (nextMessage.CommandText ?? "")).FirstOrDefault();

            if (template is null)
            {
                return(await RunErrorAsync(nextMessage, user, connectionService, webSocketHandler).ConfigureAwait(false));
            }

            nextMessage.GUID        = Guid.NewGuid();
            nextMessage.CommandText = template.CommandText;
            nextMessage.Commands    = template.Commands;
            nextMessage.Body        = template.Body;

            var messageRepository = new MessageRepository(connectionService, _cache);

            return(await messageRepository.PostAnswerAsync(webSocketHandler, nextMessage, user.Login).ConfigureAwait(false));
        }
 public override void OnMessage(WebSocket socket, WebSocketHandler handler, JsonData message)
 {
 }
Пример #23
0
 public AuthorizedConnection(WebSocketHandler handler) : base(handler)
 {
 }
Пример #24
0
 public static void StartDiscordWebSocket()
 {
     webSocketHandler?.Dispose();
     webSocketHandler = new WebSocketHandler();
     Task.Run(() => webSocketHandler.SetupDiscordWebSocket());
 }
Пример #25
0
        private static async Task <Command> GetUsers(Func <Task <GetUsersResponse> > getAction, string actionName, WebSocketHandler webSocketHandler)
        {
            User             user     = JsonConvert.DeserializeObject <User>(webSocketHandler.ReceivedCommand.CommandData.ToString());
            GetUsersResponse response = null;

            if (RightControl.IsGranted(webSocketHandler.ConnectedUserToken, actionName, "User"))
            {
                response = await getAction();
            }
            else if (RightControl.IsGranted(webSocketHandler.ConnectedUserToken, actionName + "_" + user.Username, "User"))
            {
                response = await getAction();
            }
            else
            {
                response = new GetUsersResponse(GetUsersResult.RIGHT_VIOLATION, null);
            }
            return(new Command(actionName + "Response", response));
        }
Пример #26
0
        private void OnReceived(object sender, WebSocketReceivedEventArgs e)
        {
            try
            {
                // Syntax: see SQLReaderCommand or id:int for follow up reading
                // e.g. see SQLReaderCommand as JSON serialized
                // e.g. 42

                // Library:
                // SQLReader.ExecuteQuery(query, Dictonary<string, string> wildcards...) : JsonObject[maxRows]
                // SQLReader.ExecuteStoredQuery(path, Dictonary<string, string> wildcards...) : JsonObject[maxRows]
                // SQLReader.ExecuteQuery(query, int maxRows, Dictonary<string, string> wildcards...) : QueryReader
                // SQLReader.ExecuteStoredQuery(path, int maxRows, Dictonary<string, string> wildcards...) : QueryReader
                // myQueryReader.GetNextResults() : JsonObject[maxRows] oder null wenn nichts mehr verfügbar

                int id;
                if (int.TryParse(e.Message, out id))
                {
                    // GetNextResults
                    // Continue reading already opened reader

                    SQLReaderCommand commandFound = null;
                    if (this.storedReaders.ContainsKey(e.WebSocket))
                    {
                        foreach (SQLReaderCommand command in this.storedReaders[e.WebSocket])
                        {
                            if (command.Id == id)
                            {
                                commandFound = command;
                                break;
                            }
                        }
                    }

                    if (commandFound != null)
                    {
                        Logging.Debug($"SQLReader continue reading request with id: {id} ({commandFound.TransferredRowCount} / {commandFound.BufferedData.Count})");

                        WebSocketHandler.SendTo(e.WebSocket, this.ReadRows(commandFound));

                        if (commandFound.TransferredRowCount >= commandFound.BufferedData.Count)
                        {
                            commandFound.TransferredRowCount = 0;
                            commandFound.BufferedData.Clear();
                        }
                    }
                    else
                    {
                        Logging.Error("SQLReader could not find id to continue reading: " + id);
                    }
                }
                else
                {
                    SQLReaderCommand command;
                    try
                    {
                        using (StringReader stream = new StringReader(e.Message))
                        {
                            JsonSerializer serializer = new JsonSerializer();
                            command = (SQLReaderCommand)serializer.Deserialize(stream, typeof(SQLReaderCommand));
                        }
                    }
                    catch (Exception ex)
                    {
                        Logging.Error("SQLReader could not parse command: " + e.Message, ex);
                        return;
                    }

                    Logging.Debug("SQLReader request: " + command);

                    string query;

                    if (command.IsStoredQuery)
                    {
                        string absolutePath = Path.Combine(Program.Config.RootDirectory, SQLReader.STORED_QUERY_FOLDER, command.Query.Replace("/", "\\").TrimStart('\\'));
                        absolutePath = Uri.UnescapeDataString(absolutePath);
                        if (File.Exists(absolutePath) == false)
                        {
                            Logging.Error($"Query-File not found: {command.Query}");
                            return;
                        }

                        query = File.ReadAllText(absolutePath);
                    }
                    else
                    {
                        query = command.Query;
                    }

                    if (command.Wildcards != null)
                    {
                        foreach (KeyValuePair <string, string> wildcard in command.Wildcards)
                        {
                            query = query.Replace(wildcard.Key, wildcard.Value);
                        }
                    }

                    Database.Instance.ExecuteReader(query, (DatabaseReaderCallback data) =>
                    {
                        StringBuilder stringBuilder = new StringBuilder();
                        StringWriter stringWriter   = new StringWriter(stringBuilder);
                        using (JsonWriter jsonWriter = new JsonTextWriter(stringWriter))
                        {
                            jsonWriter.WriteStartObject();

                            int fields = data.Records.FieldCount;

                            for (int i = 0; i < fields; i++)
                            {
                                jsonWriter.WritePropertyName(data.Records.GetName(i));
                                jsonWriter.WriteValue(data.Records[i]);
                            }

                            jsonWriter.WriteEndObject();

                            command.BufferedData.Add(stringWriter.ToString());
                        }
                    });

                    if (command.MaxRows == null)
                    {
                        WebSocketHandler.SendTo(e.WebSocket, command.Id + ":" + this.ReadRows(command));
                    }
                    else
                    {
                        if (this.storedReaders.ContainsKey(e.WebSocket) == false)
                        {
                            this.storedReaders.Add(e.WebSocket, new List <SQLReaderCommand>());
                        }

                        foreach (SQLReaderCommand otherCommand in this.storedReaders[e.WebSocket])
                        {
                            if (otherCommand.Id == command.Id)
                            {
                                this.storedReaders[e.WebSocket].Remove(otherCommand);
                                break;
                            }
                        }

                        this.storedReaders[e.WebSocket].Add(command);
                    }
                }

                this.CleanUp();
            }
            catch (Exception ex)
            {
                Logging.Error($"Error during receiving SQLReader request: {e.Message}", ex);
            }
        }
 public WebSocketManagerMiddleware(RequestDelegate next, WebSocketHandler webSocketHandler)
 {
     _next             = next;
     _webSocketHandler = webSocketHandler;
     _log = LogManager.GetLogger(typeof(WebSocketManagerMiddleware));
 }
 public override async void OnMessage(WebSocket socket, WebSocketHandler handler, JsonData message)
 {
     base.OnMessage(socket, handler, message);
 }
Пример #29
0
 public static IGameUserManager CreateGameUserManager(WebSocketHandler webSocketHandler, User host)
 {
     return(new GameUserManager(webSocketHandler, host));
 }
Пример #30
0
 public static IGameMessageHandler CreateGameMessageHandler(IGameUserManager gameUserManager, WebSocketHandler webSocketHandler)
 {
     return(new GameMessageHandler(gameUserManager, webSocketHandler));
 }
Пример #31
0
 public static IApplicationBuilder MapSockets(this IApplicationBuilder app, PathString path,
                                              WebSocketHandler handler)
 {
     return(app.Map(path, (builder) => builder.UseMiddleware <SocketMiddleware>(handler)));
 }