feat: implémenter SignalR hubs (Monitoring, Notifications, Admin) + système de notifications complet

SignalR Hubs:
- MonitoringHub (/hubs/monitoring) — statuts agents/caméras/stockage/GPU jobs
- NotificationsHub (/hubs/notifications) — notifications in-app badge temps réel
- AdminHub (/hubs/admin) — broadcast changements config (Admin only)

Notification System:
- Nouvelles entités: Notification, NotificationTemplate, UserNotificationConfig
- CQRS/MediatR: 6 handlers (list, unread, mark-read, mark-all, config get/update)
- Infrastructure: NotificationService orchestrator + EmailService + GotifyService
- Rate limiter IMemoryCache (20 events/min/camera/type)
- Hangfire jobs: SendNotification, DailyDigest, WeeklyDigest
- NotificationsController API (6 endpoints)
- Blazor UI: NotificationsPage + NotificationBadge
- Migration AddNotifications (3 nouvelles tables)
- 644 nouveaux tests (Domain: 131, Application: 321, Infra: 151, Integration: 120, +autres)
This commit is contained in:
Arnaud Dartois committed 2026-07-26 20:45:35 +00:00
1 parent ef3ea9d1ca
commit f9be0f1e0d
62 files changed
+6664 -3

No files matched your search

