using Heimdall.Application.Common; using System.Text.Json; using Heimdall.Application.DTOs; using Heimdall.Application.Security; using Heimdall.Domain.Enums; using MediatR; using Microsoft.EntityFrameworkCore; namespace Heimdall.Application.Settings.Queries.GetEffectiveAgentConfig; public record GetEffectiveAgentConfigQuery(Guid AgentId) : IRequest>>; public class GetEffectiveAgentConfigQueryHandler : IRequestHandler>> { private readonly IApplicationDbContext _db; private readonly ICredentialProtector _protector; public GetEffectiveAgentConfigQueryHandler(IApplicationDbContext db, ICredentialProtector protector) { _db = db; _protector = protector; } public async Task>> Handle( GetEffectiveAgentConfigQuery request, CancellationToken ct) { // Seules les clés AgentScoped=true sont exposées aux agents : les // paramètres d'intégration (SMTP/ntfy/S3/Sentry) sont GLOBAUX (#106). var appSettings = await _db.AppSettings .Where(s => s.AgentScoped) .ToListAsync(ct).ConfigureAwait(false); var config = new Dictionary(StringComparer.Ordinal); foreach (var s in appSettings) config[s.Key] = s.Value; var agentSettings = await _db.AgentSettings .Where(s => s.AgentId == request.AgentId && _db.AppSettings.Any(a => a.Key == s.Key && a.AgentScoped)) .ToListAsync(ct); foreach (var s in agentSettings.Where(s => !string.Equals(s.Key, "autoupdateenabled", StringComparison.OrdinalIgnoreCase))) config[s.Key] = s.Value; var agent = await _db.Agents .AsNoTracking() .FirstOrDefaultAsync(a => a.Id == request.AgentId, ct) .ConfigureAwait(false); if (agent is not null) { var siteAutoUpdate = await _db.Sites .AsNoTracking() .Where(s => s.Id == agent.SiteId) .Select(s => s.AutoUpdateEnabled) .FirstOrDefaultAsync(ct) .ConfigureAwait(false); if (siteAutoUpdate.HasValue) config["autoupdateenabled"] = siteAutoUpdate.Value ? "true" : "false"; else if (!config.ContainsKey("autoupdateenabled")) config["autoupdateenabled"] = "false"; } // ── Camera credential pool (encrypted, decryptable only by the agent) ── // The agent lives on the camera network, so it must own the authenticated // ONVIF enrichment. The Central ships the site's credential pairs inside // an AES-GCM envelope keyed by the agent's API key hash. The agent can // decrypt it with its plaintext API key; nobody else can. if (agent is not null && !string.IsNullOrEmpty(agent.ApiKeyHash)) { var credentials = await _db.SiteCredentials .AsNoTracking() .Where(c => c.SiteId == agent.SiteId) .ToListAsync(ct) .ConfigureAwait(false); if (credentials.Count > 0) { var pairs = credentials .Select(c => new AgentCameraCredential( c.Label, c.Username, _protector.Decrypt(c.Password))) .ToList(); var key = AgentCredentialEnvelope.DeriveKeyFromApiKeyHash(agent.ApiKeyHash); config["discovery.credentials"] = AgentCredentialEnvelope.Encrypt(pairs, key); } } // ── Camera assignments ── // The agent needs the RTSP URLs of the cameras it must capture. The // Central is the source of truth: cameras assigned to this agent (and // not soft-deleted) are shipped as flat `camera..*` keys so the // existing config pipeline (full reload + live SettingChanged events) // carries them to the agent without a new API surface. var cameras = await _db.Cameras .AsNoTracking() .Include(c => c.DetectionProfile) .Where(c => c.AgentId == request.AgentId && !c.IsDeleted) .ToListAsync(ct) .ConfigureAwait(false); foreach (var camera in cameras) { var prefix = $"camera.{camera.Id}"; var p = camera.DetectionProfile; var profile = p is null ? new DetectionProfileDto() : new DetectionProfileDto { IdleIntervalMs = p.IdleIntervalMs, MotionIntervalMs = p.MotionIntervalMs, ActiveIntervalMs = p.ActiveIntervalMs, MinConfidence = (float)p.MinConfidence, DetectPerson = p.DetectPerson, DetectVehicle = p.DetectVehicle, DetectAnimal = p.DetectAnimal, DetectPackage = p.DetectPackage, DetectMotion = p.DetectMotion, RequireMotionForAI = p.RequireMotionForAI, MotionThreshold = p.MotionThreshold, YoloModel = p.YoloModel }; config[$"{prefix}.profile"] = p?.ExecutionProfileJson ?? JsonSerializer.Serialize(profile); config[$"{prefix}.name"] = camera.Name; if (!string.IsNullOrWhiteSpace(camera.RtspUrl)) config[$"{prefix}.rtsp"] = camera.RtspUrl; 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"; config[$"{prefix}.event_recording_enabled"] = camera.EventRecordingEnabled ? "true" : "false"; } return ServiceResult>.Success(config); } }