diff --git a/coverage-report/Summary.txt b/coverage-report/Summary.txt new file mode 100644 index 0000000..5412f0c --- /dev/null +++ b/coverage-report/Summary.txt @@ -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 100% + Heimdall.Application.Behaviors.ValidationBehavior 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 0% + Heimdall.Application.Common.Mappings.MappingProfile 44.4% + Heimdall.Application.Common.ServiceResult 100% + Heimdall.Application.Common.ServiceResult 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 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 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.FBF3D522B2772D8B2CEF77394DAF1D7F439F9F4D4A6B2ABFE407DB51869AB636C__ArpPattern_0 4.9% + System.Text.RegularExpressions.Generated.FBF3D522B2772D8B2CEF77394DAF1D7F439F9F4D4A6B2ABFE407DB51869AB636C__CodecPattern_1 0% + System.Text.RegularExpressions.Generated.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 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% diff --git a/coverage-report2/Summary.txt b/coverage-report2/Summary.txt new file mode 100644 index 0000000..c378623 --- /dev/null +++ b/coverage-report2/Summary.txt @@ -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 100% + Heimdall.Application.Behaviors.ValidationBehavior 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 0% + Heimdall.Application.Common.Mappings.MappingProfile 44.4% + Heimdall.Application.Common.ServiceResult 100% + Heimdall.Application.Common.ServiceResult 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 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 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.FBF3D522B2772D8B2CEF77394DAF1D7F439F9F4D4A6B2ABFE407DB51869AB636C__ArpPattern_0 4.9% + System.Text.RegularExpressions.Generated.FBF3D522B2772D8B2CEF77394DAF1D7F439F9F4D4A6B2ABFE407DB51869AB636C__CodecPattern_1 0% + System.Text.RegularExpressions.Generated.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 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% diff --git a/coverage-report3/Summary.txt b/coverage-report3/Summary.txt new file mode 100644 index 0000000..22a6431 --- /dev/null +++ b/coverage-report3/Summary.txt @@ -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 100% + Heimdall.Application.Behaviors.ValidationBehavior 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 0% + Heimdall.Application.Common.Mappings.MappingProfile 44.4% + Heimdall.Application.Common.ServiceResult 100% + Heimdall.Application.Common.ServiceResult 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 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 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.FBF3D522B2772D8B2CEF77394DAF1D7F439F9F4D4A6B2ABFE407DB51869AB636C__ArpPattern_0 4.9% + System.Text.RegularExpressions.Generated.FBF3D522B2772D8B2CEF77394DAF1D7F439F9F4D4A6B2ABFE407DB51869AB636C__CodecPattern_1 0% + System.Text.RegularExpressions.Generated.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 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% diff --git a/docs/superpowers/plans/2026-07-26-signalr-notifications.md b/docs/superpowers/plans/2026-07-26-signalr-notifications.md new file mode 100644 index 0000000..6e6562b --- /dev/null +++ b/docs/superpowers/plans/2026-07-26-signalr-notifications.md @@ -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` 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` diff --git a/src/Heimdall.Application/Common/IApplicationDbContext.cs b/src/Heimdall.Application/Common/IApplicationDbContext.cs index 908ebcd..0fe8416 100644 --- a/src/Heimdall.Application/Common/IApplicationDbContext.cs +++ b/src/Heimdall.Application/Common/IApplicationDbContext.cs @@ -18,6 +18,11 @@ public interface IApplicationDbContext DbSet CameraDiscoveryResults { get; } DbSet CameraEvents { get; } DbSet DiscoveredStreams { get; } + + // Notification entities + DbSet Notifications { get; } + DbSet NotificationTemplates { get; } + DbSet UserNotificationConfigs { get; } DbSet Groups { get; } DbSet KnownFaces { get; } DbSet Persons { get; } diff --git a/src/Heimdall.Application/DTOs/NotificationDto.cs b/src/Heimdall.Application/DTOs/NotificationDto.cs new file mode 100644 index 0000000..fa7b18c --- /dev/null +++ b/src/Heimdall.Application/DTOs/NotificationDto.cs @@ -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? 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? SubscribedEvents +); + +public sealed record UnreadCountDto( + [property: JsonPropertyName("count")] int Count +); + +public sealed record MarkAsReadResponse( + [property: JsonPropertyName("success")] bool Success +); diff --git a/src/Heimdall.Application/Notifications/Commands/MarkAllAsRead/MarkAllAsReadCommand.cs b/src/Heimdall.Application/Notifications/Commands/MarkAllAsRead/MarkAllAsReadCommand.cs new file mode 100644 index 0000000..6d2225b --- /dev/null +++ b/src/Heimdall.Application/Notifications/Commands/MarkAllAsRead/MarkAllAsReadCommand.cs @@ -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>; diff --git a/src/Heimdall.Application/Notifications/Commands/MarkAllAsRead/MarkAllAsReadHandler.cs b/src/Heimdall.Application/Notifications/Commands/MarkAllAsRead/MarkAllAsReadHandler.cs new file mode 100644 index 0000000..ce01951 --- /dev/null +++ b/src/Heimdall.Application/Notifications/Commands/MarkAllAsRead/MarkAllAsReadHandler.cs @@ -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> +{ + private readonly IApplicationDbContext _context; + + public MarkAllAsReadHandler(IApplicationDbContext context) => _context = context; + + public async Task> 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.Success(new MarkAsReadResponse(true)); + } +} diff --git a/src/Heimdall.Application/Notifications/Commands/MarkAsRead/MarkAsReadCommand.cs b/src/Heimdall.Application/Notifications/Commands/MarkAsRead/MarkAsReadCommand.cs new file mode 100644 index 0000000..8f65782 --- /dev/null +++ b/src/Heimdall.Application/Notifications/Commands/MarkAsRead/MarkAsReadCommand.cs @@ -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>; diff --git a/src/Heimdall.Application/Notifications/Commands/MarkAsRead/MarkAsReadHandler.cs b/src/Heimdall.Application/Notifications/Commands/MarkAsRead/MarkAsReadHandler.cs new file mode 100644 index 0000000..ac133e8 --- /dev/null +++ b/src/Heimdall.Application/Notifications/Commands/MarkAsRead/MarkAsReadHandler.cs @@ -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> +{ + private readonly IApplicationDbContext _context; + + public MarkAsReadHandler(IApplicationDbContext context) => _context = context; + + public async Task> 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.NotFound("Notification not found"); + + notification.MarkAsRead(); + await _context.SaveChangesWithRetryAsync(ct: ct); + + return ServiceResult.Success(new MarkAsReadResponse(true)); + } +} diff --git a/src/Heimdall.Application/Notifications/Commands/UpdateConfig/UpdateNotificationConfigCommand.cs b/src/Heimdall.Application/Notifications/Commands/UpdateConfig/UpdateNotificationConfigCommand.cs new file mode 100644 index 0000000..d533aed --- /dev/null +++ b/src/Heimdall.Application/Notifications/Commands/UpdateConfig/UpdateNotificationConfigCommand.cs @@ -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? SubscribedEvents) : IRequest>; diff --git a/src/Heimdall.Application/Notifications/Commands/UpdateConfig/UpdateNotificationConfigHandler.cs b/src/Heimdall.Application/Notifications/Commands/UpdateConfig/UpdateNotificationConfigHandler.cs new file mode 100644 index 0000000..8af73de --- /dev/null +++ b/src/Heimdall.Application/Notifications/Commands/UpdateConfig/UpdateNotificationConfigHandler.cs @@ -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> +{ + private readonly IApplicationDbContext _context; + private readonly IMapper _mapper; + + public UpdateNotificationConfigHandler(IApplicationDbContext context, IMapper mapper) + { + _context = context; + _mapper = mapper; + } + + public async Task> 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.Success(_mapper.Map(config)); + } +} diff --git a/src/Heimdall.Application/Notifications/Mapping/NotificationMappingProfile.cs b/src/Heimdall.Application/Notifications/Mapping/NotificationMappingProfile.cs new file mode 100644 index 0000000..6977a6b --- /dev/null +++ b/src/Heimdall.Application/Notifications/Mapping/NotificationMappingProfile.cs @@ -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() + .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() + .ForMember(d => d.EventType, opt => opt.MapFrom(s => s.EventType.ToString())) + .ForMember(d => d.Channel, opt => opt.MapFrom(s => s.Channel.ToString())); + + CreateMap() + .ForCtorParam("SubscribedEvents", opt => opt.MapFrom(s => + s.SubscribedEventsJson != null + ? System.Text.Json.JsonSerializer.Deserialize>(s.SubscribedEventsJson) + : null)) + .ForMember(d => d.SubscribedEvents, opt => opt.MapFrom(s => + s.SubscribedEventsJson != null + ? System.Text.Json.JsonSerializer.Deserialize>(s.SubscribedEventsJson) + : null)); + } +} diff --git a/src/Heimdall.Application/Notifications/Queries/GetConfig/GetNotificationConfigHandler.cs b/src/Heimdall.Application/Notifications/Queries/GetConfig/GetNotificationConfigHandler.cs new file mode 100644 index 0000000..f9d7686 --- /dev/null +++ b/src/Heimdall.Application/Notifications/Queries/GetConfig/GetNotificationConfigHandler.cs @@ -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> +{ + private readonly IApplicationDbContext _context; + private readonly IMapper _mapper; + + public GetNotificationConfigHandler(IApplicationDbContext context, IMapper mapper) + { + _context = context; + _mapper = mapper; + } + + public async Task> 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.Success(_mapper.Map(config)); + } +} diff --git a/src/Heimdall.Application/Notifications/Queries/GetConfig/GetNotificationConfigQuery.cs b/src/Heimdall.Application/Notifications/Queries/GetConfig/GetNotificationConfigQuery.cs new file mode 100644 index 0000000..c69fc92 --- /dev/null +++ b/src/Heimdall.Application/Notifications/Queries/GetConfig/GetNotificationConfigQuery.cs @@ -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>; diff --git a/src/Heimdall.Application/Notifications/Queries/GetNotifications/GetNotificationsHandler.cs b/src/Heimdall.Application/Notifications/Queries/GetNotifications/GetNotificationsHandler.cs new file mode 100644 index 0000000..8f0913f --- /dev/null +++ b/src/Heimdall.Application/Notifications/Queries/GetNotifications/GetNotificationsHandler.cs @@ -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> +{ + private readonly IApplicationDbContext _context; + private readonly IMapper _mapper; + + public GetNotificationsHandler(IApplicationDbContext context, IMapper mapper) + { + _context = context; + _mapper = mapper; + } + + public async Task> 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(_mapper.ConfigurationProvider) + .ToListAsync(ct); + + return new PagedResult(items, totalCount, request.Page, request.PageSize); + } +} diff --git a/src/Heimdall.Application/Notifications/Queries/GetNotifications/GetNotificationsQuery.cs b/src/Heimdall.Application/Notifications/Queries/GetNotifications/GetNotificationsQuery.cs new file mode 100644 index 0000000..2fda9c8 --- /dev/null +++ b/src/Heimdall.Application/Notifications/Queries/GetNotifications/GetNotificationsQuery.cs @@ -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>; diff --git a/src/Heimdall.Application/Notifications/Queries/GetUnreadCount/GetUnreadCountHandler.cs b/src/Heimdall.Application/Notifications/Queries/GetUnreadCount/GetUnreadCountHandler.cs new file mode 100644 index 0000000..aa26b05 --- /dev/null +++ b/src/Heimdall.Application/Notifications/Queries/GetUnreadCount/GetUnreadCountHandler.cs @@ -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> +{ + private readonly IApplicationDbContext _context; + + public GetUnreadCountHandler(IApplicationDbContext context) => _context = context; + + public async Task> Handle(GetUnreadCountQuery request, CancellationToken ct) + { + var count = await _context.Notifications + .CountAsync(n => n.UserId == request.UserId && !n.IsRead, ct); + + return ServiceResult.Success(new UnreadCountDto(count)); + } +} diff --git a/src/Heimdall.Application/Notifications/Queries/GetUnreadCount/GetUnreadCountQuery.cs b/src/Heimdall.Application/Notifications/Queries/GetUnreadCount/GetUnreadCountQuery.cs new file mode 100644 index 0000000..91e676b --- /dev/null +++ b/src/Heimdall.Application/Notifications/Queries/GetUnreadCount/GetUnreadCountQuery.cs @@ -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>; diff --git a/src/Heimdall.Application/Services/IAdminBroadcastService.cs b/src/Heimdall.Application/Services/IAdminBroadcastService.cs new file mode 100644 index 0000000..c4254d1 --- /dev/null +++ b/src/Heimdall.Application/Services/IAdminBroadcastService.cs @@ -0,0 +1,12 @@ +namespace Heimdall.Application.Services; + +/// +/// Broadcasts admin-level configuration changes via SignalR. +/// +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); +} diff --git a/src/Heimdall.Application/Services/IEmailService.cs b/src/Heimdall.Application/Services/IEmailService.cs new file mode 100644 index 0000000..3995ff1 --- /dev/null +++ b/src/Heimdall.Application/Services/IEmailService.cs @@ -0,0 +1,6 @@ +namespace Heimdall.Application.Services; + +public interface IEmailService +{ + Task SendEmailAsync(string recipient, string subject, string bodyHtml, CancellationToken ct = default); +} diff --git a/src/Heimdall.Application/Services/IGotifyService.cs b/src/Heimdall.Application/Services/IGotifyService.cs new file mode 100644 index 0000000..435548f --- /dev/null +++ b/src/Heimdall.Application/Services/IGotifyService.cs @@ -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); +} diff --git a/src/Heimdall.Application/Services/IMonitoringBroadcastService.cs b/src/Heimdall.Application/Services/IMonitoringBroadcastService.cs new file mode 100644 index 0000000..0cd42e2 --- /dev/null +++ b/src/Heimdall.Application/Services/IMonitoringBroadcastService.cs @@ -0,0 +1,13 @@ +namespace Heimdall.Application.Services; + +/// +/// Broadcasts monitoring events (agent/camera status, storage, GPU) via SignalR. +/// +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); +} diff --git a/src/Heimdall.Application/Services/INotificationBroadcastService.cs b/src/Heimdall.Application/Services/INotificationBroadcastService.cs new file mode 100644 index 0000000..48597cf --- /dev/null +++ b/src/Heimdall.Application/Services/INotificationBroadcastService.cs @@ -0,0 +1,12 @@ +using Heimdall.Application.DTOs; + +namespace Heimdall.Application.Services; + +/// +/// Broadcasts notifications to connected clients via SignalR. +/// +public interface INotificationBroadcastService +{ + Task NotifyNewNotification(NotificationDto notification, CancellationToken ct = default); + Task NotifyUnreadCount(Guid userId, int count, CancellationToken ct = default); +} diff --git a/src/Heimdall.Application/Services/INotificationRateLimiter.cs b/src/Heimdall.Application/Services/INotificationRateLimiter.cs new file mode 100644 index 0000000..d5b83b9 --- /dev/null +++ b/src/Heimdall.Application/Services/INotificationRateLimiter.cs @@ -0,0 +1,12 @@ +using Heimdall.Domain.Enums; + +namespace Heimdall.Application.Services; + +/// +/// Rate-limits notifications per camera/type to prevent spam. +/// +public interface INotificationRateLimiter +{ + /// Returns true if the notification should be sent. + bool ShouldSend(Guid cameraId, EventType type, Guid? trackId); +} diff --git a/src/Heimdall.Application/Services/INotificationService.cs b/src/Heimdall.Application/Services/INotificationService.cs new file mode 100644 index 0000000..1f3de16 --- /dev/null +++ b/src/Heimdall.Application/Services/INotificationService.cs @@ -0,0 +1,32 @@ +using Heimdall.Application.DTOs; +using Heimdall.Application.Common; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; + +namespace Heimdall.Application.Services; + +/// +/// Core notification orchestration service. +/// Creates notifications, dispatches to channels (SignalR/Email/Gotify), respects rate limits. +/// +public interface INotificationService +{ + /// Create a notification and dispatch to all enabled channels. + Task> 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); + + /// Get unread notification count for a user. + Task GetUnreadCountAsync(Guid userId, CancellationToken ct = default); + + /// Get paginated notifications for a user. + Task> GetNotificationsAsync(Guid userId, bool? isRead, int page, int pageSize, CancellationToken ct = default); + + /// Mark a single notification as read. + Task MarkAsReadAsync(Guid notificationId, Guid userId, CancellationToken ct = default); + + /// Mark all notifications as read for a user. + Task MarkAllAsReadAsync(Guid userId, CancellationToken ct = default); +} diff --git a/src/Heimdall.Domain/Entities/Notification.cs b/src/Heimdall.Domain/Entities/Notification.cs new file mode 100644 index 0000000..53fa51f --- /dev/null +++ b/src/Heimdall.Domain/Entities/Notification.cs @@ -0,0 +1,49 @@ +using Heimdall.Domain.Enums; +using Heimdall.Domain.Primitives; + +namespace Heimdall.Domain.Entities; + +/// +/// Represents a user notification triggered by a camera event. +/// Supports read tracking, optional event/camera/site links, and snapshot URLs. +/// +public class Notification : Entity, 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; + } +} diff --git a/src/Heimdall.Domain/Entities/NotificationTemplate.cs b/src/Heimdall.Domain/Entities/NotificationTemplate.cs new file mode 100644 index 0000000..7f05209 --- /dev/null +++ b/src/Heimdall.Domain/Entities/NotificationTemplate.cs @@ -0,0 +1,41 @@ +using Heimdall.Domain.Enums; +using Heimdall.Domain.Primitives; + +namespace Heimdall.Domain.Entities; + +/// +/// Defines a per-channel and per-language notification template for a given event type. +/// Supports default fallback templates that can be overridden per user. +/// +public class NotificationTemplate : Entity, 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; + } +} diff --git a/src/Heimdall.Domain/Entities/UserNotificationConfig.cs b/src/Heimdall.Domain/Entities/UserNotificationConfig.cs new file mode 100644 index 0000000..97efc20 --- /dev/null +++ b/src/Heimdall.Domain/Entities/UserNotificationConfig.cs @@ -0,0 +1,61 @@ +using Heimdall.Domain.Enums; +using Heimdall.Domain.Primitives; + +namespace Heimdall.Domain.Entities; + +/// +/// Per-user notification preferences including channel configuration, + /// language, digest schedule, and subscribed event types. +/// +public class UserNotificationConfig : Entity, 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; + } +} diff --git a/src/Heimdall.Domain/Enums/NotificationChannel.cs b/src/Heimdall.Domain/Enums/NotificationChannel.cs new file mode 100644 index 0000000..e55f08d --- /dev/null +++ b/src/Heimdall.Domain/Enums/NotificationChannel.cs @@ -0,0 +1,8 @@ +namespace Heimdall.Domain.Enums; + +public enum NotificationChannel +{ + InApp = 0, + Email = 1, + Gotify = 2 +} diff --git a/src/Heimdall.Domain/Enums/NotificationType.cs b/src/Heimdall.Domain/Enums/NotificationType.cs new file mode 100644 index 0000000..269d410 --- /dev/null +++ b/src/Heimdall.Domain/Enums/NotificationType.cs @@ -0,0 +1,10 @@ +namespace Heimdall.Domain.Enums; + +public enum NotificationType +{ + Info = 0, + Success = 1, + Warning = 2, + Error = 3, + Alert = 4 +} diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs b/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs index 1633981..c0cc5da 100644 --- a/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs @@ -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(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); return services; } diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs index cb6f6fc..3da8498 100644 --- a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs +++ b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs @@ -16,5 +16,15 @@ public static class JobSetup "agent-failover", job => job.ExecuteAsync(CancellationToken.None), "*/1 * * * *"); + + manager.AddOrUpdate( + "daily-digest", + job => job.ExecuteAsync(CancellationToken.None), + "0 8 * * *"); // Daily at 8:00 + + manager.AddOrUpdate( + "weekly-digest", + job => job.ExecuteAsync(CancellationToken.None), + "0 8 * * 1"); // Monday at 8:00 } } diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs index 105487e..65bb3e0 100644 --- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs +++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs @@ -43,6 +43,11 @@ public class AppDbContext : IdentityDbContext, IApplicat // Event entities public DbSet CameraEvents => Set(); + // Notification entities + public DbSet Notifications => Set(); + public DbSet NotificationTemplates => Set(); + public DbSet UserNotificationConfigs => Set(); + // Security entities public DbSet RevokedRefreshTokens => Set(); diff --git a/src/Heimdall.Infrastructure/Data/Configurations/NotificationConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/NotificationConfiguration.cs new file mode 100644 index 0000000..00ce751 --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/NotificationConfiguration.cs @@ -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 +{ + public void Configure(EntityTypeBuilder 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() + .HasMaxLength(50); + + builder.Property(n => n.EventType) + .HasConversion() + .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); + } +} diff --git a/src/Heimdall.Infrastructure/Data/Configurations/NotificationTemplateConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/NotificationTemplateConfiguration.cs new file mode 100644 index 0000000..326cb3c --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/NotificationTemplateConfiguration.cs @@ -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 +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("notification_templates"); + + builder.HasKey(t => t.Id); + + builder.Property(t => t.EventType) + .HasConversion() + .HasMaxLength(50) + .IsRequired(); + + builder.Property(t => t.Channel) + .HasConversion() + .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(); + } +} diff --git a/src/Heimdall.Infrastructure/Data/Configurations/UserNotificationConfigConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/UserNotificationConfigConfiguration.cs new file mode 100644 index 0000000..065bb75 --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/UserNotificationConfigConfiguration.cs @@ -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 +{ + public void Configure(EntityTypeBuilder 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(); + } +} diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs index 211ff36..ae23998 100644 --- a/src/Heimdall.Infrastructure/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/DependencyInjection.cs @@ -137,6 +137,16 @@ public static class DependencyInjection // Camera assignment service (used by CQRS handlers) services.AddScoped(); + // Notification services + services.AddScoped(); + services.AddSingleton(); + services.AddScoped(); + services.AddScoped(); + services.AddHttpClient("Gotify", client => + { + client.Timeout = TimeSpan.FromSeconds(10); + }); + return services; } } diff --git a/src/Heimdall.Infrastructure/Jobs/DailyDigestJob.cs b/src/Heimdall.Infrastructure/Jobs/DailyDigestJob.cs new file mode 100644 index 0000000..739ad18 --- /dev/null +++ b/src/Heimdall.Infrastructure/Jobs/DailyDigestJob.cs @@ -0,0 +1,73 @@ +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Infrastructure.Jobs; + +/// +/// 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. +/// +public class DailyDigestJob +{ + private readonly IDbContextFactory _dbFactory; + private readonly IEmailService _emailService; + private readonly ILogger _logger; + + public DailyDigestJob( + IDbContextFactory dbFactory, + IEmailService emailService, + ILogger 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 = $""" +

