## Résumé
Ajoute un bouton toggle (play/stop) dans chaque tuile de la liste des caméras pour activer/désactiver une caméra directement depuis la vue liste, sans passer par la page détail.
## Changements
### API
- **`POST /api/cameras/{id}/toggle-status`** — endpoint dédié qui bascule entre `Online` et `Disabled`
- `ToggleCameraStatusCommand` + handler (Application layer)
- `ToggleCameraStatusAsync` dans `HeimdallApiClient`
### UI
- **`CameraTile.razor`** — bouton toggle ajouté (play/stop) entre View et Snapshot
- **`CamerasPage.razor`** — callback `OnToggleStatus` câblé + snackbar feedback
- **`CameraDetail.razor`** — migré vers le nouvel endpoint dédié (au lieu de `UpdateCameraAsync` avec status)
### Tests
- 4 unit tests (`ToggleCameraStatusCommandTests`)
- 2 integration tests (toggle + 404)
- Fix bUnit `CameraDetailTests` (mock PUT → POST)
## Closes
- Issue #59
Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/151
337 lines
12 KiB
Plaintext
337 lines
12 KiB
Plaintext
@page "/sites/{SiteId:guid}/cameras"
|
|
@attribute [Authorize]
|
|
@layout MainLayout
|
|
@inject HeimdallApiClient Api
|
|
@inject ISnackbar Snackbar
|
|
@inject NavigationManager Nav
|
|
|
|
<MudText Typo="Typo.h1" Class="mb-2">
|
|
<i class="fas fa-video mr-2"></i>
|
|
Caméras du site
|
|
</MudText>
|
|
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-4">
|
|
@if (_cameras is not null)
|
|
{
|
|
@($"{_cameras.Count} caméra(s)") <span class="mx-1">·</span>
|
|
@($"{_cameras.Count(c => c.Status == "Online")} en ligne")
|
|
}
|
|
</MudText>
|
|
|
|
<div class="d-flex align-center mb-4">
|
|
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@(() => _showCreate = true)">
|
|
<MudIcon Icon="@Icons.Material.Filled.Add" Class="mr-1" /> Ajouter une caméra
|
|
</MudButton>
|
|
<MudButton Variant="Variant.Outlined" Color="Color.Default" OnClick="@(() => Nav.NavigateTo("/sites"))" Class="ml-2">
|
|
← Retour aux sites
|
|
</MudButton>
|
|
<MudSpacer />
|
|
<MudTooltip Text="Actualiser les caméras">
|
|
<MudIconButton Icon="@Icons.Material.Filled.Refresh" Color="Color.Inherit" aria-label="Actualiser les caméras"
|
|
OnClick="@(() => LoadCameras(silent: false))" />
|
|
</MudTooltip>
|
|
</div>
|
|
|
|
@* ─── 4 états : loading / error / empty / data ─── *@
|
|
@if (_loading)
|
|
{
|
|
<MudGrid>
|
|
@for (var i = 0; i < 6; i++)
|
|
{
|
|
<MudItem xs="12" sm="6" md="4" xl="3">
|
|
<MudPaper Elevation="0" Style="border-radius: var(--hmd-radius-lg);">
|
|
<MudSkeleton Variant="SkeletonVariant.Rectangular" Height="140px" />
|
|
<div class="pa-3">
|
|
<MudSkeleton Width="60%" />
|
|
<MudSkeleton Width="40%" Height="16px" />
|
|
</div>
|
|
</MudPaper>
|
|
</MudItem>
|
|
}
|
|
</MudGrid>
|
|
}
|
|
else if (_error)
|
|
{
|
|
<MudAlert Severity="Severity.Error" Variant="Variant.Filled" Class="mt-4">
|
|
<MudText>Impossible de charger les caméras. Vérifiez votre connexion puis réessayez.</MudText>
|
|
<MudButton Variant="Variant.Text" Color="Color.Inherit" OnClick="@(() => LoadCameras(silent: false))" Class="mt-2">
|
|
<MudIcon Icon="@Icons.Material.Filled.Refresh" Class="mr-1" Size="Size.Small" /> Réessayer
|
|
</MudButton>
|
|
</MudAlert>
|
|
}
|
|
else if (_cameras is null || _cameras.Count == 0)
|
|
{
|
|
<MudPaper Elevation="0" Class="pa-8 text-center" Style="border-radius: var(--hmd-radius-lg); border: 1px dashed var(--mud-palette-lines-default);">
|
|
<MudIcon Icon="@Icons.Material.Filled.Videocam" Size="Size.Large" Color="Color.Secondary" />
|
|
<MudText Typo="Typo.h6" Color="Color.Secondary" Class="mt-4">Aucune caméra configurée</MudText>
|
|
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-4">
|
|
Ajoutez une caméra pour commencer la surveillance de ce site.
|
|
</MudText>
|
|
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@(() => _showCreate = true)">
|
|
<MudIcon Icon="@Icons.Material.Filled.Add" Class="mr-1" /> Ajouter une caméra
|
|
</MudButton>
|
|
</MudPaper>
|
|
}
|
|
else
|
|
{
|
|
<MudContainer MaxWidth="MaxWidth.False" Class="px-0">
|
|
<MudGrid>
|
|
@foreach (var camera in _cameras)
|
|
{
|
|
<MudItem xs="12" sm="6" md="4" xl="3">
|
|
<CameraTile Camera="@camera"
|
|
SnapshotUrl="@GetSnapshot(camera.Id)"
|
|
LoadingSnapshot="@IsSnapshotLoading(camera.Id)"
|
|
OnSnapshot="@(() => TakeSnapshot(camera))"
|
|
OnDelete="@(() => ConfirmDeleteCamera(camera.Id, camera.Name))"
|
|
OnToggleStatus="@(() => ToggleCamera(camera))" />
|
|
</MudItem>
|
|
}
|
|
</MudGrid>
|
|
</MudContainer>
|
|
}
|
|
|
|
@* ─── Confirm delete dialog ───────────────────────────────── *@
|
|
<MudOverlay Visible="@_confirmDeleteShow" OnClick="@(() => _confirmDeleteShow = false)" />
|
|
<MudDialog @bind-Visible="_confirmDeleteShow">
|
|
<TitleContent><MudText Typo="Typo.h6">Confirmer la suppression</MudText></TitleContent>
|
|
<DialogContent>
|
|
<MudText>Supprimer la caméra "@_confirmDeleteName" ? Cette action est irréversible.</MudText>
|
|
</DialogContent>
|
|
<DialogActions>
|
|
<MudButton Variant="Variant.Text" OnClick="@(() => _confirmDeleteShow = false)">Annuler</MudButton>
|
|
<MudButton Variant="Variant.Filled" Color="Color.Error" OnClick="@ExecuteDeleteCamera">Supprimer</MudButton>
|
|
</DialogActions>
|
|
</MudDialog>
|
|
|
|
<MudOverlay Visible="@_showCreate" OnClick="@(() => _showCreate = false)" />
|
|
<MudDialog @bind-Visible="_showCreate">
|
|
<TitleContent><MudText Typo="Typo.h6">Ajouter une caméra</MudText></TitleContent>
|
|
<DialogContent>
|
|
<MudTextField @bind-Value="_newName" Label="Nom *" Variant="Variant.Outlined"
|
|
Class="mb-4" Required="true" Immediate="true" />
|
|
<MudTextField @bind-Value="_newManufacturer" Label="Fabricant" Variant="Variant.Outlined" Class="mb-4" />
|
|
<MudTextField @bind-Value="_newModel" Label="Modèle" Variant="Variant.Outlined" Class="mb-4" />
|
|
<MudTextField @bind-Value="_newRtspUrl" Label="URL RTSP" Variant="Variant.Outlined" Class="mb-4"
|
|
HelperText="Ex: rtsp://192.168.1.100:554/stream1" />
|
|
@if (!string.IsNullOrEmpty(_dialogError))
|
|
{
|
|
<MudAlert Severity="Severity.Error" Class="mb-4">@_dialogError</MudAlert>
|
|
}
|
|
</DialogContent>
|
|
<DialogActions>
|
|
<MudButton Variant="Variant.Text" OnClick="@(() => _showCreate = false)">Annuler</MudButton>
|
|
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@CreateCamera" Disabled="@_saving">
|
|
@if (_saving) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
|
|
Ajouter
|
|
</MudButton>
|
|
</DialogActions>
|
|
</MudDialog>
|
|
|
|
@code {
|
|
[Parameter] public Guid SiteId { get; set; }
|
|
|
|
private IReadOnlyList<CameraItem>? _cameras;
|
|
private bool _loading = true;
|
|
private bool _error;
|
|
private bool _showCreate;
|
|
private bool _saving;
|
|
private string _dialogError = "";
|
|
|
|
private readonly Dictionary<Guid, string?> _snapshots = [];
|
|
private readonly Dictionary<Guid, bool> _snapshotLoading = [];
|
|
private CancellationTokenSource? _refreshCts;
|
|
private bool _disposed;
|
|
|
|
private string _newName = "";
|
|
private string? _newManufacturer;
|
|
private string? _newModel;
|
|
private string? _newRtspUrl;
|
|
|
|
protected override async Task OnInitializedAsync()
|
|
{
|
|
await LoadCameras();
|
|
}
|
|
|
|
// L'auto-refresh démarre après le premier rendu : une boucle infinie
|
|
// awaitée dans OnInitializedAsync bloque le rendu initial (SSR/prerender
|
|
// attend la fin du cycle de vie) → page lente.
|
|
private bool _autoRefreshStarted;
|
|
|
|
protected override async Task OnAfterRenderAsync(bool firstRender)
|
|
{
|
|
if (firstRender && !_autoRefreshStarted)
|
|
{
|
|
_autoRefreshStarted = true;
|
|
await StartAutoRefresh();
|
|
}
|
|
}
|
|
|
|
private async Task StartAutoRefresh()
|
|
{
|
|
_refreshCts = new CancellationTokenSource();
|
|
try
|
|
{
|
|
while (!_refreshCts.Token.IsCancellationRequested)
|
|
{
|
|
await Task.Delay(TimeSpan.FromSeconds(30), _refreshCts.Token);
|
|
if (!_disposed) await LoadCameras(silent: true);
|
|
}
|
|
}
|
|
catch (OperationCanceledException) { /* arrêt volontaire */ }
|
|
}
|
|
|
|
private async Task RefreshAsync() => await LoadCameras(silent: false);
|
|
|
|
private async Task LoadCameras(bool silent = false)
|
|
{
|
|
if (!silent) { _loading = true; _error = false; }
|
|
try
|
|
{
|
|
var result = await Api.GetCamerasBySiteAsync(SiteId, pageSize: 100);
|
|
_cameras = result?.Items;
|
|
if (_cameras is not null)
|
|
{
|
|
foreach (var camera in _cameras)
|
|
{
|
|
if (_snapshots.ContainsKey(camera.Id)) continue;
|
|
_snapshots[camera.Id] = null;
|
|
_ = LoadSnapshotAsync(camera.Id);
|
|
}
|
|
}
|
|
}
|
|
catch {
|
|
_error = true;
|
|
if (!silent) Snackbar.Add(UiErrors.OperationFailed(), Severity.Error);
|
|
}
|
|
finally
|
|
{
|
|
if (!silent) _loading = false;
|
|
if (!_disposed) await InvokeAsync(StateHasChanged);
|
|
}
|
|
}
|
|
|
|
private async Task LoadSnapshotAsync(Guid cameraId)
|
|
{
|
|
_snapshotLoading[cameraId] = true;
|
|
try
|
|
{
|
|
var events = await Api.GetRecentEventsAsync(cameraId, 1);
|
|
var latest = events?.FirstOrDefault(e => !string.IsNullOrEmpty(e.SnapshotThumbUrl ?? e.SnapshotUrl));
|
|
_snapshots[cameraId] = latest is null
|
|
? null
|
|
: (latest.SnapshotThumbUrl ?? latest.SnapshotUrl);
|
|
}
|
|
catch { /* vignette indisponible → placeholder */ }
|
|
finally
|
|
{
|
|
_snapshotLoading[cameraId] = false;
|
|
if (!_disposed) await InvokeAsync(StateHasChanged);
|
|
}
|
|
}
|
|
|
|
private string? GetSnapshot(Guid id) => _snapshots.TryGetValue(id, out var url) ? url : null;
|
|
|
|
private bool IsSnapshotLoading(Guid id) => _snapshotLoading.TryGetValue(id, out var loading) && loading;
|
|
|
|
private async Task TakeSnapshot(CameraItem camera)
|
|
{
|
|
try
|
|
{
|
|
Snackbar.Add($"Snapshot demandé pour {camera.Name}", Severity.Info);
|
|
await Task.CompletedTask; // endpoint snapshot agent géré côté agent/heartbeat
|
|
}
|
|
catch {
|
|
Snackbar.Add(UiErrors.OperationFailed(), Severity.Error);
|
|
}
|
|
}
|
|
|
|
private async Task ToggleCamera(CameraItem camera)
|
|
{
|
|
try
|
|
{
|
|
var result = await Api.ToggleCameraStatusAsync(camera.Id);
|
|
if (result.Succeeded && result.Data is not null)
|
|
{
|
|
camera.Status = result.Data.Status;
|
|
Snackbar.Add(
|
|
result.Data.Status == "Online" ? $"Caméra \"{camera.Name}\" activée" : $"Caméra \"{camera.Name}\" désactivée",
|
|
Severity.Success);
|
|
}
|
|
else
|
|
{
|
|
Snackbar.Add(result.ErrorMessage ?? UiErrors.OperationFailed(), Severity.Error);
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
Snackbar.Add(UiErrors.OperationFailed(), Severity.Error);
|
|
}
|
|
}
|
|
|
|
private bool _confirmDeleteShow;
|
|
private Guid _confirmDeleteId;
|
|
private string _confirmDeleteName = "";
|
|
|
|
private void ConfirmDeleteCamera(Guid id, string name)
|
|
{
|
|
_confirmDeleteId = id;
|
|
_confirmDeleteName = name;
|
|
_confirmDeleteShow = true;
|
|
}
|
|
|
|
private async Task ExecuteDeleteCamera()
|
|
{
|
|
_confirmDeleteShow = false;
|
|
await DeleteCamera(_confirmDeleteId, _confirmDeleteName);
|
|
}
|
|
|
|
private async Task CreateCamera()
|
|
{
|
|
if (string.IsNullOrWhiteSpace(_newName)) { _dialogError = "Le nom est requis"; return; }
|
|
_saving = true;
|
|
_dialogError = "";
|
|
try
|
|
{
|
|
var result = await Api.CreateCameraAsync(SiteId, _newName, _newRtspUrl, _newManufacturer, _newModel);
|
|
if (!result.Succeeded)
|
|
{
|
|
_dialogError = string.IsNullOrWhiteSpace(result.ErrorMessage)
|
|
? UiErrors.OperationFailed("la création de la caméra")
|
|
: result.ErrorMessage;
|
|
return;
|
|
}
|
|
_showCreate = false;
|
|
ResetForm();
|
|
Snackbar.Add("Caméra ajoutée", Severity.Success);
|
|
await LoadCameras();
|
|
}
|
|
catch { _dialogError = UiErrors.OperationFailed(); }
|
|
finally { _saving = false; }
|
|
}
|
|
|
|
private async Task DeleteCamera(Guid id, string name)
|
|
{
|
|
if (await Api.DeleteCameraAsync(id))
|
|
{
|
|
Snackbar.Add($"Caméra \"{name}\" supprimée", Severity.Success);
|
|
await LoadCameras();
|
|
}
|
|
else Snackbar.Add("Erreur", Severity.Error);
|
|
}
|
|
|
|
private void ResetForm()
|
|
{
|
|
_newName = "";
|
|
_newManufacturer = null;
|
|
_newModel = null;
|
|
_newRtspUrl = null;
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
_disposed = true;
|
|
_refreshCts?.Cancel();
|
|
_refreshCts?.Dispose();
|
|
}
|
|
}
|