Merge pull request 'fix(discovery): use agent for HomeKit mDNS' (#78) from fix/mdns-agent-source into main
Heimdall Gitea / Build and scan server image (push) Canceled after 0s
Heimdall Gitea / Build and scan agent image (push) Canceled after 0s
Heimdall Gitea / Publish Docker Hub latest tags (push) Canceled after 0s
Heimdall Gitea / Publish versioned release (push) Canceled after 0s
Heimdall Gitea / Build and tests (push) Canceled after 4m8s

This commit was merged in pull request #78.
This commit is contained in:
arnaud.dartois committed 2026-10-24 23:59:06 +02:00
commit 4f35e907b7
12 files changed
+3000 -52

No files matched your search

@@ -71,7 +71,7 @@ public NetworkCameraScanner(
ICameraDatabase? cameraDatabase = null)
{
_logger = logger;
_homeKitProbe = new HomeKitMdnsProbe(loggerFactory.CreateLogger<HomeKitMdnsProbe>());
_homeKitProbe = homeKitProbe ?? new HomeKitMdnsProbe(loggerFactory.CreateLogger<HomeKitMdnsProbe>());
_cameraDatabase = cameraDatabase;
var (localIp, gatewayIp) = GetLocalNetworkInfo();
_localIp = localIp;
@@ -102,7 +102,7 @@ public NetworkCameraScanner(
var results = new ConcurrentBag<AgentDiscoveredDevice>();
using var throttler = new SemaphoreSlim(40);
// Broadcast/multicast probes (ONVIF WS-Discovery, DVRIP) run in
// Broadcast/multicast probes (ONVIF WS-Discovery, DVRIP, HomeKit mDNS) run in
// parallel with the TCP sweep — one multicast probe discovers every
// ONVIF camera on the LAN, including those with TCP 3702 closed.
var broadcastTask = DiscoverByBroadcastAsync(credentialPool, ct);
@@ -140,24 +140,49 @@ public NetworkCameraScanner(
await Task.WhenAll(tasks).ConfigureAwait(false);
// Merge multicast/broadcast-discovered devices (dedupe by IP — the TCP
// sweep already probed most of them).
var seenIps = new HashSet<string>(results.Select(r => r.Ip), StringComparer.Ordinal);
// Merge multicast/broadcast-discovered devices, preserving HomeKit
// advertisement data even when the TCP sweep found that IP first.
var mergedResults = results.ToList();
var resultIndexes = mergedResults
.Select((device, index) => (device.Ip, index))
.ToDictionary(x => x.Ip, x => x.index, StringComparer.Ordinal);
foreach (var device in await broadcastTask.ConfigureAwait(false))
{
if (device.Ip == localIp || device.Ip == _gatewayIp)
continue;
if (!seenIps.Add(device.Ip))
if (resultIndexes.TryGetValue(device.Ip, out var existingIndex))
{
// A TCP scan may have found the host first. Keep the mDNS
// HomeKit metadata, which is the authoritative category and
// pairing information for these accessories.
if (!string.IsNullOrEmpty(device.HomeKitName))
mergedResults[existingIndex] = mergedResults[existingIndex] with
{
HomeKitName = device.HomeKitName,
HomeKitDeviceId = device.HomeKitDeviceId,
HomeKitModel = device.HomeKitModel,
HomeKitCategory = device.HomeKitCategory,
HomeKitIsPaired = device.HomeKitIsPaired,
HomeKitPort = device.HomeKitPort,
StreamUrls = null,
ScreenshotBase64 = null,
CredentialLabel = null
};
continue;
}
var final = await BuildFinalDeviceAsync(device, credentialPool, ct).ConfigureAwait(false);
if (final is not null)
results.Add(final);
{
resultIndexes.Add(device.Ip, mergedResults.Count);
mergedResults.Add(final);
}
}
_logger.LogInformation("Camera discovery: {Found} candidate device(s) on {Subnet}", results.Count, subnetCidr);
_logger.LogInformation("Camera discovery: {Found} candidate device(s) on {Subnet}", mergedResults.Count, subnetCidr);
return results.ToList();
return mergedResults;
}
/// <summary>
@@ -168,17 +193,17 @@ public NetworkCameraScanner(
private async Task<AgentDiscoveredDevice?> BuildFinalDeviceAsync(
AgentDiscoveredDevice device, IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
{
// 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 null;
// HomeKit accessories are proven by the mDNS advertisement (category
// ci=17/18): no RTSP candidates apply — the stream is a HAP session
// (GetImage snapshot test, ticket #67/#65), never a guessed rtsp:// URL.
if (!string.IsNullOrEmpty(device.HomeKitName))
return device;
// 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 null;
// Real ONVIF GetStreamUri URLs (agent enrichment) take priority over
// guessed templates: keep them even when the stream test fails — the
// camera is already proven by ONVIF, the stream may just need auth.
@@ -251,7 +276,7 @@ public NetworkCameraScanner(
devices.Add(new AgentDiscoveredDevice(
Ip: accessory.Ip,
IsReachable: true,
OpenPorts: [accessory.Port],
OpenPorts: accessory.Port > 0 ? [accessory.Port] : [],
MacAddress: null,
Vendor: "Apple",
Hostname: accessory.Name,
@@ -266,7 +291,10 @@ public NetworkCameraScanner(
HomeKitDeviceId: accessory.DeviceId,
HomeKitModel: accessory.Model,
CredentialLabel: null,
StreamUrls: null));
StreamUrls: null,
HomeKitCategory: accessory.Category,
HomeKitIsPaired: accessory.IsPaired,
HomeKitPort: accessory.Port));
}
}
catch (Exception ex)
@@ -34,10 +34,10 @@ public record AgentCameraCredential(
/// <summary>
/// A single device detected by an agent's network scan. The agent performs
/// the probes (ports, HTTP header, ONVIF WS-Discovery with the site's
/// credential pool, ARP) and reports devices already identified — ONVIF
/// manufacturer/model are filled in by the agent when authentication with a
/// pool credential succeeded. The Central only persists the results.
/// the probes (ports, HTTP header, ONVIF WS-Discovery, HomeKit mDNS, ARP) and
/// reports devices already identified — ONVIF manufacturer/model are filled
/// in by the agent when authentication with a pool credential succeeded. The
/// Central only persists the results.
/// </summary>
public record AgentDiscoveredDevice(
string Ip,
@@ -58,7 +58,10 @@ public record AgentDiscoveredDevice(
string? HomeKitModel,
string? CredentialLabel = null,
string[]? StreamUrls = null,
string? ScreenshotBase64 = null);
string? ScreenshotBase64 = null,
int? HomeKitCategory = null,
bool? HomeKitIsPaired = null,
int? HomeKitPort = null);
/// <summary>Response to an agent's discovery submission.</summary>
public record AgentDiscoverySubmitResponse(
@@ -92,7 +95,13 @@ public record PendingDiscoveryResponse(
DateTime ProbedAt,
bool IsProcessed,
string[] StreamUrls,
bool HasScreenshot = false);
bool HasScreenshot = false,
string? HomeKitName = null,
string? HomeKitDeviceId = null,
string? HomeKitModel = null,
int? HomeKitCategory = null,
bool? HomeKitIsPaired = null,
int? HomeKitPort = null);
/// <summary>Request to reject (ignore) a pending discovery result.</summary>
public record RejectDiscoveryRequest(Guid ResultId);
@@ -25,7 +25,9 @@ public class DiscoveryMappingProfile : Profile
: null))
.ForMember(d => d.HomeKit, o => o.MapFrom(s =>
s.IsHomeKitCamera == true
? new HomeKitProbeInfo(s.HomeKitName ?? "", s.HomeKitDeviceId ?? "", s.HomeKitModel ?? "", 17, false, 0)
? new HomeKitProbeInfo(
s.HomeKitName ?? "", s.HomeKitDeviceId ?? "", s.HomeKitModel ?? "",
s.HomeKitCategory ?? 17, s.HomeKitIsPaired ?? false, s.HomeKitPort ?? 0)
: null))
.ForMember(d => d.MatchedBrands, o => o.Ignore());
@@ -56,6 +56,9 @@ public class CameraDiscoveryResult : Entity<Guid>
public string? HomeKitName { get; private set; }
public string? HomeKitDeviceId { get; private set; }
public string? HomeKitModel { get; private set; }
public int? HomeKitCategory { get; private set; }
public bool? HomeKitIsPaired { get; private set; }
public int? HomeKitPort { get; private set; }
// ── Status ──────────────────────────────────────────────────────
/// <summary>When this probe was performed.</summary>
@@ -102,12 +105,16 @@ public class CameraDiscoveryResult : Entity<Guid>
HttpServerHeader = serverHeader;
}
public void SetHomeKitResult(string name, string deviceId, string model)
public void SetHomeKitResult(
string name, string deviceId, string model, int? category = null, bool? isPaired = null, int? port = null)
{
IsHomeKitCamera = true;
HomeKitName = name;
HomeKitDeviceId = deviceId;
HomeKitModel = model;
HomeKitCategory = category;
HomeKitIsPaired = isPaired;
HomeKitPort = port;
}
public void SetArpInfo(string mac, string? vendor)
@@ -83,6 +83,10 @@ public class CameraDiscoveryResultConfiguration : IEntityTypeConfiguration<Camer
.HasMaxLength(200)
.IsUnicode(false);
builder.Property(r => r.HomeKitCategory);
builder.Property(r => r.HomeKitIsPaired);
builder.Property(r => r.HomeKitPort);
// ── Status ──────────────────────────────────────────────────
builder.Property(r => r.ProbedAt)
.HasDefaultValueSql("NOW()");
@@ -13,7 +13,6 @@ using Heimdall.Infrastructure.Security;
using Heimdall.Infrastructure.Services;
using Heimdall.Infrastructure.Services.Discovery;
using Heimdall.Infrastructure.Storage;
using Heimdall.Mdns;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
@@ -153,11 +152,9 @@ public static class DependencyInjection
{
client.DefaultRequestHeaders.ConnectionClose = true;
});
services.AddSingleton<IMdnsClient, MdnsClient>();
services.AddSingleton<StreamTesterService>();
services.AddSingleton<ICameraDatabase, SqliteCameraDatabase>();
services.AddTransient<IOnvifProbeService, OnvifProbeService>();
services.AddTransient<IMdnsProbeService, MdnsProbeService>();
services.AddTransient<IHttpProbeService, HttpProbeService>();
services.AddTransient<IArpProbeService, ArpProbeService>();
services.AddTransient<IPortScanService, PortScanService>();
@@ -0,0 +1,36 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Heimdall.Infrastructure.Migrations;
public partial class PreserveHomeKitDiscoveryMetadata : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "HomeKitCategory",
table: "camera_discovery_results",
type: "integer",
nullable: true);
migrationBuilder.AddColumn<bool>(
name: "HomeKitIsPaired",
table: "camera_discovery_results",
type: "boolean",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "HomeKitPort",
table: "camera_discovery_results",
type: "integer",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(name: "HomeKitCategory", table: "camera_discovery_results");
migrationBuilder.DropColumn(name: "HomeKitIsPaired", table: "camera_discovery_results");
migrationBuilder.DropColumn(name: "HomeKitPort", table: "camera_discovery_results");
}
}
@@ -1009,6 +1009,15 @@ namespace Heimdall.Infrastructure.Migrations
.IsUnicode(false)
.HasColumnType("character varying(50)");
b.Property<int?>("HomeKitCategory")
.HasColumnType("integer");
b.Property<bool?>("HomeKitIsPaired")
.HasColumnType("boolean");
b.Property<int?>("HomeKitPort")
.HasColumnType("integer");
b.Property<string>("HomeKitModel")
.HasMaxLength(200)
.IsUnicode(false)
@@ -15,7 +15,7 @@ namespace Heimdall.Infrastructure.Services.Discovery;
/// <summary>
/// Camera discovery service implementation.
/// Orchestrates ONVIF, mDNS, HTTP, ARP, and port scan probes to discover
/// Orchestrates ONVIF, HTTP, ARP, and port scan probes to discover
/// cameras on a network. Provides the full pipeline:
/// probe → search DB → build URLs → test streams → confirm.
/// </summary>
@@ -23,7 +23,6 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly IOnvifProbeService _onvif;
private readonly IMdnsProbeService _mdns;
private readonly IHttpProbeService _http;
private readonly IArpProbeService _arp;
private readonly IPortScanService _portScan;
@@ -87,7 +86,6 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
public CameraDiscoveryService(
IDbContextFactory<AppDbContext> dbFactory,
IOnvifProbeService onvif,
IMdnsProbeService mdns,
IHttpProbeService http,
IArpProbeService arp,
IPortScanService portScan,
@@ -98,7 +96,6 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
{
_dbFactory = dbFactory;
_onvif = onvif;
_mdns = mdns;
_http = http;
_arp = arp;
_portScan = portScan;
@@ -108,6 +105,26 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
_logger = logger;
}
/// <summary>
/// Compatibility overload for callers compiled against the former Central
/// mDNS probe constructor. HomeKit discovery is performed by the Agent.
/// </summary>
public CameraDiscoveryService(
IDbContextFactory<AppDbContext> dbFactory,
IOnvifProbeService onvif,
IMdnsProbeService mdns,
IHttpProbeService http,
IArpProbeService arp,
IPortScanService portScan,
StreamTesterService streamTester,
ICredentialProtector credentialProtector,
ICameraDatabase cameraDatabase,
ILogger<CameraDiscoveryService> logger)
: this(dbFactory, onvif, http, arp, portScan, streamTester, credentialProtector, cameraDatabase, logger)
{
ArgumentNullException.ThrowIfNull(mdns);
}
// ─── Probe ────────────────────────────────────────────────────────
public async Task<ServiceResult<ProbeResponse>> ProbeIpAsync(ProbeRequest request, CancellationToken ct)
@@ -119,21 +136,19 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
// Run all probes in parallel
var onvifTask = _onvif.ProbeAsync(request.Ip, ct: ct);
var mdnsTask = _mdns.ProbeAsync(request.Ip, ct);
var httpTask = _http.ProbeAsync(request.Ip, ct);
var arpTask = _arp.ProbeAsync(request.Ip, ct);
var portTask = _portScan.ScanAsync(request.Ip, ct);
await Task.WhenAll(onvifTask, mdnsTask, httpTask, arpTask, portTask).ConfigureAwait(false);
await Task.WhenAll(onvifTask, httpTask, arpTask, portTask).ConfigureAwait(false);
var onvifInfo = await onvifTask.ConfigureAwait(false);
var mdnsInfo = await mdnsTask.ConfigureAwait(false);
var httpInfo = await httpTask.ConfigureAwait(false);
var arpInfo = await arpTask.ConfigureAwait(false);
var openPorts = await portTask.ConfigureAwait(false);
// Determine camera type and discovery method
var (cameraType, discoveryMethod) = ClassifyCamera(onvifInfo, mdnsInfo, httpInfo, openPorts);
var (cameraType, discoveryMethod) = ClassifyCamera(onvifInfo, httpInfo, openPorts);
var isReachable = openPorts.Count > 0 || onvifInfo is not null || httpInfo is not null;
@@ -150,9 +165,7 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
httpInfo is not null
? new Application.DTOs.HttpProbeInfo(httpInfo.Port, httpInfo.StatusCode, httpInfo.ServerHeader)
: null,
mdnsInfo is not null
? new Application.DTOs.HomeKitProbeInfo(mdnsInfo.Name, mdnsInfo.DeviceId, mdnsInfo.Model, mdnsInfo.Category, mdnsInfo.IsPaired, mdnsInfo.Port)
: null,
null,
arpInfo?.Vendor is not null ? [arpInfo.Vendor] : null);
_logger.LogInformation(
@@ -602,7 +615,13 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
result.SetHttpResult(device.HttpPort ?? 80, device.HttpStatusCode ?? 0, device.HttpServerHeader);
if (!string.IsNullOrEmpty(device.HomeKitName) && !string.IsNullOrEmpty(device.HomeKitDeviceId))
result.SetHomeKitResult(device.HomeKitName, device.HomeKitDeviceId, device.HomeKitModel ?? string.Empty);
result.SetHomeKitResult(
device.HomeKitName,
device.HomeKitDeviceId,
device.HomeKitModel ?? string.Empty,
device.HomeKitCategory,
device.HomeKitIsPaired,
device.HomeKitPort);
if (!string.IsNullOrEmpty(device.OnvifDeviceServiceUrl) || device.OnvifPort is not null)
result.SetOnvifResult(
@@ -622,7 +641,8 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
return (DetectedCameraType.Standard, CameraDiscoveryMethod.OnvifWsDiscovery);
if (!string.IsNullOrEmpty(device.HomeKitName))
return (DetectedCameraType.HomeKit, CameraDiscoveryMethod.MdnsHomeKit);
return (device.HomeKitCategory == 18 ? DetectedCameraType.Doorbell : DetectedCameraType.HomeKit,
CameraDiscoveryMethod.MdnsHomeKit);
var server = device.HttpServerHeader?.ToLowerInvariant() ?? string.Empty;
if (server.Contains("hikvision") || server.Contains("dahua") || server.Contains("imou")
@@ -809,7 +829,13 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
r.HttpServerHeader, r.HttpStatusCode, r.HttpPort,
r.ProbedAt, r.IsProcessed,
r.DiscoveredStreams.Select(s => s.Url).ToArray(),
HasScreenshot: _screenshots.TryGetValue(r.Id, out var shot) && shot.ExpiresAt > DateTime.UtcNow))
HasScreenshot: _screenshots.TryGetValue(r.Id, out var shot) && shot.ExpiresAt > DateTime.UtcNow,
HomeKitName: r.HomeKitName,
HomeKitDeviceId: r.HomeKitDeviceId,
HomeKitModel: r.HomeKitModel,
HomeKitCategory: r.HomeKitCategory,
HomeKitIsPaired: r.HomeKitIsPaired,
HomeKitPort: r.HomeKitPort))
.ToList();
return ServiceResult<IReadOnlyList<PendingDiscoveryResponse>>.Success(response);
@@ -849,14 +875,11 @@ public sealed class CameraDiscoveryService : ICameraDiscoveryService
// ─── Private Helpers ──────────────────────────────────────────────
private static (DetectedCameraType type, CameraDiscoveryMethod method) ClassifyCamera(
OnvifDeviceInfo? onvif, HomeKitDeviceInfo? homeKit, HttpProbeData? http, IReadOnlyList<int> ports)
OnvifDeviceInfo? onvif, HttpProbeData? http, IReadOnlyList<int> ports)
{
if (onvif is not null)
return (DetectedCameraType.Standard, CameraDiscoveryMethod.OnvifWsDiscovery);
if (homeKit is not null)
return (DetectedCameraType.HomeKit, CameraDiscoveryMethod.MdnsHomeKit);
if (http is not null)
{
var server = http.ServerHeader?.ToLowerInvariant() ?? "";
+7 -6
View File
@@ -479,8 +479,8 @@ public sealed class MdnsClient : IMdnsClient, IDisposable
DeviceId = deviceId,
Model = model,
Category = category,
IsPaired = sf != "0",
Port = info.Port ?? MdnsConstants.Port
IsPaired = sf == "0",
Port = info.Port ?? 0
}
});
}
@@ -504,8 +504,9 @@ public sealed class MdnsClient : IMdnsClient, IDisposable
var deviceId = response.TxtRecords.GetValueOrDefault("id")
?? $"{target}/{(response.TxtRecords.GetValueOrDefault("md") ?? "unknown")}";
var model = response.TxtRecords.GetValueOrDefault("md") ?? "Unknown";
var category = response.TxtRecords.GetValueOrDefault("c#") ?? "0";
var isPaired = response.TxtRecords.GetValueOrDefault("s#") != "0";
var category = response.TxtRecords.GetValueOrDefault("ci") ?? "0";
var statusFlags = response.TxtRecords.GetValueOrDefault("sf") ?? "1";
var isPaired = statusFlags == "0";
if (!int.TryParse(category, out var cat))
return null;
@@ -517,7 +518,7 @@ public sealed class MdnsClient : IMdnsClient, IDisposable
Model = model,
Category = cat,
IsPaired = isPaired,
Port = response.Port ?? MdnsConstants.Port
Port = response.Port ?? 0
};
}
}
}
+1 -1
View File
@@ -40,7 +40,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant
- [ ] **FEAT-03 / UI-02** Évaluer modèles/licences visage et plaques, persister `PersonId`/`VehicleId` et lier les événements ; vérifier historique paginé sans confusion d'identité, conservation et suppression des données biométriques.
- [ ] **GPU #77** Ajouter profils Compose optionnels et détection du backend effectif ; garder CPU par défaut et tester GPU réel plus fallback CPU.
- [ ] **Inventaire #86** Historiser CPU/RAM/disque/température GPU, fournir courbes 24 h/7 j et capacité par site, avec index et purge bornée.
- [ ] **mDNS #81** Choisir une seule source de probe Agent/Central, conserver PTR/SRV/TXT/A et HomeKit ci=17/18, puis couvrir les cas par tests.
- [ ] **mDNS #81** Le correctif en cours 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. Restent CI et une validation sur LAN avec caméra/sonnette réelles.
- [ ] **UI groupes #138 / accès #134** Finaliser maquette et validation produit, puis vérifier l'union accès direct/groupe et les priorités dans l'interface.
- [ ] **Localisation #142** Extraire tous les textes UI, erreurs, notifications et emails ; persister FR/EN par utilisateur, basculer sans rechargement, garder français par défaut et vérifier les clés des deux ressources.
- [ ] **Métriques #14** Les endpoints Prometheus `/metrics` Web et Agent sont mappés. La PR #68 ajoute et valide `heimdall.signalr.connections_by_hub` sur les cinq hubs Web. La jauge de viewers existe, mais aucun producteur WebRTC n'existe avant FEAT-01. Restent la validation de scraping sur un déploiement et l'évolution réelle des mesures.