| | | 1 | | using System.Security.Cryptography; |
| | | 2 | | using System.Text; |
| | | 3 | | using System.Text.Json; |
| | | 4 | | using TeleFlow.Telegram.Schema.Types; |
| | | 5 | | |
| | | 6 | | namespace TeleFlow.Telegram.Internal; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Decodes one known Telegram update envelope and captures raw payload evidence only when schema mapping fails. |
| | | 10 | | /// </summary> |
| | | 11 | | internal static class TelegramUpdateDecoder |
| | | 12 | | { |
| | | 13 | | public static TelegramUpdateDecodeResult Decode( |
| | | 14 | | JsonElement payload, |
| | | 15 | | long updateId, |
| | | 16 | | JsonSerializerOptions serializerOptions, |
| | | 17 | | string? methodName = null) |
| | | 18 | | { |
| | 30 | 19 | | ArgumentNullException.ThrowIfNull(serializerOptions); |
| | | 20 | | |
| | | 21 | | try |
| | | 22 | | { |
| | 30 | 23 | | var update = payload.Deserialize<Update>(serializerOptions) |
| | 30 | 24 | | ?? throw new JsonException("Telegram update payload deserialized to null."); |
| | | 25 | | |
| | 22 | 26 | | return TelegramUpdateDecodeResult.Success(update); |
| | | 27 | | } |
| | 8 | 28 | | catch (Exception exception) when (exception is JsonException or NotSupportedException) |
| | | 29 | | { |
| | 8 | 30 | | var rawPayloadJson = payload.GetRawText(); |
| | 8 | 31 | | var payloadSha256 = Convert.ToHexStringLower( |
| | 8 | 32 | | SHA256.HashData(Encoding.UTF8.GetBytes(rawPayloadJson))); |
| | 8 | 33 | | var jsonPath = exception is JsonException jsonException ? jsonException.Path : null; |
| | 8 | 34 | | var decodeException = new TelegramUpdateDecodeException( |
| | 8 | 35 | | $"Failed to deserialize Telegram update '{updateId}'.", |
| | 8 | 36 | | updateId, |
| | 8 | 37 | | payloadSha256, |
| | 8 | 38 | | jsonPath, |
| | 8 | 39 | | exception, |
| | 8 | 40 | | methodName); |
| | | 41 | | |
| | 8 | 42 | | return TelegramUpdateDecodeResult.Failure( |
| | 8 | 43 | | updateId, |
| | 8 | 44 | | rawPayloadJson, |
| | 8 | 45 | | payloadSha256, |
| | 8 | 46 | | decodeException); |
| | | 47 | | } |
| | 30 | 48 | | } |
| | | 49 | | } |