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

namespace MatrixRoomUtils.Core;

public class StateEvent {
    [JsonPropertyName("content")]
    public dynamic Content { get; set; } = new { };

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

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

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

    //extra properties
    [JsonIgnore]
    public JsonNode ContentAsJsonNode {
        get => JsonSerializer.SerializeToNode(Content);
        set => Content = value;
    }

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

    public StateEvent<T> As<T>() where T : class => (StateEvent<T>)this;
}

public class StateEvent<T> : StateEvent where T : class {
    public StateEvent() {
        //import base content if not an empty object
        if (base.Content.GetType() == typeof(T)) {
            Console.WriteLine($"StateEvent<{typeof(T)}> created with base content of type {base.Content.GetType()}. Importing base content.");
            Content = base.Content;
        }
    }

    [JsonPropertyName("content")]
    public new T Content { get; set; }
}