2024-01-28 18:51:18 +03:00
|
|
|
using BotFramework.Abstractions.UpdateProvider;
|
|
|
|
|
using BotFramework.Config;
|
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
using Microsoft.Extensions.Options;
|
|
|
|
|
using Newtonsoft.Json;
|
2024-01-28 20:47:19 +03:00
|
|
|
using System.IO;
|
2024-01-28 18:51:18 +03:00
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using Telegram.Bot;
|
|
|
|
|
using Telegram.Bot.Types;
|
|
|
|
|
|
|
|
|
|
namespace Kruzya.TelegramBot.Core.Controllers
|
|
|
|
|
{
|
|
|
|
|
public class Telegram : Controller
|
|
|
|
|
{
|
|
|
|
|
private const string SecretTokenHeader = "X-Telegram-Bot-Api-Secret-Token";
|
|
|
|
|
|
|
|
|
|
private readonly ILogger<Telegram> _logger;
|
|
|
|
|
private readonly ITelegramBotClient _client;
|
|
|
|
|
private readonly IUpdateTarget _updateTarget;
|
|
|
|
|
private readonly string _secretToken;
|
|
|
|
|
|
|
|
|
|
public Telegram(ILogger<Telegram> logger, ITelegramBotClient client, IUpdateTarget updateTarget, IOptions<BotConfig> config)
|
|
|
|
|
{
|
|
|
|
|
_logger = logger;
|
|
|
|
|
_client = client;
|
|
|
|
|
_updateTarget = updateTarget;
|
|
|
|
|
|
|
|
|
|
_secretToken = config.Value.Webhook.SecretToken;
|
|
|
|
|
if (string.IsNullOrEmpty(_secretToken))
|
|
|
|
|
{
|
|
|
|
|
_secretToken = null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
[HttpPost]
|
2024-01-28 20:47:19 +03:00
|
|
|
public async IActionResult Index()
|
2024-01-28 18:51:18 +03:00
|
|
|
{
|
|
|
|
|
if (_secretToken != null && !Request.Headers.ContainsKey(SecretTokenHeader))
|
|
|
|
|
{
|
|
|
|
|
_logger.LogWarning("Someone tried push update without secret key in headers");
|
|
|
|
|
return BadRequest();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var ok = (_secretToken == null || Request.Headers[SecretTokenHeader] == _secretToken);
|
|
|
|
|
if (!ok)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogWarning("Someone tried push update with wrong secret key in headers");
|
|
|
|
|
return BadRequest();
|
|
|
|
|
}
|
|
|
|
|
|
2024-01-28 20:47:19 +03:00
|
|
|
var body = await (new StreamReader(Request.Body)).ReadToEndAsync();
|
|
|
|
|
LaunchHandle(JsonConvert.DeserializeObject<Update>(body));
|
2024-01-28 18:51:18 +03:00
|
|
|
return Ok();
|
|
|
|
|
}
|
|
|
|
|
|
2024-01-28 20:25:12 +03:00
|
|
|
private void LaunchHandle(Update? update)
|
2024-01-28 18:51:18 +03:00
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
if (update == null)
|
|
|
|
|
{
|
|
|
|
|
throw new System.Exception("Invalid request body");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_updateTarget.Push(update);
|
|
|
|
|
}
|
|
|
|
|
catch (System.Exception e)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogError($"Error occured when handling a new update: {e}");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|