From 712ad189c99570f686ab779782b2a873e172428e Mon Sep 17 00:00:00 2001 From: TheArcaneBrony Date: Tue, 13 Jun 2023 20:25:05 +0200 Subject: Change syntax style --- MatrixRoomUtils.Web/Pages/About.razor | 17 ++-- MatrixRoomUtils.Web/Pages/DataExportPage.razor | 31 ++---- MatrixRoomUtils.Web/Pages/DebugTools.razor | 48 ++++----- MatrixRoomUtils.Web/Pages/DevOptions.razor | 44 ++++---- MatrixRoomUtils.Web/Pages/HSAdmin/HSAdmin.razor | 6 +- MatrixRoomUtils.Web/Pages/HSAdmin/RoomQuery.razor | 71 +++++++------ MatrixRoomUtils.Web/Pages/Index.razor | 9 +- .../Pages/KnownHomeserverList.razor | 84 ++++++--------- MatrixRoomUtils.Web/Pages/LoginPage.razor | 30 ++---- MatrixRoomUtils.Web/Pages/MediaLocator.razor | 69 +++++-------- .../Pages/PolicyList/PolicyListEditorPage.razor | 113 +++++++++------------ .../Pages/PolicyList/PolicyListRoomList.razor | 68 +++++-------- .../Pages/RoomManager/RoomManager.razor | 50 ++++----- .../Pages/RoomManager/RoomManagerCreateRoom.razor | 96 ++++++----------- .../Pages/RoomManager/RoomManagerSpace.razor | 69 ++++++------- .../Pages/RoomManager/RoomManagerTimeline.razor | 16 +-- .../Pages/RoomState/RoomStateEditorPage.razor | 62 ++++------- .../Pages/RoomState/RoomStateRoomList.razor | 25 +++-- .../Pages/RoomState/RoomStateViewerPage.razor | 59 ++++------- 19 files changed, 378 insertions(+), 589 deletions(-) (limited to 'MatrixRoomUtils.Web/Pages') diff --git a/MatrixRoomUtils.Web/Pages/About.razor b/MatrixRoomUtils.Web/Pages/About.razor index d47e60b..cf43c4f 100644 --- a/MatrixRoomUtils.Web/Pages/About.razor +++ b/MatrixRoomUtils.Web/Pages/About.razor @@ -13,26 +13,23 @@

You can find the source code on my git server.

You can also join the Matrix room for this project.

