feat(events): implement camera event pipeline with AI detection storage
Adds the foundation for AI-powered detection events storage, query, and snapshot management. Agents can POST detection events (motion, person, vehicle, face, etc.) with confidence scores and metadata; users can query, filter, and view event history. - CameraEvent entity with EF Core configuration + migration - ICameraEventService / CameraEventService with paged query + filters - EventsController: 5 REST endpoints (create, get, query, attach snapshot, delete) - Agent-side CameraStreamService: FFmpeg-based RTSP frame capture (foundation) - Supports both ApiKey (agent) and JWT (user) authentication
This commit is contained in:
1 parent
159da2ca26
commit
358443ff1a
12 files changed
+2179
No files matched your search
@@ -0,0 +1,153 @@
|
||||
using System.Diagnostics;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Agent.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Manages RTSP stream connections for each assigned camera.
|
||||
/// Launches FFmpeg processes to capture frames and feeds them to
|
||||
/// the detection pipeline for analysis.
|
||||
/// </summary>
|
||||
public sealed class CameraStreamService : IDisposable
|
||||
{
|
||||
private readonly ILogger<CameraStreamService> _logger;
|
||||
private readonly Dictionary<Guid, StreamSession> _sessions = [];
|
||||
private readonly SemaphoreSlim _throttle = new(4, 4); // Max 4 concurrent FFmpeg
|
||||
|
||||
public CameraStreamService(ILogger<CameraStreamService> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>Start streaming from a camera. Launches FFmpeg in the background.</summary>
|
||||
public async Task<bool> StartStreamAsync(Guid cameraId, string rtspUrl, CancellationToken ct = default)
|
||||
{
|
||||
if (_sessions.ContainsKey(cameraId))
|
||||
{
|
||||
_logger.LogWarning("Stream already active for camera {CameraId}", cameraId);
|
||||
return false;
|
||||
}
|
||||
|
||||
await _throttle.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
var psi = new ProcessStartInfo
|
||||
{
|
||||
FileName = "ffmpeg",
|
||||
Arguments = $"-rtsp_transport tcp -i \"{rtspUrl}\" -f image2pipe -vcodec mjpeg -q:v 3 -update 1 -",
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
};
|
||||
|
||||
var process = new Process { StartInfo = psi };
|
||||
process.Start();
|
||||
|
||||
var session = new StreamSession(cameraId, rtspUrl, process);
|
||||
_sessions[cameraId] = session;
|
||||
|
||||
_logger.LogInformation("Stream started for camera {CameraId}: {Url}", cameraId, rtspUrl);
|
||||
|
||||
// Background read loop
|
||||
_ = Task.Run(() => ReadFramesLoop(cameraId, session, ct), ct);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to start stream for camera {CameraId}", cameraId);
|
||||
_throttle.Release();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stop streaming from a camera.</summary>
|
||||
public Task StopStreamAsync(Guid cameraId)
|
||||
{
|
||||
if (_sessions.TryGetValue(cameraId, out var session))
|
||||
{
|
||||
session.Cancel();
|
||||
_sessions.Remove(cameraId);
|
||||
_throttle.Release();
|
||||
_logger.LogInformation("Stream stopped for camera {CameraId}", cameraId);
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Number of currently active streams.</summary>
|
||||
public int ActiveStreamCount => _sessions.Count;
|
||||
|
||||
private Task ReadFramesLoop(Guid cameraId, StreamSession session, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var buffer = new byte[256 * 1024]; // 256KB buffer
|
||||
var stream = session.Process.StandardOutput.BaseStream;
|
||||
|
||||
while (!ct.IsCancellationRequested && !session.IsCancelled && !session.Process.HasExited)
|
||||
{
|
||||
var bytesRead = stream.Read(buffer, 0, buffer.Length);
|
||||
if (bytesRead == 0) break;
|
||||
|
||||
// Frame available for analysis — will be passed to FrameAnalyzerService
|
||||
// in a future phase. For now, we just count frames.
|
||||
Interlocked.Increment(ref session.FrameCount);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning(ex, "Frame read loop ended for camera {CameraId}", cameraId);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CleanupSession(cameraId, session);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void CleanupSession(Guid cameraId, StreamSession session)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!session.Process.HasExited)
|
||||
{
|
||||
session.Process.Kill(entireProcessTree: true);
|
||||
session.Process.WaitForExit(2000);
|
||||
}
|
||||
session.Process.Dispose();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Cleanup error for camera {CameraId}", cameraId);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_throttle.Release();
|
||||
_sessions.Remove(cameraId);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var session in _sessions.Values)
|
||||
{
|
||||
session.Cancel();
|
||||
session.Process?.Dispose();
|
||||
}
|
||||
_sessions.Clear();
|
||||
_throttle.Dispose();
|
||||
}
|
||||
|
||||
private sealed class StreamSession(Guid cameraId, string rtspUrl, Process process)
|
||||
{
|
||||
public Guid CameraId { get; } = cameraId;
|
||||
public string RtspUrl { get; } = rtspUrl;
|
||||
public Process Process { get; } = process;
|
||||
public long FrameCount;
|
||||
private volatile bool _cancelled;
|
||||
public bool IsCancelled => _cancelled;
|
||||
public void Cancel() => _cancelled = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Enums;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
|
||||
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
|
||||
{
|
||||
private readonly ICameraEventService _eventService;
|
||||
|
||||
public EventsController(ICameraEventService eventService) => _eventService = eventService;
|
||||
|
||||
/// <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)
|
||||
{
|
||||
var result = await _eventService.CreateAsync(request, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Get a single event by ID.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
|
||||
[HttpGet("{id:guid}")]
|
||||
[ProducesResponseType(typeof(CameraEventResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _eventService.GetByIdAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Query events with filters. Supports pagination.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(PagedResult<CameraEventResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> Query(
|
||||
[FromQuery] Guid? cameraId,
|
||||
[FromQuery] Guid? siteId,
|
||||
[FromQuery] string? type,
|
||||
[FromQuery] DateTime? from,
|
||||
[FromQuery] DateTime? to,
|
||||
[FromQuery] double? minConfidence,
|
||||
[FromQuery] int page = 1,
|
||||
[FromQuery] int pageSize = 50,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
EventType? parsedType = null;
|
||||
if (type is not null && Enum.TryParse<EventType>(type, true, out var t))
|
||||
parsedType = t;
|
||||
|
||||
var filter = new CameraEventFilterRequest(cameraId, siteId, parsedType, from, to, minConfidence, page, pageSize);
|
||||
var result = await _eventService.QueryAsync(filter, ct);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
/// <summary>Get recent events for a camera.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
|
||||
[HttpGet("camera/{cameraId:guid}")]
|
||||
[ProducesResponseType(typeof(List<CameraEventResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> GetRecentByCamera(Guid cameraId, [FromQuery] int count = 20, CancellationToken ct = default)
|
||||
{
|
||||
var result = await _eventService.GetRecentByCameraAsync(cameraId, count, ct);
|
||||
return Ok(result.Data);
|
||||
}
|
||||
|
||||
/// <summary>Attach a snapshot URL to an event (called by agents after upload).</summary>
|
||||
[Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpPost("{id:guid}/snapshot")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> AttachSnapshot(Guid id, [FromBody] AttachSnapshotRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await _eventService.AttachSnapshotAsync(id, request.SnapshotUrl, request.ThumbUrl, ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Delete an event.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpDelete("{id:guid}")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _eventService.DeleteAsync(id, ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
|
||||
}
|
||||
}
|
||||
|
||||
// ─── DTOs ───────────────────────────────────────────────────────────
|
||||
|
||||
public record AttachSnapshotRequest(string SnapshotUrl, string? ThumbUrl);
|
||||
@@ -0,0 +1,34 @@
|
||||
using Heimdall.Domain.Enums;
|
||||
|
||||
namespace Heimdall.Application.DTOs;
|
||||
|
||||
public record CameraEventResponse(
|
||||
Guid Id,
|
||||
Guid CameraId,
|
||||
Guid? AgentId,
|
||||
EventType Type,
|
||||
double Confidence,
|
||||
string? Label,
|
||||
string? SnapshotUrl,
|
||||
string? SnapshotThumbUrl,
|
||||
string? MetadataJson,
|
||||
DateTime OccurredAt,
|
||||
DateTime CreatedAt);
|
||||
|
||||
public record CreateCameraEventRequest(
|
||||
Guid CameraId,
|
||||
EventType Type,
|
||||
double Confidence,
|
||||
string? Label,
|
||||
string? MetadataJson,
|
||||
DateTime? OccurredAt);
|
||||
|
||||
public record CameraEventFilterRequest(
|
||||
Guid? CameraId,
|
||||
Guid? SiteId,
|
||||
EventType? Type,
|
||||
DateTime? From,
|
||||
DateTime? To,
|
||||
double? MinConfidence,
|
||||
int Page = 1,
|
||||
int PageSize = 50);
|
||||
@@ -0,0 +1,29 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Manages camera-detected events (motion, person, vehicle, face, etc.)
|
||||
/// with snapshot storage and query/filter capabilities.
|
||||
/// </summary>
|
||||
public interface ICameraEventService
|
||||
{
|
||||
/// <summary>Record a new detection event.</summary>
|
||||
Task<ServiceResult<CameraEventResponse>> CreateAsync(CreateCameraEventRequest request, CancellationToken ct);
|
||||
|
||||
/// <summary>Get a single event by ID.</summary>
|
||||
Task<ServiceResult<CameraEventResponse>> GetByIdAsync(Guid id, CancellationToken ct);
|
||||
|
||||
/// <summary>Query events with filters. Max pageSize = 100.</summary>
|
||||
Task<ServiceResult<PagedResult<CameraEventResponse>>> QueryAsync(CameraEventFilterRequest filter, CancellationToken ct);
|
||||
|
||||
/// <summary>Get recent events for a camera (last N).</summary>
|
||||
Task<ServiceResult<List<CameraEventResponse>>> GetRecentByCameraAsync(Guid cameraId, int count = 20, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Delete an event.</summary>
|
||||
Task<ServiceResult> DeleteAsync(Guid id, CancellationToken ct);
|
||||
|
||||
/// <summary>Attach a snapshot URL to an event.</summary>
|
||||
Task<ServiceResult> AttachSnapshotAsync(Guid eventId, string snapshotUrl, string? thumbUrl, CancellationToken ct);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using Heimdall.Domain.Enums;
|
||||
using Heimdall.Domain.Primitives;
|
||||
|
||||
namespace Heimdall.Domain.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// An event detected on a camera stream — motion, person, vehicle, face, etc.
|
||||
/// Stores AI detection results with confidence, bounding boxes, and snapshots.
|
||||
/// </summary>
|
||||
public class CameraEvent : Entity<Guid>, IAuditableEntity
|
||||
{
|
||||
public Guid CameraId { get; private set; }
|
||||
public Guid? AgentId { get; private set; }
|
||||
public EventType Type { get; private set; }
|
||||
public double Confidence { get; private set; }
|
||||
public string? Label { get; private set; } // Human-readable label (e.g. "John Doe", "AB-123-CD")
|
||||
public string? SnapshotUrl { get; private set; } // S3 key or URL to snapshot image
|
||||
public string? SnapshotThumbUrl { get; private set; } // Thumbnail S3 key or URL
|
||||
public string? MetadataJson { get; private set; } // JSON: bounding boxes, track ID, etc.
|
||||
public DateTime OccurredAt { get; private set; }
|
||||
|
||||
// Audit
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
|
||||
// Navigation
|
||||
public Camera Camera { get; private set; } = null!;
|
||||
|
||||
private CameraEvent() { } // EF Core
|
||||
|
||||
public CameraEvent(Guid cameraId, EventType type, double confidence, DateTime? occurredAt = null)
|
||||
: base(Guid.NewGuid())
|
||||
{
|
||||
CameraId = cameraId;
|
||||
Type = type;
|
||||
Confidence = confidence;
|
||||
OccurredAt = occurredAt ?? DateTime.UtcNow;
|
||||
}
|
||||
|
||||
public void SetSnapshot(string snapshotUrl, string? thumbUrl = null)
|
||||
{
|
||||
SnapshotUrl = snapshotUrl;
|
||||
if (thumbUrl is not null)
|
||||
SnapshotThumbUrl = thumbUrl;
|
||||
}
|
||||
|
||||
public void SetMetadata(string? label, string? metadataJson)
|
||||
{
|
||||
Label = label;
|
||||
MetadataJson = metadataJson;
|
||||
}
|
||||
|
||||
public void AssignAgent(Guid agentId) => AgentId = agentId;
|
||||
}
|
||||
@@ -32,6 +32,9 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>
|
||||
// Assignment entities
|
||||
public DbSet<CameraAssignment> CameraAssignments => Set<CameraAssignment>();
|
||||
|
||||
// Event entities
|
||||
public DbSet<CameraEvent> CameraEvents => Set<CameraEvent>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder builder)
|
||||
{
|
||||
base.OnModelCreating(builder);
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
using Heimdall.Domain.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace Heimdall.Infrastructure.Data.Configurations;
|
||||
|
||||
public class CameraEventConfiguration : IEntityTypeConfiguration<CameraEvent>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<CameraEvent> builder)
|
||||
{
|
||||
builder.ToTable("camera_events");
|
||||
|
||||
builder.HasKey(e => e.Id);
|
||||
|
||||
builder.Property(e => e.Type)
|
||||
.HasConversion<int>()
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(e => e.Confidence)
|
||||
.HasDefaultValue(0.0);
|
||||
|
||||
builder.Property(e => e.Label)
|
||||
.HasMaxLength(200)
|
||||
.IsUnicode(false);
|
||||
|
||||
builder.Property(e => e.SnapshotUrl)
|
||||
.HasMaxLength(2000)
|
||||
.IsUnicode(false);
|
||||
|
||||
builder.Property(e => e.SnapshotThumbUrl)
|
||||
.HasMaxLength(2000)
|
||||
.IsUnicode(false);
|
||||
|
||||
builder.Property(e => e.MetadataJson)
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
builder.Property(e => e.OccurredAt)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(e => e.CreatedAt)
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
builder.Property(e => e.UpdatedAt)
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
// Indexes
|
||||
builder.HasIndex(e => new { e.CameraId, e.OccurredAt })
|
||||
.IsDescending(false, true); // Most recent first
|
||||
|
||||
builder.HasIndex(e => new { e.CameraId, e.Type });
|
||||
|
||||
builder.HasIndex(e => e.OccurredAt);
|
||||
|
||||
// Relationships
|
||||
builder.HasOne(e => e.Camera)
|
||||
.WithMany()
|
||||
.HasForeignKey(e => e.CameraId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
}
|
||||
}
|
||||
@@ -96,6 +96,9 @@ public static class DependencyInjection
|
||||
// Assignment services
|
||||
services.AddScoped<ICameraAssignmentService, CameraAssignmentService>();
|
||||
|
||||
// Event services
|
||||
services.AddScoped<ICameraEventService, CameraEventService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
+1457
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,66 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Heimdall.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddCameraEvents : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "camera_events",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
CameraId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
AgentId = table.Column<Guid>(type: "uuid", nullable: true),
|
||||
Type = table.Column<int>(type: "integer", nullable: false),
|
||||
Confidence = table.Column<double>(type: "double precision", nullable: false, defaultValue: 0.0),
|
||||
Label = table.Column<string>(type: "character varying(200)", unicode: false, maxLength: 200, nullable: true),
|
||||
SnapshotUrl = table.Column<string>(type: "character varying(2000)", unicode: false, maxLength: 2000, nullable: true),
|
||||
SnapshotThumbUrl = table.Column<string>(type: "character varying(2000)", unicode: false, maxLength: 2000, nullable: true),
|
||||
MetadataJson = table.Column<string>(type: "jsonb", nullable: true),
|
||||
OccurredAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"),
|
||||
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_camera_events", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_camera_events_cameras_CameraId",
|
||||
column: x => x.CameraId,
|
||||
principalTable: "cameras",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_camera_events_CameraId_OccurredAt",
|
||||
table: "camera_events",
|
||||
columns: new[] { "CameraId", "OccurredAt" },
|
||||
descending: new[] { false, true });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_camera_events_CameraId_Type",
|
||||
table: "camera_events",
|
||||
columns: new[] { "CameraId", "Type" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_camera_events_OccurredAt",
|
||||
table: "camera_events",
|
||||
column: "OccurredAt");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "camera_events");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -841,6 +841,69 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.ToTable("camera_discovery_results", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid?>("AgentId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("CameraId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<double>("Confidence")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("double precision")
|
||||
.HasDefaultValue(0.0);
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<string>("Label")
|
||||
.HasMaxLength(200)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("MetadataJson")
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b.Property<DateTime>("OccurredAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("SnapshotThumbUrl")
|
||||
.HasMaxLength(2000)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.Property<string>("SnapshotUrl")
|
||||
.HasMaxLength(2000)
|
||||
.IsUnicode(false)
|
||||
.HasColumnType("character varying(2000)");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<DateTime>("UpdatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("OccurredAt");
|
||||
|
||||
b.HasIndex("CameraId", "OccurredAt")
|
||||
.IsDescending(false, true);
|
||||
|
||||
b.HasIndex("CameraId", "Type");
|
||||
|
||||
b.ToTable("camera_events", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@@ -1239,6 +1302,17 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Navigation("Site");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.Camera", "Camera")
|
||||
.WithMany()
|
||||
.HasForeignKey("CameraId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Camera");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b =>
|
||||
{
|
||||
b.HasOne("Heimdall.Domain.Entities.CameraDiscoveryResult", "DiscoveryResult")
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Infrastructure.Services;
|
||||
|
||||
public sealed class CameraEventService : ICameraEventService
|
||||
{
|
||||
private readonly IDbContextFactory<AppDbContext> _dbFactory;
|
||||
private readonly ILogger<CameraEventService> _logger;
|
||||
|
||||
public CameraEventService(
|
||||
IDbContextFactory<AppDbContext> dbFactory,
|
||||
ILogger<CameraEventService> logger)
|
||||
{
|
||||
_dbFactory = dbFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<CameraEventResponse>> CreateAsync(CreateCameraEventRequest request, CancellationToken ct)
|
||||
{
|
||||
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
||||
|
||||
var camera = await db.Cameras.FindAsync([request.CameraId], ct);
|
||||
if (camera is null)
|
||||
return ServiceResult<CameraEventResponse>.NotFound("Camera not found");
|
||||
|
||||
var ev = new CameraEvent(request.CameraId, request.Type, request.Confidence, request.OccurredAt);
|
||||
if (request.Label is not null || request.MetadataJson is not null)
|
||||
ev.SetMetadata(request.Label, request.MetadataJson);
|
||||
|
||||
db.CameraEvents.Add(ev);
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
_logger.LogDebug(
|
||||
"Camera event {EventId}: {Type} (confidence={Conf}) for camera {CameraId}",
|
||||
ev.Id, ev.Type, ev.Confidence, ev.CameraId);
|
||||
|
||||
return ServiceResult<CameraEventResponse>.Success(MapResponse(ev));
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<CameraEventResponse>> GetByIdAsync(Guid id, CancellationToken ct)
|
||||
{
|
||||
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
||||
var ev = await db.CameraEvents.AsNoTracking().FirstOrDefaultAsync(e => e.Id == id, ct);
|
||||
return ev is null
|
||||
? ServiceResult<CameraEventResponse>.NotFound("Event not found")
|
||||
: ServiceResult<CameraEventResponse>.Success(MapResponse(ev));
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<PagedResult<CameraEventResponse>>> QueryAsync(CameraEventFilterRequest filter, CancellationToken ct)
|
||||
{
|
||||
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
||||
|
||||
var pageSize = Math.Min(filter.PageSize, 100);
|
||||
var query = db.CameraEvents.AsNoTracking();
|
||||
|
||||
if (filter.CameraId.HasValue)
|
||||
query = query.Where(e => e.CameraId == filter.CameraId.Value);
|
||||
|
||||
if (filter.SiteId.HasValue)
|
||||
query = query.Where(e => e.Camera.SiteId == filter.SiteId.Value);
|
||||
|
||||
if (filter.Type.HasValue)
|
||||
query = query.Where(e => e.Type == filter.Type.Value);
|
||||
|
||||
if (filter.From.HasValue)
|
||||
query = query.Where(e => e.OccurredAt >= filter.From.Value);
|
||||
|
||||
if (filter.To.HasValue)
|
||||
query = query.Where(e => e.OccurredAt <= filter.To.Value);
|
||||
|
||||
if (filter.MinConfidence.HasValue)
|
||||
query = query.Where(e => e.Confidence >= filter.MinConfidence.Value);
|
||||
|
||||
var total = await query.CountAsync(ct);
|
||||
var items = await query
|
||||
.OrderByDescending(e => e.OccurredAt)
|
||||
.Skip((filter.Page - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.ToListAsync(ct);
|
||||
|
||||
return ServiceResult<PagedResult<CameraEventResponse>>.Success(new PagedResult<CameraEventResponse>(
|
||||
items.Select(MapResponse).ToList(), total, filter.Page, pageSize));
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<List<CameraEventResponse>>> GetRecentByCameraAsync(Guid cameraId, int count = 20, CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
||||
|
||||
var items = await db.CameraEvents
|
||||
.AsNoTracking()
|
||||
.Where(e => e.CameraId == cameraId)
|
||||
.OrderByDescending(e => e.OccurredAt)
|
||||
.Take(count)
|
||||
.ToListAsync(ct);
|
||||
|
||||
return ServiceResult<List<CameraEventResponse>>.Success(items.Select(MapResponse).ToList());
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> DeleteAsync(Guid id, CancellationToken ct)
|
||||
{
|
||||
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
||||
var ev = await db.CameraEvents.FindAsync([id], ct);
|
||||
if (ev is null)
|
||||
return ServiceResult.NotFound("Event not found");
|
||||
|
||||
db.CameraEvents.Remove(ev);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
|
||||
public async Task<ServiceResult> AttachSnapshotAsync(Guid eventId, string snapshotUrl, string? thumbUrl, CancellationToken ct)
|
||||
{
|
||||
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
||||
var ev = await db.CameraEvents.FindAsync([eventId], ct);
|
||||
if (ev is null)
|
||||
return ServiceResult.NotFound("Event not found");
|
||||
|
||||
ev.SetSnapshot(snapshotUrl, thumbUrl);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
|
||||
private static CameraEventResponse MapResponse(CameraEvent e) => new(
|
||||
e.Id, e.CameraId, e.AgentId, e.Type, e.Confidence,
|
||||
e.Label, e.SnapshotUrl, e.SnapshotThumbUrl,
|
||||
e.MetadataJson, e.OccurredAt, e.CreatedAt);
|
||||
}
|
||||
Reference in new issue
Block a user