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):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 mapped=NativeChapterMapping.Build(request,Math.Clamp(configuration.GetValue("NativeCompanion:MaxChapterCharacters",120000),10000,500000)); var hash=Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(request))); var task=cache.Run(UserId,request.RequestId,hash,async cancellation=>{ await using var scope=scopes.CreateAsyncScope(); var result=await scope.ServiceProvider.GetRequiredService().AnalyseChapterAsync(mapped,cancellation); return NativeChapterMapping.Map(request,result); }); 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();} }