public override async Task <(bool, string, long, List <Message>)> GetAsync( Dictionary <string, Condition[]> dictWhere, CSSet setConditionOr = null, Dictionary <string, string> dictOrder = null, long limit = 0, bool onlyCount = false) { var(success, error, count, results) = await base.GetAsync(dictWhere, setConditionOr, dictOrder, limit, onlyCount : onlyCount).ConfigureAwait(false); if (!success) { return(false, error, 0, null); } var messages = new List <Message>(); foreach (var result in results) { var message = JsonSerializer.Deserialize <Message>(result.JsonData, GPNJsonSerializer.Option()); PrepareForClient(message, result); messages.Add(message); } return(true, null, count, messages); }
public virtual async Task <(bool, string, long, List <T>)> GetAsync( Dictionary <string, Condition[]> dictWhere, CSSet setConditionOr = null, Dictionary <string, string> dictOrder = null, long limit = 0, bool onlyCount = false) { using var db = _connectionService.DataBase(); var query = ""; var parameters = ""; try { // WHERE var(strWhere, objParams, strInfo) = Where(Model, dictWhere, setConditionOr); parameters = JsonSerializer.Serialize(objParams, GPNJsonSerializer.Option()); // SELECT COUNT(*) var(success, sql) = GetQuery(Model, "SelectCount", db.Database); if (!success) { return(false, "'SelectCount' command not found", 0, null); } query = $"{sql}{strWhere}"; StopWatch = Stopwatch.StartNew(); Count = await db.ExecuteScalarAsync <long>(query, objParams).ConfigureAwait(false); LogTime(query, strInfo); if (Count == 0) { return(true, null, 0, new List <T>()); } if (onlyCount) { return(true, null, Count, new List <T>()); } // SELECT (success, sql) = GetQuery(Model, "Select", db.Database); if (!success) { return(false, "'Select' command not found", 0, null); } // ORDER var strOrder = Order(Model, dictOrder); query = $"{sql}{strWhere}{strOrder}{(limit == 0 ? "" : $" LIMIT {limit}")}"; StopWatch.Restart(); var results = (await db.QueryAsync <T>(query, objParams).ConfigureAwait(false)).ToList(); LogTime(query, strInfo); db.Close(); return(true, null, Count, results); }
public async Task <(bool, string, Message)> PostHelloAsync(Message message) { message.JsonData = JsonSerializer.Serialize(message, GPNJsonSerializer.Option()); var(success, error, newData) = await base.PostAsync(message).ConfigureAwait(false); if (!success) { return(false, error, null); } PrepareForClient(message, newData); return(true, null, message); }
static async Task Main(string[] args) { var provider = new ServiceCollection() .AddMemoryCache() .BuildServiceProvider(); var cache = provider.GetService <IMemoryCache>(); var dbPIParams = new DBPIParams() { ConnectionString = "server=127.0.0.1;port=3307;uid=gpnadmin;pwd=8FxLWcquHb;database=pidump" }; var connectionService = new ConnectionService(dbPIParams); var errorNo = 0; for (ulong i = 10217; i < 15000; i++) { var(success, error, body) = await PI.GetInitiativeExportAsync(cache, i).ConfigureAwait(false); errorNo = success ? 0 : errorNo + 1; if (errorNo > 100) { break; } await Task.Delay(500); try { var initiative = success ? JsonSerializer.Deserialize <Initiative>(body, GPNJsonSerializer.Option()) : new Initiative() { Iid = i }; var apiLogWebRepository = new InitiativeRepository(connectionService); (success, _, _) = await apiLogWebRepository.PostAsync(initiative).ConfigureAwait(false); if (!success) { ; } } catch (Exception ex) { ; } } }
public async Task <(bool, string, Message)> PostMessageAsync(Message message, MessageParams messageParams) { if (message.GUID.Equals(Guid.Empty)) { return(false, "message.GUID.Equals.Empty", null); } if (message.Date < DateTime.UtcNow.AddDays(-1)) { return(false, "DateTime.Utc.error", null); } if (message.ServiceGuid is null) { message.ServiceGuid = Guid.Empty; } message.IsSending = false; message.JsonData = JsonSerializer.Serialize(message, GPNJsonSerializer.Option()); var(successLast, errorLast, last) = await GetLastAsync(message.UserGuid).ConfigureAwait(false); if (!successLast) { return(false, errorLast, null); } if (last is null) { var hello = Hello(messageParams.Hello, message.UserGuid, (Guid)message.ServiceGuid); hello.JsonData = JsonSerializer.Serialize(hello, GPNJsonSerializer.Option()); var(successHello, errorHello, _) = await PostAsync(hello).ConfigureAwait(false); if (!successHello) { return(false, errorHello, null); } await Task.Delay(1000).ConfigureAwait(false); } var(success, error, newData) = await base.PostAsync(message).ConfigureAwait(false); if (!success) { return(false, error, null); } PrepareForClient(message, newData); return(true, null, message); }
public async Task <bool> SendMessageAsync <T>(string login, WSMessage <T> message) { var socket = WebSocketConnectionManager.GetSocketById(login); if (socket == null || socket.State != WebSocketState.Open) { return(false); } var serializedMessage = JsonSerializer.Serialize(message, GPNJsonSerializer.Option()); var encodedMessage = Encoding.UTF8.GetBytes(serializedMessage); await socket.SendAsync(buffer : new ArraySegment <byte>(array: encodedMessage, offset: 0, count: encodedMessage.Length), messageType : WebSocketMessageType.Text, endOfMessage : true, cancellationToken : CancellationToken.None).ConfigureAwait(false); return(true); }
public async Task <(bool, string, Message)> PostAnswerAsync(WebSocketHandler webSocketHandler, Message message, string login) { if (message.GUID.Equals(Guid.Empty)) { return(false, "message.GUID.Equals.Empty", null); } if (message.Date < DateTime.UtcNow.AddDays(-1)) { return(false, "DateTime.Utc.error", null); } if (message.ServiceGuid is null) { message.ServiceGuid = Guid.Empty; } message.IsSending = false; message.JsonData = JsonSerializer.Serialize(message, GPNJsonSerializer.Option()); var(success, error, newData) = await base.PostAsync(message).ConfigureAwait(false); if (!success) { return(false, error, null); } PrepareForClient(message, newData); #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed if (webSocketHandler != null && login != null) { var x = WSMessage <Message> .EventNew(message); webSocketHandler.SendMessageAsync(login, x); } #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed return(true, null, message); }
private static async Task <(bool, string, ApsolutionsAggregate)> SearchAggregate(Guid Id, string FIO, string Position, DateTime EmploymentDate, long ServiceID, string Question) { var(client, request) = GetRequest("https://semsearch.apsolutions.ru/api/v1/question/service_request"); request.AddJsonBody(new { Profile = new { FIO, Id, Position, EmploymentDate }, Question }); try { var response = await client.ExecuteAsync(request).ConfigureAwait(false); var answer = JsonSerializer.Deserialize <ApsolutionsAggregate>(response.Content, GPNJsonSerializer.Option()); return(true, null, answer); } catch (Exception ex) { Log.Error("{source}: '{query}'. Error: '{error}'", "Apsolutions", Question, ex.Message); return(false, ex.Message, null); } }
private static async Task <(bool, string, ApsolutionsCategory)> GetCategorized(Guid Id, string FIO, string Position, DateTime EmploymentDate, string Question) { var(client, request) = GetRequest("https://semsearch.apsolutions.ru/api/v1/question/classify_extended"); request.AddJsonBody(new { Profile = new { FIO, Id, Position, EmploymentDate }, QuestionType = "1", Question, OnlySearchType = false }); try { var response = await client.ExecuteAsync(request).ConfigureAwait(false); var categories = JsonSerializer.Deserialize <ApsolutionsCategory>(response.Content, GPNJsonSerializer.Option()); return(true, null, categories); } catch (Exception ex) { Log.Error("{source}: '{query}'. Error: '{error}'", "Apsolutions", Question, ex.Message); return(false, ex.Message, null); } }
public static async Task <(bool, string, string)> GetInitiativeListAsync(IMemoryCache memoryCache, string email) { var(successToken, error, token) = await GetTokenAsync(memoryCache).ConfigureAwait(false); if (!successToken) { return(successToken, error, null); } var(client, request) = GetRequest("https://pi.gazprom-neft.ru/api/get/author_initiatives/", token); request.AddParameter("email", email); try { var response = await client.ExecuteAsync(request).ConfigureAwait(false); var gpnIList = JsonSerializer.Deserialize <GpnIList>(response.Content, GPNJsonSerializer.Option()); if (!gpnIList.Result.Equals("OK", StringComparison.InvariantCultureIgnoreCase)) { return(false, gpnIList.Error, null); } if (gpnIList.Data.Initiatives is null) { return(false, null, "Нет инициатив"); } var body = "Список инициатив:\n"; foreach (var key in gpnIList.Data.Initiatives.Keys) { body += $"{key}: '{gpnIList.Data.Initiatives[key]}'\n"; } return(true, null, body); } catch (Exception ex) { return(false, ex.Message, null); } }
public static async Task <(bool, string, string)> GetInitiativeStatusAsync(IMemoryCache memoryCache, ulong initiative) { var(successToken, error, token) = await GetTokenAsync(memoryCache).ConfigureAwait(false); if (!successToken) { return(successToken, error, null); } var(client, request) = GetRequest("https://pi.gazprom-neft.ru/api/get/initiative/", token); request.AddParameter("id", initiative); try { var response = await client.ExecuteAsync(request).ConfigureAwait(false); var gpnIStatus = JsonSerializer.Deserialize <GpnIStatus>(response.Content, GPNJsonSerializer.Option()); if (!gpnIStatus.Result.Equals("OK", StringComparison.InvariantCultureIgnoreCase)) { return(false, null, gpnIStatus.Error); } return(true, null, $"Статус инициативы {initiative} '{gpnIStatus.Data.Initiative.STATUS}'"); } catch (Exception ex) { return(false, ex.Message, null); } }
public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("allowAll", builder => { // Not a permanent solution, but just trying to isolate the problem builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }); }); services.AddMemoryCache(); services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.IgnoreNullValues = GPNJsonSerializer.Option().IgnoreNullValues; options.JsonSerializerOptions.PropertyNamingPolicy = GPNJsonSerializer.Option().PropertyNamingPolicy; options.JsonSerializerOptions.WriteIndented = GPNJsonSerializer.Option().WriteIndented; options.JsonSerializerOptions.PropertyNameCaseInsensitive = GPNJsonSerializer.Option().PropertyNameCaseInsensitive; }); services.Configure <MessageParams>(Configuration.GetSection("MessageParams")); var dialog = Configuration.GetSection("Dialog").Get <Dialog>(); foreach (var template in dialog.Templates) { template.Command = 6; if (template.Commands is null) { template.Commands = new List <CommandItem>(); } template.Commands.ForEach(c => { c.Template = c.Title; if (!string.IsNullOrEmpty(c.Email)) { c.Code = 5; var l = new List <string>() { c.CommandText ?? "" }; l.Add(c.Email); c.CommandText = string.Join(";", l); c.Email = null; } else if (!string.IsNullOrEmpty(c.Action)) { c.Code = 7; c.CommandText = $"{c.CommandText ?? ""};{c.Action}"; c.Action = null; } else { c.Code = 6; } }); } services.Configure <Dialog>(options => { options.Templates = dialog.Templates; }); services.Configure <DBServerParams>(Configuration.GetSection("DBServerParams")); services.AddTransient <IConnectionService, ConnectionService>(); services.AddSingleton <UsersRepository>(); var dbLogParams = Configuration.GetSection("DBLogParams").Get <DBLogParams>(); var logger = new LoggerConfiguration() .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.MySQL(dbLogParams) .CreateLogger(); Log.Logger = logger; services.Configure <DBPIParams>(Configuration.GetSection("DBPIParams")); SqlMapper.AddTypeHandler(new MySqlGuidTypeHandler()); SqlMapper.RemoveTypeMap(typeof(Guid)); SqlMapper.RemoveTypeMap(typeof(Guid?)); // TODO WS services.AddSingleton <WebSocketConnectionManager>(); services.AddTransient <WebSocketHandler>(); services.AddSingleton <CommnadExecutor>(); services.AddScoped <AnswerService>(); }
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)); }
public static List <QueryFilter> QueryFilters(this string queryString) { var queryDict = queryString.ToDictionary(); if (queryDict.TryGetValueIgnoreCase("filter", out var filterStr) && !string.IsNullOrEmpty(filterStr)) { try { return(JsonSerializer.Deserialize <List <QueryFilter> >(filterStr, GPNJsonSerializer.Option())); } catch { } } return(new List <QueryFilter>()); }