2026-08-27 20:28:41 +02:00
|
|
|
using System.Security.Claims;
|
2026-10-22 20:50:40 +02:00
|
|
|
using Heimdall.Api.Security;
|
|
|
|
|
using Heimdall.Application.Common;
|
2026-07-20 10:30:01 +00:00
|
|
|
using Heimdall.Application.DTOs;
|
2026-07-22 19:54:55 +00:00
|
|
|
using Heimdall.Application.Events.Commands.CreateEvent;
|
|
|
|
|
using Heimdall.Application.Events.Commands.DeleteEvent;
|
|
|
|
|
using Heimdall.Application.Events.Queries.GetEvent;
|
|
|
|
|
using Heimdall.Application.Events.Queries.GetEvents;
|
|
|
|
|
using Heimdall.Application.Events.Queries.GetRecentByCamera;
|
2026-07-20 10:30:01 +00:00
|
|
|
using Heimdall.Domain.Enums;
|
|
|
|
|
using Heimdall.Infrastructure.Security;
|
2026-10-22 20:50:40 +02:00
|
|
|
using Heimdall.Infrastructure.Storage;
|
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-22 20:50:40 +02:00
|
|
|
using Microsoft.EntityFrameworkCore;
|
2026-07-20 10:30:01 +00:00
|
|
|
|
|
|
|
|
namespace Heimdall.Api.Controllers;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Camera detection events — motion, person, vehicle, face recognition, etc.
|
|
|
|
|
/// Agents POST events as they detect them; users GET filtered views.
|
|
|
|
|
/// </summary>
|
|
|
|
|
[ApiController]
|
|
|
|
|
[Route("api/events")]
|
|
|
|
|
[EnableRateLimiting("Api")]
|
|
|
|
|
public class EventsController : ControllerBase
|
|
|
|
|
{
|
2026-10-22 20:50:40 +02:00
|
|
|
private const int MaxSnapshotBytes = 2 * 1024 * 1024;
|
2026-07-22 19:54:55 +00:00
|
|
|
private readonly IMediator _mediator;
|
2026-10-22 20:50:40 +02:00
|
|
|
private readonly IApplicationDbContext _db;
|
|
|
|
|
private readonly ResourceAccess _access;
|
|
|
|
|
private readonly StorageProviderFactory _storage;
|
|
|
|
|
private readonly ILogger<EventsController> _logger;
|
2026-07-20 10:30:01 +00:00
|
|
|
|
2026-10-22 20:50:40 +02:00
|
|
|
public EventsController(IMediator mediator, IApplicationDbContext db, ResourceAccess access,
|
|
|
|
|
StorageProviderFactory storage, ILogger<EventsController> logger)
|
|
|
|
|
{
|
|
|
|
|
_mediator = mediator;
|
|
|
|
|
_db = db;
|
|
|
|
|
_access = access;
|
|
|
|
|
_storage = storage;
|
|
|
|
|
_logger = logger;
|
|
|
|
|
}
|
2026-07-20 10:30:01 +00:00
|
|
|
|
|
|
|
|
/// <summary>Record a new detection event (called by agents).</summary>
|
|
|
|
|
[Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)]
|
|
|
|
|
[HttpPost]
|
|
|
|
|
[ProducesResponseType(typeof(CameraEventResponse), StatusCodes.Status200OK)]
|
|
|
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
|
|
|
|
|
public async Task<IActionResult> Create([FromBody] CreateCameraEventRequest request, CancellationToken ct)
|
|
|
|
|
{
|
2026-10-22 20:50:40 +02:00
|
|
|
var requester = await _access.ResolveAsync(User, ct);
|
|
|
|
|
if (requester is null || requester.Kind != RequesterKind.Agent ||
|
|
|
|
|
!await _access.CameraAsync(requester, request.CameraId, ct)) return Forbid();
|
|
|
|
|
var command = new CreateEventCommand(request.CameraId, request.Type, request.Confidence, request.Label, request.MetadataJson, request.OccurredAt, request.EventId, request.PersonId, requester.Id);
|
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 single event 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(CameraEventResponse), StatusCodes.Status200OK)]
|
|
|
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
|
|
|
|
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
|
|
|
|
{
|
2026-08-27 20:28:41 +02:00
|
|
|
var userId = GetUserId();
|
|
|
|
|
var result = await _mediator.Send(new GetEventQuery(id, userId), ct);
|
2026-07-20 10:30:01 +00:00
|
|
|
return result.IsSuccess
|
|
|
|
|
? Ok(result.Data)
|
|
|
|
|
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Query events with filters. Supports pagination.</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]
|
|
|
|
|
[ProducesResponseType(typeof(PagedResult<CameraEventResponse>), StatusCodes.Status200OK)]
|
|
|
|
|
public async Task<IActionResult> Query(
|
|
|
|
|
[FromQuery] Guid? cameraId,
|
|
|
|
|
[FromQuery] Guid? siteId,
|
|
|
|
|
[FromQuery] string? type,
|
2026-08-10 21:48:53 +02:00
|
|
|
[FromQuery] string? q,
|
2026-07-20 10:30:01 +00:00
|
|
|
[FromQuery] DateTime? from,
|
|
|
|
|
[FromQuery] DateTime? to,
|
|
|
|
|
[FromQuery] double? minConfidence,
|
2026-10-20 07:32:56 +02:00
|
|
|
[FromQuery] bool hasSnapshot = false,
|
2026-07-20 10:30:01 +00:00
|
|
|
[FromQuery] int page = 1,
|
|
|
|
|
[FromQuery] int pageSize = 50,
|
2026-10-22 20:12:25 +02:00
|
|
|
[FromQuery] Guid? personId = null,
|
2026-07-20 10:30:01 +00:00
|
|
|
CancellationToken ct = default)
|
|
|
|
|
{
|
|
|
|
|
EventType? parsedType = null;
|
|
|
|
|
if (type is not null && Enum.TryParse<EventType>(type, true, out var t))
|
|
|
|
|
parsedType = t;
|
|
|
|
|
|
2026-08-27 20:28:41 +02:00
|
|
|
var userId = GetUserId();
|
2026-10-22 20:12:25 +02:00
|
|
|
var result = await _mediator.Send(new GetEventsQuery(cameraId, siteId, parsedType, from, to, minConfidence, page, pageSize, q, userId, hasSnapshot, personId), ct);
|
2026-07-20 10:30:01 +00:00
|
|
|
return Ok(result.Data);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Get recent events for a camera.</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("camera/{cameraId:guid}")]
|
|
|
|
|
[ProducesResponseType(typeof(List<CameraEventResponse>), StatusCodes.Status200OK)]
|
|
|
|
|
public async Task<IActionResult> GetRecentByCamera(Guid cameraId, [FromQuery] int count = 20, CancellationToken ct = default)
|
|
|
|
|
{
|
2026-08-27 20:28:41 +02:00
|
|
|
var userId = GetUserId();
|
|
|
|
|
var result = await _mediator.Send(new GetRecentByCameraQuery(cameraId, count, userId), ct);
|
2026-07-20 10:30:01 +00:00
|
|
|
return Ok(result.Data);
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-22 20:50:40 +02:00
|
|
|
/// <summary>Legacy URL attachment is retired; snapshots must be uploaded to managed storage.</summary>
|
2026-07-20 10:30:01 +00:00
|
|
|
[Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)]
|
|
|
|
|
[HttpPost("{id:guid}/snapshot")]
|
2026-10-22 20:50:40 +02:00
|
|
|
[ProducesResponseType(StatusCodes.Status410Gone)]
|
|
|
|
|
public IActionResult AttachSnapshot(Guid id) => StatusCode(StatusCodes.Status410Gone,
|
|
|
|
|
new { eventId = id, error = "Use PUT /api/events/{id}/snapshot/content with image/jpeg" });
|
|
|
|
|
|
|
|
|
|
/// <summary>Persist a bounded JPEG for an event from its assigned agent.</summary>
|
|
|
|
|
[Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)]
|
|
|
|
|
[HttpPut("{id:guid}/snapshot/content")]
|
|
|
|
|
[RequestSizeLimit(MaxSnapshotBytes)]
|
2026-07-20 10:30:01 +00:00
|
|
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
2026-10-22 20:50:40 +02:00
|
|
|
public async Task<IActionResult> UploadSnapshot(Guid id, CancellationToken ct)
|
2026-07-20 10:30:01 +00:00
|
|
|
{
|
2026-10-22 20:50:40 +02:00
|
|
|
var requester = await _access.ResolveAsync(User, ct);
|
|
|
|
|
if (requester is null || requester.Kind != RequesterKind.Agent ||
|
|
|
|
|
!await _access.EventUploadAsync(requester, id, ct)) return Forbid();
|
|
|
|
|
|
|
|
|
|
var ev = await _db.CameraEvents.FirstOrDefaultAsync(e => e.Id == id, ct);
|
|
|
|
|
if (ev is null) return NotFound();
|
2026-10-23 07:30:58 +02:00
|
|
|
if (ev.SnapshotObjectKey is not null)
|
|
|
|
|
{
|
|
|
|
|
await CompleteManualSnapshotRequestAsync(ev, ct);
|
|
|
|
|
return Ok(new { url = ev.SnapshotUrl });
|
|
|
|
|
}
|
2026-10-22 20:50:40 +02:00
|
|
|
|
|
|
|
|
var mediaType = Request.ContentType?.Split(';')[0].Trim();
|
|
|
|
|
if (!string.Equals(mediaType, "image/jpeg", StringComparison.OrdinalIgnoreCase))
|
|
|
|
|
return StatusCode(StatusCodes.Status415UnsupportedMediaType);
|
|
|
|
|
if (Request.ContentLength is > MaxSnapshotBytes)
|
|
|
|
|
return StatusCode(StatusCodes.Status413PayloadTooLarge);
|
|
|
|
|
|
|
|
|
|
using var payload = new MemoryStream();
|
|
|
|
|
var buffer = new byte[64 * 1024];
|
|
|
|
|
while (true)
|
|
|
|
|
{
|
|
|
|
|
var read = await Request.Body.ReadAsync(buffer, ct);
|
|
|
|
|
if (read == 0) break;
|
|
|
|
|
if (payload.Length + read > MaxSnapshotBytes)
|
|
|
|
|
return StatusCode(StatusCodes.Status413PayloadTooLarge);
|
|
|
|
|
payload.Write(buffer, 0, read);
|
|
|
|
|
}
|
|
|
|
|
var bytes = payload.ToArray();
|
|
|
|
|
if (bytes.Length < 4 || bytes[0] != 0xff || bytes[1] != 0xd8 ||
|
|
|
|
|
bytes[^2] != 0xff || bytes[^1] != 0xd9)
|
|
|
|
|
return BadRequest(new { error = "A complete JPEG image is required" });
|
|
|
|
|
|
|
|
|
|
var location = _storage.CaptureCurrentLocation();
|
|
|
|
|
var key = $"snapshots/{ev.CameraId:D}/{ev.Id:D}/{Guid.NewGuid():N}.jpg";
|
|
|
|
|
await using (var content = new MemoryStream(bytes, writable: false))
|
|
|
|
|
await _storage.UploadAsync(key, content, "image/jpeg", location, ct);
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
ev.SetStoredSnapshot(key, location);
|
2026-10-23 07:30:58 +02:00
|
|
|
var manualRequest = ev.Type == EventType.ManualSnapshot
|
|
|
|
|
? await _db.ManualSnapshotRequests.FirstOrDefaultAsync(r => r.Id == ev.Id && r.CameraId == ev.CameraId, ct)
|
|
|
|
|
: null;
|
|
|
|
|
manualRequest?.Complete(DateTime.UtcNow);
|
2026-10-22 20:50:40 +02:00
|
|
|
await _db.SaveChangesWithRetryAsync(ct: ct);
|
|
|
|
|
}
|
|
|
|
|
catch
|
|
|
|
|
{
|
|
|
|
|
try { await _storage.DeleteAsync(key, location, CancellationToken.None); }
|
|
|
|
|
catch (Exception cleanupError) { _logger.LogWarning(cleanupError, "Could not remove unreferenced snapshot for event {EventId}", id); }
|
|
|
|
|
throw;
|
|
|
|
|
}
|
|
|
|
|
return Ok(new { url = ev.SnapshotUrl });
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-23 07:30:58 +02:00
|
|
|
private async Task CompleteManualSnapshotRequestAsync(Heimdall.Domain.Entities.CameraEvent ev, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
if (ev.Type != EventType.ManualSnapshot) return;
|
|
|
|
|
var request = await _db.ManualSnapshotRequests
|
|
|
|
|
.FirstOrDefaultAsync(r => r.Id == ev.Id && r.CameraId == ev.CameraId, ct);
|
|
|
|
|
if (request is null || request.Status == ManualSnapshotStatus.Completed) return;
|
|
|
|
|
request.Complete(DateTime.UtcNow);
|
|
|
|
|
await _db.SaveChangesWithRetryAsync(ct: ct);
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-22 20:50:40 +02:00
|
|
|
/// <summary>Stream a stored JPEG only to a user allowed to read its camera.</summary>
|
|
|
|
|
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)]
|
|
|
|
|
[HttpGet("{id:guid}/snapshot/content")]
|
|
|
|
|
public async Task<IActionResult> DownloadSnapshot(Guid id, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
var requester = await _access.ResolveAsync(User, ct);
|
|
|
|
|
if (requester is null || requester.Kind != RequesterKind.Human ||
|
|
|
|
|
!await _access.EventAsync(requester, id, ct)) return Forbid();
|
|
|
|
|
|
|
|
|
|
var ev = await _db.CameraEvents.AsNoTracking().FirstOrDefaultAsync(e => e.Id == id, ct);
|
|
|
|
|
var location = ev?.GetSnapshotLocation();
|
|
|
|
|
if (ev?.SnapshotObjectKey is null || location is null) return NotFound();
|
|
|
|
|
var stream = await _storage.DownloadAsync(ev.SnapshotObjectKey, location, ct);
|
|
|
|
|
if (stream is null) return NotFound();
|
|
|
|
|
Response.Headers["Cache-Control"] = "private, no-store";
|
|
|
|
|
Response.Headers["X-Content-Type-Options"] = "nosniff";
|
|
|
|
|
return File(stream, "image/jpeg");
|
2026-07-20 10:30:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Delete an event.</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.Status200OK)]
|
|
|
|
|
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
|
|
|
|
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
|
|
|
|
{
|
2026-07-22 19:54:55 +00:00
|
|
|
var result = await _mediator.Send(new DeleteEventCommand(id), ct);
|
2026-07-20 10:30:01 +00:00
|
|
|
return result.IsSuccess
|
|
|
|
|
? Ok()
|
|
|
|
|
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
|
|
|
|
}
|
2026-08-27 20:28:41 +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
|
|
|
}
|