about summary refs log tree commit diff
path: root/MatrixRoomUtils.Core/Extensions
diff options
context:
space:
mode:
authorEmma@Rory& <root@rory.gay>2023-07-24 20:56:42 +0200
committerEmma@Rory& <root@rory.gay>2023-07-24 20:56:42 +0200
commit5495a35403d285007d67f503042720302efdf94c (patch)
tree3db4dc545ce3ad252f82a577ecad4150320c1ba3 /MatrixRoomUtils.Core/Extensions
parentChange max line width from 120 to 180 (diff)
downloadMatrixUtils-5495a35403d285007d67f503042720302efdf94c.tar.xz
Code cleanup
Diffstat (limited to 'MatrixRoomUtils.Core/Extensions')
-rw-r--r--MatrixRoomUtils.Core/Extensions/ClassCollector.cs10
-rw-r--r--MatrixRoomUtils.Core/Extensions/HttpClientExtensions.cs28
-rw-r--r--MatrixRoomUtils.Core/Extensions/JsonElementExtensions.cs154
3 files changed, 149 insertions, 43 deletions
diff --git a/MatrixRoomUtils.Core/Extensions/ClassCollector.cs b/MatrixRoomUtils.Core/Extensions/ClassCollector.cs

index 9d3d3c0..d4ba838 100644 --- a/MatrixRoomUtils.Core/Extensions/ClassCollector.cs +++ b/MatrixRoomUtils.Core/Extensions/ClassCollector.cs
@@ -19,12 +19,4 @@ public class ClassCollector<T> where T : class { public List<Type> ResolveFromAssembly(Assembly assembly) => assembly.GetTypes() .Where(x => x is { IsClass: true, IsAbstract: false } && x.GetInterfaces().Contains(typeof(T))).ToList(); - // { - // List<Type> ret = new(); - // foreach (var x in assembly.GetTypes().Where(x => x is { IsClass: true, IsAbstract: false } && x.GetInterfaces().Contains(typeof(T))).ToList()) { - // // Console.WriteLine($"[!!] Found class {x.FullName}"); - // ret.Add(x); - // } - // return ret; - // } -} \ No newline at end of file +} diff --git a/MatrixRoomUtils.Core/Extensions/HttpClientExtensions.cs b/MatrixRoomUtils.Core/Extensions/HttpClientExtensions.cs
index 695e8e3..9ac9c6b 100644 --- a/MatrixRoomUtils.Core/Extensions/HttpClientExtensions.cs +++ b/MatrixRoomUtils.Core/Extensions/HttpClientExtensions.cs
@@ -19,40 +19,42 @@ public static class HttpClientExtensions { } public class MatrixHttpClient : HttpClient { - public override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - Console.WriteLine($"Sending request to {request.RequestUri}"); - try - { - HttpRequestOptionsKey<bool> WebAssemblyEnableStreamingResponseKey = new HttpRequestOptionsKey<bool>("WebAssemblyEnableStreamingResponse"); + public override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, + CancellationToken cancellationToken) { + Console.WriteLine($"Sending request to {request.RequestUri}"); + try { + HttpRequestOptionsKey<bool> WebAssemblyEnableStreamingResponseKey = + new HttpRequestOptionsKey<bool>("WebAssemblyEnableStreamingResponse"); request.Options.Set(WebAssemblyEnableStreamingResponseKey, true); - // var asm = Assembly.Load("Microsoft.AspNetCore.Components.WebAssembly"); - // var browserHttpHandlerType = asm.GetType("Microsoft.AspNetCore.Components.WebAssembly.Http.WebAssemblyHttpRequestMessageExtensions", true); - // var browserHttpHandlerMethod = browserHttpHandlerType.GetMethod("SetBrowserResponseStreamingEnabled", BindingFlags.Public | BindingFlags.Static); - // browserHttpHandlerMethod?.Invoke(null, new object[] {request, true}); } - catch (Exception e) - { + catch (Exception e) { Console.WriteLine("Failed to set browser response streaming:"); Console.WriteLine(e); } + var a = await base.SendAsync(request, cancellationToken); if (!a.IsSuccessStatusCode) { var content = await a.Content.ReadAsStringAsync(cancellationToken); if (content.StartsWith('{')) { var ex = JsonSerializer.Deserialize<MatrixException>(content); ex.RawContent = content; - Console.WriteLine($"Failed to send request: {ex}"); + Console.WriteLine($"Failed to send request: {ex}"); if (ex?.RetryAfterMs is not null) { await Task.Delay(ex.RetryAfterMs.Value, cancellationToken); - typeof(HttpRequestMessage).GetField("_sendStatus", BindingFlags.NonPublic | BindingFlags.Instance)?.SetValue(request, 0); + typeof(HttpRequestMessage).GetField("_sendStatus", BindingFlags.NonPublic | BindingFlags.Instance) + ?.SetValue(request, 0); return await SendAsync(request, cancellationToken); } + throw ex!; } + throw new InvalidDataException("Encountered invalid data:\n" + content); } + return a; } + // GetFromJsonAsync public async Task<T> GetFromJsonAsync<T>(string requestUri, CancellationToken cancellationToken = default) { var request = new HttpRequestMessage(HttpMethod.Get, requestUri); diff --git a/MatrixRoomUtils.Core/Extensions/JsonElementExtensions.cs b/MatrixRoomUtils.Core/Extensions/JsonElementExtensions.cs
index 36da644..7701c9e 100644 --- a/MatrixRoomUtils.Core/Extensions/JsonElementExtensions.cs +++ b/MatrixRoomUtils.Core/Extensions/JsonElementExtensions.cs
@@ -3,37 +3,149 @@ using System.Reflection; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; +using MatrixRoomUtils.Core.Responses; namespace MatrixRoomUtils.Core.Extensions; public static class JsonElementExtensions { - public static bool FindExtraJsonElementFields([DisallowNull] this JsonElement? res, Type t) { - var props = t.GetProperties(); - var unknownPropertyFound = false; - foreach (var field in res.Value.EnumerateObject()) { - if (props.Any(x => x.GetCustomAttribute<JsonPropertyNameAttribute>()?.Name == field.Name)) continue; - Console.WriteLine($"[!!] Unknown property {field.Name} in {t.Name}!"); + public static bool FindExtraJsonElementFields(this JsonElement obj, Type objectType, string objectPropertyName) { + if (objectPropertyName == "content" && objectType == typeof(JsonObject)) + objectType = typeof(StateEventResponse); + // if (t == typeof(JsonNode)) + // return false; + + Console.WriteLine($"{objectType.Name} {objectPropertyName}"); + bool unknownPropertyFound = false; + var mappedPropsDict = objectType.GetProperties() + .Where(x => x.GetCustomAttribute<JsonPropertyNameAttribute>() is not null) + .ToDictionary(x => x.GetCustomAttribute<JsonPropertyNameAttribute>()!.Name, x => x); + objectType.GetProperties().Where(x => !mappedPropsDict.ContainsKey(x.Name)) + .ToList().ForEach(x => mappedPropsDict.TryAdd(x.Name, x)); + + foreach (var field in obj.EnumerateObject()) { + if (mappedPropsDict.TryGetValue(field.Name, out var mappedProperty)) { + //dictionary + if (mappedProperty.PropertyType.IsGenericType && + mappedProperty.PropertyType.GetGenericTypeDefinition() == typeof(Dictionary<,>)) { + unknownPropertyFound |= _checkDictionary(field, objectType, mappedProperty.PropertyType); + continue; + } + + if (mappedProperty.PropertyType.IsGenericType && + mappedProperty.PropertyType.GetGenericTypeDefinition() == typeof(List<>)) { + unknownPropertyFound |= _checkList(field, objectType, mappedProperty.PropertyType); + continue; + } + + if (field.Name == "content" && (objectType == typeof(StateEventResponse) || objectType == typeof(StateEvent))) { + unknownPropertyFound |= field.FindExtraJsonPropertyFieldsByValueKind( + StateEvent.GetStateEventType(obj.GetProperty("type").GetString()), + mappedProperty.PropertyType); + continue; + } + + unknownPropertyFound |= + field.FindExtraJsonPropertyFieldsByValueKind(objectType, mappedProperty.PropertyType); + continue; + } + + Console.WriteLine($"[!!] Unknown property {field.Name} in {objectType.Name}!"); unknownPropertyFound = true; } - if (unknownPropertyFound) Console.WriteLine(res.Value.ToJson()); - return unknownPropertyFound; } - public static bool FindExtraJsonObjectFields([DisallowNull] this JsonObject? res, Type t) { - var props = t.GetProperties(); - var unknownPropertyFound = false; - foreach (var field in res) { - if (props.Any(x => x.GetCustomAttribute<JsonPropertyNameAttribute>()?.Name == field.Key)) continue; - Console.WriteLine($"[!!] Unknown property {field.Key} in {t.Name}!"); - unknownPropertyFound = true; - // foreach (var propertyInfo in props) { - // Console.WriteLine($"[!!] Known property {propertyInfo.GetCustomAttribute<JsonPropertyNameAttribute>()?.Name} in {t.Name}!"); - // } + + private static bool FindExtraJsonPropertyFieldsByValueKind(this JsonProperty field, Type containerType, + Type propertyType) { + if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { + propertyType = propertyType.GetGenericArguments()[0]; } - if (unknownPropertyFound) Console.WriteLine(res.ToJson()); + bool switchResult = false; + switch (field.Value.ValueKind) { + case JsonValueKind.Array: + switchResult = field.Value.EnumerateArray().Aggregate(switchResult, + (current, element) => current | element.FindExtraJsonElementFields(propertyType, field.Name)); + break; + case JsonValueKind.Object: + switchResult |= field.Value.FindExtraJsonElementFields(propertyType, field.Name); + break; + case JsonValueKind.True: + case JsonValueKind.False: + return _checkBool(field, containerType, propertyType); + case JsonValueKind.String: + return _checkString(field, containerType, propertyType); + case JsonValueKind.Number: + return _checkNumber(field, containerType, propertyType); + case JsonValueKind.Undefined: + case JsonValueKind.Null: + break; + default: + throw new ArgumentOutOfRangeException(); + } - return unknownPropertyFound; + return switchResult; + } + + private static bool _checkBool(this JsonProperty field, Type containerType, Type propertyType) { + if (propertyType == typeof(bool)) return true; + Console.WriteLine( + $"[!!] Encountered bool for {field.Name} in {containerType.Name}, the class defines {propertyType.Name}!"); + return false; + } + + private static bool _checkString(this JsonProperty field, Type containerType, Type propertyType) { + if (propertyType == typeof(string)) return true; + // ReSharper disable once BuiltInTypeReferenceStyle + if (propertyType == typeof(String)) return true; + Console.WriteLine( + $"[!!] Encountered string for {field.Name} in {containerType.Name}, the class defines {propertyType.Name}!"); + return false; + } + + private static bool _checkNumber(this JsonProperty field, Type containerType, Type propertyType) { + if (propertyType == typeof(int) || + propertyType == typeof(double) || + propertyType == typeof(float) || + propertyType == typeof(decimal) || + propertyType == typeof(long) || + propertyType == typeof(short) || + propertyType == typeof(uint) || + propertyType == typeof(ulong) || + propertyType == typeof(ushort) || + propertyType == typeof(byte) || + propertyType == typeof(sbyte)) + return true; + Console.WriteLine( + $"[!!] Encountered number for {field.Name} in {containerType.Name}, the class defines {propertyType.Name}!"); + return false; + } + + private static bool _checkDictionary(this JsonProperty field, Type containerType, Type propertyType) { + var keyType = propertyType.GetGenericArguments()[0]; + var valueType = propertyType.GetGenericArguments()[1]; + valueType = Nullable.GetUnderlyingType(valueType) ?? valueType; + Console.WriteLine( + $"Encountered dictionary {field.Name} with key type {keyType.Name} and value type {valueType.Name}!"); + + return field.Value.EnumerateObject() + .Where(key => !valueType.IsPrimitive && valueType != typeof(string)) + .Aggregate(false, (current, key) => + current | key.FindExtraJsonPropertyFieldsByValueKind(containerType, valueType) + ); + } + + private static bool _checkList(this JsonProperty field, Type containerType, Type propertyType) { + var valueType = propertyType.GetGenericArguments()[0]; + valueType = Nullable.GetUnderlyingType(valueType) ?? valueType; + Console.WriteLine( + $"Encountered list {field.Name} with value type {valueType.Name}!"); + + return field.Value.EnumerateArray() + .Where(key => !valueType.IsPrimitive && valueType != typeof(string)) + .Aggregate(false, (current, key) => + current | key.FindExtraJsonElementFields(valueType, field.Name) + ); } -} \ No newline at end of file +}