From ae18c049338dfcb33f721eeeb0a05571e8bd87a9 Mon Sep 17 00:00:00 2001 From: Rory& Date: Thu, 30 May 2024 08:02:40 +0000 Subject: Rename StateEvent to LegacyMatrixEvent --- LibMatrix/EventIdResponse.cs | 1 + LibMatrix/Extensions/EnumerableExtensions.cs | 4 +- LibMatrix/Extensions/JsonElementExtensions.cs | 6 +- LibMatrix/Helpers/SyncHelper.cs | 4 +- LibMatrix/Helpers/SyncStateResolver.cs | 42 ++--- LibMatrix/LegacyMatrixEvent.cs | 225 ++++++++++++++++++++++ LibMatrix/MessagesResponse.cs | 4 +- LibMatrix/Responses/CreateRoomRequest.cs | 12 +- LibMatrix/Responses/SyncResponse.cs | 6 +- LibMatrix/RoomTypes/GenericRoom.cs | 26 +-- LibMatrix/StateEvent.cs | 257 -------------------------- 11 files changed, 278 insertions(+), 309 deletions(-) create mode 100644 LibMatrix/LegacyMatrixEvent.cs delete mode 100644 LibMatrix/StateEvent.cs (limited to 'LibMatrix') diff --git a/LibMatrix/EventIdResponse.cs b/LibMatrix/EventIdResponse.cs index 4d715a4..4dca734 100644 --- a/LibMatrix/EventIdResponse.cs +++ b/LibMatrix/EventIdResponse.cs @@ -1,3 +1,4 @@ +#define BALLS using System.Text.Json.Serialization; namespace LibMatrix; diff --git a/LibMatrix/Extensions/EnumerableExtensions.cs b/LibMatrix/Extensions/EnumerableExtensions.cs index 42d9491..b5193ab 100644 --- a/LibMatrix/Extensions/EnumerableExtensions.cs +++ b/LibMatrix/Extensions/EnumerableExtensions.cs @@ -1,7 +1,7 @@ namespace LibMatrix.Extensions; public static class EnumerableExtensions { - public static void MergeStateEventLists(this IList oldState, IList newState) { + public static void MergeStateEventLists(this IList oldState, IList newState) { foreach (var stateEvent in newState) { var old = oldState.FirstOrDefault(x => x.Type == stateEvent.Type && x.StateKey == stateEvent.StateKey); if (old is null) { @@ -14,7 +14,7 @@ public static class EnumerableExtensions { } } - public static void MergeStateEventLists(this IList oldState, IList newState) { + public static void MergeStateEventLists(this IList oldState, IList newState) { foreach (var stateEvent in newState) { var old = oldState.FirstOrDefault(x => x.Type == stateEvent.Type && x.StateKey == stateEvent.StateKey); if (old is null) { diff --git a/LibMatrix/Extensions/JsonElementExtensions.cs b/LibMatrix/Extensions/JsonElementExtensions.cs index c4ed743..a2faddc 100644 --- a/LibMatrix/Extensions/JsonElementExtensions.cs +++ b/LibMatrix/Extensions/JsonElementExtensions.cs @@ -8,7 +8,7 @@ namespace LibMatrix.Extensions; public static class JsonElementExtensions { public static bool FindExtraJsonElementFields(this JsonElement obj, Type objectType, string objectPropertyName) { if (objectPropertyName == "content" && objectType == typeof(JsonObject)) - objectType = typeof(StateEventResponse); + objectType = typeof(LegacyMatrixEventResponse); // if (t == typeof(JsonNode)) // return false; @@ -35,9 +35,9 @@ public static class JsonElementExtensions { continue; } - if (field.Name == "content" && (objectType == typeof(StateEventResponse) || objectType == typeof(StateEvent))) { + if (field.Name == "content" && (objectType == typeof(LegacyMatrixEventResponse) || objectType == typeof(LegacyMatrixEvent))) { unknownPropertyFound |= field.FindExtraJsonPropertyFieldsByValueKind( - StateEvent.GetStateEventType(obj.GetProperty("type").GetString()!), // We expect type to always be present + LegacyMatrixEvent.GetStateEventType(obj.GetProperty("type").GetString()!), // We expect type to always be present mappedProperty.PropertyType); continue; } diff --git a/LibMatrix/Helpers/SyncHelper.cs b/LibMatrix/Helpers/SyncHelper.cs index 1833bd0..5635955 100644 --- a/LibMatrix/Helpers/SyncHelper.cs +++ b/LibMatrix/Helpers/SyncHelper.cs @@ -204,12 +204,12 @@ public class SyncHelper(AuthenticatedHomeserverGeneric homeserver, ILogger? logg /// /// Event fired when a timeline event is received /// - public List> TimelineEventHandlers { get; } = new(); + public List> TimelineEventHandlers { get; } = new(); /// /// Event fired when an account data event is received /// - public List> AccountDataReceivedHandlers { get; } = new(); + public List> AccountDataReceivedHandlers { get; } = new(); private void Log(string message) { if (logger is null) Console.WriteLine(message); diff --git a/LibMatrix/Helpers/SyncStateResolver.cs b/LibMatrix/Helpers/SyncStateResolver.cs index 72d600d..b1f83ff 100644 --- a/LibMatrix/Helpers/SyncStateResolver.cs +++ b/LibMatrix/Helpers/SyncStateResolver.cs @@ -37,13 +37,13 @@ public class SyncStateResolver(AuthenticatedHomeserverGeneric homeserver, ILogge oldState.NextBatch = newState.NextBatch ?? oldState.NextBatch; oldState.AccountData ??= new EventList(); - oldState.AccountData.Events ??= new List(); + oldState.AccountData.Events ??= new List(); if (newState.AccountData?.Events is not null) - oldState.AccountData.Events.MergeStateEventLists(newState.AccountData?.Events ?? new List()); + oldState.AccountData.Events.MergeStateEventLists(newState.AccountData?.Events ?? new List()); oldState.Presence ??= new SyncResponse.PresenceDataStructure(); if (newState.Presence?.Events is not null) - oldState.Presence.Events.MergeStateEventLists(newState.Presence?.Events ?? new List()); + oldState.Presence.Events.MergeStateEventLists(newState.Presence?.Events ?? new List()); oldState.DeviceOneTimeKeysCount ??= new Dictionary(); if (newState.DeviceOneTimeKeysCount is not null) @@ -55,9 +55,9 @@ public class SyncStateResolver(AuthenticatedHomeserverGeneric homeserver, ILogge oldState.Rooms = MergeRoomsDataStructure(oldState.Rooms, newState.Rooms); oldState.ToDevice ??= new EventList(); - oldState.ToDevice.Events ??= new List(); + oldState.ToDevice.Events ??= new List(); if (newState.ToDevice?.Events is not null) - oldState.ToDevice.Events.MergeStateEventLists(newState.ToDevice?.Events ?? new List()); + oldState.ToDevice.Events.MergeStateEventLists(newState.ToDevice?.Events ?? new List()); oldState.DeviceLists ??= new SyncResponse.DeviceListsDataStructure(); if (newState.DeviceLists?.Changed is not null) @@ -97,22 +97,22 @@ public class SyncStateResolver(AuthenticatedHomeserverGeneric homeserver, ILogge private SyncResponse.RoomsDataStructure.LeftRoomDataStructure MergeLeftRoomDataStructure(SyncResponse.RoomsDataStructure.LeftRoomDataStructure oldData, SyncResponse.RoomsDataStructure.LeftRoomDataStructure newData) { oldData.AccountData ??= new EventList(); - oldData.AccountData.Events ??= new List(); + oldData.AccountData.Events ??= new List(); oldData.Timeline ??= new SyncResponse.RoomsDataStructure.JoinedRoomDataStructure.TimelineDataStructure(); - oldData.Timeline.Events ??= new List(); + oldData.Timeline.Events ??= new List(); oldData.State ??= new EventList(); - oldData.State.Events ??= new List(); + oldData.State.Events ??= new List(); if (newData.AccountData?.Events is not null) - oldData.AccountData.Events.MergeStateEventLists(newData.AccountData?.Events ?? new List()); + oldData.AccountData.Events.MergeStateEventLists(newData.AccountData?.Events ?? new List()); if (newData.Timeline?.Events is not null) - oldData.Timeline.Events.MergeStateEventLists(newData.Timeline?.Events ?? new List()); + oldData.Timeline.Events.MergeStateEventLists(newData.Timeline?.Events ?? new List()); oldData.Timeline.Limited = newData.Timeline?.Limited ?? oldData.Timeline.Limited; oldData.Timeline.PrevBatch = newData.Timeline?.PrevBatch ?? oldData.Timeline.PrevBatch; if (newData.State?.Events is not null) - oldData.State.Events.MergeStateEventLists(newData.State?.Events ?? new List()); + oldData.State.Events.MergeStateEventLists(newData.State?.Events ?? new List()); return oldData; } @@ -120,9 +120,9 @@ public class SyncStateResolver(AuthenticatedHomeserverGeneric homeserver, ILogge private SyncResponse.RoomsDataStructure.InvitedRoomDataStructure MergeInvitedRoomDataStructure(SyncResponse.RoomsDataStructure.InvitedRoomDataStructure oldData, SyncResponse.RoomsDataStructure.InvitedRoomDataStructure newData) { oldData.InviteState ??= new EventList(); - oldData.InviteState.Events ??= new List(); + oldData.InviteState.Events ??= new List(); if (newData.InviteState?.Events is not null) - oldData.InviteState.Events.MergeStateEventLists(newData.InviteState?.Events ?? new List()); + oldData.InviteState.Events.MergeStateEventLists(newData.InviteState?.Events ?? new List()); return oldData; } @@ -130,27 +130,27 @@ public class SyncStateResolver(AuthenticatedHomeserverGeneric homeserver, ILogge private SyncResponse.RoomsDataStructure.JoinedRoomDataStructure MergeJoinedRoomDataStructure(SyncResponse.RoomsDataStructure.JoinedRoomDataStructure oldData, SyncResponse.RoomsDataStructure.JoinedRoomDataStructure newData) { oldData.AccountData ??= new EventList(); - oldData.AccountData.Events ??= new List(); + oldData.AccountData.Events ??= new List(); oldData.Timeline ??= new SyncResponse.RoomsDataStructure.JoinedRoomDataStructure.TimelineDataStructure(); - oldData.Timeline.Events ??= new List(); + oldData.Timeline.Events ??= new List(); oldData.State ??= new EventList(); - oldData.State.Events ??= new List(); + oldData.State.Events ??= new List(); oldData.Ephemeral ??= new EventList(); - oldData.Ephemeral.Events ??= new List(); + oldData.Ephemeral.Events ??= new List(); if (newData.AccountData?.Events is not null) - oldData.AccountData.Events.MergeStateEventLists(newData.AccountData?.Events ?? new List()); + oldData.AccountData.Events.MergeStateEventLists(newData.AccountData?.Events ?? new List()); if (newData.Timeline?.Events is not null) - oldData.Timeline.Events.MergeStateEventLists(newData.Timeline?.Events ?? new List()); + oldData.Timeline.Events.MergeStateEventLists(newData.Timeline?.Events ?? new List()); oldData.Timeline.Limited = newData.Timeline?.Limited ?? oldData.Timeline.Limited; oldData.Timeline.PrevBatch = newData.Timeline?.PrevBatch ?? oldData.Timeline.PrevBatch; if (newData.State?.Events is not null) - oldData.State.Events.MergeStateEventLists(newData.State?.Events ?? new List()); + oldData.State.Events.MergeStateEventLists(newData.State?.Events ?? new List()); if (newData.Ephemeral?.Events is not null) - oldData.Ephemeral.Events.MergeStateEventLists(newData.Ephemeral?.Events ?? new List()); + oldData.Ephemeral.Events.MergeStateEventLists(newData.Ephemeral?.Events ?? new List()); oldData.UnreadNotifications ??= new SyncResponse.RoomsDataStructure.JoinedRoomDataStructure.UnreadNotificationsDataStructure(); oldData.UnreadNotifications.HighlightCount = newData.UnreadNotifications?.HighlightCount ?? oldData.UnreadNotifications.HighlightCount; diff --git a/LibMatrix/LegacyMatrixEvent.cs b/LibMatrix/LegacyMatrixEvent.cs new file mode 100644 index 0000000..1cfc879 --- /dev/null +++ b/LibMatrix/LegacyMatrixEvent.cs @@ -0,0 +1,225 @@ +using System.Collections.Frozen; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; +using ArcaneLibs; +using ArcaneLibs.Attributes; +using ArcaneLibs.Extensions; +using LibMatrix.EventTypes; +using LibMatrix.Extensions; + +namespace LibMatrix; + +public class LegacyMatrixEvent { + public static FrozenSet KnownStateEventTypes { get; } = new ClassCollector().ResolveFromAllAccessibleAssemblies().ToFrozenSet(); + + public static FrozenDictionary KnownStateEventTypesByName { get; } = KnownStateEventTypes.Aggregate( + new Dictionary(), + (dict, type) => { + var attrs = type.GetCustomAttributes(); + foreach (var attr in attrs) { + if (dict.TryGetValue(attr.EventName, out var existing)) + Console.WriteLine($"Duplicate event type '{attr.EventName}' registered for types '{existing.Name}' and '{type.Name}'"); + dict[attr.EventName] = type; + } + + return dict; + }).OrderBy(x => x.Key).ToFrozenDictionary(); + + public static Type GetStateEventType(string? type) => + string.IsNullOrWhiteSpace(type) ? typeof(UnknownEventContent) : KnownStateEventTypesByName.GetValueOrDefault(type) ?? typeof(UnknownEventContent); + + [JsonIgnore] + public Type MappedType => GetStateEventType(Type); + + [JsonIgnore] + public bool IsLegacyType => MappedType.GetCustomAttributes().FirstOrDefault(x => x.EventName == Type)?.Legacy ?? false; + + [JsonIgnore] + public string FriendlyTypeName => MappedType.GetFriendlyNameOrNull() ?? Type; + + [JsonIgnore] + public string FriendlyTypeNamePlural => MappedType.GetFriendlyNamePluralOrNull() ?? Type; + + private static readonly JsonSerializerOptions TypedContentSerializerOptions = new() { + Converters = { + new JsonFloatStringConverter(), + new JsonDoubleStringConverter(), + new JsonDecimalStringConverter() + } + }; + + [JsonIgnore] + [SuppressMessage("ReSharper", "PropertyCanBeMadeInitOnly.Global")] + public EventContent? TypedContent { + get { + // if (Type == "m.receipt") { + // return null; + // } + try { + var mappedType = GetStateEventType(Type); + if (mappedType == typeof(UnknownEventContent)) + Console.WriteLine($"Warning: unknown event type '{Type}'"); + var deserialisedContent = (EventContent)RawContent.Deserialize(mappedType, TypedContentSerializerOptions)!; + return deserialisedContent; + } + catch (JsonException e) { + Console.WriteLine(e); + Console.WriteLine("Content:\n" + (RawContent?.ToJson() ?? "null")); + } + + return null; + } + set { + if (value is null) + RawContent?.Clear(); + else + RawContent = JsonSerializer.Deserialize(JsonSerializer.Serialize(value, value.GetType(), + new JsonSerializerOptions() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull })); + } + } + + [JsonPropertyName("state_key")] + public string? StateKey { get; set; } + + [JsonPropertyName("type")] + public string Type { get; set; } + + [JsonPropertyName("replaces_state")] + public string? ReplacesState { get; set; } + + private JsonObject? _rawContent; + + [JsonPropertyName("content")] + public JsonObject? RawContent { + get => _rawContent; + set => _rawContent = value; + } + + [JsonIgnore] + public string InternalSelfTypeName { + get { + var res = GetType().Name switch { + "StateEvent`1" => "StateEvent", + _ => GetType().Name + }; + return res; + } + } + + [JsonIgnore] + public string InternalContentTypeName => TypedContent?.GetType().Name ?? "null"; +} + +public class LegacyMatrixEventResponse : LegacyMatrixEvent { + [JsonPropertyName("origin_server_ts")] + public long? OriginServerTs { get; set; } + + [JsonPropertyName("room_id")] + public string? RoomId { get; set; } + + [JsonPropertyName("sender")] + public string? Sender { get; set; } + + [JsonPropertyName("unsigned")] + public UnsignedData? Unsigned { get; set; } + + [JsonPropertyName("event_id")] + public string? EventId { get; set; } + + public class UnsignedData { + [JsonPropertyName("age")] + public ulong? Age { get; set; } + + [JsonPropertyName("redacted_because")] + public object? RedactedBecause { get; set; } + + [JsonPropertyName("transaction_id")] + public string? TransactionId { get; set; } + + [JsonPropertyName("replaces_state")] + public string? ReplacesState { get; set; } + + [JsonPropertyName("prev_sender")] + public string? PrevSender { get; set; } + + [JsonPropertyName("prev_content")] + public JsonObject? PrevContent { get; set; } + } +} + +[JsonSourceGenerationOptions(WriteIndented = true)] +[JsonSerializable(typeof(ChunkedStateEventResponse))] +internal partial class ChunkedStateEventResponseSerializerContext : JsonSerializerContext; + +public class EventList { + public EventList() { } + + public EventList(List? events) { + Events = events; + } + + [JsonPropertyName("events")] + public List? Events { get; set; } = new(); +} + +public class ChunkedStateEventResponse { + [JsonPropertyName("chunk")] + public List? Chunk { get; set; } = new(); +} + +public class PaginatedChunkedStateEventResponse : ChunkedStateEventResponse { + [JsonPropertyName("start")] + public string? Start { get; set; } + + [JsonPropertyName("end")] + public string? End { get; set; } +} + +public class BatchedChunkedStateEventResponse : ChunkedStateEventResponse { + [JsonPropertyName("next_batch")] + public string? NextBatch { get; set; } + + [JsonPropertyName("prev_batch")] + public string? PrevBatch { get; set; } +} + +public class RecursedBatchedChunkedStateEventResponse : BatchedChunkedStateEventResponse { + [JsonPropertyName("recursion_depth")] + public int? RecursionDepth { get; set; } +} + +#region Unused code + +/* +public class StateEventContentPolymorphicTypeInfoResolver : DefaultJsonTypeInfoResolver +{ + public override JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options) + { + JsonTypeInfo jsonTypeInfo = base.GetTypeInfo(type, options); + + Type baseType = typeof(EventContent); + if (jsonTypeInfo.Type == baseType) { + jsonTypeInfo.PolymorphismOptions = new JsonPolymorphismOptions { + TypeDiscriminatorPropertyName = "type", + IgnoreUnrecognizedTypeDiscriminators = true, + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType, + + DerivedTypes = StateEvent.KnownStateEventTypesByName.Select(x => new JsonDerivedType(x.Value, x.Key)).ToList() + + // DerivedTypes = new ClassCollector() + // .ResolveFromAllAccessibleAssemblies() + // .SelectMany(t => t.GetCustomAttributes() + // .Select(a => new JsonDerivedType(t, attr.EventName)); + + }; + } + + return jsonTypeInfo; + } +} +*/ + +#endregion \ No newline at end of file diff --git a/LibMatrix/MessagesResponse.cs b/LibMatrix/MessagesResponse.cs index 526da74..97a6c78 100644 --- a/LibMatrix/MessagesResponse.cs +++ b/LibMatrix/MessagesResponse.cs @@ -10,8 +10,8 @@ public class MessagesResponse { public string? End { get; set; } [JsonPropertyName("chunk")] - public List Chunk { get; set; } = new(); + public List Chunk { get; set; } = new(); [JsonPropertyName("state")] - public List State { get; set; } = new(); + public List State { get; set; } = new(); } \ No newline at end of file diff --git a/LibMatrix/Responses/CreateRoomRequest.cs b/LibMatrix/Responses/CreateRoomRequest.cs index 6f47183..f5218b9 100644 --- a/LibMatrix/Responses/CreateRoomRequest.cs +++ b/LibMatrix/Responses/CreateRoomRequest.cs @@ -29,7 +29,7 @@ public class CreateRoomRequest { // public string Preset { get; set; } = null!; [JsonPropertyName("initial_state")] - public List? InitialState { get; set; } + public List? InitialState { get; set; } /// /// One of: ["public", "private"] @@ -50,15 +50,15 @@ public class CreateRoomRequest { /// For use only when you can't use the CreationContent property /// - public StateEvent this[string eventType, string eventKey = ""] { + public LegacyMatrixEvent this[string eventType, string eventKey = ""] { get { var stateEvent = InitialState.FirstOrDefault(x => x.Type == eventType && x.StateKey == eventKey); if (stateEvent == null) - InitialState.Add(stateEvent = new StateEvent { + InitialState.Add(stateEvent = new LegacyMatrixEvent { Type = eventType, StateKey = eventKey, TypedContent = (EventContent)Activator.CreateInstance( - StateEvent.KnownStateEventTypes.FirstOrDefault(x => + LegacyMatrixEvent.KnownStateEventTypes.FirstOrDefault(x => x.GetCustomAttributes()? .Any(y => y.EventName == eventType) ?? false) ?? typeof(UnknownEventContent) )! @@ -118,7 +118,7 @@ public class CreateRoomRequest { } }, RoomAliasName = roomAliasName, - InitialState = new List() + InitialState = new List() }; return request; @@ -158,7 +158,7 @@ public class CreateRoomRequest { } }, RoomAliasName = roomAliasName, - InitialState = new List() + InitialState = new List() }; return request; diff --git a/LibMatrix/Responses/SyncResponse.cs b/LibMatrix/Responses/SyncResponse.cs index e4addb6..7a51afe 100644 --- a/LibMatrix/Responses/SyncResponse.cs +++ b/LibMatrix/Responses/SyncResponse.cs @@ -39,7 +39,7 @@ public class SyncResponse { // supporting classes public class PresenceDataStructure { [JsonPropertyName("events")] - public List Events { get; set; } = new(); + public List Events { get; set; } = new(); } public class RoomsDataStructure { @@ -85,13 +85,13 @@ public class SyncResponse { public class TimelineDataStructure { public TimelineDataStructure() { } - public TimelineDataStructure(List? events, bool? limited) { + public TimelineDataStructure(List? events, bool? limited) { Events = events; Limited = limited; } [JsonPropertyName("events")] - public List? Events { get; set; } + public List? Events { get; set; } [JsonPropertyName("prev_batch")] public string? PrevBatch { get; set; } diff --git a/LibMatrix/RoomTypes/GenericRoom.cs b/LibMatrix/RoomTypes/GenericRoom.cs index f15327c..5d85abd 100644 --- a/LibMatrix/RoomTypes/GenericRoom.cs +++ b/LibMatrix/RoomTypes/GenericRoom.cs @@ -32,13 +32,13 @@ public class GenericRoom { public string RoomId { get; set; } - public async IAsyncEnumerable GetFullStateAsync() { - var result = Homeserver.ClientHttpClient.GetAsyncEnumerableFromJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/state"); + public async IAsyncEnumerable GetFullStateAsync() { + var result = Homeserver.ClientHttpClient.GetAsyncEnumerableFromJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/state"); await foreach (var resp in result) yield return resp; } - public Task> GetFullStateAsListAsync() => - Homeserver.ClientHttpClient.GetFromJsonAsync>($"/_matrix/client/v3/rooms/{RoomId}/state"); + public Task> GetFullStateAsListAsync() => + Homeserver.ClientHttpClient.GetFromJsonAsync>($"/_matrix/client/v3/rooms/{RoomId}/state"); public async Task GetStateAsync(string type, string stateKey = "") { if (string.IsNullOrEmpty(type)) throw new ArgumentNullException(nameof(type), "Event type must be specified"); @@ -68,7 +68,7 @@ public class GenericRoom { } } - public async Task GetStateEventAsync(string type, string stateKey = "") { + public async Task GetStateEventAsync(string type, string stateKey = "") { if (string.IsNullOrEmpty(type)) throw new ArgumentNullException(nameof(type), "Event type must be specified"); var url = $"/_matrix/client/v3/rooms/{RoomId}/state/{type}"; if (!string.IsNullOrEmpty(stateKey)) url += $"/{stateKey}"; @@ -81,7 +81,7 @@ public class GenericRoom { ErrorCode = LibMatrixException.ErrorCodes.M_UNSUPPORTED }; // throw new InvalidDataException("Returned event type does not match requested type, or server does not support passing `format`."); - return resp.Deserialize(); + return resp.Deserialize(); } catch (MatrixException e) { // if (e is not { ErrorCodode: "M_NOT_FOUND" }) { @@ -132,7 +132,7 @@ public class GenericRoom { } } - public async Task GetStateEventOrNullAsync(string type, string stateKey = "") { + public async Task GetStateEventOrNullAsync(string type, string stateKey = "") { try { return await GetStateEventAsync(type, stateKey); } @@ -227,7 +227,7 @@ public class GenericRoom { return await res.Content.ReadFromJsonAsync() ?? throw new Exception("Failed to join room?"); } - public async IAsyncEnumerable GetMembersEnumerableAsync(bool joinedOnly = true) { + public async IAsyncEnumerable GetMembersEnumerableAsync(bool joinedOnly = true) { // var sw = Stopwatch.StartNew(); var res = await Homeserver.ClientHttpClient.GetAsync($"/_matrix/client/v3/rooms/{RoomId}/members"); // if (sw.ElapsedMilliseconds > 1000) @@ -251,7 +251,7 @@ public class GenericRoom { // Console.WriteLine($"Members call iterated in {sw.GetElapsedAndRestart()}"); } - public async Task> GetMembersListAsync(bool joinedOnly = true) { + public async Task> GetMembersListAsync(bool joinedOnly = true) { // var sw = Stopwatch.StartNew(); var res = await Homeserver.ClientHttpClient.GetAsync($"/_matrix/client/v3/rooms/{RoomId}/members"); // if (sw.ElapsedMilliseconds > 1000) @@ -265,7 +265,7 @@ public class GenericRoom { // if (sw.ElapsedMilliseconds > 100) // Console.WriteLine($"Members call deserialised in {sw.GetElapsedAndRestart()}"); // else sw.Restart(); - var members = new List(); + var members = new List(); foreach (var resp in result.Chunk) { if (resp?.Type != "m.room.member") continue; if (joinedOnly && resp.RawContent?["membership"]?.GetValue() != "join") continue; @@ -451,8 +451,8 @@ public class GenericRoom { } } - public Task GetEventAsync(string eventId) => - Homeserver.ClientHttpClient.GetFromJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/event/{eventId}"); + public Task GetEventAsync(string eventId) => + Homeserver.ClientHttpClient.GetFromJsonAsync($"/_matrix/client/v3/rooms/{RoomId}/event/{eventId}"); public async Task RedactEventAsync(string eventToRedact, string reason) { var data = new { reason }; @@ -516,7 +516,7 @@ public class GenericRoom { #endregion - public async IAsyncEnumerable GetRelatedEventsAsync(string eventId, string? relationType = null, string? eventType = null, string? dir = "f", + public async IAsyncEnumerable GetRelatedEventsAsync(string eventId, string? relationType = null, string? eventType = null, string? dir = "f", string? from = null, int? chunkLimit = 100, bool? recurse = null, string? to = null) { var path = $"/_matrix/client/v1/rooms/{RoomId}/relations/{HttpUtility.UrlEncode(eventId)}"; if (!string.IsNullOrEmpty(relationType)) path += $"/{relationType}"; diff --git a/LibMatrix/StateEvent.cs b/LibMatrix/StateEvent.cs deleted file mode 100644 index 81ee3fe..0000000 --- a/LibMatrix/StateEvent.cs +++ /dev/null @@ -1,257 +0,0 @@ -using System.Collections.Frozen; -using System.Diagnostics.CodeAnalysis; -using System.Reflection; -using System.Text.Json; -using System.Text.Json.Nodes; -using System.Text.Json.Serialization; -using ArcaneLibs; -using ArcaneLibs.Attributes; -using ArcaneLibs.Extensions; -using LibMatrix.EventTypes; -using LibMatrix.Extensions; - -namespace LibMatrix; - -public class StateEvent { - public static FrozenSet KnownStateEventTypes { get; } = new ClassCollector().ResolveFromAllAccessibleAssemblies().ToFrozenSet(); - - public static FrozenDictionary KnownStateEventTypesByName { get; } = KnownStateEventTypes.Aggregate( - new Dictionary(), - (dict, type) => { - var attrs = type.GetCustomAttributes(); - foreach (var attr in attrs) { - if (dict.TryGetValue(attr.EventName, out var existing)) - Console.WriteLine($"Duplicate event type '{attr.EventName}' registered for types '{existing.Name}' and '{type.Name}'"); - dict[attr.EventName] = type; - } - - return dict; - }).OrderBy(x => x.Key).ToFrozenDictionary(); - - public static Type GetStateEventType(string? type) => - string.IsNullOrWhiteSpace(type) ? typeof(UnknownEventContent) : KnownStateEventTypesByName.GetValueOrDefault(type) ?? typeof(UnknownEventContent); - - [JsonIgnore] - public Type MappedType => GetStateEventType(Type); - - [JsonIgnore] - public bool IsLegacyType => MappedType.GetCustomAttributes().FirstOrDefault(x => x.EventName == Type)?.Legacy ?? false; - - [JsonIgnore] - public string FriendlyTypeName => MappedType.GetFriendlyNameOrNull() ?? Type; - - [JsonIgnore] - public string FriendlyTypeNamePlural => MappedType.GetFriendlyNamePluralOrNull() ?? Type; - - private static readonly JsonSerializerOptions TypedContentSerializerOptions = new() { - Converters = { - new JsonFloatStringConverter(), - new JsonDoubleStringConverter(), - new JsonDecimalStringConverter() - } - }; - - [JsonIgnore] - [SuppressMessage("ReSharper", "PropertyCanBeMadeInitOnly.Global")] - public EventContent? TypedContent { - get { - // if (Type == "m.receipt") { - // return null; - // } - try { - var mappedType = GetStateEventType(Type); - if (mappedType == typeof(UnknownEventContent)) - Console.WriteLine($"Warning: unknown event type '{Type}'"); - var deserialisedContent = (EventContent)RawContent.Deserialize(mappedType, TypedContentSerializerOptions)!; - return deserialisedContent; - } - catch (JsonException e) { - Console.WriteLine(e); - Console.WriteLine("Content:\n" + (RawContent?.ToJson() ?? "null")); - } - - return null; - } - set { - if (value is null) - RawContent?.Clear(); - else - RawContent = JsonSerializer.Deserialize(JsonSerializer.Serialize(value, value.GetType(), - new JsonSerializerOptions() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull })); - } - } - - [JsonPropertyName("state_key")] - public string? StateKey { get; set; } - - [JsonPropertyName("type")] - public string Type { get; set; } - - [JsonPropertyName("replaces_state")] - public string? ReplacesState { get; set; } - - private JsonObject? _rawContent; - - [JsonPropertyName("content")] - public JsonObject? RawContent { - get => _rawContent; - set => _rawContent = value; - } - // - // [JsonIgnore] - // public new Type GetType { - // get { - // var type = GetStateEventType(Type); - // - // //special handling for some types - // // if (type == typeof(RoomEmotesEventContent)) { - // // RawContent["emote"] = RawContent["emote"]?.AsObject() ?? new JsonObject(); - // // } - // // - // // if (this is StateEventResponse stateEventResponse) { - // // if (type == null || type == typeof(object)) { - // // Console.WriteLine($"Warning: unknown event type '{Type}'!"); - // // Console.WriteLine(RawContent.ToJson()); - // // Directory.CreateDirectory($"unknown_state_events/{Type}"); - // // File.WriteAllText($"unknown_state_events/{Type}/{stateEventResponse.EventId}.json", - // // RawContent.ToJson()); - // // Console.WriteLine($"Saved to unknown_state_events/{Type}/{stateEventResponse.EventId}.json"); - // // } - // // else if (RawContent is not null && RawContent.FindExtraJsonObjectFields(type)) { - // // Directory.CreateDirectory($"unknown_state_events/{Type}"); - // // File.WriteAllText($"unknown_state_events/{Type}/{stateEventResponse.EventId}.json", - // // RawContent.ToJson()); - // // Console.WriteLine($"Saved to unknown_state_events/{Type}/{stateEventResponse.EventId}.json"); - // // } - // // } - // - // return type; - // } - // } - - //debug - [JsonIgnore] - public string InternalSelfTypeName { - get { - var res = GetType().Name switch { - "StateEvent`1" => "StateEvent", - _ => GetType().Name - }; - return res; - } - } - - [JsonIgnore] - public string InternalContentTypeName => TypedContent?.GetType().Name ?? "null"; -} - -public class StateEventResponse : StateEvent { - [JsonPropertyName("origin_server_ts")] - public long? OriginServerTs { get; set; } - - [JsonPropertyName("room_id")] - public string? RoomId { get; set; } - - [JsonPropertyName("sender")] - public string? Sender { get; set; } - - [JsonPropertyName("unsigned")] - public UnsignedData? Unsigned { get; set; } - - [JsonPropertyName("event_id")] - public string? EventId { get; set; } - - public class UnsignedData { - [JsonPropertyName("age")] - public ulong? Age { get; set; } - - [JsonPropertyName("redacted_because")] - public object? RedactedBecause { get; set; } - - [JsonPropertyName("transaction_id")] - public string? TransactionId { get; set; } - - [JsonPropertyName("replaces_state")] - public string? ReplacesState { get; set; } - - [JsonPropertyName("prev_sender")] - public string? PrevSender { get; set; } - - [JsonPropertyName("prev_content")] - public JsonObject? PrevContent { get; set; } - } -} - -[JsonSourceGenerationOptions(WriteIndented = true)] -[JsonSerializable(typeof(ChunkedStateEventResponse))] -internal partial class ChunkedStateEventResponseSerializerContext : JsonSerializerContext; - -public class EventList { - public EventList() { } - - public EventList(List? events) { - Events = events; - } - - [JsonPropertyName("events")] - public List? Events { get; set; } = new(); -} - -public class ChunkedStateEventResponse { - [JsonPropertyName("chunk")] - public List? Chunk { get; set; } = new(); -} - -public class PaginatedChunkedStateEventResponse : ChunkedStateEventResponse { - [JsonPropertyName("start")] - public string? Start { get; set; } - - [JsonPropertyName("end")] - public string? End { get; set; } -} - -public class BatchedChunkedStateEventResponse : ChunkedStateEventResponse { - [JsonPropertyName("next_batch")] - public string? NextBatch { get; set; } - - [JsonPropertyName("prev_batch")] - public string? PrevBatch { get; set; } -} - -public class RecursedBatchedChunkedStateEventResponse : BatchedChunkedStateEventResponse { - [JsonPropertyName("recursion_depth")] - public int? RecursionDepth { get; set; } -} - -#region Unused code - -/* -public class StateEventContentPolymorphicTypeInfoResolver : DefaultJsonTypeInfoResolver -{ - public override JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options) - { - JsonTypeInfo jsonTypeInfo = base.GetTypeInfo(type, options); - - Type baseType = typeof(EventContent); - if (jsonTypeInfo.Type == baseType) { - jsonTypeInfo.PolymorphismOptions = new JsonPolymorphismOptions { - TypeDiscriminatorPropertyName = "type", - IgnoreUnrecognizedTypeDiscriminators = true, - UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType, - - DerivedTypes = StateEvent.KnownStateEventTypesByName.Select(x => new JsonDerivedType(x.Value, x.Key)).ToList() - - // DerivedTypes = new ClassCollector() - // .ResolveFromAllAccessibleAssemblies() - // .SelectMany(t => t.GetCustomAttributes() - // .Select(a => new JsonDerivedType(t, attr.EventName)); - - }; - } - - return jsonTypeInfo; - } -} -*/ - -#endregion \ No newline at end of file -- cgit 1.4.1