Résumé quotidien Heimdall

+

Bonjour,

+
    +
  • Événements détectés aujourd'hui : {eventCount}
  • +
  • Notifications non lues : {unreadNotifications}
  • +
+

Cordialement,
L'équipe Heimdall

+ """; + + 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); + } +} diff --git a/src/Heimdall.Infrastructure/Jobs/SendNotificationJob.cs b/src/Heimdall.Infrastructure/Jobs/SendNotificationJob.cs new file mode 100644 index 0000000..deac56d --- /dev/null +++ b/src/Heimdall.Infrastructure/Jobs/SendNotificationJob.cs @@ -0,0 +1,37 @@ +using Heimdall.Application.Services; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Infrastructure.Jobs; + +/// +/// Hangfire job to send a notification via email or Gotify. +/// Fire-and-forget, with retry built into Hangfire. +/// +public class SendNotificationJob +{ + private readonly IEmailService _emailService; + private readonly IGotifyService _gotifyService; + private readonly ILogger _logger; + + public SendNotificationJob( + IEmailService emailService, + IGotifyService gotifyService, + ILogger 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); + } +} diff --git a/src/Heimdall.Infrastructure/Jobs/WeeklyDigestJob.cs b/src/Heimdall.Infrastructure/Jobs/WeeklyDigestJob.cs new file mode 100644 index 0000000..ca6176f --- /dev/null +++ b/src/Heimdall.Infrastructure/Jobs/WeeklyDigestJob.cs @@ -0,0 +1,69 @@ +using Heimdall.Application.Services; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Infrastructure.Jobs; + +/// +/// 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. +/// +public class WeeklyDigestJob +{ + private readonly IDbContextFactory _dbFactory; + private readonly IEmailService _emailService; + private readonly ILogger _logger; + + public WeeklyDigestJob( + IDbContextFactory dbFactory, + IEmailService emailService, + ILogger 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 = $""" +

