## Contexte Implémentation des tickets #82, #83, #84, #85 — télémétrie inventaire matériel agent. L'objectif est de fournir au central un maximum d'informations sur les machines des agents (CPU, mémoire, disques, GPU, OS, réseau, conteneur) sans SSH. ## Changements ### Nouveaux collecteurs (src/Heimdall.Agent/Services/) - **CpuInfoProvider** : parse `/proc/cpuinfo` (vendor, modèle, cœurs physiques/logiques, fréquence, flags AVX/AVX2/FMA/AVX512, cache), topologie, détection cgroup CPU (`/sys/fs/cgroup/cpu.max` v2) - **DiskInventoryProvider** : énumère les montages (`/proc/mounts`), capacité/libre/type SSD/HDD via `/sys/block/*/queue/rotation` - **GpuInventoryProvider** : nvidia-smi, sysfs DRM, vainfo, rocm-smi avec fallback silencieux, multi-GPU - **HostInfoProvider** : os-release, uname, `/proc/uptime` (uptime machine ≠ process), températures sysfs - **ContainerInfoProvider** : détection Docker (/.dockerenv, cgroup), ID conteneur, limites CPU/mémoire ### Refonte SystemMetricsProvider - Séparation host vs process (RAM machine ≠ RAM conteneur ≠ WorkingSet64) - Uptime machine (`/proc/uptime`) distinct de l'uptime process - Mémoire swap ### Entité Agent + Migration - Champs structurés CPU/mémoire/disque/GPU/OS/réseau (tous nullable, rétrocompatible) - Migration EF `AddAgentTelemetryInventory` ### Transport heartbeat - Inventaire au register + refresh périodique (5 min, pas à chaque tick) - Champs JSON pour listes (disques, GPU, interfaces réseau, températures) ### UI Admin (AgentDetail.razor) - Sections CPU, Mémoire/Disques, GPU, Machine/Conteneur avec barres de progression et badges ### Tests - 40+ tests unitaires : providers, handlers, entité Agent - Total : 999 tests verts (Domain 149, Application 397, Agent 210, Web 243) ## Tickets liés - Fixes #82 — CPU inventory - Fixes #83 — Mémoire & disque - Fixes #84 — GPU inventory - Fixes #85 — OS, conteneur, réseau ## Résultats des tests - `dotnet build` : 0 erreur, 0 warning - Domain.Tests : 149 passed - Application.Tests : 397 passed - Agent.Tests : 210 passed - Web.Tests : 243 passed - Total : 999 tests ✅ ## Checklist - [x] `dotnet build` vert (TreatWarningsAsErrors) - [x] Tests unitaires verts - [x] Migration EF créée - [x] Champs nullable (rétrocompatible) - [x] Pas de référence Infrastructure dans les contrôleurs - [x] Collecteurs avec fallback silencieux (pas de crash sans GPU/Docker/sysfs) Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/137
955 lines
41 KiB
C#
955 lines
41 KiB
C#
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;
|
|
using Heimdall.Domain.Enums;
|
|
using Heimdall.Infrastructure.Data;
|
|
using Heimdall.Infrastructure.Security;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Heimdall.Infrastructure.Services.Discovery;
|
|
|
|
/// <summary>
|
|
/// Camera discovery service implementation.
|
|
/// Orchestrates ONVIF, mDNS, 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>
|
|
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;
|
|
private readonly StreamTesterService _streamTester;
|
|
private readonly ICredentialProtector _credentialProtector;
|
|
private readonly ICameraDatabase _cameraDatabase;
|
|
private readonly ILogger<CameraDiscoveryService> _logger;
|
|
|
|
/// <summary>
|
|
/// In-memory screenshot cache for discovery results (agent-captured JPEG,
|
|
/// base64). Never persisted — TTL 10 min, matching the discovery workflow.
|
|
/// </summary>
|
|
private readonly ConcurrentDictionary<Guid, ScreenshotEntry> _screenshots = new();
|
|
|
|
private sealed record ScreenshotEntry(byte[] Bytes, DateTime ExpiresAt);
|
|
|
|
/// <summary>Built-in camera database entries (StrixCamDB-inspired).</summary>
|
|
private static readonly CameraDbEntry[] BuiltInCameraDb =
|
|
[
|
|
// Presets (common URL templates)
|
|
new("preset", "p:onvif", "ONVIF Profile S"),
|
|
new("preset", "p:rtsp-h264", "RTSP H.264"),
|
|
new("preset", "p:rtsp-h265", "RTSP H.265"),
|
|
new("preset", "p:mjpeg", "MJPEG over HTTP"),
|
|
new("preset", "p:dvrrip", "Dahua DVRIP"),
|
|
|
|
// Popular brands
|
|
new("brand", "b:hikvision", "Hikvision"),
|
|
new("brand", "b:dahua", "Dahua"),
|
|
new("brand", "b:imou", "Imou"),
|
|
new("brand", "b:axis", "Axis Communications"),
|
|
new("brand", "b:vivotek", "Vivotek"),
|
|
new("brand", "b:amcrest", "Amcrest"),
|
|
new("brand", "b:panasonic", "Panasonic i-Pro"),
|
|
new("brand", "b:bosch", "Bosch"),
|
|
new("brand", "b:samsung", "Samsung Techwin"),
|
|
new("brand", "b:sony", "Sony"),
|
|
new("brand", "b:uniview", "Uniview"),
|
|
new("brand", "b:tp-link", "TP-Link / Tapo"),
|
|
|
|
// Common models
|
|
new("model", "m:hikvision:ds-2cd2t47", "Hikvision DS-2CD2T47G2-L"),
|
|
new("model", "m:dahua:sd22204", "Dahua SD22204"),
|
|
new("model", "m:imou:ipc-t2a30p", "Imou IPC-T2A30P"),
|
|
new("model", "m:imou:ipc-a22ep", "Imou IPC-A22EP"),
|
|
new("model", "m:imou:ipc-s41fp", "Imou IPC-S41FP"),
|
|
new("model", "m:imou:ipc-e22cp", "Imou IPC-E22CP"),
|
|
new("model", "m:imou:ranger", "Imou Ranger"),
|
|
new("model", "m:imou:cue2", "Imou Cue2"),
|
|
new("model", "m:axis:m3085", "Axis M3085-V"),
|
|
new("model", "m:amcrest:ip8m", "Amcrest IP8M-T2499EW"),
|
|
new("model", "m:tp-link:tc70", "TP-Link Tapo TC70"),
|
|
];
|
|
|
|
/// <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,
|
|
IOnvifProbeService onvif,
|
|
IMdnsProbeService mdns,
|
|
IHttpProbeService http,
|
|
IArpProbeService arp,
|
|
IPortScanService portScan,
|
|
StreamTesterService streamTester,
|
|
ICredentialProtector credentialProtector,
|
|
ICameraDatabase cameraDatabase,
|
|
ILogger<CameraDiscoveryService> logger)
|
|
{
|
|
_dbFactory = dbFactory;
|
|
_onvif = onvif;
|
|
_mdns = mdns;
|
|
_http = http;
|
|
_arp = arp;
|
|
_portScan = portScan;
|
|
_streamTester = streamTester;
|
|
_credentialProtector = credentialProtector;
|
|
_cameraDatabase = cameraDatabase;
|
|
_logger = logger;
|
|
}
|
|
|
|
// ─── Probe ────────────────────────────────────────────────────────
|
|
|
|
public async Task<ServiceResult<ProbeResponse>> ProbeIpAsync(ProbeRequest request, CancellationToken ct)
|
|
{
|
|
if (!IPAddress.TryParse(request.Ip, out _))
|
|
return ServiceResult<ProbeResponse>.Failure("Invalid IP address");
|
|
|
|
_logger.LogInformation("Probing IP {Ip} for site {SiteId}", request.Ip, request.SiteId);
|
|
|
|
// 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);
|
|
|
|
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 isReachable = openPorts.Count > 0 || onvifInfo is not null || httpInfo is not null;
|
|
|
|
var response = new ProbeResponse(
|
|
request.Ip,
|
|
isReachable,
|
|
cameraType,
|
|
discoveryMethod,
|
|
arpInfo is not null ? new Application.DTOs.ArpInfo(arpInfo.MacAddress, arpInfo.Vendor) : null,
|
|
[.. openPorts],
|
|
onvifInfo is not null
|
|
? new Application.DTOs.OnvifProbeInfo(onvifInfo.DeviceServiceUrl, onvifInfo.Port, onvifInfo.Name, onvifInfo.Hardware, onvifInfo.Location)
|
|
: null,
|
|
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,
|
|
arpInfo?.Vendor is not null ? [arpInfo.Vendor] : null);
|
|
|
|
_logger.LogInformation(
|
|
"Probe result for {Ip}: reachable={Reachable}, type={Type}, method={Method}, ports=[{Ports}]",
|
|
request.Ip, isReachable, cameraType, discoveryMethod, string.Join(",", openPorts));
|
|
|
|
return ServiceResult<ProbeResponse>.Success(response);
|
|
}
|
|
|
|
public async Task<ServiceResult<IReadOnlyList<ProbeResponse>>> ScanSubnetAsync(
|
|
ScanRequest request, CancellationToken ct, IProgress<ScanProgress>? progress = null)
|
|
{
|
|
_logger.LogInformation("Starting subnet scan for {SubnetCidr} (timeout={TimeoutMs}ms)",
|
|
request.SubnetCidr, request.TimeoutMs);
|
|
|
|
var ips = ExpandSubnet(request.SubnetCidr);
|
|
if (ips.Count == 0)
|
|
return ServiceResult<IReadOnlyList<ProbeResponse>>.Failure($"Invalid subnet CIDR: {request.SubnetCidr}");
|
|
|
|
_logger.LogInformation("Subnet scan expanded to {Count} hosts", ips.Count);
|
|
|
|
var results = new ConcurrentBag<ProbeResponse>();
|
|
var scanned = 0;
|
|
var discovered = 0;
|
|
|
|
using var throttler = new SemaphoreSlim(20);
|
|
|
|
var tasks = ips.Select(async ip =>
|
|
{
|
|
if (ct.IsCancellationRequested) return;
|
|
|
|
await throttler.WaitAsync(ct).ConfigureAwait(false);
|
|
try
|
|
{
|
|
var probeRequest = new ProbeRequest(request.SiteId, ip);
|
|
var result = await ProbeIpAsync(probeRequest, ct).ConfigureAwait(false);
|
|
if (result.IsSuccess && result.Data is not null)
|
|
{
|
|
results.Add(result.Data);
|
|
if (result.Data.IsReachable)
|
|
Interlocked.Increment(ref discovered);
|
|
}
|
|
|
|
var scannedCount = Interlocked.Increment(ref scanned);
|
|
progress?.Report(new ScanProgress(
|
|
ips.Count, scannedCount, discovered, ip));
|
|
}
|
|
finally
|
|
{
|
|
throttler.Release();
|
|
}
|
|
});
|
|
|
|
using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
timeoutCts.CancelAfter(TimeSpan.FromMilliseconds(request.TimeoutMs));
|
|
|
|
try
|
|
{
|
|
await Task.WhenAll(tasks).WaitAsync(timeoutCts.Token).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException ex) when (!ct.IsCancellationRequested)
|
|
{
|
|
_logger.LogWarning(ex, "Subnet scan timed out after {TimeoutMs}ms", request.TimeoutMs);
|
|
}
|
|
|
|
_logger.LogInformation(
|
|
"Subnet scan completed: {Discovered}/{Total} hosts reachable",
|
|
discovered, ips.Count);
|
|
|
|
return ServiceResult<IReadOnlyList<ProbeResponse>>.Success(results.ToList().AsReadOnly());
|
|
}
|
|
|
|
// ─── Camera Database ─────────────────────────────────────────────
|
|
|
|
public Task<ServiceResult<SearchResponse>> SearchDatabaseAsync(string query, CancellationToken ct)
|
|
{
|
|
ct.ThrowIfCancellationRequested();
|
|
|
|
// StrixCamDB (3 688 marques / 73 238 modèles) quand elle est embarquée,
|
|
// sinon le petit catalogue statique.
|
|
if (_cameraDatabase.IsAvailable)
|
|
{
|
|
var results = _cameraDatabase.Search(query ?? "");
|
|
_logger.LogDebug("StrixCamDB search for '{Query}': {Count} results", query, results.Count);
|
|
return Task.FromResult(ServiceResult<SearchResponse>.Success(new SearchResponse([.. results])));
|
|
}
|
|
|
|
return string.IsNullOrWhiteSpace(query)
|
|
? Task.FromResult(ServiceResult<SearchResponse>.Success(
|
|
new SearchResponse(BuiltInCameraDb)))
|
|
: Task.FromResult(SearchDatabaseInternal(query));
|
|
}
|
|
|
|
private ServiceResult<SearchResponse> SearchDatabaseInternal(string query)
|
|
{
|
|
var terms = query.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
|
|
|
var results = BuiltInCameraDb
|
|
.Where(entry => terms.Any(t =>
|
|
entry.Name.Contains(t, StringComparison.OrdinalIgnoreCase) ||
|
|
entry.Id.Contains(t, StringComparison.OrdinalIgnoreCase)))
|
|
.ToArray();
|
|
|
|
_logger.LogDebug("Camera DB search for '{Query}': {Count} results", query, results.Length);
|
|
|
|
return ServiceResult<SearchResponse>.Success(new SearchResponse(results));
|
|
}
|
|
|
|
// ─── Stream URL Building ─────────────────────────────────────────
|
|
|
|
public Task<ServiceResult<StreamBuildResponse>> BuildStreamUrlsAsync(StreamBuildRequest request, CancellationToken ct)
|
|
{
|
|
ct.ThrowIfCancellationRequested();
|
|
|
|
// StrixCamDB (100 000+ patterns réels) quand embarquée, sinon templates.
|
|
if (_cameraDatabase.IsAvailable)
|
|
{
|
|
var urls = _cameraDatabase.BuildStreams(
|
|
request.Ids, request.Ip, request.Username, request.Password, request.Channel, request.PortFilter);
|
|
if (urls.Count > 0)
|
|
{
|
|
_logger.LogDebug("StrixCamDB built {Count} stream URLs for {IdCount} entries", urls.Count, request.Ids.Length);
|
|
return Task.FromResult(
|
|
ServiceResult<StreamBuildResponse>.Success(new StreamBuildResponse([.. urls])));
|
|
}
|
|
}
|
|
|
|
var legacy = CameraStreamTemplates.BuildUrls(
|
|
request.Ids, request.Ip, request.Username, request.Password, request.Channel, request.PortFilter);
|
|
|
|
_logger.LogDebug("Built {Count} stream URLs for {IdCount} entries", legacy.Count, request.Ids.Length);
|
|
|
|
return Task.FromResult(
|
|
ServiceResult<StreamBuildResponse>.Success(new StreamBuildResponse([.. legacy])));
|
|
}
|
|
|
|
// ─── Stream Testing ──────────────────────────────────────────────
|
|
|
|
public async Task<ServiceResult<StreamTestSession>> TestStreamsAsync(StreamTestRequest request, CancellationToken ct)
|
|
{
|
|
if (request.Streams.Length == 0)
|
|
return ServiceResult<StreamTestSession>.Failure("No stream URLs provided");
|
|
|
|
var appRequest = new Application.DTOs.StreamTestRequest(request.SourceId, request.Streams);
|
|
var session = await _streamTester.CreateSessionAsync(appRequest, ct).ConfigureAwait(false);
|
|
|
|
return ServiceResult<StreamTestSession>.Success(session);
|
|
}
|
|
|
|
public async Task<ServiceResult<StreamTestSession>> GetTestSessionAsync(Guid sessionId, CancellationToken ct)
|
|
{
|
|
var session = await _streamTester.GetSessionAsync(sessionId, ct).ConfigureAwait(false);
|
|
if (session is null)
|
|
return ServiceResult<StreamTestSession>.NotFound("Test session not found");
|
|
|
|
return ServiceResult<StreamTestSession>.Success(session);
|
|
}
|
|
|
|
public async Task<byte[]?> GetScreenshotAsync(Guid sessionId, int index, CancellationToken ct)
|
|
{
|
|
// Screenshots are captured live during the stream test (ffmpeg or
|
|
// HTTP MJPEG) and kept in the in-memory session (TTL 10 min).
|
|
return await _streamTester.GetScreenshotAsync(sessionId, index, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
public async Task<ServiceResult> CancelTestSessionAsync(Guid sessionId, CancellationToken ct)
|
|
{
|
|
await _streamTester.CancelSessionAsync(sessionId, ct).ConfigureAwait(false);
|
|
return ServiceResult.Success();
|
|
}
|
|
|
|
// ─── Confirm Discovery ────────────────────────────────────────────
|
|
|
|
public async Task<ServiceResult<CameraResponse>> ConfirmDiscoveryAsync(ConfirmDiscoveryRequest request, CancellationToken ct)
|
|
{
|
|
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
|
|
|
var site = await db.Sites.FindAsync([request.SiteId], ct).ConfigureAwait(false);
|
|
if (site is null)
|
|
return ServiceResult<CameraResponse>.NotFound("Site not found");
|
|
|
|
var discoveryResult = await db.CameraDiscoveryResults
|
|
.Include(r => r.DiscoveredStreams)
|
|
.FirstOrDefaultAsync(r => r.Id == request.DiscoveryResultId, ct);
|
|
|
|
if (discoveryResult is null)
|
|
return ServiceResult<CameraResponse>.NotFound("Discovery result not found");
|
|
|
|
// ── Anti-duplication: check existing cameras ──────────────────
|
|
var dupCheck = await FindDuplicateCameraAsync(db, request.SiteId, discoveryResult.IpAddress, discoveryResult.MacAddress, ct).ConfigureAwait(false);
|
|
if (dupCheck is not null)
|
|
{
|
|
_logger.LogWarning(
|
|
"Duplicate camera detected for IP={Ip} MAC={Mac} site={SiteId}: existing camera '{ExistingName}' (ID={ExistingId})",
|
|
discoveryResult.IpAddress, discoveryResult.MacAddress, request.SiteId, dupCheck.Name, dupCheck.Id);
|
|
|
|
return ServiceResult<CameraResponse>.Conflict(
|
|
$"Camera already exists: \"{dupCheck.Name}\" (IP: {dupCheck.IpAddress}, MAC: {dupCheck.MacAddress}). " +
|
|
$"Use PUT /api/cameras/{dupCheck.Id} to update or DELETE first.");
|
|
}
|
|
|
|
// ── Create Camera ─────────────────────────────────────────────
|
|
var camera = new Camera(
|
|
request.SiteId,
|
|
request.Name,
|
|
request.MainStreamUrl,
|
|
manufacturer: discoveryResult.Vendor,
|
|
model: discoveryResult.OnvifHardware ?? discoveryResult.Hostname);
|
|
|
|
camera.SetDiscoveryInfo(
|
|
discoveryResult.DiscoveryMethod,
|
|
discoveryResult.DetectedType,
|
|
discoveryResult.MacAddress,
|
|
discoveryResult.IpAddress);
|
|
|
|
if (request.SubStreamUrl is not null)
|
|
{
|
|
camera.SetStreamTestResult(
|
|
request.SubStreamUrl, "[]", 0, 0, 0);
|
|
}
|
|
|
|
camera.SetPorts(
|
|
discoveryResult.OnvifPort,
|
|
discoveryResult.HttpPort,
|
|
null);
|
|
|
|
if (request.Username is not null || request.Password is not null)
|
|
{
|
|
var credentials = new CameraCredentials(camera.Id);
|
|
credentials.SetCredentials(
|
|
request.Username ?? "admin",
|
|
_credentialProtector.Encrypt(request.Password ?? ""),
|
|
_credentialProtector.Encrypt(request.Username ?? "admin"),
|
|
_credentialProtector.Encrypt(request.Password ?? ""));
|
|
camera.SetCredentials(credentials);
|
|
}
|
|
|
|
if (request.DetectionProfile is not null)
|
|
{
|
|
var profile = new CameraDetectionProfile(camera.Id)
|
|
{
|
|
DetectPerson = request.DetectionProfile.DetectPerson,
|
|
DetectVehicle = request.DetectionProfile.DetectVehicle,
|
|
DetectAnimal = request.DetectionProfile.DetectAnimal,
|
|
DetectPackage = request.DetectionProfile.DetectPackage,
|
|
DetectMotion = request.DetectionProfile.DetectMotion,
|
|
FaceRecognition = request.DetectionProfile.FaceRecognition,
|
|
LicensePlateRecognition = request.DetectionProfile.LicensePlateRecognition,
|
|
};
|
|
camera.SetDetectionProfile(profile);
|
|
}
|
|
|
|
// Assign to requesting agent if provided
|
|
if (request.AgentId.HasValue)
|
|
camera.AssignAgent(request.AgentId.Value);
|
|
|
|
db.Cameras.Add(camera);
|
|
discoveryResult.MarkProcessed();
|
|
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
|
|
|
_logger.LogInformation(
|
|
"Camera '{Name}' created from discovery result {ResultId} (IP={Ip}, MAC={Mac})",
|
|
request.Name, request.DiscoveryResultId, discoveryResult.IpAddress, discoveryResult.MacAddress);
|
|
|
|
return ServiceResult<CameraResponse>.Success(MapToResponse(camera));
|
|
}
|
|
|
|
/// <summary>Check for duplicate camera before confirming a discovery.</summary>
|
|
public async Task<ServiceResult<CameraCheckResponse>> CheckDuplicateAsync(CheckDuplicateRequest request, CancellationToken ct)
|
|
{
|
|
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
|
|
|
var dup = await FindDuplicateCameraAsync(db, request.SiteId, request.Ip, request.Mac, ct).ConfigureAwait(false);
|
|
|
|
return ServiceResult<CameraCheckResponse>.Success(new CameraCheckResponse(
|
|
dup is not null,
|
|
dup?.Id,
|
|
dup?.Name,
|
|
dup?.IpAddress,
|
|
dup?.MacAddress,
|
|
dup?.Status.ToString()));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Find a camera that is already registered for the same site with the same
|
|
/// IP address or MAC address. Returns null if no duplicate exists.
|
|
/// </summary>
|
|
private static async Task<Camera?> FindDuplicateCameraAsync(AppDbContext db, Guid siteId, string ip, string? mac, CancellationToken ct)
|
|
{
|
|
// Priority 1: exact IP match within the same site (most common scenario)
|
|
if (!string.IsNullOrEmpty(ip))
|
|
{
|
|
var byIp = await db.Cameras
|
|
.AsTracking()
|
|
.FirstOrDefaultAsync(c => c.SiteId == siteId
|
|
&& c.IpAddress == ip
|
|
&& !c.IsDeleted, ct);
|
|
if (byIp is not null)
|
|
return byIp;
|
|
}
|
|
|
|
// Priority 2: exact MAC match (camera may have moved to a different IP)
|
|
if (!string.IsNullOrEmpty(mac))
|
|
{
|
|
var byMac = await db.Cameras
|
|
.AsTracking()
|
|
.FirstOrDefaultAsync(c => c.SiteId == siteId
|
|
&& c.MacAddress == mac
|
|
&& !c.IsDeleted, ct);
|
|
if (byMac is not null)
|
|
return byMac;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
// ─── Agent-submitted discovery (agent → central) ────────────────────
|
|
|
|
public async Task<ServiceResult<AgentDiscoverySubmitResponse>> SubmitAgentDiscoveriesAsync(
|
|
Guid agentId, IReadOnlyList<AgentDiscoveredDevice> devices, CancellationToken ct)
|
|
{
|
|
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
|
|
|
var agent = await db.Agents.FirstOrDefaultAsync(a => a.Id == agentId, ct).ConfigureAwait(false);
|
|
if (agent is null)
|
|
return ServiceResult<AgentDiscoverySubmitResponse>.NotFound("Agent not found");
|
|
|
|
var siteId = agent.SiteId;
|
|
|
|
// Site credential pool, decrypted (tracked so LastUsedAt persists).
|
|
var credentials = await db.SiteCredentials
|
|
.Where(c => c.SiteId == siteId)
|
|
.ToListAsync(ct)
|
|
.ConfigureAwait(false);
|
|
var pool = credentials
|
|
.Select(c => (Credential: c, Password: _credentialProtector.Decrypt(c.Password)))
|
|
.ToList();
|
|
|
|
var newCount = 0;
|
|
var updatedCount = 0;
|
|
|
|
foreach (var device in devices)
|
|
{
|
|
var processed = await ProcessDiscoveredDeviceAsync(db, siteId, device, pool, ct).ConfigureAwait(false);
|
|
if (processed == 1) newCount++;
|
|
else if (processed == 2) updatedCount++;
|
|
}
|
|
|
|
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
|
|
|
_logger.LogInformation(
|
|
"Agent {AgentId} submitted {Total} devices: {New} new, {Updated} updated (site {SiteId})",
|
|
agentId, devices.Count, newCount, updatedCount, siteId);
|
|
|
|
return ServiceResult<AgentDiscoverySubmitResponse>.Success(
|
|
new AgentDiscoverySubmitResponse(devices.Count, newCount, updatedCount));
|
|
}
|
|
|
|
|
|
/// <summary>Process a single discovered device from an agent submission.</summary>
|
|
/// <returns>0 = skipped, 1 = new, 2 = updated.</returns>
|
|
private async Task<int> ProcessDiscoveredDeviceAsync(
|
|
AppDbContext db, Guid? siteId, AgentDiscoveredDevice device,
|
|
List<(SiteCredential Credential, string Password)> pool, CancellationToken ct)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(device.Ip) || !IPAddress.TryParse(device.Ip, out _))
|
|
return 0;
|
|
|
|
if (ClassifyAgentDevice(device).type == DetectedCameraType.Unknown)
|
|
return 0;
|
|
|
|
var result = await db.CameraDiscoveryResults
|
|
.Include(r => r.DiscoveredStreams)
|
|
.FirstOrDefaultAsync(r => r.SiteId == siteId && r.IpAddress == device.Ip && !r.IsProcessed, ct)
|
|
.ConfigureAwait(false);
|
|
|
|
int outcome;
|
|
if (result is null)
|
|
{
|
|
result = new CameraDiscoveryResult(siteId!.Value, device.Ip);
|
|
db.CameraDiscoveryResults.Add(result);
|
|
outcome = 1;
|
|
}
|
|
else
|
|
{
|
|
outcome = 2;
|
|
}
|
|
|
|
ApplyAgentProbeData(result, device);
|
|
CacheScreenshot(result, device);
|
|
MarkCredentialUsed(device, pool);
|
|
|
|
await BuildCandidateStreamUrlsAsync(db, result, device, pool, ct).ConfigureAwait(false);
|
|
return outcome;
|
|
}
|
|
|
|
private void CacheScreenshot(CameraDiscoveryResult result, AgentDiscoveredDevice device)
|
|
{
|
|
if (string.IsNullOrEmpty(device.ScreenshotBase64))
|
|
return;
|
|
try
|
|
{
|
|
var bytes = Convert.FromBase64String(device.ScreenshotBase64);
|
|
_screenshots[result.Id] = new ScreenshotEntry(bytes, DateTime.UtcNow.AddMinutes(10));
|
|
}
|
|
catch (FormatException ex)
|
|
{
|
|
_logger.LogDebug(ex, "Invalid screenshot base64 for {Ip}, ignoring", device.Ip);
|
|
}
|
|
}
|
|
|
|
private void MarkCredentialUsed(AgentDiscoveredDevice device, List<(SiteCredential Credential, string Password)> pool)
|
|
{
|
|
if (string.IsNullOrEmpty(device.CredentialLabel))
|
|
return;
|
|
var used = pool.FirstOrDefault(p =>
|
|
string.Equals(p.Credential.Label, device.CredentialLabel, StringComparison.Ordinal));
|
|
if (used.Credential is not null)
|
|
{
|
|
used.Credential.MarkUsed();
|
|
_logger.LogInformation(
|
|
"Agent discovery {Ip} authenticated with credential '{Label}' (reported by agent)",
|
|
device.Ip, device.CredentialLabel);
|
|
}
|
|
}
|
|
|
|
private void ApplyAgentProbeData(CameraDiscoveryResult result, AgentDiscoveredDevice device)
|
|
{
|
|
var mac = device.MacAddress ?? result.MacAddress;
|
|
|
|
// The agent reports the ONVIF manufacturer (device.OnvifName) when it
|
|
// authenticated successfully — prefer it over the MAC OUI (more
|
|
// reliable, e.g. Imou reports Dahua/Imou while sharing OUIs).
|
|
var vendor = device.Vendor;
|
|
if (vendor is null && !string.IsNullOrEmpty(device.OnvifName))
|
|
vendor = NormalizeVendor(device.OnvifName);
|
|
vendor ??= result.Vendor ?? (mac is not null ? ResolveOuiVendor(mac) : null);
|
|
|
|
if (!string.IsNullOrEmpty(mac) || !string.IsNullOrEmpty(vendor))
|
|
result.SetArpInfo(mac ?? string.Empty, vendor);
|
|
result.SetHostname(device.Hostname);
|
|
|
|
if (device.OpenPorts.Length > 0)
|
|
result.SetOpenPorts(device.OpenPorts);
|
|
|
|
if (!string.IsNullOrEmpty(device.HttpServerHeader) || device.HttpStatusCode is not null)
|
|
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);
|
|
|
|
if (!string.IsNullOrEmpty(device.OnvifDeviceServiceUrl) || device.OnvifPort is not null)
|
|
result.SetOnvifResult(
|
|
device.OnvifDeviceServiceUrl ?? result.OnvifDeviceServiceUrl ?? string.Empty,
|
|
device.OnvifName ?? result.OnvifName,
|
|
device.OnvifHardware ?? result.OnvifHardware,
|
|
device.OnvifPort ?? 80);
|
|
|
|
// Classification (mirrors ClassifyCamera for agent-submitted data).
|
|
var (type, method) = ClassifyAgentDevice(device);
|
|
result.MarkReachable(type, method);
|
|
}
|
|
|
|
private static (DetectedCameraType type, CameraDiscoveryMethod method) ClassifyAgentDevice(AgentDiscoveredDevice device)
|
|
{
|
|
if (!string.IsNullOrEmpty(device.OnvifHardware) || !string.IsNullOrEmpty(device.OnvifDeviceServiceUrl))
|
|
return (DetectedCameraType.Standard, CameraDiscoveryMethod.OnvifWsDiscovery);
|
|
|
|
if (!string.IsNullOrEmpty(device.HomeKitName))
|
|
return (DetectedCameraType.HomeKit, CameraDiscoveryMethod.MdnsHomeKit);
|
|
|
|
var server = device.HttpServerHeader?.ToLowerInvariant() ?? string.Empty;
|
|
if (server.Contains("hikvision") || server.Contains("dahua") || server.Contains("imou")
|
|
|| server.Contains("axis") || server.Contains("uniview") || server.Contains("tapo"))
|
|
return (DetectedCameraType.Standard, CameraDiscoveryMethod.HttpProbe);
|
|
|
|
// 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)
|
|
|| 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);
|
|
}
|
|
|
|
private async Task BuildCandidateStreamUrlsAsync(
|
|
AppDbContext db,
|
|
CameraDiscoveryResult result,
|
|
AgentDiscoveredDevice device,
|
|
List<(SiteCredential Credential, string Password)> pool,
|
|
CancellationToken ct)
|
|
{
|
|
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;
|
|
if (pool.Count > 0)
|
|
{
|
|
username = pool[0].Credential.Username;
|
|
password = pool[0].Password;
|
|
}
|
|
|
|
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 && CameraStreamTemplates.StreamTemplates.ContainsKey($"b:{vendorKey}"))
|
|
ids.Insert(0, $"b:{vendorKey}");
|
|
|
|
var buildRequest = new StreamBuildRequest(
|
|
[.. ids], device.Ip, username, password, Channel: 0,
|
|
PortFilter: device.OpenPorts.Contains(554) ? [554] : device.OpenPorts);
|
|
var buildResult = await BuildStreamUrlsAsync(buildRequest, ct).ConfigureAwait(false);
|
|
if (!buildResult.IsSuccess || buildResult.Data is null)
|
|
return;
|
|
|
|
// 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;
|
|
|
|
// Add through the DbSet directly — adding via the loaded navigation
|
|
// 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: agentUrls.Contains(url, StringComparer.OrdinalIgnoreCase)));
|
|
existing.Add(url);
|
|
}
|
|
}
|
|
|
|
private static StreamProtocol ProtocolFromUrl(string url)
|
|
{
|
|
if (url.StartsWith("rtsp://", StringComparison.OrdinalIgnoreCase)) return StreamProtocol.Rtsp;
|
|
if (url.StartsWith("rtsps://", StringComparison.OrdinalIgnoreCase)) return StreamProtocol.Rtsps;
|
|
if (url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) return StreamProtocol.Https;
|
|
if (url.StartsWith("rtmp://", StringComparison.OrdinalIgnoreCase)) return StreamProtocol.Rtmp;
|
|
if (url.StartsWith("rtmps://", StringComparison.OrdinalIgnoreCase)) return StreamProtocol.Rtmps;
|
|
if (url.StartsWith("dvrip://", StringComparison.OrdinalIgnoreCase)) return StreamProtocol.Dvrip;
|
|
if (url.StartsWith("bubble://", StringComparison.OrdinalIgnoreCase)) return StreamProtocol.Bubble;
|
|
if (url.StartsWith("homekit://", StringComparison.OrdinalIgnoreCase)) return StreamProtocol.HomeKit;
|
|
if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) return StreamProtocol.Http;
|
|
return StreamProtocol.Rtsp;
|
|
}
|
|
|
|
// ─── Pending discovery listing / rejection ──────────────────────────
|
|
|
|
/// <summary>
|
|
/// Minimal OUI → vendor resolution for common camera manufacturers.
|
|
/// The Central cannot read the camera network's ARP table, so the vendor
|
|
/// is resolved from the MAC prefix reported by the agent. Note: OUIs are
|
|
/// ambiguous across brands (Imou shares Dahua/Hikvision OUIs) — prefer
|
|
/// <see cref="NormalizeVendor"/> from the ONVIF manufacturer when available.
|
|
/// </summary>
|
|
private static readonly (string Prefix, string Vendor)[] OuiTable =
|
|
[
|
|
("00:0F:FF", "Hikvision"), ("44:19:B6", "Hikvision"), ("3C:EF:8C", "Hikvision"),
|
|
("54:C4:15", "Hikvision"), ("90:02:A9", "Hikvision"), ("9C:8E:99", "Hikvision"),
|
|
("E0:50:8B", "Hikvision"), ("50:6A:03", "Hikvision"),
|
|
("9C:8E:99", "Dahua"), ("3C:EF:8C", "Dahua"), ("C4:2F:90", "Dahua"),
|
|
("E0:50:8B", "Dahua"), ("58:23:8C", "Dahua"), ("A0:BD:1D", "Dahua"),
|
|
("00:1C:27", "Axis Communications"), ("00:40:8C", "Axis Communications"),
|
|
("AC:CC:8E", "Axis Communications"), ("B8:A4:4F", "Axis Communications"),
|
|
("3C:EF:8C", "Amcrest"), ("9C:8E:99", "Amcrest"),
|
|
("58:23:8C", "Uniview"), ("3C:EF:8C", "Uniview"),
|
|
("50:C7:BF", "TP-Link"), ("60:32:B1", "TP-Link"), ("F4:F2:6D", "TP-Link"),
|
|
];
|
|
|
|
private string? ResolveOuiVendor(string mac)
|
|
{
|
|
// StrixCamDB OUI table (2 406 préfixes) quand embarquée.
|
|
if (_cameraDatabase.IsAvailable)
|
|
{
|
|
var vendor = _cameraDatabase.LookupOui(mac);
|
|
if (vendor is not null)
|
|
return vendor;
|
|
}
|
|
|
|
var normalized = mac.Replace(":", string.Empty, StringComparison.OrdinalIgnoreCase)
|
|
.Replace("-", string.Empty, StringComparison.OrdinalIgnoreCase);
|
|
if (normalized.Length < 6)
|
|
return null;
|
|
|
|
var prefix = normalized[..6].ToUpperInvariant();
|
|
foreach (var (oui, vendor) in OuiTable)
|
|
{
|
|
if (oui.Replace(":", string.Empty).Equals(prefix, StringComparison.OrdinalIgnoreCase))
|
|
return vendor;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Map an ONVIF manufacturer name to a camera-database vendor key
|
|
/// (b:xxx used in <see cref="StreamTemplates"/>). Returns null when the
|
|
/// manufacturer is unknown — the generic templates still apply.
|
|
/// </summary>
|
|
private static string? NormalizeVendor(string? manufacturer)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(manufacturer))
|
|
return null;
|
|
|
|
var m = manufacturer.ToLowerInvariant();
|
|
if (m.Contains("hikvision")) return "hikvision";
|
|
if (m.Contains("imou") || m.Contains("lechange")) return "imou";
|
|
if (m.Contains("dahua")) return "dahua";
|
|
if (m.Contains("axis")) return "axis";
|
|
if (m.Contains("vivotek")) return "vivotek";
|
|
if (m.Contains("amcrest")) return "amcrest";
|
|
if (m.Contains("panasonic")) return "panasonic";
|
|
if (m.Contains("bosch")) return "bosch";
|
|
if (m.Contains("samsung")) return "samsung";
|
|
if (m.Contains("sony")) return "sony";
|
|
if (m.Contains("uniview")) return "uniview";
|
|
if (m.Contains("tp-link") || m.Contains("tapo")) return "tp-link";
|
|
return null;
|
|
}
|
|
|
|
public async Task<ServiceResult<IReadOnlyList<PendingDiscoveryResponse>>> ListPendingDiscoveriesAsync(
|
|
Guid siteId, CancellationToken ct)
|
|
{
|
|
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
|
|
|
var results = await db.CameraDiscoveryResults
|
|
.Include(r => r.DiscoveredStreams)
|
|
.Where(r => r.SiteId == siteId && !r.IsProcessed)
|
|
.OrderByDescending(r => r.ProbedAt)
|
|
.Take(200)
|
|
.ToListAsync(ct)
|
|
.ConfigureAwait(false);
|
|
|
|
var response = results.Select(r => new PendingDiscoveryResponse(
|
|
r.Id, r.SiteId, r.IpAddress, r.MacAddress, r.Vendor, r.Hostname, r.IsReachable,
|
|
r.DetectedType.ToString(), r.DiscoveryMethod.ToString(), r.OpenPorts,
|
|
r.OnvifDeviceServiceUrl, r.OnvifName, r.OnvifHardware, r.OnvifPort,
|
|
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))
|
|
.ToList();
|
|
|
|
return ServiceResult<IReadOnlyList<PendingDiscoveryResponse>>.Success(response);
|
|
}
|
|
|
|
/// <summary>Get the in-memory screenshot (agent-captured) for a discovery result.</summary>
|
|
public byte[]? GetDiscoveryScreenshot(Guid resultId)
|
|
{
|
|
if (!_screenshots.TryGetValue(resultId, out var shot))
|
|
return null;
|
|
if (shot.ExpiresAt <= DateTime.UtcNow)
|
|
{
|
|
_screenshots.TryRemove(resultId, out _);
|
|
return null;
|
|
}
|
|
return shot.Bytes;
|
|
}
|
|
|
|
public async Task<ServiceResult> RejectDiscoveryAsync(Guid resultId, CancellationToken ct)
|
|
{
|
|
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
|
|
|
var result = await db.CameraDiscoveryResults
|
|
.FirstOrDefaultAsync(r => r.Id == resultId && !r.IsProcessed, ct)
|
|
.ConfigureAwait(false);
|
|
|
|
if (result is null)
|
|
return ServiceResult.NotFound("Discovery result not found or already processed");
|
|
|
|
result.MarkProcessed();
|
|
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
|
|
|
_logger.LogInformation("Discovery result {ResultId} ({Ip}) rejected", resultId, result.IpAddress);
|
|
return ServiceResult.Success();
|
|
}
|
|
|
|
// ─── Private Helpers ──────────────────────────────────────────────
|
|
|
|
private static (DetectedCameraType type, CameraDiscoveryMethod method) ClassifyCamera(
|
|
OnvifDeviceInfo? onvif, HomeKitDeviceInfo? homeKit, 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() ?? "";
|
|
if (server.Contains("hikvision") || server.Contains("dahua") || server.Contains("axis"))
|
|
return (DetectedCameraType.Standard, CameraDiscoveryMethod.HttpProbe);
|
|
}
|
|
|
|
if (ports.Contains(8899) || ports.Contains(37777))
|
|
return (DetectedCameraType.Nvr, CameraDiscoveryMethod.NetworkScan);
|
|
|
|
if (ports.Contains(554) || ports.Contains(8554))
|
|
return (DetectedCameraType.Standard, CameraDiscoveryMethod.NetworkScan);
|
|
|
|
return (DetectedCameraType.Unknown, CameraDiscoveryMethod.NetworkScan);
|
|
}
|
|
|
|
/// <summary>Expand a CIDR subnet to individual IP addresses.</summary>
|
|
public static List<string> ExpandSubnet(string subnetCidr)
|
|
{
|
|
var parts = subnetCidr.Split('/');
|
|
if (parts.Length != 2)
|
|
return [];
|
|
|
|
if (!IPAddress.TryParse(parts[0], out var ip))
|
|
return [];
|
|
|
|
if (!int.TryParse(parts[1], out var prefixLength) || prefixLength < 0 || prefixLength > 32)
|
|
return [];
|
|
|
|
var ipBytes = ip.GetAddressBytes();
|
|
if (BitConverter.IsLittleEndian)
|
|
Array.Reverse(ipBytes);
|
|
|
|
var uintIp = BitConverter.ToUInt32(ipBytes, 0);
|
|
|
|
// Calculate network mask and host count
|
|
uint mask;
|
|
long hostCount;
|
|
int startOffset;
|
|
|
|
if (prefixLength >= 32)
|
|
{
|
|
// /32 = single host = the IP itself
|
|
mask = uint.MaxValue;
|
|
hostCount = 1;
|
|
startOffset = 0;
|
|
}
|
|
else if (prefixLength == 31)
|
|
{
|
|
// RFC 3021: /31 = point-to-point, 2 usable hosts, no broadcast
|
|
mask = uint.MaxValue << 1;
|
|
hostCount = 2;
|
|
startOffset = 0;
|
|
}
|
|
else if (prefixLength == 0)
|
|
{
|
|
mask = 0;
|
|
hostCount = (1L << 32) - 2; // All minus network and broadcast
|
|
startOffset = 1;
|
|
}
|
|
else
|
|
{
|
|
mask = uint.MaxValue << (32 - prefixLength);
|
|
hostCount = (1L << (32 - prefixLength)) - 2; // Minus network and broadcast
|
|
startOffset = 1;
|
|
}
|
|
|
|
if (hostCount < 0)
|
|
hostCount = 0;
|
|
if (hostCount > 65536)
|
|
hostCount = 65536;
|
|
|
|
var network = uintIp & mask;
|
|
var ips = new List<string>((int)hostCount);
|
|
for (int i = 0; i < hostCount; i++)
|
|
{
|
|
var hostIp = network + (uint)(i + startOffset);
|
|
var bytes = BitConverter.GetBytes(hostIp);
|
|
if (BitConverter.IsLittleEndian)
|
|
Array.Reverse(bytes);
|
|
ips.Add(new IPAddress(bytes).ToString());
|
|
}
|
|
|
|
return ips;
|
|
}
|
|
|
|
private static CameraResponse MapToResponse(Camera c) => new(
|
|
c.Id, c.SiteId, c.AgentId, c.Name, c.Manufacturer, c.Model,
|
|
c.RtspUrl, c.SubRtspUrl,
|
|
c.Status, c.DiscoveryMethod, c.DetectedType, c.Capabilities,
|
|
c.IpAddress, c.MacAddress, c.RtspPort, c.HttpPort, c.OnvifPort,
|
|
c.LastTestedCodecs, c.LastTestedWidth, c.LastTestedHeight, c.LastTestedLatencyMs,
|
|
c.LastDiscoveredAt, c.LastStreamTestAt,
|
|
c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt);
|
|
}
|