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

namespace MatrixRoomUtils.Core.Extensions;

public static class IEnumerableExtensions {
    public static List<StateEventResponse> DeserializeMatrixTypes(this List<JsonElement> stateEvents) {
        return stateEvents.Select(DeserializeMatrixType).ToList();
    }
    
    public static StateEventResponse DeserializeMatrixType(this JsonElement stateEvent) {
        var type = stateEvent.GetProperty("type").GetString();
        var knownType = StateEvent.KnownStateEventTypes.FirstOrDefault(x => x.GetCustomAttribute<MatrixEventAttribute>()?.EventName == type);
        if (knownType == null) {
            Console.WriteLine($"Warning: unknown event type '{type}'!");
            return new StateEventResponse();
        }
        
        var eventInstance = Activator.CreateInstance(typeof(StateEventResponse).MakeGenericType(knownType))!;
        stateEvent.Deserialize(eventInstance.GetType());
        
        return (StateEventResponse) eventInstance;
    }

    public static void Replace(this List<StateEvent> stateEvents, StateEvent old, StateEvent @new) {
        var index = stateEvents.IndexOf(old);
        if (index == -1) return;
        stateEvents[index] = @new;
    }
}

public class MatrixEventAttribute : Attribute {
    public string EventName { get; set; }
}