Files
xBotService/Providers/XBotProvider.cs
T

512 lines
16 KiB
C#

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<XBotProvider> logger;
private readonly IXSecurityProvider securityProvider;
private readonly IXIdentityHttpProvider httpProvider;
private readonly XValidationProvider validationProvider;
private readonly XBotServiceConfiguration configuration;
private readonly IXBotUserServiceProvider botUserServiceProvider;
public XBotProvider(
ILogger<XBotProvider> 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 ...
/// <summary>
/// Get an Instance of RestClient ...
/// </summary>
/// <returns></returns>
public RestClient GetRestClient(
XTokenResponse tokens = null
)
{
//
var result = httpProvider.GetRestClient(
tokens: tokens,
baseUrl: configuration.BaseRoute
);
//
result.Timeout = configuration.DefaultClientTimeout;
//
return result;
}
/// <summary>
/// Get an Instance of RestRequest ...
/// </summary>
public RestRequest GetRestRequest(
XBotEndpoints endpoint,
bool addXPoweredValue = true,
IDictionary<string, string> @params = null,
IDictionary<string, string> headers = null,
IDictionary<string, string> queryStrings = null
)
{
//
var result = httpProvider.GetRestRequest(
@params: @params,
headers: headers,
queryStrings: queryStrings,
addXPoweredValue: addXPoweredValue,
endpoint: endpoint.GetStringValue()
);
//
return result;
}
#endregion
//
#region Service ...
/// <summary>
/// Retrieve Bot Info ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XBotResUser> GetMe(
CancellationToken cancellationToken = default
)
{
//
var client = GetRestClient();
var request = GetRestRequest(
endpoint: XBotEndpoints.GetMe,
@params: new Dictionary<string, string>
{
{ XBotParams.XTokenParam, configuration.Token }
}
);
//
var response = await httpProvider.RunRestRequest<XBotResponse<XBotResUser>>(
client: client,
request: request,
method: XHttpMethod.GET,
cancellationToken: cancellationToken
);
//
// Ensure Success ...
response.EnsureBotResponseSucceed();
//
var result = response.Result;
//
return result;
}
/// <summary>
/// Retrieve Messages ...
/// </summary>
/// <param name="requestModel"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<IList<XBotUpdateResponse>> GetUpdates(
XBotUpdatesRequest requestModel,
CancellationToken cancellationToken = default
)
{
//
requestModel = requestModel.Normalize();
//
var client = GetRestClient();
var request = GetRestRequest(
endpoint: XBotEndpoints.GetUpdates,
@params: new Dictionary<string, string>
{
{ XBotParams.XTokenParam, configuration.Token }
},
queryStrings: new Dictionary<string, string>
{
{ XBotParams.XLimit, requestModel.Limit.ToString() },
{ XBotParams.XOffest, requestModel.Offset.ToString() },
{ XBotParams.XTimeout, requestModel.Timeout.ToString() }
}
);
//
var response = await httpProvider.RunRestRequest<XBotResponse<IList<XBotUpdateResponse>>>(
client: client,
request: request,
method: XHttpMethod.GET,
cancellationToken: cancellationToken
);
//
// Ensure Success ...
response.EnsureBotResponseSucceed();
//
var result = response.Result;
//
return result;
}
/// <summary>
/// Sending Simple String Message to Bot ...
/// </summary>
/// <param name="requestModel"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XBotMessage> 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<string, string>
{
{ XBotParams.XTokenParam, configuration.Token }
}
);
//
var req = requestModel.ToDto();
request.AddJsonBody(req.ToJSON());
//
var response = await httpProvider.RunRestRequest<XBotResponse<XBotMessage>>(
client: client,
request: request,
method: XHttpMethod.POST,
cancellationToken: cancellationToken
);
//
// Ensure Success ...
response.EnsureBotResponseSucceed();
//
var result = response.Result;
//
return result;
}
/// <summary>
/// Show Verification Request Menu ...
/// </summary>
/// <param name="botUserId"></param>
/// <param name="label"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XBotMessage> 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;
}
/// <summary>
/// Send Verification Code to Requests ...
/// </summary>
/// <param name="botUserId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XBotMessage> 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<string, string>
{
{ 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;
}
/// <summary>
/// Verify User Subscription ...
/// </summary>
/// <param name="token"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XBotMessage> 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 ...
/// <summary>
/// Calculate Verification Code ...
/// </summary>
/// <param name="user"></param>
/// <param name="verifiedTime"></param>
/// <returns></returns>
private string CalculateVerificationCode(
XBotUserDto user,
DateTime verifiedTime
)
{
//
var result = securityProvider
.Encrypt($"{user.BotUserId}{verifiedTime}")
.ToMd5String();
//
return result;
}
#endregion
}
}