using Microsoft.AspNetCore.Components; using Blazored.LocalStorage; using Blog3000.Shared; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Net.Http; using System.Text.Json; namespace Blog3000.Client { public class Config: IDisposable { public static string DBKEY_PREFIX="config-"; public MainConfig Main { get; private set; } public event EventHandler ConfigChanged; private readonly NetworkStatus networkStatus; private readonly ILocalStorageService localStorage; private readonly HttpClient httpClient; private bool configLoadedOnce = false; public Config(ILocalStorageService ls, NetworkStatus networkStatus, HttpClient http) { this.localStorage = ls; this.networkStatus = networkStatus; this.httpClient = http; } public void Dispose() { networkStatus.StatusChanged -= NetworkStatus_StatusChanged; } public async Task FetchAsync() { var config = await localStorage.GetItemAsync($"{DBKEY_PREFIX}main.json"); if (config == null) { await ReloadConfigFromRemote(); } else { System.Diagnostics.Debug.WriteLine("Using cached config"); Main = config; ConfigChanged?.Invoke(this, EventArgs.Empty); configLoadedOnce = false; _ = ReloadConfigFromRemote(); } if (Main == null) throw new Exception("Can't load config"); } private void NetworkStatus_StatusChanged(object sender, EventArgs e) { if (!configLoadedOnce && networkStatus.IsOnline) { // Ensure config will be reloaded event when started offline! _ = ReloadConfigFromRemote(); } } private async Task ReloadConfigFromRemote() { if (networkStatus.IsOnline) { var json = await httpClient.GetStringAsync("config.json?" + DateTime.Now.Ticks); //Log += json; if (String.IsNullOrEmpty(json)) throw new Exception("Can't load config from server"); var res = System.Text.Json.JsonSerializer.Deserialize(json, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }); await localStorage.SetItemAsync($"{DBKEY_PREFIX}main.json", res); Main = res; configLoadedOnce = true; ConfigChanged?.Invoke(this, EventArgs.Empty); System.Diagnostics.Debug.WriteLine($"Config reloaded from server"); //System.Diagnostics.Debug.WriteLine(res.Title); } else { System.Diagnostics.Debug.WriteLine("Config not reloading, offline"); } } } }