Files
Heimdall/src/Heimdall.Web/Components/Pages/CameraDetail.razor
T

459 lines
19 KiB
Plaintext
Raw Normal View History

2026-07-17 19:08:17 +00:00
@page "/cameras/{Id:guid}"
@attribute [Authorize]
@layout MainLayout
@inject HeimdallApiClient Api
@inject ISnackbar Snackbar
@inject NavigationManager Nav
@inject UiText Text
@inject UiLanguageService Language
@implements IDisposable
2026-07-17 19:08:17 +00:00
<MudText Typo="Typo.h1" Class="mb-2">
<i class="fas fa-camera mr-2"></i>
@Text["CameraDetail_TitlePrefix"] @_camera?.Name
2026-07-17 19:08:17 +00:00
</MudText>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-4">
@if (_camera is not null)
{
<MudBadge Color="@GetStatusColor(_camera.Status)" Variant="Variant.Filled">
@GetStatusIcon(_camera.Status) @FormatStatus(_camera.Status)
</MudBadge>
<span class="ml-2">@Text["CameraDetail_CreatedAt"] @_camera.CreatedAt.ToString("g", Language.Culture)</span>
}
</MudText>
2026-07-17 19:08:17 +00:00
@if (_loading)
{
<MudPaper Elevation="0" Style="border-radius: var(--hmd-radius-lg);">
<MudSkeleton Variant="SkeletonVariant.Rectangular" Height="360px" />
</MudPaper>
2026-07-17 19:08:17 +00:00
}
else if (_camera is null)
{
<MudAlert Severity="Severity.Warning">@Text["CameraDetail_NotFound"]</MudAlert>
2026-07-17 19:08:17 +00:00
}
else
{
@* ─── Dernière image événementielle, rafraîchie périodiquement ─── *@
<MudPaper Elevation="2" Class="pa-0 mb-6" Style="border-radius: var(--hmd-radius-lg); overflow: hidden;">
<div style="position: relative; aspect-ratio: 16/9; background: var(--mud-palette-dark);">
@if (_snapshotLoading)
{
<MudSkeleton Variant="SkeletonVariant.Rectangular" Height="100%" />
}
else if (!string.IsNullOrEmpty(_latestSnapshotUrl))
{
<img src="@_latestSnapshotUrl" alt="@string.Format(Language.Culture, Text["CameraDetail_LatestImageAlt"], _camera.Name)"
style="width:100%; height:100%; object-fit:contain;" />
@if (_latestSnapshotAt is DateTime capturedAt)
{
<span style="position:absolute; top:12px; left:12px; padding:4px 8px; border-radius:4px; background:rgba(0,0,0,0.65); color:white;">
@Text["CameraDetail_LatestImage"] @capturedAt.ToLocalTime().ToString("g", Language.Culture)
</span>
}
}
else
{
<div class="d-flex align-center justify-center flex-column" style="height:100%; min-height:240px;">
<MudIcon Icon="@Icons.Material.Filled.Videocam" Size="Size.Large" Color="Color.Secondary" />
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mt-2">
@Text["CameraDetail_NoStream"]
</MudText>
</div>
}
@* Overlay actions live *@
<div style="position:absolute; bottom:12px; right:12px;" class="d-flex gap-2">
<MudTooltip Text="@Text["CameraDetail_TakeSnapshot"]">
<MudIconButton Icon="@Icons.Material.Filled.PhotoCamera" Color="Color.Inherit" Style="background: rgba(0,0,0,0.45);"
aria-label="@Text["CameraDetail_TakeSnapshot"]" Disabled="@(_camera.Status != "Online" || _snapshotLoading)"
OnClick="@TakeSnapshot" />
</MudTooltip>
<MudTooltip Text="@Text["CameraDetail_RefreshStream"]">
<MudIconButton Icon="@Icons.Material.Filled.Refresh" Color="Color.Inherit" Style="background: rgba(0,0,0,0.45);"
aria-label="@Text["CameraDetail_RefreshStream"]" OnClick="@RefreshSnapshot" />
</MudTooltip>
</div>
</div>
</MudPaper>
@* ─── Informations & actions ─── *@
<MudPaper Elevation="1" Class="pa-5 mb-6" Style="border-radius: var(--hmd-radius-md);">
<MudText Typo="Typo.h6" Class="mb-4">@Text["CameraDetail_Information"]</MudText>
2026-07-17 19:08:17 +00:00
<MudGrid>
<MudItem xs="12" sm="6">
<MudTextField @bind-Value="_editName" Label="@Text["CameraDetail_Name"]" Variant="Variant.Outlined" Class="mb-4" Immediate="true" />
2026-07-17 19:08:17 +00:00
</MudItem>
<MudItem xs="12" sm="6">
<MudTextField @bind-Value="_editRtspUrl" Label="@Text["CameraDetail_RtspUrl"]" Variant="Variant.Outlined" Class="mb-4" Immediate="true"
InputType="@(_showRtsp ? InputType.Text : InputType.Password)"
Adornment="Adornment.End"
AdornmentIcon="@(_showRtsp ? Icons.Material.Filled.VisibilityOff : Icons.Material.Filled.Visibility)"
OnAdornmentClick="@(() => _showRtsp = !_showRtsp)" />
2026-07-17 19:08:17 +00:00
</MudItem>
<MudItem xs="12" sm="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["CameraDetail_Manufacturer"]</MudText>
2026-07-17 19:08:17 +00:00
<MudText Typo="Typo.body1">@(_camera.Manufacturer ?? "-")</MudText>
</MudItem>
<MudItem xs="12" sm="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["CameraDetail_Model"]</MudText>
2026-07-17 19:08:17 +00:00
<MudText Typo="Typo.body1">@(_camera.Model ?? "-")</MudText>
</MudItem>
</MudGrid>
@if (!string.IsNullOrEmpty(_editError))
{
<MudAlert Severity="Severity.Error" Class="mb-4">@_editError</MudAlert>
}
@if (!string.IsNullOrEmpty(_editSuccess))
{
<MudAlert Severity="Severity.Success" Class="mb-4">@_editSuccess</MudAlert>
}
<div class="d-flex flex-wrap gap-2 mt-2">
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@SaveCamera" Disabled="@_saving">
@if (_saving) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
<MudIcon Icon="@Icons.Material.Filled.Save" Class="mr-1" /> @Text["CameraDetail_Save"]
</MudButton>
<MudButton Variant="Variant.Outlined" Color="@(_camera.Status == "Disabled" ? Color.Success : Color.Default)"
OnClick="@ToggleCameraStatus" Disabled="@(_saving || _togglingStatus)">
@if (_togglingStatus) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
<MudIcon Icon="@(_camera.Status == "Disabled" ? Icons.Material.Filled.PlayArrow : Icons.Material.Filled.Stop)"
Class="mr-1" />
@(_camera.Status == "Disabled" ? Text["CameraDetail_Enable"] : Text["CameraDetail_Disable"])
</MudButton>
<MudButton Variant="Variant.Outlined" Color="Color.Error" OnClick="@(() => _confirmDeleteShow = true)" aria-label="@Text["CameraDetail_DeleteCamera"]">
<MudIcon Icon="@Icons.Material.Filled.Delete" Class="mr-1" /> @Text["CameraDetail_Delete"]
</MudButton>
<MudSpacer />
<MudButton Variant="Variant.Text" Color="Color.Default" OnClick="@(() => Nav.NavigateTo($"/sites/{_camera.SiteId}/cameras"))">
← Retour aux caméras
</MudButton>
</div>
2026-07-17 19:08:17 +00:00
</MudPaper>
@* ─── Mini-timeline : événements récents ─── *@
<MudText Typo="Typo.h6" Class="mb-4">
<MudIcon Icon="@Icons.Material.Filled.Notifications" Class="mr-1" /> @Text["CameraDetail_RecentEvents"]
</MudText>
@if (_eventsLoading)
{
<MudPaper Elevation="0" Style="border-radius: var(--hmd-radius-md);">
<MudSkeleton Variant="SkeletonVariant.Rectangular" Height="120px" />
</MudPaper>
}
else if (_events is { Count: > 0 })
{
<MudTable Items="@_events" Hover="true" Elevation="1" Dense="true">
<HeaderContent>
<MudTh>@Text["CameraDetail_Timestamp"]</MudTh>
<MudTh>@Text["CameraDetail_Type"]</MudTh>
<MudTh>@Text["CameraDetail_Confidence"]</MudTh>
<MudTh>@Text["CameraDetail_Label"]</MudTh>
<MudTh></MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="@Text["CameraDetail_Timestamp"]">@context.OccurredAt.ToLocalTime().ToString("g", Language.Culture)</MudTd>
<MudTd DataLabel="@Text["CameraDetail_Type"]">
<MudChip T="string" Size="Size.Small" Color="@GetEventColor(context.Type)" Variant="Variant.Outlined">
@FormatEventType(context.Type)
</MudChip>
</MudTd>
<MudTd DataLabel="@Text["CameraDetail_Confidence"]">@((context.Confidence * 100).ToString("0", Language.Culture) + "%")</MudTd>
<MudTd DataLabel="@Text["CameraDetail_Label"]">@context.Label</MudTd>
<MudTd DataLabel="">
<MudIconButton Icon="@Icons.Material.Filled.Image" Size="Size.Small" aria-label="@Text["CameraDetail_ViewSnapshot"]"
Disabled="@(context.SnapshotUrl is null)"
OnClick="@(() => { _showSnapshotUrl = context.SnapshotUrl; _showSnapshotDialog = true; })" />
</MudTd>
</RowTemplate>
</MudTable>
<MudLink Href="@($"/events?q={Uri.EscapeDataString(_camera.Name)}")" Class="mt-2 d-block">
Voir tous les événements →
</MudLink>
}
else
{
<MudText Class="mt-2" Typo="Typo.body2" Color="Color.Default">@Text["CameraDetail_NoRecentEvents"]</MudText>
}
@* ─── Dialogs (toujours rendus, visibilité via @bind-Visible) ─── *@
<MudOverlay Visible="@_confirmDeleteShow" OnClick="@(() => _confirmDeleteShow = false)" />
<MudDialog @bind-Visible="_confirmDeleteShow">
<TitleContent><MudText Typo="Typo.h6">@Text["CameraDetail_ConfirmDeleteTitle"]</MudText></TitleContent>
<DialogContent>
<MudText>@string.Format(Language.Culture, Text["CameraDetail_ConfirmDeleteBody"], _camera.Name)</MudText>
</DialogContent>
<DialogActions>
<MudButton Variant="Variant.Text" OnClick="@(() => _confirmDeleteShow = false)">@Text["CameraDetail_Cancel"]</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Error" OnClick="@DeleteCamera">@Text["CameraDetail_Delete"]</MudButton>
</DialogActions>
</MudDialog>
<MudDialog @bind-Visible="_showSnapshotDialog" Options="_snapshotOptions">
<DialogContent>
@if (_showSnapshotUrl is not null)
{
<img src="@_showSnapshotUrl" alt="@Text["CameraDetail_SnapshotAlt"]" style="width:100%;height:auto;" class="rounded-lg" />
}
</DialogContent>
<DialogActions>
<MudButton OnClick="@(() => _showSnapshotDialog = false)">@Text["CameraDetail_Close"]</MudButton>
</DialogActions>
</MudDialog>
2026-07-17 19:08:17 +00:00
}
@code {
[Parameter] public Guid Id { get; set; }
private CameraItem? _camera;
private string _editName = "";
private string? _editRtspUrl;
private string _editError = "";
private string _editSuccess = "";
private bool _loading = true;
private bool _saving;
private bool _togglingStatus;
private bool _showRtsp;
private bool _confirmDeleteShow;
private List<EventItem>? _events;
private bool _eventsLoading;
private string? _showSnapshotUrl;
private bool _showSnapshotDialog;
private readonly DialogOptions _snapshotOptions = new()
{
FullWidth = true,
MaxWidth = MaxWidth.Large,
CloseButton = true
};
2026-07-17 19:08:17 +00:00
private string? _latestSnapshotUrl;
private DateTime? _latestSnapshotAt;
private bool _snapshotLoading;
private CancellationTokenSource? _refreshCts;
private bool _disposed;
2026-07-17 19:08:17 +00:00
protected override async Task OnInitializedAsync()
{
Language.LanguageChanged += OnLanguageChanged;
2026-07-17 19:08:17 +00:00
try
{
_camera = await Api.GetCameraAsync(Id);
if (_camera is not null)
{
_editName = _camera.Name;
_editRtspUrl = _camera.RtspUrl;
}
}
catch { Snackbar.Add(Text["CameraDetail_OperationFailed"], Severity.Error); }
2026-07-17 19:08:17 +00:00
finally { _loading = false; }
await LoadEventsAsync();
await LoadLatestSnapshotAsync();
}
private void OnLanguageChanged() => _ = InvokeAsync(StateHasChanged);
// 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 LoadEventsAsync()
{
try { _eventsLoading = true; _events = await Api.GetRecentEventsAsync(Id, 10); }
catch { }
finally { _eventsLoading = false; }
2026-07-17 19:08:17 +00:00
}
private async Task LoadLatestSnapshotAsync()
{
_snapshotLoading = true;
try
{
var events = await Api.GetRecentEventsAsync(Id, 20);
var latest = events?.FirstOrDefault(e => !string.IsNullOrEmpty(e.SnapshotThumbUrl ?? e.SnapshotUrl));
_latestSnapshotUrl = latest?.SnapshotThumbUrl ?? latest?.SnapshotUrl;
_latestSnapshotAt = latest?.OccurredAt;
}
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 TakeSnapshot()
{
_snapshotLoading = true;
try
{
var request = await Api.RequestCameraSnapshotAsync(Id);
if (!request.Succeeded || request.Data == Guid.Empty)
{
Snackbar.Add(request.ErrorMessage ?? Text["CameraDetail_OperationFailed"], Severity.Error);
return;
}
Snackbar.Add(Text["CameraDetail_CaptureRequested"], Severity.Info);
for (var attempt = 0; attempt < 35 && !_disposed; attempt++)
{
await Task.Delay(TimeSpan.FromSeconds(1));
var status = await Api.GetCameraSnapshotStatusAsync(Id, request.Data);
if (status?.Status is "Failed" or "TimedOut")
{
Snackbar.Add(status.Reason ?? Text["CameraDetail_CaptureFailed"], Severity.Error);
return;
}
if (status?.Status != "Completed") continue;
var snapshot = await Api.GetEventAsync(request.Data);
if (snapshot is null || string.IsNullOrEmpty(snapshot.SnapshotUrl)) continue;
_latestSnapshotUrl = snapshot.SnapshotThumbUrl ?? snapshot.SnapshotUrl;
_latestSnapshotAt = snapshot.OccurredAt;
await LoadEventsAsync();
Snackbar.Add(Text["CameraDetail_SnapshotAvailable"], Severity.Success);
return;
}
Snackbar.Add(Text["CameraDetail_CapturePending"], Severity.Info);
}
catch { Snackbar.Add(Text["CameraDetail_OperationFailed"], Severity.Error); }
finally
{
_snapshotLoading = false;
if (!_disposed) await InvokeAsync(StateHasChanged);
}
}
2026-07-17 19:08:17 +00:00
private async Task SaveCamera()
{
if (string.IsNullOrWhiteSpace(_editName)) { _editError = Text["CameraDetail_NameRequired"]; return; }
2026-07-17 19:08:17 +00:00
_saving = true;
_editError = "";
_editSuccess = "";
try
{
if (await Api.UpdateCameraAsync(Id, _editName, _editRtspUrl, null))
{
_editSuccess = Text["CameraDetail_Updated"];
2026-07-17 19:08:17 +00:00
if (_camera is not null) _camera.Name = _editName;
}
else _editError = Text["CameraDetail_UpdateError"];
2026-07-17 19:08:17 +00:00
}
catch { _editError = Text["CameraDetail_OperationFailed"]; }
2026-07-17 19:08:17 +00:00
finally { _saving = false; }
}
private async Task ToggleCameraStatus()
{
if (_camera is null || _saving || _togglingStatus) return;
_saving = true;
_togglingStatus = true;
_editError = "";
try
{
var result = await Api.ToggleCameraStatusAsync(Id);
if (result.Succeeded && result.Data is not null)
{
_camera.Status = result.Data.Status;
Snackbar.Add(result.Data.Status == "Online" ? Text["CameraDetail_Enabled"] : Text["CameraDetail_Disabled"], Severity.Success);
}
else _editError = result.ErrorMessage ?? Text["CameraDetail_StatusError"];
}
catch { _editError = Text["CameraDetail_OperationFailed"]; }
finally
{
_saving = false;
_togglingStatus = false;
}
}
private async Task DeleteCamera()
{
if (_camera is null) return;
if (await Api.DeleteCameraAsync(Id))
{
Snackbar.Add(string.Format(Language.Culture, Text["CameraDetail_Deleted"], _camera.Name), Severity.Success);
Nav.NavigateTo($"/sites/{_camera.SiteId}/cameras");
}
else Snackbar.Add(Text["CameraDetail_DeleteError"], Severity.Error);
}
2026-07-17 19:08:17 +00:00
private static Color GetStatusColor(string status) => status switch
{
"Online" => Color.Success,
"Offline" => Color.Error,
"Disabled" => Color.Default,
_ => Color.Warning
};
private static string GetStatusIcon(string status) => status switch
{
"Online" => "●",
"Offline" => "○",
_ => "?"
};
private string FormatStatus(string status) => status switch
{
"Online" => Text["CameraDetail_StatusOnline"],
"Offline" => Text["CameraDetail_StatusOffline"],
"Disabled" => Text["CameraDetail_StatusDisabled"],
_ => status
};
private string FormatEventType(string type) => type switch
{
"ManualSnapshot" => Text["CameraDetail_EventManualSnapshot"],
"MotionDetected" => Text["CameraDetail_EventMotion"],
"PersonDetected" => Text["CameraDetail_EventPerson"],
"VehicleDetected" => Text["CameraDetail_EventVehicle"],
"FaceRecognized" => Text["CameraDetail_EventFace"],
"CameraOffline" => Text["CameraDetail_StatusOffline"],
_ => 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()
{
Language.LanguageChanged -= OnLanguageChanged;
_disposed = true;
_refreshCts?.Cancel();
_refreshCts?.Dispose();
}
2026-07-17 19:08:17 +00:00
}