2026-08-30 10:09:25 +02:00
|
|
|
using System.Security.Claims;
|
2026-07-22 19:54:55 +00:00
|
|
|
using Heimdall.Application.Cameras.Commands.CreateCamera;
|
|
|
|
|
using Heimdall.Application.Cameras.Commands.UpdateCamera;
|
|
|
|
|
using Heimdall.Application.Cameras.Commands.DeleteCamera;
|
2026-08-19 22:38:34 +02:00
|
|
|
using Heimdall.Application.Cameras.Commands.ToggleCameraStatus;
|
2026-07-22 19:54:55 +00:00
|
|
|
using Heimdall.Application.Cameras.Queries.GetCamera;
|
|
|
|
|
using Heimdall.Application.Cameras.Queries.GetCamerasBySite;
|
2026-07-20 10:30:01 +00:00
|
|
|
using Heimdall.Application.DTOs;
|
2026-10-23 07:20:47 +02:00
|
|
|
using Heimdall.Application.Common;
|
2026-10-23 07:30:58 +02:00
|
|
|
using Heimdall.Domain.Entities;
|
2026-10-23 07:20:47 +02:00
|
|
|
using Heimdall.Application.Services;
|
|
|
|
|
using Heimdall.Domain.Enums;
|
2026-07-20 10:30:01 +00:00
|
|
|
using Heimdall.Infrastructure.Security;
|
2026-07-22 19:54:55 +00:00
|
|
|
using MediatR;
|
2026-07-20 10:30:01 +00:00
|
|
|
using Microsoft.AspNetCore.Authorization;
|
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
|
using Microsoft.AspNetCore.RateLimiting;
|
2026-10-23 07:20:47 +02:00
|
|
|
using Microsoft.EntityFrameworkCore;
|
2026-07-20 10:30:01 +00:00
|
|
|
|
|
|
|
|
namespace Heimdall.Api.Controllers;
|
|
|
|
|
|
|
|
|
|
[ApiController]
|
|
|
|
|
[Route("api/cameras")]
|
|
|
|
|
[EnableRateLimiting("Api")]
|
|
|
|
|
public class CamerasController : ControllerBase
|
|
|
|
|
{
|
2026-07-22 19:54:55 +00:00
|
|
|
private readonly IMediator _mediator;
|
2026-10-23 07:20:47 +02:00
|
|
|
private readonly IApplicationDbContext _db;
|
|
|
|
|
private readonly IConfigBroadcastService _broadcast;
|
2026-07-20 10:30:01 +00:00
|
|
|
|
2026-10-23 07:20:47 +02:00
|
|
|
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();
|
2026-10-23 07:30:58 +02:00
|
|
|
var snapshotRequest = new ManualSnapshotRequest(requestId, id, camera.AgentId.Value, DateTime.UtcNow);
|
|
|
|
|
_db.ManualSnapshotRequests.Add(snapshotRequest);
|
|
|
|
|
await _db.SaveChangesWithRetryAsync(ct: ct);
|
2026-10-23 07:20:47 +02:00
|
|
|
if (!await _broadcast.RequestManualSnapshot(camera.AgentId.Value, id, requestId, ct))
|
2026-10-23 07:30:58 +02:00
|
|
|
{
|
|
|
|
|
snapshotRequest.Fail("L'agent affecté est indisponible.", DateTime.UtcNow);
|
|
|
|
|
await _db.SaveChangesWithRetryAsync(ct: ct);
|
2026-10-23 07:20:47 +02:00
|
|
|
return Conflict(new { error = "The assigned agent is offline" });
|
2026-10-23 07:30:58 +02:00
|
|
|
}
|
2026-10-23 07:20:47 +02:00
|
|
|
return Accepted(new { requestId });
|
|
|
|
|
}
|
2026-07-20 10:30:01 +00:00
|
|
|
|
2026-10-23 07:30:58 +02:00
|
|
|
/// <summary>Read the durable outcome of a manual capture request.</summary>
|
|
|
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)]
|
|
|
|
|
[HttpGet("{id:guid}/snapshot/{requestId:guid}")]
|
|
|
|
|
public async Task<IActionResult> GetSnapshotRequest(Guid id, Guid requestId, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
var request = await _db.ManualSnapshotRequests.AsNoTracking()
|
|
|
|
|
.FirstOrDefaultAsync(r => r.Id == requestId && r.CameraId == id, ct);
|
|
|
|
|
if (request is null) return NotFound();
|
|
|
|
|
if (request.Status == ManualSnapshotStatus.Pending && request.ExpiresAt <= DateTime.UtcNow)
|
|
|
|
|
{
|
|
|
|
|
await _db.ManualSnapshotRequests
|
|
|
|
|
.Where(r => r.Id == requestId && r.Status == ManualSnapshotStatus.Pending && r.ExpiresAt <= DateTime.UtcNow)
|
|
|
|
|
.ExecuteUpdateAsync(setters => setters
|
|
|
|
|
.SetProperty(r => r.Status, ManualSnapshotStatus.TimedOut)
|
|
|
|
|
.SetProperty(r => r.FailureReason, "La capture n'a pas été livrée dans le délai attendu.")
|
|
|
|
|
.SetProperty(r => r.UpdatedAt, DateTime.UtcNow), ct);
|
|
|
|
|
request = await _db.ManualSnapshotRequests.AsNoTracking()
|
|
|
|
|
.FirstAsync(r => r.Id == requestId, ct);
|
|
|
|
|
}
|
|
|
|
|
return Ok(new { requestId = request.Id, status = request.Status.ToString(),
|
|
|
|
|
reason = request.FailureReason, updatedAt = request.UpdatedAt });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Record a capture failure reported by the agent assigned when the command was issued.</summary>
|
|
|
|
|
[Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)]
|
|
|
|
|
[HttpPut("{id:guid}/snapshot/{requestId:guid}/failure")]
|
|
|
|
|
public async Task<IActionResult> FailSnapshotRequest(Guid id, Guid requestId,
|
|
|
|
|
[FromBody] ManualSnapshotFailure failure, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
var exists = await _db.ManualSnapshotRequests.AnyAsync(r => r.Id == requestId && r.CameraId == id, ct);
|
|
|
|
|
if (!exists) return NotFound();
|
|
|
|
|
var reason = failure.Code switch
|
|
|
|
|
{
|
|
|
|
|
"camera_unavailable" => "La caméra n'est plus affectée ou est désactivée sur l'agent.",
|
|
|
|
|
"no_frame" => "Aucune image n'a été reçue du flux de la caméra.",
|
|
|
|
|
"queue_failed" => "L'agent n'a pas pu enregistrer la capture pour livraison.",
|
|
|
|
|
_ => "La capture a échoué sur l'agent."
|
|
|
|
|
};
|
|
|
|
|
await _db.ManualSnapshotRequests
|
|
|
|
|
.Where(r => r.Id == requestId && r.CameraId == id && r.Status != ManualSnapshotStatus.Completed)
|
|
|
|
|
.ExecuteUpdateAsync(setters => setters
|
|
|
|
|
.SetProperty(r => r.Status, ManualSnapshotStatus.Failed)
|
|
|
|
|
.SetProperty(r => r.FailureReason, reason)
|
|
|
|
|
.SetProperty(r => r.UpdatedAt, DateTime.UtcNow), ct);
|
|
|
|
|
return NoContent();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public sealed record ManualSnapshotFailure(string Code);
|
|
|
|
|
|
2026-07-20 10:30:01 +00:00
|
|
|
/// <summary>Create a new camera.</summary>
|
2026-08-11 08:32:41 +02:00
|
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
|
2026-07-20 10:30:01 +00:00
|
|
|
[HttpPost]
|
|
|
|
|
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
|
|
|
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
|
|
|
public async Task<IActionResult> Create([FromBody] CreateCameraRequest request, CancellationToken ct)
|
|
|
|
|
{
|
2026-10-21 15:11:48 +02:00
|
|
|
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
|
|
|
|
|
var command = new CreateCameraCommand(request.SiteId, request.Name, request.RtspUrl,
|
|
|
|
|
request.Manufacturer, request.Model, actorId);
|
2026-07-22 19:54:55 +00:00
|
|
|
var result = await _mediator.Send(command, ct);
|
2026-07-20 10:30:01 +00:00
|
|
|
return result.IsSuccess
|
|
|
|
|
? Ok(result.Data)
|
|
|
|
|
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Get a camera by ID.</summary>
|
2026-08-11 08:32:41 +02:00
|
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)]
|
2026-07-20 10:30:01 +00:00
|
|
|
[HttpGet("{id:guid}")]
|
|
|
|
|
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
|
|
|
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
|
|
|
|
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
|
|
|
|
{
|
2026-08-30 10:09:25 +02:00
|
|
|
var userId = GetUserId();
|
|
|
|
|
var result = await _mediator.Send(new GetCameraQuery(id, userId), ct);
|
2026-07-20 10:30:01 +00:00
|
|
|
return result.IsSuccess
|
|
|
|
|
? Ok(result.Data)
|
|
|
|
|
: NotFound(new { error = result.Error });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>List cameras by site.</summary>
|
2026-08-11 08:32:41 +02:00
|
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)]
|
2026-07-20 10:30:01 +00:00
|
|
|
[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)
|
|
|
|
|
{
|
2026-08-30 10:09:25 +02:00
|
|
|
var userId = GetUserId();
|
|
|
|
|
var result = await _mediator.Send(new GetCamerasBySiteQuery(siteId, page, pageSize, userId), ct);
|
2026-07-20 10:30:01 +00:00
|
|
|
if (!result.IsSuccess)
|
|
|
|
|
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
|
|
|
return Ok(result.Data);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Update a camera.</summary>
|
2026-08-11 08:32:41 +02:00
|
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
|
2026-07-20 10:30:01 +00:00
|
|
|
[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)
|
|
|
|
|
{
|
2026-10-21 15:11:48 +02:00
|
|
|
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);
|
2026-07-22 19:54:55 +00:00
|
|
|
var result = await _mediator.Send(command, ct);
|
2026-07-20 10:30:01 +00:00
|
|
|
return result.IsSuccess
|
|
|
|
|
? Ok(result.Data)
|
|
|
|
|
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-19 22:38:34 +02:00
|
|
|
/// <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);
|
2026-08-19 22:38:34 +02:00
|
|
|
return result.IsSuccess
|
|
|
|
|
? Ok(result.Data)
|
|
|
|
|
: NotFound(new { error = result.Error });
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-20 10:30:01 +00:00
|
|
|
/// <summary>Delete a camera.</summary>
|
2026-08-11 08:32:41 +02:00
|
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
|
2026-07-20 10:30:01 +00:00
|
|
|
[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)
|
|
|
|
|
{
|
2026-10-21 15:11:48 +02:00
|
|
|
if (!this.TryGetUserId(out var actorId)) return Unauthorized();
|
|
|
|
|
var result = await _mediator.Send(new DeleteCameraCommand(id, actorId), ct);
|
2026-07-20 10:30:01 +00:00
|
|
|
return result.IsSuccess
|
|
|
|
|
? NoContent()
|
|
|
|
|
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
|
|
|
|
}
|
2026-08-30 10:09:25 +02:00
|
|
|
|
|
|
|
|
private Guid? GetUserId()
|
|
|
|
|
{
|
|
|
|
|
var sub = User?.FindFirst(ClaimTypes.NameIdentifier)?.Value
|
|
|
|
|
?? User?.FindFirst("sub")?.Value;
|
|
|
|
|
return Guid.TryParse(sub, out var userId) ? userId : null;
|
|
|
|
|
}
|
2026-07-20 10:30:01 +00:00
|
|
|
}
|