about summary refs log tree commit diff
path: root/MatrixRoomUtils.Core/StateEvent.cs
blob: cb8f0b48b75354001be4b61371cf71e4cecdd05c (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
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using MatrixRoomUtils.Core.Extensions;
using MatrixRoomUtils.Core.Interfaces;

namespace MatrixRoomUtils.Core;

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

    public object TypedContent {
        get => RawContent.Deserialize(GetType)!;
        set => RawContent = JsonSerializer.Deserialize<JsonObject>(JsonSerializer.Serialize(value));
    }

    [JsonPropertyName("state_key")]
    public string StateKey { get; set; } = "";

    [JsonPropertyName("type")]
    public string Type { get; set; }

    [JsonPropertyName("replaces_state")]
    public string? ReplacesState { get; set; }

    [JsonPropertyName("content")]
    public JsonObject? RawContent { get; set; }

    public T1 GetContent<T1>() where T1 : IStateEventType {
        return RawContent.Deserialize<T1>();
    }

    [JsonIgnore]
    public Type GetType {
        get {
            var type = StateEvent.KnownStateEventTypes.FirstOrDefault(x =>
                x.GetCustomAttribute<MatrixEventAttribute>()?.EventName == Type);
            if (type == null) {
                Console.WriteLine($"Warning: unknown event type '{Type}'!");
                Console.WriteLine(RawContent.ToJson());
                return typeof(object);
            }

            RawContent.FindExtraJsonObjectFields(type);
            
            return type;
        }
    }

    //debug
    public string dtype {
        get {
            var res = GetType().Name switch {
                "StateEvent`1" => $"StateEvent",
                _ => GetType().Name
            };
            return res;
        }
    }

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