using System.Net; using AVSCartonShipmentVerifier.Configuration; using AVSCartonShipmentVerifier.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; namespace AVSCartonShipmentVerifier.Controllers; [ApiController] [Route("api/desktop")] public sealed class DesktopController : ControllerBase { private readonly DesktopShutdownService _shutdown; private readonly IOptions _options; public DesktopController(DesktopShutdownService shutdown, IOptions options) { _shutdown = shutdown; _options = options; } [HttpPost("register-session")] public IActionResult RegisterSession() { if (!IsShutdownEnabled() || !IsLocalRequest()) { return NotFound(); } _shutdown.MarkDashboardSessionActive(); _shutdown.CancelScheduledShutdown(); return Ok(); } [HttpPost("schedule-shutdown")] public IActionResult ScheduleShutdown() { if (!IsShutdownEnabled() || !IsLocalRequest()) { return NotFound(); } if (!_shutdown.IsLifecycleShutdownAllowed) { return Ok(); } var delay = TimeSpan.FromSeconds(Math.Max(1, _options.Value.BrowserShutdownDelaySeconds)); _shutdown.ScheduleShutdown(delay); return Ok(); } [HttpPost("cancel-shutdown")] public IActionResult CancelShutdown() { if (!IsShutdownEnabled() || !IsLocalRequest()) { return NotFound(); } _shutdown.CancelScheduledShutdown(); return Ok(); } private bool IsShutdownEnabled() => _options.Value.ExitWhenBrowserCloses; private bool IsLocalRequest() { var remote = HttpContext.Connection.RemoteIpAddress; return remote is null || IPAddress.IsLoopback(remote); } }