Skip to content

Commit fbff5de

Browse files
committed
Refactor BotApp and add SomeDataRow entity
Refactored BotApp.cs by extracting logic into new methods: AuthorizeAsync, CheckMethodMatching, ExecuteResultAsync, and DisposeAsync. Added DbSet<SomeDataRow> to AppDbContext.cs and created SomeDataRow class for the some_data_rows table. Refactored AuthorizeAttribute.cs to a single-line format.
1 parent 2f276d8 commit fbff5de

5 files changed

Lines changed: 66 additions & 43 deletions

File tree

Sources/TelegramBot.ConsoleTest/Database/AppDbContext.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,6 @@ namespace TelegramBot.ConsoleTest.Database
44
{
55
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
66
{
7-
7+
public DbSet<SomeDataRow> SomeDataRows { get; set; }
88
}
99
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
using System.ComponentModel.DataAnnotations.Schema;
2+
3+
namespace TelegramBot.ConsoleTest.Database
4+
{
5+
[Table("some_data_rows")]
6+
public class SomeDataRow
7+
{
8+
[Column("id")]
9+
public int Id { get; set; }
10+
}
11+
}
Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,10 @@
11
using System;
2-
using System.Collections.Generic;
3-
using System.Text;
42

53
namespace TelegramBot.Attributes
64
{
75
/// <summary>
8-
///
6+
/// Attribute to mark a method as requiring authorization.
97
/// </summary>
108
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
11-
public class AuthorizeAttribute : Attribute
12-
{
13-
14-
}
9+
public class AuthorizeAttribute : Attribute { }
1510
}

Sources/TelegramBot/BotApp.cs

Lines changed: 48 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -245,28 +245,12 @@ private async Task HandleRequestAsync(ITelegramUpdateHandler handler, Update upd
245245
_logger.LogWarning("Method not found for message: {Text}.", update.Message?.Text);
246246
return;
247247
}
248-
if (method.GetCustomAttribute<AuthorizeAttribute>() != null
249-
|| method.DeclaringType?.GetCustomAttribute<AuthorizeAttribute>() != null)
250-
{
251-
if (_serviceProvider.GetService<IBotAuthorizationHandler>() is IBotAuthorizationHandler authorizationHandler)
252-
{
253-
if (!authorizationHandler.Authorize(user))
254-
{
255-
await authorizationHandler
256-
.HandleUnauthorized(user)
257-
.ExecuteResultAsync(new ActionContext(_client, user.Id));
258-
return;
259-
}
260-
}
261-
}
262-
if (method.ReturnType != typeof(Task<IActionResult>) && method.ReturnType != typeof(IActionResult))
248+
bool isAuthorized = await AuthorizeAsync(method, user);
249+
if (!isAuthorized)
263250
{
264-
throw new InvalidOperationException("Invalid return type: " + method.ReturnType.Name);
265-
}
266-
if (args != null && method.GetParameters().Length != args?.Length)
267-
{
268-
throw new InvalidOperationException("Invalid arguments count: " + args?.Length);
251+
return;
269252
}
253+
CheckMethodMatching(method, args);
270254
BotControllerBase controller = (BotControllerBase)ActivatorUtilities.CreateInstance(_serviceProvider, method.DeclaringType!);
271255
controller.Update = update;
272256
controller.User = user;
@@ -276,37 +260,68 @@ await authorizationHandler
276260
controller.KeyValueProvider = keyValueProvider;
277261
}
278262
var result = method.Invoke(controller, args);
279-
if (result is Task<IActionResult> taskResult)
263+
await ExecuteResultAsync(result, user.Id);
264+
await DisposeAsync(controller);
265+
await DisposeAsync(result);
266+
}
267+
268+
private void CheckMethodMatching(MethodInfo method, object[]? args)
269+
{
270+
if (method.ReturnType != typeof(Task<IActionResult>) && method.ReturnType != typeof(IActionResult))
280271
{
281-
await (await taskResult).ExecuteResultAsync(new ActionContext(_client, user.Id));
272+
throw new InvalidOperationException("Invalid return type: " + method.ReturnType.Name);
282273
}
283-
else if (result is IActionResult actionResult)
274+
if (args != null && method.GetParameters().Length != args?.Length)
284275
{
285-
await actionResult.ExecuteResultAsync(new ActionContext(_client, user.Id));
276+
throw new InvalidOperationException("Invalid arguments count: " + args?.Length);
286277
}
287-
else
278+
}
279+
280+
private async Task<bool> AuthorizeAsync(MethodInfo method, User user)
281+
{
282+
if (method.GetCustomAttribute<AuthorizeAttribute>() != null
283+
|| method.DeclaringType?.GetCustomAttribute<AuthorizeAttribute>() != null)
288284
{
289-
throw new InvalidOperationException("Invalid result type: " + result.GetType().Name);
285+
if (_serviceProvider.GetService<IBotAuthorizationHandler>() is IBotAuthorizationHandler authorizationHandler)
286+
{
287+
if (!authorizationHandler.Authorize(user))
288+
{
289+
await authorizationHandler
290+
.HandleUnauthorized(user)
291+
.ExecuteResultAsync(new ActionContext(_client, user.Id));
292+
return false;
293+
}
294+
}
290295
}
296+
return true;
297+
}
291298

292-
if (controller is IAsyncDisposable asyncDisposable)
299+
private async Task DisposeAsync(object obj)
300+
{
301+
if (obj is IAsyncDisposable asyncDisposable)
293302
{
294303
await asyncDisposable.DisposeAsync();
295304
}
296-
else if (controller is IDisposable disposable)
305+
else if (obj is IDisposable disposable)
297306
{
298307
disposable.Dispose();
299308
}
309+
}
300310

301-
if (result is IAsyncDisposable asyncDisposableResult)
311+
private async Task ExecuteResultAsync(object result, long userId)
312+
{
313+
if (result is Task<IActionResult> taskResult)
302314
{
303-
await asyncDisposableResult.DisposeAsync();
315+
await (await taskResult).ExecuteResultAsync(new ActionContext(_client, userId));
304316
}
305-
else if (result is IDisposable disposableResult)
317+
else if (result is IActionResult actionResult)
306318
{
307-
disposableResult.Dispose();
319+
await actionResult.ExecuteResultAsync(new ActionContext(_client, userId));
320+
}
321+
else
322+
{
323+
throw new InvalidOperationException("Invalid result type: " + result.GetType().Name);
308324
}
309-
310325
}
311326

312327
private void CheckDisposed()

Sources/TelegramBot/Handlers/InlineQueryHandler.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,15 @@ public InlineQueryHandler(IReadOnlyCollection<MethodInfo> controllerMethods, Upd
4343
bool match = true;
4444
for (int i = 0; i < controllerCommandParts.Length; i++)
4545
{
46-
if (controllerCommandParts[i] != incomingCommandParts[i] && !controllerCommandParts[i].StartsWith('{')
46+
if (controllerCommandParts[i] != incomingCommandParts[i]
47+
&& !controllerCommandParts[i].StartsWith('{')
4748
&& !controllerCommandParts[i].EndsWith('}'))
4849
{
4950
match = false;
5051
break;
5152
}
52-
if (controllerCommandParts[i].StartsWith('{') && controllerCommandParts[i].EndsWith('}'))
53+
if (controllerCommandParts[i].StartsWith('{')
54+
&& controllerCommandParts[i].EndsWith('}'))
5355
{
5456
_args.Add(incomingCommandParts[i]);
5557
}

0 commit comments

Comments
 (0)