about summary refs log tree commit diff
path: root/ModerationClient/ViewModels/ClientViewModel.cs
blob: 1e287ecaf2969362bd05e9e04819cce2d0e9c6bc (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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ArcaneLibs.Collections;
using LibMatrix.EventTypes.Spec.State;
using LibMatrix.Helpers;
using LibMatrix.Responses;
using MatrixUtils.Abstractions;
using Microsoft.Extensions.Logging;
using ModerationClient.Services;

namespace ModerationClient.ViewModels;

public partial class ClientViewModel : ViewModelBase {
    public ClientViewModel(ILogger<ClientViewModel> logger, MatrixAuthenticationService authService, CommandLineConfiguration cfg) {
        _logger = logger;
        _authService = authService;
        _cfg = cfg;
        DisplayedSpaces.Add(_allRoomsNode = new AllRoomsSpaceNode(this));
        _ = Task.Run(Run);
    }

    private readonly ILogger<ClientViewModel> _logger;
    private readonly MatrixAuthenticationService _authService;
    private readonly CommandLineConfiguration _cfg;
    private SpaceNode? _currentSpace;
    private readonly SpaceNode _allRoomsNode;
    public ObservableCollection<SpaceNode> DisplayedSpaces { get; } = [];
    public ObservableDictionary<string, RoomNode> AllRooms { get; } = new();

    public SpaceNode CurrentSpace {
        get => _currentSpace ?? _allRoomsNode;
        set => SetProperty(ref _currentSpace, value);
    }

    public async Task Run() {
        var sh = new SyncStateResolver(_authService.Homeserver, _logger, storageProvider: new FileStorageProvider(Path.Combine(_cfg.ProfileDirectory, "syncCache")));
        // var res = await sh.SyncAsync();
        //await sh.OptimiseStore();
        while (true) {
            var res = await sh.ContinueAsync();
            await ApplySpaceChanges(res.next);
            //OnPropertyChanged(nameof(CurrentSpace));
            //OnPropertyChanged(nameof(CurrentSpace.ChildRooms));
            // Console.WriteLine($"mow A={AllRooms.Count}|D={DisplayedSpaces.Count}");
            // for (int i = 0; i < GC.MaxGeneration; i++) {
            // GC.Collect(i, GCCollectionMode.Forced, blocking: true);
            // GC.WaitForPendingFinalizers();
            // }
        }
    }

    private async Task ApplySpaceChanges(SyncResponse newSync) {
        List<Task> tasks = [];
        foreach (var room in newSync.Rooms?.Join ?? []) {
            if (!AllRooms.ContainsKey(room.Key)) {
                AllRooms.Add(room.Key, new RoomNode { Name = "Loading..." });
            }

            if (room.Value.State?.Events is not null) {
                var nameEvent = room.Value.State!.Events!.FirstOrDefault(x => x.Type == "m.room.name" && x.StateKey == "");
                AllRooms[room.Key].Name = (nameEvent?.TypedContent as RoomNameEventContent)?.Name ?? "";
                if (string.IsNullOrWhiteSpace(AllRooms[room.Key].Name)) {
                    AllRooms[room.Key].Name = "Loading...";
                    tasks.Add(_authService.Homeserver!.GetRoom(room.Key).GetNameOrFallbackAsync().ContinueWith(r => AllRooms[room.Key].Name = r.Result));
                }
            }
        }
        
        // await Task.WhenAll(tasks);

        return;

        List<string> handledRoomIds = [];
        var spaces = newSync.Rooms?.Join?
            .Where(x => x.Value.State?.Events is not null)
            .Where(x => x.Value.State!.Events!.Any(y => y.Type == "m.room.create" && (y.TypedContent as RoomCreateEventContent)!.Type == "m.space"))
            .ToList();
        Console.WriteLine("spaces: " + spaces.Count);
        var nonRootSpaces = spaces
            .Where(x => spaces.Any(x => x.Value.State!.Events!.Any(y => y.Type == "m.space.child" && y.StateKey == x.Key)))
            .ToDictionary();

        var rootSpaces = spaces
            .Where(x => !nonRootSpaces.ContainsKey(x.Key))
            .ToDictionary();
        // var rootSpaces = spaces
        // .Where(x=>!spaces.Any(x=>x.Value.State!.Events!.Any(y=>y.Type == "m.space.child" && y.StateKey == x.Key)))
        // .ToList();

        foreach (var (roomId, room) in rootSpaces) {
            var space = new SpaceNode { Name = (room.State!.Events!.First(x => x.Type == "m.room.name")!.TypedContent as RoomNameEventContent).Name };
            DisplayedSpaces.Add(space);
            handledRoomIds.Add(roomId);
        }
    }
}

public class SpaceNode : RoomNode {
    public ObservableCollection<SpaceNode> ChildSpaces { get; set; } = [];
    public ObservableCollection<RoomNode> ChildRooms { get; set; } = [];
}

public class RoomNode {
    public string Name { get; set; }
}

// implementation details
public class AllRoomsSpaceNode : SpaceNode {
    public AllRoomsSpaceNode(ClientViewModel vm) {
        Name = "All rooms";
        vm.AllRooms.CollectionChanged += (_, args) => {
            switch (args.Action) {
                case NotifyCollectionChangedAction.Add:
                case NotifyCollectionChangedAction.Remove:
                case NotifyCollectionChangedAction.Replace: {
                    foreach (var room in args.NewItems?.Cast<KeyValuePair<string, RoomNode>>() ?? []) ChildRooms.Add(room.Value);
                    foreach (var room in args.OldItems?.Cast<KeyValuePair<string, RoomNode>>() ?? []) ChildRooms.Remove(room.Value);
                    break;
                }

                case NotifyCollectionChangedAction.Reset: {
                    ChildSpaces.Clear();
                    ChildRooms.Clear();
                    break;
                }
            }
        };
    }
}