Ejemplo n.º 1
0
        public JsonResponce Get([FromHeader] string Authorization)
        {
            var(success, _, _, _, _) = _users.ValidateToken(Authorization);
            if (!success)
            {
                return new JsonResponce {
                           Success = false, Message = "404"
                }
            }
            ;

            var services = ServiceItemRepository.GetServiceItems();

            return(new JsonResponce()
            {
                Data = services, Total = services.Count
            });
        }
    }
Ejemplo n.º 2
0
        public static async Task <(bool, string, Message)> FindServiceByQuestion(Message source, User user,
                                                                                 UsersRepository users, MessageParams messageParams)
        {
            var startTime     = DateTime.Now;
            var question      = source.Body;
            var lastMessageID = users.GetLastMessageID(user.GUID);

            var(success, error, apsolutionsAnswer) = await GetCategorized(user.GUID, user.Fio, user.Position, user.EmploymentDate, question).ConfigureAwait(false);

            if (users.IsOlderThenLast(user.GUID, lastMessageID))
            {
                return(false, null, null);
            }

            var answerHasError = !success || apsolutionsAnswer is null || apsolutionsAnswer.ServiceIDs is null || apsolutionsAnswer.QuestionCategories is null;
            var validServises  = apsolutionsAnswer?.ServiceIDs?
                                 .Where(sa => sa.ServiceID != 0 && ServiceItemRepository.GetServiceItems().Exists(s => s.Id == sa.ServiceID));

            answerHasError = validServises is null || validServises.Count() == 0;

            if (answerHasError)
            {
                users.SetLastMessageID(user.GUID);
                return(true, error, Message.Answer(source, success ? messageParams.NotFound : messageParams.AIError, DateTime.Now.Ticks - startTime.Ticks));
            }

            Message firstAnswer            = null;
            var     userMessagesForService = new Queue <Message>();

            foreach (var apsolutionService in validServises)
            {
                var serviceItem = ServiceItemRepository.GetServiceItems().FirstOrDefault(s => s.Id == apsolutionService.ServiceID);
                var commands    = CommandRepository.GetYesNo(source.ID);
                commands[0].CommandText = serviceItem.GUID.ToString();
                var answer = new Message
                {
                    SourceId    = source.ID ?? 0,
                    UserGuid    = source.UserGuid,
                    Iid         = source.Iid,
                    Date        = source.Date,
                    ServiceGuid = source.ServiceGuid,

                    Body = $"Используем '{serviceItem.Title}'?",

                    GUID     = Guid.NewGuid(),
                    Command  = 0,
                    IsFile   = false,
                    Commands = commands,
                    Style    = 1
                };

                if (firstAnswer is null)
                {
                    firstAnswer      = answer;
                    firstAnswer.Date = firstAnswer.Date.AddTicks(DateTime.Now.Ticks - startTime.Ticks);
                }
                else
                {
                    userMessagesForService.Enqueue(answer);
                }
            }

            users.SetMessages(user.GUID, QueueType.service, userMessagesForService);

            var validCategories = apsolutionsAnswer?.QuestionCategories?
                                  .Where(qc => qc.QuestionCategory != 0 && QuestionCategoryRepository.GetQuestionCategories().Exists(s => s.Id == qc.QuestionCategory));

            var userMessagesForQuestionCategory = new Queue <Message>();

            foreach (var apsolutionsCategory in validCategories)
            {
                var answer = new Message
                {
                    SourceId         = source.ID ?? 0,
                    UserGuid         = source.UserGuid,
                    Iid              = source.Iid,
                    Date             = source.Date,
                    ServiceGuid      = source.ServiceGuid,
                    QuestionCategory = apsolutionsCategory.QuestionCategory,

                    Body = "",
                    GUID = Guid.NewGuid(),
                };

                userMessagesForQuestionCategory.Enqueue(answer);
            }

            users.SetMessages(user.GUID, QueueType.category, userMessagesForQuestionCategory);
            users.SetLastMessageID(user.GUID);

            return(true, null, firstAnswer);
        }
Ejemplo n.º 3
0
        public async Task <JsonResponce> GetAsync([FromQuery] Guid serviceGuid, [FromQuery] long limit, [FromQuery] long start, [FromQuery] long page)
        {
            var login = Request.Headers.TryGetValue("UserLogin", out var userLoginStr) ? userLoginStr.ToString() : "";

            var(success, user) = _users.GetUser(login);
            //_logger.LogInformation("{source}{action}{authorization}{remoteIp}", nameof(MessageController), Request.Method, $"{success}={fio}/{userGuid}", Request.HttpContext.Connection.RemoteIpAddress);
            if (!success)
            {
                return new JsonResponce {
                           Success = false, Message = "404"
                }
            }
            ;

            if (limit == 0)
            {
                limit = 300;
            }
            var messageRepository = new MessageRepository(_connectionService, _cache);

            var(successGet, error, count, results, isHello, isStartFromZero) =
                await messageRepository.GetAsync(user.GUID, serviceGuid, Request.QueryString.Value, _messageParams, limit).ConfigureAwait(false);

            if (!successGet)
            {
                return new JsonResponce()
                       {
                           Success = false, Message = error
                       }
            }
            ;

            if (isHello)
            {
                return new JsonResponce()
                       {
                           Data = results, Total = count
                       }
            }
            ;

            var(successLast, errorLast, last) = await messageRepository.GetLastAsync(user.GUID).ConfigureAwait(false);

            if (!successLast || last is null)
            {
                return new JsonResponce {
                           Success = false, Message = _messageParams.CommandError
                }
            }
            ;

            var lastServiceGuid = last.ServiceGuid ?? Guid.Empty;
            var service         = ServiceItemRepository.GetServiceItems().FirstOrDefault(s => s.GUID == lastServiceGuid);
            var requiredService = ServiceItemRepository.GetServiceItems().FirstOrDefault(s => s.GUID == serviceGuid);

            if ((service?.Id ?? 0) != (requiredService?.Id ?? 0) && requiredService != null)
            { // Context changed привет из контекста
                var hello = MessageRepository.Hello(_messageParams.Hello, user.GUID, serviceGuid, commandText: requiredService.GUID.ToString());

                (success, error, hello) = await _commnadExecutor.RunHelloTemplateAsync(hello, user, requiredService, _connectionService, _webSocketHandler);

                if (!success)
                {
                    return new JsonResponce()
                           {
                               Success = false, Message = error
                           }
                }
                ;

                results.Add(hello);
                count++;
            }

            results.Reverse();
            return(new JsonResponce()
            {
                Data = results, Total = count
            });
        }
 public ServiceItemService()
 {
     _serviceItemRepository = new ServiceItemRepository();
 }
Ejemplo n.º 5
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));
            }
Ejemplo n.º 6
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);
        }