using System.Security.Claims; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using PlotLine.Data; using PlotLine.Services.NativeCompanion; namespace PlotLine.Controllers; [Authorize,Route("native-companion")] public sealed class NativeInstallationController(INativeInstallationRepository installations,NativeInstallationService service,TimeProvider clock):Controller { private int Author=>int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); [HttpGet("installations")] public async Task Index(){Response.Headers.CacheControl="no-store";return View(await installations.Run("list",user:Author));} [HttpPost("installations/{id:guid}/revoke"),ValidateAntiForgeryToken] public async Task Revoke(Guid id){if(!await service.RevokeUser(Author,id))return NotFound();return RedirectToAction(nameof(Index));} [HttpGet("connection-state")] public async Task State() { Response.Headers.CacheControl="no-store";var all=await installations.Run("list",user:Author);var now=clock.GetUtcNow();var active=all.Where(i=>i.RevokedUtc==null&&i.RefreshExpiresUtc>now).ToArray(); var connected=active.Any(i=>i.LastSeenUtc.HasValue&&now-i.LastSeenUtc.Valuei.DisconnectedUtc)); var recent=active.Any(i=>i.LastSeenUtc.HasValue&&now-i.LastSeenUtc.Valuei.DisconnectedUtc)); return Json(new{known=all.Count>0,state=connected?"Connected":recent?"Reconnecting":active.Length>0?"Disconnected":all.Count>0?"Action required":"Disconnected",wordConnected=false}); } } [ApiController,Authorize(AuthenticationSchemes=DesktopPairing.Scheme),Route("api/native-companion")] public sealed class NativeConnectionController(INativeInstallationRepository installations,NativePresenceStore presence):ControllerBase { [HttpPost("heartbeat")] public IActionResult Heartbeat()=>Ok(new{connected=true,catalogVersion=presence.CatalogVersion(int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!))}); // Authentication validates live installation/security stamp. [HttpPost("disconnect")] public async Task Disconnect(){if(Guid.TryParse(User.FindFirstValue("NativeCompanion.Installation"),out var id)&&Guid.TryParse(User.FindFirstValue("NativeCompanion.Connection"),out var connection)){var user=int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);await installations.Run("disconnect",id,user,connection:connection);presence.DisconnectGrant(user,User.FindFirstValue("NativeCompanion.Grant")!);}return NoContent();} }