using System.Text.Json; using System.Transactions; using Microsoft.AspNetCore.DataProtection; using PlotLine.Data; using PlotLine.Models; namespace PlotLine.Services; public sealed record BookRecoveryPreview(BookRecoveryPlan Plan, string Confirmation, ProjectBackupExport Selected, int Reused, int Created, int Available, string[] Warnings); public sealed class BookRecoveryService(IProjectBackupRepository backups, IImportRepository imports, BookRecoveryRepository repository, IProjectBackupFiles files, ISubscriptionService subscriptions, ICurrentUserService current, IDataProtectionProvider protection) { private int User => current.UserId ?? throw new UnauthorizedAccessException(); private readonly IDataProtector confirmations = protection.CreateProtector("BookRecovery.Confirmation.v2"); public Task Source(int project) => OwnerSnapshot(project); public async Task Export(int project, int[] books) { // Authorise ownership before reading/decrypting any project captures. var origin = await repository.Origin(project, User); var source = await backups.GetProjectBackupAsync(project, User) ?? throw new UnauthorizedAccessException(); var graph = BookBackupGraph.Select(source, books, origin);if(graph.Recovery.ExternalReferences.Any(r=>r.BindingRequired))throw new ArgumentException("A complete recovery backup needs the connected books. Include them in your selection; no incomplete file was generated."); await files.CaptureAsync(graph); var mappings = await repository.Mappings(project, User); var identities=new Dictionary();var used=new HashSet(StringComparer.Ordinal);var forked=0;var forks=new List<(string Collection,int ID)>(); foreach(var entity in ProjectBackupGraphValidation.Entities.Where(e=>e.Identity!=null))foreach(var row in BookBackupGraph.Rows(source,entity.Collection).OrderBy(r=>Convert.ToInt64(BookBackupGraph.Value(r,entity.Identity!)))){ if(BookBackupGraph.Value(row,entity.Identity!) is not int id)continue;var own=$"{origin:N}/{entity.Collection}/{id}";var fork=new Guid(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(own+"/independent")).AsSpan(0,16));var forkKey=$"{fork:N}/{entity.Collection}/{id}";var mapping=mappings.Where(m=>m.Collection==entity.Collection&&m.DestinationID==id).OrderBy(m=>m.PortableKey==forkKey?0:1).ThenBy(m=>m.PortableKey,StringComparer.Ordinal).ThenBy(m=>m.SourceHash,StringComparer.Ordinal).FirstOrDefault();var candidate=mapping?.PortableKey??own; var divergent=mapping!=null&&mappings.Where(m=>m.PortableKey==candidate&&m.Collection==entity.Collection).Select(m=>m.DestinationID).Distinct().Count()>1; var parts=candidate.Split('/');var ownCollision=candidate.StartsWith(origin.ToString("N")+"/",StringComparison.Ordinal)&&candidate!=own&&int.TryParse(parts.Last(),out var prior)&&BookBackupGraph.Rows(source,entity.Collection).Any(r=>Equals(BookBackupGraph.Value(r,entity.Identity!),prior)); if(candidate==forkKey||divergent||ownCollision||used.Contains(candidate)){candidate=forkKey;forked++;forks.Add((entity.Collection,id));} if(!used.Add(candidate))throw new ArgumentException("Ambiguous portable identities require an independent backup project.");identities[entity.Collection+":"+id]=candidate; } graph.Recovery.ExternalReferences=graph.Recovery.ExternalReferences.Select(r=>{var pieces=r.TargetKey.Split('/');return pieces.Length==3&&pieces[0]==origin.ToString("N")&&identities.TryGetValue(pieces[1]+":"+pieces[2],out var key)?r with{TargetKey=key}:r;}).ToList(); var package=new BookBackupPackage{SourceProjectKey=origin,Snapshot=graph,FormatVersion=graph.FormatVersion=="1.5"?"2.1":"2.0"}; foreach(var entity in ProjectBackupGraphValidation.Entities.Where(e=>e.Identity!=null))foreach(var row in BookBackupGraph.Rows(graph,entity.Collection))if(BookBackupGraph.Value(row,entity.Identity!) is int id)package.Identities[entity.Collection+":"+id]=identities[entity.Collection+":"+id]; package.Warnings = ["Contains saved books and common project definitions. Keep this file private. Download does not delete books or prove a safe local copy.", "Native review captures are historical and unbound. Import receipts, credentials, live sessions and job authority are not replayed."]; var aliases=new List();foreach(var (collection,id) in forks.Where(f=>package.Identities.ContainsKey(f.Collection+":"+f.ID))){var identity=BookBackupGraph.Identity(collection)!;var row=BookBackupGraph.Rows(graph,collection).Single(r=>Equals(BookBackupGraph.Value(r,identity),id));var actual=BookBackupGraph.Rows(source,collection).Single(r=>Equals(BookBackupGraph.Value(r,identity),id));aliases.Add(new(){Collection=collection,DestinationID=id,PortableKey=package.Identities[collection+":"+id],SourceHash=SourceFingerprint(package,graph,collection,row),DestinationHash=SourceHash(graph,collection,actual)});}if(aliases.Count>0)await repository.RegisterForks(project,User,aliases); if(forked>0)package.Warnings=package.Warnings.Append("Independent versions retain separate portable identities; divergent author data is never merged by name.").ToArray(); package.Integrity = BookBackupGraph.Hash(new { package.SourceProjectKey, package.Snapshot, package.Identities, package.Warnings }); if (JsonSerializer.SerializeToUtf8Bytes(package).Length > 64 * 1024 * 1024) throw new ArgumentException("This backup exceeds the supported 64 MiB file size. Select fewer books; no incomplete file was generated."); return package; } public static BookBackupPackage Read(string json) { if (System.Text.Encoding.UTF8.GetByteCount(json) > 64 * 1024 * 1024) throw new ArgumentException("Backup exceeds the supported 64 MiB JSON limit."); using var doc = JsonDocument.Parse(json);if(doc.RootElement.ValueKind!=JsonValueKind.Object)throw new ArgumentException("A backup must contain an object package."); RejectDuplicateProperties(doc.RootElement); BookBackupPackage package; if (doc.RootElement.EnumerateObject().Any(p=>p.Name.Equals("Format",StringComparison.OrdinalIgnoreCase)&&p.Value.ValueKind==JsonValueKind.String&&p.Value.GetString()=="PlotDirector.BookBackup")) { package = JsonSerializer.Deserialize(json, BookBackupGraph.Json) ?? throw new ArgumentException("Empty backup"); if(package.Snapshot?.Data==null||package.Snapshot.Recovery==null||package.Snapshot.Recovery.ExternalReferences==null||package.Snapshot.Recovery.NativeReviews==null||package.Snapshot.Recovery.IntentAssessments==null||package.Identities==null||package.Warnings==null)throw new ArgumentException("The backup is missing required data."); if(package.Snapshot.Recovery.ExternalReferences.Any(r=>r==null||r.TargetKey==null)||package.Snapshot.Recovery.NativeReviews.Any(r=>r==null)||package.Snapshot.Recovery.IntentAssessments.Any(r=>r==null))throw new ArgumentException("The backup contains invalid recovery records."); if(!doc.RootElement.EnumerateObject().Any(p=>p.Name.Equals("FormatVersion",StringComparison.OrdinalIgnoreCase)&&p.Value.ValueKind==JsonValueKind.String))throw new ArgumentException("The backup version is missing."); var error = BookBackupGraph.Validate(package); if (error != "") throw new ArgumentException(error); var snapshot = doc.RootElement.EnumerateObject().First(p => p.Name.Equals("Snapshot", StringComparison.OrdinalIgnoreCase)).Value;RejectServerCiphertext(snapshot);if(!snapshot.EnumerateObject().Any(p=>p.Name.Equals("FormatVersion",StringComparison.OrdinalIgnoreCase)&&p.Value.ValueKind==JsonValueKind.String&&p.Value.GetString() is "1.4" or "1.5"))throw new ArgumentException("The recovery snapshot version is missing or unsupported."); if (!ProjectBackupCollectionPresence.HasRecovery(snapshot.GetRawText()) || ProjectBackupCollectionPresence.AbsentPersistentCollections(snapshot.GetRawText()).Count > 0 || ProjectBackupStoredFieldContract.Missing(snapshot.GetRawText(), true).Count > 0) throw new ArgumentException("Current backup is incomplete. Required recovery data cannot be inferred."); } else { RejectServerCiphertext(doc.RootElement);if (!ImportService.TryReadProjectBackup(json, out var legacy, out var validation) || legacy == null || !validation.IsValid) throw new ArgumentException("This is not a supported project or book backup. " + string.Join(" ", validation.Errors)); package = new() { SourceProjectKey = new Guid(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(json)).AsSpan(0, 16)), Snapshot = legacy, Warnings = validation.Warnings.Append("Historical project backup: absent categories and upload bytes cannot be reconstructed. Native/Intent state may be unavailable. Shared identity reuse is limited to this identical legacy file.").ToArray() }; foreach (var e in ProjectBackupGraphValidation.Entities.Where(e => e.Identity != null)) foreach (var row in BookBackupGraph.Rows(legacy, e.Collection)) if (BookBackupGraph.Value(row, e.Identity!) is int id) package.Identities[e.Collection + ":" + id] = $"{package.SourceProjectKey:N}/{e.Collection}/{id}"; } if (package.Snapshot.Project is null || string.IsNullOrWhiteSpace(package.Snapshot.Project.ProjectName) || package.Snapshot.Data.Books.Count == 0) throw new ArgumentException("Backup contains no project/books."); if (package.Integrity.Length == 0) package.Integrity = BookBackupGraph.Hash(json); foreach (var e in ProjectBackupGraphValidation.Entities.Where(e => e.Identity != null)) foreach (var row in BookBackupGraph.Rows(package.Snapshot, e.Collection)) if (BookBackupGraph.Value(row, e.Identity!) is int id) _ = Key(package, e.Collection, id); if (package.Identities.Values.Distinct(StringComparer.Ordinal).Count() != package.Identities.Count) throw new ArgumentException("Duplicate portable source identities."); ValidateState(package.Snapshot); return package; } private static void RejectServerCiphertext(JsonElement snapshot){if(snapshot.ValueKind!=JsonValueKind.Object)return;var state=snapshot.EnumerateObject().FirstOrDefault(p=>p.Name.Equals("Recovery",StringComparison.OrdinalIgnoreCase)).Value;if(state.ValueKind!=JsonValueKind.Object)return;if(state.EnumerateObject().Any(p=>p.Name.Equals("Protected",StringComparison.OrdinalIgnoreCase)))throw new ArgumentException("This contains server-bound protected state, not a portable backup. Export it through Back up books on the source installation.");var reviews=state.EnumerateObject().FirstOrDefault(p=>p.Name.Equals("NativeReviews",StringComparison.OrdinalIgnoreCase)).Value;if(reviews.ValueKind==JsonValueKind.Array&&reviews.EnumerateArray().Any(r=>r.ValueKind==JsonValueKind.Object&&r.EnumerateObject().Any(p=>p.Name.Equals("EncryptedSource",StringComparison.OrdinalIgnoreCase)&&p.Value.ValueKind!=JsonValueKind.Null)))throw new ArgumentException("Encrypted source captures are not portable. Re-export from the source installation.");} private static void RejectDuplicateProperties(JsonElement node) { if (node.ValueKind == JsonValueKind.Object) { var names = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var field in node.EnumerateObject()) { if (!names.Add(field.Name)) throw new ArgumentException("Backup contains ambiguous duplicate JSON fields."); RejectDuplicateProperties(field.Value); } } else if (node.ValueKind == JsonValueKind.Array) foreach (var item in node.EnumerateArray()) RejectDuplicateProperties(item); } private static void ValidateState(ProjectBackupExport graph) { PlotLine.Services.Manuscript.ParagraphRecovery.Validate(graph); if (graph.Recovery == null || graph.Recovery.NativeReviews == null || graph.Recovery.IntentAssessments == null||graph.Recovery.ExternalReferences==null||graph.Recovery.NativeReviews.Any(r=>r==null)||graph.Recovery.IntentAssessments.Any(r=>r==null)||graph.Recovery.ExternalReferences.Any(r=>r==null||r.TargetKey==null)) throw new ArgumentException("Recovery decisions are missing."); foreach (var reference in graph.Recovery.ExternalReferences) { var schema = ProjectBackupGraphValidation.Entities.FirstOrDefault(e => e.Collection == reference.Collection); var parts = reference.TargetKey.Split('/'); if (schema == null || !BookBackupGraph.Common.Contains(reference.Collection) || schema.Identity == null || parts.Length != 3 || !Guid.TryParse(parts[0], out _) || !int.TryParse(parts[2], out var id) || id < 1 || !schema.Links.Any(l => l.Column == reference.Field && l.TargetCollection == parts[1] && l.TargetCollection is "Books" or "Chapters" or "Scenes")) throw new ArgumentException("Invalid external reference metadata."); } if (graph.Recovery.NativeReviews.Select(r => r.ReviewID).Distinct().Count() != graph.Recovery.NativeReviews.Count) throw new ArgumentException("Duplicate native review identities."); foreach (var row in graph.Recovery.NativeReviews) { if (!graph.Data.Books.Any(b => b.BookID == row.BookID) || row.ResultJson == null || row.DecisionsJson is not null && !IsJson(row.DecisionsJson) || !IsJson(row.ResultJson)) throw new ArgumentException("Invalid native review."); if (row.SourceJson != null) { var capture = JsonSerializer.Deserialize(row.SourceJson, BookBackupGraph.Json) ?? throw new ArgumentException("Invalid review source."); capture.SessionId = Guid.NewGuid(); PlotLine.Services.NativeCompanion.NativeChapterMapping.Build(capture); var hash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new { capture.ChapterStart, capture.ChapterEnd, capture.Paragraphs }))); if (capture.BookId != row.BookID || capture.ManuscriptId != row.ManuscriptID || capture.ChapterStart != row.ChapterStart || capture.ChapterEnd != row.ChapterEnd || hash != row.ContentHash) throw new ArgumentException("Captured review source does not match its identity or hash."); } } foreach (var row in graph.Recovery.IntentAssessments) if (!graph.Data.Scenes.Any(s => s.SceneID == row.SceneID) || !IsJson(row.ResultsJson) || !IsJson(row.DecisionsJson)) throw new ArgumentException("Invalid Intent decisions."); } private static ProjectBackupExport SelectPackage(BookBackupPackage package, int[] books) { var selected = BookBackupGraph.Select(package.Snapshot, books, package.SourceProjectKey); selected.Recovery.ExternalReferences = selected.Recovery.ExternalReferences.Select(r => { var parts = r.TargetKey.Split('/'); return parts.Length == 3 && parts[0] == package.SourceProjectKey.ToString("N") && int.TryParse(parts[2], out var id) && package.Identities.ContainsKey(parts[1] + ":" + id) ? r with { TargetKey = Key(package, parts[1], id) } : r; }).ToList(); return selected; } private static bool IsJson(string text) { try { using var doc = JsonDocument.Parse(text); return true; } catch (JsonException) { return false; } } public async Task Preview(Guid upload, BookBackupPackage package, int[] books, int destination, string name) { if (books.Length is < 1 or > 100) throw new ArgumentException("Choose between one and 100 books."); var selected = SelectPackage(package, books); var target = destination == 0 ? null : await OwnerSnapshot(destination); if (target?.Project?.IsArchived == true) throw new ArgumentException("Unarchive the destination project before adding books; this does not change book capacity."); if (target != null) name = target.Project!.ProjectName; if (target != null) { var mappings = await repository.Mappings(destination, User); foreach (var book in selected.Data.Books) { var key = Key(package, "Books", book.BookID); if (mappings.Any(m => m.PortableKey == key && m.Collection == "Books" && target.Data.Books.Any(b => b.BookID == m.DestinationID))) throw new ArgumentException("A selected book has already been restored to this project. Choose other books or an independent new project."); } } if(destination==0){name=string.IsNullOrWhiteSpace(name)?package.Snapshot.Project!.ProjectName:name.Trim();if(name.Length>200)throw new ArgumentException("Project names must be at most 200 characters.");} var prepared = await Prepare(package, selected, target, destination == 0 ? int.MaxValue : destination, name); var entitlement = await subscriptions.GetEffectiveEntitlementAsync(User); var usage = await subscriptions.GetUsageSummaryAsync(User); var available = entitlement.IsActive?Math.Max(0, (entitlement.EffectiveLevel?.MaxBooks ?? 0) - usage.BooksUsed):0; var plan = new BookRecoveryPlan(upload, books.Distinct().Order().ToArray(), destination, string.IsNullOrWhiteSpace(name) ? package.Snapshot.Project!.ProjectName : name.Trim(), target == null ? "" : SnapshotHash(target), Guid.NewGuid(), DateTime.UtcNow.AddMinutes(20)); var token = confirmations.Protect(JsonSerializer.Serialize(new { User, Plan = plan })); return new(plan, token, selected, prepared.Reused, prepared.Created, available, package.Warnings.Concat(prepared.Conflicts).Concat(entitlement.IsActive?Array.Empty():new[]{"An active subscription or trial is required to restore books. Your existing work remains available to read and back up."}).Concat(selected.Files.Any(f=>ProjectBackupFiles.IsActiveWebFile(f.Path))?new[]{"Some web files will be recovered as binary downloads for safety. Their bytes and original attachment metadata remain preserved."}:Array.Empty()).Append("Existing destination project settings are retained; conflicting common records create independent copies. Maps are copied as independent bundles.").ToArray()); } private async Task OwnerSnapshot(int project) { try { await repository.Mappings(project, User); } catch (Microsoft.Data.SqlClient.SqlException e) when (e.Number == 51000) { throw new UnauthorizedAccessException("Project owner authority is required."); } var graph = await backups.GetProjectBackupAsync(project, User) ?? throw new UnauthorizedAccessException(); await files.CaptureAsync(graph); return graph; } private static string SourceHash(ProjectBackupExport graph, string collection, object row) { var paths = row.GetType().GetProperties().Where(p => p.PropertyType == typeof(string)).Select(p => p.GetValue(row) as string).ToHashSet(); return BookBackupGraph.Hash(new { Row = BookBackupGraph.StoredHash(collection, row), Files = graph.Files.Where(f => paths.Contains(f.Path)).OrderBy(f => f.Path).Select(f => new { f.Path, f.Sha256 }).ToArray() }); } // Source fingerprints describe portable identities/content, not the installation's local numeric IDs or filenames. private static string SourceFingerprint(BookBackupPackage package, ProjectBackupExport graph, string collection, object row) { var node=System.Text.Json.Nodes.JsonNode.Parse(JsonSerializer.Serialize(row))!.AsObject(); var columns=ProjectBackupStoredFieldContract.Columns(collection);if(columns.Length>0)foreach(var field in node.Select(p=>p.Key).ToArray())if(!columns.Contains(field,StringComparer.OrdinalIgnoreCase))node.Remove(field); var schema=ProjectBackupGraphValidation.Entities.Single(e=>e.Collection==collection);var owner=(int)BookBackupGraph.Value(row,schema.Identity!)!; string Target(string target,int id){ var entity=ProjectBackupGraphValidation.Entities.FirstOrDefault(e=>e.Collection==target);var global=entity?.Identity==null?null:BookBackupGraph.Rows(package.Snapshot,target).FirstOrDefault(r=>Equals(BookBackupGraph.Value(r,entity.Identity),id)&&r.GetType().GetProperty("ProjectID")!=null&&BookBackupGraph.Value(r,"ProjectID")==null); if(global!=null){var data=JsonSerializer.SerializeToNode(global)!.AsObject();data.Remove(entity!.Identity!);data.Remove("ProjectID");return "global/"+target+"/"+BookBackupGraph.Hash(data);} return Key(package,target,id); } foreach(var audit in new[]{"CreatedByUserID","ModifiedByUserID","CreatedDate","UpdatedDate","CreatedDateUTC","ModifiedDateUTC"})node.Remove(audit); if(collection=="Characters"&&node.ContainsKey("SexValueID"))node["SexValueID"]="sex/"+(BookBackupGraph.Value(row,"Sex") as string??""); if(node.ContainsKey(schema.Identity!))node[schema.Identity!]=Key(package,collection,owner); if(node.ContainsKey("ProjectID"))node["ProjectID"]="project-scope"; foreach(var link in schema.Links.Where(l=>l.TargetCollection!="Project"&&node.ContainsKey(l.Column))){ var value=BookBackupGraph.Value(row,link.Column);var external=graph.Recovery.ExternalReferences.FirstOrDefault(r=>r.Collection==collection&&r.OwnerID==owner&&r.Field==link.Column); if(value is int id&&package.Identities.ContainsKey(link.TargetCollection+":"+id))node[link.Column]=Target(link.TargetCollection,id); else if(external!=null)node[link.Column]=external.TargetKey; } foreach(var field in node.ToArray())if(field.Value is System.Text.Json.Nodes.JsonValue text&&text.TryGetValue(out var path)&&graph.Files.FirstOrDefault(f=>f.Path==path) is {} file)node[field.Key]="file-sha256/"+file.Sha256; return BookBackupGraph.Hash(node); } private static string SnapshotHash(ProjectBackupExport graph) => BookBackupGraph.Hash(new { graph.Project, graph.Data, graph.Recovery, Files=graph.Files.OrderBy(f=>f.Path).Select(f=>new{f.Path,f.Sha256}).ToArray() }); private static string Key(BookBackupPackage package, string collection, int id) { if (!package.Identities.TryGetValue(collection + ":" + id, out var key) || string.IsNullOrWhiteSpace(key) || key.Length > 240) throw new ArgumentException("A portable identity is missing."); var parts = key.Split('/'); if (parts.Length != 3 || !Guid.TryParse(parts[0], out var origin) || origin == Guid.Empty || parts[1] != collection || !int.TryParse(parts[2], out var source) || source < 1) throw new ArgumentException("A portable identity has an invalid namespace or type.");if(parts[0]!=origin.ToString("N")||parts[2]!=source.ToString(System.Globalization.CultureInfo.InvariantCulture))throw new ArgumentException("Portable identity formatting is not canonical."); return key; } private sealed record Prepared(ProjectBackupExport Graph, Dictionary> Maps, List<(string Collection, int Source, string Key, string Hash)> Sources, int Reused, int Created, string[] Conflicts); private async Task Prepare(BookBackupPackage package, ProjectBackupExport selected, ProjectBackupExport? target, int project, string name) { var known = target == null ? [] : await repository.Mappings(project, User); var reuse = new Dictionary>(); // Reconnect a detached optional reference only through the same authorised, verified identity map. foreach (var reference in selected.Recovery.ExternalReferences.Where(r => !r.BindingRequired)) { var pieces = reference.TargetKey.Split('/'); if (pieces.Length != 3 || !int.TryParse(pieces[2], out var original)) continue; var mapping = known.FirstOrDefault(m => m.PortableKey == reference.TargetKey && m.Collection == pieces[1]); var targetIdentity = BookBackupGraph.Identity(pieces[1]); var existing = mapping == null || target == null || targetIdentity == null ? null : BookBackupGraph.Rows(target, pieces[1]).FirstOrDefault(r => Equals(BookBackupGraph.Value(r, targetIdentity), mapping.DestinationID)); var identity = BookBackupGraph.Identity(reference.Collection); var owner = identity == null ? null : BookBackupGraph.Rows(selected, reference.Collection).FirstOrDefault(r => Equals(BookBackupGraph.Value(r, identity), reference.OwnerID)); if (owner == null || mapping == null || existing == null || SourceHash(target!, pieces[1], existing) != mapping.DestinationHash || BookBackupGraph.Value(owner, reference.Field) != null || BookBackupGraph.Rows(selected, pieces[1]).Any(r => Equals(BookBackupGraph.Value(r, targetIdentity!), original))) continue; owner.GetType().GetProperty(reference.Field)!.SetValue(owner, original); var table = BookBackupGraph.Table(pieces[1]); if (!reuse.ContainsKey(table)) reuse[table] = []; reuse[table][original] = mapping.DestinationID; } var sourceRows = new List<(string Collection, int Source, string Key, string Hash)>(); foreach (var e in ProjectBackupGraphValidation.Entities.Where(e => e.Identity != null)) foreach (var row in BookBackupGraph.Rows(selected, e.Collection)) if (BookBackupGraph.Value(row, e.Identity!) is int id) { if (target != null && e.Collection == "TimelineSettings") continue; if (e.Collection is "AssetStates" or "CharacterAttributeTypes" or "SceneMetricTypes" && BookBackupGraph.Value(row, "ProjectID") == null) continue; sourceRows.Add((e.Collection, id, Key(package, e.Collection, id), SourceFingerprint(package,selected,e.Collection,row))); } foreach (var source in sourceRows.Where(s => BookBackupGraph.Common.Contains(s.Collection) && s.Collection is not ("StoryMaps" or "MapFeatures" or "MapRelationships" or "MapReferenceImages"))) { var identity = BookBackupGraph.Identity(source.Collection)!; var mapping = known.FirstOrDefault(m => m.PortableKey == source.Key && m.SourceHash == source.Hash && m.Collection == source.Collection); var row = mapping == null ? null : BookBackupGraph.Rows(target!, source.Collection).FirstOrDefault(r => Equals(BookBackupGraph.Value(r, identity), mapping.DestinationID)); if (mapping != null && row != null && SourceHash(target!, source.Collection, row) == mapping.DestinationHash) { var table = BookBackupGraph.Table(source.Collection); if (!reuse.ContainsKey(table)) reuse[table] = []; reuse[table][source.Source] = mapping.DestinationID; } } foreach (var reference in selected.Recovery.ExternalReferences.Where(r => r.BindingRequired)) { var identity = BookBackupGraph.Identity(reference.Collection); if (identity == null) throw new ArgumentException("Unsupported external-reference owner."); var owner = BookBackupGraph.Rows(selected, reference.Collection).FirstOrDefault(r => Equals(BookBackupGraph.Value(r, identity), reference.OwnerID)); if (owner == null) throw new ArgumentException("External reference owner is missing."); if (BookBackupGraph.Value(owner, reference.Field) is not int original) continue; var pieces = reference.TargetKey.Split('/'); if (pieces.Length != 3 || BookBackupGraph.Rows(selected, pieces[1]).Any(r => Equals(BookBackupGraph.Value(r, BookBackupGraph.Identity(pieces[1])!), original))) throw new ArgumentException("Invalid external identity; selected book records cannot be reused."); var mapping = known.FirstOrDefault(m => m.PortableKey == reference.TargetKey && m.Collection == pieces[1]); var targetIdentity = BookBackupGraph.Identity(pieces[1]); var existing = mapping == null || target == null || targetIdentity == null ? null : BookBackupGraph.Rows(target, pieces[1]).FirstOrDefault(r => Equals(BookBackupGraph.Value(r, targetIdentity), mapping.DestinationID)); if (mapping == null || existing == null || SourceHash(target!, pieces[1], existing) != mapping.DestinationHash) throw new ArgumentException("This selection requires a connected book already restored to the destination. Restore the connected books together, or restore that book first."); var table = BookBackupGraph.Table(pieces[1]); if (!reuse.ContainsKey(table)) reuse[table] = []; reuse[table][original] = mapping.DestinationID; } var imageReuse = new Dictionary(); if (target != null) foreach (var image in selected.Data.MapReferenceImages) { var matching = target.Data.MapReferenceImages.FirstOrDefault(i => i.ContentType == image.ContentType && i.Width == image.Width && i.Height == image.Height && i.ImageData != null && image.ImageData != null && i.ImageData.AsSpan().SequenceEqual(image.ImageData)); if (matching != null) imageReuse[image.ImageID] = matching.ImageID; } var max = await imports.GetIdentityMaxValuesAsync(ImportService.ProjectBackupIdentityTables); var lookups = await imports.GetRelationshipImportLookupsAsync(); ProjectBackupExport graph = null!; Dictionary> maps = null!; for (var pass = 0; pass < 16; pass++) { graph = BookBackupGraph.Clone(selected); maps = ImportService.RemapProjectBackupForImport(graph, project, name, max, lookups, [], User, reuse, imageReuse, strictLookups:true); var removed = false; foreach (var source in sourceRows) { var table = BookBackupGraph.Table(source.Collection); if (!reuse.TryGetValue(table, out var set) || !set.TryGetValue(source.Source, out var destination)) continue; var identity = BookBackupGraph.Identity(source.Collection)!; var row = BookBackupGraph.Rows(graph, source.Collection).Single(r => Equals(BookBackupGraph.Value(r, identity), destination)); var existing = BookBackupGraph.Rows(target!, source.Collection).Single(r => Equals(BookBackupGraph.Value(r, identity), destination)); foreach(var audit in new[]{"CreatedByUserID","ModifiedByUserID","CreatedDate","UpdatedDate","CreatedDateUTC","ModifiedDateUTC"})if(row.GetType().GetProperty(audit) is {CanWrite:true} auditProperty)auditProperty.SetValue(row,auditProperty.GetValue(existing)); foreach (var property in row.GetType().GetProperties().Where(p => p.CanWrite && p.PropertyType == typeof(string))) if (property.GetValue(row) is string path && selected.Files.Any(f => f.Path == path)) property.SetValue(row, property.GetValue(existing)); if (BookBackupGraph.StoredHash(source.Collection, row) != BookBackupGraph.StoredHash(source.Collection, existing)) { set.Remove(source.Source); removed = true; } } if (!removed) break; if (pass == 15) throw new ArgumentException("Shared references could not be resolved conservatively. Restore into a new project."); } var reused = 0; foreach (var source in sourceRows) { var table = BookBackupGraph.Table(source.Collection); if (reuse.TryGetValue(table, out var entries) && entries.ContainsKey(source.Source)) { reused++; var identity = BookBackupGraph.Identity(source.Collection)!; SetWithout(source.Collection, entries[source.Source], identity); } } void SetWithout(string c, int id, string field) => BookBackupGraph.SetRows(graph, c, BookBackupGraph.Rows(graph, c).Where(r => !Equals(BookBackupGraph.Value(r, field), id))); if (target != null) { foreach (var demand in graph.Data.StoryIntelligenceIllustrationDemands) if (target.Data.StoryIntelligenceIllustrationDemands.Any(d => d.DemandKey == demand.DemandKey)) demand.DemandKey = (demand.DemandKey.Length > 190 ? demand.DemandKey[..190] : demand.DemandKey) + ":recovery:" + Guid.NewGuid().ToString("N"); BookBackupGraph.SetRows(graph, "MapReferenceImages", graph.Data.MapReferenceImages.Where(i => !target.Data.MapReferenceImages.Any(t => t.ImageID == i.ImageID))); BookBackupGraph.SetRows(graph, "TimelineSettings", []); sourceRows.RemoveAll(s => s.Collection == "TimelineSettings"); } var created=BookBackupGraph.Common.Where(c=>c is not ("GenreMetricPresets" or "GenreMetricPresetMetrics")).Sum(c=>BookBackupGraph.Rows(graph,c).Count(row=> !(c is "AssetStates" or "CharacterAttributeTypes" or "SceneMetricTypes" && BookBackupGraph.Value(row,"ProjectID")==null) && !(c=="TimelineMetricSettings"&&target!=null&&target.Data.TimelineMetricSettings.Any(t=>Equals(t.MetricTypeID,BookBackupGraph.Value(row,"MetricTypeID")))))); ProjectBackupFiles.Prune(graph); return new(graph, maps, sourceRows, reused+imageReuse.Count, created, sourceRows.Where(s => BookBackupGraph.Common.Contains(s.Collection) && known.Any(m => m.PortableKey == s.Key) && !(reuse.TryGetValue(BookBackupGraph.Table(s.Collection), out var matches) && matches.ContainsKey(s.Source))).Take(20).Select(s => "An independently copied " + s.Collection + " record differs from a previously restored version; existing work is retained.").Distinct().ToArray()); } public async Task Restore(string confirmation, Func upload) { using var token = JsonDocument.Parse(confirmations.Unprotect(confirmation)); if (token.RootElement.GetProperty("User").GetInt32() != User) throw new UnauthorizedAccessException(); var plan = token.RootElement.GetProperty("Plan").Deserialize()!; var completed=await repository.Receipt(plan.Operation,User);if(completed!=null){completed.AlreadyCompleted=true;return completed;} if (plan.Expires < DateTime.UtcNow) throw new ArgumentException("Preview expired. Check your projects before uploading and previewing again."); BookBackupPackage package;try{package=upload(plan.Upload);}catch(UnauthorizedAccessException){throw new ArgumentException("The original upload is no longer available. Check your projects for the previous result before uploading again.");} var requestHash = BookBackupGraph.Hash(new { Package = package.Integrity, plan.Books, plan.Destination, plan.Name }); BookRecoveryReceipt? receipt; Guid? reservationId = null; ProjectBackupFileStage? staged = null; try { using (var transaction = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable, Timeout = TimeSpan.FromMinutes(5) }, TransactionScopeAsyncFlowOption.Enabled)) { await repository.Begin(plan.Operation, User); receipt = await repository.Receipt(plan.Operation, User); if (receipt != null) { if (receipt.RequestHash != requestHash) throw new ArgumentException("Restore retry does not match its confirmation."); receipt.AlreadyCompleted = true; transaction.Complete(); return receipt; } var selected = SelectPackage(package, plan.Books); var target = plan.Destination == 0 ? null : await OwnerSnapshot(plan.Destination); if (target != null && SnapshotHash(target) != plan.DestinationHash) throw new ArgumentException("The destination changed since preview. Preview again to preserve its latest work."); var capacity = await subscriptions.ReserveBookSlotsAsync(User, selected.Data.Books.Count); if (!capacity.Allowed) throw new ArgumentException(capacity.Message); reservationId = capacity.ReservationID; var project = plan.Destination == 0 ? await imports.CreateProjectShellAsync(plan.Name, selected.Project?.Description, User) : plan.Destination; var prepared = await Prepare(package, selected, target, project, plan.Name); var graph = prepared.Graph; var resource = await subscriptions.CanUseResourcesAsync(User, new SubscriptionResourceRequest { AdditionalBooks = selected.Data.Books.Count, FinalChapterCounts = selected.Data.Books.Select(b => selected.Data.Chapters.Count(c => c.BookID == b.BookID)).ToArray(), FinalSceneCounts = selected.Data.Books.Select(b => selected.Data.Scenes.Count(s => selected.Data.Chapters.Any(c => c.ChapterID == s.ChapterID && c.BookID == b.BookID))).ToArray(), FinalCharacterCount = (target?.Data.Characters.Count ?? 0) + prepared.Graph.Data.Characters.Count }); if (!resource.Allowed) throw new ArgumentException(resource.Message); var storage = await subscriptions.CanUploadFileAsync(User, prepared.Graph.Files.Sum(f => (long)f.Data.Length) + prepared.Graph.Data.MapReferenceImages.Sum(i => (long)(i.ImageData?.Length ?? 0))); if (!storage.Allowed) throw new ArgumentException(storage.Message); staged = await files.StageAsync(graph, true); var previousMapRevision=target?.Data.StoryMaps.Select(m=>m.Revision).DefaultIfEmpty().Max()??0; if (target != null) { var order = target.Data.Books.Select(b => b.SortOrder).DefaultIfEmpty().Max(); var number = target.Data.Books.Select(b => b.BookNumber).DefaultIfEmpty().Max(); foreach (var b in graph.Data.Books.OrderBy(b => b.SortOrder)) { b.SortOrder = ++order; b.BookNumber = ++number; } BookBackupGraph.Merge(target, graph); graph = target; } var error = ProjectBackupMapValidation.Validate(graph) ?? ProjectBackupGraphValidation.Validate(graph); if (error != null) throw new ArgumentException(error); await imports.ApplyProjectBackupJsonAsync(project, BookRecoveryRepository.Encode(graph, protection,target==null?null:prepared.Graph.Data.Books.Select(b=>b.BookID).ToArray())); foreach(var map in graph.Data.StoryMaps)map.Revision=Math.Max(map.Revision,previousMapRevision)+1; // Audited SQL invalidates prior map edit tokens. var verified = await backups.GetProjectBackupAsync(project, User) ?? throw new InvalidOperationException("Committed graph verification failed."); await files.CaptureAsync(verified); PlotLine.Services.Manuscript.ParagraphRecovery.VerifyStored(graph,verified,prepared.Graph.Data.Books.Select(b=>b.BookID)); var mappings = new List(); foreach (var source in prepared.Sources) { var table = BookBackupGraph.Table(source.Collection); if (!prepared.Maps.TryGetValue(table, out var map) || !map.TryGetValue(source.Source, out var id)) continue; var identity = BookBackupGraph.Identity(source.Collection)!; var row = BookBackupGraph.Rows(verified, source.Collection).SingleOrDefault(r => Equals(BookBackupGraph.Value(r, identity), id)) ?? throw new InvalidOperationException("Restored entity verification failed."); var expected=BookBackupGraph.Rows(graph,source.Collection).SingleOrDefault(r=>Equals(BookBackupGraph.Value(r,identity),id));if(source.Collection is not ("GenreMetricPresets" or "GenreMetricPresetMetrics")&&expected!=null&&BookBackupGraph.StoredHash(source.Collection,expected)!=BookBackupGraph.StoredHash(source.Collection,row))throw new InvalidOperationException("Stored "+source.Collection+" fields differ: "+string.Join(",",ProjectBackupStoredFieldContract.Columns(source.Collection).Where(field=>JsonSerializer.Serialize(BookBackupGraph.Value(expected,field))!=JsonSerializer.Serialize(BookBackupGraph.Value(row,field))))+"; nothing was committed.");mappings.Add(new() { PortableKey = source.Key, Collection = source.Collection, DestinationID = id, SourceHash = source.Hash, DestinationHash = SourceHash(verified, source.Collection, row) }); } await repository.Complete(plan.Operation, project, User, selected.Data.Books.Count, requestHash, mappings); receipt = new() { ProjectID = project, BooksCreated = selected.Data.Books.Count, RequestHash = requestHash }; transaction.Complete();staged?.Commit(); // Retain bytes if the SQL commit outcome becomes uncertain; receipt retry resolves it safely. } staged?.Commit(); return receipt!; } finally { staged?.Dispose(); if (reservationId.HasValue) await subscriptions.ReleaseBookSlotReservationAsync(reservationId.Value); } } }