diff --git a/src/Heimdall.Application/Agents/Mapping/AgentMappingProfile.cs b/src/Heimdall.Application/Agents/Mapping/AgentMappingProfile.cs new file mode 100644 index 0000000..219e99f --- /dev/null +++ b/src/Heimdall.Application/Agents/Mapping/AgentMappingProfile.cs @@ -0,0 +1,23 @@ +using AutoMapper; +using Heimdall.Application.Agents.Commands.Heartbeat; +using Heimdall.Application.Agents.Commands.RegisterAgent; +using Heimdall.Application.DTOs; +using Heimdall.Domain.Entities; + +namespace Heimdall.Application.Agents.Mapping; + +public class AgentMappingProfile : Profile +{ + public AgentMappingProfile() + { + CreateMap() + .ForMember(d => d.GpuType, o => o.MapFrom(s => s.GpuType.ToString())); + + CreateMap(); + CreateMap() + .ForMember(d => d.AgentId, o => o.Ignore()) + .ForMember(d => d.MemoryMb, o => o.MapFrom(s => s.MemoryMb)) + .ForMember(d => d.GpuType, o => o.MapFrom(s => + s.GpuType != null ? Enum.Parse(s.GpuType, true) : (Domain.Enums.GpuAcceleration?)null)); + } +} diff --git a/src/Heimdall.Application/Assignments/Mapping/AssignmentMappingProfile.cs b/src/Heimdall.Application/Assignments/Mapping/AssignmentMappingProfile.cs new file mode 100644 index 0000000..9ad3b97 --- /dev/null +++ b/src/Heimdall.Application/Assignments/Mapping/AssignmentMappingProfile.cs @@ -0,0 +1,17 @@ +using AutoMapper; +using Heimdall.Application.Assignments.Commands.AssignCamera; +using Heimdall.Application.DTOs; +using Heimdall.Domain.Entities; + +namespace Heimdall.Application.Assignments.Mapping; + +public class AssignmentMappingProfile : Profile +{ + public AssignmentMappingProfile() + { + CreateMap() + .ForMember(d => d.AgentName, o => o.MapFrom(s => s.Agent.Name)); + + CreateMap(); + } +} diff --git a/src/Heimdall.Application/Auth/Mapping/AuthMappingProfile.cs b/src/Heimdall.Application/Auth/Mapping/AuthMappingProfile.cs new file mode 100644 index 0000000..56c05d1 --- /dev/null +++ b/src/Heimdall.Application/Auth/Mapping/AuthMappingProfile.cs @@ -0,0 +1,20 @@ +using AutoMapper; +using Heimdall.Application.Auth.Commands.Login; +using Heimdall.Application.Auth.Commands.Register; +using Heimdall.Application.DTOs; +using Heimdall.Domain.Entities; + +namespace Heimdall.Application.Auth.Mapping; + +public class AuthMappingProfile : Profile +{ + public AuthMappingProfile() + { + CreateMap() + .ForMember(d => d.Email, o => o.MapFrom(s => s.Email ?? string.Empty)) + .ForMember(d => d.Roles, o => o.Ignore()); + + CreateMap(); + CreateMap(); + } +} diff --git a/src/Heimdall.Application/Cameras/Mapping/CameraMappingProfile.cs b/src/Heimdall.Application/Cameras/Mapping/CameraMappingProfile.cs new file mode 100644 index 0000000..f88ce3c --- /dev/null +++ b/src/Heimdall.Application/Cameras/Mapping/CameraMappingProfile.cs @@ -0,0 +1,18 @@ +using AutoMapper; +using Heimdall.Application.Cameras.Commands.CreateCamera; +using Heimdall.Application.Cameras.Commands.UpdateCamera; +using Heimdall.Application.DTOs; +using Heimdall.Domain.Entities; + +namespace Heimdall.Application.Cameras.Mapping; + +public class CameraMappingProfile : Profile +{ + public CameraMappingProfile() + { + CreateMap(); + + CreateMap(); + CreateMap(); + } +} diff --git a/src/Heimdall.Application/Discovery/Mapping/DiscoveryMappingProfile.cs b/src/Heimdall.Application/Discovery/Mapping/DiscoveryMappingProfile.cs new file mode 100644 index 0000000..8aa2931 --- /dev/null +++ b/src/Heimdall.Application/Discovery/Mapping/DiscoveryMappingProfile.cs @@ -0,0 +1,36 @@ +using AutoMapper; +using Heimdall.Application.DTOs; +using Heimdall.Domain.Entities; + +namespace Heimdall.Application.Discovery.Mapping; + +public class DiscoveryMappingProfile : Profile +{ + public DiscoveryMappingProfile() + { + CreateMap() + .ForMember(d => d.Ip, o => o.MapFrom(s => s.IpAddress)) + .ForMember(d => d.CameraType, o => o.MapFrom(s => s.DetectedType)) + .ForMember(d => d.Arp, o => o.MapFrom(s => + s.MacAddress != null + ? new ArpInfo(s.MacAddress, s.Vendor) + : null)) + .ForMember(d => d.Onvif, o => o.MapFrom(s => + s.OnvifDeviceServiceUrl != null + ? new OnvifProbeInfo(s.OnvifDeviceServiceUrl, s.OnvifPort ?? 0, s.OnvifName, s.OnvifHardware, null) + : null)) + .ForMember(d => d.Http, o => o.MapFrom(s => + s.HttpPort.HasValue + ? new HttpProbeInfo(s.HttpPort.Value, s.HttpStatusCode ?? 0, s.HttpServerHeader) + : null)) + .ForMember(d => d.HomeKit, o => o.MapFrom(s => + s.IsHomeKitCamera == true + ? new HomeKitProbeInfo(s.HomeKitName ?? "", s.HomeKitDeviceId ?? "", s.HomeKitModel ?? "", "Camera", false, 0) + : null)) + .ForMember(d => d.MatchedBrands, o => o.Ignore()); + + CreateMap() + .ForMember(d => d.SourceUrl, o => o.MapFrom(s => s.Url)) + .ForMember(d => d.ScreenshotUrl, o => o.Ignore()); + } +} diff --git a/src/Heimdall.Application/Events/Mapping/EventMappingProfile.cs b/src/Heimdall.Application/Events/Mapping/EventMappingProfile.cs new file mode 100644 index 0000000..9a04840 --- /dev/null +++ b/src/Heimdall.Application/Events/Mapping/EventMappingProfile.cs @@ -0,0 +1,17 @@ +using AutoMapper; +using Heimdall.Application.DTOs; +using Heimdall.Application.Events.Commands.CreateEvent; +using Heimdall.Domain.Entities; + +namespace Heimdall.Application.Events.Mapping; + +public class EventMappingProfile : Profile +{ + public EventMappingProfile() + { + CreateMap() + .ForMember(d => d.SiteId, o => o.Ignore()); + + CreateMap(); + } +} diff --git a/src/Heimdall.Application/Events/Notifications/ConfigChangedNotification.cs b/src/Heimdall.Application/Events/Notifications/ConfigChangedNotification.cs new file mode 100644 index 0000000..843051b --- /dev/null +++ b/src/Heimdall.Application/Events/Notifications/ConfigChangedNotification.cs @@ -0,0 +1,5 @@ +using MediatR; + +namespace Heimdall.Application.Events.Notifications; + +public record ConfigChangedNotification(string AgentId, string Key, string Value) : INotification; diff --git a/src/Heimdall.Application/Events/Notifications/ConfigChangedNotificationHandler.cs b/src/Heimdall.Application/Events/Notifications/ConfigChangedNotificationHandler.cs new file mode 100644 index 0000000..c516a73 --- /dev/null +++ b/src/Heimdall.Application/Events/Notifications/ConfigChangedNotificationHandler.cs @@ -0,0 +1,23 @@ +using Heimdall.Application.Services; +using MediatR; + +namespace Heimdall.Application.Events.Notifications; + +public class ConfigChangedNotificationHandler : INotificationHandler +{ + private readonly IConfigBroadcastService _broadcast; + + public ConfigChangedNotificationHandler(IConfigBroadcastService broadcast) => _broadcast = broadcast; + + public async Task Handle(ConfigChangedNotification notification, CancellationToken ct) + { + if (!string.IsNullOrEmpty(notification.AgentId) && Guid.TryParse(notification.AgentId, out var agentId)) + { + await _broadcast.NotifyAgentSettingChanged(agentId, notification.Key, notification.Value, ct); + } + else + { + await _broadcast.NotifyGlobalSettingChanged(notification.Key, notification.Value, ct); + } + } +} diff --git a/src/Heimdall.Application/Events/Notifications/EventCreatedNotificationHandler.cs b/src/Heimdall.Application/Events/Notifications/EventCreatedNotificationHandler.cs new file mode 100644 index 0000000..637c875 --- /dev/null +++ b/src/Heimdall.Application/Events/Notifications/EventCreatedNotificationHandler.cs @@ -0,0 +1,16 @@ +using Heimdall.Application.Services; +using MediatR; + +namespace Heimdall.Application.Events.Notifications; + +public class EventCreatedNotificationHandler : INotificationHandler +{ + private readonly IEventBroadcastService _broadcast; + + public EventCreatedNotificationHandler(IEventBroadcastService broadcast) => _broadcast = broadcast; + + public async Task Handle(EventCreatedNotification notification, CancellationToken ct) + { + await _broadcast.NotifyEventCreated(notification.Event, ct); + } +} diff --git a/src/Heimdall.Application/Groups/Mapping/GroupMappingProfile.cs b/src/Heimdall.Application/Groups/Mapping/GroupMappingProfile.cs new file mode 100644 index 0000000..dc299a2 --- /dev/null +++ b/src/Heimdall.Application/Groups/Mapping/GroupMappingProfile.cs @@ -0,0 +1,18 @@ +using AutoMapper; +using Heimdall.Application.DTOs; +using Heimdall.Domain.Entities; + +namespace Heimdall.Application.Groups.Mapping; + +public class GroupMappingProfile : Profile +{ + public GroupMappingProfile() + { + CreateMap() + .ForMember(d => d.UserCount, o => o.MapFrom(s => s.UserGroups.Count)); + + CreateMap() + .ForMember(d => d.Email, o => o.MapFrom(s => s.User.Email ?? string.Empty)) + .ForMember(d => d.DisplayName, o => o.MapFrom(s => s.User.DisplayName)); + } +} diff --git a/src/Heimdall.Application/Persons/Mapping/PersonMappingProfile.cs b/src/Heimdall.Application/Persons/Mapping/PersonMappingProfile.cs new file mode 100644 index 0000000..80a6f4e --- /dev/null +++ b/src/Heimdall.Application/Persons/Mapping/PersonMappingProfile.cs @@ -0,0 +1,16 @@ +using AutoMapper; +using Heimdall.Application.DTOs; +using Heimdall.Domain.Entities; + +namespace Heimdall.Application.Persons.Mapping; + +public class PersonMappingProfile : Profile +{ + public PersonMappingProfile() + { + CreateMap() + .ForMember(d => d.FaceCount, o => o.MapFrom(s => s.Faces.Count)); + + CreateMap(); + } +} diff --git a/src/Heimdall.Application/Services/IConfigBroadcastService.cs b/src/Heimdall.Application/Services/IConfigBroadcastService.cs new file mode 100644 index 0000000..b78dc91 --- /dev/null +++ b/src/Heimdall.Application/Services/IConfigBroadcastService.cs @@ -0,0 +1,8 @@ +namespace Heimdall.Application.Services; + +public interface IConfigBroadcastService +{ + Task NotifyGlobalSettingChanged(string key, string value, CancellationToken ct = default); + Task NotifyAgentSettingChanged(Guid agentId, string key, string value, CancellationToken ct = default); + Task NotifyAllAgentsReload(CancellationToken ct = default); +} diff --git a/src/Heimdall.Application/Settings/Mapping/SettingMappingProfile.cs b/src/Heimdall.Application/Settings/Mapping/SettingMappingProfile.cs new file mode 100644 index 0000000..9b9de8c --- /dev/null +++ b/src/Heimdall.Application/Settings/Mapping/SettingMappingProfile.cs @@ -0,0 +1,19 @@ +using AutoMapper; +using Heimdall.Application.DTOs; +using Heimdall.Application.Settings.Commands.CreateAppSetting; +using Heimdall.Application.Settings.Commands.UpdateAppSetting; +using Heimdall.Domain.Entities; + +namespace Heimdall.Application.Settings.Mapping; + +public class SettingMappingProfile : Profile +{ + public SettingMappingProfile() + { + CreateMap(); + CreateMap(); + + CreateMap(); + CreateMap(); + } +} diff --git a/src/Heimdall.Application/Sites/Mapping/SiteMappingProfile.cs b/src/Heimdall.Application/Sites/Mapping/SiteMappingProfile.cs new file mode 100644 index 0000000..f3b3502 --- /dev/null +++ b/src/Heimdall.Application/Sites/Mapping/SiteMappingProfile.cs @@ -0,0 +1,21 @@ +using AutoMapper; +using Heimdall.Application.DTOs; +using Heimdall.Application.Sites.Commands.CreateSite; +using Heimdall.Application.Sites.Commands.UpdateSite; +using Heimdall.Domain.Entities; + +namespace Heimdall.Application.Sites.Mapping; + +public class SiteMappingProfile : Profile +{ + public SiteMappingProfile() + { + CreateMap(); + CreateMap(); + CreateMap() + .ForMember(d => d.Token, o => o.Ignore()); + + CreateMap(); + CreateMap(); + } +} diff --git a/src/Heimdall.Application/Users/Mapping/UserMappingProfile.cs b/src/Heimdall.Application/Users/Mapping/UserMappingProfile.cs new file mode 100644 index 0000000..ddfa571 --- /dev/null +++ b/src/Heimdall.Application/Users/Mapping/UserMappingProfile.cs @@ -0,0 +1,26 @@ +using AutoMapper; +using Heimdall.Application.DTOs; +using Heimdall.Application.Users.Commands.CreateUser; +using Heimdall.Application.Users.Commands.UpdateUser; +using Heimdall.Domain.Entities; + +namespace Heimdall.Application.Users.Mapping; + +public class UserMappingProfile : Profile +{ + public UserMappingProfile() + { + CreateMap() + .ForMember(d => d.Email, o => o.MapFrom(s => s.Email ?? string.Empty)) + .ForMember(d => d.Roles, o => o.Ignore()) + .ForMember(d => d.SiteIds, o => o.Ignore()) + .ForMember(d => d.TwoFactorEnabled, o => o.Ignore()) + .ForMember(d => d.IsLockedOut, o => o.Ignore()) + .ForMember(d => d.LockoutEnd, o => o.MapFrom(s => s.LockoutEnd.HasValue ? s.LockoutEnd.Value.UtcDateTime : (DateTime?)null)) + .ForMember(d => d.AccessFailedCount, o => o.MapFrom(s => s.AccessFailedCount)) + .ForMember(d => d.EmailConfirmed, o => o.MapFrom(s => s.EmailConfirmed)); + + CreateMap(); + CreateMap(); + } +} diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs b/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs new file mode 100644 index 0000000..bca499b --- /dev/null +++ b/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs @@ -0,0 +1,42 @@ +using Heimdall.Infrastructure.Jobs; +using Hangfire; +using Hangfire.PostgreSql; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace Heimdall.Infrastructure.BackgroundJobs; + +public static class DependencyInjection +{ + public static IServiceCollection AddBackgroundJobs( + this IServiceCollection services, + IConfiguration configuration) + { + var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL") + ?? configuration.GetConnectionString("Default"); + + if (string.IsNullOrEmpty(connectionString)) + return services; + +#pragma warning disable CS0618 + services.AddHangfire(config => + { + config.UsePostgreSqlStorage(connectionString, new PostgreSqlStorageOptions + { + SchemaName = "hangfire" + }); + }); +#pragma warning restore CS0618 + + services.AddHangfireServer(options => + { + options.WorkerCount = 2; + options.Queues = ["default", "heartbeat"]; + }); + + services.AddScoped(); + services.AddScoped(); + + return services; + } +} diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs new file mode 100644 index 0000000..cb6f6fc --- /dev/null +++ b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs @@ -0,0 +1,20 @@ +using Heimdall.Infrastructure.Jobs; +using Hangfire; + +namespace Heimdall.Infrastructure.BackgroundJobs; + +public static class JobSetup +{ + public static void ConfigureRecurringJobs(IRecurringJobManager manager) + { + manager.AddOrUpdate( + "heartbeat-monitor", + job => job.ExecuteAsync(CancellationToken.None), + "*/1 * * * *"); + + manager.AddOrUpdate( + "agent-failover", + job => job.ExecuteAsync(CancellationToken.None), + "*/1 * * * *"); + } +} diff --git a/src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj b/src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj index bf694f4..5eb198e 100644 --- a/src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj +++ b/src/Heimdall.Infrastructure/Heimdall.Infrastructure.csproj @@ -16,6 +16,7 @@ + diff --git a/src/Heimdall.Web/Controllers/AgentsController.cs b/src/Heimdall.Web/Controllers/AgentsController.cs index ed1bf6f..881b45a 100644 --- a/src/Heimdall.Web/Controllers/AgentsController.cs +++ b/src/Heimdall.Web/Controllers/AgentsController.cs @@ -1,6 +1,12 @@ +using Heimdall.Application.Agents.Commands.RegisterAgent; +using Heimdall.Application.Agents.Commands.Heartbeat; +using Heimdall.Application.Agents.Queries.GetAgent; +using Heimdall.Application.Agents.Queries.GetAgentsBySite; +using Heimdall.Application.Agents.Queries.GetAllAgents; using Heimdall.Application.DTOs; -using Heimdall.Application.Services; +using Heimdall.Domain.Enums; using Heimdall.Infrastructure.Security; +using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; @@ -12,9 +18,9 @@ namespace Heimdall.Api.Controllers; [EnableRateLimiting("Api")] public class AgentsController : ControllerBase { - private readonly IAgentService _agentService; + private readonly IMediator _mediator; - public AgentsController(IAgentService agentService) => _agentService = agentService; + public AgentsController(IMediator mediator) => _mediator = mediator; /// Register an agent using a site registration token. [AllowAnonymous] @@ -28,7 +34,8 @@ public class AgentsController : ControllerBase var apiKey = Request.Headers.Authorization.FirstOrDefault() ?.Replace("Bearer ", "", StringComparison.OrdinalIgnoreCase); - var result = await _agentService.RegisterAsync(request, apiKey, ct); + var command = new RegisterAgentCommand(request.Token, request.Hostname, request.Version, request.PublicIp); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 401, new { error = result.Error }); @@ -42,7 +49,9 @@ public class AgentsController : ControllerBase public async Task Heartbeat( Guid id, [FromBody] AgentHeartbeatRequest request, CancellationToken ct) { - var result = await _agentService.HeartbeatAsync(id, request, ct); + GpuAcceleration? gpuType = request.GpuType is not null && Enum.TryParse(request.GpuType, true, out var parsed) ? parsed : null; + var command = new HeartbeatCommand(id, request.PublicIp, request.HasGpu, request.CpuCores, (int?)request.MemoryMb, gpuType); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -55,7 +64,7 @@ public class AgentsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task GetById(Guid id, CancellationToken ct) { - var result = await _agentService.GetByIdAsync(id, ct); + var result = await _mediator.Send(new GetAgentQuery(id), ct); return result.IsSuccess ? Ok(result.Data) : NotFound(new { error = result.Error }); @@ -69,7 +78,7 @@ public class AgentsController : ControllerBase public async Task ListBySite( Guid siteId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) { - var result = await _agentService.ListBySiteAsync(siteId, page, pageSize, ct); + var result = await _mediator.Send(new GetAgentsBySiteQuery(siteId, page, pageSize), ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); return Ok(result.Data); @@ -83,7 +92,7 @@ public class AgentsController : ControllerBase public async Task ListAll( [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) { - var result = await _agentService.ListAllAsync(page, pageSize, ct); + var result = await _mediator.Send(new GetAllAgentsQuery(page, pageSize), ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); return Ok(result.Data); diff --git a/src/Heimdall.Web/Controllers/AssignmentsController.cs b/src/Heimdall.Web/Controllers/AssignmentsController.cs index 3191108..98f488e 100644 --- a/src/Heimdall.Web/Controllers/AssignmentsController.cs +++ b/src/Heimdall.Web/Controllers/AssignmentsController.cs @@ -1,7 +1,15 @@ +using Heimdall.Application.Assignments.Commands.AssignCamera; +using Heimdall.Application.Assignments.Commands.AssignSite; +using Heimdall.Application.Assignments.Commands.Failover; +using Heimdall.Application.Assignments.Commands.ReleaseCamera; +using Heimdall.Application.Assignments.Queries.GetActiveAssignment; +using Heimdall.Application.Assignments.Queries.GetAgentAssignments; +using Heimdall.Application.Assignments.Queries.GetCameraHistory; using Heimdall.Application.Common; using Heimdall.Application.DTOs; using Heimdall.Application.Services; using Heimdall.Infrastructure.Security; +using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; @@ -20,11 +28,11 @@ namespace Heimdall.Api.Controllers; [Authorize(AuthenticationSchemes = "JwtBearer")] public class AssignmentsController : ControllerBase { - private readonly ICameraAssignmentService _assignmentService; + private readonly IMediator _mediator; - public AssignmentsController(ICameraAssignmentService assignmentService) + public AssignmentsController(IMediator mediator) { - _assignmentService = assignmentService; + _mediator = mediator; } /// Assign a single camera to a specific agent. @@ -34,8 +42,8 @@ public class AssignmentsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task AssignCamera([FromBody] AssignRequest request, CancellationToken ct) { - var result = await _assignmentService.AssignCameraAsync( - request.CameraId, request.AgentId, request.Reason ?? "manual", ct); + var command = new AssignCameraCommand(request.CameraId, request.AgentId, request.Reason ?? "manual"); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); @@ -51,10 +59,9 @@ public class AssignmentsController : ControllerBase if (!Enum.TryParse(strategy, true, out var parsed)) return BadRequest(new { error = $"Invalid strategy: {strategy}. Valid: RoundRobin, GpuPriority, LeastCameras" }); - var result = await _assignmentService.AssignSiteCamerasAsync(siteId, parsed, ct); - var assignedCount = result.Data; + var result = await _mediator.Send(new AssignSiteCommand(siteId, parsed), ct); return result.IsSuccess - ? Ok(new AssignmentResult(assignedCount)) + ? Ok(new AssignmentResult(result.Data)) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } @@ -65,9 +72,9 @@ public class AssignmentsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task FailoverAgent(Guid agentId, CancellationToken ct) { - var result = await _assignmentService.FailoverAgentAsync(agentId, ct); + var result = await _mediator.Send(new FailoverCommand(agentId), ct); return result.IsSuccess - ? Ok(new FailoverResult(result.Data?.Count ?? 0)) + ? Ok(new FailoverResult(result.Data)) : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); } @@ -78,16 +85,11 @@ public class AssignmentsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task GetCameraAssignment(Guid cameraId, CancellationToken ct) { - var assignment = await _assignmentService.GetActiveAssignmentAsync(cameraId, ct); - if (assignment is null) + var result = await _mediator.Send(new GetActiveAssignmentQuery(cameraId), ct); + if (!result.IsSuccess || result.Data is null) return NotFound(new { error = "Camera not assigned" }); - return Ok(new AssignmentResponse( - assignment.CameraId, - assignment.AgentId, - assignment.Agent.Name, - assignment.Reason, - assignment.AssignedAt)); + return Ok(result.Data); } /// Get all active assignments (workload) for an agent. @@ -96,9 +98,8 @@ public class AssignmentsController : ControllerBase [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] public async Task GetAgentAssignments(Guid agentId, CancellationToken ct) { - var assignments = await _assignmentService.GetAgentAssignmentsAsync(agentId, ct); - return Ok(assignments.Select(a => new AssignmentResponse( - a.CameraId, a.AgentId, a.Agent?.Name ?? "", a.Reason, a.AssignedAt)).ToList()); + var result = await _mediator.Send(new GetAgentAssignmentsQuery(agentId), ct); + return Ok(result.Data); } /// Get assignment history for a camera. @@ -107,9 +108,8 @@ public class AssignmentsController : ControllerBase [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] public async Task GetCameraHistory(Guid cameraId, CancellationToken ct) { - var history = await _assignmentService.GetCameraHistoryAsync(cameraId, ct); - return Ok(history.Select(a => new AssignmentResponse( - a.CameraId, a.AgentId, a.Agent?.Name ?? "", a.Reason, a.AssignedAt)).ToList()); + var result = await _mediator.Send(new GetCameraHistoryQuery(cameraId), ct); + return Ok(result.Data); } /// Release a camera from its current agent. @@ -119,7 +119,7 @@ public class AssignmentsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task ReleaseCamera(Guid cameraId, CancellationToken ct) { - var result = await _assignmentService.ReleaseCameraAsync(cameraId, ct); + var result = await _mediator.Send(new ReleaseCameraCommand(cameraId), ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); diff --git a/src/Heimdall.Web/Controllers/AuditLogsController.cs b/src/Heimdall.Web/Controllers/AuditLogsController.cs index 7b9659f..f920494 100644 --- a/src/Heimdall.Web/Controllers/AuditLogsController.cs +++ b/src/Heimdall.Web/Controllers/AuditLogsController.cs @@ -1,6 +1,7 @@ +using Heimdall.Application.Audit.Queries.GetAuditLogs; using Heimdall.Application.DTOs; -using Heimdall.Application.Services; using Heimdall.Infrastructure.Security; +using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; @@ -13,9 +14,9 @@ namespace Heimdall.Api.Controllers; [EnableRateLimiting("Api")] public class AuditLogsController : ControllerBase { - private readonly IAuditLogService _auditLogService; + private readonly IMediator _mediator; - public AuditLogsController(IAuditLogService auditLogService) => _auditLogService = auditLogService; + public AuditLogsController(IMediator mediator) => _mediator = mediator; /// List audit log entries with optional filtering. [HttpGet] @@ -28,7 +29,7 @@ public class AuditLogsController : ControllerBase [FromQuery] int pageSize = 20, CancellationToken ct = default) { - var result = await _auditLogService.ListAsync(resourceType, action, page, pageSize, ct); + var result = await _mediator.Send(new GetAuditLogsQuery(resourceType, action, page, pageSize), ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); return Ok(result.Data); diff --git a/src/Heimdall.Web/Controllers/AuthController.cs b/src/Heimdall.Web/Controllers/AuthController.cs index 8824c3e..33930cf 100644 --- a/src/Heimdall.Web/Controllers/AuthController.cs +++ b/src/Heimdall.Web/Controllers/AuthController.cs @@ -1,8 +1,17 @@ using System.Security.Claims; +using Heimdall.Application.Auth.Commands.Register; +using Heimdall.Application.Auth.Commands.Login; +using Heimdall.Application.Auth.Commands.Verify2fa; +using Heimdall.Application.Auth.Commands.RefreshToken; +using Heimdall.Application.Auth.Commands.ChangePassword; +using Heimdall.Application.Auth.Commands.RegisterAdmin; +using Heimdall.Application.Auth.Commands.Enable2fa; +using Heimdall.Application.Auth.Commands.Disable2fa; +using Heimdall.Application.Auth.Commands.Logout; using Heimdall.Application.Common; using Heimdall.Application.DTOs; -using Heimdall.Application.Services; using Heimdall.Infrastructure.Security; +using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; @@ -14,12 +23,12 @@ namespace Heimdall.Api.Controllers; [EnableRateLimiting("Auth")] public class AuthController : ControllerBase { - private readonly IAuthService _authService; + private readonly IMediator _mediator; private readonly IWebHostEnvironment _env; - public AuthController(IAuthService authService, IWebHostEnvironment env) + public AuthController(IMediator mediator, IWebHostEnvironment env) { - _authService = authService; + _mediator = mediator; _env = env; } @@ -30,7 +39,8 @@ public class AuthController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task Register([FromBody] RegisterRequest request, CancellationToken ct) { - var result = await _authService.RegisterAsync(request, ct); + var command = new RegisterCommand(request.Email, request.Password, request.DisplayName); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -43,7 +53,8 @@ public class AuthController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] public async Task Login([FromBody] LoginRequest request, CancellationToken ct) { - var result = await _authService.LoginAsync(request, ct); + var command = new LoginCommand(request.Email, request.Password); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 401, new { error = result.Error }); @@ -56,7 +67,8 @@ public class AuthController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] public async Task Verify2fa([FromBody] Verify2faRequest request, CancellationToken ct) { - var result = await _authService.Verify2faAsync(request, ct); + var command = new Verify2faCommand(request.Email, request.Code); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 401, new { error = result.Error }); @@ -69,7 +81,7 @@ public class AuthController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] public async Task Refresh([FromBody] RefreshTokenRequest request, CancellationToken ct) { - var result = await _authService.RefreshTokenAsync(request.RefreshToken, ct); + var result = await _mediator.Send(new RefreshTokenCommand(request.RefreshToken), ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 401, new { error = result.Error }); @@ -88,8 +100,8 @@ public class AuthController : ControllerBase if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) return Unauthorized(new { error = "Invalid user identity" }); - var result = await _authService.ChangePasswordAsync( - userId, request.CurrentPassword, request.NewPassword, ct); + var command = new ChangePasswordCommand(userId, request.CurrentPassword, request.NewPassword); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -106,7 +118,8 @@ public class AuthController : ControllerBase if (!_env.IsEnvironment("Testing") && !_env.IsDevelopment()) return NotFound(); - var result = await _authService.RegisterAdminAsync(request, ct); + var command = new RegisterAdminCommand(request.Email, request.Password, request.DisplayName); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -123,7 +136,7 @@ public class AuthController : ControllerBase if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) return Unauthorized(new { error = "Invalid user identity" }); - var result = await _authService.Enable2faAsync(userId, ct); + var result = await _mediator.Send(new Enable2faCommand(userId), ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -140,7 +153,7 @@ public class AuthController : ControllerBase if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) return Unauthorized(new { error = "Invalid user identity" }); - var result = await _authService.Disable2faAsync(userId, ct); + var result = await _mediator.Send(new Disable2faCommand(userId), ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -156,7 +169,7 @@ public class AuthController : ControllerBase if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) return Unauthorized(new { error = "Invalid user identity" }); - await _authService.LogoutAsync(userId, request.RefreshToken, ct); + await _mediator.Send(new LogoutCommand(userId, request.RefreshToken), ct); return Ok(); } } diff --git a/src/Heimdall.Web/Controllers/CamerasController.cs b/src/Heimdall.Web/Controllers/CamerasController.cs index 2111a8e..c77c5bb 100644 --- a/src/Heimdall.Web/Controllers/CamerasController.cs +++ b/src/Heimdall.Web/Controllers/CamerasController.cs @@ -1,6 +1,11 @@ +using Heimdall.Application.Cameras.Commands.CreateCamera; +using Heimdall.Application.Cameras.Commands.UpdateCamera; +using Heimdall.Application.Cameras.Commands.DeleteCamera; +using Heimdall.Application.Cameras.Queries.GetCamera; +using Heimdall.Application.Cameras.Queries.GetCamerasBySite; using Heimdall.Application.DTOs; -using Heimdall.Application.Services; using Heimdall.Infrastructure.Security; +using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; @@ -12,9 +17,9 @@ namespace Heimdall.Api.Controllers; [EnableRateLimiting("Api")] public class CamerasController : ControllerBase { - private readonly ICameraService _cameraService; + private readonly IMediator _mediator; - public CamerasController(ICameraService cameraService) => _cameraService = cameraService; + public CamerasController(IMediator mediator) => _mediator = mediator; /// Create a new camera. [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)] @@ -23,7 +28,8 @@ public class CamerasController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task Create([FromBody] CreateCameraRequest request, CancellationToken ct) { - var result = await _cameraService.CreateAsync(request, ct); + var command = new CreateCameraCommand(request.SiteId, request.Name, request.RtspUrl, request.Manufacturer, request.Model); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -36,7 +42,7 @@ public class CamerasController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task GetById(Guid id, CancellationToken ct) { - var result = await _cameraService.GetByIdAsync(id, ct); + var result = await _mediator.Send(new GetCameraQuery(id), ct); return result.IsSuccess ? Ok(result.Data) : NotFound(new { error = result.Error }); @@ -50,7 +56,7 @@ public class CamerasController : ControllerBase public async Task ListBySite( Guid siteId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) { - var result = await _cameraService.ListBySiteAsync(siteId, page, pageSize, ct); + var result = await _mediator.Send(new GetCamerasBySiteQuery(siteId, page, pageSize), ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); return Ok(result.Data); @@ -64,7 +70,8 @@ public class CamerasController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task Update(Guid id, [FromBody] UpdateCameraRequest request, CancellationToken ct) { - var result = await _cameraService.UpdateAsync(id, request, ct); + var command = new UpdateCameraCommand(id, request.Name, request.RtspUrl, request.Status, request.Manufacturer, request.Model); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -78,7 +85,7 @@ public class CamerasController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task Delete(Guid id, CancellationToken ct) { - var result = await _cameraService.DeleteAsync(id, ct); + var result = await _mediator.Send(new DeleteCameraCommand(id), ct); return result.IsSuccess ? NoContent() : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); diff --git a/src/Heimdall.Web/Controllers/DiscoveryController.cs b/src/Heimdall.Web/Controllers/DiscoveryController.cs index 8c92e4c..ae23ab5 100644 --- a/src/Heimdall.Web/Controllers/DiscoveryController.cs +++ b/src/Heimdall.Web/Controllers/DiscoveryController.cs @@ -1,6 +1,16 @@ +using Heimdall.Application.Discovery.Commands.ProbeIp; +using Heimdall.Application.Discovery.Commands.ScanSubnet; +using Heimdall.Application.Discovery.Commands.ConfirmDiscovery; +using Heimdall.Application.Discovery.Commands.BuildStreamUrls; +using Heimdall.Application.Discovery.Commands.TestStreams; +using Heimdall.Application.Discovery.Commands.CancelTestSession; +using Heimdall.Application.Discovery.Queries.SearchDatabase; +using Heimdall.Application.Discovery.Queries.GetTestSession; +using Heimdall.Application.Discovery.Queries.GetScreenshot; +using Heimdall.Application.Discovery.Queries.CheckDuplicate; using Heimdall.Application.DTOs; -using Heimdall.Application.Services; using Heimdall.Infrastructure.Security; +using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; @@ -18,11 +28,11 @@ namespace Heimdall.Api.Controllers; [EnableRateLimiting("Api")] public class DiscoveryController : ControllerBase { - private readonly ICameraDiscoveryService _discoveryService; + private readonly IMediator _mediator; - public DiscoveryController(ICameraDiscoveryService discoveryService) + public DiscoveryController(IMediator mediator) { - _discoveryService = discoveryService; + _mediator = mediator; } /// Probe a single IP address for camera services. @@ -32,7 +42,8 @@ public class DiscoveryController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task ProbeIp([FromBody] ProbeRequest request, CancellationToken ct) { - var result = await _discoveryService.ProbeIpAsync(request, ct); + var command = new ProbeIpCommand(request.SiteId, request.Ip); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -45,7 +56,8 @@ public class DiscoveryController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task ScanSubnet([FromBody] ScanRequest request, CancellationToken ct) { - var result = await _discoveryService.ScanSubnetAsync(request, ct); + var command = new ScanSubnetCommand(request.SiteId, request.SubnetCidr, request.TimeoutMs); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -57,7 +69,7 @@ public class DiscoveryController : ControllerBase [ProducesResponseType(typeof(SearchResponse), StatusCodes.Status200OK)] public async Task SearchDatabase([FromQuery] string? q, CancellationToken ct) { - var result = await _discoveryService.SearchDatabaseAsync(q ?? "", ct); + var result = await _mediator.Send(new SearchDatabaseQuery(q ?? ""), ct); return Ok(result.Data); } @@ -68,7 +80,8 @@ public class DiscoveryController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task BuildStreamUrls([FromBody] StreamBuildRequest request, CancellationToken ct) { - var result = await _discoveryService.BuildStreamUrlsAsync(request, ct); + var command = new BuildStreamUrlsCommand(request.Ids, request.Ip, request.Username, request.Password, request.Channel, request.PortFilter); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -81,7 +94,8 @@ public class DiscoveryController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task TestStreams([FromBody] StreamTestRequest request, CancellationToken ct) { - var result = await _discoveryService.TestStreamsAsync(request, ct); + var command = new TestStreamsCommand(request.SourceId, request.Streams); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -94,7 +108,7 @@ public class DiscoveryController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task GetTestSession(Guid sessionId, CancellationToken ct) { - var result = await _discoveryService.GetTestSessionAsync(sessionId, ct); + var result = await _mediator.Send(new GetTestSessionQuery(sessionId), ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); @@ -107,10 +121,10 @@ public class DiscoveryController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task GetScreenshot(Guid sessionId, int index, CancellationToken ct) { - var screenshot = await _discoveryService.GetScreenshotAsync(sessionId, index, ct); - if (screenshot is null) + var result = await _mediator.Send(new GetScreenshotQuery(sessionId, index), ct); + if (!result.IsSuccess || result.Data is null) return NotFound(new { error = "Screenshot not available" }); - return File(screenshot, "image/jpeg"); + return File(result.Data, "image/jpeg"); } /// Cancel a running stream test session. @@ -120,7 +134,7 @@ public class DiscoveryController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task CancelTestSession(Guid sessionId, CancellationToken ct) { - var result = await _discoveryService.CancelTestSessionAsync(sessionId, ct); + var result = await _mediator.Send(new CancelTestSessionCommand(sessionId), ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); @@ -132,7 +146,8 @@ public class DiscoveryController : ControllerBase [ProducesResponseType(typeof(CameraCheckResponse), StatusCodes.Status200OK)] public async Task CheckDuplicate([FromBody] CheckDuplicateRequest request, CancellationToken ct) { - var result = await _discoveryService.CheckDuplicateAsync(request, ct); + var query = new CheckDuplicateQuery(request.SiteId, request.Ip, request.Mac); + var result = await _mediator.Send(query, ct); return Ok(result.Data); } @@ -144,7 +159,12 @@ public class DiscoveryController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task ConfirmDiscovery([FromBody] ConfirmDiscoveryRequest request, CancellationToken ct) { - var result = await _discoveryService.ConfirmDiscoveryAsync(request, ct); + var command = new ConfirmDiscoveryCommand( + request.SiteId, request.Name, request.DiscoveryResultId, + request.MainStreamUrl, request.SubStreamUrl, + request.Username, request.Password, + request.DetectionProfile, request.AgentId); + var result = await _mediator.Send(command, ct); if (result.IsSuccess) return Ok(result.Data); diff --git a/src/Heimdall.Web/Controllers/EventsController.cs b/src/Heimdall.Web/Controllers/EventsController.cs index 9de7180..9d735fd 100644 --- a/src/Heimdall.Web/Controllers/EventsController.cs +++ b/src/Heimdall.Web/Controllers/EventsController.cs @@ -1,7 +1,13 @@ using Heimdall.Application.DTOs; -using Heimdall.Application.Services; +using Heimdall.Application.Events.Commands.CreateEvent; +using Heimdall.Application.Events.Commands.AttachSnapshot; +using Heimdall.Application.Events.Commands.DeleteEvent; +using Heimdall.Application.Events.Queries.GetEvent; +using Heimdall.Application.Events.Queries.GetEvents; +using Heimdall.Application.Events.Queries.GetRecentByCamera; using Heimdall.Domain.Enums; using Heimdall.Infrastructure.Security; +using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; @@ -17,9 +23,9 @@ namespace Heimdall.Api.Controllers; [EnableRateLimiting("Api")] public class EventsController : ControllerBase { - private readonly ICameraEventService _eventService; + private readonly IMediator _mediator; - public EventsController(ICameraEventService eventService) => _eventService = eventService; + public EventsController(IMediator mediator) => _mediator = mediator; /// Record a new detection event (called by agents). [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] @@ -28,7 +34,8 @@ public class EventsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task Create([FromBody] CreateCameraEventRequest request, CancellationToken ct) { - var result = await _eventService.CreateAsync(request, ct); + var command = new CreateEventCommand(request.CameraId, request.Type, request.Confidence, request.Label, request.MetadataJson, request.OccurredAt); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -41,7 +48,7 @@ public class EventsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task GetById(Guid id, CancellationToken ct) { - var result = await _eventService.GetByIdAsync(id, ct); + var result = await _mediator.Send(new GetEventQuery(id), ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); @@ -66,8 +73,7 @@ public class EventsController : ControllerBase if (type is not null && Enum.TryParse(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); + var result = await _mediator.Send(new GetEventsQuery(cameraId, siteId, parsedType, from, to, minConfidence, page, pageSize), ct); return Ok(result.Data); } @@ -77,7 +83,7 @@ public class EventsController : ControllerBase [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] public async Task GetRecentByCamera(Guid cameraId, [FromQuery] int count = 20, CancellationToken ct = default) { - var result = await _eventService.GetRecentByCameraAsync(cameraId, count, ct); + var result = await _mediator.Send(new GetRecentByCameraQuery(cameraId, count), ct); return Ok(result.Data); } @@ -88,7 +94,7 @@ public class EventsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task AttachSnapshot(Guid id, [FromBody] AttachSnapshotRequest request, CancellationToken ct) { - var result = await _eventService.AttachSnapshotAsync(id, request.SnapshotUrl, request.ThumbUrl, ct); + var result = await _mediator.Send(new AttachSnapshotCommand(id, request.SnapshotUrl, request.ThumbUrl), ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); @@ -101,7 +107,7 @@ public class EventsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task Delete(Guid id, CancellationToken ct) { - var result = await _eventService.DeleteAsync(id, ct); + var result = await _mediator.Send(new DeleteEventCommand(id), ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); diff --git a/src/Heimdall.Web/Controllers/GroupsController.cs b/src/Heimdall.Web/Controllers/GroupsController.cs index e1deb52..9b74cb8 100644 --- a/src/Heimdall.Web/Controllers/GroupsController.cs +++ b/src/Heimdall.Web/Controllers/GroupsController.cs @@ -1,6 +1,14 @@ using Heimdall.Application.DTOs; -using Heimdall.Application.Services; +using Heimdall.Application.Groups.Commands.CreateGroup; +using Heimdall.Application.Groups.Commands.UpdateGroup; +using Heimdall.Application.Groups.Commands.DeleteGroup; +using Heimdall.Application.Groups.Commands.AddUserToGroup; +using Heimdall.Application.Groups.Commands.RemoveUserFromGroup; +using Heimdall.Application.Groups.Queries.GetGroups; +using Heimdall.Application.Groups.Queries.GetGroup; +using Heimdall.Application.Groups.Queries.GetGroupMembers; using Heimdall.Infrastructure.Security; +using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; @@ -16,9 +24,9 @@ namespace Heimdall.Api.Controllers; [EnableRateLimiting("Api")] public class GroupsController : ControllerBase { - private readonly IGroupService _groupService; + private readonly IMediator _mediator; - public GroupsController(IGroupService groupService) => _groupService = groupService; + public GroupsController(IMediator mediator) => _mediator = mediator; /// List all groups (Admin only). [HttpGet] @@ -27,7 +35,7 @@ public class GroupsController : ControllerBase public async Task List( [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) { - var result = await _groupService.ListAsync(page, pageSize, ct); + var result = await _mediator.Send(new GetGroupsQuery(page, pageSize), ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); return Ok(result.Data); @@ -39,7 +47,7 @@ public class GroupsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task GetById(Guid id, CancellationToken ct) { - var result = await _groupService.GetByIdAsync(id, ct); + var result = await _mediator.Send(new GetGroupQuery(id), ct); return result.IsSuccess ? Ok(result.Data) : NotFound(new { error = result.Error }); @@ -51,7 +59,8 @@ public class GroupsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task Create([FromBody] CreateGroupRequest request, CancellationToken ct) { - var result = await _groupService.CreateAsync(request, ct); + var command = new CreateGroupCommand(request.Name, request.Description); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -65,7 +74,8 @@ public class GroupsController : ControllerBase public async Task Update( Guid id, [FromBody] UpdateGroupRequest request, CancellationToken ct) { - var result = await _groupService.UpdateAsync(id, request, ct); + var command = new UpdateGroupCommand(id, request.Name, request.Description); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -77,7 +87,7 @@ public class GroupsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task Delete(Guid id, CancellationToken ct) { - var result = await _groupService.DeleteAsync(id, ct); + var result = await _mediator.Send(new DeleteGroupCommand(id), ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -90,7 +100,7 @@ public class GroupsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task AddUser(Guid groupId, Guid userId, CancellationToken ct) { - var result = await _groupService.AddUserAsync(groupId, userId, ct); + var result = await _mediator.Send(new AddUserToGroupCommand(groupId, userId), ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -103,7 +113,7 @@ public class GroupsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task RemoveUser(Guid groupId, Guid userId, CancellationToken ct) { - var result = await _groupService.RemoveUserAsync(groupId, userId, ct); + var result = await _mediator.Send(new RemoveUserFromGroupCommand(groupId, userId), ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -115,7 +125,7 @@ public class GroupsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task GetMembers(Guid groupId, CancellationToken ct) { - var result = await _groupService.GetMembersAsync(groupId, ct); + var result = await _mediator.Send(new GetGroupMembersQuery(groupId), ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); diff --git a/src/Heimdall.Web/Controllers/PersonsController.cs b/src/Heimdall.Web/Controllers/PersonsController.cs index e03b8cc..204974b 100644 --- a/src/Heimdall.Web/Controllers/PersonsController.cs +++ b/src/Heimdall.Web/Controllers/PersonsController.cs @@ -1,6 +1,14 @@ using Heimdall.Application.DTOs; -using Heimdall.Application.Services; +using Heimdall.Application.Persons.Commands.CreatePerson; +using Heimdall.Application.Persons.Commands.UpdatePerson; +using Heimdall.Application.Persons.Commands.DeletePerson; +using Heimdall.Application.Persons.Commands.RegisterFace; +using Heimdall.Application.Persons.Commands.DeleteFace; +using Heimdall.Application.Persons.Queries.GetPerson; +using Heimdall.Application.Persons.Queries.GetPersons; +using Heimdall.Application.Persons.Queries.GetFaces; using Heimdall.Infrastructure.Security; +using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; @@ -12,15 +20,16 @@ namespace Heimdall.Api.Controllers; [EnableRateLimiting("Api")] public class PersonsController : ControllerBase { - private readonly IPersonService _personService; + private readonly IMediator _mediator; - public PersonsController(IPersonService personService) => _personService = personService; + public PersonsController(IMediator mediator) => _mediator = mediator; [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonWrite)] [HttpPost] public async Task Create([FromBody] CreatePersonRequest request, CancellationToken ct) { - var result = await _personService.CreateAsync(request, ct); + var command = new CreatePersonCommand(request.DisplayName, request.Category, request.Notes, request.IsWatchlisted); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } @@ -28,7 +37,8 @@ public class PersonsController : ControllerBase [HttpPut("{id:guid}")] public async Task Update(Guid id, [FromBody] UpdatePersonRequest request, CancellationToken ct) { - var result = await _personService.UpdateAsync(id, request, ct); + var command = new UpdatePersonCommand(id, request.DisplayName, request.Notes, request.Category, request.IsWatchlisted); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); } @@ -36,7 +46,7 @@ public class PersonsController : ControllerBase [HttpGet("{id:guid}")] public async Task GetById(Guid id, CancellationToken ct) { - var result = await _personService.GetByIdAsync(id, ct); + var result = await _mediator.Send(new GetPersonQuery(id), ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); } @@ -44,7 +54,7 @@ public class PersonsController : ControllerBase [HttpGet] public async Task GetAll([FromQuery] string? category, CancellationToken ct) { - var result = await _personService.GetAllAsync(category, ct); + var result = await _mediator.Send(new GetPersonsQuery(category), ct); return Ok(result.Data); } @@ -52,7 +62,7 @@ public class PersonsController : ControllerBase [HttpDelete("{id:guid}")] public async Task Delete(Guid id, CancellationToken ct) { - var result = await _personService.DeleteAsync(id, ct); + var result = await _mediator.Send(new DeletePersonCommand(id), ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); } @@ -60,7 +70,8 @@ public class PersonsController : ControllerBase [HttpPost("{personId:guid}/faces")] public async Task RegisterFace(Guid personId, [FromBody] RegisterFaceRequest request, CancellationToken ct) { - var result = await _personService.RegisterFaceAsync(request with { PersonId = personId }, ct); + var command = new RegisterFaceCommand(personId, request.Embedding, request.ThumbnailUrl, request.SourceEventId); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } @@ -68,7 +79,7 @@ public class PersonsController : ControllerBase [HttpGet("{personId:guid}/faces")] public async Task GetFaces(Guid personId, CancellationToken ct) { - var result = await _personService.GetFacesAsync(personId, ct); + var result = await _mediator.Send(new GetFacesQuery(personId), ct); return Ok(result.Data); } @@ -76,7 +87,7 @@ public class PersonsController : ControllerBase [HttpDelete("faces/{faceId:guid}")] public async Task DeleteFace(Guid faceId, CancellationToken ct) { - var result = await _personService.DeleteFaceAsync(faceId, ct); + var result = await _mediator.Send(new DeleteFaceCommand(faceId), ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); } } diff --git a/src/Heimdall.Web/Controllers/SettingsController.cs b/src/Heimdall.Web/Controllers/SettingsController.cs index 45a952f..48c5c27 100644 --- a/src/Heimdall.Web/Controllers/SettingsController.cs +++ b/src/Heimdall.Web/Controllers/SettingsController.cs @@ -1,8 +1,18 @@ using Heimdall.Application.Common; using Heimdall.Application.DTOs; using Heimdall.Application.Services; +using Heimdall.Application.Settings.Commands.CreateAppSetting; +using Heimdall.Application.Settings.Commands.UpdateAppSetting; +using Heimdall.Application.Settings.Commands.DeleteAppSetting; +using Heimdall.Application.Settings.Commands.SetAgentSetting; +using Heimdall.Application.Settings.Commands.RemoveAgentSetting; +using Heimdall.Application.Settings.Queries.GetSettings; +using Heimdall.Application.Settings.Queries.GetSettingByKey; +using Heimdall.Application.Settings.Queries.GetEffectiveAgentConfig; +using Heimdall.Application.Settings.Queries.GetAgentSettings; using Heimdall.Api.Hubs; using Heimdall.Infrastructure.Security; +using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; @@ -15,16 +25,16 @@ namespace Heimdall.Api.Controllers; [EnableRateLimiting("Api")] public class SettingsController : ControllerBase { - private readonly ISettingService _settingService; + private readonly IMediator _mediator; private readonly IConfigBroadcastService _broadcast; private readonly ILogger _logger; public SettingsController( - ISettingService settingService, + IMediator mediator, IConfigBroadcastService broadcast, ILogger logger) { - _settingService = settingService; + _mediator = mediator; _broadcast = broadcast; _logger = logger; } @@ -36,7 +46,7 @@ public class SettingsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] public async Task ListAll(CancellationToken ct) { - var result = await _settingService.GetAllSettingsAsync(ct); + var result = await _mediator.Send(new GetSettingsQuery(), ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -56,7 +66,7 @@ public class SettingsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task GetByKey(string key, CancellationToken ct) { - var result = await _settingService.GetSettingByKeyAsync(key, ct); + var result = await _mediator.Send(new GetSettingByKeyQuery(key), ct); if (!result.IsSuccess) return NotFound(new { error = result.Error }); @@ -78,7 +88,8 @@ public class SettingsController : ControllerBase public async Task Create( [FromBody] CreateAppSettingRequest request, CancellationToken ct) { - var result = await _settingService.CreateSettingAsync(request, ct); + var command = new CreateAppSettingCommand(request.Key, request.Value, request.Category, request.Description, request.ValueType, request.AllowedValues); + var result = await _mediator.Send(command, ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -96,7 +107,8 @@ public class SettingsController : ControllerBase public async Task Update( string key, [FromBody] UpdateAppSettingRequest request, CancellationToken ct) { - var result = await _settingService.UpdateSettingAsync(key, request, ct); + var command = new UpdateAppSettingCommand(key, request.Value, request.Description, request.Category, request.ValueType, request.AllowedValues); + var result = await _mediator.Send(command, ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -113,7 +125,7 @@ public class SettingsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task Delete(string key, CancellationToken ct) { - var result = await _settingService.DeleteSettingAsync(key, ct); + var result = await _mediator.Send(new DeleteAppSettingCommand(key), ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -132,7 +144,7 @@ public class SettingsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task GetEffectiveConfig(Guid agentId, CancellationToken ct) { - var result = await _settingService.GetEffectiveAgentConfigAsync(agentId, ct); + var result = await _mediator.Send(new GetEffectiveAgentConfigQuery(agentId), ct); return result.IsSuccess ? Ok(result.Data) : NotFound(new { error = result.Error }); @@ -145,7 +157,7 @@ public class SettingsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task ListAgentOverrides(Guid agentId, CancellationToken ct) { - var result = await _settingService.GetAgentSettingsAsync(agentId, ct); + var result = await _mediator.Send(new GetAgentSettingsQuery(agentId), ct); return result.IsSuccess ? Ok(result.Data) : NotFound(new { error = result.Error }); @@ -163,7 +175,8 @@ public class SettingsController : ControllerBase public async Task SetAgentOverride( Guid agentId, [FromBody] SetAgentSettingRequest request, CancellationToken ct) { - var result = await _settingService.SetAgentSettingAsync(agentId, request, ct); + var command = new SetAgentSettingCommand(agentId, request.Key, request.Value); + var result = await _mediator.Send(command, ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -184,7 +197,7 @@ public class SettingsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task RemoveAgentOverride(Guid agentId, string key, CancellationToken ct) { - var result = await _settingService.RemoveAgentSettingAsync(agentId, key, ct); + var result = await _mediator.Send(new RemoveAgentSettingCommand(agentId, key), ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); diff --git a/src/Heimdall.Web/Controllers/SitesController.cs b/src/Heimdall.Web/Controllers/SitesController.cs index 86cc237..ef4c6d9 100644 --- a/src/Heimdall.Web/Controllers/SitesController.cs +++ b/src/Heimdall.Web/Controllers/SitesController.cs @@ -1,7 +1,13 @@ using System.Security.Claims; using Heimdall.Application.DTOs; -using Heimdall.Application.Services; +using Heimdall.Application.Sites.Commands.CreateSite; +using Heimdall.Application.Sites.Commands.UpdateSite; +using Heimdall.Application.Sites.Commands.DeleteSite; +using Heimdall.Application.Sites.Commands.GenerateSiteToken; +using Heimdall.Application.Sites.Queries.GetSites; +using Heimdall.Application.Sites.Queries.GetSite; using Heimdall.Infrastructure.Security; +using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; @@ -13,9 +19,9 @@ namespace Heimdall.Api.Controllers; [EnableRateLimiting("Api")] public class SitesController : ControllerBase { - private readonly ISiteService _siteService; + private readonly IMediator _mediator; - public SitesController(ISiteService siteService) => _siteService = siteService; + public SitesController(IMediator mediator) => _mediator = mediator; /// Create a new site (Admin only). [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)] @@ -30,7 +36,8 @@ public class SitesController : ControllerBase if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId)) return Unauthorized(new { error = "Invalid user identity" }); - var result = await _siteService.CreateAsync(request, userId, ct); + var command = new CreateSiteCommand(request.Name, request.Address, request.Timezone); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -44,7 +51,7 @@ public class SitesController : ControllerBase public async Task List( [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) { - var result = await _siteService.ListAsync(page, pageSize, ct); + var result = await _mediator.Send(new GetSitesQuery(page, pageSize), ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); return Ok(result.Data); @@ -57,7 +64,7 @@ public class SitesController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task GetById(Guid id, CancellationToken ct) { - var result = await _siteService.GetByIdAsync(id, ct); + var result = await _mediator.Send(new GetSiteQuery(id), ct); return result.IsSuccess ? Ok(result.Data) : NotFound(new { error = result.Error }); @@ -72,7 +79,8 @@ public class SitesController : ControllerBase public async Task Update( Guid id, [FromBody] UpdateSiteRequest request, CancellationToken ct) { - var result = await _siteService.UpdateAsync(id, request, ct); + var command = new UpdateSiteCommand(id, request.Name, request.Address, request.Timezone); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -86,7 +94,7 @@ public class SitesController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task Delete(Guid id, CancellationToken ct) { - var result = await _siteService.DeleteAsync(id, ct); + var result = await _mediator.Send(new DeleteSiteCommand(id), ct); return result.IsSuccess ? NoContent() : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -100,7 +108,7 @@ public class SitesController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task GenerateToken(Guid id, CancellationToken ct) { - var result = await _siteService.GenerateTokenAsync(id, ct); + var result = await _mediator.Send(new GenerateSiteTokenCommand(id), ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); diff --git a/src/Heimdall.Web/Controllers/StatsController.cs b/src/Heimdall.Web/Controllers/StatsController.cs index a65087e..bd6490a 100644 --- a/src/Heimdall.Web/Controllers/StatsController.cs +++ b/src/Heimdall.Web/Controllers/StatsController.cs @@ -1,6 +1,8 @@ using Heimdall.Application.DTOs; -using Heimdall.Application.Services; +using Heimdall.Application.Stats.Queries.GetStats; +using Heimdall.Application.Stats.Queries.GetAgentStats; using Heimdall.Infrastructure.Security; +using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; @@ -12,9 +14,9 @@ namespace Heimdall.Api.Controllers; [EnableRateLimiting("Api")] public class StatsController : ControllerBase { - private readonly IStatsService _statsService; + private readonly IMediator _mediator; - public StatsController(IStatsService statsService) => _statsService = statsService; + public StatsController(IMediator mediator) => _mediator = mediator; /// Get system-wide statistics. [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] @@ -23,7 +25,7 @@ public class StatsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task GetStats(CancellationToken ct) { - var result = await _statsService.GetStatsAsync(ct); + var result = await _mediator.Send(new GetStatsQuery(), ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); return Ok(new { data = result.Data, timestamp = DateTime.UtcNow }); @@ -36,7 +38,7 @@ public class StatsController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task GetAgentStats(CancellationToken ct) { - var result = await _statsService.GetAgentStatsAsync(ct); + var result = await _mediator.Send(new GetAgentStatsQuery(), ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); return Ok(result.Data); diff --git a/src/Heimdall.Web/Controllers/UsersController.cs b/src/Heimdall.Web/Controllers/UsersController.cs index 4d39566..7ccee71 100644 --- a/src/Heimdall.Web/Controllers/UsersController.cs +++ b/src/Heimdall.Web/Controllers/UsersController.cs @@ -1,7 +1,18 @@ using System.Security.Claims; using Heimdall.Application.DTOs; -using Heimdall.Application.Services; +using Heimdall.Application.Users.Commands.CreateUser; +using Heimdall.Application.Users.Commands.UpdateUser; +using Heimdall.Application.Users.Commands.DeleteUser; +using Heimdall.Application.Users.Commands.AssignRoles; +using Heimdall.Application.Users.Commands.AssignSites; +using Heimdall.Application.Users.Commands.ResetPassword; +using Heimdall.Application.Users.Commands.LockUser; +using Heimdall.Application.Users.Commands.UnlockUser; +using Heimdall.Application.Users.Queries.GetUsers; +using Heimdall.Application.Users.Queries.GetUser; +using Heimdall.Application.Users.Queries.GetMe; using Heimdall.Infrastructure.Security; +using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; @@ -14,9 +25,9 @@ namespace Heimdall.Api.Controllers; [EnableRateLimiting("Api")] public class UsersController : ControllerBase { - private readonly IUserService _userService; + private readonly IMediator _mediator; - public UsersController(IUserService userService) => _userService = userService; + public UsersController(IMediator mediator) => _mediator = mediator; /// List all users (Admin only). [HttpGet] @@ -26,7 +37,7 @@ public class UsersController : ControllerBase public async Task List( [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) { - var result = await _userService.ListAsync(page, pageSize, ct); + var result = await _mediator.Send(new GetUsersQuery(page, pageSize), ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); return Ok(result.Data); @@ -43,7 +54,7 @@ public class UsersController : ControllerBase if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) return Unauthorized(new { error = "Invalid user identity" }); - var result = await _userService.GetByIdAsync(userId, ct); + var result = await _mediator.Send(new GetMeQuery(userId), ct); return result.IsSuccess ? Ok(result.Data) : NotFound(new { error = result.Error }); @@ -62,7 +73,8 @@ public class UsersController : ControllerBase if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) return Unauthorized(new { error = "Invalid user identity" }); - var result = await _userService.UpdateAsync(userId, request, ct); + var command = new UpdateUserCommand(userId, request.DisplayName, request.Theme, request.Language); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -75,7 +87,7 @@ public class UsersController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task GetById(Guid id, CancellationToken ct) { - var result = await _userService.GetByIdAsync(id, ct); + var result = await _mediator.Send(new GetUserQuery(id), ct); return result.IsSuccess ? Ok(result.Data) : NotFound(new { error = result.Error }); @@ -88,7 +100,8 @@ public class UsersController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task Create([FromBody] CreateUserRequest request, CancellationToken ct) { - var result = await _userService.CreateAsync(request, ct); + var command = new CreateUserCommand(request.Email, request.Password, request.DisplayName, request.Roles); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -103,7 +116,8 @@ public class UsersController : ControllerBase public async Task Update( Guid id, [FromBody] UpdateUserRequest request, CancellationToken ct) { - var result = await _userService.UpdateAsync(id, request, ct); + var command = new UpdateUserCommand(id, request.DisplayName, request.Theme, request.Language); + var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -117,7 +131,7 @@ public class UsersController : ControllerBase public async Task AssignRoles( Guid id, [FromBody] AssignRolesRequest request, CancellationToken ct) { - var result = await _userService.AssignRolesAsync(id, request, ct); + var result = await _mediator.Send(new AssignRolesCommand(id, request.Roles), ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -131,7 +145,7 @@ public class UsersController : ControllerBase public async Task AssignSites( Guid id, [FromBody] AssignSitesRequest request, CancellationToken ct) { - var result = await _userService.AssignSitesAsync(id, request, ct); + var result = await _mediator.Send(new AssignSitesCommand(id, request.SiteIds), ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -144,7 +158,7 @@ public class UsersController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task ResetPassword(Guid id, CancellationToken ct) { - var result = await _userService.ResetPasswordAsync(id, ct); + var result = await _mediator.Send(new ResetPasswordCommand(id), ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -163,7 +177,7 @@ public class UsersController : ControllerBase if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var currentUserId)) return Unauthorized(new { error = "Invalid user identity" }); - var result = await _userService.DeleteAsync(id, currentUserId, ct); + var result = await _mediator.Send(new DeleteUserCommand(id, currentUserId), ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -176,7 +190,7 @@ public class UsersController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task Lock(Guid id, CancellationToken ct) { - var result = await _userService.LockAsync(id, ct); + var result = await _mediator.Send(new LockUserCommand(id), ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); @@ -189,7 +203,7 @@ public class UsersController : ControllerBase [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task Unlock(Guid id, CancellationToken ct) { - var result = await _userService.UnlockAsync(id, ct); + var result = await _mediator.Send(new UnlockUserCommand(id), ct); return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); diff --git a/src/Heimdall.Web/Hubs/ConfigHub.cs b/src/Heimdall.Web/Hubs/ConfigHub.cs index fb6a398..e5de9f5 100644 --- a/src/Heimdall.Web/Hubs/ConfigHub.cs +++ b/src/Heimdall.Web/Hubs/ConfigHub.cs @@ -41,22 +41,6 @@ public class ConfigHub : Hub } } -/// -/// Service that broadcasts config changes to connected agents via SignalR. -/// Called by the SettingService after any setting change. -/// -public interface IConfigBroadcastService -{ - /// Notify all connected agents that a global setting changed. - Task NotifyGlobalSettingChanged(string key, string value, CancellationToken ct = default); - - /// Notify a specific agent that one of its overrides changed. - Task NotifyAgentSettingChanged(Guid agentId, string key, string value, CancellationToken ct = default); - - /// Notify all agents to reload their full configuration. - Task NotifyAllAgentsReload(CancellationToken ct = default); -} - /// /// Broadcasts config changes to connected agents via SignalR. /// Injected as a scoped service; the HubContext is a singleton so broadcasting diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index 04c2470..bc6e225 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -6,13 +6,12 @@ using Heimdall.Application; using Heimdall.Application.Services; using Heimdall.Infrastructure; using Heimdall.Infrastructure.Data; -using Heimdall.Infrastructure.Jobs; +using Heimdall.Infrastructure.BackgroundJobs; using Heimdall.Infrastructure.Security; using Heimdall.Web.Components; using Heimdall.Api.Hubs; using Heimdall.Web.Services; using Hangfire; -using Hangfire.PostgreSql; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.JwtBearer; @@ -190,25 +189,7 @@ var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL") if (!isTesting && !string.IsNullOrEmpty(connectionString)) { -#pragma warning disable CS0618 - builder.Services.AddHangfire(config => - { - config.UsePostgreSqlStorage(connectionString, new PostgreSqlStorageOptions - { - SchemaName = "hangfire" - }); - }); -#pragma warning restore CS0618 - - builder.Services.AddHangfireServer(options => - { - options.WorkerCount = 2; - options.Queues = ["default", "heartbeat"]; - }); - - // ── Jobs ────────────────────────────────────────────────────────── - builder.Services.AddScoped(); - builder.Services.AddScoped(); + builder.Services.AddBackgroundJobs(builder.Configuration); } // ── HTTP client for Heimdall API (with auto-refresh handler) ────── @@ -411,16 +392,7 @@ if (!isTesting && !string.IsNullOrEmpty(connectionString)) using (var scope = app.Services.CreateScope()) { var manager = scope.ServiceProvider.GetRequiredService(); - - manager.AddOrUpdate( - "heartbeat-monitor", - job => job.ExecuteAsync(CancellationToken.None), - "*/1 * * * *"); // Every minute - - manager.AddOrUpdate( - "agent-failover", - job => job.ExecuteAsync(CancellationToken.None), - "*/1 * * * *"); // Every minute — checks for stale heartbeats + Heimdall.Infrastructure.BackgroundJobs.JobSetup.ConfigureRecurringJobs(manager); } }