feat(cameras): activer/désactiver une caméra depuis la liste (toggle status) (#151)
## 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
This commit is contained in:
1 parent
91ec880441
commit
f54bb596af
9 files changed
+248
-17
No files matched your search
+44
@@ -0,0 +1,44 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Enums;
|
||||
using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Cameras.Commands.ToggleCameraStatus;
|
||||
|
||||
public record ToggleCameraStatusCommand(Guid Id) : IRequest<ServiceResult<CameraResponse>>;
|
||||
|
||||
public class ToggleCameraStatusCommandHandler : IRequestHandler<ToggleCameraStatusCommand, ServiceResult<CameraResponse>>
|
||||
{
|
||||
private readonly IApplicationDbContext _db;
|
||||
|
||||
public ToggleCameraStatusCommandHandler(IApplicationDbContext db)
|
||||
{
|
||||
_db = db;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<CameraResponse>> Handle(ToggleCameraStatusCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var camera = await _db.Cameras.FindAsync([request.Id], cancellationToken).ConfigureAwait(false);
|
||||
if (camera is null)
|
||||
return ServiceResult<CameraResponse>.NotFound("Camera not found");
|
||||
|
||||
var newStatus = camera.Status == CameraStatus.Disabled
|
||||
? CameraStatus.Online
|
||||
: CameraStatus.Disabled;
|
||||
|
||||
camera.SetStatus(newStatus);
|
||||
|
||||
await _db.SaveChangesWithRetryAsync(ct: cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return ServiceResult<CameraResponse>.Success(MapResponse(camera));
|
||||
}
|
||||
|
||||
private static CameraResponse MapResponse(Domain.Entities.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);
|
||||
}
|
||||
@@ -27,8 +27,8 @@
|
||||
|
||||
@* Badge statut — coin haut droit *@
|
||||
<div style="position:absolute; top:8px; right:8px;">
|
||||
<MudChip T="string" Size="Size.Small" Color="@GetStatusColor(Camera.Status)" Variant="Variant.Filled">
|
||||
@FormatStatus(Camera.Status)
|
||||
<MudChip T="string" Size="Size.Small" Color="@(GetStatusColor(Camera.Status))" Variant="Variant.Filled">
|
||||
@(GetStatusLabel(Camera.Status))
|
||||
</MudChip>
|
||||
</div>
|
||||
</div>
|
||||
@@ -52,6 +52,12 @@
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Visibility" Size="Size.Small" aria-label="Voir la caméra"
|
||||
OnClick="@(() => Nav.NavigateTo($"/cameras/{Camera.Id}"))" />
|
||||
</MudTooltip>
|
||||
<MudTooltip Text="@(Camera.Status == "Disabled" ? "Activer la caméra" : "Désactiver la caméra")">
|
||||
<MudIconButton Icon="@(Camera.Status == "Disabled" ? Icons.Material.Filled.PlayArrow : Icons.Material.Filled.Stop)"
|
||||
Size="Size.Small" Color="@(Camera.Status == "Disabled" ? Color.Success : Color.Default)"
|
||||
aria-label="@(Camera.Status == "Disabled" ? "Activer la caméra" : "Désactiver la caméra")"
|
||||
OnClick="@OnToggleStatus" Disabled="@_toggling" />
|
||||
</MudTooltip>
|
||||
<MudTooltip Text="Prendre un snapshot">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.PhotoCamera" Size="Size.Small" aria-label="Prendre un snapshot"
|
||||
Disabled="@(Camera.Status != "Online")" OnClick="@OnSnapshot" />
|
||||
@@ -70,20 +76,28 @@
|
||||
[Parameter] public bool LoadingSnapshot { get; set; }
|
||||
[Parameter] public EventCallback OnSnapshot { get; set; }
|
||||
[Parameter] public EventCallback OnDelete { get; set; }
|
||||
[Parameter] public EventCallback OnToggleStatus { get; set; }
|
||||
|
||||
private static Color GetStatusColor(string status) => status switch
|
||||
private bool _toggling;
|
||||
|
||||
protected override void OnParametersSet()
|
||||
{
|
||||
// Reset toggling state when camera data changes (after parent refreshes list)
|
||||
_toggling = false;
|
||||
}
|
||||
|
||||
private static Color GetStatusColor(string? status) => status switch
|
||||
{
|
||||
"Online" => Color.Success,
|
||||
"Offline" => Color.Error,
|
||||
"Disabled" => Color.Default,
|
||||
_ => Color.Warning
|
||||
};
|
||||
|
||||
private static string FormatStatus(string status) => status switch
|
||||
private static string GetStatusLabel(string? status) => status switch
|
||||
{
|
||||
"Online" => "En ligne",
|
||||
"Offline" => "Hors ligne",
|
||||
"Disabled" => "Désactivée",
|
||||
_ => status
|
||||
"Offline" => "Hors ligne",
|
||||
_ => status ?? "—"
|
||||
};
|
||||
}
|
||||
@@ -323,17 +323,17 @@ else
|
||||
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))
|
||||
var result = await Api.ToggleCameraStatusAsync(Id);
|
||||
if (result.Succeeded && result.Data is not null)
|
||||
{
|
||||
_camera.Status = newStatus;
|
||||
Snackbar.Add(newStatus == "Online" ? "Caméra activée" : "Caméra désactivée", Severity.Success);
|
||||
_camera.Status = result.Data.Status;
|
||||
Snackbar.Add(result.Data.Status == "Online" ? "Caméra activée" : "Caméra désactivée", Severity.Success);
|
||||
}
|
||||
else _editError = "Erreur lors de la mise à jour du statut";
|
||||
else _editError = result.ErrorMessage ?? "Erreur lors de la mise à jour du statut";
|
||||
}
|
||||
catch { _editError = UiErrors.OperationFailed(); }
|
||||
finally { _saving = false; }
|
||||
|
||||
@@ -82,7 +82,8 @@ else
|
||||
SnapshotUrl="@GetSnapshot(camera.Id)"
|
||||
LoadingSnapshot="@IsSnapshotLoading(camera.Id)"
|
||||
OnSnapshot="@(() => TakeSnapshot(camera))"
|
||||
OnDelete="@(() => ConfirmDeleteCamera(camera.Id, camera.Name))" />
|
||||
OnDelete="@(() => ConfirmDeleteCamera(camera.Id, camera.Name))"
|
||||
OnToggleStatus="@(() => ToggleCamera(camera))" />
|
||||
</MudItem>
|
||||
}
|
||||
</MudGrid>
|
||||
@@ -244,6 +245,29 @@ else
|
||||
}
|
||||
}
|
||||
|
||||
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 = "";
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using Heimdall.Application.Cameras.Commands.CreateCamera;
|
||||
using Heimdall.Application.Cameras.Commands.UpdateCamera;
|
||||
using Heimdall.Application.Cameras.Commands.DeleteCamera;
|
||||
using Heimdall.Application.Cameras.Commands.ToggleCameraStatus;
|
||||
using Heimdall.Application.Cameras.Queries.GetCamera;
|
||||
using Heimdall.Application.Cameras.Queries.GetCamerasBySite;
|
||||
using Heimdall.Application.DTOs;
|
||||
@@ -77,6 +78,19 @@ public class CamerasController : ControllerBase
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Toggle a camera between Online and Disabled.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpPost("{id:guid}/toggle-status")]
|
||||
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> ToggleStatus(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await _mediator.Send(new ToggleCameraStatusCommand(id), ct);
|
||||
return result.IsSuccess
|
||||
? Ok(result.Data)
|
||||
: NotFound(new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Delete a camera.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpDelete("{id:guid}")]
|
||||
|
||||
@@ -10,6 +10,8 @@ public class HeimdallApiClient
|
||||
{
|
||||
private readonly IHttpClientFactory _httpFactory;
|
||||
private readonly AuthState _authState;
|
||||
private const string InvalidServerResponse = "Réponse du serveur invalide.";
|
||||
|
||||
private static readonly JsonSerializerOptions Json = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -351,7 +353,7 @@ public class HeimdallApiClient
|
||||
return ApiResult<SiteWithTokenResult>.Failure(await ReadErrorMessageAsync(response));
|
||||
var site = await response.Content.ReadFromJsonAsync<SiteWithTokenResult>(Json);
|
||||
return site is null
|
||||
? ApiResult<SiteWithTokenResult>.Failure("Réponse du serveur invalide.")
|
||||
? ApiResult<SiteWithTokenResult>.Failure(InvalidServerResponse)
|
||||
: ApiResult<SiteWithTokenResult>.Success(site);
|
||||
}
|
||||
|
||||
@@ -402,6 +404,18 @@ public class HeimdallApiClient
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
public async Task<ApiResult<CameraItem>> ToggleCameraStatusAsync(Guid id)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsync($"api/cameras/{id}/toggle-status", null);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
return ApiResult<CameraItem>.Failure(await ReadErrorMessageAsync(response));
|
||||
var camera = await response.Content.ReadFromJsonAsync<CameraItem>(Json);
|
||||
return camera is null
|
||||
? ApiResult<CameraItem>.Failure(InvalidServerResponse)
|
||||
: ApiResult<CameraItem>.Success(camera);
|
||||
}
|
||||
|
||||
public async Task<ApiResult<CameraItem>> CreateCameraAsync(Guid siteId, string name, string? rtspUrl, string? manufacturer, string? model)
|
||||
{
|
||||
var client = CreateClient();
|
||||
@@ -411,7 +425,7 @@ public class HeimdallApiClient
|
||||
return ApiResult<CameraItem>.Failure(await ReadErrorMessageAsync(response));
|
||||
var camera = await response.Content.ReadFromJsonAsync<CameraItem>(Json);
|
||||
return camera is null
|
||||
? ApiResult<CameraItem>.Failure("Réponse du serveur invalide.")
|
||||
? ApiResult<CameraItem>.Failure(InvalidServerResponse)
|
||||
: ApiResult<CameraItem>.Success(camera);
|
||||
}
|
||||
|
||||
@@ -484,7 +498,7 @@ public class HeimdallApiClient
|
||||
return ApiResult<CameraItem>.Failure(await ReadErrorMessageAsync(response));
|
||||
var camera = await response.Content.ReadFromJsonAsync<CameraItem>(Json);
|
||||
return camera is null
|
||||
? ApiResult<CameraItem>.Failure("Réponse du serveur invalide.")
|
||||
? ApiResult<CameraItem>.Failure(InvalidServerResponse)
|
||||
: ApiResult<CameraItem>.Success(camera);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user