about summary refs log tree commit diff
path: root/LibMatrix/StateEvent.cs
blob: b42bd641137cc65a6ac613b37599473357ecb4dc (plain) (blame)
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
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using ArcaneLibs;
using ArcaneLibs.Extensions;
using LibMatrix.EventTypes;
using LibMatrix.Helpers;
using LibMatrix.Interfaces;

namespace LibMatrix;

public class StateEvent {
    public static List<Type> KnownStateEventTypes { get; } = new ClassCollector<EventContent>().ResolveFromAllAccessibleAssemblies();

    public static readonly Dictionary<string, Type> KnownStateEventTypesByName = KnownStateEventTypes.Aggregate(
        new Dictionary<string, Type>(),
        (dict, type) => {
            var attrs = type.GetCustomAttributes<MatrixEventAttribute>();
            foreach (var attr in attrs) {
                dict[attr.EventName] = type;
            }

            return dict;
        });

    public static Type GetStateEventType(string type) {
        if (type == "m.receipt") {
            return typeof(Dictionary<string, JsonObject>);
        }

        // var eventType = KnownStateEventTypes.FirstOrDefault(x =>
        // x.GetCustomAttributes<MatrixEventAttribute>()?.Any(y => y.EventName == type) ?? false);
        var eventType = KnownStateEventTypesByName.GetValueOrDefault(type);

        return eventType ?? typeof(UnknownEventContent);
    }

    public EventContent TypedContent {
        get {
            try {
                return (EventContent) RawContent.Deserialize(GetType)!;
            }
            catch (JsonException e) {
                Console.WriteLine(e);
                Console.WriteLine("Content:\n" + (RawContent?.ToJson() ?? "null"));
            }

            return null;
        }
        set => RawContent = JsonSerializer.Deserialize<JsonObject>(JsonSerializer.Serialize(value, value.GetType()));
    }

    [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;
            // if (Type is not null && this is StateEventResponse stateEventResponse) {
            //     if (File.Exists($"unknown_state_events/{Type}/{stateEventResponse.EventId}.json")) return;
            //     var x = GetType.Name;
            // }
        }
    }

    [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 dtype {
        get {
            var res = GetType().Name switch {
                "StateEvent`1" => "StateEvent",
                _ => GetType().Name
            };
            return res;
        }
    }

    [JsonIgnore]
    public string cdtype => TypedContent.GetType().Name;
}

/*
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;
    }
}
*/