using System.Security.Claims; using System.Security.Cryptography; using System.Text.Json; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using PlotDirector.Companion.Protocol; using PlotLine.Data; using PlotLine.Services; using PlotLine.Services.NativeCompanion; namespace PlotLine.Controllers; [ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion")] public sealed class NativeCompanionController(IWordCompanionRepository repository,NativeAnalysisCache cache,IServiceScopeFactory scopes,IConfiguration configuration,ISubscriptionService subscriptions,INativeReviewRepository? reviews=null,NativeImportService? importService=null):ControllerBase { private int UserId=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); [HttpGet("books")] public async Task Books() { var result=new List(); foreach(var project in await repository.ListProjectsAsync(UserId)) result.AddRange((await repository.ListBooksAsync(project.ProjectId,UserId)).Select(b=>new CompanionBook{BookId=b.BookId,Title=project.Title+" / "+b.DisplayTitle})); return Ok(result.Take(500)); } [HttpPost("analyse-chapter"),RequestSizeLimit(2*1024*1024)] public async Task Analyse(AiChapterRequest request) { if(!(await subscriptions.CanUseFeatureAsync(UserId,PlotLine.Models.SubscriptionFeature.StoryIntelligence)).Allowed)return Forbid(); // Access is checked on every request, including an idempotent cache hit. if(await repository.GetBookStructureAsync(request.BookId,UserId)==null)return Forbid(); try { var retain=User.HasClaim("NativeCompanion.RetainImport","true"); var mapped=NativeChapterMapping.Build(request,Math.Clamp(configuration.GetValue("NativeCompanion:MaxChapterCharacters",120000),10000,500000)); var contentHash=Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new{request.ChapterStart,request.ChapterEnd,request.Paragraphs}))); if(reviews!=null){var prior=await reviews.Find(UserId,request.BookId,request.ManuscriptId,contentHash);if(prior!=null){if(retain&&prior.EncryptedSource==null&&importService!=null){prior.EncryptedSource=importService.Protect(request);prior.SourceRevision=request.Revision;prior.SourceSession=request.SessionId;await reviews.Save(prior);}var saved=JsonSerializer.Deserialize(prior.ResultJson)!;saved.SourceRetained=prior.EncryptedSource!=null;saved.RequestId=request.RequestId;saved.DocumentRevision=request.Revision;saved.ReviewPath=$"/native-companion/reviews/{prior.ReviewID}";return Ok(saved);}} var hash=Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(request))); var author=UserId;var task=cache.Run(author,request.RequestId,hash,async cancellation=>{ await using var scope=scopes.CreateAsyncScope(); var result=await scope.ServiceProvider.GetRequiredService().AnalyseChapterAsync(mapped,cancellation); var mappedResult=NativeChapterMapping.Map(request,result); if(mappedResult.State=="complete"&&reviews!=null){var row=await scope.ServiceProvider.GetRequiredService().Save(new(){ReviewID=request.RequestId,UserID=author,BookID=request.BookId,ManuscriptID=request.ManuscriptId,ChapterStart=request.ChapterStart,ChapterEnd=request.ChapterEnd,ContentHash=contentHash,ResultJson=JsonSerializer.Serialize(mappedResult),SourceRevision=request.Revision,SourceSession=request.SessionId,EncryptedSource=retain?importService?.Protect(request):null});mappedResult.SourceRetained=row.EncryptedSource!=null;mappedResult.ReviewPath=$"/native-companion/reviews/{row.ReviewID}";} return mappedResult; },request.BookId); Response.Headers.CacheControl="no-store"; return Ok(await task.WaitAsync(HttpContext.RequestAborted)); } catch(ArgumentException e){return BadRequest(new{message=e.Message});} catch(InvalidOperationException){return StatusCode(429,new{message="Analysis capacity is busy. Retry later."});} } [HttpPost("analysis/{id:guid}/cancel")] public IActionResult Cancel(Guid id){cache.Cancel(UserId,id);return NoContent();} }