using System.Security.Claims; using Heimdall.Api.Security; using Heimdall.Application.Common; using Heimdall.Application.DTOs; 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; using Heimdall.Domain.Enums; using Heimdall.Infrastructure.Security; using Heimdall.Infrastructure.Storage; using ImageMagick; using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; using Microsoft.EntityFrameworkCore; namespace Heimdall.Api.Controllers; /// /// Camera detection events — motion, person, vehicle, face recognition, etc. /// Agents POST events as they detect them; users GET filtered views. /// [ApiController] [Route("api/events")] [EnableRateLimiting("Api")] public class EventsController : ControllerBase { private const int MaxSnapshotBytes = 2 * 1024 * 1024; private readonly IMediator _mediator; private readonly IApplicationDbContext _db; private readonly ResourceAccess _access; private readonly StorageProviderFactory _storage; private readonly ILogger _logger; public EventsController(IMediator mediator, IApplicationDbContext db, ResourceAccess access, StorageProviderFactory storage, ILogger logger) { _mediator = mediator; _db = db; _access = access; _storage = storage; _logger = logger; } /// Record a new detection event (called by agents). [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] [HttpPost] [ProducesResponseType(typeof(CameraEventResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task Create([FromBody] CreateCameraEventRequest request, CancellationToken ct) { 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); var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } /// Get a single event by ID. [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] [HttpGet("{id:guid}")] [ProducesResponseType(typeof(CameraEventResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task GetById(Guid id, CancellationToken ct) { var userId = GetUserId(); var result = await _mediator.Send(new GetEventQuery(id, userId), ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); } /// Query events with filters. Supports pagination. [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] [HttpGet] [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] public async Task Query( [FromQuery] Guid? cameraId, [FromQuery] Guid? siteId, [FromQuery] string? type, [FromQuery] string? q, [FromQuery] DateTime? from, [FromQuery] DateTime? to, [FromQuery] double? minConfidence, [FromQuery] bool hasSnapshot = false, [FromQuery] int page = 1, [FromQuery] int pageSize = 50, [FromQuery] Guid? personId = null, CancellationToken ct = default) { EventType? parsedType = null; if (type is not null && Enum.TryParse(type, true, out var t)) parsedType = t; var userId = GetUserId(); var result = await _mediator.Send(new GetEventsQuery(cameraId, siteId, parsedType, from, to, minConfidence, page, pageSize, q, userId, hasSnapshot, personId), ct); return Ok(result.Data); } /// Get recent events for a camera. [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] [HttpGet("camera/{cameraId:guid}")] [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] public async Task GetRecentByCamera(Guid cameraId, [FromQuery] int count = 20, CancellationToken ct = default) { var userId = GetUserId(); var result = await _mediator.Send(new GetRecentByCameraQuery(cameraId, count, userId), ct); return Ok(result.Data); } /// Legacy URL attachment is retired; snapshots must be uploaded to managed storage. [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] [HttpPost("{id:guid}/snapshot")] [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" }); /// Persist a bounded JPEG for an event from its assigned agent. [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] [HttpPut("{id:guid}/snapshot/content")] [RequestSizeLimit(MaxSnapshotBytes)] [ProducesResponseType(StatusCodes.Status200OK)] public async Task UploadSnapshot(Guid id, CancellationToken ct) { 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(); if (ev.SnapshotObjectKey is not null) { await CompleteManualSnapshotRequestAsync(ev, ct); return Ok(new { url = ev.SnapshotUrl }); } 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" }); byte[] thumbnail; try { // Inspect dimensions before decoding pixels: a small compressed JPEG // can otherwise request an excessive amount of native memory. var info = new MagickImageInfo(bytes); if (info.Format != MagickFormat.Jpeg || info.Width > 8192 || info.Height > 8192 || (long)info.Width * info.Height > 32_000_000) return BadRequest(new { error = "Image dimensions exceed the allowed limit" }); using var image = new MagickImage(bytes); if (image.Width > 8192 || image.Height > 8192 || (long)image.Width * image.Height > 32_000_000) return BadRequest(new { error = "Image dimensions exceed the allowed limit" }); image.AutoOrient(); image.Resize(new MagickGeometry(320, 180)); image.Strip(); image.Quality = 75; thumbnail = image.ToByteArray(MagickFormat.Jpeg); } catch (MagickException) { return BadRequest(new { error = "A decodable JPEG image is required" }); } var location = _storage.CaptureCurrentLocation(); var baseKey = $"snapshots/{ev.CameraId:D}/{ev.Id:D}/{Guid.NewGuid():N}"; var key = baseKey + ".jpg"; var thumbKey = baseKey + ".thumb.jpg"; var uploaded = new List(2); try { await using (var content = new MemoryStream(bytes, writable: false)) await _storage.UploadAsync(key, content, "image/jpeg", location, ct); uploaded.Add(key); await using (var content = new MemoryStream(thumbnail, writable: false)) await _storage.UploadAsync(thumbKey, content, "image/jpeg", location, ct); uploaded.Add(thumbKey); ev.SetStoredSnapshot(key, location, thumbKey); 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); await _db.SaveChangesWithRetryAsync(ct: ct); } catch { try { await _storage.DeleteBatchAsync(uploaded, 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 }); } 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); } /// Stream a stored JPEG only to a user allowed to read its camera. [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] [HttpGet("{id:guid}/snapshot/content")] public async Task 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"); } /// Stream a stored JPEG thumbnail under the same camera access check as the original. [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] [HttpGet("{id:guid}/snapshot/thumbnail")] public async Task DownloadSnapshotThumbnail(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?.SnapshotThumbObjectKey is null || location is null) return NotFound(); var stream = await _storage.DownloadAsync(ev.SnapshotThumbObjectKey, 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"); } /// Delete an event. [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)] [HttpDelete("{id:guid}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task Delete(Guid id, CancellationToken ct) { var result = await _mediator.Send(new DeleteEventCommand(id), ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 404, 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; } }