using JiDangJia.Contracts; using System.Security.Cryptography; using System.Text; using System.Text.Json; namespace JiDangJia.Services; public static class ContentClient { private static readonly SemaphoreSlim gate=new(1,1); private static string CachePath=>Path.Combine(FileSystem.AppDataDirectory,"content-"+Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(ServerSettings.BaseUrl)))[..12]+".json"); public static AppContent? Current {get;private set;}=Load(); private static AppContent? Load() { try{return File.Exists(CachePath)?JsonSerializer.Deserialize(File.ReadAllText(CachePath)):null;}catch(Exception ex)when(ex is IOException or JsonException){return null;} } public static void Remember(AppContent content) { // Disabled ads are retained on the server, never shown in the client cache. Current=content with{Ads=content.Ads.Where(a=>a.Enabled).ToList(),Support=content.Support?.Where(e=>e.Enabled).ToList()}; try{File.WriteAllText(CachePath,JsonSerializer.Serialize(Current));}catch(IOException){ } } public static async Task Refresh(bool publicOnly=false) { if(!await gate.WaitAsync(0))return false; try { var content=publicOnly?await AuthClient.Current.GetPublicContent():await AuthClient.Current.GetContent();bool changed=Current?.Revision!=content.Revision; // Public information refresh must not erase authenticated ad content already cached. if(publicOnly&&Current is { } previous)content=content with{Ads=previous.Ads,CommunityUrl=previous.CommunityUrl};Remember(content);return changed; } finally{gate.Release();} } }