2026-07-19 12:55:05 +00:00
|
|
|
using Heimdall.Application.Common;
|
|
|
|
|
using Heimdall.Application.DTOs;
|
2026-08-20 18:22:37 +02:00
|
|
|
using Heimdall.Application.Metrics;
|
2026-07-19 12:55:05 +00:00
|
|
|
using Heimdall.Application.Services;
|
|
|
|
|
using Heimdall.Domain.Entities;
|
|
|
|
|
using Heimdall.Infrastructure.Data;
|
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
2026-07-19 15:24:52 +00:00
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
2026-07-19 12:55:05 +00:00
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
|
|
|
|
|
namespace Heimdall.Infrastructure.Services;
|
|
|
|
|
|
|
|
|
|
public sealed class CameraEventService : ICameraEventService
|
|
|
|
|
{
|
|
|
|
|
private readonly IDbContextFactory<AppDbContext> _dbFactory;
|
2026-07-19 15:24:52 +00:00
|
|
|
private readonly IServiceProvider _serviceProvider;
|
2026-07-19 12:55:05 +00:00
|
|
|
private readonly ILogger<CameraEventService> _logger;
|
|
|
|
|
|
|
|
|
|
public CameraEventService(
|
|
|
|
|
IDbContextFactory<AppDbContext> dbFactory,
|
2026-07-19 15:24:52 +00:00
|
|
|
IServiceProvider serviceProvider,
|
2026-07-19 12:55:05 +00:00
|
|
|
ILogger<CameraEventService> logger)
|
|
|
|
|
{
|
|
|
|
|
_dbFactory = dbFactory;
|
2026-07-19 15:24:52 +00:00
|
|
|
_serviceProvider = serviceProvider;
|
2026-07-19 12:55:05 +00:00
|
|
|
_logger = logger;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<ServiceResult<CameraEventResponse>> CreateAsync(CreateCameraEventRequest request, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
2026-10-22 19:24:18 +02:00
|
|
|
var occurredAt = CameraEvent.NormalizeOccurredAt(request.OccurredAt ?? DateTime.UtcNow);
|
|
|
|
|
var eventId = request.EventId ?? Guid.NewGuid();
|
2026-07-19 12:55:05 +00:00
|
|
|
|
2026-07-27 18:59:12 +00:00
|
|
|
var camera = await db.Cameras.FindAsync([request.CameraId], ct).ConfigureAwait(false);
|
2026-07-19 12:55:05 +00:00
|
|
|
if (camera is null)
|
|
|
|
|
return ServiceResult<CameraEventResponse>.NotFound("Camera not found");
|
|
|
|
|
|
2026-10-22 19:24:18 +02:00
|
|
|
if (request.EventId.HasValue)
|
|
|
|
|
{
|
|
|
|
|
var existing = await db.CameraEvents.Include(e => e.Camera)
|
|
|
|
|
.FirstOrDefaultAsync(e => e.Id == eventId && e.OccurredAt == occurredAt, ct)
|
|
|
|
|
.ConfigureAwait(false);
|
|
|
|
|
if (existing is not null)
|
|
|
|
|
return ServiceResult<CameraEventResponse>.Success(MapResponse(existing));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var ev = new CameraEvent(request.CameraId, request.Type, request.Confidence, occurredAt, eventId);
|
2026-07-19 12:55:05 +00:00
|
|
|
if (request.Label is not null || request.MetadataJson is not null)
|
|
|
|
|
ev.SetMetadata(request.Label, request.MetadataJson);
|
|
|
|
|
|
|
|
|
|
db.CameraEvents.Add(ev);
|
2026-10-22 19:24:18 +02:00
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
|
|
|
|
}
|
|
|
|
|
catch (DbUpdateException) when (request.EventId.HasValue)
|
|
|
|
|
{
|
|
|
|
|
db.Entry(ev).State = EntityState.Detached;
|
|
|
|
|
var duplicate = await db.CameraEvents.AsNoTracking().Include(e => e.Camera)
|
|
|
|
|
.FirstOrDefaultAsync(e => e.Id == eventId && e.OccurredAt == occurredAt, ct)
|
|
|
|
|
.ConfigureAwait(false);
|
|
|
|
|
if (duplicate is null) throw;
|
|
|
|
|
return ServiceResult<CameraEventResponse>.Success(MapResponse(duplicate));
|
|
|
|
|
}
|
2026-07-19 12:55:05 +00:00
|
|
|
|
|
|
|
|
_logger.LogDebug(
|
|
|
|
|
"Camera event {EventId}: {Type} (confidence={Conf}) for camera {CameraId}",
|
|
|
|
|
ev.Id, ev.Type, ev.Confidence, ev.CameraId);
|
|
|
|
|
|
2026-08-20 18:22:37 +02:00
|
|
|
// Record metric: event created (spec 13.1)
|
|
|
|
|
HeimdallMetrics.RecordEventCreated(
|
|
|
|
|
ev.Type.ToString(),
|
|
|
|
|
ev.CameraId,
|
|
|
|
|
camera.SiteId);
|
|
|
|
|
|
2026-07-19 19:58:45 +00:00
|
|
|
// Fire-and-forget broadcast to connected SignalR clients.
|
|
|
|
|
// Use CancellationToken.None — the broadcast must outlive the HTTP request
|
|
|
|
|
// lifecycle so SignalR clients receive the notification even after the
|
|
|
|
|
// response is sent.
|
2026-07-19 15:24:52 +00:00
|
|
|
_ = Task.Run(async () =>
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
using var scope = _serviceProvider.CreateScope();
|
|
|
|
|
var broadcast = scope.ServiceProvider.GetRequiredService<IEventBroadcastService>();
|
2026-07-27 18:59:12 +00:00
|
|
|
await broadcast.NotifyEventCreated(MapResponse(ev), CancellationToken.None).ConfigureAwait(false);
|
2026-07-19 15:24:52 +00:00
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogWarning(ex, "Failed to broadcast event {EventId}", ev.Id);
|
|
|
|
|
}
|
2026-07-19 19:58:45 +00:00
|
|
|
}, CancellationToken.None);
|
2026-07-19 15:24:52 +00:00
|
|
|
|
2026-07-19 12:55:05 +00:00
|
|
|
return ServiceResult<CameraEventResponse>.Success(MapResponse(ev));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<ServiceResult<CameraEventResponse>> GetByIdAsync(Guid id, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
2026-07-27 18:59:12 +00:00
|
|
|
var ev = await db.CameraEvents.AsNoTracking().Include(e => e.Camera).FirstOrDefaultAsync(e => e.Id == id, ct).ConfigureAwait(false);
|
2026-07-19 12:55:05 +00:00
|
|
|
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);
|
2026-07-19 20:53:48 +00:00
|
|
|
IQueryable<CameraEvent> query = db.CameraEvents.AsNoTracking().Include(e => e.Camera);
|
2026-07-19 12:55:05 +00:00
|
|
|
|
|
|
|
|
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);
|
|
|
|
|
|
2026-07-27 18:59:12 +00:00
|
|
|
var total = await query.CountAsync(ct).ConfigureAwait(false);
|
2026-07-19 12:55:05 +00:00
|
|
|
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()
|
2026-07-19 20:53:48 +00:00
|
|
|
.Include(e => e.Camera)
|
2026-07-19 12:55:05 +00:00
|
|
|
.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);
|
2026-08-27 00:31:12 +02:00
|
|
|
var ev = await db.CameraEvents.FirstOrDefaultAsync(e => e.Id == id, ct).ConfigureAwait(false);
|
2026-07-19 12:55:05 +00:00
|
|
|
if (ev is null)
|
|
|
|
|
return ServiceResult.NotFound("Event not found");
|
|
|
|
|
|
|
|
|
|
db.CameraEvents.Remove(ev);
|
2026-07-27 18:59:12 +00:00
|
|
|
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
2026-07-19 12:55:05 +00:00
|
|
|
return ServiceResult.Success();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<ServiceResult> AttachSnapshotAsync(Guid eventId, string snapshotUrl, string? thumbUrl, CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
2026-08-27 00:31:12 +02:00
|
|
|
var ev = await db.CameraEvents.FirstOrDefaultAsync(e => e.Id == eventId, ct).ConfigureAwait(false);
|
2026-07-19 12:55:05 +00:00
|
|
|
if (ev is null)
|
|
|
|
|
return ServiceResult.NotFound("Event not found");
|
|
|
|
|
|
|
|
|
|
ev.SetSnapshot(snapshotUrl, thumbUrl);
|
2026-07-27 18:59:12 +00:00
|
|
|
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
2026-07-19 12:55:05 +00:00
|
|
|
return ServiceResult.Success();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static CameraEventResponse MapResponse(CameraEvent e) => new(
|
2026-07-19 20:53:48 +00:00
|
|
|
e.Id, e.CameraId, e.Camera.SiteId, e.AgentId, e.Type, e.Confidence,
|
2026-07-19 12:55:05 +00:00
|
|
|
e.Label, e.SnapshotUrl, e.SnapshotThumbUrl,
|
|
|
|
|
e.MetadataJson, e.OccurredAt, e.CreatedAt);
|
|
|
|
|
}
|