about summary refs log tree commit diff
path: root/MatrixRoomUtils.Core/StateEvent.cs
blob: 6321fb6ed82b3ee5034d9c0ccb79402ca2ba85ff (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
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 StateEvent<T> As<T>() where T : class
    {
        return (StateEvent<T>)this;
    }

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

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