@if (_snapshotLoading)
@@ -40,11 +40,13 @@ else
}
else if (!string.IsNullOrEmpty(_latestSnapshotUrl))
{
-

- @if (_camera.Status == "Online")
+ @if (_latestSnapshotAt is DateTime capturedAt)
{
-
+
+ Dernière image : @capturedAt.ToLocalTime().ToString("g")
+
}
}
else
@@ -62,7 +64,7 @@ else
+ OnClick="@TakeSnapshot" />
!string.IsNullOrEmpty(e.SnapshotThumbUrl ?? e.SnapshotUrl)) is { } latest
- ? (latest.SnapshotThumbUrl ?? latest.SnapshotUrl)
- : null;
+ 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
@@ -301,6 +303,47 @@ else
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 ?? UiErrors.OperationFailed(), Severity.Error);
+ return;
+ }
+
+ Snackbar.Add("Capture demandée à l'agent", 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 ?? "La capture a échoué.", 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("Snapshot disponible", Severity.Success);
+ return;
+ }
+ Snackbar.Add("Le résultat de la capture est encore en attente ; actualisez la page pour le consulter.", Severity.Info);
+ }
+ catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); }
+ finally
+ {
+ _snapshotLoading = false;
+ if (!_disposed) await InvokeAsync(StateHasChanged);
+ }
+ }
+
private async Task SaveCamera()
{
if (string.IsNullOrWhiteSpace(_editName)) { _editError = "Le nom est requis"; return; }
@@ -375,6 +418,7 @@ else
private static string FormatEventType(string type) => type switch
{
+ "ManualSnapshot" => "Capture manuelle",
"MotionDetected" => "Mouvement",
"PersonDetected" => "Personne",
"VehicleDetected" => "Véhicule",
diff --git a/src/Heimdall.Web/Components/Pages/EventsPage.razor b/src/Heimdall.Web/Components/Pages/EventsPage.razor
index 91dbbc0..b680afc 100644
--- a/src/Heimdall.Web/Components/Pages/EventsPage.razor
+++ b/src/Heimdall.Web/Components/Pages/EventsPage.razor
@@ -233,6 +233,7 @@ else
private static string FormatEventType(string type) => type switch
{
+ "ManualSnapshot" => "Capture manuelle",
"MotionDetected" => "Mouvement",
"PersonDetected" => "Personne",
"VehicleDetected" => "Véhicule",
diff --git a/src/Heimdall.Web/Components/Pages/SnapshotsPage.razor b/src/Heimdall.Web/Components/Pages/SnapshotsPage.razor
index 9a8d1ca..76da153 100644
--- a/src/Heimdall.Web/Components/Pages/SnapshotsPage.razor
+++ b/src/Heimdall.Web/Components/Pages/SnapshotsPage.razor
@@ -24,6 +24,7 @@
Plaque détectée
Caméra hors ligne
Caméra en ligne
+ Capture manuelle
Charger
@@ -162,6 +163,7 @@ else
private static string FormatEventType(string type) => type switch
{
+ "ManualSnapshot" => "Capture manuelle",
"MotionDetected" => "Mouvement",
"PersonDetected" => "Personne",
"VehicleDetected" => "Véhicule",
diff --git a/src/Heimdall.Web/Controllers/CamerasController.cs b/src/Heimdall.Web/Controllers/CamerasController.cs
index d883551..cc3e8c8 100644
--- a/src/Heimdall.Web/Controllers/CamerasController.cs
+++ b/src/Heimdall.Web/Controllers/CamerasController.cs
@@ -6,11 +6,16 @@ using Heimdall.Application.Cameras.Commands.ToggleCameraStatus;
using Heimdall.Application.Cameras.Queries.GetCamera;
using Heimdall.Application.Cameras.Queries.GetCamerasBySite;
using Heimdall.Application.DTOs;
+using Heimdall.Application.Common;
+using Heimdall.Domain.Entities;
+using Heimdall.Application.Services;
+using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Security;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
+using Microsoft.EntityFrameworkCore;
namespace Heimdall.Api.Controllers;
@@ -20,8 +25,88 @@ namespace Heimdall.Api.Controllers;
public class CamerasController : ControllerBase
{
private readonly IMediator _mediator;
+ private readonly IApplicationDbContext _db;
+ private readonly IConfigBroadcastService _broadcast;
- public CamerasController(IMediator mediator) => _mediator = mediator;
+ public CamerasController(IMediator mediator, IApplicationDbContext db, IConfigBroadcastService broadcast)
+ {
+ _mediator = mediator;
+ _db = db;
+ _broadcast = broadcast;
+ }
+
+ /// Ask the assigned agent to capture a new frame from its active stream.
+ [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
+ [HttpPost("{id:guid}/snapshot")]
+ [ProducesResponseType(StatusCodes.Status202Accepted)]
+ public async Task RequestSnapshot(Guid id, CancellationToken ct)
+ {
+ var camera = await _db.Cameras.AsNoTracking().Where(c => c.Id == id)
+ .Select(c => new { c.AgentId, c.Status }).FirstOrDefaultAsync(ct);
+ if (camera is null) return NotFound();
+ if (camera.Status != CameraStatus.Online) return Conflict(new { error = "The camera is not online" });
+ if (camera.AgentId is null) return Conflict(new { error = "No agent is assigned to this camera" });
+ var requestId = Guid.NewGuid();
+ var snapshotRequest = new ManualSnapshotRequest(requestId, id, camera.AgentId.Value, DateTime.UtcNow);
+ _db.ManualSnapshotRequests.Add(snapshotRequest);
+ await _db.SaveChangesWithRetryAsync(ct: ct);
+ if (!await _broadcast.RequestManualSnapshot(camera.AgentId.Value, id, requestId, ct))
+ {
+ snapshotRequest.Fail("L'agent affecté est indisponible.", DateTime.UtcNow);
+ await _db.SaveChangesWithRetryAsync(ct: ct);
+ return Conflict(new { error = "The assigned agent is offline" });
+ }
+ return Accepted(new { requestId });
+ }
+
+ /// Read the durable outcome of a manual capture request.
+ [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)]
+ [HttpGet("{id:guid}/snapshot/{requestId:guid}")]
+ public async Task GetSnapshotRequest(Guid id, Guid requestId, CancellationToken ct)
+ {
+ var request = await _db.ManualSnapshotRequests.AsNoTracking()
+ .FirstOrDefaultAsync(r => r.Id == requestId && r.CameraId == id, ct);
+ if (request is null) return NotFound();
+ if (request.Status == ManualSnapshotStatus.Pending && request.ExpiresAt <= DateTime.UtcNow)
+ {
+ await _db.ManualSnapshotRequests
+ .Where(r => r.Id == requestId && r.Status == ManualSnapshotStatus.Pending && r.ExpiresAt <= DateTime.UtcNow)
+ .ExecuteUpdateAsync(setters => setters
+ .SetProperty(r => r.Status, ManualSnapshotStatus.TimedOut)
+ .SetProperty(r => r.FailureReason, "La capture n'a pas été livrée dans le délai attendu.")
+ .SetProperty(r => r.UpdatedAt, DateTime.UtcNow), ct);
+ request = await _db.ManualSnapshotRequests.AsNoTracking()
+ .FirstAsync(r => r.Id == requestId, ct);
+ }
+ return Ok(new { requestId = request.Id, status = request.Status.ToString(),
+ reason = request.FailureReason, updatedAt = request.UpdatedAt });
+ }
+
+ /// Record a capture failure reported by the agent assigned when the command was issued.
+ [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)]
+ [HttpPut("{id:guid}/snapshot/{requestId:guid}/failure")]
+ public async Task FailSnapshotRequest(Guid id, Guid requestId,
+ [FromBody] ManualSnapshotFailure failure, CancellationToken ct)
+ {
+ var exists = await _db.ManualSnapshotRequests.AnyAsync(r => r.Id == requestId && r.CameraId == id, ct);
+ if (!exists) return NotFound();
+ var reason = failure.Code switch
+ {
+ "camera_unavailable" => "La caméra n'est plus affectée ou est désactivée sur l'agent.",
+ "no_frame" => "Aucune image n'a été reçue du flux de la caméra.",
+ "queue_failed" => "L'agent n'a pas pu enregistrer la capture pour livraison.",
+ _ => "La capture a échoué sur l'agent."
+ };
+ await _db.ManualSnapshotRequests
+ .Where(r => r.Id == requestId && r.CameraId == id && r.Status != ManualSnapshotStatus.Completed)
+ .ExecuteUpdateAsync(setters => setters
+ .SetProperty(r => r.Status, ManualSnapshotStatus.Failed)
+ .SetProperty(r => r.FailureReason, reason)
+ .SetProperty(r => r.UpdatedAt, DateTime.UtcNow), ct);
+ return NoContent();
+ }
+
+ public sealed record ManualSnapshotFailure(string Code);
/// Create a new camera.
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
diff --git a/src/Heimdall.Web/Controllers/EventsController.cs b/src/Heimdall.Web/Controllers/EventsController.cs
index fc0d7cc..ca6e9f3 100644
--- a/src/Heimdall.Web/Controllers/EventsController.cs
+++ b/src/Heimdall.Web/Controllers/EventsController.cs
@@ -10,6 +10,7 @@ using Heimdall.Application.Events.Queries.GetRecentByCamera;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Security;
using Heimdall.Infrastructure.Storage;
+using ImageMagick;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -133,7 +134,11 @@ public class EventsController : ControllerBase
var ev = await _db.CameraEvents.FirstOrDefaultAsync(e => e.Id == id, ct);
if (ev is null) return NotFound();
- if (ev.SnapshotObjectKey is not null) return Ok(new { url = ev.SnapshotUrl });
+ if (ev.SnapshotObjectKey is not null)
+ {
+ await CompleteManualSnapshotRequestAsync(ev, ct);
+ return Ok(new { url = ev.SnapshotUrl });
+ }
var mediaType = Request.ContentType?.Split(';')[0].Trim();
if (!string.Equals(mediaType, "image/jpeg", StringComparison.OrdinalIgnoreCase))
@@ -156,25 +161,70 @@ public class EventsController : ControllerBase
bytes[^2] != 0xff || bytes[^1] != 0xd9)
return BadRequest(new { error = "A complete JPEG image is required" });
+ byte[] thumbnail;
+ try
+ {
+ // Inspect dimensions before decoding pixels: a small compressed JPEG
+ // can otherwise request an excessive amount of native memory.
+ var info = new MagickImageInfo(bytes);
+ if (info.Format != MagickFormat.Jpeg || info.Width > 8192 || info.Height > 8192 ||
+ (long)info.Width * info.Height > 32_000_000)
+ return BadRequest(new { error = "Image dimensions exceed the allowed limit" });
+ using var image = new MagickImage(bytes);
+ if (image.Width > 8192 || image.Height > 8192 || (long)image.Width * image.Height > 32_000_000)
+ return BadRequest(new { error = "Image dimensions exceed the allowed limit" });
+ image.AutoOrient();
+ image.Resize(new MagickGeometry(320, 180));
+ image.Strip();
+ image.Quality = 75;
+ thumbnail = image.ToByteArray(MagickFormat.Jpeg);
+ }
+ catch (MagickException)
+ {
+ return BadRequest(new { error = "A decodable JPEG image is required" });
+ }
+
var location = _storage.CaptureCurrentLocation();
- var key = $"snapshots/{ev.CameraId:D}/{ev.Id:D}/{Guid.NewGuid():N}.jpg";
- await using (var content = new MemoryStream(bytes, writable: false))
- await _storage.UploadAsync(key, content, "image/jpeg", location, ct);
+ var baseKey = $"snapshots/{ev.CameraId:D}/{ev.Id:D}/{Guid.NewGuid():N}";
+ var key = baseKey + ".jpg";
+ var thumbKey = baseKey + ".thumb.jpg";
+ var uploaded = new List(2);
try
{
- ev.SetStoredSnapshot(key, location);
+ await using (var content = new MemoryStream(bytes, writable: false))
+ await _storage.UploadAsync(key, content, "image/jpeg", location, ct);
+ uploaded.Add(key);
+ await using (var content = new MemoryStream(thumbnail, writable: false))
+ await _storage.UploadAsync(thumbKey, content, "image/jpeg", location, ct);
+ uploaded.Add(thumbKey);
+
+ ev.SetStoredSnapshot(key, location, thumbKey);
+ var manualRequest = ev.Type == EventType.ManualSnapshot
+ ? await _db.ManualSnapshotRequests.FirstOrDefaultAsync(r => r.Id == ev.Id && r.CameraId == ev.CameraId, ct)
+ : null;
+ manualRequest?.Complete(DateTime.UtcNow);
await _db.SaveChangesWithRetryAsync(ct: ct);
}
catch
{
- try { await _storage.DeleteAsync(key, location, CancellationToken.None); }
+ try { await _storage.DeleteBatchAsync(uploaded, location, CancellationToken.None); }
catch (Exception cleanupError) { _logger.LogWarning(cleanupError, "Could not remove unreferenced snapshot for event {EventId}", id); }
throw;
}
return Ok(new { url = ev.SnapshotUrl });
}
+ private async Task CompleteManualSnapshotRequestAsync(Heimdall.Domain.Entities.CameraEvent ev, CancellationToken ct)
+ {
+ if (ev.Type != EventType.ManualSnapshot) return;
+ var request = await _db.ManualSnapshotRequests
+ .FirstOrDefaultAsync(r => r.Id == ev.Id && r.CameraId == ev.CameraId, ct);
+ if (request is null || request.Status == ManualSnapshotStatus.Completed) return;
+ request.Complete(DateTime.UtcNow);
+ await _db.SaveChangesWithRetryAsync(ct: ct);
+ }
+
/// Stream a stored JPEG only to a user allowed to read its camera.
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)]
[HttpGet("{id:guid}/snapshot/content")]
@@ -194,6 +244,25 @@ public class EventsController : ControllerBase
return File(stream, "image/jpeg");
}
+ /// Stream a stored JPEG thumbnail under the same camera access check as the original.
+ [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraRead)]
+ [HttpGet("{id:guid}/snapshot/thumbnail")]
+ public async Task DownloadSnapshotThumbnail(Guid id, CancellationToken ct)
+ {
+ var requester = await _access.ResolveAsync(User, ct);
+ if (requester is null || requester.Kind != RequesterKind.Human ||
+ !await _access.EventAsync(requester, id, ct)) return Forbid();
+
+ var ev = await _db.CameraEvents.AsNoTracking().FirstOrDefaultAsync(e => e.Id == id, ct);
+ var location = ev?.GetSnapshotLocation();
+ if (ev?.SnapshotThumbObjectKey is null || location is null) return NotFound();
+ var stream = await _storage.DownloadAsync(ev.SnapshotThumbObjectKey, location, ct);
+ if (stream is null) return NotFound();
+ Response.Headers["Cache-Control"] = "private, no-store";
+ Response.Headers["X-Content-Type-Options"] = "nosniff";
+ return File(stream, "image/jpeg");
+ }
+
/// Delete an event.
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
[HttpDelete("{id:guid}")]
diff --git a/src/Heimdall.Web/Controllers/SettingsController.cs b/src/Heimdall.Web/Controllers/SettingsController.cs
index 898700e..e3f7472 100644
--- a/src/Heimdall.Web/Controllers/SettingsController.cs
+++ b/src/Heimdall.Web/Controllers/SettingsController.cs
@@ -1,4 +1,5 @@
using Heimdall.Application.Agents.Queries.GetAgent;
+using Heimdall.Application.Agents.Commands.AcknowledgeCameraConfig;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
@@ -138,7 +139,7 @@ public class SettingsController : ControllerBase
///
/// Get the effective configuration for an agent: global defaults merged with
/// per-agent overrides, plus the site's camera credential pool inside an
- /// encrypted envelope. Accessible by the agent itself (API key, same site)
+ /// encrypted envelope. Accessible by the agent itself (API key)
/// or by an admin (JWT/Cookie).
///
[Authorize(AuthenticationSchemes = "ApiKey,JwtBearer,Cookies")]
@@ -147,10 +148,13 @@ public class SettingsController : ControllerBase
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task GetEffectiveConfig(Guid agentId, CancellationToken ct)
{
- // API key callers: the agent may only read its own site's config.
+ // The API key is bound to exactly one agent. Same-site agents must not
+ // be able to read each other's RTSP URLs or credential envelopes.
var isApiKey = User.HasClaim(c => c.Type == "auth_method" && c.Value == "api_key");
if (isApiKey)
{
+ if (User.FindFirst("agent_id")?.Value != agentId.ToString())
+ return Forbid();
var siteClaim = User.FindFirst("site_id")?.Value;
if (!Guid.TryParse(siteClaim, out var apiKeySiteId))
return Forbid();
@@ -167,9 +171,38 @@ public class SettingsController : ControllerBase
}
var result = await _mediator.Send(new GetEffectiveAgentConfigQuery(agentId), ct);
- return result.IsSuccess
- ? Ok(result.Data)
- : NotFound(new { error = result.Error });
+ if (!result.IsSuccess || result.Data is null)
+ return NotFound(new { error = result.Error });
+ Response.Headers["X-Camera-Config-Version"] = CameraConfigVersion.Compute(result.Data);
+ return Ok(result.Data);
+ }
+
+ public sealed record CameraConfigAckRequest(string Version);
+
+ /// Acknowledge the exact camera snapshot applied by this agent.
+ [Authorize(AuthenticationSchemes = "ApiKey")]
+ [HttpPost("agent/{agentId:guid}/camera-config-ack")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(StatusCodes.Status409Conflict)]
+ public async Task AcknowledgeCameraConfig(Guid agentId,
+ [FromBody] CameraConfigAckRequest request, CancellationToken ct)
+ {
+ if (User.FindFirst("agent_id")?.Value != agentId.ToString())
+ return Forbid();
+ if (request.Version?.Length != 64 || !request.Version.All(Uri.IsHexDigit))
+ return BadRequest(new { error = "Invalid camera configuration version" });
+
+ var result = await _mediator.Send(new GetEffectiveAgentConfigQuery(agentId), ct);
+ if (!result.IsSuccess || result.Data is null)
+ return NotFound(new { error = result.Error });
+ if (!string.Equals(CameraConfigVersion.Compute(result.Data), request.Version,
+ StringComparison.OrdinalIgnoreCase))
+ return Conflict(new { error = "Camera configuration changed before acknowledgement" });
+
+ if (!await _mediator.Send(new AcknowledgeCameraConfigCommand(agentId, request.Version), ct))
+ return NotFound();
+ _logger.LogInformation("Agent {AgentId} applied camera configuration {Version}", agentId, request.Version);
+ return NoContent();
}
/// List all setting overrides for a specific agent (Admin only).
diff --git a/src/Heimdall.Web/Controllers/UpdatesController.cs b/src/Heimdall.Web/Controllers/UpdatesController.cs
index 0847dba..84abca3 100644
--- a/src/Heimdall.Web/Controllers/UpdatesController.cs
+++ b/src/Heimdall.Web/Controllers/UpdatesController.cs
@@ -41,7 +41,7 @@ public class UpdatesController : ControllerBase
_configuration = configuration;
}
- [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.SiteRead)]
+ [AllowAnonymous]
[HttpGet("latest")]
[ProducesResponseType(typeof(LatestReleaseResponse), StatusCodes.Status200OK)]
public async Task GetLatestRelease(CancellationToken ct)
@@ -123,6 +123,15 @@ public class UpdatesController : ControllerBase
var image = await FetchAgentImageManifestAsync(release.Assets, client, ct);
result.ContainerImage = image?.Image;
result.ContainerImageDigest = image?.Digest;
+ var manifestBytes = await FetchBoundedReleaseAssetAsync(release.Assets,
+ "agent-update-manifest.json", client, 1_048_576, ct);
+ var signatureBytes = await FetchBoundedReleaseAssetAsync(release.Assets,
+ "agent-update-manifest.sig", client, 512, ct);
+ if (manifestBytes is not null && signatureBytes is not null)
+ {
+ result.SignedManifest = Convert.ToBase64String(manifestBytes);
+ result.ManifestSignature = Convert.ToBase64String(signatureBytes);
+ }
lock (_cacheLock) { _cache = new LatestReleaseCache(source!, result, DateTime.UtcNow); }
return result;
}
@@ -163,6 +172,36 @@ public class UpdatesController : ControllerBase
private static bool IsSha256Digest(string? value) => value is { Length: 64 } && value.All(Uri.IsHexDigit);
+ private static async Task FetchBoundedReleaseAssetAsync(List? assets,
+ string name, HttpClient client, int maxBytes, CancellationToken ct)
+ {
+ var asset = assets?.FirstOrDefault(a => string.Equals(a.Name, name, StringComparison.Ordinal));
+ var expected = asset is null ? null : ExtractSha256(asset.Digest);
+ if (asset is null || !IsSha256Digest(expected)) return null;
+ try
+ {
+ using var response = await client.GetAsync(asset.BrowserDownloadUrl,
+ HttpCompletionOption.ResponseHeadersRead, ct);
+ if (!response.IsSuccessStatusCode || response.Content.Headers.ContentLength is long length && length > maxBytes)
+ return null;
+ await using var stream = await response.Content.ReadAsStreamAsync(ct);
+ using var buffer = new MemoryStream();
+ var chunk = new byte[8192];
+ while (true)
+ {
+ var read = await stream.ReadAsync(chunk, ct);
+ if (read == 0) break;
+ if (buffer.Length + read > maxBytes) return null;
+ buffer.Write(chunk, 0, read);
+ }
+ var bytes = buffer.ToArray();
+ return string.Equals(Convert.ToHexString(SHA256.HashData(bytes)), expected,
+ StringComparison.OrdinalIgnoreCase) ? bytes : null;
+ }
+ catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
+ catch { return null; }
+ }
+
private static bool IsValidContainerImageRepository(string? image) => image is { Length: > 0 and <= 255 }
&& char.IsAsciiLetterOrDigit(image[0])
&& image.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or ':' or '/' or '-')
@@ -197,6 +236,7 @@ public class UpdatesController : ControllerBase
if (l.Contains("win-x64") || l.Contains("windows-x64")) return "win-x64";
if (l.Contains("osx-x64") || l.Contains("macos-x64")) return "osx-x64";
if (l.Contains("osx-arm64") || l.Contains("macos-arm64")) return "osx-arm64";
+ if (l.Contains("agent-portable-")) return "portable";
return null;
}
@@ -215,6 +255,8 @@ public class UpdatesController : ControllerBase
[JsonPropertyName("assets")] public Dictionary Assets { get; set; } = [];
[JsonPropertyName("containerImage")] public string? ContainerImage { get; set; }
[JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; set; }
+ [JsonPropertyName("signedManifest")] public string? SignedManifest { get; set; }
+ [JsonPropertyName("manifestSignature")] public string? ManifestSignature { get; set; }
}
public class PlatformAsset
{
diff --git a/src/Heimdall.Web/Heimdall.Web.csproj b/src/Heimdall.Web/Heimdall.Web.csproj
index 02fa911..df6b60c 100644
--- a/src/Heimdall.Web/Heimdall.Web.csproj
+++ b/src/Heimdall.Web/Heimdall.Web.csproj
@@ -23,6 +23,7 @@
+
diff --git a/src/Heimdall.Web/Hubs/ConfigHub.cs b/src/Heimdall.Web/Hubs/ConfigHub.cs
index f6fdc22..48bf8d2 100644
--- a/src/Heimdall.Web/Hubs/ConfigHub.cs
+++ b/src/Heimdall.Web/Hubs/ConfigHub.cs
@@ -134,6 +134,22 @@ public class ConfigBroadcastService : IConfigBroadcastService
return true;
}
+ /// Requests one frame from the assigned agent's active camera stream.
+ public async Task RequestManualSnapshot(Guid agentId, Guid cameraId, Guid requestId, CancellationToken ct = default)
+ {
+ using var scope = _scopeFactory.CreateScope();
+ var services = scope.ServiceProvider;
+ var access = services.GetRequiredService();
+ var subscriptions = services.GetRequiredService();
+ var recipients = await subscriptions.AuthorizedAsync("config", $"agent_{agentId}", access,
+ r => access.AgentAsync(r, agentId, ct), ct);
+ if (recipients.Count == 0) return false;
+ await _hubContext.Clients.Clients(recipients).SendAsync("ManualSnapshotRequested", cameraId, requestId, ct);
+ _logger.LogInformation("Requested manual snapshot {RequestId} from agent {AgentId} for camera {CameraId}",
+ requestId, agentId, cameraId);
+ return true;
+ }
+
///
public async Task NotifyAllAgentsReload(CancellationToken ct = default)
{
diff --git a/src/Heimdall.Web/Security/ResourceAccessFilter.cs b/src/Heimdall.Web/Security/ResourceAccessFilter.cs
index 97e8196..467ae3a 100644
--- a/src/Heimdall.Web/Security/ResourceAccessFilter.cs
+++ b/src/Heimdall.Web/Security/ResourceAccessFilter.cs
@@ -41,6 +41,10 @@ public sealed class ResourceAccessFilter(ResourceAccess access, IApplicationDbCo
{
"Create" => await Site(Id("SiteId")),
"ListBySite" => true, // camera query is filtered before pagination
+ "FailSnapshotRequest" => r.Kind == RequesterKind.Agent && Id("requestId") is Guid snapshotRequestId &&
+ Id("id") is Guid snapshotCameraId &&
+ await db.ManualSnapshotRequests.AnyAsync(s => s.Id == snapshotRequestId &&
+ s.CameraId == snapshotCameraId && s.AgentId == r.Id, ct),
_ => await Camera(Id("id"))
};
break;
diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs
index cf8ce66..7a5e7d9 100644
--- a/src/Heimdall.Web/Services/HeimdallApiClient.cs
+++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs
@@ -444,6 +444,25 @@ public class HeimdallApiClient : IDisposable
return await client.GetFromJsonAsync($"api/cameras/{id}", Json);
}
+ public async Task> RequestCameraSnapshotAsync(Guid id)
+ {
+ var client = CreateClient();
+ using var response = await client.PostAsync($"api/cameras/{id}/snapshot", null);
+ if (!response.IsSuccessStatusCode)
+ return ApiResult.Failure(await ReadErrorMessageAsync(response));
+ var request = await response.Content.ReadFromJsonAsync(Json);
+ return request is null || request.RequestId == Guid.Empty
+ ? ApiResult.Failure(InvalidServerResponse)
+ : ApiResult.Success(request.RequestId);
+ }
+
+ public async Task GetCameraSnapshotStatusAsync(Guid cameraId, Guid requestId)
+ {
+ var client = CreateClient();
+ return await client.GetFromJsonAsync(
+ $"api/cameras/{cameraId:D}/snapshot/{requestId:D}", Json);
+ }
+
public async Task UpdateCameraAsync(Guid id, string name, string? rtspUrl, string? status,
string? manufacturer = null, string? model = null)
{
@@ -1202,6 +1221,15 @@ public record SetAgentSettingRequest(
[property: JsonPropertyName("value")] string Value
);
+public record ManualSnapshotRequestResult(
+ [property: JsonPropertyName("requestId")] Guid RequestId);
+
+public record ManualSnapshotStatusItem(
+ [property: JsonPropertyName("requestId")] Guid RequestId,
+ [property: JsonPropertyName("status")] string Status,
+ [property: JsonPropertyName("reason")] string? Reason,
+ [property: JsonPropertyName("updatedAt")] DateTime UpdatedAt);
+
public record EventItem(
[property: JsonPropertyName("id")] Guid Id,
[property: JsonPropertyName("cameraId")] Guid CameraId,
diff --git a/src/Heimdall.Web/packages.lock.json b/src/Heimdall.Web/packages.lock.json
index af7c812..0d0ecbc 100644
--- a/src/Heimdall.Web/packages.lock.json
+++ b/src/Heimdall.Web/packages.lock.json
@@ -33,6 +33,15 @@
"Npgsql": "6.0.11"
}
},
+ "Magick.NET-Q16-AnyCPU": {
+ "type": "Direct",
+ "requested": "[14.16.0, )",
+ "resolved": "14.16.0",
+ "contentHash": "uVMuIVbL9+N1H/+fTgJAZydAirr2fbuvrHm+EXpXAIIOwLTHfik/HfiWhcAK5gjj0FJAXhquEgBMDJuODWKM1g==",
+ "dependencies": {
+ "Magick.NET.Core": "14.16.0"
+ }
+ },
"Microsoft.AspNetCore.App.Internal.Assets": {
"type": "Direct",
"requested": "[10.0.13, )",
@@ -222,6 +231,11 @@
"resolved": "10.0.1",
"contentHash": "4aDSyqSOhIXhh4FMQ1XkxrMcTqea3iCw3QXutzPFatUVg/Lvl7XUrSN0qn6AAYvitvTL3U0gYA/CxfSePiwaPg=="
},
+ "Magick.NET.Core": {
+ "type": "Transitive",
+ "resolved": "14.16.0",
+ "contentHash": "ddBX/Zb0sCsX4agqHdHeqUx+grfw8I7GFU+lgut3mtNl7roxbxemSQFGLIJXtzwPuAHxbaMtkXA+ijVl02EUhQ=="
+ },
"MediatR": {
"type": "Transitive",
"resolved": "12.5.0",
diff --git a/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs b/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs
index fa92f43..4705263 100644
--- a/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs
+++ b/tests/Heimdall.Agent.Tests/CameraStreamServiceTests.cs
@@ -203,6 +203,30 @@ public class CameraStreamServiceTests
}
}
+ [Fact]
+ public async Task CaptureNextFrameAsync_ReturnsFreshFrameFromActiveStream()
+ {
+ if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return;
+ var scriptPath = Path.Combine(Path.GetTempPath(), $"heimdall-frame-test-{Guid.NewGuid():N}.sh");
+ await File.WriteAllTextAsync(scriptPath,
+ "#!/bin/sh\ni=0\nwhile [ \"$i\" -lt 20 ]; do printf '\\377\\330\\377\\331'; sleep 0.2; i=$((i+1)); done\n");
+ File.SetUnixFileMode(scriptPath, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
+ try
+ {
+ using var service = new CameraStreamService(Substitute.For>(), scriptPath);
+ var cameraId = Guid.NewGuid();
+ (await service.StartStreamAsync(cameraId, "rtsp://camera/test")).ShouldBeTrue();
+
+ var frame = await service.CaptureNextFrameAsync(cameraId);
+
+ frame.ShouldNotBeNull();
+ frame.CameraId.ShouldBe(cameraId);
+ frame.JpegData.ShouldBe(new byte[] { 0xff, 0xd8, 0xff, 0xd9 });
+ await service.StopStreamAsync(cameraId);
+ }
+ finally { File.Delete(scriptPath); }
+ }
+
[Fact]
public void Constructor_WithSceneDependencies_DoesNotThrow()
{
diff --git a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs
index c094fd7..4331e7a 100644
--- a/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs
+++ b/tests/Heimdall.Agent.Tests/ConfigReceiverServiceTests.cs
@@ -1,7 +1,9 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using System.Reflection;
+using System.Text.Json;
using Heimdall.Agent.Services;
using Heimdall.Application.DTOs;
using Heimdall.Application.Security;
@@ -37,7 +39,10 @@ public class ConfigReceiverServiceTests
Substitute.For>(), new ContainerInfoProvider());
var dockerUpdateService = new DockerUpdateService(options, state, new ContainerInfoProvider(), httpFactory,
Substitute.For>());
- return new ConfigReceiverService(state, options, logger, httpFactory, scanTrigger, store ?? new AgentCredentialStore(), runtimeLogLevel, cameraStore ?? new CameraConfigStore(), updateService, dockerUpdateService, new ContainerInfoProvider());
+ return new ConfigReceiverService(state, options, logger, httpFactory, scanTrigger, store ?? new AgentCredentialStore(),
+ runtimeLogLevel, cameraStore ?? new CameraConfigStore(),
+ new CameraStreamService(Substitute.For>()),
+ Substitute.For(), updateService, dockerUpdateService, new ContainerInfoProvider());
}
///
@@ -72,7 +77,13 @@ public class ConfigReceiverServiceTests
builder.Services.AddSignalR();
await using var app = builder.Build();
app.MapHub("/hubs/config");
- app.MapGet("/api/settings/agent/{id}", () => Volatile.Read(ref config));
+ app.MapGet("/api/settings/agent/{id}", (HttpContext context) =>
+ {
+ var snapshot = Volatile.Read(ref config);
+ context.Response.Headers["X-Camera-Config-Version"] = CameraConfigVersion.Compute(snapshot);
+ return Results.Json(snapshot);
+ });
+ app.MapPost("/api/settings/agent/{id}/camera-config-ack", () => Results.NoContent());
await app.StartAsync();
var factory = Substitute.For();
factory.CreateClient("Central").Returns(_ => new HttpClient());
@@ -501,7 +512,7 @@ public class ConfigReceiverServiceTests
await service.StopAsync(CancellationToken.None);
}
- /// Returns a fixed JSON body for any request (used to stub the Central config API).
+ /// Returns the versioned Central config and accepts its acknowledgement.
private sealed class StubHttpMessageHandler : HttpMessageHandler
{
private readonly string _json;
@@ -511,10 +522,14 @@ public class ConfigReceiverServiceTests
protected override Task SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
+ if (request.Method == HttpMethod.Post)
+ return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.NoContent));
var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK)
{
Content = new StringContent(_json, System.Text.Encoding.UTF8, "application/json")
};
+ var settings = JsonSerializer.Deserialize>(_json)!;
+ response.Headers.Add("X-Camera-Config-Version", CameraConfigVersion.Compute(settings));
return Task.FromResult(response);
}
}
diff --git a/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs b/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs
index 59d2408..46c1c7c 100644
--- a/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs
+++ b/tests/Heimdall.Agent.Tests/DetectionReporterServiceTests.cs
@@ -82,4 +82,39 @@ public class DetectionReporterServiceTests
if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true);
}
}
+
+ [Fact]
+ public async Task ManualSnapshots_KeepRequestIds_WithoutCooldown()
+ {
+ var directory = Path.Combine(Path.GetTempPath(), $"heimdall-manual-outbox-{Guid.NewGuid():N}");
+ try
+ {
+ var state = new AgentState { AgentId = Guid.NewGuid(), ApiKey = "test-key" };
+ using var reporter = new DetectionReporterService(state,
+ Substitute.For(), Substitute.For>(),
+ Options.Create(new Heimdall.Agent.AgentOptions { StateDirectory = directory }));
+ var cameraId = Guid.NewGuid();
+ var firstId = Guid.NewGuid();
+ var secondId = Guid.NewGuid();
+ var jpeg = new byte[] { 0xff, 0xd8, 0xff, 0xd9 };
+
+ (await reporter.ReportAsync(cameraId, EventType.ManualSnapshot, 1, "manual",
+ snapshotJpeg: jpeg, eventId: firstId)).ShouldBeTrue();
+ (await reporter.ReportAsync(cameraId, EventType.ManualSnapshot, 1, "manual",
+ snapshotJpeg: jpeg, eventId: secondId)).ShouldBeTrue();
+
+ await using var db = new SqliteConnection($"Data Source={Path.Combine(directory, "agent-events.db")}");
+ await db.OpenAsync();
+ await using var command = db.CreateCommand();
+ command.CommandText = "SELECT event_id FROM pending_detection_events ORDER BY event_id;";
+ await using var reader = await command.ExecuteReaderAsync();
+ var ids = new List();
+ while (await reader.ReadAsync()) ids.Add(Guid.Parse(reader.GetString(0)));
+ ids.OrderBy(id => id).ShouldBe(new[] { firstId, secondId }.OrderBy(id => id));
+ }
+ finally
+ {
+ if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true);
+ }
+ }
}
diff --git a/tests/Heimdall.Api.Tests/packages.lock.json b/tests/Heimdall.Api.Tests/packages.lock.json
index ec7c5e7..20e3083 100644
--- a/tests/Heimdall.Api.Tests/packages.lock.json
+++ b/tests/Heimdall.Api.Tests/packages.lock.json
@@ -203,6 +203,19 @@
"resolved": "10.0.1",
"contentHash": "4aDSyqSOhIXhh4FMQ1XkxrMcTqea3iCw3QXutzPFatUVg/Lvl7XUrSN0qn6AAYvitvTL3U0gYA/CxfSePiwaPg=="
},
+ "Magick.NET-Q16-AnyCPU": {
+ "type": "Transitive",
+ "resolved": "14.16.0",
+ "contentHash": "uVMuIVbL9+N1H/+fTgJAZydAirr2fbuvrHm+EXpXAIIOwLTHfik/HfiWhcAK5gjj0FJAXhquEgBMDJuODWKM1g==",
+ "dependencies": {
+ "Magick.NET.Core": "14.16.0"
+ }
+ },
+ "Magick.NET.Core": {
+ "type": "Transitive",
+ "resolved": "14.16.0",
+ "contentHash": "ddBX/Zb0sCsX4agqHdHeqUx+grfw8I7GFU+lgut3mtNl7roxbxemSQFGLIJXtzwPuAHxbaMtkXA+ijVl02EUhQ=="
+ },
"MediatR": {
"type": "Transitive",
"resolved": "12.5.0",
@@ -1074,6 +1087,7 @@
"Heimdall.Application": "[1.0.0, )",
"Heimdall.Contracts": "[1.0.0, )",
"Heimdall.Infrastructure": "[1.0.0, )",
+ "Magick.NET-Q16-AnyCPU": "[14.16.0, )",
"Microsoft.AspNetCore.OpenApi": "[10.0.13, )",
"Microsoft.AspNetCore.SignalR.Client": "[10.0.13, )",
"MudBlazor": "[9.8.0, )",
diff --git a/tests/Heimdall.Application.Tests/Handlers/Events/ManualSnapshotNotificationTests.cs b/tests/Heimdall.Application.Tests/Handlers/Events/ManualSnapshotNotificationTests.cs
new file mode 100644
index 0000000..cb82105
--- /dev/null
+++ b/tests/Heimdall.Application.Tests/Handlers/Events/ManualSnapshotNotificationTests.cs
@@ -0,0 +1,27 @@
+using Heimdall.Application.DTOs;
+using Heimdall.Application.Events.Notifications;
+using Heimdall.Application.Services;
+using Heimdall.Domain.Enums;
+using NSubstitute;
+
+namespace Heimdall.Application.Tests.Handlers.Events;
+
+public class ManualSnapshotNotificationTests
+{
+ [Fact]
+ public async Task ManualSnapshot_BroadcastsEventWithoutDetectionAlert()
+ {
+ var broadcast = Substitute.For();
+ var access = Substitute.For();
+ var notifications = Substitute.For();
+ var handler = new EventCreatedNotificationHandler(broadcast, access, notifications);
+ var cameraEvent = new CameraEventResponse(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(),
+ null, null, EventType.ManualSnapshot, 1, "manual", null, null, null,
+ DateTime.UtcNow, DateTime.UtcNow);
+
+ await handler.Handle(new EventCreatedNotification(cameraEvent), CancellationToken.None);
+
+ await broadcast.Received(1).NotifyEventCreated(cameraEvent, Arg.Any());
+ await access.DidNotReceiveWithAnyArgs().GetUserIdsWithCameraAccessAsync(default);
+ }
+}
diff --git a/tests/Heimdall.E2E.Tests/packages.lock.json b/tests/Heimdall.E2E.Tests/packages.lock.json
index b78fdaf..024e173 100644
--- a/tests/Heimdall.E2E.Tests/packages.lock.json
+++ b/tests/Heimdall.E2E.Tests/packages.lock.json
@@ -287,6 +287,19 @@
"resolved": "10.0.1",
"contentHash": "4aDSyqSOhIXhh4FMQ1XkxrMcTqea3iCw3QXutzPFatUVg/Lvl7XUrSN0qn6AAYvitvTL3U0gYA/CxfSePiwaPg=="
},
+ "Magick.NET-Q16-AnyCPU": {
+ "type": "Transitive",
+ "resolved": "14.16.0",
+ "contentHash": "uVMuIVbL9+N1H/+fTgJAZydAirr2fbuvrHm+EXpXAIIOwLTHfik/HfiWhcAK5gjj0FJAXhquEgBMDJuODWKM1g==",
+ "dependencies": {
+ "Magick.NET.Core": "14.16.0"
+ }
+ },
+ "Magick.NET.Core": {
+ "type": "Transitive",
+ "resolved": "14.16.0",
+ "contentHash": "ddBX/Zb0sCsX4agqHdHeqUx+grfw8I7GFU+lgut3mtNl7roxbxemSQFGLIJXtzwPuAHxbaMtkXA+ijVl02EUhQ=="
+ },
"MediatR": {
"type": "Transitive",
"resolved": "12.5.0",
@@ -1378,6 +1391,7 @@
"Heimdall.Application": "[1.0.0, )",
"Heimdall.Contracts": "[1.0.0, )",
"Heimdall.Infrastructure": "[1.0.0, )",
+ "Magick.NET-Q16-AnyCPU": "[14.16.0, )",
"Microsoft.AspNetCore.OpenApi": "[10.0.13, )",
"Microsoft.AspNetCore.SignalR.Client": "[10.0.13, )",
"MudBlazor": "[9.8.0, )",
diff --git a/tests/Heimdall.Infrastructure.Tests/PartitionManagerJobTests.cs b/tests/Heimdall.Infrastructure.Tests/PartitionManagerJobTests.cs
index bb5f698..4b105b5 100644
--- a/tests/Heimdall.Infrastructure.Tests/PartitionManagerJobTests.cs
+++ b/tests/Heimdall.Infrastructure.Tests/PartitionManagerJobTests.cs
@@ -59,22 +59,23 @@ public class PartitionManagerJobTests(PostgreSqlContainerFixture postgres)
#pragma warning disable EF1002 // Test DDL identifiers generated exclusively from dates.
await db.Database.ExecuteSqlRawAsync($"""
CREATE TABLE camera_events (
- "Id" uuid NOT NULL,
+ "Id" uuid NOT NULL DEFAULT gen_random_uuid(),
"OccurredAt" timestamptz NOT NULL,
- "SnapshotObjectKey" text,
- "SnapshotStorageProvider" text,
- "SnapshotStorageRoot" text,
- "SnapshotStorageEndpoint" text,
- "SnapshotStorageBucket" text
+ "SnapshotObjectKey" text NULL,
+ "SnapshotThumbObjectKey" text NULL,
+ "SnapshotStorageProvider" text NULL,
+ "SnapshotStorageRoot" text NULL,
+ "SnapshotStorageEndpoint" text NULL,
+ "SnapshotStorageBucket" text NULL
) PARTITION BY RANGE ("OccurredAt");
CREATE TABLE "{expiredName}" PARTITION OF camera_events FOR VALUES FROM ('{old:yyyy-MM-dd}') TO ('{old.AddMonths(1):yyyy-MM-dd}');
CREATE TABLE "{boundaryName}" PARTITION OF camera_events FOR VALUES FROM ('{boundary:yyyy-MM-dd}') TO ('{boundary.AddMonths(1):yyyy-MM-dd}');
CREATE TABLE camera_events_bad PARTITION OF camera_events DEFAULT;
CREATE TABLE "{unrelatedName}" (id int);
- INSERT INTO camera_events ("Id", "OccurredAt", "SnapshotObjectKey",
+ INSERT INTO camera_events ("Id", "OccurredAt", "SnapshotObjectKey", "SnapshotThumbObjectKey",
"SnapshotStorageProvider", "SnapshotStorageRoot")
VALUES ('00000000-0000-0000-0000-000000000001', '{old:yyyy-MM-dd}',
- 'snapshots/old.jpg', 'Local', '/tmp/heimdall-snapshots');
+ 'snapshots/old.jpg', 'snapshots/old-thumb.jpg', 'Local', '/tmp/heimdall-snapshots');
""");
#pragma warning restore EF1002
var storage = Substitute.For();
@@ -82,7 +83,8 @@ public class PartitionManagerJobTests(PostgreSqlContainerFixture postgres)
// A second execution must be harmless.
await new PartitionManagerJob(factory, NullLogger.Instance, storage).ExecuteAsync(CancellationToken.None);
await storage.Received(1).DeleteBatchAsync(
- Arg.Is>(keys => keys != null && keys.Contains("snapshots/old.jpg")),
+ Arg.Is>(keys => keys != null &&
+ keys.Contains("snapshots/old.jpg") && keys.Contains("snapshots/old-thumb.jpg")),
Arg.Is(location => location != null && location.Provider == StorageProvider.Local &&
location.LocalRoot == "/tmp/heimdall-snapshots"), Arg.Any());
await using var conn = new NpgsqlConnection(builder.ConnectionString);
diff --git a/tests/Heimdall.IntegrationTests/Controllers/CamerasControllerTests.cs b/tests/Heimdall.IntegrationTests/Controllers/CamerasControllerTests.cs
index 65c59f4..8354960 100644
--- a/tests/Heimdall.IntegrationTests/Controllers/CamerasControllerTests.cs
+++ b/tests/Heimdall.IntegrationTests/Controllers/CamerasControllerTests.cs
@@ -87,4 +87,30 @@ public class CamerasControllerTests : PostgresTestBase
var response = await client.PostAsync($"api/cameras/{Guid.NewGuid()}/toggle-status", null);
response.StatusCode.ShouldBe(System.Net.HttpStatusCode.Forbidden);
}
+
+ [Fact]
+ public async Task ManualSnapshot_RequiresOnlineCameraAndAssignedAgent()
+ {
+ var client = await Factory.CreateAdminClientAsync();
+ var siteResponse = await client.PostAsJsonAsync("api/sites", new
+ {
+ name = $"Manual Snapshot {Guid.NewGuid():N}",
+ timezone = "UTC"
+ });
+ var siteId = (await siteResponse.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid();
+ var createResponse = await client.PostAsJsonAsync("api/cameras", new
+ {
+ siteId,
+ name = "Manual Snapshot Camera",
+ rtspUrl = "rtsp://192.168.1.100:554/stream1"
+ });
+ var cameraId = (await createResponse.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid();
+
+ (await client.PostAsync($"api/cameras/{cameraId}/snapshot", null))
+ .StatusCode.ShouldBe(System.Net.HttpStatusCode.Conflict);
+ (await client.PostAsync($"api/cameras/{cameraId}/toggle-status", null))
+ .StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
+ (await client.PostAsync($"api/cameras/{cameraId}/snapshot", null))
+ .StatusCode.ShouldBe(System.Net.HttpStatusCode.Conflict);
+ }
}
diff --git a/tests/Heimdall.IntegrationTests/packages.lock.json b/tests/Heimdall.IntegrationTests/packages.lock.json
index 10f1710..affef04 100644
--- a/tests/Heimdall.IntegrationTests/packages.lock.json
+++ b/tests/Heimdall.IntegrationTests/packages.lock.json
@@ -280,6 +280,19 @@
"resolved": "10.0.1",
"contentHash": "4aDSyqSOhIXhh4FMQ1XkxrMcTqea3iCw3QXutzPFatUVg/Lvl7XUrSN0qn6AAYvitvTL3U0gYA/CxfSePiwaPg=="
},
+ "Magick.NET-Q16-AnyCPU": {
+ "type": "Transitive",
+ "resolved": "14.16.0",
+ "contentHash": "uVMuIVbL9+N1H/+fTgJAZydAirr2fbuvrHm+EXpXAIIOwLTHfik/HfiWhcAK5gjj0FJAXhquEgBMDJuODWKM1g==",
+ "dependencies": {
+ "Magick.NET.Core": "14.16.0"
+ }
+ },
+ "Magick.NET.Core": {
+ "type": "Transitive",
+ "resolved": "14.16.0",
+ "contentHash": "ddBX/Zb0sCsX4agqHdHeqUx+grfw8I7GFU+lgut3mtNl7roxbxemSQFGLIJXtzwPuAHxbaMtkXA+ijVl02EUhQ=="
+ },
"MediatR": {
"type": "Transitive",
"resolved": "12.5.0",
@@ -1338,6 +1351,7 @@
"Heimdall.Application": "[1.0.0, )",
"Heimdall.Contracts": "[1.0.0, )",
"Heimdall.Infrastructure": "[1.0.0, )",
+ "Magick.NET-Q16-AnyCPU": "[14.16.0, )",
"Microsoft.AspNetCore.OpenApi": "[10.0.13, )",
"Microsoft.AspNetCore.SignalR.Client": "[10.0.13, )",
"MudBlazor": "[9.8.0, )",
diff --git a/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs
index 4ded1f7..ab3cc9d 100644
--- a/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs
+++ b/tests/Heimdall.Web.Tests/Components/Pages/CameraDetailTests.cs
@@ -88,7 +88,7 @@ public class CameraDetailTests : PageTestBase
cut.WaitForAssertion(() =>
{
cut.Markup.ShouldContain("http://alarik/thumbs/live.jpg");
- cut.Markup.ShouldContain("Vue live de Caméra Entrée");
+ cut.Markup.ShouldContain("Dernière image de Caméra Entrée");
});
}
diff --git a/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs
index 3cc6b57..351797b 100644
--- a/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs
+++ b/tests/Heimdall.Web.Tests/Components/Pages/PersonDetailPageTests.cs
@@ -193,7 +193,7 @@ public class PersonDetailPageTests : PageTestBase
}
[Fact]
- public void PersonDetail_HistoriqueFiltreParNom()
+ public void PersonDetail_HistoriqueFiltreParPersonId()
{
Handler.OnGet($"api/persons/{PersonId}/faces", new List());
Handler.OnGet("api/vehicles", new List());
@@ -207,8 +207,7 @@ public class PersonDetailPageTests : PageTestBase
{
cut.Markup.ShouldContain("Alice Dupont");
cut.Markup.ShouldNotContain("Bob Martin");
- Handler.Requests.ShouldContain(request => request.RequestUri != null && request.RequestUri.AbsolutePath == "/api/events"
- && request.RequestUri.Query.Contains($"personId={PersonId}", StringComparison.Ordinal));
+ Handler.Requests.ShouldContain(r => r.RequestUri!.PathAndQuery.Contains($"personId={PersonId}", StringComparison.OrdinalIgnoreCase));
});
}
diff --git a/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs b/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs
index c5a26e9..e9abc13 100644
--- a/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs
+++ b/tests/Heimdall.Web.Tests/Components/Pages/SiteDetailTests.cs
@@ -44,14 +44,10 @@ public class SiteDetailTests : PageTestBase
[Fact]
public void SiteDetail_GenererToken_AfficheDockerCompose()
{
+ Handler.OnGet("api/updates/latest", AgentRelease());
Handler.OnGet("api/sites/", new SiteItem(
SiteId, "Site Principal", null, "UTC", null, true, false, DateTime.UtcNow.AddDays(-10)));
Handler.On(HttpMethod.Post, "api/sites/", new TokenResult("tok-detail-42", DateTime.UtcNow.AddHours(24)));
- Handler.OnGet("api/updates/latest", new LatestReleaseInfo
- {
- ContainerImage = "registry.example/heimdall-agent",
- ContainerImageDigest = "sha256:" + new string('a', 64)
- });
LoginAs();
var cut = RenderPage(p => p.Add(x => x.Id, SiteId));
@@ -71,14 +67,10 @@ public class SiteDetailTests : PageTestBase
[Fact]
public void SiteDetail_CopierDockerCompose_AppellePressePapier()
{
+ Handler.OnGet("api/updates/latest", AgentRelease());
Handler.OnGet("api/sites/", new SiteItem(
SiteId, "Site Principal", null, "UTC", null, true, false, DateTime.UtcNow.AddDays(-10)));
Handler.On(HttpMethod.Post, "api/sites/", new TokenResult("tok-detail-42", DateTime.UtcNow.AddHours(24)));
- Handler.OnGet("api/updates/latest", new LatestReleaseInfo
- {
- ContainerImage = "registry.example/heimdall-agent",
- ContainerImageDigest = "sha256:" + new string('a', 64)
- });
JSInterop.SetupVoid("navigator.clipboard.writeText", _ => true).SetVoidResult();
LoginAs();
@@ -127,6 +119,13 @@ public class SiteDetailTests : PageTestBase
LastUsedAt = lastUsed,
};
+ private static LatestReleaseInfo AgentRelease() => new()
+ {
+ Version = "1.0.0",
+ ContainerImage = "registry.example/heimdall-agent",
+ ContainerImageDigest = "sha256:" + new string('a', 64)
+ };
+
[Fact]
public void SiteDetail_AucunIdentifiant_AfficheMessage()
{
diff --git a/tests/Heimdall.Web.Tests/Controllers/CamerasControllerTests.cs b/tests/Heimdall.Web.Tests/Controllers/CamerasControllerTests.cs
index fc2a234..3696a57 100644
--- a/tests/Heimdall.Web.Tests/Controllers/CamerasControllerTests.cs
+++ b/tests/Heimdall.Web.Tests/Controllers/CamerasControllerTests.cs
@@ -3,6 +3,7 @@ using Heimdall.Api.Controllers;
using Heimdall.Application.Cameras.Commands.ToggleCameraStatus;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
+using Heimdall.Application.Services;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@@ -21,7 +22,7 @@ public class CamerasControllerTests
.Returns(ServiceResult.NotFound("Camera not found"));
var actorId = Guid.NewGuid();
var cameraId = Guid.NewGuid();
- var controller = new CamerasController(mediator)
+ var controller = new CamerasController(mediator, Substitute.For(), Substitute.For())
{
ControllerContext = new ControllerContext
{
@@ -47,7 +48,7 @@ public class CamerasControllerTests
public async Task ToggleStatus_rejects_missing_actor_claim()
{
var mediator = Substitute.For();
- var controller = new CamerasController(mediator)
+ var controller = new CamerasController(mediator, Substitute.For(), Substitute.For())
{
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};
diff --git a/tests/Heimdall.Web.Tests/Security/HttpIsolationTests.cs b/tests/Heimdall.Web.Tests/Security/HttpIsolationTests.cs
index 14f789e..c3db57a 100644
--- a/tests/Heimdall.Web.Tests/Security/HttpIsolationTests.cs
+++ b/tests/Heimdall.Web.Tests/Security/HttpIsolationTests.cs
@@ -16,6 +16,7 @@ using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
+using NSubstitute;
using Shouldly;
namespace Heimdall.Web.Tests.Security;
@@ -37,6 +38,7 @@ public sealed class HttpIsolationTests
builder.Services.AddSingleton(f.Db);
builder.Services.AddSingleton(f.Db);
builder.Services.AddSingleton(f.Cameras);
+ builder.Services.AddSingleton(Substitute.For());
builder.Services.AddScoped();
builder.Services.AddMediatR(c => c.RegisterServicesFromAssemblyContaining());
builder.Services.AddControllers(o => o.Filters.Add()).AddApplicationPart(typeof(CamerasController).Assembly);
diff --git a/tests/Heimdall.Web.Tests/packages.lock.json b/tests/Heimdall.Web.Tests/packages.lock.json
index 6955949..f56b00e 100644
--- a/tests/Heimdall.Web.Tests/packages.lock.json
+++ b/tests/Heimdall.Web.Tests/packages.lock.json
@@ -272,6 +272,19 @@
"resolved": "10.0.1",
"contentHash": "4aDSyqSOhIXhh4FMQ1XkxrMcTqea3iCw3QXutzPFatUVg/Lvl7XUrSN0qn6AAYvitvTL3U0gYA/CxfSePiwaPg=="
},
+ "Magick.NET-Q16-AnyCPU": {
+ "type": "Transitive",
+ "resolved": "14.16.0",
+ "contentHash": "uVMuIVbL9+N1H/+fTgJAZydAirr2fbuvrHm+EXpXAIIOwLTHfik/HfiWhcAK5gjj0FJAXhquEgBMDJuODWKM1g==",
+ "dependencies": {
+ "Magick.NET.Core": "14.16.0"
+ }
+ },
+ "Magick.NET.Core": {
+ "type": "Transitive",
+ "resolved": "14.16.0",
+ "contentHash": "ddBX/Zb0sCsX4agqHdHeqUx+grfw8I7GFU+lgut3mtNl7roxbxemSQFGLIJXtzwPuAHxbaMtkXA+ijVl02EUhQ=="
+ },
"MediatR": {
"type": "Transitive",
"resolved": "12.5.0",
@@ -1228,6 +1241,7 @@
"Heimdall.Application": "[1.0.0, )",
"Heimdall.Contracts": "[1.0.0, )",
"Heimdall.Infrastructure": "[1.0.0, )",
+ "Magick.NET-Q16-AnyCPU": "[14.16.0, )",
"Microsoft.AspNetCore.OpenApi": "[10.0.13, )",
"Microsoft.AspNetCore.SignalR.Client": "[10.0.13, )",
"MudBlazor": "[9.8.0, )",