about summary refs log tree commit diff
path: root/MatrixRoomUtils.Web/Pages/PolicyListRoomList.razor
blob: 9be8314666a648b298c1b32eb7b8da6ea901854f (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
136
137
@page "/PolicyListEditor"
@using MatrixRoomUtils.Authentication
@using MatrixRoomUtils.Web.Classes
@using Blazored.LocalStorage
@using System.Net.Http.Headers
@using System.Text.Json
@using System.Xml.Schema
@using MatrixRoomUtils.Extensions
@using MatrixRoomUtils.StateEventTypes
@inject ILocalStorageService LocalStorage
@inject NavigationManager NavigationManager
<h3>Policy list editor</h3>

<h5>Room list</h5>
<hr/>
@if (PolicyRoomList.Count == 0)
{
    <p>No policy rooms found.</p>
    <p>Loading progress: @checkedRoomCount/@totalRoomCount</p>
}
else
{
    @if (checkedRoomCount != totalRoomCount)
    {
        <p>Loading progress: @checkedRoomCount/@totalRoomCount</p>
    }
    foreach (var s in PolicyRoomList)
    {
        <a href="@(NavigationManager.Uri + "/" + s.RoomId.Replace('.', '~'))">@s.Name</a>
        <br/>
    }
    <div style="margin-bottom: 4em;"></div>
}

<LogView></LogView>

@code {
    //get room list
    // - sync withroom list filter
    // type = support.feline.msc3784
    //support.feline.policy.lists.msc.v1

    public List<PolicyRoomInfo> PolicyRoomList { get; set; } = new();

    private int checkedRoomCount { get; set; } = 0;
    private int totalRoomCount { get; set; } = 0;

    protected override async Task OnInitializedAsync()
    {
        if (!RuntimeStorage.WasLoaded) await RuntimeStorage.LoadFromLocalStorage(LocalStorage);
        await base.OnInitializedAsync();
        if (RuntimeStorage.AccessToken == null || RuntimeStorage.CurrentHomeserver == null)
        {
            NavigationManager.NavigateTo("/Login");
            return;
        }
        await EnumeratePolicyRooms();
        Console.WriteLine("Policy list editor initialized!");
    }

    private async Task EnumeratePolicyRooms()
    {
        using HttpClient wc = new();
        wc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", RuntimeStorage.AccessToken);

    //get room list
    //temporary hack until rooms get enumerated...
        string[] rooms = { "!fTjMjIzNKEsFlUIiru:neko.dev" };
        var _rooms = await wc.GetAsync($"{RuntimeStorage.CurrentHomeserver}/_matrix/client/v3/joined_rooms");
        Console.WriteLine($"Got {_rooms.StatusCode}...");
        if (!_rooms.IsSuccessStatusCode)
        {
            Console.WriteLine($"Failed to get rooms: {await _rooms.Content.ReadAsStringAsync()}");
            return;
        }
        var _rooms_o = await _rooms.Content.ReadFromJsonAsync<JsonElement>();
        if (_rooms_o.TryGetProperty("joined_rooms", out JsonElement _rooms_j))
        {
            rooms = _rooms_j.EnumerateArray().Select(x => x.GetString()).ToArray();
        }

        totalRoomCount = rooms.Length;
        StateHasChanged();

        var semaphore = new SemaphoreSlim(128);
        var tasks = new List<Task<PolicyRoomInfo?>>();
        foreach (string room in rooms)
        {
            tasks.Add(GetPolicyRoomInfo(room, semaphore));
        }
        var results = await Task.WhenAll(tasks);
        PolicyRoomList.AddRange(results.Where(x => x != null).Select(x=>x.Value));
        

    //print to console
        Console.WriteLine($"Detected policy lists: {PolicyRoomList.ToJson()}");
    }

    private async Task<PolicyRoomInfo?> GetPolicyRoomInfo(string room, SemaphoreSlim semaphore)
    {
        try
        {
            await semaphore.WaitAsync();
            using HttpClient wc = new();
            wc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", RuntimeStorage.AccessToken);
            var sk = await wc.GetAsync($"{RuntimeStorage.CurrentHomeserver}/_matrix/client/v3/rooms/{room}/state/org.matrix.mjolnir.shortcode");
            if (sk.IsSuccessStatusCode)
            {
                var sko = await sk.Content.ReadFromJsonAsync<JsonElement>();
                if (sko.TryGetProperty("shortcode", out JsonElement shortcode))
                {
                    Console.WriteLine($"Room {room} has a shortcode: {shortcode.GetString()}!");
                    return new PolicyRoomInfo() { Name = room, Shortcode = shortcode.GetString(), RoomId = room };
                }
                else Console.WriteLine("No record found...");
            }
            else if (sk.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
            }
            else Console.WriteLine($"Got failure while checking {room}: {sk.StatusCode} ({await sk.Content.ReadAsStringAsync()})...");
            return null;
        }
        finally
        {
            checkedRoomCount++;
            StateHasChanged();
            semaphore.Release();
        }
    }
    
    public struct PolicyRoomInfo
    {
        public string RoomId { get; set; }
        public string Shortcode { get; set; }
        public string Name { get; set; }
    }
}