From ddfa22bee6991968515873e4eabee6777e40115b Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Tue, 11 Aug 2026 20:47:27 +0200 Subject: [PATCH] =?UTF-8?q?fix(agent):=20camera=20discovery=20=E2=80=94=20?= =?UTF-8?q?host-network=20compose,=20parasite=20filtering,=20auto=20stream?= =?UTF-8?q?=20detection?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Compose (dev+prod): agent on host network (bridge 172.x was skipped by the scanner), listen on 8081 (ntfy owns 8080), CentralUrl via host/domain, healthcheck adapted, no Docker DNS - Scanner: skip the LAN gateway (NAT router, never a camera); wider camera ports (+34567/34568 Imou SDK, +8000 Hikvision SDK); 750 ms port timeout; keep only devices with real camera evidence; RTSP OPTIONS + MJPEG content-type probes prove live streams from the agent (it is on the LAN) - Central: drop Unknown devices (nginx/gunicorn/gateway) on submit; classify 37777 DVRIP as Standard camera (not NVR), 8899 alone as NVR; persist agent-tested stream URLs flagged IsAlive; shared CameraStreamTemplates with the agent so both build identical candidate URLs - UI: discoveries popup auto-selects the agent-verified main stream — no manual stream choice --- docker/docker-compose.prod.yml | 16 +- docker/docker-compose.yml | 14 +- .../Services/NetworkCameraScanner.cs | 219 +++++++++++++++++- .../DTOs/SiteCredentialDto.cs | 3 +- .../Discovery/CameraStreamTemplates.cs | 73 ++++++ .../Discovery/CameraDiscoveryService.cs | 96 ++++---- .../Components/Pages/DiscoveriesPage.razor | 18 +- .../AgentDiscoveryServiceTests.cs | 8 +- 8 files changed, 357 insertions(+), 90 deletions(-) create mode 100644 src/Heimdall.Application/Discovery/CameraStreamTemplates.cs diff --git a/docker/docker-compose.prod.yml b/docker/docker-compose.prod.yml index a5a7bbb..1963476 100644 --- a/docker/docker-compose.prod.yml +++ b/docker/docker-compose.prod.yml @@ -127,16 +127,23 @@ services: heimdall-agent: image: eltruncho/heimdall-agent:latest + # Host network: the agent must see the real camera LAN to run discovery. + # On a bridge network it only sees 172.x → the scanner skips (no local subnet). + network_mode: host environment: - Agent__CentralUrl: ${HEIMDALL_CENTRAL_URL:-http://heimdall:8080} - Agent__SiteToken: ${HEIMDALL_SITE_TOKEN} + # 8080 is taken by ntfy on the host → listen on 8081 + ASPNETCORE_URLS: http://+:8081 + # Host network: Docker DNS names don't resolve → point HEIMDALL_CENTRAL_URL + # to the Central's public URL (e.g. https://heimdall.tordais.cc) + Agent__CentralUrl: ${HEIMDALL_CENTRAL_URL:?HEIMDALL_CENTRAL_URL is required (public URL of the Central, e.g. https://heimdall.tordais.cc)} + Agent__SiteToken: ${HEIMDALL_SITE_TOKEN:?HEIMDALL_SITE_TOKEN is required} Agent__AgentName: ${HEIMDALL_AGENT_NAME:-agent-01} Agent__HeartbeatIntervalSeconds: ${HEIMDALL_HEARTBEAT_INTERVAL:-30} Agent__StateDirectory: /var/lib/heimdall SENTRY_DSN: ${SENTRY_DSN} Sentry__Dsn: ${Sentry__Dsn} healthcheck: - test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"] + test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8081/healthz"] interval: 30s timeout: 5s retries: 3 @@ -147,8 +154,7 @@ services: - heimdall restart: unless-stopped logging: *default-logging - networks: - - heimdall-net + # no networks: host networking volumes: pgdata: diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index e0ae62e..bf38bd5 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -127,8 +127,15 @@ services: build: context: .. dockerfile: docker/Dockerfile.agent + # Host network: the agent must see the real camera LAN to run discovery. + # On a bridge network it only sees 172.x → the scanner skips (no local subnet). + network_mode: host environment: - Agent__CentralUrl: ${HEIMDALL_CENTRAL_URL:-http://heimdall:8080} + # 8080 is taken by ntfy on the host → listen on 8081 + ASPNETCORE_URLS: http://+:8081 + # Host network: Docker DNS names don't resolve → reach the Central via + # a host-reachable URL (same machine: http://localhost:5010) + Agent__CentralUrl: ${HEIMDALL_CENTRAL_URL:-http://localhost:5010} Agent__SiteToken: ${HEIMDALL_SITE_TOKEN} Agent__AgentName: ${HEIMDALL_AGENT_NAME:-agent-01} Agent__HeartbeatIntervalSeconds: ${HEIMDALL_HEARTBEAT_INTERVAL:-30} @@ -139,7 +146,7 @@ services: volumes: - agent_state:/var/lib/heimdall healthcheck: - test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"] + test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8081/healthz"] interval: 30s timeout: 5s retries: 3 @@ -148,8 +155,7 @@ services: - heimdall restart: unless-stopped logging: *default-logging - networks: - - heimdall-net + # no networks: host networking volumes: pgdata: diff --git a/src/Heimdall.Agent/Services/NetworkCameraScanner.cs b/src/Heimdall.Agent/Services/NetworkCameraScanner.cs index d02ac59..85a3606 100644 --- a/src/Heimdall.Agent/Services/NetworkCameraScanner.cs +++ b/src/Heimdall.Agent/Services/NetworkCameraScanner.cs @@ -6,6 +6,7 @@ using System.Net.Sockets; using System.Security.Cryptography; using System.Text; using System.Xml.Linq; +using Heimdall.Application.Discovery; using Heimdall.Application.DTOs; using Microsoft.Extensions.Logging; @@ -25,9 +26,11 @@ namespace Heimdall.Agent.Services; /// public sealed class NetworkCameraScanner { - private static readonly int[] CameraPorts = [80, 443, 554, 8554, 3702, 8899, 37777]; - private static readonly TimeSpan PortTimeout = TimeSpan.FromMilliseconds(250); + private static readonly int[] CameraPorts = [80, 443, 554, 8554, 3702, 8899, 37777, 34567, 34568, 8000]; + private static readonly TimeSpan PortTimeout = TimeSpan.FromMilliseconds(750); private static readonly TimeSpan HttpTimeout = TimeSpan.FromSeconds(2); + private static readonly TimeSpan RtspTimeout = TimeSpan.FromSeconds(2); + private static readonly TimeSpan StreamTestTimeout = TimeSpan.FromSeconds(3); private static readonly TimeSpan OnvifUdpTimeout = TimeSpan.FromMilliseconds(500); // ReSharper disable once InconsistentNaming @@ -45,11 +48,14 @@ public sealed class NetworkCameraScanner private readonly ILogger _logger; private readonly string? _localIp; + private readonly string? _gatewayIp; public NetworkCameraScanner(ILogger logger) { _logger = logger; - _localIp = GetLocalIpv4(); + var (localIp, gatewayIp) = GetLocalNetworkInfo(); + _localIp = localIp; + _gatewayIp = gatewayIp; } /// @@ -79,14 +85,37 @@ public sealed class NetworkCameraScanner var tasks = ips.Select(async ip => { if (ct.IsCancellationRequested) return; - if (ip == localIp) return; + // Skip the agent's own IP and the LAN gateway (NAT/router — never a camera). + if (ip == localIp || ip == _gatewayIp) return; await throttler.WaitAsync(ct).ConfigureAwait(false); try { var device = await ProbeHostAsync(ip, credentialPool, ct).ConfigureAwait(false); - if (device is not null) - results.Add(device); + if (device is null) + return; + + // Keep only devices with real camera evidence. Web servers with + // just 80/443 open (nginx, gunicorn, …) are filtered out here. + if (!HasDefinitiveCameraEvidence(device) && !HasCameraPorts(device)) + return; + + // Build + test candidate stream URLs (the agent is on the camera LAN, + // the Central is not — this is where the live stream is proven). + var alive = await TestStreamUrlsAsync(device, credentialPool, ct).ConfigureAwait(false); + if (alive.Count > 0) + { + results.Add(device with { StreamUrls = [.. alive] }); + } + else if (HasDefinitiveCameraEvidence(device)) + { + // Authenticated/protected camera with no anonymous stream: + // keep it with the untested candidate URLs as a fallback. + var fallback = BuildCandidateUrls(device, credentialPool); + if (fallback.Count > 0) + results.Add(device with { StreamUrls = [.. fallback] }); + } + // else: camera ports open but no live stream → not usable, skip. } catch (OperationCanceledException) when (ct.IsCancellationRequested) { @@ -377,9 +406,174 @@ public sealed class NetworkCameraScanner "; } + // ─── Camera evidence filtering ─────────────────────────────────── + + /// + /// True when the device has unambiguous camera evidence (ONVIF, HomeKit, + /// known camera vendor in the HTTP Server header, or a dedicated + /// camera/NVR port that generic appliances never expose). + /// + private static bool HasDefinitiveCameraEvidence(AgentDiscoveredDevice device) + { + if (!string.IsNullOrEmpty(device.OnvifDeviceServiceUrl) + || !string.IsNullOrEmpty(device.OnvifHardware) + || !string.IsNullOrEmpty(device.OnvifName)) + return true; + + if (!string.IsNullOrEmpty(device.HomeKitName) && !string.IsNullOrEmpty(device.HomeKitDeviceId)) + return true; + + var server = device.HttpServerHeader?.ToLowerInvariant() ?? string.Empty; + if (KnownCameraServers.Any(s => server.Contains(s))) + return true; + + // Dedicated ports that generic appliances never open: + // 8899 Dahua NVR API, 37777 Dahua/Imou DVRIP, 34567/34568 Imou SDK, + // 8000 Hikvision SDK. + return device.OpenPorts.Any(p => p is 8899 or 37777 or 34567 or 34568 or 8000); + } + + /// True when the device exposes a camera network port (RTSP/ONVIF). + private static bool HasCameraPorts(AgentDiscoveredDevice device) + => device.OpenPorts.Any(p => p is 554 or 8554 or 3702); + + private static readonly string[] KnownCameraServers = + [ + "hikvision", "dahua", "imou", "lechange", "axis", "vivotek", "amcrest", + "uniview", "tp-link", "tapo", "panasonic", "bosch", "samsung", "sony", + "reolink", "annke", "ezviz", "ubiquiti", "unifi", "geovision", "avtech", + ]; + + /// Build the candidate stream URLs for a device (shared templates). + private static List BuildCandidateUrls(AgentDiscoveredDevice device, IReadOnlyList? credentialPool) + { + var username = credentialPool is { Count: > 0 } ? credentialPool[0].Username : null; + var password = credentialPool is { Count: > 0 } ? credentialPool[0].Password : null; + + var ids = new List { "p:onvif", "p:rtsp-h264", "p:rtsp-h265", "p:mjpeg" }; + var vendorKey = (device.Vendor ?? device.OnvifName)?.ToLowerInvariant(); + if (vendorKey is not null && CameraStreamTemplates.StreamTemplates.ContainsKey($"b:{vendorKey}")) + ids.Insert(0, $"b:{vendorKey}"); + + return CameraStreamTemplates.BuildUrls( + [.. ids], device.Ip, username, password, channel: 0, + device.OpenPorts.Contains(554) ? [554] : device.OpenPorts); + } + + /// + /// Test candidate stream URLs from the agent (it is on the camera LAN). + /// RTSP: OPTIONS handshake (200 or 401 = real RTSP server). HTTP: MJPEG + /// content-type check. Returns the URLs that answered. + /// + private async Task> TestStreamUrlsAsync( + AgentDiscoveredDevice device, IReadOnlyList? credentialPool, CancellationToken ct) + { + var urls = BuildCandidateUrls(device, credentialPool); + if (urls.Count == 0) + return []; + + var alive = new List(); + using var throttler = new SemaphoreSlim(6); + var tasks = urls.Select(async url => + { + await throttler.WaitAsync(ct).ConfigureAwait(false); + try + { + if (await IsStreamUrlAliveAsync(url, ct).ConfigureAwait(false)) + lock (alive) alive.Add(url); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + // cancelled + } + catch (Exception ex) + { + _logger.LogTrace(ex, "Stream test failed for {Url}", url); + } + finally + { + throttler.Release(); + } + }); + + await Task.WhenAll(tasks).ConfigureAwait(false); + return alive; + } + + private async Task IsStreamUrlAliveAsync(string url, CancellationToken ct) + { + if (url.StartsWith("rtsp://", StringComparison.OrdinalIgnoreCase)) + { + try + { + var uri = new Uri(url); + using var client = new TcpClient(); + var connectTask = client.ConnectAsync(uri.Host, uri.Port, ct).AsTask(); + var connected = await Task.WhenAny(connectTask, Task.Delay(RtspTimeout, ct)).ConfigureAwait(false); + if (connected != connectTask || !client.Connected) + return false; + + var options = $"OPTIONS rtsp://{uri.Host}:{uri.Port}/ RTSP/1.0\r\nCSeq: 1\r\nUser-Agent: HeimdallAgent/1.0\r\n\r\n"; + var stream = client.GetStream(); + var bytes = Encoding.UTF8.GetBytes(options); + var sendTask = stream.WriteAsync(bytes, ct).AsTask(); + var sent = await Task.WhenAny(sendTask, Task.Delay(RtspTimeout, ct)).ConfigureAwait(false); + if (sent != sendTask) + return false; + + var buffer = new byte[512]; + var readTask = stream.ReadAsync(buffer, ct).AsTask(); + var read = await Task.WhenAny(readTask, Task.Delay(RtspTimeout, ct)).ConfigureAwait(false); + if (read != readTask) + return false; + var n = await readTask.ConfigureAwait(false); + if (n == 0) + return false; + + var response = Encoding.UTF8.GetString(buffer, 0, n); + // 200 = open stream, 401 = stream exists but needs credentials. + return response.StartsWith("RTSP/1.0 200", StringComparison.OrdinalIgnoreCase) + || response.StartsWith("RTSP/1.0 401", StringComparison.OrdinalIgnoreCase); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogTrace(ex, "RTSP probe failed for {Url}", url); + return false; + } + } + + if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) + || url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) + { + try + { + using var handler = new HttpClientHandler { AllowAutoRedirect = true }; + using var client = new HttpClient(handler) { Timeout = StreamTestTimeout }; + using var request = new HttpRequestMessage(HttpMethod.Get, url); + request.Headers.UserAgent.ParseAdd("HeimdallAgent/1.0"); + using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + return false; + + var contentType = response.Content.Headers.ContentType?.MediaType?.ToLowerInvariant() ?? string.Empty; + // MJPEG endpoints advertise image/jpeg or multipart/x-mixed-replace. + return contentType.Contains("jpeg", StringComparison.Ordinal) + || contentType.Contains("multipart", StringComparison.Ordinal) + || contentType.Contains("mjpg", StringComparison.Ordinal); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogTrace(ex, "HTTP stream probe failed for {Url}", url); + return false; + } + } + + return false; + } + // ─── Network helpers ──────────────────────────────────────────────── - private static string? GetLocalIpv4() + private static (string? LocalIp, string? GatewayIp) GetLocalNetworkInfo() { foreach (var ni in NetworkInterface.GetAllNetworkInterfaces()) { @@ -387,11 +581,16 @@ public sealed class NetworkCameraScanner continue; foreach (var addr in ni.GetIPProperties().UnicastAddresses) { - if (IsCandidateNetwork(addr.Address)) - return addr.Address.ToString(); + if (!IsCandidateNetwork(addr.Address)) + continue; + + var gateway = ni.GetIPProperties().GatewayAddresses + .FirstOrDefault(g => g.Address.AddressFamily == AddressFamily.InterNetwork) + ?.Address.ToString(); + return (addr.Address.ToString(), gateway); } } - return null; + return (null, null); } /// diff --git a/src/Heimdall.Application/DTOs/SiteCredentialDto.cs b/src/Heimdall.Application/DTOs/SiteCredentialDto.cs index ede7d4a..7ec56b6 100644 --- a/src/Heimdall.Application/DTOs/SiteCredentialDto.cs +++ b/src/Heimdall.Application/DTOs/SiteCredentialDto.cs @@ -56,7 +56,8 @@ public record AgentDiscoveredDevice( string? HomeKitName, string? HomeKitDeviceId, string? HomeKitModel, - string? CredentialLabel = null); + string? CredentialLabel = null, + string[]? StreamUrls = null); /// Response to an agent's discovery submission. public record AgentDiscoverySubmitResponse( diff --git a/src/Heimdall.Application/Discovery/CameraStreamTemplates.cs b/src/Heimdall.Application/Discovery/CameraStreamTemplates.cs new file mode 100644 index 0000000..3df50ad --- /dev/null +++ b/src/Heimdall.Application/Discovery/CameraStreamTemplates.cs @@ -0,0 +1,73 @@ +using System.Globalization; + +namespace Heimdall.Application.Discovery; + +/// +/// Shared camera stream URL templates used by BOTH the Central (to build +/// candidate URLs for a discovery result) and the Agent (to build + test the +/// URLs on the camera LAN, since only the agent can reach the cameras). +/// Placeholders: {IP}, {PORT}, {CHANNEL}, {USERNAME}, {PASSWORD}. +/// +public static class CameraStreamTemplates +{ + /// URL templates for stream building. {IP}, {PORT}, {CHANNEL}, {USERNAME}, {PASSWORD}. + public static readonly Dictionary StreamTemplates = new() + { + ["p:onvif"] = ["rtsp://{IP}:{PORT}/onvif/media?profile=1"], + ["p:rtsp-h264"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/stream1", + "rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/Streaming/Channels/{CHANNEL}01"], + ["p:rtsp-h265"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/stream2", + "rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/Streaming/Channels/{CHANNEL}02"], + ["p:mjpeg"] = ["http://{IP}:{PORT}/mjpeg", "http://{IP}:{PORT}/video.mjpg"], + ["p:dvrrip"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/cam/realmonitor?channel={CHANNEL}&subtype=0"], + ["b:hikvision"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:554/Streaming/Channels/{CHANNEL}01", + "http://{IP}:80/onvif/device_service"], + ["b:dahua"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:554/cam/realmonitor?channel={CHANNEL}&subtype=0", + "rtsp://{USERNAME}:{PASSWORD}@{IP}:8554/Streaming/Channels/{CHANNEL}01"], + // Imou (Dahua consumer brand): Dahua-style RTSP + HTTP snapshot/MJPEG CGI + ["b:imou"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:554/cam/realmonitor?channel={CHANNEL}&subtype=0", + "http://{IP}:80/video.mjpg?oids=1&username={USERNAME}&password={PASSWORD}", + "http://{IP}:80/cgi-bin/snapshot.cgi?loginuse={USERNAME}&loginpas={PASSWORD}"], + ["b:axis"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:554/axis-media/media.amp", + "http://{IP}:80/axis-cgi/mjpg/video.cgi"], + ["b:vivotek"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:554/live.sdp"], + ["b:amcrest"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:554/cam/realmonitor?channel={CHANNEL}&subtype=0"], + }; + + /// + /// Build candidate stream URLs for a set of template ids. Falls back to a + /// generic RTSP URL when no template matches. + /// + public static List BuildUrls( + string[] ids, string ip, string? username, string? password, int channel = 0, int[]? portFilter = null) + { + var urls = new List(); + var resolvedPort = portFilter is { Length: > 0 } + ? (portFilter.Contains(554) ? 554 : portFilter[0]) + : 554; + + foreach (var id in ids) + { + if (!StreamTemplates.TryGetValue(id, out var templates)) + continue; + + foreach (var template in templates) + { + var url = template + .Replace("{IP}", ip) + .Replace("{PORT}", resolvedPort.ToString(CultureInfo.InvariantCulture)) + .Replace("{CHANNEL}", channel.ToString(CultureInfo.InvariantCulture)) + .Replace("{USERNAME}", username ?? "admin") + .Replace("{PASSWORD}", password ?? ""); + + if (!urls.Contains(url)) + urls.Add(url); + } + } + + if (urls.Count == 0) + urls.Add($"rtsp://{ip}:{resolvedPort}/stream1"); + + return urls; + } +} diff --git a/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs b/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs index 652b6d6..6939135 100644 --- a/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs +++ b/src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs @@ -1,6 +1,7 @@ using System.Collections.Concurrent; using System.Net; using Heimdall.Application.Common; +using Heimdall.Application.Discovery; using Heimdall.Application.DTOs; using Heimdall.Application.Services; using Heimdall.Domain.Entities; @@ -68,29 +69,11 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService new("model", "m:tp-link:tc70", "TP-Link Tapo TC70"), ]; - /// URL templates for stream building. {IP}, {PORT}, {CHANNEL}, {USERNAME}, {PASSWORD}. - private static readonly Dictionary StreamTemplates = new() - { - ["p:onvif"] = ["rtsp://{IP}:{PORT}/onvif/media?profile=1"], - ["p:rtsp-h264"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/stream1", - "rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/Streaming/Channels/{CHANNEL}01"], - ["p:rtsp-h265"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/stream2", - "rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/Streaming/Channels/{CHANNEL}02"], - ["p:mjpeg"] = ["http://{IP}:{PORT}/mjpeg", "http://{IP}:{PORT}/video.mjpg"], - ["p:dvrrip"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:{PORT}/cam/realmonitor?channel={CHANNEL}&subtype=0"], - ["b:hikvision"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:554/Streaming/Channels/{CHANNEL}01", - "http://{IP}:80/onvif/device_service"], - ["b:dahua"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:554/cam/realmonitor?channel={CHANNEL}&subtype=0", - "rtsp://{USERNAME}:{PASSWORD}@{IP}:8554/Streaming/Channels/{CHANNEL}01"], - // Imou (Dahua consumer brand): Dahua-style RTSP + HTTP snapshot/MJPEG CGI - ["b:imou"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:554/cam/realmonitor?channel={CHANNEL}&subtype=0", - "http://{IP}:80/video.mjpg?oids=1&username={USERNAME}&password={PASSWORD}", - "http://{IP}:80/cgi-bin/snapshot.cgi?loginuse={USERNAME}&loginpas={PASSWORD}"], - ["b:axis"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:554/axis-media/media.amp", - "http://{IP}:80/axis-cgi/mjpg/video.cgi"], - ["b:vivotek"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:554/live.sdp"], - ["b:amcrest"] = ["rtsp://{USERNAME}:{PASSWORD}@{IP}:554/cam/realmonitor?channel={CHANNEL}&subtype=0"], - }; + /// + /// URL templates are shared with the agent () + /// so that the agent builds the SAME candidate URLs and can test them on the + /// camera LAN before submitting the discovery. + /// public CameraDiscoveryService( IDbContextFactory dbFactory, @@ -264,34 +247,8 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService { ct.ThrowIfCancellationRequested(); - var urls = new List(); - var resolvedPort = request.PortFilter is { Length: > 0 } - ? (request.PortFilter.Contains(554) ? 554 : request.PortFilter[0]) - : 554; - - foreach (var id in request.Ids) - { - if (StreamTemplates.TryGetValue(id, out var templates)) - { - foreach (var template in templates) - { - var url = template - .Replace("{IP}", request.Ip) - .Replace("{PORT}", resolvedPort.ToString(System.Globalization.CultureInfo.InvariantCulture)) - .Replace("{CHANNEL}", request.Channel.ToString(System.Globalization.CultureInfo.InvariantCulture)) - .Replace("{USERNAME}", request.Username ?? "admin") - .Replace("{PASSWORD}", request.Password ?? ""); - - if (!urls.Contains(url)) - urls.Add(url); - } - } - } - - if (urls.Count == 0) - { - urls.Add($"rtsp://{request.Ip}:{resolvedPort}/stream1"); - } + var urls = CameraStreamTemplates.BuildUrls( + request.Ids, request.Ip, request.Username, request.Password, request.Channel, request.PortFilter); _logger.LogDebug("Built {Count} stream URLs for {IdCount} entries", urls.Count, request.Ids.Length); @@ -510,6 +467,11 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService if (string.IsNullOrWhiteSpace(device.Ip) || !IPAddress.TryParse(device.Ip, out _)) continue; + // Defense: ignore devices with no camera evidence (older agents that + // still report web servers / gateways). + if (ClassifyAgentDevice(device).type == DetectedCameraType.Unknown) + continue; + // Upsert: reuse an existing unprocessed result for site+IP. var result = await db.CameraDiscoveryResults .Include(r => r.DiscoveredStreams) @@ -606,13 +568,24 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService return (DetectedCameraType.HomeKit, CameraDiscoveryMethod.MdnsHomeKit); var server = device.HttpServerHeader?.ToLowerInvariant() ?? string.Empty; - if (server.Contains("hikvision") || server.Contains("dahua") || server.Contains("axis")) + if (server.Contains("hikvision") || server.Contains("dahua") || server.Contains("imou") + || server.Contains("axis") || server.Contains("uniview") || server.Contains("tapo")) return (DetectedCameraType.Standard, CameraDiscoveryMethod.HttpProbe); - if (device.OpenPorts.Contains(8899) || device.OpenPorts.Contains(37777)) + // 37777 = DVRIP (Dahua/Imou cameras AND NVRs) → camera, not an NVR. + if (device.OpenPorts.Contains(37777)) + return (DetectedCameraType.Standard, CameraDiscoveryMethod.NetworkScan); + + // 8899 = Dahua NVR management API (without DVRIP → likely an NVR box). + if (device.OpenPorts.Contains(8899)) return (DetectedCameraType.Nvr, CameraDiscoveryMethod.NetworkScan); - if (device.OpenPorts.Contains(554) || device.OpenPorts.Contains(8554)) + if (device.OpenPorts.Contains(554) || device.OpenPorts.Contains(8554) + || device.OpenPorts.Contains(34567) || device.OpenPorts.Contains(34568)) + return (DetectedCameraType.Standard, CameraDiscoveryMethod.NetworkScan); + + // Agent-verified live stream URLs are definitive camera evidence. + if (device.StreamUrls is { Length: > 0 }) return (DetectedCameraType.Standard, CameraDiscoveryMethod.NetworkScan); return (DetectedCameraType.Unknown, CameraDiscoveryMethod.NetworkScan); @@ -627,6 +600,10 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService { var existing = result.DiscoveredStreams.Select(s => s.Url).ToHashSet(StringComparer.OrdinalIgnoreCase); + // URLs the agent proved alive on the camera LAN — they come first and + // are flagged so the UI can auto-select the main stream without asking. + var agentUrls = device.StreamUrls ?? []; + // Pick the credential pair used for ONVIF auth (or the first pool entry as a guess). string? username = null; string? password = null; @@ -639,7 +616,7 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService var ids = new List { "p:onvif", "p:rtsp-h264", "p:rtsp-h265", "p:mjpeg" }; // Prefer the enriched vendor (ONVIF manufacturer) over the raw device vendor. var vendorKey = (result.Vendor ?? device.Vendor)?.ToLowerInvariant(); - if (vendorKey is not null && StreamTemplates.ContainsKey($"b:{vendorKey}")) + if (vendorKey is not null && CameraStreamTemplates.StreamTemplates.ContainsKey($"b:{vendorKey}")) ids.Insert(0, $"b:{vendorKey}"); var buildRequest = new StreamBuildRequest( @@ -649,7 +626,12 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService if (!buildResult.IsSuccess || buildResult.Data is null) return; - foreach (var url in buildResult.Data.Streams) + // Union: agent-proven URLs first, then the central candidates. + var ordered = agentUrls + .Concat(buildResult.Data.Streams) + .Distinct(StringComparer.OrdinalIgnoreCase); + + foreach (var url in ordered) { if (existing.Contains(url)) continue; @@ -658,7 +640,7 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService // collection triggers an EF Core UPDATE-on-new-child bug with SQLite. db.DiscoveredStreams.Add(new DiscoveredStreamUrl( result.Id, url, ProtocolFromUrl(url), [], 0, 0, 0, - isMainStream: false, isAlive: false)); + isMainStream: false, isAlive: agentUrls.Contains(url, StringComparer.OrdinalIgnoreCase))); existing.Add(url); } } diff --git a/src/Heimdall.Web/Components/Pages/DiscoveriesPage.razor b/src/Heimdall.Web/Components/Pages/DiscoveriesPage.razor index 88a79b8..9bf7767 100644 --- a/src/Heimdall.Web/Components/Pages/DiscoveriesPage.razor +++ b/src/Heimdall.Web/Components/Pages/DiscoveriesPage.razor @@ -133,20 +133,20 @@ else - @if (_confirm.StreamUrls.Length > 0) + @if (!string.IsNullOrEmpty(_selectedStreamUrl)) { - - @foreach (var url in _confirm.StreamUrls) - { - @url - } - + + + + Flux principal détecté automatiquement + + @_selectedStreamUrl + } else { - Aucune URL de flux n'a pu être construite pour cette caméra. + Aucun flux n'a pu être détecté pour cette caméra (hors ligne ou protégée ?). } diff --git a/tests/Heimdall.Infrastructure.Tests/AgentDiscoveryServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/AgentDiscoveryServiceTests.cs index fbf2ec1..c9db293 100644 --- a/tests/Heimdall.Infrastructure.Tests/AgentDiscoveryServiceTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/AgentDiscoveryServiceTests.cs @@ -104,7 +104,7 @@ public class AgentDiscoveryServiceTests : IDisposable var (_, agentId) = await SeedSiteAndAgentAsync(); var service = CreateService(); - await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80)], CancellationToken.None); + await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 554)], CancellationToken.None); var result = await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80, 554)], CancellationToken.None); result.Data.ShouldNotBeNull(); @@ -200,7 +200,7 @@ public class AgentDiscoveryServiceTests : IDisposable { var (siteId, agentId) = await SeedSiteAndAgentAsync(); var service = CreateService(); - await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80), Device("192.168.1.11", 80)], CancellationToken.None); + await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 554), Device("192.168.1.11", 554)], CancellationToken.None); // Reject one of them — target the exact IP so the assertion below is // deterministic (FirstAsync() without ORDER BY is not stable across @@ -237,7 +237,7 @@ public class AgentDiscoveryServiceTests : IDisposable { var (_, agentId) = await SeedSiteAndAgentAsync(); var service = CreateService(); - await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80)], CancellationToken.None); + await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 554)], CancellationToken.None); await using (var db = await _dbFactory.CreateDbContextAsync()) { @@ -255,7 +255,7 @@ public class AgentDiscoveryServiceTests : IDisposable { var (_, agentId) = await SeedSiteAndAgentAsync(); var service = CreateService(); - await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 80)], CancellationToken.None); + await service.SubmitAgentDiscoveriesAsync(agentId, [Device("192.168.1.10", 554)], CancellationToken.None); await using (var db = await _dbFactory.CreateDbContextAsync()) {