| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using System.Collections.ObjectModel; |
| | | 3 | | using System.Globalization; |
| | | 4 | | using System.Reflection; |
| | | 5 | | using System.Text.Json; |
| | | 6 | | using System.Text.RegularExpressions; |
| | | 7 | | using Microsoft.Extensions.Logging; |
| | | 8 | | using TeleFlow.Annotations; |
| | | 9 | | using TeleFlow.Framework.Callbacks; |
| | | 10 | | using TeleFlow.Telegram.Internal; |
| | | 11 | | using TeleFlow.Telegram.Schema.Types; |
| | | 12 | | |
| | | 13 | | namespace TeleFlow.Telegram.Internal.Handlers; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Matches incoming Telegram contexts to registered handler routes and binds route |
| | | 17 | | /// values or typed callback payloads before the dispatcher invokes a handler. |
| | | 18 | | /// </summary> |
| | | 19 | | internal sealed partial class TelegramHandlerSelector |
| | | 20 | | { |
| | 1 | 21 | | private static readonly IReadOnlyDictionary<string, object?> EmptyRouteValues = |
| | 1 | 22 | | new ReadOnlyDictionary<string, object?>( |
| | 1 | 23 | | new Dictionary<string, object?>(StringComparer.Ordinal)); |
| | 1 | 24 | | private static readonly ConcurrentDictionary<Type, CallbackPayloadDeserializer> CallbackPayloadDeserializers = new() |
| | | 25 | | |
| | | 26 | | private readonly TelegramHandlerTable _table; |
| | | 27 | | private readonly TelegramBotIdentity _botIdentity; |
| | | 28 | | private readonly ILogger<TelegramHandlerSelector> _logger; |
| | | 29 | | |
| | | 30 | | public TelegramHandlerSelector( |
| | | 31 | | TelegramHandlerTable table, |
| | | 32 | | TelegramBotIdentity botIdentity, |
| | | 33 | | ILoggerFactory loggerFactory) |
| | | 34 | | { |
| | 201 | 35 | | ArgumentNullException.ThrowIfNull(table); |
| | 201 | 36 | | ArgumentNullException.ThrowIfNull(botIdentity); |
| | 201 | 37 | | ArgumentNullException.ThrowIfNull(loggerFactory); |
| | | 38 | | |
| | 201 | 39 | | _table = table; |
| | 201 | 40 | | _botIdentity = botIdentity; |
| | 201 | 41 | | _logger = loggerFactory.CreateLogger<TelegramHandlerSelector>(); |
| | 201 | 42 | | } |
| | | 43 | | |
| | 344 | 44 | | public bool HasStatefulHandlers => _table.HasStatefulHandlers; |
| | | 45 | | |
| | | 46 | | public async ValueTask<TelegramRouteSelection?> SelectMessageHandlerAsync( |
| | | 47 | | MessageContext context, |
| | | 48 | | string? currentState, |
| | | 49 | | CancellationToken cancellationToken) |
| | | 50 | | { |
| | 258 | 51 | | var selection = await SelectMessageHandlerAsync( |
| | 258 | 52 | | context, |
| | 258 | 53 | | _table.CommandHandlerCandidates, |
| | 258 | 54 | | currentState, |
| | 258 | 55 | | cancellationToken).ConfigureAwait(false); |
| | | 56 | | |
| | 258 | 57 | | if (selection is not null) |
| | | 58 | | { |
| | 80 | 59 | | return selection; |
| | | 60 | | } |
| | | 61 | | |
| | 178 | 62 | | return await SelectMessageHandlerAsync( |
| | 178 | 63 | | context, |
| | 178 | 64 | | _table.MessageHandlerCandidates, |
| | 178 | 65 | | currentState, |
| | 178 | 66 | | cancellationToken).ConfigureAwait(false); |
| | 256 | 67 | | } |
| | | 68 | | |
| | | 69 | | public async ValueTask<TelegramRouteSelection?> SelectCallbackHandlerAsync( |
| | | 70 | | CallbackQueryContext context, |
| | | 71 | | string? currentState, |
| | | 72 | | CancellationToken cancellationToken) |
| | | 73 | | { |
| | 72 | 74 | | if (HasCurrentState(currentState)) |
| | | 75 | | { |
| | 1 | 76 | | var state = currentState!; |
| | 1 | 77 | | var statefulPayloadSelection = await SelectCallbackHandlerPassAsync( |
| | 1 | 78 | | context, |
| | 1 | 79 | | _table.CallbackHandlerCandidates.GetStatefulTypedCandidates(state), |
| | 1 | 80 | | cancellationToken).ConfigureAwait(false); |
| | | 81 | | |
| | 1 | 82 | | if (statefulPayloadSelection is not null) |
| | | 83 | | { |
| | 0 | 84 | | return statefulPayloadSelection; |
| | | 85 | | } |
| | | 86 | | |
| | 1 | 87 | | var statefulRawSelection = await SelectCallbackHandlerPassAsync( |
| | 1 | 88 | | context, |
| | 1 | 89 | | _table.CallbackHandlerCandidates.GetStatefulRawCandidates(state), |
| | 1 | 90 | | cancellationToken).ConfigureAwait(false); |
| | | 91 | | |
| | 1 | 92 | | if (statefulRawSelection is not null) |
| | | 93 | | { |
| | 1 | 94 | | return statefulRawSelection; |
| | | 95 | | } |
| | 0 | 96 | | } |
| | | 97 | | |
| | 71 | 98 | | var statelessPayloadSelection = await SelectCallbackHandlerPassAsync( |
| | 71 | 99 | | context, |
| | 71 | 100 | | _table.CallbackHandlerCandidates.StatelessTyped, |
| | 71 | 101 | | cancellationToken).ConfigureAwait(false); |
| | | 102 | | |
| | 69 | 103 | | if (statelessPayloadSelection is not null) |
| | | 104 | | { |
| | 9 | 105 | | return statelessPayloadSelection; |
| | | 106 | | } |
| | | 107 | | |
| | 60 | 108 | | return await SelectCallbackHandlerPassAsync( |
| | 60 | 109 | | context, |
| | 60 | 110 | | _table.CallbackHandlerCandidates.StatelessRaw, |
| | 60 | 111 | | cancellationToken).ConfigureAwait(false); |
| | 70 | 112 | | } |
| | | 113 | | |
| | | 114 | | public async ValueTask<TelegramRouteSelection?> SelectChatMemberHandlerAsync( |
| | | 115 | | ChatMemberUpdatedContext context, |
| | | 116 | | TelegramRouteKind updateRouteKind, |
| | | 117 | | string? currentState, |
| | | 118 | | CancellationToken cancellationToken) |
| | | 119 | | { |
| | 14 | 120 | | if (HasCurrentState(currentState)) |
| | | 121 | | { |
| | 0 | 122 | | var state = currentState!; |
| | 0 | 123 | | var statefulSelection = await SelectChatMemberHandlerPassAsync( |
| | 0 | 124 | | context, |
| | 0 | 125 | | _table.ChatMemberHandlerCandidates.GetStatefulCandidates(state), |
| | 0 | 126 | | updateRouteKind, |
| | 0 | 127 | | cancellationToken).ConfigureAwait(false); |
| | | 128 | | |
| | 0 | 129 | | if (statefulSelection is not null) |
| | | 130 | | { |
| | 0 | 131 | | return statefulSelection; |
| | | 132 | | } |
| | | 133 | | } |
| | | 134 | | |
| | 14 | 135 | | return await SelectChatMemberHandlerPassAsync( |
| | 14 | 136 | | context, |
| | 14 | 137 | | _table.ChatMemberHandlerCandidates.Stateless, |
| | 14 | 138 | | updateRouteKind, |
| | 14 | 139 | | cancellationToken).ConfigureAwait(false); |
| | 14 | 140 | | } |
| | | 141 | | |
| | | 142 | | private async ValueTask<TelegramRouteSelection?> SelectMessageHandlerAsync( |
| | | 143 | | MessageContext context, |
| | | 144 | | TelegramHandlerCandidateSet candidates, |
| | | 145 | | string? currentState, |
| | | 146 | | CancellationToken cancellationToken) |
| | | 147 | | { |
| | 436 | 148 | | if (HasCurrentState(currentState)) |
| | | 149 | | { |
| | 39 | 150 | | var state = currentState!; |
| | 39 | 151 | | var statefulSelection = await SelectMessageHandlerPassAsync( |
| | 39 | 152 | | context, |
| | 39 | 153 | | candidates.GetStatefulCandidates(state), |
| | 39 | 154 | | cancellationToken).ConfigureAwait(false); |
| | | 155 | | |
| | 39 | 156 | | if (statefulSelection is not null) |
| | | 157 | | { |
| | 17 | 158 | | return statefulSelection; |
| | | 159 | | } |
| | | 160 | | } |
| | | 161 | | |
| | 419 | 162 | | return await SelectMessageHandlerPassAsync( |
| | 419 | 163 | | context, |
| | 419 | 164 | | candidates.Stateless, |
| | 419 | 165 | | cancellationToken).ConfigureAwait(false); |
| | 434 | 166 | | } |
| | | 167 | | |
| | | 168 | | private async ValueTask<TelegramRouteSelection?> SelectMessageHandlerPassAsync( |
| | | 169 | | MessageContext context, |
| | | 170 | | IReadOnlyList<TelegramHandlerCandidate> candidates, |
| | | 171 | | CancellationToken cancellationToken) |
| | | 172 | | { |
| | 2408 | 173 | | for (var index = 0; index < candidates.Count; index++) |
| | | 174 | | { |
| | 991 | 175 | | var candidate = candidates[index]; |
| | 991 | 176 | | var route = candidate.Route; |
| | | 177 | | |
| | 991 | 178 | | if (!TryMatchRoute(context.TelegramMessage, route, out var routeValues)) |
| | | 179 | | { |
| | | 180 | | continue; |
| | | 181 | | } |
| | | 182 | | |
| | 396 | 183 | | if (!await TelegramFilterEvaluator.MatchesAsync( |
| | 396 | 184 | | context, |
| | 396 | 185 | | candidate.Filters, |
| | 396 | 186 | | cancellationToken).ConfigureAwait(false)) |
| | | 187 | | { |
| | 151 | 188 | | LogRejectedByFiltersIfEnabled(context, candidate, route); |
| | 151 | 189 | | continue; |
| | | 190 | | } |
| | | 191 | | |
| | 243 | 192 | | return new TelegramRouteSelection(candidate.Handler, route, routeValues, callbackPayload: null); |
| | | 193 | | } |
| | | 194 | | |
| | 213 | 195 | | return null; |
| | 456 | 196 | | } |
| | | 197 | | |
| | | 198 | | private async ValueTask<TelegramRouteSelection?> SelectCallbackHandlerPassAsync( |
| | | 199 | | CallbackQueryContext context, |
| | | 200 | | IReadOnlyList<TelegramHandlerCandidate> candidates, |
| | | 201 | | CancellationToken cancellationToken) |
| | | 202 | | { |
| | 456 | 203 | | for (var index = 0; index < candidates.Count; index++) |
| | | 204 | | { |
| | 162 | 205 | | var candidate = candidates[index]; |
| | 162 | 206 | | var route = candidate.Route; |
| | | 207 | | |
| | 162 | 208 | | if (route.CallbackPayloadType is null) |
| | | 209 | | { |
| | 132 | 210 | | if (!await TelegramFilterEvaluator.MatchesAsync( |
| | 132 | 211 | | context, |
| | 132 | 212 | | candidate.Filters, |
| | 132 | 213 | | cancellationToken).ConfigureAwait(false)) |
| | | 214 | | { |
| | 76 | 215 | | LogRejectedByFiltersIfEnabled(context, candidate, route); |
| | 76 | 216 | | continue; |
| | | 217 | | } |
| | | 218 | | |
| | 56 | 219 | | return new TelegramRouteSelection(candidate.Handler, route, EmptyRouteValues, callbackPayload: null); |
| | | 220 | | } |
| | | 221 | | |
| | 30 | 222 | | if (string.IsNullOrWhiteSpace(context.TelegramCallbackQuery.Data)) |
| | | 223 | | { |
| | | 224 | | continue; |
| | | 225 | | } |
| | | 226 | | |
| | | 227 | | object? callbackPayload; |
| | | 228 | | |
| | | 229 | | try |
| | | 230 | | { |
| | 30 | 231 | | if (!TryDeserializeCallbackPayload( |
| | 30 | 232 | | context, |
| | 30 | 233 | | route.CallbackPayloadType, |
| | 30 | 234 | | out callbackPayload)) |
| | | 235 | | { |
| | 17 | 236 | | continue; |
| | | 237 | | } |
| | 9 | 238 | | } |
| | 2 | 239 | | catch (CallbackDataRouteDeserializationException exception) |
| | | 240 | | { |
| | 2 | 241 | | if (_logger.IsEnabled(LogLevel.Warning)) |
| | | 242 | | { |
| | 2 | 243 | | LogCallbackDataDeserializationFailed( |
| | 2 | 244 | | _logger, |
| | 2 | 245 | | exception, |
| | 2 | 246 | | context.Update.UpdateId, |
| | 2 | 247 | | exception.PayloadType.FullName ?? exception.PayloadType.Name, |
| | 2 | 248 | | TelegramUpdateLogFormatter.FormatHandler(candidate.Handler), |
| | 2 | 249 | | TelegramUpdateLogFormatter.FormatRoute(route), |
| | 2 | 250 | | exception.PayloadByteCount); |
| | | 251 | | } |
| | | 252 | | |
| | 2 | 253 | | continue; |
| | | 254 | | } |
| | | 255 | | |
| | 9 | 256 | | if (!await TelegramFilterEvaluator.MatchesAsync( |
| | 9 | 257 | | context, |
| | 9 | 258 | | candidate.Filters, |
| | 9 | 259 | | cancellationToken).ConfigureAwait(false)) |
| | | 260 | | { |
| | 0 | 261 | | LogRejectedByFiltersIfEnabled(context, candidate, route); |
| | 0 | 262 | | continue; |
| | | 263 | | } |
| | | 264 | | |
| | 9 | 265 | | return new TelegramRouteSelection(candidate.Handler, route, EmptyRouteValues, callbackPayload); |
| | | 266 | | } |
| | | 267 | | |
| | 66 | 268 | | return null; |
| | 131 | 269 | | } |
| | | 270 | | |
| | | 271 | | private async ValueTask<TelegramRouteSelection?> SelectChatMemberHandlerPassAsync( |
| | | 272 | | ChatMemberUpdatedContext context, |
| | | 273 | | IReadOnlyList<TelegramHandlerCandidate> candidates, |
| | | 274 | | TelegramRouteKind updateRouteKind, |
| | | 275 | | CancellationToken cancellationToken) |
| | | 276 | | { |
| | 38 | 277 | | for (var index = 0; index < candidates.Count; index++) |
| | | 278 | | { |
| | 19 | 279 | | var candidate = candidates[index]; |
| | 19 | 280 | | var route = candidate.Route; |
| | | 281 | | |
| | 19 | 282 | | if (route.RouteKind != updateRouteKind) |
| | | 283 | | { |
| | | 284 | | continue; |
| | | 285 | | } |
| | | 286 | | |
| | 19 | 287 | | if (!MatchesChatMemberTransition(context, route)) |
| | | 288 | | { |
| | | 289 | | continue; |
| | | 290 | | } |
| | | 291 | | |
| | 14 | 292 | | if (!await TelegramFilterEvaluator.MatchesAsync( |
| | 14 | 293 | | context, |
| | 14 | 294 | | candidate.Filters, |
| | 14 | 295 | | cancellationToken).ConfigureAwait(false)) |
| | | 296 | | { |
| | 0 | 297 | | LogRejectedByFiltersIfEnabled(context, candidate, route); |
| | 0 | 298 | | continue; |
| | | 299 | | } |
| | | 300 | | |
| | 14 | 301 | | return new TelegramRouteSelection(candidate.Handler, route, EmptyRouteValues, callbackPayload: null); |
| | | 302 | | } |
| | | 303 | | |
| | 0 | 304 | | return null; |
| | 14 | 305 | | } |
| | | 306 | | |
| | | 307 | | private void LogRejectedByFiltersIfEnabled( |
| | | 308 | | TelegramUpdateContext context, |
| | | 309 | | TelegramHandlerCandidate candidate, |
| | | 310 | | TelegramRouteDescriptor route) |
| | | 311 | | { |
| | 227 | 312 | | if (!_logger.IsEnabled(LogLevel.Debug)) |
| | | 313 | | { |
| | 226 | 314 | | return; |
| | | 315 | | } |
| | | 316 | | |
| | 1 | 317 | | LogHandlerRejectedByFilters( |
| | 1 | 318 | | _logger, |
| | 1 | 319 | | context.Update.UpdateId, |
| | 1 | 320 | | TelegramUpdateLogFormatter.GetUpdateType(context.Update), |
| | 1 | 321 | | TelegramUpdateLogFormatter.FormatHandler(candidate.Handler), |
| | 1 | 322 | | TelegramUpdateLogFormatter.FormatRoute(route)); |
| | 1 | 323 | | } |
| | | 324 | | |
| | | 325 | | private bool TryMatchRoute( |
| | | 326 | | Message message, |
| | | 327 | | TelegramRouteDescriptor route, |
| | | 328 | | out IReadOnlyDictionary<string, object?> routeValues) |
| | | 329 | | { |
| | 991 | 330 | | routeValues = EmptyRouteValues; |
| | | 331 | | |
| | 991 | 332 | | return route.RouteKind switch |
| | 991 | 333 | | { |
| | 314 | 334 | | TelegramRouteKind.MessageAny => MatchesTextFilters(message, route), |
| | 123 | 335 | | TelegramRouteKind.TextExact => MatchesTextFilters(message, route), |
| | 30 | 336 | | TelegramRouteKind.TextTemplate => TryMatchTextPattern(message.Text, route, isTemplate: true, out routeValues |
| | 3 | 337 | | TelegramRouteKind.TextRegex => TryMatchTextPattern(message.Text, route, isTemplate: false, out routeValues), |
| | 438 | 338 | | TelegramRouteKind.CommandExact => TryGetCommandBody(message.Text, route, out var body, out var isPrefixLess) |
| | 438 | 339 | | TryMatchExactCommand(body, route, isPrefixLess), |
| | 78 | 340 | | TelegramRouteKind.CommandTemplate => TryGetCommandBody(message.Text, route, out var body, out _) && |
| | 78 | 341 | | TryMatchCommandPattern(body, route, isTemplate: true, out routeValues), |
| | 5 | 342 | | TelegramRouteKind.CommandRegex => TryGetCommandBody(message.Text, route, out var body, out _) && |
| | 5 | 343 | | TryMatchCommandPattern(body, route, isTemplate: false, out routeValues), |
| | 0 | 344 | | _ => false |
| | 991 | 345 | | }; |
| | | 346 | | } |
| | | 347 | | |
| | | 348 | | private static bool HasCurrentState(string? currentState) |
| | | 349 | | { |
| | 522 | 350 | | return !string.IsNullOrWhiteSpace(currentState); |
| | | 351 | | } |
| | | 352 | | |
| | | 353 | | private static bool TryDeserializeCallbackPayload( |
| | | 354 | | CallbackQueryContext context, |
| | | 355 | | Type payloadType, |
| | | 356 | | out object? payload) |
| | | 357 | | { |
| | 30 | 358 | | var data = context.TelegramCallbackQuery.Data!; |
| | | 359 | | |
| | 30 | 360 | | if (context.CallbackData is ICallbackDataRouteDeserializer routeDeserializer) |
| | | 361 | | { |
| | | 362 | | try |
| | | 363 | | { |
| | 26 | 364 | | return routeDeserializer.TryDeserializeForRoute(payloadType, data, out payload); |
| | | 365 | | } |
| | 16 | 366 | | catch (Exception exception) when (IsCallbackPayloadNoMatchException(exception)) |
| | | 367 | | { |
| | 14 | 368 | | payload = null; |
| | 14 | 369 | | return false; |
| | | 370 | | } |
| | | 371 | | } |
| | | 372 | | |
| | 4 | 373 | | var deserializer = CallbackPayloadDeserializers.GetOrAdd(payloadType, CreateCallbackPayloadDeserializer); |
| | | 374 | | |
| | | 375 | | try |
| | | 376 | | { |
| | 4 | 377 | | payload = deserializer(context.CallbackData, data); |
| | 1 | 378 | | return true; |
| | | 379 | | } |
| | 3 | 380 | | catch (Exception exception) when (IsCallbackPayloadNoMatchException(exception)) |
| | | 381 | | { |
| | 1 | 382 | | payload = null; |
| | 1 | 383 | | return false; |
| | | 384 | | } |
| | 26 | 385 | | } |
| | | 386 | | |
| | | 387 | | private static bool IsCallbackPayloadNoMatchException(Exception exception) |
| | | 388 | | { |
| | 19 | 389 | | return exception is JsonException or FormatException or OverflowException; |
| | | 390 | | } |
| | | 391 | | |
| | | 392 | | private static CallbackPayloadDeserializer CreateCallbackPayloadDeserializer(Type payloadType) |
| | | 393 | | { |
| | 1 | 394 | | var deserializeMethod = typeof(TelegramHandlerSelector) |
| | 1 | 395 | | .GetMethod(nameof(DeserializeCallbackPayload), BindingFlags.NonPublic | BindingFlags.Static)! |
| | 1 | 396 | | .MakeGenericMethod(payloadType); |
| | | 397 | | |
| | 1 | 398 | | return deserializeMethod.CreateDelegate<CallbackPayloadDeserializer>(); |
| | | 399 | | } |
| | | 400 | | |
| | | 401 | | private static object? DeserializeCallbackPayload<TPayload>( |
| | | 402 | | ICallbackDataSerializer serializer, |
| | | 403 | | string data) |
| | | 404 | | { |
| | 4 | 405 | | return serializer.Deserialize<TPayload>(data); |
| | | 406 | | } |
| | | 407 | | |
| | | 408 | | private bool TryGetCommandBody( |
| | | 409 | | string? text, |
| | | 410 | | TelegramRouteDescriptor route, |
| | | 411 | | out string commandBody, |
| | | 412 | | out bool isPrefixLess) |
| | | 413 | | { |
| | 521 | 414 | | commandBody = string.Empty; |
| | 521 | 415 | | isPrefixLess = false; |
| | | 416 | | |
| | 521 | 417 | | if (string.IsNullOrWhiteSpace(text)) |
| | | 418 | | { |
| | 0 | 419 | | return false; |
| | | 420 | | } |
| | | 421 | | |
| | 521 | 422 | | switch (route.CommandPolicy.PrefixMode) |
| | | 423 | | { |
| | | 424 | | case CommandPrefixMode.Required: |
| | 435 | 425 | | return TryGetPrefixedCommandBody(text, route, out commandBody); |
| | | 426 | | |
| | | 427 | | case CommandPrefixMode.Optional: |
| | 80 | 428 | | if (TryGetPrefixedCommandBody(text, route, out commandBody)) |
| | | 429 | | { |
| | 17 | 430 | | return true; |
| | | 431 | | } |
| | | 432 | | |
| | 63 | 433 | | isPrefixLess = true; |
| | 63 | 434 | | return TryGetPrefixLessCommandBody(text, out commandBody); |
| | | 435 | | |
| | | 436 | | case CommandPrefixMode.NoPrefix: |
| | 6 | 437 | | isPrefixLess = true; |
| | 6 | 438 | | return TryGetPrefixLessCommandBody(text, out commandBody); |
| | | 439 | | |
| | | 440 | | default: |
| | 0 | 441 | | return false; |
| | | 442 | | } |
| | | 443 | | } |
| | | 444 | | |
| | | 445 | | private bool TryGetPrefixedCommandBody( |
| | | 446 | | string text, |
| | | 447 | | TelegramRouteDescriptor route, |
| | | 448 | | out string commandBody) |
| | | 449 | | { |
| | 515 | 450 | | commandBody = string.Empty; |
| | | 451 | | |
| | 1948 | 452 | | foreach (var prefix in route.CommandPolicy.Prefixes) |
| | | 453 | | { |
| | 549 | 454 | | if (!text.StartsWith(prefix, route.CommandPolicy.IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringCom |
| | | 455 | | { |
| | | 456 | | continue; |
| | | 457 | | } |
| | | 458 | | |
| | 180 | 459 | | commandBody = text[prefix.Length..]; |
| | | 460 | | |
| | 180 | 461 | | if (route.CommandPolicy.AllowSpaceAfterPrefix) |
| | | 462 | | { |
| | 3 | 463 | | commandBody = commandBody.TrimStart(' ', '\t'); |
| | | 464 | | } |
| | | 465 | | |
| | 180 | 466 | | if (prefix == "/") |
| | | 467 | | { |
| | 169 | 468 | | if (!TryTrimSlashCommandBotMention(commandBody, out commandBody)) |
| | | 469 | | { |
| | 25 | 470 | | return false; |
| | | 471 | | } |
| | | 472 | | } |
| | | 473 | | |
| | 155 | 474 | | return !string.IsNullOrWhiteSpace(commandBody); |
| | | 475 | | } |
| | | 476 | | |
| | 335 | 477 | | return false; |
| | 180 | 478 | | } |
| | | 479 | | |
| | | 480 | | private static bool TryGetPrefixLessCommandBody( |
| | | 481 | | string text, |
| | | 482 | | out string commandBody) |
| | | 483 | | { |
| | 69 | 484 | | commandBody = text; |
| | | 485 | | |
| | 69 | 486 | | return !string.IsNullOrWhiteSpace(commandBody); |
| | | 487 | | } |
| | | 488 | | |
| | | 489 | | private bool TryTrimSlashCommandBotMention( |
| | | 490 | | string commandBody, |
| | | 491 | | out string trimmedCommandBody) |
| | | 492 | | { |
| | 169 | 493 | | var tokenEnd = commandBody.IndexOfAny([' ', '\t', '\r', '\n']); |
| | 169 | 494 | | var token = tokenEnd < 0 ? commandBody : commandBody[..tokenEnd]; |
| | 169 | 495 | | var mentionIndex = token.IndexOf('@', StringComparison.Ordinal); |
| | | 496 | | |
| | 169 | 497 | | if (mentionIndex < 0) |
| | | 498 | | { |
| | 140 | 499 | | trimmedCommandBody = commandBody; |
| | 140 | 500 | | return true; |
| | | 501 | | } |
| | | 502 | | |
| | 29 | 503 | | if (!_botIdentity.MatchesMention(token.AsSpan()[(mentionIndex + 1)..])) |
| | | 504 | | { |
| | 25 | 505 | | trimmedCommandBody = string.Empty; |
| | 25 | 506 | | return false; |
| | | 507 | | } |
| | | 508 | | |
| | 4 | 509 | | var trimmedToken = token[..mentionIndex]; |
| | | 510 | | |
| | 4 | 511 | | trimmedCommandBody = tokenEnd < 0 |
| | 4 | 512 | | ? trimmedToken |
| | 4 | 513 | | : trimmedToken + commandBody[tokenEnd..]; |
| | 4 | 514 | | return true; |
| | | 515 | | } |
| | | 516 | | |
| | | 517 | | private static bool TryMatchExactCommand( |
| | | 518 | | string commandBody, |
| | | 519 | | TelegramRouteDescriptor route, |
| | | 520 | | bool isPrefixLess) |
| | | 521 | | { |
| | 168 | 522 | | if (string.IsNullOrWhiteSpace(route.Pattern)) |
| | | 523 | | { |
| | 0 | 524 | | return false; |
| | | 525 | | } |
| | | 526 | | |
| | 168 | 527 | | if (isPrefixLess) |
| | | 528 | | { |
| | 33 | 529 | | return string.Equals( |
| | 33 | 530 | | TelegramCommandTextNormalizer.Normalize(commandBody.Trim()), |
| | 33 | 531 | | route.Pattern, |
| | 33 | 532 | | route.CommandPolicy.IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); |
| | | 533 | | } |
| | | 534 | | |
| | 135 | 535 | | var tokenEnd = commandBody.IndexOfAny([' ', '\t', '\r', '\n']); |
| | 135 | 536 | | var token = tokenEnd < 0 ? commandBody : commandBody[..tokenEnd]; |
| | | 537 | | |
| | 135 | 538 | | return string.Equals( |
| | 135 | 539 | | TelegramCommandTextNormalizer.Normalize(token), |
| | 135 | 540 | | route.Pattern, |
| | 135 | 541 | | route.CommandPolicy.IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); |
| | | 542 | | } |
| | | 543 | | |
| | | 544 | | private static bool TryMatchTextPattern( |
| | | 545 | | string? text, |
| | | 546 | | TelegramRouteDescriptor route, |
| | | 547 | | bool isTemplate, |
| | | 548 | | out IReadOnlyDictionary<string, object?> routeValues) |
| | | 549 | | { |
| | 33 | 550 | | routeValues = EmptyRouteValues; |
| | | 551 | | |
| | 33 | 552 | | if (string.IsNullOrWhiteSpace(text)) |
| | | 553 | | { |
| | 0 | 554 | | return false; |
| | | 555 | | } |
| | | 556 | | |
| | 33 | 557 | | return TryMatchPattern(text, route, isTemplate, route.CommandPolicy.IgnoreCase, out routeValues); |
| | | 558 | | } |
| | | 559 | | |
| | | 560 | | private static bool TryMatchCommandPattern( |
| | | 561 | | string commandBody, |
| | | 562 | | TelegramRouteDescriptor route, |
| | | 563 | | bool isTemplate, |
| | | 564 | | out IReadOnlyDictionary<string, object?> routeValues) |
| | | 565 | | { |
| | 56 | 566 | | var value = isTemplate |
| | 56 | 567 | | ? TelegramCommandTextNormalizer.Normalize(commandBody) |
| | 56 | 568 | | : commandBody; |
| | | 569 | | |
| | 56 | 570 | | return TryMatchPattern(value, route, isTemplate, route.CommandPolicy.IgnoreCase, out routeValues); |
| | | 571 | | } |
| | | 572 | | |
| | | 573 | | private static bool TryMatchPattern( |
| | | 574 | | string value, |
| | | 575 | | TelegramRouteDescriptor route, |
| | | 576 | | bool isTemplate, |
| | | 577 | | bool ignoreCase, |
| | | 578 | | out IReadOnlyDictionary<string, object?> routeValues) |
| | | 579 | | { |
| | 89 | 580 | | routeValues = EmptyRouteValues; |
| | | 581 | | |
| | 89 | 582 | | if (string.IsNullOrWhiteSpace(route.Pattern)) |
| | | 583 | | { |
| | 0 | 584 | | return false; |
| | | 585 | | } |
| | | 586 | | |
| | 89 | 587 | | var regex = route.Matcher.Regex ?? (isTemplate |
| | 89 | 588 | | ? TelegramTemplateRouteParser.BuildRegex(route.Pattern, ignoreCase) |
| | 89 | 589 | | : new Regex(route.Pattern, TelegramTemplateRouteParser.GetRegexOptions(ignoreCase))); |
| | 89 | 590 | | var match = regex.Match(value); |
| | | 591 | | |
| | 89 | 592 | | if (!match.Success) |
| | | 593 | | { |
| | 57 | 594 | | return false; |
| | | 595 | | } |
| | | 596 | | |
| | 32 | 597 | | return TryBindRouteValues(route, match, out routeValues); |
| | | 598 | | } |
| | | 599 | | |
| | | 600 | | private static bool TryBindRouteValues( |
| | | 601 | | TelegramRouteDescriptor route, |
| | | 602 | | Match match, |
| | | 603 | | out IReadOnlyDictionary<string, object?> routeValues) |
| | | 604 | | { |
| | 32 | 605 | | routeValues = EmptyRouteValues; |
| | | 606 | | |
| | 32 | 607 | | if (route.RouteValues.Count == 0) |
| | | 608 | | { |
| | 4 | 609 | | return true; |
| | | 610 | | } |
| | | 611 | | |
| | 28 | 612 | | var values = new Dictionary<string, object?>(StringComparer.Ordinal); |
| | | 613 | | |
| | 110 | 614 | | foreach (var valueDescriptor in route.RouteValues) |
| | | 615 | | { |
| | 28 | 616 | | var group = match.Groups[valueDescriptor.Name]; |
| | | 617 | | |
| | 28 | 618 | | if (!group.Success) |
| | | 619 | | { |
| | 4 | 620 | | if (!valueDescriptor.IsOptional) |
| | | 621 | | { |
| | 1 | 622 | | return false; |
| | | 623 | | } |
| | | 624 | | |
| | 3 | 625 | | values[valueDescriptor.Name] = null; |
| | 3 | 626 | | continue; |
| | | 627 | | } |
| | | 628 | | |
| | 24 | 629 | | if (!TryConvertRouteValue(valueDescriptor, group.Value, out var convertedValue)) |
| | | 630 | | { |
| | 1 | 631 | | return false; |
| | | 632 | | } |
| | | 633 | | |
| | 23 | 634 | | values[valueDescriptor.Name] = convertedValue; |
| | | 635 | | } |
| | | 636 | | |
| | 26 | 637 | | routeValues = values; |
| | 26 | 638 | | return true; |
| | 2 | 639 | | } |
| | | 640 | | |
| | | 641 | | private static bool TryConvertRouteValue( |
| | | 642 | | TelegramRouteValueDescriptor descriptor, |
| | | 643 | | string value, |
| | | 644 | | out object? convertedValue) |
| | | 645 | | { |
| | 24 | 646 | | if (descriptor.ValueType == typeof(string)) |
| | | 647 | | { |
| | 4 | 648 | | convertedValue = value; |
| | 4 | 649 | | return true; |
| | | 650 | | } |
| | | 651 | | |
| | 20 | 652 | | if (descriptor.ValueType == typeof(int) && |
| | 20 | 653 | | int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intValue)) |
| | | 654 | | { |
| | 9 | 655 | | convertedValue = intValue; |
| | 9 | 656 | | return true; |
| | | 657 | | } |
| | | 658 | | |
| | 11 | 659 | | if (descriptor.ValueType == typeof(long) && |
| | 11 | 660 | | long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var longValue)) |
| | | 661 | | { |
| | 10 | 662 | | convertedValue = longValue; |
| | 10 | 663 | | return true; |
| | | 664 | | } |
| | | 665 | | |
| | 1 | 666 | | convertedValue = null; |
| | | 667 | | |
| | 1 | 668 | | if (descriptor.ValueType == typeof(int) || |
| | 1 | 669 | | descriptor.ValueType == typeof(long)) |
| | | 670 | | { |
| | 1 | 671 | | return false; |
| | | 672 | | } |
| | | 673 | | |
| | 0 | 674 | | throw new InvalidOperationException( |
| | 0 | 675 | | $"Route value '{descriptor.Name}' uses unsupported type {descriptor.ValueType.Name}."); |
| | | 676 | | } |
| | | 677 | | |
| | | 678 | | private static bool MatchesTextFilters(Message message, TelegramRouteDescriptor route) |
| | | 679 | | { |
| | 437 | 680 | | var textFilters = route.TextFilters; |
| | | 681 | | |
| | 914 | 682 | | for (var index = 0; index < textFilters.Count; index++) |
| | | 683 | | { |
| | 152 | 684 | | if (!textFilters[index].Matches(message.Text)) |
| | | 685 | | { |
| | 132 | 686 | | return false; |
| | | 687 | | } |
| | | 688 | | } |
| | | 689 | | |
| | 305 | 690 | | return true; |
| | | 691 | | } |
| | | 692 | | |
| | | 693 | | private static bool MatchesChatMemberTransition( |
| | | 694 | | ChatMemberUpdatedContext context, |
| | | 695 | | TelegramRouteDescriptor route) |
| | | 696 | | { |
| | 19 | 697 | | if (route.ChatMemberTransitions.Count == 0) |
| | | 698 | | { |
| | 5 | 699 | | return true; |
| | | 700 | | } |
| | | 701 | | |
| | 14 | 702 | | var oldStatus = TelegramChatMemberClassifier.GetStatus(context.OldChatMember); |
| | 14 | 703 | | var newStatus = TelegramChatMemberClassifier.GetStatus(context.NewChatMember); |
| | 14 | 704 | | var transitions = route.ChatMemberTransitions; |
| | | 705 | | |
| | 38 | 706 | | for (var index = 0; index < transitions.Count; index++) |
| | | 707 | | { |
| | 14 | 708 | | var transition = transitions[index]; |
| | | 709 | | |
| | 14 | 710 | | if ((transition.OldStatus & oldStatus) != 0 && |
| | 14 | 711 | | (transition.NewStatus & newStatus) != 0) |
| | | 712 | | { |
| | 9 | 713 | | return true; |
| | | 714 | | } |
| | | 715 | | } |
| | | 716 | | |
| | 5 | 717 | | return false; |
| | | 718 | | } |
| | | 719 | | |
| | | 720 | | private delegate object? CallbackPayloadDeserializer(ICallbackDataSerializer serializer, string data); |
| | | 721 | | } |