Skip to content

Cleanthat #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions src/Bot.Controller/Controller/TelegramBotController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ public abstract class TelegramBotController(IServiceProvider services)
ITelegramBotController,
ITelegramBotClient
{
/// <summary>The MIME type for a Telegram Bot update.</summary>
/// <value><inheritdoc cref="MediaType.Application.DisplayName" path="/value" />/telegram-bot-update<inheritdoc cref="Suffixes.Json.DisplayName" path="/value" /></value>
public const string TelegramBotUpdateMimeType =
$"{MediaType.Application.DisplayName}/telegram-bot-update{Suffixes.Json.DisplayName}";

Expand Down Expand Up @@ -76,8 +78,10 @@ public Task DownloadFileAsync(
}
#endregion

/// <summary>Processes an update from the Telegram bot server</summary>
/// <param name="update">The <see cref="Update" /></param>
[HttpPost]
[Consumes(Application.Json.DisplayName)]
[Consumes(TelegramBotUpdateMimeType)]
[ProducesOKResponse<IActionResult>]
public async Task<IActionResult> PostUpdateAsync(Update update)
{
Expand All @@ -101,8 +105,6 @@ await Bot.SendTextMessageAsync(
Logger.LogError(ex, ex.Message);
}

[HttpPost]
[Consumes(Application.Json.DisplayName)]
protected abstract Task HandleUpdateAsync(Update update);

protected virtual Task ExecuteBotCommandAsync(Update update, string botCommand, string[] args)
Expand Down
30 changes: 15 additions & 15 deletions src/Bot.Extensions/LoggerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,50 +10,50 @@ public static partial class LoggingExtensions
public static partial void ReceivedUpdateFrom(this ILogger logger, UpdateType updateType, OneOf<long, string> chatId);

[LoggerMessage(1, LogLevel.Trace, "Received update {UpdateType}\n{Update}", EventName = nameof(ReceivedUpdate))]
public static partial void ReceivedUpdate(this ILogger logger, Telegram.Bot.Types.Enums.UpdateType updateType, Telegram.Bot.Types.Update update);
public static partial void ReceivedUpdate(this ILogger logger, UpdateType updateType, Telegram.Bot.Types.Update update);

public static void ReceivedUpdate(this ILogger logger, Telegram.Bot.Types.Update update)
public static void ReceivedUpdate(this ILogger logger, Update update)
{
logger.ReceivedUpdate(update.Type, update);
switch(update.Type)
{
case Telegram.Bot.Types.Enums.UpdateType.Message:
case UpdateType.Message:
logger.LogInformation("Received message from {ChatId}", update.Message.Chat.Id);
break;
case Telegram.Bot.Types.Enums.UpdateType.CallbackQuery:
case UpdateType.CallbackQuery:
logger.LogInformation("Received callback query from {ChatId}", update.CallbackQuery.Message.Chat.Id);
break;
case Telegram.Bot.Types.Enums.UpdateType.InlineQuery:
case UpdateType.InlineQuery:
logger.LogInformation("Received inline query from {ChatId}", update.InlineQuery.From.Id);
break;
case Telegram.Bot.Types.Enums.UpdateType.ChosenInlineResult:
case UpdateType.ChosenInlineResult:
logger.LogInformation("Received chosen inline result from {ChatId}", update.ChosenInlineResult.From.Id);
break;
case Telegram.Bot.Types.Enums.UpdateType.EditedMessage:
case UpdateType.EditedMessage:
logger.LogInformation("Received edited message from {ChatId}", update.EditedMessage.Chat.Id);
break;
case Telegram.Bot.Types.Enums.UpdateType.ChannelPost:
case UpdateType.ChannelPost:
logger.LogInformation("Received channel post from {ChatId}", update.ChannelPost.Chat.Id);
break;
case Telegram.Bot.Types.Enums.UpdateType.EditedChannelPost:
case UpdateType.EditedChannelPost:
logger.LogInformation("Received edited channel post from {ChatId}", update.EditedChannelPost.Chat.Id);
break;
case Telegram.Bot.Types.Enums.UpdateType.ShippingQuery:
case UpdateType.ShippingQuery:
logger.LogInformation("Received shipping query from {ChatId}", update.ShippingQuery.From.Id);
break;
case Telegram.Bot.Types.Enums.UpdateType.PreCheckoutQuery:
case UpdateType.PreCheckoutQuery:
logger.LogInformation("Received pre-checkout query from {ChatId}", update.PreCheckoutQuery.From.Id);
break;
case Telegram.Bot.Types.Enums.UpdateType.Poll:
case UpdateType.Poll:
logger.LogInformation("Received poll {PollId} from chat {ChatId}", update.Poll.Id, update.Message.Chat.Id);
break;
case Telegram.Bot.Types.Enums.UpdateType.PollAnswer:
case UpdateType.PollAnswer:
logger.LogInformation("Received poll answer from {ChatId}", update.PollAnswer.User.Id);
break;
case Telegram.Bot.Types.Enums.UpdateType.MyChatMember:
case UpdateType.MyChatMember:
logger.LogInformation("Received chat member update from {ChatId}", update.MyChatMember.Chat.Id);
break;
case Telegram.Bot.Types.Enums.UpdateType.ChatMember:
case UpdateType.ChatMember:
logger.LogInformation("Received chat member update from {ChatId}", update.ChatMember.Chat.Id);
break;
default:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ namespace Telegram.Bot.Types;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using ObjectId = System.ObjectId;
using System.Data;

public static class BotApiTokenEfCoreExtensions
{
Expand Down Expand Up @@ -67,7 +68,8 @@ string functionName
new CreateFunctionOperation(
schema,
functionName,
"@value varchar(255)",
[new SqlArgument("@value", "varchar(255)")],
Bit.ShortName,
typeof(Constants).Assembly.ReadAssemblyResourceAllText(
ufn_ + IsValidBotToken + _sql
)
Expand Down
1 change: 1 addition & 0 deletions src/Bot.Extensions/Webhooks/ConfigureWebhook.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ public async Task StartAsync(CancellationToken cancellationToken)
await botClient.SetWebhookAsync(
url: webhookAddress,
allowedUpdates: Empty<UpdateType>(),
dropPendingUpdates: true,
secretToken: _botConfig.SecretToken,
cancellationToken: cancellationToken
);
Expand Down
7 changes: 4 additions & 3 deletions src/Bot.Identity/BotIdentityOptions.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
namespace Telegram.Bot.Identity;
using System;

using Telegram.Bot.Types;
using BotApiToken = Telegram.Bot.Types.BotApiToken;

using BotApiToken = Types.BotApiToken;
using Telegram.Bot.Configuration;
namespace Telegram.Bot.Identity;

public class BotIdentityOptions : Microsoft.AspNetCore.Authentication.AuthenticationSchemeOptions, IBotConfiguration
public class BotIdentityOptions : AuthenticationSchemeOptions, IBotConfiguration
{
public BotApiToken BotApiToken => BotApiToken.From(Token);

Expand Down
7 changes: 7 additions & 0 deletions src/Bot.Identity/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,30 @@ namespace Telegram.Bot.Identity.Constants;

public static class Schemas
{
/// <value>tele</value>
public const string TeleSchema = "tele";
}

public static class TableNames
{
/// <value><inheritdoc cref="tbl_" path="/value" />Role</value>
public const string TelegramB2CRole = tbl_ + "Role";
/// <value><inheritdoc cref="tbl_" path="/value" />Bot</value>
public const string Bot = tbl_ + nameof(Bot);
/// <value><inheritdoc cref="tbl_" path="/value" />User</value>
public const string TelegramB2CUser = tbl_ + "User";
}

public static class ExtensionProperties
{
/// <value>telegram_id</value>
public const string TelegramId = "telegram_id";
/// <value>telegram_username</value>
public const string TelegramUsername = "telegram_username";
}

public static class Uris
{
/// <value>https://oidc.telegram.technology</value>
public const string TelegramOidcServer = "https://oidc.telegram.technology";
}
4 changes: 2 additions & 2 deletions src/Bot.Identity/GraphServiceClientExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ public static class GraphServiceClientExtensions
{
var properties = await directoryObjectsService.GetExtensionPropertiesAsync();

return Array.Find(properties, p => p.Name.EndsWith(ExtensionProperties.TelegramId))?.Name;
return Find(properties, p => p.Name.EndsWith(ExtensionProperties.TelegramId))?.Name;
}
public static async Task<string?> GetTelegramUsernamePropertyAsync(this IDirectoryObjectsService directoryObjectsService)
{
var properties = await directoryObjectsService.GetExtensionPropertiesAsync();

return Array.Find(properties, p => p.Name.EndsWith(ExtensionProperties.TelegramUsername))?.Name;
return Find(properties, p => p.Name.EndsWith(ExtensionProperties.TelegramUsername))?.Name;
}
}
2 changes: 1 addition & 1 deletion src/Bot.Identity/Telegram.Bot.Identity.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<TargetFrameworks>net8.0</TargetFrameworks>
<UserSecretsId>3c222328-0ad6-44b0-9f6e-effab4bba7ae</UserSecretsId>
<UserSecretsId>Telegram.Bot.Identity</UserSecretsId>
</PropertyGroup>

<ItemGroup>
Expand Down
19 changes: 11 additions & 8 deletions src/Bot.Identity/TelegramB2CDbContext.cs
Original file line number Diff line number Diff line change
@@ -1,31 +1,34 @@
namespace Telegram.Bot.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Dgmjr.AzureAdB2C.Identity;

using BotApiToken = Types.BotApiToken;

public class TelegramB2CDbContext<TUser>(DbContextOptions options) : AzureAdB2CDbContext<TUser>(options)
where TUser : TelegramB2CUser
{
// public override DbSet<TUser> Users { get; set; }

protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<TelegramB2CUser>(builder =>
builder.Entity<TUser>(builder =>
{
builder.HasOne<AzureAdB2CUser>().WithOne().HasForeignKey<TelegramB2CUser>(u => u.Id).HasPrincipalKey<AzureAdB2CUser>(u => u.Id);
builder.HasOne<AzureAdB2CUser>().WithOne().HasForeignKey<TUser>(u => u.Id).HasPrincipalKey<AzureAdB2CUser>(u => u.Id);
builder.ToTable(Constants.TableNames.TelegramB2CUser, Constants.Schemas.TeleSchema);
// builder.HasAlternateKey(u => u.TelegramId);
builder.Property(u => u.TelegramId).IsRequired();
builder.Property(u => u.TelegramUsername);
builder.HasIndex(u => u.TelegramId).IsUnique();
builder.HasIndex(u => u.TelegramUsername);//.IsUnique();
builder.HasIndex(u => u.TelegramUsername);
builder.Property(u => u.AccessFailedCount).HasDefaultValue(0);
builder.Property(u => u.LockoutEnabled).HasDefaultValue(false);
builder.Property(u => u.PhoneNumberConfirmed).HasDefaultValue(false);
builder.Property(u => u.TwoFactorEnabled).HasDefaultValue(false);
});

builder.Entity<AzureAdB2CUser>(builder =>
{
builder.ToTable(Dgmjr.AzureAdB2C.Identity.TableNames.AzureAdB2CUser, Dgmjr.AzureAdB2C.Identity.Schemas.AzureAdB2C);
builder.ToTable(TableNames.AzureAdB2CUser, Dgmjr.AzureAdB2C.Identity.Schemas.AzureAdB2C);
builder.HasIndex(u => u.TenantId);
});
}

public bool IsValidBotToken(string s) => !BotApiToken.Validate(s).ErrorMessage.IsPresent();
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public static class TelegramAuthenticationDefaults
/// <summary>
/// Default value for the identity provider.
/// </summary>
public const string IdentityProvider = "Telegram OIDC Connect";
public const string IdentityProvider = "oidc.telegram.technology";

/// <summary>
/// Default value for <see cref="Microsoft.AspNetCore.Authentication.AuthenticationScheme.Name" />.
Expand Down
2 changes: 1 addition & 1 deletion src/OpenIdConnect.Server/Extensions/LoggingExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ ClaimsPrincipal principal
principal.Claims
.Select(c => c.Type)
.Distinct()
.ToDictionary(t => t, t => principal.FindFirstValue(t))
.ToDictionary(t => t, t => System.Security.Claims.ClaimsPrincipalExtensions.FindFirstValue(principal, t))
)
);

Expand Down
98 changes: 0 additions & 98 deletions src/OpenIdConnect.Server/Telegram.OpenIdConnect.Server.sln

This file was deleted.

Loading