Files
Heimdall/src/Heimdall.Web/Components/Pages/DiscoveriesPage.razor
T
Arnaud Dartois ddfa22bee6 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
2026-08-11 20:47:27 +02:00

320 lines
12 KiB
Plaintext

@page "/sites/{SiteId:guid}/discoveries"
@attribute [Authorize]
@layout MainLayout
@inject HeimdallApiClient Api
@inject ISnackbar Snackbar
@inject NavigationManager Nav
<MudText Typo="Typo.h1" Class="mb-1">
<i class="fas fa-radar mr-2"></i>
Caméras détectées
</MudText>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-4">
Résultats des scans réseau effectués par les agents du site. Les caméras compatibles
sont détectées automatiquement ; confirmez celles à ajouter.
</MudText>
<div class="d-flex justify-space-between align-center mb-4">
<div>
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@ScanNow" Disabled="@_scanning">
@if (_scanning) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
<MudIcon Icon="@Icons.Material.Filled.Radar" Class="mr-1" /> Scanner maintenant
</MudButton>
<MudTooltip Text="Rafraîchir la liste">
<MudIconButton Icon="@Icons.Material.Filled.Refresh" OnClick="@LoadDiscoveries" Class="ml-2" />
</MudTooltip>
</div>
<MudButton Variant="Variant.Text" Color="Color.Default" OnClick="@(() => Nav.NavigateTo($"/sites/{SiteId}"))">
← Retour au site
</MudButton>
</div>
@if (_scanning)
{
<MudAlert Severity="Severity.Info" Class="mb-4">
Scan demandé aux agents du site. Les résultats arrivent dans quelques instants…
</MudAlert>
}
@if (_loading)
{
<MudProgressCircular Indeterminate="true" />
}
else if (_discoveries.Count == 0)
{
<MudPaper Elevation="2" Class="pa-6 text-center" Style="border-radius: 12px;">
<MudIcon Icon="@Icons.Material.Filled.VideocamOff" Size="Size.Large" Color="Color.Default" />
<MudText Typo="Typo.h6" Class="mt-2">Aucune caméra détectée</MudText>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-4">
Lancez un scan avec « Scanner maintenant » (les agents doivent être en ligne),
ou vérifiez que des identifiants caméras sont déclarés sur le site.
</MudText>
</MudPaper>
}
else
{
<MudTable Items="@_discoveries" Hover="true" Striped="true" Elevation="2">
<HeaderContent>
<MudTh>Adresse IP</MudTh>
<MudTh>Marque / Modèle</MudTh>
<MudTh>Type</MudTh>
<MudTh>Ports</MudTh>
<MudTh>Détecté le</MudTh>
<MudTh>Actions</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="IP">
<strong>@context.IpAddress</strong>
@if (!string.IsNullOrEmpty(context.MacAddress))
{
<MudText Typo="Typo.caption" Color="Color.Secondary">@context.MacAddress</MudText>
}
</MudTd>
<MudTd DataLabel="Marque">
@if (!string.IsNullOrEmpty(context.Vendor) || !string.IsNullOrEmpty(context.OnvifHardware))
{
<MudText Typo="Typo.body2">@(context.Vendor ?? "Inconnu")</MudText>
@if (!string.IsNullOrEmpty(context.OnvifHardware))
{
<MudText Typo="Typo.caption" Color="Color.Secondary">@context.OnvifHardware</MudText>
}
}
else if (!string.IsNullOrEmpty(context.HttpServerHeader))
{
<MudText Typo="Typo.body2">@context.HttpServerHeader</MudText>
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary">Inconnue</MudText>
}
</MudTd>
<MudTd DataLabel="Type">
<StatusChip Text="@FormatType(context.DetectedType)" Color="@TypeColor(context.DetectedType)"
Icon="@Icons.Material.Filled.Videocam" />
</MudTd>
<MudTd DataLabel="Ports">
@if (context.OpenPorts.Length == 0) { <MudText Typo="Typo.body2">-</MudText> }
else
{
<div class="d-flex flex-wrap" style="gap: 4px;">
@foreach (var port in context.OpenPorts)
{
<MudChip T="string" Size="Size.Small" Variant="Variant.Outlined">@port</MudChip>
}
</div>
}
</MudTd>
<MudTd DataLabel="Détecté le">@context.ProbedAt.ToLocalTime().ToString("g")</MudTd>
<MudTd DataLabel="Actions">
<MudTooltip Text="Ajouter cette caméra">
<MudIconButton Icon="@Icons.Material.Filled.AddCircle" Color="Color.Success"
aria-label="Confirmer la caméra"
OnClick="@(() => OpenConfirm(context))" />
</MudTooltip>
<MudTooltip Text="Ignorer cette détection">
<MudIconButton Icon="@Icons.Material.Filled.Cancel" Color="Color.Default"
aria-label="Ignorer la détection"
OnClick="@(() => Reject(context))" />
</MudTooltip>
</MudTd>
</RowTemplate>
</MudTable>
}
@* ─── Dialog de confirmation ─────────────────────────────────────── *@
<MudOverlay Visible="@_confirmShow" OnClick="@(() => _confirmShow = false)" />
<MudDialog @bind-Visible="_confirmShow" Options="new DialogOptions { MaxWidth = MaxWidth.Medium, FullWidth = true }">
<TitleContent>
<MudText Typo="Typo.h6">Ajouter la caméra @_confirm?.IpAddress</MudText>
</TitleContent>
<DialogContent>
@if (_confirm is not null)
{
<MudTextField @bind-Value="_confirmName" Label="Nom de la caméra *" Variant="Variant.Outlined"
Class="mb-4" Immediate="true" />
@if (!string.IsNullOrEmpty(_selectedStreamUrl))
{
<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">
Aucun flux n'a pu être détecté pour cette caméra (hors ligne ou protégée ?).
</MudAlert>
}
<MudText Typo="Typo.caption" Color="Color.Secondary" Class="mb-4">
@(_confirm.Vendor ?? "Marque inconnue")
@if (!string.IsNullOrEmpty(_confirm.OnvifHardware)) { <text>· @_confirm.OnvifHardware</text> }
@if (!string.IsNullOrEmpty(_confirm.MacAddress)) { <text>· @_confirm.MacAddress</text> }
</MudText>
@if (!string.IsNullOrEmpty(_confirmError))
{
<MudAlert Severity="Severity.Error" Class="mb-4">@_confirmError</MudAlert>
}
}
</DialogContent>
<DialogActions>
<MudButton Variant="Variant.Text" OnClick="@(() => _confirmShow = false)">Annuler</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Success" OnClick="@ConfirmCamera"
Disabled="@(_confirming || string.IsNullOrWhiteSpace(_confirmName) || string.IsNullOrEmpty(_selectedStreamUrl))">
@if (_confirming) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
Ajouter la caméra
</MudButton>
</DialogActions>
</MudDialog>
@code {
[Parameter] public Guid SiteId { get; set; }
private List<PendingDiscoveryItem> _discoveries = [];
private bool _loading = true;
private bool _scanning;
// Confirmation
private PendingDiscoveryItem? _confirm;
private bool _confirmShow;
private bool _confirming;
private string _confirmName = "";
private string _selectedStreamUrl = "";
private string _confirmError = "";
private Guid? _siteAgentId;
protected override async Task OnInitializedAsync()
{
await LoadDiscoveries();
await LoadSiteAgent();
}
private async Task LoadDiscoveries()
{
_loading = true;
try
{
_discoveries = await Api.GetPendingDiscoveriesAsync(SiteId);
}
catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); }
finally { _loading = false; }
}
private async Task LoadSiteAgent()
{
try
{
var agents = await Api.GetAgentsBySiteAsync(SiteId, 1, 50);
_siteAgentId = agents?.Items.FirstOrDefault()?.Id;
}
catch { /* best effort — la caméra sera créée sans agent assigné */ }
}
private async Task ScanNow()
{
_scanning = true;
try
{
var result = await Api.ScanNowAsync(SiteId);
Snackbar.Add(
result is { AgentsNotified: > 0 }
? $"Scan demandé à {result.AgentsNotified} agent(s)"
: "Scan demandé (aucun agent en ligne ?)",
result is { AgentsNotified: > 0 } ? Severity.Success : Severity.Warning);
await Task.Delay(TimeSpan.FromSeconds(8));
await LoadDiscoveries();
}
catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); }
finally { _scanning = false; }
}
private void OpenConfirm(PendingDiscoveryItem item)
{
_confirm = item;
_confirmName = DefaultName(item);
_selectedStreamUrl = item.StreamUrls.FirstOrDefault() ?? "";
_confirmError = "";
_confirmShow = true;
}
private static string DefaultName(PendingDiscoveryItem item)
{
var vendor = item.Vendor ?? item.OnvifHardware ?? "Caméra";
return $"{vendor} ({item.IpAddress})";
}
private async Task ConfirmCamera()
{
if (_confirm is null || string.IsNullOrEmpty(_selectedStreamUrl)) return;
_confirming = true;
_confirmError = "";
try
{
var (user, pass) = ExtractCredentials(_selectedStreamUrl);
var camera = await Api.ConfirmDiscoveryAsync(
SiteId, _confirm.Id, _confirmName.Trim(), _selectedStreamUrl,
user, pass, _siteAgentId);
if (camera is null)
{
_confirmError = "Impossible d'ajouter la caméra (déjà enregistrée ou erreur).";
return;
}
Snackbar.Add($"Caméra \"{camera.Name}\" ajoutée", Severity.Success);
_confirmShow = false;
await LoadDiscoveries();
}
catch { _confirmError = UiErrors.OperationFailed(); }
finally { _confirming = false; }
}
private async Task Reject(PendingDiscoveryItem item)
{
if (await Api.RejectDiscoveryAsync(item.Id))
{
Snackbar.Add($"Détection {item.IpAddress} ignorée", Severity.Info);
await LoadDiscoveries();
}
else
{
Snackbar.Add("Erreur lors de l'ignorance", Severity.Error);
}
}
private static (string? User, string? Pass) ExtractCredentials(string url)
{
try
{
var uri = new Uri(url);
if (!string.IsNullOrEmpty(uri.UserInfo))
{
var parts = uri.UserInfo.Split(':', 2);
return (Uri.UnescapeDataString(parts[0]),
parts.Length > 1 ? Uri.UnescapeDataString(parts[1]) : "");
}
}
catch { /* URL invalide — pas de credentials */ }
return (null, null);
}
private static string FormatType(string detectedType) => detectedType switch
{
"Standard" => "Caméra",
"Nvr" => "NVR",
"HomeKit" => "HomeKit",
"Doorbell" => "Sonnette",
_ => "Inconnu"
};
private static Color TypeColor(string detectedType) => detectedType switch
{
"Standard" or "Nvr" => Color.Success,
"HomeKit" => Color.Info,
_ => Color.Default
};
}