diff options
author | TheArcaneBrony <myrainbowdash949@gmail.com> | 2023-06-13 01:49:10 +0200 |
---|---|---|
committer | TheArcaneBrony <myrainbowdash949@gmail.com> | 2023-06-13 01:49:10 +0200 |
commit | fc749b3e57098740377e6eabd5d010d133256fa5 (patch) | |
tree | cc97267a3d4222c910769e46bdb37c96c7c31531 | |
parent | unknown changes (diff) | |
download | MatrixUtils-fc749b3e57098740377e6eabd5d010d133256fa5.tar.xz |
Improved many features
25 files changed, 524 insertions, 68 deletions
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<Room> 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<JsonElement>(); 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<string> 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<JsonElement>(); return resJson.GetProperty("content_uri").GetString()!; } - - + public async Task<Room> 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<JsonObject>())!["room_id"]!.ToString()!); + return await GetRoom((await res.Content.ReadFromJsonAsync<JsonObject>())!["room_id"]!.ToString()); } - - - + public class HomeserverAdminApi { private readonly AuthenticatedHomeServer _authenticatedHomeServer; @@ -96,6 +94,47 @@ public class AuthenticatedHomeServer : IHomeServer { _authenticatedHomeServer = authenticatedHomeServer; } - } -} + public async IAsyncEnumerable<AdminRoomListingResult.AdminRoomListingResultRoom> 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<AdminRoomListingResult>(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<AdminRoomListingResultRoom> 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<T> : 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<T>(); } + + public async Task<MessagesResponse> 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<MessagesResponse>(); + return result ?? new MessagesResponse(); + } public async Task<string> 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<StateEventResponse> Chunk { get; set; } = new(); + [JsonPropertyName("state")] + public List<StateEventResponse> 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<string, (DateTime cachedAt, ProfileResponse response)> ProfileCache { get; set; } = new(); public static Dictionary<string, ObjectCache<object>> GenericResponseCache { get; set; } = new(); - - public static Action Save { get; set; } = () => - { - Console.WriteLine("RuntimeCache.Save() was called, but no callback was set!"); - }; - public static Action<string, object> 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<string, object> SaveObject { get; set; } = (key, value) => { Console.WriteLine($"RuntimeCache.SaveObject({key}, {value}) was called, but no callback was set!"); }; + public static Action<string> 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<T> where T : class { public Dictionary<string, GenericResult<T>> Cache { get; set; } = new(); public string Name { get; set; } = null!; + public GenericResult<T> this[string key] { get @@ -65,11 +70,11 @@ public class ObjectCache<T> 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<T> 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<T> where T : class public bool ContainsKey(string key) => Cache.ContainsKey(key); } + public class GenericResult<T> { 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. /// </summary> [JsonPropertyName("entity")] - public string? Entity { get; set; } + public string Entity { get; set; } /// <summary> /// Reason this user is banned /// </summary> 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 @@ <ItemGroup> <ProjectReference Include="..\MatrixRoomUtils.Web\MatrixRoomUtils.Web.csproj" /> - <ProjectReference Include="..\MatrixRoomUtils.Core\MatrixRoomUtils.Core.csproj" /> </ItemGroup> <ItemGroup> 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 @@ <ItemGroup> <ProjectReference Include="..\MatrixRoomUtils.Core\MatrixRoomUtils.Core.csproj" /> </ItemGroup> + + <ItemGroup> + <Folder Include="Shared\TimelineComponents\TimelineMessageComponents" /> + </ItemGroup> </Project> 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 +<h3>Homeserver Administration - Room Query</h3> + +<label>Search name: </label> +<InputText @bind-Value="SearchTerm" /><br/> +<label>Search id/name/creator (slow!): </label> +<InputText @bind-Value="ContentSearchTerm" /><br/> +<label>Order by: </label> +<select @bind="OrderBy"> + @foreach (var item in validOrderBy) + { + <option value="@item.Key">@item.Value</option> + } +</select><br/> +<label>Ascending: </label> +<InputCheckbox @bind-Value="Ascending" /><br/> +<button class="btn btn-primary" @onclick="Search">Search</button> +<br/> + +@foreach (var res in Results) +{ + <div style="background-color: #ffffff11; border-radius: 0.5em; display: block; margin-top: 4px; padding: 4px;"> + <RoomListItem RoomId="@res.RoomId"></RoomListItem> + <p>@res.CanonicalAlias, created by <InlineUserItem UserId="@res.Creator"></InlineUserItem></p> + <p>@res.StateEvents state events</p> + <p>@res.JoinedMembers members, of which @res.JoinedLocalMembers are on this server</p> + </div> +} + +@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<AdminRoomListingResult.AdminRoomListingResultRoom> 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<string, string> validOrderBy = new Dictionary<string, string>() + { + { "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<string, string> avatars = new Dictionary<string, string>(); + static Dictionary<string, string?> avatars = new Dictionary<string, string?>(); static Dictionary<string, RemoteHomeServer> servers = new Dictionary<string, RemoteHomeServer>(); public static List<StateEventResponse<PolicyRuleStateEventData>> 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) { <p>You are not in any rooms!</p> - @* <p>Loading progress: @checkedRoomCount/@totalRoomCount</p> *@ } 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<object>[] States { get; set; } = Array.Empty<StateEventResponse<object>>(); private List<Room> Rooms { get; set; } = new(); + private List<string> 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<StateEventResponse<object>[]>()!; 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 +<h3>RoomManagerTimeline</h3> +<hr/> +<p>Loaded @Events.Count events...</p> + +@foreach (var evt in Events) +{ + <div type="@evt.Type" key="@evt.StateKey" itemid="@evt.EventId"> + <DynamicComponent Type="@ComponentType(evt)" Parameters="@(new Dictionary<string, object> { { "Event", evt }, { "Events", Events } })"></DynamicComponent> + </div> +} + +@code { + + [Parameter] + public string RoomId { get; set; } = "invalid!!!!!!"; + + private List<MessagesResponse> Messages { get; set; } = new(); + private List<StateEventResponse> 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<string, object> ComponentParameters(Type ComponentType, StateEventResponse Event) => ComponentType switch { + Type t when t == typeof(TimelineMessageItem) => new Dictionary<string, object> { { "Event", Event }, { "Events", Events } }, + Type t when t == typeof(TimelineMemberItem) => new Dictionary<string, object> { { "Event", Event }, { "Events", Events } }, + _ => new Dictionary<string, object> { { "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 +<div style="background-color: #ffffff11; border-radius: 0.5em; height: 1em; display: inline-block; vertical-align: middle;" alt="@UserId"> + <img style="@(ChildContent != null ? "vertical-align: baseline;" : "vertical-align: top;") width: 1em; height: 1em; border-radius: 50%;" src="@ProfileAvatar"/> + <span style="position: relative; top: -5px;">@ProfileName</span> + + <div style="display: inline-block;"> + @if (ChildContent != null) + { + @ChildContent + } + </div> + +</div> + +@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 -<div style="background-color: #ffffff11; border-radius: 25px; margin: 8px; width: fit-Content; @(hasDangerousRoomVersion ? "border: red 4px solid;" : hasOldRoomVersion ? "border: #FF0 1px solid;" : "")"> +<div class="roomListItem" style="background-color: #ffffff11; border-radius: 25px; margin: 8px; width: fit-Content; @(hasDangerousRoomVersion ? "border: red 4px solid;" : hasOldRoomVersion ? "border: #FF0 1px solid;" : "")"> @if (ShowOwnProfile) { - <img style="@(ChildContent != null ? "vertical-align: baseline;":"") width: 32px; height: 32px; border-radius: 50%; @(hasCustomProfileAvatar ? "border-color: red; border-width: 3px; border-style: dashed;" : "")" src="@profileAvatar"/> - <span style="vertical-align: middle; margin-right: 8px; border-radius: 75px; @(hasCustomProfileName ? "background-color: red;" : "")">@profileName</span> + <img class="imageUnloaded @(string.IsNullOrWhiteSpace(profileAvatar) ? "" : "imageLoaded")" style="@(ChildContent != null ? "vertical-align: baseline;":"") width: 32px; height: 32px; border-radius: 50%; @(hasCustomProfileAvatar ? "border-color: red; border-width: 3px; border-style: dashed;" : "")" src="@(profileAvatar ?? "/icon-192.png")" @onload="Callback"/> + <span style="vertical-align: middle; margin-right: 8px; border-radius: 75px; @(hasCustomProfileName ? "background-color: red;" : "")">@(profileName ?? "Loading...")</span> <span style="vertical-align: middle; padding-right: 8px; padding-left: 0px;">-></span> } <img style="@(ChildContent != null ? "vertical-align: baseline;":"") width: 32px; height: 32px; border-radius: 50%;" src="@roomIcon"/> @@ -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<string>() == "ban") +{ + <i>@Event.StateKey was banned</i> +} +else if (Event.ContentAsJsonNode["membership"]!.GetValue<string>() == "invite") +{ + <i>@Event.StateKey was invited</i> +} +else if (Event.ContentAsJsonNode["membership"]!.GetValue<string>() == "join") +{ + @if (Event.ReplacesState != null) + { + <i>@Event.StateKey changed their display name to @(Event.ContentAsJsonNode["displayname"]!.GetValue<string>())</i> + } + else + { + <i><InlineUserItem UserId="@Event.StateKey"></InlineUserItem> joined</i> + } +} +else if (Event.ContentAsJsonNode["membership"]!.GetValue<string>() == "leave") +{ + <i>@Event.StateKey left</i> +} +else if (Event.ContentAsJsonNode["membership"]!.GetValue<string>() == "knock") +{ + <i>@Event.StateKey knocked</i> +} +else +{ + <i>@Event.StateKey has an unknown state:</i> + <pre> + @Event.ToJson() + </pre> +} + +@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 +<pre> + @ObjectExtensions.ToJson(Event.Content, indent: false) +</pre> + +@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 +<div> + + <details style="display: inline;"> + <summary> + <i style="color: red;"> + Unknown event type: <pre style="display: inline;">@Event.Type</pre> + </i> + </summary> + <pre> + @Event.ToJson() + </pre> + </details> +</div> + +@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); |