feat: complete local camera and operations acceptance
Heimdall Gitea / Detect CI scope (pull_request) Successful in 1m27s
Heimdall Gitea / Build and tests (pull_request) Failing after 12m27s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 4s
Heimdall Gitea / Detect CI scope (pull_request) Successful in 1m27s
Heimdall Gitea / Build and tests (pull_request) Failing after 12m27s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 4s
This commit is contained in:
1 parent
ae3203222b
commit
3208bc93fe
52 files changed
+1193
-106
No files matched your search
@@ -265,7 +265,7 @@ public NetworkCameraScanner(
|
||||
/// are kept; the HomeKit* fields of the device are filled for the Central
|
||||
/// ClassifyAgentDevice HomeKit path.
|
||||
/// </summary>
|
||||
private async Task<List<AgentDiscoveredDevice>> DiscoverHomeKitAsync(CancellationToken ct)
|
||||
internal async Task<List<AgentDiscoveredDevice>> DiscoverHomeKitAsync(CancellationToken ct)
|
||||
{
|
||||
var devices = new List<AgentDiscoveredDevice>();
|
||||
try
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace Heimdall.Application.Common;
|
||||
|
||||
/// <summary>Serializes recording usage checks across cameras and exposes the validated Central quota.</summary>
|
||||
public interface IRecordingQuotaGuard
|
||||
{
|
||||
long MaxStorageBytes { get; }
|
||||
Task<IRecordingQuotaLease> AcquireAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>A short-lived database transaction holding the global recording quota lock.</summary>
|
||||
public interface IRecordingQuotaLease : IAsyncDisposable
|
||||
{
|
||||
Task CommitAsync(CancellationToken ct = default);
|
||||
}
|
||||
+98
-17
@@ -4,6 +4,7 @@ using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Application.Recordings.Commands.UploadRecording;
|
||||
|
||||
@@ -18,7 +19,10 @@ public sealed record UploadRecordingCommand(
|
||||
|
||||
public sealed class UploadRecordingHandler(
|
||||
IApplicationDbContext db,
|
||||
IRecordingStorage storage) : IRequestHandler<UploadRecordingCommand, ServiceResult<RecordingDto>>
|
||||
IRecordingStorage storage,
|
||||
IRecordingQuotaGuard quota,
|
||||
IStorageObjectDeletion objectDeletion,
|
||||
ILogger<UploadRecordingHandler> logger) : IRequestHandler<UploadRecordingCommand, ServiceResult<RecordingDto>>
|
||||
{
|
||||
public async Task<ServiceResult<RecordingDto>> Handle(UploadRecordingCommand request, CancellationToken ct)
|
||||
{
|
||||
@@ -29,9 +33,9 @@ public sealed class UploadRecordingHandler(
|
||||
|
||||
var camera = await db.Cameras.AsNoTracking()
|
||||
.Where(c => c.Id == request.CameraId && !c.IsDeleted)
|
||||
.Select(c => new { c.Id, c.AgentId, c.StoragePolicyId })
|
||||
.Select(c => new { c.Id, c.AgentId, c.StoragePolicyId, c.RecordingEnabled })
|
||||
.SingleOrDefaultAsync(ct).ConfigureAwait(false);
|
||||
if (camera?.AgentId != request.AgentId)
|
||||
if (camera?.AgentId != request.AgentId || !camera.RecordingEnabled)
|
||||
return ServiceResult<RecordingDto>.NotFound("Camera not found");
|
||||
|
||||
var existing = await db.Recordings.AsNoTracking()
|
||||
@@ -45,23 +49,100 @@ public sealed class UploadRecordingHandler(
|
||||
|
||||
var timestamp = CameraEvent.NormalizeOccurredAt(request.Timestamp);
|
||||
var location = storage.CaptureCurrentLocation();
|
||||
var key = $"recordings/{request.CameraId:D}/{request.RecordingId:D}.mp4";
|
||||
if (request.Content.CanSeek) request.Content.Position = 0;
|
||||
await storage.UploadAsync(key, request.Content, "video/mp4", location, ct).ConfigureAwait(false);
|
||||
// Each attempt gets its own key so a racing retry cannot overwrite the winner's object
|
||||
// before the transaction discovers its already-persisted metadata row.
|
||||
var key = $"recordings/{request.CameraId:D}/{request.RecordingId:D}/{Guid.NewGuid():N}.mp4";
|
||||
|
||||
var recording = new Recording(request.CameraId, timestamp, request.DurationSeconds,
|
||||
key, request.SizeBytes, location.Provider, location, camera.StoragePolicyId, request.RecordingId);
|
||||
db.Recordings.Add(recording);
|
||||
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
||||
var shouldDeleteObject = false;
|
||||
var commitAttempted = false;
|
||||
try
|
||||
{
|
||||
if (request.Content.CanSeek) request.Content.Position = 0;
|
||||
await storage.UploadAsync(key, request.Content, "video/mp4", location, ct).ConfigureAwait(false);
|
||||
|
||||
var end = timestamp.AddSeconds(request.DurationSeconds);
|
||||
await db.CameraEvents
|
||||
.Where(e => e.CameraId == request.CameraId && e.RecordingId == null && e.OccurredAt >= timestamp && e.OccurredAt < end)
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(e => e.RecordingId, recording.Id), ct)
|
||||
.ConfigureAwait(false);
|
||||
ServiceResult<RecordingDto> result;
|
||||
await using (var quotaLease = await quota.AcquireAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
// Recheck under the quota lock to keep duplicate retries safe when uploads race.
|
||||
existing = await db.Recordings.AsNoTracking()
|
||||
.Where(r => r.Id == request.RecordingId)
|
||||
.Select(r => new { r.Id, r.CameraId, r.Timestamp, r.DurationSeconds, r.SizeBytes })
|
||||
.SingleOrDefaultAsync(ct).ConfigureAwait(false);
|
||||
if (existing is not null)
|
||||
{
|
||||
// The uploaded key is unique to this attempt, so it cannot be the
|
||||
// already-persisted object's key and is safe to remove in either case.
|
||||
shouldDeleteObject = true;
|
||||
result = existing.CameraId == request.CameraId
|
||||
? ServiceResult<RecordingDto>.Success(Map(existing.Id, existing.CameraId,
|
||||
existing.Timestamp, existing.DurationSeconds, existing.SizeBytes))
|
||||
: ServiceResult<RecordingDto>.Conflict("Recording identifier already belongs to another camera");
|
||||
commitAttempted = true;
|
||||
await quotaLease.CommitAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
var usedBytes = await db.Recordings.AsNoTracking()
|
||||
.SumAsync(r => (long?)r.SizeBytes, ct).ConfigureAwait(false) ?? 0;
|
||||
var overQuota = request.SizeBytes > quota.MaxStorageBytes ||
|
||||
usedBytes > quota.MaxStorageBytes - request.SizeBytes;
|
||||
if (overQuota)
|
||||
{
|
||||
shouldDeleteObject = true;
|
||||
result = ServiceResult<RecordingDto>.Failure(
|
||||
"Central recording storage quota exceeded; segment was not retained", 507);
|
||||
commitAttempted = true;
|
||||
await quotaLease.CommitAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
var recording = new Recording(request.CameraId, timestamp, request.DurationSeconds,
|
||||
key, request.SizeBytes, location.Provider, location, camera.StoragePolicyId, request.RecordingId);
|
||||
db.Recordings.Add(recording);
|
||||
await db.SaveChangesAsync(ct).ConfigureAwait(false);
|
||||
|
||||
return ServiceResult<RecordingDto>.Success(Map(recording.Id, recording.CameraId,
|
||||
recording.Timestamp, recording.DurationSeconds, recording.SizeBytes));
|
||||
var end = timestamp.AddSeconds(request.DurationSeconds);
|
||||
await db.CameraEvents
|
||||
.Where(e => e.CameraId == request.CameraId && e.RecordingId == null &&
|
||||
e.OccurredAt >= timestamp && e.OccurredAt < end)
|
||||
.ExecuteUpdateAsync(setters => setters.SetProperty(e => e.RecordingId, recording.Id), ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
commitAttempted = true;
|
||||
await quotaLease.CommitAsync(ct).ConfigureAwait(false);
|
||||
result = ServiceResult<RecordingDto>.Success(Map(recording.Id, recording.CameraId,
|
||||
recording.Timestamp, recording.DurationSeconds, recording.SizeBytes));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldDeleteObject)
|
||||
await TryDeleteUploadedObjectAsync(key, location, request.RecordingId, ct).ConfigureAwait(false);
|
||||
return result;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Once commit starts its outcome can be ambiguous; leave this attempt's unique object
|
||||
// for the retry/orphan sweep instead of risking deletion after a successful DB commit.
|
||||
if (!commitAttempted)
|
||||
await TryDeleteUploadedObjectAsync(key, location, request.RecordingId, CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task TryDeleteUploadedObjectAsync(string key, StorageLocation location, Guid recordingId,
|
||||
CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await objectDeletion.DeleteBatchAsync([key], location, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
logger.LogWarning("Could not clean up an unretained recording object {RecordingId} (error type {ErrorType})",
|
||||
recordingId, ex.GetType().Name);
|
||||
}
|
||||
}
|
||||
|
||||
private static RecordingDto Map(Guid id, Guid cameraId, DateTime timestamp, double duration, long size) =>
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace Heimdall.Application.Services;
|
||||
|
||||
public sealed record PlateOcrResult(string Text, double Confidence);
|
||||
|
||||
/// <summary>Runs self-hosted OCR over a user-supplied plate crop.</summary>
|
||||
public interface ILicensePlateOcr
|
||||
{
|
||||
Task<PlateOcrResult?> RecognizeAsync(ReadOnlyMemory<byte> image, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed record LicensePlateRecognitionResponse(Guid PlateId, Guid EventId, string PlateText,
|
||||
double Confidence, Guid? SuggestedVehicleId, Guid? SuggestedPersonId);
|
||||
|
||||
public interface ILicensePlateRecognitionService
|
||||
{
|
||||
Task<Common.ServiceResult<LicensePlateRecognitionResponse>> RecognizeAsync(
|
||||
Guid cameraId, ReadOnlyMemory<byte> image, CancellationToken ct);
|
||||
}
|
||||
@@ -45,6 +45,12 @@ public static class DependencyInjection
|
||||
|
||||
services.AddScoped<IApplicationDbContext>(sp => sp.GetRequiredService<AppDbContext>());
|
||||
services.AddScoped<IIdentityPersistenceContext>(sp => sp.GetRequiredService<AppDbContext>());
|
||||
services.AddOptions<PlateOcrOptions>()
|
||||
.Bind(configuration.GetSection(PlateOcrOptions.SectionName))
|
||||
.Validate(options => options.IsValid(), "Plate OCR options are invalid")
|
||||
.ValidateOnStart();
|
||||
services.AddSingleton<ILicensePlateOcr, TesseractPlateOcr>();
|
||||
services.AddScoped<ILicensePlateRecognitionService, LicensePlateRecognitionService>();
|
||||
|
||||
// Stockage (spec Phase 8) — provider résolu depuis les settings DB
|
||||
// (storage.provider = Local | S3), factory scoped (lit la config à
|
||||
@@ -52,7 +58,6 @@ public static class DependencyInjection
|
||||
services.AddSingleton<StorageProviderFactory>();
|
||||
services.AddScoped<IStorageProvider>(sp => sp.GetRequiredService<StorageProviderFactory>());
|
||||
services.AddScoped<IStorageObjectDeletion>(sp => sp.GetRequiredService<StorageProviderFactory>());
|
||||
services.AddScoped<IRecordingStorage, RecordingStorageAdapter>();
|
||||
|
||||
// Health checks (spec 13.2) — PostgreSQL + dépendances optionnelles.
|
||||
services.AddHealthChecks()
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
using System.Text.Json;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Domain.Entities;
|
||||
using Heimdall.Domain.Enums;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Infrastructure.Services;
|
||||
|
||||
public sealed class LicensePlateRecognitionService(
|
||||
IDbContextFactory<AppDbContext> dbFactory,
|
||||
ILicensePlateOcr ocr) : ILicensePlateRecognitionService
|
||||
{
|
||||
public async Task<ServiceResult<LicensePlateRecognitionResponse>> RecognizeAsync(
|
||||
Guid cameraId, ReadOnlyMemory<byte> image, CancellationToken ct)
|
||||
{
|
||||
var result = await ocr.RecognizeAsync(image, ct).ConfigureAwait(false);
|
||||
if (result is null) return ServiceResult<LicensePlateRecognitionResponse>.Failure("OCR could not read this plate crop", 422);
|
||||
var plateText = new string(result.Text.Where(c => char.IsAsciiLetterOrDigit(c) || c == '-').ToArray())
|
||||
.ToUpperInvariant();
|
||||
if (plateText.Length is < 3 or > LicensePlate.MaxPlateTextLength)
|
||||
return ServiceResult<LicensePlateRecognitionResponse>.Failure("OCR output is not a valid plate candidate", 422);
|
||||
|
||||
await using var db = await dbFactory.CreateDbContextAsync(ct).ConfigureAwait(false);
|
||||
var camera = await db.Cameras.AsNoTracking()
|
||||
.Where(c => c.Id == cameraId && !c.IsDeleted)
|
||||
.Select(c => new { c.Id, c.SiteId })
|
||||
.FirstOrDefaultAsync(ct).ConfigureAwait(false);
|
||||
if (camera is null) return ServiceResult<LicensePlateRecognitionResponse>.NotFound("Camera not found");
|
||||
|
||||
var normalized = plateText.Replace("-", string.Empty);
|
||||
var vehicles = await db.Vehicles.AsNoTracking()
|
||||
.Where(v => v.LicensePlate != null && v.LicensePlate.Replace("-", "") == normalized)
|
||||
.OrderBy(v => v.Id)
|
||||
.Take(2)
|
||||
.Select(v => new { v.Id, v.PersonId })
|
||||
.ToListAsync(ct).ConfigureAwait(false);
|
||||
// Suggest only. OCR output is not proof of identity: a human must verify it before linking.
|
||||
var vehicle = vehicles.Count == 1 ? vehicles[0] : null;
|
||||
var observation = new LicensePlate(plateText, confidence: result.Confidence);
|
||||
var ev = new CameraEvent(cameraId, EventType.LicensePlateDetected, result.Confidence);
|
||||
ev.SetMetadata(plateText, JsonSerializer.Serialize(new { source = "local-opt-in-ocr", plateId = observation.Id }));
|
||||
db.LicensePlates.Add(observation);
|
||||
db.CameraEvents.Add(ev);
|
||||
await db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
||||
return ServiceResult<LicensePlateRecognitionResponse>.Success(
|
||||
new(observation.Id, ev.Id, plateText, result.Confidence, vehicle?.Id, vehicle?.PersonId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Heimdall.Infrastructure.Services;
|
||||
|
||||
public sealed class PlateOcrOptions
|
||||
{
|
||||
public const string SectionName = "PlateOcr";
|
||||
public bool Enabled { get; set; }
|
||||
public string ExecutablePath { get; set; } = "/usr/bin/tesseract";
|
||||
public int MaxImageBytes { get; set; } = 512 * 1024;
|
||||
public int TimeoutSeconds { get; set; } = 10;
|
||||
|
||||
public bool IsValid() => !Enabled ||
|
||||
(!string.IsNullOrWhiteSpace(ExecutablePath) && MaxImageBytes is >= 1024 and <= 512 * 1024 &&
|
||||
TimeoutSeconds is >= 1 and <= 60);
|
||||
}
|
||||
|
||||
/// <summary>Invokes local Tesseract against a temporary, bounded image crop.</summary>
|
||||
public sealed class TesseractPlateOcr(IOptionsMonitor<PlateOcrOptions> options) : Application.Services.ILicensePlateOcr
|
||||
{
|
||||
public async Task<Application.Services.PlateOcrResult?> RecognizeAsync(ReadOnlyMemory<byte> image, CancellationToken ct)
|
||||
{
|
||||
var settings = options.CurrentValue;
|
||||
if (!settings.Enabled || !IsSafeImage(image.Span, settings.MaxImageBytes))
|
||||
return null;
|
||||
|
||||
var tempFile = Path.Combine(Path.GetTempPath(), $"heimdall-plate-{Guid.NewGuid():N}.img");
|
||||
try
|
||||
{
|
||||
var fileOptions = new FileStreamOptions
|
||||
{
|
||||
Mode = FileMode.CreateNew,
|
||||
Access = FileAccess.Write,
|
||||
Share = FileShare.None,
|
||||
BufferSize = 4096
|
||||
};
|
||||
if (!OperatingSystem.IsWindows())
|
||||
fileOptions.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite;
|
||||
await using (var output = new FileStream(tempFile, fileOptions))
|
||||
await output.WriteAsync(image, ct).ConfigureAwait(false);
|
||||
var start = new ProcessStartInfo(settings.ExecutablePath)
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
};
|
||||
start.ArgumentList.Add(tempFile);
|
||||
start.ArgumentList.Add("stdout");
|
||||
start.ArgumentList.Add("--oem"); start.ArgumentList.Add("1");
|
||||
start.ArgumentList.Add("--psm"); start.ArgumentList.Add("7");
|
||||
start.ArgumentList.Add("-l"); start.ArgumentList.Add("eng");
|
||||
start.ArgumentList.Add("tsv");
|
||||
start.ArgumentList.Add("-c"); start.ArgumentList.Add("tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-");
|
||||
|
||||
using var process = Process.Start(start);
|
||||
if (process is null) return null;
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(settings.TimeoutSeconds));
|
||||
try
|
||||
{
|
||||
var stdoutTask = process.StandardOutput.ReadToEndAsync(timeout.Token);
|
||||
var stderrTask = process.StandardError.ReadToEndAsync(timeout.Token);
|
||||
await Task.WhenAll(stdoutTask, stderrTask, process.WaitForExitAsync(timeout.Token)).ConfigureAwait(false);
|
||||
var stdout = await stdoutTask.ConfigureAwait(false);
|
||||
if (process.ExitCode != 0 || stdout.Length > 32_768) return null;
|
||||
return ParseTsv(stdout);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
try { process.Kill(entireProcessTree: true); } catch (InvalidOperationException) { }
|
||||
if (ct.IsCancellationRequested) throw;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or IOException or
|
||||
UnauthorizedAccessException or InvalidOperationException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { File.Delete(tempFile); } catch (IOException) { }
|
||||
}
|
||||
}
|
||||
|
||||
public static Application.Services.PlateOcrResult? ParseTsv(string tsv)
|
||||
{
|
||||
var text = new System.Text.StringBuilder();
|
||||
var confidenceSum = 0d;
|
||||
var words = 0;
|
||||
foreach (var line in tsv.Split('\n').Skip(1))
|
||||
{
|
||||
var fields = line.TrimEnd('\r').Split('\t');
|
||||
if (fields.Length < 12 || !double.TryParse(fields[10], NumberStyles.Float,
|
||||
CultureInfo.InvariantCulture, out var confidence) || !double.IsFinite(confidence) || confidence < 0 || string.IsNullOrWhiteSpace(fields[11]))
|
||||
continue;
|
||||
var token = new string(fields[11].Where(c => char.IsAsciiLetterOrDigit(c) || c == '-').ToArray());
|
||||
if (token.Length == 0) continue;
|
||||
if (text.Length > 0) text.Append(' ');
|
||||
text.Append(token.ToUpperInvariant());
|
||||
confidenceSum += Math.Clamp(confidence / 100d, 0, 1);
|
||||
words++;
|
||||
}
|
||||
return words == 0 ? null : new Application.Services.PlateOcrResult(text.ToString(), confidenceSum / words);
|
||||
}
|
||||
|
||||
public static bool IsSafeImage(ReadOnlySpan<byte> image, int maxBytes = 512 * 1024) =>
|
||||
image.Length is >= 16 && image.Length <= maxBytes &&
|
||||
PlateImageHeader.TryGetDimensions(image, out var width, out var height) &&
|
||||
width is >= 32 and <= 4096 && height is >= 16 and <= 4096 && (long)width * height <= 4_000_000;
|
||||
}
|
||||
|
||||
internal static class PlateImageHeader
|
||||
{
|
||||
public static bool TryGetDimensions(ReadOnlySpan<byte> data, out int width, out int height)
|
||||
{
|
||||
width = height = 0;
|
||||
if (data.Length >= 24 && data[..8].SequenceEqual(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }))
|
||||
{
|
||||
width = System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(data.Slice(16, 4));
|
||||
height = System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(data.Slice(20, 4));
|
||||
return width > 0 && height > 0;
|
||||
}
|
||||
|
||||
if (data.Length < 4 || data[0] != 0xff || data[1] != 0xd8) return false;
|
||||
var offset = 2;
|
||||
while (offset + 4 <= data.Length)
|
||||
{
|
||||
if (data[offset++] != 0xff) return false;
|
||||
while (offset < data.Length && data[offset] == 0xff) offset++;
|
||||
if (offset >= data.Length) return false;
|
||||
var marker = data[offset++];
|
||||
if (marker is 0xd8 or 0xd9 or 0x01 || marker is >= 0xd0 and <= 0xd7) continue;
|
||||
var segmentLength = System.Buffers.Binary.BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset, 2));
|
||||
if (segmentLength < 2 || offset + segmentLength > data.Length) return false;
|
||||
if (marker is >= 0xc0 and <= 0xc3 or >= 0xc5 and <= 0xc7 or >= 0xc9 and <= 0xcb or >= 0xcd and <= 0xcf)
|
||||
{
|
||||
if (segmentLength < 7) return false;
|
||||
height = System.Buffers.Binary.BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset + 3, 2));
|
||||
width = System.Buffers.Binary.BinaryPrimitives.ReadUInt16BigEndian(data.Slice(offset + 5, 2));
|
||||
return width > 0 && height > 0;
|
||||
}
|
||||
offset += segmentLength;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.Data;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Heimdall.Infrastructure.Storage;
|
||||
|
||||
/// <summary>Uses one PostgreSQL transaction advisory lock to make the global quota check atomic.</summary>
|
||||
public sealed class RecordingQuotaGuard(
|
||||
AppDbContext db,
|
||||
IOptions<RecordingStorageQuotaOptions> options) : IRecordingQuotaGuard
|
||||
{
|
||||
private const long QuotaLockKey = 0x4845494D44525155;
|
||||
|
||||
public long MaxStorageBytes => options.Value.MaxBytes;
|
||||
|
||||
public async Task<IRecordingQuotaLease> AcquireAsync(CancellationToken ct = default)
|
||||
{
|
||||
var transaction = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct)
|
||||
.ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
// EF Core exception: PostgreSQL transaction advisory locks have no portable LINQ equivalent.
|
||||
// The lock serializes only the short metadata/quota check, after object upload has completed.
|
||||
await db.Database.ExecuteSqlInterpolatedAsync(
|
||||
$"SELECT pg_advisory_xact_lock({QuotaLockKey})", ct).ConfigureAwait(false);
|
||||
return new TransactionLease(transaction);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await transaction.DisposeAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class TransactionLease(IDbContextTransaction transaction) : IRecordingQuotaLease
|
||||
{
|
||||
public Task CommitAsync(CancellationToken ct = default) => transaction.CommitAsync(ct);
|
||||
public ValueTask DisposeAsync() => transaction.DisposeAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Heimdall.Infrastructure.Storage;
|
||||
|
||||
/// <summary>Central-wide cap for bytes stored as camera recordings.</summary>
|
||||
public sealed class RecordingStorageQuotaOptions
|
||||
{
|
||||
public const string SectionName = "Recordings:StorageQuota";
|
||||
|
||||
/// <summary>Maximum persisted recording bytes; defaults to 1 TiB.</summary>
|
||||
[Range(1, long.MaxValue)]
|
||||
public long MaxBytes { get; set; } = 1L << 40;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("Heimdall.Agent.Tests")]
|
||||
@@ -289,6 +289,21 @@ public sealed class MdnsClient : IMdnsClient, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
internal static IReadOnlyList<MdnsDiscoveredDevice> ParseMulticastResponses(IEnumerable<byte[]> packets)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(packets);
|
||||
var replies = new List<MdnsReply>();
|
||||
foreach (var packet in packets)
|
||||
{
|
||||
if (packet is not null)
|
||||
replies.AddRange(ParsePacket(packet));
|
||||
}
|
||||
|
||||
return BuildDevices(replies)
|
||||
.Where(device => device.HomeKitInfo?.Category is 17 or 18)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
private static List<MdnsReply> ParsePacket(byte[] data)
|
||||
{
|
||||
var replies = new List<MdnsReply>();
|
||||
@@ -453,7 +468,6 @@ public sealed class MdnsClient : IMdnsClient, IDisposable
|
||||
// target host, then any A record seen (best effort).
|
||||
var ip = info.Ips.FirstOrDefault()
|
||||
?? (info.SrvTarget is not null && addressByHost.TryGetValue(info.SrvTarget, out var srvIp) ? srvIp : null)
|
||||
?? addressByHost.Values.FirstOrDefault()
|
||||
?? "";
|
||||
|
||||
if (string.IsNullOrEmpty(ip) || !seenIps.Add(ip))
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
@inject ISnackbar Snackbar
|
||||
@inject NavigationManager Nav
|
||||
@inject UiText Text
|
||||
@using Microsoft.AspNetCore.Components.Forms
|
||||
@inject UiLanguageService Language
|
||||
@inject IJSRuntime JS
|
||||
@implements IAsyncDisposable
|
||||
@@ -199,6 +200,20 @@ else
|
||||
<MudText Class="mb-6" Typo="Typo.body2" Color="Color.Secondary">@Text["CameraDetail_NoRecordings"]</MudText>
|
||||
}
|
||||
|
||||
<MudPaper Elevation="1" Class="pa-5 mb-6" Style="border-radius: var(--hmd-radius-md);">
|
||||
<MudText Typo="Typo.h6" Class="mb-2">@Text["CameraDetail_PlateOcrTitle"]</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-3">@Text["CameraDetail_PlateOcrPrivacy"]</MudText>
|
||||
<InputFile OnChange="RecognizePlateCropAsync" accept="image/jpeg,image/png" disabled="@_recognizingPlate" />
|
||||
@if (_recognizingPlate)
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" Size="Size.Small" Class="ml-2" />
|
||||
}
|
||||
@if (!string.IsNullOrEmpty(_plateOcrMessage))
|
||||
{
|
||||
<MudAlert Severity="@(_plateOcrSuccess ? Severity.Success : Severity.Error)" Class="mt-3">@_plateOcrMessage</MudAlert>
|
||||
}
|
||||
</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"]
|
||||
@@ -285,6 +300,9 @@ else
|
||||
private bool _togglingStatus;
|
||||
private bool _showRtsp;
|
||||
private bool _confirmDeleteShow;
|
||||
private bool _recognizingPlate;
|
||||
private bool _plateOcrSuccess;
|
||||
private string? _plateOcrMessage;
|
||||
|
||||
private List<EventItem>? _events;
|
||||
private List<RecordingItem> _recordings = [];
|
||||
@@ -350,6 +368,33 @@ else
|
||||
finally { _eventsLoading = false; }
|
||||
}
|
||||
|
||||
private async Task RecognizePlateCropAsync(InputFileChangeEventArgs args)
|
||||
{
|
||||
var file = args.File;
|
||||
if (file.Size is < 16 or > 512 * 1024 || file.ContentType is not ("image/jpeg" or "image/png"))
|
||||
{
|
||||
_plateOcrSuccess = false;
|
||||
_plateOcrMessage = Text["CameraDetail_PlateOcrInvalid"];
|
||||
return;
|
||||
}
|
||||
|
||||
_recognizingPlate = true;
|
||||
_plateOcrMessage = null;
|
||||
try
|
||||
{
|
||||
await using var stream = file.OpenReadStream(512 * 1024);
|
||||
var response = await Api.RecognizePlateCropAsync(Id, stream, file.ContentType, file.Name);
|
||||
_plateOcrSuccess = response.Succeeded;
|
||||
_plateOcrMessage = response.Succeeded && response.Data is not null
|
||||
? string.Format(Language.Culture, Text["CameraDetail_PlateOcrResult"], response.Data.PlateText,
|
||||
(response.Data.Confidence * 100).ToString("0", Language.Culture))
|
||||
: response.ErrorMessage ?? Text["CameraDetail_OperationFailed"];
|
||||
if (response.Succeeded) await LoadEventsAsync();
|
||||
}
|
||||
catch { _plateOcrSuccess = false; _plateOcrMessage = Text["CameraDetail_OperationFailed"]; }
|
||||
finally { _recognizingPlate = false; }
|
||||
}
|
||||
|
||||
private async Task LoadRecordingsAsync()
|
||||
{
|
||||
_recordingsLoading = true;
|
||||
@@ -531,6 +576,7 @@ else
|
||||
"PersonDetected" => Text["CameraDetail_EventPerson"],
|
||||
"VehicleDetected" => Text["CameraDetail_EventVehicle"],
|
||||
"FaceRecognized" => Text["CameraDetail_EventFace"],
|
||||
"LicensePlateDetected" => Text["LicensePlateDetected"],
|
||||
"CameraOffline" => Text["CameraDetail_StatusOffline"],
|
||||
_ => type
|
||||
};
|
||||
@@ -541,6 +587,7 @@ else
|
||||
"PersonDetected" => Color.Error,
|
||||
"VehicleDetected" => Color.Info,
|
||||
"FaceRecognized" => Color.Success,
|
||||
"LicensePlateDetected" => Color.Info,
|
||||
_ => Color.Default
|
||||
};
|
||||
|
||||
|
||||
@@ -242,6 +242,7 @@ else
|
||||
"PersonDetected" => Text["EventsPage_Person"],
|
||||
"VehicleDetected" => Text["EventsPage_Vehicle"],
|
||||
"FaceRecognized" => Text["EventsPage_Face"],
|
||||
"LicensePlateDetected" => Text["LicensePlateDetected"],
|
||||
"CameraOffline" => Text["EventsPage_Offline"],
|
||||
_ => type
|
||||
};
|
||||
@@ -252,6 +253,7 @@ else
|
||||
"PersonDetected" => Color.Error,
|
||||
"VehicleDetected" => Color.Info,
|
||||
"FaceRecognized" => Color.Success,
|
||||
"LicensePlateDetected" => Color.Info,
|
||||
_ => Color.Default
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Api.Security;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Heimdall.Infrastructure.Services;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Heimdall.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/cameras/{cameraId:guid}/plate-recognition")]
|
||||
[EnableRateLimiting("Api")]
|
||||
public sealed class PlateRecognitionController(
|
||||
ResourceAccess access,
|
||||
ILicensePlateRecognitionService recognition,
|
||||
IOptionsMonitor<PlateOcrOptions> options) : ControllerBase
|
||||
{
|
||||
private const int MaxCropBytes = 512 * 1024;
|
||||
|
||||
/// <summary>Processes a user-selected plate crop locally; image bytes are discarded after OCR.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpPost]
|
||||
[RequestSizeLimit(MaxCropBytes + 16 * 1024)]
|
||||
[Consumes("multipart/form-data")]
|
||||
public async Task<IActionResult> Recognize(Guid cameraId, IFormFile? image, CancellationToken ct)
|
||||
{
|
||||
if (!options.CurrentValue.Enabled) return StatusCode(503, new { error = "Local plate OCR is disabled" });
|
||||
var requester = await access.ResolveAsync(User, ct);
|
||||
if (requester is null || requester.Kind != RequesterKind.Human ||
|
||||
!await access.CameraAsync(requester, cameraId, ct)) return Forbid();
|
||||
if (image is null || image.Length is < 16 or > MaxCropBytes || image.Length > options.CurrentValue.MaxImageBytes ||
|
||||
image.ContentType is not ("image/jpeg" or "image/png"))
|
||||
return BadRequest(new { error = "Provide a JPEG or PNG plate crop up to 512 KiB" });
|
||||
|
||||
await using var input = image.OpenReadStream();
|
||||
using var buffer = new MemoryStream((int)image.Length);
|
||||
await input.CopyToAsync(buffer, ct);
|
||||
var bytes = buffer.ToArray();
|
||||
var png = bytes.AsSpan().StartsWith(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 });
|
||||
var jpeg = bytes.AsSpan().StartsWith(new byte[] { 255, 216, 255 });
|
||||
if (!png && !jpeg) return BadRequest(new { error = "Image content does not match JPEG or PNG" });
|
||||
|
||||
var result = await recognition.RecognizeAsync(cameraId, bytes, ct);
|
||||
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 422, new { error = result.Error });
|
||||
}
|
||||
}
|
||||
@@ -4109,4 +4109,8 @@
|
||||
<data name="CameraDetail_WatchLive" xml:space="preserve"><value>Watch live</value></data>
|
||||
<data name="CameraDetail_StopLive" xml:space="preserve"><value>Stop live</value></data>
|
||||
<data name="CameraDetail_LiveUnavailable" xml:space="preserve"><value>Live view is unavailable. Check the media service and camera access.</value></data>
|
||||
<data name="CameraDetail_PlateOcrTitle" xml:space="preserve"><value>Local plate reading (manual action)</value></data>
|
||||
<data name="CameraDetail_PlateOcrPrivacy" xml:space="preserve"><value>Select a JPEG/PNG crop of the plate. The image is processed on this Heimdall server and deleted afterward; only the plate observation and history event are stored. Enable the feature in configuration first.</value></data>
|
||||
<data name="CameraDetail_PlateOcrInvalid" xml:space="preserve"><value>Select a JPEG or PNG crop no larger than 512 KiB.</value></data>
|
||||
<data name="CameraDetail_PlateOcrResult" xml:space="preserve"><value>Plate {0} recognized with {1}% confidence; an event was added to history.</value></data>
|
||||
</root>
|
||||
@@ -4109,4 +4109,8 @@
|
||||
<data name="CameraDetail_WatchLive" xml:space="preserve"><value>Voir en direct</value></data>
|
||||
<data name="CameraDetail_StopLive" xml:space="preserve"><value>Arrêter le direct</value></data>
|
||||
<data name="CameraDetail_LiveUnavailable" xml:space="preserve"><value>Le direct est indisponible. Vérifiez le service média et les droits caméra.</value></data>
|
||||
<data name="CameraDetail_PlateOcrTitle" xml:space="preserve"><value>Lecture de plaque locale (action manuelle)</value></data>
|
||||
<data name="CameraDetail_PlateOcrPrivacy" xml:space="preserve"><value>Sélectionnez un recadrage JPEG/PNG de la plaque. L’image est traitée sur ce serveur Heimdall puis supprimée; seule la plaque reconnue et son événement d’historique sont conservés. Activez d’abord la fonction dans la configuration.</value></data>
|
||||
<data name="CameraDetail_PlateOcrInvalid" xml:space="preserve"><value>Sélectionnez un recadrage JPEG ou PNG de 512 Kio maximum.</value></data>
|
||||
<data name="CameraDetail_PlateOcrResult" xml:space="preserve"><value>Plaque {0} reconnue avec une confiance de {1} %; un événement a été ajouté à l’historique.</value></data>
|
||||
</root>
|
||||
@@ -4109,4 +4109,8 @@
|
||||
<data name="CameraDetail_WatchLive" xml:space="preserve"><value>Watch live</value></data>
|
||||
<data name="CameraDetail_StopLive" xml:space="preserve"><value>Stop live</value></data>
|
||||
<data name="CameraDetail_LiveUnavailable" xml:space="preserve"><value>Live view is unavailable. Check the media service and camera access.</value></data>
|
||||
<data name="CameraDetail_PlateOcrTitle" xml:space="preserve"><value>Lecture de plaque locale (action manuelle)</value></data>
|
||||
<data name="CameraDetail_PlateOcrPrivacy" xml:space="preserve"><value>Sélectionnez un recadrage JPEG/PNG de la plaque. L’image est traitée sur ce serveur Heimdall puis supprimée; seule la plaque reconnue et son événement d’historique sont conservés. Activez d’abord la fonction dans la configuration.</value></data>
|
||||
<data name="CameraDetail_PlateOcrInvalid" xml:space="preserve"><value>Sélectionnez un recadrage JPEG ou PNG de 512 Kio maximum.</value></data>
|
||||
<data name="CameraDetail_PlateOcrResult" xml:space="preserve"><value>Plaque {0} reconnue avec une confiance de {1} %; un événement a été ajouté à l’historique.</value></data>
|
||||
</root>
|
||||
@@ -3,6 +3,7 @@ using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Application.Services;
|
||||
|
||||
namespace Heimdall.Web.Services;
|
||||
|
||||
@@ -514,6 +515,22 @@ public class HeimdallApiClient : IDisposable
|
||||
return await client.GetFromJsonAsync<CameraItem>($"api/cameras/{id}", Json);
|
||||
}
|
||||
|
||||
public async Task<ApiResult<LicensePlateRecognitionResponse>> RecognizePlateCropAsync(
|
||||
Guid cameraId, Stream image, string contentType, string fileName, CancellationToken ct = default)
|
||||
{
|
||||
using var content = new MultipartFormDataContent();
|
||||
using var imageContent = new StreamContent(image);
|
||||
imageContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
|
||||
content.Add(imageContent, "image", Path.GetFileName(fileName));
|
||||
using var response = await CreateClient().PostAsync($"api/cameras/{cameraId:D}/plate-recognition", content, ct);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
return ApiResult<LicensePlateRecognitionResponse>.Failure(await ReadErrorMessageAsync(response));
|
||||
var result = await response.Content.ReadFromJsonAsync<LicensePlateRecognitionResponse>(Json, ct);
|
||||
return result is null
|
||||
? ApiResult<LicensePlateRecognitionResponse>.Failure(InvalidServerResponse)
|
||||
: ApiResult<LicensePlateRecognitionResponse>.Success(result);
|
||||
}
|
||||
|
||||
public async Task<PagedData<RecordingItem>?> GetCameraRecordingsAsync(Guid id, int page = 1, int pageSize = 20)
|
||||
{
|
||||
var client = CreateClient();
|
||||
|
||||
@@ -36,8 +36,8 @@ export async function stop(cameraId) {
|
||||
const s = active.get(cameraId);
|
||||
if (!s) return;
|
||||
active.delete(cameraId);
|
||||
s.pc.close();
|
||||
if (s.resource) { try { await fetch(s.resource, { method: "DELETE", headers: { Authorization: `Bearer ${s.token}` } }); } catch { } }
|
||||
s.pc.close();
|
||||
try { await fetch(`/api/live-media/cameras/${cameraId}/session/${s.sessionId}`, { method: "DELETE", credentials: "same-origin" }); } catch { }
|
||||
const v = document.querySelector(`[data-live-camera="${cameraId}"]`);
|
||||
if (v) v.srcObject = null;
|
||||
|
||||
Reference in new issue
Block a user