-@if (showBinDownload) -{ +@if (showBinDownload) {

This deployment also serves a copy of the compiled, hosting-ready binaries at /MRU-BIN.tar.xz!

} -@if (showSrcDownload) -{ +@if (showSrcDownload) {

This deployment also serves a copy of the compiled, hosting-ready binaries at /MRU-SRC.tar.xz!

} @code { - private bool showBinDownload { get; set; } = false; - private bool showSrcDownload { get; set; } = false; + private bool showBinDownload { get; set; } + private bool showSrcDownload { get; set; } - protected override async Task OnInitializedAsync() - { + protected override async Task OnInitializedAsync() { using var hc = new HttpClient(); - var hr = await hc.SendAsync(new(HttpMethod.Head, NavigationManager.ToAbsoluteUri("/MRU-BIN.tar.xz").AbsoluteUri)); + var hr = await hc.SendAsync(new HttpRequestMessage(HttpMethod.Head, NavigationManager.ToAbsoluteUri("/MRU-BIN.tar.xz").AbsoluteUri)); showBinDownload = hr.StatusCode == HttpStatusCode.OK; - hr = await hc.SendAsync(new(HttpMethod.Head, NavigationManager.ToAbsoluteUri("/MRU-SRC.tar.xz").AbsoluteUri)); + hr = await hc.SendAsync(new HttpRequestMessage(HttpMethod.Head, NavigationManager.ToAbsoluteUri("/MRU-SRC.tar.xz").AbsoluteUri)); showSrcDownload = hr.StatusCode == HttpStatusCode.OK; await base.OnInitializedAsync(); } diff --git a/MatrixRoomUtils.Web/Pages/DataExportPage.razor b/MatrixRoomUtils.Web/Pages/DataExportPage.razor index 49fb700..732cd74 100644 --- a/MatrixRoomUtils.Web/Pages/DataExportPage.razor +++ b/MatrixRoomUtils.Web/Pages/DataExportPage.razor @@ -1,5 +1,4 @@ @page "/Export" -@using MatrixRoomUtils.Web.Shared.IndexComponents @using System.Text.Json @inject NavigationManager NavigationManager @inject ILocalStorageService LocalStorage @@ -11,12 +10,10 @@

Signed in accounts - Add new account or Import from TSV

-@if (_isLoaded) -{ -@foreach (var (token, user) in RuntimeCache.LoginSessions) -{ +@if (_isLoaded) { + @foreach (var (token, user) in RuntimeCache.LoginSessions) { @* *@ -
+        
 @user.LoginResponse.UserId[1..].Split(":")[0]\auth\access_token=@token
 @user.LoginResponse.UserId[1..].Split(":")[0]\auth\device_id=@user.LoginResponse.DeviceId
 @user.LoginResponse.UserId[1..].Split(":")[0]\auth\home_server=@(RuntimeCache.HomeserverResolutionCache.ContainsKey(user.LoginResponse.HomeServer) ? RuntimeCache.HomeserverResolutionCache[user.LoginResponse.HomeServer].Result : "loading...")
@@ -26,10 +23,9 @@
 @user.LoginResponse.UserId[1..].Split(":")[0]\user\online_key_backup=true
 @user.LoginResponse.UserId[1..].Split(":")[0]\user\only_share_keys_with_verified_users=false
     
+ } } -} -else -{ +else {

Loading...

@resolvedHomeservers/@totalHomeservers homeservers resolved...

} @@ -39,31 +35,26 @@ else private int resolvedHomeservers; private int totalHomeservers; - protected override async Task OnInitializedAsync() - { + protected override async Task OnInitializedAsync() { await base.OnInitializedAsync(); - if (!RuntimeCache.WasLoaded) - { + if (!RuntimeCache.WasLoaded) { await LocalStorageWrapper.LoadFromLocalStorage(LocalStorage); } var homeservers = RuntimeCache.LoginSessions.Values.Select(x => x.LoginResponse.HomeServer).Distinct(); totalHomeservers = homeservers.Count(); StateHasChanged(); - foreach (var hs in homeservers) - { - if (RuntimeCache.HomeserverResolutionCache.ContainsKey(hs)) - { + foreach (var hs in homeservers) { + if (RuntimeCache.HomeserverResolutionCache.ContainsKey(hs)) { resolvedHomeservers++; continue; } var resolvedHomeserver = (await new RemoteHomeServer(hs).Configure()).FullHomeServerDomain; - RuntimeCache.HomeserverResolutionCache.Add(hs, new() { Result = resolvedHomeserver, ResolutionTime = DateTime.Now }); + RuntimeCache.HomeserverResolutionCache.Add(hs, new HomeServerResolutionResult { Result = resolvedHomeserver, ResolutionTime = DateTime.Now }); await LocalStorageWrapper.SaveCacheToLocalStorage(LocalStorage); Console.WriteLine("Saved to local storage:"); - Console.WriteLine(JsonSerializer.Serialize(RuntimeCache.HomeserverResolutionCache, new JsonSerializerOptions() - { + Console.WriteLine(JsonSerializer.Serialize(RuntimeCache.HomeserverResolutionCache, new JsonSerializerOptions { WriteIndented = true })); resolvedHomeservers++; diff --git a/MatrixRoomUtils.Web/Pages/DebugTools.razor b/MatrixRoomUtils.Web/Pages/DebugTools.razor index c8fabaa..da5c172 100644 --- a/MatrixRoomUtils.Web/Pages/DebugTools.razor +++ b/MatrixRoomUtils.Web/Pages/DebugTools.razor @@ -1,26 +1,24 @@ @page "/Debug" -@using MatrixRoomUtils.Core.Interfaces -@using MatrixRoomUtils.Core.Extensions @using System.Reflection +@using MatrixRoomUtils.Core.Extensions +@using MatrixRoomUtils.Core.Interfaces @inject ILocalStorageService LocalStorage @inject NavigationManager NavigationManager

Debug Tools


-@if (Rooms.Count == 0) -{ +@if (Rooms.Count == 0) {

You are not in any rooms!

@*

Loading progress: @checkedRoomCount/@totalRoomCount

*@ } -else -{ +else {
Room List - @foreach (var room in Rooms) - { - + @foreach (var room in Rooms) { + + + }
- }
@@ -38,50 +36,44 @@ else @code { public List Rooms { get; set; } = new(); - protected override async Task OnInitializedAsync() - { + + protected override async Task OnInitializedAsync() { await LocalStorageWrapper.LoadFromLocalStorage(LocalStorage); await base.OnInitializedAsync(); - if (RuntimeCache.CurrentHomeServer == null) - { + if (RuntimeCache.CurrentHomeServer == null) { NavigationManager.NavigateTo("/Login"); return; } - Rooms = (await RuntimeCache.CurrentHomeServer.GetJoinedRooms()).Select(x=>x.RoomId).ToList(); + Rooms = (await RuntimeCache.CurrentHomeServer.GetJoinedRooms()).Select(x => x.RoomId).ToList(); Console.WriteLine("Fetched joined rooms!"); } - //send req string get_request_url { get; set; } = ""; string get_request_result { get; set; } = ""; - private async Task SendGetRequest() - { + + private async Task SendGetRequest() { var field = typeof(IHomeServer).GetRuntimeFields().First(x => x.ToString().Contains("<_httpClient>k__BackingField")); var httpClient = field.GetValue(RuntimeCache.CurrentHomeServer) as HttpClient; - try - { + try { var res = await httpClient.GetAsync(get_request_url); - if (res.IsSuccessStatusCode) - { - if(res.Content.Headers.ContentType.MediaType == "application/json") + if (res.IsSuccessStatusCode) { + if (res.Content.Headers.ContentType.MediaType == "application/json") get_request_result = (await res.Content.ReadFromJsonAsync()).ToJson(); else get_request_result = await res.Content.ReadAsStringAsync(); StateHasChanged(); return; } - if(res.Content.Headers.ContentType.MediaType == "application/json") + if (res.Content.Headers.ContentType.MediaType == "application/json") get_request_result = $"Error: {res.StatusCode}\n" + (await res.Content.ReadFromJsonAsync()).ToJson(); else get_request_result = $"Error: {res.StatusCode}\n" + await res.Content.ReadAsStringAsync(); - } - catch (Exception e) - { + catch (Exception e) { get_request_result = $"Error: {e}"; } StateHasChanged(); } -} \ No newline at end of file +} \ No newline at end of file diff --git a/MatrixRoomUtils.Web/Pages/DevOptions.razor b/MatrixRoomUtils.Web/Pages/DevOptions.razor index 3ca86b4..0843d5f 100644 --- a/MatrixRoomUtils.Web/Pages/DevOptions.razor +++ b/MatrixRoomUtils.Web/Pages/DevOptions.razor @@ -19,15 +19,13 @@ View caches

Generic cache:

    - @foreach (var item in RuntimeCache.GenericResponseCache) - { + @foreach (var item in RuntimeCache.GenericResponseCache) {
  • @item.Key: @item.Value.Cache.Count entries
    - @if (item.Value.Cache.Count > 0) - { + @if (item.Value.Cache.Count > 0) {

    Earliest expiry: @(item.Value.Cache.Min(x => x.Value.ExpiryTime)) (@string.Format("{0:g}", item.Value.Cache.Min(x => x.Value.ExpiryTime).Value.Subtract(DateTime.Now)) from now)

    @*

    Average expiry: @(item.Value.Cache.Average(x => x.Value.ExpiryTime.Value))(@item.Value.Cache.Average(x => x.Value.ExpiryTime).Value.Subtract(DateTime.Now) from now)

    *@ -

    Last expiry: @(item.Value.Cache.Max(x => x.Value.ExpiryTime)) (@string.Format("{0:g}", item.Value.Cache.Max(x => x.Value.ExpiryTime).Value.Subtract(DateTime.Now)) from now)

    +

    Last expiry: @(item.Value.Cache.Max(x => x.Value.ExpiryTime)) (@string.Format("{0:g}", item.Value.Cache.Max(x => x.Value.ExpiryTime).Value.Subtract(DateTime.Now)) from now)

    }
  • } @@ -35,50 +33,42 @@ @code { - protected override async Task OnInitializedAsync() - { + + protected override async Task OnInitializedAsync() { await LocalStorageWrapper.LoadFromLocalStorage(LocalStorage); await base.OnInitializedAsync(); - Task.Run(async () => - { - while (true) - { + Task.Run(async () => { + while (true) { await Task.Delay(1000); StateHasChanged(); } }); } - protected async Task LogStuff() - { + protected async Task LogStuff() { await Task.Delay(100); Console.WriteLine($"Settings: {LocalStorageWrapper.Settings.ToJson()}"); - + await LocalStorageWrapper.SaveToLocalStorage(LocalStorage); } - protected async Task DropCaches() - { - foreach (var (key, value) in RuntimeCache.GenericResponseCache) - { + protected async Task DropCaches() { + foreach (var (key, value) in RuntimeCache.GenericResponseCache) { value.Cache.Clear(); } - - //RuntimeCache.GenericResponseCache.Clear(); + + //RuntimeCache.GenericResponseCache.Clear(); RuntimeCache.HomeserverResolutionCache.Clear(); await LocalStorageWrapper.SaveCacheToLocalStorage(LocalStorage); } - protected async Task RandomiseCacheTimers() - { - foreach (var keyValuePair in RuntimeCache.GenericResponseCache) - { + protected async Task RandomiseCacheTimers() { + foreach (var keyValuePair in RuntimeCache.GenericResponseCache) { Console.WriteLine($"Randomising cache timer for {keyValuePair.Key}"); - foreach (var cacheItem in keyValuePair.Value.Cache) - { + foreach (var cacheItem in keyValuePair.Value.Cache) { cacheItem.Value.ExpiryTime = DateTime.Now.AddSeconds(Random.Shared.Next(15, 120)); } - + await LocalStorageWrapper.SaveCacheToLocalStorage(LocalStorage); } } diff --git a/MatrixRoomUtils.Web/Pages/HSAdmin/HSAdmin.razor b/MatrixRoomUtils.Web/Pages/HSAdmin/HSAdmin.razor index b77012b..f972236 100644 --- a/MatrixRoomUtils.Web/Pages/HSAdmin/HSAdmin.razor +++ b/MatrixRoomUtils.Web/Pages/HSAdmin/HSAdmin.razor @@ -2,6 +2,10 @@

    Homeserver Admininistration


    +

    Synapse tools

    +
    +Query rooms + @code { - + } \ No newline at end of file diff --git a/MatrixRoomUtils.Web/Pages/HSAdmin/RoomQuery.razor b/MatrixRoomUtils.Web/Pages/HSAdmin/RoomQuery.razor index 109ad7d..e6f95c7 100644 --- a/MatrixRoomUtils.Web/Pages/HSAdmin/RoomQuery.razor +++ b/MatrixRoomUtils.Web/Pages/HSAdmin/RoomQuery.razor @@ -1,73 +1,78 @@ -@page "/RoomQuery" +@page "/HSAdmin/RoomQuery" @using MatrixRoomUtils.Core.Extensions -@using System.Runtime.InteropServices -@using System.ComponentModel @using MatrixRoomUtils.Core.Responses.Admin

    Homeserver Administration - Room Query

    -
    +
    -
    +

    -
    +

    -@foreach (var res in Results) -{ +@foreach (var res in Results) {
    - -

    @res.CanonicalAlias, created by

    + +

    + @res.CanonicalAlias + @if (!string.IsNullOrWhiteSpace(res.Creator)) { + + , created by + + } +

    @res.StateEvents state events

    @res.JoinedMembers members, of which @res.JoinedLocalMembers are on this server

    } @code { - - [Parameter, SupplyParameterFromQuery(Name = "order_by")] + + [Parameter] + [SupplyParameterFromQuery(Name = "order_by")] public string? OrderBy { get; set; } - - [Parameter, SupplyParameterFromQuery(Name = "search_term")] + + [Parameter] + [SupplyParameterFromQuery(Name = "search_term")] public string SearchTerm { get; set; } - - [Parameter, SupplyParameterFromQuery(Name = "content_search_term")] + + [Parameter] + [SupplyParameterFromQuery(Name = "content_search_term")] public string ContentSearchTerm { get; set; } - - [Parameter, SupplyParameterFromQuery(Name = "ascending")] + + [Parameter] + [SupplyParameterFromQuery(Name = "ascending")] public bool Ascending { get; set; } public List Results { get; set; } = new(); - - protected override async Task OnParametersSetAsync() - { - if(Ascending == null) + + private string Status { get; set; } + + protected override async Task OnParametersSetAsync() { + if (Ascending == null) Ascending = true; OrderBy ??= "name"; } - - private async Task Search() - { + + private async Task Search() { Results.Clear(); var searchRooms = RuntimeCache.CurrentHomeServer.Admin.SearchRoomsAsync(orderBy: OrderBy!, dir: Ascending ? "f" : "b", searchTerm: SearchTerm, contentSearch: ContentSearchTerm).GetAsyncEnumerator(); - while (await searchRooms.MoveNextAsync()) - { + while (await searchRooms.MoveNextAsync()) { var room = searchRooms.Current; - Console.WriteLine("Hit: " + room.ToJson(indent: false)); + Console.WriteLine("Hit: " + room.ToJson(false)); Results.Add(room); } } - private Dictionary validOrderBy = new Dictionary() - { + private readonly Dictionary validOrderBy = new() { { "name", "Room name" }, { "canonical_alias", "Main alias address" }, { "joined_members", "Number of members (reversed)" }, @@ -80,7 +85,7 @@ { "join_rules", "Join rules" }, { "guest_access", "Guest access" }, { "history_visibility", "Visibility of history" }, - { "state_events", "Number of state events" }, + { "state_events", "Number of state events" } }; } \ No newline at end of file diff --git a/MatrixRoomUtils.Web/Pages/Index.razor b/MatrixRoomUtils.Web/Pages/Index.razor index decdb0c..33cca61 100644 --- a/MatrixRoomUtils.Web/Pages/Index.razor +++ b/MatrixRoomUtils.Web/Pages/Index.razor @@ -12,18 +12,15 @@ Small collection of tools to do not-so-everyday things.
    Signed in accounts - Add new account

    - @foreach (var (token, user) in RuntimeCache.LoginSessions) - { + @foreach (var (token, user) in RuntimeCache.LoginSessions) { } @code { - protected override async Task OnInitializedAsync() - { - if (!RuntimeCache.WasLoaded) - { + protected override async Task OnInitializedAsync() { + if (!RuntimeCache.WasLoaded) { Console.WriteLine("[INDEX] !!! LOCALSTORAGE WAS NOT LOADED !!!"); await LocalStorageWrapper.LoadFromLocalStorage(LocalStorage); } diff --git a/MatrixRoomUtils.Web/Pages/KnownHomeserverList.razor b/MatrixRoomUtils.Web/Pages/KnownHomeserverList.razor index 13b717d..92a8445 100644 --- a/MatrixRoomUtils.Web/Pages/KnownHomeserverList.razor +++ b/MatrixRoomUtils.Web/Pages/KnownHomeserverList.razor @@ -5,33 +5,25 @@

    Known Homeserver List


    -@if (!IsFinished) -{ +@if (!IsFinished) {

    Loading... Please wait...

    @QueryProgress.ProcessedRooms / @QueryProgress.TotalRooms

    - @foreach (var (room, state) in QueryProgress.ProcessedUsers.Where(x => !x.Value.IsFinished).OrderByDescending(x => x.Value.Total).ToList()) - { - @if (state.Blocked) - { + @foreach (var (room, state) in QueryProgress.ProcessedUsers.Where(x => !x.Value.IsFinished).OrderByDescending(x => x.Value.Total).ToList()) { + @if (state.Blocked) {

    🔒 @room.RoomId - @state.Processed / @state.Total, @state.Timing.Elapsed elapsed...

    } - else if (state.Slowmode) - { - + else if (state.Slowmode) {

    🐢 @room.RoomId - @state.Processed / @state.Total, @state.Timing.Elapsed elapsed...

    } - else - { + else {

    @room.RoomId - @state.Processed / @state.Total, @state.Timing.Elapsed elapsed...

    } } } -else -{ - @foreach (var server in HomeServers.OrderByDescending(x => x.KnownUserCount).ThenBy(x => x.Server).ToList()) - { +else { + @foreach (var server in HomeServers.OrderByDescending(x => x.KnownUserCount).ThenBy(x => x.Server).ToList()) {

    @server.Server - @server.KnownUserCount

    } } @@ -42,15 +34,12 @@ else bool IsFinished { get; set; } HomeServerInfoQueryProgress QueryProgress { get; set; } = new(); - protected override async Task OnInitializedAsync() - { + protected override async Task OnInitializedAsync() { await LocalStorageWrapper.LoadFromLocalStorage(LocalStorage); var sw = Stopwatch.StartNew(); - HomeServers = await GetHomeservers(progressCallback: async progress => - { - if (sw.ElapsedMilliseconds > 1000) - { + HomeServers = await GetHomeservers(progressCallback: async progress => { + if (sw.ElapsedMilliseconds > 1000) { Console.WriteLine("Progress updated..."); QueryProgress = progress; StateHasChanged(); @@ -69,9 +58,7 @@ else await base.OnInitializedAsync(); } - - private async Task> GetHomeservers(int memberLimit = 1000, Func>? progressCallback = null) - { + private async Task> GetHomeservers(int memberLimit = 1000, Func>? progressCallback = null) { HomeServerInfoQueryProgress progress = new(); List homeServers = new(); var rooms = await RuntimeCache.CurrentHomeServer.GetJoinedRooms(); @@ -79,16 +66,14 @@ else var semaphore = new SemaphoreSlim(4); var semLock = new SemaphoreSlim(1); - var tasks = rooms.Select(async room => - { + var tasks = rooms.Select(async room => { await semaphore.WaitAsync(); - progress.ProcessedUsers.Add(room, new()); + progress.ProcessedUsers.Add(room, new HomeServerInfoQueryProgress.State()); Console.WriteLine($"Fetching states for room ({rooms.IndexOf(room)}/{rooms.Count}) ({room.RoomId})"); var states = (await room.GetStateAsync("")).Value.Deserialize>(); states.RemoveAll(x => x.Type != "m.room.member" || x.Content.GetProperty("membership").GetString() != "join"); Console.WriteLine($"Room {room.RoomId} has {states.Count} members"); - if (states.Count > memberLimit) - { + if (states.Count > memberLimit) { Console.WriteLine("Skipping!"); semaphore.Release(); progress.ProcessedUsers.Remove(room); @@ -97,37 +82,31 @@ else } progress.ProcessedUsers[room].Total = states.Count; var updateInterval = progress.ProcessedUsers[room].Total >= 1000 ? 1000 : 100; - while (progress.ProcessedUsers.Any(x => x.Value.Total == 0) && progress.ProcessedUsers[room].Total >= 1000) - { + while (progress.ProcessedUsers.Any(x => x.Value.Total == 0) && progress.ProcessedUsers[room].Total >= 1000) { progress.ProcessedUsers[room].Blocked = true; await Task.Delay(1000); - // if(progressCallback != null) - // await progressCallback.Invoke(progress); + // if(progressCallback != null) + // await progressCallback.Invoke(progress); } progress.ProcessedUsers[room].Blocked = false; - int processedStates = 0; - foreach (var state in states) - { + var processedStates = 0; + foreach (var state in states) { await semLock.WaitAsync(); semLock.Release(); - if (progress.ProcessedUsers.Count(x => x.Value.Total == 0) > 5 && progress.ProcessedUsers[room].Total >= 200) - { + if (progress.ProcessedUsers.Count(x => x.Value.Total == 0) > 5 && progress.ProcessedUsers[room].Total >= 200) { progress.ProcessedUsers[room].Slowmode = true; await Task.Delay(progress.ProcessedUsers[room].Total >= 500 ? 1000 : 100); } - else - { + else { progress.ProcessedUsers[room].Slowmode = false; } - if (!homeServers.Any(x => x.Server == state.StateKey.Split(':')[1])) - { - homeServers.Add(new HomeServerInfo() { Server = state.StateKey.Split(':')[1] }); + if (!homeServers.Any(x => x.Server == state.StateKey.Split(':')[1])) { + homeServers.Add(new HomeServerInfo { Server = state.StateKey.Split(':')[1] }); } var hs = homeServers.First(x => x.Server == state.StateKey.Split(':')[1]); if (!hs.KnownUsers.Contains(state.StateKey.Split(':')[0])) hs.KnownUsers.Add(state.StateKey.Split(':')[0]); - if (++progress.ProcessedUsers[room].Processed % updateInterval == 0 && progressCallback != null) - { + if (++progress.ProcessedUsers[room].Processed % updateInterval == 0 && progressCallback != null) { await semLock.WaitAsync(); var _ = await progressCallback.Invoke(progress); semLock.Release(); @@ -148,29 +127,26 @@ else return homeServers; } - class HomeServerInfo - { + class HomeServerInfo { public string Server { get; set; } public int? KnownUserCount { get; set; } - public List KnownUsers { get; set; } = new(); + public List KnownUsers { get; } = new(); } - class HomeServerInfoQueryProgress - { + class HomeServerInfoQueryProgress { public int ProcessedRooms { get; set; } public int TotalRooms { get; set; } - public Dictionary ProcessedUsers { get; set; } = new(); + public Dictionary ProcessedUsers { get; } = new(); public List CurrentState { get; set; } = new(); - public class State - { + public class State { public int Processed { get; set; } public int Total { get; set; } public bool Blocked { get; set; } public bool Slowmode { get; set; } public float Progress => (float)Processed / Total; public bool IsFinished { get; set; } - public Stopwatch Timing { get; set; } = Stopwatch.StartNew(); + public Stopwatch Timing { get; } = Stopwatch.StartNew(); } } diff --git a/MatrixRoomUtils.Web/Pages/LoginPage.razor b/MatrixRoomUtils.Web/Pages/LoginPage.razor index c46dc9a..16fdd24 100644 --- a/MatrixRoomUtils.Web/Pages/LoginPage.razor +++ b/MatrixRoomUtils.Web/Pages/LoginPage.razor @@ -1,6 +1,6 @@ @page "/Login" -@using System.Text.Json @using MatrixRoomUtils.Core.Authentication +@using System.Text.Json @using MatrixRoomUtils.Web.Shared.SimpleComponents @inject ILocalStorageService LocalStorage @inject IJSRuntime JsRuntime @@ -27,8 +27,7 @@

    Parsed records


    - @foreach (var (homeserver, username, password) in records) - { + @foreach (var (homeserver, username, password) in records) { @@ -41,19 +40,16 @@ @code { - List<(string homeserver, string username, string password)> records = new(); + readonly List<(string homeserver, string username, string password)> records = new(); (string homeserver, string username, string password) newRecordInput = ("", "", ""); - async Task Login() - { - foreach (var (homeserver, username, password) in records) - { + async Task Login() { + foreach (var (homeserver, username, password) in records) { if (RuntimeCache.LoginSessions.Any(x => x.Value.LoginResponse.UserId == $"@{username}:{homeserver}")) continue; var result = await MatrixAuth.Login(homeserver, username, password); Console.WriteLine($"Obtained access token for {result.UserId}!"); - var userinfo = new UserInfo() - { + var userinfo = new UserInfo { LoginResponse = result }; userinfo.Profile = await (await new AuthenticatedHomeServer(result.UserId, result.AccessToken, result.HomeServer).Configure()).GetProfile(result.UserId); @@ -66,18 +62,15 @@ await LocalStorageWrapper.SaveToLocalStorage(LocalStorage); } - private async Task FileChanged(InputFileChangeEventArgs obj) - { - Console.WriteLine(JsonSerializer.Serialize(obj, new JsonSerializerOptions() - { + private async Task FileChanged(InputFileChangeEventArgs obj) { + Console.WriteLine(JsonSerializer.Serialize(obj, new JsonSerializerOptions { WriteIndented = true })); await using var rs = obj.File.OpenReadStream(); using var sr = new StreamReader(rs); - string TsvData = await sr.ReadToEndAsync(); + var TsvData = await sr.ReadToEndAsync(); records.Clear(); - foreach (var line in TsvData.Split('\n')) - { + foreach (var line in TsvData.Split('\n')) { var parts = line.Split('\t'); if (parts.Length != 3) continue; @@ -85,8 +78,7 @@ } } - private void AddRecord() - { + private void AddRecord() { records.Add(newRecordInput); newRecordInput = ("", "", ""); } diff --git a/MatrixRoomUtils.Web/Pages/MediaLocator.razor b/MatrixRoomUtils.Web/Pages/MediaLocator.razor index 19a0d4e..36cd8e6 100644 --- a/MatrixRoomUtils.Web/Pages/MediaLocator.razor +++ b/MatrixRoomUtils.Web/Pages/MediaLocator.razor @@ -7,8 +7,7 @@
    Checked homeserver list (@homeservers.Count entries)
      - @foreach (var hs in homeservers) - { + @foreach (var hs in homeservers) {
    • @hs
    • }
    @@ -16,26 +15,22 @@
    MXC URL: - + -@if (successResults.Count > 0) -{ +@if (successResults.Count > 0) {

    Successes

      - @foreach (var result in successResults) - { + @foreach (var result in successResults) {
    • @result
    • }
    } -@if (errorResults.Count > 0) -{ +@if (errorResults.Count > 0) {

    Errors

      - @foreach (var result in errorResults) - { + @foreach (var result in errorResults) {
    • @result
    • }
    @@ -44,15 +39,13 @@ @code { string mxcUrl { get; set; } - List successResults = new List(); - List errorResults = new List(); - List homeservers = new List(); + readonly List successResults = new(); + readonly List errorResults = new(); + readonly List homeservers = new(); - protected override async Task OnInitializedAsync() - { + protected override async Task OnInitializedAsync() { await base.OnInitializedAsync(); - homeservers.AddRange(new [] - { + homeservers.AddRange(new[] { "matrix.org", "feline.support", "rory.gay", @@ -62,70 +55,58 @@ }); } - async Task executeSearch() - { + async Task executeSearch() { var sem = new SemaphoreSlim(128, 128); - homeservers.ForEach(async hs => - { + homeservers.ForEach(async hs => { await sem.WaitAsync(); var httpClient = new HttpClient { BaseAddress = new Uri(hs) }; httpClient.Timeout = TimeSpan.FromSeconds(5); var rmu = mxcUrl.Replace("mxc://", $"{hs}/_matrix/media/r0/download/"); - try - { + try { var res = await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, rmu)); - if (res.IsSuccessStatusCode) - { + if (res.IsSuccessStatusCode) { successResults.Add($"{hs}: found - {res.Content.Headers.ContentLength} bytes"); StateHasChanged(); return; } errorResults.Add($"Error: {hs} - {res.StatusCode}\n" + await res.Content.ReadAsStringAsync()); } - catch (Exception e) - { + catch (Exception e) { errorResults.Add($"Error: {e}"); } - finally - { + finally { sem.Release(); } StateHasChanged(); }); } - - async Task addMoreHomeservers() - { + async Task addMoreHomeservers() { await LocalStorageWrapper.LoadFromLocalStorage(LocalStorage); var res = await Http.GetAsync("/homeservers.txt"); var content = await res.Content.ReadAsStringAsync(); homeservers.Clear(); var lines = content.Split("\n"); - + var rhs = new RemoteHomeServer("rory.gay"); var sem = new SemaphoreSlim(128, 128); - lines.ToList().ForEach(async line => - { + lines.ToList().ForEach(async line => { await sem.WaitAsync(); - try - { + try { homeservers.Add(await rhs.ResolveHomeserverFromWellKnown(line)); StateHasChanged(); - if(Random.Shared.Next(0,101) == 50) + if (Random.Shared.Next(0, 101) == 50) await LocalStorageWrapper.SaveCacheToLocalStorage(LocalStorage); } - catch (Exception e) - { + catch (Exception e) { Console.WriteLine(e); } - finally - { + finally { sem.Release(); } }); - StateHasChanged(); } + } \ No newline at end of file diff --git a/MatrixRoomUtils.Web/Pages/PolicyList/PolicyListEditorPage.razor b/MatrixRoomUtils.Web/Pages/PolicyList/PolicyListEditorPage.razor index bf03ee3..b15928a 100644 --- a/MatrixRoomUtils.Web/Pages/PolicyList/PolicyListEditorPage.razor +++ b/MatrixRoomUtils.Web/Pages/PolicyList/PolicyListEditorPage.razor @@ -1,7 +1,7 @@ @page "/PolicyListEditor/{RoomId}" -@using System.Text.Json @using MatrixRoomUtils.Core.Extensions @using MatrixRoomUtils.Core.StateEventTypes +@using System.Text.Json @inject ILocalStorageService LocalStorage @inject NavigationManager NavigationManager

    Policy list editor - Editing @RoomId

    @@ -15,12 +15,10 @@ -@if (!PolicyEvents.Any(x => x.Type == "m.policy.rule.server")) -{ +@if (!PolicyEvents.Any(x => x.Type == "m.policy.rule.server")) {

    No server policies

    } -else -{ +else {

    Server policies


    @username @homeserver
    @@ -33,8 +31,7 @@ else - @foreach (var policyEvent in PolicyEvents.Where(x => x.Type == "m.policy.rule.server" && x.Content.Entity != null)) - { + @foreach (var policyEvent in PolicyEvents.Where(x => x.Type == "m.policy.rule.server" && x.Content.Entity != null)) { @@ -59,23 +56,20 @@ else - @foreach (var policyEvent in PolicyEvents.Where(x => x.Type == "m.policy.rule.server" && x.Content.Entity == null)) - { + @foreach (var policyEvent in PolicyEvents.Where(x => x.Type == "m.policy.rule.server" && x.Content.Entity == null)) { - + }
    Entity: @policyEvent.Content.Entity
    State: @policyEvent.StateKey
    @policyEvent.Content.Reason
    @policyEvent.StateKey@policyEvent.Content.ToJson(indent: false, ignoreNull: true)@policyEvent.Content.ToJson(false, true)
    } -@if (!PolicyEvents.Any(x => x.Type == "m.policy.rule.room")) -{ +@if (!PolicyEvents.Any(x => x.Type == "m.policy.rule.room")) {

    No room policies

    } -else -{ +else {

    Room policies


    @@ -88,8 +82,7 @@ else - @foreach (var policyEvent in PolicyEvents.Where(x => x.Type == "m.policy.rule.room" && x.Content.Entity != null)) - { + @foreach (var policyEvent in PolicyEvents.Where(x => x.Type == "m.policy.rule.room" && x.Content.Entity != null)) { @@ -113,30 +106,26 @@ else - @foreach (var policyEvent in PolicyEvents.Where(x => x.Type == "m.policy.rule.room" && x.Content.Entity == null)) - { + @foreach (var policyEvent in PolicyEvents.Where(x => x.Type == "m.policy.rule.room" && x.Content.Entity == null)) { - + }
    Entity: @policyEvent.Content.Entity
    State: @policyEvent.StateKey
    @policyEvent.Content.Reason
    @policyEvent.StateKey@policyEvent.Content.ToJson(indent: false, ignoreNull: true)@policyEvent.Content.ToJson(false, true)
    } -@if (!PolicyEvents.Any(x => x.Type == "m.policy.rule.user")) -{ +@if (!PolicyEvents.Any(x => x.Type == "m.policy.rule.user")) {

    No user policies

    } -else -{ +else {

    User policies


    - @if (_enableAvatars) - { + @if (_enableAvatars) { } @@ -146,12 +135,12 @@ else - @foreach (var policyEvent in PolicyEvents.Where(x => x.Type == "m.policy.rule.user" && x.Content.Entity != null)) - { + @foreach (var policyEvent in PolicyEvents.Where(x => x.Type == "m.policy.rule.user" && x.Content.Entity != null)) { - @if (_enableAvatars) - { - + @if (_enableAvatars) { + } @@ -175,11 +164,10 @@ else - @foreach (var policyEvent in PolicyEvents.Where(x => x.Type == "m.policy.rule.user" && x.Content.Entity == null)) - { + @foreach (var policyEvent in PolicyEvents.Where(x => x.Type == "m.policy.rule.user" && x.Content.Entity == null)) { - + } @@ -197,21 +185,19 @@ else [Parameter] public string? RoomId { get; set; } - - private bool _enableAvatars = false; - - static Dictionary avatars = new Dictionary(); - static Dictionary servers = new Dictionary(); + + private bool _enableAvatars; + + static readonly Dictionary avatars = new(); + static readonly Dictionary servers = new(); public static List> PolicyEvents { get; set; } = new(); - protected override async Task OnInitializedAsync() - { + protected override async Task OnInitializedAsync() { await LocalStorageWrapper.LoadFromLocalStorage(LocalStorage); await base.OnInitializedAsync(); - // if(RuntimeCache.AccessToken == null || RuntimeCache.CurrentHomeserver == null) - if (RuntimeCache.CurrentHomeServer == null) - { + // if(RuntimeCache.AccessToken == null || RuntimeCache.CurrentHomeserver == null) + if (RuntimeCache.CurrentHomeServer == null) { NavigationManager.NavigateTo("/Login"); return; } @@ -220,18 +206,16 @@ else Console.WriteLine("Policy list editor initialized!"); } - private async Task LoadStatesAsync() - { - // using var client = new HttpClient(); - // client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", LocalStorageWrapper.AccessToken); - // var response = await client.GetAsync($"{LocalStorageWrapper.CurrentHomeserver}/_matrix/client/r0/rooms/{RoomId}/state"); - // var Content = await response.Content.ReadAsStringAsync(); - // Console.WriteLine(JsonSerializer.Deserialize(Content).ToJson()); - // var stateEvents = JsonSerializer.Deserialize>(Content); + private async Task LoadStatesAsync() { + // using var client = new HttpClient(); + // client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", LocalStorageWrapper.AccessToken); + // var response = await client.GetAsync($"{LocalStorageWrapper.CurrentHomeserver}/_matrix/client/r0/rooms/{RoomId}/state"); + // var Content = await response.Content.ReadAsStringAsync(); + // Console.WriteLine(JsonSerializer.Deserialize(Content).ToJson()); + // var stateEvents = JsonSerializer.Deserialize>(Content); var room = await RuntimeCache.CurrentHomeServer.GetRoom(RoomId); var stateEventsQuery = await room.GetStateAsync(""); - if (stateEventsQuery == null) - { + if (stateEventsQuery == null) { Console.WriteLine("state events query is null!!!"); } var stateEvents = stateEventsQuery.Value.Deserialize>(); @@ -239,30 +223,25 @@ else .Select(x => JsonSerializer.Deserialize>(JsonSerializer.Serialize(x))).ToList(); StateHasChanged(); } - - private async Task GetAvatar(string userId) - { - try - { + + private async Task GetAvatar(string userId) { + try { if (avatars.ContainsKey(userId)) return; var hs = userId.Split(':')[1]; - RemoteHomeServer server = servers.ContainsKey(hs) ? servers[hs] : await new RemoteHomeServer(userId.Split(':')[1]).Configure(); + var server = servers.ContainsKey(hs) ? servers[hs] : await new RemoteHomeServer(userId.Split(':')[1]).Configure(); if (!servers.ContainsKey(hs)) servers.Add(hs, server); var profile = await server.GetProfile(userId); avatars.Add(userId, server.ResolveMediaUri(profile.AvatarUrl)); servers.Add(userId, server); StateHasChanged(); } - catch - { - // ignored + catch { + // ignored } } - - private async Task GetAllAvatars() - { - foreach (var policyEvent in PolicyEvents.Where(x => x.Type == "m.policy.rule.user" && x.Content.Entity != null)) - { + + private async Task GetAllAvatars() { + foreach (var policyEvent in PolicyEvents.Where(x => x.Type == "m.policy.rule.user" && x.Content.Entity != null)) { await GetAvatar(policyEvent.Content.Entity); } StateHasChanged(); diff --git a/MatrixRoomUtils.Web/Pages/PolicyList/PolicyListRoomList.razor b/MatrixRoomUtils.Web/Pages/PolicyList/PolicyListRoomList.razor index e61598a..20eab7a 100644 --- a/MatrixRoomUtils.Web/Pages/PolicyList/PolicyListRoomList.razor +++ b/MatrixRoomUtils.Web/Pages/PolicyList/PolicyListRoomList.razor @@ -1,29 +1,25 @@ @page "/PolicyListEditor" -@using System.Text.Json @using MatrixRoomUtils.Core.Extensions @inject ILocalStorageService LocalStorage @inject NavigationManager NavigationManager

    Policy list editor - Room list


    -@if (PolicyRoomList.Count == 0) -{ +@if (PolicyRoomList.Count == 0) {

    No policy rooms found.

    Loading progress: @checkedRoomCount/@totalRoomCount

    } -else -{ - @if (checkedRoomCount != totalRoomCount) - { +else { + @if (checkedRoomCount != totalRoomCount) {

    Loading progress: @checkedRoomCount/@totalRoomCount

    } - foreach (var s in PolicyRoomList) - { - - -
    - Shortcode: @s.Shortcode -
    + foreach (var s in PolicyRoomList) { + + +
    + Shortcode: @s.Shortcode +
    +
    @* [@s.Shortcode] @s.Name (@s.RoomId) *@ @*
    *@ } @@ -40,15 +36,13 @@ else public List PolicyRoomList { get; set; } = new(); - private int checkedRoomCount { get; set; } = 0; - private int totalRoomCount { get; set; } = 0; + private int checkedRoomCount { get; set; } + private int totalRoomCount { get; set; } - protected override async Task OnInitializedAsync() - { + protected override async Task OnInitializedAsync() { await LocalStorageWrapper.LoadFromLocalStorage(LocalStorage); await base.OnInitializedAsync(); - if (RuntimeCache.CurrentHomeServer == null) - { + if (RuntimeCache.CurrentHomeServer == null) { NavigationManager.NavigateTo("/Login"); return; } @@ -56,59 +50,48 @@ else Console.WriteLine("Policy list editor initialized!"); } - private async Task EnumeratePolicyRooms() - { + private async Task EnumeratePolicyRooms() { var xxxrooms = await RuntimeCache.CurrentHomeServer.GetJoinedRooms(); totalRoomCount = xxxrooms.Count; StateHasChanged(); var xxxsemaphore = new SemaphoreSlim(1000); var xxxtasks = new List>(); - foreach (var room in xxxrooms) - { + foreach (var room in xxxrooms) { xxxtasks.Add(GetPolicyRoomInfo(room.RoomId, xxxsemaphore)); } var xxxresults = await Task.WhenAll(xxxtasks); PolicyRoomList.AddRange(xxxresults.Where(x => x != null).Select(x => x.Value)); Console.WriteLine($"Detected policy lists: {PolicyRoomList.ToJson()}"); - return; } - private async Task GetPolicyRoomInfo(string room, SemaphoreSlim semaphore) - { - try - { + private async Task GetPolicyRoomInfo(string room, SemaphoreSlim semaphore) { + try { await semaphore.WaitAsync(); - PolicyRoomInfo roomInfo = new() - { + PolicyRoomInfo roomInfo = new() { RoomId = room }; var r = await RuntimeCache.CurrentHomeServer.GetRoom(room); var shortcodeState = await r.GetStateAsync("org.matrix.mjolnir.shortcode"); - if(!shortcodeState.HasValue) return null; - roomInfo.Shortcode = shortcodeState.Value.TryGetProperty("shortcode", out JsonElement shortcode) ? shortcode.GetString() : null; + if (!shortcodeState.HasValue) return null; + roomInfo.Shortcode = shortcodeState.Value.TryGetProperty("shortcode", out var shortcode) ? shortcode.GetString() : null; - if (roomInfo.Shortcode != null) - { + if (roomInfo.Shortcode != null) { roomInfo.Name = await r.GetNameAsync(); return roomInfo; } return null; } - finally - - { + finally { checkedRoomCount++; StateHasChanged(); semaphore.Release(); } } - public struct PolicyRoomInfo - - { + public struct PolicyRoomInfo { public string RoomId { get; set; } @@ -118,4 +101,5 @@ else public string? Name { get; set; } } - } \ No newline at end of file + +} \ No newline at end of file diff --git a/MatrixRoomUtils.Web/Pages/RoomManager/RoomManager.razor b/MatrixRoomUtils.Web/Pages/RoomManager/RoomManager.razor index 5daa97c..9b0bb88 100644 --- a/MatrixRoomUtils.Web/Pages/RoomManager/RoomManager.razor +++ b/MatrixRoomUtils.Web/Pages/RoomManager/RoomManager.razor @@ -3,12 +3,10 @@ @inject NavigationManager NavigationManager

    Room manager


    -@if (Rooms.Count == 0) -{ +@if (Rooms.Count == 0) {

    You are not in any rooms!

    } -else -{ +else {

    You are in @Rooms.Count rooms and @Spaces.Count spaces

    Create room @@ -16,8 +14,7 @@ else

    Space List - @foreach (var room in Spaces) - { + @foreach (var room in Spaces) { @@ -25,8 +22,7 @@ else
    Room List - @foreach (var room in Rooms) - { + @foreach (var room in Rooms) { @@ -41,15 +37,13 @@ else public List Rooms { get; set; } = new(); public List Spaces { get; set; } = new(); - protected override async Task OnInitializedAsync() - { + protected override async Task OnInitializedAsync() { Console.WriteLine("Initializing room manager"); await LocalStorageWrapper.LoadFromLocalStorage(LocalStorage); Console.WriteLine("Loaded from local storage"); await base.OnInitializedAsync(); Console.WriteLine("Initialized base"); - if (RuntimeCache.CurrentHomeServer == null) - { + if (RuntimeCache.CurrentHomeServer == null) { NavigationManager.NavigateTo("/Login"); return; } @@ -59,8 +53,7 @@ else Console.WriteLine($"Got {_rooms.Count} rooms"); var semaphore = new SemaphoreSlim(10); var tasks = new List>(); - foreach (var room in _rooms) - { + foreach (var room in _rooms) { tasks.Add(CheckIfSpace(room, semaphore)); } await Task.WhenAll(tasks); @@ -68,45 +61,36 @@ else Console.WriteLine("Fetched joined rooms!"); } - private async Task CheckIfSpace(Room room, SemaphoreSlim semaphore) - { + private async Task CheckIfSpace(Room room, SemaphoreSlim semaphore) { await semaphore.WaitAsync(); - // Console.WriteLine($"Checking if {room.RoomId} is a space"); - try - { + // Console.WriteLine($"Checking if {room.RoomId} is a space"); + try { var state = await room.GetStateAsync("m.room.create"); - if (state != null) - { + if (state != null) { //Console.WriteLine(state.Value.ToJson()); - if (state.Type != null) - { - if (state.Type == "m.space") - { + if (state.Type != null) { + if (state.Type == "m.space") { Console.WriteLine($"Room {room.RoomId} is a space!"); Spaces.Add(room); StateHasChanged(); return room; } - else - { + else { Console.WriteLine($"Encountered unknown room type {state.Type}"); } } - else - { + else { Rooms.Add(room); //this is fine, apprently... // Console.WriteLine($"Room {room.RoomId} has no Content.type in m.room.create!"); } } } - catch (Exception e) - { + catch (Exception e) { Console.WriteLine(e); return null; } - finally - { + finally { semaphore.Release(); } return null; diff --git a/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerCreateRoom.razor b/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerCreateRoom.razor index d561eb0..5cfda77 100644 --- a/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerCreateRoom.razor +++ b/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerCreateRoom.razor @@ -1,12 +1,13 @@ @page "/RoomManagerCreateRoom" -@using System.Text.Json @using MatrixRoomUtils.Core.Extensions @using MatrixRoomUtils.Core.Responses -@using MatrixRoomUtils.Web.Shared.SimpleComponents -@using System.Reflection -@using System.Runtime.Intrinsics.X86 +@using System.Text.Json @using System.Text.Json.Serialization +@using System.Reflection @using MatrixRoomUtils.Web.Classes.RoomCreationTemplates +@* ReSharper disable once RedundantUsingDirective - Must not remove this, Rider marks this as "unused" when it's not *@ +@using MatrixRoomUtils.Web.Shared.SimpleComponents +

    Room Manager - Create Room

    @*
    @JsonString
    *@ @@ -20,15 +21,13 @@
    - @if (creationEvent != null) - { + @if (creationEvent != null) {
    @creationEvent.PowerLevelContentOverride.Users.Count members - @foreach (var user in creationEvent.PowerLevelContentOverride.Events.Keys) - { + @foreach (var user in creationEvent.PowerLevelContentOverride.Events.Keys) { var _event = user;
    @@ -99,8 +97,7 @@ } - @foreach (var user in creationEvent.PowerLevelContentOverride.Users.Keys) - { + @foreach (var user in creationEvent.PowerLevelContentOverride.Users.Keys) { var _user = user; @@ -131,8 +128,7 @@
    @creationEvent.InitialState.Count(x => x.Type == "m.room.member") members - @foreach (var member in creationEvent.InitialState.Where(x => x.Type == "m.room.member" && x.StateKey != RuntimeCache.CurrentHomeServer.UserId)) - { + @foreach (var member in creationEvent.InitialState.Where(x => x.Type == "m.room.member" && x.StateKey != RuntimeCache.CurrentHomeServer.UserId)) { }
    @@ -154,13 +150,11 @@ @creationEvent.InitialState.Count(x => !ImplementedStates.Contains(x.Type)) custom states
    User
    + + Entity: @string.Join("", policyEvent.Content.Entity.Take(64))
    State: @string.Join("", policyEvent.StateKey.Take(64))
    @policyEvent.Content.Reason
    @policyEvent.StateKey@policyEvent.Content.ToJson(indent: false, ignoreNull: true)@policyEvent.Content.ToJson(false, true)
    Preset: - @foreach (var createRoomRequest in Presets) - { + @foreach (var createRoomRequest in Presets) { }
    Room name: @@ -89,8 +88,7 @@ Permissions:
    :
    :
    - @foreach (var initialState in creationEvent.InitialState.Where(x => !ImplementedStates.Contains(x.Type))) - { + @foreach (var initialState in creationEvent.InitialState.Where(x => !ImplementedStates.Contains(x.Type))) {
    @(initialState.Type): - @if (!string.IsNullOrEmpty(initialState.StateKey)) - { + @if (!string.IsNullOrEmpty(initialState.StateKey)) {
    (@initialState.StateKey) } @@ -176,8 +170,7 @@
    @creationEvent.InitialState.Count initial states - @foreach (var initialState in creationEvent.InitialState) - { + @foreach (var initialState in creationEvent.InitialState) { var _state = initialState; - @foreach (var stateEvent in FilteredEvents.Where(x => x.state_key == "").OrderBy(x => x.origin_server_ts)) - { + @foreach (var stateEvent in FilteredEvents.Where(x => x.state_key == "").OrderBy(x => x.origin_server_ts)) {
    @@ -214,25 +207,21 @@ @code { - private string RoomPreset - { - get - { - if (Presets.ContainsValue(creationEvent)) - { + private string RoomPreset { + get { + if (Presets.ContainsValue(creationEvent)) { return Presets.First(x => x.Value == creationEvent).Key; } return "Not a preset"; } - set - { + set { creationEvent = Presets[value]; JsonChanged(); OverwriteWrappedPropertiesFromEvent(); creationEvent.PowerLevelContentOverride.Events = creationEvent.PowerLevelContentOverride.Events.OrderByDescending(x => x.Value).ThenBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value); creationEvent.PowerLevelContentOverride.Users = creationEvent.PowerLevelContentOverride.Users.OrderByDescending(x => x.Value).ThenBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value); guestAccessEvent = creationEvent["m.room.guest_access"].As().Content; - + Console.WriteLine($"Creation event uncasted: {creationEvent["m.room.guest_access"].ToJson()}"); Console.WriteLine($"Creation event casted: {creationEvent["m.room.guest_access"].As().ToJson()}"); creationEvent["m.room.guest_access"].As().Content.IsGuestAccessEnabled = true; @@ -251,21 +240,18 @@ private Dictionary Presets { get; set; } = new(); - protected override async Task OnInitializedAsync() - { + protected override async Task OnInitializedAsync() { await LocalStorageWrapper.LoadFromLocalStorage(LocalStorage); //creationEvent = Presets["Default room"] = - foreach (var x in Assembly.GetExecutingAssembly().GetTypes().Where(x => x.IsClass && !x.IsAbstract && x.GetInterfaces().Contains(typeof(IRoomCreationTemplate))).ToList()) - { + foreach (var x in Assembly.GetExecutingAssembly().GetTypes().Where(x => x.IsClass && !x.IsAbstract && x.GetInterfaces().Contains(typeof(IRoomCreationTemplate))).ToList()) { Console.WriteLine($"Found room creation template in class: {x.FullName}"); var instance = (IRoomCreationTemplate)Activator.CreateInstance(x); Presets[instance.Name] = instance.CreateRoomRequest; } Presets = Presets.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value); - if (!Presets.ContainsKey("Default")) - { + if (!Presets.ContainsKey("Default")) { Console.WriteLine($"No default room found in {Presets.Count} presets: {string.Join(", ", Presets.Keys)}"); } else RoomPreset = "Default"; @@ -273,30 +259,23 @@ await base.OnInitializedAsync(); } - private void JsonChanged() - { - Console.WriteLine(creationEvent.ToJson()); - } - + private void JsonChanged() => Console.WriteLine(creationEvent.ToJson()); //wrappers private List ServerACLAllowRules { get; set; } = new(); private List ServerACLDenyRules { get; set; } = new(); - private void OverwriteWrappedPropertiesFromEvent() - { + private void OverwriteWrappedPropertiesFromEvent() { Console.WriteLine("Overwriting wrapped properties from event"); ServerACLAllowRules = creationEvent.ServerACLs.Allow; ServerACLDenyRules = creationEvent.ServerACLs.Deny; } - private async Task OverwriteWrappedProperties() - { + private async Task OverwriteWrappedProperties() { Console.WriteLine("Overwriting wrapped properties"); Console.WriteLine($"Allow: {ServerACLAllowRules.Count}: {string.Join(", ", ServerACLAllowRules)}"); Console.WriteLine($"Deny: {ServerACLDenyRules.Count}: {string.Join(", ", ServerACLDenyRules)}"); - creationEvent.ServerACLs = new() - { + creationEvent.ServerACLs = new ServerACL { Allow = ServerACLAllowRules, Deny = ServerACLDenyRules, AllowIpLiterals = creationEvent.ServerACLs.AllowIpLiterals @@ -305,16 +284,14 @@ StateHasChanged(); } - private async Task RoomIconFilePicked(InputFileChangeEventArgs obj) - { + private async Task RoomIconFilePicked(InputFileChangeEventArgs obj) { var res = await RuntimeCache.CurrentHomeServer.UploadFile(obj.File.Name, obj.File.OpenReadStream(), obj.File.ContentType); Console.WriteLine(res); creationEvent.RoomIcon = res; StateHasChanged(); } - private async Task CreateRoom() - { + private async Task CreateRoom() { Console.WriteLine("Create room"); Console.WriteLine(creationEvent.ToJson()); creationEvent.CreationContent.Add("rory.gay.created_using", "Rory&::MatrixRoomUtils (https://mru.rory.gay)"); @@ -323,22 +300,18 @@ // NavigationManager.NavigateTo($"/RoomManager/{id.RoomId.Replace('.','~')}"); } - private void InviteMember(string mxid) - { + private void InviteMember(string mxid) { if (!creationEvent.InitialState.Any(x => x.Type == "m.room.member" && x.StateKey == mxid) && RuntimeCache.CurrentHomeServer.UserId != mxid) - creationEvent.InitialState.Add(new() - { + creationEvent.InitialState.Add(new StateEvent { Type = "m.room.member", StateKey = mxid, - Content = new - { + Content = new { membership = "invite", reason = "Automatically invited at room creation time." } }); } - private string GetStateFriendlyName(string key) => key switch { "m.room.history_visibility" => "History visibility", "m.room.guest_access" => "Guest access", @@ -363,19 +336,14 @@ _ => key }; - public class GuestAccessContent - { + public class GuestAccessContent { [JsonPropertyName("guest_access")] public string GuestAccess { get; set; } - public bool IsGuestAccessEnabled - { + public bool IsGuestAccessEnabled { get => GuestAccess == "can_join"; set => GuestAccess = value ? "can_join" : "forbidden"; } } - - } - diff --git a/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerSpace.razor b/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerSpace.razor index 1e7e065..c5e1569 100644 --- a/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerSpace.razor +++ b/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerSpace.razor @@ -4,8 +4,7 @@

    Room manager - Viewing Space

    -@foreach (var room in Rooms) -{ +@foreach (var room in Rooms) { } @@ -13,8 +12,7 @@
    State list - @foreach (var stateEvent in States.OrderBy(x => x.StateKey).ThenBy(x => x.Type)) - { + @foreach (var stateEvent in States.OrderBy(x => x.StateKey).ThenBy(x => x.Type)) {

    @stateEvent.StateKey/@stateEvent.Type:

    @stateEvent.Content.ToJson()
    } @@ -24,61 +22,52 @@ [Parameter] public string RoomId { get; set; } = "invalid!!!!!!"; - + private Room? Room { get; set; } - + private StateEventResponse[] States { get; set; } = Array.Empty>(); - private List Rooms { get; set; } = new(); - private List ServersInSpace { get; set; } = new(); - - protected override async Task OnInitializedAsync() - { + private List Rooms { get; } = new(); + private List ServersInSpace { get; } = new(); + + protected override async Task OnInitializedAsync() { await LocalStorageWrapper.LoadFromLocalStorage(LocalStorage); Room = await RuntimeCache.CurrentHomeServer.GetRoom(RoomId.Replace('~', '.')); var state = await Room.GetStateAsync(""); - if (state != null) - { - // Console.WriteLine(state.Value.ToJson()); + if (state != null) { + // Console.WriteLine(state.Value.ToJson()); States = state.Value.Deserialize[]>()!; - - foreach (var stateEvent in States) - { - if (stateEvent.Type == "m.space.child") - { - // if (stateEvent.Content.ToJson().Length < 5) return; + + foreach (var stateEvent in States) { + if (stateEvent.Type == "m.space.child") { + // if (stateEvent.Content.ToJson().Length < 5) return; var roomId = stateEvent.StateKey; var room = await RuntimeCache.CurrentHomeServer.GetRoom(roomId); - if (room != null) - { + if (room != null) { Rooms.Add(room); } } - else if (stateEvent.Type == "m.room.member") - { + else if (stateEvent.Type == "m.room.member") { var serverName = stateEvent.StateKey.Split(':').Last(); - if (!ServersInSpace.Contains(serverName)) - { + if (!ServersInSpace.Contains(serverName)) { ServersInSpace.Add(serverName); } } } - - // if(state.Value.TryGetProperty("Type", out var Type)) - // { - // } - // else - // { - // //this is fine, apprently... - // //Console.WriteLine($"Room {room.RoomId} has no Content.Type in m.room.create!"); - // } + + // if(state.Value.TryGetProperty("Type", out var Type)) + // { + // } + // else + // { + // //this is fine, apprently... + // //Console.WriteLine($"Room {room.RoomId} has no Content.Type in m.room.create!"); + // } } await base.OnInitializedAsync(); } - - private async Task JoinAllRooms() - { - foreach (var room in Rooms) - { + + private async Task JoinAllRooms() { + foreach (var room in Rooms) { room.JoinAsync(ServersInSpace.ToArray()); } } diff --git a/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerTimeline.razor b/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerTimeline.razor index a8a7fc2..2db7cab 100644 --- a/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerTimeline.razor +++ b/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerTimeline.razor @@ -1,12 +1,10 @@ @page "/RoomManager/Timeline/{RoomId}" @using MatrixRoomUtils.Web.Shared.TimelineComponents -@using MatrixRoomUtils.Core.Extensions

    RoomManagerTimeline


    Loaded @Events.Count events...

    -@foreach (var evt in Events) -{ +@foreach (var evt in Events) {
    @@ -17,18 +15,16 @@ [Parameter] public string RoomId { get; set; } = "invalid!!!!!!"; - private List Messages { get; set; } = new(); - private List Events { get; set; } = new(); + private List Messages { get; } = new(); + private List Events { get; } = new(); - protected override async Task OnInitializedAsync() - { + protected override async Task OnInitializedAsync() { await LocalStorageWrapper.LoadFromLocalStorage(LocalStorage); RoomId = RoomId.Replace('~', '.'); Console.WriteLine("RoomId: " + RoomId); var room = await RuntimeCache.CurrentHomeServer.GetRoom(RoomId); MessagesResponse? msgs = null; - do - { + do { msgs = await room.GetMessagesAsync(limit: 250, from: msgs?.End, dir: "b"); Messages.Add(msgs); Console.WriteLine($"Got {msgs.Chunk.Count} messages"); @@ -37,13 +33,11 @@ StateHasChanged(); } while (msgs.End != null); - await base.OnInitializedAsync(); } private StateEventResponse GetProfileEventBefore(StateEventResponse Event) => Events.TakeWhile(x => x != Event).Last(e => e.Type == "m.room.member" && e.StateKey == Event.Sender); - private Type ComponentType(StateEventResponse Event) => Event.Type switch { "m.room.message" => typeof(TimelineMessageItem), "m.room.member" => typeof(TimelineMemberItem), diff --git a/MatrixRoomUtils.Web/Pages/RoomState/RoomStateEditorPage.razor b/MatrixRoomUtils.Web/Pages/RoomState/RoomStateEditorPage.razor index 3037dcc..74f4f92 100644 --- a/MatrixRoomUtils.Web/Pages/RoomState/RoomStateEditorPage.razor +++ b/MatrixRoomUtils.Web/Pages/RoomState/RoomStateEditorPage.razor @@ -12,8 +12,7 @@
    - @foreach (var stateEvent in FilteredEvents.Where(x => x.StateKey != "").Select(x => x.StateKey).Distinct().OrderBy(x => x)) - { + @foreach (var stateEvent in FilteredEvents.Where(x => x.StateKey != "").Select(x => x.StateKey).Distinct().OrderBy(x => x)) { Console.WriteLine(stateEvent); } @@ -21,8 +20,7 @@
    - @foreach (var stateEvent in FilteredEvents.Where(x => x.StateKey != shownStateKey).Select(x => x.Type).Distinct().OrderBy(x => x)) - { + @foreach (var stateEvent in FilteredEvents.Where(x => x.StateKey != shownStateKey).Select(x => x.Type).Distinct().OrderBy(x => x)) { } @@ -45,12 +43,10 @@ public List Events { get; set; } = new(); public string status = ""; - protected override async Task OnInitializedAsync() - { + protected override async Task OnInitializedAsync() { await LocalStorageWrapper.LoadFromLocalStorage(LocalStorage); await base.OnInitializedAsync(); - if (RuntimeCache.CurrentHomeServer != null) - { + if (RuntimeCache.CurrentHomeServer != null) { NavigationManager.NavigateTo("/Login"); return; } @@ -61,34 +57,29 @@ private DateTime _lastUpdate = DateTime.Now; - private async Task LoadStatesAsync() - { - int StateLoaded = 0; + private async Task LoadStatesAsync() { + var StateLoaded = 0; using var client = new HttpClient(); - //TODO: can this be improved? + //TODO: can this be improved? client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", RuntimeCache.CurrentHomeServer.AccessToken); var response = await client.GetAsync($"{RuntimeCache.CurrentHomeServer.FullHomeServerDomain}/_matrix/client/r0/rooms/{RoomId}/state"); // var response = await client.GetAsync($"http://localhost:5117/matrix-hq-state.json"); //var _events = await response.Content.ReadFromJsonAsync>(); var _data = await response.Content.ReadAsStreamAsync(); var __events = JsonSerializer.DeserializeAsyncEnumerable(_data); - await foreach (var _ev in __events) - { - var e = new StateEventResponse() - { + await foreach (var _ev in __events) { + var e = new StateEventResponse { Type = _ev.Type, StateKey = _ev.StateKey, OriginServerTs = _ev.OriginServerTs, Content = _ev.Content }; Events.Add(e); - if (string.IsNullOrEmpty(e.StateKey)) - { + if (string.IsNullOrEmpty(e.StateKey)) { FilteredEvents.Add(e); } StateLoaded++; - if ((DateTime.Now - _lastUpdate).TotalMilliseconds > 100) - { + if ((DateTime.Now - _lastUpdate).TotalMilliseconds > 100) { _lastUpdate = DateTime.Now; status = $"Loaded {StateLoaded} state events"; StateHasChanged(); @@ -99,8 +90,7 @@ StateHasChanged(); } - private async Task RebuildFilteredData() - { + private async Task RebuildFilteredData() { status = "Rebuilding filtered data..."; StateHasChanged(); await Task.Delay(1); @@ -112,16 +102,14 @@ StateHasChanged(); await Task.Delay(1); FilteredEvents = _FilteredEvents; - - if(_shownType != null) + + if (_shownType != null) shownEventJson = _FilteredEvents.Where(x => x.Type == _shownType).First().Content.ToJson(indent: true, ignoreNull: true); - + StateHasChanged(); } - - public struct PreRenderedStateEvent - { + public struct PreRenderedStateEvent { public string content { get; set; } public long origin_server_ts { get; set; } public string state_key { get; set; } @@ -132,11 +120,9 @@ // public string ReplacesState { get; set; } } - public bool ShowMembershipEvents - { + public bool ShowMembershipEvents { get => _showMembershipEvents; - set - { + set { _showMembershipEvents = value; RebuildFilteredData(); } @@ -146,21 +132,17 @@ private string _shownStateKey; private string _shownType; - private string shownStateKey - { + private string shownStateKey { get => _shownStateKey; - set - { + set { _shownStateKey = value; RebuildFilteredData(); } } - private string shownType - { + private string shownType { get => _shownType; - set - { + set { _shownType = value; RebuildFilteredData(); } diff --git a/MatrixRoomUtils.Web/Pages/RoomState/RoomStateRoomList.razor b/MatrixRoomUtils.Web/Pages/RoomState/RoomStateRoomList.razor index c654b13..82b5d75 100644 --- a/MatrixRoomUtils.Web/Pages/RoomState/RoomStateRoomList.razor +++ b/MatrixRoomUtils.Web/Pages/RoomState/RoomStateRoomList.razor @@ -3,16 +3,15 @@ @inject NavigationManager NavigationManager

    Room state viewer - Room list


    -@if (Rooms.Count == 0) -{ +@if (Rooms.Count == 0) {

    You are not in any rooms!

    @*

    Loading progress: @checkedRoomCount/@totalRoomCount

    *@ } -else -{ - @foreach (var room in Rooms) - { - +else { + @foreach (var room in Rooms) { + + + }
    } @@ -21,16 +20,16 @@ else @code { public List Rooms { get; set; } = new(); - protected override async Task OnInitializedAsync() - { + + protected override async Task OnInitializedAsync() { await LocalStorageWrapper.LoadFromLocalStorage(LocalStorage); await base.OnInitializedAsync(); - if (RuntimeCache.CurrentHomeServer == null) - { + if (RuntimeCache.CurrentHomeServer == null) { NavigationManager.NavigateTo("/Login"); return; } - Rooms = (await RuntimeCache.CurrentHomeServer.GetJoinedRooms()).Select(x=>x.RoomId).ToList(); + Rooms = (await RuntimeCache.CurrentHomeServer.GetJoinedRooms()).Select(x => x.RoomId).ToList(); Console.WriteLine("Fetched joined rooms!"); } -} \ No newline at end of file + +} \ No newline at end of file diff --git a/MatrixRoomUtils.Web/Pages/RoomState/RoomStateViewerPage.razor b/MatrixRoomUtils.Web/Pages/RoomState/RoomStateViewerPage.razor index c7f9f3c..bfd4d10 100644 --- a/MatrixRoomUtils.Web/Pages/RoomState/RoomStateViewerPage.razor +++ b/MatrixRoomUtils.Web/Pages/RoomState/RoomStateViewerPage.razor @@ -1,7 +1,7 @@ @page "/RoomStateViewer/{RoomId}" +@using MatrixRoomUtils.Core.Extensions @using System.Net.Http.Headers @using System.Text.Json -@using MatrixRoomUtils.Core.Extensions @inject ILocalStorageService LocalStorage @inject NavigationManager NavigationManager

    Room state viewer - Viewing @RoomId

    @@ -19,8 +19,7 @@
    @stateEvent.type @@ -31,8 +30,7 @@
    -@foreach (var group in FilteredEvents.GroupBy(x => x.state_key).OrderBy(x => x.Key).Where(x => x.Key != "")) -{ +@foreach (var group in FilteredEvents.GroupBy(x => x.state_key).OrderBy(x => x.Key).Where(x => x.Key != "")) {
    @group.Key @@ -43,8 +41,7 @@ - @foreach (var stateEvent in group.OrderBy(x => x.origin_server_ts)) - { + @foreach (var stateEvent in group.OrderBy(x => x.origin_server_ts)) {
    @stateEvent.type @@ -72,12 +69,10 @@ public List Events { get; set; } = new(); public string status = ""; - protected override async Task OnInitializedAsync() - { + protected override async Task OnInitializedAsync() { await LocalStorageWrapper.LoadFromLocalStorage(LocalStorage); await base.OnInitializedAsync(); - if (RuntimeCache.CurrentHomeServer == null) - { + if (RuntimeCache.CurrentHomeServer == null) { NavigationManager.NavigateTo("/Login"); return; } @@ -85,56 +80,50 @@ await LoadStatesAsync(); Console.WriteLine("Policy list editor initialized!"); } + private DateTime _lastUpdate = DateTime.Now; - private async Task LoadStatesAsync() - { - int StateLoaded = 0; - //TODO: can we improve this? + private async Task LoadStatesAsync() { + var StateLoaded = 0; + //TODO: can we improve this? using var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", RuntimeCache.CurrentHomeServer.AccessToken); - var response = await client.GetAsync($"{RuntimeCache.CurrentHomeServer.FullHomeServerDomain}/_matrix/client/r0/rooms/{RoomId}/state"); - // var response = await client.GetAsync($"http://localhost:5117/matrix-hq-state.json"); + var response = await client.GetAsync($"{RuntimeCache.CurrentHomeServer.FullHomeServerDomain}/_matrix/client/r0/rooms/{RoomId}/state"); + // var response = await client.GetAsync($"http://localhost:5117/matrix-hq-state.json"); //var _events = await response.Content.ReadFromJsonAsync>(); var _data = await response.Content.ReadAsStreamAsync(); var __events = JsonSerializer.DeserializeAsyncEnumerable(_data); - await foreach (var _ev in __events) - { - var e = new PreRenderedStateEvent() - { + await foreach (var _ev in __events) { + var e = new PreRenderedStateEvent { type = _ev.type, state_key = _ev.state_key, origin_server_ts = _ev.origin_server_ts, - content = _ev.content.ToJson(indent: true, ignoreNull: true), + content = _ev.content.ToJson(true, true) }; Events.Add(e); - if (string.IsNullOrEmpty(e.state_key)) - { + if (string.IsNullOrEmpty(e.state_key)) { FilteredEvents.Add(e); } StateLoaded++; - if ((DateTime.Now - _lastUpdate).TotalMilliseconds > 100) - { + if ((DateTime.Now - _lastUpdate).TotalMilliseconds > 100) { _lastUpdate = DateTime.Now; status = $"Loaded {StateLoaded} state events"; StateHasChanged(); await Task.Delay(0); } - } StateHasChanged(); } - private async Task RebuildFilteredData() - { + private async Task RebuildFilteredData() { status = "Rebuilding filtered data..."; StateHasChanged(); await Task.Delay(1); var _FilteredEvents = Events; if (!ShowMembershipEvents) _FilteredEvents = _FilteredEvents.Where(x => x.type != "m.room.member").ToList(); - + status = "Done, rerendering!"; StateHasChanged(); await Task.Delay(1); @@ -142,9 +131,7 @@ StateHasChanged(); } - - public struct PreRenderedStateEvent - { + public struct PreRenderedStateEvent { public string content { get; set; } public long origin_server_ts { get; set; } public string state_key { get; set; } @@ -155,11 +142,9 @@ // public string ReplacesState { get; set; } } - public bool ShowMembershipEvents - { + public bool ShowMembershipEvents { get => _showMembershipEvents; - set - { + set { _showMembershipEvents = value; RebuildFilteredData(); } -- cgit 1.5.1