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,ProjectTitle=project.Title,BookTitle=b.DisplayTitle})); return Ok(result.Take(500)); } // Ownership is checked before looking up a private cover path. No public URLs or client paths accepted. [HttpGet("books/{bookId:int}/cover")] public async Task Cover(int bookId,[FromServices] IBookRepository books,[FromServices] IUploadStorageService storage) { if(await repository.GetBookStructureAsync(bookId,UserId)==null)return Forbid(); Response.Headers.CacheControl="no-store"; var book=await books.GetCoverPathsAsync(bookId); var path=storage.TryResolvePublicPath(book?.CoverThumbnailPath,$"uploads/books/{bookId}"); if(path==null||!System.IO.File.Exists(path))return Ok(new BookCoverReply()); if(new FileInfo(path).Length>2*1024*1024)return StatusCode(413); using var input=System.IO.File.OpenRead(path); using var codec=SkiaSharp.SKCodec.Create(input); if(codec==null||codec.Info.Width>600||codec.Info.Height>900)return Ok(new BookCoverReply()); using var bitmap=SkiaSharp.SKBitmap.Decode(codec); if(bitmap==null||bitmap.Width>600||bitmap.Height>900)return Ok(new BookCoverReply()); using var image=SkiaSharp.SKImage.FromBitmap(bitmap); using var png=image.Encode(SkiaSharp.SKEncodedImageFormat.Png,90); if(png.Size>700000)return StatusCode(413); return Ok(new BookCoverReply{Png=Convert.ToBase64String(png.ToArray())}); } [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();} }