60 lines
8.2 KiB
C#
60 lines
8.2 KiB
C#
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using Microsoft.AspNetCore.DataProtection;
|
|
using PlotDirector.Companion.Protocol;
|
|
using PlotLine.Data;
|
|
namespace PlotLine.Services.NativeCompanion;
|
|
public sealed record NativeImportItem(Guid ReviewID,int Version,string Key,string Hash,string Title,int Start,int End,NativeImportScene[] Scenes);
|
|
public sealed record NativeImportScene(string Key,string Title,string Summary,string Text,int? StartParagraph,int? EndParagraph,int Words);
|
|
public sealed record NativeImportPlan(int BookID,Guid ManuscriptID,NativeImportItem[] Items,string[] Conflicts,int Skipped,string Ticket,string BookTitle="",int ProjectID=0);
|
|
public sealed record NativeImportTicket(int User,int Book,Guid[] Reviews,int[] Versions,DateTime Expires,Guid Operation);
|
|
public sealed class NativeImportResult {public int ProjectID{get;set;}public string BookTitle{get;set;}="";public int BookID{get;set;}public int Skipped{get;set;}public int BuildID{get;set;}public int ChaptersCreated{get;set;}public int ScenesCreated{get;set;}public bool AlreadyBuilt{get;set;}public string Message{get;set;}="";}
|
|
public sealed class NativeImportService(INativeReviewRepository reviews,IWordCompanionRepository access,INativeImportRepository imports,IDataProtectionProvider protection,ISubscriptionService subscriptions,IBookRepository? books=null)
|
|
{
|
|
private readonly IDataProtector ticket=protection.CreateProtector("NativeImport.Confirmation.v1");
|
|
private readonly IDataProtector source=protection.CreateProtector("NativeImport.Source.v1");
|
|
public string Protect(AiChapterRequest request)=>source.Protect(JsonSerializer.Serialize(request));
|
|
public async Task<NativeImportPlan> Preview(int user,int book,Guid[] ids,Guid? operation=null)
|
|
{
|
|
if(!(await subscriptions.CanUseFeatureAsync(user,Models.SubscriptionFeature.Import)).Allowed)throw new UnauthorizedAccessException("Import is not available on this account.");
|
|
var structure=await access.GetBookStructureAsync(book,user)??throw new UnauthorizedAccessException("Book access denied.");
|
|
if(ids.Length is <1 or >100||ids.Distinct().Count()!=ids.Length)throw new ArgumentException("Select up to 100 different chapter reviews.");
|
|
var metadata=books==null?null:await books.GetAsync(book);
|
|
var items=new List<NativeImportItem>();var conflicts=new List<string>();var skipped=0;Guid manuscript=Guid.Empty;var versions=new List<int>();
|
|
foreach(var id in ids){var row=await reviews.Get(user,id)??throw new ArgumentException("A review expired or is unavailable.");if(row.BookID!=book)throw new UnauthorizedAccessException("Reviews must belong to this book.");versions.Add(row.Version);
|
|
if(manuscript==Guid.Empty)manuscript=row.ManuscriptID;if(manuscript!=row.ManuscriptID)throw new ArgumentException("Select chapters from one manuscript.");
|
|
var result=JsonSerializer.Deserialize<AiChapterResult>(row.ResultJson)!;var decisions=string.IsNullOrEmpty(row.DecisionsJson)?[]:JsonSerializer.Deserialize<Controllers.NativeSceneDecision[]>(row.DecisionsJson)!;
|
|
var approved=decisions.Where(d=>d.State=="approved").OrderBy(d=>d.Index).ToArray();skipped+=result.Scenes.Length-approved.Length;
|
|
if(approved.Length==0){conflicts.Add($"{result.ChapterTitle}: no approved scenes. Save review decisions first.");continue;}
|
|
if(string.IsNullOrEmpty(row.EncryptedSource)){conflicts.Add($"{result.ChapterTitle}: source prose was not retained. Reconnect the Companion, enable encrypted import capture in browser approval, and explicitly resubmit this chapter.");continue;}
|
|
var capture=JsonSerializer.Deserialize<AiChapterRequest>(source.Unprotect(row.EncryptedSource))!;NativeChapterMapping.Build(capture);
|
|
if(Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{capture.ChapterStart,capture.ChapterEnd,capture.Paragraphs})))!=row.ContentHash)throw new ArgumentException("Source content no longer matches this review.");
|
|
if(capture.ManuscriptId!=row.ManuscriptID||capture.BookId!=book||capture.ChapterStart!=row.ChapterStart||capture.ChapterEnd!=row.ChapterEnd)throw new ArgumentException("Source identity mismatch.");
|
|
var title=string.IsNullOrWhiteSpace(result.ChapterTitle)?"Chapter":result.ChapterTitle;var key="native:"+manuscript.ToString("N")+":"+row.ChapterStart;
|
|
// Captures use chapter-relative paragraph indices. Do not mislabel them as
|
|
// whole-document Word paragraph positions; native navigation uses absolute ranges.
|
|
var scenes=new List<NativeImportScene>();foreach(var choice in approved){if(choice.Index<0||choice.Index>=result.Scenes.Length)throw new ArgumentException("Review boundaries are invalid.");var scene=result.Scenes[choice.Index];var paragraphs=capture.Paragraphs.Where(p=>p.Start>=scene.Start&&p.End<=scene.End&&!p.IsHeading).ToArray();if(paragraphs.Length==0)throw new ArgumentException("A scene has no source paragraphs.");var text=string.Join("",paragraphs.Select(p=>p.Text));scenes.Add(new(key+":"+scene.Start,choice.Title,choice.Summary,text,null,null,Count(text)));}
|
|
items.Add(new(row.ReviewID,row.Version,key,row.ContentHash,title,row.ChapterStart,row.ChapterEnd,scenes.ToArray()));
|
|
}
|
|
var imported=await imports.List(user,book);var pending=new List<NativeImportItem>();foreach(var item in items.OrderBy(i=>i.Start)){
|
|
var prior=imported.FirstOrDefault(p=>p.ChapterKey==item.Key);if(prior!=null){if(prior.ContentHash==item.Hash&&prior.ReviewVersion==item.Version){skipped+=item.Scenes.Length;continue;}conflicts.Add(item.Title+": already imported with different content/decisions; existing scenes will not be overwritten.");continue;}
|
|
if(imported.Any(p=>p.DocumentGuid==manuscript&&p.ChapterStart<item.End&&item.Start<p.ChapterEnd))conflicts.Add(item.Title+": overlaps an imported chapter. Reconcile before importing.");
|
|
if(structure.Chapters.Any(c=>string.Equals(c.Title.Trim(),item.Title.Trim(),StringComparison.OrdinalIgnoreCase)))conflicts.Add(item.Title+": an existing chapter has this title. Resolve the match before importing; no replacement is performed.");
|
|
if(pending.Any(p=>p.Start<item.End&&item.Start<p.End))conflicts.Add(item.Title+": competing or overlapping chapter captures selected.");pending.Add(item);
|
|
}
|
|
var payload=new NativeImportTicket(user,book,ids,versions.ToArray(),DateTime.UtcNow.AddMinutes(20),operation??Guid.NewGuid());
|
|
return new(book,manuscript,pending.ToArray(),conflicts.ToArray(),skipped,ticket.Protect(JsonSerializer.Serialize(payload)),metadata?.BookDisplayTitle??"Book "+book,metadata?.ProjectID??0);
|
|
}
|
|
public async Task<NativeImportResult> Commit(int user,string confirmation)
|
|
{
|
|
NativeImportTicket saved;try{saved=JsonSerializer.Deserialize<NativeImportTicket>(ticket.Unprotect(confirmation))!;}catch(Exception e)when(e is CryptographicException or JsonException or ArgumentException){throw new ArgumentException("Invalid import confirmation.");}
|
|
if(saved.User!=user||saved.Expires<DateTime.UtcNow)throw new UnauthorizedAccessException("Import confirmation expired or belongs to another account.");
|
|
var prior=await imports.Result(user,saved.Operation);if(prior!=null){if(await access.GetBookStructureAsync(saved.Book,user)==null)throw new UnauthorizedAccessException();prior.BookID=saved.Book;return prior;}
|
|
var plan=await Preview(user,saved.Book,saved.Reviews,saved.Operation);for(var i=0;i<saved.Reviews.Length;i++)if((await reviews.Get(user,saved.Reviews[i]))?.Version!=saved.Versions[i])throw new ArgumentException("Review decisions changed. Preview again.");
|
|
if(plan.Conflicts.Length>0)throw new ArgumentException(string.Join(" ",plan.Conflicts));if(plan.Items.Length==0)return new(){BookID=saved.Book,Skipped=plan.Skipped,AlreadyBuilt=true,Message="All selected approved chapters already match an import. Nothing changed."};
|
|
var result=await imports.Commit(user,saved.Operation,plan);result.BookID=saved.Book;result.ProjectID=plan.ProjectID;result.BookTitle=plan.BookTitle;result.Skipped=plan.Skipped;return result;
|
|
}
|
|
private static int Count(string text)=>text.Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries).Length;
|
|
}
|