XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

STHApplication

【MAUI】寄当家——安卓端交易管理系统

公开
关注 0 Fork 0 Star 0
UTF-8
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<AppContent>(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<bool> 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();}
    }
}