Unify selective book backups and transactional restore
This commit is contained in:
parent
00f7305dcb
commit
b4bf21328e
BIN
Docs/Recovery/Images/book-restore-desktop.png
Normal file
BIN
Docs/Recovery/Images/book-restore-desktop.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 133 KiB |
BIN
Docs/Recovery/Images/book-restore-narrow-dark.png
Normal file
BIN
Docs/Recovery/Images/book-restore-narrow-dark.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 105 KiB |
35
Docs/Recovery/book-backup-contract.md
Normal file
35
Docs/Recovery/book-backup-contract.md
Normal file
@ -0,0 +1,35 @@
|
||||
# Selective book recovery contract — implementation decisions
|
||||
|
||||
Book capacity counts every owned book, active or archived, even in archived projects. Downloads never delete data or release capacity. Existing Delete Forever is explicit and separate; deletion releases the slot only on commit.
|
||||
|
||||
Author package: `PlotDirector.BookBackup`, version `2.0`, `.plotdirector`, UTF-8 JSON. It wraps the proven project graph plus book selection, typed portable source identities and an integrity SHA256. Project snapshot format1.4 adds recovery-critical native review/Intent state. Existing1.0–1.3 readers remain supported with explicit completeness warnings. Current-format missing categories are errors, not inferred empty data.
|
||||
|
||||
All common project entity definitions (characters, locations, maps/floors, relationships, plots, assets and project settings) are retained deterministically. Book-owned content/history is filtered by the existing typed graph. Required cross-book canonical dependencies fail selection with a request to include the connected books. Nullable references from common definitions to excluded books/scenes are recorded as external source references and detached in the selected graph, with a visible warning and persisted external-reference history. They never become coincidentally matching destination database IDs. Unrelated book prose, attachments, goals and scene history are not exported.
|
||||
|
||||
Restore creates new books in a new or owner-authorised existing project. Existing project content is captured, validated and merged under the same serializable operation; the proven apply/file-stage engine is reused. Preview is bound to immutable uploaded content, selection, destination and destination snapshot. Stale destination previews require review again. No existing shared data is overwritten.
|
||||
|
||||
Portable keys are namespaced by a durable source-project GUID and typed entity identity. Destination mappings are scoped to the authorised target project; matching names/numbers alone never permit reuse. Stored-field compatibility and dependency remapping are checked; conflicts create independent copies. A restore operation has a durable author-scoped receipt and content/destination fingerprint for duplicate-safe retries.
|
||||
|
||||
Native review decisions and saved Intent evidence/decisions are portable. Encrypted review captures are decrypted only by the source server and reprotected on the destination; ciphertext, credentials, grants and live sessions are not portable. Imported review captures are historical/unbound. Native operation receipts and live cursor mappings are not replayed; stale receipts are invalidated/checked against canonical records. Intent evidence whose source identity/hash changes remains labelled historical/stale, with author decisions preserved.
|
||||
|
||||
Saved restore points remain a distinct same-project rewind, owner-authorised and safety-backed. Older points that omit populated recovery-critical state must fail closed. Archive/Unarchive remains visibility only. No backup workflow automatically deletes or claims a browser download proves safe local storage.
|
||||
|
||||
Implementation and qualification evidence will be recorded in the delivery report. Conservative refusals are explicit limitations, never successful partial backups.
|
||||
|
||||
## Bounded compatibility and inclusion details
|
||||
|
||||
Files are currently bounded to 64 MiB serialized JSON (including embedded bytes); an oversized export refuses without emitting an incomplete file. Uploads are author-bound, immutable, memory-bounded and expire after 30 minutes. A newer upload invalidates that author's previous upload; confirmations expire after 20 minutes. Restarting the application requires re-uploading. Retrying the same valid confirmation is receipt-safe; a new upload of a book already present in the same destination refuses instead of duplicating it. A deliberately independent new project can receive another copy if capacity permits.
|
||||
|
||||
Book-specific author plot seeds follow their owning book; project-wide seeds remain included. Timeline view presets are book/filter-specific: only presets valid for the selected book/scene graph are included. Project-wide illustration definitions travel as common data; conflicting internal demand keys receive a new recovery key without replacing existing content. Global metric/relationship vocabulary is resolved through the existing import lookup contract. Existing destination singleton timeline settings win. Maps are independent copies; identical image blobs can be reused within the authorised destination, with exact byte/type/dimension checks.
|
||||
|
||||
Optional detached references can reconnect when the destination already contains a matching, unchanged, mapped source entity. Otherwise their typed source reference stays as disconnected history. Required cross-book references require their connected book first or the combined selection; no guessed reference is inserted. Previously imported shared definitions reuse only when both exported and current destination fingerprints and all remapped stored dependencies agree. Existing entities without a proven mapping are independent copies, even if their names match. This conservative policy can create duplicates when restoring to the original project; it never guesses ownership from an exported number.
|
||||
|
||||
All restores are additive. There is no replace-existing-book option. New recovery tables retain operation/mapping provenance; mappings are never considered authority without a current project-owner check and existence/content checks. Portable Intent evidence keeps original input-hash provenance but receives an invalidated destination input hash, so it cannot masquerade as fresh analysis. Native review captures get new review/manuscript identities on cross-project import and no live session. Native operation/review-import receipts are excluded from packages; same-project replacement checks/removes receipts whose canonical chapters/build/scene counts no longer exist.
|
||||
|
||||
Imported active web files (HTML, SVG, XML, JavaScript and CSS) keep their bytes but receive a `.bin` storage suffix, preventing a backup from publishing executable same-origin web content. Original attachment metadata remains available; these files may need explicit local recovery to use their original format. Other supported uploaded files retain normal extensions.
|
||||
|
||||
Source compatibility fingerprints normalise primary/foreign identities to typed portable keys, project ownership to its destination scope, and uploaded paths to content checksums. This allows a restored/re-exported book to reuse unchanged common entities despite different local IDs and generated filenames. Destination fingerprints separately retain actual stored references and file checksums to detect intervening edits. Names never establish portable identity. Multiple source authors' Intent assessments remain distinct historical records after ownership transfer; actor provenance is retained without granting those source users destination access.
|
||||
|
||||
Appending to an existing project uses a server-only protected append mode: existing Native review ciphertext/session binding and existing Intent records are left intact; only newly created books receive the portable historical state. The SQL guard forbids removal of old books in append mode. Package uploads cannot select this mode directly. Replacement/rewind retains the separate full-state safety policy.
|
||||
|
||||
Independent copies that share original provenance receive distinct deterministic source namespaces when exported, with fork aliases retained in the existing authorised mapping table. Identity assignment considers the full source project before selecting books, so choosing a different book subset does not collapse independent common entities back together. Required, non-detachable cross-book dependencies refuse export rather than producing a standalone file that cannot reconstruct the selection. Named global vocabularies must resolve in the destination; no new book restore falls back to an unverified exported lookup number. Historical files lacking those names may require assisted recovery.
|
||||
57
Docs/Recovery/book-backup-implementation.md
Normal file
57
Docs/Recovery/book-backup-implementation.md
Normal file
@ -0,0 +1,57 @@
|
||||
# Unified book backup and restore — 6 November 2026
|
||||
|
||||
## Delivered implementation
|
||||
|
||||
Projects and the shared application/PWA menus use one **Back up books** / **Restore books from backup** workflow. Book actions preselect one book; project actions select all, with individual selection available. Manuscript onboarding remains separate. The PWA ribbon uses the same wizards and an antiforgery-protected manuscript-onboarding action. The old ordinary Import JSON route redirects to restore; compatibility readers and guarded POST endpoints remain for recovery. Archive/Unarchive is distinct from downloaded recovery and saved-point rewind.
|
||||
|
||||
The implementation extends the audited project graph, stored-field contract, typed remapper, file staging and transactional SQL apply engine. It does not replace those mechanisms. See [the package and identity contract](book-backup-contract.md) for inclusion, conflict and compatibility decisions.
|
||||
|
||||
`PlotDirector.BookBackup` version2.0 wraps project snapshot1.4. Required native/Intent author state is mandatory in current packages. Upload validation precedes persistent changes. Previews bind the author, immutable upload, selection, destination and snapshot hash in an expiring protected confirmation. Explicit confirmation is required. Restore is additive and owner-authorised; conflicting definitions copy independently. Serializable SQL, account-scoped locks, slot reservations, fresh file names, rollback cleanup and durable receipts protect commit/retry.
|
||||
|
||||
Native captures are source-decrypted and destination-reprotected, with new portable-import review/manuscript identities and no live session. Author review/Intent decisions and original evidence/provenance survive. Receipts and consent/job authority do not replay. Restored Intent evidence is stale until reassessed. Historical project formats1.0–1.3 have explicit limitations; incomplete current packages refuse.
|
||||
|
||||
Migration236 adds source namespaces, typed mappings, external-reference history and operation receipts. It wraps the existing SQL graph engine for native/Intent state and invalid receipt cleanup, and enforces book capacity on net-positive saved-point rewinds. Usage/reservation/summary procedures count archived books and books in archived projects. The existing explicit archived-book permanent-delete route is extended for newer dependent tables; download never invokes it.
|
||||
|
||||
## Verification and deployment
|
||||
|
||||
Qualification results, migration backup identity and release details are recorded below after the final gates. No Production changes or Windows Companion installation/source changes are included.
|
||||
|
||||
## Deliberate bounds
|
||||
|
||||
- 64MiB JSON package ceiling, at most100 selected books per restore, 30-minute author upload workspace and20-minute confirmations. Restart requires re-upload.
|
||||
- Required unresolved cross-book dependencies refuse; select connected books or restore the mapped dependency first. Optional external references remain visible disconnected history when safe reconnection is unavailable.
|
||||
- Maps copy as independent bundles; identical authorised image blobs can reuse. Shared entities without proven durable mappings copy independently; the original project can therefore receive duplicate common definitions rather than an unsafe name/number merge.
|
||||
- Existing destination project/singleton timeline settings are retained. Book/filter-specific timeline presets belonging to excluded books are excluded.
|
||||
- A file integrity checksum detects accidental alteration, not cryptographic proof of who authored a backup. Imported content still undergoes ownership, typed graph, file and resource validation.
|
||||
- SQL/files publication is transaction-backed; a process kill before commit can leave unreferenced newly staged files, but not published references to partially committed books. Exceptions before commit is requested delete staged files. Once commit is requested, files are retained if its outcome becomes uncertain; an original-confirmation receipt retry resolves completion without needing the temporary upload. This favours retaining unreferenced files over deleting bytes that might already have committed references. No background automatic import/analysis resumes.
|
||||
- Normal restore has no replace-existing-book option. Saved restore points remain the explicit same-project historical rewind with safety snapshot and owner checks.
|
||||
|
||||
## Qualification evidence
|
||||
|
||||
All SQL mutation tests use the literal, extended-property-guarded `PlotDirector_Phase2_20261103_2305` synthetic database. No existing author's project was used for deletion, replacement or restore testing. Before qualification, a unique COPY_ONLY/CHECKSUM backup was taken and RESTORE VERIFYONLY succeeded: `/var/opt/mssql/backups/PlotDirector_Phase2_20261103_2305-book-recovery-20261106T160114.bak`.
|
||||
|
||||
- Solution build: zero warnings/errors (`dotnet build PlotLine.slnx --disable-build-servers -m:1 /p:UseSharedCompilation=false`).
|
||||
- Selective recovery database harness: 33 passed assertions. Covers single/multiple/all books, new/existing project, cross-account transfer with independent encryption keys, exact prose and uploaded-file SHA256 values, map/floor-plan graph, multiple authors' Intent decisions, populated native receipts excluded from packages, full-rewind receipt invalidation even with unchanged IDs, live destination capture preservation, re-export/shared reuse after local-ID changes, divergent copies/fork identity stability, stale destination refusal, binary handling of active web files, archive accounting, full-capacity refusal without project allocation, backup/delete/restore slot exchange, injected file and SQL failures, durable cacheless receipt retry, project deletion cleanup, and expired-account export versus restore refusal.
|
||||
- Existing guarded project-transfer harness: exit0. SQL-to-backup comparison covers106 populated entity sets/2,599 stored values; copy comparison covers103 persistent collections/2,467 stored values, and in-place restore compares2,563 stored values. Its53 malformed-data/map/version pre-allocation cases, actor/reference isolation, uploaded files, writing plans, omission/refusal guards, same-project safety restore and historical illustration handling remain enabled. Direct SQL regression inputs now explicitly model the trusted protected-state boundary so old negative tests still reach their intended graph guards.
|
||||
- Separate rollback-only capacity script covers a book inside an archived project, unarchive invariance, full capacity rejection and capacity after explicit deletion.
|
||||
|
||||
Commands:
|
||||
|
||||
```sh
|
||||
dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj -- --project-transfer-database --book-recovery-only PlotDirector_Phase2_20261103_2305
|
||||
dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj -- --project-transfer-database PlotDirector_Phase2_20261103_2305
|
||||
dotnet run --no-build --project PlotLine.Tests/PlotLine.Tests.csproj
|
||||
node PlotLine.Tests/Browser/backup-upload-generation.cjs
|
||||
# With the existing --toolbar-browser-host running on loopback5238:
|
||||
node PlotLine.Tests/Browser/book-recovery.cjs
|
||||
```
|
||||
|
||||
The browser host renders actual compiled Razor and application assets with controlled fixture data; it is separate from the application and does not connect to a database. It is not evidence of native Windows/Word execution. Test logs and fixture screenshots are under `/tmp/book-recovery-*`; the synthetic portable fixture is outside the repository under `/srv/repos/plotdirector-phase2-artifacts/book-recovery-validation/`.
|
||||
|
||||
Final normal regression harness: **414 passed checks, exit0**. Browser regressions pass for actual Razor at1440px and390px; additional narrow theme checks use modern-light, modern-dark and warm-dark (the main fixture is warm-light). They cover book select-all/clear, explicit confirmation, capacity-disabled restore, manuscript-onboarding POST/antiforgery wiring, and absence of legacy ribbon import. The separate FileReader regression forces out-of-order completion and manual edits. These are controlled fixtures, not screenshots of an author's data.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
Historical compatibility retains the existing1.0–1.3 readers and refusal/warning policy. These tests cover version/older-shape contracts; no claim is made that an arbitrary external historical archive contains data that its original writer never exported. Missing vocabulary definitions or required dependencies fail safely rather than trusting numeric IDs.
|
||||
105
PlotLine.Tests/BookRecoveryDatabaseTests.cs
Normal file
105
PlotLine.Tests/BookRecoveryDatabaseTests.cs
Normal file
@ -0,0 +1,105 @@
|
||||
using Dapper;
|
||||
using System.Data;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.Models;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
internal static class BookRecoveryDatabaseTests
|
||||
{
|
||||
static void Check(bool value, string text) { if (!value) throw new Exception(text); Console.WriteLine("PASS " + text); }
|
||||
public static async Task Run(ISqlConnectionFactory factory, IProjectBackupFiles files, IUploadStorageService uploads, int owner, int other, int project, int book, int chapter, int scene)
|
||||
{
|
||||
using var db = factory.CreateConnection(); Check(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()") == "PlotDirector_Phase2_20261103_2305", "book recovery refuses live databases");
|
||||
var protection = new EphemeralDataProtectionProvider(); var repository = new BookRecoveryRepository(factory, protection); var backups = new ProjectBackupRepository(factory, protection); var imports = new ImportRepository(factory); var sourceId = Guid.NewGuid();
|
||||
var second = await db.ExecuteScalarAsync<int>("INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder,IsArchived) VALUES(@project,N'Second archived book',2,2,1);SELECT CONVERT(int,SCOPE_IDENTITY())", new { project });
|
||||
var secondChapter = await db.ExecuteScalarAsync<int>("INSERT dbo.Chapters(BookID,ChapterNumber,ChapterTitle,SortOrder,RevisionStatusID) SELECT @second,1,N'Second chapter',1,RevisionStatusID FROM dbo.Chapters WHERE ChapterID=@chapter;SELECT CONVERT(int,SCOPE_IDENTITY())", new { second, chapter });
|
||||
var capture = new AiChapterRequest { ChapterTitle = "Reviewed chapter", BookId = book, ManuscriptId = Guid.NewGuid(), SessionId = Guid.NewGuid(), RequestId = sourceId, ChapterStart = 10, ChapterEnd = 40, Paragraphs = [new() { Index = 1, Start = 10, End = 40, Text = "Recovered captured prose.\r" }] };
|
||||
var result = new AiChapterResult { RequestId = sourceId, State = "complete", ChapterTitle = "Reviewed chapter", Scenes = [new() { Start = 10, End = 40, Title = "Approved", Summary = "Author summary" }] };
|
||||
await db.ExecuteAsync("INSERT dbo.NativeChapterReviews(ReviewID,UserID,BookID,ManuscriptID,ChapterStart,ChapterEnd,ContentHash,ResultJson,DecisionsJson,Version,EncryptedSource) VALUES(@sourceId,@owner,@book,@manuscript,10,40,@hash,@result,@decision,4,@encrypted);INSERT dbo.WritingIntentAssessments(UserID,SceneID,InputHash,ResultsJson,DecisionsJson,Model) VALUES(@owner,@scene,REPLICATE('A',64),@intent,N'{\"purpose\":\"deferred\"}',N'synthetic');", new { sourceId, owner, book, manuscript = capture.ManuscriptId, hash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new { capture.ChapterStart, capture.ChapterEnd, capture.Paragraphs }))), result = JsonSerializer.Serialize(result), decision = "[{\"Index\":0,\"State\":\"approved\",\"Title\":\"Edited author title\",\"Summary\":\"Kept\"}]", encrypted = protection.CreateProtector("NativeImport.Source.v1").Protect(JsonSerializer.Serialize(capture)), scene, intent = JsonSerializer.Serialize(new[] { new IntentEvidence("purpose", "partial", "Historical evidence", "Exact quote", "Author objective") }) });
|
||||
await db.ExecuteAsync("INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole,IsActive) VALUES(@project,@other,N'Collaborator',1);INSERT dbo.WritingIntentAssessments(UserID,SceneID,InputHash,ResultsJson,DecisionsJson,Model) SELECT @other,SceneID,InputHash,ResultsJson,N'{\"purpose\":\"achieved\"}',Model FROM dbo.WritingIntentAssessments WHERE UserID=@owner AND SceneID=@scene",new{project,other,owner,scene});
|
||||
ICurrentUserService Actor(int id) => NativeWorkflowTests.Proxy<ICurrentUserService>((n, a) => n switch { "get_UserId" => (int?)id, "get_IsAuthenticated" => true, _ => "synthetic" });
|
||||
var subscription = new SubscriptionService(new SubscriptionRepository(factory), NativeWorkflowTests.Proxy<IUserFileRepository>((n, a) => n == "GetStorageUsageForOwnerAsync" ? Task.FromResult(0L) : throw new Exception(n)));
|
||||
var destinationProtection=new EphemeralDataProtectionProvider();var destinationBackups=new ProjectBackupRepository(factory,destinationProtection);var destinationRepository=new BookRecoveryRepository(factory,destinationProtection);
|
||||
BookRecoveryService Service(int id) => id==other?new(destinationBackups,imports,destinationRepository,files,subscription,Actor(id),destinationProtection):new(backups, imports, repository, files, subscription, Actor(id), protection);
|
||||
var source = Service(owner); var destination = Service(other); var package = await source.Export(project, [book]); var text = JsonSerializer.Serialize(package); var parsed = BookRecoveryService.Read(text);
|
||||
var artifactDirectory="/srv/repos/plotdirector-phase2-artifacts/book-recovery-validation";Directory.CreateDirectory(artifactDirectory);await File.WriteAllTextAsync(Path.Combine(artifactDirectory,"latest.plotdirector"),text);
|
||||
Check(parsed.Snapshot.Data.Books.Single().BookID == book && !parsed.Snapshot.Data.Chapters.Any(c => c.BookID == second), "single-book export excludes unrelated archived-book content");
|
||||
Check(!text.Contains(capture.SessionId.ToString()) && !text.Contains("EncryptedSource") && parsed.Snapshot.Recovery.NativeReviews.Single().SourceJson!.Contains("Recovered captured prose"), "portable native source excludes live session and server ciphertext");
|
||||
var all = await source.Export(project, [book, second]); Check(all.Snapshot.Data.Books.Count == 2 && all.Snapshot.Data.Books.Any(b => b.IsArchived), "multi/all-book export retains archive status");
|
||||
var archived = await source.Export(project, [second]); Check(archived.Snapshot.Data.Books.Single().IsArchived, "archived single-book backup remains available without releasing capacity");
|
||||
var originalBuild = package.Snapshot.Data.OnboardingManuscriptBuilds.First().OnboardingManuscriptBuildID;
|
||||
await db.ExecuteAsync("INSERT dbo.NativeImportOperations(OperationID,UserID,BookID,BuildID,ChaptersCreated,ScenesCreated) VALUES(NEWID(),@owner,@book,@originalBuild,1,1);INSERT dbo.NativeReviewImports(BookID,ChapterKey,ContentHash,ReviewID,ReviewVersion,ChapterID,BuildID) VALUES(@book,N'synthetic-source',REPLICATE('B',64),@sourceId,4,@chapter,@originalBuild)", new { owner, book, originalBuild, sourceId, chapter });
|
||||
var withReceipts=await source.Export(project,[book]);Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.NativeImportOperations WHERE BookID=@book",new{book})==1&&!JsonSerializer.Serialize(withReceipts).Contains("NativeImportOperations"),"populated source import receipts are excluded as operational authority");
|
||||
var samePoint=await new ProjectRestorePointRepository(factory).CreateAsync(project,"Same-ID rewind fixture","Manual",JsonSerializer.Serialize(all.Snapshot),"Synthetic only");await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,SourceRestorePointID=samePoint.ProjectRestorePointID,JsonData=BookRecoveryRepository.Encode(all.Snapshot,protection)},commandType:CommandType.StoredProcedure);
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.NativeImportOperations WHERE BookID=@book",new{book})==0&&await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.NativeReviewImports WHERE BookID=@book",new{book})==0,"rewinding invalidates native receipts even when canonical chapter IDs still exist");
|
||||
var upload = Guid.NewGuid(); var preview = await destination.Preview(upload, parsed, [book], 0, "Recovered book project"); var restored = await destination.Restore(preview.Confirmation, _ => parsed); var after = (await destinationBackups.GetProjectBackupAsync(restored.ProjectID, other))!;
|
||||
Check(after.Data.Books.Count == 1 && after.Recovery.NativeReviews.Single().DecisionsJson!.Contains("Edited author title") && after.Recovery.IntentAssessments.Count==2&&after.Recovery.IntentAssessments.Any(a=>a.DecisionsJson.Contains("deferred"))&&after.Recovery.IntentAssessments.Any(a=>a.DecisionsJson.Contains("achieved")), "cross-account restore with independent encryption keys preserves native and multi-author Intent decisions");
|
||||
Check(after.Data.SceneManuscriptSources.Select(x => x.SourceText).SequenceEqual(parsed.Snapshot.Data.SceneManuscriptSources.Select(x => x.SourceText)), "exact saved manuscript prose survives book restore");
|
||||
await files.CaptureAsync(after); Check(after.Files.Select(f => f.Sha256).Order().SequenceEqual(parsed.Snapshot.Files.Select(f => f.Sha256).Order()), "all uploaded image and attachment bytes match their restored SHA256 checksums");
|
||||
Check(after.Data.MapFeatures.Count == parsed.Snapshot.Data.MapFeatures.Count && after.Data.FloorPlanBlocks.Count == parsed.Snapshot.Data.FloorPlanBlocks.Count, "map geometry and floor-plan blocks survive typed graph restoration");
|
||||
var beforeRetry = await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Books"); await destination.Restore(preview.Confirmation, _ => parsed); Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Books") == beforeRetry, "same confirmation retry is durable and duplicate safe");
|
||||
var cachelessRetry=await destination.Restore(preview.Confirmation,_=>throw new UnauthorizedAccessException());Check(cachelessRetry.AlreadyCompleted,"durable receipt confirms a completed restore even after its upload workspace is gone");
|
||||
var keptReview=after.Recovery.NativeReviews.Single();var liveCapture=JsonSerializer.Deserialize<AiChapterRequest>(keptReview.SourceJson!)!;liveCapture.SessionId=Guid.NewGuid();var liveCipher=destinationProtection.CreateProtector("NativeImport.Source.v1").Protect(JsonSerializer.Serialize(liveCapture));var liveResult=System.Text.Json.Nodes.JsonNode.Parse(keptReview.ResultJson)!;liveResult["CaptureSession"]=liveCapture.SessionId;var liveResultJson=liveResult.ToJsonString();await db.ExecuteAsync("UPDATE dbo.NativeChapterReviews SET EncryptedSource=@liveCipher,ResultJson=@liveResultJson WHERE ReviewID=@id",new{liveCipher,liveResultJson,id=keptReview.ReviewID});
|
||||
var allPreview = await source.Preview(Guid.NewGuid(), all, [book, second], 0, "All-books recovery"); var allReceipt = await source.Restore(allPreview.Confirmation, _ => all); var allAfter = (await backups.GetProjectBackupAsync(allReceipt.ProjectID, owner))!;
|
||||
Check(allAfter.Data.Books.Count == 2 && allAfter.Data.Scenes.Count == all.Snapshot.Data.Scenes.Count, "all books restore together with exact story structure");
|
||||
var reexported=await source.Export(allReceipt.ProjectID,[allAfter.Data.Books.Single(b=>b.IsArchived).BookID]);var reexportedBook=reexported.Snapshot.Data.Books.Single().BookID;
|
||||
var next = await destination.Preview(Guid.NewGuid(), reexported, [reexportedBook], restored.ProjectID, ""); var appended = await destination.Restore(next.Confirmation, _ => reexported); after = (await destinationBackups.GetProjectBackupAsync(appended.ProjectID, other))!; Check(after.Data.Books.Count == 2 && after.Data.Books.Count(b => b.IsArchived) == 1, "restore into an existing project preserves existing book and adds archived book");
|
||||
Check(await db.ExecuteScalarAsync<string>("SELECT EncryptedSource FROM dbo.NativeChapterReviews WHERE ReviewID=@id",new{id=keptReview.ReviewID})==liveCipher&&await db.ExecuteScalarAsync<string>("SELECT ResultJson FROM dbo.NativeChapterReviews WHERE ReviewID=@id",new{id=keptReview.ReviewID})==liveResultJson,"append restore preserves unrelated existing live native capture ciphertext and session binding exactly");
|
||||
Check(after.Data.Characters.Count == parsed.Snapshot.Data.Characters.Count, "re-exported unchanged shared characters reuse scoped source identities despite different local database IDs");
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.NativeImportOperations o JOIN dbo.Books b ON b.BookID=o.BookID WHERE b.ProjectID=@id", new { id = restored.ProjectID }) == 0, "import receipts are not replayed as destination authority");
|
||||
var conflictingPreview = await source.Preview(Guid.NewGuid(), package, [book], 0, "Independent edits"); var conflicting = await source.Restore(conflictingPreview.Confirmation, _ => package); var conflictBefore = (await backups.GetProjectBackupAsync(conflicting.ProjectID, owner))!;
|
||||
await db.ExecuteAsync("UPDATE dbo.Characters SET CharacterName=N'Independent destination edit' WHERE CharacterID=@id", new { id = conflictBefore.Data.Characters.First().CharacterID });
|
||||
var conflictAppend = await source.Preview(Guid.NewGuid(), archived, [second], conflicting.ProjectID, ""); await source.Restore(conflictAppend.Confirmation, _ => archived); var conflictAfter = (await backups.GetProjectBackupAsync(conflicting.ProjectID, owner))!;
|
||||
Check(conflictAfter.Data.Characters.Any(c => c.CharacterName == "Independent destination edit") && conflictAfter.Data.Characters.Count > conflictBefore.Data.Characters.Count, "divergent shared definitions copy independently without overwriting destination work");
|
||||
var forkBackup=await source.Export(conflicting.ProjectID,conflictAfter.Data.Books.Select(b=>b.BookID).ToArray());BookRecoveryService.Read(JsonSerializer.Serialize(forkBackup));var forkAgain=await source.Export(conflicting.ProjectID,[conflictAfter.Data.Books.First().BookID]);BookRecoveryService.Read(JsonSerializer.Serialize(forkAgain));
|
||||
Check(forkBackup.Identities.Where(p=>p.Key.StartsWith("Characters:")).All(p=>forkAgain.Identities.GetValueOrDefault(p.Key)==p.Value),"independent conflicting copies re-export with distinct stable shared identities across book selections");
|
||||
var staleProject=await imports.CreateProjectShellAsync("Stale preview fixture",null,owner);var stalePreview=await source.Preview(Guid.NewGuid(),package,[book],staleProject,"");
|
||||
await db.ExecuteAsync("UPDATE dbo.Projects SET Description=N'Independent edit after preview' WHERE ProjectID=@staleProject",new{staleProject});
|
||||
try{await source.Restore(stalePreview.Confirmation,_=>package);throw new Exception("Stale destination accepted");}catch(ArgumentException){}
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Books WHERE ProjectID=@staleProject",new{staleProject})==0,"destination edits invalidate stale confirmations without adding books");
|
||||
var oldPath=package.Snapshot.Files.First().Path;var activePath=oldPath[..oldPath.LastIndexOf('.')]+".html";
|
||||
var activePackage=JsonSerializer.Deserialize<BookBackupPackage>(JsonSerializer.Serialize(package).Replace(oldPath,activePath))!;
|
||||
activePackage.Integrity=BookBackupGraph.Hash(new{activePackage.SourceProjectKey,activePackage.Snapshot,activePackage.Identities,activePackage.Warnings});activePackage=BookRecoveryService.Read(JsonSerializer.Serialize(activePackage));
|
||||
var activePreview=await source.Preview(Guid.NewGuid(),activePackage,[book],0,"Active file recovery");var activeReceipt=await source.Restore(activePreview.Confirmation,_=>activePackage);var activeAfter=(await backups.GetProjectBackupAsync(activeReceipt.ProjectID,owner))!;await files.CaptureAsync(activeAfter);
|
||||
Check(activeAfter.Files.All(f=>!f.Path.EndsWith(".html",StringComparison.OrdinalIgnoreCase))&&activeAfter.Files.Any(f=>f.Path.EndsWith(".bin")&&f.Sha256==package.Snapshot.Files.First().Sha256),"active web file bytes recover as binary downloads without publishing executable HTML");
|
||||
var quota = await db.ExecuteScalarAsync<int>("INSERT dbo.SubscriptionLevel(Name,DisplayName,MaxBooks,MaxChaptersPerBook,MaxScenesPerBook,MaxCharactersPerProject,MaxStorageMB,MaxCollaborators,SortOrder,RequiresStripeSubscription) VALUES(CONVERT(nvarchar(36),NEWID()),N'Recovery capacity test',2,1000,10000,10000,10000,100,0,0);SELECT CONVERT(int,SCOPE_IDENTITY());");
|
||||
await db.ExecuteAsync("INSERT dbo.SubscriptionOverride(UserID,SubscriptionLevelID,StartDateUTC,Reason,CreatedByUserID,ModifiedByUserID) VALUES(@other,@quota,DATEADD(minute,-1,SYSUTCDATETIME()),N'Synthetic capacity test',@other,@other)", new { other, quota });
|
||||
Check((await subscription.GetUsageSummaryAsync(other)).BooksUsed == 2, "active and archived books both consume capacity");
|
||||
var refused = await destination.Preview(Guid.NewGuid(), all, [book, second], 0, "No capacity"); var projectsBefore = await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects"); try { await destination.Restore(refused.Confirmation, _ => all); throw new Exception("Full capacity accepted"); } catch (ArgumentException) { }
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects") == projectsBefore, "full-capacity restore refuses before project allocation");
|
||||
var exchanged=after.Data.Books.Single(b=>!b.IsArchived).BookID;await db.ExecuteAsync("UPDATE dbo.Books SET IsArchived=1 WHERE BookID=@exchanged",new{exchanged});await db.ExecuteAsync("dbo.BookHardDelete_ForOwner",new{BookID=exchanged,UserID=other},commandType:CommandType.StoredProcedure);
|
||||
Check((await subscription.GetUsageSummaryAsync(other)).BooksUsed==1,"explicit deletion frees one slot while the other archived book still counts");
|
||||
var exchangePreview=await destination.Preview(Guid.NewGuid(),package,[book],restored.ProjectID,"");await destination.Restore(exchangePreview.Confirmation,_=>package);var exchangedAfter=(await destinationBackups.GetProjectBackupAsync(restored.ProjectID,other))!;
|
||||
Check((await subscription.GetUsageSummaryAsync(other)).BooksUsed==2&&exchangedAfter.Data.Books.Count==2&&exchangedAfter.Data.SceneManuscriptSources.Select(x=>x.SourceText).SequenceEqual(package.Snapshot.Data.SceneManuscriptSources.Select(x=>x.SourceText)),"downloaded book can be deleted and restored into its former project using the released slot with exact prose");
|
||||
var projectsAtFailure = await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects");
|
||||
var failingFiles = NativeWorkflowTests.Proxy<IProjectBackupFiles>((n, a) => n == "StageAsync" ? throw new IOException("Synthetic interruption before file publication") : files.CaptureAsync((ProjectBackupExport)a![0]!));
|
||||
var failingService = new BookRecoveryService(backups, imports, repository, failingFiles, subscription, Actor(owner), protection); var failurePreview = await failingService.Preview(Guid.NewGuid(), package, [book], 0, "Interrupted restore");
|
||||
try { await failingService.Restore(failurePreview.Confirmation, _ => package); throw new Exception("Interrupted restore succeeded"); } catch (IOException) { }
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects") == projectsAtFailure, "interrupted file staging rolls back newly allocated project and books");
|
||||
var sqlPreview = await source.Preview(Guid.NewGuid(), package, [book], 0, "Synthetic forced SQL failure"); var pathsBefore = Directory.GetFiles(uploads.UploadsRootPath, "*", SearchOption.AllDirectories).Order().ToArray(); var projectsBeforeSql = await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects");
|
||||
await db.ExecuteAsync("CREATE OR ALTER TRIGGER dbo.BookRecoverySyntheticFailure ON dbo.Books AFTER INSERT AS BEGIN IF EXISTS(SELECT 1 FROM inserted b JOIN dbo.Projects p ON p.ProjectID=b.ProjectID WHERE p.ProjectName=N'Synthetic forced SQL failure') THROW 51000,'Injected synthetic restore failure',1;END;");
|
||||
try { try { await source.Restore(sqlPreview.Confirmation, _ => package); throw new Exception("Injected SQL failure did not execute"); } catch (Microsoft.Data.SqlClient.SqlException) { } }
|
||||
finally { await db.ExecuteAsync("DROP TRIGGER IF EXISTS dbo.BookRecoverySyntheticFailure"); }
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects") == projectsBeforeSql && pathsBefore.SequenceEqual(Directory.GetFiles(uploads.UploadsRootPath, "*", SearchOption.AllDirectories).Order()), "SQL refusal after staging rolls back project and deletes only newly staged files");
|
||||
await files.CaptureAsync(allAfter);var savedPoint=await new ProjectRestorePointRepository(factory).CreateAsync(allReceipt.ProjectID,"Capacity rewind fixture","Manual",JsonSerializer.Serialize(allAfter),"Synthetic only");
|
||||
var deleteBook = allAfter.Data.Books.Single(b => !b.IsArchived).BookID; await db.ExecuteAsync("UPDATE dbo.Books SET IsArchived=1 WHERE BookID=@deleteBook", new { deleteBook });
|
||||
await db.ExecuteAsync("dbo.BookHardDelete_ForOwner", new { BookID = deleteBook, UserID = owner }, commandType: CommandType.StoredProcedure);
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Books WHERE BookID=@deleteBook", new { deleteBook }) == 0, "explicit permanent deletion of a populated restored book releases its slot");
|
||||
var ownerUsed=await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID WHERE a.UserID=@owner AND a.AccessRole=N'Owner' AND a.IsActive=1",new{owner});
|
||||
await db.ExecuteAsync("UPDATE dbo.SubscriptionLevel SET MaxBooks=@ownerUsed WHERE SubscriptionLevelID=@quota;INSERT dbo.SubscriptionOverride(UserID,SubscriptionLevelID,StartDateUTC,Reason,CreatedByUserID,ModifiedByUserID) VALUES(@owner,@quota,DATEADD(minute,-1,SYSUTCDATETIME()),N'Synthetic rewind capacity',@owner,@owner)",new{ownerUsed,quota,owner});
|
||||
try{await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=allReceipt.ProjectID,SourceRestorePointID=savedPoint.ProjectRestorePointID,JsonData=BookRecoveryRepository.Encode(allAfter,protection)},commandType:CommandType.StoredProcedure);throw new Exception("Saved-point rewind bypassed book capacity");}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Message.Contains("capacity")){}
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Books WHERE BookID=@deleteBook",new{deleteBook})==0,"saved-point rewind cannot recreate a deleted book when the account is full");
|
||||
try { await destination.Export(project, [book]); throw new Exception("Foreign backup allowed"); } catch (Microsoft.Data.SqlClient.SqlException) { } catch (UnauthorizedAccessException) { }
|
||||
var node = System.Text.Json.Nodes.JsonNode.Parse(text)!; node["Integrity"] = "corrupt"; try { BookRecoveryService.Read(node.ToJsonString()); throw new Exception("Corrupt backup accepted"); } catch (ArgumentException) { }
|
||||
var removedReviews=conflictAfter.Recovery.NativeReviews.Select(r=>r.ReviewID).ToArray();var removedScenes=conflictAfter.Data.Scenes.Select(s=>s.SceneID).ToArray();await db.ExecuteAsync("UPDATE dbo.Projects SET IsArchived=1 WHERE ProjectID=@id",new{id=conflicting.ProjectID});
|
||||
var deleted=(IDictionary<string,object>)(await db.QuerySingleAsync("dbo.Archive_DeleteForever",new{EntityType="Project",EntityID=conflicting.ProjectID,ConfirmationText="DELETE",UserID=owner},commandType:CommandType.StoredProcedure));
|
||||
Check(Convert.ToBoolean(deleted["Succeeded"])&&await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.NativeChapterReviews WHERE ReviewID IN @removedReviews",new{removedReviews})==0&&await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.WritingIntentAssessments WHERE SceneID IN @removedScenes",new{removedScenes})==0,"project deletion cleans restored native and Intent author state without orphaned captures");
|
||||
await db.ExecuteAsync("UPDATE dbo.SubscriptionOverride SET RevokedDateUTC=SYSUTCDATETIME() WHERE UserID=@other;UPDATE dbo.UserSubscription SET TrialExpiryDateUTC='2000-01-01' WHERE UserID=@other",new{other});
|
||||
var expiredBackup=await destination.Export(restored.ProjectID,exchangedAfter.Data.Books.Select(b=>b.BookID).ToArray());BookRecoveryService.Read(JsonSerializer.Serialize(expiredBackup));var inactivePreview=await destination.Preview(Guid.NewGuid(),package,[book],0,"Inactive account restore");var inactiveProjects=await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects");
|
||||
try{await destination.Restore(inactivePreview.Confirmation,_=>package);throw new Exception("Inactive account allocated books");}catch(ArgumentException){}
|
||||
Check(inactivePreview.Available==0&&await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects")==inactiveProjects&&(await destination.Restore(preview.Confirmation,_=>throw new UnauthorizedAccessException())).AlreadyCompleted,"read-only accounts can export and check receipts but cannot allocate restored books");
|
||||
Console.WriteLine("PASS selective recovery real SQL new/existing project, cross-account identity, decisions, source, maps, archive capacity, corruption and retry");
|
||||
}
|
||||
}
|
||||
39
PlotLine.Tests/BookRecoveryTests.cs
Normal file
39
PlotLine.Tests/BookRecoveryTests.cs
Normal file
@ -0,0 +1,39 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
internal static class BookRecoveryTests
|
||||
{
|
||||
public static void ReadOnlyBackupAccess()=>ReadOnlyBackupAccessAsync().GetAwaiter().GetResult();
|
||||
private static async Task ReadOnlyBackupAccessAsync(){
|
||||
var user=NativeWorkflowTests.Proxy<ICurrentUserService>((n,a)=>n=="get_UserId"?(int?)1:throw new Exception(n));
|
||||
var subscription=NativeWorkflowTests.Proxy<ISubscriptionService>((n,a)=>throw new Exception("Read-only backup/validation must not use the edit-content gate."));
|
||||
var filter=new SubscriptionEnforcementFilter(user,subscription);
|
||||
foreach(var action in new[]{"ReviewBackup","Download","Upload","Preview","Confirm"}){
|
||||
var http=new Microsoft.AspNetCore.Http.DefaultHttpContext();http.Request.Method="POST";
|
||||
var descriptor=new Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor{ActionName=action};
|
||||
var context=new Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext(new Microsoft.AspNetCore.Mvc.ActionContext(http,new Microsoft.AspNetCore.Routing.RouteData(),descriptor),[],new Dictionary<string,object?>(),new PlotLine.Controllers.BookRecoveryController(null!,null!,null!,user));var called=false;
|
||||
await filter.OnActionExecutionAsync(context,()=>{called=true;return Task.FromResult(new Microsoft.AspNetCore.Mvc.Filters.ActionExecutedContext(context,[],context.Controller));});if(!called)throw new Exception("Backup read-only access blocked.");
|
||||
}
|
||||
}
|
||||
public static void Contracts()
|
||||
{
|
||||
var snapshot = new ProjectBackupExport { Project = new() { ProjectID = 1, ProjectName = "Fixture" }, Data = new() { Books = [new() { BookID = 1, ProjectID = 1, BookTitle = "First" }, new() { BookID = 2, ProjectID = 1, BookTitle = "Second", IsArchived = true }] } };
|
||||
var package = new BookBackupPackage { SourceProjectKey = Guid.NewGuid(), Snapshot = BookBackupGraph.Select(snapshot, [2], Guid.NewGuid()), Identities = new() { ["Books:2"] = Guid.NewGuid().ToString("N") + "/Books/2" } };
|
||||
package.Integrity = BookBackupGraph.Hash(new { package.SourceProjectKey, package.Snapshot, package.Identities, package.Warnings }); var json = JsonSerializer.Serialize(package);
|
||||
if (BookRecoveryService.Read(json).Snapshot.Data.Books.Single().BookID != 2) throw new Exception("Selection included an unselected book.");
|
||||
var store = new BookRecoveryUploads(); var old = store.Add(1, json); var latest = store.Add(1, json); try { store.Get(2, latest); throw new Exception("Foreign upload leaked."); } catch (UnauthorizedAccessException) { }
|
||||
try { store.Get(1, old); throw new Exception("Superseded generation survived."); } catch (UnauthorizedAccessException) { }
|
||||
store.Get(1, latest);
|
||||
var firstGeneration=store.Begin(1);var newerGeneration=store.Begin(1);store.Add(1,json,"newer.plotdirector",newerGeneration);
|
||||
try{store.Add(1,json,"earlier.plotdirector",firstGeneration);throw new Exception("Slow earlier server upload replaced the latest generation.");}catch(ArgumentException){}
|
||||
if(store.Name(1,newerGeneration)!="newer.plotdirector")throw new Exception("Filename and upload generation diverged.");
|
||||
var node = JsonNode.Parse(json)!; node["Snapshot"]!["Data"]!["Books"]![0]!["BookTitle"] = "Tampered"; try { BookRecoveryService.Read(node.ToJsonString()); throw new Exception("Invalid integrity accepted."); } catch (ArgumentException) { }
|
||||
node = JsonNode.Parse(json)!; node["FormatVersion"] = "999"; try { BookRecoveryService.Read(node.ToJsonString()); throw new Exception("Future format accepted."); } catch (ArgumentException) { }
|
||||
node = JsonNode.Parse(json)!; node["Snapshot"]!["Data"]!.AsObject().Remove("SceneChecklistItems"); try { BookRecoveryService.Read(node.ToJsonString()); throw new Exception("Incomplete current backup accepted."); } catch (ArgumentException) { }
|
||||
try { BookRecoveryService.Read("{\"Format\":\"PlotDirector.BookBackup\",\"Format\":\"other\"}"); throw new Exception("Duplicate JSON fields accepted."); } catch (ArgumentException) { }
|
||||
node=JsonNode.Parse(json)!;node["Snapshot"]!["Recovery"]!["Protected"]=true;try{BookRecoveryService.Read(node.ToJsonString());throw new Exception("Server-only protected state accepted as a portable backup.");}catch(ArgumentException){}
|
||||
foreach(var malformed in new[]{"null","[]","{\"Format\":\"PlotDirector.BookBackup\",\"Snapshot\":null}","{\"Format\":42}"})try{BookRecoveryService.Read(malformed);throw new Exception("Malformed root accepted.");}catch(Exception e)when(e is ArgumentException or JsonException){}
|
||||
try { BookBackupGraph.Select(snapshot, [404]); throw new Exception("Foreign selection accepted."); } catch (ArgumentException) { }
|
||||
}
|
||||
}
|
||||
2
PlotLine.Tests/Browser/backup-upload-generation.cjs
Normal file
2
PlotLine.Tests/Browser/backup-upload-generation.cjs
Normal file
@ -0,0 +1,2 @@
|
||||
const {chromium}=require('playwright'),fs=require('fs'),path=require('path'),assert=require('node:assert/strict');
|
||||
(async()=>{const browser=await chromium.launch();try{const page=await browser.newPage();await page.setContent('<form><input id="JsonFile" type="file"><textarea id="JsonText"></textarea><p data-upload-status></p><input data-json-carry-forward></form>');await page.evaluate(()=>{window.readers=[];window.FileReader=class{abort(){}readAsText(file){this.name=file.name;readers.push(this);}};});const view=fs.readFileSync(path.resolve(__dirname,'../../PlotLine/Views/Imports/Index.cshtml'),'utf8');await page.addScriptTag({content:[...view.matchAll(/<script>([\s\S]*?)<\/script>/g)].at(-1)[1]});for(const name of ['first.json','second.json'])await page.setInputFiles('#JsonFile',{name,mimeType:'application/json',buffer:Buffer.from('{}')});await page.evaluate(()=>{readers[1].result='newer content';readers[1].onload();readers[0].result='stale content';readers[0].onload();});assert.equal(await page.inputValue('#JsonText'),'newer content');await page.setInputFiles('#JsonFile',{name:'third.json',mimeType:'application/json',buffer:Buffer.from('{}')});await page.fill('#JsonText','author edit');await page.evaluate(()=>{readers[2].result='late file';readers[2].onload();});assert.equal(await page.inputValue('#JsonText'),'author edit');console.log('PASS actual legacy reader rejects superseded callbacks and preserves newer file/manual edits');}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);});
|
||||
7
PlotLine.Tests/Browser/book-recovery.cjs
Normal file
7
PlotLine.Tests/Browser/book-recovery.cjs
Normal file
@ -0,0 +1,7 @@
|
||||
const {chromium}=require('playwright'),assert=require('node:assert/strict');
|
||||
(async()=>{const browser=await chromium.launch();try{const page=await browser.newPage();const base=process.env.TOOLBAR_HOST||'http://127.0.0.1:5238';
|
||||
for(const size of [{width:1440,height:1000},{width:390,height:844}]){await page.setViewportSize(size);for(const step of ['Backup?single=1','BackupPreview','Restore','Preview','Complete']){await page.goto(base+'/book-recovery-fixture/'+step);await page.locator('h1').waitFor();assert.equal(await page.locator('body').evaluate(e=>e.scrollWidth>innerWidth+2),false,'page overflows '+step);assert.equal(await page.locator('textarea').count(),0);if(step.startsWith('Backup?')){assert.equal(await page.locator('input[name=books]:checked').count(),1);await page.locator('[data-books-all]').click();assert.equal(await page.locator('input[name=books]:checked').count(),2);await page.locator('[data-books-none]').click();assert.equal(await page.locator('input[name=books]:checked').count(),0);}if(step==='Preview'){await assert.rejects(()=>page.locator('form').last().evaluate(e=>{if(e.checkValidity())return;throw Error('unconfirmed');}));await page.locator('#confirm').check();assert.equal(await page.locator('form').last().evaluate(e=>e.checkValidity()),true);}}
|
||||
await page.goto(base+'/book-recovery-fixture/Preview');await page.screenshot({path:'/tmp/book-recovery-'+size.width+'.png',fullPage:true});}
|
||||
for(const theme of ['modern-light','modern-dark','warm-dark']){await page.goto(base+'/book-recovery-fixture/Preview');await page.evaluate(theme=>{document.documentElement.dataset.appTheme=theme;document.documentElement.dataset.theme=theme.endsWith('dark')?'dark':'light';document.documentElement.dataset.bsTheme=document.documentElement.dataset.theme;},theme);assert.equal(await page.locator('body').evaluate(e=>e.scrollWidth>innerWidth+2),false,'theme overflow '+theme);await page.locator('#confirm').check();await page.screenshot({path:'/tmp/book-recovery-'+theme+'.png',fullPage:true});}
|
||||
const manuscript=page.locator('button.pd-ribbon-command[data-command-operation="onboarding.startimport"]');assert.equal(await manuscript.locator('..').getAttribute('method'),'post');assert.equal(await manuscript.locator('..').locator('input[name=__RequestVerificationToken]').count(),1);assert.equal(await page.locator('.pd-ribbon-command[href*="/Imports"]').count(),0);
|
||||
await page.goto(base+'/book-recovery-fixture/Preview?full=1');assert.equal(await page.getByRole('button',{name:'Restore books',exact:true}).isDisabled(),true);console.log('PASS real backup/restore Razor views, responsive layouts, book selections, confirmation and capacity states');}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);});
|
||||
@ -158,6 +158,8 @@ var tests = new (string Name, Action Test)[]
|
||||
("Writing Solver anonymous state is protected, expires and rejects stale versions", WritingSolverTests.AnonymousState),
|
||||
("Writing Solver scoring, multi-select, revision, fallback and graph routes", WritingSolverTests.RoutingAndRevision),
|
||||
("Writing Solver import rejects invalid graphs and editorial identities", WritingSolverTests.Validation),
|
||||
("Book recovery read-only exports and receipt retries remain accessible", BookRecoveryTests.ReadOnlyBackupAccess),
|
||||
("Book recovery validates integrity, selection and author-bound upload generations", BookRecoveryTests.Contracts),
|
||||
("Project export and restore access gates enforce author and ownership boundaries", ProjectAccessRegressionTests.FilterBoundaries),
|
||||
("Retired checklist bookmarks redirect without report access", LegacyAcceptanceTests.RedirectsWithoutReporting),
|
||||
("Ribbon operation identity and semantic icons stay consistent", RibbonPresentationTests.SemanticMetadata),
|
||||
|
||||
@ -58,9 +58,10 @@ internal static class ProjectAccessRegressionTests
|
||||
await Check("Exports", "ProjectBackup", new() { ["projectId"] = 7 }, false, "Owner");
|
||||
await Check("Exports", "SceneBrief", new() { ["id"] = 98 }, false, "Scene");
|
||||
await Check("Exports", "SceneBrief", new() { ["id"] = 23 }, true, "Scene");
|
||||
await Check("ProjectRestorePoints", "Download", new() { ["projectId"] = 7, ["id"] = 98 }, false, "ProjectRestorePoint");
|
||||
await Check("ProjectRestorePoints", "Restore", new() { ["projectId"] = 7, ["id"] = 98 }, false, "ProjectRestorePoint");
|
||||
await Check("ProjectRestorePoints", "Delete", new() { ["projectId"] = 7, ["id"] = 98 }, false, "ProjectRestorePoint");
|
||||
await Check("ProjectRestorePoints", "Download", new() { ["projectId"] = 7, ["id"] = 98 }, false, "Owner");
|
||||
await Check("ProjectRestorePoints", "Restore", new() { ["projectId"] = 7, ["id"] = 98 }, false, "Owner");
|
||||
await Check("ProjectRestorePoints", "Delete", new() { ["projectId"] = 7, ["id"] = 98 }, false, "Owner");
|
||||
await Check("BookRecovery", "Backup", new() { ["projectId"] = 7 }, false, "Owner");
|
||||
repo.Calls.Clear();
|
||||
var anonymous = new ProjectAccessService(repo, new User(null));
|
||||
if (await anonymous.CanAccessProjectAsync(7) || await anonymous.CanAccessEntityAsync("Scene", 23)
|
||||
|
||||
@ -110,7 +110,7 @@ internal static class ProjectExportDatabaseTests
|
||||
else
|
||||
{
|
||||
var backup=JsonSerializer.Deserialize<ProjectBackupExport>(await response.Content.ReadAsStringAsync(),new JsonSerializerOptions{PropertyNameCaseInsensitive=true})!;
|
||||
if(backup.FormatVersion!="1.3" || backup.Files.Count!=12 || backup.Data.CharacterImages.Count!=2)failures.Add("ProjectBackup HTTP omitted embedded files/gallery");
|
||||
if(backup.FormatVersion!="1.4" || backup.Files.Count!=12 || backup.Data.CharacterImages.Count!=2)failures.Add("ProjectBackup HTTP omitted embedded files/gallery");
|
||||
}
|
||||
}
|
||||
using(var response=await Get($"/Exports/ProjectBackup?projectId={project}",other))if(response.StatusCode!=HttpStatusCode.NotFound)failures.Add("Full project backup crossed author boundary");
|
||||
|
||||
@ -2,6 +2,7 @@ using System.Data;
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Dapper;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
@ -18,6 +19,8 @@ internal static class ProjectTransferDatabaseTests
|
||||
static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
|
||||
static T Proxy<T>(Func<string, object?[]?, object?> handler) where T : class
|
||||
{ var proxy=DispatchProxy.Create<T,StoryPointProxy>();((StoryPointProxy)(object)proxy).Handler=handler;return proxy; }
|
||||
// Model the application's trusted SQL boundary without filling omitted test collections.
|
||||
internal static string SqlPayload(string json){var node=JsonNode.Parse(json)!;if(node["Recovery"] is JsonObject state)state["Protected"]=true;return node.ToJsonString();}
|
||||
public static async Task RunAsync(string target, bool applyMigrations = false, bool requireWritingPlans = false, bool schemaCoverageOnly = false, bool exportsOnly = false, bool legacyOnly = false, bool wordOnly = false, bool coreOnly = false, bool imagesOnly = false, bool consistencyOnly = false, bool omissionsOnly = false)
|
||||
{
|
||||
Check(target==Database,"An explicitly named Phase 2 synthetic database is required.");
|
||||
@ -174,6 +177,7 @@ internal static class ProjectTransferDatabaseTests
|
||||
catch(Exception error){Console.Error.WriteLine(error.StackTrace);throw;}
|
||||
return;
|
||||
}
|
||||
if(Environment.GetCommandLineArgs().Contains("--book-recovery-only")){await BookRecoveryDatabaseTests.Run(factory,assetFiles,uploads,user,importingUser,project,book,chapter,scene);return;}
|
||||
var before=(await backups.GetProjectBackupAsync(project,user))!;
|
||||
await assetFiles.CaptureAsync(before);Check(before.Project is not null,"Fixture project exported.");
|
||||
var retainedRun=before.Data.StoryIntelligenceRuns.Single();
|
||||
@ -402,26 +406,26 @@ internal static class ProjectTransferDatabaseTests
|
||||
await db.ExecuteAsync("UPDATE dbo.StoryIntelligenceJobs SET Status=N'Preparing' WHERE ProjectID=@project",new{project});
|
||||
try
|
||||
{
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=sourceJson},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore replaced an active analysis job."); }
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=SqlPayload(sourceJson)},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore replaced an active analysis job."); }
|
||||
catch(SqlException error) when(error.Number==51017) { }
|
||||
}
|
||||
finally { await db.ExecuteAsync("UPDATE dbo.StoryIntelligenceJobs SET Status=N'Completed' WHERE ProjectID=@project",new{project}); }
|
||||
var protectedBookRemoval=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!;
|
||||
protectedBookRemoval["Data"]!["Books"]!.AsArray().Clear();
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=protectedBookRemoval.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore removed a book required by immutable account consent/job history."); }
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=SqlPayload(protectedBookRemoval.ToJsonString())},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore removed a book required by immutable account consent/job history."); }
|
||||
catch(SqlException error) when(error.Number==51018) { }
|
||||
var accountStateAtRestore=await AccountStateAsync();
|
||||
await ProjectTransferIllustrationAssertions.VerifyRestoreGuardsAsync(db,before,sourceJson,project);
|
||||
foreach(var omitted in new[]{"WholeBookPlotSynthesisRuns","StoryIntelligenceNarrativeCandidates","StoryIntelligenceNarrativeCandidateEvidence","StoryIntelligenceNarrativeCandidateEvents"})
|
||||
{
|
||||
var older=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!;older["Data"]!.AsObject().Remove(omitted);
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=older.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Older snapshot erased narrative synthesis/review history."); }
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=SqlPayload(older.ToJsonString())},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Older snapshot erased narrative synthesis/review history."); }
|
||||
catch(SqlException error) when(error.Number==51021) { }
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.StoryIntelligenceNarrativeCandidates WHERE ProjectID=@project",new{project})==6,"Refused snapshot preserves every narrative review state.");
|
||||
}
|
||||
var unfinishedSynthesis=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!;
|
||||
unfinishedSynthesis["Data"]!["WholeBookPlotSynthesisRuns"]![0]!["Status"]="Queued";
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=unfinishedSynthesis.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore requeued paid narrative synthesis."); }
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=SqlPayload(unfinishedSynthesis.ToJsonString())},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore requeued paid narrative synthesis."); }
|
||||
catch(SqlException error) when(error.Number==51022) { }
|
||||
Check((await service.PreviewAsync(new(){JsonText=unfinishedSynthesis.ToJsonString()})).Preview!.Validation.Warnings.Any(w=>w.Contains("Unfinished narrative synthesis",StringComparison.Ordinal)),"Unfinished synthesis warning is explicit.");
|
||||
var synthesisCopy=await service.ImportAsync(new(){JsonText=unfinishedSynthesis.ToJsonString(),ConfirmImport=true,AcknowledgeWarnings=true,AllowDuplicateProjectTitle=true});
|
||||
@ -450,13 +454,13 @@ internal static class ProjectTransferDatabaseTests
|
||||
foreach(var omitted in new[]{"CharacterEnrichmentRuns","CharacterEnrichmentEvidence"})
|
||||
{
|
||||
var older=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!;older["Data"]!.AsObject().Remove(omitted);
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=older.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Older snapshot erased retained enrichment evidence."); }
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=SqlPayload(older.ToJsonString())},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Older snapshot erased retained enrichment evidence."); }
|
||||
catch(SqlException error) when(error.Number==51019) { }
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterEnrichmentEvidence WHERE CharacterID=@character",new{character})==2,"Refused snapshot preserves enrichment evidence.");
|
||||
}
|
||||
var unfinishedEnrichment=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!;
|
||||
unfinishedEnrichment["Data"]!["CharacterEnrichmentRuns"]![0]!["Status"]="Queued";
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=unfinishedEnrichment.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore requeued paid enrichment."); }
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=SqlPayload(unfinishedEnrichment.ToJsonString())},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore requeued paid enrichment."); }
|
||||
catch(SqlException error) when(error.Number==51020) { }
|
||||
Check((await service.PreviewAsync(new(){JsonText=unfinishedEnrichment.ToJsonString()})).Preview!.Validation.Warnings.Any(w=>w.Contains("Unfinished character enrichment",StringComparison.Ordinal)),"Unfinished enrichment warning is explicit.");
|
||||
var enrichmentCopy=await service.ImportAsync(new(){JsonText=unfinishedEnrichment.ToJsonString(),ConfirmImport=true,AcknowledgeWarnings=true,AllowDuplicateProjectTitle=true});
|
||||
@ -476,13 +480,13 @@ internal static class ProjectTransferDatabaseTests
|
||||
foreach(var omitted in new[]{"StoryIntelligenceReviewCandidateGenerations","StoryIntelligenceReviewCandidates","StoryIntelligenceReviewCandidateEvidence"})
|
||||
{
|
||||
var older=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!;older["Data"]!.AsObject().Remove(omitted);
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=older.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Older snapshot erased persisted author review decisions."); }
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=SqlPayload(older.ToJsonString())},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Older snapshot erased persisted author review decisions."); }
|
||||
catch(SqlException error) when(error.Number==51015) { }
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.StoryIntelligenceReviewCandidates WHERE ProjectID=@project",new{project})==16,"Refused snapshot preserves all author review states.");
|
||||
}
|
||||
var preparingSnapshot=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!;
|
||||
preparingSnapshot["Data"]!["StoryIntelligenceReviewCandidateGenerations"]![0]!["Status"]="Preparing";
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=preparingSnapshot.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore reintroduced unfinished preparation."); }
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=SqlPayload(preparingSnapshot.ToJsonString())},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore reintroduced unfinished preparation."); }
|
||||
catch(SqlException error) when(error.Number==51016) { }
|
||||
Check((await service.PreviewAsync(new(){JsonText=preparingSnapshot.ToJsonString()})).Preview!.Validation.Warnings.Any(w=>w.Contains("Unfinished candidate preparation",StringComparison.Ordinal)),"Unfinished preparation warning is explicit.");
|
||||
var preparationCopy=await service.ImportAsync(new(){JsonText=preparingSnapshot.ToJsonString(),ConfirmImport=true,AcknowledgeWarnings=true,AllowDuplicateProjectTitle=true});
|
||||
@ -495,7 +499,7 @@ internal static class ProjectTransferDatabaseTests
|
||||
await db.ExecuteAsync("UPDATE dbo.StoryIntelligenceReviewCandidateGenerations SET Status=N'Preparing' WHERE ReviewCandidateGenerationID=@id",new{id=sourceGeneration});
|
||||
try
|
||||
{
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=sourceJson},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore replaced active candidate preparation."); }
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=SqlPayload(sourceJson)},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore replaced active candidate preparation."); }
|
||||
catch(SqlException error) when(error.Number==51016) { }
|
||||
}
|
||||
finally { await db.ExecuteAsync("UPDATE dbo.StoryIntelligenceReviewCandidateGenerations SET Status=N'Ready' WHERE ReviewCandidateGenerationID=@id",new{id=sourceGeneration}); }
|
||||
@ -503,7 +507,7 @@ internal static class ProjectTransferDatabaseTests
|
||||
{
|
||||
var older=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!;
|
||||
older["Data"]!.AsObject().Remove(omitted);
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=older.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Older snapshot erased retained pipeline/memory data."); }
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=SqlPayload(older.ToJsonString())},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Older snapshot erased retained pipeline/memory data."); }
|
||||
catch(SqlException error) when(error.Number==51013) { }
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.StoryMemoryCharacters WHERE ProjectID=@project",new{project})==1,"Refused snapshot preserves memory identities.");
|
||||
}
|
||||
@ -512,7 +516,7 @@ internal static class ProjectTransferDatabaseTests
|
||||
pipelineSnapshot["Data"]!["StoryIntelligenceBookPipelines"]![0]!["CurrentStage"]="SceneImport";
|
||||
pipelineSnapshot["Data"]!["StoryIntelligenceBookPipelines"]![0]!["LastCompletedStage"]="SceneReview";
|
||||
pipelineSnapshot["Data"]!["StoryIntelligenceBookPipelines"]![0]!["CurrentReviewStage"]="SceneReview";
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=pipelineSnapshot.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore reintroduced an unfinished pipeline."); }
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=SqlPayload(pipelineSnapshot.ToJsonString())},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore reintroduced an unfinished pipeline."); }
|
||||
catch(SqlException error) when(error.Number==51014) { }
|
||||
var pipelineCopy=await service.ImportAsync(new(){JsonText=pipelineSnapshot.ToJsonString(),ConfirmImport=true,AcknowledgeWarnings=true,AllowDuplicateProjectTitle=true});
|
||||
Check(pipelineCopy.Succeeded,"Unfinished pipeline copy failed: "+pipelineCopy.Message+" "+pipelineCopy.TechnicalDetail);
|
||||
@ -520,7 +524,7 @@ internal static class ProjectTransferDatabaseTests
|
||||
await db.ExecuteAsync("UPDATE dbo.StoryIntelligenceBookPipelines SET Status=N'InProgress' WHERE ProjectID=@project",new{project});
|
||||
try
|
||||
{
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=sourceJson},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore replaced an active pipeline."); }
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=SqlPayload(sourceJson)},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore replaced an active pipeline."); }
|
||||
catch(SqlException error) when(error.Number==51014) { }
|
||||
}
|
||||
finally { await db.ExecuteAsync("UPDATE dbo.StoryIntelligenceBookPipelines SET Status=N'Complete' WHERE ProjectID=@project",new{project}); }
|
||||
@ -528,16 +532,16 @@ internal static class ProjectTransferDatabaseTests
|
||||
{
|
||||
var older=System.Text.Json.Nodes.JsonNode.Parse(JsonSerializer.Serialize(before))!;
|
||||
older["Data"]!.AsObject().Remove(omitted);
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=older.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Older snapshot erased retained analysis audit."); }
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=SqlPayload(older.ToJsonString())},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Older snapshot erased retained analysis audit."); }
|
||||
catch(SqlException error) when(error.Number==51011) { }
|
||||
Check(await db.ExecuteScalarAsync<string>("SELECT RawResponseJson FROM dbo.StoryIntelligenceSceneResults WHERE SceneResultID=@id",new{id=before.Data.StoryIntelligenceSceneResults.Single().SceneResultID})==before.Data.StoryIntelligenceSceneResults.Single().RawResponseJson,"Refused restore retains raw audit JSON exactly.");
|
||||
}
|
||||
var unfinished=System.Text.Json.Nodes.JsonNode.Parse(sourceJson)!;
|
||||
unfinished["Data"]!["StoryIntelligenceImportCommits"]![0]!["Status"]="Pending";
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=unfinished.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore reintroduced unfinished materialization."); }
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=SqlPayload(unfinished.ToJsonString())},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore reintroduced unfinished materialization."); }
|
||||
catch(SqlException error) when(error.Number==51012) { }
|
||||
unfinished["Data"]!["StoryIntelligenceRuns"]![0]!["Status"]="Pending";
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=unfinished.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore reintroduced unfinished paid analysis."); }
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=SqlPayload(unfinished.ToJsonString())},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore reintroduced unfinished paid analysis."); }
|
||||
catch(SqlException error) when(error.Number==51012) { }
|
||||
var unfinishedPreview=(await service.PreviewAsync(new(){JsonText=unfinished.ToJsonString()})).Preview!;
|
||||
Check(unfinishedPreview.Validation.Warnings.Any(w=>w.Contains("cancelled audit history",StringComparison.Ordinal)),"Unfinished analysis copy warning is explicit.");
|
||||
@ -548,7 +552,7 @@ internal static class ProjectTransferDatabaseTests
|
||||
await db.ExecuteAsync("UPDATE dbo.StoryIntelligenceRuns SET Status=N'Running' WHERE StoryIntelligenceRunID=@id",new{id=before.Data.StoryIntelligenceRuns.Single().StoryIntelligenceRunID});
|
||||
try
|
||||
{
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=sourceJson},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore replaced active analysis."); }
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=SqlPayload(sourceJson)},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Restore replaced active analysis."); }
|
||||
catch(SqlException error) when(error.Number==51012) { }
|
||||
}
|
||||
finally { await db.ExecuteAsync("UPDATE dbo.StoryIntelligenceRuns SET Status=N'Completed' WHERE StoryIntelligenceRunID=@id",new{id=before.Data.StoryIntelligenceRuns.Single().StoryIntelligenceRunID}); }
|
||||
@ -556,7 +560,7 @@ internal static class ProjectTransferDatabaseTests
|
||||
{
|
||||
var older=System.Text.Json.Nodes.JsonNode.Parse(JsonSerializer.Serialize(before))!;
|
||||
older["Data"]!.AsObject().Remove(omitted);
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=older.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Older snapshot erased existing Core Import location history."); }
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=SqlPayload(older.ToJsonString())},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Older snapshot erased existing Core Import location history."); }
|
||||
catch(SqlException error) when(error.Number==51010) { }
|
||||
Check((await backups.GetProjectBackupAsync(project,user))!.Data.CoreImportBasicLocationEvidence.Count==1,"Older snapshot refusal retains location evidence.");
|
||||
}
|
||||
@ -564,7 +568,7 @@ internal static class ProjectTransferDatabaseTests
|
||||
{
|
||||
var older=System.Text.Json.Nodes.JsonNode.Parse(JsonSerializer.Serialize(before))!;
|
||||
older["Data"]!.AsObject().Remove(omitted);
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=older.ToJsonString()},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Older snapshot erased existing suggestion history."); }
|
||||
try { await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=SqlPayload(older.ToJsonString())},commandType:CommandType.StoredProcedure);throw new InvalidOperationException("Older snapshot erased existing suggestion history."); }
|
||||
catch(SqlException error) when(error.Number==51009) { }
|
||||
Check((await backups.GetProjectBackupAsync(project,user))!.Data.SceneAssetSuggestions.Count==4,"Older snapshot refusal retains review history.");
|
||||
}
|
||||
|
||||
@ -35,14 +35,14 @@ internal static class ProjectTransferIllustrationAssertions
|
||||
foreach(var table in new[]{"StoryMemoryIllustrationAssignments","StoryMemoryIllustrationDemands","StoryIntelligenceIllustrationDemands"})
|
||||
{
|
||||
var old=JsonNode.Parse(json)!;old["Data"]!.AsObject().Remove(table);
|
||||
try{await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=old.ToJsonString()},commandType:System.Data.CommandType.StoredProcedure);throw new InvalidOperationException("Missing illustration collection accepted: "+table);}
|
||||
try{await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=ProjectTransferDatabaseTests.SqlPayload(old.ToJsonString())},commandType:System.Data.CommandType.StoredProcedure);throw new InvalidOperationException("Missing illustration collection accepted: "+table);}
|
||||
catch(SqlException ex) when(ex.Number==51023){}
|
||||
}
|
||||
var item=before.Data.StoryMemoryIllustrationAssignments.First(x=>x.InvalidatedUtc is null && x.IllustrationLibraryItemID.HasValue).IllustrationLibraryItemID!.Value;
|
||||
try
|
||||
{
|
||||
await db.ExecuteAsync("UPDATE dbo.IllustrationLibraryItems SET Status=N'Generating' WHERE IllustrationLibraryItemID=@item",new{item});
|
||||
try{await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=json},commandType:System.Data.CommandType.StoredProcedure);throw new InvalidOperationException("Active illustration generation accepted.");}
|
||||
try{await db.ExecuteAsync("dbo.ProjectRestore_ApplyFromJson",new{ProjectID=project,JsonData=ProjectTransferDatabaseTests.SqlPayload(json)},commandType:System.Data.CommandType.StoredProcedure);throw new InvalidOperationException("Active illustration generation accepted.");}
|
||||
catch(SqlException ex) when(ex.Number==51024){}
|
||||
}
|
||||
finally{await db.ExecuteAsync("UPDATE dbo.IllustrationLibraryItems SET Status=N'Approved' WHERE IllustrationLibraryItemID=@item",new{item});}
|
||||
|
||||
23
PlotLine.Tests/Sql/BookRecoveryCapacity.sql
Normal file
23
PlotLine.Tests/Sql/BookRecoveryCapacity.sql
Normal file
@ -0,0 +1,23 @@
|
||||
-- Synthetic database only; every fixture and reservation is rolled back.
|
||||
IF DB_NAME()<>N'PlotDirector_Phase2_20261103_2305' THROW 51000,'Synthetic target required',1;
|
||||
BEGIN TRANSACTION;
|
||||
DECLARE @User int,@Level int,@Project int,@Book int;
|
||||
INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+N'@recovery.invalid',N'Capacity fixture',N'not-a-credential');SET @User=SCOPE_IDENTITY();
|
||||
INSERT dbo.SubscriptionLevel(Name,DisplayName,MaxBooks,MaxChaptersPerBook,MaxScenesPerBook,MaxCharactersPerProject,MaxStorageMB,MaxCollaborators,SortOrder,RequiresStripeSubscription) VALUES(CONVERT(nvarchar(36),NEWID()),N'Capacity fixture',1,100,100,100,100,0,0,0);SET @Level=SCOPE_IDENTITY();
|
||||
INSERT dbo.UserSubscription(UserID,SubscriptionLevelID,IsActive,IsTrial,TrialExpiryDateUTC) VALUES(@User,@Level,1,1,'2030-01-01');
|
||||
INSERT dbo.Projects(ProjectName,IsArchived) VALUES(N'Capacity fixture',1);SET @Project=SCOPE_IDENTITY();
|
||||
INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole,IsActive) VALUES(@Project,@User,N'Owner',1);
|
||||
INSERT dbo.Books(ProjectID,BookTitle,BookNumber,SortOrder,IsArchived) VALUES(@Project,N'Archived capacity fixture',1,1,1);SET @Book=SCOPE_IDENTITY();
|
||||
CREATE TABLE #Usage(Value int);INSERT #Usage EXEC dbo.SubscriptionUsage_BookCountForOwner @User;
|
||||
IF (SELECT Value FROM #Usage)<>1 THROW 51000,'Archived book/project escaped capacity',1;
|
||||
DECLARE @Now datetime2=SYSUTCDATETIME();
|
||||
CREATE TABLE #Reservation(Allowed bit,ReservationID uniqueidentifier,CurrentUsage int,MaximumAllowed int,Message nvarchar(max));
|
||||
INSERT #Reservation EXEC dbo.SubscriptionEntitlement_TryReserveBookSlots @User,1,@Now;
|
||||
IF EXISTS(SELECT 1 FROM #Reservation WHERE Allowed=1) THROW 51000,'Full capacity accepted',1;
|
||||
UPDATE dbo.Books SET IsArchived=0 WHERE BookID=@Book;TRUNCATE TABLE #Usage;INSERT #Usage EXEC dbo.SubscriptionUsage_BookCountForOwner @User;
|
||||
IF (SELECT Value FROM #Usage)<>1 THROW 51000,'Unarchive changed capacity',1;
|
||||
DELETE dbo.Books WHERE BookID=@Book;TRUNCATE TABLE #Reservation;
|
||||
INSERT #Reservation EXEC dbo.SubscriptionEntitlement_TryReserveBookSlots @User,1,@Now;
|
||||
IF NOT EXISTS(SELECT 1 FROM #Reservation WHERE Allowed=1) THROW 51000,'Committed deletion did not permit reservation',1;
|
||||
ROLLBACK;
|
||||
SELECT 'PASS archived books/projects count, unarchive does not free capacity, full capacity refused, explicit deletion allows a slot; fixtures rolled back';
|
||||
@ -249,6 +249,15 @@ internal static class ToolbarBrowserHost
|
||||
await view.View!.RenderAsync(new ViewContext(action,view.View,data,new TempDataDictionary(context,context.RequestServices.GetRequiredService<ITempDataProvider>()),writer,new HtmlHelperOptions()));
|
||||
context.Response.ContentType="text/html";await context.Response.WriteAsync("<html data-theme='light'><head><meta name='viewport' content='width=device-width'><link rel='stylesheet' href='/lib/bootstrap/dist/css/bootstrap.min.css'><link rel='stylesheet' href='/css/site.css'><link rel='stylesheet' href='/css/plotline-theme.css'></head><body class='writing-embedded'><main class='writing-context-page'>"+writer+"</main><script src='/js/intent-assessment.js'></script></body></html>");
|
||||
});
|
||||
app.MapGet("/book-recovery-fixture/{step}",async context=>{
|
||||
var project=new Project{ProjectID=7,ProjectName="Harbour collection"};
|
||||
var snapshot=new ProjectBackupExport{Project=project,Data=new(){Books=[new(){BookID=12,ProjectID=7,BookTitle="A Distant Shore — long title with notes",SortOrder=1},new(){BookID=13,ProjectID=7,BookTitle="The archived sequel",IsArchived=true,SortOrder=2}]}};
|
||||
var package=new BookBackupPackage{SourceProjectKey=Guid.NewGuid(),Snapshot=snapshot,Warnings=["Contains private manuscript prose. Downloading never deletes your books."]};var upload=Guid.NewGuid();
|
||||
var model=new BookRecoveryPage{Projects=[project],ProjectID=7,BookID=context.Request.Query.ContainsKey("single")?12:null,Source=snapshot,Package=package,Upload=upload,UploadName="Harbour-books.plotdirector"};
|
||||
var step=context.Request.RouteValues["step"]?.ToString()??"Backup";
|
||||
if(step=="Preview")model.Preview=new(new(upload,[12,13],0,"Recovered harbour","",Guid.NewGuid(),DateTime.UtcNow.AddMinutes(20)),"fixture-confirmation",snapshot,12,5,context.Request.Query.ContainsKey("full")?0:4,package.Warnings);
|
||||
await RenderFullAsync(context,"BookRecovery",step,step=="Complete"?new BookRecoveryReceipt{ProjectID=7,BooksCreated=2}:model);
|
||||
});
|
||||
app.MapGet("/Writing/Context", context => RenderFullAsync(context, "Writing", "Context", new WritingContextPageViewModel { ProjectID = 7, BookID = int.TryParse(context.Request.Query["bookId"].ToString(), out var bookId) ? bookId : 12 })).WithOrder(-1);
|
||||
app.MapGet("/Writing/Intent", context => RenderFullAsync(context, "Writing", "Intent", new WritingIntentPageViewModel { ProjectID = 7, BookID = int.TryParse(context.Request.Query["bookId"].ToString(), out var bookId) ? bookId : 12 })).WithOrder(-1);
|
||||
app.MapGet("/fixture", async context =>
|
||||
|
||||
20
PlotLine/Controllers/BookRecoveryController.cs
Normal file
20
PlotLine/Controllers/BookRecoveryController.cs
Normal file
@ -0,0 +1,20 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PlotLine.Services;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.ViewModels;
|
||||
namespace PlotLine.Controllers;
|
||||
|
||||
[Authorize]
|
||||
public sealed class BookRecoveryController(BookRecoveryService recovery, BookRecoveryRepository repository, BookRecoveryUploads uploads, ICurrentUserService current) : Controller
|
||||
{
|
||||
private int UserID => current.UserId ?? throw new UnauthorizedAccessException();
|
||||
[HttpGet] public async Task<IActionResult> Backup(int projectId = 0, int? bookId = null) { try { return View(new BookRecoveryPage { Projects = await repository.Projects(UserID), ProjectID = projectId, BookID = bookId, Source = projectId > 0 ? await recovery.Source(projectId) : null }); } catch (UnauthorizedAccessException) { return NotFound(); } }
|
||||
[HttpPost, ValidateAntiForgeryToken] public async Task<IActionResult> Download(int projectId, int[] books, Guid? staged = null) { try { var package = staged.HasValue ? uploads.Get(UserID, staged.Value) : await recovery.Export(projectId, books); await repository.Mappings(package.Snapshot.Project!.ProjectID, UserID); var title = string.Concat(package.Snapshot.Project!.ProjectName.Select(c => char.IsLetterOrDigit(c) || c is '-' or '_' ? c : '_')); return File(System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(package), "application/json", $"{title}_books_{DateTime.UtcNow:yyyy-MM-dd_HHmmss}.plotdirector"); } catch (UnauthorizedAccessException) { return NotFound(); } catch (Exception e) when (e is ArgumentException or InvalidOperationException or System.IO.IOException) { var model = new BookRecoveryPage { Projects = await repository.Projects(UserID), ProjectID = projectId, Source = await recovery.Source(projectId), Error = e.Message }; return View("Backup", model); } }
|
||||
[HttpPost, ValidateAntiForgeryToken] public async Task<IActionResult> ReviewBackup(int projectId, int[] books) { try { var generation=uploads.Begin(UserID);var package = await recovery.Export(projectId, books); var id = uploads.Add(UserID, System.Text.Json.JsonSerializer.Serialize(package),generation:generation); return View("BackupPreview", new BookRecoveryPage { ProjectID = projectId, Package = package, Upload = id }); } catch (UnauthorizedAccessException) { return NotFound(); } catch (Exception e) when (e is ArgumentException or InvalidOperationException or IOException) { return View("Backup", new BookRecoveryPage { ProjectID = projectId, Source = await recovery.Source(projectId), Projects = await repository.Projects(UserID), Error = e.Message }); } }
|
||||
[HttpGet] public IActionResult Restore() => View(new BookRecoveryPage());
|
||||
[HttpPost, ValidateAntiForgeryToken, RequestSizeLimit(80 * 1024 * 1024), RequestFormLimits(MultipartBodyLengthLimit = 80 * 1024 * 1024)]
|
||||
public async Task<IActionResult> Upload(IFormFile? backup) { try { if (backup == null || backup.Length is < 1 or > 64 * 1024 * 1024) throw new ArgumentException("Choose a nonempty .plotdirector or compatible JSON backup up to 64 MiB."); var generation=uploads.Begin(UserID);using var reader = new StreamReader(backup.OpenReadStream(), System.Text.Encoding.UTF8, true); var text = await reader.ReadToEndAsync(HttpContext.RequestAborted); var package = BookRecoveryService.Read(text); var id = uploads.Add(UserID, text, backup.FileName, generation); return View("Restore", new BookRecoveryPage { Upload = id, UploadName=uploads.Name(UserID,id), Package = package, Projects = await repository.Projects(UserID) }); } catch(UnauthorizedAccessException){return View("Restore",new BookRecoveryPage{Error="A newer upload replaced this request. Choose your latest file again."});} catch (Exception e) when (e is ArgumentException or System.Text.Json.JsonException or System.IO.InvalidDataException) { return View("Restore", new BookRecoveryPage { Error = "Backup validation failed. " + e.Message }); } }
|
||||
[HttpPost, ValidateAntiForgeryToken] public async Task<IActionResult> Preview(Guid upload, int[] books, int destination, string name) { try { var package = uploads.Get(UserID, upload); return View(new BookRecoveryPage { Upload = upload, UploadName=uploads.Name(UserID,upload), Package = package, Preview = await recovery.Preview(upload, package, books, destination, name) }); } catch (UnauthorizedAccessException) { return NotFound(); } catch (Exception e) when (e is ArgumentException or InvalidOperationException) { return View("Restore", new BookRecoveryPage { Error = e.Message + " Choose the backup again to start a new preview." }); } }
|
||||
[HttpPost, ValidateAntiForgeryToken] public async Task<IActionResult> Confirm(string confirmation, bool confirm = false) { if (!confirm) return BadRequest("Confirm the preview before restoring."); try { var receipt = await recovery.Restore(confirmation, id => uploads.Get(UserID, id)); return View("Complete", receipt); } catch (UnauthorizedAccessException) { return NotFound(); } catch (Exception e) when (e is ArgumentException or InvalidOperationException or Microsoft.Data.SqlClient.SqlException or System.Security.Cryptography.CryptographicException or System.Transactions.TransactionException or IOException) { return View("Restore", new BookRecoveryPage { RetryConfirmation=confirmation,Error = "The restore result could not be confirmed. Existing books were not overwritten. " + (e is ArgumentException ? e.Message : "Retry the original confirmation below before starting another restore; contact support if it continues.") }); } }
|
||||
}
|
||||
@ -10,10 +10,7 @@ namespace PlotLine.Controllers;
|
||||
[RequestFormLimits(ValueLengthLimit = 32 * 1024 * 1024)]
|
||||
public sealed class ImportsController(IImportService imports) : Controller
|
||||
{
|
||||
public IActionResult Index() => View(new ImportIndexViewModel
|
||||
{
|
||||
JsonText = ImportIndexViewModel.SampleJson
|
||||
});
|
||||
public IActionResult Index() => RedirectToAction("Restore","BookRecovery");
|
||||
|
||||
public IActionResult Sample()
|
||||
=> File(Encoding.UTF8.GetBytes(ImportIndexViewModel.SampleJson), "application/json", "plotline-import-sample.json");
|
||||
|
||||
33
PlotLine/Data/BookRecoveryRepository.cs
Normal file
33
PlotLine/Data/BookRecoveryRepository.cs
Normal file
@ -0,0 +1,33 @@
|
||||
using System.Data;
|
||||
using System.Text.Json;
|
||||
using Dapper;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using PlotLine.Models;
|
||||
namespace PlotLine.Data;
|
||||
|
||||
public sealed class BookRecoveryRepository(ISqlConnectionFactory factory, IDataProtectionProvider protection)
|
||||
{
|
||||
public async Task<Project[]> Projects(int user) { using var db = factory.CreateConnection(); return (await db.QueryAsync<Project>("dbo.BookRecovery", new { Action = "Projects", UserID = user }, commandType: CommandType.StoredProcedure)).ToArray(); }
|
||||
public async Task<Guid> Origin(int project, int user) { using var db = factory.CreateConnection(); return await db.QuerySingleAsync<Guid>("dbo.BookRecovery", new { Action = "Origin", ProjectID = project, UserID = user }, commandType: CommandType.StoredProcedure); }
|
||||
public async Task<BookRecoveryReceipt?> Receipt(Guid operation, int user) { using var db = factory.CreateConnection(); return await db.QuerySingleOrDefaultAsync<BookRecoveryReceipt>("dbo.BookRecovery", new { Action = "Receipt", OperationID = operation, UserID = user }, commandType: CommandType.StoredProcedure); }
|
||||
public async Task Begin(Guid operation, int user) { using var db = factory.CreateConnection(); await db.ExecuteAsync("dbo.BookRecovery", new { Action = "Begin", OperationID = operation, UserID = user }, commandType: CommandType.StoredProcedure); }
|
||||
public async Task<IReadOnlyList<BookRecoveryMapping>> Mappings(int project, int user) { using var db = factory.CreateConnection(); return (await db.QueryAsync<BookRecoveryMapping>("dbo.BookRecovery", new { Action = "Mappings", ProjectID = project, UserID = user }, commandType: CommandType.StoredProcedure)).ToArray(); }
|
||||
public async Task RegisterForks(int project,int user,IEnumerable<BookRecoveryMapping> mappings){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.BookRecovery",new{Action="Forks",ProjectID=project,UserID=user,MappingsJson=JsonSerializer.Serialize(mappings)},commandType:CommandType.StoredProcedure);}
|
||||
public async Task Complete(Guid operation, int project, int user, int books, string hash, IEnumerable<BookRecoveryMapping> mappings) { using var db = factory.CreateConnection(); await db.ExecuteAsync("dbo.BookRecovery", new { Action = "Complete", OperationID = operation, ProjectID = project, UserID = user, BooksCreated = books, RequestHash = hash, MappingsJson = JsonSerializer.Serialize(mappings) }, commandType: CommandType.StoredProcedure); }
|
||||
public static async Task<ProjectRecoveryState> ReadState(ISqlConnectionFactory factory, int project, IDataProtectionProvider? protection, IDbConnection? connection = null, IDbTransaction? transaction = null)
|
||||
{
|
||||
using var owned = connection == null ? factory.CreateConnection() : null; var db = connection ?? owned!; using var rows = await db.QueryMultipleAsync("dbo.ProjectRecovery_State", new { ProjectID = project }, transaction: transaction, commandType: CommandType.StoredProcedure); var result = new ProjectRecoveryState { NativeReviews = (await rows.ReadAsync<PortableNativeReview>()).ToList(), IntentAssessments = (await rows.ReadAsync<PortableIntentAssessment>()).ToList() }; var references = await rows.ReadSingleOrDefaultAsync<string>(); result.ExternalReferences = references == null ? [] : JsonSerializer.Deserialize<List<PortableExternalReference>>(references) ?? [];
|
||||
foreach(var r in result.NativeReviews){
|
||||
if(r.EncryptedSource!=null){if(protection==null)throw new InvalidOperationException("Source protection is required to export captured reviews safely.");var capture=JsonSerializer.Deserialize<PlotDirector.Companion.Protocol.AiChapterRequest>(protection.CreateProtector("NativeImport.Source.v1").Unprotect(r.EncryptedSource))??throw new InvalidDataException("Invalid captured source");capture.SessionId=Guid.Empty;r.SourceJson=JsonSerializer.Serialize(capture);r.EncryptedSource=null;}
|
||||
var resultJson=System.Text.Json.Nodes.JsonNode.Parse(r.ResultJson)!.AsObject();resultJson.Remove("CaptureSession");r.ResultJson=resultJson.ToJsonString();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
public static string ProtectState(ProjectRecoveryState state, IDataProtectionProvider? protection)
|
||||
{
|
||||
// The SQL apply path receives locally protected captures; exported JSON never contains this ciphertext.
|
||||
return JsonSerializer.Serialize(new { Protected = true, state.ExternalReferences, NativeReviews = state.NativeReviews.Select(r => new { r.ReviewID, r.UserID, r.BookID, r.ManuscriptID, r.ChapterStart, r.ChapterEnd, r.ContentHash, r.ResultJson, r.DecisionsJson, r.Version, r.CreatedUtc, EncryptedSource = r.SourceJson == null ? null : (protection ?? throw new InvalidOperationException("Source protection unavailable")).CreateProtector("NativeImport.Source.v1").Protect(r.SourceJson) }), state.IntentAssessments });
|
||||
}
|
||||
public static string Encode(ProjectBackupExport backup, IDataProtectionProvider? protection,int[]? appendBooks=null) { var node = System.Text.Json.Nodes.JsonNode.Parse(JsonSerializer.Serialize(backup))!; node["Recovery"] = System.Text.Json.Nodes.JsonNode.Parse(ProtectState(backup.Recovery, protection));if(appendBooks!=null){node["Recovery"]!["AppendOnly"]=true;node["Recovery"]!["AppendBooks"]=JsonSerializer.SerializeToNode(appendBooks);} return node.ToJsonString(); }
|
||||
public async Task ApplyState(int project, ProjectRecoveryState state) { using var db = factory.CreateConnection(); await db.ExecuteAsync("dbo.ProjectRecovery_Apply", new { ProjectID = project, StateJson = ProtectState(state, protection) }, commandType: CommandType.StoredProcedure); }
|
||||
}
|
||||
@ -10,14 +10,14 @@ public interface IProjectBackupRepository
|
||||
Task<ProjectBackupExport?> GetProjectBackupAsync(int projectId, int? userId = null);
|
||||
}
|
||||
|
||||
public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFactory) : IProjectBackupRepository
|
||||
public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFactory, Microsoft.AspNetCore.DataProtection.IDataProtectionProvider? protection=null) : IProjectBackupRepository
|
||||
{
|
||||
public async Task<ProjectBackupExport?> GetProjectBackupAsync(int projectId, int? userId = null)
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
if(connection is DbConnection asynchronous)await asynchronous.OpenAsync();else connection.Open();
|
||||
// All selectors must observe one SQL version, including rows inserted between result sets.
|
||||
using var transaction=connection.BeginTransaction(IsolationLevel.Serializable);
|
||||
using var transaction=System.Transactions.Transaction.Current is null?connection.BeginTransaction(IsolationLevel.Serializable):null;
|
||||
using var result = await connection.QueryMultipleAsync(
|
||||
"dbo.ProjectBackup_Export",
|
||||
new { ProjectID = projectId, UserID = userId },
|
||||
@ -305,7 +305,8 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
|
||||
Note = "Original database IDs are included for diagnostics. Project access records are exported for reference only; importing a project backup creates a new project owned by the importing user and does not recreate collaborators. Account onboarding and analysis consent/job records stay in their original account and are not recreated or rewound by project transfer. Existing project activity history is retained on same-project restore; copies do not recreate it. Shared illustration catalogue entries, approval/usage state and library files require a separate administrator backup and are never recreated or rewound by project transfer. Project illustration assignment/demand history is included; copied assignments become inactive and catalogue links are detached."
|
||||
}
|
||||
};
|
||||
transaction.Commit();
|
||||
backup.Recovery=await BookRecoveryRepository.ReadState(connectionFactory,projectId,protection,connection,transaction);
|
||||
transaction?.Commit();
|
||||
return backup;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
---
|
||||
title: Archived Records
|
||||
category: Archive
|
||||
tags: archive, restore, delete, recovery
|
||||
tags: archive, unarchive, delete, recovery
|
||||
contextKey: archive.archivedRecords
|
||||
micro: Review hidden items and decide whether to restore or permanently remove them.
|
||||
micro: Review hidden items and decide whether to unarchive or permanently remove them.
|
||||
quickTitle: Archived records
|
||||
quickSummary: Archived Records keeps removed planning material available for restoration until you choose to delete it forever.
|
||||
screenshot:
|
||||
@ -19,11 +19,11 @@ Use it after restructuring, cutting a subplot, retiring a location, removing a c
|
||||
|
||||
# How To Use It
|
||||
|
||||
Restore items that belong back in active planning. Delete forever only when you are certain the material should be permanently removed.
|
||||
Unarchive items that belong back in active planning. Delete forever only when you are certain the material should be permanently removed.
|
||||
|
||||
# Example
|
||||
|
||||
You might restore an archived clue after discovering it solves a payoff problem in the final act.
|
||||
You might unarchive an archived clue after discovering it solves a payoff problem in the final act.
|
||||
|
||||
# Writer Tip
|
||||
|
||||
@ -40,3 +40,5 @@ Archive first, delete later. Drafts change their minds.
|
||||
- [Archived Items](/Help/Article/archive.overview)
|
||||
- [Projects](/Help/Article/projects.overview)
|
||||
- [Story Bible](/Help/Article/storyBible.overview)
|
||||
|
||||
Archived books still use subscription slots. Unarchive changes visibility only. To preserve books locally, use [Back up books and restore from backup](/Help/Article/bookRecovery.overview). Downloading never deletes a book; only a separately confirmed permanent deletion releases its slot.
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
---
|
||||
title: Archived Items
|
||||
category: Archive
|
||||
tags: archive, restore, cleanup, recovery, organisation
|
||||
tags: archive, unarchive, cleanup, recovery, organisation
|
||||
contextKey: archive.overview
|
||||
micro: Recover or permanently remove planning items that were archived.
|
||||
quickTitle: What is the Archive?
|
||||
quickSummary: The Archive holds hidden projects and planning items so you can restore useful material or permanently remove items you no longer need.
|
||||
quickSummary: The Archive holds hidden projects and planning items so you can unarchive useful material or permanently remove items you no longer need.
|
||||
screenshot:
|
||||
---
|
||||
|
||||
@ -19,19 +19,19 @@ The Archive also helps keep active lists cleaner. If something is no longer part
|
||||
|
||||
# When Should I Use This?
|
||||
|
||||
Use the Archive when you want to review hidden work, restore something that should be active again, or permanently delete material you are sure you no longer need.
|
||||
Use the Archive when you want to review hidden work, unarchive something that should be active again, or permanently delete material you are sure you no longer need.
|
||||
|
||||
It is especially useful after big restructuring passes, when several scenes, assets, locations or threads may have been moved out of the active draft.
|
||||
|
||||
# How To Use It
|
||||
|
||||
Use the filters to narrow the list by project or item type. Restore returns an item to active lists where that makes sense. Delete Forever permanently removes it and should be used carefully.
|
||||
Use the filters to narrow the list by project or item type. Unarchive returns an item to active lists where that makes sense. Delete Forever permanently removes it and should be used carefully.
|
||||
|
||||
If you are unsure, restore the item or leave it archived rather than deleting it.
|
||||
If you are unsure, unarchive the item or leave it archived rather than deleting it.
|
||||
|
||||
# Example
|
||||
|
||||
You archive a subplot thread during a tighter second draft. Later, you realise a clue from that subplot solves a continuity problem. Open the Archive, filter to plot threads, and restore it.
|
||||
You archive a subplot thread during a tighter second draft. Later, you realise a clue from that subplot solves a continuity problem. Open the Archive, filter to plot threads, and unarchive it.
|
||||
|
||||
# Writer Tip
|
||||
|
||||
@ -48,3 +48,5 @@ Archive is a thinking space, not a bin. Let ideas rest there until you know whet
|
||||
|
||||
- [Projects](/Help/Article/projects.overview)
|
||||
- [Story Bible](/Help/Article/storyBible.overview)
|
||||
|
||||
Archived books still use subscription slots. Unarchive changes visibility only. To preserve books locally, use [Back up books and restore from backup](/Help/Article/bookRecovery.overview). Downloading never deletes a book; only a separately confirmed permanent deletion releases its slot.
|
||||
|
||||
38
PlotLine/Help/Articles/BookRecovery/Overview.md
Normal file
38
PlotLine/Help/Articles/BookRecovery/Overview.md
Normal file
@ -0,0 +1,38 @@
|
||||
---
|
||||
title: Back Up and Restore Books
|
||||
slug: overview
|
||||
category: Book Recovery
|
||||
tags: backup, restore, books, capacity, subscription, recovery
|
||||
contextKey: bookRecovery.overview
|
||||
micro: Keep books locally and restore them when you have space.
|
||||
quickTitle: Book backups
|
||||
quickSummary: Back up selected books and their shared project data. Restore into a new project or add books to a project you own.
|
||||
---
|
||||
|
||||
# Books use your subscription slots
|
||||
|
||||
Active and archived books both count. Backing up does not free a slot. Archive and Unarchive change visibility only. Separately deleting a book with Delete Forever releases its slot; restoring a book uses one slot. Projects organise books and do not provide extra capacity.
|
||||
|
||||
# Back up
|
||||
|
||||
From Projects choose **Back up books**, then a project and one, several or all books. A book's backup action preselects it. Review the contents and download the `.plotdirector` file. Common project definitions and required files travel with the selected story data. Dependencies that cannot safely be split require including connected books.
|
||||
|
||||
Keep backups private: they can contain prose, research, images and personal information. A successful download response does not prove the file is stored safely. Verify your local file before separately deleting online copies. Backups never automatically delete anything. Use the existing Archived Items **Delete Forever** action when you deliberately want to release a book's capacity; read its confirmation carefully and keep a tested local backup first.
|
||||
|
||||
# Restore
|
||||
|
||||
Choose **Restore books from backup**, upload your file, select books and choose a new project or an existing project you own. Review slots, destination and shared-data handling, then confirm. Existing books and shared records are not overwritten. Known, unchanged source identities can reuse compatible shared records; conflicts create independent copies. Maps are restored as independent bundles. Destination project settings stay in place.
|
||||
|
||||
A repeated submission of the same confirmation records the same restore operation. To restore again after deliberately deleting those books, start a new preview. If the destination changes before confirmation, preview again.
|
||||
|
||||
# Historical files and writing connections
|
||||
|
||||
Supported older project backups can be read with warnings. Data or uploaded-file bytes absent from an old file cannot be reconstructed. A current backup includes saved prose and author review/Intent decisions, not unsaved Word changes or your original `.docx` file.
|
||||
|
||||
Restored native review captures are historical and disconnected from live Word sessions. Server encryption keys, credentials, consent authority and active jobs are never replayed. Intent evidence can remain stale after identity remapping; author decisions stay available for review, and reassessment is explicit.
|
||||
|
||||
# Other kinds of recovery
|
||||
|
||||
Saved **Restore Points** rewind the same project and create a safety snapshot first. They are separate from adding books from a downloaded backup. **Unarchive** only brings an existing book back into view.
|
||||
|
||||
Packages are limited to 64 MiB; choose fewer books if needed. Restore previews identify special files that must be recovered as binary downloads for safety. Their original bytes are preserved.
|
||||
@ -1,56 +1,27 @@
|
||||
---
|
||||
title: Imports
|
||||
title: Bring your writing into PlotDirector
|
||||
category: Imports
|
||||
tags: imports, json, structure, setup, migration
|
||||
tags: imports, manuscript, backup, recovery
|
||||
contextKey: imports.overview
|
||||
micro: Bring prepared project structure into PlotDirector.
|
||||
quickTitle: What are Imports?
|
||||
quickSummary: Imports let you bring prepared story structure into PlotDirector so books, chapters, scenes and related items can be created together.
|
||||
micro: Choose manuscript onboarding or restore a book backup.
|
||||
quickTitle: Manuscript or backup?
|
||||
quickSummary: Use manuscript onboarding for Word documents, and Restore books for downloaded PlotDirector backups.
|
||||
screenshot:
|
||||
---
|
||||
|
||||
# Overview
|
||||
# Bring your writing into PlotDirector
|
||||
|
||||
Imports allow you to bring prepared story structure into PlotDirector instead of entering every project, book, chapter and scene by hand. This is useful when you have planned elsewhere, generated a structured outline, or need to move a project from another format into the app.
|
||||
On Projects, choose **Import a manuscript** to use the established manuscript onboarding and Word Companion workflow. Structure and AI suggestions remain subject to your review.
|
||||
|
||||
The import page is intentionally practical. You can upload or paste a JSON package, preview the result, run checks, and then create a new project when the package looks safe. The goal is to reduce setup friction while still protecting your data from accidental messy imports.
|
||||
Choose **Restore books from backup** for a `.plotdirector` file. Select books, choose a new project or a project you own, then review the preview before confirming. Each book needs an available subscription slot, including archived books.
|
||||
|
||||
Imports are best for structure and known planning information. They are not a replacement for revision judgement. After importing, you should still review the project as a writer.
|
||||
The old JSON outline editor, schema samples and paste box are no longer part of the ordinary author workflow. Historical project backup files remain supported through Restore books, with warnings where older formats cannot contain newer information.
|
||||
|
||||
# When Should I Use This?
|
||||
# Keep these actions separate
|
||||
|
||||
Use imports when you already have a structured outline or data package. This might include books, chapters, scenes, characters, locations, plot lines, story assets, scene links or other supported planning details.
|
||||
- **Back up books** downloads selected books and necessary shared project information. It never deletes anything.
|
||||
- **Archive** hides an online book; it still uses capacity.
|
||||
- **Delete Forever** permanently removes an archived online book and releases its slot. Check your local backup first.
|
||||
- **Saved restore points** rewind the same project. They are separate from adding books from a downloaded backup.
|
||||
|
||||
Imports are also useful for testing a large project shape quickly. A dry run can show whether the package is valid before anything is saved.
|
||||
|
||||
Do not use imports for small changes to an existing project if normal editing is simpler. The import flow is designed for bringing in a prepared package, not for everyday scene editing.
|
||||
|
||||
# How To Use It
|
||||
|
||||
Upload a JSON file or paste the package into the text area. Use validation and preview before importing. Read any warnings carefully. Warnings may not block the import, but they often point to names, aliases or links that deserve attention.
|
||||
|
||||
Use dry run when you want to check mapping and structure without saving data. If a duplicate project title is found, the importer can rename the new project so existing work is not overwritten.
|
||||
|
||||
After a successful import, open the created project and review the books, chapters, scenes, characters and related records.
|
||||
|
||||
# Example
|
||||
|
||||
You may have an outline with three books, thirty chapters and two hundred scenes. Entering that manually would be slow. An import package can create the structure, then you can use PlotDirector to refine scene summaries, metrics, relationships, locations and continuity.
|
||||
|
||||
# Writer Tip
|
||||
|
||||
Preview before committing. The most useful import is not the fastest one; it is the one that gives you a clean starting structure you trust.
|
||||
|
||||
# Common Mistakes
|
||||
|
||||
- Importing without checking whether scene order and chapter order are correct.
|
||||
- Treating warnings as meaningless because the import can still continue.
|
||||
- Expecting imports to solve story quality rather than structure setup.
|
||||
- Re-importing the same material instead of editing the created project.
|
||||
|
||||
# Related Guides
|
||||
|
||||
- [Books](/Help/Article/books.overview)
|
||||
- [Chapters](/Help/Article/chapters.overview)
|
||||
- [Scenes](/Help/Article/scenes.overview)
|
||||
- [Characters](/Help/Article/characters.overview)
|
||||
Read [Book backup and restore](/Help/Article/bookRecovery.overview) for the complete workflow.
|
||||
|
||||
@ -49,3 +49,7 @@ Name restore points after the decision you are protecting, not just the date. Fu
|
||||
- [Project Dashboard](/Help/Article/projectDashboard.overview)
|
||||
- [Imports](/Help/Article/imports.overview)
|
||||
- [Projects](/Help/Article/projects.overview)
|
||||
|
||||
# Downloaded book backups and capacity
|
||||
|
||||
For portable recovery, use **Projects → Back up books** and **Restore books from backup**. A saved restore point rewinds this same project; it is not selective book recovery. Owner authority is required for project-wide downloads, saved-point deletion and replacement. A rewind that adds books must fit your current allowance, including archived books. Older points that omit existing author review or Intent decisions are refused to protect that information.
|
||||
|
||||
40
PlotLine/Models/BookRecoveryModels.cs
Normal file
40
PlotLine/Models/BookRecoveryModels.cs
Normal file
@ -0,0 +1,40 @@
|
||||
namespace PlotLine.Models;
|
||||
|
||||
public sealed class BookBackupPackage
|
||||
{
|
||||
public string Format { get; set; } = "PlotDirector.BookBackup"; public string FormatVersion { get; set; } = "2.0";
|
||||
public Guid SourceProjectKey { get; set; }
|
||||
public DateTime CreatedUtc { get; set; } = DateTime.UtcNow;
|
||||
public ProjectBackupExport Snapshot { get; set; } = new();
|
||||
public Dictionary<string, string> Identities { get; set; } = []; public string[] Warnings { get; set; } = []; public string Integrity { get; set; } = "";
|
||||
}
|
||||
public sealed record BookRecoveryPlan(Guid Upload, int[] Books, int Destination, string Name, string DestinationHash, Guid Operation, DateTime Expires);
|
||||
public sealed class BookRecoveryReceipt { public bool AlreadyCompleted { get; set; } public int ProjectID { get; set; } public int BooksCreated { get; set; } public string RequestHash { get; set; } = ""; }
|
||||
public sealed class BookRecoveryMapping { public string PortableKey { get; set; } = ""; public string Collection { get; set; } = ""; public int DestinationID { get; set; } public string SourceHash { get; set; } = ""; public string DestinationHash { get; set; } = ""; }
|
||||
public sealed class ProjectRecoveryState
|
||||
{
|
||||
public List<PortableExternalReference> ExternalReferences { get; set; } = [];
|
||||
public List<PortableNativeReview> NativeReviews { get; set; } = []; public List<PortableIntentAssessment> IntentAssessments { get; set; } = [];
|
||||
}
|
||||
public sealed class PortableNativeReview
|
||||
{
|
||||
public Guid ReviewID { get; set; }
|
||||
public int UserID { get; set; }
|
||||
public int BookID { get; set; }
|
||||
public Guid ManuscriptID { get; set; }
|
||||
public int ChapterStart { get; set; }
|
||||
public int ChapterEnd { get; set; }
|
||||
public string ContentHash { get; set; } = ""; public string ResultJson { get; set; } = ""; public string? DecisionsJson { get; set; }
|
||||
public int Version { get; set; }
|
||||
public DateTime CreatedUtc { get; set; }
|
||||
public string? SourceJson { get; set; }
|
||||
[System.Text.Json.Serialization.JsonIgnore] public string? EncryptedSource { get; set; }
|
||||
}
|
||||
public sealed class PortableIntentAssessment
|
||||
{
|
||||
public int UserID { get; set; }
|
||||
public int SceneID { get; set; }
|
||||
public string InputHash { get; set; } = ""; public string ResultsJson { get; set; } = "[]"; public string DecisionsJson { get; set; } = "{}"; public string Model { get; set; } = ""; public DateTime CreatedUtc { get; set; }
|
||||
}
|
||||
|
||||
public sealed record PortableExternalReference(string Collection, int OwnerID, string Field, string TargetKey, bool BindingRequired = false);
|
||||
@ -3,7 +3,8 @@ namespace PlotLine.Models;
|
||||
public sealed class ProjectBackupExport
|
||||
{
|
||||
public string Format { get; init; } = "PlotDirector.ProjectBackup";
|
||||
public string FormatVersion { get; init; } = "1.3";
|
||||
public string FormatVersion { get; init; } = "1.4";
|
||||
public ProjectRecoveryState Recovery {get;set;}=new();
|
||||
public DateTime ExportedAtUtc { get; init; }
|
||||
public string SourceApplication { get; init; } = "PlotDirector";
|
||||
public Project? Project { get; init; }
|
||||
|
||||
@ -99,6 +99,9 @@ public class Program
|
||||
builder.Services.AddSingleton<PlotLine.Services.NativeCompanion.NativeAnalysisCache>();
|
||||
builder.Services.AddScoped<PlotLine.Data.IIntentAssessmentRepository,PlotLine.Data.IntentAssessmentRepository>();
|
||||
builder.Services.AddScoped<IntentAssessmentService>();
|
||||
builder.Services.AddScoped<PlotLine.Data.BookRecoveryRepository>();
|
||||
builder.Services.AddScoped<BookRecoveryService>();
|
||||
builder.Services.AddSingleton<BookRecoveryUploads>();
|
||||
builder.Services.AddScoped<PlotLine.Data.INativePositionRepository,PlotLine.Data.NativePositionRepository>();
|
||||
builder.Services.AddScoped<PlotLine.Data.INativeImportRepository,PlotLine.Data.NativeImportRepository>();
|
||||
builder.Services.AddScoped<PlotLine.Services.NativeCompanion.NativeImportService>();
|
||||
|
||||
@ -2,7 +2,7 @@ using PlotLine.ViewModels;
|
||||
namespace PlotLine.Services;
|
||||
|
||||
public sealed record RibbonCommand(string Label, string IconKey, string Controller, string Action,
|
||||
string Scope = "project", bool OwnerOnly = false, string? ToolbarKey = null)
|
||||
string Scope = "project", bool OwnerOnly = false, string? ToolbarKey = null, bool Post = false)
|
||||
{
|
||||
public bool Available(ApplicationNavigationViewModel model) => (Scope == "global" || model.Project is not null)
|
||||
&& (Scope != "book" && Scope != "chapter" || model.Book is not null) && (!OwnerOnly || model.Project?.IsOwner == true);
|
||||
@ -25,9 +25,9 @@ public static class ApplicationRibbon
|
||||
private static RibbonCommand S(string key) => RibbonCommand.Shortcut(key);
|
||||
public static IReadOnlyList<RibbonCategory> Categories { get; } = [
|
||||
new("project", "Project",
|
||||
new("Workspace", S("overview"), S("projects"), S("writer"), new("Import", "assets", "Imports", "Index", "global")),
|
||||
new("Workspace", S("overview"), S("projects"), S("writer"), new("Import a manuscript", "assets", "Onboarding", "StartImport", "global", Post: true)),
|
||||
new("Project", new("Edit project", "writer", "Projects", "Edit", "id"), new("Add book", "bible", "Books", "Create"), new("Activity", "metrics", "Projects", "Activity", "id")),
|
||||
new("Manage", new("Collaborators", "characters", "ProjectCollaborators", "Index", OwnerOnly: true), new("Backup", "archive", "Exports", "ProjectBackup", OwnerOnly: true), new("Restore points", "archive", "ProjectRestorePoints", "Index"))),
|
||||
new("Manage", new("Collaborators", "characters", "ProjectCollaborators", "Index", OwnerOnly: true), new("Back up books", "backup", "BookRecovery", "Backup", OwnerOnly: true), new("Restore books", "restore", "BookRecovery", "Restore", "global"), new("Rewind project", "restore", "ProjectRestorePoints", "Index", OwnerOnly: true))),
|
||||
new("book", "Book",
|
||||
new("Selected book", new("Book overview", "bible", "Books", "Details", "book"), new("Edit book", "writer", "Books", "Edit", "book"), new("Add chapter", "threads", "Chapters", "Create", "chapter")),
|
||||
new("Manuscript review", S("review")), new("Library", S("overview"), new("Add book", "bible", "Books", "Create"))),
|
||||
|
||||
102
PlotLine/Services/BookBackupGraph.cs
Normal file
102
PlotLine/Services/BookBackupGraph.cs
Normal file
@ -0,0 +1,102 @@
|
||||
using System.Collections;
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using PlotLine.Models;
|
||||
namespace PlotLine.Services;
|
||||
|
||||
public static class BookBackupGraph
|
||||
{
|
||||
public static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true };
|
||||
internal static readonly HashSet<string> Common = new(StringComparer.Ordinal) { "StoryIntelligenceIllustrationDemands", "Characters", "CharacterAliases", "CharacterImages", "CharacterAttributeTypes", "CharacterRelationships", "Locations", "LocationAliases", "LocationRelationships", "FloorPlans", "FloorPlanFloors", "FloorPlanBlocks", "FloorPlanTransitions", "StoryMaps", "MapFeatures", "MapRelationships", "MapReferenceImages", "PlotLines", "PlotThreads", "StoryAssets", "AssetAliases", "AssetStates", "AssetDependencies", "SceneMetricTypes", "TimelineSettings", "TimelineMetricSettings", "GenreMetricPresets", "GenreMetricPresetMetrics" };
|
||||
internal static readonly Dictionary<string, string> Aliases = new() { ["TimelineSettings"] = "ProjectTimelineSettings", ["TimelineMetricSettings"] = "ProjectTimelineMetricSettings", ["AssetCustodyCharacters"] = "AssetCustodyEventCharacters" };
|
||||
internal static string Table(string collection) => Aliases.GetValueOrDefault(collection, collection);
|
||||
internal static object[] Rows(ProjectBackupExport b, string c) => ((IEnumerable)typeof(ProjectBackupData).GetProperty(c)!.GetValue(b.Data)!).Cast<object>().ToArray();
|
||||
internal static object? Value(object row, string field) => row.GetType().GetProperty(field)?.GetValue(row);
|
||||
internal static string? Identity(string c) => ProjectBackupGraphValidation.Entities.FirstOrDefault(e => e.Collection == c)?.Identity;
|
||||
internal static void SetRows(ProjectBackupExport b, string c, IEnumerable<object> rows) { var p = typeof(ProjectBackupData).GetProperty(c)!; var type = p.PropertyType.GetGenericArguments()[0]; var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(type))!; foreach (var r in rows) list.Add(r); p.SetValue(b.Data, list); }
|
||||
public static string Hash(object value) => Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(value)));
|
||||
public static ProjectBackupExport Clone(ProjectBackupExport b) => JsonSerializer.Deserialize<ProjectBackupExport>(JsonSerializer.Serialize(b), Json)!;
|
||||
public static ProjectBackupExport Select(ProjectBackupExport source, IEnumerable<int> selected, Guid origin = default)
|
||||
{
|
||||
var b = Clone(source); var books = selected.Distinct().ToHashSet(); if (books.Count == 0 || books.Any(id => !b.Data.Books.Any(x => x.BookID == id))) throw new ArgumentException("Choose books contained in this backup.");
|
||||
SetRows(b, "Books", b.Data.Books.Where(x => books.Contains(x.BookID))); var schema = ProjectBackupGraphValidation.Entities;
|
||||
// Ownership is rooted in books. Shared definitions stay complete; book-specific children follow their parent.
|
||||
var owned = new HashSet<string> { "Books" }; bool changed = true; while (changed) { changed = false; foreach (var e in schema) if (!Common.Contains(e.Collection) && e.Links.Any(l => owned.Contains(l.TargetCollection))) changed |= owned.Add(e.Collection); }
|
||||
var priority = new[] { "BookID", "ChapterID", "ReviewCandidateID", "ReviewCandidateGenerationID", "CharacterEnrichmentRunID", "WholeBookPlotSynthesisRunID", "ImportSessionID", "BuildID", "WritingPlanID", "ScenarioID", "StoryMemoryCharacterID", "StoryMemoryLocationID", "StoryMemoryAssetID", "StoryIntelligenceRunID", "SceneResultID", "SceneID" };
|
||||
for (var pass = 0; pass < schema.Length; pass++)
|
||||
{
|
||||
var removed = false; foreach (var e in schema.Where(e => owned.Contains(e.Collection) && e.Collection != "Books"))
|
||||
{
|
||||
var owners = e.Links.Where(l => owned.Contains(l.TargetCollection)).OrderBy(l => Array.IndexOf(priority, l.Column) < 0 ? 999 : Array.IndexOf(priority, l.Column)).ToArray(); if (owners.Length == 0) continue;
|
||||
var rows = Rows(b, e.Collection); var keep = rows.Where(row => { var owner = owners.FirstOrDefault(l => Value(row, l.Column) != null); return owner == null || Rows(b, owner.TargetCollection).Any(target => Equals(Value(target, owner.TargetColumn), Value(row, owner.Column))); }).ToArray(); if (keep.Length != rows.Length) { SetRows(b, e.Collection, keep); removed = true; }
|
||||
}
|
||||
if (!removed) break;
|
||||
}
|
||||
var scenes = b.Data.Scenes.Select(s => s.SceneID).ToHashSet();
|
||||
if (source.Data.SceneDependencies.Any(d => scenes.Contains(d.SourceSceneID) != scenes.Contains(d.TargetSceneID))) throw new ArgumentException("These books have a cross-book scene dependency. Include the connected books to preserve it.");
|
||||
if (source.Data.MapJourneyNotes.Any(n => scenes.Contains(n.FromSceneID) != scenes.Contains(n.ToSceneID))) throw new ArgumentException("A saved map journey connects these books. Include the connected books to preserve it.");
|
||||
b.Recovery.ExternalReferences = b.Recovery.ExternalReferences.Where(r => Identity(r.Collection) is string identity && Rows(b, r.Collection).Any(owner => Equals(Value(owner, identity), r.OwnerID))).ToList();
|
||||
// Never turn an excluded source number into a destination reference. Refuse rather than dropping canonical links.
|
||||
foreach (var entity in schema.Where(e => Common.Contains(e.Collection) && e.Identity != null)) foreach (var link in entity.Links.Where(l => owned.Contains(l.TargetCollection)))
|
||||
{
|
||||
var allowed = Rows(b, link.TargetCollection).Select(r => Value(r, link.TargetColumn)).ToHashSet(); foreach (var row in Rows(b, entity.Collection)) if (Value(row, link.Column) is object value && !allowed.Contains(value))
|
||||
{
|
||||
var property = row.GetType().GetProperty(link.Column)!; if (Value(row, entity.Identity!) is not int id || origin == Guid.Empty) throw new ArgumentException("A common definition requires another book. Include the related books.");
|
||||
if (!b.Recovery.ExternalReferences.Any(r => r.Collection == entity.Collection && r.OwnerID == id && r.Field == link.Column && r.BindingRequired)) { b.Recovery.ExternalReferences.RemoveAll(r => r.Collection == entity.Collection && r.OwnerID == id && r.Field == link.Column); b.Recovery.ExternalReferences.Add(new(entity.Collection, id, link.Column, $"{origin:N}/{link.TargetCollection}/{value}", Nullable.GetUnderlyingType(property.PropertyType) == null)); }
|
||||
if (Nullable.GetUnderlyingType(property.PropertyType) != null) property.SetValue(row, null);
|
||||
}
|
||||
}
|
||||
var retainedPresets = new List<object>(); foreach (var preset in b.Data.TimelineViewPresets.ToArray()) { SetRows(b, "TimelineViewPresets", [preset]); if (ProjectBackupTimelineState.Validate(b) == null) retainedPresets.Add(preset); else if (ProjectBackupTimelineState.Validate(source) != null) throw new ArgumentException("A source timeline preset is invalid; repair it before backing up."); }
|
||||
SetRows(b, "TimelineViewPresets", retainedPresets);
|
||||
var error = ProjectBackupMapValidation.Validate(b) ?? ProjectBackupGraphValidation.Validate(b, true); if (error != null) throw new ArgumentException("The selection has a dependency outside these books. Include the related books. " + error);
|
||||
b.Recovery.NativeReviews = b.Recovery.NativeReviews.Where(r => books.Contains(r.BookID)).ToList(); b.Recovery.IntentAssessments = b.Recovery.IntentAssessments.Where(r => scenes.Contains(r.SceneID)).ToList();
|
||||
SetRows(b, "ProjectAccess", []); SetRows(b, "UserFiles", []);
|
||||
ProjectBackupFiles.Prune(b); return b;
|
||||
}
|
||||
public static string StoredHash(string collection, object row)
|
||||
{
|
||||
var fields = ProjectBackupStoredFieldContract.Columns(collection); if (fields.Length == 0) return Hash(row); var node = JsonSerializer.SerializeToNode(row)!.AsObject(); foreach (var key in node.Select(p => p.Key).ToArray()) if (!fields.Contains(key, StringComparer.OrdinalIgnoreCase)) node.Remove(key); foreach(var property in row.GetType().GetProperties().Where(p=>node.ContainsKey(p.Name))){var value=property.GetValue(row);if(value is DateTime date)node[property.Name]=JsonSerializer.SerializeToNode(DateTime.SpecifyKind(date,DateTimeKind.Unspecified));else if(value is decimal number)node[property.Name]=JsonNode.Parse(number.ToString("G29",System.Globalization.CultureInfo.InvariantCulture));}
|
||||
return Hash(node);
|
||||
}
|
||||
internal static void Merge(ProjectBackupExport destination, ProjectBackupExport incoming)
|
||||
{
|
||||
foreach (var p in typeof(ProjectBackupData).GetProperties())
|
||||
{
|
||||
if (p.Name is "ProjectAccess" or "UserFiles" or "GenreMetricPresets" or "GenreMetricPresetMetrics" or "TimelineSettings") continue;
|
||||
var original = Rows(destination, p.Name); var next = Rows(incoming, p.Name); var key = Identity(p.Name);
|
||||
if (key != null) { var keys = original.ToDictionary(r => Value(r, key)!); foreach (var row in next) if (keys.TryGetValue(Value(row, key)!, out var prior) && StoredHash(p.Name, prior) != StoredHash(p.Name, row)) throw new ArgumentException("A destination identity conflict was detected; nothing was overwritten."); next = next.Where(r => !keys.ContainsKey(Value(r, key)!)).ToArray(); }
|
||||
if (p.Name == "TimelineMetricSettings") next = next.Where(r => !original.Any(o => Equals(Value(o, "ProjectID"), Value(r, "ProjectID")) && Equals(Value(o, "MetricTypeID"), Value(r, "MetricTypeID")))).ToArray();
|
||||
SetRows(destination, p.Name, original.Concat(next).DistinctBy(r => StoredHash(p.Name, r)));
|
||||
}
|
||||
destination.Recovery.ExternalReferences.AddRange(incoming.Recovery.ExternalReferences);
|
||||
destination.Recovery.NativeReviews.AddRange(incoming.Recovery.NativeReviews); destination.Recovery.IntentAssessments.AddRange(incoming.Recovery.IntentAssessments);
|
||||
}
|
||||
public static void RemapState(ProjectBackupExport b, Dictionary<string, Dictionary<int, int>> maps, int user)
|
||||
{
|
||||
int Id(string type, int old) => maps.TryGetValue(type, out var rows) && rows.TryGetValue(old, out var value) ? value : throw new ArgumentException("Recovery state has an unresolved " + type + " reference.");
|
||||
string Key(string key) => key.StartsWith("checklist-", StringComparison.Ordinal) && int.TryParse(key[10..], out var old) ? maps.TryGetValue("SceneChecklistItems", out var ids) && ids.TryGetValue(old, out var mapped) ? "checklist-" + mapped : "historical-" + key : key;
|
||||
var manuscripts = new Dictionary<(Guid, int), Guid>();
|
||||
foreach (var review in b.Recovery.NativeReviews)
|
||||
{
|
||||
var original = review.CreatedUtc;var sourceUser=review.UserID; review.BookID = Id("Books", review.BookID); review.UserID = user; var originalReview = review.ReviewID; review.ReviewID = Guid.NewGuid(); var manuscriptKey = (review.ManuscriptID, review.BookID); if (!manuscripts.TryGetValue(manuscriptKey, out var manuscript)) manuscripts[manuscriptKey] = manuscript = Guid.NewGuid(); review.ManuscriptID = manuscript; review.CreatedUtc = DateTime.UtcNow;
|
||||
var result = JsonNode.Parse(review.ResultJson)!.AsObject(); if(result["RecoverySourceUserID"]==null)result["RecoverySourceUserID"]=sourceUser;result["RecoverySourceReviewID"] = originalReview; result["RecoveryOriginalCreatedUtc"] = original; result["RequestId"] = review.ReviewID; result["ReviewPath"] = "/native-companion/reviews/" + review.ReviewID; review.ResultJson = result.ToJsonString();
|
||||
if (review.SourceJson != null) { var capture = JsonSerializer.Deserialize<PlotDirector.Companion.Protocol.AiChapterRequest>(review.SourceJson, Json) ?? throw new ArgumentException("Invalid review source"); capture.BookId = review.BookID; capture.ManuscriptId = review.ManuscriptID; capture.SessionId = Guid.Empty; capture.RequestId = review.ReviewID; review.SourceJson = JsonSerializer.Serialize(capture); }
|
||||
}
|
||||
b.Recovery.ExternalReferences = b.Recovery.ExternalReferences.Select(r => r with { OwnerID = Id(Table(r.Collection), r.OwnerID), BindingRequired = false }).ToList();
|
||||
foreach (var assessment in b.Recovery.IntentAssessments)
|
||||
{
|
||||
var sourceUser=assessment.UserID;assessment.UserID = user; assessment.SceneID = Id("Scenes", assessment.SceneID); var originalHash = assessment.InputHash; assessment.InputHash = Hash(new { assessment.InputHash, ImportedScene = assessment.SceneID, SourceUser=sourceUser });
|
||||
var rows = JsonNode.Parse(assessment.ResultsJson)!.AsArray(); foreach (var item in rows) { var record = item!.AsObject(); record["Key"] = Key(record["Key"]!.GetValue<string>()); record["RecoverySourceInputHash"] = originalHash;if(record["RecoverySourceUserID"]==null)record["RecoverySourceUserID"]=sourceUser; }
|
||||
assessment.ResultsJson = rows.ToJsonString(); var decisions = JsonSerializer.Deserialize<Dictionary<string, string>>(assessment.DecisionsJson) ?? []; assessment.DecisionsJson = JsonSerializer.Serialize(decisions.ToDictionary(p => Key(p.Key), p => p.Value));
|
||||
}
|
||||
}
|
||||
public static string Validate(BookBackupPackage package)
|
||||
{
|
||||
if (package.Snapshot.FormatVersion != "1.4") throw new ArgumentException("Current book backup requires a complete recovery snapshot.");
|
||||
if (package.Format != "PlotDirector.BookBackup" || package.FormatVersion != "2.0" || package.SourceProjectKey == Guid.Empty) throw new ArgumentException("Unsupported book backup version.");
|
||||
var expected = Hash(new { package.SourceProjectKey, package.Snapshot, package.Identities, package.Warnings }); if (!string.Equals(expected, package.Integrity, StringComparison.Ordinal)) throw new ArgumentException("Backup integrity check failed.");
|
||||
return ProjectBackupMapValidation.Validate(package.Snapshot) ?? ProjectBackupGraphValidation.Validate(package.Snapshot, true) ?? ProjectBackupFiles.Validate(package.Snapshot) ?? "";
|
||||
}
|
||||
}
|
||||
183
PlotLine/Services/BookRecoveryService.cs
Normal file
183
PlotLine/Services/BookRecoveryService.cs
Normal file
@ -0,0 +1,183 @@
|
||||
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<ProjectBackupExport> Source(int project) => OwnerSnapshot(project);
|
||||
public async Task<BookBackupPackage> 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<string,string>();var used=new HashSet<string>(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};
|
||||
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<BookRecoveryMapping>();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<BookBackupPackage>(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()=="1.4"))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<string>(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)
|
||||
{
|
||||
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<PlotDirector.Companion.Protocol.AiChapterRequest>(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<BookRecoveryPreview> 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<string>():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<string>()).Append("Existing destination project settings are retained; conflicting common records create independent copies. Maps are copied as independent bundles.").ToArray());
|
||||
}
|
||||
private async Task<ProjectBackupExport> 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<string>(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<string, Dictionary<int, int>> Maps, List<(string Collection, int Source, string Key, string Hash)> Sources, int Reused, int Created, string[] Conflicts);
|
||||
private async Task<Prepared> Prepare(BookBackupPackage package, ProjectBackupExport selected, ProjectBackupExport? target, int project, string name)
|
||||
{
|
||||
var known = target == null ? [] : await repository.Mappings(project, User);
|
||||
var reuse = new Dictionary<string, Dictionary<int, int>>();
|
||||
// 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<Guid, Guid>(); 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<string, Dictionary<int, int>> 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<BookRecoveryReceipt> Restore(string confirmation, Func<Guid, BookBackupPackage> 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<BookRecoveryPlan>()!; 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); var mappings = new List<BookRecoveryMapping>(); 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); }
|
||||
}
|
||||
}
|
||||
40
PlotLine/Services/BookRecoveryUploads.cs
Normal file
40
PlotLine/Services/BookRecoveryUploads.cs
Normal file
@ -0,0 +1,40 @@
|
||||
using PlotLine.Models;
|
||||
namespace PlotLine.Services;
|
||||
|
||||
// Author-bound immutable uploads. Register before reading so slow earlier requests cannot supersede newer files.
|
||||
public sealed class BookRecoveryUploads
|
||||
{
|
||||
private sealed record Entry(int User, string Json, DateTime Expires, string Name);
|
||||
private readonly object gate = new();
|
||||
private readonly Dictionary<Guid, Entry> items = [];
|
||||
private readonly Dictionary<int, (Guid Version, DateTime Expires)> generations = [];
|
||||
public Guid Begin(int user)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
foreach (var key in items.Where(p => p.Value.Expires < DateTime.UtcNow || p.Value.User == user).Select(p => p.Key).ToArray()) items.Remove(key);
|
||||
foreach (var key in generations.Where(p => p.Value.Expires < DateTime.UtcNow).Select(p => p.Key).ToArray()) generations.Remove(key);
|
||||
if (!generations.ContainsKey(user) && generations.Count >= 4096) throw new ArgumentException("Backup workspace is busy. Try again shortly.");
|
||||
var version = Guid.NewGuid(); generations[user] = (version, DateTime.UtcNow.AddMinutes(30)); return version;
|
||||
}
|
||||
}
|
||||
public Guid Add(int user, string json, string name = "", Guid? generation = null)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
var version = generation ?? Begin(user);
|
||||
if (!generations.TryGetValue(user, out var latest) || latest.Version != version || latest.Expires < DateTime.UtcNow) throw new ArgumentException("A newer backup replaced this request. Choose your latest file again.");
|
||||
if (json.Length * 2L + items.Values.Sum(x => x.Json.Length * 2L) > 128 * 1024 * 1024) throw new ArgumentException("Backup workspace is busy. Try again shortly.");
|
||||
var filename = Path.GetFileName(name.Replace('\\', '/')); if (filename.Length > 200) filename = filename[..200];
|
||||
items.Add(version, new(user, json, latest.Expires, filename)); return version;
|
||||
}
|
||||
}
|
||||
private Entry EntryFor(int user, Guid id)
|
||||
{
|
||||
if (!items.TryGetValue(id, out var entry) || entry.User != user) throw new UnauthorizedAccessException();
|
||||
if (entry.Expires < DateTime.UtcNow) throw new ArgumentException("Upload expired. Choose the file again.");
|
||||
return entry;
|
||||
}
|
||||
public string Name(int user, Guid id) { lock (gate) return EntryFor(user, id).Name; }
|
||||
public BookBackupPackage Get(int user, Guid id) { string json; lock (gate) json = EntryFor(user, id).Json; return BookRecoveryService.Read(json); }
|
||||
}
|
||||
@ -14,7 +14,7 @@ public interface IImportService
|
||||
Task<string> BuildValidationReportAsync(ImportIndexViewModel model);
|
||||
}
|
||||
|
||||
public sealed class ImportService(IImportRepository imports, ICurrentUserService currentUser, ISubscriptionService subscriptions, ILogger<ImportService> logger, IProjectBackupFiles files) : IImportService
|
||||
public sealed class ImportService(IImportRepository imports, ICurrentUserService currentUser, ISubscriptionService subscriptions, ILogger<ImportService> logger, IProjectBackupFiles files, Microsoft.AspNetCore.DataProtection.IDataProtectionProvider? protection=null) : IImportService
|
||||
{
|
||||
private const int TitleMaxLength = 200;
|
||||
private const int RelativeTimeMaxLength = 200;
|
||||
@ -364,7 +364,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
||||
validation.Warnings.Add("Unfinished analysis will be copied as cancelled audit history. No paid analysis is restarted; retained source and raw result JSON remain historical audit data.");
|
||||
if(backup.Data.OnboardingManuscriptBuilds.Any(build=>build.Status is not ("Built" or "Complete" or "Completed" or "Failed" or "Cancelled") || build.Status=="Built" && build.MarkerStatus is not ("UserConfirmedSave" or "Completed" or "Complete")))
|
||||
validation.Warnings.Add("Unfinished Word import operations will be copied as cancelled history. They will not restart or send markers to the original document.");
|
||||
if (backup.FormatVersion != "1.3" && ProjectBackupFiles.HasUploads(backup))
|
||||
if (backup.FormatVersion is not ("1.3" or "1.4") && ProjectBackupFiles.HasUploads(backup))
|
||||
validation.Warnings.Add("This older backup does not contain uploaded file bytes. Imported copies retain text and link metadata, but uploaded images, covers and attachments must be added again.");
|
||||
if (duplicate)
|
||||
{
|
||||
@ -469,7 +469,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
||||
}
|
||||
|
||||
fileStage=await files.StageAsync(backup,importingCopy:true);
|
||||
var restoreJson = JsonSerializer.Serialize(backup, RestoreJsonOptions);
|
||||
var restoreJson = BookRecoveryRepository.Encode(backup,protection);
|
||||
await imports.ApplyProjectBackupJsonAsync(projectId, restoreJson);
|
||||
var relationshipDiagnostics = await imports.GetRelationshipImportDiagnosticsAsync(projectId);
|
||||
logger.LogInformation(
|
||||
@ -574,7 +574,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
||||
FinalCharacterCount = preview.CharacterCount
|
||||
};
|
||||
|
||||
private static bool TryReadProjectBackup(string jsonText, out ProjectBackupExport? backup, out ImportValidationResult validation)
|
||||
internal static bool TryReadProjectBackup(string jsonText, out ProjectBackupExport? backup, out ImportValidationResult validation)
|
||||
{
|
||||
backup = null;
|
||||
validation = new ImportValidationResult();
|
||||
@ -638,6 +638,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
||||
validation.Errors.Add("The project backup does not contain a project name.");
|
||||
}
|
||||
|
||||
if(backup.FormatVersion=="1.4"&&!ProjectBackupCollectionPresence.HasRecovery(jsonText)){validation.Errors.Add("Recovery decisions are missing from this current-format backup.");return true;}
|
||||
var mapError = ProjectBackupMapValidation.Validate(backup) ?? ProjectBackupGraphValidation.Validate(backup) ?? ProjectBackupNarrative.ValidatePortableSources(backup) ?? ProjectBackupFiles.Validate(backup);
|
||||
if(mapError is null && backup.Data.StoryMemoryLocations.Any(location=>location.ParentLocationID.HasValue))
|
||||
mapError="This backup contains a story-memory parent identifier whose portable relationship is not defined. Same-project restore retains it, but import as a copy is not supported for this field.";
|
||||
@ -856,7 +857,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
||||
return package;
|
||||
}
|
||||
|
||||
private static readonly string[] ProjectBackupIdentityTables =
|
||||
internal static readonly string[] ProjectBackupIdentityTables =
|
||||
[
|
||||
"ProjectTimelineSettings", "TimelineViewPresets", "SceneMetricTypes", "Books", "Chapters", "Scenes", "StoryMaps",
|
||||
"StoryMemoryIllustrationAssignments", "StoryMemoryIllustrationDemands", "StoryIntelligenceIllustrationDemands", "WholeBookPlotSynthesisRuns", "StoryIntelligenceNarrativeCandidates", "StoryIntelligenceNarrativeCandidateEvidence", "StoryIntelligenceNarrativeCandidateEvents", "CharacterEnrichmentRuns", "CharacterEnrichmentEvidence", "StoryIntelligenceReviewCandidateGenerations", "StoryIntelligenceReviewCandidates", "StoryIntelligenceReviewCandidateEvidence", "StoryIntelligenceBookPipelines", "StoryMemoryCharacters", "StoryMemoryCharacterAliases", "StoryMemoryCharacterAttributes", "StoryMemoryLocations", "StoryMemoryAssets", "StoryMemoryRelationships", "StoryMemoryProcessedSceneResults", "StoryMemoryImportPreferences", "CharacterIntelligenceProfiles", "CharacterIntelligenceEvidenceEvents", "StoryIntelligenceRuns", "StoryIntelligenceChapterResults", "StoryIntelligenceSceneResults", "StoryIntelligenceImportCommits", "CoreImportBasicLocationReviews", "CoreImportBasicLocationCandidates", "CoreImportBasicLocationEvidence", "SceneAssetSuggestions", "SceneCharacterSuggestions", "SceneLocationSuggestions", "OnboardingManuscriptBuilds", "CharacterImages", "WordCompanionSceneAssets", "WordCompanionSceneLocations", "ManuscriptDocuments", "WritingPlans", "WritingScheduleItems", "CharacterAliases", "AssetAliases", "LocationAliases", "AuthorPlotSeeds", "ContinuityWarningAcknowledgements",
|
||||
@ -870,23 +871,23 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
||||
"ScenarioWarnings"
|
||||
];
|
||||
|
||||
private static readonly string[] SupportedProjectBackupVersions = ["1.0", "1.1", "1.2", "1.3"];
|
||||
private static readonly string[] SupportedProjectBackupVersions = ["1.0", "1.1", "1.2", "1.3", "1.4"];
|
||||
|
||||
private static void RemapProjectBackupForImport(
|
||||
internal static Dictionary<string,Dictionary<int,int>> RemapProjectBackupForImport(
|
||||
ProjectBackupExport backup,
|
||||
int projectId,
|
||||
string projectName,
|
||||
IReadOnlyDictionary<string, int> maxIds,
|
||||
ProjectBackupRelationshipImportLookups relationshipLookups,
|
||||
ICollection<string> warnings,
|
||||
int importingUserId)
|
||||
int importingUserId,Dictionary<string,Dictionary<int,int>>? reuse=null,Dictionary<Guid,Guid>? reusableImages=null,bool strictLookups=false)
|
||||
{
|
||||
if (backup.Project is null)
|
||||
{
|
||||
return;
|
||||
throw new ArgumentException("Missing project");
|
||||
}
|
||||
|
||||
var maps = new Dictionary<string, Dictionary<int, int>>(StringComparer.OrdinalIgnoreCase);
|
||||
var maps = reuse?.ToDictionary(p=>p.Key,p=>new Dictionary<int,int>(p.Value),StringComparer.OrdinalIgnoreCase) ?? new Dictionary<string, Dictionary<int, int>>(StringComparer.OrdinalIgnoreCase);
|
||||
var nextIds = ProjectBackupIdentityTables.ToDictionary(table => table, table => maxIds.TryGetValue(table, out var maxId) ? maxId : 0, StringComparer.OrdinalIgnoreCase);
|
||||
int Next(string table) => nextIds[table] = nextIds[table] + 1;
|
||||
Dictionary<int, int> Map(string table) => maps.TryGetValue(table, out var map) ? map : maps[table] = new Dictionary<int, int>();
|
||||
@ -895,7 +896,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
||||
var map = Map(table);
|
||||
if (!map.TryGetValue(oldId, out var newId))
|
||||
{
|
||||
newId = Next(table);
|
||||
newId = reuse!=null&&reuse.TryGetValue(table,out var reusable)&&reusable.TryGetValue(oldId,out var existing)?existing:Next(table);
|
||||
map[oldId] = newId;
|
||||
}
|
||||
|
||||
@ -954,6 +955,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
||||
return resolvedId;
|
||||
}
|
||||
|
||||
if(strictLookups)throw new ArgumentException($"{context} has an unavailable vocabulary value. Resolve the named value before restoring; numeric IDs cannot establish compatibility.");
|
||||
warnings.Add($"{context} has lookup value \"{lookupName}\" which was not found in the target database. The exported ID {currentId} was retained.");
|
||||
return currentId;
|
||||
}
|
||||
@ -988,6 +990,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
||||
return relationshipTypeId;
|
||||
}
|
||||
|
||||
if(strictLookups)throw new ArgumentException("A relationship type is unavailable in this installation. Resolve its named vocabulary before restoring.");
|
||||
warnings.Add($"Relationship {relationship.CharacterRelationshipID} between \"{relationship.CharacterAName}\" and \"{relationship.CharacterBName}\" has relationship type \"{relationship.RelationshipTypeName}\" which was not found in the target database. The exported ID {relationship.RelationshipTypeID} was retained.");
|
||||
return relationship.RelationshipTypeID;
|
||||
}
|
||||
@ -1004,6 +1007,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
||||
return relationshipStateId;
|
||||
}
|
||||
|
||||
if(strictLookups)throw new ArgumentException($"{context} has an unavailable relationship state. Resolve its named vocabulary before restoring.");
|
||||
warnings.Add($"{context} has relationship state \"{stateName}\" which was not found in the target database. The exported ID {stateId.Value} was retained.");
|
||||
return stateId;
|
||||
}
|
||||
@ -1542,7 +1546,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
||||
foreach (var image in backup.Data.MapReferenceImages)
|
||||
{
|
||||
var oldId = image.ImageID;
|
||||
image.ImageID = Guid.NewGuid();
|
||||
image.ImageID = reusableImages!=null&&reusableImages.TryGetValue(oldId,out var imageId)?imageId:Guid.NewGuid();
|
||||
image.ProjectID = projectId;
|
||||
imageIds.Add(oldId, image.ImageID);
|
||||
}
|
||||
@ -1769,7 +1773,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
||||
row.IllustrationLibraryItemID=null;
|
||||
if(row.InvalidatedUtc is null)
|
||||
{
|
||||
row.InvalidatedUtc=DateTime.UtcNow;
|
||||
var invalidated=DateTime.UtcNow;row.InvalidatedUtc=new DateTime(invalidated.Ticks-invalidated.Ticks%TimeSpan.TicksPerSecond,DateTimeKind.Utc); // SQL datetime2(0).
|
||||
row.InvalidationReason="Imported as inactive history; shared illustration catalogue links require explicit reassignment.";
|
||||
}
|
||||
}
|
||||
@ -1921,7 +1925,7 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
||||
image.ProjectID=projectId;
|
||||
}
|
||||
foreach (var character in backup.Data.Characters)
|
||||
character.AvatarSourceCharacterImageID=backup.FormatVersion=="1.3" ? ExistingOrNewNullable("CharacterImages",character.AvatarSourceCharacterImageID) : null;
|
||||
character.AvatarSourceCharacterImageID=backup.FormatVersion is ("1.3" or "1.4") ? ExistingOrNewNullable("CharacterImages",character.AvatarSourceCharacterImageID) : null;
|
||||
foreach (var link in backup.Data.WordCompanionSceneAssets)
|
||||
{
|
||||
link.WordCompanionSceneAssetID=NewId("WordCompanionSceneAssets",link.WordCompanionSceneAssetID);
|
||||
@ -1936,6 +1940,8 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService
|
||||
}
|
||||
foreach (var preset in backup.Data.TimelineViewPresets)
|
||||
ProjectBackupTimelineState.Remap(preset,projectId,ExistingOrNewNullable);
|
||||
BookBackupGraph.RemapState(backup,maps,importingUserId);
|
||||
return maps;
|
||||
}
|
||||
|
||||
private static int? RemapPolymorphicEntityID(string? entityType, int? entityId, Func<string, int?, int?> remap)
|
||||
|
||||
@ -80,6 +80,7 @@ public sealed class ProjectAccessFilter(IProjectAccessService access, ICurrentUs
|
||||
["PlotLineWorkspace"] = new(StringComparer.OrdinalIgnoreCase) { ["projectId"] = "Project", ["bookId"] = "Book", ["sceneId"] = "Scene", ["scenarioId"] = "Scenario" },
|
||||
["ProjectMetrics"] = new(StringComparer.OrdinalIgnoreCase) { ["projectId"] = "Project" },
|
||||
["ProjectRestorePoints"] = new(StringComparer.OrdinalIgnoreCase) { ["projectId"] = "Project", ["id"] = "ProjectRestorePoint" },
|
||||
["BookRecovery"] = new(StringComparer.OrdinalIgnoreCase) { ["projectId"] = "Project", ["bookId"] = "Book" },
|
||||
["RelationshipMap"] = new(StringComparer.OrdinalIgnoreCase) { ["projectId"] = "Project", ["bookId"] = "Book", ["chapterId"] = "Chapter", ["sceneId"] = "Scene", ["focusCharacterId"] = "Character" },
|
||||
["Scenarios"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "Scenario", ["scenarioId"] = "Scenario", ["projectId"] = "Project", ["bookId"] = "Book", ["sceneId"] = "Scene", ["anchorSceneId"] = "Scene", ["targetChapterId"] = "Chapter" },
|
||||
["StoryAssets"] = new(StringComparer.OrdinalIgnoreCase) { ["id"] = "StoryAsset", ["returnAssetId"] = "StoryAsset", ["projectId"] = "Project" },
|
||||
@ -100,7 +101,9 @@ public sealed class ProjectAccessFilter(IProjectAccessService access, ICurrentUs
|
||||
{
|
||||
["Projects"] = new(StringComparer.OrdinalIgnoreCase) { "Archive" },
|
||||
["ProjectCollaborators"] = new(StringComparer.OrdinalIgnoreCase) { "Index", "Add", "Remove" },
|
||||
["Exports"] = new(StringComparer.OrdinalIgnoreCase) { "ProjectBackup" }
|
||||
["Exports"] = new(StringComparer.OrdinalIgnoreCase) { "ProjectBackup" },
|
||||
["ProjectRestorePoints"] = new(StringComparer.OrdinalIgnoreCase) { "Index", "Create", "Download", "Delete", "Restore" },
|
||||
["BookRecovery"] = new(StringComparer.OrdinalIgnoreCase) { "Backup", "ReviewBackup", "Download" }
|
||||
};
|
||||
|
||||
private static readonly Dictionary<string, Dictionary<string, string>> ActionIdEntities = new(StringComparer.OrdinalIgnoreCase)
|
||||
|
||||
@ -64,6 +64,7 @@ internal static class ProjectBackupCollectionPresence
|
||||
return missing;
|
||||
}
|
||||
|
||||
internal static bool HasRecovery(string json){using var d=JsonDocument.Parse(json,ReadOptions);var state=Property(d.RootElement,"Recovery");return state.ValueKind==JsonValueKind.Object&&Property(state,"NativeReviews").ValueKind==JsonValueKind.Array&&Property(state,"IntentAssessments").ValueKind==JsonValueKind.Array&&Property(state,"ExternalReferences").ValueKind==JsonValueKind.Array;}
|
||||
internal static string PreserveOmissions(string originalJson,string mappedJson)
|
||||
{
|
||||
using var original=JsonDocument.Parse(originalJson,ReadOptions);
|
||||
|
||||
@ -28,6 +28,7 @@ public sealed class ProjectBackupFileStage : IDisposable
|
||||
|
||||
public sealed class ProjectBackupFiles(IUploadStorageService storage) : IProjectBackupFiles
|
||||
{
|
||||
public static bool IsActiveWebFile(string path)=>new[]{".html",".htm",".xhtml",".svg",".xml",".js",".mjs",".css"}.Contains(Path.GetExtension(path),StringComparer.OrdinalIgnoreCase);
|
||||
private sealed record Reference(string? Path, string Folder, string EntityType, int EntityID, Action<string?> Assign);
|
||||
private static IEnumerable<Reference> References(ProjectBackupExport backup)
|
||||
{
|
||||
@ -73,11 +74,12 @@ public sealed class ProjectBackupFiles(IUploadStorageService storage) : IProject
|
||||
return path.StartsWith("/uploads/"+reference.Folder+"/",StringComparison.Ordinal)
|
||||
&& !path.Contains('\\') && !path.Split('/').Any(segment=>segment is "." or "..");
|
||||
}
|
||||
public static void Prune(ProjectBackupExport backup){var paths=References(backup).Where(IsFile).Select(r=>r.Path).ToHashSet();backup.Files=backup.Files.Where(f=>paths.Contains(f.Path)).ToArray();}
|
||||
public static bool HasUploads(ProjectBackupExport backup) => References(backup).Any(IsFile);
|
||||
public static string? Validate(ProjectBackupExport backup)
|
||||
{
|
||||
if(backup.Files is null || backup.Files.Any(file=>file is null))return "Project backup contains invalid file records.";
|
||||
if(backup.FormatVersion!="1.3" && backup.Files.Count>0)return "Embedded files require project backup format 1.3.";
|
||||
if(backup.FormatVersion is not ("1.3" or "1.4") && backup.Files.Count>0)return "Embedded files require project backup format 1.3.";
|
||||
var references=References(backup).Where(IsFile).ToArray();
|
||||
if(references.Any(reference=>!ValidPath(reference)))return "Project backup contains a file path outside its owning entity's upload folder.";
|
||||
if(backup.Files.Select(file=>file.Path).Distinct(StringComparer.Ordinal).Count()!=backup.Files.Count)return "Project backup contains duplicate file paths.";
|
||||
@ -85,7 +87,7 @@ public sealed class ProjectBackupFiles(IUploadStorageService storage) : IProject
|
||||
foreach(var file in backup.Files)
|
||||
if(file.Path is null || !referenced.Contains(file.Path) || file.Data is null || !string.Equals(file.Sha256,Convert.ToHexString(SHA256.HashData(file.Data)),StringComparison.OrdinalIgnoreCase))
|
||||
return "Project backup contains an unreferenced file or file bytes do not match their checksum.";
|
||||
if(backup.FormatVersion=="1.3" && references.Any(reference=>!backup.Files.Any(file=>file.Path==reference.Path)))
|
||||
if(backup.FormatVersion is ("1.3" or "1.4") && references.Any(reference=>!backup.Files.Any(file=>file.Path==reference.Path)))
|
||||
return "Project backup is missing bytes for a referenced uploaded file.";
|
||||
return null;
|
||||
}
|
||||
@ -113,7 +115,7 @@ public sealed class ProjectBackupFiles(IUploadStorageService storage) : IProject
|
||||
{
|
||||
foreach(var file in backup.Files){file.RestoredPath=null;file.EntityType=null;file.EntityID=0;}
|
||||
var references=References(backup).Where(IsFile).ToArray();
|
||||
if(backup.FormatVersion!="1.3")
|
||||
if(backup.FormatVersion is not ("1.3" or "1.4"))
|
||||
{
|
||||
foreach(var reference in references)
|
||||
{
|
||||
@ -131,6 +133,8 @@ public sealed class ProjectBackupFiles(IUploadStorageService storage) : IProject
|
||||
var owner=owners[0];
|
||||
var extension=Path.GetExtension(file.Path);
|
||||
if(extension.Length is <2 or >12 || extension[1..].Any(character=>!char.IsAsciiLetterOrDigit(character)))extension=".bin";
|
||||
// Imported bytes must not become executable same-origin web content. Preserve bytes as a binary download.
|
||||
if(IsActiveWebFile(file.Path))extension=".bin";
|
||||
var filename=$"backup-{Guid.NewGuid():N}{extension.ToLowerInvariant()}";
|
||||
var physical=storage.GetFilePath(owner.Folder,filename);
|
||||
storage.GetDirectory(owner.Folder);
|
||||
|
||||
@ -5,9 +5,9 @@ namespace PlotLine.Services;
|
||||
// Explicit persisted relationships for the current serialized entity sets, not inferred author names.
|
||||
internal static class ProjectBackupGraphValidation
|
||||
{
|
||||
private sealed record Link(string Column, string TargetCollection, string TargetColumn);
|
||||
private sealed record Entity(string Collection, string? Identity, params Link[] Links);
|
||||
private static readonly Entity[] Entities = [
|
||||
internal sealed record Link(string Column, string TargetCollection, string TargetColumn);
|
||||
internal sealed record Entity(string Collection, string? Identity, params Link[] Links);
|
||||
internal static readonly Entity[] Entities = [
|
||||
new("StoryMemoryIllustrationAssignments","StoryMemoryIllustrationAssignmentID",new Link("ImportSessionID","StoryIntelligenceBookPipelines","StoryIntelligenceBookPipelineID")),
|
||||
new("StoryMemoryIllustrationDemands","StoryMemoryIllustrationDemandID",new Link("ImportSessionID","StoryIntelligenceBookPipelines","StoryIntelligenceBookPipelineID"),new Link("ProjectID","Project","ProjectID")),
|
||||
new("StoryIntelligenceIllustrationDemands","StoryIntelligenceIllustrationDemandID",new Link("ProjectID","Project","ProjectID")),
|
||||
@ -116,7 +116,7 @@ internal static class ProjectBackupGraphValidation
|
||||
new("WritingPlans", "WritingPlanID", new Link("BookID", "Books", "BookID"), new Link("ProjectID", "Project", "ProjectID")),
|
||||
new("WritingScheduleItems", "WritingScheduleItemID", new Link("SceneID", "Scenes", "SceneID"), new Link("WritingPlanID", "WritingPlans", "WritingPlanID"))
|
||||
];
|
||||
public static string? Validate(ProjectBackupExport backup)
|
||||
public static string? Validate(ProjectBackupExport backup,bool portable=false)
|
||||
{
|
||||
if(backup.Project is null || backup.Project.ProjectID<=0) return "Project backup contains an invalid source project identifier.";
|
||||
var rows=Entities.ToDictionary(entity=>entity.Collection,entity=>((IEnumerable)typeof(ProjectBackupData).GetProperty(entity.Collection)!.GetValue(backup.Data)!).Cast<object>().ToArray());
|
||||
@ -136,7 +136,7 @@ internal static class ProjectBackupGraphValidation
|
||||
if(link.TargetCollection=="ManuscriptDocuments" && backup.FormatVersion is "1.0" or "1.1") continue;
|
||||
var allowed=link.TargetCollection=="Project" ? new HashSet<object?> { backup.Project.ProjectID }
|
||||
: rows[link.TargetCollection].Select(row=>Value(row,link.TargetColumn)).Where(value=>value is not null).ToHashSet();
|
||||
if(rows[entity.Collection].Any(row=>Value(row,link.Column) is object value && !allowed.Contains(value)))
|
||||
if(rows[entity.Collection].Any(row=>Value(row,link.Column) is object value && !allowed.Contains(value)&&!(portable&&entity.Identity!=null&&Value(row,entity.Identity) is int owner&&backup.Recovery.ExternalReferences.Any(r=>r.BindingRequired&&r.Collection==entity.Collection&&r.OwnerID==owner&&r.Field==link.Column&&r.TargetKey.Split('/').Length==3&&r.TargetKey.Split('/')[1]==link.TargetCollection))))
|
||||
return $"Project backup {entity.Collection}.{link.Column} references a missing or foreign {link.TargetCollection} record.";
|
||||
}
|
||||
}
|
||||
|
||||
@ -7,6 +7,7 @@ namespace PlotLine.Services;
|
||||
|
||||
internal static partial class ProjectBackupStoredFieldContract
|
||||
{
|
||||
internal static string[] Columns(string collection)=>StoredColumns.TryGetValue(collection,out var value)?value.Columns.Split(','):[];
|
||||
private sealed record Field(string Name,bool LegacyProjectAudit);
|
||||
private static readonly JsonDocumentOptions ReadOptions=new(){AllowTrailingCommas=true,CommentHandling=JsonCommentHandling.Skip};
|
||||
private static readonly HashSet<string> MixedReferenceCollections=new(StringComparer.OrdinalIgnoreCase)
|
||||
|
||||
@ -13,7 +13,7 @@ public sealed class ProjectRestoreService(
|
||||
IProjectRestorePointRepository restorePointRepository,
|
||||
IProjectRestorePointService restorePointService,
|
||||
ILogger<ProjectRestoreService> logger,
|
||||
IProjectBackupFiles files) : IProjectRestoreService
|
||||
IProjectBackupFiles files,Microsoft.AspNetCore.DataProtection.IDataProtectionProvider? protection=null) : IProjectRestoreService
|
||||
{
|
||||
private static readonly JsonSerializerOptions ReadOptions = new()
|
||||
{
|
||||
@ -79,6 +79,7 @@ public sealed class ProjectRestoreService(
|
||||
{
|
||||
var completeSafety=await restorePointRepository.GetAsync(safetyBackup.ProjectRestorePointID,projectId);
|
||||
if(completeSafety?.JsonData is null)throw new InvalidDataException("The complete safety backup could not be verified.");
|
||||
if(!ProjectBackupCollectionPresence.HasRecovery(restorePoint.JsonData)){var current=JsonSerializer.Deserialize<ProjectBackupExport>(completeSafety.JsonData,ReadOptions)!;if(current.Recovery.NativeReviews.Count>0||current.Recovery.IntentAssessments.Count>0||current.Recovery.ExternalReferences.Count>0) return Failure("Older snapshot omits native or Intent author decisions. Replacement refused; safety backup retained.");}
|
||||
var missing=ProjectBackupCollectionPresence.MissingPersistentCollections(restorePoint.JsonData,completeSafety.JsonData,projectId);
|
||||
if(missing.Count>0)
|
||||
{
|
||||
@ -87,7 +88,7 @@ public sealed class ProjectRestoreService(
|
||||
Message="This older restore point omits existing project information. Restore was aborted to protect it. Your safety backup has been kept."};
|
||||
}
|
||||
using var fileStage=await files.StageAsync(backup!,importingCopy:false);
|
||||
var restoreJson = ProjectBackupCollectionPresence.PreserveOmissions(restorePoint.JsonData,JsonSerializer.Serialize(backup, RestoreSqlOptions));
|
||||
var restoreJson = ProjectBackupCollectionPresence.PreserveOmissions(restorePoint.JsonData,BookRecoveryRepository.Encode(backup!,protection));
|
||||
await restorePointRepository.RestoreAsync(projectId, projectRestorePointId, safetyBackup.ProjectRestorePointID, restoreJson);
|
||||
fileStage.Commit();
|
||||
logger.LogInformation("Project {ProjectID} restored from restore point {ProjectRestorePointID}. Safety backup {SafetyRestorePointID} was created first.",
|
||||
@ -134,7 +135,7 @@ public sealed class ProjectRestoreService(
|
||||
return "Restore point format is not recognised. No project data was changed.";
|
||||
}
|
||||
|
||||
if (backup.FormatVersion is not ("1.0" or "1.1" or "1.2" or "1.3"))
|
||||
if (backup.FormatVersion is not ("1.0" or "1.1" or "1.2" or "1.3" or "1.4"))
|
||||
{
|
||||
return "Restore point format version is not supported. No project data was changed.";
|
||||
}
|
||||
|
||||
@ -19,6 +19,8 @@ public static class RibbonPresentation
|
||||
"exports.writingsession" => "session", _ => "export"
|
||||
};
|
||||
}
|
||||
if (operation == "bookrecovery.backup") return "backup";
|
||||
if (operation == "bookrecovery.restore") return "restore";
|
||||
if (operation == "maps.index") return "maps";
|
||||
if (operation == "floorplans.index") return "floorplans";
|
||||
if (operation == "timeline.settings" || operation is "manageaccount.index" or "manageaccount.subscription") return "settings";
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.AspNetCore.Mvc.Controllers;
|
||||
|
||||
namespace PlotLine.Services;
|
||||
|
||||
@ -14,10 +15,14 @@ public sealed class SubscriptionEnforcementFilter(
|
||||
|
||||
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
|
||||
{
|
||||
// Export, validation and receipt retries remain available in read-only accounts.
|
||||
// Confirm independently reserves active book entitlement before any new domain allocation.
|
||||
var recoverySafe=context.Controller is PlotLine.Controllers.BookRecoveryController&&context.ActionDescriptor is ControllerActionDescriptor {ActionName:"ReviewBackup" or "Download" or "Upload" or "Preview" or "Confirm"};
|
||||
if (HttpMethods.IsGet(context.HttpContext.Request.Method)
|
||||
|| HttpMethods.IsHead(context.HttpContext.Request.Method)
|
||||
|| HttpMethods.IsOptions(context.HttpContext.Request.Method)
|
||||
|| currentUser.UserId is not int userId
|
||||
|| recoverySafe
|
||||
|| ReadOnlySafeControllers.Contains(context.Controller.GetType().Name.Replace("Controller", string.Empty, StringComparison.Ordinal)))
|
||||
{
|
||||
await next();
|
||||
|
||||
228
PlotLine/Sql/236_BookRecovery.sql
Normal file
228
PlotLine/Sql/236_BookRecovery.sql
Normal file
@ -0,0 +1,228 @@
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
IF OBJECT_ID(N'dbo.BookRecoveryExternalReferences',N'U') IS NULL CREATE TABLE dbo.BookRecoveryExternalReferences(ProjectID int PRIMARY KEY,ReferencesJson nvarchar(max) NOT NULL);
|
||||
IF OBJECT_ID(N'dbo.BookRecoveryOrigins',N'U') IS NULL CREATE TABLE dbo.BookRecoveryOrigins(ProjectID int PRIMARY KEY,Origin uniqueidentifier NOT NULL DEFAULT NEWID());
|
||||
IF OBJECT_ID(N'dbo.BookRecoveryOperations',N'U') IS NULL CREATE TABLE dbo.BookRecoveryOperations(OperationID uniqueidentifier PRIMARY KEY,UserID int NOT NULL,ProjectID int NOT NULL,BooksCreated int NOT NULL,RequestHash char(64) NOT NULL,CreatedUtc datetime2 NOT NULL DEFAULT SYSUTCDATETIME());
|
||||
IF OBJECT_ID(N'dbo.BookRecoveryMappings',N'U') IS NULL CREATE TABLE dbo.BookRecoveryMappings(ProjectID int NOT NULL,PortableKey nvarchar(240) NOT NULL,Collection nvarchar(128) NOT NULL,DestinationID int NOT NULL,SourceHash char(64) NOT NULL,DestinationHash char(64) NOT NULL,CONSTRAINT PK_BookRecoveryMappings PRIMARY KEY(ProjectID,PortableKey,SourceHash));
|
||||
GO
|
||||
IF NOT EXISTS(SELECT 1 FROM sys.foreign_keys WHERE name=N'FK_BookRecoveryOrigins_Project') ALTER TABLE dbo.BookRecoveryOrigins ADD CONSTRAINT FK_BookRecoveryOrigins_Project FOREIGN KEY(ProjectID) REFERENCES dbo.Projects(ProjectID) ON DELETE CASCADE;
|
||||
IF NOT EXISTS(SELECT 1 FROM sys.foreign_keys WHERE name=N'FK_BookRecoveryMappings_Project') ALTER TABLE dbo.BookRecoveryMappings ADD CONSTRAINT FK_BookRecoveryMappings_Project FOREIGN KEY(ProjectID) REFERENCES dbo.Projects(ProjectID) ON DELETE CASCADE;
|
||||
IF NOT EXISTS(SELECT 1 FROM sys.foreign_keys WHERE name=N'FK_BookRecoveryReferences_Project') ALTER TABLE dbo.BookRecoveryExternalReferences ADD CONSTRAINT FK_BookRecoveryReferences_Project FOREIGN KEY(ProjectID) REFERENCES dbo.Projects(ProjectID) ON DELETE CASCADE;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.BookRecovery @Action varchar(16),@UserID int,@ProjectID int=0,@OperationID uniqueidentifier=NULL,@BooksCreated int=0,@RequestHash char(64)=NULL,@MappingsJson nvarchar(max)=NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;SET XACT_ABORT ON;
|
||||
IF @Action='Begin' BEGIN
|
||||
IF @@TRANCOUNT=0 THROW 51000,'Recovery requires an enclosing transaction',1;
|
||||
DECLARE @Lock int,@Resource nvarchar(255)=CONCAT('BookRecovery:',@UserID);
|
||||
EXEC @Lock=sys.sp_getapplock @Resource=@Resource,@LockMode='Exclusive',@LockOwner='Transaction',@LockTimeout=10000;
|
||||
IF @Lock<0 THROW 51000,'Another restore is running. Retry shortly.',1;RETURN;
|
||||
END;
|
||||
IF @Action='Receipt' BEGIN SELECT ProjectID,BooksCreated,RequestHash FROM dbo.BookRecoveryOperations WHERE UserID=@UserID AND OperationID=@OperationID;RETURN;END;
|
||||
IF @Action='Projects' BEGIN SELECT p.* FROM dbo.Projects p JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID WHERE a.UserID=@UserID AND a.AccessRole='Owner' AND a.IsActive=1 ORDER BY p.ProjectName;RETURN;END;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND AccessRole='Owner' AND IsActive=1) THROW 51000,'Project owner authority required',1;
|
||||
IF @Action='Origin' BEGIN
|
||||
BEGIN TRANSACTION;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.BookRecoveryOrigins WITH(UPDLOCK,HOLDLOCK) WHERE ProjectID=@ProjectID) INSERT dbo.BookRecoveryOrigins(ProjectID) VALUES(@ProjectID);
|
||||
SELECT Origin FROM dbo.BookRecoveryOrigins WHERE ProjectID=@ProjectID;COMMIT;RETURN;
|
||||
END;
|
||||
IF @Action='Mappings' BEGIN SELECT PortableKey,Collection,DestinationID,SourceHash,DestinationHash FROM dbo.BookRecoveryMappings WHERE ProjectID=@ProjectID;RETURN;END;
|
||||
IF @Action='Forks' BEGIN
|
||||
BEGIN TRANSACTION;
|
||||
INSERT dbo.BookRecoveryMappings(ProjectID,PortableKey,Collection,DestinationID,SourceHash,DestinationHash)
|
||||
SELECT @ProjectID,j.PortableKey,j.Collection,j.DestinationID,j.SourceHash,j.DestinationHash FROM OPENJSON(@MappingsJson) WITH(PortableKey nvarchar(240),Collection nvarchar(128),DestinationID int,SourceHash char(64),DestinationHash char(64)) j
|
||||
WHERE NOT EXISTS(SELECT 1 FROM dbo.BookRecoveryMappings WITH(UPDLOCK,HOLDLOCK) WHERE ProjectID=@ProjectID AND PortableKey=j.PortableKey AND SourceHash=j.SourceHash);
|
||||
COMMIT;RETURN;
|
||||
END;
|
||||
IF @Action='Complete' BEGIN
|
||||
IF @@TRANCOUNT=0 THROW 51000,'Recovery requires an enclosing transaction',1;
|
||||
INSERT dbo.BookRecoveryOperations(OperationID,UserID,ProjectID,BooksCreated,RequestHash) VALUES(@OperationID,@UserID,@ProjectID,@BooksCreated,@RequestHash);
|
||||
DELETE m FROM dbo.BookRecoveryMappings m JOIN OPENJSON(@MappingsJson) WITH(PortableKey nvarchar(240),SourceHash char(64)) j ON j.PortableKey=m.PortableKey AND j.SourceHash=m.SourceHash WHERE m.ProjectID=@ProjectID;
|
||||
INSERT dbo.BookRecoveryMappings(ProjectID,PortableKey,Collection,DestinationID,SourceHash,DestinationHash)
|
||||
SELECT @ProjectID,j.PortableKey,j.Collection,j.DestinationID,j.SourceHash,j.DestinationHash FROM OPENJSON(@MappingsJson) WITH(PortableKey nvarchar(240),Collection nvarchar(128),DestinationID int,SourceHash char(64),DestinationHash char(64)) j
|
||||
WHERE NOT EXISTS(SELECT 1 FROM dbo.BookRecoveryMappings m WHERE m.ProjectID=@ProjectID AND m.PortableKey=j.PortableKey AND m.SourceHash=j.SourceHash);RETURN;
|
||||
END;
|
||||
THROW 51000,'Invalid recovery action',1;
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.ProjectRecovery_State @ProjectID int
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
SELECT r.* FROM dbo.NativeChapterReviews r JOIN dbo.Books b ON b.BookID=r.BookID WHERE b.ProjectID=@ProjectID;
|
||||
SELECT r.* FROM dbo.WritingIntentAssessments r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID;
|
||||
SELECT ReferencesJson FROM dbo.BookRecoveryExternalReferences WHERE ProjectID=@ProjectID;
|
||||
END;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.ProjectRecovery_Apply @ProjectID int,@StateJson nvarchar(max),@PriorBooks nvarchar(max)=NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;SET XACT_ABORT ON;
|
||||
IF @@TRANCOUNT=0 OR ISJSON(@StateJson)<>1 THROW 51000,'Recovery state requires a transaction',1;
|
||||
DECLARE @Append bit=CASE WHEN JSON_VALUE(@StateJson,'$.AppendOnly')='true' THEN 1 ELSE 0 END;
|
||||
DECLARE @NewBooks table(ID int PRIMARY KEY);IF @Append=1 INSERT @NewBooks SELECT CONVERT(int,value) FROM OPENJSON(@StateJson,'$.AppendBooks');
|
||||
IF EXISTS(SELECT 1 FROM OPENJSON(@StateJson,'$.NativeReviews') WITH(BookID int) r WHERE NOT EXISTS(SELECT 1 FROM dbo.Books WHERE BookID=r.BookID AND ProjectID=@ProjectID)) THROW 51000,'Review belongs to another project',1;
|
||||
IF EXISTS(SELECT 1 FROM OPENJSON(@StateJson,'$.IntentAssessments') WITH(SceneID int) r WHERE NOT EXISTS(SELECT 1 FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE s.SceneID=r.SceneID AND b.ProjectID=@ProjectID)) THROW 51000,'Intent belongs to another project',1;
|
||||
DELETE r FROM dbo.NativeChapterReviews r JOIN dbo.Books b ON b.BookID=r.BookID WHERE b.ProjectID=@ProjectID AND (@Append=0 OR b.BookID IN(SELECT ID FROM @NewBooks));
|
||||
DELETE r FROM dbo.WritingIntentAssessments r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID AND (@Append=0 OR b.BookID IN(SELECT ID FROM @NewBooks));
|
||||
INSERT dbo.NativeChapterReviews(ReviewID,UserID,BookID,ManuscriptID,ChapterStart,ChapterEnd,ContentHash,ResultJson,DecisionsJson,Version,CreatedUtc,EncryptedSource)
|
||||
SELECT ReviewID,UserID,BookID,ManuscriptID,ChapterStart,ChapterEnd,ContentHash,ResultJson,DecisionsJson,Version,CreatedUtc,EncryptedSource FROM OPENJSON(@StateJson,'$.NativeReviews') WITH(ReviewID uniqueidentifier,UserID int,BookID int,ManuscriptID uniqueidentifier,ChapterStart int,ChapterEnd int,ContentHash varchar(64),ResultJson nvarchar(max),DecisionsJson nvarchar(max),Version int,CreatedUtc datetime2,EncryptedSource nvarchar(max)) WHERE @Append=0 OR BookID IN(SELECT ID FROM @NewBooks);
|
||||
INSERT dbo.WritingIntentAssessments(UserID,SceneID,InputHash,ResultsJson,DecisionsJson,Model,CreatedUtc)
|
||||
SELECT UserID,SceneID,InputHash,ResultsJson,DecisionsJson,Model,CreatedUtc FROM OPENJSON(@StateJson,'$.IntentAssessments') WITH(UserID int,SceneID int,InputHash char(64),ResultsJson nvarchar(max),DecisionsJson nvarchar(max),Model nvarchar(200),CreatedUtc datetime2) r WHERE @Append=0 OR EXISTS(SELECT 1 FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE s.SceneID=r.SceneID AND c.BookID IN(SELECT ID FROM @NewBooks));
|
||||
DELETE FROM dbo.BookRecoveryExternalReferences WHERE ProjectID=@ProjectID;
|
||||
INSERT dbo.BookRecoveryExternalReferences(ProjectID,ReferencesJson) VALUES(@ProjectID,COALESCE(JSON_QUERY(@StateJson,'$.ExternalReferences'),N'[]'));
|
||||
DECLARE @Affected table(BookID int PRIMARY KEY);INSERT @Affected SELECT BookID FROM dbo.Books WHERE ProjectID=@ProjectID UNION SELECT BookID FROM OPENJSON(@PriorBooks) WITH(BookID int);
|
||||
-- Never preserve receipts that claim removed canonical chapters/builds still exist.
|
||||
DELETE r FROM dbo.NativeReviewImports r WHERE r.BookID IN(SELECT BookID FROM @Affected) AND (NOT EXISTS(SELECT 1 FROM dbo.Chapters c JOIN dbo.Books b ON b.BookID=c.BookID WHERE c.ChapterID=r.ChapterID AND b.BookID=r.BookID) OR NOT EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds WHERE OnboardingManuscriptBuildID=r.BuildID));
|
||||
DELETE r FROM dbo.NativeImportOperations r WHERE r.BookID IN(SELECT BookID FROM @Affected) AND (r.ChaptersCreated<>(SELECT COUNT(*) FROM dbo.NativeReviewImports i JOIN dbo.Chapters c ON c.ChapterID=i.ChapterID AND c.BookID=i.BookID WHERE i.BuildID=r.BuildID AND i.BookID=r.BookID) OR r.ScenesCreated<>(SELECT COUNT(*) FROM dbo.OnboardingManuscriptBuildSceneMap m JOIN dbo.Scenes s ON s.SceneID=m.SceneID WHERE m.OnboardingManuscriptBuildID=r.BuildID));
|
||||
END;
|
||||
GO
|
||||
-- Preserve the audited SQL engine. A wrapper adds state handling and an outer rollback boundary.
|
||||
IF OBJECT_ID(N'dbo.ProjectRestore_ApplyGraph236',N'P') IS NULL EXEC sys.sp_rename N'dbo.ProjectRestore_ApplyFromJson',N'ProjectRestore_ApplyGraph236';
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.ProjectRestore_ApplyFromJson @ProjectID int,@SourceRestorePointID int=NULL,@SafetyRestorePointID int=NULL,@JsonData nvarchar(max)
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;SET XACT_ABORT ON;
|
||||
DECLARE @State nvarchar(max)=JSON_QUERY(@JsonData,'$.Recovery');
|
||||
IF @State IS NULL AND (EXISTS(SELECT 1 FROM dbo.NativeChapterReviews r JOIN dbo.Books b ON b.BookID=r.BookID WHERE b.ProjectID=@ProjectID) OR EXISTS(SELECT 1 FROM dbo.BookRecoveryExternalReferences WHERE ProjectID=@ProjectID AND ReferencesJson<>N'[]') OR EXISTS(SELECT 1 FROM dbo.WritingIntentAssessments r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID)) THROW 51000,'Older snapshot omits native or Intent author decisions. Replacement refused.',1;
|
||||
IF JSON_VALUE(@JsonData,'$.FormatVersion')='1.4' SET @JsonData=JSON_MODIFY(@JsonData,'$.FormatVersion','1.3');
|
||||
BEGIN TRANSACTION;
|
||||
BEGIN TRY
|
||||
DECLARE @PriorBooks nvarchar(max)=(SELECT BookID FROM dbo.Books WITH(UPDLOCK,HOLDLOCK) WHERE ProjectID=@ProjectID FOR JSON PATH);
|
||||
DECLARE @AppendOnly bit=CASE WHEN JSON_VALUE(@State,'$.AppendOnly')='true' THEN 1 ELSE 0 END;
|
||||
IF @AppendOnly=1 AND (@SourceRestorePointID IS NOT NULL OR NOT EXISTS(SELECT 1 FROM OPENJSON(@State,'$.AppendBooks')) OR EXISTS(SELECT 1 FROM OPENJSON(@PriorBooks) WITH(BookID int) p WHERE NOT EXISTS(SELECT 1 FROM OPENJSON(@JsonData,'$.Data.Books') WITH(BookID int) b WHERE b.BookID=p.BookID)) OR EXISTS(SELECT 1 FROM OPENJSON(@State,'$.AppendBooks') n WHERE EXISTS(SELECT 1 FROM OPENJSON(@PriorBooks) WITH(BookID int) p WHERE p.BookID=TRY_CONVERT(int,n.value)))) THROW 51000,'Append mode must preserve existing books and identify only new books',1;
|
||||
DECLARE @ReservationID uniqueidentifier=NULL;
|
||||
IF @SourceRestorePointID IS NOT NULL BEGIN
|
||||
DECLARE @Delta int=(SELECT COUNT(*) FROM OPENJSON(@JsonData,'$.Data.Books'))-(SELECT COUNT(*) FROM dbo.Books WHERE ProjectID=@ProjectID);
|
||||
IF @Delta>0 BEGIN
|
||||
DECLARE @Owner int=(SELECT TOP(1) UserID FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND AccessRole='Owner' AND IsActive=1),@Now datetime2=SYSUTCDATETIME();
|
||||
DECLARE @Capacity table(Allowed bit,ReservationID uniqueidentifier,CurrentUsage int,MaximumAllowed int,Message nvarchar(max));
|
||||
INSERT @Capacity EXEC dbo.SubscriptionEntitlement_TryReserveBookSlots @Owner,@Delta,@Now;
|
||||
IF EXISTS(SELECT 1 FROM @Capacity WHERE Allowed=0) THROW 51000,'Not enough book capacity to rewind this project',1;
|
||||
SELECT @ReservationID=ReservationID FROM @Capacity;
|
||||
END;
|
||||
END;
|
||||
IF @State IS NOT NULL AND ISNULL(JSON_VALUE(@State,'$.Protected'),'false')<>'true' THROW 51000,'Recovery state must be validated and protected by the application',1;
|
||||
IF @State IS NOT NULL AND @AppendOnly=0 BEGIN
|
||||
DELETE r FROM dbo.NativeChapterReviews r JOIN dbo.Books b ON b.BookID=r.BookID WHERE b.ProjectID=@ProjectID;
|
||||
DELETE r FROM dbo.WritingIntentAssessments r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID;
|
||||
END;
|
||||
IF @AppendOnly=0 BEGIN
|
||||
-- Receipts are operational authority, not snapshot author data. Even matching IDs cannot prove old imports.
|
||||
DELETE FROM dbo.NativeReviewImports WHERE BookID IN(SELECT BookID FROM OPENJSON(@PriorBooks) WITH(BookID int));
|
||||
DELETE FROM dbo.NativeImportOperations WHERE BookID IN(SELECT BookID FROM OPENJSON(@PriorBooks) WITH(BookID int));
|
||||
END;
|
||||
EXEC dbo.ProjectRestore_ApplyGraph236 @ProjectID,@SourceRestorePointID,@SafetyRestorePointID,@JsonData;
|
||||
-- Protected state is supplied by the application after validating/decrypting the portable representation.
|
||||
IF @State IS NOT NULL AND JSON_VALUE(@State,'$.Protected')='true' EXEC dbo.ProjectRecovery_Apply @ProjectID,@State,@PriorBooks;
|
||||
ELSE BEGIN
|
||||
DELETE r FROM dbo.NativeReviewImports r WHERE r.BookID IN(SELECT BookID FROM OPENJSON(@PriorBooks) WITH(BookID int)) AND NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE ChapterID=r.ChapterID AND BookID=r.BookID);
|
||||
DELETE r FROM dbo.NativeImportOperations r WHERE r.BookID IN(SELECT BookID FROM OPENJSON(@PriorBooks) WITH(BookID int)) AND NOT EXISTS(SELECT 1 FROM dbo.NativeReviewImports WHERE BuildID=r.BuildID AND BookID=r.BookID);
|
||||
END;
|
||||
IF @ReservationID IS NOT NULL EXEC dbo.SubscriptionEntitlement_ReleaseBookSlots @ReservationID;
|
||||
COMMIT;
|
||||
END TRY BEGIN CATCH IF @@TRANCOUNT>0 ROLLBACK;THROW;END CATCH;
|
||||
END;
|
||||
GO
|
||||
-- Capacity counts owned books irrespective of either archive flag.
|
||||
CREATE OR ALTER PROCEDURE dbo.SubscriptionUsage_BookCountForOwner @UserID int
|
||||
AS BEGIN SET NOCOUNT ON;SELECT COUNT(DISTINCT b.BookID) FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID WHERE a.UserID=@UserID AND a.AccessRole='Owner' AND a.IsActive=1;END;
|
||||
GO
|
||||
DECLARE @Definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.SubscriptionEntitlement_TryReserveBookSlots'));
|
||||
IF @Definition IS NULL THROW 51000,'Book reservation procedure missing',1;
|
||||
SET @Definition=N'ALTER '+SUBSTRING(@Definition,CHARINDEX(N'PROCEDURE',UPPER(@Definition)),LEN(@Definition));
|
||||
SET @Definition=REPLACE(@Definition,'AND p.IsArchived = 0 AND b.IsArchived = 0','');
|
||||
EXEC sys.sp_executesql @Definition;
|
||||
GO
|
||||
DECLARE @Definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.SubscriptionUsage_GetSummaryForOwner'));
|
||||
IF @Definition IS NULL THROW 51000,'Usage summary missing',1;
|
||||
SET @Definition=N'ALTER '+SUBSTRING(@Definition,CHARINDEX(N'PROCEDURE',UPPER(@Definition)),LEN(@Definition));
|
||||
SET @Definition=REPLACE(@Definition,'WHERE b.IsArchived = 0','WHERE 1=1');
|
||||
EXEC sys.sp_executesql @Definition;
|
||||
GO
|
||||
-- Book deletion predates the newer manuscript/AI/review tables. Keep its owner/typed-confirmation
|
||||
-- contract and canonical cleanup, adding narrowly book-scoped descendants in the same transaction.
|
||||
IF OBJECT_ID(N'dbo.BookHardDelete_Core236',N'P') IS NULL EXEC sys.sp_rename N'dbo.BookHardDelete_ForOwner',N'BookHardDelete_Core236';
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.BookHardDelete_ForOwner @BookID int,@UserID int
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;SET XACT_ABORT ON;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID WHERE b.BookID=@BookID AND b.IsArchived=1 AND a.UserID=@UserID AND a.AccessRole=N'Owner' AND a.IsActive=1) THROW 52201,'An archived book owned by this author is required.',1;
|
||||
BEGIN TRANSACTION;
|
||||
BEGIN TRY
|
||||
DECLARE @Scenes table(ID int PRIMARY KEY);INSERT @Scenes SELECT s.SceneID FROM dbo.Scenes s JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID WHERE c.BookID=@BookID;
|
||||
DECLARE @Pipelines table(ID int PRIMARY KEY);INSERT @Pipelines SELECT StoryIntelligenceBookPipelineID FROM dbo.StoryIntelligenceBookPipelines WHERE BookID=@BookID;
|
||||
IF EXISTS(SELECT 1 FROM dbo.StoryIntelligenceJobs WHERE BookID=@BookID AND Status IN(N'Queued',N'Running',N'Processing')) THROW 52203,'Wait for active analysis to finish before deleting this book.',1;
|
||||
-- Book-specific presets belong to the deleted book. Preserve other views while clearing obsolete selectors.
|
||||
DELETE FROM dbo.TimelineViewPresets WHERE BookID=@BookID;
|
||||
DECLARE @PresetFields table(PresetID int,FieldName nvarchar(128));
|
||||
INSERT @PresetFields
|
||||
SELECT p.TimelineViewPresetID,f.[key] FROM dbo.TimelineViewPresets p CROSS APPLY OPENJSON(CASE WHEN ISJSON(p.FilterJson)=1 THEN p.FilterJson ELSE N'{}' END) f
|
||||
WHERE p.ProjectID=(SELECT ProjectID FROM dbo.Books WHERE BookID=@BookID) AND
|
||||
((f.[key]=N'BookID' AND TRY_CONVERT(int,f.value)=@BookID)
|
||||
OR (f.[key] IN(N'ChapterFromID',N'ChapterToID') AND TRY_CONVERT(int,f.value) IN(SELECT ChapterID FROM dbo.Chapters WHERE BookID=@BookID))
|
||||
OR (f.[key] IN(N'SelectedSceneID',N'SceneFromID',N'SceneToID') AND TRY_CONVERT(int,f.value) IN(SELECT ID FROM @Scenes))
|
||||
OR (f.[key]=N'FocusID' AND TRY_CONVERT(int,f.value) IN(SELECT ID FROM @Scenes) AND EXISTS(SELECT 1 FROM OPENJSON(p.FilterJson) t WHERE t.[key]=N'FocusType' AND t.value=N'scene')));
|
||||
DECLARE @PresetID int,@Field nvarchar(128);WHILE EXISTS(SELECT 1 FROM @PresetFields) BEGIN
|
||||
SELECT TOP(1) @PresetID=PresetID,@Field=FieldName FROM @PresetFields;
|
||||
UPDATE dbo.TimelineViewPresets SET FilterJson=JSON_MODIFY(FilterJson,N'$.'+@Field,NULL) WHERE TimelineViewPresetID=@PresetID;
|
||||
DELETE FROM @PresetFields WHERE PresetID=@PresetID AND FieldName=@Field;
|
||||
END;
|
||||
UPDATE dbo.TimelineViewPresets SET FocusID=NULL,FocusType=NULL WHERE ProjectID=(SELECT ProjectID FROM dbo.Books WHERE BookID=@BookID) AND FocusType=N'scene' AND FocusID IN(SELECT ID FROM @Scenes);
|
||||
DELETE FROM dbo.NativeReviewImports WHERE BookID=@BookID;
|
||||
DELETE FROM dbo.NativeImportOperations WHERE BookID=@BookID;
|
||||
DELETE FROM dbo.NativeChapterReviews WHERE BookID=@BookID;
|
||||
DELETE FROM dbo.WritingIntentAssessments WHERE SceneID IN(SELECT ID FROM @Scenes);
|
||||
DELETE FROM dbo.CharacterEnrichmentEvidence WHERE SceneID IN(SELECT ID FROM @Scenes);
|
||||
DELETE FROM dbo.CharacterEnrichmentRuns WHERE BookID=@BookID OR StoryIntelligenceBookPipelineID IN(SELECT ID FROM @Pipelines);
|
||||
DELETE FROM dbo.CharacterIntelligenceEvidenceEvents WHERE CharacterIntelligenceProfileID IN(SELECT CharacterIntelligenceProfileID FROM dbo.CharacterIntelligenceProfiles WHERE BookID=@BookID OR ImportSessionID IN(SELECT ID FROM @Pipelines));
|
||||
DELETE FROM dbo.CharacterIntelligenceProfiles WHERE BookID=@BookID OR ImportSessionID IN(SELECT ID FROM @Pipelines);
|
||||
DELETE FROM dbo.StoryMemoryIllustrationAssignments WHERE ImportSessionID IN(SELECT ID FROM @Pipelines);
|
||||
DELETE FROM dbo.StoryMemoryIllustrationDemands WHERE ImportSessionID IN(SELECT ID FROM @Pipelines);
|
||||
DELETE FROM dbo.StoryMemoryRelationships WHERE ImportSessionID IN(SELECT ID FROM @Pipelines);
|
||||
DELETE FROM dbo.StoryMemoryCharacterAliases WHERE StoryMemoryCharacterID IN(SELECT StoryMemoryCharacterID FROM dbo.StoryMemoryCharacters WHERE ImportSessionID IN(SELECT ID FROM @Pipelines));
|
||||
DELETE FROM dbo.StoryMemoryCharacterAttributes WHERE StoryMemoryCharacterID IN(SELECT StoryMemoryCharacterID FROM dbo.StoryMemoryCharacters WHERE ImportSessionID IN(SELECT ID FROM @Pipelines));
|
||||
DELETE FROM dbo.StoryMemoryCharacters WHERE ImportSessionID IN(SELECT ID FROM @Pipelines);
|
||||
DELETE FROM dbo.StoryMemoryLocations WHERE ImportSessionID IN(SELECT ID FROM @Pipelines);
|
||||
DELETE FROM dbo.StoryMemoryAssets WHERE ImportSessionID IN(SELECT ID FROM @Pipelines);
|
||||
DELETE FROM dbo.StoryMemoryProcessedSceneResults WHERE ImportSessionID IN(SELECT ID FROM @Pipelines);
|
||||
DELETE FROM dbo.StoryMemoryImportPreferences WHERE ImportSessionID IN(SELECT ID FROM @Pipelines);
|
||||
DELETE FROM dbo.StoryIntelligenceNarrativeCandidateEvents WHERE SceneID IN(SELECT ID FROM @Scenes) OR WholeBookPlotSynthesisRunID IN(SELECT WholeBookPlotSynthesisRunID FROM dbo.WholeBookPlotSynthesisRuns WHERE BookID=@BookID);
|
||||
DELETE FROM dbo.CoreImportBasicLocationReviews WHERE BookID=@BookID;
|
||||
DELETE FROM dbo.SceneManuscriptSources WHERE BookID=@BookID;
|
||||
DELETE FROM dbo.ManuscriptStructuralChapterSources WHERE BookID=@BookID;
|
||||
DELETE FROM dbo.MapJourneyNotes WHERE FromSceneID IN(SELECT ID FROM @Scenes) OR ToSceneID IN(SELECT ID FROM @Scenes);
|
||||
DELETE FROM dbo.OnboardingManuscriptBuildCharacterMap WHERE OnboardingManuscriptBuildID IN(SELECT OnboardingManuscriptBuildID FROM dbo.OnboardingManuscriptBuilds WHERE BookID=@BookID);
|
||||
EXEC dbo.BookHardDelete_Core236 @BookID,@UserID;
|
||||
COMMIT;
|
||||
END TRY BEGIN CATCH IF @@TRANCOUNT>0 ROLLBACK;THROW;END CATCH;
|
||||
END;
|
||||
GO
|
||||
-- Refresh the existing caller after renaming its old dependency.
|
||||
EXEC sys.sp_recompile N'dbo.Archive_DeleteForever';
|
||||
GO
|
||||
-- Project/account deletion must not orphan the newer portable author state.
|
||||
IF OBJECT_ID(N'dbo.ProjectHardDelete_PrepareCore236',N'P') IS NULL EXEC sys.sp_rename N'dbo.ProjectHardDelete_PrepareDependencies',N'ProjectHardDelete_PrepareCore236';
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.ProjectHardDelete_PrepareDependencies @ProjectID int,@UserID int,@AllowActiveProject bit=0
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;SET XACT_ABORT ON;BEGIN TRANSACTION;
|
||||
BEGIN TRY
|
||||
EXEC dbo.ProjectHardDelete_PrepareCore236 @ProjectID,@UserID,@AllowActiveProject;
|
||||
DELETE r FROM dbo.NativeReviewImports r JOIN dbo.Books b ON b.BookID=r.BookID WHERE b.ProjectID=@ProjectID;
|
||||
DELETE r FROM dbo.NativeImportOperations r JOIN dbo.Books b ON b.BookID=r.BookID WHERE b.ProjectID=@ProjectID;
|
||||
DELETE r FROM dbo.NativeChapterReviews r JOIN dbo.Books b ON b.BookID=r.BookID WHERE b.ProjectID=@ProjectID;
|
||||
DELETE r FROM dbo.WritingIntentAssessments r JOIN dbo.Scenes s ON s.SceneID=r.SceneID JOIN dbo.Chapters c ON c.ChapterID=s.ChapterID JOIN dbo.Books b ON b.BookID=c.BookID WHERE b.ProjectID=@ProjectID;
|
||||
COMMIT;
|
||||
END TRY BEGIN CATCH IF @@TRANCOUNT>0 ROLLBACK;THROW;END CATCH;
|
||||
END;
|
||||
GO
|
||||
EXEC sys.sp_recompile N'dbo.ProjectHardDelete_ForOwner';
|
||||
GO
|
||||
IF NOT EXISTS(SELECT 1 FROM sys.foreign_keys WHERE name=N'FK_BookRecoveryOperations_User') ALTER TABLE dbo.BookRecoveryOperations ADD CONSTRAINT FK_BookRecoveryOperations_User FOREIGN KEY(UserID) REFERENCES dbo.AppUser(UserID) ON DELETE CASCADE;
|
||||
GO
|
||||
14
PlotLine/ViewModels/BookRecoveryViewModels.cs
Normal file
14
PlotLine/ViewModels/BookRecoveryViewModels.cs
Normal file
@ -0,0 +1,14 @@
|
||||
using PlotLine.Models;
|
||||
using PlotLine.Services;
|
||||
namespace PlotLine.ViewModels;
|
||||
|
||||
public sealed class BookRecoveryPage
|
||||
{
|
||||
public Project[] Projects { get; set; } = []; public int ProjectID { get; set; }
|
||||
public int? BookID { get; set; }
|
||||
public ProjectBackupExport? Source { get; set; }
|
||||
public Guid Upload { get; set; } public string UploadName {get;set;}="";
|
||||
public BookBackupPackage? Package { get; set; }
|
||||
public BookRecoveryPreview? Preview { get; set; }
|
||||
public string Error { get; set; } = "";public string RetryConfirmation {get;set;}="";
|
||||
}
|
||||
@ -29,7 +29,7 @@
|
||||
<div>
|
||||
<p class="eyebrow">Archive</p>
|
||||
<h1>Archived Items <help-icon key="archive.overview" /></h1>
|
||||
<p class="lead-text">Restore projects, scenes, characters, assets, locations, threads, scenarios, and other archived planning items.</p>
|
||||
<p class="lead-text">Unarchive projects, books, scenes, characters, assets, locations, threads, scenarios, and other archived planning items.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -57,7 +57,7 @@
|
||||
<section class="story-bible-section">
|
||||
<div class="story-bible-section-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Restore</p>
|
||||
<p class="eyebrow">Unarchive</p>
|
||||
<h2>Archived Records <help-icon key="archive.archivedRecords" /></h2>
|
||||
</div>
|
||||
<span class="soft-count">@Model.Items.Count item@(Model.Items.Count == 1 ? "" : "s")</span>
|
||||
@ -92,11 +92,11 @@
|
||||
}
|
||||
</div>
|
||||
<div class="archive-actions">
|
||||
<form asp-action="Restore" method="post" data-confirm-message="Restore this @item.EntityType.ToLowerInvariant()? This will return it to active lists and timelines where applicable.">
|
||||
<form asp-action="Restore" method="post" data-confirm-message="Unarchive this @item.EntityType.ToLowerInvariant()? This will return it to active lists and timelines where applicable. Archiving and unarchiving do not change book capacity.">
|
||||
<input type="hidden" name="entityType" value="@item.EntityType" />
|
||||
<input type="hidden" name="entityId" value="@item.EntityID" />
|
||||
<input type="hidden" name="projectId" value="@Model.ProjectID" />
|
||||
<button class="btn btn-outline-primary btn-sm restore-button" type="submit">Restore</button>
|
||||
<button class="btn btn-outline-primary btn-sm restore-button" type="submit">Unarchive</button>
|
||||
</form>
|
||||
<form asp-action="DeleteForever" method="post" class="delete-forever-form" data-confirm-message="Permanently delete this @item.EntityType.ToLowerInvariant()? This cannot be undone. Any linked planning data may also be removed or become unavailable. Only continue if you are certain." data-require-delete-text="true">
|
||||
<input type="hidden" name="entityType" value="@item.EntityType" />
|
||||
|
||||
11
PlotLine/Views/BookRecovery/Backup.cshtml
Normal file
11
PlotLine/Views/BookRecovery/Backup.cshtml
Normal file
@ -0,0 +1,11 @@
|
||||
@model BookRecoveryPage
|
||||
@{ViewData["Title"]="Back up books";}
|
||||
<div class="page-heading" data-pwa-header><div><p class="eyebrow">Your writing, safely portable</p><h1>Back up books <help-icon key="bookRecovery.overview" /></h1><p>Choose one, several or every book. Necessary shared project information travels with them.</p></div><a class="btn btn-outline-secondary" asp-controller="Projects" asp-action="Index">Projects</a></div>
|
||||
@if(Model.Error!=""){<div class="alert alert-warning" role="alert">@Model.Error</div>}
|
||||
@if(Model.Projects.Length==0){<p class="alert alert-info">There are no projects you own to back up yet. Create or restore a book first.</p>}
|
||||
<section class="edit-panel"><form method="get"><label for="projectId" class="form-label">Project</label><div class="input-group"><select name="projectId" id="projectId" class="form-select">@foreach(var p in Model.Projects){<option value="@p.ProjectID" selected="@(p.ProjectID==Model.ProjectID)">@p.ProjectName @(p.IsArchived?"· Archived project":"")</option>}</select><button class="btn btn-outline-primary">Choose project</button></div></form></section>
|
||||
@if(Model.Source is not null){<section class="edit-panel mt-3"><form asp-action="ReviewBackup" method="post"><input type="hidden" name="projectId" value="@Model.ProjectID"/><h2>Choose books</h2>@if(Model.Source.Data.Books.Count==0){<p class="alert alert-info">This project has no books to back up.</p>}<p>Archived books are included when selected. Archive status does not release subscription capacity.</p><div class="button-row"><button type="button" class="btn btn-outline-secondary btn-sm" data-books-all>Select all</button><button type="button" class="btn btn-outline-secondary btn-sm" data-books-none>Clear selection</button></div>
|
||||
@foreach(var b in Model.Source.Data.Books.OrderBy(b=>b.SortOrder)){<div class="form-check my-3"><input class="form-check-input" type="checkbox" name="books" value="@b.BookID" id="book-@b.BookID" checked="@(!Model.BookID.HasValue||Model.BookID==b.BookID)"/><label class="form-check-label" for="book-@b.BookID"><strong>@b.BookDisplayTitle</strong> @(b.IsArchived?"· Archived":"")</label></div>}
|
||||
<details class="my-3"><summary>What is included?</summary><p>Selected chapters, scenes, saved prose, planning and author review decisions; common characters, locations, relationships, maps, floor plans, plot lines, assets and required files. A selection with an unresolved cross-book dependency is refused rather than losing it.</p></details>
|
||||
<p class="alert alert-info">Keep backup files private: they may contain manuscript prose, research and personal information. Downloading does not delete books, release capacity or prove your file is safely stored. Verify your local copy before separately choosing Delete Forever.</p><button class="btn btn-primary" disabled="@(Model.Source.Data.Books.Count==0)">Review selected backup</button> <a asp-action="Restore" class="btn btn-outline-secondary">Restore books</a></form></section>}
|
||||
@section Scripts{<script src="~/js/book-recovery.js" asp-append-version="true"></script>}
|
||||
3
PlotLine/Views/BookRecovery/BackupPreview.cshtml
Normal file
3
PlotLine/Views/BookRecovery/BackupPreview.cshtml
Normal file
@ -0,0 +1,3 @@
|
||||
@model BookRecoveryPage
|
||||
@{ViewData["Title"]="Review book backup";var package=Model.Package!;}
|
||||
<div class="page-heading" data-pwa-header><h1>Review your backup</h1></div><section class="edit-panel"><h2>@package.Snapshot.Project?.ProjectName</h2><ul>@foreach(var book in package.Snapshot.Data.Books){<li>@book.BookDisplayTitle @(book.IsArchived?"· Archived":"")</li>}</ul><p>@package.Snapshot.Data.Chapters.Count chapters · @package.Snapshot.Data.Scenes.Count scenes · @package.Snapshot.Files.Count uploaded files</p><p>Includes saved manuscript sources, planning, review decisions and common project data. Your backup is a snapshot taken @package.CreatedUtc.ToString("d MMM yyyy HH:mm") UTC.</p>@foreach(var warning in package.Warnings){<p>@warning</p>}@if(package.Snapshot.Recovery.ExternalReferences.Count>0){<p class="alert alert-warning">@package.Snapshot.Recovery.ExternalReferences.Count common-data references point to books outside this selection. Their source identities are preserved as disconnected history; they will never be attached to unrelated destination records.</p>}<form asp-action="Download" method="post"><input type="hidden" name="staged" value="@Model.Upload"/><button class="btn btn-primary">Download backup</button> <a asp-action="Backup" asp-route-projectId="@Model.ProjectID" class="btn btn-outline-secondary">Change selection</a></form><p class="mt-3">This does not delete books or free slots. Check your local file before separately choosing Delete Forever. Archived books still count towards capacity.</p></section>
|
||||
3
PlotLine/Views/BookRecovery/Complete.cshtml
Normal file
3
PlotLine/Views/BookRecovery/Complete.cshtml
Normal file
@ -0,0 +1,3 @@
|
||||
@model PlotLine.Models.BookRecoveryReceipt
|
||||
@{ViewData["Title"]="Books restored";}
|
||||
<section class="edit-panel"><h1>@(Model.AlreadyCompleted?"Previous restore confirmed":"Books restored")</h1><p>@Model.BooksCreated books were committed by this restore operation. Later edits or deletions are not undone by a retry. A repeated submission with the same confirmation does not create more books.</p><p>Word bindings and live sessions must be connected explicitly. Historical review and Intent evidence retain author decisions; stale evidence needs reassessment.</p><a class="btn btn-primary" asp-controller="Projects" asp-action="Details" asp-route-id="@Model.ProjectID">Open project</a></section>
|
||||
4
PlotLine/Views/BookRecovery/Preview.cshtml
Normal file
4
PlotLine/Views/BookRecovery/Preview.cshtml
Normal file
@ -0,0 +1,4 @@
|
||||
@model BookRecoveryPage
|
||||
@{ViewData["Title"]="Review book restore";var p=Model.Preview!;}
|
||||
<div class="page-heading" data-pwa-header><h1>4. Review your restore</h1></div><section class="edit-panel"><p class="form-text">Backup file: @Model.UploadName</p><h2>@(p.Plan.Destination==0?"New project: "+p.Plan.Name:"Add books to: "+p.Plan.Name)</h2><ul>@foreach(var b in p.Selected.Data.Books){<li>@b.BookDisplayTitle @(b.IsArchived?"(archived)":"")</li>}</ul><dl><dt>Book slots required</dt><dd>@p.Selected.Data.Books.Count</dd><dt>Available slots now</dt><dd>@p.Available</dd><dt>Compatible common records reused</dt><dd>@p.Reused</dd><dt>Independent common records created</dt><dd>@p.Created</dd><dt>Uploaded files</dt><dd>@p.Selected.Files.Count</dd></dl><p>Common data is reused only with a verified source mapping and compatible saved content. Divergent data is copied independently. Existing work stays intact. Books are appended after existing books; chapter and scene order is preserved. Slot availability and destination state are checked again when you confirm.</p>@foreach(var warning in p.Warnings){<p class="alert alert-info">@warning</p>}@if(p.Available<p.Selected.Data.Books.Count){<p class="alert alert-warning">There are not enough book slots. Choose fewer books or free capacity separately; archiving does not release slots.</p>}<p>Confirmation starts a single transaction. Wait for its result; retrying the same confirmation is safe. Cancel below to leave without restoring.</p><form asp-action="Confirm" method="post"><input name="confirmation" type="hidden" value="@p.Confirmation"/><div class="form-check my-3"><input name="confirm" value="true" type="checkbox" required id="confirm" class="form-check-input"/><label for="confirm" class="form-check-label">Restore these books into the destination shown above. This uses @p.Selected.Data.Books.Count book slots.</label></div><button class="btn btn-primary" disabled="@(p.Available<p.Selected.Data.Books.Count)">Restore books</button> <a asp-action="Restore" class="btn btn-outline-secondary">Cancel</a></form></section>
|
||||
@section Scripts{<script src="~/js/book-recovery.js" asp-append-version="true"></script>}
|
||||
9
PlotLine/Views/BookRecovery/Restore.cshtml
Normal file
9
PlotLine/Views/BookRecovery/Restore.cshtml
Normal file
@ -0,0 +1,9 @@
|
||||
@model BookRecoveryPage
|
||||
@{ViewData["Title"]="Restore books from backup";}
|
||||
<div class="page-heading" data-pwa-header><div><p class="eyebrow">Make room for the books you need</p><h1>Restore books <help-icon key="bookRecovery.overview" /></h1><p>Restore selected books into a new project or add them safely to a project you own.</p></div><a class="btn btn-outline-secondary" asp-controller="Projects" asp-action="Index">Projects</a></div>
|
||||
@if(Model.Error!=""){<div class="alert alert-warning" role="alert">@Model.Error</div>}
|
||||
@if(Model.RetryConfirmation!=""){<section class="edit-panel mb-3"><h2>Check the previous restore</h2><p>Use its original confirmation to retrieve a committed result or safely retry the same operation. This does not duplicate a completed restore.</p><form asp-action="Confirm" method="post"><input name="confirmation" type="hidden" value="@Model.RetryConfirmation"/><input name="confirm" type="hidden" value="true"/><button class="btn btn-primary">Retry original confirmation</button></form></section>}
|
||||
<section class="edit-panel"><h2>1. Choose a backup</h2><form asp-action="Upload" method="post" enctype="multipart/form-data"><label for="backup" class="form-label">PlotDirector backup file</label><input id="backup" name="backup" type="file" class="form-control" accept=".plotdirector,.json,application/json" required/><p class="form-text">Up to 64 MiB. Supported historical project backups are recognised with compatibility warnings. No project changes happen during validation.</p><button class="btn btn-primary mt-2">Validate backup</button></form></section>
|
||||
@if(Model.Package is not null){<section class="edit-panel mt-3"><form asp-action="Preview" method="post"><input type="hidden" name="upload" value="@Model.Upload"/><p class="form-text">Validated file: @Model.UploadName</p><h2>2. Choose books from @Model.Package.Snapshot.Project?.ProjectName</h2><div class="button-row"><button type="button" class="btn btn-outline-secondary btn-sm" data-books-all>Select all</button><button type="button" class="btn btn-outline-secondary btn-sm" data-books-none>Clear selection</button></div>@foreach(var b in Model.Package.Snapshot.Data.Books.OrderBy(b=>b.SortOrder)){<div class="form-check my-3"><input name="books" value="@b.BookID" type="checkbox" id="restore-@b.BookID" class="form-check-input" checked/><label for="restore-@b.BookID" class="form-check-label">@b.BookDisplayTitle @(b.IsArchived?"· Archived":"")</label></div>}
|
||||
<h2>3. Choose destination</h2><label for="destination" class="form-label">Project</label><select id="destination" name="destination" class="form-select"><option value="0">Create a new project</option>@foreach(var p in Model.Projects.Where(p=>!p.IsArchived)){<option value="@p.ProjectID">@p.ProjectName</option>}</select><label for="name" class="form-label mt-2">New project name</label><input id="name" name="name" class="form-control" maxlength="200" value="@Model.Package.Snapshot.Project?.ProjectName"/><p class="form-text">Existing books and shared entities will not be overwritten. Each restored book needs a slot, including archived books.</p><button class="btn btn-primary">Preview restore</button></form></section>}
|
||||
@section Scripts{<script src="~/js/book-recovery.js" asp-append-version="true"></script>}
|
||||
@ -51,6 +51,8 @@
|
||||
Actions
|
||||
</button>
|
||||
<div class="dropdown-menu dropdown-menu-end">
|
||||
@if(Model.Project.IsOwner){<a class="dropdown-item" asp-controller="BookRecovery" asp-action="Backup" asp-route-projectId="@Model.Project.ProjectID" asp-route-bookId="@Model.Book.BookID">Back up this book</a>}
|
||||
<a class="dropdown-item" asp-controller="BookRecovery" asp-action="Restore">Restore books from backup</a>
|
||||
<a class="dropdown-item" asp-controller="Analytics" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID" asp-route-bookId="@Model.Book.BookID">Story health</a>
|
||||
<div class="dropdown-divider"></div>
|
||||
<form asp-action="Archive" method="post" class="archive-button-form" data-confirm-message="Archive this book? This will hide it from active lists and timelines, but the data will be kept and can be restored later.">
|
||||
|
||||
@ -400,6 +400,7 @@
|
||||
|
||||
if (button && textarea && sample) {
|
||||
button.addEventListener("click", () => {
|
||||
uploadGeneration++;activeReader?.abort();
|
||||
textarea.value = JSON.parse(sample.textContent);
|
||||
syncHiddenJson();
|
||||
if (uploadStatus) uploadStatus.textContent = "Sample JSON loaded into the package textarea.";
|
||||
@ -407,9 +408,12 @@
|
||||
});
|
||||
}
|
||||
|
||||
let uploadGeneration=0, activeReader=null;
|
||||
fileInput?.addEventListener("change", () => {
|
||||
const generation=++uploadGeneration;activeReader?.abort();if(textarea)textarea.value="";syncHiddenJson();
|
||||
const file = fileInput.files && fileInput.files[0];
|
||||
if (!file || !textarea) return;
|
||||
if (!file || !textarea) {if(uploadStatus)uploadStatus.textContent="No file selected.";return;}
|
||||
if(uploadStatus)uploadStatus.textContent=`Reading ${file.name}…`;
|
||||
|
||||
if (file.size === 0) {
|
||||
if (uploadStatus) uploadStatus.textContent = `${file.name} is empty. Choose a JSON file with content.`;
|
||||
@ -417,20 +421,22 @@
|
||||
return;
|
||||
}
|
||||
|
||||
const reader = new FileReader();
|
||||
const reader = new FileReader();activeReader=reader;
|
||||
reader.onload = () => {
|
||||
if(generation!==uploadGeneration)return;
|
||||
textarea.value = reader.result || "";
|
||||
syncHiddenJson();
|
||||
if (uploadStatus) uploadStatus.textContent = `Loaded JSON from ${file.name}.`;
|
||||
};
|
||||
reader.onerror = () => {
|
||||
if(generation!==uploadGeneration)return;
|
||||
if (uploadStatus) uploadStatus.textContent = `Could not read ${file.name}. Try choosing the file again.`;
|
||||
fileInput.value = "";
|
||||
};
|
||||
reader.readAsText(file, "UTF-8");
|
||||
});
|
||||
|
||||
textarea?.addEventListener("input", syncHiddenJson);
|
||||
textarea?.addEventListener("input",()=>{uploadGeneration++;activeReader?.abort();if(fileInput)fileInput.value="";if(uploadStatus)uploadStatus.textContent="JSON edited manually. Preview it again before importing.";syncHiddenJson();});
|
||||
document.querySelectorAll("form").forEach((form) => {
|
||||
form.addEventListener("submit", syncHiddenJson);
|
||||
});
|
||||
|
||||
@ -53,9 +53,10 @@
|
||||
}
|
||||
@if (Model.Project.IsOwner)
|
||||
{
|
||||
<a class="dropdown-item" asp-controller="Exports" asp-action="ProjectBackup" asp-route-projectId="@Model.Project.ProjectID">Download Project Backup</a>
|
||||
<a class="dropdown-item" asp-controller="BookRecovery" asp-action="Backup" asp-route-projectId="@Model.Project.ProjectID">Back up books</a>
|
||||
}
|
||||
<a class="dropdown-item" asp-controller="ProjectRestorePoints" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID">Restore Points</a>
|
||||
<a class="dropdown-item" asp-controller="BookRecovery" asp-action="Restore">Restore books from backup</a>
|
||||
@if(Model.Project.IsOwner){<a class="dropdown-item" asp-controller="ProjectRestorePoints" asp-action="Index" asp-route-projectId="@Model.Project.ProjectID">Rewind project · saved restore points</a>}
|
||||
@if (Model.Project.IsOwner)
|
||||
{
|
||||
<div class="dropdown-divider"></div>
|
||||
@ -174,7 +175,8 @@
|
||||
<div class="button-row mt-auto">
|
||||
<a class="btn btn-primary btn-sm" asp-controller="Books" asp-action="Details" asp-route-id="@book.BookID">Open Book</a>
|
||||
<a class="btn btn-outline-secondary btn-sm" asp-controller="Books" asp-action="Edit" asp-route-id="@book.BookID">Edit Book</a>
|
||||
<form asp-controller="Books" asp-action="Archive" method="post" class="archive-button-form" data-confirm-message="Archive this book? This will hide it from active lists and timelines, but the data will be kept and can be restored later.">
|
||||
@if(Model.Project.IsOwner){<a class="btn btn-outline-secondary btn-sm" asp-controller="BookRecovery" asp-action="Backup" asp-route-projectId="@Model.Project.ProjectID" asp-route-bookId="@book.BookID">Back up this book</a>}
|
||||
<form asp-controller="Books" asp-action="Archive" method="post" class="archive-button-form" data-confirm-message="Archive this book? This will hide it from active lists and timelines, but the data will be kept and can be unarchived later. Archived books still use subscription capacity.">
|
||||
<input type="hidden" name="id" value="@book.BookID" />
|
||||
<input type="hidden" name="projectId" value="@Model.Project.ProjectID" />
|
||||
<button class="btn btn-outline-danger btn-sm" type="submit">Archive</button>
|
||||
|
||||
@ -11,7 +11,9 @@
|
||||
<h1>Projects <help-icon key="projects.overview" /></h1>
|
||||
</div>
|
||||
<div class="button-row">
|
||||
<a class="btn btn-outline-primary" asp-controller="Imports" asp-action="Index">Import JSON</a>
|
||||
<form asp-controller="Onboarding" asp-action="StartImport" method="post"><button class="btn btn-outline-primary">Import a manuscript</button></form>
|
||||
<a class="btn btn-outline-primary" asp-controller="BookRecovery" asp-action="Backup">Back up books</a>
|
||||
<a class="btn btn-outline-primary" asp-controller="BookRecovery" asp-action="Restore">Restore books from backup</a>
|
||||
<a class="btn btn-primary" asp-action="Create">New project</a>
|
||||
</div>
|
||||
</div>
|
||||
@ -193,8 +195,8 @@ else
|
||||
More
|
||||
</button>
|
||||
<div class="dropdown-menu dropdown-menu-end">
|
||||
<a class="dropdown-item" asp-controller="Exports" asp-action="ProjectBackup" asp-route-projectId="@project.ProjectID">Download backup</a>
|
||||
<div class="dropdown-divider"></div>
|
||||
<a class="dropdown-item" asp-controller="BookRecovery" asp-action="Backup" asp-route-projectId="@project.ProjectID">Back up books</a>
|
||||
<a class="dropdown-item" asp-controller="BookRecovery" asp-action="Restore">Restore books from backup</a><div class="dropdown-divider"></div>
|
||||
<form asp-action="Archive" method="post" class="archive-button-form" data-confirm-message="Archive this project? Archived projects are hidden from your active workspace but remain stored within PlotDirector. Export your project first if you wish to maintain an external backup.">
|
||||
<input type="hidden" name="id" value="@project.ProjectID" />
|
||||
<button class="dropdown-item text-danger" type="submit">Archive</button>
|
||||
@ -269,10 +271,10 @@ else
|
||||
</div>
|
||||
</div>
|
||||
<div class="project-card__actions">
|
||||
<a class="btn btn-outline-secondary btn-sm" asp-controller="Exports" asp-action="ProjectBackup" asp-route-projectId="@project.ProjectID">Download backup</a>
|
||||
<form asp-action="Restore" method="post" class="archive-button-form" data-confirm-message="Restore this project? It will return to your active project list.">
|
||||
<a class="btn btn-outline-secondary btn-sm" asp-controller="BookRecovery" asp-action="Backup" asp-route-projectId="@project.ProjectID">Back up books</a>
|
||||
<form asp-action="Restore" method="post" class="archive-button-form" data-confirm-message="Unarchive this project? It will return to your active project list.">
|
||||
<input type="hidden" name="id" value="@project.ProjectID" />
|
||||
<button class="btn btn-outline-primary btn-sm" type="submit">Restore</button>
|
||||
<button class="btn btn-outline-primary btn-sm" type="submit">Unarchive</button>
|
||||
</form>
|
||||
@if (project.IsOwner)
|
||||
{
|
||||
|
||||
@ -36,14 +36,16 @@
|
||||
@if (project.IsOwner)
|
||||
{
|
||||
<li><a class="dropdown-item" asp-controller="ProjectCollaborators" asp-action="Index" asp-route-projectId="@project.ProjectID">Collaborators</a></li>
|
||||
<li><a class="dropdown-item" asp-controller="Exports" asp-action="ProjectBackup" asp-route-projectId="@project.ProjectID">Download Project Backup</a></li>
|
||||
<li><a class="dropdown-item" asp-controller="BookRecovery" asp-action="Backup" asp-route-projectId="@project.ProjectID">Back up books</a></li>
|
||||
}
|
||||
<li><a class="dropdown-item" asp-controller="ProjectRestorePoints" asp-action="Index" asp-route-projectId="@project.ProjectID">Restore Points</a></li>
|
||||
@if(project.IsOwner){<li><a class="dropdown-item" asp-controller="ProjectRestorePoints" asp-action="Index" asp-route-projectId="@project.ProjectID">Rewind project · saved restore points</a></li>}
|
||||
<li><hr class="dropdown-divider" /></li>
|
||||
}
|
||||
<li><a class="dropdown-item" asp-controller="Projects" asp-action="Index">@(project is null ? "Projects" : "Switch project…")</a></li>
|
||||
<li><a class="dropdown-item" asp-controller="Writer" asp-action="Index">Writer Workspace</a></li>
|
||||
<li><a class="dropdown-item" asp-controller="Imports" asp-action="Index">Import</a></li>
|
||||
<li><form asp-controller="Onboarding" asp-action="StartImport" method="post"><button class="dropdown-item">Import a manuscript</button></form></li>
|
||||
@if(project is null){<li><a class="dropdown-item" asp-controller="BookRecovery" asp-action="Backup">Back up books</a></li>}
|
||||
<li><a class="dropdown-item" asp-controller="BookRecovery" asp-action="Restore">Restore books from backup</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
@if (project is not null)
|
||||
|
||||
@ -31,14 +31,16 @@
|
||||
@if (project.IsOwner)
|
||||
{
|
||||
<li><a class="dropdown-item" asp-controller="ProjectCollaborators" asp-action="Index" asp-route-projectId="@project.ProjectID">Collaborators</a></li>
|
||||
<li><a class="dropdown-item" asp-controller="Exports" asp-action="ProjectBackup" asp-route-projectId="@project.ProjectID">Download Project Backup</a></li>
|
||||
<li><a class="dropdown-item" asp-controller="BookRecovery" asp-action="Backup" asp-route-projectId="@project.ProjectID">Back up books</a></li>
|
||||
}
|
||||
<li><a class="dropdown-item" asp-controller="ProjectRestorePoints" asp-action="Index" asp-route-projectId="@project.ProjectID">Restore Points</a></li>
|
||||
@if(project.IsOwner){<li><a class="dropdown-item" asp-controller="ProjectRestorePoints" asp-action="Index" asp-route-projectId="@project.ProjectID">Rewind project · saved restore points</a></li>}
|
||||
<li><hr class="dropdown-divider" /></li>
|
||||
}
|
||||
<li><a class="dropdown-item" asp-controller="Projects" asp-action="Index">@(project is null ? "Projects" : "Switch project…")</a></li>
|
||||
<li><a class="dropdown-item" asp-controller="Writer" asp-action="Index">Writer Workspace</a></li>
|
||||
<li><a class="dropdown-item" asp-controller="Imports" asp-action="Index">Import</a></li>
|
||||
<li><form asp-controller="Onboarding" asp-action="StartImport" method="post"><button class="dropdown-item">Import a manuscript</button></form></li>
|
||||
@if(project is null){<li><a class="dropdown-item" asp-controller="BookRecovery" asp-action="Backup">Back up books</a></li>}
|
||||
<li><a class="dropdown-item" asp-controller="BookRecovery" asp-action="Restore">Restore books from backup</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
}
|
||||
@ -137,12 +139,20 @@
|
||||
var bookScoped = command.Scope is "book" or "chapter";
|
||||
var presentationIcon = RibbonPresentation.IconFor(RibbonPresentation.Operation(command.Controller, command.Action)) ?? command.IconKey;
|
||||
var icon = ApplicationRibbon.Icon(presentationIcon);
|
||||
@if(command.Post){
|
||||
<form asp-controller="@command.Controller" asp-action="@command.Action" method="post">
|
||||
<button class="pd-ribbon-command" disabled="@(!available)" data-command-operation="@RibbonPresentation.Operation(command.Controller,command.Action)" data-ribbon-icon="@presentationIcon" title="@command.Label">
|
||||
<svg viewBox="0 0 24 24" class="pd-icon" data-tone="@icon.Tone" aria-hidden="true" focusable="false"><path d="@icon.IconPath" /></svg><span>@command.Label</span>
|
||||
</button>
|
||||
</form>
|
||||
}else{
|
||||
<a class="pd-ribbon-command" href="@url" aria-disabled="@(!available ? "true" : null)" aria-current="@(active ? "page" : null)"
|
||||
data-review-url="@(command.ToolbarKey == "review" ? Url.Action(command.Action, command.Controller, new { bookId = 0 }) : null)"
|
||||
data-ribbon-book-url="@(bookScoped ? Url.Action(command.Action, command.Controller, new { id = (int?)null, bookId = (int?)null }) : null)" data-book-param="@(command.Scope == "chapter" ? "bookId" : "id")"
|
||||
data-command-operation="@RibbonPresentation.Operation(command.Controller, command.Action)" data-ribbon-icon="@presentationIcon" title="@(available ? command.Label : bookScoped || shortcut?.RequiresBook == true ? "Select a book to use this command" : "Select a project to use this command")">
|
||||
<svg viewBox="0 0 24 24" class="pd-icon" data-tone="@icon.Tone" aria-hidden="true" focusable="false"><path d="@icon.IconPath" /></svg><span>@command.Label @if (command.Controller == "FeatureRequests" && Model.FeatureRequestAttentionCount > 0) { <span class="badge text-bg-warning">@Model.FeatureRequestAttentionCount</span> }</span>
|
||||
</a>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
<span class="pd-ribbon-group-label">@group.Label</span>
|
||||
|
||||
@ -132,6 +132,7 @@ html[data-app-theme] .app-layout {
|
||||
.pd-ribbon-group:last-child { border: 0; }
|
||||
.pd-ribbon-commands { display: flex; gap: 4px; flex: 1; align-items: flex-start; }
|
||||
.pd-shell .pd-ribbon-command { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 5px; padding: 6px 10px; min-width: 65px; border-radius: 4px; text-decoration: none; color: var(--pd-text) !important; font-size: 12px; white-space: nowrap; line-height: 18px; }
|
||||
.pd-shell button.pd-ribbon-command { border: 0; background: none; font-family: inherit; }
|
||||
.pd-shell .pd-ribbon-command:hover { background: var(--pd-hover); }
|
||||
.pd-shell .pd-ribbon-command[aria-current="page"] { background: var(--pd-selected); }
|
||||
.pd-ribbon-group-label { display: block; text-align: center; color: var(--pd-muted); font-size: 10px; letter-spacing: .03em; padding-top: 4px; }
|
||||
|
||||
1
PlotLine/wwwroot/js/book-recovery.js
Normal file
1
PlotLine/wwwroot/js/book-recovery.js
Normal file
@ -0,0 +1 @@
|
||||
(()=>{document.addEventListener('click',e=>{const b=e.target.closest('[data-books-all],[data-books-none]');if(!b)return;b.closest('form').querySelectorAll('input[name="books"]').forEach(x=>x.checked=b.hasAttribute('data-books-all'));});document.querySelectorAll('form[method="post"]').forEach(form=>form.addEventListener('submit',()=>{if(!form.checkValidity())return;form.querySelectorAll('button[type="submit"],button:not([type])').forEach(b=>{b.disabled=true;b.dataset.originalText=b.textContent;b.textContent=form.enctype==='multipart/form-data'?'Validating backup…':'Working safely…';});}));})();
|
||||
Loading…
x
Reference in New Issue
Block a user