using RestSharp; using System.Threading; using xCommons.Providers; using xBotService.Models; using xCommons.Extensions; using xBotService.Constants; using xBotService.Extensions; using xBotService.Interfaces; using xIdentityModels.Models; using System.Threading.Tasks; using xHttpService.Constants; using xBotService.Configuration; using System.Collections.Generic; using xIdentityService.Interfaces; using Microsoft.Extensions.Logging; using xExceptions.Constants; using System; using xBotService.Models.Dtos; using xIdentityService.Security; namespace xBotService.Providers { public class XBotProvider : IXBotProvider { // private readonly ILogger logger; private readonly IXSecurityProvider securityProvider; private readonly IXIdentityHttpProvider httpProvider; private readonly XValidationProvider validationProvider; private readonly XBotServiceConfiguration configuration; public XBotProvider( ILogger logger, IXSecurityProvider securityProvider, IXIdentityHttpProvider httpProvider, XValidationProvider validationProvider, XBotServiceConfiguration configuration ) { // this.logger = logger; this.securityProvider = securityProvider; this.httpProvider = httpProvider; this.configuration = configuration; this.validationProvider = validationProvider; } // #region Tools ... /// /// Get an Instance of RestClient ... /// /// public RestClient GetRestClient( XTokenResponse tokens = null ) { // var result = httpProvider.GetRestClient( tokens: tokens, baseUrl: configuration.BaseRoute ); // result.Timeout = configuration.DefaultClientTimeout; // return result; } /// /// Get an Instance of RestRequest ... /// public RestRequest GetRestRequest( XBotEndpoints endpoint, bool addXPoweredValue = true, IDictionary @params = null, IDictionary headers = null, IDictionary queryStrings = null ) { // var result = httpProvider.GetRestRequest( @params: @params, headers: headers, queryStrings: queryStrings, addXPoweredValue: addXPoweredValue, endpoint: endpoint.GetStringValue() ); // return result; } #endregion // #region Service ... /// /// Retrieve Bot Info ... /// /// /// public virtual async Task GetMe( CancellationToken cancellationToken = default ) { // var client = GetRestClient(); var request = GetRestRequest( endpoint: XBotEndpoints.GetMe, @params: new Dictionary { { XBotParams.XTokenParam, configuration.Token } } ); // var response = await httpProvider.RunRestRequest>( client: client, request: request, method: XHttpMethod.GET, cancellationToken: cancellationToken ); // // Ensure Success ... response.EnsureBotResponseSucceed(); // var result = response.Result; // return result; } /// /// Retrieve Messages ... /// /// /// /// public virtual async Task> GetUpdates( XBotUpdatesRequest requestModel, CancellationToken cancellationToken = default ) { // requestModel = requestModel.Normalize(); // var client = GetRestClient(); var request = GetRestRequest( endpoint: XBotEndpoints.GetUpdates, @params: new Dictionary { { XBotParams.XTokenParam, configuration.Token } }, queryStrings: new Dictionary { { XBotParams.XLimit, requestModel.Limit.ToString() }, { XBotParams.XOffest, requestModel.Offset.ToString() }, { XBotParams.XTimeout, requestModel.Timeout.ToString() } } ); // var response = await httpProvider.RunRestRequest>>( client: client, request: request, method: XHttpMethod.GET, cancellationToken: cancellationToken ); // // Ensure Success ... response.EnsureBotResponseSucceed(); // var result = response.Result; // return result; } /// /// Sending Simple String Message to Bot ... /// /// /// /// public virtual async Task SendMessage( XBotSendMessageRequest requestModel, CancellationToken cancellationToken = default ) { // // Validate ... if (!requestModel.IsValid()) { XException.InvalidArgs.Throw(); } // var client = GetRestClient(); var request = GetRestRequest( endpoint: XBotEndpoints.SendMessage, @params: new Dictionary { { XBotParams.XTokenParam, configuration.Token } } ); // var req = requestModel.ToDto(); request.AddJsonBody(req.ToJSON()); // var response = await httpProvider.RunRestRequest>( client: client, request: request, method: XHttpMethod.POST, cancellationToken: cancellationToken ); // // Ensure Success ... response.EnsureBotResponseSucceed(); // var result = response.Result; // return result; } /// /// Show Verification Request Menu ... /// /// /// /// /// public virtual async Task ShowVerificationMenu( long botUserId, string label = XBotMessageIds.XBotRequestVerificationCodeLabel, CancellationToken cancellationToken = default ) { // // Validate ... if (botUserId <= 0 || label.IsNullOrEmpty()) { XException.InvalidArgs.Throw(); } // // Markup for Keyboards ... var markup = XBotReplyMarkup .InlineKeyboardMarkup(new XBotInlineKeyboardMarkup { InlineKeyboard = [ [ new XBotInlineKeyboardButton{ Text = label, CallbackData = XBotMessageIds.XBotRequestVerificationCode } ] ] }); // var requestModel = new XBotSendMessageRequest { ChatId = botUserId, ReplyMarkup = markup.ReplyMarkup, Text = XBotMessageIds.XBotRequestVerificationCodeMessageText, }; // var result = await SendMessage( requestModel: requestModel, cancellationToken: cancellationToken ); // return result; } /// /// Send Verification Code to Requests ... /// /// /// /// public virtual async Task SendVerificationCode( XBotUserDto botUser, CancellationToken cancellationToken = default ) { // // Validate ... if ( botUser.IsNullOrDefault() || botUser.BotUserId <= 0) { XException.InvalidArgs.Throw(); } // // Check User not Verified ... if (botUser.VerifiedOn.HasValue) { XException.NotAllowed.Throw(); } // var code = securityProvider .Encrypt(botUser.BotUserId.ToString()) .ToMd5String(); // var message = XBotMessageIds.XBotVerificationCodeMessageText .ApplyTemplates(new Dictionary { { XBotParams.XVerificationTokenParam, code }, { XBotParams.XTTLInMinuteParam, configuration.VerificationCodeTTL.ToString() }, }); // var response = await SendMessage( cancellationToken: cancellationToken, requestModel: new XBotSendMessageRequest { Text = message, ChatId = botUser.BotUserId, } ); // return response; } /// /// an Accept for Exit Loading on Bot ... /// /// /// /// /// /// // public virtual async Task AnswerCallbackQuery( // string callbackQueryId, // string text = null, // bool showAlert = false, // CancellationToken cancellationToken = default // ) // { // // // // Validation ... // validationProvider.GroupValidationBuilder() // .AddNotEmpty(callbackQueryId) // .ValidateGroup(); // // // var client = GetRestClient(); // var request = GetRestRequest( // endpoint: XBotEndpoints.AnswerCallbackQuery, // @params: new Dictionary // { // { XBotParams.XTokenParam, configuration.Token } // } // ); // // // request.AddJsonBody(new // { // text = text, // show_alert = showAlert, // callback_query_id = callbackQueryId, // }); // // // var response = await httpProvider.RunRestRequest( // client: client, // request: request, // method: XHttpMethod.POST, // cancellationToken: cancellationToken // ); // // // return response; // } /// /// Remove Inline Keyboard After Click (Optional) ... /// /// /// /// /// // public virtual async Task RemoveInlineKeyboard( // long chatId, // long messageId, // CancellationToken cancellationToken = default // ) // { // // // // Validation ... // if (chatId <= 0 || messageId <= 0) // { // XException.InvalidArgs.Throw(); // } // // // var client = GetRestClient(); // var request = GetRestRequest( // endpoint: XBotEndpoints.EditMessageReplyMarkup, // @params: new Dictionary // { // { XBotParams.XTokenParam, configuration.Token } // } // ); // // // request.AddJsonBody(new // { // chat_id = chatId, // message_id = messageId, // reply_markup = new { inline_keyboard = new List>() } // }); // // // var response = await httpProvider.RunRestRequest( // client: client, // request: request, // method: XHttpMethod.POST, // cancellationToken: cancellationToken // ); // // // return response; // } /// /// Set Webhook for Retrieve Messages on Recieved ... /// /// /// /// /// // public virtual async Task SetWebhook( // string webhookUrl, // string secretToken = null, // CancellationToken cancellationToken = default // ) // { // // // var client = GetRestClient(); // var request = GetRestRequest( // endpoint: XBotEndpoints.SetWebhook, // @params: new Dictionary // { // { XBotParams.XTokenParam, configuration.Token } // } // ); // // // request.AddJsonBody(new // { // url = webhookUrl, // secret_token = secretToken // }); // // // var iResponse = await httpProvider.RunRestRequest( // client: client, // request: request, // method: XHttpMethod.POST, // cancellationToken: cancellationToken // ); // var response = iResponse?.Ok ?? false; // // // return response; // } #endregion // #region Private ... #endregion } }