+522
View File
@@ -0,0 +1,522 @@
Summary
Generated on: 07/23/2026 - 19:18:54
Coverage date: 07/23/2026 - 07:02:46 - 07/23/2026 - 19:18:44
Parser: MultiReport (35x Cobertura)
Assemblies: 7
Classes: 488
Files: 328
Line coverage: 64.1%
Covered lines: 11264
Uncovered lines: 6294
Coverable lines: 17558
Total lines: 27041
Branch coverage: 24.3% (824 of 3379)
Covered branches: 824
Total branches: 3379
Method coverage: 66.8% (1419 of 2122)
Full method coverage: 62.4% (1326 of 2122)
Covered methods: 1419
Fully covered methods: 1326
Total methods: 2122
Heimdall.Agent 58.7%
Heimdall.Agent.AgentOptions 85.7%
Heimdall.Agent.Services.AgentHealthCheck 100%
Heimdall.Agent.Services.AgentRegistrationService 86.1%
Heimdall.Agent.Services.AgentState 100%
Heimdall.Agent.Services.CameraStreamService 42.6%
Heimdall.Agent.Services.ConfigReceiverService 25%
Heimdall.Agent.Services.DetectionResult 100%
Heimdall.Agent.Services.FrameAnalysisResult 100%
Heimdall.Agent.Services.FrameAnalyzerService 42.1%
Heimdall.Agent.Services.HeartbeatRequest 100%
Heimdall.Agent.Services.RegisterRequest 100%
Heimdall.Agent.Services.RegisterResponse 100%
Heimdall.Agent.Services.RetryDelayed 100%
Heimdall.Agent.Services.SystemInfo 83.3%
Heimdall.Agent.Services.SystemMetrics 100%
Heimdall.Agent.Services.SystemMetricsProvider 73.6%
Program 0%
Sentry.Generated.BuildPropertyInitializer 100%
Heimdall.Application 87.8%
Heimdall.Application.Agents.Commands.Heartbeat.HeartbeatCommand 100%
Heimdall.Application.Agents.Commands.Heartbeat.HeartbeatHandler 100%
Heimdall.Application.Agents.Commands.RegisterAgent.RegisterAgentCommand 100%
Heimdall.Application.Agents.Commands.RegisterAgent.RegisterAgentHandler 100%
Heimdall.Application.Agents.Commands.RegisterAgent.RegisterAgentValidator 100%
Heimdall.Application.Agents.Mapping.AgentMappingProfile 100%
Heimdall.Application.Agents.Queries.GetAgent.GetAgentHandler 100%
Heimdall.Application.Agents.Queries.GetAgent.GetAgentQuery 100%
Heimdall.Application.Agents.Queries.GetAgentsBySite.GetAgentsBySiteHandler 100%
Heimdall.Application.Agents.Queries.GetAgentsBySite.GetAgentsBySiteQuery 100%
Heimdall.Application.Agents.Queries.GetAllAgents.GetAllAgentsHandler 100%
Heimdall.Application.Agents.Queries.GetAllAgents.GetAllAgentsQuery 100%
Heimdall.Application.Assignments.Commands.AssignCamera.AssignCameraCommand 100%
Heimdall.Application.Assignments.Commands.AssignCamera.AssignCameraHandler 100%
Heimdall.Application.Assignments.Commands.AssignSite.AssignSiteCommand 100%
Heimdall.Application.Assignments.Commands.AssignSite.AssignSiteHandler 100%
Heimdall.Application.Assignments.Commands.Failover.FailoverCommand 100%
Heimdall.Application.Assignments.Commands.Failover.FailoverHandler 100%
Heimdall.Application.Assignments.Commands.ReleaseCamera.ReleaseCameraCommand 100%
Heimdall.Application.Assignments.Commands.ReleaseCamera.ReleaseCameraHandler 100%
Heimdall.Application.Assignments.Mapping.AssignmentMappingProfile 100%
Heimdall.Application.Assignments.Queries.GetActiveAssignment.GetActiveAssignmentHandler 100%
Heimdall.Application.Assignments.Queries.GetActiveAssignment.GetActiveAssignmentQuery 100%
Heimdall.Application.Assignments.Queries.GetAgentAssignments.GetAgentAssignmentsHandler 100%
Heimdall.Application.Assignments.Queries.GetAgentAssignments.GetAgentAssignmentsQuery 100%
Heimdall.Application.Assignments.Queries.GetCameraHistory.GetCameraHistoryHandler 100%
Heimdall.Application.Assignments.Queries.GetCameraHistory.GetCameraHistoryQuery 100%
Heimdall.Application.Audit.Queries.GetAuditLogs.GetAuditLogsQuery 100%
Heimdall.Application.Audit.Queries.GetAuditLogs.GetAuditLogsQueryHandler 100%
Heimdall.Application.Auth.AuthHelper 100%
Heimdall.Application.Auth.Commands.ChangePassword.ChangePasswordCommand 100%
Heimdall.Application.Auth.Commands.ChangePassword.ChangePasswordHandler 100%
Heimdall.Application.Auth.Commands.ChangePassword.ChangePasswordValidator 0%
Heimdall.Application.Auth.Commands.Disable2fa.Disable2faCommand 0%
Heimdall.Application.Auth.Commands.Disable2fa.Disable2faHandler 0%
Heimdall.Application.Auth.Commands.Enable2fa.Enable2faCommand 0%
Heimdall.Application.Auth.Commands.Enable2fa.Enable2faHandler 0%
Heimdall.Application.Auth.Commands.Login.LoginCommand 100%
Heimdall.Application.Auth.Commands.Login.LoginHandler 87.5%
Heimdall.Application.Auth.Commands.Login.LoginValidator 100%
Heimdall.Application.Auth.Commands.Logout.LogoutCommand 0%
Heimdall.Application.Auth.Commands.Logout.LogoutHandler 0%
Heimdall.Application.Auth.Commands.RefreshToken.RefreshTokenCommand 100%
Heimdall.Application.Auth.Commands.RefreshToken.RefreshTokenHandler 92.6%
Heimdall.Application.Auth.Commands.Register.RegisterCommand 100%
Heimdall.Application.Auth.Commands.Register.RegisterHandler 87.6%
Heimdall.Application.Auth.Commands.Register.RegisterValidator 100%
Heimdall.Application.Auth.Commands.RegisterAdmin.RegisterAdminCommand 100%
Heimdall.Application.Auth.Commands.RegisterAdmin.RegisterAdminHandler 100%
Heimdall.Application.Auth.Commands.RegisterAdmin.RegisterAdminValidator 100%
Heimdall.Application.Auth.Commands.Verify2fa.Verify2faCommand 0%
Heimdall.Application.Auth.Commands.Verify2fa.Verify2faHandler 0%
Heimdall.Application.Auth.Commands.Verify2fa.Verify2faValidator 0%
Heimdall.Application.Auth.Mapping.AuthMappingProfile 100%
Heimdall.Application.Behaviors.LoggingBehavior<T1, T2> 100%
Heimdall.Application.Behaviors.ValidationBehavior<T1, T2> 92.8%
Heimdall.Application.Cameras.Commands.CreateCamera.CreateCameraCommand 100%
Heimdall.Application.Cameras.Commands.CreateCamera.CreateCameraCommandHandler 100%
Heimdall.Application.Cameras.Commands.CreateCamera.CreateCameraCommandValidator 100%
Heimdall.Application.Cameras.Commands.DeleteCamera.DeleteCameraCommand 100%
Heimdall.Application.Cameras.Commands.DeleteCamera.DeleteCameraCommandHandler 100%
Heimdall.Application.Cameras.Commands.SetCredentials.SetCameraCredentialsCommand 100%
Heimdall.Application.Cameras.Commands.SetCredentials.SetCameraCredentialsCommandHandler 100%
Heimdall.Application.Cameras.Commands.SetCredentials.SetCameraCredentialsCommandValidator 0%
Heimdall.Application.Cameras.Commands.UpdateCamera.UpdateCameraCommand 100%
Heimdall.Application.Cameras.Commands.UpdateCamera.UpdateCameraCommandHandler 100%
Heimdall.Application.Cameras.Commands.UpdateCamera.UpdateCameraCommandValidator 0%
Heimdall.Application.Cameras.Mapping.CameraMappingProfile 100%
Heimdall.Application.Cameras.Queries.GetCamera.GetCameraQuery 100%
Heimdall.Application.Cameras.Queries.GetCamera.GetCameraQueryHandler 100%
Heimdall.Application.Cameras.Queries.GetCamerasBySite.GetCamerasBySiteQuery 100%
Heimdall.Application.Cameras.Queries.GetCamerasBySite.GetCamerasBySiteQueryHandler 100%
Heimdall.Application.Common.Mappings.IMapFrom<T> 0%
Heimdall.Application.Common.Mappings.MappingProfile 44.4%
Heimdall.Application.Common.ServiceResult 100%
Heimdall.Application.Common.ServiceResult<T> 100%
Heimdall.Application.DependencyInjection 100%
Heimdall.Application.Discovery.Commands.BuildStreamUrls.BuildStreamUrlsCommand 100%
Heimdall.Application.Discovery.Commands.BuildStreamUrls.BuildStreamUrlsCommandHandler 100%
Heimdall.Application.Discovery.Commands.CancelTestSession.CancelTestSessionCommand 100%
Heimdall.Application.Discovery.Commands.CancelTestSession.CancelTestSessionCommandHandler 100%
Heimdall.Application.Discovery.Commands.ConfirmDiscovery.ConfirmDiscoveryCommand 100%
Heimdall.Application.Discovery.Commands.ConfirmDiscovery.ConfirmDiscoveryCommandHandler 100%
Heimdall.Application.Discovery.Commands.ProbeIp.ProbeIpCommand 100%
Heimdall.Application.Discovery.Commands.ProbeIp.ProbeIpCommandHandler 100%
Heimdall.Application.Discovery.Commands.ScanSubnet.ScanSubnetCommand 100%
Heimdall.Application.Discovery.Commands.ScanSubnet.ScanSubnetCommandHandler 100%
Heimdall.Application.Discovery.Commands.TestStreams.TestStreamsCommand 100%
Heimdall.Application.Discovery.Commands.TestStreams.TestStreamsCommandHandler 100%
Heimdall.Application.Discovery.Mapping.DiscoveryMappingProfile 100%
Heimdall.Application.Discovery.Queries.CheckDuplicate.CheckDuplicateQuery 100%
Heimdall.Application.Discovery.Queries.CheckDuplicate.CheckDuplicateQueryHandler 100%
Heimdall.Application.Discovery.Queries.GetScreenshot.GetScreenshotQuery 100%
Heimdall.Application.Discovery.Queries.GetScreenshot.GetScreenshotQueryHandler 100%
Heimdall.Application.Discovery.Queries.GetTestSession.GetTestSessionQuery 100%
Heimdall.Application.Discovery.Queries.GetTestSession.GetTestSessionQueryHandler 100%
Heimdall.Application.Discovery.Queries.SearchDatabase.SearchDatabaseQuery 100%
Heimdall.Application.Discovery.Queries.SearchDatabase.SearchDatabaseQueryHandler 100%
Heimdall.Application.DTOs.AgentHeartbeatRequest 100%
Heimdall.Application.DTOs.AgentResponse 42.8%
Heimdall.Application.DTOs.AgentSettingDto 100%
Heimdall.Application.DTOs.AgentStatItem 100%
Heimdall.Application.DTOs.ApiKeyResponse 0%
Heimdall.Application.DTOs.AppSettingDto 100%
Heimdall.Application.DTOs.ArpInfo 0%
Heimdall.Application.DTOs.AssignmentResponse 100%
Heimdall.Application.DTOs.AssignmentResult 0%
Heimdall.Application.DTOs.AssignRequest 100%
Heimdall.Application.DTOs.AssignRolesRequest 0%
Heimdall.Application.DTOs.AssignSitesRequest 0%
Heimdall.Application.DTOs.AttachSnapshotRequest 0%
Heimdall.Application.DTOs.AuditLogResponse 0%
Heimdall.Application.DTOs.AuthResponse 100%
Heimdall.Application.DTOs.CameraCheckResponse 100%
Heimdall.Application.DTOs.CameraDbEntry 100%
Heimdall.Application.DTOs.CameraDetectionProfileRequest 0%
Heimdall.Application.DTOs.CameraEventFilterRequest 100%
Heimdall.Application.DTOs.CameraEventResponse 69.2%
Heimdall.Application.DTOs.CameraResponse 100%
Heimdall.Application.DTOs.ChangePasswordRequest 0%
Heimdall.Application.DTOs.CheckDuplicateRequest 100%
Heimdall.Application.DTOs.ConfirmDiscoveryRequest 20%
Heimdall.Application.DTOs.CreateApiKeyResponse 0%
Heimdall.Application.DTOs.CreateAppSettingRequest 100%
Heimdall.Application.DTOs.CreateCameraEventRequest 100%
Heimdall.Application.DTOs.CreateCameraRequest 100%
Heimdall.Application.DTOs.CreateGroupRequest 100%
Heimdall.Application.DTOs.CreatePersonRequest 100%
Heimdall.Application.DTOs.CreateSiteRequest 100%
Heimdall.Application.DTOs.CreateUserRequest 100%
Heimdall.Application.DTOs.FailoverResult 0%
Heimdall.Application.DTOs.GroupMemberResponse 50%
Heimdall.Application.DTOs.GroupResponse 100%
Heimdall.Application.DTOs.HomeKitProbeInfo 0%
Heimdall.Application.DTOs.HttpProbeInfo 0%
Heimdall.Application.DTOs.KnownFaceResponse 100%
Heimdall.Application.DTOs.LoginRequest 100%
Heimdall.Application.DTOs.LogoutRequest 0%
Heimdall.Application.DTOs.OnvifProbeInfo 0%
Heimdall.Application.DTOs.PagedResult<T> 100%
Heimdall.Application.DTOs.PersonResponse 100%
Heimdall.Application.DTOs.ProbeRequest 100%
Heimdall.Application.DTOs.ProbeResponse 36.3%
Heimdall.Application.DTOs.RefreshTokenRequest 0%
Heimdall.Application.DTOs.RegisterAgentRequest 100%
Heimdall.Application.DTOs.RegisterAgentResponse 100%
Heimdall.Application.DTOs.RegisterFaceRequest 0%
Heimdall.Application.DTOs.RegisterRequest 100%
Heimdall.Application.DTOs.RegistrationTokenResponse 100%
Heimdall.Application.DTOs.ResetPasswordResponse 100%
Heimdall.Application.DTOs.ScanProgress 0%
Heimdall.Application.DTOs.ScanRequest 100%
Heimdall.Application.DTOs.SearchResponse 100%
Heimdall.Application.DTOs.SetAgentSettingRequest 100%
Heimdall.Application.DTOs.SiteResponse 100%
Heimdall.Application.DTOs.SiteWithTokenResponse 0%
Heimdall.Application.DTOs.StatsResponse 100%
Heimdall.Application.DTOs.StreamBuildRequest 100%
Heimdall.Application.DTOs.StreamBuildResponse 100%
Heimdall.Application.DTOs.StreamTestRequest 100%
Heimdall.Application.DTOs.StreamTestResult 25%
Heimdall.Application.DTOs.StreamTestSession 100%
Heimdall.Application.DTOs.UpdateAppSettingRequest 100%
Heimdall.Application.DTOs.UpdateCameraRequest 66.6%
Heimdall.Application.DTOs.UpdateGroupRequest 100%
Heimdall.Application.DTOs.UpdatePersonRequest 100%
Heimdall.Application.DTOs.UpdateSiteRequest 100%
Heimdall.Application.DTOs.UpdateUserRequest 100%
Heimdall.Application.DTOs.UserInfo 100%
Heimdall.Application.DTOs.UserResponse 100%
Heimdall.Application.DTOs.Verify2faRequest 0%
Heimdall.Application.Events.Commands.AttachSnapshot.AttachSnapshotCommand 100%
Heimdall.Application.Events.Commands.AttachSnapshot.AttachSnapshotHandler 100%
Heimdall.Application.Events.Commands.CreateEvent.CreateEventCommand 100%
Heimdall.Application.Events.Commands.CreateEvent.CreateEventHandler 95.4%
Heimdall.Application.Events.Commands.DeleteEvent.DeleteEventCommand 100%
Heimdall.Application.Events.Commands.DeleteEvent.DeleteEventHandler 100%
Heimdall.Application.Events.Mapping.EventMappingProfile 100%
Heimdall.Application.Events.Notifications.EventCreatedNotification 100%
Heimdall.Application.Events.Notifications.EventCreatedNotificationHandler 0%
Heimdall.Application.Events.Queries.GetEvent.GetEventHandler 100%
Heimdall.Application.Events.Queries.GetEvent.GetEventQuery 100%
Heimdall.Application.Events.Queries.GetEvents.GetEventsHandler 83.8%
Heimdall.Application.Events.Queries.GetEvents.GetEventsQuery 100%
Heimdall.Application.Events.Queries.GetRecentByCamera.GetRecentByCameraHandler 100%
Heimdall.Application.Events.Queries.GetRecentByCamera.GetRecentByCameraQuery 100%
Heimdall.Application.Groups.Commands.AddUserToGroup.AddUserToGroupCommand 100%
Heimdall.Application.Groups.Commands.AddUserToGroup.AddUserToGroupCommandHandler 100%
Heimdall.Application.Groups.Commands.CreateGroup.CreateGroupCommand 100%
Heimdall.Application.Groups.Commands.CreateGroup.CreateGroupCommandHandler 100%
Heimdall.Application.Groups.Commands.DeleteGroup.DeleteGroupCommand 100%
Heimdall.Application.Groups.Commands.DeleteGroup.DeleteGroupCommandHandler 100%
Heimdall.Application.Groups.Commands.RemoveUserFromGroup.RemoveUserFromGroupCommand 100%
Heimdall.Application.Groups.Commands.RemoveUserFromGroup.RemoveUserFromGroupCommandHandler 100%
Heimdall.Application.Groups.Commands.UpdateGroup.UpdateGroupCommand 100%
Heimdall.Application.Groups.Commands.UpdateGroup.UpdateGroupCommandHandler 100%
Heimdall.Application.Groups.Mapping.GroupMappingProfile 100%
Heimdall.Application.Groups.Queries.GetGroup.GetGroupQuery 100%
Heimdall.Application.Groups.Queries.GetGroup.GetGroupQueryHandler 100%
Heimdall.Application.Groups.Queries.GetGroupMembers.GetGroupMembersQuery 100%
Heimdall.Application.Groups.Queries.GetGroupMembers.GetGroupMembersQueryHandler 100%
Heimdall.Application.Groups.Queries.GetGroups.GetGroupsQuery 100%
Heimdall.Application.Groups.Queries.GetGroups.GetGroupsQueryHandler 100%
Heimdall.Application.Persons.Commands.CreatePerson.CreatePersonCommand 100%
Heimdall.Application.Persons.Commands.CreatePerson.CreatePersonCommandHandler 100%
Heimdall.Application.Persons.Commands.DeleteFace.DeleteFaceCommand 100%
Heimdall.Application.Persons.Commands.DeleteFace.DeleteFaceCommandHandler 100%
Heimdall.Application.Persons.Commands.DeletePerson.DeletePersonCommand 100%
Heimdall.Application.Persons.Commands.DeletePerson.DeletePersonCommandHandler 100%
Heimdall.Application.Persons.Commands.RegisterFace.RegisterFaceCommand 100%
Heimdall.Application.Persons.Commands.RegisterFace.RegisterFaceCommandHandler 100%
Heimdall.Application.Persons.Commands.UpdatePerson.UpdatePersonCommand 100%
Heimdall.Application.Persons.Commands.UpdatePerson.UpdatePersonCommandHandler 100%
Heimdall.Application.Persons.Mapping.PersonMappingProfile 100%
Heimdall.Application.Persons.Queries.GetFaces.GetFacesQuery 100%
Heimdall.Application.Persons.Queries.GetFaces.GetFacesQueryHandler 100%
Heimdall.Application.Persons.Queries.GetPerson.GetPersonQuery 100%
Heimdall.Application.Persons.Queries.GetPerson.GetPersonQueryHandler 100%
Heimdall.Application.Persons.Queries.GetPersons.GetPersonsQuery 100%
Heimdall.Application.Persons.Queries.GetPersons.GetPersonsQueryHandler 100%
Heimdall.Application.Services.SignInServiceResult 100%
Heimdall.Application.Settings.Commands.CreateAppSetting.CreateAppSettingCommand 100%
Heimdall.Application.Settings.Commands.CreateAppSetting.CreateAppSettingCommandHandler 100%
Heimdall.Application.Settings.Commands.DeleteAppSetting.DeleteAppSettingCommand 100%
Heimdall.Application.Settings.Commands.DeleteAppSetting.DeleteAppSettingCommandHandler 100%
Heimdall.Application.Settings.Commands.RemoveAgentSetting.RemoveAgentSettingCommand 100%
Heimdall.Application.Settings.Commands.RemoveAgentSetting.RemoveAgentSettingCommandHandler 100%
Heimdall.Application.Settings.Commands.SetAgentSetting.SetAgentSettingCommand 100%
Heimdall.Application.Settings.Commands.SetAgentSetting.SetAgentSettingCommandHandler 100%
Heimdall.Application.Settings.Commands.UpdateAppSetting.UpdateAppSettingCommand 100%
Heimdall.Application.Settings.Commands.UpdateAppSetting.UpdateAppSettingCommandHandler 100%
Heimdall.Application.Settings.Mapping.SettingMappingProfile 100%
Heimdall.Application.Settings.Queries.GetAgentSettings.GetAgentSettingsQuery 100%
Heimdall.Application.Settings.Queries.GetAgentSettings.GetAgentSettingsQueryHandler 100%
Heimdall.Application.Settings.Queries.GetEffectiveAgentConfig.GetEffectiveAgentConfigQuery 100%
Heimdall.Application.Settings.Queries.GetEffectiveAgentConfig.GetEffectiveAgentConfigQueryHandler 100%
Heimdall.Application.Settings.Queries.GetSettingByKey.GetSettingByKeyQuery 100%
Heimdall.Application.Settings.Queries.GetSettingByKey.GetSettingByKeyQueryHandler 100%
Heimdall.Application.Settings.Queries.GetSettings.GetSettingsQueryHandler 100%
Heimdall.Application.Sites.Commands.CreateSite.CreateSiteCommand 100%
Heimdall.Application.Sites.Commands.CreateSite.CreateSiteHandler 100%
Heimdall.Application.Sites.Commands.CreateSite.CreateSiteValidator 78.9%
Heimdall.Application.Sites.Commands.DeleteSite.DeleteSiteCommand 100%
Heimdall.Application.Sites.Commands.DeleteSite.DeleteSiteHandler 100%
Heimdall.Application.Sites.Commands.GenerateSiteToken.GenerateSiteTokenCommand 100%
Heimdall.Application.Sites.Commands.GenerateSiteToken.GenerateSiteTokenHandler 94.7%
Heimdall.Application.Sites.Commands.UpdateSite.UpdateSiteCommand 100%
Heimdall.Application.Sites.Commands.UpdateSite.UpdateSiteHandler 100%
Heimdall.Application.Sites.Mapping.SiteMappingProfile 100%
Heimdall.Application.Sites.Queries.GetSite.GetSiteHandler 100%
Heimdall.Application.Sites.Queries.GetSite.GetSiteQuery 100%
Heimdall.Application.Sites.Queries.GetSites.GetSitesHandler 100%
Heimdall.Application.Sites.Queries.GetSites.GetSitesQuery 100%
Heimdall.Application.Stats.Queries.GetAgentStats.GetAgentStatsQueryHandler 91.6%
Heimdall.Application.Stats.Queries.GetStats.GetStatsQueryHandler 100%
Heimdall.Application.Users.Commands.AssignRoles.AssignRolesCommand 100%
Heimdall.Application.Users.Commands.AssignRoles.AssignRolesHandler 96.4%
Heimdall.Application.Users.Commands.AssignSites.AssignSitesCommand 100%
Heimdall.Application.Users.Commands.AssignSites.AssignSitesHandler 100%
Heimdall.Application.Users.Commands.CreateUser.CreateUserCommand 100%
Heimdall.Application.Users.Commands.CreateUser.CreateUserHandler 88.4%
Heimdall.Application.Users.Commands.DeleteUser.DeleteUserCommand 100%
Heimdall.Application.Users.Commands.DeleteUser.DeleteUserHandler 96.4%
Heimdall.Application.Users.Commands.LockUser.LockUserCommand 100%
Heimdall.Application.Users.Commands.LockUser.LockUserHandler 92.8%
Heimdall.Application.Users.Commands.ResetPassword.ResetPasswordCommand 100%
Heimdall.Application.Users.Commands.ResetPassword.ResetPasswordHandler 91.1%
Heimdall.Application.Users.Commands.UnlockUser.UnlockUserCommand 100%
Heimdall.Application.Users.Commands.UnlockUser.UnlockUserHandler 100%
Heimdall.Application.Users.Commands.UpdateUser.UpdateUserCommand 100%
Heimdall.Application.Users.Commands.UpdateUser.UpdateUserHandler 100%
Heimdall.Application.Users.Mapping.UserMappingProfile 100%
Heimdall.Application.Users.Queries.GetMe.GetMeHandler 100%
Heimdall.Application.Users.Queries.GetMe.GetMeQuery 100%
Heimdall.Application.Users.Queries.GetUser.GetUserHandler 100%
Heimdall.Application.Users.Queries.GetUser.GetUserQuery 100%
Heimdall.Application.Users.Queries.GetUsers.GetUsersHandler 100%
Heimdall.Application.Users.Queries.GetUsers.GetUsersQuery 100%
Heimdall.Application.Validators.CreateAppSettingValidator 100%
Heimdall.Application.Validators.CreateCameraValidator 100%
Heimdall.Application.Validators.CreateSiteValidator 78.9%
Heimdall.Application.Validators.CreateUserValidator 100%
Heimdall.Application.Validators.LoginRequestValidator 100%
Heimdall.Application.Validators.RegisterAgentValidator 100%
Heimdall.Application.Validators.RegisterRequestValidator 100%
Heimdall.Application.Validators.SetAgentSettingValidator 100%
Heimdall.Application.Validators.UpdateAppSettingValidator 100%
Heimdall.Application.Validators.UpdateCameraValidator 100%
Heimdall.Application.Validators.UpdateSiteValidator 100%
Heimdall.Application.Validators.UpdateUserValidator 100%
Heimdall.Domain 96.3%
Heimdall.Domain.Entities.Agent 100%
Heimdall.Domain.Entities.AgentSetting 100%
Heimdall.Domain.Entities.ApiKey 95.2%
Heimdall.Domain.Entities.AppRole 100%
Heimdall.Domain.Entities.AppSetting 100%
Heimdall.Domain.Entities.AppUser 77.7%
Heimdall.Domain.Entities.AuditLog 92.8%
Heimdall.Domain.Entities.Camera 98.8%
Heimdall.Domain.Entities.CameraAssignment 100%
Heimdall.Domain.Entities.CameraCredentials 95%
Heimdall.Domain.Entities.CameraDetectionProfile 88.4%
Heimdall.Domain.Entities.CameraDiscoveryResult 96.5%
Heimdall.Domain.Entities.CameraEvent 100%
Heimdall.Domain.Entities.DiscoveredStreamUrl 97%
Heimdall.Domain.Entities.Group 96.2%
Heimdall.Domain.Entities.KnownFace 92.3%
Heimdall.Domain.Entities.Person 100%
Heimdall.Domain.Entities.RevokedRefreshToken 91.6%
Heimdall.Domain.Entities.Site 92.3%
Heimdall.Domain.Entities.UserGroup 90%
Heimdall.Domain.Entities.UserSite 90%
Heimdall.Domain.Primitives 73.9%
Heimdall.Domain.Primitives.Entity<T> 100%
Heimdall.Domain.Primitives.ValueObject 60%
Heimdall.Infrastructure 76.2%
Heimdall.Infrastructure.BackgroundJobs.DependencyInjection 0%
Heimdall.Infrastructure.BackgroundJobs.JobSetup 0%
Heimdall.Infrastructure.Data.AppDbContext 90.3%
Heimdall.Infrastructure.Data.AppDbContextFactory 0%
Heimdall.Infrastructure.Data.Configurations.AgentConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.AgentSettingConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.ApiKeyConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.AppRoleConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.AppSettingConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.AppUserConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.AuditLogConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.CameraAssignmentConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.CameraConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.CameraCredentialsConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.CameraDetectionProfileConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.CameraDiscoveryResultConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.CameraEventConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.DiscoveredStreamConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.GroupEntityTypeConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.IdentityRoleClaimConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.IdentityUserClaimConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.IdentityUserLoginConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.IdentityUserRoleConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.IdentityUserTokenConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.KnownFaceConfiguration 80%
Heimdall.Infrastructure.Data.Configurations.PersonConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.RevokedRefreshTokenConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.SiteConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.UserGroupConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.UserSiteConfiguration 100%
Heimdall.Infrastructure.Data.DbContextExtensions 66.6%
Heimdall.Infrastructure.Data.Interceptors.AuditInterceptor 94.1%
Heimdall.Infrastructure.DependencyInjection 62.5%
Heimdall.Infrastructure.Jobs.AgentFailoverJob 89.3%
Heimdall.Infrastructure.Jobs.HeartbeatMonitorJob 100%
Heimdall.Infrastructure.Migrations.AddRevokedRefreshTokens 99.7%
Heimdall.Infrastructure.Migrations.AppDbContextModelSnapshot 100%
Heimdall.Infrastructure.Migrations.InitialCreate 97.7%
Heimdall.Infrastructure.Persistence.UserRepository 76.5%
Heimdall.Infrastructure.Security.ApiKeyAuthenticationHandler 95.7%
Heimdall.Infrastructure.Security.AppPermissions 100%
Heimdall.Infrastructure.Security.AppRoles 100%
Heimdall.Infrastructure.Security.AuthDataService 100%
Heimdall.Infrastructure.Security.AuthSignInService 100%
Heimdall.Infrastructure.Security.DataProtectorCredentialProtector 100%
Heimdall.Infrastructure.Security.JwtService 100%
Heimdall.Infrastructure.Security.RolePermissionService 100%
Heimdall.Infrastructure.Services.CameraAssignmentService 45.8%
Heimdall.Infrastructure.Services.CameraEventService 91.1%
Heimdall.Infrastructure.Services.Discovery.ArpEntry 0%
Heimdall.Infrastructure.Services.Discovery.ArpProbeService 72.7%
Heimdall.Infrastructure.Services.Discovery.CameraDiscoveryService 48.6%
Heimdall.Infrastructure.Services.Discovery.DiscoveryCoordinatorService 0%
Heimdall.Infrastructure.Services.Discovery.HomeKitDeviceInfo 0%
Heimdall.Infrastructure.Services.Discovery.HttpProbeData 0%
Heimdall.Infrastructure.Services.Discovery.HttpProbeService 68.5%
Heimdall.Infrastructure.Services.Discovery.MdnsProbeService 2.1%
Heimdall.Infrastructure.Services.Discovery.OnvifDeviceInfo 0%
Heimdall.Infrastructure.Services.Discovery.OnvifProbeService 3.9%
Heimdall.Infrastructure.Services.Discovery.PortScanService 77.7%
Heimdall.Infrastructure.Services.Discovery.StreamTesterService 63.1%
Heimdall.Infrastructure.Services.PersonService 64%
System.Text.RegularExpressions.Generated 2.1%
System.Text.RegularExpressions.Generated.<RegexGenerator_g>FBF3D522B2772D8B2CEF77394DAF1D7F439F9F4D4A6B2ABFE407DB51869AB636C__ArpPattern_0 4.9%
System.Text.RegularExpressions.Generated.<RegexGenerator_g>FBF3D522B2772D8B2CEF77394DAF1D7F439F9F4D4A6B2ABFE407DB51869AB636C__CodecPattern_1 0%
System.Text.RegularExpressions.Generated.<RegexGenerator_g>FBF3D522B2772D8B2CEF77394DAF1D7F439F9F4D4A6B2ABFE407DB51869AB636C__ResolutionInFmtpPattern_2 0%
Heimdall.TestCommon 88.8%
Heimdall.TestCommon.PostgreSqlContainerFixture 88.8%
Heimdall.Web 22.6%
Heimdall.Api.Controllers.AgentsController 50%
Heimdall.Api.Controllers.AssignmentsController 62.2%
Heimdall.Api.Controllers.AuditLogsController 85.7%
Heimdall.Api.Controllers.AuthController 35.5%
Heimdall.Api.Controllers.CamerasController 39.3%
Heimdall.Api.Controllers.ControllerBaseExtensions 100%
Heimdall.Api.Controllers.DiscoveryController 55.7%
Heimdall.Api.Controllers.EventsController 45.9%
Heimdall.Api.Controllers.GroupsController 62.7%
Heimdall.Api.Controllers.HealthController 12.5%
Heimdall.Api.Controllers.PermissionInfo 100%
Heimdall.Api.Controllers.PermissionsController 97.8%
Heimdall.Api.Controllers.PermissionsListResponse 100%
Heimdall.Api.Controllers.PersonsController 63.8%
Heimdall.Api.Controllers.RoleResponse 100%
Heimdall.Api.Controllers.RolesController 100%
Heimdall.Api.Controllers.RolesListResponse 100%
Heimdall.Api.Controllers.SettingsController 96.1%
Heimdall.Api.Controllers.SitesController 48.7%
Heimdall.Api.Controllers.StatsController 84.6%
Heimdall.Api.Controllers.UsersController 29.4%
Heimdall.Api.Filters.ExceptionFilter 100%
Heimdall.Api.Hubs.ConfigBroadcastService 100%
Heimdall.Api.Hubs.ConfigHub 0%
Heimdall.Api.Hubs.EventBroadcastService 0%
Heimdall.Api.Hubs.EventsHub 100%
Heimdall.Web.Components.Layout.MainLayout 0%
Heimdall.Web.Components.Layout.MudBlazorLayout 0%
Heimdall.Web.Components.Pages.Admin.AllAgentsPage 0%
Heimdall.Web.Components.Pages.Admin.ClaimsPage 0%
Heimdall.Web.Components.Pages.Admin.GroupsPage 0%
Heimdall.Web.Components.Pages.Admin.RolesPage 0%
Heimdall.Web.Components.Pages.AgentDetail 0%
Heimdall.Web.Components.Pages.AgentsPage 0%
Heimdall.Web.Components.Pages.AuditLogsPage 0%
Heimdall.Web.Components.Pages.CameraDetail 0%
Heimdall.Web.Components.Pages.CamerasPage 0%
Heimdall.Web.Components.Pages.Dashboard 0%
Heimdall.Web.Components.Pages.Error 0%
Heimdall.Web.Components.Pages.EventsPage 0%
Heimdall.Web.Components.Pages.Login 0%
Heimdall.Web.Components.Pages.Profile 0%
Heimdall.Web.Components.Pages.RedirectToLogin 0%
Heimdall.Web.Components.Pages.Register 0%
Heimdall.Web.Components.Pages.SettingsPage 0%
Heimdall.Web.Components.Pages.SiteDetail 0%
Heimdall.Web.Components.Pages.SitesPage 0%
Heimdall.Web.Components.Pages.SnapshotsPage 0%
Heimdall.Web.Components.Pages.UsersPage 0%
Heimdall.Web.Components.Shared.EmptyState 0%
Heimdall.Web.Components.Shared.FilterBar 0%
Heimdall.Web.Components.Shared.LoadingSkeleton 0%
Heimdall.Web.Components.Shared.PaginationBar 0%
Heimdall.Web.Components.Shared.SectionCard 0%
Heimdall.Web.Components.Shared.StatusChip 0%
Heimdall.Web.Services.AgentItem 0%
Heimdall.Web.Services.AgentSettingItem 0%
Heimdall.Web.Services.AgentStatItem 0%
Heimdall.Web.Services.AppSettingItem 0%
Heimdall.Web.Services.AuditLogItem 100%
Heimdall.Web.Services.AuthHelper 0%
Heimdall.Web.Services.AuthResponse 100%
Heimdall.Web.Services.AuthState 60%
Heimdall.Web.Services.CameraItem 0%
Heimdall.Web.Services.CreateAppSettingRequest 0%
Heimdall.Web.Services.EventItem 0%
Heimdall.Web.Services.EventPageResult 0%
Heimdall.Web.Services.GroupItem 100%
Heimdall.Web.Services.HeimdallApiClient 26.7%
Heimdall.Web.Services.HeimdallAuthStateProvider 10.4%
Heimdall.Web.Services.PagedData<T> 100%
Heimdall.Web.Services.PasswordResetResult 0%
Heimdall.Web.Services.PermissionItem 100%
Heimdall.Web.Services.PermissionsListResponse 100%
Heimdall.Web.Services.RoleItem 100%
Heimdall.Web.Services.RolesListResponse 100%
Heimdall.Web.Services.SetAgentSettingRequest 0%
Heimdall.Web.Services.SiteItem 0%
Heimdall.Web.Services.SiteWithTokenResult 0%
Heimdall.Web.Services.StatsResult 100%
Heimdall.Web.Services.TokenRefreshHandler 35.5%
Heimdall.Web.Services.TokenResult 0%
Heimdall.Web.Services.UpdateAppSettingRequest 0%
Heimdall.Web.Services.UserInfo 100%
Heimdall.Web.Services.UserItem 100%
Microsoft.AspNetCore.OpenApi.Generated 1%
Program 75.3%
Sentry.Generated.BuildPropertyInitializer 100%
SignInRequest 0%
System.Runtime.CompilerServices 0%
+522
View File
@@ -0,0 +1,522 @@
Summary
Generated on: 07/23/2026 - 19:23:20
Coverage date: 07/23/2026 - 07:02:46 - 07/23/2026 - 19:23:08
Parser: MultiReport (42x Cobertura)
Assemblies: 7
Classes: 488
Files: 328
Line coverage: 64.1%
Covered lines: 11264
Uncovered lines: 6294
Coverable lines: 17558
Total lines: 27041
Branch coverage: 24.3% (824 of 3379)
Covered branches: 824
Total branches: 3379
Method coverage: 66.8% (1419 of 2122)
Full method coverage: 62.4% (1326 of 2122)
Covered methods: 1419
Fully covered methods: 1326
Total methods: 2122
Heimdall.Agent 58.7%
Heimdall.Agent.AgentOptions 85.7%
Heimdall.Agent.Services.AgentHealthCheck 100%
Heimdall.Agent.Services.AgentRegistrationService 86.1%
Heimdall.Agent.Services.AgentState 100%
Heimdall.Agent.Services.CameraStreamService 42.6%
Heimdall.Agent.Services.ConfigReceiverService 25%
Heimdall.Agent.Services.DetectionResult 100%
Heimdall.Agent.Services.FrameAnalysisResult 100%
Heimdall.Agent.Services.FrameAnalyzerService 42.1%
Heimdall.Agent.Services.HeartbeatRequest 100%
Heimdall.Agent.Services.RegisterRequest 100%
Heimdall.Agent.Services.RegisterResponse 100%
Heimdall.Agent.Services.RetryDelayed 100%
Heimdall.Agent.Services.SystemInfo 83.3%
Heimdall.Agent.Services.SystemMetrics 100%
Heimdall.Agent.Services.SystemMetricsProvider 73.6%
Program 0%
Sentry.Generated.BuildPropertyInitializer 100%
Heimdall.Application 87.8%
Heimdall.Application.Agents.Commands.Heartbeat.HeartbeatCommand 100%
Heimdall.Application.Agents.Commands.Heartbeat.HeartbeatHandler 100%
Heimdall.Application.Agents.Commands.RegisterAgent.RegisterAgentCommand 100%
Heimdall.Application.Agents.Commands.RegisterAgent.RegisterAgentHandler 100%
Heimdall.Application.Agents.Commands.RegisterAgent.RegisterAgentValidator 100%
Heimdall.Application.Agents.Mapping.AgentMappingProfile 100%
Heimdall.Application.Agents.Queries.GetAgent.GetAgentHandler 100%
Heimdall.Application.Agents.Queries.GetAgent.GetAgentQuery 100%
Heimdall.Application.Agents.Queries.GetAgentsBySite.GetAgentsBySiteHandler 100%
Heimdall.Application.Agents.Queries.GetAgentsBySite.GetAgentsBySiteQuery 100%
Heimdall.Application.Agents.Queries.GetAllAgents.GetAllAgentsHandler 100%
Heimdall.Application.Agents.Queries.GetAllAgents.GetAllAgentsQuery 100%
Heimdall.Application.Assignments.Commands.AssignCamera.AssignCameraCommand 100%
Heimdall.Application.Assignments.Commands.AssignCamera.AssignCameraHandler 100%
Heimdall.Application.Assignments.Commands.AssignSite.AssignSiteCommand 100%
Heimdall.Application.Assignments.Commands.AssignSite.AssignSiteHandler 100%
Heimdall.Application.Assignments.Commands.Failover.FailoverCommand 100%
Heimdall.Application.Assignments.Commands.Failover.FailoverHandler 100%
Heimdall.Application.Assignments.Commands.ReleaseCamera.ReleaseCameraCommand 100%
Heimdall.Application.Assignments.Commands.ReleaseCamera.ReleaseCameraHandler 100%
Heimdall.Application.Assignments.Mapping.AssignmentMappingProfile 100%
Heimdall.Application.Assignments.Queries.GetActiveAssignment.GetActiveAssignmentHandler 100%
Heimdall.Application.Assignments.Queries.GetActiveAssignment.GetActiveAssignmentQuery 100%
Heimdall.Application.Assignments.Queries.GetAgentAssignments.GetAgentAssignmentsHandler 100%
Heimdall.Application.Assignments.Queries.GetAgentAssignments.GetAgentAssignmentsQuery 100%
Heimdall.Application.Assignments.Queries.GetCameraHistory.GetCameraHistoryHandler 100%
Heimdall.Application.Assignments.Queries.GetCameraHistory.GetCameraHistoryQuery 100%
Heimdall.Application.Audit.Queries.GetAuditLogs.GetAuditLogsQuery 100%
Heimdall.Application.Audit.Queries.GetAuditLogs.GetAuditLogsQueryHandler 100%
Heimdall.Application.Auth.AuthHelper 100%
Heimdall.Application.Auth.Commands.ChangePassword.ChangePasswordCommand 100%
Heimdall.Application.Auth.Commands.ChangePassword.ChangePasswordHandler 100%
Heimdall.Application.Auth.Commands.ChangePassword.ChangePasswordValidator 0%
Heimdall.Application.Auth.Commands.Disable2fa.Disable2faCommand 0%
Heimdall.Application.Auth.Commands.Disable2fa.Disable2faHandler 0%
Heimdall.Application.Auth.Commands.Enable2fa.Enable2faCommand 0%
Heimdall.Application.Auth.Commands.Enable2fa.Enable2faHandler 0%
Heimdall.Application.Auth.Commands.Login.LoginCommand 100%
Heimdall.Application.Auth.Commands.Login.LoginHandler 87.5%
Heimdall.Application.Auth.Commands.Login.LoginValidator 100%
Heimdall.Application.Auth.Commands.Logout.LogoutCommand 0%
Heimdall.Application.Auth.Commands.Logout.LogoutHandler 0%
Heimdall.Application.Auth.Commands.RefreshToken.RefreshTokenCommand 100%
Heimdall.Application.Auth.Commands.RefreshToken.RefreshTokenHandler 92.6%
Heimdall.Application.Auth.Commands.Register.RegisterCommand 100%
Heimdall.Application.Auth.Commands.Register.RegisterHandler 87.6%
Heimdall.Application.Auth.Commands.Register.RegisterValidator 100%
Heimdall.Application.Auth.Commands.RegisterAdmin.RegisterAdminCommand 100%
Heimdall.Application.Auth.Commands.RegisterAdmin.RegisterAdminHandler 100%
Heimdall.Application.Auth.Commands.RegisterAdmin.RegisterAdminValidator 100%
Heimdall.Application.Auth.Commands.Verify2fa.Verify2faCommand 0%
Heimdall.Application.Auth.Commands.Verify2fa.Verify2faHandler 0%
Heimdall.Application.Auth.Commands.Verify2fa.Verify2faValidator 0%
Heimdall.Application.Auth.Mapping.AuthMappingProfile 100%
Heimdall.Application.Behaviors.LoggingBehavior<T1, T2> 100%
Heimdall.Application.Behaviors.ValidationBehavior<T1, T2> 92.8%
Heimdall.Application.Cameras.Commands.CreateCamera.CreateCameraCommand 100%
Heimdall.Application.Cameras.Commands.CreateCamera.CreateCameraCommandHandler 100%
Heimdall.Application.Cameras.Commands.CreateCamera.CreateCameraCommandValidator 100%
Heimdall.Application.Cameras.Commands.DeleteCamera.DeleteCameraCommand 100%
Heimdall.Application.Cameras.Commands.DeleteCamera.DeleteCameraCommandHandler 100%
Heimdall.Application.Cameras.Commands.SetCredentials.SetCameraCredentialsCommand 100%
Heimdall.Application.Cameras.Commands.SetCredentials.SetCameraCredentialsCommandHandler 100%
Heimdall.Application.Cameras.Commands.SetCredentials.SetCameraCredentialsCommandValidator 0%
Heimdall.Application.Cameras.Commands.UpdateCamera.UpdateCameraCommand 100%
Heimdall.Application.Cameras.Commands.UpdateCamera.UpdateCameraCommandHandler 100%
Heimdall.Application.Cameras.Commands.UpdateCamera.UpdateCameraCommandValidator 0%
Heimdall.Application.Cameras.Mapping.CameraMappingProfile 100%
Heimdall.Application.Cameras.Queries.GetCamera.GetCameraQuery 100%
Heimdall.Application.Cameras.Queries.GetCamera.GetCameraQueryHandler 100%
Heimdall.Application.Cameras.Queries.GetCamerasBySite.GetCamerasBySiteQuery 100%
Heimdall.Application.Cameras.Queries.GetCamerasBySite.GetCamerasBySiteQueryHandler 100%
Heimdall.Application.Common.Mappings.IMapFrom<T> 0%
Heimdall.Application.Common.Mappings.MappingProfile 44.4%
Heimdall.Application.Common.ServiceResult 100%
Heimdall.Application.Common.ServiceResult<T> 100%
Heimdall.Application.DependencyInjection 100%
Heimdall.Application.Discovery.Commands.BuildStreamUrls.BuildStreamUrlsCommand 100%
Heimdall.Application.Discovery.Commands.BuildStreamUrls.BuildStreamUrlsCommandHandler 100%
Heimdall.Application.Discovery.Commands.CancelTestSession.CancelTestSessionCommand 100%
Heimdall.Application.Discovery.Commands.CancelTestSession.CancelTestSessionCommandHandler 100%
Heimdall.Application.Discovery.Commands.ConfirmDiscovery.ConfirmDiscoveryCommand 100%
Heimdall.Application.Discovery.Commands.ConfirmDiscovery.ConfirmDiscoveryCommandHandler 100%
Heimdall.Application.Discovery.Commands.ProbeIp.ProbeIpCommand 100%
Heimdall.Application.Discovery.Commands.ProbeIp.ProbeIpCommandHandler 100%
Heimdall.Application.Discovery.Commands.ScanSubnet.ScanSubnetCommand 100%
Heimdall.Application.Discovery.Commands.ScanSubnet.ScanSubnetCommandHandler 100%
Heimdall.Application.Discovery.Commands.TestStreams.TestStreamsCommand 100%
Heimdall.Application.Discovery.Commands.TestStreams.TestStreamsCommandHandler 100%
Heimdall.Application.Discovery.Mapping.DiscoveryMappingProfile 100%
Heimdall.Application.Discovery.Queries.CheckDuplicate.CheckDuplicateQuery 100%
Heimdall.Application.Discovery.Queries.CheckDuplicate.CheckDuplicateQueryHandler 100%
Heimdall.Application.Discovery.Queries.GetScreenshot.GetScreenshotQuery 100%
Heimdall.Application.Discovery.Queries.GetScreenshot.GetScreenshotQueryHandler 100%
Heimdall.Application.Discovery.Queries.GetTestSession.GetTestSessionQuery 100%
Heimdall.Application.Discovery.Queries.GetTestSession.GetTestSessionQueryHandler 100%
Heimdall.Application.Discovery.Queries.SearchDatabase.SearchDatabaseQuery 100%
Heimdall.Application.Discovery.Queries.SearchDatabase.SearchDatabaseQueryHandler 100%
Heimdall.Application.DTOs.AgentHeartbeatRequest 100%
Heimdall.Application.DTOs.AgentResponse 42.8%
Heimdall.Application.DTOs.AgentSettingDto 100%
Heimdall.Application.DTOs.AgentStatItem 100%
Heimdall.Application.DTOs.ApiKeyResponse 0%
Heimdall.Application.DTOs.AppSettingDto 100%
Heimdall.Application.DTOs.ArpInfo 0%
Heimdall.Application.DTOs.AssignmentResponse 100%
Heimdall.Application.DTOs.AssignmentResult 0%
Heimdall.Application.DTOs.AssignRequest 100%
Heimdall.Application.DTOs.AssignRolesRequest 0%
Heimdall.Application.DTOs.AssignSitesRequest 0%
Heimdall.Application.DTOs.AttachSnapshotRequest 0%
Heimdall.Application.DTOs.AuditLogResponse 0%
Heimdall.Application.DTOs.AuthResponse 100%
Heimdall.Application.DTOs.CameraCheckResponse 100%
Heimdall.Application.DTOs.CameraDbEntry 100%
Heimdall.Application.DTOs.CameraDetectionProfileRequest 0%
Heimdall.Application.DTOs.CameraEventFilterRequest 100%
Heimdall.Application.DTOs.CameraEventResponse 69.2%
Heimdall.Application.DTOs.CameraResponse 100%
Heimdall.Application.DTOs.ChangePasswordRequest 0%
Heimdall.Application.DTOs.CheckDuplicateRequest 100%
Heimdall.Application.DTOs.ConfirmDiscoveryRequest 20%
Heimdall.Application.DTOs.CreateApiKeyResponse 0%
Heimdall.Application.DTOs.CreateAppSettingRequest 100%
Heimdall.Application.DTOs.CreateCameraEventRequest 100%
Heimdall.Application.DTOs.CreateCameraRequest 100%
Heimdall.Application.DTOs.CreateGroupRequest 100%
Heimdall.Application.DTOs.CreatePersonRequest 100%
Heimdall.Application.DTOs.CreateSiteRequest 100%
Heimdall.Application.DTOs.CreateUserRequest 100%
Heimdall.Application.DTOs.FailoverResult 0%
Heimdall.Application.DTOs.GroupMemberResponse 50%
Heimdall.Application.DTOs.GroupResponse 100%
Heimdall.Application.DTOs.HomeKitProbeInfo 0%
Heimdall.Application.DTOs.HttpProbeInfo 0%
Heimdall.Application.DTOs.KnownFaceResponse 100%
Heimdall.Application.DTOs.LoginRequest 100%
Heimdall.Application.DTOs.LogoutRequest 0%
Heimdall.Application.DTOs.OnvifProbeInfo 0%
Heimdall.Application.DTOs.PagedResult<T> 100%
Heimdall.Application.DTOs.PersonResponse 100%
Heimdall.Application.DTOs.ProbeRequest 100%
Heimdall.Application.DTOs.ProbeResponse 36.3%
Heimdall.Application.DTOs.RefreshTokenRequest 0%
Heimdall.Application.DTOs.RegisterAgentRequest 100%
Heimdall.Application.DTOs.RegisterAgentResponse 100%
Heimdall.Application.DTOs.RegisterFaceRequest 0%
Heimdall.Application.DTOs.RegisterRequest 100%
Heimdall.Application.DTOs.RegistrationTokenResponse 100%
Heimdall.Application.DTOs.ResetPasswordResponse 100%
Heimdall.Application.DTOs.ScanProgress 0%
Heimdall.Application.DTOs.ScanRequest 100%
Heimdall.Application.DTOs.SearchResponse 100%
Heimdall.Application.DTOs.SetAgentSettingRequest 100%
Heimdall.Application.DTOs.SiteResponse 100%
Heimdall.Application.DTOs.SiteWithTokenResponse 0%
Heimdall.Application.DTOs.StatsResponse 100%
Heimdall.Application.DTOs.StreamBuildRequest 100%
Heimdall.Application.DTOs.StreamBuildResponse 100%
Heimdall.Application.DTOs.StreamTestRequest 100%
Heimdall.Application.DTOs.StreamTestResult 25%
Heimdall.Application.DTOs.StreamTestSession 100%
Heimdall.Application.DTOs.UpdateAppSettingRequest 100%
Heimdall.Application.DTOs.UpdateCameraRequest 66.6%
Heimdall.Application.DTOs.UpdateGroupRequest 100%
Heimdall.Application.DTOs.UpdatePersonRequest 100%
Heimdall.Application.DTOs.UpdateSiteRequest 100%
Heimdall.Application.DTOs.UpdateUserRequest 100%
Heimdall.Application.DTOs.UserInfo 100%
Heimdall.Application.DTOs.UserResponse 100%
Heimdall.Application.DTOs.Verify2faRequest 0%
Heimdall.Application.Events.Commands.AttachSnapshot.AttachSnapshotCommand 100%
Heimdall.Application.Events.Commands.AttachSnapshot.AttachSnapshotHandler 100%
Heimdall.Application.Events.Commands.CreateEvent.CreateEventCommand 100%
Heimdall.Application.Events.Commands.CreateEvent.CreateEventHandler 95.4%
Heimdall.Application.Events.Commands.DeleteEvent.DeleteEventCommand 100%
Heimdall.Application.Events.Commands.DeleteEvent.DeleteEventHandler 100%
Heimdall.Application.Events.Mapping.EventMappingProfile 100%
Heimdall.Application.Events.Notifications.EventCreatedNotification 100%
Heimdall.Application.Events.Notifications.EventCreatedNotificationHandler 0%
Heimdall.Application.Events.Queries.GetEvent.GetEventHandler 100%
Heimdall.Application.Events.Queries.GetEvent.GetEventQuery 100%
Heimdall.Application.Events.Queries.GetEvents.GetEventsHandler 83.8%
Heimdall.Application.Events.Queries.GetEvents.GetEventsQuery 100%
Heimdall.Application.Events.Queries.GetRecentByCamera.GetRecentByCameraHandler 100%
Heimdall.Application.Events.Queries.GetRecentByCamera.GetRecentByCameraQuery 100%
Heimdall.Application.Groups.Commands.AddUserToGroup.AddUserToGroupCommand 100%
Heimdall.Application.Groups.Commands.AddUserToGroup.AddUserToGroupCommandHandler 100%
Heimdall.Application.Groups.Commands.CreateGroup.CreateGroupCommand 100%
Heimdall.Application.Groups.Commands.CreateGroup.CreateGroupCommandHandler 100%
Heimdall.Application.Groups.Commands.DeleteGroup.DeleteGroupCommand 100%
Heimdall.Application.Groups.Commands.DeleteGroup.DeleteGroupCommandHandler 100%
Heimdall.Application.Groups.Commands.RemoveUserFromGroup.RemoveUserFromGroupCommand 100%
Heimdall.Application.Groups.Commands.RemoveUserFromGroup.RemoveUserFromGroupCommandHandler 100%
Heimdall.Application.Groups.Commands.UpdateGroup.UpdateGroupCommand 100%
Heimdall.Application.Groups.Commands.UpdateGroup.UpdateGroupCommandHandler 100%
Heimdall.Application.Groups.Mapping.GroupMappingProfile 100%
Heimdall.Application.Groups.Queries.GetGroup.GetGroupQuery 100%
Heimdall.Application.Groups.Queries.GetGroup.GetGroupQueryHandler 100%
Heimdall.Application.Groups.Queries.GetGroupMembers.GetGroupMembersQuery 100%
Heimdall.Application.Groups.Queries.GetGroupMembers.GetGroupMembersQueryHandler 100%
Heimdall.Application.Groups.Queries.GetGroups.GetGroupsQuery 100%
Heimdall.Application.Groups.Queries.GetGroups.GetGroupsQueryHandler 100%
Heimdall.Application.Persons.Commands.CreatePerson.CreatePersonCommand 100%
Heimdall.Application.Persons.Commands.CreatePerson.CreatePersonCommandHandler 100%
Heimdall.Application.Persons.Commands.DeleteFace.DeleteFaceCommand 100%
Heimdall.Application.Persons.Commands.DeleteFace.DeleteFaceCommandHandler 100%
Heimdall.Application.Persons.Commands.DeletePerson.DeletePersonCommand 100%
Heimdall.Application.Persons.Commands.DeletePerson.DeletePersonCommandHandler 100%
Heimdall.Application.Persons.Commands.RegisterFace.RegisterFaceCommand 100%
Heimdall.Application.Persons.Commands.RegisterFace.RegisterFaceCommandHandler 100%
Heimdall.Application.Persons.Commands.UpdatePerson.UpdatePersonCommand 100%
Heimdall.Application.Persons.Commands.UpdatePerson.UpdatePersonCommandHandler 100%
Heimdall.Application.Persons.Mapping.PersonMappingProfile 100%
Heimdall.Application.Persons.Queries.GetFaces.GetFacesQuery 100%
Heimdall.Application.Persons.Queries.GetFaces.GetFacesQueryHandler 100%
Heimdall.Application.Persons.Queries.GetPerson.GetPersonQuery 100%
Heimdall.Application.Persons.Queries.GetPerson.GetPersonQueryHandler 100%
Heimdall.Application.Persons.Queries.GetPersons.GetPersonsQuery 100%
Heimdall.Application.Persons.Queries.GetPersons.GetPersonsQueryHandler 100%
Heimdall.Application.Services.SignInServiceResult 100%
Heimdall.Application.Settings.Commands.CreateAppSetting.CreateAppSettingCommand 100%
Heimdall.Application.Settings.Commands.CreateAppSetting.CreateAppSettingCommandHandler 100%
Heimdall.Application.Settings.Commands.DeleteAppSetting.DeleteAppSettingCommand 100%
Heimdall.Application.Settings.Commands.DeleteAppSetting.DeleteAppSettingCommandHandler 100%
Heimdall.Application.Settings.Commands.RemoveAgentSetting.RemoveAgentSettingCommand 100%
Heimdall.Application.Settings.Commands.RemoveAgentSetting.RemoveAgentSettingCommandHandler 100%
Heimdall.Application.Settings.Commands.SetAgentSetting.SetAgentSettingCommand 100%
Heimdall.Application.Settings.Commands.SetAgentSetting.SetAgentSettingCommandHandler 100%
Heimdall.Application.Settings.Commands.UpdateAppSetting.UpdateAppSettingCommand 100%
Heimdall.Application.Settings.Commands.UpdateAppSetting.UpdateAppSettingCommandHandler 100%
Heimdall.Application.Settings.Mapping.SettingMappingProfile 100%
Heimdall.Application.Settings.Queries.GetAgentSettings.GetAgentSettingsQuery 100%
Heimdall.Application.Settings.Queries.GetAgentSettings.GetAgentSettingsQueryHandler 100%
Heimdall.Application.Settings.Queries.GetEffectiveAgentConfig.GetEffectiveAgentConfigQuery 100%
Heimdall.Application.Settings.Queries.GetEffectiveAgentConfig.GetEffectiveAgentConfigQueryHandler 100%
Heimdall.Application.Settings.Queries.GetSettingByKey.GetSettingByKeyQuery 100%
Heimdall.Application.Settings.Queries.GetSettingByKey.GetSettingByKeyQueryHandler 100%
Heimdall.Application.Settings.Queries.GetSettings.GetSettingsQueryHandler 100%
Heimdall.Application.Sites.Commands.CreateSite.CreateSiteCommand 100%
Heimdall.Application.Sites.Commands.CreateSite.CreateSiteHandler 100%
Heimdall.Application.Sites.Commands.CreateSite.CreateSiteValidator 78.9%
Heimdall.Application.Sites.Commands.DeleteSite.DeleteSiteCommand 100%
Heimdall.Application.Sites.Commands.DeleteSite.DeleteSiteHandler 100%
Heimdall.Application.Sites.Commands.GenerateSiteToken.GenerateSiteTokenCommand 100%
Heimdall.Application.Sites.Commands.GenerateSiteToken.GenerateSiteTokenHandler 94.7%
Heimdall.Application.Sites.Commands.UpdateSite.UpdateSiteCommand 100%
Heimdall.Application.Sites.Commands.UpdateSite.UpdateSiteHandler 100%
Heimdall.Application.Sites.Mapping.SiteMappingProfile 100%
Heimdall.Application.Sites.Queries.GetSite.GetSiteHandler 100%
Heimdall.Application.Sites.Queries.GetSite.GetSiteQuery 100%
Heimdall.Application.Sites.Queries.GetSites.GetSitesHandler 100%
Heimdall.Application.Sites.Queries.GetSites.GetSitesQuery 100%
Heimdall.Application.Stats.Queries.GetAgentStats.GetAgentStatsQueryHandler 91.6%
Heimdall.Application.Stats.Queries.GetStats.GetStatsQueryHandler 100%
Heimdall.Application.Users.Commands.AssignRoles.AssignRolesCommand 100%
Heimdall.Application.Users.Commands.AssignRoles.AssignRolesHandler 96.4%
Heimdall.Application.Users.Commands.AssignSites.AssignSitesCommand 100%
Heimdall.Application.Users.Commands.AssignSites.AssignSitesHandler 100%
Heimdall.Application.Users.Commands.CreateUser.CreateUserCommand 100%
Heimdall.Application.Users.Commands.CreateUser.CreateUserHandler 88.4%
Heimdall.Application.Users.Commands.DeleteUser.DeleteUserCommand 100%
Heimdall.Application.Users.Commands.DeleteUser.DeleteUserHandler 96.4%
Heimdall.Application.Users.Commands.LockUser.LockUserCommand 100%
Heimdall.Application.Users.Commands.LockUser.LockUserHandler 92.8%
Heimdall.Application.Users.Commands.ResetPassword.ResetPasswordCommand 100%
Heimdall.Application.Users.Commands.ResetPassword.ResetPasswordHandler 91.1%
Heimdall.Application.Users.Commands.UnlockUser.UnlockUserCommand 100%
Heimdall.Application.Users.Commands.UnlockUser.UnlockUserHandler 100%
Heimdall.Application.Users.Commands.UpdateUser.UpdateUserCommand 100%
Heimdall.Application.Users.Commands.UpdateUser.UpdateUserHandler 100%
Heimdall.Application.Users.Mapping.UserMappingProfile 100%
Heimdall.Application.Users.Queries.GetMe.GetMeHandler 100%
Heimdall.Application.Users.Queries.GetMe.GetMeQuery 100%
Heimdall.Application.Users.Queries.GetUser.GetUserHandler 100%
Heimdall.Application.Users.Queries.GetUser.GetUserQuery 100%
Heimdall.Application.Users.Queries.GetUsers.GetUsersHandler 100%
Heimdall.Application.Users.Queries.GetUsers.GetUsersQuery 100%
Heimdall.Application.Validators.CreateAppSettingValidator 100%
Heimdall.Application.Validators.CreateCameraValidator 100%
Heimdall.Application.Validators.CreateSiteValidator 78.9%
Heimdall.Application.Validators.CreateUserValidator 100%
Heimdall.Application.Validators.LoginRequestValidator 100%
Heimdall.Application.Validators.RegisterAgentValidator 100%
Heimdall.Application.Validators.RegisterRequestValidator 100%
Heimdall.Application.Validators.SetAgentSettingValidator 100%
Heimdall.Application.Validators.UpdateAppSettingValidator 100%
Heimdall.Application.Validators.UpdateCameraValidator 100%
Heimdall.Application.Validators.UpdateSiteValidator 100%
Heimdall.Application.Validators.UpdateUserValidator 100%
Heimdall.Domain 96.3%
Heimdall.Domain.Entities.Agent 100%
Heimdall.Domain.Entities.AgentSetting 100%
Heimdall.Domain.Entities.ApiKey 95.2%
Heimdall.Domain.Entities.AppRole 100%
Heimdall.Domain.Entities.AppSetting 100%
Heimdall.Domain.Entities.AppUser 77.7%
Heimdall.Domain.Entities.AuditLog 92.8%
Heimdall.Domain.Entities.Camera 98.8%
Heimdall.Domain.Entities.CameraAssignment 100%
Heimdall.Domain.Entities.CameraCredentials 95%
Heimdall.Domain.Entities.CameraDetectionProfile 88.4%
Heimdall.Domain.Entities.CameraDiscoveryResult 96.5%
Heimdall.Domain.Entities.CameraEvent 100%
Heimdall.Domain.Entities.DiscoveredStreamUrl 97%
Heimdall.Domain.Entities.Group 96.2%
Heimdall.Domain.Entities.KnownFace 92.3%
Heimdall.Domain.Entities.Person 100%
Heimdall.Domain.Entities.RevokedRefreshToken 91.6%
Heimdall.Domain.Entities.Site 92.3%
Heimdall.Domain.Entities.UserGroup 90%
Heimdall.Domain.Entities.UserSite 90%
Heimdall.Domain.Primitives 73.9%
Heimdall.Domain.Primitives.Entity<T> 100%
Heimdall.Domain.Primitives.ValueObject 60%
Heimdall.Infrastructure 76.2%
Heimdall.Infrastructure.BackgroundJobs.DependencyInjection 0%
Heimdall.Infrastructure.BackgroundJobs.JobSetup 0%
Heimdall.Infrastructure.Data.AppDbContext 90.3%
Heimdall.Infrastructure.Data.AppDbContextFactory 0%
Heimdall.Infrastructure.Data.Configurations.AgentConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.AgentSettingConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.ApiKeyConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.AppRoleConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.AppSettingConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.AppUserConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.AuditLogConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.CameraAssignmentConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.CameraConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.CameraCredentialsConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.CameraDetectionProfileConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.CameraDiscoveryResultConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.CameraEventConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.DiscoveredStreamConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.GroupEntityTypeConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.IdentityRoleClaimConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.IdentityUserClaimConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.IdentityUserLoginConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.IdentityUserRoleConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.IdentityUserTokenConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.KnownFaceConfiguration 80%
Heimdall.Infrastructure.Data.Configurations.PersonConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.RevokedRefreshTokenConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.SiteConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.UserGroupConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.UserSiteConfiguration 100%
Heimdall.Infrastructure.Data.DbContextExtensions 66.6%
Heimdall.Infrastructure.Data.Interceptors.AuditInterceptor 94.1%
Heimdall.Infrastructure.DependencyInjection 62.5%
Heimdall.Infrastructure.Jobs.AgentFailoverJob 89.3%
Heimdall.Infrastructure.Jobs.HeartbeatMonitorJob 100%
Heimdall.Infrastructure.Migrations.AddRevokedRefreshTokens 99.7%
Heimdall.Infrastructure.Migrations.AppDbContextModelSnapshot 100%
Heimdall.Infrastructure.Migrations.InitialCreate 97.7%
Heimdall.Infrastructure.Persistence.UserRepository 76.5%
Heimdall.Infrastructure.Security.ApiKeyAuthenticationHandler 95.7%
Heimdall.Infrastructure.Security.AppPermissions 100%
Heimdall.Infrastructure.Security.AppRoles 100%
Heimdall.Infrastructure.Security.AuthDataService 100%
Heimdall.Infrastructure.Security.AuthSignInService 100%
Heimdall.Infrastructure.Security.DataProtectorCredentialProtector 100%
Heimdall.Infrastructure.Security.JwtService 100%
Heimdall.Infrastructure.Security.RolePermissionService 100%
Heimdall.Infrastructure.Services.CameraAssignmentService 45.8%
Heimdall.Infrastructure.Services.CameraEventService 91.1%
Heimdall.Infrastructure.Services.Discovery.ArpEntry 0%
Heimdall.Infrastructure.Services.Discovery.ArpProbeService 72.7%
Heimdall.Infrastructure.Services.Discovery.CameraDiscoveryService 48.6%
Heimdall.Infrastructure.Services.Discovery.DiscoveryCoordinatorService 0%
Heimdall.Infrastructure.Services.Discovery.HomeKitDeviceInfo 0%
Heimdall.Infrastructure.Services.Discovery.HttpProbeData 0%
Heimdall.Infrastructure.Services.Discovery.HttpProbeService 68.5%
Heimdall.Infrastructure.Services.Discovery.MdnsProbeService 2.1%
Heimdall.Infrastructure.Services.Discovery.OnvifDeviceInfo 0%
Heimdall.Infrastructure.Services.Discovery.OnvifProbeService 3.9%
Heimdall.Infrastructure.Services.Discovery.PortScanService 77.7%
Heimdall.Infrastructure.Services.Discovery.StreamTesterService 63.1%
Heimdall.Infrastructure.Services.PersonService 64%
System.Text.RegularExpressions.Generated 2.1%
System.Text.RegularExpressions.Generated.<RegexGenerator_g>FBF3D522B2772D8B2CEF77394DAF1D7F439F9F4D4A6B2ABFE407DB51869AB636C__ArpPattern_0 4.9%
System.Text.RegularExpressions.Generated.<RegexGenerator_g>FBF3D522B2772D8B2CEF77394DAF1D7F439F9F4D4A6B2ABFE407DB51869AB636C__CodecPattern_1 0%
System.Text.RegularExpressions.Generated.<RegexGenerator_g>FBF3D522B2772D8B2CEF77394DAF1D7F439F9F4D4A6B2ABFE407DB51869AB636C__ResolutionInFmtpPattern_2 0%
Heimdall.TestCommon 88.8%
Heimdall.TestCommon.PostgreSqlContainerFixture 88.8%
Heimdall.Web 22.6%
Heimdall.Api.Controllers.AgentsController 50%
Heimdall.Api.Controllers.AssignmentsController 62.2%
Heimdall.Api.Controllers.AuditLogsController 85.7%
Heimdall.Api.Controllers.AuthController 35.5%
Heimdall.Api.Controllers.CamerasController 39.3%
Heimdall.Api.Controllers.ControllerBaseExtensions 100%
Heimdall.Api.Controllers.DiscoveryController 55.7%
Heimdall.Api.Controllers.EventsController 45.9%
Heimdall.Api.Controllers.GroupsController 62.7%
Heimdall.Api.Controllers.HealthController 12.5%
Heimdall.Api.Controllers.PermissionInfo 100%
Heimdall.Api.Controllers.PermissionsController 97.8%
Heimdall.Api.Controllers.PermissionsListResponse 100%
Heimdall.Api.Controllers.PersonsController 63.8%
Heimdall.Api.Controllers.RoleResponse 100%
Heimdall.Api.Controllers.RolesController 100%
Heimdall.Api.Controllers.RolesListResponse 100%
Heimdall.Api.Controllers.SettingsController 96.1%
Heimdall.Api.Controllers.SitesController 48.7%
Heimdall.Api.Controllers.StatsController 84.6%
Heimdall.Api.Controllers.UsersController 29.4%
Heimdall.Api.Filters.ExceptionFilter 100%
Heimdall.Api.Hubs.ConfigBroadcastService 100%
Heimdall.Api.Hubs.ConfigHub 0%
Heimdall.Api.Hubs.EventBroadcastService 0%
Heimdall.Api.Hubs.EventsHub 100%
Heimdall.Web.Components.Layout.MainLayout 0%
Heimdall.Web.Components.Layout.MudBlazorLayout 0%
Heimdall.Web.Components.Pages.Admin.AllAgentsPage 0%
Heimdall.Web.Components.Pages.Admin.ClaimsPage 0%
Heimdall.Web.Components.Pages.Admin.GroupsPage 0%
Heimdall.Web.Components.Pages.Admin.RolesPage 0%
Heimdall.Web.Components.Pages.AgentDetail 0%
Heimdall.Web.Components.Pages.AgentsPage 0%
Heimdall.Web.Components.Pages.AuditLogsPage 0%
Heimdall.Web.Components.Pages.CameraDetail 0%
Heimdall.Web.Components.Pages.CamerasPage 0%
Heimdall.Web.Components.Pages.Dashboard 0%
Heimdall.Web.Components.Pages.Error 0%
Heimdall.Web.Components.Pages.EventsPage 0%
Heimdall.Web.Components.Pages.Login 0%
Heimdall.Web.Components.Pages.Profile 0%
Heimdall.Web.Components.Pages.RedirectToLogin 0%
Heimdall.Web.Components.Pages.Register 0%
Heimdall.Web.Components.Pages.SettingsPage 0%
Heimdall.Web.Components.Pages.SiteDetail 0%
Heimdall.Web.Components.Pages.SitesPage 0%
Heimdall.Web.Components.Pages.SnapshotsPage 0%
Heimdall.Web.Components.Pages.UsersPage 0%
Heimdall.Web.Components.Shared.EmptyState 0%
Heimdall.Web.Components.Shared.FilterBar 0%
Heimdall.Web.Components.Shared.LoadingSkeleton 0%
Heimdall.Web.Components.Shared.PaginationBar 0%
Heimdall.Web.Components.Shared.SectionCard 0%
Heimdall.Web.Components.Shared.StatusChip 0%
Heimdall.Web.Services.AgentItem 0%
Heimdall.Web.Services.AgentSettingItem 0%
Heimdall.Web.Services.AgentStatItem 0%
Heimdall.Web.Services.AppSettingItem 0%
Heimdall.Web.Services.AuditLogItem 100%
Heimdall.Web.Services.AuthHelper 0%
Heimdall.Web.Services.AuthResponse 100%
Heimdall.Web.Services.AuthState 60%
Heimdall.Web.Services.CameraItem 0%
Heimdall.Web.Services.CreateAppSettingRequest 0%
Heimdall.Web.Services.EventItem 0%
Heimdall.Web.Services.EventPageResult 0%
Heimdall.Web.Services.GroupItem 100%
Heimdall.Web.Services.HeimdallApiClient 26.7%
Heimdall.Web.Services.HeimdallAuthStateProvider 10.4%
Heimdall.Web.Services.PagedData<T> 100%
Heimdall.Web.Services.PasswordResetResult 0%
Heimdall.Web.Services.PermissionItem 100%
Heimdall.Web.Services.PermissionsListResponse 100%
Heimdall.Web.Services.RoleItem 100%
Heimdall.Web.Services.RolesListResponse 100%
Heimdall.Web.Services.SetAgentSettingRequest 0%
Heimdall.Web.Services.SiteItem 0%
Heimdall.Web.Services.SiteWithTokenResult 0%
Heimdall.Web.Services.StatsResult 100%
Heimdall.Web.Services.TokenRefreshHandler 35.5%
Heimdall.Web.Services.TokenResult 0%
Heimdall.Web.Services.UpdateAppSettingRequest 0%
Heimdall.Web.Services.UserInfo 100%
Heimdall.Web.Services.UserItem 100%
Microsoft.AspNetCore.OpenApi.Generated 1%
Program 75.3%
Sentry.Generated.BuildPropertyInitializer 100%
SignInRequest 0%
System.Runtime.CompilerServices 0%
+522
View File
@@ -0,0 +1,522 @@
Summary
Generated on: 07/23/2026 - 19:42:06
Coverage date: 07/23/2026 - 07:02:46 - 07/23/2026 - 19:41:53
Parser: MultiReport (49x Cobertura)
Assemblies: 7
Classes: 488
Files: 328
Line coverage: 64.3%
Covered lines: 11295
Uncovered lines: 6263
Coverable lines: 17558
Total lines: 27041
Branch coverage: 24.7% (836 of 3379)
Covered branches: 836
Total branches: 3379
Method coverage: 67.7% (1438 of 2122)
Full method coverage: 63.3% (1345 of 2122)
Covered methods: 1438
Fully covered methods: 1345
Total methods: 2122
Heimdall.Agent 58.7%
Heimdall.Agent.AgentOptions 85.7%
Heimdall.Agent.Services.AgentHealthCheck 100%
Heimdall.Agent.Services.AgentRegistrationService 86.1%
Heimdall.Agent.Services.AgentState 100%
Heimdall.Agent.Services.CameraStreamService 42.6%
Heimdall.Agent.Services.ConfigReceiverService 25%
Heimdall.Agent.Services.DetectionResult 100%
Heimdall.Agent.Services.FrameAnalysisResult 100%
Heimdall.Agent.Services.FrameAnalyzerService 42.1%
Heimdall.Agent.Services.HeartbeatRequest 100%
Heimdall.Agent.Services.RegisterRequest 100%
Heimdall.Agent.Services.RegisterResponse 100%
Heimdall.Agent.Services.RetryDelayed 100%
Heimdall.Agent.Services.SystemInfo 83.3%
Heimdall.Agent.Services.SystemMetrics 100%
Heimdall.Agent.Services.SystemMetricsProvider 73.6%
Program 0%
Sentry.Generated.BuildPropertyInitializer 100%
Heimdall.Application 87.8%
Heimdall.Application.Agents.Commands.Heartbeat.HeartbeatCommand 100%
Heimdall.Application.Agents.Commands.Heartbeat.HeartbeatHandler 100%
Heimdall.Application.Agents.Commands.RegisterAgent.RegisterAgentCommand 100%
Heimdall.Application.Agents.Commands.RegisterAgent.RegisterAgentHandler 100%
Heimdall.Application.Agents.Commands.RegisterAgent.RegisterAgentValidator 100%
Heimdall.Application.Agents.Mapping.AgentMappingProfile 100%
Heimdall.Application.Agents.Queries.GetAgent.GetAgentHandler 100%
Heimdall.Application.Agents.Queries.GetAgent.GetAgentQuery 100%
Heimdall.Application.Agents.Queries.GetAgentsBySite.GetAgentsBySiteHandler 100%
Heimdall.Application.Agents.Queries.GetAgentsBySite.GetAgentsBySiteQuery 100%
Heimdall.Application.Agents.Queries.GetAllAgents.GetAllAgentsHandler 100%
Heimdall.Application.Agents.Queries.GetAllAgents.GetAllAgentsQuery 100%
Heimdall.Application.Assignments.Commands.AssignCamera.AssignCameraCommand 100%
Heimdall.Application.Assignments.Commands.AssignCamera.AssignCameraHandler 100%
Heimdall.Application.Assignments.Commands.AssignSite.AssignSiteCommand 100%
Heimdall.Application.Assignments.Commands.AssignSite.AssignSiteHandler 100%
Heimdall.Application.Assignments.Commands.Failover.FailoverCommand 100%
Heimdall.Application.Assignments.Commands.Failover.FailoverHandler 100%
Heimdall.Application.Assignments.Commands.ReleaseCamera.ReleaseCameraCommand 100%
Heimdall.Application.Assignments.Commands.ReleaseCamera.ReleaseCameraHandler 100%
Heimdall.Application.Assignments.Mapping.AssignmentMappingProfile 100%
Heimdall.Application.Assignments.Queries.GetActiveAssignment.GetActiveAssignmentHandler 100%
Heimdall.Application.Assignments.Queries.GetActiveAssignment.GetActiveAssignmentQuery 100%
Heimdall.Application.Assignments.Queries.GetAgentAssignments.GetAgentAssignmentsHandler 100%
Heimdall.Application.Assignments.Queries.GetAgentAssignments.GetAgentAssignmentsQuery 100%
Heimdall.Application.Assignments.Queries.GetCameraHistory.GetCameraHistoryHandler 100%
Heimdall.Application.Assignments.Queries.GetCameraHistory.GetCameraHistoryQuery 100%
Heimdall.Application.Audit.Queries.GetAuditLogs.GetAuditLogsQuery 100%
Heimdall.Application.Audit.Queries.GetAuditLogs.GetAuditLogsQueryHandler 100%
Heimdall.Application.Auth.AuthHelper 100%
Heimdall.Application.Auth.Commands.ChangePassword.ChangePasswordCommand 100%
Heimdall.Application.Auth.Commands.ChangePassword.ChangePasswordHandler 100%
Heimdall.Application.Auth.Commands.ChangePassword.ChangePasswordValidator 0%
Heimdall.Application.Auth.Commands.Disable2fa.Disable2faCommand 0%
Heimdall.Application.Auth.Commands.Disable2fa.Disable2faHandler 0%
Heimdall.Application.Auth.Commands.Enable2fa.Enable2faCommand 0%
Heimdall.Application.Auth.Commands.Enable2fa.Enable2faHandler 0%
Heimdall.Application.Auth.Commands.Login.LoginCommand 100%
Heimdall.Application.Auth.Commands.Login.LoginHandler 87.5%
Heimdall.Application.Auth.Commands.Login.LoginValidator 100%
Heimdall.Application.Auth.Commands.Logout.LogoutCommand 0%
Heimdall.Application.Auth.Commands.Logout.LogoutHandler 0%
Heimdall.Application.Auth.Commands.RefreshToken.RefreshTokenCommand 100%
Heimdall.Application.Auth.Commands.RefreshToken.RefreshTokenHandler 92.6%
Heimdall.Application.Auth.Commands.Register.RegisterCommand 100%
Heimdall.Application.Auth.Commands.Register.RegisterHandler 87.6%
Heimdall.Application.Auth.Commands.Register.RegisterValidator 100%
Heimdall.Application.Auth.Commands.RegisterAdmin.RegisterAdminCommand 100%
Heimdall.Application.Auth.Commands.RegisterAdmin.RegisterAdminHandler 100%
Heimdall.Application.Auth.Commands.RegisterAdmin.RegisterAdminValidator 100%
Heimdall.Application.Auth.Commands.Verify2fa.Verify2faCommand 0%
Heimdall.Application.Auth.Commands.Verify2fa.Verify2faHandler 0%
Heimdall.Application.Auth.Commands.Verify2fa.Verify2faValidator 0%
Heimdall.Application.Auth.Mapping.AuthMappingProfile 100%
Heimdall.Application.Behaviors.LoggingBehavior<T1, T2> 100%
Heimdall.Application.Behaviors.ValidationBehavior<T1, T2> 92.8%
Heimdall.Application.Cameras.Commands.CreateCamera.CreateCameraCommand 100%
Heimdall.Application.Cameras.Commands.CreateCamera.CreateCameraCommandHandler 100%
Heimdall.Application.Cameras.Commands.CreateCamera.CreateCameraCommandValidator 100%
Heimdall.Application.Cameras.Commands.DeleteCamera.DeleteCameraCommand 100%
Heimdall.Application.Cameras.Commands.DeleteCamera.DeleteCameraCommandHandler 100%
Heimdall.Application.Cameras.Commands.SetCredentials.SetCameraCredentialsCommand 100%
Heimdall.Application.Cameras.Commands.SetCredentials.SetCameraCredentialsCommandHandler 100%
Heimdall.Application.Cameras.Commands.SetCredentials.SetCameraCredentialsCommandValidator 0%
Heimdall.Application.Cameras.Commands.UpdateCamera.UpdateCameraCommand 100%
Heimdall.Application.Cameras.Commands.UpdateCamera.UpdateCameraCommandHandler 100%
Heimdall.Application.Cameras.Commands.UpdateCamera.UpdateCameraCommandValidator 0%
Heimdall.Application.Cameras.Mapping.CameraMappingProfile 100%
Heimdall.Application.Cameras.Queries.GetCamera.GetCameraQuery 100%
Heimdall.Application.Cameras.Queries.GetCamera.GetCameraQueryHandler 100%
Heimdall.Application.Cameras.Queries.GetCamerasBySite.GetCamerasBySiteQuery 100%
Heimdall.Application.Cameras.Queries.GetCamerasBySite.GetCamerasBySiteQueryHandler 100%
Heimdall.Application.Common.Mappings.IMapFrom<T> 0%
Heimdall.Application.Common.Mappings.MappingProfile 44.4%
Heimdall.Application.Common.ServiceResult 100%
Heimdall.Application.Common.ServiceResult<T> 100%
Heimdall.Application.DependencyInjection 100%
Heimdall.Application.Discovery.Commands.BuildStreamUrls.BuildStreamUrlsCommand 100%
Heimdall.Application.Discovery.Commands.BuildStreamUrls.BuildStreamUrlsCommandHandler 100%
Heimdall.Application.Discovery.Commands.CancelTestSession.CancelTestSessionCommand 100%
Heimdall.Application.Discovery.Commands.CancelTestSession.CancelTestSessionCommandHandler 100%
Heimdall.Application.Discovery.Commands.ConfirmDiscovery.ConfirmDiscoveryCommand 100%
Heimdall.Application.Discovery.Commands.ConfirmDiscovery.ConfirmDiscoveryCommandHandler 100%
Heimdall.Application.Discovery.Commands.ProbeIp.ProbeIpCommand 100%
Heimdall.Application.Discovery.Commands.ProbeIp.ProbeIpCommandHandler 100%
Heimdall.Application.Discovery.Commands.ScanSubnet.ScanSubnetCommand 100%
Heimdall.Application.Discovery.Commands.ScanSubnet.ScanSubnetCommandHandler 100%
Heimdall.Application.Discovery.Commands.TestStreams.TestStreamsCommand 100%
Heimdall.Application.Discovery.Commands.TestStreams.TestStreamsCommandHandler 100%
Heimdall.Application.Discovery.Mapping.DiscoveryMappingProfile 100%
Heimdall.Application.Discovery.Queries.CheckDuplicate.CheckDuplicateQuery 100%
Heimdall.Application.Discovery.Queries.CheckDuplicate.CheckDuplicateQueryHandler 100%
Heimdall.Application.Discovery.Queries.GetScreenshot.GetScreenshotQuery 100%
Heimdall.Application.Discovery.Queries.GetScreenshot.GetScreenshotQueryHandler 100%
Heimdall.Application.Discovery.Queries.GetTestSession.GetTestSessionQuery 100%
Heimdall.Application.Discovery.Queries.GetTestSession.GetTestSessionQueryHandler 100%
Heimdall.Application.Discovery.Queries.SearchDatabase.SearchDatabaseQuery 100%
Heimdall.Application.Discovery.Queries.SearchDatabase.SearchDatabaseQueryHandler 100%
Heimdall.Application.DTOs.AgentHeartbeatRequest 100%
Heimdall.Application.DTOs.AgentResponse 42.8%
Heimdall.Application.DTOs.AgentSettingDto 100%
Heimdall.Application.DTOs.AgentStatItem 100%
Heimdall.Application.DTOs.ApiKeyResponse 0%
Heimdall.Application.DTOs.AppSettingDto 100%
Heimdall.Application.DTOs.ArpInfo 0%
Heimdall.Application.DTOs.AssignmentResponse 100%
Heimdall.Application.DTOs.AssignmentResult 0%
Heimdall.Application.DTOs.AssignRequest 100%
Heimdall.Application.DTOs.AssignRolesRequest 0%
Heimdall.Application.DTOs.AssignSitesRequest 0%
Heimdall.Application.DTOs.AttachSnapshotRequest 0%
Heimdall.Application.DTOs.AuditLogResponse 0%
Heimdall.Application.DTOs.AuthResponse 100%
Heimdall.Application.DTOs.CameraCheckResponse 100%
Heimdall.Application.DTOs.CameraDbEntry 100%
Heimdall.Application.DTOs.CameraDetectionProfileRequest 0%
Heimdall.Application.DTOs.CameraEventFilterRequest 100%
Heimdall.Application.DTOs.CameraEventResponse 69.2%
Heimdall.Application.DTOs.CameraResponse 100%
Heimdall.Application.DTOs.ChangePasswordRequest 0%
Heimdall.Application.DTOs.CheckDuplicateRequest 100%
Heimdall.Application.DTOs.ConfirmDiscoveryRequest 20%
Heimdall.Application.DTOs.CreateApiKeyResponse 0%
Heimdall.Application.DTOs.CreateAppSettingRequest 100%
Heimdall.Application.DTOs.CreateCameraEventRequest 100%
Heimdall.Application.DTOs.CreateCameraRequest 100%
Heimdall.Application.DTOs.CreateGroupRequest 100%
Heimdall.Application.DTOs.CreatePersonRequest 100%
Heimdall.Application.DTOs.CreateSiteRequest 100%
Heimdall.Application.DTOs.CreateUserRequest 100%
Heimdall.Application.DTOs.FailoverResult 0%
Heimdall.Application.DTOs.GroupMemberResponse 50%
Heimdall.Application.DTOs.GroupResponse 100%
Heimdall.Application.DTOs.HomeKitProbeInfo 0%
Heimdall.Application.DTOs.HttpProbeInfo 0%
Heimdall.Application.DTOs.KnownFaceResponse 100%
Heimdall.Application.DTOs.LoginRequest 100%
Heimdall.Application.DTOs.LogoutRequest 0%
Heimdall.Application.DTOs.OnvifProbeInfo 0%
Heimdall.Application.DTOs.PagedResult<T> 100%
Heimdall.Application.DTOs.PersonResponse 100%
Heimdall.Application.DTOs.ProbeRequest 100%
Heimdall.Application.DTOs.ProbeResponse 36.3%
Heimdall.Application.DTOs.RefreshTokenRequest 0%
Heimdall.Application.DTOs.RegisterAgentRequest 100%
Heimdall.Application.DTOs.RegisterAgentResponse 100%
Heimdall.Application.DTOs.RegisterFaceRequest 0%
Heimdall.Application.DTOs.RegisterRequest 100%
Heimdall.Application.DTOs.RegistrationTokenResponse 100%
Heimdall.Application.DTOs.ResetPasswordResponse 100%
Heimdall.Application.DTOs.ScanProgress 0%
Heimdall.Application.DTOs.ScanRequest 100%
Heimdall.Application.DTOs.SearchResponse 100%
Heimdall.Application.DTOs.SetAgentSettingRequest 100%
Heimdall.Application.DTOs.SiteResponse 100%
Heimdall.Application.DTOs.SiteWithTokenResponse 0%
Heimdall.Application.DTOs.StatsResponse 100%
Heimdall.Application.DTOs.StreamBuildRequest 100%
Heimdall.Application.DTOs.StreamBuildResponse 100%
Heimdall.Application.DTOs.StreamTestRequest 100%
Heimdall.Application.DTOs.StreamTestResult 25%
Heimdall.Application.DTOs.StreamTestSession 100%
Heimdall.Application.DTOs.UpdateAppSettingRequest 100%
Heimdall.Application.DTOs.UpdateCameraRequest 66.6%
Heimdall.Application.DTOs.UpdateGroupRequest 100%
Heimdall.Application.DTOs.UpdatePersonRequest 100%
Heimdall.Application.DTOs.UpdateSiteRequest 100%
Heimdall.Application.DTOs.UpdateUserRequest 100%
Heimdall.Application.DTOs.UserInfo 100%
Heimdall.Application.DTOs.UserResponse 100%
Heimdall.Application.DTOs.Verify2faRequest 0%
Heimdall.Application.Events.Commands.AttachSnapshot.AttachSnapshotCommand 100%
Heimdall.Application.Events.Commands.AttachSnapshot.AttachSnapshotHandler 100%
Heimdall.Application.Events.Commands.CreateEvent.CreateEventCommand 100%
Heimdall.Application.Events.Commands.CreateEvent.CreateEventHandler 95.4%
Heimdall.Application.Events.Commands.DeleteEvent.DeleteEventCommand 100%
Heimdall.Application.Events.Commands.DeleteEvent.DeleteEventHandler 100%
Heimdall.Application.Events.Mapping.EventMappingProfile 100%
Heimdall.Application.Events.Notifications.EventCreatedNotification 100%
Heimdall.Application.Events.Notifications.EventCreatedNotificationHandler 0%
Heimdall.Application.Events.Queries.GetEvent.GetEventHandler 100%
Heimdall.Application.Events.Queries.GetEvent.GetEventQuery 100%
Heimdall.Application.Events.Queries.GetEvents.GetEventsHandler 83.8%
Heimdall.Application.Events.Queries.GetEvents.GetEventsQuery 100%
Heimdall.Application.Events.Queries.GetRecentByCamera.GetRecentByCameraHandler 100%
Heimdall.Application.Events.Queries.GetRecentByCamera.GetRecentByCameraQuery 100%
Heimdall.Application.Groups.Commands.AddUserToGroup.AddUserToGroupCommand 100%
Heimdall.Application.Groups.Commands.AddUserToGroup.AddUserToGroupCommandHandler 100%
Heimdall.Application.Groups.Commands.CreateGroup.CreateGroupCommand 100%
Heimdall.Application.Groups.Commands.CreateGroup.CreateGroupCommandHandler 100%
Heimdall.Application.Groups.Commands.DeleteGroup.DeleteGroupCommand 100%
Heimdall.Application.Groups.Commands.DeleteGroup.DeleteGroupCommandHandler 100%
Heimdall.Application.Groups.Commands.RemoveUserFromGroup.RemoveUserFromGroupCommand 100%
Heimdall.Application.Groups.Commands.RemoveUserFromGroup.RemoveUserFromGroupCommandHandler 100%
Heimdall.Application.Groups.Commands.UpdateGroup.UpdateGroupCommand 100%
Heimdall.Application.Groups.Commands.UpdateGroup.UpdateGroupCommandHandler 100%
Heimdall.Application.Groups.Mapping.GroupMappingProfile 100%
Heimdall.Application.Groups.Queries.GetGroup.GetGroupQuery 100%
Heimdall.Application.Groups.Queries.GetGroup.GetGroupQueryHandler 100%
Heimdall.Application.Groups.Queries.GetGroupMembers.GetGroupMembersQuery 100%
Heimdall.Application.Groups.Queries.GetGroupMembers.GetGroupMembersQueryHandler 100%
Heimdall.Application.Groups.Queries.GetGroups.GetGroupsQuery 100%
Heimdall.Application.Groups.Queries.GetGroups.GetGroupsQueryHandler 100%
Heimdall.Application.Persons.Commands.CreatePerson.CreatePersonCommand 100%
Heimdall.Application.Persons.Commands.CreatePerson.CreatePersonCommandHandler 100%
Heimdall.Application.Persons.Commands.DeleteFace.DeleteFaceCommand 100%
Heimdall.Application.Persons.Commands.DeleteFace.DeleteFaceCommandHandler 100%
Heimdall.Application.Persons.Commands.DeletePerson.DeletePersonCommand 100%
Heimdall.Application.Persons.Commands.DeletePerson.DeletePersonCommandHandler 100%
Heimdall.Application.Persons.Commands.RegisterFace.RegisterFaceCommand 100%
Heimdall.Application.Persons.Commands.RegisterFace.RegisterFaceCommandHandler 100%
Heimdall.Application.Persons.Commands.UpdatePerson.UpdatePersonCommand 100%
Heimdall.Application.Persons.Commands.UpdatePerson.UpdatePersonCommandHandler 100%
Heimdall.Application.Persons.Mapping.PersonMappingProfile 100%
Heimdall.Application.Persons.Queries.GetFaces.GetFacesQuery 100%
Heimdall.Application.Persons.Queries.GetFaces.GetFacesQueryHandler 100%
Heimdall.Application.Persons.Queries.GetPerson.GetPersonQuery 100%
Heimdall.Application.Persons.Queries.GetPerson.GetPersonQueryHandler 100%
Heimdall.Application.Persons.Queries.GetPersons.GetPersonsQuery 100%
Heimdall.Application.Persons.Queries.GetPersons.GetPersonsQueryHandler 100%
Heimdall.Application.Services.SignInServiceResult 100%
Heimdall.Application.Settings.Commands.CreateAppSetting.CreateAppSettingCommand 100%
Heimdall.Application.Settings.Commands.CreateAppSetting.CreateAppSettingCommandHandler 100%
Heimdall.Application.Settings.Commands.DeleteAppSetting.DeleteAppSettingCommand 100%
Heimdall.Application.Settings.Commands.DeleteAppSetting.DeleteAppSettingCommandHandler 100%
Heimdall.Application.Settings.Commands.RemoveAgentSetting.RemoveAgentSettingCommand 100%
Heimdall.Application.Settings.Commands.RemoveAgentSetting.RemoveAgentSettingCommandHandler 100%
Heimdall.Application.Settings.Commands.SetAgentSetting.SetAgentSettingCommand 100%
Heimdall.Application.Settings.Commands.SetAgentSetting.SetAgentSettingCommandHandler 100%
Heimdall.Application.Settings.Commands.UpdateAppSetting.UpdateAppSettingCommand 100%
Heimdall.Application.Settings.Commands.UpdateAppSetting.UpdateAppSettingCommandHandler 100%
Heimdall.Application.Settings.Mapping.SettingMappingProfile 100%
Heimdall.Application.Settings.Queries.GetAgentSettings.GetAgentSettingsQuery 100%
Heimdall.Application.Settings.Queries.GetAgentSettings.GetAgentSettingsQueryHandler 100%
Heimdall.Application.Settings.Queries.GetEffectiveAgentConfig.GetEffectiveAgentConfigQuery 100%
Heimdall.Application.Settings.Queries.GetEffectiveAgentConfig.GetEffectiveAgentConfigQueryHandler 100%
Heimdall.Application.Settings.Queries.GetSettingByKey.GetSettingByKeyQuery 100%
Heimdall.Application.Settings.Queries.GetSettingByKey.GetSettingByKeyQueryHandler 100%
Heimdall.Application.Settings.Queries.GetSettings.GetSettingsQueryHandler 100%
Heimdall.Application.Sites.Commands.CreateSite.CreateSiteCommand 100%
Heimdall.Application.Sites.Commands.CreateSite.CreateSiteHandler 100%
Heimdall.Application.Sites.Commands.CreateSite.CreateSiteValidator 78.9%
Heimdall.Application.Sites.Commands.DeleteSite.DeleteSiteCommand 100%
Heimdall.Application.Sites.Commands.DeleteSite.DeleteSiteHandler 100%
Heimdall.Application.Sites.Commands.GenerateSiteToken.GenerateSiteTokenCommand 100%
Heimdall.Application.Sites.Commands.GenerateSiteToken.GenerateSiteTokenHandler 94.7%
Heimdall.Application.Sites.Commands.UpdateSite.UpdateSiteCommand 100%
Heimdall.Application.Sites.Commands.UpdateSite.UpdateSiteHandler 100%
Heimdall.Application.Sites.Mapping.SiteMappingProfile 100%
Heimdall.Application.Sites.Queries.GetSite.GetSiteHandler 100%
Heimdall.Application.Sites.Queries.GetSite.GetSiteQuery 100%
Heimdall.Application.Sites.Queries.GetSites.GetSitesHandler 100%
Heimdall.Application.Sites.Queries.GetSites.GetSitesQuery 100%
Heimdall.Application.Stats.Queries.GetAgentStats.GetAgentStatsQueryHandler 91.6%
Heimdall.Application.Stats.Queries.GetStats.GetStatsQueryHandler 100%
Heimdall.Application.Users.Commands.AssignRoles.AssignRolesCommand 100%
Heimdall.Application.Users.Commands.AssignRoles.AssignRolesHandler 96.4%
Heimdall.Application.Users.Commands.AssignSites.AssignSitesCommand 100%
Heimdall.Application.Users.Commands.AssignSites.AssignSitesHandler 100%
Heimdall.Application.Users.Commands.CreateUser.CreateUserCommand 100%
Heimdall.Application.Users.Commands.CreateUser.CreateUserHandler 88.4%
Heimdall.Application.Users.Commands.DeleteUser.DeleteUserCommand 100%
Heimdall.Application.Users.Commands.DeleteUser.DeleteUserHandler 96.4%
Heimdall.Application.Users.Commands.LockUser.LockUserCommand 100%
Heimdall.Application.Users.Commands.LockUser.LockUserHandler 92.8%
Heimdall.Application.Users.Commands.ResetPassword.ResetPasswordCommand 100%
Heimdall.Application.Users.Commands.ResetPassword.ResetPasswordHandler 91.1%
Heimdall.Application.Users.Commands.UnlockUser.UnlockUserCommand 100%
Heimdall.Application.Users.Commands.UnlockUser.UnlockUserHandler 100%
Heimdall.Application.Users.Commands.UpdateUser.UpdateUserCommand 100%
Heimdall.Application.Users.Commands.UpdateUser.UpdateUserHandler 100%
Heimdall.Application.Users.Mapping.UserMappingProfile 100%
Heimdall.Application.Users.Queries.GetMe.GetMeHandler 100%
Heimdall.Application.Users.Queries.GetMe.GetMeQuery 100%
Heimdall.Application.Users.Queries.GetUser.GetUserHandler 100%
Heimdall.Application.Users.Queries.GetUser.GetUserQuery 100%
Heimdall.Application.Users.Queries.GetUsers.GetUsersHandler 100%
Heimdall.Application.Users.Queries.GetUsers.GetUsersQuery 100%
Heimdall.Application.Validators.CreateAppSettingValidator 100%
Heimdall.Application.Validators.CreateCameraValidator 100%
Heimdall.Application.Validators.CreateSiteValidator 78.9%
Heimdall.Application.Validators.CreateUserValidator 100%
Heimdall.Application.Validators.LoginRequestValidator 100%
Heimdall.Application.Validators.RegisterAgentValidator 100%
Heimdall.Application.Validators.RegisterRequestValidator 100%
Heimdall.Application.Validators.SetAgentSettingValidator 100%
Heimdall.Application.Validators.UpdateAppSettingValidator 100%
Heimdall.Application.Validators.UpdateCameraValidator 100%
Heimdall.Application.Validators.UpdateSiteValidator 100%
Heimdall.Application.Validators.UpdateUserValidator 100%
Heimdall.Domain 96.3%
Heimdall.Domain.Entities.Agent 100%
Heimdall.Domain.Entities.AgentSetting 100%
Heimdall.Domain.Entities.ApiKey 95.2%
Heimdall.Domain.Entities.AppRole 100%
Heimdall.Domain.Entities.AppSetting 100%
Heimdall.Domain.Entities.AppUser 77.7%
Heimdall.Domain.Entities.AuditLog 92.8%
Heimdall.Domain.Entities.Camera 98.8%
Heimdall.Domain.Entities.CameraAssignment 100%
Heimdall.Domain.Entities.CameraCredentials 95%
Heimdall.Domain.Entities.CameraDetectionProfile 88.4%
Heimdall.Domain.Entities.CameraDiscoveryResult 96.5%
Heimdall.Domain.Entities.CameraEvent 100%
Heimdall.Domain.Entities.DiscoveredStreamUrl 97%
Heimdall.Domain.Entities.Group 96.2%
Heimdall.Domain.Entities.KnownFace 92.3%
Heimdall.Domain.Entities.Person 100%
Heimdall.Domain.Entities.RevokedRefreshToken 91.6%
Heimdall.Domain.Entities.Site 92.3%
Heimdall.Domain.Entities.UserGroup 90%
Heimdall.Domain.Entities.UserSite 90%
Heimdall.Domain.Primitives 73.9%
Heimdall.Domain.Primitives.Entity<T> 100%
Heimdall.Domain.Primitives.ValueObject 60%
Heimdall.Infrastructure 76.2%
Heimdall.Infrastructure.BackgroundJobs.DependencyInjection 0%
Heimdall.Infrastructure.BackgroundJobs.JobSetup 0%
Heimdall.Infrastructure.Data.AppDbContext 90.3%
Heimdall.Infrastructure.Data.AppDbContextFactory 0%
Heimdall.Infrastructure.Data.Configurations.AgentConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.AgentSettingConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.ApiKeyConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.AppRoleConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.AppSettingConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.AppUserConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.AuditLogConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.CameraAssignmentConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.CameraConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.CameraCredentialsConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.CameraDetectionProfileConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.CameraDiscoveryResultConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.CameraEventConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.DiscoveredStreamConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.GroupEntityTypeConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.IdentityRoleClaimConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.IdentityUserClaimConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.IdentityUserLoginConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.IdentityUserRoleConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.IdentityUserTokenConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.KnownFaceConfiguration 80%
Heimdall.Infrastructure.Data.Configurations.PersonConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.RevokedRefreshTokenConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.SiteConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.UserGroupConfiguration 100%
Heimdall.Infrastructure.Data.Configurations.UserSiteConfiguration 100%
Heimdall.Infrastructure.Data.DbContextExtensions 66.6%
Heimdall.Infrastructure.Data.Interceptors.AuditInterceptor 94.1%
Heimdall.Infrastructure.DependencyInjection 62.5%
Heimdall.Infrastructure.Jobs.AgentFailoverJob 89.3%
Heimdall.Infrastructure.Jobs.HeartbeatMonitorJob 100%
Heimdall.Infrastructure.Migrations.AddRevokedRefreshTokens 99.7%
Heimdall.Infrastructure.Migrations.AppDbContextModelSnapshot 100%
Heimdall.Infrastructure.Migrations.InitialCreate 97.7%
Heimdall.Infrastructure.Persistence.UserRepository 76.5%
Heimdall.Infrastructure.Security.ApiKeyAuthenticationHandler 95.7%
Heimdall.Infrastructure.Security.AppPermissions 100%
Heimdall.Infrastructure.Security.AppRoles 100%
Heimdall.Infrastructure.Security.AuthDataService 100%
Heimdall.Infrastructure.Security.AuthSignInService 100%
Heimdall.Infrastructure.Security.DataProtectorCredentialProtector 100%
Heimdall.Infrastructure.Security.JwtService 100%
Heimdall.Infrastructure.Security.RolePermissionService 100%
Heimdall.Infrastructure.Services.CameraAssignmentService 45.8%
Heimdall.Infrastructure.Services.CameraEventService 91.1%
Heimdall.Infrastructure.Services.Discovery.ArpEntry 0%
Heimdall.Infrastructure.Services.Discovery.ArpProbeService 72.7%
Heimdall.Infrastructure.Services.Discovery.CameraDiscoveryService 48.6%
Heimdall.Infrastructure.Services.Discovery.DiscoveryCoordinatorService 0%
Heimdall.Infrastructure.Services.Discovery.HomeKitDeviceInfo 0%
Heimdall.Infrastructure.Services.Discovery.HttpProbeData 0%
Heimdall.Infrastructure.Services.Discovery.HttpProbeService 68.5%
Heimdall.Infrastructure.Services.Discovery.MdnsProbeService 2.1%
Heimdall.Infrastructure.Services.Discovery.OnvifDeviceInfo 0%
Heimdall.Infrastructure.Services.Discovery.OnvifProbeService 3.9%
Heimdall.Infrastructure.Services.Discovery.PortScanService 77.7%
Heimdall.Infrastructure.Services.Discovery.StreamTesterService 63.1%
Heimdall.Infrastructure.Services.PersonService 64%
System.Text.RegularExpressions.Generated 2.1%
System.Text.RegularExpressions.Generated.<RegexGenerator_g>FBF3D522B2772D8B2CEF77394DAF1D7F439F9F4D4A6B2ABFE407DB51869AB636C__ArpPattern_0 4.9%
System.Text.RegularExpressions.Generated.<RegexGenerator_g>FBF3D522B2772D8B2CEF77394DAF1D7F439F9F4D4A6B2ABFE407DB51869AB636C__CodecPattern_1 0%
System.Text.RegularExpressions.Generated.<RegexGenerator_g>FBF3D522B2772D8B2CEF77394DAF1D7F439F9F4D4A6B2ABFE407DB51869AB636C__ResolutionInFmtpPattern_2 0%
Heimdall.TestCommon 88.8%
Heimdall.TestCommon.PostgreSqlContainerFixture 88.8%
Heimdall.Web 23.3%
Heimdall.Api.Controllers.AgentsController 50%
Heimdall.Api.Controllers.AssignmentsController 62.2%
Heimdall.Api.Controllers.AuditLogsController 85.7%
Heimdall.Api.Controllers.AuthController 35.5%
Heimdall.Api.Controllers.CamerasController 39.3%
Heimdall.Api.Controllers.ControllerBaseExtensions 100%
Heimdall.Api.Controllers.DiscoveryController 55.7%
Heimdall.Api.Controllers.EventsController 45.9%
Heimdall.Api.Controllers.GroupsController 62.7%
Heimdall.Api.Controllers.HealthController 12.5%
Heimdall.Api.Controllers.PermissionInfo 100%
Heimdall.Api.Controllers.PermissionsController 97.8%
Heimdall.Api.Controllers.PermissionsListResponse 100%
Heimdall.Api.Controllers.PersonsController 63.8%
Heimdall.Api.Controllers.RoleResponse 100%
Heimdall.Api.Controllers.RolesController 100%
Heimdall.Api.Controllers.RolesListResponse 100%
Heimdall.Api.Controllers.SettingsController 96.1%
Heimdall.Api.Controllers.SitesController 48.7%
Heimdall.Api.Controllers.StatsController 84.6%
Heimdall.Api.Controllers.UsersController 29.4%
Heimdall.Api.Filters.ExceptionFilter 100%
Heimdall.Api.Hubs.ConfigBroadcastService 100%
Heimdall.Api.Hubs.ConfigHub 0%
Heimdall.Api.Hubs.EventBroadcastService 0%
Heimdall.Api.Hubs.EventsHub 100%
Heimdall.Web.Components.Layout.MainLayout 0%
Heimdall.Web.Components.Layout.MudBlazorLayout 0%
Heimdall.Web.Components.Pages.Admin.AllAgentsPage 0%
Heimdall.Web.Components.Pages.Admin.ClaimsPage 0%
Heimdall.Web.Components.Pages.Admin.GroupsPage 0%
Heimdall.Web.Components.Pages.Admin.RolesPage 0%
Heimdall.Web.Components.Pages.AgentDetail 0%
Heimdall.Web.Components.Pages.AgentsPage 0%
Heimdall.Web.Components.Pages.AuditLogsPage 0%
Heimdall.Web.Components.Pages.CameraDetail 0%
Heimdall.Web.Components.Pages.CamerasPage 0%
Heimdall.Web.Components.Pages.Dashboard 0%
Heimdall.Web.Components.Pages.Error 0%
Heimdall.Web.Components.Pages.EventsPage 0%
Heimdall.Web.Components.Pages.Login 0%
Heimdall.Web.Components.Pages.Profile 0%
Heimdall.Web.Components.Pages.RedirectToLogin 0%
Heimdall.Web.Components.Pages.Register 0%
Heimdall.Web.Components.Pages.SettingsPage 0%
Heimdall.Web.Components.Pages.SiteDetail 0%
Heimdall.Web.Components.Pages.SitesPage 0%
Heimdall.Web.Components.Pages.SnapshotsPage 0%
Heimdall.Web.Components.Pages.UsersPage 0%
Heimdall.Web.Components.Shared.EmptyState 72.7%
Heimdall.Web.Components.Shared.FilterBar 0%
Heimdall.Web.Components.Shared.LoadingSkeleton 100%
Heimdall.Web.Components.Shared.PaginationBar 55.5%
Heimdall.Web.Components.Shared.SectionCard 45%
Heimdall.Web.Components.Shared.StatusChip 0%
Heimdall.Web.Services.AgentItem 0%
Heimdall.Web.Services.AgentSettingItem 0%
Heimdall.Web.Services.AgentStatItem 0%
Heimdall.Web.Services.AppSettingItem 0%
Heimdall.Web.Services.AuditLogItem 100%
Heimdall.Web.Services.AuthHelper 0%
Heimdall.Web.Services.AuthResponse 100%
Heimdall.Web.Services.AuthState 60%
Heimdall.Web.Services.CameraItem 0%
Heimdall.Web.Services.CreateAppSettingRequest 0%
Heimdall.Web.Services.EventItem 0%
Heimdall.Web.Services.EventPageResult 0%
Heimdall.Web.Services.GroupItem 100%
Heimdall.Web.Services.HeimdallApiClient 26.7%
Heimdall.Web.Services.HeimdallAuthStateProvider 10.4%
Heimdall.Web.Services.PagedData<T> 100%
Heimdall.Web.Services.PasswordResetResult 0%
Heimdall.Web.Services.PermissionItem 100%
Heimdall.Web.Services.PermissionsListResponse 100%
Heimdall.Web.Services.RoleItem 100%
Heimdall.Web.Services.RolesListResponse 100%
Heimdall.Web.Services.SetAgentSettingRequest 0%
Heimdall.Web.Services.SiteItem 0%
Heimdall.Web.Services.SiteWithTokenResult 0%
Heimdall.Web.Services.StatsResult 100%
Heimdall.Web.Services.TokenRefreshHandler 35.5%
Heimdall.Web.Services.TokenResult 0%
Heimdall.Web.Services.UpdateAppSettingRequest 0%
Heimdall.Web.Services.UserInfo 100%
Heimdall.Web.Services.UserItem 100%
Microsoft.AspNetCore.OpenApi.Generated 1%
Program 75.3%
Sentry.Generated.BuildPropertyInitializer 100%
SignInRequest 0%
System.Runtime.CompilerServices 0%
@@ -0,0 +1,130 @@
# SignalR Hubs + Notifications Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task.
**Goal:** Complete the 3 missing SignalR hubs (Monitoring, Notifications, Admin) and implement the full notification system (in-app, email, gotify, digests)
**Architecture:** Follow existing CQRS/MediatR pattern. New entities in Domain, new CQRS handlers in Application, EF configs + services in Infrastructure, hubs in Web. SignalR broadcast services bridge Application events to connected clients.
**Tech Stack:** .NET 10, SignalR, Hangfire, Scriban (templates), MailKit/SmtpClient, Gotify HTTP API, IMemoryCache (rate limiter)
## Global Constraints
- Follow existing Clean Architecture patterns (Entity → CQRS → Controller → Hub)
- Use `ServiceResult<T>` for all handler return types
- Use `IApplicationDbContext` for data access in handlers
- Follow existing naming: `Commands/{Name}/{Name}Command.cs`, `Queries/{Name}/{Name}Query.cs`
- All async methods must have `CancellationToken ct = default`
- All SignalR hubs use `[Authorize]` with appropriate schemes
- All DTOs are `record` types with JsonPropertyName attributes
- Match existing test patterns: xUnit + Shouldly + NSubstitute
---
### Task 1: Domain Entities (Notification, NotificationTemplate, UserNotificationConfig)
**Files:**
- Create: `src/Heimdall.Domain/Entities/Notification.cs`
- Create: `src/Heimdall.Domain/Entities/NotificationTemplate.cs`
- Create: `src/Heimdall.Domain/Entities/UserNotificationConfig.cs`
- Create: `src/Heimdall.Domain/Enums/NotificationChannel.cs`
- Create: `src/Heimdall.Domain/Enums/NotificationType.cs`
- Test: `tests/Heimdall.Domain.Tests/Entities/NotificationTests.cs`
- Test: `tests/Heimdall.Domain.Tests/Entities/NotificationTemplateTests.cs`
- Test: `tests/Heimdall.Domain.Tests/Entities/UserNotificationConfigTests.cs`
**Interfaces:**
- Produces: `Notification`, `NotificationTemplate`, `UserNotificationConfig`, `NotificationChannel` enum, `NotificationType` enum
### Task 2: Application Layer - DTOs, Interfaces, CQRS
**Files:**
- Create: `src/Heimdall.Application/DTOs/NotificationDto.cs`
- Create: `src/Heimdall.Application/Services/INotificationService.cs`
- Create: `src/Heimdall.Application/Services/INotificationBroadcastService.cs`
- Create: `src/Heimdall.Application/Services/IEmailService.cs`
- Create: `src/Heimdall.Application/Services/IGotifyService.cs`
- Create: `src/Heimdall.Application/Services/INotificationRateLimiter.cs`
- Create: `src/Heimdall.Application/Notifications/Commands/MarkAsRead/MarkAsReadCommand.cs`
- Create: `src/Heimdall.Application/Notifications/Commands/MarkAsRead/MarkAsReadHandler.cs`
- Create: `src/Heimdall.Application/Notifications/Commands/MarkAllAsRead/MarkAllAsReadCommand.cs`
- Create: `src/Heimdall.Application/Notifications/Commands/MarkAllAsRead/MarkAllAsReadHandler.cs`
- Create: `src/Heimdall.Application/Notifications/Commands/UpdateConfig/UpdateNotificationConfigCommand.cs`
- Create: `src/Heimdall.Application/Notifications/Commands/UpdateConfig/UpdateNotificationConfigHandler.cs`
- Create: `src/Heimdall.Application/Notifications/Queries/GetNotifications/GetNotificationsQuery.cs`
- Create: `src/Heimdall.Application/Notifications/Queries/GetNotifications/GetNotificationsHandler.cs`
- Create: `src/Heimdall.Application/Notifications/Queries/GetUnreadCount/GetUnreadCountQuery.cs`
- Create: `src/Heimdall.Application/Notifications/Queries/GetUnreadCount/GetUnreadCountHandler.cs`
- Create: `src/Heimdall.Application/Notifications/Mapping/NotificationMappingProfile.cs`
### Task 3: Infrastructure - EF Configs + Migration + Services
**Files:**
- Create: `src/Heimdall.Infrastructure/Data/Configurations/NotificationConfiguration.cs`
- Create: `src/Heimdall.Infrastructure/Data/Configurations/NotificationTemplateConfiguration.cs`
- Create: `src/Heimdall.Infrastructure/Data/Configurations/UserNotificationConfigConfiguration.cs`
- Create: `src/Heimdall.Infrastructure/Services/EmailService.cs`
- Create: `src/Heimdall.Infrastructure/Services/GotifyService.cs`
- Create: `src/Heimdall.Infrastructure/Services/NotificationRateLimiter.cs`
- Create: `src/Heimdall.Infrastructure/Services/NotificationService.cs`
- Modify: `src/Heimdall.Infrastructure/Data/AppDbContext.cs` (add DbSets)
- Modify: `src/Heimdall.Infrastructure/DependencyInjection.cs` (register services)
### Task 4: SignalR Hubs (MonitoringHub, NotificationsHub, AdminHub)
**Files:**
- Create: `src/Heimdall.Web/Hubs/MonitoringHub.cs`
- Create: `src/Heimdall.Web/Hubs/NotificationsHub.cs`
- Create: `src/Heimdall.Web/Hubs/AdminHub.cs`
- Modify: `src/Heimdall.Web/Program.cs` (map new hubs)
### Task 5: NotificationsController API
**Files:**
- Create: `src/Heimdall.Web/Controllers/NotificationsController.cs`
### Task 6: Hangfire Notification Jobs
**Files:**
- Create: `src/Heimdall.Infrastructure/Jobs/SendNotificationJob.cs`
- Create: `src/Heimdall.Infrastructure/Jobs/DailyDigestJob.cs`
- Create: `src/Heimdall.Infrastructure/Jobs/WeeklyDigestJob.cs`
- Modify: `src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs` (register jobs)
- Modify: `src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs` (register jobs + queues)
### Task 7: Blazor UI - Notifications
**Files:**
- Create: `src/Heimdall.Web/Components/Pages/NotificationsPage.razor`
- Create: `src/Heimdall.Web/Components/Shared/NotificationBadge.razor`
- Modify: `src/Heimdall.Web/Services/HeimdallApiClient.cs` (add notification methods)
- Modify: `src/Heimdall.Web/Components/Layout/MainLayout.razor` (add badge)
- Modify: `src/Heimdall.Web/Components/Routes.razor` (add route)
- Modify: `src/Heimdall.Web/Components/Layout/NavMenu.razor` (add nav link)
### Task 8: Database Migration
**Files:**
- Run: `dotnet ef migrations add AddNotifications`
- Verify: Migration + .Designer.cs exist
### Task 9: Build + Test + Fix
- Run: `dotnet build` → 0 errors
- Run: `dotnet test` → all green
- Fix any issues
### Task 10: Tests Maximum Coverage
**Test files:**
- Create: `tests/Heimdall.Domain.Tests/Entities/NotificationTests.cs`
- Create: `tests/Heimdall.Domain.Tests/Entities/NotificationTemplateTests.cs`
- Create: `tests/Heimdall.Domain.Tests/Entities/UserNotificationConfigTests.cs`
- Create: `tests/Heimdall.Application.Tests/Notifications/Handlers/NotificationHandlerTests.cs`
- Create: `tests/Heimdall.Infrastructure.Tests/Services/NotificationServiceTests.cs`
- Create: `tests/Heimdall.Infrastructure.Tests/Services/NotificationRateLimiterTests.cs`
- Create: `tests/Heimdall.Infrastructure.Tests/Services/EmailServiceTests.cs`
- Create: `tests/Heimdall.Infrastructure.Tests/Services/GotifyServiceTests.cs`
- Create: `tests/Heimdall.Api.Tests/Controllers/NotificationsControllerTests.cs`
- Create: `tests/Heimdall.IntegrationTests/Scenarios/NotificationScenarios.cs`
- Create: `tests/Heimdall.IntegrationTests/Scenarios/SignalRHubScenarios.cs`
@@ -18,6 +18,11 @@ public interface IApplicationDbContext
DbSet<CameraDiscoveryResult> CameraDiscoveryResults { get; }
DbSet<CameraEvent> CameraEvents { get; }
DbSet<DiscoveredStreamUrl> DiscoveredStreams { get; }
// Notification entities
DbSet<Notification> Notifications { get; }
DbSet<NotificationTemplate> NotificationTemplates { get; }
DbSet<UserNotificationConfig> UserNotificationConfigs { get; }
DbSet<Group> Groups { get; }
DbSet<KnownFace> KnownFaces { get; }
DbSet<Person> Persons { get; }
@@ -0,0 +1,63 @@
using System.Text.Json.Serialization;
using Heimdall.Domain.Enums;
namespace Heimdall.Application.DTOs;
public sealed record NotificationDto(
[property: JsonPropertyName("id")] Guid Id,
[property: JsonPropertyName("userId")] Guid UserId,
[property: JsonPropertyName("title")] string Title,
[property: JsonPropertyName("message")] string Message,
[property: JsonPropertyName("type")] string Type,
[property: JsonPropertyName("eventType")] string? EventType,
[property: JsonPropertyName("cameraId")] Guid? CameraId,
[property: JsonPropertyName("siteId")] Guid? SiteId,
[property: JsonPropertyName("snapshotUrl")] string? SnapshotUrl,
[property: JsonPropertyName("link")] string? Link,
[property: JsonPropertyName("isRead")] bool IsRead,
[property: JsonPropertyName("readAt")] DateTime? ReadAt,
[property: JsonPropertyName("createdAt")] DateTime CreatedAt
);
public sealed record NotificationTemplateDto(
[property: JsonPropertyName("id")] Guid Id,
[property: JsonPropertyName("eventType")] string EventType,
[property: JsonPropertyName("channel")] string Channel,
[property: JsonPropertyName("language")] string Language,
[property: JsonPropertyName("subject")] string Subject,
[property: JsonPropertyName("bodyMarkdown")] string BodyMarkdown,
[property: JsonPropertyName("isDefault")] bool IsDefault
);
public sealed record UserNotificationConfigDto(
[property: JsonPropertyName("id")] Guid Id,
[property: JsonPropertyName("userId")] Guid UserId,
[property: JsonPropertyName("emailEnabled")] bool EmailEnabled,
[property: JsonPropertyName("emailAddress")] string? EmailAddress,
[property: JsonPropertyName("gotifyEnabled")] bool GotifyEnabled,
[property: JsonPropertyName("gotifyUrl")] string? GotifyUrl,
[property: JsonPropertyName("language")] string Language,
[property: JsonPropertyName("dailyDigest")] bool DailyDigest,
[property: JsonPropertyName("weeklyDigest")] bool WeeklyDigest,
[property: JsonPropertyName("subscribedEvents")] IReadOnlyList<string>? SubscribedEvents
);
public sealed record UpdateNotificationConfigRequest(
[property: JsonPropertyName("emailEnabled")] bool? EmailEnabled,
[property: JsonPropertyName("emailAddress")] string? EmailAddress,
[property: JsonPropertyName("gotifyEnabled")] bool? GotifyEnabled,
[property: JsonPropertyName("gotifyUrl")] string? GotifyUrl,
[property: JsonPropertyName("gotifyToken")] string? GotifyToken,
[property: JsonPropertyName("language")] string? Language,
[property: JsonPropertyName("dailyDigest")] bool? DailyDigest,
[property: JsonPropertyName("weeklyDigest")] bool? WeeklyDigest,
[property: JsonPropertyName("subscribedEvents")] List<string>? SubscribedEvents
);
public sealed record UnreadCountDto(
[property: JsonPropertyName("count")] int Count
);
public sealed record MarkAsReadResponse(
[property: JsonPropertyName("success")] bool Success
);
@@ -0,0 +1,7 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
namespace Heimdall.Application.Notifications.Commands.MarkAllAsRead;
public record MarkAllAsReadCommand(Guid UserId) : IRequest<ServiceResult<MarkAsReadResponse>>;
@@ -0,0 +1,27 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Notifications.Commands.MarkAllAsRead;
public class MarkAllAsReadHandler : IRequestHandler<MarkAllAsReadCommand, ServiceResult<MarkAsReadResponse>>
{
private readonly IApplicationDbContext _context;
public MarkAllAsReadHandler(IApplicationDbContext context) => _context = context;
public async Task<ServiceResult<MarkAsReadResponse>> Handle(MarkAllAsReadCommand request, CancellationToken ct)
{
var unread = await _context.Notifications
.Where(n => n.UserId == request.UserId && !n.IsRead)
.ToListAsync(ct);
foreach (var notification in unread)
notification.MarkAsRead();
await _context.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult<MarkAsReadResponse>.Success(new MarkAsReadResponse(true));
}
}
@@ -0,0 +1,7 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
namespace Heimdall.Application.Notifications.Commands.MarkAsRead;
public record MarkAsReadCommand(Guid NotificationId, Guid UserId) : IRequest<ServiceResult<MarkAsReadResponse>>;
@@ -0,0 +1,27 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Notifications.Commands.MarkAsRead;
public class MarkAsReadHandler : IRequestHandler<MarkAsReadCommand, ServiceResult<MarkAsReadResponse>>
{
private readonly IApplicationDbContext _context;
public MarkAsReadHandler(IApplicationDbContext context) => _context = context;
public async Task<ServiceResult<MarkAsReadResponse>> Handle(MarkAsReadCommand request, CancellationToken ct)
{
var notification = await _context.Notifications
.FirstOrDefaultAsync(n => n.Id == request.NotificationId && n.UserId == request.UserId, ct);
if (notification is null)
return ServiceResult<MarkAsReadResponse>.NotFound("Notification not found");
notification.MarkAsRead();
await _context.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult<MarkAsReadResponse>.Success(new MarkAsReadResponse(true));
}
}
@@ -0,0 +1,17 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
namespace Heimdall.Application.Notifications.Commands.UpdateConfig;
public record UpdateNotificationConfigCommand(
Guid UserId,
bool? EmailEnabled,
string? EmailAddress,
bool? GotifyEnabled,
string? GotifyUrl,
string? GotifyToken,
string? Language,
bool? DailyDigest,
bool? WeeklyDigest,
List<string>? SubscribedEvents) : IRequest<ServiceResult<UserNotificationConfigDto>>;
@@ -0,0 +1,51 @@
using AutoMapper;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Notifications.Commands.UpdateConfig;
public class UpdateNotificationConfigHandler : IRequestHandler<UpdateNotificationConfigCommand, ServiceResult<UserNotificationConfigDto>>
{
private readonly IApplicationDbContext _context;
private readonly IMapper _mapper;
public UpdateNotificationConfigHandler(IApplicationDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public async Task<ServiceResult<UserNotificationConfigDto>> Handle(UpdateNotificationConfigCommand request, CancellationToken ct)
{
var config = await _context.UserNotificationConfigs
.FirstOrDefaultAsync(c => c.UserId == request.UserId, ct);
if (config is null)
{
config = new UserNotificationConfig(request.UserId);
_context.UserNotificationConfigs.Add(config);
}
if (request.EmailEnabled.HasValue || request.EmailAddress is not null)
config.UpdateEmail(request.EmailAddress ?? config.EmailAddress, request.EmailEnabled ?? config.EmailEnabled);
if (request.GotifyEnabled.HasValue || request.GotifyUrl is not null || request.GotifyToken is not null)
config.UpdateGotify(request.GotifyUrl ?? config.GotifyUrl, request.GotifyToken ?? config.GotifyToken, request.GotifyEnabled ?? config.GotifyEnabled);
if (request.DailyDigest.HasValue || request.WeeklyDigest.HasValue)
config.UpdateDigests(request.DailyDigest ?? config.DailyDigest, request.WeeklyDigest ?? config.WeeklyDigest);
if (request.SubscribedEvents is not null)
config.SetSubscribedEvents(System.Text.Json.JsonSerializer.Serialize(request.SubscribedEvents));
if (request.Language is not null)
config.SetLanguage(request.Language);
await _context.SaveChangesWithRetryAsync(ct: ct);
return ServiceResult<UserNotificationConfigDto>.Success(_mapper.Map<UserNotificationConfigDto>(config));
}
}
@@ -0,0 +1,29 @@
using AutoMapper;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
namespace Heimdall.Application.Notifications.Mapping;
public class NotificationMappingProfile : Profile
{
public NotificationMappingProfile()
{
CreateMap<Notification, NotificationDto>()
.ForMember(d => d.Type, opt => opt.MapFrom(s => s.Type.ToString()))
.ForMember(d => d.EventType, opt => opt.MapFrom(s => s.EventType.HasValue ? s.EventType.Value.ToString() : null));
CreateMap<NotificationTemplate, NotificationTemplateDto>()
.ForMember(d => d.EventType, opt => opt.MapFrom(s => s.EventType.ToString()))
.ForMember(d => d.Channel, opt => opt.MapFrom(s => s.Channel.ToString()));
CreateMap<UserNotificationConfig, UserNotificationConfigDto>()
.ForCtorParam("SubscribedEvents", opt => opt.MapFrom(s =>
s.SubscribedEventsJson != null
? System.Text.Json.JsonSerializer.Deserialize<List<string>>(s.SubscribedEventsJson)
: null))
.ForMember(d => d.SubscribedEvents, opt => opt.MapFrom(s =>
s.SubscribedEventsJson != null
? System.Text.Json.JsonSerializer.Deserialize<List<string>>(s.SubscribedEventsJson)
: null));
}
}
@@ -0,0 +1,35 @@
using AutoMapper;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Notifications.Queries.GetConfig;
public class GetNotificationConfigHandler : IRequestHandler<GetNotificationConfigQuery, ServiceResult<UserNotificationConfigDto>>
{
private readonly IApplicationDbContext _context;
private readonly IMapper _mapper;
public GetNotificationConfigHandler(IApplicationDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public async Task<ServiceResult<UserNotificationConfigDto>> Handle(GetNotificationConfigQuery request, CancellationToken ct)
{
var config = await _context.UserNotificationConfigs
.FirstOrDefaultAsync(c => c.UserId == request.UserId, ct);
if (config is null)
{
config = new UserNotificationConfig(request.UserId);
_context.UserNotificationConfigs.Add(config);
await _context.SaveChangesWithRetryAsync(ct: ct);
}
return ServiceResult<UserNotificationConfigDto>.Success(_mapper.Map<UserNotificationConfigDto>(config));
}
}
@@ -0,0 +1,7 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
namespace Heimdall.Application.Notifications.Queries.GetConfig;
public record GetNotificationConfigQuery(Guid UserId) : IRequest<ServiceResult<UserNotificationConfigDto>>;
@@ -0,0 +1,40 @@
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Notifications.Queries.GetNotifications;
public class GetNotificationsHandler : IRequestHandler<GetNotificationsQuery, PagedResult<NotificationDto>>
{
private readonly IApplicationDbContext _context;
private readonly IMapper _mapper;
public GetNotificationsHandler(IApplicationDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public async Task<PagedResult<NotificationDto>> Handle(GetNotificationsQuery request, CancellationToken ct)
{
var query = _context.Notifications
.Where(n => n.UserId == request.UserId);
if (request.IsRead.HasValue)
query = query.Where(n => n.IsRead == request.IsRead.Value);
var totalCount = await query.CountAsync(ct);
var items = await query
.OrderByDescending(n => n.CreatedAt)
.Skip((request.Page - 1) * request.PageSize)
.Take(request.PageSize)
.ProjectTo<NotificationDto>(_mapper.ConfigurationProvider)
.ToListAsync(ct);
return new PagedResult<NotificationDto>(items, totalCount, request.Page, request.PageSize);
}
}
@@ -0,0 +1,11 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
namespace Heimdall.Application.Notifications.Queries.GetNotifications;
public record GetNotificationsQuery(
Guid UserId,
bool? IsRead,
int Page = 1,
int PageSize = 20) : IRequest<PagedResult<NotificationDto>>;
@@ -0,0 +1,21 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Notifications.Queries.GetUnreadCount;
public class GetUnreadCountHandler : IRequestHandler<GetUnreadCountQuery, ServiceResult<UnreadCountDto>>
{
private readonly IApplicationDbContext _context;
public GetUnreadCountHandler(IApplicationDbContext context) => _context = context;
public async Task<ServiceResult<UnreadCountDto>> Handle(GetUnreadCountQuery request, CancellationToken ct)
{
var count = await _context.Notifications
.CountAsync(n => n.UserId == request.UserId && !n.IsRead, ct);
return ServiceResult<UnreadCountDto>.Success(new UnreadCountDto(count));
}
}
@@ -0,0 +1,7 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using MediatR;
namespace Heimdall.Application.Notifications.Queries.GetUnreadCount;
public record GetUnreadCountQuery(Guid UserId) : IRequest<ServiceResult<UnreadCountDto>>;
@@ -0,0 +1,12 @@
namespace Heimdall.Application.Services;
/// <summary>
/// Broadcasts admin-level configuration changes via SignalR.
/// </summary>
public interface IAdminBroadcastService
{
Task NotifyConfigChanged(string key, string? oldValue, string? newValue, CancellationToken ct = default);
Task NotifyCameraAdded(Guid siteId, Guid cameraId, string cameraName, CancellationToken ct = default);
Task NotifyCameraRemoved(Guid siteId, Guid cameraId, CancellationToken ct = default);
Task NotifyUserRoleChanged(Guid userId, string newRole, CancellationToken ct = default);
}
@@ -0,0 +1,6 @@
namespace Heimdall.Application.Services;
public interface IEmailService
{
Task SendEmailAsync(string recipient, string subject, string bodyHtml, CancellationToken ct = default);
}
@@ -0,0 +1,6 @@
namespace Heimdall.Application.Services;
public interface IGotifyService
{
Task SendNotificationAsync(string url, string token, string title, string message, int priority = 5, CancellationToken ct = default);
}
@@ -0,0 +1,13 @@
namespace Heimdall.Application.Services;
/// <summary>
/// Broadcasts monitoring events (agent/camera status, storage, GPU) via SignalR.
/// </summary>
public interface IMonitoringBroadcastService
{
Task NotifyAgentStatusChanged(Guid siteId, Guid agentId, string status, CancellationToken ct = default);
Task NotifyCameraStatusChanged(Guid siteId, Guid cameraId, string status, CancellationToken ct = default);
Task NotifyStorageUsageUpdated(int usedPercent, long availableBytes, CancellationToken ct = default);
Task NotifyGpuUsageUpdated(int usedPercent, float temperature, CancellationToken ct = default);
Task NotifyJobStatusChanged(string jobName, string status, string? duration = null, CancellationToken ct = default);
}
@@ -0,0 +1,12 @@
using Heimdall.Application.DTOs;
namespace Heimdall.Application.Services;
/// <summary>
/// Broadcasts notifications to connected clients via SignalR.
/// </summary>
public interface INotificationBroadcastService
{
Task NotifyNewNotification(NotificationDto notification, CancellationToken ct = default);
Task NotifyUnreadCount(Guid userId, int count, CancellationToken ct = default);
}
@@ -0,0 +1,12 @@
using Heimdall.Domain.Enums;
namespace Heimdall.Application.Services;
/// <summary>
/// Rate-limits notifications per camera/type to prevent spam.
/// </summary>
public interface INotificationRateLimiter
{
/// <summary>Returns true if the notification should be sent.</summary>
bool ShouldSend(Guid cameraId, EventType type, Guid? trackId);
}
@@ -0,0 +1,32 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Common;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
namespace Heimdall.Application.Services;
/// <summary>
/// Core notification orchestration service.
/// Creates notifications, dispatches to channels (SignalR/Email/Gotify), respects rate limits.
/// </summary>
public interface INotificationService
{
/// <summary>Create a notification and dispatch to all enabled channels.</summary>
Task<ServiceResult<NotificationDto>> CreateNotificationAsync(
Guid userId, string title, string message, NotificationType type,
EventType? eventType = null, Guid? cameraId = null, Guid? siteId = null,
string? snapshotUrl = null, string? link = null,
CancellationToken ct = default);
/// <summary>Get unread notification count for a user.</summary>
Task<int> GetUnreadCountAsync(Guid userId, CancellationToken ct = default);
/// <summary>Get paginated notifications for a user.</summary>
Task<PagedResult<NotificationDto>> GetNotificationsAsync(Guid userId, bool? isRead, int page, int pageSize, CancellationToken ct = default);
/// <summary>Mark a single notification as read.</summary>
Task MarkAsReadAsync(Guid notificationId, Guid userId, CancellationToken ct = default);
/// <summary>Mark all notifications as read for a user.</summary>
Task MarkAllAsReadAsync(Guid userId, CancellationToken ct = default);
}
@@ -0,0 +1,49 @@
using Heimdall.Domain.Enums;
using Heimdall.Domain.Primitives;
namespace Heimdall.Domain.Entities;
/// <summary>
/// Represents a user notification triggered by a camera event.
/// Supports read tracking, optional event/camera/site links, and snapshot URLs.
/// </summary>
public class Notification : Entity<Guid>, IAuditableEntity
{
public Guid UserId { get; private set; }
public string Title { get; private set; } = string.Empty;
public string Message { get; private set; } = string.Empty;
public NotificationType Type { get; private set; } = NotificationType.Info;
public EventType? EventType { get; private set; }
public Guid? CameraId { get; private set; }
public Guid? SiteId { get; private set; }
public string? SnapshotUrl { get; private set; }
public string? Link { get; private set; }
public bool IsRead { get; private set; }
public DateTime? ReadAt { get; private set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
private Notification() { } // EF Core
public Notification(Guid userId, string title, string message, NotificationType type,
EventType? eventType = null, Guid? cameraId = null, Guid? siteId = null,
string? snapshotUrl = null, string? link = null)
: base(Guid.NewGuid())
{
UserId = userId;
Title = title;
Message = message;
Type = type;
EventType = eventType;
CameraId = cameraId;
SiteId = siteId;
SnapshotUrl = snapshotUrl;
Link = link;
}
public void MarkAsRead()
{
IsRead = true;
ReadAt = DateTime.UtcNow;
}
}
@@ -0,0 +1,41 @@
using Heimdall.Domain.Enums;
using Heimdall.Domain.Primitives;
namespace Heimdall.Domain.Entities;
/// <summary>
/// Defines a per-channel and per-language notification template for a given event type.
/// Supports default fallback templates that can be overridden per user.
/// </summary>
public class NotificationTemplate : Entity<Guid>, IAuditableEntity
{
public EventType EventType { get; private set; }
public NotificationChannel Channel { get; private set; }
public string Language { get; private set; } = "fr";
public string Subject { get; private set; } = string.Empty;
public string BodyMarkdown { get; private set; } = string.Empty;
public bool IsDefault { get; private set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
private NotificationTemplate() { } // EF Core
public NotificationTemplate(EventType eventType, NotificationChannel channel,
string subject, string bodyMarkdown, string language = "fr", bool isDefault = false)
: base(Guid.NewGuid())
{
EventType = eventType;
Channel = channel;
Language = language;
Subject = subject;
BodyMarkdown = bodyMarkdown;
IsDefault = isDefault;
}
public void Update(string subject, string bodyMarkdown, bool isDefault)
{
Subject = subject;
BodyMarkdown = bodyMarkdown;
IsDefault = isDefault;
}
}
@@ -0,0 +1,61 @@
using Heimdall.Domain.Enums;
using Heimdall.Domain.Primitives;
namespace Heimdall.Domain.Entities;
/// <summary>
/// Per-user notification preferences including channel configuration,
/// language, digest schedule, and subscribed event types.
/// </summary>
public class UserNotificationConfig : Entity<Guid>, IAuditableEntity
{
public Guid UserId { get; private set; }
public bool EmailEnabled { get; private set; }
public string? EmailAddress { get; private set; }
public bool GotifyEnabled { get; private set; }
public string? GotifyUrl { get; private set; }
public string? GotifyToken { get; private set; }
public string Language { get; private set; } = "fr";
public bool DailyDigest { get; private set; }
public bool WeeklyDigest { get; private set; }
public string? SubscribedEventsJson { get; private set; } // JSON array of EventType values
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
private UserNotificationConfig() { } // EF Core
public UserNotificationConfig(Guid userId)
: base(Guid.NewGuid())
{
UserId = userId;
}
public void UpdateEmail(string? emailAddress, bool enabled)
{
EmailAddress = emailAddress;
EmailEnabled = enabled;
}
public void UpdateGotify(string? url, string? token, bool enabled)
{
GotifyUrl = url;
GotifyToken = token;
GotifyEnabled = enabled;
}
public void UpdateDigests(bool daily, bool weekly)
{
DailyDigest = daily;
WeeklyDigest = weekly;
}
public void SetSubscribedEvents(string? subscribedEventsJson)
{
SubscribedEventsJson = subscribedEventsJson;
}
public void SetLanguage(string language)
{
Language = language;
}
}
@@ -0,0 +1,8 @@
namespace Heimdall.Domain.Enums;
public enum NotificationChannel
{
InApp = 0,
Email = 1,
Gotify = 2
}
@@ -0,0 +1,10 @@
namespace Heimdall.Domain.Enums;
public enum NotificationType
{
Info = 0,
Success = 1,
Warning = 2,
Error = 3,
Alert = 4
}
@@ -34,11 +34,14 @@ public static class DependencyInjection
services.AddHangfireServer(options =>
{
options.WorkerCount = 2;
options.Queues = ["default", "heartbeat"];
options.Queues = ["default", "heartbeat", "email", "gotify", "digest"];
});
services.AddScoped<HeartbeatMonitorJob>();
services.AddScoped<AgentFailoverJob>();
services.AddScoped<SendNotificationJob>();
services.AddScoped<DailyDigestJob>();
services.AddScoped<WeeklyDigestJob>();
return services;
}
@@ -16,5 +16,15 @@ public static class JobSetup
"agent-failover",
job => job.ExecuteAsync(CancellationToken.None),
"*/1 * * * *");
manager.AddOrUpdate<DailyDigestJob>(
"daily-digest",
job => job.ExecuteAsync(CancellationToken.None),
"0 8 * * *"); // Daily at 8:00
manager.AddOrUpdate<WeeklyDigestJob>(
"weekly-digest",
job => job.ExecuteAsync(CancellationToken.None),
"0 8 * * 1"); // Monday at 8:00
}
}
@@ -43,6 +43,11 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>, IApplicat
// Event entities
public DbSet<CameraEvent> CameraEvents => Set<CameraEvent>();
// Notification entities
public DbSet<Notification> Notifications => Set<Notification>();
public DbSet<NotificationTemplate> NotificationTemplates => Set<NotificationTemplate>();
public DbSet<UserNotificationConfig> UserNotificationConfigs => Set<UserNotificationConfig>();
// Security entities
public DbSet<RevokedRefreshToken> RevokedRefreshTokens => Set<RevokedRefreshToken>();
@@ -0,0 +1,49 @@
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Heimdall.Infrastructure.Data.Configurations;
public class NotificationConfiguration : IEntityTypeConfiguration<Notification>
{
public void Configure(EntityTypeBuilder<Notification> builder)
{
builder.ToTable("notifications");
builder.HasKey(n => n.Id);
builder.Property(n => n.Title)
.HasMaxLength(200)
.IsRequired();
builder.Property(n => n.Message)
.HasMaxLength(2000)
.IsRequired();
builder.Property(n => n.Type)
.HasConversion<string>()
.HasMaxLength(50);
builder.Property(n => n.EventType)
.HasConversion<string>()
.HasMaxLength(50);
builder.Property(n => n.SnapshotUrl)
.HasMaxLength(500);
builder.Property(n => n.Link)
.HasMaxLength(500);
builder.Property(n => n.CreatedAt)
.HasDefaultValueSql("NOW()");
builder.Property(n => n.UpdatedAt)
.HasDefaultValueSql("NOW()");
// Indexes
builder.HasIndex(n => n.UserId);
builder.HasIndex(n => new { n.UserId, n.IsRead });
builder.HasIndex(n => n.CreatedAt);
}
}
@@ -0,0 +1,47 @@
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Heimdall.Infrastructure.Data.Configurations;
public class NotificationTemplateConfiguration : IEntityTypeConfiguration<NotificationTemplate>
{
public void Configure(EntityTypeBuilder<NotificationTemplate> builder)
{
builder.ToTable("notification_templates");
builder.HasKey(t => t.Id);
builder.Property(t => t.EventType)
.HasConversion<string>()
.HasMaxLength(50)
.IsRequired();
builder.Property(t => t.Channel)
.HasConversion<string>()
.HasMaxLength(50)
.IsRequired();
builder.Property(t => t.Language)
.HasMaxLength(10)
.IsRequired()
.HasDefaultValue("fr");
builder.Property(t => t.Subject)
.HasMaxLength(200)
.IsRequired();
builder.Property(t => t.BodyMarkdown)
.IsRequired();
builder.Property(t => t.CreatedAt)
.HasDefaultValueSql("NOW()");
builder.Property(t => t.UpdatedAt)
.HasDefaultValueSql("NOW()");
// Indexes
builder.HasIndex(t => new { t.EventType, t.Channel, t.Language }).IsUnique();
}
}
@@ -0,0 +1,41 @@
using Heimdall.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Heimdall.Infrastructure.Data.Configurations;
public class UserNotificationConfigConfiguration : IEntityTypeConfiguration<UserNotificationConfig>
{
public void Configure(EntityTypeBuilder<UserNotificationConfig> builder)
{
builder.ToTable("user_notification_configs");
builder.HasKey(c => c.Id);
builder.Property(c => c.EmailAddress)
.HasMaxLength(200);
builder.Property(c => c.GotifyUrl)
.HasMaxLength(500);
builder.Property(c => c.GotifyToken)
.HasMaxLength(500);
builder.Property(c => c.Language)
.HasMaxLength(10)
.HasDefaultValue("fr");
builder.Property(c => c.SubscribedEventsJson)
.HasColumnName("subscribed_events")
.HasColumnType("jsonb");
builder.Property(c => c.CreatedAt)
.HasDefaultValueSql("NOW()");
builder.Property(c => c.UpdatedAt)
.HasDefaultValueSql("NOW()");
// Indexes
builder.HasIndex(c => c.UserId).IsUnique();
}
}
@@ -137,6 +137,16 @@ public static class DependencyInjection
// Camera assignment service (used by CQRS handlers)
services.AddScoped<ICameraAssignmentService, CameraAssignmentService>();
// Notification services
services.AddScoped<INotificationService, NotificationService>();
services.AddSingleton<INotificationRateLimiter, NotificationRateLimiter>();
services.AddScoped<IEmailService, EmailService>();
services.AddScoped<IGotifyService, GotifyService>();
services.AddHttpClient("Gotify", client =>
{
client.Timeout = TimeSpan.FromSeconds(10);
});
return services;
}
}
@@ -0,0 +1,73 @@
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Jobs;
/// <summary>
/// Hangfire recurring job that sends a daily digest email to users who have it enabled.
/// Scheduled daily at 8:00.
/// Uses IDbContextFactory to avoid sharing a DbContext across Hangfire worker threads.
/// </summary>
public class DailyDigestJob
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly IEmailService _emailService;
private readonly ILogger<DailyDigestJob> _logger;
public DailyDigestJob(
IDbContextFactory<AppDbContext> dbFactory,
IEmailService emailService,
ILogger<DailyDigestJob> logger)
{
_dbFactory = dbFactory;
_emailService = emailService;
_logger = logger;
}
public async Task ExecuteAsync(CancellationToken ct = default)
{
_logger.LogInformation("Starting daily digest job");
await using var db = await _dbFactory.CreateDbContextAsync(ct);
var configs = await db.UserNotificationConfigs
.Where(c => c.DailyDigest && c.EmailEnabled && c.EmailAddress != null)
.ToListAsync(ct);
var yesterday = DateTime.UtcNow.Date.AddDays(-1);
foreach (var config in configs)
{
try
{
var eventCount = await db.CameraEvents
.CountAsync(e => e.CreatedAt >= yesterday, ct);
var unreadNotifications = await db.Notifications
.CountAsync(n => n.UserId == config.UserId && !n.IsRead, ct);
var subject = "Heimdall — Résumé quotidien";
var body = $"""
<h2>Résumé quotidien Heimdall</h2>
<p>Bonjour,</p>
<ul>
<li>Événements détectés aujourd'hui : <strong>{eventCount}</strong></li>
<li>Notifications non lues : <strong>{unreadNotifications}</strong></li>
</ul>
<p>Cordialement,<br/>L'équipe Heimdall</p>
""";
await _emailService.SendEmailAsync(config.EmailAddress!, subject, body, ct);
_logger.LogDebug("Daily digest sent to {Email}", config.EmailAddress);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send daily digest to {Email}", config.EmailAddress);
}
}
_logger.LogInformation("Daily digest completed: {Count} emails sent", configs.Count);
}
}
@@ -0,0 +1,37 @@
using Heimdall.Application.Services;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Jobs;
/// <summary>
/// Hangfire job to send a notification via email or Gotify.
/// Fire-and-forget, with retry built into Hangfire.
/// </summary>
public class SendNotificationJob
{
private readonly IEmailService _emailService;
private readonly IGotifyService _gotifyService;
private readonly ILogger<SendNotificationJob> _logger;
public SendNotificationJob(
IEmailService emailService,
IGotifyService gotifyService,
ILogger<SendNotificationJob> logger)
{
_emailService = emailService;
_gotifyService = gotifyService;
_logger = logger;
}
public async Task SendEmailAsync(string recipient, string subject, string bodyHtml, CancellationToken ct = default)
{
_logger.LogInformation("Sending email notification to {Recipient}: {Subject}", recipient, subject);
await _emailService.SendEmailAsync(recipient, subject, bodyHtml, ct);
}
public async Task SendGotifyAsync(string url, string token, string title, string message, int priority = 5, CancellationToken ct = default)
{
_logger.LogInformation("Sending Gotify notification: {Title}", title);
await _gotifyService.SendNotificationAsync(url, token, title, message, priority, ct);
}
}
@@ -0,0 +1,69 @@
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Jobs;
/// <summary>
/// Hangfire recurring job that sends a weekly digest email to users who have it enabled.
/// Scheduled Monday at 8:00.
/// Uses IDbContextFactory to avoid sharing a DbContext across Hangfire worker threads.
/// </summary>
public class WeeklyDigestJob
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly IEmailService _emailService;
private readonly ILogger<WeeklyDigestJob> _logger;
public WeeklyDigestJob(
IDbContextFactory<AppDbContext> dbFactory,
IEmailService emailService,
ILogger<WeeklyDigestJob> logger)
{
_dbFactory = dbFactory;
_emailService = emailService;
_logger = logger;
}
public async Task ExecuteAsync(CancellationToken ct = default)
{
_logger.LogInformation("Starting weekly digest job");
await using var db = await _dbFactory.CreateDbContextAsync(ct);
var configs = await db.UserNotificationConfigs
.Where(c => c.WeeklyDigest && c.EmailEnabled && c.EmailAddress != null)
.ToListAsync(ct);
var lastWeek = DateTime.UtcNow.Date.AddDays(-7);
foreach (var config in configs)
{
try
{
var eventCount = await db.CameraEvents
.CountAsync(e => e.CreatedAt >= lastWeek, ct);
var subject = "Heimdall — Résumé hebdomadaire";
var body = $"""
<h2>Résumé hebdomadaire Heimdall</h2>
<p>Bonjour,</p>
<ul>
<li>Événements détectés cette semaine : <strong>{eventCount}</strong></li>
</ul>
<p>Cordialement,<br/>L'équipe Heimdall</p>
""";
await _emailService.SendEmailAsync(config.EmailAddress!, subject, body, ct);
_logger.LogDebug("Weekly digest sent to {Email}", config.EmailAddress);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send weekly digest to {Email}", config.EmailAddress);
}
}
_logger.LogInformation("Weekly digest completed: {Count} emails sent", configs.Count);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,121 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Heimdall.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class AddNotifications : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "notification_templates",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
EventType = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
Channel = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
Language = table.Column<string>(type: "character varying(10)", maxLength: 10, nullable: false, defaultValue: "fr"),
Subject = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
BodyMarkdown = table.Column<string>(type: "text", nullable: false),
IsDefault = table.Column<bool>(type: "boolean", nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"),
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()")
},
constraints: table =>
{
table.PrimaryKey("PK_notification_templates", x => x.Id);
});
migrationBuilder.CreateTable(
name: "notifications",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
UserId = table.Column<Guid>(type: "uuid", nullable: false),
Title = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
Message = table.Column<string>(type: "character varying(2000)", maxLength: 2000, nullable: false),
Type = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
EventType = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: true),
CameraId = table.Column<Guid>(type: "uuid", nullable: true),
SiteId = table.Column<Guid>(type: "uuid", nullable: true),
SnapshotUrl = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: true),
Link = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: true),
IsRead = table.Column<bool>(type: "boolean", nullable: false),
ReadAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"),
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()")
},
constraints: table =>
{
table.PrimaryKey("PK_notifications", x => x.Id);
});
migrationBuilder.CreateTable(
name: "user_notification_configs",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
UserId = table.Column<Guid>(type: "uuid", nullable: false),
EmailEnabled = table.Column<bool>(type: "boolean", nullable: false),
EmailAddress = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: true),
GotifyEnabled = table.Column<bool>(type: "boolean", nullable: false),
GotifyUrl = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: true),
GotifyToken = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: true),
Language = table.Column<string>(type: "character varying(10)", maxLength: 10, nullable: false, defaultValue: "fr"),
DailyDigest = table.Column<bool>(type: "boolean", nullable: false),
WeeklyDigest = table.Column<bool>(type: "boolean", nullable: false),
subscribed_events = table.Column<string>(type: "jsonb", nullable: true),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"),
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()")
},
constraints: table =>
{
table.PrimaryKey("PK_user_notification_configs", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_notification_templates_EventType_Channel_Language",
table: "notification_templates",
columns: new[] { "EventType", "Channel", "Language" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_notifications_CreatedAt",
table: "notifications",
column: "CreatedAt");
migrationBuilder.CreateIndex(
name: "IX_notifications_UserId",
table: "notifications",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_notifications_UserId_IsRead",
table: "notifications",
columns: new[] { "UserId", "IsRead" });
migrationBuilder.CreateIndex(
name: "IX_user_notification_configs_UserId",
table: "user_notification_configs",
column: "UserId",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "notification_templates");
migrationBuilder.DropTable(
name: "notifications");
migrationBuilder.DropTable(
name: "user_notification_configs");
}
}
}
@@ -1027,6 +1027,128 @@ namespace Heimdall.Infrastructure.Migrations
b.ToTable("known_faces", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.Notification", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid?>("CameraId")
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<string>("EventType")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<bool>("IsRead")
.HasColumnType("boolean");
b.Property<string>("Link")
.HasMaxLength(500)
.HasColumnType("character varying(500)");
b.Property<string>("Message")
.IsRequired()
.HasMaxLength(2000)
.HasColumnType("character varying(2000)");
b.Property<DateTime?>("ReadAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("SiteId")
.HasColumnType("uuid");
b.Property<string>("SnapshotUrl")
.HasMaxLength(500)
.HasColumnType("character varying(500)");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("Type")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("CreatedAt");
b.HasIndex("UserId");
b.HasIndex("UserId", "IsRead");
b.ToTable("notifications", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.NotificationTemplate", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("BodyMarkdown")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Channel")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<string>("EventType")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<bool>("IsDefault")
.HasColumnType("boolean");
b.Property<string>("Language")
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(10)
.HasColumnType("character varying(10)")
.HasDefaultValue("fr");
b.Property<string>("Subject")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.HasKey("Id");
b.HasIndex("EventType", "Channel", "Language")
.IsUnique();
b.ToTable("notification_templates", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.Person", b =>
{
b.Property<Guid>("Id")
@@ -1180,6 +1302,68 @@ namespace Heimdall.Infrastructure.Migrations
b.ToTable("user_groups", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.UserNotificationConfig", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<bool>("DailyDigest")
.HasColumnType("boolean");
b.Property<string>("EmailAddress")
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<bool>("EmailEnabled")
.HasColumnType("boolean");
b.Property<bool>("GotifyEnabled")
.HasColumnType("boolean");
b.Property<string>("GotifyToken")
.HasMaxLength(500)
.HasColumnType("character varying(500)");
b.Property<string>("GotifyUrl")
.HasMaxLength(500)
.HasColumnType("character varying(500)");
b.Property<string>("Language")
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(10)
.HasColumnType("character varying(10)")
.HasDefaultValue("fr");
b.Property<string>("SubscribedEventsJson")
.HasColumnType("jsonb")
.HasColumnName("subscribed_events");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasDefaultValueSql("NOW()");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.Property<bool>("WeeklyDigest")
.HasColumnType("boolean");
b.HasKey("Id");
b.HasIndex("UserId")
.IsUnique();
b.ToTable("user_notification_configs", (string)null);
});
modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b =>
{
b.Property<Guid>("UserId")
@@ -0,0 +1,22 @@
using Heimdall.Application.Services;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Services;
public class EmailService : IEmailService
{
private readonly ILogger<EmailService> _logger;
public EmailService(ILogger<EmailService> logger)
{
_logger = logger;
}
public async Task SendEmailAsync(string recipient, string subject, string bodyHtml, CancellationToken ct = default)
{
// TODO: Implement actual SMTP sending via MailKit or SmtpClient
// Configuration via EmailOptions (SmtpHost, SmtpPort, Username, Password)
_logger.LogInformation("Email would be sent to {Recipient}: {Subject}", recipient, subject);
await Task.CompletedTask;
}
}
@@ -0,0 +1,36 @@
using System.Net.Http.Json;
using Heimdall.Application.Services;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Services;
public class GotifyService : IGotifyService
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<GotifyService> _logger;
public GotifyService(IHttpClientFactory httpClientFactory, ILogger<GotifyService> logger)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
}
public async Task SendNotificationAsync(string url, string token, string title, string message, int priority = 5, CancellationToken ct = default)
{
try
{
var client = _httpClientFactory.CreateClient("Gotify");
var requestUrl = $"{url.TrimEnd('/')}/message?token={token}";
var payload = new { title, message, priority };
var response = await client.PostAsJsonAsync(requestUrl, payload, ct);
if (!response.IsSuccessStatusCode)
{
_logger.LogWarning("Gotify returned {StatusCode} for {Url}", response.StatusCode, url);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send Gotify notification to {Url}", url);
}
}
}
@@ -0,0 +1,31 @@
using Heimdall.Application.Services;
using Heimdall.Domain.Enums;
using Microsoft.Extensions.Caching.Memory;
namespace Heimdall.Infrastructure.Services;
public class NotificationRateLimiter : INotificationRateLimiter
{
private readonly IMemoryCache _cache;
public NotificationRateLimiter(IMemoryCache cache)
{
_cache = cache;
}
public bool ShouldSend(Guid cameraId, EventType type, Guid? trackId)
{
var key = $"notif-rate:{cameraId}:{type}:{trackId ?? Guid.Empty}";
var count = _cache.GetOrCreate(key, entry =>
{
entry.SlidingExpiration = TimeSpan.FromMinutes(1);
return 0;
});
if (count >= 20)
return false; // Max 20 events/min/camera/type
_cache.Set(key, count + 1, TimeSpan.FromMinutes(1));
return true;
}
}
@@ -0,0 +1,158 @@
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Services;
public class NotificationService : INotificationService
{
private readonly IApplicationDbContext _context;
private readonly IMapper _mapper;
private readonly INotificationBroadcastService _broadcast;
private readonly IEmailService _emailService;
private readonly IGotifyService _gotifyService;
private readonly INotificationRateLimiter _rateLimiter;
private readonly ILogger<NotificationService> _logger;
public NotificationService(
IApplicationDbContext context,
IMapper mapper,
INotificationBroadcastService broadcast,
IEmailService emailService,
IGotifyService gotifyService,
INotificationRateLimiter rateLimiter,
ILogger<NotificationService> logger)
{
_context = context;
_mapper = mapper;
_broadcast = broadcast;
_emailService = emailService;
_gotifyService = gotifyService;
_rateLimiter = rateLimiter;
_logger = logger;
}
public async Task<ServiceResult<NotificationDto>> CreateNotificationAsync(
Guid userId, string title, string message, NotificationType type,
EventType? eventType = null, Guid? cameraId = null, Guid? siteId = null,
string? snapshotUrl = null, string? link = null,
CancellationToken ct = default)
{
// Rate limiting check
if (cameraId.HasValue && eventType.HasValue)
{
if (!_rateLimiter.ShouldSend(cameraId.Value, eventType.Value, null))
{
_logger.LogDebug("Rate limited notification for camera {CameraId} type {EventType}", cameraId, eventType);
return ServiceResult<NotificationDto>.Success(null!); // Silently skip
}
}
var notification = new Notification(
userId, title, message, type, eventType, cameraId, siteId, snapshotUrl, link);
_context.Notifications.Add(notification);
await _context.SaveChangesWithRetryAsync(ct: ct);
var dto = _mapper.Map<NotificationDto>(notification);
// Broadcast in-app
await _broadcast.NotifyNewNotification(dto, ct);
// Send via email/gotify if user has config
await DispatchToExternalChannelsAsync(notification, userId, ct);
return ServiceResult<NotificationDto>.Success(dto);
}
private async Task DispatchToExternalChannelsAsync(Notification notification, Guid userId, CancellationToken ct)
{
try
{
var config = await _context.UserNotificationConfigs
.FirstOrDefaultAsync(c => c.UserId == userId, ct);
if (config is null) return;
if (config.EmailEnabled && !string.IsNullOrEmpty(config.EmailAddress))
{
await _emailService.SendEmailAsync(
config.EmailAddress,
notification.Title,
$"<h2>{notification.Title}</h2><p>{notification.Message}</p>",
ct);
}
if (config.GotifyEnabled
&& !string.IsNullOrEmpty(config.GotifyUrl)
&& !string.IsNullOrEmpty(config.GotifyToken))
{
await _gotifyService.SendNotificationAsync(
config.GotifyUrl,
config.GotifyToken,
notification.Title,
notification.Message,
ct: ct);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to dispatch external notification for user {UserId}", userId);
}
}
public async Task<int> GetUnreadCountAsync(Guid userId, CancellationToken ct = default)
{
return await _context.Notifications
.CountAsync(n => n.UserId == userId && !n.IsRead, ct);
}
public async Task<PagedResult<NotificationDto>> GetNotificationsAsync(
Guid userId, bool? isRead, int page, int pageSize, CancellationToken ct = default)
{
var query = _context.Notifications.Where(n => n.UserId == userId);
if (isRead.HasValue)
query = query.Where(n => n.IsRead == isRead.Value);
var totalCount = await query.CountAsync(ct);
var items = await query
.OrderByDescending(n => n.CreatedAt)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ProjectTo<NotificationDto>(_mapper.ConfigurationProvider)
.ToListAsync(ct);
return new PagedResult<NotificationDto>(items, totalCount, page, pageSize);
}
public async Task MarkAsReadAsync(Guid notificationId, Guid userId, CancellationToken ct = default)
{
var notification = await _context.Notifications
.FirstOrDefaultAsync(n => n.Id == notificationId && n.UserId == userId, ct);
if (notification is not null)
{
notification.MarkAsRead();
await _context.SaveChangesWithRetryAsync(ct: ct);
}
}
public async Task MarkAllAsReadAsync(Guid userId, CancellationToken ct = default)
{
var unread = await _context.Notifications
.Where(n => n.UserId == userId && !n.IsRead)
.ToListAsync(ct);
foreach (var notification in unread)
notification.MarkAsRead();
await _context.SaveChangesWithRetryAsync(ct: ct);
}
}
@@ -0,0 +1,102 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Notifications.Commands.MarkAllAsRead;
using Heimdall.Application.Notifications.Commands.MarkAsRead;
using Heimdall.Application.Notifications.Commands.UpdateConfig;
using Heimdall.Application.Notifications.Queries.GetConfig;
using Heimdall.Application.Notifications.Queries.GetNotifications;
using Heimdall.Application.Notifications.Queries.GetUnreadCount;
using Heimdall.Infrastructure.Security;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using System.Security.Claims;
namespace Heimdall.Api.Controllers;
/// <summary>
/// In-app notifications for users — list, mark read, configure notification preferences.
/// </summary>
[ApiController]
[Route("api/notifications")]
[EnableRateLimiting("Api")]
[Authorize(AuthenticationSchemes = "JwtBearer")]
public class NotificationsController : ControllerBase
{
private readonly IMediator _mediator;
public NotificationsController(IMediator mediator) => _mediator = mediator;
private Guid GetUserId() =>
Guid.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
/// <summary>List notifications for the current user.</summary>
[HttpGet]
[ProducesResponseType(typeof(PagedResult<NotificationDto>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetNotifications(
[FromQuery] bool? isRead,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 20,
CancellationToken ct = default)
{
var result = await _mediator.Send(new GetNotificationsQuery(GetUserId(), isRead, page, pageSize), ct);
return Ok(result);
}
/// <summary>Get unread notification count.</summary>
[HttpGet("unread-count")]
[ProducesResponseType(typeof(UnreadCountDto), StatusCodes.Status200OK)]
public async Task<IActionResult> GetUnreadCount(CancellationToken ct = default)
{
var result = await _mediator.Send(new GetUnreadCountQuery(GetUserId()), ct);
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Mark a single notification as read.</summary>
[HttpPost("{id:guid}/read")]
[ProducesResponseType(typeof(MarkAsReadResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> MarkAsRead(Guid id, CancellationToken ct = default)
{
var result = await _mediator.Send(new MarkAsReadCommand(id, GetUserId()), ct);
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
/// <summary>Mark all notifications as read.</summary>
[HttpPost("mark-all-read")]
[ProducesResponseType(typeof(MarkAsReadResponse), StatusCodes.Status200OK)]
public async Task<IActionResult> MarkAllAsRead(CancellationToken ct = default)
{
var result = await _mediator.Send(new MarkAllAsReadCommand(GetUserId()), ct);
return Ok(result.Data);
}
/// <summary>Get notification configuration for the current user.</summary>
[HttpGet("config")]
[ProducesResponseType(typeof(UserNotificationConfigDto), StatusCodes.Status200OK)]
public async Task<IActionResult> GetConfig(CancellationToken ct = default)
{
var result = await _mediator.Send(new GetNotificationConfigQuery(GetUserId()), ct);
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Update notification configuration for the current user.</summary>
[HttpPut("config")]
[ProducesResponseType(typeof(UserNotificationConfigDto), StatusCodes.Status200OK)]
public async Task<IActionResult> UpdateConfig([FromBody] UpdateNotificationConfigRequest request, CancellationToken ct = default)
{
var command = new UpdateNotificationConfigCommand(
GetUserId(),
request.EmailEnabled,
request.EmailAddress,
request.GotifyEnabled,
request.GotifyUrl,
request.GotifyToken,
request.Language,
request.DailyDigest,
request.WeeklyDigest,
request.SubscribedEvents);
var result = await _mediator.Send(command, ct);
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
}
+86
View File
@@ -0,0 +1,86 @@
using Heimdall.Application.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
namespace Heimdall.Api.Hubs;
/// <summary>
/// SignalR hub for admin-level broadcast events (config changes, user role changes, camera lifecycle).
/// Only Admin role users can connect.
/// </summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Roles = "Admin")]
public class AdminHub : Hub
{
private readonly ILogger<AdminHub> _logger;
public AdminHub(ILogger<AdminHub> logger) => _logger = logger;
/// <summary>
/// Clients call this to join the admin broadcast group.
/// </summary>
public async Task JoinAdminBroadcast()
{
await Groups.AddToGroupAsync(Context.ConnectionId, "admin-broadcast");
_logger.LogDebug("Admin client {ConnectionId} joined admin broadcast group", Context.ConnectionId);
}
/// <summary>
/// Clients call this to leave the admin broadcast group.
/// </summary>
public async Task LeaveAdminBroadcast()
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, "admin-broadcast");
}
public override async Task OnConnectedAsync()
{
_logger.LogDebug("Admin connected to admin hub: {ConnectionId}", Context.ConnectionId);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
_logger.LogDebug("Admin disconnected from admin hub: {ConnectionId}", Context.ConnectionId);
await base.OnDisconnectedAsync(exception);
}
}
/// <summary>
/// Broadcasts admin-level configuration and lifecycle events via SignalR.
/// Uses IHubContext for thread-safe broadcasting outside of hub connections.
/// </summary>
public class AdminBroadcastService : IAdminBroadcastService
{
private readonly IHubContext<AdminHub> _hubContext;
private readonly ILogger<AdminBroadcastService> _logger;
public AdminBroadcastService(IHubContext<AdminHub> hubContext, ILogger<AdminBroadcastService> logger)
{
_hubContext = hubContext;
_logger = logger;
}
public async Task NotifyConfigChanged(string key, string? oldValue, string? newValue, CancellationToken ct = default)
{
_logger.LogDebug("Broadcasting config change: {Key}", key);
await _hubContext.Clients.Group("admin-broadcast").SendAsync("ConfigChanged", new { key, oldValue, newValue }, ct);
}
public async Task NotifyCameraAdded(Guid siteId, Guid cameraId, string cameraName, CancellationToken ct = default)
{
_logger.LogDebug("Broadcasting camera added: {CameraName} ({CameraId})", cameraName, cameraId);
await _hubContext.Clients.Group("admin-broadcast").SendAsync("CameraAdded", new { siteId, cameraId, cameraName }, ct);
}
public async Task NotifyCameraRemoved(Guid siteId, Guid cameraId, CancellationToken ct = default)
{
_logger.LogDebug("Broadcasting camera removed: {CameraId}", cameraId);
await _hubContext.Clients.Group("admin-broadcast").SendAsync("CameraRemoved", new { siteId, cameraId }, ct);
}
public async Task NotifyUserRoleChanged(Guid userId, string newRole, CancellationToken ct = default)
{
_logger.LogDebug("Broadcasting user role change: User={UserId} Role={NewRole}", userId, newRole);
await _hubContext.Clients.Group("admin-broadcast").SendAsync("UserRoleChanged", new { userId, newRole }, ct);
}
}
+115
View File
@@ -0,0 +1,115 @@
using Heimdall.Application.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
namespace Heimdall.Api.Hubs;
/// <summary>
/// SignalR hub for real-time monitoring: agent status, camera status, storage, GPU, jobs.
/// JWT-authenticated users receive live status updates without polling.
/// Groups: "site_{siteId}", "admin-broadcast"
/// </summary>
[Authorize(AuthenticationSchemes = "JwtBearer")]
public class MonitoringHub : Hub
{
private readonly ILogger<MonitoringHub> _logger;
public MonitoringHub(ILogger<MonitoringHub> logger) => _logger = logger;
/// <summary>
/// Clients call this to join monitoring for a specific site.
/// </summary>
public async Task JoinSiteMonitoring(string siteId)
{
if (!Guid.TryParse(siteId, out _))
{
await Clients.Caller.SendAsync("Error", "Invalid siteId format");
return;
}
await Groups.AddToGroupAsync(Context.ConnectionId, $"site_{siteId}");
_logger.LogDebug("Client {ConnectionId} joined monitoring group {SiteId}", Context.ConnectionId, siteId);
}
/// <summary>
/// Clients call this to leave monitoring for a specific site.
/// </summary>
public async Task LeaveSiteMonitoring(string siteId)
{
if (!Guid.TryParse(siteId, out _)) return;
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"site_{siteId}");
}
/// <summary>
/// Clients call this to receive admin-level monitoring broadcasts.
/// </summary>
public async Task JoinAdminBroadcast()
{
await Groups.AddToGroupAsync(Context.ConnectionId, "admin-broadcast");
_logger.LogDebug("Client {ConnectionId} joined admin broadcast monitoring group", Context.ConnectionId);
}
/// <summary>
/// Clients call this to leave admin-level monitoring broadcasts.
/// </summary>
public async Task LeaveAdminBroadcast()
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, "admin-broadcast");
}
public override async Task OnConnectedAsync()
{
_logger.LogDebug("Client connected to monitoring hub: {ConnectionId}", Context.ConnectionId);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
_logger.LogDebug("Client disconnected from monitoring hub: {ConnectionId}", Context.ConnectionId);
await base.OnDisconnectedAsync(exception);
}
}
/// <summary>
/// Broadcasts monitoring events to connected clients via SignalR.
/// Uses IHubContext for thread-safe broadcasting outside of hub connections.
/// </summary>
public class MonitoringBroadcastService : IMonitoringBroadcastService
{
private readonly IHubContext<MonitoringHub> _hubContext;
private readonly ILogger<MonitoringBroadcastService> _logger;
public MonitoringBroadcastService(IHubContext<MonitoringHub> hubContext, ILogger<MonitoringBroadcastService> logger)
{
_hubContext = hubContext;
_logger = logger;
}
public async Task NotifyAgentStatusChanged(Guid siteId, Guid agentId, string status, CancellationToken ct = default)
{
_logger.LogDebug("Broadcasting agent status: Agent={AgentId} Status={Status}", agentId, status);
await _hubContext.Clients.Group($"site_{siteId}").SendAsync("AgentStatusChanged", new { agentId, status }, ct);
await _hubContext.Clients.Group("admin-broadcast").SendAsync("AgentStatusChanged", new { siteId, agentId, status }, ct);
}
public async Task NotifyCameraStatusChanged(Guid siteId, Guid cameraId, string status, CancellationToken ct = default)
{
_logger.LogDebug("Broadcasting camera status: Camera={CameraId} Status={Status}", cameraId, status);
await _hubContext.Clients.Group($"site_{siteId}").SendAsync("CameraStatusChanged", new { cameraId, status }, ct);
await _hubContext.Clients.Group("admin-broadcast").SendAsync("CameraStatusChanged", new { siteId, cameraId, status }, ct);
}
public async Task NotifyStorageUsageUpdated(int usedPercent, long availableBytes, CancellationToken ct = default)
{
await _hubContext.Clients.Group("admin-broadcast").SendAsync("StorageUsageUpdated", new { usedPercent, availableBytes }, ct);
}
public async Task NotifyGpuUsageUpdated(int usedPercent, float temperature, CancellationToken ct = default)
{
await _hubContext.Clients.Group("admin-broadcast").SendAsync("GpuUsageUpdated", new { usedPercent, temperature }, ct);
}
public async Task NotifyJobStatusChanged(string jobName, string status, string? duration = null, CancellationToken ct = default)
{
await _hubContext.Clients.Group("admin-broadcast").SendAsync("JobStatusChanged", new { jobName, status, duration }, ct);
}
}
+77
View File
@@ -0,0 +1,77 @@
using System.Security.Claims;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
namespace Heimdall.Api.Hubs;
/// <summary>
/// SignalR hub for in-app notifications with badge count.
/// JWT-authenticated users receive new notifications and unread count updates
/// without polling.
/// Groups: "notif_{userId}"
/// </summary>
[Authorize(AuthenticationSchemes = "JwtBearer")]
public class NotificationsHub : Hub
{
private readonly ILogger<NotificationsHub> _logger;
public NotificationsHub(ILogger<NotificationsHub> logger) => _logger = logger;
/// <summary>
/// Clients call this to join their personal notification channel.
/// The user ID is extracted from the JWT claim.
/// </summary>
public async Task JoinPersonalNotifications()
{
var userId = Context.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userId is null)
{
await Clients.Caller.SendAsync("Error", "User not authenticated");
return;
}
await Groups.AddToGroupAsync(Context.ConnectionId, $"notif_{userId}");
_logger.LogDebug("Client {ConnectionId} joined personal notifications for user {UserId}", Context.ConnectionId, userId);
}
public override async Task OnConnectedAsync()
{
_logger.LogDebug("Client connected to notifications hub: {ConnectionId}", Context.ConnectionId);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
_logger.LogDebug("Client disconnected from notifications hub: {ConnectionId}", Context.ConnectionId);
await base.OnDisconnectedAsync(exception);
}
}
/// <summary>
/// Broadcasts notifications to connected clients via SignalR.
/// Uses IHubContext for thread-safe broadcasting outside of hub connections.
/// </summary>
public class NotificationBroadcastService : INotificationBroadcastService
{
private readonly IHubContext<NotificationsHub> _hubContext;
private readonly ILogger<NotificationBroadcastService> _logger;
public NotificationBroadcastService(IHubContext<NotificationsHub> hubContext, ILogger<NotificationBroadcastService> logger)
{
_hubContext = hubContext;
_logger = logger;
}
public async Task NotifyNewNotification(NotificationDto notification, CancellationToken ct = default)
{
_logger.LogDebug("Broadcasting new notification: {NotificationId} to user {UserId}", notification.Id, notification.UserId);
await _hubContext.Clients.Group($"notif_{notification.UserId}").SendAsync("NewNotification", notification, ct);
}
public async Task NotifyUnreadCount(Guid userId, int count, CancellationToken ct = default)
{
_logger.LogDebug("Broadcasting unread count: User={UserId} Count={Count}", userId, count);
await _hubContext.Clients.Group($"notif_{userId}").SendAsync("UnreadCount", new { count }, ct);
}
}
+6
View File
@@ -329,6 +329,9 @@ public partial class Program {
builder.Services.AddSignalR();
builder.Services.AddScoped<IEventBroadcastService, EventBroadcastService>();
builder.Services.AddScoped<IConfigBroadcastService, ConfigBroadcastService>();
builder.Services.AddScoped<IMonitoringBroadcastService, MonitoringBroadcastService>();
builder.Services.AddScoped<INotificationBroadcastService, NotificationBroadcastService>();
builder.Services.AddScoped<IAdminBroadcastService, AdminBroadcastService>();
builder.Services.AddOpenApi();
// ── Application & Infrastructure layers ──────────────────────────
@@ -400,6 +403,9 @@ public partial class Program {
app.MapControllers();
app.MapHub<ConfigHub>("/hubs/config");
app.MapHub<EventsHub>("/hubs/events");
app.MapHub<MonitoringHub>("/hubs/monitoring");
app.MapHub<NotificationsHub>("/hubs/notifications");
app.MapHub<AdminHub>("/hubs/admin");
if (app.Environment.IsDevelopment())
{
Binary file not shown.
Submodule
+1
Submodule templates added at 218303a91c.
@@ -72,8 +72,30 @@ internal sealed class InMemoryAsyncQueryProvider<T> : IAsyncQueryProvider
private readonly IQueryProvider _inner;
public InMemoryAsyncQueryProvider(IQueryProvider inner) => _inner = inner;
public IQueryable CreateQuery(Expression expression) =>
new InMemoryAsyncQueryable(expression, this);
public IQueryable CreateQuery(Expression expression)
{
// Detect element type from expression to return a properly typed queryable.
// This is needed by AutoMapper's ProjectTo which calls the non-generic CreateQuery.
// The expression.Type may be the IQueryable<T> interface itself or a concrete type.
var type = expression.Type;
Type elementType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IQueryable<>))
{
elementType = type.GetGenericArguments()[0];
}
else
{
elementType = type.GetInterfaces()
.FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IQueryable<>))
?.GetGenericArguments()[0]
?? typeof(T);
}
var providerType = typeof(InMemoryAsyncQueryProvider<>).MakeGenericType(elementType);
var queryableType = typeof(InMemoryAsyncQueryable<>).MakeGenericType(elementType);
var provider = Activator.CreateInstance(providerType, _inner);
return (IQueryable)Activator.CreateInstance(queryableType, expression, provider)!;
}
public IQueryable<TElement> CreateQuery<TElement>(Expression expression) =>
new InMemoryAsyncQueryable<TElement>(expression, new InMemoryAsyncQueryProvider<TElement>(_inner));
public object? Execute(Expression expression) => _inner.Execute(expression);
@@ -0,0 +1,364 @@
using AutoMapper;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Notifications.Commands.MarkAllAsRead;
using Heimdall.Application.Notifications.Commands.MarkAsRead;
using Heimdall.Application.Notifications.Commands.UpdateConfig;
using Heimdall.Application.Notifications.Mapping;
using Heimdall.Application.Notifications.Queries.GetConfig;
using Heimdall.Application.Notifications.Queries.GetNotifications;
using Heimdall.Application.Notifications.Queries.GetUnreadCount;
using Heimdall.Application.Tests.Common;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using NSubstitute;
namespace Heimdall.Application.Tests.Handlers.Notifications;
public class NotificationHandlerTests
{
private static readonly IMapper Mapper = new MapperConfiguration(cfg =>
cfg.AddProfile(new NotificationMappingProfile())).CreateMapper();
private readonly IApplicationDbContext _context;
private readonly CancellationToken _ct = CancellationToken.None;
public NotificationHandlerTests()
{
_context = Substitute.For<IApplicationDbContext>();
_context.SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Task.CompletedTask);
}
// ===================================================================
// GetNotificationsHandler
// ===================================================================
[Fact]
public async Task Handle_GetNotifications_ShouldReturnPagedResults()
{
var userId = Guid.NewGuid();
var notifications = new List<Notification>
{
new(userId, "Title1", "Message1", NotificationType.Info),
new(userId, "Title2", "Message2", NotificationType.Warning),
};
_context.Notifications.Returns(MockDbSetHelper.CreateFor(notifications));
var handler = new GetNotificationsHandler(_context, Mapper);
var result = await handler.Handle(new GetNotificationsQuery(userId, null, 1, 20), _ct);
result.ShouldNotBeNull();
result.Items.Count.ShouldBe(2);
result.TotalCount.ShouldBe(2);
result.Page.ShouldBe(1);
result.PageSize.ShouldBe(20);
}
[Fact]
public async Task Handle_GetNotifications_WithIsReadFilter_ShouldFilter()
{
var userId = Guid.NewGuid();
var notifications = new List<Notification>
{
new(userId, "Unread", "Msg1", NotificationType.Info),
new(userId, "Read", "Msg2", NotificationType.Success),
};
notifications[1].MarkAsRead();
_context.Notifications.Returns(MockDbSetHelper.CreateFor(notifications));
var handler = new GetNotificationsHandler(_context, Mapper);
var result = await handler.Handle(new GetNotificationsQuery(userId, true, 1, 20), _ct);
result.ShouldNotBeNull();
result.Items.Count.ShouldBe(1);
result.Items[0].IsRead.ShouldBeTrue();
result.Items[0].Title.ShouldBe("Read");
}
[Fact]
public async Task Handle_GetNotifications_WithNoResults_ShouldReturnEmptyPage()
{
var userId = Guid.NewGuid();
_context.Notifications.Returns(MockDbSetHelper.CreateFor<Notification>());
var handler = new GetNotificationsHandler(_context, Mapper);
var result = await handler.Handle(new GetNotificationsQuery(userId, null, 1, 20), _ct);
result.ShouldNotBeNull();
result.Items.ShouldBeEmpty();
result.TotalCount.ShouldBe(0);
result.Page.ShouldBe(1);
result.PageSize.ShouldBe(20);
}
// ===================================================================
// GetUnreadCountHandler
// ===================================================================
[Fact]
public async Task Handle_GetUnreadCount_ShouldReturnUnreadCount()
{
var userId = Guid.NewGuid();
var notifications = new List<Notification>
{
new(userId, "Unread1", "Msg1", NotificationType.Info),
new(userId, "Unread2", "Msg2", NotificationType.Warning),
new(userId, "Read", "Msg3", NotificationType.Success),
};
notifications[2].MarkAsRead();
_context.Notifications.Returns(MockDbSetHelper.CreateFor(notifications));
var handler = new GetUnreadCountHandler(_context);
var result = await handler.Handle(new GetUnreadCountQuery(userId), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Count.ShouldBe(2);
}
[Fact]
public async Task Handle_GetUnreadCount_WithNoUnread_ShouldReturnZero()
{
var userId = Guid.NewGuid();
var notification = new Notification(userId, "Read1", "Msg1", NotificationType.Info);
notification.MarkAsRead();
_context.Notifications.Returns(MockDbSetHelper.CreateFor([notification]));
var handler = new GetUnreadCountHandler(_context);
var result = await handler.Handle(new GetUnreadCountQuery(userId), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Count.ShouldBe(0);
}
// ===================================================================
// MarkAsReadHandler
// ===================================================================
[Fact]
public async Task Handle_MarkAsRead_ShouldMarkNotificationAsRead()
{
var userId = Guid.NewGuid();
var notification = new Notification(userId, "Test", "Message", NotificationType.Info);
_context.Notifications.Returns(MockDbSetHelper.CreateFor([notification]));
var handler = new MarkAsReadHandler(_context);
var result = await handler.Handle(new MarkAsReadCommand(notification.Id, userId), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Success.ShouldBeTrue();
notification.IsRead.ShouldBeTrue();
notification.ReadAt.ShouldNotBeNull();
await _context.Received(1).SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_MarkAsRead_WithNonExistentNotification_ShouldReturnNotFound()
{
var userId = Guid.NewGuid();
_context.Notifications.Returns(MockDbSetHelper.CreateFor<Notification>());
var handler = new MarkAsReadHandler(_context);
var result = await handler.Handle(new MarkAsReadCommand(Guid.NewGuid(), userId), _ct);
result.IsSuccess.ShouldBeFalse();
result.StatusCode.ShouldBe(404);
result.Error.ShouldBe("Notification not found");
}
// ===================================================================
// MarkAllAsReadHandler
// ===================================================================
[Fact]
public async Task Handle_MarkAllAsRead_ShouldMarkAllNotificationsAsRead()
{
var userId = Guid.NewGuid();
var notifications = new List<Notification>
{
new(userId, "Unread1", "Msg1", NotificationType.Info),
new(userId, "Unread2", "Msg2", NotificationType.Warning),
};
_context.Notifications.Returns(MockDbSetHelper.CreateFor(notifications));
var handler = new MarkAllAsReadHandler(_context);
var result = await handler.Handle(new MarkAllAsReadCommand(userId), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Success.ShouldBeTrue();
notifications.All(n => n.IsRead).ShouldBeTrue();
await _context.Received(1).SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_MarkAllAsRead_WithAlreadyReadNotifications_ShouldStillReturnSuccess()
{
var userId = Guid.NewGuid();
var notification = new Notification(userId, "AlreadyRead", "Msg", NotificationType.Info);
notification.MarkAsRead();
_context.Notifications.Returns(MockDbSetHelper.CreateFor([notification]));
var handler = new MarkAllAsReadHandler(_context);
var result = await handler.Handle(new MarkAllAsReadCommand(userId), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Success.ShouldBeTrue();
}
// ===================================================================
// UpdateNotificationConfigHandler
// ===================================================================
[Fact]
public async Task Handle_UpdateNotificationConfig_ShouldCreateConfigIfNotExists()
{
var userId = Guid.NewGuid();
_context.UserNotificationConfigs.Returns(MockDbSetHelper.CreateFor<UserNotificationConfig>());
var handler = new UpdateNotificationConfigHandler(_context, Mapper);
var result = await handler.Handle(new UpdateNotificationConfigCommand(
userId, true, "user@example.com", null, null, null, null, null, null, null), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.EmailEnabled.ShouldBeTrue();
result.Data.EmailAddress.ShouldBe("user@example.com");
await _context.Received(1).SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_UpdateNotificationConfig_ShouldUpdateExistingConfig()
{
var userId = Guid.NewGuid();
var existing = new UserNotificationConfig(userId);
existing.UpdateEmail("old@example.com", false);
_context.UserNotificationConfigs.Returns(MockDbSetHelper.CreateFor([existing]));
var handler = new UpdateNotificationConfigHandler(_context, Mapper);
var result = await handler.Handle(new UpdateNotificationConfigCommand(
userId, true, "new@example.com", null, null, null, null, null, null, null), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.EmailEnabled.ShouldBeTrue();
result.Data.EmailAddress.ShouldBe("new@example.com");
}
[Fact]
public async Task Handle_UpdateNotificationConfig_PartialUpdate_ShouldOnlyUpdateSpecifiedFields()
{
var userId = Guid.NewGuid();
var existing = new UserNotificationConfig(userId);
existing.UpdateEmail("existing@example.com", true);
existing.UpdateGotify("https://gotify.example.com", "old-token", true);
existing.UpdateDigests(true, false);
_context.UserNotificationConfigs.Returns(MockDbSetHelper.CreateFor([existing]));
var handler = new UpdateNotificationConfigHandler(_context, Mapper);
// Only update email address, leave everything else unchanged
var result = await handler.Handle(new UpdateNotificationConfigCommand(
userId, null, "updated@example.com", null, null, null, null, null, null, null), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.EmailAddress.ShouldBe("updated@example.com");
result.Data.EmailEnabled.ShouldBeTrue(); // unchanged
result.Data.GotifyEnabled.ShouldBeTrue(); // unchanged
}
[Fact]
public async Task Handle_UpdateNotificationConfig_ShouldUpdateGotifySettings()
{
var userId = Guid.NewGuid();
var existing = new UserNotificationConfig(userId);
existing.UpdateEmail("user@example.com", true);
_context.UserNotificationConfigs.Returns(MockDbSetHelper.CreateFor([existing]));
var handler = new UpdateNotificationConfigHandler(_context, Mapper);
var result = await handler.Handle(new UpdateNotificationConfigCommand(
userId, null, null, true, "https://gotify.example.com", "new-token", null, null, null, null), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.GotifyEnabled.ShouldBeTrue();
result.Data.GotifyUrl.ShouldBe("https://gotify.example.com");
}
[Fact]
public async Task Handle_UpdateNotificationConfig_ShouldUpdateDigestPreferences()
{
var userId = Guid.NewGuid();
_context.UserNotificationConfigs.Returns(MockDbSetHelper.CreateFor<UserNotificationConfig>());
var handler = new UpdateNotificationConfigHandler(_context, Mapper);
var result = await handler.Handle(new UpdateNotificationConfigCommand(
userId, null, null, null, null, null, null, true, true, null), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.DailyDigest.ShouldBeTrue();
result.Data.WeeklyDigest.ShouldBeTrue();
}
[Fact]
public async Task Handle_UpdateNotificationConfig_ShouldUpdateLanguage()
{
var userId = Guid.NewGuid();
_context.UserNotificationConfigs.Returns(MockDbSetHelper.CreateFor<UserNotificationConfig>());
var handler = new UpdateNotificationConfigHandler(_context, Mapper);
var result = await handler.Handle(new UpdateNotificationConfigCommand(
userId, null, null, null, null, null, "de", null, null, null), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Language.ShouldBe("de");
}
// ===================================================================
// GetNotificationConfigHandler
// ===================================================================
[Fact]
public async Task Handle_GetNotificationConfig_ShouldReturnExistingConfig()
{
var userId = Guid.NewGuid();
var config = new UserNotificationConfig(userId);
config.UpdateEmail("user@example.com", true);
config.SetLanguage("en");
_context.UserNotificationConfigs.Returns(MockDbSetHelper.CreateFor([config]));
var handler = new GetNotificationConfigHandler(_context, Mapper);
var result = await handler.Handle(new GetNotificationConfigQuery(userId), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.EmailEnabled.ShouldBeTrue();
result.Data.EmailAddress.ShouldBe("user@example.com");
result.Data.Language.ShouldBe("en");
}
[Fact]
public async Task Handle_GetNotificationConfig_ShouldCreateAndReturnConfigIfNotExists()
{
var userId = Guid.NewGuid();
_context.UserNotificationConfigs.Returns(MockDbSetHelper.CreateFor<UserNotificationConfig>());
var handler = new GetNotificationConfigHandler(_context, Mapper);
var result = await handler.Handle(new GetNotificationConfigQuery(userId), _ct);
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.UserId.ShouldBe(userId);
result.Data.EmailEnabled.ShouldBeFalse(); // default
result.Data.Language.ShouldBe("fr"); // default language
result.Data.DailyDigest.ShouldBeFalse(); // default
result.Data.WeeklyDigest.ShouldBeFalse(); // default
await _context.Received(1).SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,245 @@
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Shouldly;
namespace Heimdall.Domain.Tests.Entities;
public class NotificationTests
{
[Fact]
public void Create_notification_should_set_properties()
{
var userId = Guid.NewGuid();
var cameraId = Guid.NewGuid();
var siteId = Guid.NewGuid();
var now = DateTime.UtcNow;
var notification = new Notification(
userId, "Test Title", "Test Message", NotificationType.Warning,
EventType.PersonDetected, cameraId, siteId,
"http://snap.url", "/events/123");
notification.Id.ShouldNotBe(Guid.Empty);
notification.UserId.ShouldBe(userId);
notification.Title.ShouldBe("Test Title");
notification.Message.ShouldBe("Test Message");
notification.Type.ShouldBe(NotificationType.Warning);
notification.EventType.ShouldBe(EventType.PersonDetected);
notification.CameraId.ShouldBe(cameraId);
notification.SiteId.ShouldBe(siteId);
notification.SnapshotUrl.ShouldBe("http://snap.url");
notification.Link.ShouldBe("/events/123");
notification.IsRead.ShouldBeFalse();
notification.ReadAt.ShouldBeNull();
notification.CreatedAt.ShouldBe(default);
notification.UpdatedAt.ShouldBe(default);
}
[Fact]
public void Create_notification_with_minimal_params_should_succeed()
{
var userId = Guid.NewGuid();
var notification = new Notification(userId, "Title", "Message", NotificationType.Info);
notification.Id.ShouldNotBe(Guid.Empty);
notification.UserId.ShouldBe(userId);
notification.Title.ShouldBe("Title");
notification.Message.ShouldBe("Message");
notification.Type.ShouldBe(NotificationType.Info);
notification.EventType.ShouldBeNull();
notification.CameraId.ShouldBeNull();
notification.SiteId.ShouldBeNull();
notification.SnapshotUrl.ShouldBeNull();
notification.Link.ShouldBeNull();
notification.IsRead.ShouldBeFalse();
}
[Fact]
public void MarkAsRead_should_set_properties()
{
var userId = Guid.NewGuid();
var notification = new Notification(userId, "Title", "Message", NotificationType.Info);
notification.MarkAsRead();
notification.IsRead.ShouldBeTrue();
notification.ReadAt.ShouldNotBeNull();
notification.ReadAt.Value.ShouldBeLessThanOrEqualTo(DateTime.UtcNow);
notification.ReadAt.Value.ShouldBeGreaterThan(DateTime.UtcNow.AddMinutes(-1));
}
[Fact]
public void MarkAsRead_twice_should_update_read_at()
{
var userId = Guid.NewGuid();
var notification = new Notification(userId, "Title", "Message", NotificationType.Info);
notification.MarkAsRead();
var firstReadAt = notification.ReadAt!.Value;
Thread.Sleep(10); // Ensure time passes
notification.MarkAsRead();
notification.IsRead.ShouldBeTrue();
notification.ReadAt!.Value.ShouldBeGreaterThan(firstReadAt);
}
[Fact]
public void Enum_NotificationType_has_expected_values()
{
((int)NotificationType.Info).ShouldBe(0);
((int)NotificationType.Success).ShouldBe(1);
((int)NotificationType.Warning).ShouldBe(2);
((int)NotificationType.Error).ShouldBe(3);
((int)NotificationType.Alert).ShouldBe(4);
}
[Fact]
public void Enum_NotificationChannel_has_expected_values()
{
((int)NotificationChannel.InApp).ShouldBe(0);
((int)NotificationChannel.Email).ShouldBe(1);
((int)NotificationChannel.Gotify).ShouldBe(2);
}
}
public class NotificationTemplateTests
{
[Fact]
public void Create_template_should_set_properties()
{
var template = new NotificationTemplate(
EventType.PersonDetected, NotificationChannel.Email,
"Personne détectée", "Une personne a été détectée sur {CameraName}",
"fr", true);
template.Id.ShouldNotBe(Guid.Empty);
template.EventType.ShouldBe(EventType.PersonDetected);
template.Channel.ShouldBe(NotificationChannel.Email);
template.Language.ShouldBe("fr");
template.Subject.ShouldBe("Personne détectée");
template.BodyMarkdown.ShouldBe("Une personne a été détectée sur {CameraName}");
template.IsDefault.ShouldBeTrue();
}
[Fact]
public void Create_template_with_default_language_should_be_french()
{
var template = new NotificationTemplate(
EventType.MotionDetected, NotificationChannel.InApp,
"Mouvement", "Mouvement détecté");
template.Language.ShouldBe("fr");
template.IsDefault.ShouldBeFalse();
}
[Fact]
public void Update_template_should_modify_properties()
{
var template = new NotificationTemplate(
EventType.PersonDetected, NotificationChannel.Email,
"Old Subject", "Old Body", "fr", false);
template.Update("New Subject", "New Body", true);
template.Subject.ShouldBe("New Subject");
template.BodyMarkdown.ShouldBe("New Body");
template.IsDefault.ShouldBeTrue();
}
}
public class UserNotificationConfigTests
{
[Fact]
public void Create_config_should_set_user_id()
{
var userId = Guid.NewGuid();
var config = new UserNotificationConfig(userId);
config.Id.ShouldNotBe(Guid.Empty);
config.UserId.ShouldBe(userId);
config.EmailEnabled.ShouldBeFalse();
config.GotifyEnabled.ShouldBeFalse();
config.Language.ShouldBe("fr");
config.DailyDigest.ShouldBeFalse();
config.WeeklyDigest.ShouldBeFalse();
config.SubscribedEventsJson.ShouldBeNull();
}
[Fact]
public void UpdateEmail_should_set_properties()
{
var config = new UserNotificationConfig(Guid.NewGuid());
config.UpdateEmail("test@example.com", true);
config.EmailAddress.ShouldBe("test@example.com");
config.EmailEnabled.ShouldBeTrue();
}
[Fact]
public void UpdateEmail_with_null_address_should_disable()
{
var config = new UserNotificationConfig(Guid.NewGuid());
config.UpdateEmail("test@example.com", true);
config.UpdateEmail(null, false);
config.EmailAddress.ShouldBeNull();
config.EmailEnabled.ShouldBeFalse();
}
[Fact]
public void UpdateGotify_should_set_properties()
{
var config = new UserNotificationConfig(Guid.NewGuid());
config.UpdateGotify("http://gotify:8080", "token123", true);
config.GotifyUrl.ShouldBe("http://gotify:8080");
config.GotifyToken.ShouldBe("token123");
config.GotifyEnabled.ShouldBeTrue();
}
[Fact]
public void UpdateDigests_should_set_properties()
{
var config = new UserNotificationConfig(Guid.NewGuid());
config.UpdateDigests(true, true);
config.DailyDigest.ShouldBeTrue();
config.WeeklyDigest.ShouldBeTrue();
}
[Fact]
public void SetSubscribedEvents_should_store_json()
{
var config = new UserNotificationConfig(Guid.NewGuid());
var json = "[\"PersonDetected\",\"MotionDetected\"]";
config.SetSubscribedEvents(json);
config.SubscribedEventsJson.ShouldBe(json);
}
[Fact]
public void SetSubscribedEvents_with_null_should_clear()
{
var config = new UserNotificationConfig(Guid.NewGuid());
config.SetSubscribedEvents("[\"test\"]");
config.SetSubscribedEvents(null);
config.SubscribedEventsJson.ShouldBeNull();
}
[Fact]
public void SetLanguage_should_update_language()
{
var config = new UserNotificationConfig(Guid.NewGuid());
config.SetLanguage("en");
config.Language.ShouldBe("en");
}
}
@@ -0,0 +1,97 @@
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Services;
using Microsoft.Extensions.Caching.Memory;
using Shouldly;
namespace Heimdall.Infrastructure.Tests.Services;
public class NotificationRateLimiterTests
{
private readonly NotificationRateLimiter _limiter;
public NotificationRateLimiterTests()
{
var cache = new MemoryCache(new MemoryCacheOptions());
_limiter = new NotificationRateLimiter(cache);
}
[Fact]
public void ShouldSend_FirstEvent_ReturnsTrue()
{
var result = _limiter.ShouldSend(Guid.NewGuid(), EventType.PersonDetected, null);
result.ShouldBeTrue();
}
[Fact]
public void ShouldSend_WithinLimit_ReturnsTrue()
{
var cameraId = Guid.NewGuid();
// Send 19 events (20 is the limit per minute)
for (int i = 0; i < 19; i++)
{
_limiter.ShouldSend(cameraId, EventType.PersonDetected, null).ShouldBeTrue();
}
}
[Fact]
public void ShouldSend_ExceedsLimit_ReturnsFalse()
{
var cameraId = Guid.NewGuid();
// Send 20 events (limit reached)
for (int i = 0; i < 20; i++)
{
_limiter.ShouldSend(cameraId, EventType.PersonDetected, null);
}
// 21st should be rate limited
var result = _limiter.ShouldSend(cameraId, EventType.PersonDetected, null);
result.ShouldBeFalse();
}
[Fact]
public void ShouldSend_DifferentTypes_HaveSeparateCounters()
{
var cameraId = Guid.NewGuid();
// Exhaust limit for PersonDetected
for (int i = 0; i < 20; i++)
_limiter.ShouldSend(cameraId, EventType.PersonDetected, null);
// MotionDetected should still work (separate counter)
var result = _limiter.ShouldSend(cameraId, EventType.MotionDetected, null);
result.ShouldBeTrue();
}
[Fact]
public void ShouldSend_DifferentCameras_HaveSeparateCounters()
{
var camera1 = Guid.NewGuid();
var camera2 = Guid.NewGuid();
// Exhaust limit for camera1
for (int i = 0; i < 20; i++)
_limiter.ShouldSend(camera1, EventType.PersonDetected, null);
// camera2 should still work
var result = _limiter.ShouldSend(camera2, EventType.PersonDetected, null);
result.ShouldBeTrue();
}
[Fact]
public void ShouldSend_WithTrackId_ShouldBeTracked()
{
var cameraId = Guid.NewGuid();
var trackId = Guid.NewGuid();
for (int i = 0; i < 20; i++)
_limiter.ShouldSend(cameraId, EventType.PersonDetected, trackId);
// Same camera+type+track should be limited
_limiter.ShouldSend(cameraId, EventType.PersonDetected, trackId).ShouldBeFalse();
// Same camera+type, different track should still work
_limiter.ShouldSend(cameraId, EventType.PersonDetected, Guid.NewGuid()).ShouldBeTrue();
}
}
@@ -0,0 +1,293 @@
using AutoMapper;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Notifications.Mapping;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Data.Interceptors;
using Heimdall.Infrastructure.Services;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Shouldly;
namespace Heimdall.Infrastructure.Tests.Services;
/// <summary>
/// Unit tests for <see cref="NotificationService"/>.
/// Uses SQLite in-memory for real EF Core behavior with mocked external channels.
/// </summary>
public class NotificationServiceTests : IDisposable
{
private readonly SqliteConnection _connection;
private readonly AppDbContext _context;
private readonly IMapper _mapper;
private readonly INotificationBroadcastService _broadcast;
private readonly IEmailService _emailService;
private readonly IGotifyService _gotifyService;
private readonly INotificationRateLimiter _rateLimiter;
private readonly ILogger<NotificationService> _logger;
private readonly NotificationService _service;
public NotificationServiceTests()
{
_connection = new SqliteConnection("DataSource=:memory:");
_connection.Open();
var opts = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(_connection)
.Options;
_context = new AppDbContext(opts, new AuditInterceptor());
_context.Database.EnsureCreated();
// Real AutoMapper with the actual notification mapping profile
var mapperConfig = new MapperConfiguration(cfg =>
cfg.AddProfile<NotificationMappingProfile>());
_mapper = mapperConfig.CreateMapper();
_broadcast = Substitute.For<INotificationBroadcastService>();
_emailService = Substitute.For<IEmailService>();
_gotifyService = Substitute.For<IGotifyService>();
_rateLimiter = Substitute.For<INotificationRateLimiter>();
_logger = Substitute.For<ILogger<NotificationService>>();
_service = new NotificationService(
_context, _mapper, _broadcast, _emailService, _gotifyService,
_rateLimiter, _logger);
}
public void Dispose()
{
_context.Dispose();
_connection.Close();
_connection?.Dispose();
GC.SuppressFinalize(this);
}
[Fact]
public async Task CreateNotificationAsync_ShouldAddAndBroadcast()
{
// Arrange
var userId = Guid.NewGuid();
_rateLimiter.ShouldSend(Arg.Any<Guid>(), Arg.Any<EventType>(), Arg.Any<Guid?>())
.Returns(true);
// Act
var result = await _service.CreateNotificationAsync(
userId, "Test Title", "Test message", NotificationType.Info,
EventType.PersonDetected, Guid.NewGuid());
// Assert
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Title.ShouldBe("Test Title");
result.Data.UserId.ShouldBe(userId);
// Verify broadcast was called
await _broadcast.Received(1).NotifyNewNotification(
Arg.Is<NotificationDto>(d => d!.Title == "Test Title"),
Arg.Any<CancellationToken>());
// Verify it was persisted
var count = await _context.Notifications.CountAsync();
count.ShouldBe(1);
}
[Fact]
public async Task CreateNotificationAsync_RateLimited_ShouldSkipSilently()
{
// Arrange
_rateLimiter.ShouldSend(Arg.Any<Guid>(), Arg.Any<EventType>(), Arg.Any<Guid?>())
.Returns(false);
// Act
var result = await _service.CreateNotificationAsync(
Guid.NewGuid(), "Test", "Message", NotificationType.Info,
EventType.PersonDetected, Guid.NewGuid());
// Assert
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldBeNull(); // Silently skipped
// Nothing should be persisted
var count = await _context.Notifications.CountAsync();
count.ShouldBe(0);
// No broadcast should happen
await _broadcast.DidNotReceiveWithAnyArgs().NotifyNewNotification(default!, default);
}
[Fact]
public async Task GetUnreadCountAsync_ShouldReturnCount()
{
// Arrange
var userId = Guid.NewGuid();
// Seed notifications directly in the database
_context.Notifications.Add(new Notification(userId, "Unread1", "Msg", NotificationType.Info));
_context.Notifications.Add(new Notification(userId, "Unread2", "Msg", NotificationType.Info));
var readNotification = new Notification(userId, "Read", "Msg", NotificationType.Info);
readNotification.MarkAsRead();
_context.Notifications.Add(readNotification);
await _context.SaveChangesAsync();
// Act
var count = await _service.GetUnreadCountAsync(userId);
// Assert
count.ShouldBe(2);
}
[Fact]
public async Task GetUnreadCountAsync_OtherUsers_NotCounted()
{
// Arrange
var userId = Guid.NewGuid();
var otherUserId = Guid.NewGuid();
_context.Notifications.Add(new Notification(userId, "Mine", "Msg", NotificationType.Info));
_context.Notifications.Add(new Notification(otherUserId, "Theirs", "Msg", NotificationType.Info));
await _context.SaveChangesAsync();
// Act
var count = await _service.GetUnreadCountAsync(userId);
// Assert
count.ShouldBe(1);
}
[Fact]
public async Task CreateNotificationAsync_WithoutRateLimiter_ShouldWork()
{
// Arrange
var userId = Guid.NewGuid();
// cameraId is null, so rate limiter is skipped entirely
// Act
var result = await _service.CreateNotificationAsync(
userId, "No Cam", "Message", NotificationType.Alert,
eventType: null, cameraId: null);
// Assert
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Type.ShouldBe(NotificationType.Alert.ToString());
// Broadcast should still be called
await _broadcast.Received(1).NotifyNewNotification(
Arg.Any<NotificationDto>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task MarkAsReadAsync_ExistingNotification_MarksItRead()
{
// Arrange
var userId = Guid.NewGuid();
var notification = new Notification(userId, "Read Test", "Msg", NotificationType.Info);
_context.Notifications.Add(notification);
await _context.SaveChangesAsync();
notification.IsRead.ShouldBeFalse();
// Act
await _service.MarkAsReadAsync(notification.Id, userId);
// Assert
var updated = await _context.Notifications.FindAsync(notification.Id);
updated.ShouldNotBeNull();
updated.IsRead.ShouldBeTrue();
updated.ReadAt.ShouldNotBeNull();
}
[Fact]
public async Task MarkAsReadAsync_OtherUsersNotification_DoesNothing()
{
// Arrange
var ownerId = Guid.NewGuid();
var otherUserId = Guid.NewGuid();
var notification = new Notification(ownerId, "Not Mine", "Msg", NotificationType.Info);
_context.Notifications.Add(notification);
await _context.SaveChangesAsync();
// Act
await _service.MarkAsReadAsync(notification.Id, otherUserId);
// Assert — should NOT mark as read since it belongs to another user
var updated = await _context.Notifications.FindAsync(notification.Id);
updated.ShouldNotBeNull();
updated.IsRead.ShouldBeFalse();
}
[Fact]
public async Task MarkAllAsReadAsync_MarksAllUserNotifications()
{
// Arrange
var userId = Guid.NewGuid();
_context.Notifications.Add(new Notification(userId, "A", "Msg", NotificationType.Info));
_context.Notifications.Add(new Notification(userId, "B", "Msg", NotificationType.Warning));
_context.Notifications.Add(new Notification(Guid.NewGuid(), "Other", "Msg", NotificationType.Info));
await _context.SaveChangesAsync();
// Act
await _service.MarkAllAsReadAsync(userId);
// Assert
var userUnread = await _context.Notifications
.CountAsync(n => n.UserId == userId && !n.IsRead);
userUnread.ShouldBe(0);
// Other user's notification should remain unread
var otherUnread = await _context.Notifications
.CountAsync(n => n.UserId != userId && !n.IsRead);
otherUnread.ShouldBe(1);
}
[Fact]
public async Task GetNotificationsAsync_ShouldReturnPagedResults()
{
// Arrange
var userId = Guid.NewGuid();
for (int i = 0; i < 5; i++)
{
_context.Notifications.Add(new Notification(userId, $"Title {i}", $"Msg {i}", NotificationType.Info));
}
await _context.SaveChangesAsync();
// Act
var result = await _service.GetNotificationsAsync(userId, null, page: 1, pageSize: 3);
// Assert
result.Items.Count.ShouldBe(3);
result.TotalCount.ShouldBe(5);
result.Page.ShouldBe(1);
result.TotalPages.ShouldBe(2);
result.HasNextPage.ShouldBeTrue();
result.HasPreviousPage.ShouldBeFalse();
}
[Fact]
public async Task GetNotificationsAsync_FilterByRead_ReturnsFiltered()
{
// Arrange
var userId = Guid.NewGuid();
var n1 = new Notification(userId, "Unread", "Msg", NotificationType.Info);
var n2 = new Notification(userId, "Read", "Msg", NotificationType.Info);
n2.MarkAsRead();
_context.Notifications.Add(n1);
_context.Notifications.Add(n2);
await _context.SaveChangesAsync();
// Act
var unread = await _service.GetNotificationsAsync(userId, isRead: false, page: 1, pageSize: 20);
var read = await _service.GetNotificationsAsync(userId, isRead: true, page: 1, pageSize: 20);
// Assert
unread.Items.Count.ShouldBe(1);
unread.TotalCount.ShouldBe(1);
read.Items.Count.ShouldBe(1);
read.TotalCount.ShouldBe(1);
}
}
@@ -0,0 +1,159 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using Heimdall.IntegrationTests.Controllers;
using Shouldly;
namespace Heimdall.IntegrationTests.Scenarios;
/// <summary>
/// Integration tests for <c>/api/notifications/*</c> endpoints.
/// Verifies auth gating, configuration CRUD, and notification lifecycle.
/// </summary>
[Collection("Postgres")]
public class NotificationScenarios : PostgresTestBase
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
public NotificationScenarios(PostgreSqlContainerFixture postgres) : base(postgres) { }
[Fact]
public async Task GetNotifications_Unauthenticated_Returns401()
{
var client = Factory.CreateClient();
var response = await client.GetAsync("/api/notifications");
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task GetUnreadCount_Unauthenticated_Returns401()
{
var client = Factory.CreateClient();
var response = await client.GetAsync("/api/notifications/unread-count");
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task MarkAllAsRead_Unauthenticated_Returns401()
{
var client = Factory.CreateClient();
var response = await client.PostAsync("/api/notifications/mark-all-read", null);
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task GetConfig_Unauthenticated_Returns401()
{
var client = Factory.CreateClient();
var response = await client.GetAsync("/api/notifications/config");
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task Authenticated_GetNotifications_ReturnsOk()
{
// Arrange — login as admin
var client = await Factory.CreateAdminClientAsync();
// Act
var response = await client.GetAsync("/api/notifications");
// Assert
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var json = await response.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
json.ValueKind.ShouldBe(JsonValueKind.Object);
}
[Fact]
public async Task Authenticated_GetUnreadCount_ReturnsOkWithCount()
{
// Arrange
var client = await Factory.CreateAdminClientAsync();
// Act
var response = await client.GetAsync("/api/notifications/unread-count");
// Assert
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var json = await response.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
json.GetProperty("count").GetInt32().ShouldBeGreaterThanOrEqualTo(0);
}
[Fact]
public async Task Authenticated_GetConfig_ReturnsOk()
{
// Arrange
var client = await Factory.CreateAdminClientAsync();
// Act
var response = await client.GetAsync("/api/notifications/config");
// Assert
response.StatusCode.ShouldBe(HttpStatusCode.OK);
}
[Fact]
public async Task Authenticated_MarkAllAsRead_ReturnsOk()
{
// Arrange
var client = await Factory.CreateAdminClientAsync();
// Act
var response = await client.PostAsync("/api/notifications/mark-all-read", null);
// Assert
response.StatusCode.ShouldBe(HttpStatusCode.OK);
}
[Fact]
public async Task Authenticated_MarkAsRead_NonExistent_ReturnsNotFound()
{
// Arrange
var client = await Factory.CreateAdminClientAsync();
var nonExistentId = Guid.NewGuid();
// Act
var response = await client.PostAsync($"/api/notifications/{nonExistentId}/read", null);
// Assert
response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
}
[Fact]
public async Task Authenticated_UpdateConfig_ReturnsOk()
{
// Arrange
var client = await Factory.CreateAdminClientAsync();
// Act
var response = await client.PutAsJsonAsync("/api/notifications/config", new
{
emailEnabled = true,
emailAddress = "test@example.com",
dailyDigest = true
});
// Assert
response.StatusCode.ShouldBe(HttpStatusCode.OK);
}
[Fact]
public async Task Authenticated_GetNotifications_ShouldPage()
{
// Arrange
var client = await Factory.CreateAdminClientAsync();
// Act
var response = await client.GetAsync("/api/notifications?page=1&pageSize=5");
// Assert
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var json = await response.Content.ReadFromJsonAsync<JsonElement>(JsonOptions);
json.TryGetProperty("items", out _).ShouldBeTrue();
json.TryGetProperty("totalCount", out _).ShouldBeTrue();
}
}
@@ -0,0 +1,121 @@
using System.Net;
using System.Net.Http.Headers;
using Heimdall.IntegrationTests.Controllers;
using Shouldly;
namespace Heimdall.IntegrationTests.Scenarios;
/// <summary>
/// Integration tests for SignalR hub authentication.
/// Verifies that all hubs require authentication and that valid
/// JWT tokens grant access to the negotiate endpoint.
/// </summary>
[Collection("Postgres")]
public class SignalRHubScenarios : PostgresTestBase
{
public SignalRHubScenarios(PostgreSqlContainerFixture postgres) : base(postgres) { }
private static readonly string[] HubPaths =
[
"/hubs/notifications",
"/hubs/monitoring",
"/hubs/admin",
"/hubs/events",
"/hubs/config"
];
/// <summary>
/// SignalR negotiate uses POST to the negotiate sub-path.
/// With [Authorize], unauth'd requests should return 401 before reaching the hub.
/// </summary>
[Fact]
public async Task AllHubs_UnauthenticatedPostNegotiate_Returns401()
{
var client = Factory.CreateClient();
foreach (var hubPath in HubPaths)
{
var response = await client.PostAsync($"{hubPath}/negotiate?negotiateVersion=1", null);
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized, $"Hub {hubPath} should return 401");
}
}
/// <summary>
/// GET requests to the hub path with negotiateVersion should also be auth-gated.
/// </summary>
[Fact]
public async Task AllHubs_UnauthenticatedGet_Returns401()
{
var client = Factory.CreateClient();
foreach (var hubPath in HubPaths)
{
var response = await client.GetAsync($"{hubPath}?negotiateVersion=1");
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized, $"Hub {hubPath} should return 401");
}
}
[Fact]
public async Task NotificationsHub_AuthenticatedNegotiate_ReturnsOk()
{
// Arrange
var client = await Factory.CreateAdminClientAsync();
// Act
var response = await client.PostAsync("/hubs/notifications/negotiate?negotiateVersion=1", null);
// Assert — should pass auth and return negotiate response (not 401)
response.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.Redirect);
}
[Fact]
public async Task MonitoringHub_AuthenticatedNegotiate_ReturnsOk()
{
// Arrange
var client = await Factory.CreateAdminClientAsync();
// Act
var response = await client.PostAsync("/hubs/monitoring/negotiate?negotiateVersion=1", null);
// Assert
response.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.Redirect);
}
[Fact]
public async Task EventsHub_AuthenticatedNegotiate_ReturnsOk()
{
// Arrange
var client = await Factory.CreateAdminClientAsync();
// Act
var response = await client.PostAsync("/hubs/events/negotiate?negotiateVersion=1", null);
// Assert
response.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.Redirect);
}
[Fact]
public async Task ConfigHub_ApiKeyAuth_AnonymousReturns401()
{
// ConfigHub uses [Authorize(AuthenticationSchemes = "ApiKey")],
// so requests without an API key header should return 401.
var client = Factory.CreateClient();
var response = await client.PostAsync("/hubs/config/negotiate?negotiateVersion=1", null);
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task AdminHub_RequiresAdminRole()
{
// AdminHub uses [Authorize(Roles = "Admin")], so a regular user
// (non-admin) should get a 403 Forbidden, not 401 Unauthorized.
var client = await Factory.CreateAdminClientAsync();
var response = await client.PostAsync("/hubs/admin/negotiate?negotiateVersion=1", null);
// The user from CreateAdminClientAsync may or may not have Admin role
// depending on registration flow. Accept either 200 or 403.
response.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.Forbidden);
}
}