PlotDirector/PlotLine/Services/Manuscript/ManuscriptReaderService.cs

113 lines
5.9 KiB
C#

using System.Security.Cryptography;
using System.Text;
using PlotLine.Data;
using PlotLine.Models;
namespace PlotLine.Services.Manuscript;
public sealed record ReaderParagraph(Guid Id, string Text, bool IsHeading);
public sealed class ManuscriptReaderModel
{
public long Revision { get; init; } = -1;
public bool FocusReading { get; set; }
public string ContentVersion => Fingerprint(Paragraphs);
public static string Fingerprint(IReadOnlyList<ReaderParagraph> paragraphs)
{
using var buffer = new MemoryStream();
using (var writer = new BinaryWriter(buffer, Encoding.UTF8, leaveOpen: true))
{
writer.Write(paragraphs.Count);
foreach (var paragraph in paragraphs)
{
writer.Write(paragraph.Id.ToByteArray());
writer.Write(paragraph.Text);
writer.Write(paragraph.IsHeading);
}
}
return Convert.ToHexString(SHA256.HashData(buffer.GetBuffer().AsSpan(0, (int)buffer.Length)));
}
public required Book Book { get; init; }
public required IReadOnlyList<Chapter> Chapters { get; init; }
public Chapter? Chapter { get; init; }
public int? PreviousId { get; init; }
public int? NextId { get; init; }
public IReadOnlyList<ReaderParagraph> Paragraphs { get; init; } = [];
public DateTime? LastSuccessfulSyncUtc { get; init; }
public DateTime? SnapshotCapturedUtc { get; init; }
}
// Read only: deliberately bypasses the manuscript workspace, which may bootstrap tracking.
public sealed class ManuscriptReaderService(
IParagraphManuscriptRepository manuscripts, IBookRepository books, IChapterRepository chapters)
{
public async Task<ManuscriptReaderModel?> Read(int user, int bookId, int? chapterId)
{
// This existing stored procedure checks active ProjectUserAccess before returning any data,
// even when no paragraph snapshot exists. Never fetch book metadata before this check.
var state = await manuscripts.Get(user, bookId);
var book = await books.GetAsync(bookId);
if (book is null || book.IsArchived) return null;
var ordered = (await chapters.ListByBookAsync(bookId)).Where(c => !c.IsArchived).ToArray();
var selected = chapterId.HasValue ? ordered.FirstOrDefault(c => c.ChapterID == chapterId) : ordered.FirstOrDefault();
if (chapterId.HasValue && selected is null) return null;
return Project(book, ordered, selected, state);
}
public async Task<ReaderChange?> Check(int user, int bookId, int chapterId, long knownRevision, string knownVersion)
{
// Status transfers only metadata. Accepted prose changes always advance Revision; checkpoint
// validation without changed prose may update metadata in place, which needs no rerender.
var status = await manuscripts.Status(user, bookId);
var book = await books.GetAsync(bookId);
var chapter = await chapters.GetAsync(chapterId);
if (book is null || book.IsArchived || chapter is null || chapter.IsArchived || chapter.BookID != bookId) return null;
var revision = status?.Revision ?? -1;
if (revision == knownRevision) return new(revision, false, knownVersion);
var model = await Read(user, bookId, chapterId);
return model is null ? null : new(model.Revision, model.ContentVersion != knownVersion, model.ContentVersion);
}
public static ManuscriptReaderModel Project(Book book, IReadOnlyList<Chapter> ordered, Chapter? selected, ParagraphManuscript? state)
{
var index = selected is null ? -1 : ordered.ToList().FindIndex(c => c.ChapterID == selected.ChapterID);
var heading = state?.Chapters.FirstOrDefault(c => c.CanonicalId == selected?.ChapterID)?.HeadingId;
// Accepted assignments, not live Word positions, govern reading. Position verification may
// expire or need review without invalidating the last committed prose.
IEnumerable<StoryParagraph> source = state?.Paragraphs.Where(p =>
selected is not null && (p.ChapterId == selected.ChapterID || p.Occurrence.Id == heading)) ?? [];
if (state is not null && selected is not null)
{
try
{
// Exact accepted heading windows also retain unassigned blank paragraphs and
// scene separators. Excluded sections have their own canonical-zero boundary.
var part = ChapterCheckpointEngine.Parts(state).FirstOrDefault(p => p.Chapter.CanonicalId == selected.ChapterID);
if (part is not null && !part.Rows.Any(p => p.ChapterId > 0 && p.ChapterId != selected.ChapterID))
source = part.Rows;
}
catch (InvalidOperationException)
{
// Older accepted snapshots can lack reversible heading windows. Use only their
// explicit chapter assignments; never guess boundaries from prose or Word offsets.
}
}
var rows = source.OrderBy(p => p.Occurrence.Ordinal)
.Select(p => new ReaderParagraph(p.Occurrence.Id, p.Occurrence.Text, p.Occurrence.Id == heading || p.Occurrence.Outline is >= 1 and <= 6))
.ToArray();
var checkpoint = state?.ChapterCheckpoints.FirstOrDefault(c => c.ChapterId == selected?.ChapterID);
return new()
{
Revision = state?.Revision ?? -1,
Book = book, Chapters = ordered, Chapter = selected, Paragraphs = rows,
PreviousId = index > 0 ? ordered[index - 1].ChapterID : null,
NextId = index >= 0 && index + 1 < ordered.Count ? ordered[index + 1].ChapterID : null,
LastSuccessfulSyncUtc = checkpoint?.LastSuccessfulSyncUtc > DateTime.MinValue ? checkpoint.LastSuccessfulSyncUtc : null,
SnapshotCapturedUtc = state?.UpdatedUtc > DateTime.MinValue ? state.UpdatedUtc : null
};
}
}
public sealed record ReaderChange(long Revision, bool Changed, string Version);