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

STHApplication

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

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using JiDangJia.Contracts;
using JiDangJia.Core;

namespace JiDangJia.Services;

public static class AppNotifications
{
    private static readonly SemaphoreSlim inbox=new(1,1),plans=new(1,1);
    private static readonly JsonSerializerOptions json=new(JsonSerializerDefaults.Web);
    private static Database? database;private static string account="";private static IDispatcherTimer? timer;private static int generation;
    public static async void Start(Database db,IDispatcher dispatcher)
    {
        if(database is not null)database.Committed-=Changed;database=db;account=AuthClient.Current.AccountId;generation++;db.Committed+=Changed;
        timer?.Stop();
        await RefreshPlan();
#if ANDROID

        try{if(!Preferences.Default.Get("notification-permission-asked",false)){Preferences.Default.Set("notification-permission-asked",true);await NotificationPlatform.RequestPermission();}NotificationPlatform.Reschedule();}catch(Exception ex)when(ex is PermissionException or InvalidOperationException){}
#endif

    }
    public static void Pause()=>timer?.Stop();
    public static void Resume(){Changed();}
    public static void Stop(bool wipe=false)
    {
        var owner=account.Length>0?account:AuthClient.Current.AccountId;
        if(wipe&&owner.Length>0)Preferences.Default.Remove("inbox-notification-"+Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(ServerSettings.BaseUrl+"/"+owner))));
        generation++;timer?.Stop();timer=null;if(database is not null)database.Committed-=Changed;database=null;
#if ANDROID
        NotificationPlatform.Cancel(wipe);
#endif
        account="";
    }
    private static void Changed()=>_=RefreshPlan();
    private static async Task RefreshPlan()
    {
        await plans.WaitAsync();try
        {
            var owner=account;var db=database;int stamp=generation;if(db is null||owner.Length==0)return;var due=await Task.Run(()=>DueNotificationPlan.Read(db,DateTime.Today));if(stamp!=generation||owner!=AuthClient.Current.AccountId)return;
#if ANDROID
            NotificationPlatform.Plan(owner,due);
#endif
        }
        catch(Exception ex)when(ex is IOException or InvalidOperationException or Microsoft.Data.Sqlite.SqliteException){}
        finally{plans.Release();}
    }
    public static Task CheckInbox(CancellationToken ct=default)=>Task.CompletedTask;
}