using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using JiDangJia.Contracts;
namespace JiDangJia.Services;
public static class AppNotifications
{
private static readonly SemaphoreSlim inbox=new(1,1);
private static readonly JsonSerializerOptions json=new(JsonSerializerDefaults.Web);
private static IDispatcherTimer? timer;private static int generation;
public static async void Start(IDispatcher dispatcher)
{
generation++;timer?.Stop();timer=dispatcher.CreateTimer();timer.Interval=TimeSpan.FromSeconds(5);timer.Tick+=(_,_)=>_=CheckInbox();timer.Start();
#if ANDROID
NotificationPlatform.PlanOwner(AuthClient.Current.AccountId);NotificationPlatform.ScheduleInbox();
try{if(!Preferences.Default.Get("notification-permission-asked",false)){Preferences.Default.Set("notification-permission-asked",true);await NotificationPlatform.RequestPermission();}}catch(Exception ex)when(ex is PermissionException or InvalidOperationException){}
#endif
await CheckInbox();
}
public static void Pause()=>timer?.Stop();
public static void Resume(){timer?.Start();_=CheckInbox();}
public static void Stop(bool wipe=false)
{
generation++;timer?.Stop();timer=null;CommunityChatArchive.Stop();
#if ANDROID
NotificationPlatform.Cancel(wipe);
#endif
}
public static async Task CheckInbox(CancellationToken ct=default)
{
// Saving messages must work even when notification permission is disabled.
await CommunityChatArchive.Sync(ct);
#if ANDROID
if(!NotificationPlatform.Allowed)return;
#endif
if(!await inbox.WaitAsync(0,ct))return;
try
{
int stamp=generation;var saved=await SecureStorage.Default.GetAsync("server_session");if(saved is null)return;using var session=JsonDocument.Parse(saved);var s=session.RootElement;
var owner=s.GetProperty("accountId").GetString()??"";var server=s.GetProperty("server").GetString()??"";var token=s.GetProperty("token").GetString()??"";
if(server!=ServerSettings.BaseUrl||!System.Text.RegularExpressions.Regex.IsMatch(owner,"^[a-f0-9]{32}$")||token.Length!=64)return;
var key="inbox-notification-"+Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(server+"/"+owner)));long cursor=Preferences.Default.Get(key,0L);
using var client=new HttpClient{Timeout=TimeSpan.FromSeconds(20)};
for(int page=0;page<5;page++)
{
using var request=new HttpRequestMessage(HttpMethod.Get,server+"/api/community/chat/reminders?after="+cursor);request.Headers.Authorization=new("Bearer",token);request.Headers.Add("X-Device-Id",Preferences.Default.Get("device_id",""));
using var response=await client.SendAsync(request,ct);if(!response.IsSuccessStatusCode)return;var reminders=await response.Content.ReadFromJsonAsync<InboxReminderPage>(json,ct);if(reminders is null)return;
if(stamp!=generation||saved!=await SecureStorage.Default.GetAsync("server_session"))return;
#if ANDROID
if(!NotificationPlatform.Allowed)return;if(reminders.Items.Count>0&&!NotificationPlatform.Message(owner))return;
#endif
cursor=Math.Max(cursor,reminders.Cursor);Preferences.Default.Set(key,cursor);if(!reminders.HasMore)break;
}
}
catch(Exception ex)when(ex is HttpRequestException or OperationCanceledException or JsonException or IOException or InvalidOperationException or KeyNotFoundException or System.Security.Cryptography.CryptographicException){}
finally{inbox.Release();}
}
}
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using JiDangJia.Contracts;
namespace JiDangJia.Services;
public static class AppNotifications
{
private static readonly SemaphoreSlim inbox=new(1,1);
private static readonly JsonSerializerOptions json=new(JsonSerializerDefaults.Web);
private static IDispatcherTimer? timer;private static int generation;
public static async void Start(IDispatcher dispatcher)
{
generation++;timer?.Stop();timer=dispatcher.CreateTimer();timer.Interval=TimeSpan.FromSeconds(5);timer.Tick+=(_,_)=>_=CheckInbox();timer.Start();
#if ANDROID
NotificationPlatform.PlanOwner(AuthClient.Current.AccountId);NotificationPlatform.ScheduleInbox();
try{if(!Preferences.Default.Get("notification-permission-asked",false)){Preferences.Default.Set("notification-permission-asked",true);await NotificationPlatform.RequestPermission();}}catch(Exception ex)when(ex is PermissionException or InvalidOperationException){}
#endif
await CheckInbox();
}
public static void Pause()=>timer?.Stop();
public static void Resume(){timer?.Start();_=CheckInbox();}
public static void Stop(bool wipe=false)
{
generation++;timer?.Stop();timer=null;CommunityChatArchive.Stop();
#if ANDROID
NotificationPlatform.Cancel(wipe);
#endif
}
public static async Task CheckInbox(CancellationToken ct=default)
{
// Saving messages must work even when notification permission is disabled.
await CommunityChatArchive.Sync(ct);
#if ANDROID
if(!NotificationPlatform.Allowed)return;
#endif
if(!await inbox.WaitAsync(0,ct))return;
try
{
int stamp=generation;var saved=await SecureStorage.Default.GetAsync("server_session");if(saved is null)return;using var session=JsonDocument.Parse(saved);var s=session.RootElement;
var owner=s.GetProperty("accountId").GetString()??"";var server=s.GetProperty("server").GetString()??"";var token=s.GetProperty("token").GetString()??"";
if(server!=ServerSettings.BaseUrl||!System.Text.RegularExpressions.Regex.IsMatch(owner,"^[a-f0-9]{32}$")||token.Length!=64)return;
var key="inbox-notification-"+Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(server+"/"+owner)));long cursor=Preferences.Default.Get(key,0L);
using var client=new HttpClient{Timeout=TimeSpan.FromSeconds(20)};
for(int page=0;page<5;page++)
{
using var request=new HttpRequestMessage(HttpMethod.Get,server+"/api/community/chat/reminders?after="+cursor);request.Headers.Authorization=new("Bearer",token);request.Headers.Add("X-Device-Id",Preferences.Default.Get("device_id",""));
using var response=await client.SendAsync(request,ct);if(!response.IsSuccessStatusCode)return;var reminders=await response.Content.ReadFromJsonAsync<InboxReminderPage>(json,ct);if(reminders is null)return;
if(stamp!=generation||saved!=await SecureStorage.Default.GetAsync("server_session"))return;
#if ANDROID
if(!NotificationPlatform.Allowed)return;if(reminders.Items.Count>0&&!NotificationPlatform.Message(owner))return;
#endif
cursor=Math.Max(cursor,reminders.Cursor);Preferences.Default.Set(key,cursor);if(!reminders.HasMore)break;
}
}
catch(Exception ex)when(ex is HttpRequestException or OperationCanceledException or JsonException or IOException or InvalidOperationException or KeyNotFoundException or System.Security.Cryptography.CryptographicException){}
finally{inbox.Release();}
}
}