using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; using ArcaneLibs.Extensions; using LibMatrix.Extensions; using LibMatrix.Helpers; using LibMatrix.Responses; using LibMatrix.RoomTypes; using LibMatrix.Services; namespace LibMatrix.Homeservers; public class AuthenticatedHomeserverGeneric : RemoteHomeServer { public AuthenticatedHomeserverGeneric(TieredStorageService storage, string canonicalHomeServerDomain, string accessToken) : base(canonicalHomeServerDomain) { Storage = storage; AccessToken = accessToken.Trim(); SyncHelper = new SyncHelper(this, storage); } public virtual TieredStorageService Storage { get; set; } public virtual SyncHelper SyncHelper { get; init; } public virtual WhoAmIResponse WhoAmI { get; set; } = null!; public virtual string UserId => WhoAmI.UserId; public virtual string AccessToken { get; set; } public virtual Task GetRoom(string roomId) => Task.FromResult(new(this, roomId)); public virtual async Task> GetJoinedRooms() { var roomQuery = await _httpClient.GetAsync("/_matrix/client/v3/joined_rooms"); var roomsJson = await roomQuery.Content.ReadFromJsonAsync(); var rooms = roomsJson.GetProperty("joined_rooms").EnumerateArray().Select(room => new GenericRoom(this, room.GetString()!)).ToList(); Console.WriteLine($"Fetched {rooms.Count} rooms"); return rooms; } public virtual async Task UploadFile(string fileName, Stream fileStream, string contentType = "application/octet-stream") { var res = await _httpClient.PostAsync($"/_matrix/media/v3/upload?filename={fileName}", new StreamContent(fileStream)); if (!res.IsSuccessStatusCode) { 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 virtual async Task CreateRoom(CreateRoomRequest creationEvent) { creationEvent.CreationContent["creator"] = UserId; var res = await _httpClient.PostAsJsonAsync("/_matrix/client/v3/createRoom", creationEvent, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }); if (!res.IsSuccessStatusCode) { Console.WriteLine($"Failed to create room: {await res.Content.ReadAsStringAsync()}"); throw new InvalidDataException($"Failed to create room: {await res.Content.ReadAsStringAsync()}"); } var room = await GetRoom((await res.Content.ReadFromJsonAsync())!["room_id"]!.ToString()); foreach (var user in creationEvent.Invite) { await room.InviteUser(user); } return room; } #region Utility Functions public virtual async IAsyncEnumerable GetJoinedRoomsByType(string type) { var rooms = await GetJoinedRooms(); var tasks = rooms.Select(async room => { var roomType = await room.GetRoomType(); if (roomType == type) { return room; } return null; }).ToAsyncEnumerable(); await foreach (var result in tasks) { if (result is not null) yield return result; } } #endregion #region Account Data public virtual async Task GetAccountData(string key) { // var res = await _httpClient.GetAsync($"/_matrix/client/v3/user/{UserId}/account_data/{key}"); // if (!res.IsSuccessStatusCode) { // Console.WriteLine($"Failed to get account data: {await res.Content.ReadAsStringAsync()}"); // throw new InvalidDataException($"Failed to get account data: {await res.Content.ReadAsStringAsync()}"); // } // // return await res.Content.ReadFromJsonAsync(); return await _httpClient.GetFromJsonAsync($"/_matrix/client/v3/user/{UserId}/account_data/{key}"); } public virtual async Task SetAccountData(string key, object data) { var res = await _httpClient.PutAsJsonAsync($"/_matrix/client/v3/user/{UserId}/account_data/{key}", data); if (!res.IsSuccessStatusCode) { Console.WriteLine($"Failed to set account data: {await res.Content.ReadAsStringAsync()}"); throw new InvalidDataException($"Failed to set account data: {await res.Content.ReadAsStringAsync()}"); } } #endregion }