fix(agent): camera discovery — host-network compose, parasite filtering, auto stream detection

- 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
This commit is contained in:
Arnaud Dartois committed 2026-08-11 20:47:27 +02:00
1 parent 0136bf33ec
commit ddfa22bee6
8 files changed
+357 -90

No files matched your search

+11 -5
View File
@@ -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:
+10 -4
View File
@@ -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:
@@ -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;
/// </summary>
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<NetworkCameraScanner> _logger;
private readonly string? _localIp;
private readonly string? _gatewayIp;
public NetworkCameraScanner(ILogger<NetworkCameraScanner> logger)
{
_logger = logger;
_localIp = GetLocalIpv4();
var (localIp, gatewayIp) = GetLocalNetworkInfo();
_localIp = localIp;
_gatewayIp = gatewayIp;
}
/// <summary>
@@ -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
</soap:Envelope>";
}
// ─── Camera evidence filtering ───────────────────────────────────
/// <summary>
/// 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).
/// </summary>
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);
}
/// <summary>True when the device exposes a camera network port (RTSP/ONVIF).</summary>
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",
];
/// <summary>Build the candidate stream URLs for a device (shared templates).</summary>
private static List<string> BuildCandidateUrls(AgentDiscoveredDevice device, IReadOnlyList<AgentCameraCredential>? 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<string> { "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);
}
/// <summary>
/// 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.
/// </summary>
private async Task<List<string>> TestStreamUrlsAsync(
AgentDiscoveredDevice device, IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
{
var urls = BuildCandidateUrls(device, credentialPool);
if (urls.Count == 0)
return [];
var alive = new List<string>();
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<bool> 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);
}
/// <summary>
@@ -56,7 +56,8 @@ public record AgentDiscoveredDevice(
string? HomeKitName,
string? HomeKitDeviceId,
string? HomeKitModel,
string? CredentialLabel = null);
string? CredentialLabel = null,
string[]? StreamUrls = null);
/// <summary>Response to an agent's discovery submission.</summary>
public record AgentDiscoverySubmitResponse(
@@ -0,0 +1,73 @@
using System.Globalization;
namespace Heimdall.Application.Discovery;
/// <summary>
/// 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}.
/// </summary>
public static class CameraStreamTemplates
{
/// <summary>URL templates for stream building. {IP}, {PORT}, {CHANNEL}, {USERNAME}, {PASSWORD}.</summary>
public static readonly Dictionary<string, string[]> 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"],
};
/// <summary>
/// Build candidate stream URLs for a set of template ids. Falls back to a
/// generic RTSP URL when no template matches.
/// </summary>
public static List<string> BuildUrls(
string[] ids, string ip, string? username, string? password, int channel = 0, int[]? portFilter = null)
{
var urls = new List<string>();
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;
}
}
@@ -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"),
];
/// <summary>URL templates for stream building. {IP}, {PORT}, {CHANNEL}, {USERNAME}, {PASSWORD}.</summary>
private static readonly Dictionary<string, string[]> 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"],
};
/// <summary>
/// URL templates are shared with the agent (<see cref="CameraStreamTemplates"/>)
/// so that the agent builds the SAME candidate URLs and can test them on the
/// camera LAN before submitting the discovery.
/// </summary>
public CameraDiscoveryService(
IDbContextFactory<AppDbContext> dbFactory,
@@ -264,34 +247,8 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
{
ct.ThrowIfCancellationRequested();
var urls = new List<string>();
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<string> { "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);
}
}
@@ -133,20 +133,20 @@ else
<MudTextField @bind-Value="_confirmName" Label="Nom de la caméra *" Variant="Variant.Outlined"
Class="mb-4" Immediate="true" />
@if (_confirm.StreamUrls.Length > 0)
@if (!string.IsNullOrEmpty(_selectedStreamUrl))
{
<MudSelect T="string" @bind-Value="_selectedStreamUrl" Label="Flux principal"
Variant="Variant.Outlined" Class="mb-2" HelperText="URL construite automatiquement">
@foreach (var url in _confirm.StreamUrls)
{
<MudSelectItem Value="@url"><code>@url</code></MudSelectItem>
}
</MudSelect>
<MudAlert Severity="Severity.Success" Variant="Variant.Outlined" Class="mb-4">
<MudText Typo="Typo.body2" Class="mb-1">
<MudIcon Icon="@Icons.Material.Filled.CheckCircle" Class="mr-1" Size="Size.Small" />
Flux principal détecté automatiquement
</MudText>
<MudText Typo="Typo.body2"><code>@_selectedStreamUrl</code></MudText>
</MudAlert>
}
else
{
<MudAlert Severity="Severity.Warning" Class="mb-4">
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 ?).
</MudAlert>
}
@@ -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())
{