- ui-pages.md : retirer écran 'Clé API' du login, ajouter champ 2FA (TOTP) - auth-roles.md : ajouter 2FA optionnel, User.TwoFactorEnabled, API Keys = Agents uniquement, header clarifié - implementation.md Phase 6 : +2FA endpoints, API Keys scope Agents - signalr-usage.md : clarifier JWT pour humains, API Key pour Agents
1205 lines
32 KiB
Markdown
1205 lines
32 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 |
|
|
| 2FA (TOTP authenticator) | 🟠 Important |
|
|
| Rôles (Admin, Superviseur, Viewer) | 🟠 Important |
|
|
| Permissions (Camera.Read, etc.) | 🔴 Requis |
|
|
| API Keys (hash SHA256) **— Agents uniquement** | 🔴 Requis |
|
|
| API Key middleware (scopes `/api/agents/*`) | 🔴 Requis |
|
|
|
|
**Les API Keys sont strictement réservées aux Agents.** Les utilisateurs
|
|
humains se connectent exclusivement par email + mot de passe (+2FA optionnel).
|
|
|
|
## Tests
|
|
|
|
```
|
|
User can register with email + password
|
|
User can login and receive JWT token
|
|
2FA code is requested when enabled for user
|
|
Invalid 2FA code returns error
|
|
JWT token is validated on protected endpoints
|
|
User without permission receives 403
|
|
API key authentication works for agent endpoints
|
|
API key login is NOT available on login page
|
|
Expired API key is rejected
|
|
```
|
|
|
|
## 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/2fa/verify` | JWT partiel | Valider code 2FA |
|
|
| `POST` | `/api/auth/refresh` | — | Rafraîchir JWT |
|
|
| `POST` | `/api/api-keys` | JWT/Admin | Générer clé API (pour Agent) |
|
|
| `GET` | `/api/api-keys` | JWT/Admin | Lister les clés |
|
|
| `DELETE` | `/api/api-keys/{id}` | JWT/Admin | Révoquer clé API |
|
|
|
|
**Les utilisateurs se connectent par login/password. Les API Keys sont
|
|
réservées aux Agents pour les endpoints `/api/agents/*`.**
|
|
|
|
---
|
|
|
|
# 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 | NuGet | Installation | Usage |
|
|
|---|---|---|---|
|
|
| **MinIO** | `Minio` | Docker `minio/minio` | Défaut, stockage central |
|
|
| **Local** | — | Dossier `/recordings` | Fallback bas-débit |
|
|
| **AWS S3** | `AWSSDK.S3` | AWS | Alternative cloud |
|
|
|
|
## Tests
|
|
|
|
```
|
|
Agent can upload video segment to MinIO
|
|
Agent can upload snapshot to MinIO
|
|
Central can read segment for playback
|
|
Storage fallback to Local works when MinIO unavailable
|
|
DeleteByPrefix removes all files for a camera
|
|
```
|
|
|
|
---
|
|
|
|
# Phase 14 — SignalR Hubs (temps réel)
|
|
|
|
## Objectif
|
|
|
|
Mettre en place la communication temps réel entre Central, Agents et navigateurs.
|
|
|
|
## 5 hubs à implémenter
|
|
|
|
| Hub | Route | Clients | Usage |
|
|
|---|---|---|---|
|
|
| **EventsHub** | `/hubs/events` | Browser + Agent | Événements détection, alertes |
|
|
| **StreamingHub** | `/hubs/streaming` | Browser + Agent | Signaling WebRTC (SDP + ICE) |
|
|
| **MonitoringHub** | `/hubs/monitoring` | Browser | Status agents, caméras, stockage |
|
|
| **NotificationsHub** | `/hubs/notifications` | Browser | Notifications in-app avec badge |
|
|
| **AdminHub** | `/hubs/admin` | Admin browser | Broadcast changements config |
|
|
|
|
## Groupes SignalR
|
|
|
|
```csharp
|
|
// À l'implémentation, chaque hub groupe les connexions par :
|
|
"all-sites" // Admin : voit tout
|
|
"site-{siteId}" // User : voit ses sites
|
|
"camera-{cameraId}" // Streaming : Agent source
|
|
"viewer-{cameraId}" // Streaming : Browser viewer
|
|
"notif-{userId}" // Notifications : par user
|
|
"admin-broadcast" // Admin : changements config
|
|
```
|
|
|
|
## Dépendance
|
|
|
|
SignalR est inclus dans ASP.NET Core — pas de package supplémentaire.
|
|
|
|
## Tests
|
|
|
|
```
|
|
EventsHub emits EventCreated to correct site group
|
|
StreamingHub relays SDP offer Agent ↔ Browser
|
|
MonitoringHub sends AgentStatusChanged on timeout
|
|
NotificationsHub sends NewNotification to correct user
|
|
AdminHub ConfigChanged reaches all connected admins
|
|
Hub groups correctly scoped per site
|
|
Unauthenticated connection receives 403
|
|
```
|
|
|
|
**Voir `docs/signalr-usage.md` pour le code complet de chaque hub.**
|
|
|
|
---
|
|
|
|
# Phase 15 — Hangfire Central (PostgreSQL)
|
|
|
|
## Objectif
|
|
|
|
Jobs planifiés persistants côté Central, stockés dans PostgreSQL.
|
|
|
|
## Installation
|
|
|
|
```
|
|
dotnet add package Hangfire
|
|
dotnet add package Hangfire.PostgreSql
|
|
dotnet add package Hangfire.AspNetCore
|
|
```
|
|
|
|
## Configuration
|
|
|
|
```csharp
|
|
// Program.cs — Central
|
|
builder.Services.AddHangfire(config =>
|
|
{
|
|
config.UsePostgreSqlStorage(options =>
|
|
{
|
|
options.ConnectionString = builder.Configuration.GetConnectionString("Hangfire");
|
|
});
|
|
});
|
|
|
|
builder.Services.AddHangfireServer();
|
|
|
|
// Dashboard (Admin only)
|
|
app.UseHangfireDashboard("/admin/jobs", new DashboardOptions
|
|
{
|
|
Authorization = [new HangfireAdminFilter()]
|
|
});
|
|
```
|
|
|
|
## Jobs récurrents
|
|
|
|
| Job | Schedule | Code |
|
|
|---|---|---|
|
|
| `RetentionCheck` | Tous les jours à 3h | Purge enregistrements > rétention |
|
|
| `S3Cleanup` | Tous les jours à 4h | Nettoie fichiers orphelins MinIO |
|
|
| `CleanupUnknownFaces` | Dimanche 5h | Supprime visages inconnus > 30j |
|
|
| `CleanupLicensePlates` | Dimanche 6h | Plaques non associées > 30j |
|
|
| `DatabaseMaintenance` | 1er du mois 7h | REINDEX + VACUUM |
|
|
| `DailyDigest` | Tous les jours à 8h | Résumé quotidien email |
|
|
|
|
## Tests
|
|
|
|
```
|
|
RetentionCheck deletes expired recordings
|
|
S3Cleanup removes orphaned files
|
|
DailyDigestJob sends email to subscribed users
|
|
Hangfire dashboard accessible only to Admin
|
|
Hangfire dashboard returns 403 for non-Admin
|
|
DatabaseMaintenanceJob runs without error
|
|
```
|
|
|
|
**Voir `docs/hangfire-usage.md` §2 pour le code complet de chaque job.**
|
|
|
|
---
|
|
|
|
# Phase 16 — Hangfire Agent (InMemory, jobs volatiles)
|
|
|
|
## Objectif
|
|
|
|
Jobs légers côté Agent, sans persistance. Les jobs disparaissent au redémarrage
|
|
et sont recréés au démarrage de l'Agent — c'est voulu.
|
|
|
|
## Installation
|
|
|
|
```
|
|
dotnet add package Hangfire
|
|
dotnet add package Hangfire.InMemory
|
|
```
|
|
|
|
## Configuration
|
|
|
|
```csharp
|
|
// Program.cs — Agent
|
|
builder.Services.AddHangfire(config =>
|
|
{
|
|
config.UseInMemoryStorage(); // Aucune config, aucun fichier, zéro dépendance
|
|
});
|
|
|
|
builder.Services.AddHangfireServer(options =>
|
|
{
|
|
options.WorkerCount = 2; // Agent léger
|
|
options.Queues = ["agent"]; // File dédiée
|
|
options.ServerName = $"agent-{hostname}";
|
|
});
|
|
|
|
// Pas de dashboard — l'Agent n'expose pas de HTTP
|
|
```
|
|
|
|
## Jobs Agent
|
|
|
|
| Job | Schedule | Description |
|
|
|---|---|---|
|
|
| `CameraHealthCheck` | Toutes les 30s | Vérifie si les caméras répondent |
|
|
| `HeartbeatSender` | Toutes les 30s | POST /heartbeat vers le Central |
|
|
| `GpuWatchdog` | Toutes les 5min | Détecte GPU, rapporte au Central |
|
|
| `LocalRetentionCleanup` | Toutes les heures | Nettoie enregistrements locaux (fallback) |
|
|
|
|
## Initialisation au démarrage
|
|
|
|
```csharp
|
|
public class HangfireInitializer : IHostedService
|
|
{
|
|
public Task StartAsync(CancellationToken ct)
|
|
{
|
|
var agentId = _stateManager.GetAgentId();
|
|
var prefix = $"agent-{agentId}";
|
|
|
|
RecurringJob.AddOrUpdate<CameraHealthCheckJob>(
|
|
$"{prefix}-camera-health",
|
|
j => j.ExecuteAsync(CancellationToken.None),
|
|
Cron.MinuteInterval(1));
|
|
|
|
RecurringJob.AddOrUpdate<HeartbeatSenderJob>(
|
|
$"{prefix}-heartbeat",
|
|
j => j.ExecuteAsync(CancellationToken.None),
|
|
Cron.MinuteInterval(1));
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|
|
```
|
|
|
|
## Tests
|
|
|
|
```
|
|
Agent CameraHealthCheckJob detects offline camera
|
|
Agent HeartbeatSenderJob sends heartbeat to Central
|
|
Agent GpuWatchdogJob detects GPU changes
|
|
Agent jobs are recreated after agent restart
|
|
Agent InMemory storage has zero files on disk
|
|
```
|
|
|
|
**Voir `docs/hangfire-usage.md` §3 pour le code complet de chaque job Agent.**
|
|
|
|
---
|
|
|
|
# Phase 17 — Notifications (Email + Gotify + Templates)
|
|
|
|
## Objectif
|
|
|
|
Notifier les utilisateurs des événements de détection.
|
|
|
|
## Canaux
|
|
|
|
| Canal | Librairie | Usage |
|
|
|---|---|---|
|
|
| **Email SMTP** | `FluentEmail.Smtp` | Notifications importantes + résumés |
|
|
| **Gotify** (push) | `Gotify.NET` | Alertes temps réel |
|
|
| **In-app** | SignalR (intégré) | Badge notifications dans l'UI |
|
|
|
|
## Templates Markdown (Scriban)
|
|
|
|
Les templates sont stockés en base et éditables depuis l'UI Admin.
|
|
|
|
```xml
|
|
<PackageReference Include="Scriban" Version="5.12.0" />
|
|
```
|
|
|
|
Variables disponibles : `{{SiteName}}`, `{{CameraName}}`, `{{EventType}}`,
|
|
`{{PersonName}}`, `{{VehiclePlate}}`, `{{SnapshotUrl}}`, `{{EventUrl}}`
|
|
|
|
Templates par langue (fr, en) avec fallback.
|
|
|
|
## File d'attente Hangfire
|
|
|
|
Toutes les notifications passent par Hangfire (retry 3x, délais progressifs) :
|
|
|
|
```csharp
|
|
BackgroundJob.Enqueue<SendNotificationJob>(j =>
|
|
j.ExecuteAsync(eventId, "email", user.Language, CancellationToken.None));
|
|
```
|
|
|
|
## Tests
|
|
|
|
```
|
|
Notification is sent when person detected
|
|
SMTP failure retries 3 times via Hangfire
|
|
Gotify notification is sent correctly
|
|
Template rendering replaces all variables
|
|
Template editing in UI saves correctly
|
|
User language changes template language
|
|
Daily digest is generated at configured hour
|
|
```
|
|
|
|
**Voir `docs/notifications.md` pour le détail complet (SMTP config, Gotify,
|
|
tous les templates, variables, i18n).**
|
|
|
|
---
|
|
|
|
# Phase 18 — Blazor UI : Auth + Sites + Caméras
|
|
|
|
## Objectif
|
|
|
|
Interface utilisateur sans le live vidéo (implémenté à la phase 20).
|
|
|
|
## Pages (ordre d'implémentation)
|
|
|
|
| Page | Route | Priorité |
|
|
|---|---|---|
|
|
| Login | `/login` | P0 |
|
|
| Dashboard (statique) | `/` | P0 |
|
|
| Sites liste | `/sites` | P0 |
|
|
| Site détail | `/sites/{id}` | P0 |
|
|
| Caméra détail | `/cameras/{id}` | P1 |
|
|
| Personnes liste | `/persons` | P1 |
|
|
| Personne détail | `/persons/{id}` | P1 |
|
|
| Événements | `/events` | P1 |
|
|
| Administration | `/admin` | P1 |
|
|
|
|
## Layout
|
|
|
|
```text
|
|
MudLayout
|
|
├── MudAppBar → titre + notifications + user menu
|
|
├── MudDrawer → navigation responsive
|
|
└── MudMainContent → contenu page
|
|
```
|
|
|
|
## Règles
|
|
|
|
- `AuthorizeView` pour masquer/ montrer les contrôles par rôle
|
|
- `MudSkeleton` pour loading state
|
|
- SignalR pour temps réel (events, monitoring)
|
|
- Localisation via `T.T("key")`
|
|
|
|
**Voir `docs/ui-pages.md` pour les maquettes ASCII complètes de chaque page.**
|
|
|
|
---
|
|
|
|
# Phase 19 — WebRTC Streaming (Agent → Browser)
|
|
|
|
## 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) SFU (MediaMTX si >2 vues) │
|
|
```
|
|
|
|
## Tests
|
|
|
|
```
|
|
Agent creates WebRTC offer with H264 codec
|
|
Browser receives SDP offer and creates answer
|
|
ICE candidates are exchanged bidirectionally
|
|
WebRTC connection state transitions to Connected
|
|
Stream stops cleanly on disconnect
|
|
SFU distributes 1 Agent stream to 3 viewers
|
|
```
|
|
|
|
**Voir `docs/signalr-usage.md` §3 pour le protocole signaling complet.**
|
|
|
|
---
|
|
|
|
# Phase 20 — Blazor UI : Live Vidéo
|
|
|
|
## Objectif
|
|
|
|
Intégrer le flux WebRTC dans l'interface — dernière fonctionnalité Blazor.
|
|
|
|
## 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: [══════■══════■══════════] │
|
|
└──────────────────────────────────────────────────────┘
|
|
```
|
|
|
|
## JS Module autonome
|
|
|
|
Le module `wwwroot/js/liveView.js` :
|
|
- Crée le `RTCPeerConnection` côté navigateur
|
|
- Se connecte au hub SignalR `/hubs/streaming`
|
|
- Échange SDP + ICE avec l'Agent via le Central
|
|
- Affiche le flux dans `<video>`
|
|
- **Survit aux reconnexions Blazor Server**
|
|
|
|
## Tests
|
|
|
|
```
|
|
User can view live stream from permitted camera
|
|
Live stream shows loading state while connecting
|
|
Stream quality selector changes resolution
|
|
Snapshot button captures current frame
|
|
Unauthorized user cannot access live view
|
|
Flow stops when navigating away
|
|
```
|
|
|
|
---
|
|
|
|
# Phase 21 — Application Mobile Android (Avalonia UI)
|
|
|
|
## Objectif
|
|
|
|
Application Android lecture seule pour les utilisateurs.
|
|
|
|
## Stack
|
|
|
|
| Technologie | Version | Usage |
|
|
|---|---|---|
|
|
| Avalonia UI | 11.x+ | Framework UI |
|
|
| Kiota | 1.15+ | Client API généré depuis OpenAPI |
|
|
| SignalR Client | 10.x | Temps réel |
|
|
|
|
## Pages
|
|
|
|
| Page | Description |
|
|
|---|---|
|
|
| Login | Connexion JWT + URL serveur |
|
|
| Dashboard | KPIs, derniers événements, sites |
|
|
| Sites List | Liste des sites accessibles |
|
|
| Site Detail | Caméras du site avec snapshots |
|
|
| Camera Live | Flux WebRTC via WebView + JS bridge |
|
|
| Events List | Événements filtrés par type/site |
|
|
|
|
## API Client — Kiota
|
|
|
|
Le client est généré depuis l'OpenAPI du Central, filtré sur `/api/mobile/*` :
|
|
|
|
```bash
|
|
kiota generate \
|
|
--language csharp \
|
|
--openapi https://central/ openapi/v1.json \
|
|
--namespace-name Heimdall.Mobile.ApiClient \
|
|
--include-path "/api/auth/**" \
|
|
--include-path "/api/mobile/**" \
|
|
--clean-output
|
|
```
|
|
|
|
## Tests
|
|
|
|
```
|
|
User can login with valid JWT
|
|
Dashboard shows user's sites only
|
|
Site list shows only assigned sites
|
|
Live WebRTC stream starts on camera tap
|
|
Event list is paginated
|
|
Offline cache shows stale data when offline
|
|
Push notification opens relevant event page
|
|
```
|
|
|
|
**Voir `docs/mobile-app.md` pour l'architecture MVVM, toutes les pages,
|
|
WebView WebRTC bridge, cache offline, notifications push.**
|
|
|
|
---
|
|
|
|
# Phase 22 — 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 |
|
|
|
|
## Tests
|
|
|
|
```
|
|
Dashboard loads all KPIs within 2s
|
|
Dashboard updates in real-time via SignalR
|
|
Empty dashboard shows setup prompt
|
|
All agents offline shows warning banner
|
|
Storage KPI shows correct available space
|
|
```
|
|
|
|
---
|
|
|
|
# Phase 23 — 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 automatisé
|
|
- [ ] Backup MinIO (S3 → S3)
|
|
- [ ] Documentation déploiement
|
|
- [ ] API documentation (OpenAPI/Swagger)
|
|
- [ ] Tests de charge (k6)
|
|
- [ ] Security audit
|
|
- [ ] k6 load tests : 10 agents, 50 caméras, 20 viewers simultanés
|