Files
Heimdall/src/Heimdall.Web/Controllers/CamerasController.cs
T

153 lines
7.1 KiB
C#
Raw Normal View History

using System.Security.Claims;
using Heimdall.Application.Cameras.Commands.CreateCamera;
using Heimdall.Application.Cameras.Commands.UpdateCamera;
using Heimdall.Application.Cameras.Commands.DeleteCamera;
using Heimdall.Application.Cameras.Commands.ToggleCameraStatus;
using Heimdall.Application.Cameras.Queries.GetCamera;
using Heimdall.Application.Cameras.Queries.GetCamerasBySite;
using Heimdall.Application.DTOs;
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Security;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/cameras")]
[EnableRateLimiting("Api")]
public class CamerasController : ControllerBase
{
private readonly IMediator _mediator;
private readonly IApplicationDbContext _db;
private readonly IConfigBroadcastService _broadcast;
public CamerasController(IMediator mediator, IApplicationDbContext db, IConfigBroadcastService broadcast)
{
_mediator = mediator;
_db = db;
_broadcast = broadcast;
}
/// <summary>Ask the assigned agent to capture a new frame from its active stream.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
[HttpPost("{id:guid}/snapshot")]
[ProducesResponseType(StatusCodes.Status202Accepted)]
public async Task<IActionResult> RequestSnapshot(Guid id, CancellationToken ct)
{
var camera = await _db.Cameras.AsNoTracking().Where(c => c.Id == id)
.Select(c => new { c.AgentId, c.Status }).FirstOrDefaultAsync(ct);
if (camera is null) return NotFound();
if (camera.Status != CameraStatus.Online) return Conflict(new { error = "The camera is not online" });
if (camera.AgentId is null) return Conflict(new { error = "No agent is assigned to this camera" });
var requestId = Guid.NewGuid();
if (!await _broadcast.RequestManualSnapshot(camera.AgentId.Value, id, requestId, ct))
return Conflict(new { error = "The assigned agent is offline" });
return Accepted(new { requestId });
}
/// <summary>Create a new camera.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
[HttpPost]
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create([FromBody] CreateCameraRequest request, CancellationToken ct)
{
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
var command = new CreateCameraCommand(request.SiteId, request.Name, request.RtspUrl,
request.Manufacturer, request.Model, actorId);
var result = await _mediator.Send(command, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Get a camera by ID.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)]
[HttpGet("{id:guid}")]
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
{
var userId = GetUserId();
var result = await _mediator.Send(new GetCameraQuery(id, userId), ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>List cameras by site.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)]
[HttpGet("by-site/{siteId:guid}")]
[ProducesResponseType(typeof(PagedResult<CameraResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ListBySite(
Guid siteId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var userId = GetUserId();
var result = await _mediator.Send(new GetCamerasBySiteQuery(siteId, page, pageSize, userId), ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
/// <summary>Update a camera.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
[HttpPut("{id:guid}")]
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Update(Guid id, [FromBody] UpdateCameraRequest request, CancellationToken ct)
{
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
var command = new UpdateCameraCommand(id, request.Name, request.RtspUrl, request.Status,
request.Manufacturer, request.Model, request.DetectionProfile, actorId);
var result = await _mediator.Send(command, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Toggle a camera between Online and Disabled.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
[HttpPost("{id:guid}/toggle-status")]
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> ToggleStatus(Guid id, CancellationToken ct)
{
2026-10-21 10:15:26 +02:00
if (!this.TryGetUserId(out var actorId))
return Unauthorized();
var result = await _mediator.Send(new ToggleCameraStatusCommand(id, actorId), ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>Delete a camera.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
{
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
var result = await _mediator.Send(new DeleteCameraCommand(id, actorId), ct);
return result.IsSuccess
? NoContent()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
private Guid? GetUserId()
{
var sub = User?.FindFirst(ClaimTypes.NameIdentifier)?.Value
?? User?.FindFirst("sub")?.Value;
return Guid.TryParse(sub, out var userId) ? userId : null;
}
}