PlotDirector/PlotLine/Data/BookRecoveryRepository.cs

36 lines
5.9 KiB
C#

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) ?? [];
if(!rows.IsConsumed){var paragraphs=(await rows.ReadAsync<string>()).Select(json=>JsonSerializer.Deserialize<ParagraphManuscript>(json)??throw new InvalidDataException("Invalid paragraph recovery state.")).ToList();if(paragraphs.Count>0)result.ParagraphManuscripts=paragraphs;}
foreach(var state in result.ParagraphManuscripts??[])PlotLine.Services.Manuscript.ParagraphRecovery.Detach(state);
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, state.ParagraphManuscripts });
}
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); }
}