diff options
Diffstat (limited to 'MatrixRoomUtils.Core')
-rw-r--r-- | MatrixRoomUtils.Core/AuthenticatedHomeServer.cs | 63 | ||||
-rw-r--r-- | MatrixRoomUtils.Core/Interfaces/IHomeServer.cs | 2 | ||||
-rw-r--r-- | MatrixRoomUtils.Core/Responses/Admin/AdminRoomListingResult.cs | 66 | ||||
-rw-r--r-- | MatrixRoomUtils.Core/Responses/ProfileResponse.cs | 2 | ||||
-rw-r--r-- | MatrixRoomUtils.Core/Responses/StateEventResponse.cs | 26 | ||||
-rw-r--r-- | MatrixRoomUtils.Core/Room.cs | 27 | ||||
-rw-r--r-- | MatrixRoomUtils.Core/RuntimeCache.cs | 50 | ||||
-rw-r--r-- | MatrixRoomUtils.Core/StateEventTypes/PolicyRuleStateEventData.cs | 2 |
8 files changed, 192 insertions, 46 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> |