| | | 1 | | using System.Text; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | |
| | | 4 | | namespace TeleFlow.Telegram; |
| | | 5 | | |
| | | 6 | | public sealed class Base64UrlJsonDeepLinkPayloadSerializer : IDeepLinkPayloadSerializer |
| | | 7 | | { |
| | 1 | 8 | | private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); |
| | | 9 | | |
| | | 10 | | public string Serialize<TPayload>(TPayload payload) |
| | | 11 | | { |
| | 3 | 12 | | ArgumentNullException.ThrowIfNull(payload); |
| | | 13 | | |
| | 3 | 14 | | var json = JsonSerializer.Serialize(payload, JsonOptions); |
| | 3 | 15 | | var bytes = Encoding.UTF8.GetBytes(json); |
| | 3 | 16 | | return Convert.ToBase64String(bytes) |
| | 3 | 17 | | .TrimEnd('=') |
| | 3 | 18 | | .Replace('+', '-') |
| | 3 | 19 | | .Replace('/', '_'); |
| | | 20 | | } |
| | | 21 | | |
| | | 22 | | public TPayload Deserialize<TPayload>(string payload) |
| | | 23 | | { |
| | 3 | 24 | | ArgumentException.ThrowIfNullOrWhiteSpace(payload); |
| | | 25 | | |
| | | 26 | | try |
| | | 27 | | { |
| | 3 | 28 | | var base64 = payload |
| | 3 | 29 | | .Replace('-', '+') |
| | 3 | 30 | | .Replace('_', '/'); |
| | 3 | 31 | | var padding = base64.Length % 4; |
| | 3 | 32 | | if (padding != 0) |
| | | 33 | | { |
| | 3 | 34 | | base64 = base64.PadRight(base64.Length + 4 - padding, '='); |
| | | 35 | | } |
| | | 36 | | |
| | 3 | 37 | | var bytes = Convert.FromBase64String(base64); |
| | 3 | 38 | | return JsonSerializer.Deserialize<TPayload>(bytes, JsonOptions) |
| | 3 | 39 | | ?? throw new ArgumentException("Deep-link payload JSON deserialized to null.", nameof(payload)); |
| | | 40 | | } |
| | 1 | 41 | | catch (Exception exception) when (exception is FormatException or JsonException) |
| | | 42 | | { |
| | 1 | 43 | | throw new ArgumentException( |
| | 1 | 44 | | "Deep-link payload is not a valid Base64Url JSON payload.", |
| | 1 | 45 | | nameof(payload), |
| | 1 | 46 | | exception); |
| | | 47 | | } |
| | 2 | 48 | | } |
| | | 49 | | } |