104 lines
7.4 KiB
C#

using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace PlotDirector.Companion.Protocol.Manuscript;
[DataContract]
public sealed class ChapterParagraph
{
[DataMember] public string NativeId {get;set;}="";
[DataMember] public int Length {get;set;}
[DataMember] public int Outline {get;set;}=10;
[DataMember] public string? Text {get;set;}
}
[DataContract]
public sealed class ChapterObservation
{
[DataMember] public Guid OperationId {get;set;}
[DataMember] public Guid RequestId {get;set;}=Guid.NewGuid();
[DataMember] public Guid ManuscriptId {get;set;}
[DataMember] public Guid InstanceId {get;set;}
[DataMember] public Guid SessionId {get;set;}
[DataMember] public long WordRevision {get;set;}
[DataMember] public long BaseRevision {get;set;}
[DataMember] public int ChapterId {get;set;}
[DataMember] public int Start {get;set;}
[DataMember] public int End {get;set;}
[DataMember] public string Algorithm {get;set;}=ChapterFingerprint.Version;
[DataMember] public string ContentHash {get;set;}="";
[DataMember] public string IdentityHash {get;set;}="";
[DataMember] public string NextHeadingId {get;set;}="";
[DataMember] public bool Reconcile {get;set;}
[DataMember] public ChapterParagraph[] Paragraphs {get;set;}=Array.Empty<ChapterParagraph>();
}
public static class ChapterFingerprint
{
public const string Version="sha256-utf16le-paragraphs-v1";
public const int MaxCharacters=256*1024,MaxParagraphs=10000;
private static string Digest(Action<BinaryWriter> write)
{
using var bytes=new MemoryStream();using(var writer=new BinaryWriter(bytes,Encoding.UTF8,true))write(writer);
using var sha=SHA256.Create();return BitConverter.ToString(sha.ComputeHash(bytes.ToArray())).Replace("-","");
}
// Encoding code units explicitly preserves even isolated UTF-16 surrogates without replacement or normalisation.
private static void Text(BinaryWriter writer,string text){writer.Write(text.Length);foreach(var c in text)writer.Write((ushort)c);}
public static string Content(IEnumerable<string> paragraphs)
{
var rows=paragraphs.ToArray();if(rows.Length>MaxParagraphs||rows.Sum(p=>(long)p.Length)>MaxCharacters)throw new ArgumentException("Chapter exceeds bounded validation size.");
return Digest(w=>{Text(w,Version);w.Write(rows.Length);foreach(var row in rows)Text(w,row);});
}
public static string Identity(IEnumerable<ChapterParagraph> paragraphs)
{
var rows=paragraphs.ToArray();if(rows.Length==0||rows.Length>MaxParagraphs||rows.Any(p=>p.Length<=0||WordParagraphIdentity.Normalise(p.NativeId)!=p.NativeId||p.Outline<1||p.Outline>10)||rows.Select(p=>p.NativeId).Distinct().Count()!=rows.Length)throw new ArgumentException("Complete unique native paragraph identities are required.");
return Digest(w=>{Text(w,Version+"/identity");w.Write(rows.Length);foreach(var row in rows){Text(w,row.NativeId);w.Write(row.Length);w.Write(row.Outline);}});
}
public static string Mapping(IEnumerable<string> assignments)=>Content(assignments);
// Parses only the main Word part. Complex constructs require the established bounded reader rather than guessed offsets.
public static ChapterParagraph[] ReadXml(string xml,string rangeText)
{
if(xml.Length>8*1024*1024||rangeText.Length>MaxCharacters)throw new ArgumentException("Chapter XML exceeds the bounded reader.");
using var reader=XmlReader.Create(new StringReader(xml),new XmlReaderSettings{DtdProcessing=DtdProcessing.Prohibit,XmlResolver=null,MaxCharactersInDocument=8*1024*1024});
var root=XDocument.Load(reader);XNamespace w="http://schemas.openxmlformats.org/wordprocessingml/2006/main",pkg="http://schemas.microsoft.com/office/2006/xmlPackage",w14="http://schemas.microsoft.com/office/word/2010/wordml";
var document=root.Root?.Name==w+"document"?root.Root:root.Descendants(pkg+"part").Where(p=>(string?)p.Attribute(pkg+"name")=="/word/document.xml").SelectMany(p=>p.Descendants(w+"document")).SingleOrDefault();
var body=document?.Element(w+"body")??throw new ArgumentException("Main Word document part is missing.");
var unsafeNames=new HashSet<XName>(new[]{"tbl","txbxContent","fldChar","instrText","footnoteReference","endnoteReference","drawing","object","ins","del","moveFrom","moveTo","altChunk","sym"}.Select(n=>w+n));
if(body.Descendants().Any(e=>unsafeNames.Contains(e.Name)))throw new ArgumentException("Complex chapter content needs bounded reconciliation; positions were not guessed.");
var styles=root.Descendants(w+"style").Where(e=>e.Attribute(w+"styleId")!=null).GroupBy(e=>(string)e.Attribute(w+"styleId")!).ToDictionary(g=>g.Key,g=>g.First());
int Outline(XElement paragraph){
var properties=paragraph.Element(w+"pPr");var seen=new HashSet<string>();
for(int depth=0;depth<16;depth++){
if(int.TryParse((string?)properties?.Element(w+"outlineLvl")?.Attribute(w+"val"),out var n))return n+1;
var style=(string?)properties?.Element(w+"pStyle")?.Attribute(w+"val");
if(style==null||!seen.Add(style)||!styles.TryGetValue(style,out var definition))return 10;
properties=definition.Element(w+"pPr");
if(properties?.Element(w+"outlineLvl")==null&&definition.Element(w+"basedOn")?.Attribute(w+"val") is {} parent)properties=new XElement(w+"pPr",new XElement(w+"pStyle",new XAttribute(w+"val",parent.Value)));
}throw new ArgumentException("Cyclic Word style inheritance.");
}
var rows=body.Elements(w+"p").Select(p=>{
var text=new StringBuilder();foreach(var node in p.Descendants()){
if(node.Name==w+"t")text.Append(node.Value);else if(node.Name==w+"tab")text.Append('\t');else if(node.Name==w+"br"||node.Name==w+"cr"){if((string?)node.Attribute(w+"type") is {} type&&type!="textWrapping")throw new ArgumentException("Page/column break requires measured Word extraction.");text.Append('\v');}
}text.Append('\r');
var outline=Outline(p);
return new ChapterParagraph{NativeId=WordParagraphIdentity.Normalise((string?)p.Attribute(w14+"paraId")),Text=text.ToString(),Length=text.Length,Outline=outline};
}).ToArray();
if(string.Concat(rows.Select(p=>p.Text))!=rangeText)throw new ArgumentException("XML paragraph text does not equal Word Range.Text; no positions were accepted.");
Identity(rows);Content(rows.Select(p=>p.Text!));return rows;
}
}
public sealed class ChapterManifest
{
public int BookId{get;set;}public Guid ManuscriptId{get;set;}public long Revision{get;set;}public string Mode{get;set;}="Manual";public ChapterManifestItem[] Chapters{get;set;}=Array.Empty<ChapterManifestItem>();
}
public sealed class ChapterManifestItem
{
public int ChapterId{get;set;}public string Title{get;set;}="";public string HeadingNativeId{get;set;}="";public string ContentHash{get;set;}="";public string IdentityHash{get;set;}="";public int Start{get;set;}public int End{get;set;}public int ParagraphCount{get;set;}public string State{get;set;}="Not yet checked";
}
public sealed class ChapterSyncReply
{
public bool Accepted{get;set;}public string State{get;set;}="Not yet checked";public string Message{get;set;}="";public int ChapterId{get;set;}public long Revision{get;set;}public bool AllowText{get;set;}
}