- Add mobile-app.md: Android Avalonia UI app spec with 6 pages, WebRTC via WebView bridge, SignalR real-time, offline cache, push notifications - Add auth-roles.md: 2 user types (Admin + User), site-scoped permissions, policy-based authorization, UI visibility per role - Add notifications.md: Email SMTP (FluentEmail), Gotify push, Scriban Markdown templates i18n editable from UI, per-user config - Add hangfire-usage.md: Central PostgreSQL jobs (retention, cleanup, digests) + Agent InMemory jobs (heartbeat, camera health, GPU watchdog) - Add signalr-usage.md: 5 hubs (events, streaming, monitoring, notifications, admin) with full hub code, group management, Agent SignalR connection - Update implementation.md: 23 phases with mobile app (phase 21) - Update specs.md: reference all new documentation files
884 lines
24 KiB
Markdown
884 lines
24 KiB
Markdown
# Heimdall — Plan d'implémentation
|
|
|
|
**Principe :** On implémente d'abord le **plus simple et le plus important**.
|
|
La **vidéo live** arrive en dernier dans l'IHM.
|
|
|
|
```
|
|
Phase 1 : Solution .NET 10 + Clean Architecture
|
|
Phase 2 : Tests Framework
|
|
Phase 3 : CI/CD DockerHub
|
|
Phase 4 : Domain Model
|
|
Phase 5 : Application Layer (CQRS)
|
|
Phase 6 : Security — mini identification
|
|
Phase 7 : API — Sites + Agent Tokens
|
|
Phase 8 : Agent — Registration + Heartbeat
|
|
Phase 9 : ONVIF Discovery
|
|
Phase 10 : Camera Management API
|
|
Phase 11 : Video Pipeline (FFmpeg)
|
|
Phase 12 : AI Pipeline (pré-détection Agent + CodeProject.AI)
|
|
Phase 13 : Storage (MinIO/S3)
|
|
Phase 14 : SignalR Hubs (real-time : events, monitoring, notifications)
|
|
Phase 15 : Hangfire Central (PostgreSQL storage + recurring jobs)
|
|
Phase 16 : Hangfire Agent (InMemory, jobs volatiles : heartbeat, health)
|
|
Phase 17 : Notifications (Email SMTP + Gotify + templates Markdown i18n)
|
|
Phase 18 : Blazor UI — Auth + Sites + Caméras (sans live)
|
|
Phase 19 : WebRTC Streaming (Agent → Browser via SIPSorcery + SignalR)
|
|
Phase 20 : Blazor UI — Live Vidéo
|
|
Phase 21 : Application Mobile Android (Avalonia UI)
|
|
Phase 22 : Dashboard KPI
|
|
Phase 23 : Production Hardening
|
|
```
|
|
|
|
---
|
|
|
|
# Phase 1 — Solution .NET 10 + Clean Architecture
|
|
|
|
## Objectif
|
|
|
|
Créer le socle technique stable : solution .NET 10 avec Clean Architecture.
|
|
|
|
## Arborescence
|
|
|
|
```
|
|
Heimdall/
|
|
├── src/
|
|
│ ├── Heimdall.Domain # Entities, Value Objects, Enums
|
|
│ ├── Heimdall.Domain.Primitives # Base types (Entity<TId>, ValueObject)
|
|
│ ├── Heimdall.Contracts # Shared DTOs, Constants
|
|
│ ├── Heimdall.Application # CQRS, Interfaces, Validators
|
|
│ ├── Heimdall.Infrastructure # EF Core, PostgreSQL, Identity, S3
|
|
│ ├── Heimdall.Api # REST API + SignalR hubs
|
|
│ ├── Heimdall.Web # Blazor Web App (MudBlazor)
|
|
│ ├── Heimdall.Agent # Worker Service (SIPSorcery, FFmpeg)
|
|
│ └── Heimdall.Workers # Hangfire background jobs
|
|
├── tests/
|
|
│ ├── Heimdall.Domain.Tests
|
|
│ ├── Heimdall.Application.Tests
|
|
│ ├── Heimdall.Infrastructure.Tests
|
|
│ ├── Heimdall.Api.Tests
|
|
│ ├── Heimdall.Agent.Tests
|
|
│ ├── Heimdall.Web.Tests # bUnit
|
|
│ ├── Heimdall.Workers.Tests
|
|
│ └── Heimdall.IntegrationTests # Testcontainers
|
|
├── docker/
|
|
├── docs/
|
|
└── .github/workflows/
|
|
```
|
|
|
|
## Dépendances entre projets
|
|
|
|
```
|
|
Domain (aucune dépendance)
|
|
↑
|
|
Application (ref Domain) — MediatR, FluentValidation
|
|
↑
|
|
Infrastructure (ref Application) — EF Core, Npgsql, Identity
|
|
↑
|
|
┌───┴───┐
|
|
Api Web (Blazor)
|
|
├── ── ┘
|
|
Agent (ref Application, Infrastructure) — Worker Service
|
|
Workers (ref Application, Infrastructure) — Hangfire jobs
|
|
```
|
|
|
|
## Directory.Build.props
|
|
|
|
```xml
|
|
<TargetFramework>net10.0</TargetFramework>
|
|
<ImplicitUsings>enable</ImplicitUsings>
|
|
<Nullable>enable</Nullable>
|
|
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
|
<AnalysisLevel>latest-Recommended</AnalysisLevel>
|
|
```
|
|
|
|
Build : `dotnet build` doit passer 0 error.
|
|
|
|
---
|
|
|
|
# Phase 2 — Framework de tests
|
|
|
|
## Objectif
|
|
|
|
Avoir les tests avant le métier (TDD).
|
|
|
|
## Stack
|
|
|
|
| Outil | Usage |
|
|
|---|---|
|
|
| **xUnit** | Framework de tests |
|
|
| **Shouldly** | Assertions fluides |
|
|
| **NSubstitute** | Mocking |
|
|
| **Testcontainers** | PostgreSQL en integration |
|
|
| **bUnit** | Tests composants Blazor |
|
|
|
|
## Projets de test
|
|
|
|
Un par projet source, nommage :
|
|
|
|
```
|
|
Heimdall.X.Tests
|
|
```
|
|
|
|
## Tests d'exemple (Domain)
|
|
|
|
```csharp
|
|
[Fact]
|
|
public void Camera_should_start_disabled()
|
|
{
|
|
var camera = new Camera("Entrée", "192.168.1.100");
|
|
camera.Status.ShouldBe(CameraStatus.Disabled);
|
|
}
|
|
```
|
|
|
|
Faire passer le test AVANT d'écrire le code (TDD).
|
|
|
|
---
|
|
|
|
# Phase 3 — CI/CD DockerHub
|
|
|
|
## Objectif
|
|
|
|
Chaque commit build et push les images Docker.
|
|
|
|
## Pipeline
|
|
|
|
```yaml
|
|
push → restore → build → unit tests → coverage → docker build → docker push
|
|
```
|
|
|
|
## Images
|
|
|
|
```
|
|
heimdall/api:latest, heimdall/api:{sha}
|
|
heimdall/web:latest, heimdall/web:{sha}
|
|
heimdall/agent:latest, heimdall/agent:{sha}
|
|
```
|
|
|
|
## Quality gates
|
|
|
|
- Build OK (0 errors, 0 warnings)
|
|
- Tests OK
|
|
- Coverage ≥ 80% (Domain, Application)
|
|
- SonarQube optionnel
|
|
|
|
---
|
|
|
|
# Phase 4 — Domain Model
|
|
|
|
## Objectif
|
|
|
|
Toutes les entités métier, énumérations, value objects.
|
|
|
|
## Entités (ordre de création)
|
|
|
|
```text
|
|
1. Site
|
|
2. Agent
|
|
3. Camera
|
|
4. Person
|
|
5. Vehicle
|
|
6. LicensePlate
|
|
7. Event
|
|
8. Recording
|
|
9. StoragePolicy
|
|
10. ApiKey
|
|
```
|
|
|
|
## Enumérations
|
|
|
|
```csharp
|
|
CameraStatus { Unknown, Online, Offline, Disabled, Error }
|
|
EventType { MotionDetected, PersonDetected, VehicleDetected,
|
|
UnknownPerson, FaceRecognized, LicensePlateDetected,
|
|
CameraOffline, CameraOnline }
|
|
StorageProvider { Local, S3 }
|
|
AgentStatus { Online, Offline, Error }
|
|
GpuAcceleration { None, NvidiaCuda, IntelQuickSync, Vaapi }
|
|
ThemeMode { Light, Dark, Auto }
|
|
```
|
|
|
|
## Exemple TDD
|
|
|
|
```csharp
|
|
// 1. Test
|
|
[Fact]
|
|
public void Site_should_generate_registration_token_on_create()
|
|
{
|
|
var site = new Site("Entrepôt A");
|
|
site.RegistrationToken.ShouldNotBeNull();
|
|
site.RegistrationToken.ShouldBeOfType<string>();
|
|
site.TokenExpiresAt.ShouldBeGreaterThan(DateTime.UtcNow);
|
|
}
|
|
|
|
// 2. Implémentation
|
|
public class Site
|
|
{
|
|
public Guid Id { get; private set; }
|
|
public string Name { get; private set; }
|
|
public string RegistrationToken { get; private set; }
|
|
public DateTime? TokenExpiresAt { get; private set; }
|
|
|
|
public Site(string name)
|
|
{
|
|
Id = Guid.NewGuid();
|
|
Name = name;
|
|
RegistrationToken = GenerateToken();
|
|
TokenExpiresAt = DateTime.UtcNow.AddDays(1);
|
|
}
|
|
|
|
private static string GenerateToken() => Guid.NewGuid().ToString("N");
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
# Phase 5 — Application Layer (CQRS)
|
|
|
|
## Objectif
|
|
|
|
Toutes les commandes, queries, DTOs, validateurs, interfaces.
|
|
|
|
## Structure par feature
|
|
|
|
```
|
|
Application/
|
|
├── Sites/
|
|
│ ├── CreateSite/
|
|
│ │ ├── CreateSiteCommand.cs
|
|
│ │ ├── CreateSiteCommandHandler.cs
|
|
│ │ ├── CreateSiteCommandValidator.cs
|
|
│ │ └── CreateSiteResponse.cs
|
|
│ ├── GetSite/
|
|
│ │ ├── GetSiteQuery.cs
|
|
│ │ └── GetSiteQueryHandler.cs
|
|
│ └── GenerateToken/
|
|
│ ├── GenerateSiteTokenCommand.cs
|
|
│ └── GenerateSiteTokenCommandHandler.cs
|
|
├── Agents/
|
|
│ ├── RegisterAgent/
|
|
│ │ ├── RegisterAgentCommand.cs
|
|
│ │ ├── RegisterAgentCommandHandler.cs
|
|
│ │ └── RegisterAgentCommandValidator.cs
|
|
│ ├── AgentHeartbeat/
|
|
│ │ ├── AgentHeartbeatCommand.cs
|
|
│ │ └── AgentHeartbeatCommandHandler.cs
|
|
│ └── GetSiteAgents/
|
|
│ └── GetSiteAgentsQuery.cs
|
|
├── Cameras/
|
|
│ ├── CreateCamera/
|
|
│ ├── UpdateCamera/
|
|
│ └── GetCamera/
|
|
├── Events/
|
|
├── Persons/
|
|
├── Vehicles/
|
|
├── Common/
|
|
│ ├── Interfaces/
|
|
│ │ ├── ISiteRepository.cs
|
|
│ │ ├── IAgentRepository.cs
|
|
│ │ ├── ICameraRepository.cs
|
|
│ │ └── IUnitOfWork.cs
|
|
│ └── DTOs/
|
|
│ ├── PagedResult.cs
|
|
│ └── ValidationError.cs
|
|
└── DependencyInjection.cs
|
|
```
|
|
|
|
## Règles
|
|
|
|
| Règle | Description |
|
|
|---|---|
|
|
| **Command** = action (Create, Update, Delete) | Retourne un Id ou un Result |
|
|
| **Query** = lecture (Get, List) | Retourne un DTO |
|
|
| **Validator** = FluentValidation | Valide TOUT avant le handler |
|
|
| **Interface** = dans Application | Implémentation dans Infrastructure |
|
|
| **DTO** = immutable records | `record CreateSiteResponse(Guid Id, string Token)` |
|
|
|
|
---
|
|
|
|
# Phase 6 — Security (mini identification)
|
|
|
|
## Objectif
|
|
|
|
Authentification minimale AVANT d'exposer l'API (sécurité critique).
|
|
|
|
## Ce qu'on implémente
|
|
|
|
| Fonctionnalité | Priorité |
|
|
|---|---|
|
|
| ASP.NET Core Identity | 🔴 Requis |
|
|
| JWT Bearer tokens | 🔴 Requis |
|
|
| Refresh tokens | 🟠 Important |
|
|
| Rôles (Admin, Superviseur, Viewer) | 🟠 Important |
|
|
| Permissions (Camera.Read, etc.) | 🔴 Requis |
|
|
| API Keys (hash SHA256) | 🔴 Requis |
|
|
| API Key middleware | 🔴 Requis |
|
|
|
|
## Tests
|
|
|
|
```
|
|
User can register with email + password
|
|
User can login and receive JWT token
|
|
JWT token is validated on protected endpoints
|
|
User without permission receives 403
|
|
API key authentication works
|
|
API key with wrong key returns 401
|
|
Expired API key returns 401
|
|
```
|
|
|
|
## Endpoints d'auth
|
|
|
|
| Méthode | Route | Auth | Description |
|
|
|---|---|---|---|
|
|
| `POST` | `/api/auth/register` | — | Créer un compte |
|
|
| `POST` | `/api/auth/login` | — | Obtenir JWT |
|
|
| `POST` | `/api/auth/refresh` | — | Rafraîchir JWT |
|
|
| `POST` | `/api/api-keys` | JWT | Générer une clé API |
|
|
| `GET` | `/api/api-keys` | JWT | Lister les clés |
|
|
| `DELETE` | `/api/api-keys/{id}` | JWT | Révoquer une clé |
|
|
|
|
**Tous les endpoints API suivants sont protégés** (JWT ou API Key).
|
|
|
|
---
|
|
|
|
# Phase 7 — API : Sites + Agent Tokens
|
|
|
|
## Objectif
|
|
|
|
Permettre de créer un Site et de générer un token d'enregistrement Agent.
|
|
C'est le point de départ : sans Site, rien n'existe.
|
|
|
|
## Endpoints
|
|
|
|
| Méthode | Route | Auth | Description |
|
|
|---|---|---|---|
|
|
| `POST` | `/api/sites` | JWT/Admin | Créer un site |
|
|
| `GET` | `/api/sites` | JWT | Lister les sites |
|
|
| `GET` | `/api/sites/{id}` | JWT | Détail site |
|
|
| `PUT` | `/api/sites/{id}` | JWT/Admin | Modifier site |
|
|
| `DELETE` | `/api/sites/{id}` | JWT/Admin | Supprimer site |
|
|
| `POST` | `/api/sites/{id}/tokens` | JWT/Admin | Générer token Agent |
|
|
| `GET` | `/api/sites/{id}/tokens` | JWT/Admin | Lister tokens actifs |
|
|
| `DELETE` | `/api/sites/{id}/tokens/{tokenId}` | JWT/Admin | Révoquer token |
|
|
|
|
## Tests
|
|
|
|
```
|
|
Admin can create site
|
|
Non-admin cannot create site (403)
|
|
Creating site generates registration token
|
|
Token is returned once and hashed in DB
|
|
Token expiry is set to 24h by default
|
|
Revoked token cannot be used
|
|
```
|
|
|
|
## Création d'un Site — séquence
|
|
|
|
```csharp
|
|
// POST /api/sites
|
|
var command = new CreateSiteCommand("Entrepôt A", "Paris", "Europe/Paris");
|
|
var result = await mediator.Send(command);
|
|
|
|
// Résultat :
|
|
{
|
|
"id": "guid-...",
|
|
"name": "Entrepôt A",
|
|
"registrationToken": "a1b2c3d4-...", // ← affiché 1 seule fois
|
|
"tokenExpiresAt": "2026-07-17T19:00:00Z",
|
|
"dockerCommand": "docker run -e HEIMDALL_CENTRAL_URL=... -e HEIMDALL_SITE_TOKEN=a1b2c3d4-... heimdall/agent:latest"
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
# Phase 8 — Agent : Registration + Heartbeat
|
|
|
|
## Objectif
|
|
|
|
L'Agent s'enregistre auprès du Central avec son token Site,
|
|
puis envoie son heartbeat périodiquement.
|
|
|
|
## Tests Agent (côté Central)
|
|
|
|
```
|
|
Agent can register with valid site token
|
|
Agent registration with invalid token returns 401
|
|
Agent registration with expired token returns 401
|
|
Duplicate registration returns 409 (token already used)
|
|
Agent heartbeat updates LastHeartbeat timestamp
|
|
Agent is marked Offline after 90s without heartbeat
|
|
Agents are listed per site
|
|
```
|
|
|
|
## Endpoints (Central)
|
|
|
|
| Méthode | Route | Auth | Description |
|
|
|---|---|---|---|
|
|
| `POST` | `/api/agents/register` | Token | Enregistrer Agent |
|
|
| `POST` | `/api/agents/{id}/heartbeat` | API Key | Heartbeat |
|
|
| `GET` | `/api/agents/{id}` | JWT | Détail Agent |
|
|
| `GET` | `/api/sites/{id}/agents` | JWT | Liste Agents du site |
|
|
|
|
## Côté Agent (Worker Service)
|
|
|
|
```csharp
|
|
public class AgentRegistrationService : BackgroundService
|
|
{
|
|
private readonly string _centralUrl;
|
|
private readonly string _siteToken;
|
|
private readonly string _hostname;
|
|
private Guid? _agentId;
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken ct)
|
|
{
|
|
// 1. Register
|
|
var (agentId, iceServers) = await RegisterAsync(ct);
|
|
|
|
// 2. Start heartbeat loop
|
|
while (!ct.IsCancellationRequested)
|
|
{
|
|
await SendHeartbeatAsync(agentId, ct);
|
|
await Task.Delay(TimeSpan.FromSeconds(30), ct);
|
|
}
|
|
}
|
|
|
|
private async Task<Guid> RegisterAsync(CancellationToken ct)
|
|
{
|
|
using var http = new HttpClient();
|
|
http.BaseAddress = new Uri(_centralUrl);
|
|
|
|
var response = await http.PostAsJsonAsync("/api/agents/register", new
|
|
{
|
|
token = _siteToken,
|
|
hostname = _hostname,
|
|
version = "1.0.0"
|
|
}, ct);
|
|
|
|
response.EnsureSuccessStatusCode();
|
|
var result = await response.Content.ReadFromJsonAsync<RegisterResponse>(ct);
|
|
return result!.AgentId;
|
|
}
|
|
}
|
|
```
|
|
|
|
## Variables d'environnement Agent
|
|
|
|
```
|
|
HEIMDALL_CENTRAL_URL=https://central.heimdall.example.com
|
|
HEIMDALL_SITE_TOKEN=a1b2c3d4-...
|
|
HEIMDALL_AGENT_NAME=entrepot-a # optionnel
|
|
```
|
|
|
|
---
|
|
|
|
# Phase 9 — ONVIF Discovery
|
|
|
|
## Objectif
|
|
|
|
L'Agent découvre les caméras sur le réseau local via ONVIF WS-Discovery.
|
|
|
|
## Fonctionnalités
|
|
|
|
- Découverte multicast WS-Discovery
|
|
- Identification fabricant + modèle + firmware
|
|
- Détection URL RTSP + snapshot
|
|
- Détection capacités PTZ
|
|
- Fallback discovery manuelle (IP fixe)
|
|
|
|
## Tests
|
|
|
|
```
|
|
Agent discovers cameras on same subnet
|
|
Agent rejects invalid ONVIF credentials
|
|
Agent detects camera manufacturer and model
|
|
Agent discovers RTSP URL
|
|
Manual discovery works with IP + port
|
|
Discovery does not discover non-ONVIF devices
|
|
```
|
|
|
|
## Architecture
|
|
|
|
```csharp
|
|
public interface IOnvifDiscoveryService
|
|
{
|
|
Task<IReadOnlyList<DiscoveredCamera>> DiscoverAsync(
|
|
TimeSpan timeout, CancellationToken ct);
|
|
|
|
Task<DiscoveredCamera?> DiscoverByIpAsync(
|
|
string ip, int port, CancellationToken ct);
|
|
}
|
|
|
|
public record DiscoveredCamera(
|
|
string Host,
|
|
int Port,
|
|
string Manufacturer,
|
|
string Model,
|
|
string FirmwareVersion,
|
|
string RtspUrl,
|
|
string? SnapshotUrl,
|
|
bool HasPtz);
|
|
```
|
|
|
|
## Limites techniques
|
|
|
|
- WS-Discovery utilise **multicast UDP** → même VLAN uniquement
|
|
- Si caméras sur VLAN différent → discovery manuelle obligatoire
|
|
- Les caméras Imou nécessitent activation manuelle du RTSP
|
|
- Stocker les credentials ONVIF (optionnels, chiffrés avec IDataProtector)
|
|
|
|
---
|
|
|
|
# Phase 10 — Camera Management API
|
|
|
|
## Objectif
|
|
|
|
CRUD complet des caméras, liées à un Site et un Agent.
|
|
|
|
## Tests
|
|
|
|
```
|
|
Admin can add camera to site
|
|
Camera is created with Disabled status
|
|
Camera can be enabled/disabled
|
|
Camera can be assigned to an Agent
|
|
Camera list returns only cameras for user's site
|
|
Invalid RTSP URL is rejected
|
|
```
|
|
|
|
## Endpoints
|
|
|
|
| Méthode | Route | Auth | Description |
|
|
|---|---|---|---|
|
|
| `POST` | `/api/sites/{id}/cameras` | JWT/Admin | Ajouter caméra |
|
|
| `GET` | `/api/sites/{id}/cameras` | JWT | Lister caméras du site |
|
|
| `GET` | `/api/cameras/{id}` | JWT | Détail caméra |
|
|
| `PUT` | `/api/cameras/{id}` | JWT/Admin | Modifier caméra |
|
|
| `DELETE` | `/api/cameras/{id}` | JWT/Admin | Supprimer caméra |
|
|
| `POST` | `/api/cameras/{id}/test` | JWT | Tester connexion RTSP |
|
|
| `PATCH` | `/api/cameras/{id}/status` | API Key | Agent met à jour le statut |
|
|
|
|
---
|
|
|
|
# Phase 11 — Video Pipeline (FFmpeg)
|
|
|
|
## Objectif
|
|
|
|
L'Agent capture le flux RTSP et produit des segments vidéo + snapshots.
|
|
|
|
## Abstraction
|
|
|
|
```csharp
|
|
public interface IVideoCaptureService
|
|
{
|
|
Task StartAsync(Camera camera, CancellationToken ct);
|
|
Task StopAsync(Guid cameraId);
|
|
Task<byte[]> CaptureSnapshotAsync(Guid cameraId, CancellationToken ct);
|
|
}
|
|
```
|
|
|
|
## Pipeline
|
|
|
|
```text
|
|
Caméra RTSP
|
|
│
|
|
▼
|
|
FFmpeg process (démarré par l'Agent)
|
|
│
|
|
├── Encode H264 (GPU si dispo, sinon CPU)
|
|
├── Produit segments .ts (HLS, 5min)
|
|
├── Snapshots JPEG (200ms interval)
|
|
└── Détection GPU auto
|
|
```
|
|
|
|
## GPU auto-détection
|
|
|
|
```csharp
|
|
public enum GpuAcceleration { None, NvidiaCuda, IntelQuickSync, Vaapi }
|
|
|
|
// Détecté au démarrage de l'Agent
|
|
public GpuAcceleration DetectGpu()
|
|
{
|
|
if (File.Exists("/usr/bin/nvidia-smi")) return NvidiaCuda;
|
|
if (Directory.Exists("/dev/dri")) return DetectVaapiOrQsv();
|
|
return None;
|
|
}
|
|
```
|
|
|
|
## Capacités estimées (CPU Intel i5-10gen)
|
|
|
|
| Mode | 720p | 1080p | 4K |
|
|
|---|---|---|---|
|
|
| CPU (libx264 medium) | 8 flux | 4 flux | 1 flux |
|
|
| GPU (NVENC/QSV) | 20+ flux | 12+ flux | 4+ flux |
|
|
|
|
---
|
|
|
|
# Phase 12 — AI Pipeline
|
|
|
|
## Objectif
|
|
|
|
Détection d'objets, visages et plaques avec pré-détection CPU sur l'Agent
|
|
et IA lourde GPU sur le Central.
|
|
|
|
## Architecture two-tier
|
|
|
|
```text
|
|
AGENT (CPU léger)
|
|
──────────────
|
|
Snapshot JPEG
|
|
↓
|
|
YOLOv8 nano / MobileNet
|
|
├── Rien → ignore
|
|
├── Mouvement → snapshot baseline
|
|
└── Personne/Véhicule → alerte + snapshot → HTTPS → CENTRAL
|
|
|
|
CENTRAL (GPU)
|
|
──────────────
|
|
CodeProject.AI
|
|
├── Confirmation objet
|
|
├── Reconnaissance faciale
|
|
└── Lecture plaque (LPR)
|
|
↓
|
|
Événement → Notification
|
|
```
|
|
|
|
## Pré-détection sur l'Agent paramétrable
|
|
|
|
```csharp
|
|
public record AiDetectionConfig
|
|
{
|
|
public int SnapshotIntervalMs { get; init; } = 200;
|
|
public double MotionThreshold { get; init; } = 0.3;
|
|
public string Model { get; init; } = "yolov8n";
|
|
public bool SendFullSnapshot { get; init; } = true;
|
|
}
|
|
```
|
|
|
|
## Tests
|
|
|
|
```
|
|
Agent detects motion from snapshot
|
|
Agent sends alert when person detected
|
|
Agent does NOT send alert when nothing detected
|
|
Central confirms object type from Agent snapshot
|
|
Face recognition matches known person
|
|
Unknown face creates alert with snapshot
|
|
License plate OCR reads plate correctly
|
|
```
|
|
|
|
---
|
|
|
|
# Phase 13 — Storage (MinIO/S3)
|
|
|
|
## Objectif
|
|
|
|
Stockage centralisé des enregistrements vidéo sur MinIO (compatible S3).
|
|
|
|
## Architecture
|
|
|
|
```text
|
|
Agent écrit segments vidéo (.ts) + snapshots → MinIO (Central)
|
|
↓
|
|
Central lit pour playback (HLS)
|
|
Hangfire purge les fichiers expirés
|
|
```
|
|
|
|
## Abstraction
|
|
|
|
```csharp
|
|
public interface IStorageProvider
|
|
{
|
|
Task UploadAsync(string path, Stream content, CancellationToken ct);
|
|
Task<Stream> DownloadAsync(string path, CancellationToken ct);
|
|
Task DeleteAsync(string path, CancellationToken ct);
|
|
Task DeleteByPrefixAsync(string prefix, CancellationToken ct);
|
|
}
|
|
```
|
|
|
|
## Implémentations
|
|
|
|
| Provider | Installation | Usage |
|
|
|---|---|---|
|
|
| **MinIO** | Docker `minio/minio` | Défaut, stockage principal |
|
|
| **Local** | `/recordings` | Fallback bas-débit |
|
|
| **AWS S3** | SDK | Alternative cloud |
|
|
|
|
---
|
|
|
|
# Phase 14 — Hangfire (rétention)
|
|
|
|
## Objectif
|
|
|
|
Jobs planifiés pour gérer la rétention et le nettoyage.
|
|
|
|
## Jobs
|
|
|
|
| Job | Schedule | Description |
|
|
|---|---|---|
|
|
| `RetentionCheck` | Tous les jours | Supprime enregistrements > rétention |
|
|
| `S3Cleanup` | Tous les jours | Nettoie les fichiers orphelins |
|
|
| `CleanupUnknownFaces` | Toutes les semaines | Supprime visages inconnus > 30j |
|
|
| `CleanupLicensePlates` | Toutes les semaines | Supprime plaques non associées > 30j |
|
|
| `DatabaseMaintenance` | Tous les mois | REINDEX, VACUUM |
|
|
|
|
---
|
|
|
|
# Phase 15 — Blazor UI : Auth + Sites + Caméras
|
|
|
|
## Objectif
|
|
|
|
Interface utilisateur sans le live vidéo (implémenté à la fin).
|
|
|
|
## Pages implémentées (dans l'ordre)
|
|
|
|
| Page | Route | Priorité | Description |
|
|
|---|---|---|---|
|
|
| Login | `/login` | P0 | Authentification JWT |
|
|
| Sites liste | `/sites` | P0 | Liste des sites |
|
|
| Site détail | `/sites/{id}` | P0 | Tabs : caméras, agents, config |
|
|
| Caméra détail | `/cameras/{id}` | P1 | Infos + config |
|
|
| Personnes liste | `/persons` | P1 | Grille des personnes |
|
|
| Personne détail | `/persons/{id}` | P1 | Photos + événements |
|
|
| Événements | `/events` | P1 | Tableau filtré |
|
|
| Administration | `/admin` | P1 | Users, API keys, jobs |
|
|
|
|
## Layout
|
|
|
|
```text
|
|
MudLayout
|
|
├── MudAppBar → titre + notifications + user menu
|
|
├── MudDrawer → navigation responsive
|
|
└── MudMainContent → contenu page
|
|
```
|
|
|
|
**Voir `docs/ui-pages.md` pour les maquettes détaillées de chaque page.**
|
|
|
|
---
|
|
|
|
# Phase 16 — WebRTC Streaming
|
|
|
|
## Objectif
|
|
|
|
L'Agent diffuse le flux vidéo live vers le navigateur via WebRTC P2P.
|
|
|
|
## Librairie
|
|
|
|
**SIPSorcery** v10.0.12+ — implémentation WebRTC 100% C#.
|
|
|
|
```
|
|
dotnet add package SIPSorcery
|
|
dotnet add package SIPSorceryMedia.FFmpeg
|
|
```
|
|
|
|
## Architecture
|
|
|
|
```text
|
|
Agent (SIPSorcery) Central (SignalR) Navigateur
|
|
│ │ │
|
|
│ SignalR hub │ │
|
|
│◄════════════════════════╪════════════════════════►│
|
|
│ (SDP + ICE) │ (SDP + ICE) │
|
|
│ │ │
|
|
│══════════════════ WebRTC P2P ════════════════════►│
|
|
│ Flux H264 (SRTP) │
|
|
```
|
|
|
|
## SignalR Hub
|
|
|
|
```csharp
|
|
public class StreamingHub : Hub
|
|
{
|
|
// Agent → Central : s'enregistre comme source
|
|
public async Task RegisterSource(Guid agentId, Guid cameraId)
|
|
|
|
// Browser → Central : demande un flux
|
|
public async Task RequestStream(Guid cameraId)
|
|
|
|
// Agent ↔ Browser : relay SDP + ICE
|
|
public async Task SendSdp(string sdp, string targetConnectionId)
|
|
public async Task SendIceCandidate(string candidate, string targetConnectionId)
|
|
}
|
|
```
|
|
|
|
## Modules JS côté Blazor
|
|
|
|
Voir `docs/specs.md` §26 pour le détail du module JS autonome
|
|
et du cycle de vie Blazor/WebRTC.
|
|
|
|
---
|
|
|
|
# Phase 17 — Blazor UI : Live Vidéo (DERNIER)
|
|
|
|
## Objectif
|
|
|
|
Intégrer le flux WebRTC dans l'interface — c'est la dernière fonctionnalité.
|
|
|
|
## Page Live
|
|
|
|
**Route** : `/cameras/{id}/live`
|
|
|
|
```text
|
|
┌──────────────────────────────────────────────────────┐
|
|
│ 📷 Entrée — Live [Plein écran]│
|
|
│ │
|
|
│ ┌──────────────────────────────────────────────────┐ │
|
|
│ │ <video> NATIF HTML │ │
|
|
│ │ (géré par module JS autonome) │ │
|
|
│ └──────────────────────────────────────────────────┘ │
|
|
│ │
|
|
│ Qualité: [1080p ▼] [📷 Snapshot] [⏺️ Record] │
|
|
│ Timeline: [══════■══════■══════════] │
|
|
└──────────────────────────────────────────────────────┘
|
|
```
|
|
|
|
**Composants MudBlazor :** `MudSelect` (qualité), `MudIconButton` (actions),
|
|
`MudSlider` (timeline). Le `<video>` est un élément HTML standard.
|
|
|
|
## SignalR temps réel
|
|
|
|
Les contrôles (qualité, snapshot, record) envoient des commandes
|
|
via SignalR au hub `/hubs/streaming`. Le module JS y est déjà connecté.
|
|
|
|
---
|
|
|
|
# Phase 18 — Dashboard KPI
|
|
|
|
## Objectif
|
|
|
|
Tableau de bord avec les indicateurs clés.
|
|
|
|
## Widgets MudBlazor
|
|
|
|
| Widget | Composant | Source |
|
|
|---|---|---|
|
|
| Caméras total/en ligne | `MudCard` + `MudText` | API Dashboard |
|
|
| Événements aujourd'hui | `MudCard` + `MudText` | API Dashboard |
|
|
| Stockage libre | `MudCard` + `MudProgressLinear` | API Dashboard |
|
|
| Événements récents | `MudTable` (5 lignes) | API + SignalR |
|
|
| Status Agents | `MudChip` | API + SignalR |
|
|
| Alertes non lues | `MudBadge` | SignalR |
|
|
|
|
---
|
|
|
|
# Phase 19 — Production Hardening
|
|
|
|
## Objectif
|
|
|
|
Rendre le système prêt pour la production.
|
|
|
|
## Checklist
|
|
|
|
- [ ] Observabilité : Serilog + Seq/GlitchTip
|
|
- [ ] Sentry pour les erreurs
|
|
- [ ] Métriques Prometheus
|
|
- [ ] Health checks (API, Agent, DB, MinIO, CodeProject.AI, Ollama)
|
|
- [ ] Rate limiting sur endpoints publics
|
|
- [ ] CORS configuration
|
|
- [ ] SSL/TLS partout
|
|
- [ ] Docker Compose production-ready
|
|
- [ ] Backup PostgreSQL
|
|
- [ ] Documentation déploiement
|
|
- [ ] README complet
|
|
- [ ] API documentation (OpenAPI/Swagger)
|
|
- [ ] Tests de charge (k6)
|
|
- [ ] Security audit
|