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; using xBotService.Interfaces.Dtos; 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; private readonly IXBotUserServiceProvider botUserServiceProvider; public XBotProvider( ILogger logger, IXSecurityProvider securityProvider, IXIdentityHttpProvider httpProvider, XValidationProvider validationProvider, XBotServiceConfiguration configuration, IXBotUserServiceProvider botUserServiceProvider ) { // this.logger = logger; this.httpProvider = httpProvider; this.configuration = configuration; this.securityProvider = securityProvider; this.validationProvider = validationProvider; this.botUserServiceProvider = botUserServiceProvider; } // #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(); } // // Normalize ... if (label.IsNullOrEmpty()) { label = XBotMessageIds.XBotRequestVerificationCodeLabel; } // // 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( long botUserId, CancellationToken cancellationToken = default ) { // // Validate ... if (botUserId <= 0) { XException.InvalidArgs.Throw(); } // // Check Bot User Exists ... var botUser = await botUserServiceProvider.FindOneAsync( includeBuilder: null, ignoreSoftDeleteds: true, cancellationToken: cancellationToken, predicate: x => x.BotUserId.Equals(botUserId) ); if ( botUser.IsNullOrDefault() || botUser.BotUserId <= 0) { XException.InvalidArgs.Throw(); } // // Check User not Verified ... if (botUser.VerifiedOn.HasValue) { XException.NotAllowed.Throw(); } // var verifiedTime = DateTime.UtcNow; var code = CalculateVerificationCode( user: botUser, verifiedTime: verifiedTime ); // var message = XBotMessageIds.XBotVerificationCodeMessageText .ApplyTemplates(new Dictionary { { XBotParams.XVerificationTokenParam, code }, { XBotParams.XTTLInMinuteParam, configuration.VerificationCodeTTL.ToString() }, }); // var result = await SendMessage( cancellationToken: cancellationToken, requestModel: new XBotSendMessageRequest { Text = message, ChatId = botUser.BotUserId, } ); if (!result.IsNullOrDefault()) { // // Update Bot User ... botUser.VerificationCode = code; botUser.LastVerificationSent = verifiedTime; botUser = await botUserServiceProvider.UpdateAsync( item: botUser, id: botUser.Id, saveChanges: true, connectionId: null, cancellationToken: cancellationToken ); } // return result; } /// /// Verify User Subscription ... /// /// /// /// /// public virtual async Task VerifyUser( string token, XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ) { // // Validation ... if (!token.IsMD5String() || token.IsNullOrEmpty() || userInfo.IsNullOrDefault()) { XException.InvalidArgs.Throw(); } // // Detect Verified User ... var botUser = await botUserServiceProvider.FindOneAsync( includeBuilder: null, ignoreSoftDeleteds: true, cancellationToken: cancellationToken, predicate: x => x.LastVerificationSent.HasValue && x.VerificationCode.Equals(token) ); if (botUser.IsNullOrDefault()) { XException.NotFound.Throw(); } // // Check Verification Code is Valid ... var userCode = CalculateVerificationCode( user: botUser, verifiedTime: botUser.LastVerificationSent.Value ); if (!token.Equals(userCode)) { XException.NotAllowed.Throw(); } // // Validate Toke Life Time ... var isExpired = botUser.LastVerificationSent.Value .IsExpiredTTL(configuration.VerificationCodeTTL * 60); if (isExpired) { // // Cleanup User Verification Info ... botUser.VerificationCode = null; botUser.LastVerificationSent = null; botUser.ShownVirificationMenu = false; // botUser = await botUserServiceProvider.UpdateAsync( item: botUser, id: botUser.Id, saveChanges: true, connectionId: null, cancellationToken: cancellationToken ); // XException.ExpiredDate.Throw(); } // // Make User Valid ... botUser.VerificationCode = null; botUser.UserId = userInfo.UserId; botUser.LastVerificationSent = null; botUser.VerifiedOn = DateTime.UtcNow; botUser.ShownVirificationMenu = false; // botUser = await botUserServiceProvider.UpdateAsync( item: botUser, id: botUser.Id, saveChanges: true, connectionId: null, cancellationToken: cancellationToken ); // // Send User Verification Message ... var result = await SendMessage( cancellationToken: cancellationToken, requestModel: new XBotSendMessageRequest { ChatId = botUser.BotUserId, Text = XBotMessageIds.XBotUserVerificationSucceedMessageText } ); // return result; } #endregion // #region Private ... /// /// Calculate Verification Code ... /// /// /// /// private string CalculateVerificationCode( XBotUserDto user, DateTime verifiedTime ) { // var result = securityProvider .Encrypt($"{user.BotUserId}{verifiedTime}") .ToMd5String(); // return result; } #endregion } }