Résumé hebdomadaire Heimdall

+

Bonjour,

+
    +
  • Événements détectés cette semaine : {eventCount}
  • +
+

Cordialement,
L'équipe Heimdall

+ """; + + 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); + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20260726202220_AddNotifications.Designer.cs b/src/Heimdall.Infrastructure/Migrations/20260726202220_AddNotifications.Designer.cs new file mode 100644 index 0000000..9c7feaf --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20260726202220_AddNotifications.Designer.cs @@ -0,0 +1,1765 @@ +// +using System; +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260726202220_AddNotifications")] + partial class AddNotifications + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.8") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ApiKeyHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("ApiKeyPrefix") + .HasMaxLength(8) + .IsUnicode(false) + .HasColumnType("character varying(8)"); + + b.Property("CpuCores") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("GpuType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HasGpu") + .HasColumnType("boolean"); + + b.Property("Hostname") + .IsRequired() + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastHeartbeat") + .HasColumnType("timestamp with time zone"); + + b.Property("MemoryMb") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("PublicIp") + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.HasKey("Id"); + + b.HasIndex("LastHeartbeat") + .HasFilter("\"Status\" = 'Online'"); + + b.HasIndex("SiteId"); + + b.ToTable("agents", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid") + .HasColumnName("agent_id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("key"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "Key") + .IsUnique(); + + b.ToTable("agent_settings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("KeyHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("KeyPrefix") + .IsRequired() + .HasMaxLength(8) + .IsUnicode(false) + .HasColumnType("character varying(8)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("KeyHash"); + + b.HasIndex("KeyPrefix"); + + b.HasIndex("SiteId"); + + b.ToTable("api_keys", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("roles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppSetting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AllowedValues") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)") + .HasColumnName("allowed_values"); + + b.Property("Category") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("category"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)") + .HasColumnName("description"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("key"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.Property("ValueType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("value_type"); + + b.HasKey("Id"); + + b.HasIndex("Key") + .IsUnique(); + + b.ToTable("app_settings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .IsUnicode(false) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("MustChangePassword") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("Theme") + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)") + .HasDefaultValue("Auto"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("users", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("IpAddress") + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("NewValue") + .HasColumnType("text"); + + b.Property("OldValue") + .HasColumnType("text"); + + b.Property("ResourceId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ResourceType") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Timestamp") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Timestamp") + .IsDescending(); + + b.HasIndex("UserId"); + + b.HasIndex("ResourceType", "ResourceId", "Timestamp") + .IsDescending(false, false, true); + + b.ToTable("audit_logs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Capabilities") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DetectedType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HasAudio") + .HasColumnType("boolean"); + + b.Property("HasMotionDetection") + .HasColumnType("boolean"); + + b.Property("HasPtz") + .HasColumnType("boolean"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("character varying(45)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastDiscoveredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastStreamTestAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastTestedCodecs") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("LastTestedHeight") + .HasColumnType("integer"); + + b.Property("LastTestedLatencyMs") + .HasColumnType("bigint"); + + b.Property("LastTestedWidth") + .HasColumnType("integer"); + + b.Property("MacAddress") + .HasMaxLength(17) + .HasColumnType("character varying(17)"); + + b.Property("Manufacturer") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.Property("RtspPort") + .HasColumnType("integer"); + + b.Property("RtspUrl") + .HasMaxLength(1000) + .IsUnicode(false) + .HasColumnType("character varying(1000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("SubRtspUrl") + .HasMaxLength(1000) + .IsUnicode(false) + .HasColumnType("character varying(1000)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("AgentId"); + + b.HasIndex("IpAddress"); + + b.HasIndex("MacAddress"); + + b.HasIndex("SiteId"); + + b.ToTable("cameras", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("AssignedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Reason") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("ReleasedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AssignedAt"); + + b.HasIndex("AgentId", "ReleasedAt") + .HasFilter("\"ReleasedAt\" IS NULL"); + + b.HasIndex("CameraId", "ReleasedAt") + .IsUnique() + .HasFilter("\"ReleasedAt\" IS NULL"); + + b.ToTable("camera_assignments", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("OnvifPassword") + .IsRequired() + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifUsername") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("admin"); + + b.Property("RtspPassword") + .IsRequired() + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("RtspUsername") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("CameraId"); + + b.ToTable("camera_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("ActiveIntervalMs") + .HasColumnType("integer"); + + b.Property("AnimalCooldownSec") + .HasColumnType("integer"); + + b.Property("DetectAnimal") + .HasColumnType("boolean"); + + b.Property("DetectMotion") + .HasColumnType("boolean"); + + b.Property("DetectPackage") + .HasColumnType("boolean"); + + b.Property("DetectPerson") + .HasColumnType("boolean"); + + b.Property("DetectVehicle") + .HasColumnType("boolean"); + + b.Property("FaceRecognition") + .HasColumnType("boolean"); + + b.Property("IdleIntervalMs") + .HasColumnType("integer"); + + b.Property("IoUThreshold") + .HasColumnType("double precision"); + + b.Property("LicensePlateRecognition") + .HasColumnType("boolean"); + + b.Property("MaxEventsPerMinute") + .HasColumnType("integer"); + + b.Property("MinConfidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.40000000000000002); + + b.Property("MotionIntervalMs") + .HasColumnType("integer"); + + b.Property("MotionThreshold") + .HasColumnType("double precision"); + + b.Property("PersonCooldownSec") + .HasColumnType("integer"); + + b.Property("RequireMotionForAI") + .HasColumnType("boolean"); + + b.Property("VehicleCooldownSec") + .HasColumnType("integer"); + + b.Property("YoloModel") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)") + .HasDefaultValue("yolov8n"); + + b.HasKey("CameraId"); + + b.ToTable("camera_detection_profiles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("DetectedType") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HomeKitDeviceId") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("HomeKitModel") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HomeKitName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("Hostname") + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("HttpServerHeader") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HttpStatusCode") + .HasColumnType("integer"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("IsHomeKitCamera") + .HasColumnType("boolean"); + + b.Property("IsProcessed") + .HasColumnType("boolean"); + + b.Property("IsReachable") + .HasColumnType("boolean"); + + b.Property("MacAddress") + .HasMaxLength(17) + .IsUnicode(false) + .HasColumnType("character varying(17)"); + + b.Property("OnvifDeviceServiceUrl") + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifHardware") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.PrimitiveCollection("OpenPorts") + .IsRequired() + .IsUnicode(false) + .HasColumnType("integer[]"); + + b.Property("ProbedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Vendor") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.HasKey("Id"); + + b.HasIndex("IpAddress"); + + b.HasIndex("IsProcessed"); + + b.HasIndex("SiteId"); + + b.ToTable("camera_discovery_results", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Confidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Label") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("MetadataJson") + .HasColumnType("jsonb"); + + b.Property("OccurredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SnapshotThumbUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Type") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("OccurredAt"); + + b.HasIndex("CameraId", "OccurredAt") + .IsDescending(false, true); + + b.HasIndex("CameraId", "Type"); + + b.ToTable("camera_events", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.PrimitiveCollection("Codecs") + .IsRequired() + .IsUnicode(false) + .HasColumnType("text[]"); + + b.Property("DiscoveryResultId") + .HasColumnType("uuid"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("IsAlive") + .HasColumnType("boolean"); + + b.Property("IsMainStream") + .HasColumnType("boolean"); + + b.Property("LatencyMs") + .HasColumnType("bigint"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Url") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DiscoveryResultId"); + + b.HasIndex("IsAlive"); + + b.HasIndex("IsMainStream"); + + b.ToTable("discovered_streams", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Embedding") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("SourceEventId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ThumbnailUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.ToTable("known_faces", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Notification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("Link") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ReadAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("SnapshotUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BodyMarkdown") + .IsRequired() + .HasColumnType("text"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsDefault") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Category") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("IsWatchlisted") + .HasColumnType("boolean"); + + b.Property("Notes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PhotoUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Category"); + + b.HasIndex("DisplayName"); + + b.HasIndex("IsWatchlisted"); + + b.ToTable("persons", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.RevokedRefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("RevokedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("revoked_refresh_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Address") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("RegistrationTokenHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("Timezone") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)") + .HasDefaultValue("UTC"); + + b.Property("TokenExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "GroupId"); + + b.HasIndex("GroupId"); + + b.ToTable("user_groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserNotificationConfig", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DailyDigest") + .HasColumnType("boolean"); + + b.Property("EmailAddress") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("EmailEnabled") + .HasColumnType("boolean"); + + b.Property("GotifyEnabled") + .HasColumnType("boolean"); + + b.Property("GotifyToken") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("GotifyUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("SubscribedEventsJson") + .HasColumnType("jsonb") + .HasColumnName("subscribed_events"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("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("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "SiteId"); + + b.HasIndex("SiteId"); + + b.ToTable("user_sites", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("role_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("user_claims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("user_logins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("user_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Agents") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany("Cameras") + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Cameras") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Agent"); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Agent"); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("Credentials") + .HasForeignKey("Heimdall.Domain.Entities.CameraCredentials", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("DetectionProfile") + .HasForeignKey("Heimdall.Domain.Entities.CameraDetectionProfile", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.HasOne("Heimdall.Domain.Entities.CameraDiscoveryResult", "DiscoveryResult") + .WithMany("DiscoveredStreams") + .HasForeignKey("DiscoveryResultId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DiscoveryResult"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany("Faces") + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Person"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.HasOne("Heimdall.Domain.Entities.Group", "Group") + .WithMany("UserGroups") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserGroups") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserSites") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Navigation("Cameras"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b => + { + b.Navigation("UserGroups"); + + b.Navigation("UserSites"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Navigation("Credentials"); + + b.Navigation("DetectionProfile"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Navigation("DiscoveredStreams"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Navigation("UserGroups"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Navigation("Faces"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Navigation("Agents"); + + b.Navigation("Cameras"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20260726202220_AddNotifications.cs b/src/Heimdall.Infrastructure/Migrations/20260726202220_AddNotifications.cs new file mode 100644 index 0000000..61cb2f8 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20260726202220_AddNotifications.cs @@ -0,0 +1,121 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + /// + public partial class AddNotifications : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "notification_templates", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + EventType = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), + Channel = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), + Language = table.Column(type: "character varying(10)", maxLength: 10, nullable: false, defaultValue: "fr"), + Subject = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + BodyMarkdown = table.Column(type: "text", nullable: false), + IsDefault = table.Column(type: "boolean", nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"), + UpdatedAt = table.Column(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(type: "uuid", nullable: false), + UserId = table.Column(type: "uuid", nullable: false), + Title = table.Column(type: "character varying(200)", maxLength: 200, nullable: false), + Message = table.Column(type: "character varying(2000)", maxLength: 2000, nullable: false), + Type = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), + EventType = table.Column(type: "character varying(50)", maxLength: 50, nullable: true), + CameraId = table.Column(type: "uuid", nullable: true), + SiteId = table.Column(type: "uuid", nullable: true), + SnapshotUrl = table.Column(type: "character varying(500)", maxLength: 500, nullable: true), + Link = table.Column(type: "character varying(500)", maxLength: 500, nullable: true), + IsRead = table.Column(type: "boolean", nullable: false), + ReadAt = table.Column(type: "timestamp with time zone", nullable: true), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"), + UpdatedAt = table.Column(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(type: "uuid", nullable: false), + UserId = table.Column(type: "uuid", nullable: false), + EmailEnabled = table.Column(type: "boolean", nullable: false), + EmailAddress = table.Column(type: "character varying(200)", maxLength: 200, nullable: true), + GotifyEnabled = table.Column(type: "boolean", nullable: false), + GotifyUrl = table.Column(type: "character varying(500)", maxLength: 500, nullable: true), + GotifyToken = table.Column(type: "character varying(500)", maxLength: 500, nullable: true), + Language = table.Column(type: "character varying(10)", maxLength: 10, nullable: false, defaultValue: "fr"), + DailyDigest = table.Column(type: "boolean", nullable: false), + WeeklyDigest = table.Column(type: "boolean", nullable: false), + subscribed_events = table.Column(type: "jsonb", nullable: true), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()"), + UpdatedAt = table.Column(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); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "notification_templates"); + + migrationBuilder.DropTable( + name: "notifications"); + + migrationBuilder.DropTable( + name: "user_notification_configs"); + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 6119296..403b3a2 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -1027,6 +1027,128 @@ namespace Heimdall.Infrastructure.Migrations b.ToTable("known_faces", (string)null); }); + modelBuilder.Entity("Heimdall.Domain.Entities.Notification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("Link") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ReadAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("SnapshotUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BodyMarkdown") + .IsRequired() + .HasColumnType("text"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsDefault") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("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("Id") @@ -1180,6 +1302,68 @@ namespace Heimdall.Infrastructure.Migrations b.ToTable("user_groups", (string)null); }); + modelBuilder.Entity("Heimdall.Domain.Entities.UserNotificationConfig", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DailyDigest") + .HasColumnType("boolean"); + + b.Property("EmailAddress") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("EmailEnabled") + .HasColumnType("boolean"); + + b.Property("GotifyEnabled") + .HasColumnType("boolean"); + + b.Property("GotifyToken") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("GotifyUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("SubscribedEventsJson") + .HasColumnType("jsonb") + .HasColumnName("subscribed_events"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("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("UserId") diff --git a/src/Heimdall.Infrastructure/Services/EmailService.cs b/src/Heimdall.Infrastructure/Services/EmailService.cs new file mode 100644 index 0000000..98bf4da --- /dev/null +++ b/src/Heimdall.Infrastructure/Services/EmailService.cs @@ -0,0 +1,22 @@ +using Heimdall.Application.Services; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Infrastructure.Services; + +public class EmailService : IEmailService +{ + private readonly ILogger _logger; + + public EmailService(ILogger 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; + } +} diff --git a/src/Heimdall.Infrastructure/Services/GotifyService.cs b/src/Heimdall.Infrastructure/Services/GotifyService.cs new file mode 100644 index 0000000..9e2e391 --- /dev/null +++ b/src/Heimdall.Infrastructure/Services/GotifyService.cs @@ -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 _logger; + + public GotifyService(IHttpClientFactory httpClientFactory, ILogger 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); + } + } +} diff --git a/src/Heimdall.Infrastructure/Services/NotificationRateLimiter.cs b/src/Heimdall.Infrastructure/Services/NotificationRateLimiter.cs new file mode 100644 index 0000000..ef8cf0f --- /dev/null +++ b/src/Heimdall.Infrastructure/Services/NotificationRateLimiter.cs @@ -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; + } +} diff --git a/src/Heimdall.Infrastructure/Services/NotificationService.cs b/src/Heimdall.Infrastructure/Services/NotificationService.cs new file mode 100644 index 0000000..691051e --- /dev/null +++ b/src/Heimdall.Infrastructure/Services/NotificationService.cs @@ -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 _logger; + + public NotificationService( + IApplicationDbContext context, + IMapper mapper, + INotificationBroadcastService broadcast, + IEmailService emailService, + IGotifyService gotifyService, + INotificationRateLimiter rateLimiter, + ILogger logger) + { + _context = context; + _mapper = mapper; + _broadcast = broadcast; + _emailService = emailService; + _gotifyService = gotifyService; + _rateLimiter = rateLimiter; + _logger = logger; + } + + public async Task> 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.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(notification); + + // Broadcast in-app + await _broadcast.NotifyNewNotification(dto, ct); + + // Send via email/gotify if user has config + await DispatchToExternalChannelsAsync(notification, userId, ct); + + return ServiceResult.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, + $"

{notification.Title}

{notification.Message}

", + 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 GetUnreadCountAsync(Guid userId, CancellationToken ct = default) + { + return await _context.Notifications + .CountAsync(n => n.UserId == userId && !n.IsRead, ct); + } + + public async Task> 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(_mapper.ConfigurationProvider) + .ToListAsync(ct); + + return new PagedResult(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); + } +} diff --git a/src/Heimdall.Web/Controllers/NotificationsController.cs b/src/Heimdall.Web/Controllers/NotificationsController.cs new file mode 100644 index 0000000..fe7f731 --- /dev/null +++ b/src/Heimdall.Web/Controllers/NotificationsController.cs @@ -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; + +/// +/// In-app notifications for users — list, mark read, configure notification preferences. +/// +[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)!); + + /// List notifications for the current user. + [HttpGet] + [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] + public async Task 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); + } + + /// Get unread notification count. + [HttpGet("unread-count")] + [ProducesResponseType(typeof(UnreadCountDto), StatusCodes.Status200OK)] + public async Task 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 }); + } + + /// Mark a single notification as read. + [HttpPost("{id:guid}/read")] + [ProducesResponseType(typeof(MarkAsReadResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] + public async Task 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 }); + } + + /// Mark all notifications as read. + [HttpPost("mark-all-read")] + [ProducesResponseType(typeof(MarkAsReadResponse), StatusCodes.Status200OK)] + public async Task MarkAllAsRead(CancellationToken ct = default) + { + var result = await _mediator.Send(new MarkAllAsReadCommand(GetUserId()), ct); + return Ok(result.Data); + } + + /// Get notification configuration for the current user. + [HttpGet("config")] + [ProducesResponseType(typeof(UserNotificationConfigDto), StatusCodes.Status200OK)] + public async Task 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 }); + } + + /// Update notification configuration for the current user. + [HttpPut("config")] + [ProducesResponseType(typeof(UserNotificationConfigDto), StatusCodes.Status200OK)] + public async Task 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 }); + } +} diff --git a/src/Heimdall.Web/Hubs/AdminHub.cs b/src/Heimdall.Web/Hubs/AdminHub.cs new file mode 100644 index 0000000..8effcaf --- /dev/null +++ b/src/Heimdall.Web/Hubs/AdminHub.cs @@ -0,0 +1,86 @@ +using Heimdall.Application.Services; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.SignalR; + +namespace Heimdall.Api.Hubs; + +/// +/// SignalR hub for admin-level broadcast events (config changes, user role changes, camera lifecycle). +/// Only Admin role users can connect. +/// +[Authorize(AuthenticationSchemes = "JwtBearer", Roles = "Admin")] +public class AdminHub : Hub +{ + private readonly ILogger _logger; + + public AdminHub(ILogger logger) => _logger = logger; + + /// + /// Clients call this to join the admin broadcast group. + /// + public async Task JoinAdminBroadcast() + { + await Groups.AddToGroupAsync(Context.ConnectionId, "admin-broadcast"); + _logger.LogDebug("Admin client {ConnectionId} joined admin broadcast group", Context.ConnectionId); + } + + /// + /// Clients call this to leave the admin broadcast group. + /// + 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); + } +} + +/// +/// Broadcasts admin-level configuration and lifecycle events via SignalR. +/// Uses IHubContext for thread-safe broadcasting outside of hub connections. +/// +public class AdminBroadcastService : IAdminBroadcastService +{ + private readonly IHubContext _hubContext; + private readonly ILogger _logger; + + public AdminBroadcastService(IHubContext hubContext, ILogger 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); + } +} diff --git a/src/Heimdall.Web/Hubs/MonitoringHub.cs b/src/Heimdall.Web/Hubs/MonitoringHub.cs new file mode 100644 index 0000000..21093f6 --- /dev/null +++ b/src/Heimdall.Web/Hubs/MonitoringHub.cs @@ -0,0 +1,115 @@ +using Heimdall.Application.Services; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.SignalR; + +namespace Heimdall.Api.Hubs; + +/// +/// 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" +/// +[Authorize(AuthenticationSchemes = "JwtBearer")] +public class MonitoringHub : Hub +{ + private readonly ILogger _logger; + + public MonitoringHub(ILogger logger) => _logger = logger; + + /// + /// Clients call this to join monitoring for a specific site. + /// + 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); + } + + /// + /// Clients call this to leave monitoring for a specific site. + /// + public async Task LeaveSiteMonitoring(string siteId) + { + if (!Guid.TryParse(siteId, out _)) return; + await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"site_{siteId}"); + } + + /// + /// Clients call this to receive admin-level monitoring broadcasts. + /// + public async Task JoinAdminBroadcast() + { + await Groups.AddToGroupAsync(Context.ConnectionId, "admin-broadcast"); + _logger.LogDebug("Client {ConnectionId} joined admin broadcast monitoring group", Context.ConnectionId); + } + + /// + /// Clients call this to leave admin-level monitoring broadcasts. + /// + 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); + } +} + +/// +/// Broadcasts monitoring events to connected clients via SignalR. +/// Uses IHubContext for thread-safe broadcasting outside of hub connections. +/// +public class MonitoringBroadcastService : IMonitoringBroadcastService +{ + private readonly IHubContext _hubContext; + private readonly ILogger _logger; + + public MonitoringBroadcastService(IHubContext hubContext, ILogger 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); + } +} diff --git a/src/Heimdall.Web/Hubs/NotificationsHub.cs b/src/Heimdall.Web/Hubs/NotificationsHub.cs new file mode 100644 index 0000000..d7ed08d --- /dev/null +++ b/src/Heimdall.Web/Hubs/NotificationsHub.cs @@ -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; + +/// +/// SignalR hub for in-app notifications with badge count. +/// JWT-authenticated users receive new notifications and unread count updates +/// without polling. +/// Groups: "notif_{userId}" +/// +[Authorize(AuthenticationSchemes = "JwtBearer")] +public class NotificationsHub : Hub +{ + private readonly ILogger _logger; + + public NotificationsHub(ILogger logger) => _logger = logger; + + /// + /// Clients call this to join their personal notification channel. + /// The user ID is extracted from the JWT claim. + /// + 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); + } +} + +/// +/// Broadcasts notifications to connected clients via SignalR. +/// Uses IHubContext for thread-safe broadcasting outside of hub connections. +/// +public class NotificationBroadcastService : INotificationBroadcastService +{ + private readonly IHubContext _hubContext; + private readonly ILogger _logger; + + public NotificationBroadcastService(IHubContext hubContext, ILogger 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); + } +} diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index eff2005..45e565d 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -329,6 +329,9 @@ public partial class Program { builder.Services.AddSignalR(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddOpenApi(); // ── Application & Infrastructure layers ────────────────────────── @@ -400,6 +403,9 @@ public partial class Program { app.MapControllers(); app.MapHub("/hubs/config"); app.MapHub("/hubs/events"); + app.MapHub("/hubs/monitoring"); + app.MapHub("/hubs/notifications"); + app.MapHub("/hubs/admin"); if (app.Environment.IsDevelopment()) { diff --git a/src/Heimdall.Web/core.109404 b/src/Heimdall.Web/core.109404 new file mode 100644 index 0000000..c267d62 Binary files /dev/null and b/src/Heimdall.Web/core.109404 differ diff --git a/templates b/templates new file mode 160000 index 0000000..218303a --- /dev/null +++ b/templates @@ -0,0 +1 @@ +Subproject commit 218303a91c6042e9a3bbc934a5f04d366c8a146a diff --git a/tests/Heimdall.Application.Tests/Common/MockDbSetHelper.cs b/tests/Heimdall.Application.Tests/Common/MockDbSetHelper.cs index d9ca7d4..e6a1476 100644 --- a/tests/Heimdall.Application.Tests/Common/MockDbSetHelper.cs +++ b/tests/Heimdall.Application.Tests/Common/MockDbSetHelper.cs @@ -72,8 +72,30 @@ internal sealed class InMemoryAsyncQueryProvider : 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 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 CreateQuery(Expression expression) => new InMemoryAsyncQueryable(expression, new InMemoryAsyncQueryProvider(_inner)); public object? Execute(Expression expression) => _inner.Execute(expression); diff --git a/tests/Heimdall.Application.Tests/Handlers/Notifications/NotificationHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Notifications/NotificationHandlerTests.cs new file mode 100644 index 0000000..2bde55a --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/Notifications/NotificationHandlerTests.cs @@ -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(); + _context.SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + } + + // =================================================================== + // GetNotificationsHandler + // =================================================================== + + [Fact] + public async Task Handle_GetNotifications_ShouldReturnPagedResults() + { + var userId = Guid.NewGuid(); + var notifications = new List + { + 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 + { + 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()); + 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 + { + 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(), Arg.Any()); + } + + [Fact] + public async Task Handle_MarkAsRead_WithNonExistentNotification_ShouldReturnNotFound() + { + var userId = Guid.NewGuid(); + _context.Notifications.Returns(MockDbSetHelper.CreateFor()); + 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 + { + 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(), Arg.Any()); + } + + [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()); + 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(), Arg.Any()); + } + + [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()); + 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()); + 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()); + 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(), Arg.Any()); + } +} diff --git a/tests/Heimdall.Domain.Tests/Entities/NotificationDomainTests.cs b/tests/Heimdall.Domain.Tests/Entities/NotificationDomainTests.cs new file mode 100644 index 0000000..f8cb516 --- /dev/null +++ b/tests/Heimdall.Domain.Tests/Entities/NotificationDomainTests.cs @@ -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"); + } +} diff --git a/tests/Heimdall.Infrastructure.Tests/Services/NotificationRateLimiterTests.cs b/tests/Heimdall.Infrastructure.Tests/Services/NotificationRateLimiterTests.cs new file mode 100644 index 0000000..0b3bad4 --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/Services/NotificationRateLimiterTests.cs @@ -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(); + } +} diff --git a/tests/Heimdall.Infrastructure.Tests/Services/NotificationServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/Services/NotificationServiceTests.cs new file mode 100644 index 0000000..09cfda9 --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/Services/NotificationServiceTests.cs @@ -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; + +/// +/// Unit tests for . +/// Uses SQLite in-memory for real EF Core behavior with mocked external channels. +/// +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 _logger; + private readonly NotificationService _service; + + public NotificationServiceTests() + { + _connection = new SqliteConnection("DataSource=:memory:"); + _connection.Open(); + + var opts = new DbContextOptionsBuilder() + .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()); + _mapper = mapperConfig.CreateMapper(); + + _broadcast = Substitute.For(); + _emailService = Substitute.For(); + _gotifyService = Substitute.For(); + _rateLimiter = Substitute.For(); + _logger = Substitute.For>(); + + _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(), Arg.Any(), Arg.Any()) + .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(d => d!.Title == "Test Title"), + Arg.Any()); + + // 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(), Arg.Any(), Arg.Any()) + .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(), Arg.Any()); + } + + [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); + } +} diff --git a/tests/Heimdall.IntegrationTests/Scenarios/NotificationScenarios.cs b/tests/Heimdall.IntegrationTests/Scenarios/NotificationScenarios.cs new file mode 100644 index 0000000..1034609 --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Scenarios/NotificationScenarios.cs @@ -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; + +/// +/// Integration tests for /api/notifications/* endpoints. +/// Verifies auth gating, configuration CRUD, and notification lifecycle. +/// +[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(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(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(JsonOptions); + json.TryGetProperty("items", out _).ShouldBeTrue(); + json.TryGetProperty("totalCount", out _).ShouldBeTrue(); + } +} diff --git a/tests/Heimdall.IntegrationTests/Scenarios/SignalRHubScenarios.cs b/tests/Heimdall.IntegrationTests/Scenarios/SignalRHubScenarios.cs new file mode 100644 index 0000000..7cb8992 --- /dev/null +++ b/tests/Heimdall.IntegrationTests/Scenarios/SignalRHubScenarios.cs @@ -0,0 +1,121 @@ +using System.Net; +using System.Net.Http.Headers; +using Heimdall.IntegrationTests.Controllers; +using Shouldly; + +namespace Heimdall.IntegrationTests.Scenarios; + +/// +/// Integration tests for SignalR hub authentication. +/// Verifies that all hubs require authentication and that valid +/// JWT tokens grant access to the negotiate endpoint. +/// +[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" + ]; + + /// + /// SignalR negotiate uses POST to the negotiate sub-path. + /// With [Authorize], unauth'd requests should return 401 before reaching the hub. + /// + [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"); + } + } + + /// + /// GET requests to the hub path with negotiateVersion should also be auth-gated. + /// + [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); + } +}