Compare commits

..
3 Commits
Author SHA1 Message Date
saherelm 30c75ba03d Fix Verification User Senario ... 2026-11-13 19:00:56 +03:30
saherelm 3e57ed6af9 last ... 2026-11-13 13:47:53 +03:30
saherelm 2b7209c5fb Try to Handle Commands ... 2026-11-12 23:48:17 +03:30
14 changed files with 855 additions and 471 deletions
+2 -7
View File
@@ -13,14 +13,9 @@ namespace xBotService.Configuration
public string BaseRoute { get; set; }
/// <summary>
/// Verification Code Time to Live ...
/// Verification Code Time to Live in Minute ...
/// </summary>
public int VerificationCodeTTL { get; set; } = 300;
/// <summary>
/// Verification Code Length ...
/// </summary>
public int VerificationCodeLength { get; set; } = 6;
public int VerificationCodeTTL { get; set; } = 5;
/// <summary>
/// Default Timeout ...
+15
View File
@@ -0,0 +1,15 @@
namespace xBotService.Constants
{
public struct XBotMessageIds
{
public const string XBotRequestVerificationCode = "request_verification_code";
public const string XBotRequestVerificationCodeLabel = "🔐 دریافت کد اعتبارسنجی";
public const string XBotVerificationCodeMessageText = """
کد اعتبارسنجی شما: {xVerificationCode}
مدت اعتبار {xTTLInMinute} دقیقه
این کد را با ورود به سامانه در بخش پروفایل کاربری وارد کنید
""";
public const string XBotRequestVerificationCodeMessageText = "برای دریافت کد اعتبارسنجی روی دکمه زیر کلیک کنید:";
public const string XBotUserVerificationSucceedMessageText = "کاربر گرامی، اعتبار سنجی شما با موفقیت انجام شد.";
}
}
+2
View File
@@ -6,5 +6,7 @@ namespace xBotService.Constants
public const string XOffest = "offset";
public const string XTimeout = "timeout";
public const string XTokenParam = "{xBotToken}";
public const string XTTLInMinuteParam = "{xTTLInMinute}";
public const string XVerificationTokenParam = "{xVerificationCode}";
}
}
+16
View File
@@ -0,0 +1,16 @@
using xExceptions.Attributes;
namespace xBotService.Constants
{
public enum XBotStyle
{
[StringValue("primary")]
Primary,
[StringValue("success")]
Success,
[StringValue("danger")]
Danger,
}
}
+89 -188
View File
@@ -12,19 +12,22 @@ using System.Collections.Generic;
using xIdentityService.Interfaces;
using xIdentityService.Controllers;
using Microsoft.Extensions.Logging;
using xBotService.Reciever;
namespace xBotService.Controllers
{
public abstract class XBotProviderControllerBase : XBaseIdentityApiV1Controller
{
private readonly IXBotProvider botProvider;
private readonly XBotBotUpdateRecieverBackgroundService botHandler;
protected XBotProviderControllerBase(
IXBotProvider botProvider,
ILogger<XBotProviderControllerBase> logger,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider
XValidationProvider validationProvider,
ILogger<XBotProviderControllerBase> logger,
XBotBotUpdateRecieverBackgroundService botHandler
) : base(
logger,
appConfiguration,
@@ -33,6 +36,7 @@ namespace xBotService.Controllers
)
{
this.botProvider = botProvider;
this.botHandler = botHandler;
}
//
@@ -130,200 +134,97 @@ namespace xBotService.Controllers
}
}
// [HttpPost("{chatId}/ShowVerificationMenu")]
// public virtual async Task<ActionResult<XBotMessageResponse>> ShowVerificationMenu(
// [FromRoute] long chatId,
// CancellationToken cancellationToken = default
// )
// {
// //
// try
// {
// //
// // Validation ...
// if (!ModelState.IsValid)
// {
// XException.InvalidArgs.Throw();
// }
// if (chatId <= 0)
// {
// XException.InvalidArgs.Throw();
// }
[HttpPost("{botUserId}/ShowVerificationMenu")]
public virtual async Task<ActionResult<XBotMessage>> ShowVerificationMenu(
[FromRoute] long botUserId,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Validation ...
if (botUserId <= 0)
{
XException.InvalidArgs.Throw();
}
// //
// var result = await botProvider.SendVerificationMenu(
// chatId: chatId,
// cancellationToken: cancellationToken
// );
//
var result = await botProvider.ShowVerificationMenu(
botUserId: botUserId,
cancellationToken: cancellationToken
);
// //
// return Ok(result.ToDynamicObject());
// }
// catch (Exception ex)
// {
// //
// var result = GetExceptionActionResult(ex);
// return result;
// }
// }
//
return Ok(result.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
// [HttpPost("{chatId}/SendVerificationCode")]
// public virtual async Task<ActionResult<XBotMessageResponse>> SendVerificationCode(
// [FromRoute] long chatId,
// [FromQuery] string code,
// [FromQuery] int ttlSeconds,
// CancellationToken cancellationToken = default
// )
// {
// //
// try
// {
// //
// // Validation ...
// if (!ModelState.IsValid)
// {
// XException.InvalidArgs.Throw();
// }
// if (chatId <= 0 || code.IsNullOrEmpty() || ttlSeconds < 60)
// {
// XException.InvalidArgs.Throw();
// }
[HttpPost("{token}/VerifyUser")]
public virtual async Task<ActionResult<XBotMessage>> VerifyUser(
[FromRoute] string token,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Validation ...
if (token.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
// //
// var result = await botProvider.SendVerificationCode(
// code: code,
// chatId: chatId,
// ttlSeconds: ttlSeconds,
// cancellationToken: cancellationToken
// );
//
var userInfo = await GetUserInfo();
// //
// return Ok(result.ToDynamicObject());
// }
// catch (Exception ex)
// {
// //
// var result = GetExceptionActionResult(ex);
// return result;
// }
// }
//
var result = await botProvider.VerifyUser(
token: token,
userInfo: userInfo,
cancellationToken: cancellationToken
);
// [HttpPost("{id}/AnswerCallback")]
// public virtual async Task<ActionResult<XBotMessageResponse>> AnswerCallbackQuery(
// [FromRoute] string callbackQueryId,
// [FromQuery] string text = null,
// [FromQuery] bool showAlert = false,
// CancellationToken cancellationToken = default
// )
// {
// //
// try
// {
// //
// // Validation ...
// if (!ModelState.IsValid ||
// callbackQueryId.IsNullOrEmpty())
// {
// XException.InvalidArgs.Throw();
// }
//
return Ok(result.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
// //
// var result = await botProvider.AnswerCallbackQuery(
// text: text,
// showAlert: showAlert,
// callbackQueryId: callbackQueryId,
// cancellationToken: cancellationToken
// );
[HttpPost("Refresh")]
public virtual async Task<ActionResult> Refresh(
CancellationToken cancellationToken = default
)
{
//
try
{
//
await botHandler.Refresh(cancellationToken);
// //
// return Ok(result.ToDynamicObject());
// }
// catch (Exception ex)
// {
// //
// var result = GetExceptionActionResult(ex);
// return result;
// }
// }
// [HttpPost("{chatId}/RemoveInlineKeyboard")]
// public virtual async Task<ActionResult<XBotMessageResponse>> RemoveInlineKeyboard(
// [FromRoute] long chatId,
// [FromQuery] long messageId,
// CancellationToken cancellationToken = default
// )
// {
// //
// try
// {
// //
// // Validation ...
// if (!ModelState.IsValid)
// {
// XException.InvalidArgs.Throw();
// }
// if (chatId <= 0 || messageId <= 0)
// {
// XException.InvalidArgs.Throw();
// }
// //
// var result = await botProvider.RemoveInlineKeyboard(
// chatId: chatId,
// messageId: messageId,
// cancellationToken: cancellationToken
// );
// //
// return Ok(result.ToDynamicObject());
// }
// catch (Exception ex)
// {
// //
// var result = GetExceptionActionResult(ex);
// return result;
// }
// }
// [HttpPost("Webhook")]
// public virtual async Task<ActionResult<bool>> SetWebhook(
// [FromQuery] string webhookUrl,
// [FromQuery] string secretToken = null,
// CancellationToken cancellationToken = default
// )
// {
// //
// try
// {
// //
// // Validation ...
// if (!ModelState.IsValid)
// {
// XException.InvalidArgs.Throw();
// }
// await ValidationProvider
// .GroupValidationBuilder()
// .AddNotEmpty(webhookUrl)
// .AddUrl(webhookUrl)
// .ValidateGroupAsync();
// //
// var result = await botProvider.SetWebhook(
// webhookUrl: webhookUrl,
// secretToken: secretToken,
// cancellationToken: cancellationToken
// );
// //
// return Ok(result);
// }
// catch (Exception ex)
// {
// //
// var result = GetExceptionActionResult(ex);
// return result;
// }
// }
//
return Ok();
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
#endregion
}
}
+1 -1
View File
@@ -6,6 +6,7 @@ using xCommons.Helpers;
using xCommons.Extensions;
using xDataService.Models;
using xPushService.Helpers;
using xBotService.Reciever;
using xExceptions.Constants;
using xBotService.Constants;
using xBotService.Providers;
@@ -23,7 +24,6 @@ using Microsoft.Extensions.Configuration;
using xBotService.Interfaces.Entities.Dtos;
using Microsoft.Extensions.DependencyInjection;
using ConfigurationNodeNames = xBotService.Constants.ConfigurationNodeNames;
using xBotService.Reciever;
namespace xBotService.DI
{
+92 -1
View File
@@ -1,6 +1,9 @@
using xBotService.Models;
using xCommons.Extensions;
using xExceptions.Constants;
using xBotService.Models.Dtos;
using xBotService.Configuration;
using xBotService.Models.Entities;
namespace xBotService.Extensions
{
@@ -42,6 +45,94 @@ namespace xBotService.Extensions
return result;
}
/// <summary>
/// Check a User is Verified or not ...
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static bool IsVerified(
this XBotUser source
)
{
//
var result =
!source.IsNullOrDefault() &&
source.VerifiedOn.HasValue;
//
return result;
}
/// <summary>
/// Check a User is Verified or not ...
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static bool IsVerified(
this XBotUserDto source
)
{
//
var result =
!source.IsNullOrDefault() &&
source.VerifiedOn.HasValue;
//
return result;
}
/// <summary>
/// Check a User's Verification Code is Expired or not ...
/// </summary>
/// <param name="source"></param>
/// <param name="configuration"></param>
/// <returns></returns>
public static bool IsExpired(
this XBotUser source,
XBotServiceConfiguration configuration
)
{
//
// Validate ...
if (configuration.IsNull() ||
source.IsNullOrDefault() ||
!source.VerifiedOn.HasValue ||
configuration.VerificationCodeTTL <= 0)
{
XException.InvalidArgs.Throw();
}
//
var result = source.VerifiedOn.Value.IsExpiredTTL(configuration.VerificationCodeTTL);
return result;
}
/// <summary>
/// Check a User's Verification Code is Expired or not ...
/// </summary>
/// <param name="source"></param>
/// <param name="configuration"></param>
/// <returns></returns>
public static bool IsExpired(
this XBotUserDto source,
XBotServiceConfiguration configuration
)
{
//
// Validate ...
if (configuration.IsNull() ||
source.IsNullOrDefault() ||
!source.VerifiedOn.HasValue ||
configuration.VerificationCodeTTL <= 0)
{
XException.InvalidArgs.Throw();
}
//
var result = source.VerifiedOn.Value.IsExpiredTTL(configuration.VerificationCodeTTL);
return result;
}
/// <summary>
/// Normalize ot Update Request ...
/// </summary>
@@ -98,7 +189,7 @@ namespace xBotService.Extensions
//
result = new();
result.UpdateData(source);
result = source.MapConvert<XBotSendMessageRequestDto, XBotSendMessageRequest>();
//
return result;
+24 -54
View File
@@ -4,11 +4,13 @@ using xBotService.Constants;
using System.Threading.Tasks;
using System.Collections.Generic;
using xCommons.Extensions;
using xBotService.Models.Dtos;
using xIdentityModels.Models;
namespace xBotService.Interfaces
{
public interface IXBotProvider
{
{
/// <summary>
/// Retrieve Bot Info ...
/// </summary>
@@ -28,7 +30,7 @@ namespace xBotService.Interfaces
XBotUpdatesRequest requestModel,
CancellationToken cancellationToken = default
);
/// <summary>
/// Sending Simple String Message to Bot ...
/// </summary>
@@ -41,72 +43,40 @@ namespace xBotService.Interfaces
);
/// <summary>
/// Sending Verification Request Menu ...
/// Show Verification Request Menu ...
/// </summary>
/// <param name="chatId"></param>
/// <param name="botUserId"></param>
/// <param name="label"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
// Task<XBotMessageResponse> SendVerificationMenu(
// long chatId,
// string label = "🔐 دریافت کد وریفیکیشن",
// CancellationToken cancellationToken = default
// );
Task<XBotMessage> ShowVerificationMenu(
long botUserId,
string label = XBotMessageIds.XBotRequestVerificationCodeLabel,
CancellationToken cancellationToken = default
);
/// <summary>
/// Send Verification Code to Requests ...
/// </summary>
/// <param name="chatId"></param>
/// <param name="code"></param>
/// <param name="ttlSeconds"></param>
/// <param name="botUserId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
// Task<XBotMessageResponse> SendVerificationCode(
// long chatId,
// string code,
// int ttlSeconds,
// CancellationToken cancellationToken = default
// );
Task<XBotMessage> SendVerificationCode(
long botUserId,
CancellationToken cancellationToken = default
);
/// <summary>
/// an Accept for Exit Loading on Bot ...
/// Verify User Subscription ...
/// </summary>
/// <param name="callbackQueryId"></param>
/// <param name="text"></param>
/// <param name="showAlert"></param>
/// <param name="token"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
// Task<XBotMessageResponse> AnswerCallbackQuery(
// string callbackQueryId,
// string text = null,
// bool showAlert = false,
// CancellationToken cancellationToken = default
// );
/// <summary>
/// Remove Inline Keyboard After Click (Optional) ...
/// </summary>
/// <param name="chatId"></param>
/// <param name="messageId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
// Task<XBotMessageResponse> RemoveInlineKeyboard(
// long chatId,
// long messageId,
// CancellationToken cancellationToken = default
// );
/// <summary>
/// Set Webhook for Retrieve Messages on Recieved ...
/// </summary>
/// <param name="webhookUrl"></param>
/// <param name="secretToken"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
// Task<bool> SetWebhook(
// string webhookUrl,
// string secretToken = null,
// CancellationToken cancellationToken = default
// );
Task<XBotMessage> VerifyUser(
string token,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
}
}
+20 -2
View File
@@ -1,3 +1,4 @@
using System;
using xModels.Base;
using xModels.Dtos;
@@ -21,10 +22,27 @@ namespace xBotService.Models.Dtos
public virtual XPersonDto User { get; set; } = null;
/// <summary>
/// Check Bot User is Verified or not ...
/// Last Verification Code Sent ...
/// </summary>
/// <value></value>
public bool Verified { get; set; }
public DateTime? LastVerificationSent { get; set; } = null;
/// <summary>
/// Verification Menu Shown or not ...
/// </summary>
public bool ShownVirificationMenu { get; set; }
/// <summary>
/// Verification Code ...
/// </summary>
/// <value></value>
public string VerificationCode { get; set; }
/// <summary>
/// Verified On ...
/// </summary>
/// <value></value>
public DateTime? VerifiedOn { get; set; } = null;
/// <summary>
/// Bot User Id ...
+20 -2
View File
@@ -1,3 +1,4 @@
using System;
using xModels.Base;
namespace xBotService.Models.Entities
@@ -14,10 +15,27 @@ namespace xBotService.Models.Entities
public string UserId { get; set; }
/// <summary>
/// Check Bot User is Verified or not ...
/// Last Verification Code Sent ...
/// </summary>
/// <value></value>
public bool Verified { get; set; }
public DateTime? LastVerificationSent { get; set; } = null;
/// <summary>
/// Verification Menu Shown or not ...
/// </summary>
public bool ShownVirificationMenu { get; set; }
/// <summary>
/// Verification Code ...
/// </summary>
/// <value></value>
public string VerificationCode { get; set; }
/// <summary>
/// Verified On ...
/// </summary>
/// <value></value>
public DateTime? VerifiedOn { get; set; } = null;
/// <summary>
/// Bot User Id ...
+162 -1
View File
@@ -2,6 +2,7 @@ using System;
using Newtonsoft.Json;
using xCommons.Extensions;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace xBotService.Models
{
@@ -301,7 +302,7 @@ namespace xBotService.Models
[JsonProperty("from",
NullValueHandling = NullValueHandling.Ignore)]
public XBotResUser User { get; set; }
public XBotResUser From { get; set; }
[JsonProperty("message",
NullValueHandling = NullValueHandling.Ignore)]
@@ -346,5 +347,165 @@ namespace xBotService.Models
public long ReplyToMessageId { get; set; }
}
/// <summary>
/// a Bot Button Keyboard ...
/// </summary>
public class XBotKeyboardButton
{
[JsonProperty("text",
NullValueHandling = NullValueHandling.Ignore)]
public string Text { get; set; }
[JsonProperty("style",
NullValueHandling = NullValueHandling.Ignore)]
public string Style { get; set; }
[JsonProperty("request_contact",
NullValueHandling = NullValueHandling.Ignore)]
public bool RequestContact { get; set; }
[JsonProperty("request_location",
NullValueHandling = NullValueHandling.Ignore)]
public bool RequestLocation { get; set; }
[JsonProperty("web_app",
NullValueHandling = NullValueHandling.Ignore)]
public XBotWebAppInfo WebApp { get; set; } = null;
}
/// <summary>
/// XBot Web App Info ...
/// </summary>
public class XBotWebAppInfo
{
public string Url { get; set; }
}
/// <summary>
/// a Bot Copy Text Button ...
/// </summary>
public class XBotCopyTextButton
{
[StringLength(256)]
public string Text { get; set; }
}
/// <summary>
/// An Inline Keyboard Button ...
/// </summary>
public class XBotInlineKeyboardButton
{
[JsonProperty("url",
NullValueHandling = NullValueHandling.Ignore)]
public string Url { get; set; }
[JsonProperty("text",
NullValueHandling = NullValueHandling.Ignore)]
public string Text { get; set; }
[JsonProperty("style",
NullValueHandling = NullValueHandling.Ignore)]
public string Style { get; set; }
[JsonProperty("callback_data",
NullValueHandling = NullValueHandling.Ignore)]
public string CallbackData { get; set; }
[JsonProperty("disabled",
NullValueHandling = NullValueHandling.Ignore)]
public object Disabled { get; set; } = null;
[JsonProperty("web_app",
NullValueHandling = NullValueHandling.Ignore)]
public XBotWebAppInfo WebApp { get; set; } = null;
[JsonProperty("copy_text",
NullValueHandling = NullValueHandling.Ignore)]
public XBotCopyTextButton CopyText { get; set; } = null;
}
/// <summary>
/// Bot Inline Keyboard ...
/// </summary>
public class XBotInlineKeyboardMarkup
{
[JsonProperty("inline_keyboard",
NullValueHandling = NullValueHandling.Ignore)]
public IList<IList<XBotInlineKeyboardButton>> InlineKeyboard { get; set; } = [];
}
/// <summary>
/// Bot Reply Keyboard Markup ...
/// </summary>
public class XBotReplyKeyboardMarkup
{
[JsonProperty("keyboard",
NullValueHandling = NullValueHandling.Ignore)]
public IList<XBotKeyboardButton> Keyboard { get; set; } = [];
}
/// <summary>
/// Reply Bot Keyboard Remove ...
/// </summary>
public class XBotReplyKeyboardRemoveMarkup
{
[JsonProperty("remove_keyboard",
NullValueHandling = NullValueHandling.Ignore)]
public bool RemoveKeyboard { get; set; }
}
/// <summary>
/// Bot Reply Markup ...
/// </summary>
public class XBotReplyMarkup
{
[JsonProperty("reply_markup",
NullValueHandling = NullValueHandling.Ignore)]
public IList<XBotKeyboardButton> Keyboard { get; set; } = [];
public object ReplyMarkup { get; set; }
public static XBotReplyMarkup InlineKeyboardMarkup(
XBotInlineKeyboardMarkup source
)
{
//
var result = new XBotReplyMarkup
{
ReplyMarkup = source
};
//
return result;
}
public static XBotReplyMarkup ReplyKeyboardMarkup(
XBotReplyKeyboardMarkup source
)
{
//
var data = source.ToJSON();
var result = new XBotReplyMarkup
{
ReplyMarkup = data
};
//
return result;
}
public static XBotReplyMarkup ReplyKeyboardRemoveMarkup(
XBotReplyKeyboardRemoveMarkup source
)
{
//
var data = source.ToJSON();
var result = new XBotReplyMarkup
{
ReplyMarkup = data
};
//
return result;
}
}
}
+4 -1
View File
@@ -8,11 +8,14 @@ namespace xBotService.Providers.GraphQL
public XBotUserGraphType() : base()
{
Field(x => x.UserId);
Field(x => x.Verified);
Field(x => x.BotUserId);
Field(x => x.VerifiedOn);
Field(x => x.BotUserName);
Field(x => x.BotLastname);
Field(x => x.BotFirstname);
Field(x => x.VerificationCode);
Field(x => x.LastVerificationSent);
Field(x => x.ShownVirificationMenu);
}
}
}
+250 -199
View File
@@ -14,6 +14,10 @@ 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
{
@@ -21,22 +25,28 @@ namespace xBotService.Providers
{
//
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
XBotServiceConfiguration configuration,
IXBotUserServiceProvider botUserServiceProvider
)
{
//
this.logger = logger;
this.httpProvider = httpProvider;
this.configuration = configuration;
this.securityProvider = securityProvider;
this.validationProvider = validationProvider;
this.botUserServiceProvider = botUserServiceProvider;
}
//
@@ -55,6 +65,9 @@ namespace xBotService.Providers
baseUrl: configuration.BaseRoute
);
//
result.Timeout = configuration.DefaultClientTimeout;
//
return result;
}
@@ -225,237 +238,275 @@ namespace xBotService.Providers
}
/// <summary>
/// Sending Verification Request Menu ...
/// Show Verification Request Menu ...
/// </summary>
/// <param name="chatId"></param>
/// <param name="botUserId"></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();
// }
public virtual async Task<XBotMessage> ShowVerificationMenu(
long botUserId,
string label = XBotMessageIds.XBotRequestVerificationCodeLabel,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (botUserId <= 0 || label.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
// //
// // Markup for Keyboards ...
// var markup = new XBotReplyMarkup
// {
// //
// InlineKeyboard =
// [
// //
// [
// //
// new XBotInlineButton
// {
// Text = label,
// CallbackData = "request_verification_code"
// }
// ]
// ]
// };
//
// Normalize ...
if (label.IsNullOrEmpty())
{
label = XBotMessageIds.XBotRequestVerificationCodeLabel;
}
// //
// var response = await SendMessage(
// chatId: chatId,
// text: "برای دریافت کد وریفیکیشن روی دکمه زیر کلیک کنید:",
// replyMarkup: markup,
// cancellationToken: cancellationToken
// );
//
// Markup for Keyboards ...
var markup = XBotReplyMarkup
.InlineKeyboardMarkup(new XBotInlineKeyboardMarkup
{
InlineKeyboard = [
[
new XBotInlineKeyboardButton{
Text = label,
CallbackData = XBotMessageIds.XBotRequestVerificationCode
}
]
]
});
// //
// return response;
// }
//
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="chatId"></param>
/// <param name="code"></param>
/// <param name="ttlSeconds"></param>
/// <param name="botUserId"></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();
// }
public virtual async Task<XBotMessage> SendVerificationCode(
long botUserId,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (botUserId <= 0)
{
XException.InvalidArgs.Throw();
}
// //
// var minutes = ttlSeconds / 60;
// var response = await SendMessage(
// chatId: chatId,
// cancellationToken: cancellationToken,
// text: $"✅ کد وریفیکیشن شما:\n\n<code>{code}</code>\n\n⏱ این کد تا {minutes} دقیقه معتبر است."
// );
//
// 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();
}
// //
// return response;
// }
//
// 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>
/// an Accept for Exit Loading on Bot ...
/// Verify User Subscription ...
/// </summary>
/// <param name="callbackQueryId"></param>
/// <param name="text"></param>
/// <param name="showAlert"></param>
/// <param name="token"></param>
/// <param name="userInfo"></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();
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();
}
// //
// var client = GetRestClient();
// var request = GetRestRequest(
// endpoint: XBotEndpoints.AnswerCallbackQuery,
// @params: new Dictionary<string, string>
// {
// { XBotParams.XTokenParam, configuration.Token }
// }
// );
//
// 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();
}
// //
// request.AddJsonBody(new
// {
// text = text,
// show_alert = showAlert,
// callback_query_id = callbackQueryId,
// });
//
// Check Verification Code is Valid ...
var userCode = CalculateVerificationCode(
user: botUser,
verifiedTime: botUser.LastVerificationSent.Value
);
if (!token.Equals(userCode))
{
XException.NotAllowed.Throw();
}
// //
// var response = await httpProvider.RunRestRequest<XBotMessageResponse>(
// client: client,
// request: request,
// method: XHttpMethod.POST,
// cancellationToken: cancellationToken
// );
//
// 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;
// //
// return response;
// }
//
botUser = await botUserServiceProvider.UpdateAsync(
item: botUser,
id: botUser.Id,
saveChanges: true,
connectionId: null,
cancellationToken: cancellationToken
);
/// <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();
// }
//
XException.ExpiredDate.Throw();
}
// //
// var client = GetRestClient();
// var request = GetRestRequest(
// endpoint: XBotEndpoints.EditMessageReplyMarkup,
// @params: new Dictionary<string, string>
// {
// { XBotParams.XTokenParam, configuration.Token }
// }
// );
//
// Make User Valid ...
botUser.VerificationCode = null;
botUser.UserId = userInfo.UserId;
botUser.LastVerificationSent = null;
botUser.VerifiedOn = DateTime.UtcNow;
botUser.ShownVirificationMenu = false;
// //
// request.AddJsonBody(new
// {
// chat_id = chatId,
// message_id = messageId,
// reply_markup = new { inline_keyboard = new List<List<object>>() }
// });
//
botUser = await botUserServiceProvider.UpdateAsync(
item: botUser,
id: botUser.Id,
saveChanges: true,
connectionId: null,
cancellationToken: cancellationToken
);
// //
// var response = await httpProvider.RunRestRequest<XBotMessageResponse>(
// client: client,
// request: request,
// method: XHttpMethod.POST,
// cancellationToken: cancellationToken
// );
//
// Send User Verification Message ...
var result = await SendMessage(
cancellationToken: cancellationToken,
requestModel: new XBotSendMessageRequest
{
ChatId = botUser.BotUserId,
Text = XBotMessageIds.XBotUserVerificationSucceedMessageText
}
);
// //
// 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 httpProvider.RunRestRequest<XBotMessageResponse>(
// client: client,
// request: request,
// method: XHttpMethod.POST,
// cancellationToken: cancellationToken
// );
// var response = iResponse?.Ok ?? false;
// //
// return response;
// }
//
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
}
}
@@ -11,6 +11,12 @@ using System.Collections.Generic;
using xBotService.Interfaces.Dtos;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using xBotService.Constants;
using xBotService.Extensions;
using System.Linq.Expressions;
using UglyToad.PdfPig.Graphics.Operations.PathConstruction;
using xBotService.Models.Entities;
using xExceptions.Constants;
namespace xBotService.Reciever
{
@@ -73,7 +79,7 @@ namespace xBotService.Reciever
//
// Log ...
logger.LogInformation($"Updates: {Environment.NewLine}{updates.ToJSON()}");
logger.LogInformation($"Updates: {Environment.NewLine}");
//
// HandleRecieved Updates ...
@@ -81,32 +87,79 @@ namespace xBotService.Reciever
{
//
logger
.LogInformation($"Handle Bot Update: {Environment.NewLine} {update}");
.LogInformation($"Handle Update: {Environment.NewLine} {update.ToJSON()}");
//
// Check Item Exists in Db ...
Expression<Func<XBotUser, bool>> predicator = null;
if (!update.Message.IsNullOrDefault())
{
predicator = x => x.BotUserId.Equals(update.Message.From.Id);
}
else if (!update.CallbackQuery.IsNullOrDefault() &&
!update.CallbackQuery.From.IsNullOrDefault())
{
predicator = x => x.BotUserId.Equals(update.CallbackQuery.From.Id);
}
else
{
XException.NotFound.Throw();
}
//
// Check Item Exists in Db ...
var item = await botUserProvider.FindOneAsync(
predicate: x => x.BotUserId.Equals(update.Message.From.Id)
predicate: predicator,
cancellationToken: cancellationToken
);
if (item.IsNullOrDefault())
{
//
// Not Exists ...
item = await botUserProvider.AddAsync(
saveChanges: true,
connectionId: null,
item: new XBotUserDto
var itemForAdd = new XBotUserDto();
if (!update.Message.IsNullOrDefault())
{
//
itemForAdd = new XBotUserDto
{
BotUserId = update.Message.From.Id,
BotUserName = update.Message.From.Username,
BotLastname = update.Message.From.LastName,
BotFirstname = update.Message.From.FirstName,
},
cancellationToken: cancellationToken
);
};
}
else if (!update.CallbackQuery.IsNullOrDefault() &&
!update.CallbackQuery.From.IsNullOrDefault())
{
//
itemForAdd = new XBotUserDto
{
BotUserId = update.CallbackQuery.From.Id,
BotUserName = update.CallbackQuery.From.Username,
BotLastname = update.CallbackQuery.From.LastName,
BotFirstname = update.CallbackQuery.From.FirstName,
};
}
//
logger.LogInformation("Add new BotUser ...");
if (!itemForAdd.IsNullOrDefault())
{
//
item = await botUserProvider.AddAsync(
saveChanges: true,
connectionId: null,
item: new XBotUserDto
{
BotUserId = update.Message.From.Id,
BotUserName = update.Message.From.Username,
BotLastname = update.Message.From.LastName,
BotFirstname = update.Message.From.FirstName,
},
cancellationToken: cancellationToken
);
//
logger.LogInformation("Add new BotUser ...");
}
}
else
{
@@ -117,17 +170,107 @@ namespace xBotService.Reciever
//
// Check Verified ...
if (item.Verified)
if (item.IsVerified())
{
//
logger.LogInformation("User Verified ...");
continue;
}
//
// TODO: Remove this ...
if (item.BotUserName != "saherelm_it_center")
{
continue;
}
//
// Handle Callback Commands ...
if (!update.CallbackQuery.IsNullOrDefault())
{
//
await HandleBotAction(
botUser: item,
update: update,
cancellationToken: cancellationToken
);
return;
}
//
// Try to Show Verification Menu on User ...
logger
.LogInformation($"Show Verification Request Method to User: {item.User.GetFullname()}");
if (!item.ShownVirificationMenu)
{
//
logger
.LogInformation($"Show Verification Request Method to User: {item.User.GetFullname()}");
var response = await botProvider.ShowVerificationMenu(
botUserId: item.BotUserId,
cancellationToken: cancellationToken
);
if (!response.IsNullOrDefault())
{
//
item.ShownVirificationMenu = true;
item = await botUserProvider.UpdateAsync(
item: item,
id: item.Id,
saveChanges: true,
connectionId: null,
cancellationToken: cancellationToken
);
}
}
//
logger.LogInformation($"Verification Menu Shown for User: {item.BotUserId}");
}
}
/// <summary>
/// Handle Bot Sent Commands ...
/// </summary>
/// <param name="update"></param>
/// <param name="botUser"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task HandleBotAction(
XBotUpdateResponse update,
XBotUserDto botUser,
CancellationToken cancellationToken = default
)
{
//
// Validate ...
if (update.IsNullOrDefault() ||
update.CallbackQuery.IsNullOrDefault() ||
update.CallbackQuery.Data.IsNullOrEmpty())
{
return;
}
//
// Inject Provider ...
using var scope = serviceProvider.CreateScope();
var botProvider = scope.ServiceProvider.GetRequiredService<IXBotProvider>();
var botUserProvider = scope.ServiceProvider.GetRequiredService<IXBotUserServiceProvider>();
//
// Switch Betwen Data ...
switch (update.CallbackQuery.Data)
{
//
case XBotMessageIds.XBotRequestVerificationCode:
{
//
// Remove Inline Keyboard ...
// And Send Verification ...
await botProvider.SendVerificationCode(
botUserId: botUser.BotUserId,
cancellationToken: cancellationToken
);
break;
}
}
}
}