PlotDirector/PlotLine/Services/NativeCompanion/NativeManuscriptCapture.cs

111 lines
13 KiB
C#

using System.Collections.Concurrent;
using System.Text;
using PlotDirector.Companion.Protocol;
using PlotLine.Models;
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)
{
private sealed record Pending(int User,int Onboarding,int Project,int Book,NativeLease Lease,DateTimeOffset Expires,string? Hash=null);
private readonly ConcurrentDictionary<Guid,Pending> pending=new();
private readonly SemaphoreSlim acceptance=new(1,1);
public async Task<ManuscriptScanState?> Start(int user,int onboarding,int project,int book)
{
await acceptance.WaitAsync();try{
using var scope=scopes.CreateScope();var access=scope.ServiceProvider.GetRequiredService<PlotLine.Data.IWordCompanionRepository>();
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 documents=presence.Read(user,book).Where(l=>l.Position.WordAvailable&&l.Position.CanCapture).ToArray();
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));
if(!presence.RequestCapture(user,selected,id)){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<ManuscriptScanState> Accept(int user,string grant,ManuscriptCapture capture)
{
await acceptance.WaitAsync();try{
if(!pending.TryGetValue(capture.RequestId,out var request)||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<PlotLine.Data.IWordCompanionRepository>();var onboardingState=scope.ServiceProvider.GetRequiredService<PlotLine.Data.IOnboardingRepository>();
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=Build(capture,user,request.Onboarding,request.Project,request.Book,request.Lease.Position.DocumentTitle,structure);
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<ManuscriptScanState?> Progress(int user,string grant,Guid id,int percent)
{
if(!pending.TryGetValue(id,out var request)||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<IReadOnlyList<(int User,ManuscriptScanState State)>> 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,item.Value.Book).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<bool> 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<PlotLine.Data.IManuscriptCaptureRepository>().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());
}
return true;
}
public async Task<ManuscriptScanState?> 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 _);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<ManuscriptScanChapterPreview>();var scenes=new List<ManuscriptScanScenePreview>();
var starts=paragraphs.Select((p,i)=>(p,i)).Where(x=>x.p.Outline==1||Marker(x.p.Tags,"PD-CHAPTER-").HasValue).Select(x=>x.i).ToList();
if(paragraphs.Count>0&&(starts.Count==0||starts[0]!=0))starts.Insert(0,0);
for(int c=0;c<starts.Count;c++){
var rows=paragraphs.Skip(starts[c]).Take((c+1<starts.Count?starts[c+1]:paragraphs.Count)-starts[c]).ToArray();var first=rows[0];bool heading=first.Outline==1;var key="chapter-"+(c+1);var body=rows.Where(p=>!(p.Index==first.Index&&heading)&&p.Outline!=2&&!Separator(p.Text)).ToArray();var chapterText=string.Concat(body.Select(p=>p.Text));
chapters.Add(new(){TemporaryChapterKey=key,ChapterNumber=c+1,Title=heading?first.Text.Trim():Marker(first.Tags,"PD-CHAPTER-").HasValue?"Chapter "+(c+1):"Opening material",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});
}
return new(){NativeInstanceID=capture.InstanceId,NativeSessionID=capture.SessionId,NativeRevision=capture.Revision,NativeDocumentEnd=capture.End,NativeParagraphPositions=paragraphs.ToDictionary(p=>p.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,SceneCount=scenes.Count,TotalWordCount=chapters.Sum(c=>c.WordCount),Chapters=chapters,Scenes=scenes};
}
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<PlotLine.Hubs.WordCompanionFollowHub> 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);}}
}