From 153be535d46b435d060c2178e27d52017aa4922a Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 19 Jul 2026 19:58:45 +0000 Subject: [PATCH] fix(multiple): auth, workers, EF Core, MudTheme fixes - Auth: AssignmentsController auth bug, ReleaseCamera result, logout endpoint - Security: open redirect fix - Workers: AgentState thread-safety, CameraStreamService async, HttpClientFactory - EF Core: AddCameraDiscoveryFields migration, DI interceptors, retry helper - UI: MudTheme palette config, aria-labels on icon buttons --- src/Heimdall.Agent/Services/AgentState.cs | 37 +- .../Services/CameraStreamService.cs | 10 +- .../Services/ConfigReceiverService.cs | 8 +- .../Controllers/AssignmentsController.cs | 11 +- .../Controllers/AuthController.cs | 15 + src/Heimdall.Application/DTOs/AuthDto.cs | 2 + .../Data/AppDbContext.cs | 16 +- .../Data/AppDbContextFactory.cs | 6 +- .../Data/DbContextExtensions.cs | 32 + .../DependencyInjection.cs | 5 + ...95445_AddCameraDiscoveryFields.Designer.cs | 1548 +++++++++++++++++ ...20260719195445_AddCameraDiscoveryFields.cs | 202 +++ .../Services/CameraEventService.cs | 11 +- .../Components/Layout/MainLayout.razor | 53 +- src/Heimdall.Web/Components/Pages/Login.razor | 2 +- .../CameraAssignmentServiceTests.cs | 9 +- .../CameraEventServiceTests.cs | 9 +- 17 files changed, 1944 insertions(+), 32 deletions(-) create mode 100644 src/Heimdall.Infrastructure/Data/DbContextExtensions.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20260719195445_AddCameraDiscoveryFields.Designer.cs create mode 100644 src/Heimdall.Infrastructure/Migrations/20260719195445_AddCameraDiscoveryFields.cs diff --git a/src/Heimdall.Agent/Services/AgentState.cs b/src/Heimdall.Agent/Services/AgentState.cs index e949b68..9a8c039 100644 --- a/src/Heimdall.Agent/Services/AgentState.cs +++ b/src/Heimdall.Agent/Services/AgentState.cs @@ -5,10 +5,18 @@ namespace Heimdall.Agent.Services; /// /// Persisted identity of this agent instance. Survives restarts so the Central /// server sees the same AgentId across reboots (no orphaned agents). +/// Uses an immutable snapshot pattern with for +/// thread-safe concurrent reads/writes from multiple services. /// -public class AgentState +public sealed class AgentState { private string _stateDir = "/var/lib/heimdall"; + private AgentSnapshot _snapshot = AgentSnapshot.Default; + + private sealed record AgentSnapshot(Guid AgentId, string? ApiKey, string? ApiKeyPrefix, string? PublicIp) + { + public static readonly AgentSnapshot Default = new(Guid.Empty, null, null, null); + } /// /// Sets the directory for the state file. Called during DI setup. @@ -20,10 +28,29 @@ public class AgentState private string StatePath => Path.Combine(_stateDir, "agent-state.json"); - public Guid AgentId { get; set; } - public string? ApiKey { get; set; } - public string? ApiKeyPrefix { get; set; } - public string? PublicIp { get; set; } + public Guid AgentId + { + get => _snapshot.AgentId; + set => Interlocked.Exchange(ref _snapshot, _snapshot with { AgentId = value }); + } + + public string? ApiKey + { + get => _snapshot.ApiKey; + set => Interlocked.Exchange(ref _snapshot, _snapshot with { ApiKey = value }); + } + + public string? ApiKeyPrefix + { + get => _snapshot.ApiKeyPrefix; + set => Interlocked.Exchange(ref _snapshot, _snapshot with { ApiKeyPrefix = value }); + } + + public string? PublicIp + { + get => _snapshot.PublicIp; + set => Interlocked.Exchange(ref _snapshot, _snapshot with { PublicIp = value }); + } /// /// Loads a previously saved identity, or returns null if none exists. diff --git a/src/Heimdall.Agent/Services/CameraStreamService.cs b/src/Heimdall.Agent/Services/CameraStreamService.cs index 3c57622..c41681e 100644 --- a/src/Heimdall.Agent/Services/CameraStreamService.cs +++ b/src/Heimdall.Agent/Services/CameraStreamService.cs @@ -1,3 +1,4 @@ +using System.Buffers; using System.Collections.Concurrent; using System.Diagnostics; using Microsoft.Extensions.Logging; @@ -78,16 +79,16 @@ public sealed class CameraStreamService : IDisposable /// Number of currently active streams. public int ActiveStreamCount => _sessions.Count; - private Task ReadFramesLoop(Guid cameraId, StreamSession session, CancellationToken ct) + private async Task ReadFramesLoop(Guid cameraId, StreamSession session, CancellationToken ct) { + var buffer = ArrayPool.Shared.Rent(256 * 1024); try { - var buffer = new byte[256 * 1024]; // 256KB buffer var stream = session.Process.StandardOutput.BaseStream; while (!ct.IsCancellationRequested && !session.IsCancelled && !session.Process.HasExited) { - var bytesRead = stream.Read(buffer, 0, buffer.Length); + var bytesRead = await stream.ReadAsync(buffer.AsMemory(), ct); if (bytesRead == 0) break; // Frame available for analysis — will be passed to FrameAnalyzerService @@ -101,10 +102,9 @@ public sealed class CameraStreamService : IDisposable } finally { + ArrayPool.Shared.Return(buffer); CleanupSession(cameraId, session); } - - return Task.CompletedTask; } private void CleanupSession(Guid cameraId, StreamSession session) diff --git a/src/Heimdall.Agent/Services/ConfigReceiverService.cs b/src/Heimdall.Agent/Services/ConfigReceiverService.cs index f8d27de..06e6844 100644 --- a/src/Heimdall.Agent/Services/ConfigReceiverService.cs +++ b/src/Heimdall.Agent/Services/ConfigReceiverService.cs @@ -13,16 +13,19 @@ public sealed class ConfigReceiverService : BackgroundService private readonly AgentState _state; private readonly AgentOptions _options; private readonly ILogger _logger; + private readonly IHttpClientFactory _httpClientFactory; private HubConnection? _connection; public ConfigReceiverService( AgentState state, IOptions options, - ILogger logger) + ILogger logger, + IHttpClientFactory httpClientFactory) { _state = state; _options = options.Value; _logger = logger; + _httpClientFactory = httpClientFactory; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) @@ -143,7 +146,8 @@ public sealed class ConfigReceiverService : BackgroundService { try { - using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) }; + using var http = _httpClientFactory.CreateClient("Central"); + http.Timeout = TimeSpan.FromSeconds(10); http.DefaultRequestHeaders.Add("Authorization", $"Bearer {_state.ApiKey}"); var url = $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}"; diff --git a/src/Heimdall.Api/Controllers/AssignmentsController.cs b/src/Heimdall.Api/Controllers/AssignmentsController.cs index 506ebbf..3191108 100644 --- a/src/Heimdall.Api/Controllers/AssignmentsController.cs +++ b/src/Heimdall.Api/Controllers/AssignmentsController.cs @@ -17,7 +17,7 @@ namespace Heimdall.Api.Controllers; [ApiController] [Route("api/assignments")] [EnableRateLimiting("Api")] -[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)] +[Authorize(AuthenticationSchemes = "JwtBearer")] public class AssignmentsController : ControllerBase { private readonly ICameraAssignmentService _assignmentService; @@ -29,6 +29,7 @@ public class AssignmentsController : ControllerBase /// Assign a single camera to a specific agent. [HttpPost] + [Authorize(Policy = AppPermissions.CameraWrite)] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task AssignCamera([FromBody] AssignRequest request, CancellationToken ct) @@ -42,6 +43,7 @@ public class AssignmentsController : ControllerBase /// Assign all cameras in a site using a strategy. [HttpPost("site/{siteId:guid}")] + [Authorize(Policy = AppPermissions.CameraWrite)] [ProducesResponseType(typeof(AssignmentResult), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] public async Task AssignSiteCameras(Guid siteId, [FromQuery] string strategy = "RoundRobin", CancellationToken ct = default) @@ -58,6 +60,7 @@ public class AssignmentsController : ControllerBase /// Trigger failover for an offline agent — reassign its cameras. [HttpPost("failover/{agentId:guid}")] + [Authorize(Policy = AppPermissions.CameraWrite)] [ProducesResponseType(typeof(FailoverResult), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task FailoverAgent(Guid agentId, CancellationToken ct) @@ -111,10 +114,14 @@ public class AssignmentsController : ControllerBase /// Release a camera from its current agent. [HttpDelete("camera/{cameraId:guid}")] + [Authorize(Policy = AppPermissions.CameraWrite)] [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task ReleaseCamera(Guid cameraId, CancellationToken ct) { var result = await _assignmentService.ReleaseCameraAsync(cameraId, ct); - return Ok(); + return result.IsSuccess + ? Ok() + : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); } } diff --git a/src/Heimdall.Api/Controllers/AuthController.cs b/src/Heimdall.Api/Controllers/AuthController.cs index afc214f..02ca8d2 100644 --- a/src/Heimdall.Api/Controllers/AuthController.cs +++ b/src/Heimdall.Api/Controllers/AuthController.cs @@ -1,4 +1,5 @@ using System.Security.Claims; +using Heimdall.Application.Common; using Heimdall.Application.DTOs; using Heimdall.Application.Services; using Heimdall.Infrastructure.Security; @@ -110,4 +111,18 @@ public class AuthController : ControllerBase ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } + + /// Logout — revoke the current refresh token. + [Authorize] + [HttpPost("logout")] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task Logout([FromBody] LogoutRequest request, CancellationToken ct) + { + var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier); + if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId)) + return Unauthorized(); + + await _authService.LogoutAsync(userId, request.RefreshToken, ct); + return Ok(); + } } diff --git a/src/Heimdall.Application/DTOs/AuthDto.cs b/src/Heimdall.Application/DTOs/AuthDto.cs index 11ce06f..deea6ca 100644 --- a/src/Heimdall.Application/DTOs/AuthDto.cs +++ b/src/Heimdall.Application/DTOs/AuthDto.cs @@ -37,3 +37,5 @@ public record CreateApiKeyResponse( DateTime? ExpiresAt); public record ChangePasswordRequest(string CurrentPassword, string NewPassword); + +public record LogoutRequest(string RefreshToken); diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs index 2a6e6a0..5245a0c 100644 --- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs +++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs @@ -9,7 +9,17 @@ namespace Heimdall.Infrastructure.Data; public class AppDbContext : IdentityDbContext { - public AppDbContext(DbContextOptions options) : base(options) { } + private readonly AuditInterceptor _auditInterceptor; + private readonly SoftDeleteInterceptor _softDeleteInterceptor; + + public AppDbContext( + DbContextOptions options, + AuditInterceptor auditInterceptor, + SoftDeleteInterceptor softDeleteInterceptor) : base(options) + { + _auditInterceptor = auditInterceptor; + _softDeleteInterceptor = softDeleteInterceptor; + } // Domain entities public DbSet Sites => Set(); @@ -67,8 +77,8 @@ public class AppDbContext : IdentityDbContext protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.AddInterceptors( - new AuditInterceptor(), - new SoftDeleteInterceptor()); + _auditInterceptor, + _softDeleteInterceptor); // Suppress informational EF Core messages that create noise in // error tracking (GlitchTip #538). Redundant index warnings are diff --git a/src/Heimdall.Infrastructure/Data/AppDbContextFactory.cs b/src/Heimdall.Infrastructure/Data/AppDbContextFactory.cs index 2484bbd..ed64371 100644 --- a/src/Heimdall.Infrastructure/Data/AppDbContextFactory.cs +++ b/src/Heimdall.Infrastructure/Data/AppDbContextFactory.cs @@ -1,3 +1,4 @@ +using Heimdall.Infrastructure.Data.Interceptors; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; @@ -19,6 +20,9 @@ public class AppDbContextFactory : IDesignTimeDbContextFactory optionsBuilder.UseNpgsql(connectionString, npgsql => npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public")); - return new AppDbContext(optionsBuilder.Options); + return new AppDbContext( + optionsBuilder.Options, + new AuditInterceptor(), + new SoftDeleteInterceptor()); } } diff --git a/src/Heimdall.Infrastructure/Data/DbContextExtensions.cs b/src/Heimdall.Infrastructure/Data/DbContextExtensions.cs new file mode 100644 index 0000000..a395578 --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/DbContextExtensions.cs @@ -0,0 +1,32 @@ +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Infrastructure.Data; + +public static class DbContextExtensions +{ + public static async Task SaveChangesWithRetryAsync(this DbContext context, + int maxRetries = 3, CancellationToken ct = default) + { + for (int attempt = 1; attempt <= maxRetries; attempt++) + { + try + { + await context.SaveChangesAsync(ct); + return; + } + catch (Exception ex) when (attempt < maxRetries && IsTransient(ex)) + { + await Task.Delay(TimeSpan.FromMilliseconds(100 * Math.Pow(2, attempt - 1)), ct); + } + } + } + + private static bool IsTransient(Exception ex) + { + if (ex is Npgsql.NpgsqlException npgsqlEx) + { + return npgsqlEx.SqlState is "40001" or "40P01"; + } + return false; + } +} diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs index 93e8682..760370b 100644 --- a/src/Heimdall.Infrastructure/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/DependencyInjection.cs @@ -2,6 +2,7 @@ using System.IO; using Heimdall.Application.Services; using Heimdall.Domain.Entities; using Heimdall.Infrastructure.Data; +using Heimdall.Infrastructure.Data.Interceptors; using Heimdall.Infrastructure.Security; using Heimdall.Infrastructure.Services; using Heimdall.Infrastructure.Services.Discovery; @@ -23,6 +24,10 @@ public static class DependencyInjection var env = environmentName ?? Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"; var isTesting = env == "Testing"; + // EF Core interceptors (registered as singletons — they are stateless) + services.AddSingleton(); + services.AddSingleton(); + if (isTesting) { var dbName = configuration.GetValue("InMemoryDbName") ?? "HeimdallTestDb"; diff --git a/src/Heimdall.Infrastructure/Migrations/20260719195445_AddCameraDiscoveryFields.Designer.cs b/src/Heimdall.Infrastructure/Migrations/20260719195445_AddCameraDiscoveryFields.Designer.cs new file mode 100644 index 0000000..e9c8c6b --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20260719195445_AddCameraDiscoveryFields.Designer.cs @@ -0,0 +1,1548 @@ +// +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("20260719195445_AddCameraDiscoveryFields")] + partial class AddCameraDiscoveryFields + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .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.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.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.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/20260719195445_AddCameraDiscoveryFields.cs b/src/Heimdall.Infrastructure/Migrations/20260719195445_AddCameraDiscoveryFields.cs new file mode 100644 index 0000000..d812516 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20260719195445_AddCameraDiscoveryFields.cs @@ -0,0 +1,202 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + /// + public partial class AddCameraDiscoveryFields : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "Capabilities", + table: "cameras", + type: "character varying(64)", + unicode: false, + maxLength: 64, + nullable: false, + defaultValue: "None"); + + migrationBuilder.AddColumn( + name: "DetectedType", + table: "cameras", + type: "character varying(20)", + unicode: false, + maxLength: 20, + nullable: false, + defaultValue: "Standard"); + + migrationBuilder.AddColumn( + name: "DiscoveryMethod", + table: "cameras", + type: "character varying(20)", + unicode: false, + maxLength: 20, + nullable: false, + defaultValue: "Manual"); + + migrationBuilder.AddColumn( + name: "HttpPort", + table: "cameras", + type: "integer", + nullable: true); + + migrationBuilder.AddColumn( + name: "IpAddress", + table: "cameras", + type: "character varying(45)", + maxLength: 45, + nullable: true); + + migrationBuilder.AddColumn( + name: "LastDiscoveredAt", + table: "cameras", + type: "timestamp with time zone", + nullable: true); + + migrationBuilder.AddColumn( + name: "LastStreamTestAt", + table: "cameras", + type: "timestamp with time zone", + nullable: true); + + migrationBuilder.AddColumn( + name: "LastTestedCodecs", + table: "cameras", + type: "character varying(200)", + unicode: false, + maxLength: 200, + nullable: true); + + migrationBuilder.AddColumn( + name: "LastTestedHeight", + table: "cameras", + type: "integer", + nullable: true); + + migrationBuilder.AddColumn( + name: "LastTestedLatencyMs", + table: "cameras", + type: "bigint", + nullable: true); + + migrationBuilder.AddColumn( + name: "LastTestedWidth", + table: "cameras", + type: "integer", + nullable: true); + + migrationBuilder.AddColumn( + name: "MacAddress", + table: "cameras", + type: "character varying(17)", + maxLength: 17, + nullable: true); + + migrationBuilder.AddColumn( + name: "OnvifPort", + table: "cameras", + type: "integer", + nullable: true); + + migrationBuilder.AddColumn( + name: "RtspPort", + table: "cameras", + type: "integer", + nullable: true); + + migrationBuilder.AddColumn( + name: "SubRtspUrl", + table: "cameras", + type: "character varying(1000)", + unicode: false, + maxLength: 1000, + nullable: true); + + migrationBuilder.CreateIndex( + name: "IX_cameras_IpAddress", + table: "cameras", + column: "IpAddress"); + + migrationBuilder.CreateIndex( + name: "IX_cameras_MacAddress", + table: "cameras", + column: "MacAddress"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_cameras_IpAddress", + table: "cameras"); + + migrationBuilder.DropIndex( + name: "IX_cameras_MacAddress", + table: "cameras"); + + migrationBuilder.DropColumn( + name: "Capabilities", + table: "cameras"); + + migrationBuilder.DropColumn( + name: "DetectedType", + table: "cameras"); + + migrationBuilder.DropColumn( + name: "DiscoveryMethod", + table: "cameras"); + + migrationBuilder.DropColumn( + name: "HttpPort", + table: "cameras"); + + migrationBuilder.DropColumn( + name: "IpAddress", + table: "cameras"); + + migrationBuilder.DropColumn( + name: "LastDiscoveredAt", + table: "cameras"); + + migrationBuilder.DropColumn( + name: "LastStreamTestAt", + table: "cameras"); + + migrationBuilder.DropColumn( + name: "LastTestedCodecs", + table: "cameras"); + + migrationBuilder.DropColumn( + name: "LastTestedHeight", + table: "cameras"); + + migrationBuilder.DropColumn( + name: "LastTestedLatencyMs", + table: "cameras"); + + migrationBuilder.DropColumn( + name: "LastTestedWidth", + table: "cameras"); + + migrationBuilder.DropColumn( + name: "MacAddress", + table: "cameras"); + + migrationBuilder.DropColumn( + name: "OnvifPort", + table: "cameras"); + + migrationBuilder.DropColumn( + name: "RtspPort", + table: "cameras"); + + migrationBuilder.DropColumn( + name: "SubRtspUrl", + table: "cameras"); + } + } +} diff --git a/src/Heimdall.Infrastructure/Services/CameraEventService.cs b/src/Heimdall.Infrastructure/Services/CameraEventService.cs index b1b90b1..8af2c40 100644 --- a/src/Heimdall.Infrastructure/Services/CameraEventService.cs +++ b/src/Heimdall.Infrastructure/Services/CameraEventService.cs @@ -44,22 +44,23 @@ public sealed class CameraEventService : ICameraEventService "Camera event {EventId}: {Type} (confidence={Conf}) for camera {CameraId}", ev.Id, ev.Type, ev.Confidence, ev.CameraId); - // Fire-and-forget broadcast to connected SignalR clients - var broadcastCt = ct; + // Fire-and-forget broadcast to connected SignalR clients. + // Use CancellationToken.None — the broadcast must outlive the HTTP request + // lifecycle so SignalR clients receive the notification even after the + // response is sent. _ = Task.Run(async () => { try { using var scope = _serviceProvider.CreateScope(); var broadcast = scope.ServiceProvider.GetRequiredService(); - await broadcast.NotifyEventCreated(MapResponse(ev), broadcastCt); + await broadcast.NotifyEventCreated(MapResponse(ev), CancellationToken.None); } - catch (OperationCanceledException) when (broadcastCt.IsCancellationRequested) { } catch (Exception ex) { _logger.LogWarning(ex, "Failed to broadcast event {EventId}", ev.Id); } - }, broadcastCt); + }, CancellationToken.None); return ServiceResult.Success(MapResponse(ev)); } diff --git a/src/Heimdall.Web/Components/Layout/MainLayout.razor b/src/Heimdall.Web/Components/Layout/MainLayout.razor index 8a8bbd2..b4ddc2a 100644 --- a/src/Heimdall.Web/Components/Layout/MainLayout.razor +++ b/src/Heimdall.Web/Components/Layout/MainLayout.razor @@ -4,13 +4,13 @@ @inject HeimdallAuthStateProvider AuthStateProvider @inject IJSRuntime JsRuntime - + - Heimdall @@ -23,11 +23,11 @@ @if (Auth.IsLoggedIn) { - - + @@ -110,6 +110,51 @@ @code { private bool _drawerOpen = true; private string _searchQuery = ""; + private readonly MudTheme _theme = new() + { + PaletteLight = new PaletteLight + { + Primary = "#1976D2", + Secondary = "#9E9E9E", + Tertiary = "#009688", + AppbarBackground = "#1565C0", + AppbarText = "#FFFFFF", + Background = "#F5F5F5", + Surface = "#FFFFFF", + DrawerBackground = "#FFFFFF", + DrawerText = "#424242", + TextPrimary = "#212121", + TextSecondary = "#616161", + TextDisabled = "#BDBDBD", + Dark = "#0D47A1", + DarkLighten = "#1976D2", + Info = "#42A5F5", + Warning = "#FF9800", + Error = "#F44336", + Success = "#4CAF50", + }, + PaletteDark = new PaletteDark + { + Primary = "#64B5F6", + Secondary = "#BDBDBD", + Tertiary = "#80CBC4", + AppbarBackground = "#212121", + AppbarText = "#FFFFFF", + Background = "#121212", + Surface = "#424242", + DrawerBackground = "#424242", + DrawerText = "#BDBDBD", + TextPrimary = "#E0E0E0", + TextSecondary = "#BDBDBD", + TextDisabled = "#757575", + Dark = "#1A237E", + DarkLighten = "#1976D2", + Info = "#42A5F5", + Warning = "#FFA726", + Error = "#EF5350", + Success = "#66BB6A", + } + }; private async Task Logout() { diff --git a/src/Heimdall.Web/Components/Pages/Login.razor b/src/Heimdall.Web/Components/Pages/Login.razor index 2707f95..3b1d736 100644 --- a/src/Heimdall.Web/Components/Pages/Login.razor +++ b/src/Heimdall.Web/Components/Pages/Login.razor @@ -85,7 +85,7 @@ if (query.TryGetValue("returnUrl", out var returnUrl)) { var raw = returnUrl.FirstOrDefault() ?? "/dashboard"; - if (raw.StartsWith('/') && !raw.Contains("://", StringComparison.Ordinal)) + if (raw.StartsWith('/') && !raw.StartsWith("//") && !raw.Contains("://", StringComparison.Ordinal)) _returnUrl = raw; } } diff --git a/tests/Heimdall.Infrastructure.Tests/CameraAssignmentServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/CameraAssignmentServiceTests.cs index 25d16e8..f418832 100644 --- a/tests/Heimdall.Infrastructure.Tests/CameraAssignmentServiceTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/CameraAssignmentServiceTests.cs @@ -163,8 +163,13 @@ public class CameraAssignmentServiceTests private sealed class TestDbContextFactory(DbContextOptions opts) : IDbContextFactory { - public AppDbContext CreateDbContext() => new(opts); + private static readonly Heimdall.Infrastructure.Data.Interceptors.AuditInterceptor Audit + = new(); + private static readonly Heimdall.Infrastructure.Data.Interceptors.SoftDeleteInterceptor SoftDelete + = new(); + + public AppDbContext CreateDbContext() => new(opts, Audit, SoftDelete); public Task CreateDbContextAsync(CancellationToken ct = default) - => Task.FromResult(new AppDbContext(opts)); + => Task.FromResult(new AppDbContext(opts, Audit, SoftDelete)); } } diff --git a/tests/Heimdall.Infrastructure.Tests/CameraEventServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/CameraEventServiceTests.cs index fbdfb6f..7b21b9b 100644 --- a/tests/Heimdall.Infrastructure.Tests/CameraEventServiceTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/CameraEventServiceTests.cs @@ -186,8 +186,13 @@ public class CameraEventServiceTests private sealed class TestDbContextFactory(DbContextOptions opts) : IDbContextFactory { - public AppDbContext CreateDbContext() => new(opts); + private static readonly Heimdall.Infrastructure.Data.Interceptors.AuditInterceptor Audit + = new(); + private static readonly Heimdall.Infrastructure.Data.Interceptors.SoftDeleteInterceptor SoftDelete + = new(); + + public AppDbContext CreateDbContext() => new(opts, Audit, SoftDelete); public Task CreateDbContextAsync(CancellationToken ct = default) - => Task.FromResult(new AppDbContext(opts)); + => Task.FromResult(new AppDbContext(opts, Audit, SoftDelete)); } }