using Microsoft.UI.Dispatching; using Microsoft.Windows.AppNotifications; using XFEEDToolBox.Core.Models; using XFEEDToolBox.Core.Notifications; using XFEEDToolBox.Core.Services; namespace XFEEDToolBox.Services.Arrival; internal sealed class ArrivalNotifications(ToolboxRuntime runtime,DispatcherQueue dispatcher,Action openPage):IDisposable { private readonly CancellationTokenSource stop=new(); private readonly object sceneGate=new(); private readonly List pendingWork=[]; private NavigationArrival? starScene; private Task? starFrame; private volatile bool registered,disposed; public bool Start() { try { if(!AppNotificationManager.IsSupported()){runtime.Log("通知","当前 Windows 通知接口不可用。");return false;} AppNotificationManager.Default.NotificationInvoked+=Invoked; try{AppNotificationManager.Default.Register("XFE ED 工具箱",new Uri(Path.Combine(AppContext.BaseDirectory,"Assets","icon.png")));registered=true;} catch{AppNotificationManager.Default.NotificationInvoked-=Invoked;throw;} return true; } catch(Exception error){runtime.Log("通知","Windows 通知暂不可用:"+error.Message);return false;} } public void Send(NavigationArrival arrival,int gameProcess,Func currentPlayer) { lock(sceneGate) { if(!registered||disposed)return; Track(SendAsync(arrival,gameProcess,currentPlayer)); } } public void Send(SessionReadyNotification ready,int gameProcess,Func currentPlayer) { lock(sceneGate) { if(!registered||disposed)return; Track(SendSessionReadyAsync(ready,gameProcess,currentPlayer)); } } public void Send(GameAnnouncement notice) { if(!registered||disposed)return; try { var notification=new AppNotification(notice.ToastXml()) {Tag=notice.Id[..16],Group="game-announcements",Expiration=DateTimeOffset.UtcNow.AddDays(1)}; AppNotificationManager.Default.Show(notification); runtime.Log("通知",notification.Id>0?notice.Title+" · 已提交 Windows 通知":"Windows 尚未接受公告通知。"); } catch(Exception error){runtime.Log("通知","公告通知发送失败:"+error.Message);} } private async Task SendSessionReadyAsync(SessionReadyNotification ready,int process,Func currentPlayer) { try { var token=stop.Token;string? hero=null; try { var frame=await CaptureStarAsync(ready.Scene,process,currentPlayer,token); if(frame is not null&&ready.Scene.SameScene(currentPlayer())) { var directory=Path.Combine(runtime.DataDirectory,"notifications","arrivals");hero=Path.Combine(directory,ready.Id+".png"); await ArrivalHeroCard.SaveAsync(ArrivalHeroCard.Render(frame,ready),hero);PruneExpiredPictures(directory); } } catch(OperationCanceledException)when(token.IsCancellationRequested){return;} catch(Exception error){hero=null;runtime.Log("通知画面","重进完成画面暂不可用,使用文字通知:"+error.Message);} token.ThrowIfCancellationRequested(); var notification=new AppNotification(ArrivalToastContent.Build(ready,hero)) {Tag=ready.Id[..16],Group="session",Expiration=DateTimeOffset.UtcNow.AddDays(1)}; AppNotificationManager.Default.Show(notification); runtime.Log("通知",notification.Id>0?ready.Title+" · 已提交 Windows 通知":"Windows 未接受重进完成通知,请检查系统通知设置。"); } catch(OperationCanceledException)when(stop.IsCancellationRequested){} catch(Exception error){runtime.Log("通知","重进完成通知发送失败:"+error.Message);} } private void Track(Task task){pendingWork.RemoveAll(x=>x.IsCompleted);pendingWork.Add(task);} public void CaptureStar(NavigationArrival scene,int gameProcess,Func currentPlayer) { lock(sceneGate) { if(disposed||gameProcess<=0)return; if(starScene is {} previous&&previous.SystemAddress==scene.SystemAddress&&previous.CommanderId==scene.CommanderId&&previous.SessionAt==scene.SessionAt &&starFrame is {} cached&&(!cached.IsCompleted||cached.IsCompletedSuccessfully&&cached.Result is not null))return; starScene=scene;starFrame=CaptureStarAsync(scene,gameProcess,currentPlayer,stop.Token); Track(starFrame); } } private static async Task CaptureStarAsync(NavigationArrival scene,int process,Func player,CancellationToken token) { try { await Task.Delay(450,token); if(!scene.SameScene(player()))return null; var frame=await Task.Run(()=>ArrivalWindowCapture.CaptureAsync(process,token),token); return frame is not null&&scene.SameScene(player())&&StarFrameCandidate.HasStar(frame.Width,frame.Height,frame.Bgra)?frame:null; } catch(OperationCanceledException)when(token.IsCancellationRequested){return null;} catch{return null;} } private async Task SendAsync(NavigationArrival arrival,int gameProcess,Func currentPlayer) { try { var token=stop.Token;string? hero=null; try { if(!arrival.LocalNavigation)CaptureStar(arrival,gameProcess,currentPlayer); Task? pending; lock(sceneGate)pending=starScene is {} scene&&scene.SystemAddress==arrival.SystemAddress &&scene.CommanderId==arrival.CommanderId&&scene.SessionAt==arrival.SessionAt?starFrame:null; if(pending is not null&&arrival.SameScene(currentPlayer())) { var frame=await pending.WaitAsync(token); if(frame is not null&&arrival.SameScene(currentPlayer())) { var directory=Path.Combine(runtime.DataDirectory,"notifications","arrivals"); hero=Path.Combine(directory,arrival.Id+".png"); await ArrivalHeroCard.SaveAsync(ArrivalHeroCard.Render(frame,arrival),hero); PruneExpiredPictures(directory); } } } catch(OperationCanceledException)when(token.IsCancellationRequested){return;} catch(Exception error){hero=null;runtime.Log("通知画面","抵达截图暂不可用,使用文字通知:"+error.Message);} token.ThrowIfCancellationRequested(); var notification=new AppNotification(ArrivalToastContent.Build(arrival,hero)) {Tag=arrival.Id[..16],Group="arrival",Expiration=DateTimeOffset.UtcNow.AddDays(1)}; AppNotificationManager.Default.Show(notification); runtime.Log("通知",notification.Id>0?arrival.Title+" · 已提交 Windows 通知":"Windows 未接受抵达通知,请检查系统通知设置。"); } catch(OperationCanceledException)when(stop.IsCancellationRequested){} catch(Exception error){runtime.Log("通知","抵达通知发送失败:"+error.Message);} } private void Invoked(AppNotificationManager sender,AppNotificationActivatedEventArgs args) { if(disposed)return; var parts=args.Argument.Split('&').ToHashSet(StringComparer.Ordinal); if(parts.Contains("action=announcement")){dispatcher.TryEnqueue(()=>{if(!disposed)openPage("home");});return;} if(parts.Contains("action=session")&&parts.Contains("page=home")) {dispatcher.TryEnqueue(()=>{if(!disposed)openPage("home");});return;} if(!parts.Contains("action=arrival"))return; var local=parts.Contains("page=current-system"); dispatcher.TryEnqueue(()=>{if(!disposed)openPage(local?"current-system":"navigation");}); } private static void PruneExpiredPictures(string directory) { // Notification Center may still need yesterday's images. Only remove // this feature's expired UUID filenames, never other user images. foreach(var path in Directory.EnumerateFiles(directory,"*.png")) { var name=Path.GetFileNameWithoutExtension(path); if(name.Length!=32||!name.All(char.IsAsciiHexDigit)||File.GetLastWriteTimeUtc(path)>DateTime.UtcNow.AddDays(-2))continue; try{File.Delete(path);}catch(IOException){} } } public void Dispose() { Task[] pending; lock(sceneGate){if(disposed)return;disposed=true;stop.Cancel();pending=pendingWork.ToArray();} if(registered) { AppNotificationManager.Default.NotificationInvoked-=Invoked; try{AppNotificationManager.Default.Unregister();}catch(Exception error){runtime.Log("通知",error.Message);} registered=false; } _=Task.WhenAll(pending).ContinueWith(_=>stop.Dispose(),CancellationToken.None,TaskContinuationOptions.None,TaskScheduler.Default); } }