From 2ddf51c57e835761a7c3924d3020dca3ca7c14c0 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Mon, 10 Aug 2026 23:07:43 +0200 Subject: [PATCH] feat(web): live view & CameraDetail enrichie (Fixes #35) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Vue live 16:9 : snapshot rafraîchi toutes les 10s (garde CancellationToken, pause si disposé), skeleton pendant chargement, point live pulsant, actions Prendre un snapshot / Actualiser en overlay. - RTSP masquée par défaut (InputType.Password) avec toggle œil. - Actions complètes : Enregistrer, Activer/Désactiver (statut), Supprimer avec dialog de confirmation — toujours rendus, @bind-Visible (pattern c266f26, corrige le @if autour du dialog snapshot présent avant). - Mini-timeline : 10 événements récents avec chips colorées par type (traduit), confiance en %, snapshot cliquable, lien vers /events?q=. - Statut traduit en badge (En ligne/Hors ligne/Désactivée). - Tests : 5 nouveaux (infos, RTSP masqué+toggle, vue live, toggle statut, suppression+navigation). 178 tests Web verts. --- .../Components/Pages/CameraDetail.razor | 289 +++++++++++++++--- .../Components/Pages/CameraDetailTests.cs | 136 +++++++++ 2 files changed, 376 insertions(+), 49 deletions(-) create mode 100644 tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs diff --git a/src/Heimdall.Web/Components/Pages/CameraDetail.razor b/src/Heimdall.Web/Components/Pages/CameraDetail.razor index 6570280..9737bc2 100644 --- a/src/Heimdall.Web/Components/Pages/CameraDetail.razor +++ b/src/Heimdall.Web/Components/Pages/CameraDetail.razor @@ -5,14 +5,25 @@ @inject ISnackbar Snackbar @inject NavigationManager Nav - + Caméra : @_camera?.Name + + @if (_camera is not null) + { + + @GetStatusIcon(_camera.Status) @FormatStatus(_camera.Status) + + Créée le @_camera.CreatedAt.ToString("g") + } + @if (_loading) { - + + + } else if (_camera is null) { @@ -20,14 +31,60 @@ else if (_camera is null) } else { - + @* ─── Live view : snapshot rafraîchi ─── *@ + +
+ @if (_snapshotLoading) + { + + } + else if (!string.IsNullOrEmpty(_latestSnapshotUrl)) + { + Vue live de @_camera.Name + @if (_camera.Status == "Online") + { + + } + } + else + { +
+ + + Aucun flux disponible pour cette caméra + +
+ } + + @* Overlay actions live *@ +
+ + + + + + +
+
+
+ + @* ─── Informations & actions ─── *@ + Informations - + Fabricant @@ -37,48 +94,52 @@ else Modèle @(_camera.Model ?? "-") - - Statut - - @GetStatusIcon(_camera.Status) @_camera.Status - - - - Créée le - @_camera.CreatedAt.ToString("g") - + + @if (!string.IsNullOrEmpty(_editError)) + { + @_editError + } + @if (!string.IsNullOrEmpty(_editSuccess)) + { + @_editSuccess + } + +
+ + @if (_saving) { } + Enregistrer + + + + @(_camera.Status == "Disabled" ? "Activer" : "Désactiver") + + + Supprimer + + + + ← Retour aux caméras + +
- @if (!string.IsNullOrEmpty(_editError)) - { - @_editError - } - @if (!string.IsNullOrEmpty(_editSuccess)) - { - @_editSuccess - } - - - @if (_saving) { } - Enregistrer - - - ← Retour aux caméras - - - @* Recent Events *@ - + @* ─── Mini-timeline : événements récents ─── *@ + Événements récents @if (_eventsLoading) { - + + + } else if (_events is { Count: > 0 }) { - + Horodatage Type @@ -88,17 +149,21 @@ else @context.OccurredAt.ToLocalTime().ToString("g") - @context.Type - @($"{context.Confidence:P0}") + + + @FormatEventType(context.Type) + + + @($"{(context.Confidence * 100):0}%") @context.Label + OnClick="@(() => { _showSnapshotUrl = context.SnapshotUrl; _showSnapshotDialog = true; })" /> - + Voir tous les événements → } @@ -107,17 +172,30 @@ else Aucun événement récent. } - @if (_showSnapshotUrl is not null) - { - - + @* ─── Dialogs (toujours rendus, visibilité via @bind-Visible) ─── *@ + + + Confirmer la suppression + + Supprimer la caméra "@_camera.Name" ? Cette action est irréversible. + + + Annuler + Supprimer + + + + + + @if (_showSnapshotUrl is not null) + { Snapshot - - - Fermer - - - } + } + + + Fermer + + } @code { @@ -130,6 +208,8 @@ else private string _editSuccess = ""; private bool _loading = true; private bool _saving; + private bool _showRtsp; + private bool _confirmDeleteShow; private List? _events; private bool _eventsLoading; @@ -142,6 +222,11 @@ else CloseButton = true }; + private string? _latestSnapshotUrl; + private bool _snapshotLoading; + private CancellationTokenSource? _refreshCts; + private bool _disposed; + protected override async Task OnInitializedAsync() { try @@ -156,11 +241,53 @@ else catch (Exception ex) { Snackbar.Add($"Erreur : {ex.Message}", Severity.Error); } finally { _loading = false; } + await LoadEventsAsync(); + await LoadLatestSnapshotAsync(); + await StartAutoRefresh(); + } + + private async Task LoadEventsAsync() + { try { _eventsLoading = true; _events = await Api.GetRecentEventsAsync(Id, 10); } catch { } finally { _eventsLoading = false; } } + private async Task LoadLatestSnapshotAsync() + { + _snapshotLoading = true; + try + { + var events = await Api.GetRecentEventsAsync(Id, 1); + _latestSnapshotUrl = events? + .FirstOrDefault(e => !string.IsNullOrEmpty(e.SnapshotThumbUrl ?? e.SnapshotUrl)) is { } latest + ? (latest.SnapshotThumbUrl ?? latest.SnapshotUrl) + : null; + } + catch { /* flux indisponible */ } + finally + { + _snapshotLoading = false; + if (!_disposed) await InvokeAsync(StateHasChanged); + } + } + + private async Task StartAutoRefresh() + { + _refreshCts = new CancellationTokenSource(); + try + { + while (!_refreshCts.Token.IsCancellationRequested) + { + await Task.Delay(TimeSpan.FromSeconds(10), _refreshCts.Token); + if (!_disposed) await LoadLatestSnapshotAsync(); + } + } + catch (OperationCanceledException) { /* arrêt volontaire */ } + } + + private async Task RefreshSnapshot() => await LoadLatestSnapshotAsync(); + private async Task SaveCamera() { if (string.IsNullOrWhiteSpace(_editName)) { _editError = "Le nom est requis"; return; } @@ -180,6 +307,36 @@ else finally { _saving = false; } } + private async Task ToggleCameraStatus() + { + if (_camera is null) return; + var newStatus = _camera.Status == "Disabled" ? "Online" : "Disabled"; + _saving = true; + _editError = ""; + try + { + if (await Api.UpdateCameraAsync(Id, _camera.Name, _camera.RtspUrl, newStatus)) + { + _camera.Status = newStatus; + Snackbar.Add(newStatus == "Online" ? "Caméra activée" : "Caméra désactivée", Severity.Success); + } + else _editError = "Erreur lors de la mise à jour du statut"; + } + catch (Exception ex) { _editError = $"Erreur : {ex.Message}"; } + finally { _saving = false; } + } + + private async Task DeleteCamera() + { + if (_camera is null) return; + if (await Api.DeleteCameraAsync(Id)) + { + Snackbar.Add($"Caméra \"{_camera.Name}\" supprimée", Severity.Success); + Nav.NavigateTo($"/sites/{_camera.SiteId}/cameras"); + } + else Snackbar.Add("Erreur lors de la suppression", Severity.Error); + } + private static Color GetStatusColor(string status) => status switch { "Online" => Color.Success, @@ -194,4 +351,38 @@ else "Offline" => "○", _ => "?" }; + + private static string FormatStatus(string status) => status switch + { + "Online" => "En ligne", + "Offline" => "Hors ligne", + "Disabled" => "Désactivée", + _ => status + }; + + private static string FormatEventType(string type) => type switch + { + "MotionDetected" => "Mouvement", + "PersonDetected" => "Personne", + "VehicleDetected" => "Véhicule", + "FaceRecognized" => "Visage", + "CameraOffline" => "Hors ligne", + _ => type + }; + + private static Color GetEventColor(string type) => type switch + { + "MotionDetected" => Color.Warning, + "PersonDetected" => Color.Error, + "VehicleDetected" => Color.Info, + "FaceRecognized" => Color.Success, + _ => Color.Default + }; + + public void Dispose() + { + _disposed = true; + _refreshCts?.Cancel(); + _refreshCts?.Dispose(); + } } diff --git a/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs new file mode 100644 index 0000000..4bbbf65 --- /dev/null +++ b/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs @@ -0,0 +1,136 @@ +using Bunit; +using Bunit.TestDoubles; +using Heimdall.Web.Components.Pages; +using Heimdall.Web.Services; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; + +namespace Heimdall.Web.Tests.Components.Pages; + +public class CameraDetailTests : PageTestBase +{ + private static readonly Guid CameraId = Guid.NewGuid(); + private static readonly Guid SiteId = Guid.NewGuid(); + + private static CameraItem Camera(string status = "Online") => new() + { + Id = CameraId, + SiteId = SiteId, + Name = "Caméra Entrée", + Manufacturer = "Hikvision", + Model = "DS-2CD", + RtspUrl = "rtsp://192.168.1.50:554/stream1", + Status = status, + CreatedAt = DateTime.UtcNow.AddDays(-2) + }; + + private void HandlerCamera(CameraItem camera) + => Handler.OnGet("api/cameras/", camera); + + [Fact] + public void CameraDetail_AfficheInformationsEtStatut() + { + HandlerCamera(Camera()); + Handler.OnGet("api/events/camera/", new List()); + LoginAs(); + + var cut = RenderPage(p => p.Add(x => x.Id, CameraId)); + + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("Caméra : Caméra Entrée"); + cut.Markup.ShouldContain("Hikvision"); + cut.Markup.ShouldContain("DS-2CD"); + cut.Markup.ShouldContain("En ligne"); + }); + } + + [Fact] + public void CameraDetail_RtspMasqueParDefaut_ToggleRevele() + { + HandlerCamera(Camera()); + Handler.OnGet("api/events/camera/", new List()); + LoginAs(); + + var cut = RenderPage(p => p.Add(x => x.Id, CameraId)); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Caméra : Caméra Entrée")); + + // Par défaut le champ RTSP est de type password (masqué) + var rtspInput = cut.FindAll("input").First(i => i.GetAttribute("value")!.Contains("rtsp://")); + rtspInput.GetAttribute("type").ShouldBe("password"); + + // Cliquer sur l'adornment (icon-button du champ) révèle le mot de passe. + // MudBlazor : wrapper .mud-input-adornment-end contenant un button.mud-icon-button. + var adornment = cut.Find(".mud-input-adornment-end button.mud-icon-button"); + adornment.Click(); + + cut.WaitForAssertion(() => + { + var visible = cut.FindAll("input").First(i => (i.GetAttribute("value") ?? "").Contains("rtsp://")); + visible.GetAttribute("type").ShouldBe("text"); + }); + } + + [Fact] + public void CameraDetail_VueLive_AfficheDernierSnapshot() + { + HandlerCamera(Camera()); + Handler.OnGet("api/events/camera/", new List + { + new(Guid.NewGuid(), CameraId, "PersonDetected", 0.9, "Personne", + "http://alarik/snapshots/live.jpg", "http://alarik/thumbs/live.jpg", + DateTime.UtcNow.AddMinutes(-1), DateTime.UtcNow) + }); + LoginAs(); + + var cut = RenderPage(p => p.Add(x => x.Id, CameraId)); + + cut.WaitForAssertion(() => + { + cut.Markup.ShouldContain("http://alarik/thumbs/live.jpg"); + cut.Markup.ShouldContain("Vue live de Caméra Entrée"); + }); + } + + [Fact] + public void CameraDetail_ToggleStatut_ActiveEtDesactive() + { + HandlerCamera(Camera("Disabled")); + Handler.OnGet("api/events/camera/", new List()); + Handler.On(HttpMethod.Put, "api/cameras/", System.Net.HttpStatusCode.OK); + LoginAs(); + + var cut = RenderPage(p => p.Add(x => x.Id, CameraId)); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Désactivée")); + + cut.FindAll("button").Single(b => b.TextContent.Contains("Activer")).Click(); + + cut.WaitForAssertion(() => + { + var snackbar = Services.GetRequiredService(); + snackbar.ShownSnackbars.Select(m => m.Message?.ToString() ?? "") + .ShouldContain(m => m.Contains("Caméra activée", StringComparison.OrdinalIgnoreCase)); + }); + } + + [Fact] + public void CameraDetail_Supprimer_ConfirmeEtNavigue() + { + HandlerCamera(Camera()); + Handler.OnGet("api/events/camera/", new List()); + Handler.On(HttpMethod.Delete, "api/cameras/", System.Net.HttpStatusCode.OK); + LoginAs(); + + var nav = Services.GetRequiredService(); + var cut = RenderPage(p => p.Add(x => x.Id, CameraId)); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Caméra : Caméra Entrée")); + + // Bouton "Supprimer la caméra" de la barre d'actions. + cut.Find("button[aria-label=\"Supprimer la caméra\"]").Click(); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Confirmer la suppression")); + // Dans le dialog, le bouton de confirmation est le seul "Supprimer" du dialog. + cut.FindAll(".mud-dialog button").Single(b => b.TextContent.Trim() == "Supprimer").Click(); + + cut.WaitForAssertion(() => nav.Uri.ShouldBe("http://localhost/sites/" + SiteId + "/cameras")); + } +}