diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 8a16920..2435dda 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -61,5 +61,4 @@ volumes: networks: heimdall-net: - name: heimdall-net driver: bridge diff --git a/skills/video-recording/SKILL.md b/skills/video-recording/SKILL.md new file mode 100644 index 0000000..f8a5ad5 --- /dev/null +++ b/skills/video-recording/SKILL.md @@ -0,0 +1,18 @@ +--- +name: video-recording +description: Implement and validate Heimdall Agent video segments, central recording storage, access checks, ranges, and retention. +--- + +# Heimdall video recording + +Recording is opt-in per camera (`RecordingEnabled`, default false). Agent capture is a separate FFmpeg process and only runs while the assigned camera's RTSP stream is already active. Keep RTSP values out of logs, command strings printed to logs, and failure responses. + +- Bound segment duration, size, and Agent spool usage through validated `AgentOptions`; preserve incomplete uploads for retry and make completed segment identifiers stable across retries. +- Upload only MP4 content from the Agent API-key boundary. Validate camera assignment at the API and application boundaries. Persist metadata through `IApplicationDbContext` and use `IRecordingStorage` as the Application port. +- Capture storage destination at upload time. Downloads must check camera access before opening the stored object. Implement byte ranges in the storage adapter rather than downloading whole objects for partial playback. +- The CameraDetail recording list/player uses the authorized API client for metadata and same-origin `/api/recordings/{id}/content` URLs for browser Range requests. Keep the export link on that authorized endpoint and never render an arbitrary storage URL. +- Preserve the existing recording retention policy and storage-final orphan sweep. Ensure recording rows are removed only after object deletion succeeds; do not guess destinations for legacy rows without provenance. +- Add PostgreSQL tests for migration, metadata/idempotency, camera access, range translation, and retention semantics when touching those paths. Agent tests should cover bounded argument construction, defaults, and spool/config behavior. +- For acceptance, build Central from this changed source in a unique disposable Compose project. Register an isolated Agent and synthetic RTSP source, enable recording, prove at least one segment reaches Central, verify scoped list/range download and unauthorized denial, then remove only that Compose project and confirm its containers/volumes/network are gone. + +Current product gaps are audio/event-trigger capture, an explicit Central storage quota, and validation against real cameras/codecs. Keep FEAT-02 open until these are addressed and validated. diff --git a/src/Heimdall.Agent/AgentOptions.cs b/src/Heimdall.Agent/AgentOptions.cs index eda76cf..98eab52 100644 --- a/src/Heimdall.Agent/AgentOptions.cs +++ b/src/Heimdall.Agent/AgentOptions.cs @@ -51,6 +51,17 @@ public sealed class AgentOptions /// Directory for persisting agent identity state. Defaults to /var/lib/heimdall on Linux. public string? StateDirectory { get; init; } + /// Length of completed MP4 segments created for recording-enabled cameras. + [Range(5, 300)] + public int RecordingSegmentSeconds { get; init; } = 60; + + /// Upper bound for queued completed recordings kept locally while Central is unavailable. + [Range(typeof(long), "16777216", "107374182400")] + public long RecordingSpoolMaxBytes { get; init; } = 1_073_741_824; + + /// FFmpeg executable used for opt-in segment recording. + public string RecordingFfmpegPath { get; init; } = "ffmpeg"; + /// Max retries for agent registration (default: 5). [Range(1, 20)] public int RegistrationMaxRetries { get; init; } = 5; diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index 61c6d94..1ceb708 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -171,6 +171,7 @@ builder.Services.AddSingleton(sp => new SnapshotPipelineService(new SnapshotPipe sp.GetRequiredService(), sp.GetRequiredService()))); builder.Services.AddHostedService(sp => sp.GetRequiredService()); +builder.Services.AddHostedService(); // Log capture & upload to Central (ticket #50) builder.Services.AddSingleton(); diff --git a/src/Heimdall.Agent/Services/AgentCameraConfig.cs b/src/Heimdall.Agent/Services/AgentCameraConfig.cs index e2fb29b..0603193 100644 --- a/src/Heimdall.Agent/Services/AgentCameraConfig.cs +++ b/src/Heimdall.Agent/Services/AgentCameraConfig.cs @@ -11,7 +11,8 @@ public sealed record AgentCameraConfig( string RtspUrl, string? SubRtspUrl, bool Enabled, - Heimdall.Application.DTOs.DetectionProfileDto? DetectionProfile = null) + Heimdall.Application.DTOs.DetectionProfileDto? DetectionProfile = null, + bool RecordingEnabled = false) { /// /// URL used for AI capture: the low-res sub-stream when available, diff --git a/src/Heimdall.Agent/Services/AgentRecordingService.cs b/src/Heimdall.Agent/Services/AgentRecordingService.cs new file mode 100644 index 0000000..647c910 --- /dev/null +++ b/src/Heimdall.Agent/Services/AgentRecordingService.cs @@ -0,0 +1,315 @@ +using System.Diagnostics; +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using Heimdall.Agent.Services; +using Microsoft.Extensions.Options; + +namespace Heimdall.Agent; + +/// +/// Starts an opt-in FFmpeg segment process for enabled cameras, persists completed +/// segments under the Agent state volume, and retries uploads until Central acknowledges them. +/// +public sealed class AgentRecordingService : BackgroundService +{ + private const long MaxSegmentBytes = 100 * 1024 * 1024; + private static readonly TimeSpan LoopDelay = TimeSpan.FromSeconds(5); + private readonly CameraConfigStore _cameras; + private readonly CameraStreamService _streams; + private readonly AgentState _state; + private readonly AgentOptions _options; + private readonly IHttpClientFactory _clients; + private readonly ILogger _logger; + private readonly Dictionary _sessions = []; + private readonly SemaphoreSlim _lifecycle = new(1, 1); + private string _spoolRoot = string.Empty; + + public AgentRecordingService(CameraConfigStore cameras, CameraStreamService streams, AgentState state, + IOptions options, IHttpClientFactory clients, ILogger logger) + { + _cameras = cameras; + _streams = streams; + _state = state; + _options = options.Value; + _clients = clients; + _logger = logger; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + var stateDirectory = _options.StateDirectory ?? + (OperatingSystem.IsLinux() ? "/var/lib/heimdall" : Directory.GetCurrentDirectory()); + _spoolRoot = Path.GetFullPath(Path.Combine(stateDirectory, "recordings")); + Directory.CreateDirectory(_spoolRoot); + if (OperatingSystem.IsLinux()) + File.SetUnixFileMode(_spoolRoot, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + + try + { + while (!stoppingToken.IsCancellationRequested) + { + try + { + await ReconcileAsync(stoppingToken).ConfigureAwait(false); + await UploadCompletedSegmentsAsync(stoppingToken).ConfigureAwait(false); + await TrimSpoolAsync(stoppingToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } + catch (Exception ex) + { + _logger.LogWarning("Recording loop failed (error type {ErrorType})", ex.GetType().Name); + } + await Task.Delay(LoopDelay, stoppingToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { } + finally + { + foreach (var cameraId in _sessions.Keys.ToArray()) + await StopSessionAsync(cameraId, CancellationToken.None).ConfigureAwait(false); + } + } + + private async Task ReconcileAsync(CancellationToken ct) + { + await _lifecycle.WaitAsync(ct).ConfigureAwait(false); + try + { + var configured = _cameras.Cameras.ToDictionary(c => c.CameraId); + foreach (var (cameraId, session) in _sessions.ToArray()) + { + if (!configured.TryGetValue(cameraId, out var camera) || !camera.Enabled || !camera.RecordingEnabled || + camera.RtspUrl != session.RtspUrl || !_streams.IsStreamActive(cameraId) || session.Process.HasExited) + await StopSessionCoreAsync(cameraId, session, ct).ConfigureAwait(false); + } + + foreach (var camera in configured.Values.Where(c => c.Enabled && c.RecordingEnabled && + !string.IsNullOrWhiteSpace(c.RtspUrl))) + { + if (_streams.IsStreamActive(camera.CameraId) && !_sessions.ContainsKey(camera.CameraId)) + StartSession(camera); + } + } + finally { _lifecycle.Release(); } + } + + private void StartSession(AgentCameraConfig camera) + { + var cameraRoot = Path.Combine(_spoolRoot, camera.CameraId.ToString("N")); + var sessionDirectory = Path.Combine(cameraRoot, Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(sessionDirectory); + if (OperatingSystem.IsLinux()) + File.SetUnixFileMode(sessionDirectory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + var startedAt = DateTime.UtcNow; + File.WriteAllText(Path.Combine(sessionDirectory, "started-at.txt"), startedAt.ToString("O", CultureInfo.InvariantCulture)); + var startInfo = CreateStartInfo(_options.RecordingFfmpegPath, camera.RtspUrl!, sessionDirectory, + _options.RecordingSegmentSeconds); + Process? process = null; + try + { + process = new Process { StartInfo = startInfo, EnableRaisingEvents = true }; + if (!process.Start()) throw new InvalidOperationException("FFmpeg did not start"); + var session = new RecordingSession(camera.CameraId, camera.RtspUrl!, sessionDirectory, startedAt, process); + _sessions[camera.CameraId] = session; + session.ErrorDrain = DrainStandardErrorAsync(process); + _logger.LogInformation("Video recording started for camera {CameraId}", camera.CameraId); + } + catch (Exception ex) + { + process?.Dispose(); + _logger.LogWarning("Video recording could not start for camera {CameraId} (error type {ErrorType})", + camera.CameraId, ex.GetType().Name); + } + } + + internal static ProcessStartInfo CreateStartInfo(string ffmpegPath, string rtspUrl, string sessionDirectory, + int segmentSeconds) + { + var info = new ProcessStartInfo + { + FileName = ffmpegPath, + RedirectStandardInput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + }; + foreach (var argument in new[] + { + "-hide_banner", "-loglevel", "error", "-rtsp_transport", "tcp", "-i", rtspUrl, + "-map", "0:v:0", "-c:v", "copy", "-f", "segment", "-segment_time", + segmentSeconds.ToString(CultureInfo.InvariantCulture), "-segment_format", "mp4", + "-reset_timestamps", "1", "-segment_list", Path.Combine(sessionDirectory, "segments.csv"), + "-segment_list_type", "csv", "-segment_list_size", "10000", + Path.Combine(sessionDirectory, "segment-%06d.mp4") + }) info.ArgumentList.Add(argument); + return info; + } + + private static async Task DrainStandardErrorAsync(Process process) + { + try + { + while (await process.StandardError.ReadLineAsync().ConfigureAwait(false) is not null) { } + } + catch (IOException) { } + catch (ObjectDisposedException) { } + } + + private async Task StopSessionAsync(Guid cameraId, CancellationToken ct) + { + await _lifecycle.WaitAsync(ct).ConfigureAwait(false); + try + { + if (_sessions.TryGetValue(cameraId, out var session)) + await StopSessionCoreAsync(cameraId, session, ct).ConfigureAwait(false); + } + finally { _lifecycle.Release(); } + } + + private async Task StopSessionCoreAsync(Guid cameraId, RecordingSession session, CancellationToken ct) + { + _sessions.Remove(cameraId); + try + { + if (!session.Process.HasExited) + { + try { await session.Process.StandardInput.WriteLineAsync("q").ConfigureAwait(false); } + catch (IOException) { } + try { await session.Process.WaitForExitAsync(ct).WaitAsync(TimeSpan.FromSeconds(5), ct).ConfigureAwait(false); } + catch (TimeoutException) { session.Process.Kill(entireProcessTree: true); } + catch (InvalidOperationException) { } + } + if (session.ErrorDrain is not null) await session.ErrorDrain.ConfigureAwait(false); + _logger.LogInformation("Video recording stopped for camera {CameraId}", cameraId); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + catch (Exception ex) + { + _logger.LogDebug("FFmpeg cleanup failed for camera {CameraId} (error type {ErrorType})", cameraId, ex.GetType().Name); + } + finally { session.Process.Dispose(); } + } + + private async Task UploadCompletedSegmentsAsync(CancellationToken ct) + { + if (!Directory.Exists(_spoolRoot)) return; + foreach (var manifest in Directory.EnumerateFiles(_spoolRoot, "segments.csv", SearchOption.AllDirectories)) + { + ct.ThrowIfCancellationRequested(); + if (!Guid.TryParseExact(Directory.GetParent(Directory.GetParent(manifest)!.FullName)!.Name, "N", out var cameraId)) + continue; + DateTime startedAt; + try + { + startedAt = DateTime.Parse(File.ReadAllText(Path.Combine(Path.GetDirectoryName(manifest)!, "started-at.txt")), + CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind).ToUniversalTime(); + } + catch (IOException) { continue; } + catch (FormatException) { continue; } + string[] rows; + try { rows = await File.ReadAllLinesAsync(manifest, ct).ConfigureAwait(false); } + catch (IOException) { continue; } + foreach (var row in rows) + { + var fields = row.Split(','); + if (fields.Length < 3) continue; + var fileName = Path.GetFileName(fields[0]); + if (!fileName.StartsWith("segment-", StringComparison.Ordinal) || !fileName.EndsWith(".mp4", StringComparison.Ordinal) || + !double.TryParse(fields[1], CultureInfo.InvariantCulture, out var startSeconds) || + !double.TryParse(fields[2], CultureInfo.InvariantCulture, out var endSeconds)) continue; + var duration = endSeconds - startSeconds; + if (duration is < 1 or > 300 || !double.IsFinite(duration) || !double.IsFinite(startSeconds)) continue; + var path = Path.Combine(Path.GetDirectoryName(manifest)!, fileName); + if (!File.Exists(path)) continue; + var info = new FileInfo(path); + if (info.Length > MaxSegmentBytes) + { + _logger.LogWarning("Dropping oversized video segment for camera {CameraId} ({SizeBytes} bytes)", cameraId, info.Length); + info.Delete(); + continue; + } + await UploadSegmentAsync(cameraId, path, startedAt.AddSeconds(startSeconds), duration, ct).ConfigureAwait(false); + } + } + } + + private async Task UploadSegmentAsync(Guid cameraId, string path, DateTime timestamp, double duration, CancellationToken ct) + { + var relativePath = Path.GetRelativePath(_spoolRoot, path).Replace(Path.DirectorySeparatorChar, '/'); + var hash = SHA256.HashData(Encoding.UTF8.GetBytes(relativePath)); + var recordingId = new Guid(hash.AsSpan(0, 16)); + var url = $"api/cameras/{cameraId:D}/recordings/{recordingId:D}/content?timestamp={Uri.EscapeDataString(timestamp.ToString("O", CultureInfo.InvariantCulture))}&durationSeconds={duration.ToString(CultureInfo.InvariantCulture)}"; + try + { + using var request = new HttpRequestMessage(HttpMethod.Put, url); + request.Headers.Add("X-API-Key", _state.ApiKey); + await using var input = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, + 128 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan); + request.Content = new StreamContent(input); + request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("video/mp4"); + request.Content.Headers.ContentLength = input.Length; + using var response = await _clients.CreateClient("Central").SendAsync(request, + HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + { + _logger.LogWarning("Video segment upload returned HTTP {StatusCode} for camera {CameraId}", + (int)response.StatusCode, cameraId); + return; + } + input.Close(); + File.Delete(path); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + catch (HttpRequestException ex) + { + _logger.LogWarning("Video segment upload failed for camera {CameraId} (error type {ErrorType})", + cameraId, ex.GetType().Name); + } + catch (IOException ex) + { + _logger.LogWarning("Video segment could not be read or removed for camera {CameraId} (error type {ErrorType})", + cameraId, ex.GetType().Name); + } + } + + private async Task TrimSpoolAsync(CancellationToken ct) + { + var ready = new List(); + foreach (var manifest in Directory.EnumerateFiles(_spoolRoot, "segments.csv", SearchOption.AllDirectories)) + { + string[] rows; + try { rows = await File.ReadAllLinesAsync(manifest, ct).ConfigureAwait(false); } + catch (IOException) { continue; } + foreach (var row in rows) + { + var fileName = Path.GetFileName(row.Split(',')[0]); + if (!fileName.StartsWith("segment-", StringComparison.Ordinal) || !fileName.EndsWith(".mp4", StringComparison.Ordinal)) continue; + var path = Path.Combine(Path.GetDirectoryName(manifest)!, fileName); + if (File.Exists(path)) ready.Add(new FileInfo(path)); + } + } + var total = ready.Sum(file => file.Length); + foreach (var file in ready.OrderBy(file => file.LastWriteTimeUtc)) + { + if (total <= _options.RecordingSpoolMaxBytes) break; + ct.ThrowIfCancellationRequested(); + var size = file.Length; + try + { + file.Delete(); + total -= size; + _logger.LogWarning("Dropping oldest queued video segment for camera {CameraId}; local recording spool reached its configured limit", + Path.GetFileName(Path.GetDirectoryName(Path.GetDirectoryName(file.FullName)))); + } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + } + } + + private sealed record RecordingSession(Guid CameraId, string RtspUrl, string Directory, + DateTime StartedAt, Process Process) + { + public Task? ErrorDrain { get; set; } + } +} diff --git a/src/Heimdall.Agent/Services/CameraConfigStore.cs b/src/Heimdall.Agent/Services/CameraConfigStore.cs index 3913e87..fb94add 100644 --- a/src/Heimdall.Agent/Services/CameraConfigStore.cs +++ b/src/Heimdall.Agent/Services/CameraConfigStore.cs @@ -102,6 +102,7 @@ public sealed class CameraConfigStore "rtsp" => existing with { RtspUrl = value }, "sub_rtsp" => existing with { SubRtspUrl = value }, "enabled" => existing with { Enabled = ParseBool(value) }, + "recording_enabled" => existing with { RecordingEnabled = ParseBool(value) }, "profile" => existing with { DetectionProfile = ParseProfile(value) }, _ => throw new ArgumentException($"Unknown camera configuration field: {field}", nameof(field)) }; diff --git a/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs b/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs index e0779d5..30f1abc 100644 --- a/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs +++ b/src/Heimdall.Application/Cameras/Commands/CreateCamera/CreateCameraCommand.cs @@ -53,5 +53,5 @@ public class CreateCameraCommandHandler : IRequestHandler>; + Guid? ActorId = null, + bool? RecordingEnabled = null) : IRequest>; public class UpdateCameraCommandHandler : IRequestHandler> { @@ -48,11 +49,14 @@ public class UpdateCameraCommandHandler : IRequestHandlerStorage operations for recording media, bound to the captured destination. +public interface IRecordingStorage +{ + StorageLocation CaptureCurrentLocation(); + Task UploadAsync(string key, Stream content, string contentType, StorageLocation location, CancellationToken ct = default); + Task DownloadAsync(string key, StorageLocation location, CancellationToken ct = default); + Task DownloadRangeAsync(string key, StorageLocation location, long start, long endInclusive, + CancellationToken ct = default); +} diff --git a/src/Heimdall.Application/Common/IStorageProvider.cs b/src/Heimdall.Application/Common/IStorageProvider.cs index b413c94..b13b8fc 100644 --- a/src/Heimdall.Application/Common/IStorageProvider.cs +++ b/src/Heimdall.Application/Common/IStorageProvider.cs @@ -20,6 +20,9 @@ public interface IStorageProvider /// Open a stream for reading a stored object. Null when missing. Task DownloadAsync(string key, CancellationToken ct = default); + /// Open a single inclusive byte range without downloading the rest of the object. + Task DownloadRangeAsync(string key, long start, long endInclusive, CancellationToken ct = default); + /// Delete a single object. No-op when missing. Task DeleteAsync(string key, CancellationToken ct = default); diff --git a/src/Heimdall.Application/DTOs/CameraDto.cs b/src/Heimdall.Application/DTOs/CameraDto.cs index 46bbc52..9e980a0 100644 --- a/src/Heimdall.Application/DTOs/CameraDto.cs +++ b/src/Heimdall.Application/DTOs/CameraDto.cs @@ -15,7 +15,8 @@ public record UpdateCameraRequest( CameraStatus? Status, string? Manufacturer = null, string? Model = null, - DetectionProfileDto? DetectionProfile = null); + DetectionProfileDto? DetectionProfile = null, + bool? RecordingEnabled = null); /// Camera response including all discovery and stream test metadata. public record CameraResponse( @@ -45,4 +46,5 @@ public record CameraResponse( bool HasPtz, bool HasAudio, bool HasMotionDetection, - DateTime CreatedAt); + DateTime CreatedAt, + bool RecordingEnabled = false); diff --git a/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs b/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs index 754b47e..92f12bd 100644 --- a/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs +++ b/src/Heimdall.Application/Groups/Queries/GetCamerasByGroup/GetCamerasByGroupQuery.cs @@ -45,10 +45,10 @@ public class GetCamerasByGroupHandler : IRequestHandler>.Success( new PagedResult(items, total, request.Page, request.PageSize)); } -} \ No newline at end of file +} diff --git a/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs b/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs new file mode 100644 index 0000000..afc8fc5 --- /dev/null +++ b/src/Heimdall.Application/Recordings/Commands/UploadRecording/UploadRecordingCommand.cs @@ -0,0 +1,69 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Recordings; +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Application.Recordings.Commands.UploadRecording; + +public sealed record UploadRecordingCommand( + Guid AgentId, + Guid CameraId, + Guid RecordingId, + DateTime Timestamp, + double DurationSeconds, + long SizeBytes, + Stream Content) : IRequest>; + +public sealed class UploadRecordingHandler( + IApplicationDbContext db, + IRecordingStorage storage) : IRequestHandler> +{ + public async Task> Handle(UploadRecordingCommand request, CancellationToken ct) + { + if (request.AgentId == Guid.Empty || request.CameraId == Guid.Empty || request.RecordingId == Guid.Empty || + request.DurationSeconds is < 1 or > 300 || !double.IsFinite(request.DurationSeconds) || + request.SizeBytes is < 12 or > 100 * 1024 * 1024 || request.Content.CanSeek && request.Content.Length != request.SizeBytes) + return ServiceResult.Failure("Invalid recording segment metadata", 400); + + var camera = await db.Cameras.AsNoTracking() + .Where(c => c.Id == request.CameraId && !c.IsDeleted) + .Select(c => new { c.Id, c.AgentId, c.StoragePolicyId }) + .SingleOrDefaultAsync(ct).ConfigureAwait(false); + if (camera?.AgentId != request.AgentId) + return ServiceResult.NotFound("Camera not found"); + + var existing = await db.Recordings.AsNoTracking() + .Where(r => r.Id == request.RecordingId) + .Select(r => new { r.Id, r.CameraId, r.Timestamp, r.DurationSeconds, r.SizeBytes }) + .SingleOrDefaultAsync(ct).ConfigureAwait(false); + if (existing is not null) + return existing.CameraId == request.CameraId + ? ServiceResult.Success(Map(existing.Id, existing.CameraId, existing.Timestamp, existing.DurationSeconds, existing.SizeBytes)) + : ServiceResult.Conflict("Recording identifier already belongs to another camera"); + + var timestamp = CameraEvent.NormalizeOccurredAt(request.Timestamp); + var location = storage.CaptureCurrentLocation(); + var key = $"recordings/{request.CameraId:D}/{request.RecordingId:D}.mp4"; + if (request.Content.CanSeek) request.Content.Position = 0; + await storage.UploadAsync(key, request.Content, "video/mp4", location, ct).ConfigureAwait(false); + + var recording = new Recording(request.CameraId, timestamp, request.DurationSeconds, + key, request.SizeBytes, location.Provider, location, camera.StoragePolicyId, request.RecordingId); + db.Recordings.Add(recording); + await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); + + var end = timestamp.AddSeconds(request.DurationSeconds); + await db.CameraEvents + .Where(e => e.CameraId == request.CameraId && e.RecordingId == null && e.OccurredAt >= timestamp && e.OccurredAt < end) + .ExecuteUpdateAsync(setters => setters.SetProperty(e => e.RecordingId, recording.Id), ct) + .ConfigureAwait(false); + + return ServiceResult.Success(Map(recording.Id, recording.CameraId, + recording.Timestamp, recording.DurationSeconds, recording.SizeBytes)); + } + + private static RecordingDto Map(Guid id, Guid cameraId, DateTime timestamp, double duration, long size) => + new(id, cameraId, timestamp, duration, size, $"/api/recordings/{id:D}/content"); +} diff --git a/src/Heimdall.Application/Recordings/Queries/GetCameraRecordings/GetCameraRecordingsQuery.cs b/src/Heimdall.Application/Recordings/Queries/GetCameraRecordings/GetCameraRecordingsQuery.cs new file mode 100644 index 0000000..20a4c74 --- /dev/null +++ b/src/Heimdall.Application/Recordings/Queries/GetCameraRecordings/GetCameraRecordingsQuery.cs @@ -0,0 +1,37 @@ +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; +using Heimdall.Application.Recordings; +using Heimdall.Application.Services; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Application.Recordings.Queries.GetCameraRecordings; + +public sealed record GetCameraRecordingsQuery(Guid CameraId, Guid UserId, DateTime? From, DateTime? To, int Page, int PageSize) + : IRequest>>; + +public sealed class GetCameraRecordingsHandler( + IApplicationDbContext db, + ICameraAccessService access) : IRequestHandler>> +{ + public async Task>> Handle(GetCameraRecordingsQuery request, CancellationToken ct) + { + if (request.Page < 1 || request.PageSize is < 1 or > 100 || + request.From.HasValue && request.To.HasValue && request.From >= request.To) + return ServiceResult>.Failure("Invalid recording page or time range", 400); + if (!await access.HasCameraAccessAsync(request.UserId, request.CameraId, ct).ConfigureAwait(false)) + return ServiceResult>.NotFound("Camera not found"); + + var query = db.Recordings.AsNoTracking().Where(r => r.CameraId == request.CameraId); + if (request.From is DateTime from) query = query.Where(r => r.Timestamp >= from); + if (request.To is DateTime to) query = query.Where(r => r.Timestamp < to); + var total = await query.CountAsync(ct).ConfigureAwait(false); + var rows = await query.OrderByDescending(r => r.Timestamp) + .Skip((request.Page - 1) * request.PageSize).Take(request.PageSize) + .Select(r => new { r.Id, r.CameraId, r.Timestamp, r.DurationSeconds, r.SizeBytes }) + .ToListAsync(ct).ConfigureAwait(false); + var items = rows.Select(r => new RecordingDto(r.Id, r.CameraId, r.Timestamp, + r.DurationSeconds, r.SizeBytes, $"/api/recordings/{r.Id:D}/content")).ToArray(); + return ServiceResult>.Success(new(items, total, request.Page, request.PageSize)); + } +} diff --git a/src/Heimdall.Application/Recordings/Queries/GetRecordingContent/GetRecordingContentQuery.cs b/src/Heimdall.Application/Recordings/Queries/GetRecordingContent/GetRecordingContentQuery.cs new file mode 100644 index 0000000..fd557b8 --- /dev/null +++ b/src/Heimdall.Application/Recordings/Queries/GetRecordingContent/GetRecordingContentQuery.cs @@ -0,0 +1,64 @@ +using Heimdall.Application.Common; +using Heimdall.Application.Recordings; +using Heimdall.Application.Services; +using MediatR; +using Microsoft.EntityFrameworkCore; + +namespace Heimdall.Application.Recordings.Queries.GetRecordingContent; + +public sealed record GetRecordingContentQuery(Guid RecordingId, Guid UserId, + long? RangeStart = null, long? RangeEnd = null, long? SuffixLength = null) + : IRequest>; + +public sealed class GetRecordingContentHandler( + IApplicationDbContext db, + ICameraAccessService access, + IRecordingStorage storage) : IRequestHandler> +{ + public async Task> Handle(GetRecordingContentQuery request, CancellationToken ct) + { + var recording = await db.Recordings.AsNoTracking() + .Where(r => r.Id == request.RecordingId) + .Select(r => new + { + r.CameraId, r.StoragePath, r.SizeBytes, r.StorageProvider, + r.StorageRoot, r.StorageEndpoint, r.StorageBucket, r.StorageLocationCaptured + }) + .SingleOrDefaultAsync(ct).ConfigureAwait(false); + if (recording is null || !recording.StorageLocationCaptured || + !await access.HasCameraAccessAsync(request.UserId, recording.CameraId, ct).ConfigureAwait(false)) + return ServiceResult.NotFound("Recording not found"); + + var location = new Heimdall.Domain.Entities.StorageLocation(recording.StorageProvider, + recording.StorageRoot, recording.StorageEndpoint, recording.StorageBucket); + if (!location.IsComplete) + return ServiceResult.NotFound("Recording not found"); + if (request.SuffixLength is <= 0 || request.RangeStart is < 0 || request.RangeEnd is < 0 || + request.RangeStart.HasValue && request.SuffixLength.HasValue) + return ServiceResult.Failure("Invalid byte range", 416); + + var isPartial = request.RangeStart.HasValue || request.SuffixLength.HasValue; + var start = request.SuffixLength is long suffix + ? Math.Max(0, recording.SizeBytes - suffix) + : request.RangeStart ?? 0; + var end = Math.Min(request.RangeEnd ?? recording.SizeBytes - 1, recording.SizeBytes - 1); + if (isPartial && (start >= recording.SizeBytes || end < start)) + return ServiceResult.Failure("Byte range is not satisfiable", 416); + + Stream? stream; + try + { + stream = isPartial + ? await storage.DownloadRangeAsync(recording.StoragePath, location, start, end, ct).ConfigureAwait(false) + : await storage.DownloadAsync(recording.StoragePath, location, ct).ConfigureAwait(false); + } + catch (ArgumentOutOfRangeException) + { + return ServiceResult.Failure("Byte range is not satisfiable", 416); + } + return stream is null + ? ServiceResult.NotFound("Recording content not found") + : ServiceResult.Success(new(stream, recording.SizeBytes, start, + isPartial ? end - start + 1 : recording.SizeBytes, isPartial, "video/mp4")); + } +} diff --git a/src/Heimdall.Application/Recordings/RecordingDtos.cs b/src/Heimdall.Application/Recordings/RecordingDtos.cs new file mode 100644 index 0000000..fd61d7c --- /dev/null +++ b/src/Heimdall.Application/Recordings/RecordingDtos.cs @@ -0,0 +1,12 @@ +namespace Heimdall.Application.Recordings; + +public sealed record RecordingDto( + Guid Id, + Guid CameraId, + DateTime Timestamp, + double DurationSeconds, + long SizeBytes, + string ContentUrl); + +public sealed record RecordingContent(Stream Stream, long SizeBytes, long Offset, long ContentLength, + bool IsPartial, string ContentType); diff --git a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs index db7e3fb..5b97fd2 100644 --- a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs +++ b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs @@ -121,6 +121,7 @@ public class GetEffectiveAgentConfigQueryHandler if (!string.IsNullOrWhiteSpace(camera.SubRtspUrl)) config[$"{prefix}.sub_rtsp"] = camera.SubRtspUrl; config[$"{prefix}.enabled"] = camera.Status != CameraStatus.Disabled ? "true" : "false"; + config[$"{prefix}.recording_enabled"] = camera.RecordingEnabled ? "true" : "false"; } return ServiceResult>.Success(config); diff --git a/src/Heimdall.Domain/Entities/Camera.cs b/src/Heimdall.Domain/Entities/Camera.cs index 2dce07c..fac65dd 100644 --- a/src/Heimdall.Domain/Entities/Camera.cs +++ b/src/Heimdall.Domain/Entities/Camera.cs @@ -13,6 +13,8 @@ public class Camera : Entity, IAuditableEntity, ISoftDeletable public string? Model { get; private set; } public string? RtspUrl { get; private set; } public CameraStatus Status { get; private set; } = CameraStatus.Disabled; + /// Whether the assigned Agent stores bounded video segments for this camera. + public bool RecordingEnabled { get; private set; } // ── Discovery ─────────────────────────────────────────────────── /// How this camera was discovered (manual, ONVIF, mDNS, etc.). @@ -111,6 +113,7 @@ public class Camera : Entity, IAuditableEntity, ISoftDeletable } public void SetStatus(CameraStatus status) => Status = status; + public void SetRecordingEnabled(bool enabled) => RecordingEnabled = enabled; public void SetCapabilities(bool ptz, bool audio, bool motion) { diff --git a/src/Heimdall.Domain/Entities/Recording.cs b/src/Heimdall.Domain/Entities/Recording.cs index e6bc01d..fe7aff9 100644 --- a/src/Heimdall.Domain/Entities/Recording.cs +++ b/src/Heimdall.Domain/Entities/Recording.cs @@ -37,8 +37,9 @@ public class Recording : Entity, IAuditableEntity long sizeBytes, StorageProvider storageProvider, StorageLocation storageLocation, - Guid? storagePolicyId = null) - : base(Guid.NewGuid()) + Guid? storagePolicyId = null, + Guid? id = null) + : base(id ?? Guid.NewGuid()) { CameraId = cameraId; Timestamp = timestamp; diff --git a/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs index 7ac1afe..9648181 100644 --- a/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs +++ b/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs @@ -35,6 +35,10 @@ public class CameraConfiguration : IEntityTypeConfiguration .IsRequired() .IsUnicode(false); + builder.Property(c => c.RecordingEnabled) + .HasDefaultValue(false) + .IsRequired(); + // ── Discovery ─────────────────────────────────────────────── builder.Property(c => c.DiscoveryMethod) .HasConversion() diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs index 64f5af7..6973e32 100644 --- a/src/Heimdall.Infrastructure/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/DependencyInjection.cs @@ -52,6 +52,7 @@ public static class DependencyInjection services.AddSingleton(); services.AddScoped(sp => sp.GetRequiredService()); services.AddScoped(sp => sp.GetRequiredService()); + services.AddScoped(); // Health checks (spec 13.2) — PostgreSQL + dépendances optionnelles. services.AddHealthChecks() diff --git a/src/Heimdall.Infrastructure/Migrations/20261104202743_AddCameraRecordingEnabled.Designer.cs b/src/Heimdall.Infrastructure/Migrations/20261104202743_AddCameraRecordingEnabled.Designer.cs new file mode 100644 index 0000000..8fae6a1 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261104202743_AddCameraRecordingEnabled.Designer.cs @@ -0,0 +1,2892 @@ +// +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("20261104202743_AddCameraRecordingEnabled")] + partial class AddCameraRecordingEnabled + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .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("Arch") + .HasColumnType("text"); + + b.Property("ContainerCpuLimit") + .HasColumnType("bigint"); + + b.Property("ContainerId") + .HasColumnType("text"); + + b.Property("ContainerImage") + .HasColumnType("text"); + + b.Property("ContainerMemoryLimitBytes") + .HasColumnType("bigint"); + + b.Property("CpuArchitecture") + .HasColumnType("text"); + + b.Property("CpuCacheBytes") + .HasColumnType("bigint"); + + b.Property("CpuCores") + .HasColumnType("integer"); + + b.Property("CpuFlags") + .HasColumnType("text"); + + b.Property("CpuFrequencyMhz") + .HasColumnType("double precision"); + + b.Property("CpuModel") + .HasColumnType("text"); + + b.Property("CpuUsagePercent") + .HasColumnType("double precision"); + + b.Property("CpuVendor") + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiskInventoryJson") + .HasColumnType("text"); + + b.Property("DiskUsagePercent") + .HasColumnType("double precision"); + + b.Property("GpuInventoryJson") + .HasColumnType("text"); + + b.Property("GpuLoadPercent") + .HasColumnType("double precision"); + + b.Property("GpuName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + 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("InventoryObservedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("KernelVersion") + .HasColumnType("text"); + + b.Property("LastAppliedCameraConfigAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastAppliedCameraConfigVersion") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("LastHeartbeat") + .HasColumnType("timestamp with time zone"); + + b.Property("LogicalCores") + .HasColumnType("integer"); + + b.Property("MemAvailableBytes") + .HasColumnType("bigint"); + + b.Property("MemTotalBytes") + .HasColumnType("bigint"); + + b.Property("MemoryMb") + .HasColumnType("bigint"); + + b.Property("MemoryUsageBytes") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("NetworkInterfacesJson") + .HasColumnType("text"); + + b.Property("OsName") + .HasColumnType("text"); + + b.Property("PhysicalCores") + .HasColumnType("integer"); + + 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("SwapFreeBytes") + .HasColumnType("bigint"); + + b.Property("SwapTotalBytes") + .HasColumnType("bigint"); + + b.Property("TemperatureJson") + .HasColumnType("text"); + + b.Property("ThreadsPerCore") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UptimeMachineSeconds") + .HasColumnType("bigint"); + + b.Property("UptimeSeconds") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("VramMb") + .HasColumnType("bigint"); + + b.Property("VramUsageBytes") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("LastHeartbeat") + .HasFilter("\"Status\" = 'Online'"); + + b.HasIndex("SiteId"); + + b.ToTable("agents", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Exception") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Level") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Source") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "TimestampUtc"); + + b.ToTable("agent_log_entries", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentMetricSample", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CapturedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CpuUsagePercent") + .HasColumnType("double precision"); + + b.Property("DiskUsagePercent") + .HasColumnType("double precision"); + + b.Property("GpuTemperatureCelsius") + .HasColumnType("double precision"); + + b.Property("GpuUtilizationPercent") + .HasColumnType("double precision"); + + b.Property("InventoryObservedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LogicalCores") + .HasColumnType("integer"); + + b.Property("MemAvailableBytes") + .HasColumnType("bigint"); + + b.Property("MemTotalBytes") + .HasColumnType("bigint"); + + b.Property("MemoryUsageBytes") + .HasColumnType("bigint"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("TemperatureJson") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("CapturedAtUtc"); + + b.HasIndex("AgentId", "CapturedAtUtc") + .IsUnique(); + + b.HasIndex("SiteId", "CapturedAtUtc"); + + b.ToTable("agent_metric_samples", (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.AnalysisJob", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AssignedAgentId") + .HasColumnType("uuid"); + + b.Property("AttemptId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CompletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DispatchedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ErrorMessage") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("JobType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("MaxExecutionTime") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(3000000000L); + + b.Property("MaxRetries") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(3); + + b.Property("ParametersJson") + .HasColumnType("jsonb"); + + b.Property("Priority") + .HasColumnType("integer"); + + b.Property("RequiredCpuCores") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("RequiredMemoryMb") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L); + + b.Property("RequiresGpu") + .HasColumnType("boolean"); + + b.Property("ResultJson") + .HasColumnType("jsonb"); + + b.Property("RetryCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("StartedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CameraId") + .HasDatabaseName("ix_analysis_jobs_camera"); + + b.HasIndex("AssignedAgentId", "Status") + .HasDatabaseName("ix_analysis_jobs_agent_workload") + .HasFilter("\"AssignedAgentId\" IS NOT NULL"); + + b.HasIndex("Status", "DispatchedAt") + .HasDatabaseName("ix_analysis_jobs_timeout"); + + b.HasIndex("Status", "Priority", "CreatedAt") + .HasDatabaseName("ix_analysis_jobs_pending"); + + b.ToTable("analysis_jobs", (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.AppSetting", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentScoped") + .HasColumnType("boolean"); + + 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.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("RecordingEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + 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("StoragePolicyId") + .HasColumnType("uuid"); + + 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.HasIndex("StoragePolicyId"); + + 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("ExecutionProfileJson") + .HasColumnType("text"); + + 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("HomeKitCategory") + .HasColumnType("integer"); + + b.Property("HomeKitDeviceId") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("HomeKitIsPaired") + .HasColumnType("boolean"); + + b.Property("HomeKitModel") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HomeKitName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HomeKitPort") + .HasColumnType("integer"); + + 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") + .HasColumnType("uuid"); + + b.Property("OccurredAt") + .HasColumnType("timestamp with time zone"); + + 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("DetectionHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("IsSuppressed") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("Label") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("MetadataJson") + .HasColumnType("jsonb"); + + b.Property("ParentEventId") + .HasColumnType("uuid"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("RecordingId") + .HasColumnType("uuid"); + + b.Property("SnapshotObjectKey") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotStorageBucket") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("SnapshotStorageEndpoint") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotStorageProvider") + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("SnapshotStorageRoot") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotThumbObjectKey") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotThumbUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("TrackId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Type") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("VehicleId") + .HasColumnType("uuid"); + + b.HasKey("Id", "OccurredAt"); + + b.HasIndex("DetectionHash"); + + b.HasIndex("MetadataJson"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("MetadataJson"), "gin"); + NpgsqlIndexBuilderExtensions.HasOperators(b.HasIndex("MetadataJson"), new[] { "jsonb_path_ops" }); + + b.HasIndex("OccurredAt"); + + b.HasIndex("ParentEventId"); + + b.HasIndex("RecordingId"); + + b.HasIndex("TrackId"); + + b.HasIndex("VehicleId"); + + b.HasIndex("CameraId", "OccurredAt") + .IsDescending(false, true); + + b.HasIndex("CameraId", "Type"); + + b.HasIndex("PersonId", "OccurredAt"); + + 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.GroupCameraAccess", 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("GroupId") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("CameraId"); + + b.HasIndex("GroupId", "CameraId") + .IsUnique(); + + b.ToTable("group_camera_accesses", (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.LicensePlate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .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("PersonId") + .HasColumnType("uuid"); + + b.Property("PlateText") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("VehicleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.HasIndex("PlateText"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("PlateText"), "gin"); + NpgsqlIndexBuilderExtensions.HasOperators(b.HasIndex("PlateText"), new[] { "gin_trgm_ops" }); + + b.HasIndex("VehicleId"); + + b.ToTable("license_plates", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LoginChallenge", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("Consumed") + .HasColumnType("boolean"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SecurityStamp") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("Verifying") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("UserId"); + + b.ToTable("login_challenges", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ManualSnapshotRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("FailureReason") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("CameraId", "CreatedAt"); + + b.ToTable("manual_snapshot_requests", (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.NotificationDelivery", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeliveredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastErrorType") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("LeaseExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone"); + + b.Property("NotificationId") + .HasColumnType("uuid"); + + b.Property("Priority") + .HasColumnType("integer"); + + b.Property("Recipient") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)"); + + b.Property("ServiceUrl") + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("NotificationId", "Channel") + .IsUnique() + .HasDatabaseName("ux_notification_deliveries_notification_channel"); + + b.HasIndex("Status", "NextAttemptAt", "LeaseExpiresAt") + .HasDatabaseName("ix_notification_deliveries_dispatch"); + + b.ToTable("notification_deliveries", (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.Recording", 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("DurationSeconds") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("StorageBucket") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("StorageEndpoint") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("StorageLocationCaptured") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("StoragePath") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("StoragePolicyId") + .HasColumnType("uuid"); + + b.Property("StorageProvider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("StorageRoot") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("StoragePath") + .IsUnique(); + + b.HasIndex("StoragePolicyId"); + + b.HasIndex("CameraId", "Timestamp"); + + b.ToTable("recordings", (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("AutoUpdateEnabled") + .HasColumnType("boolean"); + + 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("NtfyTopic") + .HasColumnType("text"); + + 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.SiteCredential", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Password") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("SiteId"); + + b.ToTable("site_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.StorageDestination", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("FirstSeenAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("LocalRoot") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("S3Bucket") + .IsRequired() + .HasMaxLength(256) + .IsUnicode(false) + .HasColumnType("character varying(256)"); + + b.Property("S3Endpoint") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("Provider") + .HasDatabaseName("ix_storage_destinations_provider"); + + b.ToTable("storage_destinations", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.StoragePolicy", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("RetentionDays") + .HasColumnType("integer"); + + b.Property("StorageProvider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.ToTable("storage_policies", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCamera", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "CameraId"); + + b.HasIndex("CameraId"); + + b.HasIndex("UserId"); + + b.ToTable("user_cameras", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("UserId", "SiteId", "CameraId"); + + b.HasIndex("CameraId"); + + b.HasIndex("SiteId"); + + b.ToTable("UserCameraAccesses", (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("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("NtfyEnabled") + .HasColumnType("boolean"); + + b.Property("NtfyTopic") + .HasColumnType("text"); + + b.Property("NtfyUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + 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.UserRecoveryCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CodeHash") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "CodeHash") + .IsUnique(); + + b.ToTable("user_recovery_codes", (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("Heimdall.Domain.Entities.Vehicle", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Color") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("LicensePlate") + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Make") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("LicensePlate"); + + b.HasIndex("PersonId"); + + b.ToTable("vehicles", (string)null); + }); + + modelBuilder.Entity("Heimdall.Infrastructure.Identity.IdentityAppRole", 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.Infrastructure.Identity.IdentityAppUser", 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("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.AgentLogEntry", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentMetricSample", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", null) + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + 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.AnalysisJob", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "AssignedAgent") + .WithMany() + .HasForeignKey("AssignedAgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AssignedAgent"); + + b.Navigation("Camera"); + }); + + 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.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.SetNull); + }); + + 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.HasOne("Heimdall.Domain.Entities.StoragePolicy", "StoragePolicy") + .WithMany() + .HasForeignKey("StoragePolicyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Agent"); + + b.Navigation("Site"); + + b.Navigation("StoragePolicy"); + }); + + 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.GroupCameraAccess", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany("GroupCameraAccesses") + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Group", "Group") + .WithMany("GroupCameraAccesses") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("Group"); + }); + + 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.LicensePlate", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany() + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Vehicle", "Vehicle") + .WithMany() + .HasForeignKey("VehicleId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Person"); + + b.Navigation("Vehicle"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LoginChallenge", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationDelivery", b => + { + b.HasOne("Heimdall.Domain.Entities.Notification", null) + .WithMany() + .HasForeignKey("NotificationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.StoragePolicy", "StoragePolicy") + .WithMany() + .HasForeignKey("StoragePolicyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Camera"); + + b.Navigation("StoragePolicy"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Credentials") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCamera", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("Site"); + }); + + 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.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Vehicle", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany() + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Person"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Heimdall.Infrastructure.Identity.IdentityAppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Navigation("Cameras"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Navigation("Credentials"); + + b.Navigation("DetectionProfile"); + + b.Navigation("GroupCameraAccesses"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Navigation("DiscoveredStreams"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Navigation("GroupCameraAccesses"); + + 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"); + + b.Navigation("Credentials"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20261104202743_AddCameraRecordingEnabled.cs b/src/Heimdall.Infrastructure/Migrations/20261104202743_AddCameraRecordingEnabled.cs new file mode 100644 index 0000000..1ab95dd --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261104202743_AddCameraRecordingEnabled.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations +{ + /// + public partial class AddCameraRecordingEnabled : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "RecordingEnabled", + table: "cameras", + type: "boolean", + nullable: false, + defaultValue: false); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "RecordingEnabled", + table: "cameras"); + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 5a48432..86407ed 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -719,6 +719,11 @@ namespace Heimdall.Infrastructure.Migrations b.Property("OnvifPort") .HasColumnType("integer"); + b.Property("RecordingEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + b.Property("RtspPort") .HasColumnType("integer"); diff --git a/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs b/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs index 73021e7..cbb76d5 100644 --- a/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs +++ b/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs @@ -115,6 +115,30 @@ public sealed class AlarikStorageProvider : IStorageProvider, IDisposable } } + public async Task DownloadRangeAsync(string key, long start, long endInclusive, CancellationToken ct = default) + { + if (_client is null) return null; + if (start < 0 || endInclusive < start) throw new ArgumentOutOfRangeException(nameof(start)); + try + { + var response = await _client.GetObjectAsync(new GetObjectRequest + { + BucketName = _bucket, + Key = key, + ByteRange = new ByteRange(start, endInclusive), + }, ct).ConfigureAwait(false); + return response.ResponseStream; + } + catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound) + { + return null; + } + catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.RequestedRangeNotSatisfiable) + { + throw new ArgumentOutOfRangeException(nameof(endInclusive)); + } + } + public async Task DeleteAsync(string key, CancellationToken ct = default) { if (_client is null) diff --git a/src/Heimdall.Infrastructure/Storage/BoundedReadStream.cs b/src/Heimdall.Infrastructure/Storage/BoundedReadStream.cs new file mode 100644 index 0000000..0c2b842 --- /dev/null +++ b/src/Heimdall.Infrastructure/Storage/BoundedReadStream.cs @@ -0,0 +1,62 @@ +namespace Heimdall.Infrastructure.Storage; + +/// Limits a provider stream to an inclusive storage byte range. +internal sealed class BoundedReadStream : Stream +{ + private readonly Stream inner; + private readonly long length; + private long remaining; + + public BoundedReadStream(Stream inner, long length) + { + this.inner = inner; + this.length = length; + remaining = length; + } + public override bool CanRead => inner.CanRead; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => length; + public override long Position { get => Length - remaining; set => throw new NotSupportedException(); } + public override void Flush() { } + public override int Read(byte[] buffer, int offset, int count) + { + if (remaining == 0) return 0; + var read = inner.Read(buffer, offset, (int)Math.Min(count, remaining)); + remaining -= read; + return read; + } + public override int Read(Span buffer) + { + if (remaining == 0) return 0; + var read = inner.Read(buffer[..(int)Math.Min(buffer.Length, remaining)]); + remaining -= read; + return read; + } + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (remaining == 0) return 0; + var read = await inner.ReadAsync(buffer[..(int)Math.Min(buffer.Length, remaining)], cancellationToken).ConfigureAwait(false); + remaining -= read; + return read; + } + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => ReadArrayAsync(buffer, offset, count, cancellationToken); + + private Task ReadArrayAsync(byte[] buffer, int offset, int count, CancellationToken ct) => + ReadAsync(buffer.AsMemory(offset, count), ct).AsTask(); + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + protected override void Dispose(bool disposing) + { + if (disposing) inner.Dispose(); + base.Dispose(disposing); + } + public override async ValueTask DisposeAsync() + { + await inner.DisposeAsync().ConfigureAwait(false); + await base.DisposeAsync().ConfigureAwait(false); + } +} diff --git a/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs b/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs index 23f7a53..1018a65 100644 --- a/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs +++ b/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs @@ -90,6 +90,21 @@ public sealed class LocalStorageProvider : IStorageProvider return Task.FromResult(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 64 * 1024, useAsync: true)); } + public Task DownloadRangeAsync(string key, long start, long endInclusive, CancellationToken ct = default) + { + if (start < 0 || endInclusive < start) throw new ArgumentOutOfRangeException(nameof(start)); + var path = ResolvePath(key); + if (!File.Exists(path)) return Task.FromResult(null); + var inner = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 64 * 1024, useAsync: true); + if (endInclusive >= inner.Length) + { + inner.Dispose(); + throw new ArgumentOutOfRangeException(nameof(endInclusive)); + } + inner.Position = start; + return Task.FromResult(new BoundedReadStream(inner, endInclusive - start + 1)); + } + public Task DeleteAsync(string key, CancellationToken ct = default) { var path = ResolvePath(key); diff --git a/src/Heimdall.Infrastructure/Storage/RecordingStorageAdapter.cs b/src/Heimdall.Infrastructure/Storage/RecordingStorageAdapter.cs new file mode 100644 index 0000000..613e35d --- /dev/null +++ b/src/Heimdall.Infrastructure/Storage/RecordingStorageAdapter.cs @@ -0,0 +1,18 @@ +using Heimdall.Application.Common; +using Heimdall.Domain.Entities; + +namespace Heimdall.Infrastructure.Storage; + +public sealed class RecordingStorageAdapter(StorageProviderFactory storage) : IRecordingStorage +{ + public StorageLocation CaptureCurrentLocation() => storage.CaptureCurrentLocation(); + + public Task UploadAsync(string key, Stream content, string contentType, StorageLocation location, + CancellationToken ct = default) => storage.UploadAsync(key, content, contentType, location, ct); + + public Task DownloadAsync(string key, StorageLocation location, CancellationToken ct = default) => + storage.DownloadAsync(key, location, ct); + + public Task DownloadRangeAsync(string key, StorageLocation location, long start, long endInclusive, + CancellationToken ct = default) => storage.DownloadRangeAsync(key, location, start, endInclusive, ct); +} diff --git a/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs b/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs index 10eab97..1f59e90 100644 --- a/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs +++ b/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs @@ -183,6 +183,42 @@ public sealed class StorageProviderFactory : IStorageProvider, Heimdall.Applicat } } + public async Task DownloadRangeAsync( + string key, + long start, + long endInclusive, + CancellationToken ct = default) + { + var location = CaptureCurrentLocation(); + return await DownloadRangeAsync(key, location, start, endInclusive, ct).ConfigureAwait(false); + } + + public async Task DownloadRangeAsync( + string key, + Heimdall.Domain.Entities.StorageLocation location, + long start, + long endInclusive, + CancellationToken ct = default) + { + if (start < 0 || endInclusive < start) throw new ArgumentOutOfRangeException(nameof(start)); + var provider = Resolve(location); + try + { + var stream = await provider.DownloadRangeAsync(key, start, endInclusive, ct).ConfigureAwait(false); + if (stream is null) + { + DisposeProvider(provider); + return null; + } + return new ProviderOwnedStream(stream, provider as IDisposable); + } + catch + { + DisposeProvider(provider); + throw; + } + } + public async Task DeleteAsync(string key, CancellationToken ct = default) { var provider = Resolve(); diff --git a/src/Heimdall.Web/Components/Pages/CameraDetail.razor b/src/Heimdall.Web/Components/Pages/CameraDetail.razor index 43f3fb1..17d320e 100644 --- a/src/Heimdall.Web/Components/Pages/CameraDetail.razor +++ b/src/Heimdall.Web/Components/Pages/CameraDetail.razor @@ -99,6 +99,11 @@ else @Text["CameraDetail_Model"] @(_camera.Model ?? "-") + + + @Text["CameraDetail_RecordingHelp"] + @if (!string.IsNullOrEmpty(_editError)) @@ -132,6 +137,57 @@ else + @* ─── Enregistrements: les URL same-origin héritent de l'authentification du navigateur et supportent Range. ─── *@ + + @Text["CameraDetail_Recordings"] + + @if (_recordingsLoading) + { + + + + } + else if (_recordings.Count > 0) + { + @if (_selectedRecording is not null) + { + + + } + + + @Text["CameraDetail_Timestamp"] + @Text["CameraDetail_Duration"] + @Text["CameraDetail_Size"] + + + + @context.Timestamp.ToLocalTime().ToString("g", Language.Culture) + @FormatRecordingDuration(context.DurationSeconds) + @FormatRecordingSize(context.SizeBytes) + + + @Text["CameraDetail_PlayRecording"] + + + + + } + else + { + @Text["CameraDetail_NoRecordings"] + } + @* ─── Mini-timeline : événements récents ─── *@ @Text["CameraDetail_RecentEvents"] @@ -210,6 +266,7 @@ else private CameraItem? _camera; private string _editName = ""; private string? _editRtspUrl; + private bool _recordingEnabled; private string _editError = ""; private string _editSuccess = ""; private bool _loading = true; @@ -219,6 +276,9 @@ else private bool _confirmDeleteShow; private List? _events; + private List _recordings = []; + private RecordingItem? _selectedRecording; + private bool _recordingsLoading; private bool _eventsLoading; private string? _showSnapshotUrl; private bool _showSnapshotDialog; @@ -245,12 +305,14 @@ else { _editName = _camera.Name; _editRtspUrl = _camera.RtspUrl; + _recordingEnabled = _camera.RecordingEnabled; } } catch { Snackbar.Add(Text["CameraDetail_OperationFailed"], Severity.Error); } finally { _loading = false; } await LoadEventsAsync(); + await LoadRecordingsAsync(); await LoadLatestSnapshotAsync(); } @@ -277,6 +339,27 @@ else finally { _eventsLoading = false; } } + private async Task LoadRecordingsAsync() + { + _recordingsLoading = true; + try + { + var page = await Api.GetCameraRecordingsAsync(Id); + _recordings = page?.Items.ToList() ?? []; + _selectedRecording = _recordings.FirstOrDefault(); + } + catch { _recordings = []; _selectedRecording = null; } + finally { _recordingsLoading = false; } + } + + private void SelectRecording(RecordingItem recording) => _selectedRecording = recording; + private static string RecordingContentUrl(Guid recordingId) => $"/api/recordings/{recordingId:D}/content"; + private static string RecordingDownloadName(Guid recordingId) => $"heimdall-recording-{recordingId:N}.mp4"; + private static string FormatRecordingDuration(double seconds) => TimeSpan.FromSeconds(seconds).ToString("hh\\:mm\\:ss"); + private static string FormatRecordingSize(long bytes) => bytes >= 1024 * 1024 + ? $"{bytes / 1024d / 1024d:0.0} MB" + : $"{bytes / 1024d:0} KB"; + private async Task LoadLatestSnapshotAsync() { _snapshotLoading = true; @@ -360,10 +443,11 @@ else _editSuccess = ""; try { - if (await Api.UpdateCameraAsync(Id, _editName, _editRtspUrl, null)) + if (await Api.UpdateCameraAsync(Id, _editName, _editRtspUrl, null, recordingEnabled: _recordingEnabled)) { _editSuccess = Text["CameraDetail_Updated"]; if (_camera is not null) _camera.Name = _editName; + if (_camera is not null) _camera.RecordingEnabled = _recordingEnabled; } else _editError = Text["CameraDetail_UpdateError"]; } diff --git a/src/Heimdall.Web/Controllers/CamerasController.cs b/src/Heimdall.Web/Controllers/CamerasController.cs index cc3e8c8..6dc3bed 100644 --- a/src/Heimdall.Web/Controllers/CamerasController.cs +++ b/src/Heimdall.Web/Controllers/CamerasController.cs @@ -163,7 +163,7 @@ public class CamerasController : ControllerBase { if (!this.TryGetUserId(out var actorId)) return Unauthorized(); var command = new UpdateCameraCommand(id, request.Name, request.RtspUrl, request.Status, - request.Manufacturer, request.Model, request.DetectionProfile, actorId); + request.Manufacturer, request.Model, request.DetectionProfile, actorId, request.RecordingEnabled); var result = await _mediator.Send(command, ct); return result.IsSuccess ? Ok(result.Data) diff --git a/src/Heimdall.Web/Controllers/RecordingsController.cs b/src/Heimdall.Web/Controllers/RecordingsController.cs new file mode 100644 index 0000000..934c11a --- /dev/null +++ b/src/Heimdall.Web/Controllers/RecordingsController.cs @@ -0,0 +1,118 @@ +using System.Security.Claims; +using Heimdall.Api.Security; +using Heimdall.Application.Recordings.Commands.UploadRecording; +using Heimdall.Application.Recordings.Queries.GetCameraRecordings; +using Heimdall.Application.Recordings.Queries.GetRecordingContent; +using Heimdall.Infrastructure.Security; +using MediatR; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; +using System.Net.Http.Headers; + +namespace Heimdall.Api.Controllers; + +[ApiController] +[Route("api")] +[EnableRateLimiting("Api")] +public sealed class RecordingsController(IMediator mediator, ResourceAccess access) : ControllerBase +{ + private const long MaxSegmentBytes = 100 * 1024 * 1024; + + /// Lists recordings for a camera the authenticated user can access. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] + [HttpGet("cameras/{cameraId:guid}/recordings")] + public async Task List(Guid cameraId, [FromQuery] DateTime? from, + [FromQuery] DateTime? to, [FromQuery] int page = 1, [FromQuery] int pageSize = 50, + CancellationToken ct = default) + { + var requester = await access.ResolveAsync(User, ct).ConfigureAwait(false); + if (requester is null || requester.Kind != RequesterKind.Human) return NotFound(); + var result = await mediator.Send(new GetCameraRecordingsQuery(cameraId, requester.Id, from, to, page, pageSize), ct) + .ConfigureAwait(false); + return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); + } + + /// Accepts one completed MP4 segment from the currently assigned Agent. + [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] + [HttpPut("cameras/{cameraId:guid}/recordings/{recordingId:guid}/content")] + [RequestSizeLimit(MaxSegmentBytes)] + public async Task Upload(Guid cameraId, Guid recordingId, + [FromQuery] DateTime timestamp, [FromQuery] double durationSeconds, CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct).ConfigureAwait(false); + if (requester is null || requester.Kind != RequesterKind.Agent || + !await access.CameraAsync(requester, cameraId, ct).ConfigureAwait(false)) return Forbid(); + if (!string.Equals(Request.ContentType?.Split(';')[0].Trim(), "video/mp4", StringComparison.OrdinalIgnoreCase)) + return StatusCode(StatusCodes.Status415UnsupportedMediaType); + if (Request.ContentLength is not long length || length is < 12 or > MaxSegmentBytes) + return StatusCode(StatusCodes.Status413PayloadTooLarge); + + var temporaryPath = Path.Combine(Path.GetTempPath(), $"heimdall-recording-{Guid.NewGuid():N}.mp4"); + try + { + await using (var output = new FileStream(temporaryPath, FileMode.CreateNew, FileAccess.ReadWrite, + FileShare.None, 128 * 1024, FileOptions.Asynchronous | FileOptions.SequentialScan)) + { + await Request.Body.CopyToAsync(output, ct).ConfigureAwait(false); + if (output.Length != length) return BadRequest(new { error = "Incomplete recording segment" }); + output.Position = 4; + var signature = new byte[4]; + if (await output.ReadAsync(signature, ct).ConfigureAwait(false) != 4 || + !signature.AsSpan().SequenceEqual("ftyp"u8)) + return BadRequest(new { error = "A valid MP4 segment is required" }); + output.Position = 0; + var result = await mediator.Send(new UploadRecordingCommand(requester.Id, cameraId, recordingId, + timestamp, durationSeconds, length, output), ct).ConfigureAwait(false); + return result.IsSuccess + ? Ok(result.Data) + : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + } + } + finally + { + try { System.IO.File.Delete(temporaryPath); } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + } + } + + /// Streams a recording with byte ranges when the configured object provider supports seeking. + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)] + [HttpGet("recordings/{recordingId:guid}/content")] + public async Task Download(Guid recordingId, CancellationToken ct) + { + var requester = await access.ResolveAsync(User, ct).ConfigureAwait(false); + if (requester is null || requester.Kind != RequesterKind.Human) return NotFound(); + long? start = null; + long? end = null; + long? suffixLength = null; + if (Request.Headers.TryGetValue("Range", out var headerValue)) + { + if (!RangeHeaderValue.TryParse(headerValue.ToString(), out var range) || + !string.Equals(range.Unit, "bytes", StringComparison.OrdinalIgnoreCase) || range.Ranges.Count != 1) + return StatusCode(StatusCodes.Status416RangeNotSatisfiable); + var item = range.Ranges.Single(); + start = item.From; + end = item.To; + suffixLength = item.From is null ? item.To : null; + if (start is null && suffixLength is null) + return StatusCode(StatusCodes.Status416RangeNotSatisfiable); + } + var result = await mediator.Send(new GetRecordingContentQuery(recordingId, requester.Id, + start, end, suffixLength), ct) + .ConfigureAwait(false); + if (!result.IsSuccess || result.Data is null) + return result.StatusCode == StatusCodes.Status416RangeNotSatisfiable + ? StatusCode(StatusCodes.Status416RangeNotSatisfiable) + : NotFound(); + Response.Headers["Accept-Ranges"] = "bytes"; + Response.ContentLength = result.Data.ContentLength; + if (result.Data.IsPartial) + { + Response.StatusCode = StatusCodes.Status206PartialContent; + Response.Headers.ContentRange = $"bytes {result.Data.Offset}-{result.Data.Offset + result.Data.ContentLength - 1}/{result.Data.SizeBytes}"; + } + return File(result.Data.Stream, result.Data.ContentType, enableRangeProcessing: false); + } +} diff --git a/src/Heimdall.Web/Localization/SharedResources.en.resx b/src/Heimdall.Web/Localization/SharedResources.en.resx index 992e5ec..6558233 100644 --- a/src/Heimdall.Web/Localization/SharedResources.en.resx +++ b/src/Heimdall.Web/Localization/SharedResources.en.resx @@ -2367,6 +2367,12 @@ Model + + Record video segments + + + Stores rolling MP4 segments in the configured storage. Disabling stops new segments; retention removes expired recordings. + Name @@ -4075,4 +4081,10 @@ Could not save the role permissions. Role permissions saved. Affected users must sign in again. Saving… + Recordings + Download / export MP4 + No recordings are available for this camera. + Duration + Size + Play diff --git a/src/Heimdall.Web/Localization/SharedResources.fr.resx b/src/Heimdall.Web/Localization/SharedResources.fr.resx index 3ba52e6..413d4a4 100644 --- a/src/Heimdall.Web/Localization/SharedResources.fr.resx +++ b/src/Heimdall.Web/Localization/SharedResources.fr.resx @@ -2367,6 +2367,12 @@ Modèle + + Enregistrer des segments vidéo + + + Stocke des segments MP4 dans l’emplacement configuré. La désactivation arrête les nouveaux segments ; la rétention supprime les enregistrements arrivés à échéance. + Nom @@ -4075,4 +4081,10 @@ Impossible d’enregistrer les droits du rôle. Droits du rôle enregistrés. Les utilisateurs concernés devront se reconnecter. Enregistrement… + Enregistrements + Télécharger / exporter en MP4 + Aucun enregistrement n’est disponible pour cette caméra. + Durée + Taille + Lire diff --git a/src/Heimdall.Web/Localization/SharedResources.resx b/src/Heimdall.Web/Localization/SharedResources.resx index 96b09b7..b98051f 100644 --- a/src/Heimdall.Web/Localization/SharedResources.resx +++ b/src/Heimdall.Web/Localization/SharedResources.resx @@ -2367,6 +2367,12 @@ Modèle + + Enregistrer des segments vidéo + + + Stocke des segments MP4 dans l’emplacement configuré. La désactivation arrête les nouveaux segments ; la rétention supprime les enregistrements arrivés à échéance. + Nom @@ -4075,4 +4081,10 @@ Could not save the role permissions. Role permissions saved. Affected users must sign in again. Saving… + Recordings + Download / export MP4 + No recordings are available for this camera. + Duration + Size + Play diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index 75c0e2f..ed5e844 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -508,6 +508,13 @@ public class HeimdallApiClient : IDisposable return await client.GetFromJsonAsync($"api/cameras/{id}", Json); } + public async Task?> GetCameraRecordingsAsync(Guid id, int page = 1, int pageSize = 20) + { + var client = CreateClient(); + return await client.GetFromJsonAsync>( + $"api/cameras/{id}/recordings?page={page}&pageSize={pageSize}", Json); + } + public async Task> RequestCameraSnapshotAsync(Guid id) { var client = CreateClient(); @@ -528,11 +535,11 @@ public class HeimdallApiClient : IDisposable } public async Task UpdateCameraAsync(Guid id, string name, string? rtspUrl, string? status, - string? manufacturer = null, string? model = null) + string? manufacturer = null, string? model = null, bool? recordingEnabled = null) { var client = CreateClient(); var response = await client.PutAsJsonAsync($"api/cameras/{id}", - new { name, rtspUrl, status, manufacturer, model }, Json); + new { name, rtspUrl, status, manufacturer, model, recordingEnabled }, Json); return response.IsSuccessStatusCode; } @@ -1045,6 +1052,7 @@ public class CameraItem public string? RtspUrl { get; set; } public string Status { get; set; } = "Unknown"; public DateTime CreatedAt { get; set; } + public bool RecordingEnabled { get; set; } } /// @@ -1347,6 +1355,14 @@ public record EventItem( [property: JsonPropertyName("occurredAt")] DateTime OccurredAt, [property: JsonPropertyName("createdAt")] DateTime CreatedAt); +public record RecordingItem( + [property: JsonPropertyName("id")] Guid Id, + [property: JsonPropertyName("cameraId")] Guid CameraId, + [property: JsonPropertyName("timestamp")] DateTime Timestamp, + [property: JsonPropertyName("durationSeconds")] double DurationSeconds, + [property: JsonPropertyName("sizeBytes")] long SizeBytes, + [property: JsonPropertyName("contentUrl")] string ContentUrl); + public record EventPageResult( [property: JsonPropertyName("items")] List Items, [property: JsonPropertyName("totalCount")] int TotalCount, diff --git a/tests/Heimdall.Agent.Tests/AgentRecordingServiceTests.cs b/tests/Heimdall.Agent.Tests/AgentRecordingServiceTests.cs new file mode 100644 index 0000000..3d54255 --- /dev/null +++ b/tests/Heimdall.Agent.Tests/AgentRecordingServiceTests.cs @@ -0,0 +1,22 @@ +namespace Heimdall.Agent.Tests; + +public sealed class AgentRecordingServiceTests +{ + [Fact] + public void CreateStartInfo_UsesSegmentedMp4AndTreatsRtspAsOneArgument() + { + const string rtsp = "rtsp://user:p@ss@camera/stream?profile=1&x=2"; + var info = AgentRecordingService.CreateStartInfo("ffmpeg-test", rtsp, "/tmp/segments", 45); + + info.FileName.ShouldBe("ffmpeg-test"); + info.ArgumentList.ShouldContain(rtsp); + info.ArgumentList.ShouldContain("-segment_time"); + info.ArgumentList.ShouldContain("45"); + info.ArgumentList.ShouldContain("-segment_format"); + info.ArgumentList.ShouldContain("mp4"); + info.ArgumentList.ShouldContain("-segment_list_type"); + info.ArgumentList.ShouldContain("csv"); + info.ArgumentList.ShouldContain("/tmp/segments/segment-%06d.mp4"); + info.UseShellExecute.ShouldBeFalse(); + } +} diff --git a/tests/Heimdall.Agent.Tests/CameraConfigStoreTests.cs b/tests/Heimdall.Agent.Tests/CameraConfigStoreTests.cs index 8657142..5f26edd 100644 --- a/tests/Heimdall.Agent.Tests/CameraConfigStoreTests.cs +++ b/tests/Heimdall.Agent.Tests/CameraConfigStoreTests.cs @@ -52,6 +52,19 @@ public class CameraConfigStoreTests store.Cameras.ShouldHaveSingleItem().Enabled.ShouldBeFalse(); } + [Fact] + public void ApplyCameraSetting_RecordingIsOptInAndPropagates() + { + var store = new CameraConfigStore(); + var id = Guid.NewGuid(); + store.ApplyCameraSetting($"camera.{id}.name", "Door"); + store.Cameras.ShouldHaveSingleItem().RecordingEnabled.ShouldBeFalse(); + + store.ApplyCameraSetting($"camera.{id}.recording_enabled", "true"); + + store.Cameras.ShouldHaveSingleItem().RecordingEnabled.ShouldBeTrue(); + } + [Fact] public void ApplyCameraSetting_InvalidKey_Ignored() { diff --git a/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs index 691f0db..8cff26b 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Settings/GetEffectiveAgentConfigHandlerTests.cs @@ -59,6 +59,24 @@ public class GetEffectiveAgentConfigHandlerTests result.Data!["autoupdateenabled"].ShouldBe("true"); } + [Fact] + public async Task Get_effective_config_should_ship_recording_opt_in_for_assigned_camera() + { + var site = new Site("recording-site"); + var agent = new Agent(site.Id, "recording-agent", "host", "1.0.0"); + var camera = new Camera(site.Id, "front door", "rtsp://camera/stream"); + camera.AssignAgent(agent.Id); + camera.SetStatus(CameraStatus.Online); + camera.SetRecordingEnabled(true); + var context = CreateContext(agents: [agent], sites: [site], cameras: [camera]); + var handler = new GetEffectiveAgentConfigQueryHandler(context, Protector); + + var result = await handler.Handle(new GetEffectiveAgentConfigQuery(agent.Id), CancellationToken.None); + + result.IsSuccess.ShouldBeTrue(); + result.Data![ $"camera.{camera.Id}.recording_enabled"].ShouldBe("true"); + } + [Fact] public async Task Get_effective_config_should_merge_app_and_agent_settings() { diff --git a/tests/Heimdall.Infrastructure.Tests/LocalStorageProviderTests.cs b/tests/Heimdall.Infrastructure.Tests/LocalStorageProviderTests.cs index f31ba6c..a53f2a8 100644 --- a/tests/Heimdall.Infrastructure.Tests/LocalStorageProviderTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/LocalStorageProviderTests.cs @@ -35,6 +35,31 @@ public class LocalStorageProviderTests : IDisposable (await reader.ReadToEndAsync()).ShouldBe("hello storage"); } + [Fact] + public async Task DownloadRange_ReturnsOnlyRequestedBytesAndKeepsContentLengthStable() + { + await _provider.UploadAsync("recordings/camera/segment.mp4", + new MemoryStream(Encoding.ASCII.GetBytes("0123456789")), "video/mp4"); + + await using var stream = await _provider.DownloadRangeAsync("recordings/camera/segment.mp4", 2, 5); + stream.ShouldNotBeNull(); + stream.CanSeek.ShouldBeFalse(); + stream.Length.ShouldBe(4); + using var reader = new StreamReader(stream); + (await reader.ReadToEndAsync()).ShouldBe("2345"); + stream.Length.ShouldBe(4); + } + + [Fact] + public async Task DownloadRange_EndBeyondObjectLength_IsRejected() + { + await _provider.UploadAsync("recordings/camera/segment.mp4", + new MemoryStream(Encoding.ASCII.GetBytes("0123456789")), "video/mp4"); + + await Should.ThrowAsync(() => + _provider.DownloadRangeAsync("recordings/camera/segment.mp4", 2, 10)); + } + [Fact] public async Task Download_Missing_ReturnsNull() { diff --git a/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs index ab3cc9d..69abeb4 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs @@ -92,6 +92,28 @@ public class CameraDetailTests : PageTestBase }); } + [Fact] + public void CameraDetail_AfficheLecteurEtExportPourLesEnregistrementsAutorises() + { + var recordingId = Guid.NewGuid(); + Handler.OnGet($"api/cameras/{CameraId}/recordings", new PagedData( + [new RecordingItem(recordingId, CameraId, DateTime.UtcNow.AddMinutes(-2), 12.5, 4096, + $"/api/recordings/{recordingId:D}/content")], 1, 1, 20)); + HandlerCamera(Camera()); + Handler.OnGet("api/events/camera/", new List()); + LoginAs(); + + var cut = RenderPage(p => p.Add(x => x.Id, CameraId)); + + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("([recording], 1, 1, 20)); + + var result = await _sut.GetCameraRecordingsAsync(cameraId); + + Assert.NotNull(result); + Assert.Single(result.Items); + Assert.Equal(recording.Id, result.Items[0].Id); + Assert.Contains($"api/cameras/{cameraId}/recordings?page=1&pageSize=20", _handler.LastRequest!.RequestUri!.ToString()); + } + [Fact] public async Task UpdateCameraAsync_WhenSuccess_ReturnsTrue() { @@ -293,6 +310,20 @@ public sealed class HeimdallApiClientCoverageTests : IDisposable Assert.True(result); } + [Fact] + public async Task UpdateCameraAsync_SendsRecordingEnabledOptIn() + { + SetAuthToken(); + _handler.QueueResponse(HttpStatusCode.OK); + + var result = await _sut.UpdateCameraAsync(Guid.NewGuid(), "Cam", "rtsp://cam", null, + recordingEnabled: true); + + Assert.True(result); + using var body = System.Text.Json.JsonDocument.Parse(await _handler.LastRequest!.Content!.ReadAsStringAsync()); + Assert.True(body.RootElement.GetProperty("recordingEnabled").GetBoolean()); + } + [Fact] public async Task DeleteCameraAsync_WhenSuccess_ReturnsTrue() { diff --git a/todo.md b/todo.md index 9599e49..6ac8fa1 100644 --- a/todo.md +++ b/todo.md @@ -28,7 +28,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PIPE-01/02** La PR #61 implémente une première verticale PostgreSQL : dispatch vers l'agent assigné, claim atomique, tentative protégée, capture/analyse `ObjectDetection` CPU et résultat JSON persisté. Les PR #66 et #67 couvrent et valident avec PostgreSQL deux agents, réaffectation après échec, timeout par le sweep Hangfire, rejet des résultats tardifs et persistance du résultat courant. Restent les validations sur deux agents déployés et les autres types d'analyse. - [ ] **Heartbeat / failover** La PR #87 aligne le délai Offline sur la fréquence configurée (globalement ou par Agent), supprime le job concurrent qui pouvait empêcher la réaffectation, et relance celle-ci pour les Agents Offline qui gardent des caméras actives. La plage est limitée à 5–300 s comme côté Agent (timeout effectif maximal : 660 s). Les fixtures de failover utilisent un heartbeat vieux de 900 s pour tester un Agent effectivement expiré. Le run PR #276 a validé build/tests et les scans des images serveur et Agent; la validation sur plusieurs Agents reste à faire. - [ ] **PIPE-10 / FEAT-05** La PR #74 fait remonter les erreurs ntfy; la PR #76 ajoute une outbox SQL atomique avec état, leases, reprise périodique et unicité par notification/canal. Sa CI (run #242) a validé les tests et scans d’images. La PR #110 ajoute des tests PostgreSQL du succès, du backoff après erreur, de la reprise de lease expirée, de l’ignorance des livraisons différées ou déjà prises et du routage Hangfire par canal. Le run PR #332 a passé les 155 tests d’intégration et les 35 E2E sans test ignoré, les builds/scans des deux images et `CI policy`; la publication Docker Hub a été ignorée comme prévu. Restent les essais SMTP/ntfy réels. La livraison reste au moins une fois : une panne après acceptation fournisseur mais avant l’acquittement SQL peut produire un doublon; aucune garantie exactement une fois n’est possible avec ces interfaces. -- [ ] **OPS-02** Les PR #62, #63 et #106 protègent les références de caméras supprimées logiquement, enregistrent l'inventaire des destinations avant upload et font parcourir ces destinations par le nettoyage final. Le run PR #317 a passé les 284 tests Infrastructure, dont les scénarios de changement de destination (snapshot référencé conservé, puis orphelin supprimé) et de S3 historique inaccessible (références conservées). Restent les objets recording tant que FEAT-02 n'a pas de producteur, les lignes historiques sans provenance (ne pas deviner), et la validation du changement de provider sur stockage déployé. +- [ ] **OPS-02** Les PR #62, #63 et #106 protègent les références de caméras supprimées logiquement, enregistrent l'inventaire des destinations avant upload et font parcourir ces destinations par le nettoyage final. Le run PR #317 a passé les 284 tests Infrastructure, dont les scénarios de changement de destination (snapshot référencé conservé, puis orphelin supprimé) et de S3 historique inaccessible (références conservées). FEAT-02 ajoute maintenant des objets recording avec destination capturée; le contrôle de rétention supprime l'objet du provider enregistré avant sa ligne DB. Restent les lignes historiques sans provenance (ne pas deviner) et la validation du changement de provider sur stockage déployé. - [ ] **OPS-05 / AGENT-06** Les Compose sont simplifiés en un noyau Central + PostgreSQL (avec Watchtower pour la mise à jour Central), un Compose Agent de développement local et des Compose facultatifs séparés par logiciel. En production, le Compose Agent est fourni par l’IHM pour le site sélectionné; le Compose statique de production a été supprimé. La PR #114 retire du Compose les réglages métier (SMTP, ntfy, Ollama, stockage, source des releases et URL API) pour les gérer par l’IHM avec portée globale, en laissant les destinations de notification à leur portée site/utilisateur. La PR #117 ajoute l’installateur interactif Linux Central + PostgreSQL; CI PR #394 passée puis fusionnée (`d1f3f1a`). Le scan du 4 novembre 2026 a retiré les domaines Central des pages Sites/Détail; ces commandes prennent l’origine exposée par l’UI. La source de releases est `updates.releaseapiurl`, vide jusqu’à configuration. DSN Sentry retirés d’appsettings. L’IP publique Agent est optionnelle via `Agent:PublicIpResolverUrl`. `HEIMDALL_SOURCE_BASE_URL` ne sert qu’aux fichiers Heimdall; les installateurs serveur ont l’origine officielle en défaut et permettent un override pour épingler une révision; les dépendances .NET restent distribuées par les sources Microsoft officielles. Renovate lit son endpoint Gitea depuis `GITEA_API_ENDPOINT`; `heima-manager` exige ses origines API en variables d’environnement. Une recette Compose Central jetable avec identifiants, ports loopback et volumes propres au projet a validé `/healthz`, `/setup` et CORS sur l’origine configurée; conteneurs, volumes, réseau et fichiers temporaires supprimés et absence de résidu confirmée. Tests Web 414/414 et Agent 388/388. `bash -n` et `git diff --check` passés. Restent les validations réelles de signature et de mise à jour Agent. - [ ] **Installateurs Agent / mises à jour façon Pangolin** La PR #120 ajoute les choix d’OS et méthodes supportés dans l’IHM, les commandes Bash/PowerShell qui téléchargent les scripts depuis Central, les installs natives Linux/Windows vérifiant signature et digest, le mode service, le rollback après contrôle de démarrage, le réglage global avec surcharge nullable de site, et les mises à jour natives après 24 h de stabilité (les conteneurs restent gérés par l’orchestrateur). La migration conserve les choix existants. La PR #127 rend la commande PowerShell compatible avec les postes `Restricted` en appliquant le contournement d’exécution à la session courante seulement; une GPO peut encore prévaloir. Le run PR #437 a passé tests/build, scans des deux images et `CI policy`. Restent les validations réelles d’installation, mise à jour et rollback sur hôtes Linux et Windows. - [ ] **Installateur Central sans clone (Linux/Windows)** Les scripts `install/install-server.sh` et `install/install-server.ps1` peuvent être téléchargés depuis la branche `main` et exécutés directement; ils créent le Compose Central + PostgreSQL + Watchtower, les secrets locaux protégés et téléchargent seulement les Compose facultatifs choisis. Les images publiées des Compose d’exploitation utilisent `pull_policy: always`; Watchtower (fork actif `nickfedor/watchtower`) ne surveille que Central, vérifie toutes les 24 h et supprime les anciennes images après mise à jour (`--cleanup`), sans effacer les volumes. Une réexécution peut sauvegarder/remplacer le Compose, sauvegarder les fichiers optionnels sélectionnés et compléter uniquement les variables absentes, en conservant `.env`, secrets existants et volumes. La recette Linux première installation + réexécution a passé; une vérification supplémentaire du script téléchargé depuis `main` a généré le Compose sans démarrage, passé `docker compose config` et confirmé les modes 600 du `.env` et du secret. Le Compose Central/PostgreSQL/Watchtower a passé auparavant la recette jetable, son health check et le nettoyage ciblé. Restent la validation Windows réelle/ACL, les hôtes propres et les services facultatifs démarrés. @@ -46,9 +46,10 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. La recette Compose source a été interrompue avant son build/acceptance pour libérer le daemon Docker d’un autre chantier ; elle reste requise avant fusion. Restent également l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe. -- [ ] **FEAT-02** Implémenter enregistrement continu/événement, segments et index temporel, upload repris, replay/range/export autorisés, quotas et purge complète. +- [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe. +- [ ] **FEAT-02** Enregistrement MP4 FFmpeg sur Agent lorsque le flux RTSP est actif, spool local borné avec reprise d'upload idempotente, métadonnées PostgreSQL et association des événements, liste paginée + lecteur/export MP4 de même origine dans CameraDetail, lecture/range protégés par accès caméra. Le stockage capture la destination à l'upload; la rétention existante supprime l'objet avant la ligne et le nettoyage final inspecte les objets recordings. Preuve Compose Central + Agent + MediaMTX + FFmpeg synthétique construit depuis cette source (après ajout du lecteur UI) : 10 segments/listés après redémarrage Central, GET autorisé 206 Range (`bytes 0-15`, signature MP4), anonyme 401, Viewer sans accès caméra 404 sur liste et contenu; GET `/healthz` 200 (le healthcheck Docker courant emploie HEAD via `wget --spider`, que le serveur refuse; corrigé séparément sur la branche intégratrice). Agent ciblé 10/10, Application config 8/8, Infrastructure stockage/rétention 23/23, Web CameraDetail + client API 84/84; build Web sans avertissement. Restent capture audio/événementielle, quota explicite du stockage Central (le spool Agent est borné), validations caméra/codecs réels et tests PostgreSQL dédiés de migration, idempotence et purge; item non terminé. - [ ] **FEAT-03 / UI-02** Les entités Person/KnownFace/Vehicle/LicensePlate et l’historique filtrable par `PersonId` existent, mais l’Agent ne traite encore que `ObjectDetection`; aucune reconnaissance faciale ni OCR plaque n’est livré. Durcissement local du 4 novembre 2026 : vecteurs d’embedding bornés à 4 096 valeurs finies et copiés, corps d’API limité à 256 Kio, plaque bornée à 20 caractères selon le schéma et confiance finie dans [0,1]. Validation : Domain 191/191, handlers Application 6/6, PersonService SQLite 13/13 et Web 414/414. Aucun poids de modèle n’est embarqué : InsightFace réserve ses poids pré-entraînés à la recherche non commerciale; FaceONNX n’indique pas de licence distincte des poids; PaddleOCR ne clarifie pas les droits du modèle plaque précis; le dépôt LdDl est orienté plaques russes et ne précise pas séparément les droits des poids. Garder le statut ouvert jusqu’au choix d’un modèle avec droits vérifiés, tests d’exactitude sur données représentatives, inférence locale opt-in et validation des règles de conservation/suppression biométrique. Recette Compose de cette évolution en attente du créneau Docker coordonné. -- [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel ne servent qu'à l'inventaire. L'Agent accepte `Agent__InferenceExecutionProvider=CPU|CUDA`, sélectionne le fournisseur CUDA seulement s'il est disponible, expose celui attaché à la session et journalise le repli vers CPU si CUDA est absent ou si la création de session échoue. Le package ONNX GPU 1.22.0 a son lock séparé. Validation locale : restores CPU/GPU verrouillés et builds Agent CPU/GPU réussis; la suite Agent GPU a compilé et exécuté 391/392 tests, le seul échec étant la recherche du modèle depuis une sortie redirigée hors dépôt; le test réel `RealOnnx_CpuModel_ProcessesFullHdImage` a ensuite réussi seul avec ce package. Reste à fournir/publier une image/runtime CUDA compatible, l'exposer via installation/UI, valider la recette Compose jetable et exécuter sur matériel GPU réel; aucun GPU n'est déclaré validé. +- [ ] **GPU #77** Les Compose CPU restent indépendants de NVIDIA et les overlays optionnels NVIDIA/AMD/Intel ne servent qu'à l'inventaire. L'Agent accepte `Agent__InferenceExecutionProvider=CPU|CUDA`, sélectionne le fournisseur CUDA seulement s'il est disponible, expose celui attaché à la session et journalise le repli vers CPU si CUDA est absent ou si la création de session échoue. Le package ONNX GPU 1.22.0 a son lock séparé. Validation locale : restores CPU/GPU verrouillés et builds Agent CPU/GPU réussis; la suite Agent GPU a compilé et exécuté 391/392 tests, le seul échec étant la recherche du modèle depuis une sortie redirigée hors dépôt. Test d'inférence ONNX CPU 1080p autonome : 1/1. Restent image/runtime GPU, sélection UI/installateur, manifeste de release, test complet et matériel CUDA réel. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. - [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Le client partagé assemble PTR/SRV/TXT/A, décode `ci` et `sf`, et filtre les catégories 17/18. La CI #246 a passé build, tests et scans d'images ; reste une validation sur LAN avec caméra/sonnette réelles. - [ ] **UI groupes #138 / accès #134** L'édition des groupes permet maintenant de lister les caméras des sites, d'accorder/révoquer les accès de groupe et d'afficher les noms de site/caméra via l'API existante. Restent la validation produit et la vérification de l'union accès direct/groupe ainsi que des priorités dans l'interface.