using LibMatrix; using LibMatrix.Homeservers; using LibMatrix.Responses; using LibMatrix.Services; using Microsoft.AspNetCore.Components; namespace MatrixRoomUtils.Web.Classes; public class MRUStorageWrapper { private readonly TieredStorageService _storageService; private readonly HomeserverProviderService _homeserverProviderService; private readonly NavigationManager _navigationManager; public MRUStorageWrapper( TieredStorageService storageService, HomeserverProviderService homeserverProviderService, NavigationManager navigationManager ) { _storageService = storageService; _homeserverProviderService = homeserverProviderService; _navigationManager = navigationManager; } public async Task?> GetAllTokens() { return await _storageService.DataStorageProvider.LoadObjectAsync>("mru.tokens") ?? new List(); } public async Task GetCurrentToken() { var currentToken = await _storageService.DataStorageProvider.LoadObjectAsync("token"); var allTokens = await GetAllTokens(); if (allTokens is null or { Count: 0 }) { await SetCurrentToken(null); return null; } if (currentToken is null) { await SetCurrentToken(currentToken = allTokens[0]); } if (!allTokens.Any(x => x.AccessToken == currentToken.AccessToken)) { await SetCurrentToken(currentToken = allTokens[0]); } return currentToken; } public async Task AddToken(UserAuth UserAuth) { var tokens = await GetAllTokens() ?? new List(); tokens.Add(UserAuth); await _storageService.DataStorageProvider.SaveObjectAsync("mru.tokens", tokens); } private async Task GetCurrentSession() { var token = await GetCurrentToken(); if (token == null) { return null; } return await _homeserverProviderService.GetAuthenticatedWithToken(token.Homeserver, token.AccessToken); } public async Task GetCurrentSessionOrNavigate() { AuthenticatedHomeserverGeneric? session = null; try { //catch if the token is invalid session = await GetCurrentSession(); } catch (MatrixException e) { if (e.ErrorCode == "M_UNKNOWN_TOKEN") { var token = await GetCurrentToken(); _navigationManager.NavigateTo("/InvalidSession?ctx=" + token.AccessToken); return null; } throw; } if (session is null) { _navigationManager.NavigateTo("/Login"); } return session; } public class Settings { public DeveloperSettings DeveloperSettings { get; set; } = new(); } public class DeveloperSettings { public bool EnableLogViewers { get; set; } public bool EnableConsoleLogging { get; set; } = true; public bool EnablePortableDevtools { get; set; } } public async Task RemoveToken(UserAuth auth) { var tokens = await GetAllTokens(); if (tokens == null) { return; } tokens.RemoveAll(x => x.AccessToken == auth.AccessToken); await _storageService.DataStorageProvider.SaveObjectAsync("mru.tokens", tokens); } public async Task SetCurrentToken(UserAuth? auth) => await _storageService.DataStorageProvider.SaveObjectAsync("token", auth); }