PlotDirector/PlotLine/Hubs/WordCompanionFollowHub.cs

453 lines
21 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using System.Security.Claims;
using System.Text.Json;
namespace PlotLine.Hubs;
[Authorize]
public sealed class WordCompanionFollowHub(
IWordCompanionPresenceService presence,
IOnboardingRepository onboarding,
IManuscriptScanPreviewStore scanStore,
IOnboardingService onboardingService,
IOnboardingBuildRepository onboardingBuilds,
ILogger<WordCompanionFollowHub> logger,
PlotLine.Services.NativeCompanion.NativeManuscriptCapture? nativeCapture=null,
PlotLine.Services.NativeCompanion.NativePresenceStore? nativePresence=null,IBookRepository? nativeBooks=null,IWordCompanionRepository? nativeAccess=null,ContextWorkspaceNotifications? contextNotifications=null) : Hub
{
public override async Task OnConnectedAsync()
{
if (TryGetUserId(out var userId))
{
await Groups.AddToGroupAsync(Context.ConnectionId, PresenceGroup(userId));
}
await base.OnConnectedAsync();
}
public async Task<WordCompanionPresenceStatus> WatchCompanionPresence()
{
var userId = RequireUserId();
await Groups.AddToGroupAsync(Context.ConnectionId, PresenceGroup(userId));
return await CombinedPresence(userId);
}
public async Task<WordCompanionPresenceStatus> RegisterCompanion(WordCompanionPresenceRegistration registration)
{
var userId = RequireUserId();
if (registration.UserID.HasValue && registration.UserID.Value != userId)
{
throw new HubException("The Companion is signed in as a different user.");
}
var status = await presence.RegisterAsync(userId, Context.ConnectionId, registration);
logger.LogInformation(
"Word Companion registered. UserID={UserID} ProjectID={ProjectID} BookID={BookID} DocumentOpen={DocumentOpen}",
userId,
registration.LinkedProjectID,
registration.LinkedBookID,
registration.DocumentOpen);
await Clients.Group(PresenceGroup(userId)).SendAsync("WordCompanionPresenceChanged", status);
if(contextNotifications!=null)await contextNotifications.Position(userId);
return status;
}
public async Task<WordCompanionPresenceStatus> CompanionHeartbeat(WordCompanionPresenceHeartbeat heartbeat)
{
var userId = RequireUserId();
var status = await presence.HeartbeatAsync(userId, Context.ConnectionId, heartbeat);
logger.LogDebug(
"Word Companion heartbeat. UserID={UserID} ProjectID={ProjectID} BookID={BookID} DocumentOpen={DocumentOpen}",
userId,
heartbeat.LinkedProjectID,
heartbeat.LinkedBookID,
heartbeat.DocumentOpen);
await Clients.Group(PresenceGroup(userId)).SendAsync("WordCompanionPresenceChanged", status);
if(contextNotifications!=null)await contextNotifications.Position(userId);
return status;
}
public Task<ManuscriptScanState> StartOnboardingManuscriptScan()=>StartManuscriptScan(false);
public Task<ManuscriptScanState> StartParagraphManuscriptScan()=>StartManuscriptScan(true);
private async Task<ManuscriptScanState> StartManuscriptScan(bool paragraphs)
{
var userId = RequireUserId();
var state = await onboarding.GetAsync(userId);
if (state is null
|| !IsMicrosoftWordState(state)
|| !state.ProjectID.HasValue
|| !state.BookID.HasValue)
{
throw new HubException("Finish choosing a Project and Book before scanning.");
}
if(nativeCapture!=null){
try{var native=await nativeCapture.Start(userId,state.UserOnboardingStateID,state.ProjectID.Value,state.BookID.Value,paragraphs);if(native!=null){await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingScanStateChanged",native);return native;}}
catch(InvalidOperationException e){throw new HubException(e.Message);}
}
if(paragraphs)throw new HubException("Connect the updated native Companion to use paragraph tracking. No legacy capture was started.");
var presenceStatus = await presence.GetStatusAsync(userId);
if (!presenceStatus.IsConnected)
{
throw new HubException(nativePresence?.Read(userId,state.BookID.Value).Any(l=>l.Position.WordAvailable)==true?"Update the native Word add-in and agent together to enable manuscript transfer. No content was sent.":"The Word Companion is not connected. Open Word and try again.");
}
if (!presenceStatus.DocumentOpen)
{
throw new HubException("Open your manuscript in Word before scanning.");
}
var companionConnectionId = await presence.GetCompanionConnectionIdAsync(userId);
if (string.IsNullOrWhiteSpace(companionConnectionId))
{
throw new HubException("The Word Companion connection is not ready. Try reconnecting the Companion.");
}
var scanState = await scanStore.StartAsync(userId, state.UserOnboardingStateID, state.ProjectID.Value, state.BookID.Value);
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingScanStateChanged", scanState);
logger.LogInformation(
"Word Companion onboarding scan requested. UserID={UserID} OnboardingID={OnboardingID} ProjectID={ProjectID} BookID={BookID} ScanID={ScanID} CompanionConnectionID={CompanionConnectionID}",
userId,
state.UserOnboardingStateID,
state.ProjectID.Value,
state.BookID.Value,
scanState.ScanID,
companionConnectionId);
await Clients.Client(companionConnectionId).SendAsync("ScanCurrentDocument", new ManuscriptScanCommand
{
ScanID = scanState.ScanID ?? Guid.NewGuid(),
UserID = userId,
OnboardingID = state.UserOnboardingStateID,
ProjectID = state.ProjectID.Value,
BookID = state.BookID.Value,
RequestedUtc = DateTime.UtcNow
});
return scanState;
}
public async Task<ManuscriptScanState> ReceiveOnboardingScanChunk(ManuscriptScanChunk chunk)
{
var userId = RequireUserId();
var scanState = await scanStore.AddChunkAsync(userId, chunk);
if (string.Equals(scanState.Status, ManuscriptScanStatuses.Complete, StringComparison.Ordinal))
{
logger.LogInformation(
"Word Companion onboarding scan completed from chunked payload. UserID={UserID} OnboardingID={OnboardingID} ScanID={ScanID} Chunks={Chunks} PayloadCharacters={PayloadCharacters} Words={Words} Chapters={Chapters}",
userId,
chunk.OnboardingID,
chunk.ScanID,
chunk.TotalChunks,
chunk.TotalLength,
scanState.TotalWordCount,
scanState.ChapterCount);
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingScanCompleted", scanState);
}
else
{
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingScanProgress", scanState);
}
return scanState;
}
public async Task<ManuscriptScanState> ReportOnboardingScanProgress(ManuscriptScanProgress progress)
{
var userId = RequireUserId();
var scanState = await scanStore.ProgressAsync(userId, progress);
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingScanProgress", scanState);
return scanState;
}
public async Task<ManuscriptScanState> CompleteOnboardingScan(ManuscriptScanPreview preview)
{
var userId = RequireUserId();
var state = await onboarding.GetAsync(userId);
if (state is not null)
{
preview = NormalisePreviewContext(preview, userId, state);
}
if (state is null
|| state.UserOnboardingStateID != preview.OnboardingID
|| state.ProjectID != preview.ProjectID
|| state.BookID != preview.BookID)
{
throw new HubException("The scan result does not match your onboarding setup.");
}
var scanState = await scanStore.CompleteAsync(userId, preview);
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingScanCompleted", scanState);
return scanState;
}
public async Task<ManuscriptScanState> FailOnboardingScan(ManuscriptScanFailure failure)
{
var userId = RequireUserId();
var scanState = await scanStore.FailAsync(userId, failure.OnboardingID, failure.Message);
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingScanFailed", scanState);
return scanState;
}
public async Task<OnboardingManuscriptBuildResult> StartOnboardingProjectBuild(Guid previewId, bool generateSceneTitles = true)
{
var userId = RequireUserId();
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingBuildProgress", new OnboardingBuildProgress
{
Status = "Running",
Message = "Creating chapters...",
PercentComplete = 0,
PreviewID = previewId
});
OnboardingManuscriptBuildResult? result;
try
{
result = await onboardingService.BuildApprovedStructureAsync(
previewId,
generateSceneTitles,
progress => Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingBuildProgress", progress));
}
catch (InvalidOperationException ex)
{
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingBuildProgress", new OnboardingBuildProgress
{
Status = "Failed",
Message = ex.Message,
PercentComplete = 25,
PreviewID = previewId
});
throw new HubException(ex.Message);
}
if (result is null)
{
throw new HubException("The reviewed scan could not be found.");
}
if(nativeCapture!=null&&await nativeCapture.Built(userId,previewId,result)){
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingBuildProgress",new OnboardingBuildProgress{Status="Complete",Message="Chapters, scenes and manuscript sources are saved in PlotDirector. Paragraph-capable imports have their scene mappings ready; continue the existing review stages. Word text and markers have not been rewritten.",PercentComplete=100,PreviewID=previewId,BuildID=result.BuildID});
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingBuildCompleted",result);
return result;
}
var companionConnectionId = await presence.GetCompanionConnectionIdAsync(userId);
if (!string.IsNullOrWhiteSpace(companionConnectionId))
{
await onboardingBuilds.MarkMarkerSyncSentAsync(result.BuildID);
await Clients.Client(companionConnectionId).SendAsync("UpdateOnboardingBuildMarkers", result);
}
else
{
await onboardingBuilds.MarkMarkerSyncFailedAsync(result.BuildID, "The Word Companion disconnected before marker sync could be sent.");
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingBuildProgress", new OnboardingBuildProgress
{
Status = "Failed",
Message = "The Word Companion disconnected before PlotDirector could update and save Word markers.",
PercentComplete = 90,
ChaptersCreated = result.ChaptersCreated,
ScenesCreated = result.ScenesCreated,
CharactersCreated = result.CharactersCreated + result.CharactersReused,
SceneAppearancesCreated = result.SceneAppearancesCreated,
PreviewID = previewId
});
}
return result;
}
public async Task CompleteOnboardingBuildMarkerSync(int buildId, MarkerSyncClientResult? result = null)
{
var userId = RequireUserId();
var markerStatus = NormaliseCompletedMarkerStatus(result?.MarkerStatus);
var message = string.IsNullOrWhiteSpace(result?.Message)
? markerStatus switch
{
"SaveNotRequired" => "Scene markers already existed. No Word save was required.",
"UserConfirmedSave" => "Scene markers added; user confirmed the Word document was saved.",
_ => "Scene markers added and document saved."
}
: result.Message;
logger.LogInformation(
"Onboarding marker sync completed. UserID={UserID} BuildID={BuildID} MarkerStatus={MarkerStatus} MarkersChanged={MarkersChanged} SaveState={SaveState} SaveApi={SaveApi} Host={Host} Platform={Platform} Version={Version} DocumentGuid={DocumentGuid}",
userId,
buildId,
markerStatus,
result?.MarkersChanged,
result?.SaveState,
result?.SaveApi,
result?.Host,
result?.Platform,
result?.Version,
result?.DocumentGuid);
var acknowledged = await AcknowledgeOwnedMarkersAsync(userId, buildId, result, markerStatus, message);
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingBuildProgress", new OnboardingBuildProgress
{
Status = "Complete",
Message = "Manuscript structure has been created and saved. Word may now be closed; keep this browser workflow open to review characters.",
PercentComplete = 100,
PreviewID = acknowledged.PreviewID,
BuildID = buildId,
MarkerStatus = markerStatus
});
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingBuildMarkerSyncCompleted", new { buildId, markerStatus, previewID = acknowledged.PreviewID });
}
public async Task RequireOnboardingBuildManualSave(int buildId, string message, MarkerSyncClientResult? result = null)
{
var userId = RequireUserId();
logger.LogWarning(
"Onboarding marker sync requires manual Word save. UserID={UserID} BuildID={BuildID} Message={Message} Diagnostics={Diagnostics}",
userId,
buildId,
message,
SerialiseMarkerDiagnostics(result));
var acknowledged = await AcknowledgeOwnedMarkersAsync(userId, buildId, result, "UserSaveRequired", message);
var progress = new OnboardingBuildProgress
{
Status = "Running",
Message = string.IsNullOrWhiteSpace(message)
? "Scene markers have been added. Save the document in Word, then continue the import again."
: message,
PercentComplete = 90,
PreviewID = acknowledged.PreviewID,
BuildID = buildId,
MarkerStatus = "UserSaveRequired"
};
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingBuildProgress", progress);
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingBuildManualSaveRequired", progress);
}
public async Task FailOnboardingBuildMarkerSync(int buildId, string message, MarkerSyncClientResult? result = null)
{
var userId = RequireUserId();
logger.LogWarning(
"Onboarding marker sync failed. UserID={UserID} BuildID={BuildID} Message={Message} Diagnostics={Diagnostics}",
userId,
buildId,
message,
SerialiseMarkerDiagnostics(result));
var acknowledged = await AcknowledgeOwnedMarkersAsync(userId, buildId, result, "Failed", message);
await Clients.Group(PresenceGroup(userId)).SendAsync("OnboardingBuildProgress", new OnboardingBuildProgress
{
Status = "Failed",
Message = string.IsNullOrWhiteSpace(message)
? "Word marker sync failed. Keep Word open and try again."
: message,
PercentComplete = 90,
PreviewID = acknowledged.PreviewID,
BuildID = buildId,
MarkerStatus = "Failed"
});
}
private async Task<MarkerAcknowledgementContext> AcknowledgeOwnedMarkersAsync(int userId, int buildId, MarkerSyncClientResult? result, string status, string message)
{
Guid? documentGuid = null;
if (!string.IsNullOrWhiteSpace(result?.DocumentGuid))
{
if (!Guid.TryParse(result.DocumentGuid, out var parsed) || parsed == Guid.Empty)
throw new HubException("The Word document identity is invalid.");
documentGuid = parsed;
}
// Legacy Office.js/browser clients may omit GUID/preview. SQL still verifies the
// authenticated build owner, current project access and exact active book/document association.
return await onboardingBuilds.AcknowledgeMarkersAsync(userId, buildId, result?.PreviewID, documentGuid, status, message)
?? throw new HubException("The marker acknowledgement does not match an accessible manuscript build.");
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
var status = await presence.DisconnectAsync(Context.ConnectionId);
if (status is not null)
{
await Clients.Group(PresenceGroup(status.UserID)).SendAsync("WordCompanionPresenceChanged", status);
if(contextNotifications!=null)await contextNotifications.Position(status.UserID);
var failedScans = await scanStore.FailRunningForUserAsync(
status.UserID,
"The Word Companion disconnected before the scan finished. Reopen Word and try again.");
foreach (var failedScan in failedScans)
{
await Clients.Group(PresenceGroup(status.UserID)).SendAsync("OnboardingScanFailed", failedScan);
}
}
await base.OnDisconnectedAsync(exception);
}
private async Task<WordCompanionPresenceStatus> CombinedPresence(int userId)
{
if(nativePresence!=null&&nativeBooks!=null&&nativeAccess!=null){
var docs=nativePresence.Read(userId,0).Where(l=>l.Position.WordAvailable).ToArray();var active=docs.Where(l=>l.Position.Active).ToArray();
var lease=active.Length==1?active[0]:docs.Length==1?docs[0]:null;
if(lease!=null&&await nativeAccess.GetBookStructureAsync(lease.Position.BookId,userId)!=null&&await nativeBooks.GetAsync(lease.Position.BookId) is {} book)
return new(){UserID=userId,IsConnected=true,Status=WordCompanionPresenceStatuses.Connected,CompanionVersion="Native",DocumentOpen=true,CurrentDocumentName=lease.Position.DocumentTitle,LinkedProjectID=book.ProjectID,LinkedBookID=book.BookID,LastHeartbeatUtc=lease.Updated.UtcDateTime,CurrentStoryPosition=new(book.ProjectID,book.BookID,lease.Position.ChapterId,lease.Position.SceneId)};
}
return await presence.GetStatusAsync(userId);
}
private int RequireUserId()
=> TryGetUserId(out var userId) ? userId : throw new HubException("Sign in to use the Word Companion.");
private bool TryGetUserId(out int userId)
=> int.TryParse(Context.User?.FindFirstValue(ClaimTypes.NameIdentifier), out userId);
public static string PresenceGroup(int userId) => $"word-companion-presence:{userId}";
private static bool IsMicrosoftWordState(UserOnboardingState state)
=> string.Equals(state.WritingSoftware, WritingSoftwareValues.MicrosoftWord, StringComparison.Ordinal)
|| state.UsesWordCompanion == true;
private static string NormaliseCompletedMarkerStatus(string? markerStatus)
=> markerStatus is "SaveNotRequired" or "UserConfirmedSave" ? markerStatus : "Completed";
private static string? SerialiseMarkerDiagnostics(MarkerSyncClientResult? result)
=> result is null ? null : JsonSerializer.Serialize(result);
private static ManuscriptScanPreview NormalisePreviewContext(ManuscriptScanPreview preview, int userId, UserOnboardingState state)
{
return new()
{
PreviewID = preview.PreviewID,
UserID = preview.UserID == 0 ? userId : preview.UserID,
OnboardingID = preview.OnboardingID == 0 ? state.UserOnboardingStateID : preview.OnboardingID,
ProjectID = preview.ProjectID == 0 && state.ProjectID.HasValue ? state.ProjectID.Value : preview.ProjectID,
BookID = preview.BookID == 0 && state.BookID.HasValue ? state.BookID.Value : preview.BookID,
Source = preview.Source,
DocumentTitle = preview.DocumentTitle,
CompanionDocumentIdentifier = preview.CompanionDocumentIdentifier,
TotalWordCount = preview.TotalWordCount,
ChapterCount = preview.ChapterCount,
SceneCount = 0,
CharacterCandidateCount = 0,
CreatedUtc = preview.CreatedUtc,
Chapters = preview.Chapters,
Scenes = [],
CharacterCandidates = []
};
}
}
public sealed class MarkerSyncClientResult
{
public Guid? PreviewID { get; init; }
public string? MarkerStatus { get; init; }
public string? Message { get; init; }
public bool? MarkersChanged { get; init; }
public string? SaveState { get; init; }
public string? SaveApi { get; init; }
public string? Host { get; init; }
public string? Platform { get; init; }
public string? Version { get; init; }
public string? DocumentGuid { get; init; }
public string? DocumentUrl { get; init; }
public string? ErrorName { get; init; }
public string? ErrorCode { get; init; }
public string? ErrorMessage { get; init; }
}