feat(cqrs): migrate Events, Agents, Assignments, Discovery, Others to CQRS

- Events: CRUD commands/queries + EventCreatedNotification for SignalR
- Agents: Register (with API key gen), Heartbeat, queries
- Assignments: Assign, Failover, Release commands + queries
- Discovery: 10 handlers delegating to existing probes/services
- Groups/Persons/Settings/Audit/Stats: full CQRS for remaining domains
- Extend IApplicationDbContext with all DbSets
This commit is contained in:
Arnaud Dartois committed 2026-07-22 19:48:16 +00:00
1 parent 11f7fd8d20
commit c1b3b3d3b4
74 files changed
+1981 -2

No files matched your search

@@ -0,0 +1,13 @@
using Heimdall.Application.Common;
using Heimdall.Domain.Enums;
using MediatR;
namespace Heimdall.Application.Agents.Commands.Heartbeat;
public record HeartbeatCommand(
Guid AgentId,
string? PublicIp,
bool? HasGpu,
int? CpuCores,
int? MemoryMb,
GpuAcceleration? GpuType) : IRequest<ServiceResult>;
@@ -0,0 +1,34 @@
using Heimdall.Application.Common;
using Heimdall.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Agents.Commands.Heartbeat;
public class HeartbeatHandler : IRequestHandler<HeartbeatCommand, ServiceResult>
{
private readonly IApplicationDbContext _db;
public HeartbeatHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult> Handle(HeartbeatCommand request, CancellationToken ct)
{
var agent = await _db.Agents.FirstOrDefaultAsync(a => a.Id == request.AgentId, ct);
if (agent is null)
return ServiceResult.NotFound("Agent not found");
agent.UpdateHeartbeat(request.PublicIp);
if (request.HasGpu.HasValue || request.CpuCores.HasValue || request.MemoryMb.HasValue || request.GpuType.HasValue)
{
agent.UpdateCapabilities(
request.HasGpu ?? false,
request.CpuCores ?? 0,
request.MemoryMb ?? 0,
request.GpuType ?? GpuAcceleration.None);
}
await _db.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult.Success();
}
}
@@ -0,0 +1,11 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
namespace Heimdall.Application.Agents.Commands.RegisterAgent;
public record RegisterAgentCommand(
string Token,
string Hostname,
string? Version,
string? PublicIp) : IRequest<ServiceResult<RegisterAgentResponse>>;
@@ -0,0 +1,60 @@
using System.Security.Cryptography;
using System.Text;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Agents.Commands.RegisterAgent;
public class RegisterAgentHandler : IRequestHandler<RegisterAgentCommand, ServiceResult<RegisterAgentResponse>>
{
private readonly IApplicationDbContext _db;
public RegisterAgentHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<RegisterAgentResponse>> Handle(RegisterAgentCommand request, CancellationToken ct)
{
var tokenHash = Convert.ToHexString(
SHA256.HashData(Encoding.UTF8.GetBytes(request.Token))).ToLowerInvariant();
var site = await _db.Sites
.FirstOrDefaultAsync(s => s.RegistrationTokenHash == tokenHash
&& s.TokenExpiresAt > DateTime.UtcNow, ct);
if (site is null)
return ServiceResult<RegisterAgentResponse>.Unauthorized("Invalid or expired registration token");
var existing = await _db.Agents
.AnyAsync(a => a.SiteId == site.Id && a.Hostname == request.Hostname, ct);
if (existing)
return ServiceResult<RegisterAgentResponse>.Conflict(
"An agent with this hostname is already registered for this site");
var keyBytes = new byte[32];
RandomNumberGenerator.Fill(keyBytes);
var plainKey = Convert.ToHexString(keyBytes).ToLowerInvariant();
var prefix = plainKey[..8];
var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(plainKey))).ToLowerInvariant();
var agent = new Agent(site.Id, request.Hostname, request.Hostname, request.Version ?? "unknown");
agent.Register(hash, prefix);
agent.UpdateHeartbeat(request.PublicIp);
_db.Agents.Add(agent);
var apiKeyEntity = new ApiKey(hash, prefix, site.Id);
_db.ApiKeys.Add(apiKeyEntity);
site.ClearRegistrationToken();
_db.AuditLogs.Add(new AuditLog(null, "Agent.Registered", "Agent",
agent.Id.ToString(), ipAddress: request.PublicIp));
await _db.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult<RegisterAgentResponse>.Success(
new RegisterAgentResponse(agent.Id, plainKey, prefix));
}
}
@@ -0,0 +1,20 @@
using FluentValidation;
namespace Heimdall.Application.Agents.Commands.RegisterAgent;
public class RegisterAgentValidator : AbstractValidator<RegisterAgentCommand>
{
public RegisterAgentValidator()
{
RuleFor(x => x.Token)
.NotEmpty();
RuleFor(x => x.Hostname)
.NotEmpty()
.MaximumLength(255);
RuleFor(x => x.Version)
.MaximumLength(50)
.When(x => x.Version is not null);
}
}
@@ -0,0 +1,29 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Agents.Queries.GetAgent;
public record GetAgentQuery(Guid Id) : IRequest<ServiceResult<AgentResponse>>;
public class GetAgentHandler : IRequestHandler<GetAgentQuery, ServiceResult<AgentResponse>>
{
private readonly IApplicationDbContext _db;
public GetAgentHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<AgentResponse>> Handle(GetAgentQuery request, CancellationToken ct)
{
var agent = await _db.Agents.FindAsync([request.Id], ct);
if (agent is null)
return ServiceResult<AgentResponse>.NotFound("Agent not found");
return ServiceResult<AgentResponse>.Success(MapResponse(agent));
}
private static AgentResponse MapResponse(Domain.Entities.Agent a) => new(
a.Id, a.SiteId, a.Name, a.Hostname, a.Version, a.Status,
a.LastHeartbeat, a.PublicIp, a.HasGpu, a.CpuCores, a.MemoryMb,
a.GpuType.ToString(), a.CreatedAt);
}
@@ -0,0 +1,40 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Agents.Queries.GetAgentsBySite;
public record GetAgentsBySiteQuery(
Guid SiteId,
int Page = 1,
int PageSize = 20) : IRequest<ServiceResult<PagedResult<AgentResponse>>>;
public class GetAgentsBySiteHandler : IRequestHandler<GetAgentsBySiteQuery, ServiceResult<PagedResult<AgentResponse>>>
{
private readonly IApplicationDbContext _db;
public GetAgentsBySiteHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<PagedResult<AgentResponse>>> Handle(GetAgentsBySiteQuery request, CancellationToken ct)
{
var query = _db.Agents
.Where(a => a.SiteId == request.SiteId)
.OrderBy(a => a.Name);
var total = await query.CountAsync(ct);
var items = await query
.Skip((request.Page - 1) * request.PageSize)
.Take(request.PageSize)
.Select(a => MapResponse(a))
.ToListAsync(ct);
return ServiceResult<PagedResult<AgentResponse>>.Success(
new PagedResult<AgentResponse>(items, total, request.Page, request.PageSize));
}
private static AgentResponse MapResponse(Domain.Entities.Agent a) => new(
a.Id, a.SiteId, a.Name, a.Hostname, a.Version, a.Status,
a.LastHeartbeat, a.PublicIp, a.HasGpu, a.CpuCores, a.MemoryMb,
a.GpuType.ToString(), a.CreatedAt);
}
@@ -0,0 +1,37 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Agents.Queries.GetAllAgents;
public record GetAllAgentsQuery(
int Page = 1,
int PageSize = 20) : IRequest<ServiceResult<PagedResult<AgentResponse>>>;
public class GetAllAgentsHandler : IRequestHandler<GetAllAgentsQuery, ServiceResult<PagedResult<AgentResponse>>>
{
private readonly IApplicationDbContext _db;
public GetAllAgentsHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<PagedResult<AgentResponse>>> Handle(GetAllAgentsQuery request, CancellationToken ct)
{
var query = _db.Agents.OrderBy(a => a.Name);
var total = await query.CountAsync(ct);
var items = await query
.Skip((request.Page - 1) * request.PageSize)
.Take(request.PageSize)
.Select(a => MapResponse(a))
.ToListAsync(ct);
return ServiceResult<PagedResult<AgentResponse>>.Success(
new PagedResult<AgentResponse>(items, total, request.Page, request.PageSize));
}
private static AgentResponse MapResponse(Domain.Entities.Agent a) => new(
a.Id, a.SiteId, a.Name, a.Hostname, a.Version, a.Status,
a.LastHeartbeat, a.PublicIp, a.HasGpu, a.CpuCores, a.MemoryMb,
a.GpuType.ToString(), a.CreatedAt);
}
@@ -0,0 +1,9 @@
using Heimdall.Application.Common;
using MediatR;
namespace Heimdall.Application.Assignments.Commands.AssignCamera;
public record AssignCameraCommand(
Guid CameraId,
Guid AgentId,
string Reason) : IRequest<ServiceResult>;
@@ -0,0 +1,21 @@
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Assignments.Commands.AssignCamera;
public sealed class AssignCameraHandler : IRequestHandler<AssignCameraCommand, ServiceResult>
{
private readonly ICameraAssignmentService _assignmentService;
public AssignCameraHandler(ICameraAssignmentService assignmentService)
{
_assignmentService = assignmentService;
}
public async Task<ServiceResult> Handle(AssignCameraCommand command, CancellationToken ct)
{
return await _assignmentService.AssignCameraAsync(
command.CameraId, command.AgentId, command.Reason, ct);
}
}
@@ -0,0 +1,9 @@
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Assignments.Commands.AssignSite;
public record AssignSiteCommand(
Guid SiteId,
AssignmentStrategy Strategy) : IRequest<ServiceResult<int>>;
@@ -0,0 +1,21 @@
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Assignments.Commands.AssignSite;
public sealed class AssignSiteHandler : IRequestHandler<AssignSiteCommand, ServiceResult<int>>
{
private readonly ICameraAssignmentService _assignmentService;
public AssignSiteHandler(ICameraAssignmentService assignmentService)
{
_assignmentService = assignmentService;
}
public async Task<ServiceResult<int>> Handle(AssignSiteCommand command, CancellationToken ct)
{
return await _assignmentService.AssignSiteCamerasAsync(
command.SiteId, command.Strategy, ct);
}
}
@@ -0,0 +1,6 @@
using Heimdall.Application.Common;
using MediatR;
namespace Heimdall.Application.Assignments.Commands.Failover;
public record FailoverCommand(Guid AgentId) : IRequest<ServiceResult<int>>;
@@ -0,0 +1,24 @@
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Assignments.Commands.Failover;
public sealed class FailoverHandler : IRequestHandler<FailoverCommand, ServiceResult<int>>
{
private readonly ICameraAssignmentService _assignmentService;
public FailoverHandler(ICameraAssignmentService assignmentService)
{
_assignmentService = assignmentService;
}
public async Task<ServiceResult<int>> Handle(FailoverCommand command, CancellationToken ct)
{
var result = await _assignmentService.FailoverAgentAsync(command.AgentId, ct);
if (!result.IsSuccess)
return ServiceResult<int>.Failure(result.Error!, result.StatusCode ?? 400);
return ServiceResult<int>.Success(result.Data!.Count);
}
}
@@ -0,0 +1,6 @@
using Heimdall.Application.Common;
using MediatR;
namespace Heimdall.Application.Assignments.Commands.ReleaseCamera;
public record ReleaseCameraCommand(Guid CameraId) : IRequest<ServiceResult>;
@@ -0,0 +1,20 @@
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Assignments.Commands.ReleaseCamera;
public sealed class ReleaseCameraHandler : IRequestHandler<ReleaseCameraCommand, ServiceResult>
{
private readonly ICameraAssignmentService _assignmentService;
public ReleaseCameraHandler(ICameraAssignmentService assignmentService)
{
_assignmentService = assignmentService;
}
public async Task<ServiceResult> Handle(ReleaseCameraCommand command, CancellationToken ct)
{
return await _assignmentService.ReleaseCameraAsync(command.CameraId, ct);
}
}
@@ -0,0 +1,32 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Assignments.Queries.GetActiveAssignment;
public sealed class GetActiveAssignmentHandler
: IRequestHandler<GetActiveAssignmentQuery, ServiceResult<AssignmentResponse?>>
{
private readonly ICameraAssignmentService _assignmentService;
public GetActiveAssignmentHandler(ICameraAssignmentService assignmentService)
{
_assignmentService = assignmentService;
}
public async Task<ServiceResult<AssignmentResponse?>> Handle(
GetActiveAssignmentQuery query, CancellationToken ct)
{
var assignment = await _assignmentService.GetActiveAssignmentAsync(query.CameraId, ct);
if (assignment is null)
return ServiceResult<AssignmentResponse?>.Success(null);
return ServiceResult<AssignmentResponse?>.Success(new AssignmentResponse(
assignment.CameraId,
assignment.AgentId,
assignment.Agent.Name,
assignment.Reason,
assignment.AssignedAt));
}
}
@@ -0,0 +1,7 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
namespace Heimdall.Application.Assignments.Queries.GetActiveAssignment;
public record GetActiveAssignmentQuery(Guid CameraId) : IRequest<ServiceResult<AssignmentResponse?>>;
@@ -0,0 +1,32 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Assignments.Queries.GetAgentAssignments;
public sealed class GetAgentAssignmentsHandler
: IRequestHandler<GetAgentAssignmentsQuery, ServiceResult<List<AssignmentResponse>>>
{
private readonly ICameraAssignmentService _assignmentService;
public GetAgentAssignmentsHandler(ICameraAssignmentService assignmentService)
{
_assignmentService = assignmentService;
}
public async Task<ServiceResult<List<AssignmentResponse>>> Handle(
GetAgentAssignmentsQuery query, CancellationToken ct)
{
var assignments = await _assignmentService.GetAgentAssignmentsAsync(query.AgentId, ct);
var result = assignments.Select(a => new AssignmentResponse(
a.CameraId,
a.AgentId,
a.Agent.Name,
a.Reason,
a.AssignedAt)).ToList();
return ServiceResult<List<AssignmentResponse>>.Success(result);
}
}
@@ -0,0 +1,7 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
namespace Heimdall.Application.Assignments.Queries.GetAgentAssignments;
public record GetAgentAssignmentsQuery(Guid AgentId) : IRequest<ServiceResult<List<AssignmentResponse>>>;
@@ -0,0 +1,32 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Assignments.Queries.GetCameraHistory;
public sealed class GetCameraHistoryHandler
: IRequestHandler<GetCameraHistoryQuery, ServiceResult<List<AssignmentResponse>>>
{
private readonly ICameraAssignmentService _assignmentService;
public GetCameraHistoryHandler(ICameraAssignmentService assignmentService)
{
_assignmentService = assignmentService;
}
public async Task<ServiceResult<List<AssignmentResponse>>> Handle(
GetCameraHistoryQuery query, CancellationToken ct)
{
var assignments = await _assignmentService.GetCameraHistoryAsync(query.CameraId, ct);
var result = assignments.Select(a => new AssignmentResponse(
a.CameraId,
a.AgentId,
a.Agent.Name,
a.Reason,
a.AssignedAt)).ToList();
return ServiceResult<List<AssignmentResponse>>.Success(result);
}
}
@@ -0,0 +1,7 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
namespace Heimdall.Application.Assignments.Queries.GetCameraHistory;
public record GetCameraHistoryQuery(Guid CameraId) : IRequest<ServiceResult<List<AssignmentResponse>>>;
@@ -0,0 +1,47 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Audit.Queries.GetAuditLogs;
public record GetAuditLogsQuery(
string? ResourceType = null,
string? Action = null,
int Page = 1,
int PageSize = 20) : IRequest<ServiceResult<PagedResult<AuditLogResponse>>>;
public class GetAuditLogsQueryHandler
: IRequestHandler<GetAuditLogsQuery, ServiceResult<PagedResult<AuditLogResponse>>>
{
private readonly IApplicationDbContext _db;
public GetAuditLogsQueryHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<PagedResult<AuditLogResponse>>> Handle(
GetAuditLogsQuery request, CancellationToken ct)
{
var query = _db.AuditLogs.AsNoTracking();
if (!string.IsNullOrEmpty(request.ResourceType))
query = query.Where(al => al.ResourceType == request.ResourceType);
if (!string.IsNullOrEmpty(request.Action))
query = query.Where(al => al.Action == request.Action);
var total = await query.CountAsync(ct);
var items = await query
.OrderByDescending(al => al.Timestamp)
.Skip((request.Page - 1) * request.PageSize)
.Take(request.PageSize)
.Select(al => new AuditLogResponse(
al.Id, al.UserId,
al.User != null ? al.User.Email : null,
al.Action, al.ResourceType, al.ResourceId,
al.OldValue, al.NewValue, al.IpAddress, al.Timestamp))
.ToListAsync(ct);
return ServiceResult<PagedResult<AuditLogResponse>>.Success(
new PagedResult<AuditLogResponse>(items, total, request.Page, request.PageSize));
}
}
@@ -5,9 +5,26 @@ namespace Heimdall.Application.Common;
public interface IApplicationDbContext
{
DbSet<Camera> Cameras { get; }
DbSet<Site> Sites { get; }
DbSet<Agent> Agents { get; }
DbSet<AgentSetting> AgentSettings { get; }
DbSet<ApiKey> ApiKeys { get; }
DbSet<AppSetting> AppSettings { get; }
DbSet<AppUser> Users { get; }
DbSet<AuditLog> AuditLogs { get; }
DbSet<Camera> Cameras { get; }
DbSet<CameraAssignment> CameraAssignments { get; }
DbSet<CameraCredentials> CameraCredentials { get; }
DbSet<CameraDetectionProfile> CameraDetectionProfiles { get; }
DbSet<CameraDiscoveryResult> CameraDiscoveryResults { get; }
DbSet<CameraEvent> CameraEvents { get; }
DbSet<DiscoveredStreamUrl> DiscoveredStreams { get; }
DbSet<Group> Groups { get; }
DbSet<KnownFace> KnownFaces { get; }
DbSet<Person> Persons { get; }
DbSet<RevokedRefreshToken> RevokedRefreshTokens { get; }
DbSet<Site> Sites { get; }
DbSet<UserGroup> UserGroups { get; }
DbSet<UserSite> UserSites { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
Task SaveChangesWithRetryAsync(int maxRetries = 3, CancellationToken ct = default);
}
@@ -0,0 +1,32 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Discovery.Commands.BuildStreamUrls;
public record BuildStreamUrlsCommand(
string[] Ids,
string Ip,
string? Username,
string? Password,
int Channel = 0,
int[]? PortFilter = null) : IRequest<ServiceResult<StreamBuildResponse>>;
public class BuildStreamUrlsCommandHandler : IRequestHandler<BuildStreamUrlsCommand, ServiceResult<StreamBuildResponse>>
{
private readonly ICameraDiscoveryService _discovery;
public BuildStreamUrlsCommandHandler(ICameraDiscoveryService discovery)
{
_discovery = discovery;
}
public async Task<ServiceResult<StreamBuildResponse>> Handle(BuildStreamUrlsCommand request, CancellationToken ct)
{
var dto = new StreamBuildRequest(
request.Ids, request.Ip, request.Username, request.Password,
request.Channel, request.PortFilter);
return await _discovery.BuildStreamUrlsAsync(dto, ct);
}
}
@@ -0,0 +1,22 @@
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Discovery.Commands.CancelTestSession;
public record CancelTestSessionCommand(Guid SessionId) : IRequest<ServiceResult>;
public class CancelTestSessionCommandHandler : IRequestHandler<CancelTestSessionCommand, ServiceResult>
{
private readonly ICameraDiscoveryService _discovery;
public CancelTestSessionCommandHandler(ICameraDiscoveryService discovery)
{
_discovery = discovery;
}
public async Task<ServiceResult> Handle(CancelTestSessionCommand request, CancellationToken ct)
{
return await _discovery.CancelTestSessionAsync(request.SessionId, ct);
}
}
@@ -0,0 +1,37 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Discovery.Commands.ConfirmDiscovery;
public record ConfirmDiscoveryCommand(
Guid SiteId,
string Name,
Guid DiscoveryResultId,
string MainStreamUrl,
string? SubStreamUrl,
string? Username,
string? Password,
CameraDetectionProfileRequest? DetectionProfile,
Guid? AgentId = null) : IRequest<ServiceResult<CameraResponse>>;
public class ConfirmDiscoveryCommandHandler : IRequestHandler<ConfirmDiscoveryCommand, ServiceResult<CameraResponse>>
{
private readonly ICameraDiscoveryService _discovery;
public ConfirmDiscoveryCommandHandler(ICameraDiscoveryService discovery)
{
_discovery = discovery;
}
public async Task<ServiceResult<CameraResponse>> Handle(ConfirmDiscoveryCommand request, CancellationToken ct)
{
var dto = new ConfirmDiscoveryRequest(
request.SiteId, request.Name, request.DiscoveryResultId,
request.MainStreamUrl, request.SubStreamUrl,
request.Username, request.Password,
request.DetectionProfile, request.AgentId);
return await _discovery.ConfirmDiscoveryAsync(dto, ct);
}
}
@@ -0,0 +1,24 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Discovery.Commands.ProbeIp;
public record ProbeIpCommand(Guid SiteId, string Ip) : IRequest<ServiceResult<ProbeResponse>>;
public class ProbeIpCommandHandler : IRequestHandler<ProbeIpCommand, ServiceResult<ProbeResponse>>
{
private readonly ICameraDiscoveryService _discovery;
public ProbeIpCommandHandler(ICameraDiscoveryService discovery)
{
_discovery = discovery;
}
public async Task<ServiceResult<ProbeResponse>> Handle(ProbeIpCommand request, CancellationToken ct)
{
var dto = new ProbeRequest(request.SiteId, request.Ip);
return await _discovery.ProbeIpAsync(dto, ct);
}
}
@@ -0,0 +1,27 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Discovery.Commands.ScanSubnet;
public record ScanSubnetCommand(
Guid SiteId,
string SubnetCidr,
int TimeoutMs = 30000) : IRequest<ServiceResult<IReadOnlyList<ProbeResponse>>>;
public class ScanSubnetCommandHandler : IRequestHandler<ScanSubnetCommand, ServiceResult<IReadOnlyList<ProbeResponse>>>
{
private readonly ICameraDiscoveryService _discovery;
public ScanSubnetCommandHandler(ICameraDiscoveryService discovery)
{
_discovery = discovery;
}
public async Task<ServiceResult<IReadOnlyList<ProbeResponse>>> Handle(ScanSubnetCommand request, CancellationToken ct)
{
var dto = new ScanRequest(request.SiteId, request.SubnetCidr, request.TimeoutMs);
return await _discovery.ScanSubnetAsync(dto, ct);
}
}
@@ -0,0 +1,26 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Discovery.Commands.TestStreams;
public record TestStreamsCommand(
string SourceId,
string[] Streams) : IRequest<ServiceResult<StreamTestSession>>;
public class TestStreamsCommandHandler : IRequestHandler<TestStreamsCommand, ServiceResult<StreamTestSession>>
{
private readonly ICameraDiscoveryService _discovery;
public TestStreamsCommandHandler(ICameraDiscoveryService discovery)
{
_discovery = discovery;
}
public async Task<ServiceResult<StreamTestSession>> Handle(TestStreamsCommand request, CancellationToken ct)
{
var dto = new StreamTestRequest(request.SourceId, request.Streams);
return await _discovery.TestStreamsAsync(dto, ct);
}
}
@@ -0,0 +1,27 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Discovery.Queries.CheckDuplicate;
public record CheckDuplicateQuery(
Guid SiteId,
string Ip,
string? Mac) : IRequest<ServiceResult<CameraCheckResponse>>;
public class CheckDuplicateQueryHandler : IRequestHandler<CheckDuplicateQuery, ServiceResult<CameraCheckResponse>>
{
private readonly ICameraDiscoveryService _discovery;
public CheckDuplicateQueryHandler(ICameraDiscoveryService discovery)
{
_discovery = discovery;
}
public async Task<ServiceResult<CameraCheckResponse>> Handle(CheckDuplicateQuery request, CancellationToken ct)
{
var dto = new CheckDuplicateRequest(request.SiteId, request.Ip, request.Mac);
return await _discovery.CheckDuplicateAsync(dto, ct);
}
}
@@ -0,0 +1,26 @@
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Discovery.Queries.GetScreenshot;
public record GetScreenshotQuery(Guid SessionId, int Index) : IRequest<ServiceResult<byte[]>>;
public class GetScreenshotQueryHandler : IRequestHandler<GetScreenshotQuery, ServiceResult<byte[]>>
{
private readonly ICameraDiscoveryService _discovery;
public GetScreenshotQueryHandler(ICameraDiscoveryService discovery)
{
_discovery = discovery;
}
public async Task<ServiceResult<byte[]>> Handle(GetScreenshotQuery request, CancellationToken ct)
{
var bytes = await _discovery.GetScreenshotAsync(request.SessionId, request.Index, ct);
if (bytes is null || bytes.Length == 0)
return ServiceResult<byte[]>.NotFound("Screenshot not found");
return ServiceResult<byte[]>.Success(bytes);
}
}
@@ -0,0 +1,23 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Discovery.Queries.GetTestSession;
public record GetTestSessionQuery(Guid SessionId) : IRequest<ServiceResult<StreamTestSession>>;
public class GetTestSessionQueryHandler : IRequestHandler<GetTestSessionQuery, ServiceResult<StreamTestSession>>
{
private readonly ICameraDiscoveryService _discovery;
public GetTestSessionQueryHandler(ICameraDiscoveryService discovery)
{
_discovery = discovery;
}
public async Task<ServiceResult<StreamTestSession>> Handle(GetTestSessionQuery request, CancellationToken ct)
{
return await _discovery.GetTestSessionAsync(request.SessionId, ct);
}
}
@@ -0,0 +1,23 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using MediatR;
namespace Heimdall.Application.Discovery.Queries.SearchDatabase;
public record SearchDatabaseQuery(string Query) : IRequest<ServiceResult<SearchResponse>>;
public class SearchDatabaseQueryHandler : IRequestHandler<SearchDatabaseQuery, ServiceResult<SearchResponse>>
{
private readonly ICameraDiscoveryService _discovery;
public SearchDatabaseQueryHandler(ICameraDiscoveryService discovery)
{
_discovery = discovery;
}
public async Task<ServiceResult<SearchResponse>> Handle(SearchDatabaseQuery request, CancellationToken ct)
{
return await _discovery.SearchDatabaseAsync(request.Query, ct);
}
}
@@ -0,0 +1,6 @@
using Heimdall.Application.Common;
using MediatR;
namespace Heimdall.Application.Events.Commands.AttachSnapshot;
public record AttachSnapshotCommand(Guid EventId, string SnapshotUrl, string? ThumbUrl) : IRequest<ServiceResult>;
@@ -0,0 +1,25 @@
using Heimdall.Application.Common;
using MediatR;
namespace Heimdall.Application.Events.Commands.AttachSnapshot;
#pragma warning disable CA1711
public class AttachSnapshotHandler : IRequestHandler<AttachSnapshotCommand, ServiceResult>
#pragma warning restore CA1711
{
private readonly IApplicationDbContext _context;
public AttachSnapshotHandler(IApplicationDbContext context) => _context = context;
public async Task<ServiceResult> Handle(AttachSnapshotCommand request, CancellationToken ct)
{
var ev = await _context.CameraEvents.FindAsync([request.EventId], ct);
if (ev is null)
return ServiceResult.NotFound("Event not found");
ev.SetSnapshot(request.SnapshotUrl, request.ThumbUrl);
await _context.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult.Success();
}
}
@@ -0,0 +1,14 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Enums;
using MediatR;
namespace Heimdall.Application.Events.Commands.CreateEvent;
public record CreateEventCommand(
Guid CameraId,
EventType Type,
double Confidence,
string? Label,
string? MetadataJson,
DateTime? OccurredAt) : IRequest<ServiceResult<CameraEventResponse>>;
@@ -0,0 +1,37 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Events.Commands.CreateEvent;
#pragma warning disable CA1711
public class CreateEventHandler : IRequestHandler<CreateEventCommand, ServiceResult<CameraEventResponse>>
#pragma warning restore CA1711
{
private readonly IApplicationDbContext _context;
public CreateEventHandler(IApplicationDbContext context) => _context = context;
public async Task<ServiceResult<CameraEventResponse>> Handle(CreateEventCommand request, CancellationToken ct)
{
var camera = await _context.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);
_context.CameraEvents.Add(ev);
await _context.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult<CameraEventResponse>.Success(MapResponse(ev));
}
private static CameraEventResponse MapResponse(CameraEvent e) => new(
e.Id, e.CameraId, e.Camera.SiteId, e.AgentId, e.Type, e.Confidence,
e.Label, e.SnapshotUrl, e.SnapshotThumbUrl,
e.MetadataJson, e.OccurredAt, e.CreatedAt);
}
@@ -0,0 +1,6 @@
using Heimdall.Application.Common;
using MediatR;
namespace Heimdall.Application.Events.Commands.DeleteEvent;
public record DeleteEventCommand(Guid Id) : IRequest<ServiceResult>;
@@ -0,0 +1,25 @@
using Heimdall.Application.Common;
using MediatR;
namespace Heimdall.Application.Events.Commands.DeleteEvent;
#pragma warning disable CA1711
public class DeleteEventHandler : IRequestHandler<DeleteEventCommand, ServiceResult>
#pragma warning restore CA1711
{
private readonly IApplicationDbContext _context;
public DeleteEventHandler(IApplicationDbContext context) => _context = context;
public async Task<ServiceResult> Handle(DeleteEventCommand request, CancellationToken ct)
{
var ev = await _context.CameraEvents.FindAsync([request.Id], ct);
if (ev is null)
return ServiceResult.NotFound("Event not found");
_context.CameraEvents.Remove(ev);
await _context.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult.Success();
}
}
@@ -0,0 +1,6 @@
using Heimdall.Application.DTOs;
using MediatR;
namespace Heimdall.Application.Events.Notifications;
public record EventCreatedNotification(CameraEventResponse Event) : INotification;
@@ -0,0 +1,33 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Events.Queries.GetEvent;
#pragma warning disable CA1711
public class GetEventHandler : IRequestHandler<GetEventQuery, ServiceResult<CameraEventResponse>>
#pragma warning restore CA1711
{
private readonly IApplicationDbContext _context;
public GetEventHandler(IApplicationDbContext context) => _context = context;
public async Task<ServiceResult<CameraEventResponse>> Handle(GetEventQuery request, CancellationToken ct)
{
var ev = await _context.CameraEvents
.AsNoTracking()
.Include(e => e.Camera)
.FirstOrDefaultAsync(e => e.Id == request.Id, ct);
return ev is null
? ServiceResult<CameraEventResponse>.NotFound("Event not found")
: ServiceResult<CameraEventResponse>.Success(MapResponse(ev));
}
private static CameraEventResponse MapResponse(CameraEvent e) => new(
e.Id, e.CameraId, e.Camera.SiteId, e.AgentId, e.Type, e.Confidence,
e.Label, e.SnapshotUrl, e.SnapshotThumbUrl,
e.MetadataJson, e.OccurredAt, e.CreatedAt);
}
@@ -0,0 +1,7 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
namespace Heimdall.Application.Events.Queries.GetEvent;
public record GetEventQuery(Guid Id) : IRequest<ServiceResult<CameraEventResponse>>;
@@ -0,0 +1,57 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Events.Queries.GetEvents;
#pragma warning disable CA1711
public class GetEventsHandler : IRequestHandler<GetEventsQuery, ServiceResult<PagedResult<CameraEventResponse>>>
#pragma warning restore CA1711
{
private readonly IApplicationDbContext _context;
public GetEventsHandler(IApplicationDbContext context) => _context = context;
public async Task<ServiceResult<PagedResult<CameraEventResponse>>> Handle(GetEventsQuery request, CancellationToken ct)
{
var pageSize = Math.Min(request.PageSize, 100);
IQueryable<CameraEvent> query = _context.CameraEvents
.AsNoTracking()
.Include(e => e.Camera);
if (request.CameraId.HasValue)
query = query.Where(e => e.CameraId == request.CameraId.Value);
if (request.SiteId.HasValue)
query = query.Where(e => e.Camera.SiteId == request.SiteId.Value);
if (request.Type.HasValue)
query = query.Where(e => e.Type == request.Type.Value);
if (request.From.HasValue)
query = query.Where(e => e.OccurredAt >= request.From.Value);
if (request.To.HasValue)
query = query.Where(e => e.OccurredAt <= request.To.Value);
if (request.MinConfidence.HasValue)
query = query.Where(e => e.Confidence >= request.MinConfidence.Value);
var total = await query.CountAsync(ct);
var items = await query
.OrderByDescending(e => e.OccurredAt)
.Skip((request.Page - 1) * pageSize)
.Take(pageSize)
.ToListAsync(ct);
return ServiceResult<PagedResult<CameraEventResponse>>.Success(new PagedResult<CameraEventResponse>(
items.Select(MapResponse).ToList(), total, request.Page, pageSize));
}
private static CameraEventResponse MapResponse(CameraEvent e) => new(
e.Id, e.CameraId, e.Camera.SiteId, e.AgentId, e.Type, e.Confidence,
e.Label, e.SnapshotUrl, e.SnapshotThumbUrl,
e.MetadataJson, e.OccurredAt, e.CreatedAt);
}
@@ -0,0 +1,16 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Enums;
using MediatR;
namespace Heimdall.Application.Events.Queries.GetEvents;
public record GetEventsQuery(
Guid? CameraId,
Guid? SiteId,
EventType? Type,
DateTime? From,
DateTime? To,
double? MinConfidence,
int Page = 1,
int PageSize = 50) : IRequest<ServiceResult<PagedResult<CameraEventResponse>>>;
@@ -0,0 +1,34 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Events.Queries.GetRecentByCamera;
#pragma warning disable CA1711
public class GetRecentByCameraHandler : IRequestHandler<GetRecentByCameraQuery, ServiceResult<List<CameraEventResponse>>>
#pragma warning restore CA1711
{
private readonly IApplicationDbContext _context;
public GetRecentByCameraHandler(IApplicationDbContext context) => _context = context;
public async Task<ServiceResult<List<CameraEventResponse>>> Handle(GetRecentByCameraQuery request, CancellationToken ct)
{
var items = await _context.CameraEvents
.AsNoTracking()
.Include(e => e.Camera)
.Where(e => e.CameraId == request.CameraId)
.OrderByDescending(e => e.OccurredAt)
.Take(request.Count)
.ToListAsync(ct);
return ServiceResult<List<CameraEventResponse>>.Success(items.Select(MapResponse).ToList());
}
private static CameraEventResponse MapResponse(CameraEvent e) => new(
e.Id, e.CameraId, e.Camera.SiteId, e.AgentId, e.Type, e.Confidence,
e.Label, e.SnapshotUrl, e.SnapshotThumbUrl,
e.MetadataJson, e.OccurredAt, e.CreatedAt);
}
@@ -0,0 +1,7 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
namespace Heimdall.Application.Events.Queries.GetRecentByCamera;
public record GetRecentByCameraQuery(Guid CameraId, int Count = 20) : IRequest<ServiceResult<List<CameraEventResponse>>>;
@@ -0,0 +1,39 @@
using Heimdall.Application.Common;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Groups.Commands.AddUserToGroup;
public record AddUserToGroupCommand(Guid GroupId, Guid UserId) : IRequest<ServiceResult>;
public class AddUserToGroupCommandHandler : IRequestHandler<AddUserToGroupCommand, ServiceResult>
{
private readonly IApplicationDbContext _db;
public AddUserToGroupCommandHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult> Handle(AddUserToGroupCommand request, CancellationToken ct)
{
var group = await _db.Groups.FindAsync([request.GroupId], ct);
if (group is null)
return ServiceResult.NotFound("Group not found");
var user = await _db.Users.FindAsync([request.UserId], ct);
if (user is null)
return ServiceResult.NotFound("User not found");
var alreadyMember = await _db.UserGroups.AnyAsync(
ug => ug.GroupId == request.GroupId && ug.UserId == request.UserId, ct);
if (alreadyMember)
return ServiceResult.Conflict("User is already a member of this group");
_db.UserGroups.Add(new UserGroup(request.UserId, request.GroupId));
_db.AuditLogs.Add(new AuditLog(null, "Group.UserAdded", "Group",
request.GroupId.ToString(), null, request.UserId.ToString()));
await _db.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult.Success();
}
}
@@ -0,0 +1,34 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Groups.Commands.CreateGroup;
public record CreateGroupCommand(string Name, string? Description) : IRequest<ServiceResult<GroupResponse>>;
public class CreateGroupCommandHandler : IRequestHandler<CreateGroupCommand, ServiceResult<GroupResponse>>
{
private readonly IApplicationDbContext _db;
public CreateGroupCommandHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<GroupResponse>> Handle(CreateGroupCommand request, CancellationToken ct)
{
var exists = await _db.Groups.AnyAsync(g => g.Name == request.Name, ct);
if (exists)
return ServiceResult<GroupResponse>.Conflict("A group with this name already exists");
var group = new Group(request.Name, request.Description);
_db.Groups.Add(group);
_db.AuditLogs.Add(new AuditLog(null, "Group.Created", "Group", group.Id.ToString()));
await _db.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult<GroupResponse>.Success(Map(group, 0));
}
private static GroupResponse Map(Group g, int userCount) => new(
g.Id, g.Name, g.Description, userCount, g.CreatedAt, g.UpdatedAt);
}
@@ -0,0 +1,28 @@
using Heimdall.Application.Common;
using Heimdall.Domain.Entities;
using MediatR;
namespace Heimdall.Application.Groups.Commands.DeleteGroup;
public record DeleteGroupCommand(Guid Id) : IRequest<ServiceResult>;
public class DeleteGroupCommandHandler : IRequestHandler<DeleteGroupCommand, ServiceResult>
{
private readonly IApplicationDbContext _db;
public DeleteGroupCommandHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult> Handle(DeleteGroupCommand request, CancellationToken ct)
{
var group = await _db.Groups.FindAsync([request.Id], ct);
if (group is null)
return ServiceResult.NotFound("Group not found");
group.SoftDelete();
_db.AuditLogs.Add(new AuditLog(null, "Group.Deleted", "Group", request.Id.ToString()));
await _db.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult.Success();
}
}
@@ -0,0 +1,29 @@
using Heimdall.Application.Common;
using Heimdall.Domain.Entities;
using MediatR;
namespace Heimdall.Application.Groups.Commands.RemoveUserFromGroup;
public record RemoveUserFromGroupCommand(Guid GroupId, Guid UserId) : IRequest<ServiceResult>;
public class RemoveUserFromGroupCommandHandler : IRequestHandler<RemoveUserFromGroupCommand, ServiceResult>
{
private readonly IApplicationDbContext _db;
public RemoveUserFromGroupCommandHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult> Handle(RemoveUserFromGroupCommand request, CancellationToken ct)
{
var userGroup = await _db.UserGroups.FindAsync([request.UserId, request.GroupId], ct);
if (userGroup is null)
return ServiceResult.NotFound("User is not a member of this group");
_db.UserGroups.Remove(userGroup);
_db.AuditLogs.Add(new AuditLog(null, "Group.UserRemoved", "Group",
request.GroupId.ToString(), request.UserId.ToString(), null));
await _db.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult.Success();
}
}
@@ -0,0 +1,35 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Groups.Commands.UpdateGroup;
public record UpdateGroupCommand(Guid Id, string Name, string? Description) : IRequest<ServiceResult<GroupResponse>>;
public class UpdateGroupCommandHandler : IRequestHandler<UpdateGroupCommand, ServiceResult<GroupResponse>>
{
private readonly IApplicationDbContext _db;
public UpdateGroupCommandHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<GroupResponse>> Handle(UpdateGroupCommand request, CancellationToken ct)
{
var group = await _db.Groups.FindAsync([request.Id], ct);
if (group is null)
return ServiceResult<GroupResponse>.NotFound("Group not found");
group.Update(request.Name, request.Description);
_db.AuditLogs.Add(new AuditLog(null, "Group.Updated", "Group", request.Id.ToString()));
await _db.SaveChangesWithRetryAsync(ct: ct);
var memberCount = await _db.UserGroups.CountAsync(ug => ug.GroupId == request.Id, ct);
return ServiceResult<GroupResponse>.Success(Map(group, memberCount));
}
private static GroupResponse Map(Group g, int userCount) => new(
g.Id, g.Name, g.Description, userCount, g.CreatedAt, g.UpdatedAt);
}
@@ -0,0 +1,30 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Groups.Queries.GetGroup;
public record GetGroupQuery(Guid Id) : IRequest<ServiceResult<GroupResponse>>;
public class GetGroupQueryHandler : IRequestHandler<GetGroupQuery, ServiceResult<GroupResponse>>
{
private readonly IApplicationDbContext _db;
public GetGroupQueryHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<GroupResponse>> Handle(GetGroupQuery request, CancellationToken ct)
{
var group = await _db.Groups.FindAsync([request.Id], ct);
if (group is null)
return ServiceResult<GroupResponse>.NotFound("Group not found");
var memberCount = await _db.UserGroups.CountAsync(ug => ug.GroupId == request.Id, ct);
return ServiceResult<GroupResponse>.Success(Map(group, memberCount));
}
private static GroupResponse Map(Group g, int userCount) => new(
g.Id, g.Name, g.Description, userCount, g.CreatedAt, g.UpdatedAt);
}
@@ -0,0 +1,35 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Groups.Queries.GetGroupMembers;
public record GetGroupMembersQuery(Guid GroupId) : IRequest<ServiceResult<IReadOnlyList<GroupMemberResponse>>>;
public class GetGroupMembersQueryHandler
: IRequestHandler<GetGroupMembersQuery, ServiceResult<IReadOnlyList<GroupMemberResponse>>>
{
private readonly IApplicationDbContext _db;
public GetGroupMembersQueryHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<IReadOnlyList<GroupMemberResponse>>> Handle(
GetGroupMembersQuery request, CancellationToken ct)
{
var groupExists = await _db.Groups.AnyAsync(g => g.Id == request.GroupId, ct);
if (!groupExists)
return ServiceResult<IReadOnlyList<GroupMemberResponse>>.NotFound("Group not found");
var members = await _db.UserGroups.AsNoTracking()
.Where(ug => ug.GroupId == request.GroupId)
.Join(_db.Users.AsNoTracking(),
ug => ug.UserId,
u => u.Id,
(ug, u) => new GroupMemberResponse(u.Id, u.Email ?? string.Empty, u.DisplayName))
.OrderBy(m => m.DisplayName)
.ToListAsync(ct);
return ServiceResult<IReadOnlyList<GroupMemberResponse>>.Success(members);
}
}
@@ -0,0 +1,40 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Groups.Queries.GetGroups;
public record GetGroupsQuery(int Page = 1, int PageSize = 20) : IRequest<ServiceResult<PagedResult<GroupResponse>>>;
public class GetGroupsQueryHandler : IRequestHandler<GetGroupsQuery, ServiceResult<PagedResult<GroupResponse>>>
{
private readonly IApplicationDbContext _db;
public GetGroupsQueryHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<PagedResult<GroupResponse>>> Handle(GetGroupsQuery request, CancellationToken ct)
{
var query = _db.Groups.AsNoTracking().OrderBy(g => g.Name);
var total = await query.CountAsync(ct);
var groups = await query
.Skip((request.Page - 1) * request.PageSize)
.Take(request.PageSize)
.ToListAsync(ct);
var groupIds = groups.Select(g => g.Id).ToList();
var memberCounts = await _db.UserGroups.AsNoTracking()
.Where(ug => groupIds.Contains(ug.GroupId))
.GroupBy(ug => ug.GroupId)
.Select(g => new { GroupId = g.Key, Count = g.Count() })
.ToDictionaryAsync(x => x.GroupId, x => x.Count, ct);
var items = groups.Select(g =>
new GroupResponse(g.Id, g.Name, g.Description,
memberCounts.GetValueOrDefault(g.Id, 0), g.CreatedAt, g.UpdatedAt)).ToList();
return ServiceResult<PagedResult<GroupResponse>>.Success(
new PagedResult<GroupResponse>(items, total, request.Page, request.PageSize));
}
}
@@ -0,0 +1,32 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
namespace Heimdall.Application.Persons.Commands.CreatePerson;
public record CreatePersonCommand(
string DisplayName, string? Category, string? Notes, bool IsWatchlisted = false)
: IRequest<ServiceResult<PersonResponse>>;
public class CreatePersonCommandHandler : IRequestHandler<CreatePersonCommand, ServiceResult<PersonResponse>>
{
private readonly IApplicationDbContext _db;
public CreatePersonCommandHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<PersonResponse>> Handle(CreatePersonCommand request, CancellationToken ct)
{
var person = new Person(request.DisplayName, request.Category);
person.Update(request.DisplayName, request.Notes ?? "", request.Category, request.IsWatchlisted);
_db.Persons.Add(person);
await _db.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult<PersonResponse>.Success(Map(person));
}
private static PersonResponse Map(Person p) => new(
p.Id, p.DisplayName, p.Notes, p.PhotoUrl,
p.Category, p.IsWatchlisted, p.Faces.Count, p.CreatedAt);
}
@@ -0,0 +1,25 @@
using Heimdall.Application.Common;
using MediatR;
namespace Heimdall.Application.Persons.Commands.DeleteFace;
public record DeleteFaceCommand(Guid FaceId) : IRequest<ServiceResult>;
public class DeleteFaceCommandHandler : IRequestHandler<DeleteFaceCommand, ServiceResult>
{
private readonly IApplicationDbContext _db;
public DeleteFaceCommandHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult> Handle(DeleteFaceCommand request, CancellationToken ct)
{
var face = await _db.KnownFaces.FindAsync([request.FaceId], ct);
if (face is null)
return ServiceResult.NotFound("Face not found");
_db.KnownFaces.Remove(face);
await _db.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult.Success();
}
}
@@ -0,0 +1,25 @@
using Heimdall.Application.Common;
using MediatR;
namespace Heimdall.Application.Persons.Commands.DeletePerson;
public record DeletePersonCommand(Guid Id) : IRequest<ServiceResult>;
public class DeletePersonCommandHandler : IRequestHandler<DeletePersonCommand, ServiceResult>
{
private readonly IApplicationDbContext _db;
public DeletePersonCommandHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult> Handle(DeletePersonCommand request, CancellationToken ct)
{
var person = await _db.Persons.FindAsync([request.Id], ct);
if (person is null)
return ServiceResult.NotFound("Person not found");
_db.Persons.Remove(person);
await _db.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult.Success();
}
}
@@ -0,0 +1,37 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Persons.Commands.RegisterFace;
public record RegisterFaceCommand(
Guid PersonId, float[] Embedding, string? ThumbnailUrl = null, string? SourceEventId = null)
: IRequest<ServiceResult<KnownFaceResponse>>;
public class RegisterFaceCommandHandler : IRequestHandler<RegisterFaceCommand, ServiceResult<KnownFaceResponse>>
{
private readonly IApplicationDbContext _db;
public RegisterFaceCommandHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<KnownFaceResponse>> Handle(RegisterFaceCommand request, CancellationToken ct)
{
var person = await _db.Persons
.Include(p => p.Faces)
.FirstOrDefaultAsync(p => p.Id == request.PersonId, ct);
if (person is null)
return ServiceResult<KnownFaceResponse>.NotFound("Person not found");
var face = new KnownFace(request.PersonId, request.Embedding,
request.ThumbnailUrl, request.SourceEventId);
person.AddFace(face);
await _db.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult<KnownFaceResponse>.Success(Map(face));
}
private static KnownFaceResponse Map(KnownFace f) => new(
f.Id, f.PersonId, f.ThumbnailUrl, f.SourceEventId);
}
@@ -0,0 +1,33 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
namespace Heimdall.Application.Persons.Commands.UpdatePerson;
public record UpdatePersonCommand(
Guid Id, string DisplayName, string? Notes, string? Category, bool IsWatchlisted)
: IRequest<ServiceResult<PersonResponse>>;
public class UpdatePersonCommandHandler : IRequestHandler<UpdatePersonCommand, ServiceResult<PersonResponse>>
{
private readonly IApplicationDbContext _db;
public UpdatePersonCommandHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<PersonResponse>> Handle(UpdatePersonCommand request, CancellationToken ct)
{
var person = await _db.Persons.FindAsync([request.Id], ct);
if (person is null)
return ServiceResult<PersonResponse>.NotFound("Person not found");
person.Update(request.DisplayName, request.Notes, request.Category, request.IsWatchlisted);
await _db.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult<PersonResponse>.Success(Map(person));
}
private static PersonResponse Map(Person p) => new(
p.Id, p.DisplayName, p.Notes, p.PhotoUrl,
p.Category, p.IsWatchlisted, p.Faces.Count, p.CreatedAt);
}
@@ -0,0 +1,29 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Persons.Queries.GetFaces;
public record GetFacesQuery(Guid PersonId) : IRequest<ServiceResult<List<KnownFaceResponse>>>;
public class GetFacesQueryHandler : IRequestHandler<GetFacesQuery, ServiceResult<List<KnownFaceResponse>>>
{
private readonly IApplicationDbContext _db;
public GetFacesQueryHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<List<KnownFaceResponse>>> Handle(GetFacesQuery request, CancellationToken ct)
{
var faces = await _db.KnownFaces
.AsNoTracking()
.Where(f => f.PersonId == request.PersonId)
.ToListAsync(ct);
return ServiceResult<List<KnownFaceResponse>>.Success(faces.Select(Map).ToList());
}
private static KnownFaceResponse Map(KnownFace f) => new(
f.Id, f.PersonId, f.ThumbnailUrl, f.SourceEventId);
}
@@ -0,0 +1,31 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Persons.Queries.GetPerson;
public record GetPersonQuery(Guid Id) : IRequest<ServiceResult<PersonResponse>>;
public class GetPersonQueryHandler : IRequestHandler<GetPersonQuery, ServiceResult<PersonResponse>>
{
private readonly IApplicationDbContext _db;
public GetPersonQueryHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<PersonResponse>> Handle(GetPersonQuery request, CancellationToken ct)
{
var person = await _db.Persons
.Include(p => p.Faces)
.FirstOrDefaultAsync(p => p.Id == request.Id, ct);
return person is null
? ServiceResult<PersonResponse>.NotFound("Person not found")
: ServiceResult<PersonResponse>.Success(Map(person));
}
private static PersonResponse Map(Person p) => new(
p.Id, p.DisplayName, p.Notes, p.PhotoUrl,
p.Category, p.IsWatchlisted, p.Faces.Count, p.CreatedAt);
}
@@ -0,0 +1,30 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Persons.Queries.GetPersons;
public record GetPersonsQuery(string? Category = null) : IRequest<ServiceResult<List<PersonResponse>>>;
public class GetPersonsQueryHandler : IRequestHandler<GetPersonsQuery, ServiceResult<List<PersonResponse>>>
{
private readonly IApplicationDbContext _db;
public GetPersonsQueryHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<List<PersonResponse>>> Handle(GetPersonsQuery request, CancellationToken ct)
{
var query = _db.Persons.Include(p => p.Faces).AsNoTracking();
if (!string.IsNullOrEmpty(request.Category))
query = query.Where(p => p.Category == request.Category);
var persons = await query.OrderBy(p => p.DisplayName).ToListAsync(ct);
return ServiceResult<List<PersonResponse>>.Success(persons.Select(Map).ToList());
}
private static PersonResponse Map(Person p) => new(
p.Id, p.DisplayName, p.Notes, p.PhotoUrl,
p.Category, p.IsWatchlisted, p.Faces.Count, p.CreatedAt);
}
@@ -0,0 +1,42 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Settings.Commands.CreateAppSetting;
public record CreateAppSettingCommand(
string Key,
string Value,
string Category = "General",
string? Description = null,
string ValueType = "string",
string? AllowedValues = null) : IRequest<ServiceResult<AppSettingDto>>;
public class CreateAppSettingCommandHandler : IRequestHandler<CreateAppSettingCommand, ServiceResult<AppSettingDto>>
{
private readonly IApplicationDbContext _db;
public CreateAppSettingCommandHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<AppSettingDto>> Handle(CreateAppSettingCommand request, CancellationToken ct)
{
var key = request.Key.Trim().ToLowerInvariant();
var exists = await _db.AppSettings.AnyAsync(s => s.Key == key, ct);
if (exists)
return ServiceResult<AppSettingDto>.Conflict($"Setting '{key}' already exists");
var setting = new AppSetting(key, request.Value, request.Category, request.Description);
setting.UpdateMetadata(null, null, request.ValueType, request.AllowedValues);
_db.AppSettings.Add(setting);
await _db.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult<AppSettingDto>.Success(Map(setting));
}
private static AppSettingDto Map(AppSetting s) => new(
s.Id, s.Key, s.Value, s.Description, s.Category, s.ValueType, s.AllowedValues, s.UpdatedAt);
}
@@ -0,0 +1,26 @@
using Heimdall.Application.Common;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Settings.Commands.DeleteAppSetting;
public record DeleteAppSettingCommand(string Key) : IRequest<ServiceResult>;
public class DeleteAppSettingCommandHandler : IRequestHandler<DeleteAppSettingCommand, ServiceResult>
{
private readonly IApplicationDbContext _db;
public DeleteAppSettingCommandHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult> Handle(DeleteAppSettingCommand request, CancellationToken ct)
{
var setting = await _db.AppSettings.FirstOrDefaultAsync(s => s.Key == request.Key, ct);
if (setting is null)
return ServiceResult.NotFound($"Setting '{request.Key}' not found");
_db.AppSettings.Remove(setting);
await _db.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult.Success();
}
}
@@ -0,0 +1,27 @@
using Heimdall.Application.Common;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Settings.Commands.RemoveAgentSetting;
public record RemoveAgentSettingCommand(Guid AgentId, string Key) : IRequest<ServiceResult>;
public class RemoveAgentSettingCommandHandler : IRequestHandler<RemoveAgentSettingCommand, ServiceResult>
{
private readonly IApplicationDbContext _db;
public RemoveAgentSettingCommandHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult> Handle(RemoveAgentSettingCommand request, CancellationToken ct)
{
var setting = await _db.AgentSettings
.FirstOrDefaultAsync(s => s.AgentId == request.AgentId && s.Key == request.Key, ct);
if (setting is null)
return ServiceResult.NotFound($"Agent setting '{request.Key}' not found for agent {request.AgentId}");
_db.AgentSettings.Remove(setting);
await _db.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult.Success();
}
}
@@ -0,0 +1,42 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Settings.Commands.SetAgentSetting;
public record SetAgentSettingCommand(Guid AgentId, string Key, string Value)
: IRequest<ServiceResult<AgentSettingDto>>;
public class SetAgentSettingCommandHandler : IRequestHandler<SetAgentSettingCommand, ServiceResult<AgentSettingDto>>
{
private readonly IApplicationDbContext _db;
public SetAgentSettingCommandHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<AgentSettingDto>> Handle(SetAgentSettingCommand request, CancellationToken ct)
{
var key = request.Key.Trim().ToLowerInvariant();
var existing = await _db.AgentSettings
.FirstOrDefaultAsync(s => s.AgentId == request.AgentId && s.Key == key, ct);
if (existing is not null)
{
existing.UpdateValue(request.Value);
}
else
{
existing = new AgentSetting(request.AgentId, key, request.Value);
_db.AgentSettings.Add(existing);
}
await _db.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult<AgentSettingDto>.Success(Map(existing));
}
private static AgentSettingDto Map(AgentSetting s) => new(
s.Id, s.AgentId, s.Key, s.Value, s.UpdatedAt);
}
@@ -0,0 +1,38 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Settings.Commands.UpdateAppSetting;
public record UpdateAppSettingCommand(
string Key,
string Value,
string? Description = null,
string? Category = null,
string? ValueType = null,
string? AllowedValues = null) : IRequest<ServiceResult<AppSettingDto>>;
public class UpdateAppSettingCommandHandler : IRequestHandler<UpdateAppSettingCommand, ServiceResult<AppSettingDto>>
{
private readonly IApplicationDbContext _db;
public UpdateAppSettingCommandHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<AppSettingDto>> Handle(UpdateAppSettingCommand request, CancellationToken ct)
{
var setting = await _db.AppSettings.FirstOrDefaultAsync(s => s.Key == request.Key, ct);
if (setting is null)
return ServiceResult<AppSettingDto>.NotFound($"Setting '{request.Key}' not found");
setting.UpdateValue(request.Value);
setting.UpdateMetadata(request.Description, request.Category, request.ValueType, request.AllowedValues);
await _db.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult<AppSettingDto>.Success(Map(setting));
}
private static AppSettingDto Map(AppSetting s) => new(
s.Id, s.Key, s.Value, s.Description, s.Category, s.ValueType, s.AllowedValues, s.UpdatedAt);
}
@@ -0,0 +1,31 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Settings.Queries.GetAgentSettings;
public record GetAgentSettingsQuery(Guid AgentId) : IRequest<ServiceResult<List<AgentSettingDto>>>;
public class GetAgentSettingsQueryHandler
: IRequestHandler<GetAgentSettingsQuery, ServiceResult<List<AgentSettingDto>>>
{
private readonly IApplicationDbContext _db;
public GetAgentSettingsQueryHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<List<AgentSettingDto>>> Handle(
GetAgentSettingsQuery request, CancellationToken ct)
{
var settings = await _db.AgentSettings
.Where(s => s.AgentId == request.AgentId)
.OrderBy(s => s.Key)
.ToListAsync(ct);
return ServiceResult<List<AgentSettingDto>>.Success(settings.Select(Map).ToList());
}
private static AgentSettingDto Map(AgentSetting s) => new(
s.Id, s.AgentId, s.Key, s.Value, s.UpdatedAt);
}
@@ -0,0 +1,34 @@
using Heimdall.Application.Common;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Settings.Queries.GetEffectiveAgentConfig;
public record GetEffectiveAgentConfigQuery(Guid AgentId) : IRequest<ServiceResult<Dictionary<string, string>>>;
public class GetEffectiveAgentConfigQueryHandler
: IRequestHandler<GetEffectiveAgentConfigQuery, ServiceResult<Dictionary<string, string>>>
{
private readonly IApplicationDbContext _db;
public GetEffectiveAgentConfigQueryHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<Dictionary<string, string>>> Handle(
GetEffectiveAgentConfigQuery request, CancellationToken ct)
{
var appSettings = await _db.AppSettings.ToListAsync(ct);
var config = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var s in appSettings)
config[s.Key] = s.Value;
var agentSettings = await _db.AgentSettings
.Where(s => s.AgentId == request.AgentId)
.ToListAsync(ct);
foreach (var s in agentSettings)
config[s.Key] = s.Value;
return ServiceResult<Dictionary<string, string>>.Success(config);
}
}
@@ -0,0 +1,28 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Settings.Queries.GetSettingByKey;
public record GetSettingByKeyQuery(string Key) : IRequest<ServiceResult<AppSettingDto>>;
public class GetSettingByKeyQueryHandler : IRequestHandler<GetSettingByKeyQuery, ServiceResult<AppSettingDto>>
{
private readonly IApplicationDbContext _db;
public GetSettingByKeyQueryHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<AppSettingDto>> Handle(GetSettingByKeyQuery request, CancellationToken ct)
{
var setting = await _db.AppSettings.FirstOrDefaultAsync(s => s.Key == request.Key, ct);
if (setting is null)
return ServiceResult<AppSettingDto>.NotFound($"Setting '{request.Key}' not found");
return ServiceResult<AppSettingDto>.Success(Map(setting));
}
private static AppSettingDto Map(AppSetting s) => new(
s.Id, s.Key, s.Value, s.Description, s.Category, s.ValueType, s.AllowedValues, s.UpdatedAt);
}
@@ -0,0 +1,29 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Settings.Queries.GetSettings;
public record GetSettingsQuery : IRequest<ServiceResult<List<AppSettingDto>>>;
public class GetSettingsQueryHandler : IRequestHandler<GetSettingsQuery, ServiceResult<List<AppSettingDto>>>
{
private readonly IApplicationDbContext _db;
public GetSettingsQueryHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<List<AppSettingDto>>> Handle(GetSettingsQuery request, CancellationToken ct)
{
var settings = await _db.AppSettings
.OrderBy(s => s.Category)
.ThenBy(s => s.Key)
.ToListAsync(ct);
return ServiceResult<List<AppSettingDto>>.Success(settings.Select(Map).ToList());
}
private static AppSettingDto Map(AppSetting s) => new(
s.Id, s.Key, s.Value, s.Description, s.Category, s.ValueType, s.AllowedValues, s.UpdatedAt);
}
@@ -0,0 +1,48 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Stats.Queries.GetAgentStats;
public record GetAgentStatsQuery : IRequest<ServiceResult<List<AgentStatItem>>>;
public class GetAgentStatsQueryHandler
: IRequestHandler<GetAgentStatsQuery, ServiceResult<List<AgentStatItem>>>
{
private readonly IApplicationDbContext _db;
public GetAgentStatsQueryHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<List<AgentStatItem>>> Handle(
GetAgentStatsQuery request, CancellationToken ct)
{
var totalAgents = await _db.Agents.CountAsync(ct);
var onlineAgents = await _db.Agents.CountAsync(a => a.Status == AgentStatus.Online, ct);
var offlineAgents = await _db.Agents.CountAsync(a => a.Status == AgentStatus.Offline, ct);
var errorAgents = await _db.Agents.CountAsync(a => a.Status == AgentStatus.Error, ct);
var byVersion = await _db.Agents
.AsNoTracking()
.GroupBy(a => a.Version)
.Select(g => new { Version = g.Key, Count = g.Count() })
.OrderByDescending(x => x.Count)
.ToListAsync(ct);
var items = new List<AgentStatItem>
{
new(StatType.Agents, "Total Agents", totalAgents, "#3B82F6"),
new(StatType.AgentsOnline, "Online", onlineAgents, "#22C55E"),
new(StatType.AgentsOffline, "Offline", offlineAgents, "#EF4444"),
};
if (errorAgents > 0)
items.Add(new(StatType.Agents, "Error", errorAgents, "#F59E0B"));
foreach (var v in byVersion)
items.Add(new(StatType.Agents, $"v{v.Version}", v.Count, "#8B5CF6"));
return ServiceResult<List<AgentStatItem>>.Success(items);
}
}
@@ -0,0 +1,41 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Stats.Queries.GetStats;
public record GetStatsQuery : IRequest<ServiceResult<StatsResponse>>;
public class GetStatsQueryHandler : IRequestHandler<GetStatsQuery, ServiceResult<StatsResponse>>
{
private readonly IApplicationDbContext _db;
public GetStatsQueryHandler(IApplicationDbContext db) => _db = db;
public async Task<ServiceResult<StatsResponse>> Handle(GetStatsQuery request, CancellationToken ct)
{
var totalSitesTask = _db.Sites.CountAsync(ct);
var totalCamerasTask = _db.Cameras.CountAsync(ct);
var totalAgentsTask = _db.Agents.CountAsync(ct);
var onlineAgentsTask = _db.Agents.CountAsync(a => a.Status == AgentStatus.Online, ct);
var activeSitesTask = _db.Sites.CountAsync(s => s.Enabled, ct);
var camerasOnlineTask = _db.Cameras.CountAsync(c => c.Status == CameraStatus.Online, ct);
var totalUsersTask = _db.Users.CountAsync(ct);
await Task.WhenAll(totalSitesTask, totalCamerasTask, totalAgentsTask,
onlineAgentsTask, activeSitesTask, camerasOnlineTask, totalUsersTask);
return ServiceResult<StatsResponse>.Success(new StatsResponse(
await totalSitesTask,
await totalCamerasTask,
await totalAgentsTask,
await onlineAgentsTask,
await activeSitesTask,
await totalAgentsTask - await onlineAgentsTask,
await camerasOnlineTask,
await totalCamerasTask - await camerasOnlineTask,
await totalUsersTask));
}
}