From fc749b3e57098740377e6eabd5d010d133256fa5 Mon Sep 17 00:00:00 2001 From: TheArcaneBrony Date: Tue, 13 Jun 2023 01:49:10 +0200 Subject: Improved many features --- MatrixRoomUtils.Core/AuthenticatedHomeServer.cs | 63 +++++++++++++--- MatrixRoomUtils.Core/Interfaces/IHomeServer.cs | 2 +- .../Responses/Admin/AdminRoomListingResult.cs | 66 +++++++++++++++++ MatrixRoomUtils.Core/Responses/ProfileResponse.cs | 2 +- .../Responses/StateEventResponse.cs | 26 ++++--- MatrixRoomUtils.Core/Room.cs | 27 +++++++ MatrixRoomUtils.Core/RuntimeCache.cs | 50 +++++++------ .../StateEventTypes/PolicyRuleStateEventData.cs | 2 +- .../MatrixRoomUtils.Web.Server.csproj | 1 - MatrixRoomUtils.Web/Classes/LocalStorageWrapper.cs | 1 + MatrixRoomUtils.Web/MatrixRoomUtils.Web.csproj | 4 + MatrixRoomUtils.Web/Pages/DevOptions.razor | 7 +- MatrixRoomUtils.Web/Pages/HSAdmin/RoomQuery.razor | 86 ++++++++++++++++++++++ .../Pages/PolicyList/PolicyListEditorPage.razor | 2 +- .../Pages/RoomManager/RoomManager.razor | 1 - .../Pages/RoomManager/RoomManagerSpace.razor | 13 +++- .../Pages/RoomManager/RoomManagerTimeline.razor | 59 +++++++++++++++ .../Shared/IndexComponents/IndexUserItem.razor | 2 +- MatrixRoomUtils.Web/Shared/InlineUserItem.razor | 63 ++++++++++++++++ MatrixRoomUtils.Web/Shared/RoomListItem.razor | 27 +++---- MatrixRoomUtils.Web/Shared/RoomListItem.razor.css | 10 +++ .../TimelineComponents/TimelineMemberItem.razor | 42 +++++++++++ .../TimelineComponents/TimelineMessageItem.razor | 11 +++ .../TimelineComponents/TimelineUnknownItem.razor | 21 ++++++ MatrixRoomUtils.Web/Shared/UserListItem.razor | 4 +- 25 files changed, 524 insertions(+), 68 deletions(-) create mode 100644 MatrixRoomUtils.Core/Responses/Admin/AdminRoomListingResult.cs create mode 100644 MatrixRoomUtils.Web/Pages/HSAdmin/RoomQuery.razor create mode 100644 MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerTimeline.razor create mode 100644 MatrixRoomUtils.Web/Shared/InlineUserItem.razor create mode 100644 MatrixRoomUtils.Web/Shared/RoomListItem.razor.css create mode 100644 MatrixRoomUtils.Web/Shared/TimelineComponents/TimelineMemberItem.razor create mode 100644 MatrixRoomUtils.Web/Shared/TimelineComponents/TimelineMessageItem.razor create mode 100644 MatrixRoomUtils.Web/Shared/TimelineComponents/TimelineUnknownItem.razor diff --git a/MatrixRoomUtils.Core/AuthenticatedHomeServer.cs b/MatrixRoomUtils.Core/AuthenticatedHomeServer.cs index be085c1..368aa20 100644 --- a/MatrixRoomUtils.Core/AuthenticatedHomeServer.cs +++ b/MatrixRoomUtils.Core/AuthenticatedHomeServer.cs @@ -2,8 +2,10 @@ using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Nodes; +using MatrixRoomUtils.Core.Extensions; using MatrixRoomUtils.Core.Interfaces; using MatrixRoomUtils.Core.Responses; +using MatrixRoomUtils.Core.Responses.Admin; namespace MatrixRoomUtils.Core; @@ -32,7 +34,6 @@ public class AuthenticatedHomeServer : IHomeServer return this; } - public async Task GetRoom(string roomId) { @@ -48,19 +49,18 @@ public class AuthenticatedHomeServer : IHomeServer Console.WriteLine($"Failed to get rooms: {await roomQuery.Content.ReadAsStringAsync()}"); throw new InvalidDataException($"Failed to get rooms: {await roomQuery.Content.ReadAsStringAsync()}"); } - var roomsJson = await roomQuery.Content.ReadFromJsonAsync(); foreach (var room in roomsJson.GetProperty("joined_rooms").EnumerateArray()) { rooms.Add(new Room(_httpClient, room.GetString())); } - + Console.WriteLine($"Fetched {rooms.Count} rooms"); return rooms; } - + public async Task UploadFile(string fileName, Stream fileStream, string contentType = "application/octet-stream") { var res = await _httpClient.PostAsync($"/_matrix/media/r0/upload?filename={fileName}", new StreamContent(fileStream)); @@ -69,11 +69,11 @@ public class AuthenticatedHomeServer : IHomeServer Console.WriteLine($"Failed to upload file: {await res.Content.ReadAsStringAsync()}"); throw new InvalidDataException($"Failed to upload file: {await res.Content.ReadAsStringAsync()}"); } + var resJson = await res.Content.ReadFromJsonAsync(); return resJson.GetProperty("content_uri").GetString()!; } - - + public async Task CreateRoom(CreateRoomRequest creationEvent) { var res = await _httpClient.PostAsJsonAsync("/_matrix/client/r0/createRoom", creationEvent); @@ -83,11 +83,9 @@ public class AuthenticatedHomeServer : IHomeServer throw new InvalidDataException($"Failed to create room: {await res.Content.ReadAsStringAsync()}"); } - return await GetRoom((await res.Content.ReadFromJsonAsync())!["room_id"]!.ToString()!); + return await GetRoom((await res.Content.ReadFromJsonAsync())!["room_id"]!.ToString()); } - - - + public class HomeserverAdminApi { private readonly AuthenticatedHomeServer _authenticatedHomeServer; @@ -96,6 +94,47 @@ public class AuthenticatedHomeServer : IHomeServer { _authenticatedHomeServer = authenticatedHomeServer; } - } -} + public async IAsyncEnumerable SearchRoomsAsync(int limit = int.MaxValue, string orderBy = "name", string dir = "f", string? searchTerm = null, string? contentSearch = null) + { + AdminRoomListingResult? res = null; + int i = 0; + int? totalRooms = null; + do + { + var url = $"/_synapse/admin/v1/rooms?limit={Math.Min(limit, 100)}&dir={dir}&order_by={orderBy}"; + if (!string.IsNullOrEmpty(searchTerm)) + { + url += $"&search_term={searchTerm}"; + } + + if (res?.NextBatch != null) + { + url += $"&from={res.NextBatch}"; + } + Console.WriteLine($"--- ADMIN Querying Room List with URL: {url} - Already have {i} items... ---"); + + res = await _authenticatedHomeServer._httpClient.GetFromJsonAsync(url); + totalRooms ??= res?.TotalRooms; + Console.WriteLine(res.ToJson(indent:false)); + foreach (var room in res.Rooms) + { + if (contentSearch != null && !string.IsNullOrEmpty(contentSearch) && + !( + room.Name?.Contains(contentSearch, StringComparison.InvariantCultureIgnoreCase) == true || + room.CanonicalAlias?.Contains(contentSearch, StringComparison.InvariantCultureIgnoreCase) == true || + room.Creator?.Contains(contentSearch, StringComparison.InvariantCultureIgnoreCase) == true + ) + ) + { + totalRooms--; + continue; + } + + i++; + yield return room; + } + } while (i < Math.Min(limit, totalRooms ?? limit)); + } + } +} \ No newline at end of file diff --git a/MatrixRoomUtils.Core/Interfaces/IHomeServer.cs b/MatrixRoomUtils.Core/Interfaces/IHomeServer.cs index bae55e7..3ae1355 100644 --- a/MatrixRoomUtils.Core/Interfaces/IHomeServer.cs +++ b/MatrixRoomUtils.Core/Interfaces/IHomeServer.cs @@ -108,7 +108,7 @@ public class IHomeServer _profileCache[mxid] = profile; return profile; } - public string ResolveMediaUri(string mxc) + public string? ResolveMediaUri(string mxc) { return mxc.Replace("mxc://", $"{FullHomeServerDomain}/_matrix/media/r0/download/"); } diff --git a/MatrixRoomUtils.Core/Responses/Admin/AdminRoomListingResult.cs b/MatrixRoomUtils.Core/Responses/Admin/AdminRoomListingResult.cs new file mode 100644 index 0000000..8ec0e4f --- /dev/null +++ b/MatrixRoomUtils.Core/Responses/Admin/AdminRoomListingResult.cs @@ -0,0 +1,66 @@ +using System.Text.Json.Serialization; + +namespace MatrixRoomUtils.Core.Responses.Admin; + +public class AdminRoomListingResult +{ + [JsonPropertyName("offset")] + public int Offset { get; set; } + + [JsonPropertyName("total_rooms")] + public int TotalRooms { get; set; } + + [JsonPropertyName("next_batch")] + public int? NextBatch { get; set; } + + [JsonPropertyName("prev_batch")] + public int? PrevBatch { get; set; } + + [JsonPropertyName("rooms")] + public List Rooms { get; set; } = new(); + + public class AdminRoomListingResultRoom + { + [JsonPropertyName("room_id")] + public string RoomId { get; set; } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("canonical_alias")] + public string CanonicalAlias { get; set; } + + [JsonPropertyName("joined_members")] + public int JoinedMembers { get; set; } + + [JsonPropertyName("joined_local_members")] + public int JoinedLocalMembers { get; set; } + + [JsonPropertyName("version")] + public string Version { get; set; } + + [JsonPropertyName("creator")] + public string Creator { get; set; } + + [JsonPropertyName("encryption")] + public string Encryption { get; set; } + + [JsonPropertyName("federatable")] + public bool Federatable { get; set; } + + [JsonPropertyName("public")] + public bool Public { get; set; } + + [JsonPropertyName("join_rules")] + public string JoinRules { get; set; } + + [JsonPropertyName("guest_access")] + public string GuestAccess { get; set; } + + [JsonPropertyName("history_visibility")] + public string HistoryVisibility { get; set; } + + [JsonPropertyName("state_events")] + public int StateEvents { get; set; } + } +} \ No newline at end of file diff --git a/MatrixRoomUtils.Core/Responses/ProfileResponse.cs b/MatrixRoomUtils.Core/Responses/ProfileResponse.cs index f8026cb..2c0b679 100644 --- a/MatrixRoomUtils.Core/Responses/ProfileResponse.cs +++ b/MatrixRoomUtils.Core/Responses/ProfileResponse.cs @@ -7,5 +7,5 @@ public class ProfileResponse [JsonPropertyName("avatar_url")] public string? AvatarUrl { get; set; } = ""; [JsonPropertyName("displayname")] - public string DisplayName { get; set; } = ""; + public string? DisplayName { get; set; } = ""; } \ No newline at end of file diff --git a/MatrixRoomUtils.Core/Responses/StateEventResponse.cs b/MatrixRoomUtils.Core/Responses/StateEventResponse.cs index 1af3e1f..670c121 100644 --- a/MatrixRoomUtils.Core/Responses/StateEventResponse.cs +++ b/MatrixRoomUtils.Core/Responses/StateEventResponse.cs @@ -2,22 +2,16 @@ using System.Text.Json.Serialization; namespace MatrixRoomUtils.Core; -public class StateEventResponse +public class StateEventResponse : StateEvent { - [JsonPropertyName("content")] - public dynamic Content { get; set; } [JsonPropertyName("origin_server_ts")] - public long OriginServerTs { get; set; } + public ulong OriginServerTs { get; set; } [JsonPropertyName("room_id")] public string RoomId { get; set; } [JsonPropertyName("sender")] public string Sender { get; set; } - [JsonPropertyName("state_key")] - public string StateKey { get; set; } - [JsonPropertyName("type")] - public string Type { get; set; } [JsonPropertyName("unsigned")] - public dynamic Unsigned { get; set; } + public UnsignedData? Unsigned { get; set; } [JsonPropertyName("event_id")] public string EventId { get; set; } [JsonPropertyName("user_id")] @@ -26,6 +20,20 @@ public class StateEventResponse public string ReplacesState { get; set; } [JsonPropertyName("prev_content")] public dynamic PrevContent { get; set; } + + + public class UnsignedData + { + [JsonPropertyName("age")] + public ulong Age { get; set; } + [JsonPropertyName("prev_content")] + public dynamic? PrevContent { get; set; } + [JsonPropertyName("redacted_because")] + public dynamic? RedactedBecause { get; set; } + [JsonPropertyName("transaction_id")] + public string? TransactionId { get; set; } + + } } public class StateEventResponse : StateEventResponse where T : class diff --git a/MatrixRoomUtils.Core/Room.cs b/MatrixRoomUtils.Core/Room.cs index 73a2bc5..f228271 100644 --- a/MatrixRoomUtils.Core/Room.cs +++ b/MatrixRoomUtils.Core/Room.cs @@ -42,6 +42,21 @@ public class Room if (res == null) return default; return res.Value.Deserialize(); } + + public async Task GetMessagesAsync(string from = "", int limit = 10, string dir = "b", string filter = "") + { + var url = $"/_matrix/client/r0/rooms/{RoomId}/messages?from={from}&limit={limit}&dir={dir}"; + if (!string.IsNullOrEmpty(filter)) url += $"&filter={filter}"; + var res = await _httpClient.GetAsync(url); + if (!res.IsSuccessStatusCode) + { + Console.WriteLine($"Failed to get messages for {RoomId} - got status: {res.StatusCode}"); + throw new Exception($"Failed to get messages for {RoomId} - got status: {res.StatusCode}"); + } + + var result = await res.Content.ReadFromJsonAsync(); + return result ?? new MessagesResponse(); + } public async Task GetNameAsync() { @@ -148,6 +163,18 @@ public class Room } } +public class MessagesResponse +{ + [JsonPropertyName("start")] + public string Start { get; set; } + [JsonPropertyName("end")] + public string? End { get; set; } + [JsonPropertyName("chunk")] + public List Chunk { get; set; } = new(); + [JsonPropertyName("state")] + public List State { get; set; } = new(); +} + public class CreateEvent { [JsonPropertyName("creator")] public string Creator { get; set; } diff --git a/MatrixRoomUtils.Core/RuntimeCache.cs b/MatrixRoomUtils.Core/RuntimeCache.cs index 25b3682..4f73341 100644 --- a/MatrixRoomUtils.Core/RuntimeCache.cs +++ b/MatrixRoomUtils.Core/RuntimeCache.cs @@ -14,38 +14,41 @@ public class RuntimeCache // public static Dictionary ProfileCache { get; set; } = new(); public static Dictionary> GenericResponseCache { get; set; } = new(); - - public static Action Save { get; set; } = () => - { - Console.WriteLine("RuntimeCache.Save() was called, but no callback was set!"); - }; - public static Action SaveObject { get; set; } = (key, value) => - { - Console.WriteLine($"RuntimeCache.SaveObject({key}, {value}) was called, but no callback was set!"); - }; + + public static Action Save { get; set; } = () => { Console.WriteLine("RuntimeCache.Save() was called, but no callback was set!"); }; + public static Action SaveObject { get; set; } = (key, value) => { Console.WriteLine($"RuntimeCache.SaveObject({key}, {value}) was called, but no callback was set!"); }; + public static Action RemoveObject { get; set; } = key => { Console.WriteLine($"RuntimeCache.RemoveObject({key}) was called, but no callback was set!"); }; static RuntimeCache() { Task.Run(async () => { - while (true) + while(true) { await Task.Delay(1000); - foreach (var (key, value) in RuntimeCache.GenericResponseCache) + foreach (var (key, value) in GenericResponseCache) { - SaveObject("rory.matrixroomutils.generic_cache:" + key, value); + if (value.Cache.Any()) + SaveObject("rory.matrixroomutils.generic_cache:" + key, value); + else + { + RemoveObject("rory.matrixroomutils.generic_cache:" + key); + } } } }); } } - public class UserInfo { public ProfileResponse Profile { get; set; } = new(); public LoginResponse LoginResponse { get; set; } - public string AccessToken { get => LoginResponse.AccessToken; } + + public string AccessToken + { + get => LoginResponse.AccessToken; + } } public class HomeServerResolutionResult @@ -53,10 +56,12 @@ public class HomeServerResolutionResult public string Result { get; set; } public DateTime ResolutionTime { get; set; } } + public class ObjectCache where T : class { public Dictionary> Cache { get; set; } = new(); public string Name { get; set; } = null!; + public GenericResult this[string key] { get @@ -65,11 +70,11 @@ public class ObjectCache where T : class { // Console.WriteLine($"cache.get({key}): hit"); // Console.WriteLine($"Found item in cache: {key} - {Cache[key].Result.ToJson(indent: false)}"); - if(Cache[key].ExpiryTime < DateTime.Now) + if (Cache[key].ExpiryTime < DateTime.Now) Console.WriteLine($"WARNING: item {key} in cache {Name} expired at {Cache[key].ExpiryTime}:\n{Cache[key].Result.ToJson(indent: false)}"); return Cache[key]; - } + Console.WriteLine($"cache.get({key}): miss"); return null; } @@ -82,19 +87,19 @@ public class ObjectCache where T : class // Console.Error.WriteLine("Full cache: " + Cache.ToJson()); } } - + public ObjectCache() { //expiry timer Task.Run(async () => { - while (true) + while (Cache.Any()) { await Task.Delay(1000); foreach (var x in Cache.Where(x => x.Value.ExpiryTime < DateTime.Now).OrderBy(x => x.Value.ExpiryTime).Take(15).ToList()) { // Console.WriteLine($"Removing {x.Key} from cache"); - Cache.Remove(x.Key); + Cache.Remove(x.Key); } //RuntimeCache.SaveObject("rory.matrixroomutils.generic_cache:" + Name, this); } @@ -103,19 +108,20 @@ public class ObjectCache where T : class public bool ContainsKey(string key) => Cache.ContainsKey(key); } + public class GenericResult { public T? Result { get; set; } public DateTime? ExpiryTime { get; set; } = DateTime.Now; - + public GenericResult() { //expiry timer - } + public GenericResult(T? result, DateTime? expiryTime = null) : this() { Result = result; ExpiryTime = expiryTime; } -} +} \ No newline at end of file diff --git a/MatrixRoomUtils.Core/StateEventTypes/PolicyRuleStateEventData.cs b/MatrixRoomUtils.Core/StateEventTypes/PolicyRuleStateEventData.cs index 108bb4d..a927ace 100644 --- a/MatrixRoomUtils.Core/StateEventTypes/PolicyRuleStateEventData.cs +++ b/MatrixRoomUtils.Core/StateEventTypes/PolicyRuleStateEventData.cs @@ -8,7 +8,7 @@ public class PolicyRuleStateEventData /// Entity this ban applies to, can use * and ? as globs. /// [JsonPropertyName("entity")] - public string? Entity { get; set; } + public string Entity { get; set; } /// /// Reason this user is banned /// diff --git a/MatrixRoomUtils.Web.Server/MatrixRoomUtils.Web.Server.csproj b/MatrixRoomUtils.Web.Server/MatrixRoomUtils.Web.Server.csproj index 014df56..71c3d08 100644 --- a/MatrixRoomUtils.Web.Server/MatrixRoomUtils.Web.Server.csproj +++ b/MatrixRoomUtils.Web.Server/MatrixRoomUtils.Web.Server.csproj @@ -12,7 +12,6 @@ - diff --git a/MatrixRoomUtils.Web/Classes/LocalStorageWrapper.cs b/MatrixRoomUtils.Web/Classes/LocalStorageWrapper.cs index e21b363..f70572b 100644 --- a/MatrixRoomUtils.Web/Classes/LocalStorageWrapper.cs +++ b/MatrixRoomUtils.Web/Classes/LocalStorageWrapper.cs @@ -16,6 +16,7 @@ public partial class LocalStorageWrapper RuntimeCache.Save = Save; RuntimeCache.SaveObject = async (key, obj) => await localStorage.SetItemAsync(key, obj); + RuntimeCache.RemoveObject = async (key) => await localStorage.RemoveItemAsync(key); if (RuntimeCache.LastUsedToken != null) { Console.WriteLine($"Access token is not null, creating authenticated home server"); diff --git a/MatrixRoomUtils.Web/MatrixRoomUtils.Web.csproj b/MatrixRoomUtils.Web/MatrixRoomUtils.Web.csproj index 12555c3..cf6ce87 100644 --- a/MatrixRoomUtils.Web/MatrixRoomUtils.Web.csproj +++ b/MatrixRoomUtils.Web/MatrixRoomUtils.Web.csproj @@ -15,5 +15,9 @@ + + + + diff --git a/MatrixRoomUtils.Web/Pages/DevOptions.razor b/MatrixRoomUtils.Web/Pages/DevOptions.razor index c2894b3..3ca86b4 100644 --- a/MatrixRoomUtils.Web/Pages/DevOptions.razor +++ b/MatrixRoomUtils.Web/Pages/DevOptions.razor @@ -59,7 +59,12 @@ protected async Task DropCaches() { - RuntimeCache.GenericResponseCache.Clear(); + foreach (var (key, value) in RuntimeCache.GenericResponseCache) + { + value.Cache.Clear(); + } + + //RuntimeCache.GenericResponseCache.Clear(); RuntimeCache.HomeserverResolutionCache.Clear(); await LocalStorageWrapper.SaveCacheToLocalStorage(LocalStorage); } diff --git a/MatrixRoomUtils.Web/Pages/HSAdmin/RoomQuery.razor b/MatrixRoomUtils.Web/Pages/HSAdmin/RoomQuery.razor new file mode 100644 index 0000000..109ad7d --- /dev/null +++ b/MatrixRoomUtils.Web/Pages/HSAdmin/RoomQuery.razor @@ -0,0 +1,86 @@ +@page "/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) +{ +
+ +

@res.CanonicalAlias, created by

+

@res.StateEvents state events

+

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

+
+} + +@code { + + [Parameter, SupplyParameterFromQuery(Name = "order_by")] + public string? OrderBy { get; set; } + + [Parameter, SupplyParameterFromQuery(Name = "search_term")] + public string SearchTerm { get; set; } + + [Parameter, SupplyParameterFromQuery(Name = "content_search_term")] + public string ContentSearchTerm { get; set; } + + [Parameter, SupplyParameterFromQuery(Name = "ascending")] + public bool Ascending { get; set; } + + public List Results { get; set; } = new(); + + protected override async Task OnParametersSetAsync() + { + if(Ascending == null) + Ascending = true; + OrderBy ??= "name"; + } + + 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()) + { + var room = searchRooms.Current; + Console.WriteLine("Hit: " + room.ToJson(indent: false)); + Results.Add(room); + } + } + + private Dictionary validOrderBy = new Dictionary() + { + { "name", "Room name" }, + { "canonical_alias", "Main alias address" }, + { "joined_members", "Number of members (reversed)" }, + { "joined_local_members", "Number of local members (reversed)" }, + { "version", "Room version" }, + { "creator", "Creator of the room" }, + { "encryption", "End-to-end encryption algorithm" }, + { "federatable", "Is room federated" }, + { "public", "Visibility in room list" }, + { "join_rules", "Join rules" }, + { "guest_access", "Guest access" }, + { "history_visibility", "Visibility of history" }, + { "state_events", "Number of state events" }, + }; + +} \ No newline at end of file diff --git a/MatrixRoomUtils.Web/Pages/PolicyList/PolicyListEditorPage.razor b/MatrixRoomUtils.Web/Pages/PolicyList/PolicyListEditorPage.razor index 4b9c2f6..bf03ee3 100644 --- a/MatrixRoomUtils.Web/Pages/PolicyList/PolicyListEditorPage.razor +++ b/MatrixRoomUtils.Web/Pages/PolicyList/PolicyListEditorPage.razor @@ -200,7 +200,7 @@ else private bool _enableAvatars = false; - static Dictionary avatars = new Dictionary(); + static Dictionary avatars = new Dictionary(); static Dictionary servers = new Dictionary(); public static List> PolicyEvents { get; set; } = new(); diff --git a/MatrixRoomUtils.Web/Pages/RoomManager/RoomManager.razor b/MatrixRoomUtils.Web/Pages/RoomManager/RoomManager.razor index a8b8fd4..5daa97c 100644 --- a/MatrixRoomUtils.Web/Pages/RoomManager/RoomManager.razor +++ b/MatrixRoomUtils.Web/Pages/RoomManager/RoomManager.razor @@ -6,7 +6,6 @@ @if (Rooms.Count == 0) {

You are not in any rooms!

- @*

Loading progress: @checkedRoomCount/@totalRoomCount

*@ } else { diff --git a/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerSpace.razor b/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerSpace.razor index e9d1421..1e7e065 100644 --- a/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerSpace.razor +++ b/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerSpace.razor @@ -29,6 +29,7 @@ private StateEventResponse[] States { get; set; } = Array.Empty>(); private List Rooms { get; set; } = new(); + private List ServersInSpace { get; set; } = new(); protected override async Task OnInitializedAsync() { @@ -37,7 +38,7 @@ var state = await Room.GetStateAsync(""); if (state != null) { - Console.WriteLine(state.Value.ToJson()); + // Console.WriteLine(state.Value.ToJson()); States = state.Value.Deserialize[]>()!; foreach (var stateEvent in States) @@ -52,6 +53,14 @@ Rooms.Add(room); } } + else if (stateEvent.Type == "m.room.member") + { + var serverName = stateEvent.StateKey.Split(':').Last(); + if (!ServersInSpace.Contains(serverName)) + { + ServersInSpace.Add(serverName); + } + } } // if(state.Value.TryGetProperty("Type", out var Type)) @@ -70,7 +79,7 @@ { foreach (var room in Rooms) { - room.JoinAsync(); + room.JoinAsync(ServersInSpace.ToArray()); } } diff --git a/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerTimeline.razor b/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerTimeline.razor new file mode 100644 index 0000000..a8a7fc2 --- /dev/null +++ b/MatrixRoomUtils.Web/Pages/RoomManager/RoomManagerTimeline.razor @@ -0,0 +1,59 @@ +@page "/RoomManager/Timeline/{RoomId}" +@using MatrixRoomUtils.Web.Shared.TimelineComponents +@using MatrixRoomUtils.Core.Extensions +

RoomManagerTimeline

+
+

Loaded @Events.Count events...

+ +@foreach (var evt in Events) +{ +
+ +
+} + +@code { + + [Parameter] + public string RoomId { get; set; } = "invalid!!!!!!"; + + private List Messages { get; set; } = new(); + private List Events { get; set; } = new(); + + 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 + { + msgs = await room.GetMessagesAsync(limit: 250, from: msgs?.End, dir: "b"); + Messages.Add(msgs); + Console.WriteLine($"Got {msgs.Chunk.Count} messages"); + msgs.Chunk.Reverse(); + Events.InsertRange(0, msgs.Chunk); + 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), + _ => typeof(TimelineUnknownItem) + }; + + private Dictionary ComponentParameters(Type ComponentType, StateEventResponse Event) => ComponentType switch { + Type t when t == typeof(TimelineMessageItem) => new Dictionary { { "Event", Event }, { "Events", Events } }, + Type t when t == typeof(TimelineMemberItem) => new Dictionary { { "Event", Event }, { "Events", Events } }, + _ => new Dictionary { { "Event", Event }, { "Events", Events } } + }; + +} \ No newline at end of file diff --git a/MatrixRoomUtils.Web/Shared/IndexComponents/IndexUserItem.razor b/MatrixRoomUtils.Web/Shared/IndexComponents/IndexUserItem.razor index 42f2c09..03a7145 100644 --- a/MatrixRoomUtils.Web/Shared/IndexComponents/IndexUserItem.razor +++ b/MatrixRoomUtils.Web/Shared/IndexComponents/IndexUserItem.razor @@ -24,7 +24,7 @@ [Parameter] public UserInfo User { get; set; } = null!; - private string _avatarUrl { get; set; } + private string? _avatarUrl { get; set; } private int _roomCount { get; set; } = 0; protected override async Task OnInitializedAsync() diff --git a/MatrixRoomUtils.Web/Shared/InlineUserItem.razor b/MatrixRoomUtils.Web/Shared/InlineUserItem.razor new file mode 100644 index 0000000..56131c8 --- /dev/null +++ b/MatrixRoomUtils.Web/Shared/InlineUserItem.razor @@ -0,0 +1,63 @@ +@using MatrixRoomUtils.Core.Responses +
+ + @ProfileName + +
+ @if (ChildContent != null) + { + @ChildContent + } +
+ +
+ +@code { + + [Parameter] + public RenderFragment? ChildContent { get; set; } + + [Parameter] + public ProfileResponse User { get; set; } + + [Parameter] + public string UserId { get; set; } + + [Parameter] + public string? ProfileAvatar { get; set; } = null; + + [Parameter] + public string? ProfileName { get; set; } = null; + + + private static SemaphoreSlim _semaphoreSlim = new(128); + + protected override async Task OnInitializedAsync() + { + await base.OnInitializedAsync(); + await LocalStorageWrapper.LoadFromLocalStorage(LocalStorage); + + await _semaphoreSlim.WaitAsync(); + + var hs = await new AuthenticatedHomeServer(RuntimeCache.CurrentHomeServer.UserId, RuntimeCache.CurrentHomeServer.AccessToken, RuntimeCache.CurrentHomeServer.HomeServerDomain).Configure(); + + if (User == null) + { + if (UserId == null) + { + throw new ArgumentNullException(nameof(UserId)); + } + User = await hs.GetProfile(UserId); + } + else + { + // UserId = User.; + } + + ProfileAvatar ??= RuntimeCache.CurrentHomeServer.ResolveMediaUri(User.AvatarUrl); + ProfileName ??= User.DisplayName; + + _semaphoreSlim.Release(); + } + +} \ No newline at end of file diff --git a/MatrixRoomUtils.Web/Shared/RoomListItem.razor b/MatrixRoomUtils.Web/Shared/RoomListItem.razor index 4990b3c..fb28c3c 100644 --- a/MatrixRoomUtils.Web/Shared/RoomListItem.razor +++ b/MatrixRoomUtils.Web/Shared/RoomListItem.razor @@ -1,11 +1,11 @@ @using MatrixRoomUtils.Core.Authentication @using System.Text.Json @using MatrixRoomUtils.Core.Extensions -
+
@if (ShowOwnProfile) { - - @profileName + + @(profileName ?? "Loading...") -> } @@ -34,10 +34,10 @@ public bool ShowOwnProfile { get; set; } = false; private string roomName { get; set; } = "Loading..."; - private string roomIcon { get; set; } = "/icon-192.png"; + private string? roomIcon { get; set; } = "/icon-192.png"; - private string profileAvatar { get; set; } = "/icon-192.png"; - private string profileName { get; set; } = "Loading..."; + private string? profileAvatar { get; set; } + private string? profileName { get; set; } private bool hasCustomProfileAvatar { get; set; } = false; private bool hasCustomProfileName { get; set; } = false; @@ -53,8 +53,8 @@ await LocalStorageWrapper.LoadFromLocalStorage(LocalStorage); await _semaphoreSlim.WaitAsync(); - - var hs = await new AuthenticatedHomeServer(RuntimeCache.CurrentHomeServer.UserId, RuntimeCache.CurrentHomeServer.AccessToken, RuntimeCache.CurrentHomeServer.HomeServerDomain).Configure(); + + var hs = RuntimeCache.CurrentHomeServer; //await new AuthenticatedHomeServer(RuntimeCache.CurrentHomeServer.UserId, RuntimeCache.CurrentHomeServer.AccessToken, RuntimeCache.CurrentHomeServer.HomeServerDomain).Configure(); if (Room == null) { @@ -69,11 +69,7 @@ RoomId = Room.RoomId; } - roomName = await Room.GetNameAsync(); - if (roomName == null) - { - roomName = "Unnamed room: " + RoomId; - } + roomName = await Room.GetNameAsync() ?? "Unnamed room: " + RoomId; var ce = await Room.GetCreateEventAsync(); if (ce != null) @@ -143,4 +139,9 @@ await LocalStorageWrapper.SaveCacheToLocalStorage(LocalStorage); } + private void Callback(ProgressEventArgs obj) + { + Console.WriteLine("prog: " + obj.ToJson(indent: false)); + } + } \ No newline at end of file diff --git a/MatrixRoomUtils.Web/Shared/RoomListItem.razor.css b/MatrixRoomUtils.Web/Shared/RoomListItem.razor.css new file mode 100644 index 0000000..8b9a9f6 --- /dev/null +++ b/MatrixRoomUtils.Web/Shared/RoomListItem.razor.css @@ -0,0 +1,10 @@ +/*.imageUnloaded {*/ +/* scale: 3;*/ +/* opacity: 0.5;*/ +/* transition: scale 0.5s ease-in-out;*/ +/*}*/ + +.imageLoaded { + opacity: 1; + scale: 1; + } \ No newline at end of file diff --git a/MatrixRoomUtils.Web/Shared/TimelineComponents/TimelineMemberItem.razor b/MatrixRoomUtils.Web/Shared/TimelineComponents/TimelineMemberItem.razor new file mode 100644 index 0000000..3803d38 --- /dev/null +++ b/MatrixRoomUtils.Web/Shared/TimelineComponents/TimelineMemberItem.razor @@ -0,0 +1,42 @@ +@using MatrixRoomUtils.Core.Extensions +@if (Event.ContentAsJsonNode["membership"]!.GetValue() == "ban") +{ + @Event.StateKey was banned +} +else if (Event.ContentAsJsonNode["membership"]!.GetValue() == "invite") +{ + @Event.StateKey was invited +} +else if (Event.ContentAsJsonNode["membership"]!.GetValue() == "join") +{ + @if (Event.ReplacesState != null) + { + @Event.StateKey changed their display name to @(Event.ContentAsJsonNode["displayname"]!.GetValue()) + } + else + { + joined + } +} +else if (Event.ContentAsJsonNode["membership"]!.GetValue() == "leave") +{ + @Event.StateKey left +} +else if (Event.ContentAsJsonNode["membership"]!.GetValue() == "knock") +{ + @Event.StateKey knocked +} +else +{ + @Event.StateKey has an unknown state: +
+        @Event.ToJson()
+    
+} + +@code { + + [Parameter] + public StateEvent Event { get; set; } + +} \ No newline at end of file diff --git a/MatrixRoomUtils.Web/Shared/TimelineComponents/TimelineMessageItem.razor b/MatrixRoomUtils.Web/Shared/TimelineComponents/TimelineMessageItem.razor new file mode 100644 index 0000000..8d688ea --- /dev/null +++ b/MatrixRoomUtils.Web/Shared/TimelineComponents/TimelineMessageItem.razor @@ -0,0 +1,11 @@ +@using MatrixRoomUtils.Core.Extensions +
+    @ObjectExtensions.ToJson(Event.Content, indent: false)
+
+ +@code { + + [Parameter] + public StateEventResponse Event { get; set; } + +} \ No newline at end of file diff --git a/MatrixRoomUtils.Web/Shared/TimelineComponents/TimelineUnknownItem.razor b/MatrixRoomUtils.Web/Shared/TimelineComponents/TimelineUnknownItem.razor new file mode 100644 index 0000000..f78bdc9 --- /dev/null +++ b/MatrixRoomUtils.Web/Shared/TimelineComponents/TimelineUnknownItem.razor @@ -0,0 +1,21 @@ +@using MatrixRoomUtils.Core.Extensions +
+ +
+ + + Unknown event type:
@Event.Type
+
+
+
+           @Event.ToJson()
+        
+
+
+ +@code { + + [Parameter] + public StateEvent Event { get; set; } + +} \ No newline at end of file diff --git a/MatrixRoomUtils.Web/Shared/UserListItem.razor b/MatrixRoomUtils.Web/Shared/UserListItem.razor index ae1fcd1..d357b0d 100644 --- a/MatrixRoomUtils.Web/Shared/UserListItem.razor +++ b/MatrixRoomUtils.Web/Shared/UserListItem.razor @@ -23,8 +23,8 @@ [Parameter] public string UserId { get; set; } - private string profileAvatar { get; set; } = "/icon-192.png"; - private string profileName { get; set; } = "Loading..."; + private string? profileAvatar { get; set; } = "/icon-192.png"; + private string? profileName { get; set; } = "Loading..."; private static SemaphoreSlim _semaphoreSlim = new(128); -- cgit 1.4.1