using System.Security.Claims; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; using PlotLine.Data; using PlotLine.Services.Context; namespace PlotLine.Hubs; // The existing browser connection carries presence, saved-data invalidation and targeted Context interactions. [Authorize] public sealed class NativeCompanionPresenceHub(ContextWindows windows,IWordCompanionRepository access,IBookRepository books, ICharacterRepository characters,ILocationRepository locations):Hub { public static string UserGroup(int user)=>"native-presence:user:"+user; private int Author=>int.TryParse(Context.User?.FindFirstValue(ClaimTypes.NameIdentifier),out var user)?user:throw new HubException("Sign in again."); public override async Task OnConnectedAsync(){await Groups.AddToGroupAsync(Context.ConnectionId,UserGroup(Author));await base.OnConnectedAsync();} private async Task Book(int book) => await access.GetBookStructureAsync(book,Author)??throw new HubException("Book unavailable."); public async Task RegisterContextWindow(ContextWindowRegistration registration) { if(registration==null)throw new HubException("Invalid registration.");if(registration.BookID>0||registration.Kind!="main")await Book(registration.BookID); if(registration.Kind!="main"&®istration.BookIDs?.Length>0)throw new HubException("Invalid book registration."); if(registration.Kind=="main"){if(registration.EnvironmentID is null||registration.EnvironmentID==Guid.Empty)throw new HubException("Browser environment required.");foreach(var id in (registration.BookIDs??[]).Distinct().Take(65))await Book(id);} var prior=windows.Read(Context.ConnectionId); try{windows.Register(Author,Context.ConnectionId,registration);}catch(Exception e)when(e is ArgumentException or InvalidOperationException){throw new HubException(e.Message);} if(prior!=null&&prior.Registration.BookID!=registration.BookID){await Groups.RemoveFromGroupAsync(Context.ConnectionId,ContextWindows.Group(Author,prior.Registration.BookID));await Clients.Group(ContextWindows.Group(Author,prior.Registration.BookID)).SendAsync("ContextWindowsChanged");} await Groups.AddToGroupAsync(Context.ConnectionId,ContextWindows.Group(Author,registration.BookID)); // Registration is also a heartbeat; only discovery changes need a broadcast. if(prior==null||prior.Registration.BookID!=registration.BookID||prior.Registration.WindowID!=registration.WindowID||!System.Text.Json.JsonSerializer.Serialize(prior.Registration.Panes).Equals(System.Text.Json.JsonSerializer.Serialize(registration.Panes))) await Clients.Group(ContextWindows.Group(Author,registration.BookID)).SendAsync("ContextWindowsChanged"); return windows.List(Author,registration.BookID); } public async Task ClaimContextMainWindow(int bookId,Guid environmentID) {await Book(bookId);try{return windows.TryLaunch(Author,Context.ConnectionId,bookId,environmentID);}catch(ArgumentException){throw new HubException("Invalid navigation scope.");}} public async Task MyContextWindows(int bookId){await Book(bookId);return windows.List(Author,bookId);} public async Task OpenContextWindow(int bookId) { await Book(bookId);(string Status,string? Connection) result; try{result=windows.OpenContext(Author,Context.ConnectionId,bookId);}catch(Exception e)when(e is ArgumentException or InvalidOperationException){throw new HubException(e.Message);} if(result.Connection!=null)await Clients.Client(result.Connection).SendAsync("ContextWindowRequested"); return result.Status; } public async Task SendContextInteraction(ContextInteraction command) { if(command==null||command.Version!=1||command.TargetUserID.HasValue||!ContextWindows.Actions.Contains(command.Action))throw new HubException("Unsupported interaction."); var structure=await Book(command.BookID);var book=await books.GetAsync(command.BookID)??throw new HubException("Book unavailable."); if(command.StoryPoint is {} point&&((point.ChapterID.HasValue&&!structure.Chapters.Any(c=>c.ChapterId==point.ChapterID))|| (point.SceneID.HasValue&&!structure.Chapters.Any(c=>(!point.ChapterID.HasValue||c.ChapterId==point.ChapterID)&&c.Scenes.Any(s=>s.SceneId==point.SceneID)))))throw new HubException("Invalid story point."); var allowed=command.Action switch { "character.focus"=>command.CharacterID is >0&&(await characters.GetCharacterAsync(command.CharacterID.Value))?.ProjectID==book.ProjectID, "location.focus" or "location.focusAtStoryPoint"=>command.LocationID is >0&&(await locations.GetAsync(command.LocationID.Value))?.ProjectID==book.ProjectID, "relationship.focus"=>command.RelationshipID is >0&&(await characters.GetRelationshipAsync(command.RelationshipID.Value))?.ProjectID==book.ProjectID, "scene.focus"=>command.StoryPoint?.SceneID is >0, "workspace.open"=>await WorkspaceAllowed(command,book.ProjectID,structure), _=>false}; if(!allowed)throw new HubException("Reference unavailable in this book's project."); (ContextWindowLease Window,ContextPaneCapability Pane,Guid CommandID)? target; try{target=windows.Route(Author,Context.ConnectionId,command);}catch(Exception e)when(e is ArgumentException or InvalidOperationException){throw new HubException(e.Message);} if(target==null)return new("no-handler"); await Clients.Client(target.Value.Window.Connection).SendAsync("ContextInteraction",new ContextInteractionDelivery(target.Value.CommandID,command,target.Value.Pane.PaneID)); return new("delivered",target.Value.CommandID); } private async Task WorkspaceAllowed(ContextInteraction command,int project,PlotLine.Models.WordCompanionBookStructureResponse structure) { var target=command.Workspace;if(target==null)return false; return target.Tool switch{ "characters"=>!target.EntityID.HasValue||(await characters.GetCharacterAsync(target.EntityID.Value))?.ProjectID==project, "names"=>!target.EntityID.HasValue, "relationships"=>!target.EntityID.HasValue||(await characters.GetRelationshipAsync(target.EntityID.Value))?.ProjectID==project, "scene"=>target.EntityID is >0&&structure.Chapters.Any(c=>c.Scenes.Any(s=>s.SceneId==target.EntityID)),_=>false}; } public async Task CompleteContextInteraction(Guid commandId,string status) { if(status is not ("focused" or "not-visible" or "busy" or "unavailable"))throw new HubException("Invalid result."); var origin=windows.Complete(Author,Context.ConnectionId,commandId);if(origin!=null)await Clients.Client(origin).SendAsync("ContextInteractionResult",new ContextInteractionResult(status,commandId)); } public override async Task OnDisconnectedAsync(Exception? exception) { var prior=windows.Remove(Context.ConnectionId);if(prior!=null)await Clients.Group(ContextWindows.Group(prior.User,prior.Registration.BookID)).SendAsync("ContextWindowsChanged"); await base.OnDisconnectedAsync(exception); } }