77 lines
7.1 KiB
C#
77 lines
7.1 KiB
C#
using System.Security.Claims;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.Data.SqlClient;
|
|
using PlotLine.Data;
|
|
using PlotLine.Models;
|
|
using PlotLine.Services.NativeCompanion;
|
|
using PlotDirector.Companion.Protocol;
|
|
namespace PlotLine.Controllers;
|
|
[Authorize,Route("Writer/Work")]
|
|
public sealed class WriterWorkController(WriterWorkRepository work,NativePresenceStore presence):Controller
|
|
{
|
|
private int Actor=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
|
[HttpGet("State")]
|
|
public async Task<IActionResult> State(int bookId)
|
|
{
|
|
Response.Headers.CacheControl="no-store";
|
|
try {var state=await work.State(Actor,bookId);var current=state.Current;if(current?.StartedUtc<DateTime.UtcNow.AddHours(-12))current=null;return Json(new{defaultPauseOnEdit=state.PauseOnEdit,session=current==null?null:new{current.SessionID,current.BookID,current.ChapterID,current.ChapterTitle,current.Kind,startedUtc=DateTime.SpecifyKind(current.StartedUtc,DateTimeKind.Utc),current.EngagedSeconds,current.PlaybackSeconds,current.UniqueSeconds,current.PauseOnEdit,current.PlaybackState,current.PositionSeconds,current.DurationSeconds,current.Pauses,current.Seeks,current.LastError,capabilities=current.MediaReceivedUtc>DateTime.UtcNow.AddSeconds(-45)?current.Capabilities:null,live=current.MediaReceivedUtc>DateTime.UtcNow.AddSeconds(-45)&&presence.Read(Actor,bookId).Any(l=>l.Instance==current.NativeInstance&&l.Session==current.NativeDocument&&l.Grant==current.NativeGrant),coveragePartial=current.CoveragePartial,sequence=current.BrowserSequence}});}
|
|
catch(SqlException e)when(e.Number==51000){return NotFound();}
|
|
}
|
|
[HttpPost("Start"),ValidateAntiForgeryToken]
|
|
public async Task<IActionResult> Start(int bookId,int? chapterId,string kind,Guid requestId,bool pauseOnEdit=true)
|
|
{
|
|
if(requestId==Guid.Empty||kind is not("Writing" or "Editing" or "Planning" or "Reading" or "AudioReview")||kind=="AudioReview"&&!chapterId.HasValue)return BadRequest("Choose a chapter and activity.");
|
|
var leases=presence.Read(Actor,bookId).ToArray();var lease=leases.Length==1?leases[0]:leases.Count(x=>x.Position.Active)==1?leases.Single(x=>x.Position.Active):null;
|
|
try {await work.Execute(new{Action="start",UserID=Actor,BookID=bookId,ChapterID=chapterId,Kind=kind,SessionID=requestId,PauseOnEdit=pauseOnEdit,NativeInstance=kind=="AudioReview"?lease?.Instance:null,NativeDocument=kind=="AudioReview"?lease?.Session:null,NativeGrant=kind=="AudioReview"?lease?.Grant:null});return Ok(new{sessionID=requestId});}
|
|
catch(SqlException e)when(e.Number==51000){return Conflict(new{message="Session could not start. Check book access, chapter availability and Reports recording settings."});}
|
|
}
|
|
[HttpPost("Heartbeat"),ValidateAntiForgeryToken]
|
|
public Task<IActionResult> Heartbeat(int bookId,Guid sessionId,long sequence,bool engaged)=>sequence<=0?Task.FromResult<IActionResult>(BadRequest()):Change(new{Action="heartbeat",UserID=Actor,BookID=bookId,SessionID=sessionId,Sequence=sequence,Engaged=engaged});
|
|
[HttpPost("End"),ValidateAntiForgeryToken]
|
|
public Task<IActionResult> End(int bookId,Guid sessionId,string? note)
|
|
{if(note?.Length>2000)return Task.FromResult<IActionResult>(BadRequest());return Change(new{Action="end",UserID=Actor,BookID=bookId,SessionID=sessionId,Note=note});}
|
|
[HttpPost("Preference"),ValidateAntiForgeryToken]
|
|
public Task<IActionResult> Preference(int bookId,Guid sessionId,bool pauseOnEdit)=>Change(new{Action="preference",UserID=Actor,BookID=bookId,SessionID=sessionId,PauseOnEdit=pauseOnEdit});
|
|
[HttpPost("Command"),ValidateAntiForgeryToken]
|
|
public async Task<IActionResult> Command(int bookId,Guid sessionId,string command)
|
|
{
|
|
try {
|
|
var current=(await work.State(Actor,bookId)).Current;if(current?.SessionID!=sessionId)current=null;
|
|
if(current==null||current.MediaReceivedUtc is not {} received||received<=DateTime.UtcNow.AddSeconds(-45)||
|
|
current.PlaybackState is "unavailable" or "error"||!presence.Read(Actor,bookId).Any(l=>l.Instance==current.NativeInstance&&l.Session==current.NativeDocument&&l.Grant==current.NativeGrant)||command is not("play" or "pause" or "back15" or "forward15")||!(current.Capabilities??"").Split(',').Contains(command))return Conflict(new{message="This media operation is unavailable."});
|
|
return await Change(new{Action="command",UserID=Actor,BookID=bookId,SessionID=sessionId,CommandID=Guid.NewGuid(),Command=command});
|
|
} catch(SqlException e)when(e.Number==51000){return NotFound();}
|
|
}
|
|
[HttpGet("Export")]
|
|
public async Task<IActionResult> Export(int bookId,DateTime? day=null)
|
|
{try{return Json((await work.History(Actor,bookId,day)).Select(x=>new{x.SessionID,x.BookID,x.ChapterID,x.Kind,startedUtc=DateTime.SpecifyKind(x.StartedUtc,DateTimeKind.Utc),endedUtc=x.EndedUtc.HasValue?DateTime.SpecifyKind(x.EndedUtc.Value,DateTimeKind.Utc):(DateTime?)null,x.EngagedSeconds,x.PlaybackSeconds,x.UniqueSeconds,x.CoveragePartial,x.Pauses,x.Seeks,x.Note,x.StartRevision,x.EndRevision,x.StartParagraphCount,x.EndParagraphCount,x.ChangesDuringSession,x.AdditionsDuringSession,x.RemovalsDuringSession,x.ChangedParagraphs}));}catch(SqlException e)when(e.Number==51000){return NotFound();}}
|
|
[HttpPost("Erase"),ValidateAntiForgeryToken]
|
|
public Task<IActionResult> Erase(int bookId,bool confirm)=>confirm?Change(new{Action="erase",UserID=Actor,BookID=bookId}):Task.FromResult<IActionResult>(BadRequest("Confirm erasure."));
|
|
private async Task<IActionResult> Change(object values)
|
|
{try{await work.Execute(values);return Ok();}catch(SqlException e)when(e.Number==51000){return Conflict(new{message="Session ended, expired, or recording is paused. Check Reports or start a new session."});}}
|
|
}
|
|
[ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion/instances/{instance:guid}/documents/{document:guid}/audio-review")]
|
|
public sealed class NativeAudioReviewController(WriterWorkRepository work,NativePresenceStore presence):ControllerBase
|
|
{
|
|
[HttpPost,RequestSizeLimit(4096)]
|
|
public async Task<IActionResult> Observe(Guid instance,Guid document,AudioReviewObservation value)
|
|
{
|
|
var user=int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);var grant=User.FindFirstValue("NativeCompanion.Grant");
|
|
var lease=presence.Read(user,value.BookID).SingleOrDefault(x=>x.Instance==instance&&x.Session==document&&x.Grant==grant);
|
|
if(lease==null||value.BookID<=0)return Forbid();
|
|
try
|
|
{
|
|
PlotLine.Services.Writer.AudioReviewMetrics.Validate(value);
|
|
var current=(await work.State(user,value.BookID)).Current;if(current?.Kind!="AudioReview"||current.NativeInstance!=instance||current.NativeDocument!=document||current.NativeGrant!=grant)current=null;
|
|
if(current==null||current.StartedUtc<DateTime.UtcNow.AddHours(-12))return Ok(new AudioReviewReply());
|
|
if(value.ReviewID==null)return Ok(WriterWorkRepository.Reply(current,DateTime.UtcNow));
|
|
if(value.ReviewID!=current.SessionID)return Conflict(new{code="review_scope"});
|
|
return Ok(await work.Media(user,value.BookID,instance,document,grant!,value));
|
|
}
|
|
catch(ArgumentException){return BadRequest(new{code="audio_contract"});}
|
|
catch(UnauthorizedAccessException){return Forbid();}
|
|
catch(SqlException e)when(e.Number==51000){return Conflict(new{code="review_unavailable"});}
|
|
}
|
|
}
|