1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
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<Type> KnownStateEventTypes { get; } = new ClassCollector<EventContent>().ResolveFromAllAccessibleAssemblies().ToFrozenSet();
public static FrozenDictionary<string, Type> KnownStateEventTypesByName { get; } = KnownStateEventTypes.Aggregate(
new Dictionary<string, Type>(),
(dict, type) => {
var attrs = type.GetCustomAttributes<MatrixEventAttribute>();
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<MatrixEventAttribute>().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<JsonObject>(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<LegacyMatrixEventResponse>? events) {
Events = events;
}
[JsonPropertyName("events")]
public List<LegacyMatrixEventResponse>? Events { get; set; } = new();
}
public class ChunkedStateEventResponse {
[JsonPropertyName("chunk")]
public List<LegacyMatrixEventResponse>? 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<EventContent>()
// .ResolveFromAllAccessibleAssemblies()
// .SelectMany(t => t.GetCustomAttributes<MatrixEventAttribute>()
// .Select(a => new JsonDerivedType(t, attr.EventName));
};
}
return jsonTypeInfo;
}
}
*/
#endregion
|