| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using System.Globalization; |
| | | 3 | | using System.Reflection; |
| | | 4 | | using System.Text; |
| | | 5 | | using System.Text.Json; |
| | | 6 | | using TeleFlow.Annotations; |
| | | 7 | | |
| | | 8 | | namespace TeleFlow.Telegram.Internal; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Caches compact callback payload metadata discovered from <see cref="CallbackDataAttribute"/> |
| | | 12 | | /// so typed callback routing and keyboard packing share one prefix-plus-fields contract. |
| | | 13 | | /// </summary> |
| | | 14 | | internal sealed class CallbackDataMetadata |
| | | 15 | | { |
| | 1 | 16 | | private static readonly ConcurrentDictionary<Type, Lazy<MetadataLookup>> MetadataCache = new(); |
| | | 17 | | |
| | | 18 | | private CallbackDataMetadata( |
| | | 19 | | Type payloadType, |
| | | 20 | | string prefix, |
| | | 21 | | IReadOnlyList<CallbackDataField> fields, |
| | | 22 | | ConstructorInfo? constructor) |
| | | 23 | | { |
| | | 24 | | PayloadType = payloadType; |
| | | 25 | | Prefix = prefix; |
| | | 26 | | Fields = fields; |
| | | 27 | | Constructor = constructor; |
| | 5 | 28 | | } |
| | | 29 | | |
| | | 30 | | public Type PayloadType { get; } |
| | | 31 | | |
| | | 32 | | public string Prefix { get; } |
| | | 33 | | |
| | | 34 | | public IReadOnlyList<CallbackDataField> Fields { get; } |
| | | 35 | | |
| | | 36 | | public ConstructorInfo? Constructor { get; } |
| | | 37 | | |
| | | 38 | | public static bool TryCreate(Type payloadType, out CallbackDataMetadata metadata) |
| | | 39 | | { |
| | 92 | 40 | | ArgumentNullException.ThrowIfNull(payloadType); |
| | | 41 | | |
| | 92 | 42 | | var lookup = MetadataCache.GetOrAdd( |
| | 92 | 43 | | payloadType, |
| | 104 | 44 | | static type => new Lazy<MetadataLookup>( |
| | 12 | 45 | | () => CreateLookup(type), |
| | 104 | 46 | | LazyThreadSafetyMode.ExecutionAndPublication)).Value; |
| | | 47 | | |
| | 92 | 48 | | if (lookup.ErrorMessage is not null) |
| | | 49 | | { |
| | 2 | 50 | | throw new InvalidOperationException(lookup.ErrorMessage); |
| | | 51 | | } |
| | | 52 | | |
| | 90 | 53 | | if (lookup.Metadata is null) |
| | | 54 | | { |
| | 59 | 55 | | metadata = null!; |
| | 59 | 56 | | return false; |
| | | 57 | | } |
| | | 58 | | |
| | 31 | 59 | | metadata = lookup.Metadata; |
| | 31 | 60 | | return true; |
| | | 61 | | } |
| | | 62 | | |
| | | 63 | | private static MetadataLookup CreateLookup(Type payloadType) |
| | | 64 | | { |
| | 12 | 65 | | var attribute = payloadType.GetCustomAttribute<CallbackDataAttribute>(inherit: false); |
| | 12 | 66 | | if (attribute is null) |
| | | 67 | | { |
| | 6 | 68 | | return MetadataLookup.Missing; |
| | | 69 | | } |
| | | 70 | | |
| | | 71 | | try |
| | | 72 | | { |
| | 6 | 73 | | return MetadataLookup.Valid(Create(payloadType, attribute.Prefix)); |
| | | 74 | | } |
| | | 75 | | catch (InvalidOperationException exception) |
| | | 76 | | { |
| | 1 | 77 | | return MetadataLookup.Invalid(exception.Message); |
| | | 78 | | } |
| | 6 | 79 | | } |
| | | 80 | | |
| | | 81 | | private static CallbackDataMetadata Create(Type payloadType, string prefix) |
| | | 82 | | { |
| | 6 | 83 | | ValidatePrefix(prefix, payloadType); |
| | | 84 | | |
| | 6 | 85 | | var constructor = payloadType |
| | 6 | 86 | | .GetConstructors(BindingFlags.Instance | BindingFlags.Public) |
| | 6 | 87 | | .Where(static candidate => candidate.GetParameters().Length > 0) |
| | 6 | 88 | | .OrderByDescending(static candidate => candidate.GetParameters().Length) |
| | 6 | 89 | | .FirstOrDefault(); |
| | | 90 | | |
| | 6 | 91 | | var fields = constructor is not null |
| | 6 | 92 | | ? CreateConstructorFields(payloadType, constructor) |
| | 6 | 93 | | : CreatePropertyFields(payloadType); |
| | | 94 | | |
| | 5 | 95 | | return new CallbackDataMetadata(payloadType, prefix, fields, constructor); |
| | | 96 | | } |
| | | 97 | | |
| | | 98 | | private static CallbackDataField[] CreateConstructorFields( |
| | | 99 | | Type payloadType, |
| | | 100 | | ConstructorInfo constructor) |
| | | 101 | | { |
| | 6 | 102 | | var properties = payloadType |
| | 6 | 103 | | .GetProperties(BindingFlags.Instance | BindingFlags.Public) |
| | 7 | 104 | | .Where(static property => property.GetMethod is not null) |
| | 13 | 105 | | .ToDictionary(static property => property.Name, StringComparer.OrdinalIgnoreCase); |
| | | 106 | | |
| | 6 | 107 | | return constructor |
| | 6 | 108 | | .GetParameters() |
| | 6 | 109 | | .Select(parameter => |
| | 6 | 110 | | { |
| | 7 | 111 | | if (!properties.TryGetValue(parameter.Name ?? string.Empty, out var property)) |
| | 6 | 112 | | { |
| | 0 | 113 | | throw new InvalidOperationException( |
| | 0 | 114 | | $"Callback data payload type '{payloadType.FullName}' constructor parameter '{parameter.Name}' d |
| | 6 | 115 | | } |
| | 6 | 116 | | |
| | 7 | 117 | | ValidateFieldType(payloadType, property.PropertyType, property.Name); |
| | 6 | 118 | | return new CallbackDataField(property, parameter); |
| | 6 | 119 | | }) |
| | 6 | 120 | | .ToArray(); |
| | | 121 | | } |
| | | 122 | | |
| | | 123 | | private static CallbackDataField[] CreatePropertyFields(Type payloadType) |
| | | 124 | | { |
| | 0 | 125 | | var properties = payloadType |
| | 0 | 126 | | .GetProperties(BindingFlags.Instance | BindingFlags.Public) |
| | 0 | 127 | | .Where(static property => property.GetMethod is not null) |
| | 0 | 128 | | .OrderBy(static property => property.MetadataToken) |
| | 0 | 129 | | .ToArray(); |
| | | 130 | | |
| | 0 | 131 | | foreach (var property in properties) |
| | | 132 | | { |
| | 0 | 133 | | if (property.SetMethod is null) |
| | | 134 | | { |
| | 0 | 135 | | throw new InvalidOperationException( |
| | 0 | 136 | | $"Callback data payload type '{payloadType.FullName}' property '{property.Name}' must be settable wh |
| | | 137 | | } |
| | | 138 | | |
| | 0 | 139 | | ValidateFieldType(payloadType, property.PropertyType, property.Name); |
| | | 140 | | } |
| | | 141 | | |
| | 0 | 142 | | return properties |
| | 0 | 143 | | .Select(static property => new CallbackDataField(property, Parameter: null)) |
| | 0 | 144 | | .ToArray(); |
| | | 145 | | } |
| | | 146 | | |
| | | 147 | | private static void ValidatePrefix(string prefix, Type payloadType) |
| | | 148 | | { |
| | 6 | 149 | | if (string.IsNullOrWhiteSpace(prefix)) |
| | | 150 | | { |
| | 0 | 151 | | throw new InvalidOperationException( |
| | 0 | 152 | | $"Callback data payload type '{payloadType.FullName}' must declare a non-empty callback data prefix."); |
| | | 153 | | } |
| | | 154 | | |
| | 6 | 155 | | if (prefix.Contains(':', StringComparison.Ordinal) || |
| | 6 | 156 | | prefix.Contains('%', StringComparison.Ordinal) || |
| | 6 | 157 | | prefix.Any(char.IsWhiteSpace)) |
| | | 158 | | { |
| | 0 | 159 | | throw new InvalidOperationException( |
| | 0 | 160 | | $"Callback data payload type '{payloadType.FullName}' prefix must not contain ':', '%', or whitespace.") |
| | | 161 | | } |
| | | 162 | | |
| | 6 | 163 | | if (Encoding.UTF8.GetByteCount(prefix) > CallbackDataCodec.MaxTelegramCallbackDataBytes) |
| | | 164 | | { |
| | 0 | 165 | | throw new InvalidOperationException( |
| | 0 | 166 | | $"Callback data payload type '{payloadType.FullName}' prefix must be at most {CallbackDataCodec.MaxTeleg |
| | | 167 | | } |
| | 6 | 168 | | } |
| | | 169 | | |
| | | 170 | | private static void ValidateFieldType(Type payloadType, Type fieldType, string fieldName) |
| | | 171 | | { |
| | 7 | 172 | | var type = Nullable.GetUnderlyingType(fieldType) ?? fieldType; |
| | | 173 | | |
| | 7 | 174 | | if (Nullable.GetUnderlyingType(fieldType) is not null) |
| | | 175 | | { |
| | 1 | 176 | | throw new InvalidOperationException( |
| | 1 | 177 | | $"Callback data payload type '{payloadType.FullName}' field '{fieldName}' must not be nullable."); |
| | | 178 | | } |
| | | 179 | | |
| | 6 | 180 | | if (type == typeof(string) || |
| | 6 | 181 | | type == typeof(int) || |
| | 6 | 182 | | type == typeof(long) || |
| | 6 | 183 | | type == typeof(bool) || |
| | 6 | 184 | | type.IsEnum) |
| | | 185 | | { |
| | 6 | 186 | | return; |
| | | 187 | | } |
| | | 188 | | |
| | 0 | 189 | | throw new InvalidOperationException( |
| | 0 | 190 | | $"Callback data payload type '{payloadType.FullName}' field '{fieldName}' has unsupported type '{fieldType.F |
| | 0 | 191 | | "Supported compact callback data types are string, int, long, bool, and enums."); |
| | | 192 | | } |
| | | 193 | | |
| | | 194 | | public string FormatField(object? value, Type fieldType) |
| | | 195 | | { |
| | 13 | 196 | | if (value is null) |
| | | 197 | | { |
| | 0 | 198 | | throw new InvalidOperationException( |
| | 0 | 199 | | $"Callback data payload type '{PayloadType.FullName}' contains a null field value. Compact callback data |
| | | 200 | | } |
| | | 201 | | |
| | 13 | 202 | | var type = Nullable.GetUnderlyingType(fieldType) ?? fieldType; |
| | | 203 | | |
| | 13 | 204 | | string text = type == typeof(bool) |
| | 13 | 205 | | ? ((bool)value ? "true" : "false") |
| | 13 | 206 | | : type.IsEnum |
| | 13 | 207 | | ? value.ToString()! |
| | 13 | 208 | | : Convert.ToString(value, CultureInfo.InvariantCulture)!; |
| | | 209 | | |
| | 13 | 210 | | return Escape(text); |
| | | 211 | | } |
| | | 212 | | |
| | | 213 | | public string Pack(object payload) |
| | | 214 | | { |
| | 10 | 215 | | ArgumentNullException.ThrowIfNull(payload); |
| | | 216 | | |
| | 10 | 217 | | if (!PayloadType.IsInstanceOfType(payload)) |
| | | 218 | | { |
| | 0 | 219 | | throw new InvalidOperationException( |
| | 0 | 220 | | $"Callback data payload type '{payload.GetType().FullName}' is not compatible with metadata for '{Payloa |
| | | 221 | | } |
| | | 222 | | |
| | 10 | 223 | | var builder = new StringBuilder(Prefix); |
| | | 224 | | |
| | 46 | 225 | | for (var index = 0; index < Fields.Count; index++) |
| | | 226 | | { |
| | 13 | 227 | | var field = Fields[index]; |
| | 13 | 228 | | builder |
| | 13 | 229 | | .Append(':') |
| | 13 | 230 | | .Append(FormatField(field.Property.GetValue(payload), field.Property.PropertyType)); |
| | | 231 | | } |
| | | 232 | | |
| | 10 | 233 | | return builder.ToString(); |
| | | 234 | | } |
| | | 235 | | |
| | | 236 | | public object ParseField(string value, Type fieldType) |
| | | 237 | | { |
| | 10 | 238 | | var text = Unescape(value); |
| | 10 | 239 | | var type = Nullable.GetUnderlyingType(fieldType) ?? fieldType; |
| | | 240 | | |
| | 10 | 241 | | if (type == typeof(string)) |
| | | 242 | | { |
| | 5 | 243 | | return text; |
| | | 244 | | } |
| | | 245 | | |
| | 5 | 246 | | if (type == typeof(int)) |
| | | 247 | | { |
| | 5 | 248 | | return int.Parse(text, CultureInfo.InvariantCulture); |
| | | 249 | | } |
| | | 250 | | |
| | 0 | 251 | | if (type == typeof(long)) |
| | | 252 | | { |
| | 0 | 253 | | return long.Parse(text, CultureInfo.InvariantCulture); |
| | | 254 | | } |
| | | 255 | | |
| | 0 | 256 | | if (type == typeof(bool)) |
| | | 257 | | { |
| | 0 | 258 | | return bool.Parse(text); |
| | | 259 | | } |
| | | 260 | | |
| | 0 | 261 | | if (type.IsEnum) |
| | | 262 | | { |
| | 0 | 263 | | if (Enum.TryParse(type, text, ignoreCase: false, out var enumValue)) |
| | | 264 | | { |
| | 0 | 265 | | return enumValue; |
| | | 266 | | } |
| | | 267 | | |
| | 0 | 268 | | throw new JsonException( |
| | 0 | 269 | | $"Telegram callback data field for payload type '{PayloadType.FullName}' is not a valid enum value for ' |
| | | 270 | | } |
| | | 271 | | |
| | 0 | 272 | | throw new InvalidOperationException( |
| | 0 | 273 | | $"Callback data payload type '{PayloadType.FullName}' has unsupported field type '{fieldType.FullName}'."); |
| | | 274 | | } |
| | | 275 | | |
| | | 276 | | public bool MatchesSerializedPayload(string serializedPayload) |
| | | 277 | | { |
| | 10 | 278 | | ArgumentNullException.ThrowIfNull(serializedPayload); |
| | | 279 | | |
| | 10 | 280 | | if (!serializedPayload.StartsWith(Prefix, StringComparison.Ordinal)) |
| | | 281 | | { |
| | 2 | 282 | | return false; |
| | | 283 | | } |
| | | 284 | | |
| | 8 | 285 | | if (Fields.Count == 0) |
| | | 286 | | { |
| | 0 | 287 | | return serializedPayload.Length == Prefix.Length; |
| | | 288 | | } |
| | | 289 | | |
| | 8 | 290 | | if (serializedPayload.Length <= Prefix.Length || |
| | 8 | 291 | | serializedPayload[Prefix.Length] != ':') |
| | | 292 | | { |
| | 1 | 293 | | return false; |
| | | 294 | | } |
| | | 295 | | |
| | 7 | 296 | | var separatorCount = 0; |
| | | 297 | | |
| | 114 | 298 | | for (var index = Prefix.Length; index < serializedPayload.Length; index++) |
| | | 299 | | { |
| | 50 | 300 | | if (serializedPayload[index] == ':') |
| | | 301 | | { |
| | 14 | 302 | | separatorCount++; |
| | | 303 | | } |
| | | 304 | | } |
| | | 305 | | |
| | 7 | 306 | | return separatorCount == Fields.Count; |
| | | 307 | | } |
| | | 308 | | |
| | | 309 | | private static string Escape(string value) |
| | | 310 | | { |
| | 13 | 311 | | return value |
| | 13 | 312 | | .Replace("%", "%25", StringComparison.Ordinal) |
| | 13 | 313 | | .Replace(":", "%3A", StringComparison.Ordinal); |
| | | 314 | | } |
| | | 315 | | |
| | | 316 | | private static string Unescape(string value) |
| | | 317 | | { |
| | 10 | 318 | | return value |
| | 10 | 319 | | .Replace("%3A", ":", StringComparison.Ordinal) |
| | 10 | 320 | | .Replace("%25", "%", StringComparison.Ordinal); |
| | | 321 | | } |
| | | 322 | | |
| | | 323 | | private sealed class MetadataLookup |
| | | 324 | | { |
| | 1 | 325 | | public static readonly MetadataLookup Missing = new(metadata: null, errorMessage: null); |
| | | 326 | | |
| | | 327 | | private MetadataLookup( |
| | | 328 | | CallbackDataMetadata? metadata, |
| | | 329 | | string? errorMessage) |
| | | 330 | | { |
| | | 331 | | Metadata = metadata; |
| | | 332 | | ErrorMessage = errorMessage; |
| | 7 | 333 | | } |
| | | 334 | | |
| | | 335 | | public CallbackDataMetadata? Metadata { get; } |
| | | 336 | | |
| | | 337 | | public string? ErrorMessage { get; } |
| | | 338 | | |
| | | 339 | | public static MetadataLookup Valid(CallbackDataMetadata metadata) |
| | | 340 | | { |
| | 5 | 341 | | return new MetadataLookup(metadata, errorMessage: null); |
| | | 342 | | } |
| | | 343 | | |
| | | 344 | | public static MetadataLookup Invalid(string errorMessage) |
| | | 345 | | { |
| | 1 | 346 | | return new MetadataLookup(metadata: null, errorMessage); |
| | | 347 | | } |
| | | 348 | | } |
| | | 349 | | } |
| | | 350 | | |
| | | 351 | | internal sealed record CallbackDataField(PropertyInfo Property, ParameterInfo? Parameter); |