Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| db122e8aef | |||
| fce6e8d013 | |||
| 57b3706241 | |||
| f9584c5afe | |||
| 07df710ce6 |
@@ -14,9 +14,12 @@ public interface IMessengerAdapter
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Отправить текстовое сообщение в чат.
|
/// Отправить текстовое сообщение в чат.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Task SendTextAsync(string chatId, string text, MessageFormat format,
|
Task<string?> SendTextAsync(string chatId, string text, MessageFormat format,
|
||||||
IEnumerable<IEnumerable<InlineButton>>? inline,
|
IEnumerable<IEnumerable<InlineButton>>? inline,
|
||||||
IEnumerable<IEnumerable<ReplyButton>>? reply, CancellationToken ct);
|
IEnumerable<IEnumerable<ReplyButton>>? reply,
|
||||||
|
string? messageId,
|
||||||
|
CancellationToken ct
|
||||||
|
);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Отправить файл в чат.
|
/// Отправить файл в чат.
|
||||||
@@ -28,16 +31,6 @@ public interface IMessengerAdapter
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
IAlbumBuilder CreateAlbumBuilder(PageContext ctx);
|
IAlbumBuilder CreateAlbumBuilder(PageContext ctx);
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Начать отображение прогресса операции.
|
|
||||||
/// </summary>
|
|
||||||
Task<string?> StartProgressAsync(PageContext ctx, string title, CancellationToken ct);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Обновить прогресс операции.
|
|
||||||
/// </summary>
|
|
||||||
Task UpdateProgressAsync(PageContext ctx, string messageId, string title, int percent, CancellationToken ct);
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Вызывается при выходе со страницы.
|
/// Вызывается при выходе со страницы.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ using BotPages.Core.Abstractions;
|
|||||||
using BotPages.Core.Context;
|
using BotPages.Core.Context;
|
||||||
using BotPages.Core.Logging;
|
using BotPages.Core.Logging;
|
||||||
using BotPages.Core.Routing;
|
using BotPages.Core.Routing;
|
||||||
|
using System.Reflection;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Основное приложение BotPages.
|
/// Основное приложение BotPages.
|
||||||
@@ -90,6 +91,45 @@ public sealed class BotPagesApp
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Зарегистрировать все маршруты для страницы.
|
||||||
|
/// Маршрутом является <see cref="RouteAttribute"/>.
|
||||||
|
/// Так же берется полное название класса.
|
||||||
|
/// </summary>
|
||||||
|
public BotPagesApp AutoMapRoute()
|
||||||
|
{
|
||||||
|
// Берём все загруженные сборки в текущем AppDomain
|
||||||
|
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
|
||||||
|
|
||||||
|
// Находим все типы, которые наследуются от Page
|
||||||
|
var pageTypes = assemblies
|
||||||
|
.SelectMany(a =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return a.GetTypes();
|
||||||
|
}
|
||||||
|
catch (ReflectionTypeLoadException ex)
|
||||||
|
{
|
||||||
|
// Если часть типов не загрузилась — берём только успешные
|
||||||
|
return ex.Types.Where(t => t != null)!;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.Where(t => t != null
|
||||||
|
&& t.IsClass
|
||||||
|
&& !t.IsAbstract
|
||||||
|
&& t.IsSubclassOf(typeof(Page)))
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
// Выводим полные имена
|
||||||
|
foreach (var type in pageTypes)
|
||||||
|
{
|
||||||
|
_routes.Map(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Обработать входящее обновление.
|
/// Обработать входящее обновление.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -161,7 +201,7 @@ public sealed class BotPagesApp
|
|||||||
|
|
||||||
if (page is null)
|
if (page is null)
|
||||||
{
|
{
|
||||||
await ctx.Navigation.GoToHome(ctx, ct);
|
await ctx.Navigation.GoToHomeAsync(ctx, ct);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -22,93 +22,9 @@ public sealed class PageContext
|
|||||||
/// <summary>Адаптер мессенджера.</summary>
|
/// <summary>Адаптер мессенджера.</summary>
|
||||||
public required IMessengerAdapter Adapter { get; init; }
|
public required IMessengerAdapter Adapter { get; init; }
|
||||||
|
|
||||||
//Storage
|
|
||||||
|
|
||||||
/// <summary>Получить состояние по ключу.</summary>
|
|
||||||
public Task<T?> GetStorageAsync<T>(string key, CancellationToken ct)
|
|
||||||
=> StateStorage.GetAsync<T>(SessionKey, key, ct);
|
|
||||||
|
|
||||||
/// <summary>Сохранить состояние по ключу.</summary>
|
|
||||||
public Task SetStorageAsync<T>(string key, T state, CancellationToken ct)
|
|
||||||
=> StateStorage.SetAsync<T>(SessionKey, key, state, ct);
|
|
||||||
|
|
||||||
/// <summary>Удалить состояние по ключу.</summary>
|
|
||||||
public Task<bool> RemoveStorageAsync(string key, CancellationToken ct)
|
|
||||||
=> StateStorage.RemoveAsync(SessionKey, key, ct);
|
|
||||||
|
|
||||||
/// <summary>Удалить все состояния по ключу.</summary>
|
|
||||||
public Task<bool> ClearStorageAsync(CancellationToken ct)
|
|
||||||
=> StateStorage.ClearAsync(SessionKey, ct);
|
|
||||||
|
|
||||||
//Adapter
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Отправить текстовое сообщение.
|
|
||||||
/// </summary>
|
|
||||||
public Task SendTextAsync(string text, MessageFormat format = MessageFormat.Plain,
|
|
||||||
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
|
||||||
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
|
||||||
CancellationToken ct = default)
|
|
||||||
=> Adapter.SendTextAsync(this.Update.Chat.Id, text, format, inline, reply, ct);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Отправить файл.
|
|
||||||
/// </summary>
|
|
||||||
public Task SendFileAsync(FileDescriptor file, string? caption = null, MessageFormat? captionFormat = null, CancellationToken ct = default)
|
|
||||||
=> Adapter.SendFileAsync(this.Update.Chat.Id, file, caption, captionFormat, ct);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Отправить файл.
|
|
||||||
/// </summary>
|
|
||||||
public Task SendFileAsync(FileDescriptor file, string? caption = null, CancellationToken ct = default)
|
|
||||||
=> Adapter.SendFileAsync(this.Update.Chat.Id, file, caption, null, ct);
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получить билдер альбомов.
|
/// Получить билдер альбомов.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public IAlbumBuilder Albums => Adapter.CreateAlbumBuilder(this);
|
public IAlbumBuilder Albums => Adapter.CreateAlbumBuilder(this);
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Начать прогресс операции.
|
|
||||||
/// </summary>
|
|
||||||
public async Task<string?> StartProgressAsync(string title, CancellationToken ct)
|
|
||||||
{
|
|
||||||
var messageId = await Adapter.StartProgressAsync(this, title, ct);
|
|
||||||
|
|
||||||
if (messageId != null)
|
|
||||||
{
|
|
||||||
_progressMessageId = messageId;
|
|
||||||
_progressTitle = title;
|
|
||||||
}
|
|
||||||
|
|
||||||
return messageId;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Обновить прогресс операции.
|
|
||||||
/// </summary>
|
|
||||||
public Task UpdateProgressAsync(int percent, CancellationToken ct)
|
|
||||||
{
|
|
||||||
if (_progressMessageId != null)
|
|
||||||
{
|
|
||||||
return Adapter.UpdateProgressAsync(this, _progressMessageId, _progressTitle ?? "", percent, ct);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Обновить прогресс операции.
|
|
||||||
/// </summary>
|
|
||||||
public Task UpdateProgressAsync(string messageId, int percent, CancellationToken ct)
|
|
||||||
{
|
|
||||||
return Adapter.UpdateProgressAsync(this, messageId, _progressTitle ?? "", percent, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private string? _progressMessageId = null;
|
|
||||||
private string? _progressTitle = null;
|
|
||||||
|
|
||||||
}
|
}
|
||||||
32
BotPages.Core/Context/PageContextAdapterExtensions.cs
Normal file
32
BotPages.Core/Context/PageContextAdapterExtensions.cs
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
using BotPages.Core.Abstractions;
|
||||||
|
using BotPages.Core.Messaging;
|
||||||
|
|
||||||
|
namespace BotPages.Core;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Расширения <see cref="PageContext"/> для работы с <see cref="IMessengerAdapter"/>
|
||||||
|
/// </summary>
|
||||||
|
public static class PageContextAdapterExtensions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Отправить текстовое сообщение.
|
||||||
|
/// </summary>
|
||||||
|
public static Task<string?> SendTextAsync(this PageContext ctx, string text, MessageFormat format = MessageFormat.Plain,
|
||||||
|
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||||
|
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||||
|
string? messageId = null,
|
||||||
|
CancellationToken ct = default)
|
||||||
|
=> ctx.Adapter.SendTextAsync(ctx.Update.Chat.Id, text, format, inline, reply, messageId, ct);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Отправить файл.
|
||||||
|
/// </summary>
|
||||||
|
public static Task SendFileAsync(this PageContext ctx, FileDescriptor file, string? caption = null, MessageFormat? captionFormat = null, CancellationToken ct = default)
|
||||||
|
=> ctx.Adapter.SendFileAsync(ctx.Update.Chat.Id, file, caption, captionFormat, ct);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Отправить файл.
|
||||||
|
/// </summary>
|
||||||
|
public static Task SendFileAsync(this PageContext ctx, FileDescriptor file, string? caption = null, CancellationToken ct = default)
|
||||||
|
=> ctx.Adapter.SendFileAsync(ctx.Update.Chat.Id, file, caption, null, ct);
|
||||||
|
}
|
||||||
38
BotPages.Core/Context/PageContextNavigationExtensions.cs
Normal file
38
BotPages.Core/Context/PageContextNavigationExtensions.cs
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
namespace BotPages.Core;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Расширения <see cref="PageContext"/> для работы с <see cref="NavigationService"/>
|
||||||
|
/// </summary>
|
||||||
|
public static class PageContextNavigationExtensions
|
||||||
|
{
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Перейти по маршруту без аргументов.
|
||||||
|
/// </summary>
|
||||||
|
public static Task GoToHomeAsync(this PageContext ctx, CancellationToken ct)
|
||||||
|
=> ctx.Navigation.GoToHomeAsync(ctx, ct);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Перейти по маршруту без аргументов.
|
||||||
|
/// </summary>
|
||||||
|
public static Task GoToAsync(this PageContext ctx, string route, CancellationToken ct)
|
||||||
|
=> ctx.Navigation.GoToAsync(route, ctx, ct);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Перейти по маршруту с аргументами.
|
||||||
|
/// </summary>
|
||||||
|
public static Task GoToAsync<TArgs>(this PageContext ctx, string route, TArgs args, CancellationToken ct)
|
||||||
|
=> ctx.Navigation.GoToAsync<TArgs>(route, args, ctx, ct);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Перейти на страницу без аргументов.
|
||||||
|
/// </summary>
|
||||||
|
public static Task GoToAsync<TPage>(this PageContext ctx, CancellationToken ct) where TPage : Page
|
||||||
|
=> ctx.Navigation.GoToAsync<TPage>(ctx, ct);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Перейти на страницу с аргументами.
|
||||||
|
/// </summary>
|
||||||
|
public static Task GoToAsync<TPage, TArgs>(this PageContext ctx, TArgs args, CancellationToken ct) where TPage : StatefullPage<TArgs>
|
||||||
|
=> ctx.Navigation.GoToAsync<TPage, TArgs>(ctx, args!, ct);
|
||||||
|
}
|
||||||
26
BotPages.Core/Context/PageContextStorageExtensions.cs
Normal file
26
BotPages.Core/Context/PageContextStorageExtensions.cs
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
using BotPages.Core.Abstractions;
|
||||||
|
|
||||||
|
namespace BotPages.Core;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Расширения <see cref="PageContext"/> для работы с <see cref="IStateStorage"/>
|
||||||
|
/// </summary>
|
||||||
|
public static class PageContextStorageExtensions
|
||||||
|
{
|
||||||
|
|
||||||
|
/// <summary>Получить состояние по ключу.</summary>
|
||||||
|
public static Task<T?> GetStorageAsync<T>(this PageContext ctx, string key, CancellationToken ct)
|
||||||
|
=> ctx.StateStorage.GetAsync<T>(ctx.SessionKey, key, ct);
|
||||||
|
|
||||||
|
/// <summary>Сохранить состояние по ключу.</summary>
|
||||||
|
public static Task SetStorageAsync<T>(this PageContext ctx, string key, T state, CancellationToken ct)
|
||||||
|
=> ctx.StateStorage.SetAsync<T>(ctx.SessionKey, key, state, ct);
|
||||||
|
|
||||||
|
/// <summary>Удалить состояние по ключу.</summary>
|
||||||
|
public static Task<bool> RemoveStorageAsync(this PageContext ctx, string key, CancellationToken ct)
|
||||||
|
=> ctx.StateStorage.RemoveAsync(ctx.SessionKey, key, ct);
|
||||||
|
|
||||||
|
/// <summary>Удалить все состояния по ключу.</summary>
|
||||||
|
public static Task<bool> ClearStorageAsync(this PageContext ctx, CancellationToken ct)
|
||||||
|
=> ctx.StateStorage.ClearAsync(ctx.SessionKey, ct);
|
||||||
|
}
|
||||||
@@ -14,9 +14,8 @@ public sealed class MessageBuilder
|
|||||||
private readonly List<List<ReplyButton>> _reply = new();
|
private readonly List<List<ReplyButton>> _reply = new();
|
||||||
private readonly List<(FileDescriptor file, string? caption, MessageFormat? captionFormat)> _files = new();
|
private readonly List<(FileDescriptor file, string? caption, MessageFormat? captionFormat)> _files = new();
|
||||||
private readonly List<(FileDescriptor file, string? caption, MessageFormat? captionFormat)> _album = new();
|
private readonly List<(FileDescriptor file, string? caption, MessageFormat? captionFormat)> _album = new();
|
||||||
private string? _progressTitle = null;
|
private bool _disableReplyKeyboard;
|
||||||
private int? _progressPercent = null;
|
private string? _editMessageId = null;
|
||||||
private string? _progressMessageId = null;
|
|
||||||
|
|
||||||
/// <summary>Создать билдер сообщений.</summary>
|
/// <summary>Создать билдер сообщений.</summary>
|
||||||
public MessageBuilder(PageContext ctx) => _ctx = ctx;
|
public MessageBuilder(PageContext ctx) => _ctx = ctx;
|
||||||
@@ -29,6 +28,13 @@ public sealed class MessageBuilder
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Редактировать сообщение.</summary>
|
||||||
|
public MessageBuilder EditMessage(string messagId)
|
||||||
|
{
|
||||||
|
_editMessageId = messagId;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Добавить inline‑кнопку.</summary>
|
/// <summary>Добавить inline‑кнопку.</summary>
|
||||||
public MessageBuilder Inline(string label, string value)
|
public MessageBuilder Inline(string label, string value)
|
||||||
{
|
{
|
||||||
@@ -64,9 +70,20 @@ public sealed class MessageBuilder
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Отключение Reply клавиатуры.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
public MessageBuilder DisableReply()
|
||||||
|
{
|
||||||
|
_disableReplyKeyboard = true;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Добавить reply‑кнопку.</summary>
|
/// <summary>Добавить reply‑кнопку.</summary>
|
||||||
public MessageBuilder Reply(params ReplyButton[] label)
|
public MessageBuilder Reply(params ReplyButton[] label)
|
||||||
{
|
{
|
||||||
|
_disableReplyKeyboard = false;
|
||||||
_reply.Add(label.ToList());
|
_reply.Add(label.ToList());
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
@@ -74,6 +91,7 @@ public sealed class MessageBuilder
|
|||||||
/// <summary>Добавить строку reply‑кнопок.</summary>
|
/// <summary>Добавить строку reply‑кнопок.</summary>
|
||||||
public MessageBuilder Reply(IEnumerable<ReplyButton> row)
|
public MessageBuilder Reply(IEnumerable<ReplyButton> row)
|
||||||
{
|
{
|
||||||
|
_disableReplyKeyboard = false;
|
||||||
_reply.Add(row.ToList());
|
_reply.Add(row.ToList());
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
@@ -81,6 +99,7 @@ public sealed class MessageBuilder
|
|||||||
/// <summary>Добавить строку reply‑кнопок.</summary>
|
/// <summary>Добавить строку reply‑кнопок.</summary>
|
||||||
public MessageBuilder Reply(IEnumerable<IEnumerable<ReplyButton>> row)
|
public MessageBuilder Reply(IEnumerable<IEnumerable<ReplyButton>> row)
|
||||||
{
|
{
|
||||||
|
_disableReplyKeyboard = false;
|
||||||
_reply.AddRange(row.Select(t => t.ToList()).ToList());
|
_reply.AddRange(row.Select(t => t.ToList()).ToList());
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
@@ -99,21 +118,19 @@ public sealed class MessageBuilder
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Установить прогресс операции.</summary>
|
|
||||||
public MessageBuilder Progress(string title, int percent = 0)
|
|
||||||
{
|
|
||||||
_progressTitle = title;
|
|
||||||
_progressPercent = percent;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Отправить собранное сообщение.</summary>
|
/// <summary>Отправить собранное сообщение.</summary>
|
||||||
public async Task SendAsync(CancellationToken ct = default)
|
public async Task<string?> SendAsync(CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
|
string? messageId = null;
|
||||||
|
|
||||||
// Текст
|
// Текст
|
||||||
if (!string.IsNullOrWhiteSpace(_text))
|
if (!string.IsNullOrWhiteSpace(_text))
|
||||||
{
|
{
|
||||||
await _ctx.SendTextAsync(_text, _format, _inline, _reply, ct);
|
List<List<ReplyButton>>? reply = null;
|
||||||
|
if (_disableReplyKeyboard) reply = new();
|
||||||
|
else if (_reply.Any()) reply = _reply;
|
||||||
|
|
||||||
|
messageId = await _ctx.SendTextAsync(_text, _format, _inline, reply, _editMessageId, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Файлы
|
// Файлы
|
||||||
@@ -129,25 +146,12 @@ public sealed class MessageBuilder
|
|||||||
await builder.SendAsync(ct);
|
await builder.SendAsync(ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Прогресс
|
|
||||||
if (_progressTitle is not null)
|
|
||||||
{
|
|
||||||
if (_progressMessageId is null)
|
|
||||||
_progressMessageId = await _ctx.StartProgressAsync(_progressTitle, ct);
|
|
||||||
|
|
||||||
if (_progressPercent > 0 && !string.IsNullOrEmpty(_progressMessageId))
|
|
||||||
await _ctx.UpdateProgressAsync(_progressMessageId, _progressPercent.Value, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
_text = null;
|
_text = null;
|
||||||
_files.Clear();
|
_files.Clear();
|
||||||
_album.Clear();
|
_album.Clear();
|
||||||
|
|
||||||
if (_progressPercent >= 100)
|
_editMessageId = null;
|
||||||
{
|
|
||||||
_progressTitle = null;
|
return messageId;
|
||||||
_progressMessageId = null;
|
|
||||||
_progressPercent = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ public sealed class NavigationService
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Перейти по маршруту без аргументов.
|
/// Перейти по маршруту без аргументов.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public Task GoToHome(PageContext ctx, CancellationToken ct)
|
public Task GoToHomeAsync(PageContext ctx, CancellationToken ct)
|
||||||
{
|
{
|
||||||
return NavigateAsync(_defaultPage!, ctx, null, ct);
|
return NavigateAsync(_defaultPage!, ctx, null, ct);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
namespace BotPages.Core.Routing;
|
using System.Reflection;
|
||||||
|
|
||||||
|
namespace BotPages.Core.Routing;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Реестр маршрутов страниц.
|
/// Реестр маршрутов страниц.
|
||||||
@@ -26,4 +28,14 @@ internal sealed class RoutesRegistry
|
|||||||
/// Получить снимок всех маршрутов.
|
/// Получить снимок всех маршрутов.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public IReadOnlyDictionary<string, Type> Snapshot() => _routes;
|
public IReadOnlyDictionary<string, Type> Snapshot() => _routes;
|
||||||
|
|
||||||
|
internal void Map(Type? type)
|
||||||
|
{
|
||||||
|
foreach(var attr in type.GetCustomAttributes<RouteAttribute>(inherit: true))
|
||||||
|
{
|
||||||
|
_routes.Add(attr.Template, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
_routes.Add(type.FullName, type);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -85,33 +85,43 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public async Task SendTextAsync(string chatId, string text, MessageFormat format,
|
public async Task<string?> SendTextAsync(string chatId, string text, MessageFormat format,
|
||||||
IEnumerable<IEnumerable<InlineButton>>? inline,
|
IEnumerable<IEnumerable<InlineButton>>? inline,
|
||||||
IEnumerable<IEnumerable<ReplyButton>>? reply, CancellationToken ct)
|
IEnumerable<IEnumerable<ReplyButton>>? reply,
|
||||||
|
string? messageId,
|
||||||
|
CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (_client is null)
|
if (_client is null)
|
||||||
{
|
{
|
||||||
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
|
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
|
||||||
return;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
InlineKeyboardMarkup? inlineMarkup = null;
|
||||||
ReplyMarkup? markup = null;
|
ReplyMarkup? markup = null;
|
||||||
|
|
||||||
if (inline is not null && inline.Any())
|
if (inline is not null && inline.Any())
|
||||||
{
|
{
|
||||||
markup = new InlineKeyboardMarkup(
|
inlineMarkup = new InlineKeyboardMarkup(
|
||||||
inline.Select(row => row.Select(b => new InlineKeyboardButton(b.Label, b.Value)).ToArray())
|
inline.Select(row => row.Select(b => new InlineKeyboardButton(b.Label, b.Value)).ToArray())
|
||||||
.ToArray()
|
.ToArray()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
else if (reply is not null && reply.Any())
|
else if (reply is not null)
|
||||||
{
|
{
|
||||||
markup = new ReplyKeyboardMarkup(
|
if (reply.Any())
|
||||||
reply.Select(row => row.Select(b => new KeyboardButton(b.Label)).ToArray()).ToArray()
|
|
||||||
)
|
|
||||||
{
|
{
|
||||||
ResizeKeyboard = true
|
markup = new ReplyKeyboardMarkup(
|
||||||
};
|
reply.Select(row => row.Select(b => new KeyboardButton(b.Label)).ToArray()).ToArray()
|
||||||
|
)
|
||||||
|
{
|
||||||
|
ResizeKeyboard = true
|
||||||
|
};
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
markup = new ReplyKeyboardRemove();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var parseMode = ParseMode.None;
|
var parseMode = ParseMode.None;
|
||||||
@@ -147,13 +157,33 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
|||||||
text = text.Substring(0, Capabilities.MaxMessageLength);
|
text = text.Substring(0, Capabilities.MaxMessageLength);
|
||||||
}
|
}
|
||||||
|
|
||||||
await _client.SendMessage(
|
if (!string.IsNullOrWhiteSpace(messageId))
|
||||||
chatId: long.Parse(chatId),
|
{
|
||||||
text: text,
|
await _client.EditMessageText(
|
||||||
parseMode: parseMode,
|
messageId: int.Parse(messageId),
|
||||||
replyMarkup: markup,
|
chatId: long.Parse(chatId),
|
||||||
cancellationToken: ct
|
text: text,
|
||||||
);
|
parseMode: parseMode,
|
||||||
|
replyMarkup: inlineMarkup,
|
||||||
|
cancellationToken: ct
|
||||||
|
);
|
||||||
|
|
||||||
|
return messageId;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (inlineMarkup is not null) markup = inlineMarkup;
|
||||||
|
|
||||||
|
var message = await _client.SendMessage(
|
||||||
|
chatId: long.Parse(chatId),
|
||||||
|
text: text,
|
||||||
|
parseMode: parseMode,
|
||||||
|
replyMarkup: markup,
|
||||||
|
cancellationToken: ct
|
||||||
|
);
|
||||||
|
|
||||||
|
return message.Id.ToString();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
@@ -240,62 +270,6 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
|||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public IAlbumBuilder CreateAlbumBuilder(PageContext ctx) => new TelegramAlbumBuilder(this, ctx, _logger, _client);
|
public IAlbumBuilder CreateAlbumBuilder(PageContext ctx) => new TelegramAlbumBuilder(this, ctx, _logger, _client);
|
||||||
|
|
||||||
/// <inheritdoc />
|
|
||||||
public async Task<string?> StartProgressAsync(PageContext ctx, string title, CancellationToken ct)
|
|
||||||
{
|
|
||||||
if (_client is null)
|
|
||||||
{
|
|
||||||
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
string text = "0%";
|
|
||||||
if (!string.IsNullOrEmpty(title))
|
|
||||||
{
|
|
||||||
text = title + Environment.NewLine + text;
|
|
||||||
}
|
|
||||||
|
|
||||||
var message = await _client.SendMessage(
|
|
||||||
chatId: long.Parse(ctx.Update.Chat.Id),
|
|
||||||
text: text,
|
|
||||||
cancellationToken: ct
|
|
||||||
);
|
|
||||||
|
|
||||||
return message.Id.ToString();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <inheritdoc />
|
|
||||||
public async Task UpdateProgressAsync(PageContext ctx, string messageId, string title, int percent, CancellationToken ct)
|
|
||||||
{
|
|
||||||
if (_client is null)
|
|
||||||
{
|
|
||||||
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
percent = Math.Clamp(percent, 0, 100);
|
|
||||||
|
|
||||||
string text = $"{percent}%";
|
|
||||||
if (!string.IsNullOrEmpty(title))
|
|
||||||
{
|
|
||||||
text = title + Environment.NewLine + text;
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await _client.EditMessageText(
|
|
||||||
messageId: int.Parse(messageId),
|
|
||||||
chatId: long.Parse(ctx.Update.Chat.Id),
|
|
||||||
text: text,
|
|
||||||
cancellationToken: ct
|
|
||||||
);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
_logger.Log(LogLevel.Critical, ex.Message, ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public Task OnLeaveAsync(PageContext ctx, CancellationToken ct) => Task.CompletedTask;
|
public Task OnLeaveAsync(PageContext ctx, CancellationToken ct) => Task.CompletedTask;
|
||||||
}
|
}
|
||||||
@@ -12,8 +12,8 @@ public sealed class SubmitPage : SingletonPage
|
|||||||
{
|
{
|
||||||
var progress = new MessageBuilder(ctx);
|
var progress = new MessageBuilder(ctx);
|
||||||
|
|
||||||
await progress
|
var messageId = await progress
|
||||||
.Progress("Отправка заявки", 7)
|
.Text("Отправка заявки\n7%")
|
||||||
.SendAsync(ct);
|
.SendAsync(ct);
|
||||||
|
|
||||||
int i = 7;
|
int i = 7;
|
||||||
@@ -22,12 +22,13 @@ public sealed class SubmitPage : SingletonPage
|
|||||||
i += 25;
|
i += 25;
|
||||||
Thread.Sleep(TimeSpan.FromMilliseconds(200));
|
Thread.Sleep(TimeSpan.FromMilliseconds(200));
|
||||||
await progress
|
await progress
|
||||||
.Progress("Отправка заявки", i)
|
.Text($"Отправка заявки\n{i}%")
|
||||||
|
.EditMessage(messageId!)
|
||||||
.SendAsync(ct);
|
.SendAsync(ct);
|
||||||
}
|
}
|
||||||
while (i < 100);
|
while (i < 100);
|
||||||
|
|
||||||
await ctx.Navigation.GoToHome(ctx, ct);
|
await ctx.Navigation.GoToHomeAsync(ctx, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public override Task OnLeave(PageContext ctx, CancellationToken ct)
|
public override Task OnLeave(PageContext ctx, CancellationToken ct)
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ public sealed class TitlePage : SingletonPage
|
|||||||
{
|
{
|
||||||
if (text == "Меню")
|
if (text == "Меню")
|
||||||
{
|
{
|
||||||
return ctx.Navigation.GoToHome(ctx, ct);
|
return ctx.Navigation.GoToHomeAsync(ctx, ct);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
|||||||
5
TZ.md
5
TZ.md
@@ -17,7 +17,6 @@
|
|||||||
- **Page** — класс, отвечающий за состояние экрана бота.
|
- **Page** — класс, отвечающий за состояние экрана бота.
|
||||||
- `Page` — базовый класс.
|
- `Page` — базовый класс.
|
||||||
- `Page<TArguments>` — страница с аргументами.
|
- `Page<TArguments>` — страница с аргументами.
|
||||||
- `ModalPage` / `ModalPage<TArguments>` — модальная страница (перехватывает ввод, блокирует переходы).
|
|
||||||
- **Контекст:**
|
- **Контекст:**
|
||||||
- `UserContext` — данные пользователя (UserId, MessengerType).
|
- `UserContext` — данные пользователя (UserId, MessengerType).
|
||||||
- `ChatContext` — данные чата (ChatId, Title, ThreadId?, ленивое обновление).
|
- `ChatContext` — данные чата (ChatId, Title, ThreadId?, ленивое обновление).
|
||||||
@@ -25,7 +24,7 @@
|
|||||||
- **Состояние:**
|
- **Состояние:**
|
||||||
- `IStateStorage` — универсальный интерфейс хранения.
|
- `IStateStorage` — универсальный интерфейс хранения.
|
||||||
- Базовая реализация: InMemory.
|
- Базовая реализация: InMemory.
|
||||||
- Ключ: `CompositeSessionKey(MessengerType:string, ChatId, UserId?)`.
|
- Ключ: `CompositeSessionKey(MessengerType:string, ChatId, UserId)`.
|
||||||
- История состояний: опционально (None, LastN, TimeWindow, Full).
|
- История состояний: опционально (None, LastN, TimeWindow, Full).
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -125,7 +124,7 @@
|
|||||||
```
|
```
|
||||||
- Пример:
|
- Пример:
|
||||||
```csharp
|
```csharp
|
||||||
app.AddMiddleware<IUpdateMiddleware, LoggingMiddleware>();
|
app.AddMiddleware<LoggingMiddleware>();
|
||||||
app.AddMiddleware<ErrorMiddleware>(params);
|
app.AddMiddleware<ErrorMiddleware>(params);
|
||||||
```
|
```
|
||||||
- Порядок регистрации = порядок выполнения.
|
- Порядок регистрации = порядок выполнения.
|
||||||
|
|||||||
Reference in New Issue
Block a user