using System.Collections.Concurrent; using System.Text; using PlotDirector.Companion.Protocol; using PlotLine.Models; using PlotLine.Services.Manuscript; using PlotDirector.Companion.Protocol.Manuscript; namespace PlotLine.Services.NativeCompanion; // Short-lived transfer authorisation, issued only by the authenticated existing import wizard. // Prose acceptance is durable through IManuscriptScanPreviewStore, not through this dictionary. public sealed class NativeManuscriptCapture(NativePresenceStore presence,IManuscriptScanPreviewStore scans,TimeProvider clock,IServiceScopeFactory scopes,IConfiguration? configuration=null) { private sealed record Pending(int User,int Onboarding,int Project,int Book,NativeLease Lease,DateTimeOffset Expires,string? Hash=null,bool Paragraphs=false,bool Sync=false,long BaseRevision=-1,ManuscriptScanPreview? Prepared=null,ParagraphManuscript? AcceptedSnapshot=null); private readonly ConcurrentDictionary pending=new(); private readonly SemaphoreSlim acceptance=new(1,1); public async Task Start(int user,int onboarding,int project,int book,bool paragraphs=false) { await acceptance.WaitAsync();try{ if(paragraphs&&configuration?.GetValue("Features:ParagraphManuscripts")!=true)throw new InvalidOperationException("Paragraph tracking is not enabled on this server."); using var scope=scopes.CreateScope();var access=scope.ServiceProvider.GetRequiredService(); if(await access.GetBookStructureAsync(book,user)==null)throw new InvalidOperationException("The selected book is not accessible."); foreach(var expired in pending.Where(p=>p.Value.Expires<=clock.GetUtcNow()).Select(p=>p.Key))pending.TryRemove(expired,out _); var all=presence.Read(user,0).Where(l=>l.Position.WordAvailable&&l.Position.CanCapture&&(!paragraphs||l.Position.CanParagraphSync)).ToArray(); var linked=all.Where(l=>l.Position.BookId==book).ToArray(); var documents=linked.Length>0?linked:all.Where(l=>l.Position.BookId==0).ToArray(); if(linked.Length==0&&documents.Length>0&&all.Any(l=>l.Position.Active&&l.Position.BookId>0&&l.Position.BookId!=book)) throw new InvalidOperationException("Activate the intended unassociated manuscript in Word before importing. The active document belongs to another book."); if(documents.Length==0)return null; var active=documents.Where(l=>l.Position.Active).ToArray(); var selected=active.Length==1?active[0]:documents.Length==1?documents[0]:throw new InvalidOperationException("More than one Word document is linked to this book. Activate the intended document, then retry."); if(pending.Values.Any(p=>p.User==user&&p.Hash==null))throw new InvalidOperationException("A manuscript transfer is already pending. Wait for it to finish or expire before retrying."); if(pending.Count>=128)throw new InvalidOperationException("Manuscript transfers are busy. Try again later."); var state=await scans.StartAsync(user,onboarding,project,book);var id=state.ScanID!.Value; pending[id]=new(user,onboarding,project,book,selected,clock.GetUtcNow().AddMinutes(20),Paragraphs:paragraphs); if(!presence.RequestCapture(user,selected,id,book,paragraphs)){pending.TryRemove(id,out _);await scans.FailAsync(user,onboarding,"Word changed or is busy. Retry the manuscript transfer.");throw new InvalidOperationException("Word changed or is busy. Retry the manuscript transfer.");} return state; }finally{acceptance.Release();} } public async Task ResolveParagraphPosition(int user,int book,Guid manuscript,Guid session,long revision,int position){if(configuration?.GetValue("Features:ParagraphManuscripts")!=true)return null;using var scope=scopes.CreateScope();return await scope.ServiceProvider.GetRequiredService().Position(user,book,manuscript,session,revision,position);} public async Task CancelParagraphSnapshot(int user,int book){using var scope=scopes.CreateScope();var status=await scope.ServiceProvider.GetRequiredService().Status(user,book);if(status?.CanWrite!=true)throw new UnauthorizedAccessException();foreach(var item in pending.Where(p=>p.Value.User==user&&p.Value.Book==book&&p.Value.Sync&&p.Value.Hash==null).ToArray()){presence.RequestCancellation(user,item.Value.Lease);await Fail(user,item.Value.Lease.Grant,item.Key);}} private readonly Dictionary<(int,Guid,Guid),DateTimeOffset> autoChecks=[]; public async Task RequestParagraphSnapshot(int user,int book,NativeLease? automatic=null) { if(configuration?.GetValue("Features:ParagraphManuscripts")!=true)throw new InvalidOperationException("Paragraph tracking is not enabled."); await acceptance.WaitAsync();try{ using var scope=scopes.CreateScope();var repository=scope.ServiceProvider.GetRequiredService(); var status=await repository.Status(user,book)??throw new InvalidOperationException("Enable paragraph tracking for this book first."); if(!status.CanWrite)throw new UnauthorizedAccessException();if(status.Paused)throw new InvalidOperationException("The existing book import is still active. Synchronisation is paused to protect it."); var documents=presence.Read(user,book).Where(l=>l.Position.WordAvailable&&l.Position.CanParagraphSync).ToArray(); if(automatic!=null&&(status.Mode!="OnSave"||documents.Length!=1||!automatic.Position.WordSaved.GetValueOrDefault()||(status.SessionId==automatic.Session&&status.WordRevision==automatic.Position.Revision)))return Guid.Empty; var active=documents.Where(l=>l.Position.Active).ToArray();var selected=automatic??(active.Length==1?active[0]:documents.Length==1?documents[0]:throw new InvalidOperationException("Activate the intended Word manuscript. Multiple or no eligible documents are connected.")); if(selected.Position.ManuscriptId!=status.ManuscriptId)throw new InvalidOperationException("This is a different document. Import a different manuscript into a separate book; automatic cross-document evidence matching is refused."); if(pending.Values.Any(p=>p.User==user&&p.Hash==null))return Guid.Empty; if(pending.Count>=128)throw new InvalidOperationException("Manuscript transfer capacity is busy.");var id=Guid.NewGuid(); pending[id]=new(user,0,0,book,selected,clock.GetUtcNow().AddMinutes(20),Paragraphs:true,Sync:true,BaseRevision:status.Revision); if(!presence.RequestCapture(user,selected,id,book,true,true,status.Revision,status.SnapshotHash)){pending.TryRemove(id,out _);throw new InvalidOperationException("Word changed or is busy. Request a fresh snapshot.");}return id; }finally{acceptance.Release();} } public async Task ObserveParagraphSave(int user,NativeLease lease) { if(configuration?.GetValue("Features:ParagraphManuscripts")!=true||!lease.Position.CanParagraphSync||lease.Position.BookId<=0||lease.Position.WordSaved!=true)return; var key=(user,lease.Instance,lease.Session);lock(autoChecks){var now=clock.GetUtcNow();if(autoChecks.TryGetValue(key,out var after)&&now=256)autoChecks.Clear();autoChecks[key]=now.AddSeconds(15);} try{await RequestParagraphSnapshot(user,lease.Position.BookId,automatic:lease);}catch(Exception e)when(e is InvalidOperationException or UnauthorizedAccessException or Microsoft.Data.SqlClient.SqlException){/* Paused/unauthorised books never trigger a transfer. */} } public Guid[]? AcceptedParagraphIds(int user,Guid request)=>pending.TryGetValue(request,out var value)&&value.User==user?value.Prepared?.NativeParagraphs?.Select(p=>p.Id).ToArray():null; public Task AcceptedParagraphState(int user,Guid id){if(!pending.TryGetValue(id,out var request)||request.User!=user||!request.Sync||request.Hash==null||request.AcceptedSnapshot==null)throw new UnauthorizedAccessException();return Task.FromResult(request.AcceptedSnapshot);} public async Task AcceptParagraphSnapshot(int user,string grant,ManuscriptCapture capture) { await acceptance.WaitAsync();try{ if(!pending.TryGetValue(capture.RequestId,out var request)||!request.Sync)return false; if(request.User!=user||request.Lease.Grant!=grant||request.Expires<=clock.GetUtcNow()||!capture.ParagraphTracking||capture.InstanceId!=request.Lease.Instance||capture.SessionId!=request.Lease.Session||capture.ManuscriptId!=request.Lease.Position.ManuscriptId||capture.Revision!=request.Lease.Position.Revision)throw new UnauthorizedAccessException(); var hash=Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(capture))); if(request.Hash!=null){if(request.Hash!=hash)throw new ArgumentException("Snapshot retry has different contents.");return true;} using var scope=scopes.CreateScope();var accepted=await scope.ServiceProvider.GetRequiredService().Snapshot(user,request.Book,capture,request.BaseRevision); presence.BooksChanged(user); pending[capture.RequestId]=request with{Hash=hash,AcceptedSnapshot=new ParagraphManuscript{BookId=accepted.BookId,Revision=accepted.Revision,SnapshotHash=accepted.SnapshotHash,Paragraphs=accepted.Paragraphs.Select(p=>new StoryParagraph{Occurrence=new ParagraphOccurrence{Id=p.Occurrence.Id}}).ToList()}};return true; }finally{acceptance.Release();} } public async Task Accept(int user,string grant,ManuscriptCapture capture) { await acceptance.WaitAsync();try{ if(!pending.TryGetValue(capture.RequestId,out var request)||request.Sync||request.Paragraphs!=capture.ParagraphTracking||request.Expires<=clock.GetUtcNow()||request.User!=user||request.Lease.Grant!=grant||capture.InstanceId!=request.Lease.Instance||capture.SessionId!=request.Lease.Session||capture.ManuscriptId!=request.Lease.Position.ManuscriptId||capture.Revision!=request.Lease.Position.Revision)throw new UnauthorizedAccessException(); using var scope=scopes.CreateScope();var access=scope.ServiceProvider.GetRequiredService();var onboardingState=scope.ServiceProvider.GetRequiredService(); var current=await onboardingState.GetAsync(user); if(current==null||current.UserOnboardingStateID!=request.Onboarding||current.ProjectID!=request.Project||current.BookID!=request.Book)throw new UnauthorizedAccessException(); var structure=await access.GetBookStructureAsync(request.Book,user)??throw new UnauthorizedAccessException(); var hash=Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(capture))); if(request.Hash!=null){if(request.Hash!=hash)throw new ArgumentException("Capture identity conflict. Start a new transfer.");return await scans.GetStateAsync(user,request.Onboarding);} var preview=request.Prepared??Build(capture,user,request.Onboarding,request.Project,request.Book,request.Lease.Position.DocumentTitle,structure); // Reuse server-minted occurrence IDs if a durable write succeeds but its acknowledgement is lost. pending[capture.RequestId]=request=request with{Prepared=preview}; var state=await scans.CompleteAsync(user,preview); pending[capture.RequestId]=request with{Hash=hash}; // Retain request until expiry for idempotent same-ID retransmission; no import is committed here. return state; }finally{acceptance.Release();} } public async Task Progress(int user,string grant,Guid id,int percent) { if(!pending.TryGetValue(id,out var request)||request.Sync||request.User!=user||request.Lease.Grant!=grant||request.Hash!=null)return null; return await scans.ProgressAsync(user,new(){OnboardingID=request.Onboarding,PercentComplete=Math.Clamp(percent,0,100)*9/10,Message="Reading Word manuscript in bounded batches. Keep Word open until PlotDirector acknowledges receipt."}); } public async Task> Expire() { var failures=new List<(int,ManuscriptScanState)>(); foreach(var item in pending.ToArray())if(item.Value.Hash==null&&(item.Value.Expires<=clock.GetUtcNow()||!presence.Read(item.Value.User,0).Any(l=>l.Instance==item.Value.Lease.Instance&&l.Session==item.Value.Lease.Session))){var state=await Fail(item.Value.User,item.Value.Lease.Grant,item.Key);if(state!=null)failures.Add((item.Value.User,state));} return failures; } public async Task Built(int user,Guid previewId,OnboardingManuscriptBuildResult result) { var preview=await scans.GetPreviewAsync(user,previewId);if(preview?.Source!="NativeWordCompanion")return false; using var scope=scopes.CreateScope();await scope.ServiceProvider.GetRequiredService().CompleteBuild(user,previewId); if(preview.NativeSessionID.HasValue&&preview.NativeRevision.HasValue&&Guid.TryParse(preview.CompanionDocumentIdentifier,out var manuscript)){ var chapterMarkers=result.ChapterMarkerInstructions.Where(i=>preview.NativeParagraphPositions.ContainsKey(i.WordParagraphIndex)).Select(i=>(Start:preview.NativeParagraphPositions[i.WordParagraphIndex],Chapter:i.EntityID,Scene:(int?)null)); var boundaries=chapterMarkers.OrderBy(i=>i.Start).ToArray(); var sceneMarkers=result.SceneMarkerInstructions.Where(i=>preview.NativeParagraphPositions.ContainsKey(i.WordParagraphIndex)).Select(i=>{var start=preview.NativeParagraphPositions[i.WordParagraphIndex];return(Start:start,Chapter:boundaries.LastOrDefault(c=>c.Start<=start).Chapter,Scene:(int?)i.EntityID);}).Where(i=>i.Chapter>0); presence.Map(user,preview.BookID,manuscript,preview.NativeSessionID.Value,preview.NativeRevision.Value,preview.NativeDocumentEnd,boundaries.Concat(sceneMarkers).OrderBy(i=>i.Start).ThenBy(i=>i.Scene.HasValue?1:0).ToArray()); } if(preview.ParagraphTracking){ var paragraphs=scope.ServiceProvider.GetRequiredService();var bookRow=await scope.ServiceProvider.GetRequiredService().GetAsync(preview.BookID); var sources=await scope.ServiceProvider.GetRequiredService().ListSceneManuscriptSourcesByBookAsync(preview.BookID); await paragraphs.Initialise(user,preview,sources,bookRow!.ProjectID,"OnSave"); } return true; } public async Task Fail(int user,string grant,Guid id) { await acceptance.WaitAsync();try{ if(!pending.TryGetValue(id,out var request)||request.User!=user||request.Lease.Grant!=grant||request.Hash!=null)return null; pending.TryRemove(id,out _);if(request.Sync)return null;var state=await scans.GetStateAsync(user,request.Onboarding); return state.ScanID==id?await scans.FailAsync(user,request.Onboarding,"Word transfer interrupted before server acceptance. Retry Import manuscript; existing story data is unchanged."):null; }finally{acceptance.Release();} } public static ManuscriptScanPreview Build(ManuscriptCapture capture,int user,int onboarding,int project,int book,string title,WordCompanionBookStructureResponse? structure=null) { if(capture.End<0||capture.End>16*1024*1024||capture.Paragraphs==null||capture.Paragraphs.Length>200000)throw new ArgumentException("Manuscript exceeds the bounded capture limit."); var paragraphs=new List<(int Start,int Index,int Outline,string Text,string[] Tags)>();var text=new StringBuilder();int position=0,index=1,start=0,outline=10,totalCharacters=0;string[] tags=[]; foreach(var fragment in capture.Paragraphs){ if(fragment==null||fragment.Text==null||fragment.Text.Length>ProtocolVersion.MaxParagraphCharacters||fragment.Start!=position||fragment.End<=position||fragment.End>capture.End||fragment.End-fragment.Start>ProtocolVersion.MaxParagraphCharacters||fragment.ParagraphIndex!=index||fragment.OutlineLevel is <1 or >10||fragment.MarkerTags==null||fragment.MarkerTags.Length>16||fragment.MarkerTags.Any(t=>t==null||t.Length>128))throw new ArgumentException("Incomplete or invalid Word paragraph stream."); if(text.Length==0){start=fragment.Start;outline=fragment.OutlineLevel;tags=fragment.MarkerTags;} totalCharacters+=fragment.Text.Length;if(totalCharacters>16*1024*1024)throw new ArgumentException("Capture text exceeds limit."); text.Append(fragment.Text);if(text.Length>16*1024*1024)throw new ArgumentException("Paragraph too large.");position=fragment.End; if(fragment.CompletesParagraph){paragraphs.Add((start,index++,outline,text.ToString(),tags));text.Clear();} } if(position!=capture.End||text.Length!=0)throw new ArgumentException("Manuscript transfer is incomplete."); var chapters=new List();var scenes=new List(); var starts=new List(); // Same front-heading vocabulary as the established Office.js importer, only before story starts. for(var i=0;i0||!FrontMatterHeading(p.Text))))starts.Add(i);} var hasStoryHeading=starts.Count>0;var opening=hasStoryHeading&&starts[0]>0; if(paragraphs.Count>0&&(starts.Count==0||starts[0]!=0))starts.Insert(0,0); for(int c=0;c!(p.Index==first.Index&&heading)&&p.Outline!=2&&!Separator(p.Text)).ToArray();var chapterText=string.Concat(body.Select(p=>p.Text)); chapters.Add(new(){IsFrontMatter=front,TemporaryChapterKey=key,ChapterNumber=number,Title=front?"Opening material (not a story chapter)":heading?first.Text.Trim():Marker(first.Tags,"PD-CHAPTER-").HasValue?"Chapter "+number:"Manuscript",ChapterText=chapterText,WordCount=Words(chapterText),StartPosition=first.Index,ExistingChapterID=structure?.Chapters.FirstOrDefault(c=>c.ChapterId==Marker(first.Tags,"PD-CHAPTER-"))?.ChapterId,ParagraphMap=body.Where(p=>!string.IsNullOrWhiteSpace(p.Text)).Select((p,i)=>new ManuscriptScanParagraphMap{StructuralParagraphOrdinal=i+1,WordParagraphIndex=p.Index,Text=p.Text}).ToArray(),SourceParagraphs=rows.Select(p=>new ManuscriptScanSourceParagraph{WordParagraphIndex=p.Index,Text=p.Text,IsBlank=string.IsNullOrWhiteSpace(p.Text),IsChapterHeading=p.Index==first.Index&&heading,IsSceneHeading=p.Outline==2,IsSceneSeparator=Separator(p.Text),IncludeInSourceText=!(p.Index==first.Index&&heading)&&p.Outline!=2&&!Separator(p.Text)}).ToArray()}); foreach(var row in rows.Where(p=>p.Outline==2||Marker(p.Tags,"PD-SCENE-").HasValue))scenes.Add(new(){TemporaryChapterKey=key,TemporarySceneKey="scene-"+(scenes.Count+1),SceneNumberWithinChapter=scenes.Count(s=>s.TemporaryChapterKey==key)+1,Title=row.Text.Trim(),StartPosition=row.Index,ExistingSceneID=structure?.Chapters.SelectMany(c=>c.Scenes).FirstOrDefault(s=>s.SceneId==Marker(row.Tags,"PD-SCENE-"))?.SceneId}); } var nativeParagraphs=capture.ParagraphTracking?ParagraphReconciliation.Compare([],ParagraphReconciliation.Assemble(capture.Paragraphs,capture.End)).Current:null; if(nativeParagraphs!=null&&capture.ParagraphIds!=null){if(capture.ParagraphIds.Length!=nativeParagraphs.Length||capture.ParagraphIds.Any(id=>id==Guid.Empty)||capture.ParagraphIds.Distinct().Count()!=nativeParagraphs.Length)throw new ArgumentException("Invalid paragraph occurrence identities.");for(int n=0;np.Index,p=>p.Start),Source="NativeWordCompanion",PreviewID=capture.RequestId,UserID=user,OnboardingID=onboarding,ProjectID=project,BookID=book,DocumentTitle=title,CompanionDocumentIdentifier=capture.ManuscriptId.ToString("D"),ChapterCount=chapters.Count(c=>!c.IsFrontMatter),SceneCount=scenes.Count,TotalWordCount=chapters.Sum(c=>c.WordCount),Chapters=chapters,Scenes=scenes}; } private static bool FrontMatterHeading(string text)=>new[]{"title page","copyright","dedication","contents","table of contents","acknowledgements","acknowledgments","about the author"}.Contains(text.Trim(),StringComparer.OrdinalIgnoreCase); private static int? Marker(string[] tags,string prefix)=>tags.Where(t=>t.StartsWith(prefix,StringComparison.Ordinal)).Select(t=>int.TryParse(t[prefix.Length..],out var id)&&id>0?(int?)id:null).FirstOrDefault(id=>id.HasValue); private static bool Separator(string text)=>text.Trim() is "***" or "* * *" or "#"; private static int Words(string text)=>text.Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries).Length; } public sealed class NativeCaptureExpiry(NativeManuscriptCapture capture,Microsoft.AspNetCore.SignalR.IHubContext live):BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken){using var timer=new PeriodicTimer(TimeSpan.FromSeconds(15));while(await timer.WaitForNextTickAsync(stoppingToken)){foreach(var failure in await capture.Expire())await Microsoft.AspNetCore.SignalR.ClientProxyExtensions.SendAsync(live.Clients.Group(PlotLine.Hubs.WordCompanionFollowHub.PresenceGroup(failure.User)),"OnboardingScanFailed",failure.State,stoppingToken);}} }