diff options
Diffstat (limited to 'MatrixRoomUtils.Core')
-rw-r--r-- | MatrixRoomUtils.Core/Responses/StateEventResponse.cs | 24 | ||||
-rw-r--r-- | MatrixRoomUtils.Core/Room.cs | 123 | ||||
-rw-r--r-- | MatrixRoomUtils.Core/RuntimeCache.cs | 4 |
3 files changed, 49 insertions, 102 deletions
diff --git a/MatrixRoomUtils.Core/Responses/StateEventResponse.cs b/MatrixRoomUtils.Core/Responses/StateEventResponse.cs index d86f546..1af3e1f 100644 --- a/MatrixRoomUtils.Core/Responses/StateEventResponse.cs +++ b/MatrixRoomUtils.Core/Responses/StateEventResponse.cs @@ -4,31 +4,33 @@ namespace MatrixRoomUtils.Core; public class StateEventResponse { - [JsonPropertyName("Content")] + [JsonPropertyName("content")] public dynamic Content { get; set; } [JsonPropertyName("origin_server_ts")] public long OriginServerTs { get; set; } - [JsonPropertyName("RoomId")] + [JsonPropertyName("room_id")] public string RoomId { get; set; } - [JsonPropertyName("Sender")] + [JsonPropertyName("sender")] public string Sender { get; set; } - [JsonPropertyName("StateKey")] + [JsonPropertyName("state_key")] public string StateKey { get; set; } - [JsonPropertyName("Type")] + [JsonPropertyName("type")] public string Type { get; set; } - [JsonPropertyName("Unsigned")] + [JsonPropertyName("unsigned")] public dynamic Unsigned { get; set; } - [JsonPropertyName("EventId")] + [JsonPropertyName("event_id")] public string EventId { get; set; } - [JsonPropertyName("UserId")] + [JsonPropertyName("user_id")] public string UserId { get; set; } - [JsonPropertyName("ReplacesState")] + [JsonPropertyName("replaces_state")] public string ReplacesState { get; set; } - [JsonPropertyName("PrevContent")] + [JsonPropertyName("prev_content")] public dynamic PrevContent { get; set; } } public class StateEventResponse<T> : StateEventResponse where T : class { - public T content { get; set; } + + [JsonPropertyName("content")] + public T Content { get; set; } } \ No newline at end of file diff --git a/MatrixRoomUtils.Core/Room.cs b/MatrixRoomUtils.Core/Room.cs index b96546e..73a2bc5 100644 --- a/MatrixRoomUtils.Core/Room.cs +++ b/MatrixRoomUtils.Core/Room.cs @@ -10,8 +10,6 @@ namespace MatrixRoomUtils.Core; public class Room { - private static SemaphoreSlim _semaphore = new SemaphoreSlim(16, 16); - private readonly HttpClient _httpClient; public string RoomId { get; set; } @@ -21,72 +19,26 @@ public class Room RoomId = roomId; } - public async Task<JsonElement?> GetStateAsync(string type, string state_key = "", bool logOnFailure = false) + public async Task<JsonElement?> GetStateAsync(string type, string stateKey = "", bool logOnFailure = true) { - await _semaphore.WaitAsync(); var url = $"/_matrix/client/v3/rooms/{RoomId}/state"; - var stateCombo = ""; - if (!string.IsNullOrEmpty(state_key)) stateCombo += $"{type}/{state_key}"; - else if (!string.IsNullOrEmpty(type)) stateCombo += $"{type}"; - if (!string.IsNullOrEmpty(stateCombo)) url += $"/{stateCombo}"; - var cache_key = "room_states#" + RoomId; - if (!RuntimeCache.GenericResponseCache.ContainsKey(cache_key)) - { - Console.WriteLine($"[!!] No cache for {cache_key}, creating..."); - RuntimeCache.GenericResponseCache.Add(cache_key, new ObjectCache<object?>() - { - Name = cache_key - }); - } - var cache = RuntimeCache.GenericResponseCache[cache_key]; - - if (cache.ContainsKey(stateCombo)) - { - if (cache[stateCombo].ExpiryTime > DateTime.Now) - { - // Console.WriteLine($"[:3] Found cached state: {RuntimeCache.GenericResponseCache[cache_key][url].Result}"); - _semaphore.Release(); - return (JsonElement?) cache[stateCombo].Result; - } - else - { - Console.WriteLine($"[!!] Cached state expired at {cache[stateCombo].ExpiryTime}: {cache[stateCombo].Result}"); - if(cache[stateCombo].ExpiryTime == null)Console.WriteLine("Exiryt time was null"); - } - } - // else - // { - // Console.WriteLine($"[!!] No cached state for {url}"); - // } + if (!string.IsNullOrEmpty(type)) url += $"/{type}"; + if (!string.IsNullOrEmpty(stateKey)) url += $"/{stateKey}"; var res = await _httpClient.GetAsync(url); if (!res.IsSuccessStatusCode) { - if (logOnFailure) Console.WriteLine($"{RoomId}/{state_key}/{type} - got status: {res.StatusCode}"); - _semaphore.Release(); + if (logOnFailure) Console.WriteLine($"{RoomId}/{stateKey}/{type} - got status: {res.StatusCode}"); return null; } var result = await res.Content.ReadFromJsonAsync<JsonElement>(); - var expiryTime = type switch - { - "m.room.name" => TimeSpan.FromMinutes(30), - "org.matrix.mjolnir.shortcode" => TimeSpan.FromHours(4), - "" => TimeSpan.FromSeconds(0), - _ => TimeSpan.FromMinutes(15) - }; - if(!string.IsNullOrWhiteSpace(type) && !string.IsNullOrWhiteSpace(state_key)) - cache[stateCombo] = new GenericResult<object>() - { - Result = result, - ExpiryTime = DateTime.Now.Add(expiryTime) - }; - _semaphore.Release(); return result; } - public async Task<T?> GetStateAsync<T>(string type, string state_key = "", bool logOnFailure = false) + + public async Task<T?> GetStateAsync<T>(string type, string stateKey = "", bool logOnFailure = false) { - var res = await GetStateAsync(type, state_key, logOnFailure); + var res = await GetStateAsync(type, stateKey, logOnFailure); if (res == null) return default; return res.Value.Deserialize<T>(); } @@ -108,27 +60,28 @@ public class Room public async Task JoinAsync(string[]? homeservers = null) { string join_url = $"/_matrix/client/r0/join/{HttpUtility.UrlEncode(RoomId)}"; - Console.WriteLine($"Calling {join_url} with {(homeservers == null ? 0 : homeservers.Length)} via's..."); - if(homeservers == null || homeservers.Length == 0) homeservers = new[] { RoomId.Split(':')[1] }; - var full_join_url = $"{join_url}?server_name=" + string.Join("&server_name=", homeservers); - var res = await _httpClient.PostAsync(full_join_url, null); + Console.WriteLine($"Calling {join_url} with {homeservers?.Length ?? 0} via's..."); + if (homeservers == null || homeservers.Length == 0) homeservers = new[] { RoomId.Split(':')[1] }; + var fullJoinUrl = $"{join_url}?server_name=" + string.Join("&server_name=", homeservers); + var res = await _httpClient.PostAsync(fullJoinUrl, null); } - - public async Task<List<string>> GetMembersAsync() + + public async Task<List<string>> GetMembersAsync(bool joinedOnly = true) { var res = await GetStateAsync(""); if (!res.HasValue) return new List<string>(); var members = new List<string>(); foreach (var member in res.Value.EnumerateArray()) { - if(member.GetProperty("Type").GetString() != "m.room.member") continue; - var member_id = member.GetProperty("StateKey").GetString(); - members.Add(member_id); + if (member.GetProperty("type").GetString() != "m.room.member") continue; + if (joinedOnly && member.GetProperty("content").GetProperty("membership").GetString() != "join") continue; + var memberId = member.GetProperty("state_key").GetString(); + members.Add(memberId ?? throw new InvalidOperationException("Event type was member but state key was null!")); } return members; } - + public async Task<List<string>> GetAliasesAsync() { var res = await GetStateAsync("m.room.aliases"); @@ -141,54 +94,54 @@ public class Room return aliases; } - + public async Task<string> GetCanonicalAliasAsync() { var res = await GetStateAsync("m.room.canonical_alias"); if (!res.HasValue) return ""; return res.Value.GetProperty("alias").GetString() ?? ""; } - + public async Task<string> GetTopicAsync() { var res = await GetStateAsync("m.room.topic"); if (!res.HasValue) return ""; return res.Value.GetProperty("topic").GetString() ?? ""; } - + public async Task<string> GetAvatarUrlAsync() { var res = await GetStateAsync("m.room.avatar"); if (!res.HasValue) return ""; return res.Value.GetProperty("url").GetString() ?? ""; } - + public async Task<JoinRules> GetJoinRuleAsync() { var res = await GetStateAsync("m.room.join_rules"); if (!res.HasValue) return new JoinRules(); return res.Value.Deserialize<JoinRules>() ?? new JoinRules(); } - + public async Task<string> GetHistoryVisibilityAsync() { var res = await GetStateAsync("m.room.history_visibility"); if (!res.HasValue) return ""; return res.Value.GetProperty("history_visibility").GetString() ?? ""; } - + public async Task<string> GetGuestAccessAsync() { var res = await GetStateAsync("m.room.guest_access"); if (!res.HasValue) return ""; return res.Value.GetProperty("guest_access").GetString() ?? ""; } - + public async Task<CreateEvent> GetCreateEventAsync() { var res = await GetStateAsync("m.room.create"); if (!res.HasValue) return new CreateEvent(); - + res.FindExtraJsonFields(typeof(CreateEvent)); return res.Value.Deserialize<CreateEvent>() ?? new CreateEvent(); @@ -197,17 +150,11 @@ public class Room public class CreateEvent { - [JsonPropertyName("creator")] - public string Creator { get; set; } - [JsonPropertyName("room_version")] - public string RoomVersion { get; set; } - [JsonPropertyName("type")] - public string? Type { get; set; } - [JsonPropertyName("predecessor")] - public object? Predecessor { get; set; } - - [JsonPropertyName("m.federate")] - public bool Federate { get; set; } + [JsonPropertyName("creator")] public string Creator { get; set; } + [JsonPropertyName("room_version")] public string RoomVersion { get; set; } + [JsonPropertyName("type")] public string? Type { get; set; } + [JsonPropertyName("predecessor")] public object? Predecessor { get; set; } + [JsonPropertyName("m.federate")] public bool Federate { get; set; } } public class JoinRules @@ -215,9 +162,7 @@ public class JoinRules private const string Public = "public"; private const string Invite = "invite"; private const string Knock = "knock"; - - [JsonPropertyName("join_rule")] - public string JoinRule { get; set; } - [JsonPropertyName("allow")] - public List<string> Allow { get; set; } + + [JsonPropertyName("join_rule")] public string JoinRule { get; set; } + [JsonPropertyName("allow")] public List<string> Allow { get; set; } } \ No newline at end of file diff --git a/MatrixRoomUtils.Core/RuntimeCache.cs b/MatrixRoomUtils.Core/RuntimeCache.cs index 380a150..25b3682 100644 --- a/MatrixRoomUtils.Core/RuntimeCache.cs +++ b/MatrixRoomUtils.Core/RuntimeCache.cs @@ -76,8 +76,8 @@ public class ObjectCache<T> where T : class set { Cache[key] = value; - Console.WriteLine($"set({key}) = {Cache[key].Result.ToJson(indent:false)}"); - Console.WriteLine($"new_state: {this.ToJson(indent:false)}"); + // Console.WriteLine($"set({key}) = {Cache[key].Result.ToJson(indent:false)}"); + // Console.WriteLine($"new_state: {this.ToJson(indent:false)}"); // Console.WriteLine($"New item in cache: {key} - {Cache[key].Result.ToJson(indent: false)}"); // Console.Error.WriteLine("Full cache: " + Cache.ToJson()); } |