Files
xSaherelmWorkspace/Documents/Codes/XBotProvider.cs
T
2026-11-12 20:19:19 +03:30

973 lines
32 KiB
C#

using System;
using RestSharp;
using System.Linq;
using System.Net.Http;
using System.Threading;
using xCommons.Providers;
using xCommons.Constants;
using xBotService.Models;
using xCommons.Extensions;
using xBotService.Constants;
using xExceptions.Constants;
using xBotService.Interfaces;
using xIdentityModels.Models;
using System.Threading.Tasks;
using xHttpService.Constants;
using xIdentityService.Models;
using xHttpService.Interfaces;
using RestSharp.Authenticators;
using xIdentityModels.Constants;
using xBotService.Configuration;
using xIdentityModels.Extensions;
using xIdentityService.Constants;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using xIdentityService.Configuration;
namespace xBotService.Providers
{
public class XBotProvider : IXBotProvider
{
//
private readonly IXHttpProvider httpProvider;
private readonly ILogger<XBotProvider> logger;
private readonly IXTokenProvider tokenProvider;
private readonly IXIdentityProvider identityProvider;
private readonly XValidationProvider validationProvider;
private readonly XBotServiceConfiguration configuration;
private readonly XIdentityServiceConfiguration identityConfiguration;
public XBotProvider(
IXHttpProvider httpProvider,
ILogger<XBotProvider> logger,
IXTokenProvider tokenProvider,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider,
XBotServiceConfiguration configuration,
XIdentityServiceConfiguration identityConfiguration
)
{
//
this.logger = logger;
this.httpProvider = httpProvider;
this.tokenProvider = tokenProvider;
this.configuration = configuration;
this.identityProvider = identityProvider;
this.validationProvider = validationProvider;
this.identityConfiguration = identityConfiguration;
}
//
#region Tools ...
/// <summary>
/// Get an Instance of Http Client
/// </summary>
/// <returns></returns>
public HttpClient GetHttpClient()
{
//
HttpClient httpClient = null;
//
// httpClient = new HttpClient ();
var httpClientHandler = new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) =>
{
//
logger.LogInformation(
$"XSSL Handler: {Environment.NewLine}, sender: {sender}, {Environment.NewLine} cert: {cert}, {Environment.NewLine} chain: {chain}, {Environment.NewLine} sslPolicyErrors: {sslPolicyErrors}"
);
//
return true;
},
ClientCertificateOptions = ClientCertificateOption.Manual,
};
httpClient = new HttpClient(httpClientHandler);
//
// Set Timeout ...
// TODO: Fix this ...
// httpClient.Timeout = TimeSpan
// .FromSeconds (identityConfiguration.DefaultClientTimeout);
//
return httpClient;
}
/// <summary>
/// Get an Instance of RestClient
/// </summary>
/// <returns></returns>
public RestClient GetRestClient(XTokenResponse tokens = null)
{
//
var client = new RestClient(configuration.BaseRoute);
//
// Set Authenticator ...
if (!tokens.IsNull() &&
!tokens.AccessToken.IsNullOrEmpty())
{
client.Authenticator = new JwtAuthenticator(tokens.AccessToken);
}
//
// Refresh Token ...
if (!tokens.IsNull() &&
!tokens.RefreshToken.IsNullOrEmpty())
{
client.AddDefaultHeader(XAuthorization.RefreshToken, tokens.RefreshToken);
}
//
// ExpiresAt ...
if (!tokens.IsNull() &&
tokens.ExpiresAt > 0)
{
client.AddDefaultHeader(XAuthorization.ExpiresAt, tokens.ExpiresAt.AsHttpParamString());
}
//
// Set Default Timeout ...
client.Timeout = configuration.DefaultClientTimeout;
//
// SSL Validation Handler ...
client.RemoteCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) =>
{
//
logger.LogInformation(
$"XSSL Handler: {Environment.NewLine}, sender: {sender}, {Environment.NewLine} cert: {cert}, {Environment.NewLine} chain: {chain}, {Environment.NewLine} sslPolicyErrors: {sslPolicyErrors}"
);
//
return true;
};
//
return client;
}
/// <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 url = endpoint.GetStringValue();
//
// Add Route Payloads ...
if (!@params.IsNull() && @params.Count > 0)
{
//
var enumerator = @params.GetEnumerator();
while (enumerator.MoveNext())
{
//
var item = enumerator.Current;
//
url = url.Replace(item.Key, item.Value.ToUrlEncoded());
}
}
//
// Add Query Strings ...
if (!queryStrings.IsNull() && queryStrings.Count > 0)
{
//
url = $"{url}?";
var enumerator = queryStrings.GetEnumerator();
while (enumerator.MoveNext())
{
//
var item = enumerator.Current;
//
url += $"{item.Key}={item.Value.ToUrlEncoded()}&";
}
//
// remove lates & ...
if (url.EndsWith("&"))
{
url = url.Substring(0, url.Length - 1);
}
}
//
// Create request ...
var request = new RestRequest(url, DataFormat.Json);
//
if (addXPoweredValue)
{
request.AddHeader(XAuthorization.XPoweredBy, identityConfiguration.XPoweredValue);
}
//
// Add Headers to request ...
if (!headers.IsNull() && headers.Count > 0)
{
//
var enumerator = headers.GetEnumerator();
while (enumerator.MoveNext())
{
//
var item = enumerator.Current;
request.AddHeader(item.Key, item.Value);
}
}
//
return request;
}
/// <summary>
/// Handle Call Specific Request and retrieve Response
/// </summary>
/// <param name="client"></param>
/// <param name="request"></param>
/// <param name="method"></param>
/// <param name="supportRefreshingTokens"></param>
/// <param name="cancellationToken"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public async Task<T> RunRestRequest<T>(
RestClient client,
RestRequest request,
XHttpMethod method,
bool supportRefreshingTokens = true,
CancellationToken cancellationToken = default
)
{
//
var response = await Task.Run(async () =>
{
//
IRestResponse resp = null;
//
// Call Endpoint Service using Specified Method ...
switch (method)
{
//
// Get ...
case XHttpMethod.GET:
resp = client.Get(request);
break;
//
// Put ...
case XHttpMethod.PUT:
resp = client.Put(request);
break;
//
// Post ...
case XHttpMethod.POST:
resp = client.Post(request);
break;
//
// Delete ...
case XHttpMethod.DELETE:
resp = client.Delete(request);
break;
}
//
if (!resp.IsSuccessful)
{
//
// Log Exception ...
logger.LogError($"Error: {resp.ErrorMessage}");
logger.LogError($"Exception: {resp.ErrorException.ToJSON()}");
if (!resp.ErrorMessage.IsNullOrEmpty() &&
resp.ErrorMessage.Contains("timed out"))
{
XException.Timeout.Throw();
}
//
// Refresh Tokens or Issue Correct Exception ...
if (supportRefreshingTokens &&
resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
//
var isRefreshed = request.Parameters.Any(rp =>
rp.Name == XParam.XIsRefreshed.GetStringValue() &&
rp.Value.ToString().ToNormalString() == true.ToJSON());
//
logger.LogInformation($"isRefreshed: {isRefreshed}");
//
// Get Access Token ...
XTokenResponse tokens = null;
var accessToken = request.Parameters.FirstOrDefault(rp =>
rp.Name.ToNormalString() == XAuthorization.Header.ToNormalString()).Value.ToString();
if (!accessToken.IsNullOrEmpty())
{
//
accessToken = accessToken.Replace(XAuthorization.TokenIdentifier, "");
//
if (!accessToken.IsNullOrEmpty())
{
tokens = await tokenProvider.RetrieveToken(accessToken);
}
}
//
// Refresh Token and then re do request ...
if (!isRefreshed &&
!accessToken.IsNullOrEmpty() &&
!tokens.IsNull() &&
tokens.IsRefreshable())
{
//
request.AddHeader(XParam.XIsRefreshed.GetStringValue(), true.ToJSON());
//
// Refreshe Tokens ...
var refreshedTokens = await identityProvider.RefreshTokens(tokens);
//
// Renew Rest Client with Refreshed Tokens ...
var timeout = client.Timeout;
client = GetRestClient(refreshedTokens);
client.Timeout = Timeout.Infinite;
//
// Do Request Again using renew Client ...
return await RunRestRequest<T>(
client: client,
request: request,
method: method);
}
}
//
var ex = resp.Content.ToXError();
if (!ex.IsNull())
{
throw ex.ToException();
}
//
// UnAuthorized ...
if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
XException.NotAuthorized.Throw();
}
//
// NotFound ...
if (resp.StatusCode == System.Net.HttpStatusCode.NotFound)
{
XException.NotFound.Throw();
}
//
XException.ActionFailed.Throw();
}
//
var result = resp.Content.FromJSON<T>();
return result;
}, cancellationToken);
//
return response;
}
public async Task<XBaseRestResponse<T>> RunRestRequestByResponse<T>(
RestClient client,
RestRequest request,
XHttpMethod method,
bool supportRefreshingTokens = true,
CancellationToken cancellationToken = default
)
{
//
var response = await Task.Run(async () =>
{
//
IRestResponse resp = null;
//
// Call Endpoint Service using Specified Method ...
switch (method)
{
//
// Get ...
case XHttpMethod.GET:
resp = client.Get(request);
break;
//
// Put ...
case XHttpMethod.PUT:
resp = client.Put(request);
break;
//
// Post ...
case XHttpMethod.POST:
resp = client.Post(request);
break;
//
// Delete ...
case XHttpMethod.DELETE:
resp = client.Delete(request);
break;
}
//
if (!resp.IsSuccessful)
{
//
// Log Exception ...
logger.LogError($"Error: {resp.ErrorMessage}");
logger.LogError($"Exception: {resp.ErrorException.ToJSON()}");
if (!resp.ErrorMessage.IsNullOrEmpty() &&
resp.ErrorMessage.Contains("timed out"))
{
XException.Timeout.Throw();
}
//
// Refresh Tokens or Issue Correct Exception ...
if (supportRefreshingTokens &&
resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
//
var isRefreshed = request.Parameters.Any(rp =>
rp.Name == XParam.XIsRefreshed.GetStringValue() &&
rp.Value.ToString().ToNormalString() == true.ToJSON());
//
logger.LogInformation($"isRefreshed: {isRefreshed}");
//
// Get Access Token ...
XTokenResponse tokens = null;
var accessToken = request.Parameters.FirstOrDefault(rp =>
rp.Name.ToNormalString() == XAuthorization.Header.ToNormalString()).Value.ToString();
if (!accessToken.IsNullOrEmpty())
{
//
accessToken = accessToken.Replace(XAuthorization.TokenIdentifier, "");
//
if (!accessToken.IsNullOrEmpty())
{
tokens = await tokenProvider.RetrieveToken(accessToken);
}
}
//
// Refresh Token and then re do request ...
if (!isRefreshed &&
!accessToken.IsNullOrEmpty() &&
!tokens.IsNull() &&
tokens.IsRefreshable())
{
//
request.AddHeader(XParam.XIsRefreshed.GetStringValue(), true.ToJSON());
//
// Refreshe Tokens ...
var refreshedTokens = await identityProvider.RefreshTokens(tokens);
//
// Renew Rest Client with Refreshed Tokens ...
var timeout = client.Timeout;
client = GetRestClient(refreshedTokens);
client.Timeout = Timeout.Infinite;
//
// Do Request Again using renew Client ...
return await RunRestRequestByResponse<T>(
client: client,
request: request,
method: method
);
}
}
//
var ex = resp.Content.ToXError();
if (!ex.IsNull())
{
throw ex.ToException();
}
//
// UnAuthorized ...
if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
XException.NotAuthorized.Throw();
}
//
// NotFound ...
if (resp.StatusCode == System.Net.HttpStatusCode.NotFound)
{
XException.NotFound.Throw();
}
//
XException.ActionFailed.Throw();
}
//
var result = new XBaseRestResponse<T>
{
Response = resp,
Model = resp.Content.FromJSON<T>()
};
//
return result;
}, cancellationToken);
//
return response;
}
/// <summary>
/// Get User SelectBy Param
/// </summary>
/// <param name="model"></param>
/// <param name="forceNotNull"></param>
/// <param name="excludes"></param>
/// <returns></returns>
public string GetUserSelectByParam(
XActionRequest model,
bool forceNotNull = true,
ICollection<XUserSelectBy> excludes = null
)
{
//
// Validate Args ...
validationProvider.NotNull(model);
//
var id = model.UserId;
var userName = model.UserName;
var email = model.Email;
var phoneNumber = model.MobileNumber;
//
if (excludes != null)
{
//
if (excludes.Contains(XUserSelectBy.ID))
{
id = null;
}
if (excludes.Contains(XUserSelectBy.Email))
{
email = null;
}
if (excludes.Contains(XUserSelectBy.MobileNumber))
{
phoneNumber = null;
}
if (excludes.Contains(XUserSelectBy.Username))
{
userName = null;
}
}
var selectByParam =
id.IsNullOrEmpty() ?
userName.IsNullOrEmpty() ?
email.IsNullOrEmpty() ?
phoneNumber.IsNullOrEmpty() ? null : phoneNumber : email : userName : id;
//
// Check result ...
if (forceNotNull &&
selectByParam.IsNullOrEmpty())
{
XException.InvalidData.Throw();
}
//
return selectByParam;
}
#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 RunRestRequest<XBotResUser>(
client: client,
request: request,
method: XHttpMethod.GET,
cancellationToken: cancellationToken
);
//
return response;
}
/// <summary>
/// Sending Simple String Message to Bot ...
/// </summary>
/// <param name="chatId"></param>
/// <param name="text"></param>
/// <param name="replyMarkup"></param>
/// <param name="parseMode"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XBotMessageResponse> SendMessage(
long chatId,
string text,
XBotReplyMarkup replyMarkup = null,
XBotMessageParseMode parseMode = XBotMessageParseMode.Html,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (chatId <= 0 || text.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
var client = GetRestClient();
var request = GetRestRequest(
endpoint: XBotEndpoints.SendMessage,
@params: new Dictionary<string, string>
{
{ XBotParams.XTokenParam, configuration.Token }
}
);
//
request.AddJsonBody(new
{
text = text,
caht_id = chatId,
reply_markup = replyMarkup,
parse_mode = parseMode.GetStringValue()
});
//
var response = await RunRestRequest<XBotMessageResponse>(
client: client,
request: request,
method: XHttpMethod.POST,
cancellationToken: cancellationToken
);
//
return response;
}
/// <summary>
/// Sending Verification Request Menu ...
/// </summary>
/// <param name="chatId"></param>
/// <param name="label"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XBotMessageResponse> SendVerificationMenu(
long chatId,
string label = "🔐 دریافت کد وریفیکیشن",
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (chatId <= 0 || label.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
// Markup for Keyboards ...
var markup = new XBotReplyMarkup
{
//
InlineKeyboard =
[
//
[
//
new XBotInlineButton
{
Text = label,
CallbackData = "request_verification_code"
}
]
]
};
//
var response = await SendMessage(
chatId: chatId,
text: "برای دریافت کد وریفیکیشن روی دکمه زیر کلیک کنید:",
replyMarkup: markup,
cancellationToken: cancellationToken
);
//
return response;
}
/// <summary>
/// Send Verification Code to Requests ...
/// </summary>
/// <param name="chatId"></param>
/// <param name="code"></param>
/// <param name="ttlSeconds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XBotMessageResponse> SendVerificationCode(
long chatId,
string code,
int ttlSeconds,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (chatId <= 0 || ttlSeconds < 60 || code.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
var minutes = ttlSeconds / 60;
var response = await SendMessage(
chatId: chatId,
cancellationToken: cancellationToken,
text: $"✅ کد وریفیکیشن شما:\n\n<code>{code}</code>\n\n⏱ این کد تا {minutes} دقیقه معتبر است."
);
//
return response;
}
/// <summary>
/// an Accept for Exit Loading on Bot ...
/// </summary>
/// <param name="callbackQueryId"></param>
/// <param name="text"></param>
/// <param name="showAlert"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XBotMessageResponse> 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<string, string>
{
{ XBotParams.XTokenParam, configuration.Token }
}
);
//
request.AddJsonBody(new
{
text = text,
show_alert = showAlert,
callback_query_id = callbackQueryId,
});
//
var response = await RunRestRequest<XBotMessageResponse>(
client: client,
request: request,
method: XHttpMethod.POST,
cancellationToken: cancellationToken
);
//
return response;
}
/// <summary>
/// Remove Inline Keyboard After Click (Optional) ...
/// </summary>
/// <param name="chatId"></param>
/// <param name="messageId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<XBotMessageResponse> 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<string, string>
{
{ XBotParams.XTokenParam, configuration.Token }
}
);
//
request.AddJsonBody(new
{
chat_id = chatId,
message_id = messageId,
reply_markup = new { inline_keyboard = new List<List<object>>() }
});
//
var response = await RunRestRequest<XBotMessageResponse>(
client: client,
request: request,
method: XHttpMethod.POST,
cancellationToken: cancellationToken
);
//
return response;
}
/// <summary>
/// Retrieve Messages ...
/// </summary>
/// <param name="offset"></param>
/// <param name="timeout"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<List<XBotUpdate>> GetUpdates(
long offset = 0,
int timeout = 30,
CancellationToken cancellationToken = default
)
{
//
var client = GetRestClient();
var request = GetRestRequest(
endpoint: XBotEndpoints.GetUpdates,
@params: new Dictionary<string, string>
{
{ XBotParams.XTokenParam, configuration.Token }
},
queryStrings: new Dictionary<string, string>
{
{ XBotParams.XOffest, offset.ToString() },
{ XBotParams.XTimeout, timeout.ToString() }
}
);
//
var iResponse = await RunRestRequest<XBotUpdatesResponse>(
client: client,
request: request,
method: XHttpMethod.GET,
cancellationToken: cancellationToken
);
var response = iResponse.Result ?? [];
//
return response;
}
/// <summary>
/// Set Webhook for Retrieve Messages on Recieved ...
/// </summary>
/// <param name="webhookUrl"></param>
/// <param name="secretToken"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<bool> SetWebhook(
string webhookUrl,
string secretToken = null,
CancellationToken cancellationToken = default
)
{
//
var client = GetRestClient();
var request = GetRestRequest(
endpoint: XBotEndpoints.SetWebhook,
@params: new Dictionary<string, string>
{
{ XBotParams.XTokenParam, configuration.Token }
}
);
//
request.AddJsonBody(new
{
url = webhookUrl,
secret_token = secretToken
});
//
var iResponse = await RunRestRequest<XBotMessageResponse>(
client: client,
request: request,
method: XHttpMethod.POST,
cancellationToken: cancellationToken
);
var response = iResponse?.Ok ?? false;
//
return response;
}
#endregion
}
}