- Complete rewrite of mobile-app.md: Kotlin 2.1+, Jetpack Compose 1.7+ - Clean Architecture: data/domain/presentation layers - Ktor 3.0 HTTP client (replaces Kiota, Kotlin-native) - WebRTC natif Android (SurfaceViewRenderer + PeerConnection) - SignalR client Java Microsoft (compatible Kotlin) - Hilt DI, Room cache, DataStore preferences, Coil images - Firebase Cloud Messaging push notifications - MVVM with StateFlow + collectAsStateWithLifecycle - Compose Navigation (NavHost, sealed Screen routes) - Tests: JUnit 5 + MockK + Turbine (Flow) + Compose UI Test - CI/CD Gradle with lint + detekt + unit tests + APK signing - GitHub Actions workflow dedicated to mobile - Update implementation.md Phase 21 with new stack - Update README.md references
1479 lines
44 KiB
Markdown
1479 lines
44 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 & Camera Authentication
|
|
|
|
## Objectif
|
|
|
|
L'Agent découvre les caméras sur le réseau local via ONVIF WS-Discovery
|
|
et stocke les credentials d'accès (différents par site/caméra).
|
|
|
|
## Librairie ONVIF
|
|
|
|
```xml
|
|
<!-- SharpOnvifClient — v0.9.5, .NET 10, juillet 2026 -->
|
|
<PackageReference Include="SharpOnvifClient" Version="0.9.5" />
|
|
<PackageReference Include="SharpOnvifClient.DeviceMgmt" Version="0.9.5" />
|
|
<PackageReference Include="SharpOnvifClient.Media" Version="0.9.5" />
|
|
<PackageReference Include="OnvifDiscovery" Version="2.1.1" />
|
|
```
|
|
|
|
Alternative : `QuickNV.Onvif` (mise à jour 05/2026, compatible .NET 10).
|
|
|
|
## Fonctionnalités
|
|
|
|
- Découverte multicast WS-Discovery (via `OnvifDiscovery`)
|
|
- Identification fabricant + modèle + firmware
|
|
- Détection URL RTSP + snapshot
|
|
- Détection capacités PTZ
|
|
- Fallback discovery manuelle (IP fixe + port)
|
|
- Authentification ONVIF avec credentials stockés (chiffrés)
|
|
|
|
## Credentials — Stockage et gestion
|
|
|
|
Les caméras peuvent avoir des identifiants différents **par site**,
|
|
**par caméra**, ou être **sans auth** (réseau interne non protégé).
|
|
|
|
### Modèle de données
|
|
|
|
```csharp
|
|
public class CameraCredentials
|
|
{
|
|
public Guid CameraId { get; set; }
|
|
public string OnvifUsername { get; set; } = "admin";
|
|
public string OnvifPassword { get; set; } = string.Empty; // Chiffré (IDataProtector)
|
|
public string RtspUsername { get; set; } = string.Empty; // Souvent identique à ONVIF
|
|
public string RtspPassword { get; set; } = string.Empty; // Chiffré
|
|
public DateTime UpdatedAt { get; set; }
|
|
}
|
|
```
|
|
|
|
Le mot de passe est **chiffré au repos** avec `IDataProtector` (ASP.NET Core).
|
|
Il n'est jamais retourné par l'API — seulement utilisé côté Agent.
|
|
|
|
### Héritage par Site
|
|
|
|
Si toutes les caméras d'un site partagent le même login, on peut définir
|
|
des credentials par défaut au niveau du Site :
|
|
|
|
```csharp
|
|
public class Site
|
|
{
|
|
// Credentials par défaut pour les caméras du site
|
|
public string? DefaultOnvifUsername { get; set; }
|
|
public string? DefaultOnvifPassword { get; set; } // Chiffré
|
|
}
|
|
```
|
|
|
|
Règle : CameraCredentials > Site.Default > pas d'auth.
|
|
|
|
### UI Admin
|
|
|
|
```text
|
|
┌──────────────────────────────────────────────┐
|
|
│ Caméra : Entrée │
|
|
│ │
|
|
│ Authentification ONVIF : │
|
|
│ [✅] Utiliser les identifiants du site │
|
|
│ [ ] Identifiants spécifiques : │
|
|
│ Utilisateur: [admin ] │
|
|
│ Mot de passe: [******** ] │
|
|
│ [ ] Pas d'authentification │
|
|
│ │
|
|
│ Authentification RTSP : │
|
|
│ (identiques à ONVIF par défaut) │
|
|
└──────────────────────────────────────────────┘
|
|
```
|
|
|
|
## Tests
|
|
|
|
```
|
|
Agent discovers cameras on same subnet via WS-Discovery
|
|
Agent discovers camera with ONVIF credentials
|
|
Agent rejects invalid ONVIF credentials (401)
|
|
Agent detects camera manufacturer and model
|
|
Agent discovers RTSP URL from ONVIF device
|
|
Manual discovery works with IP + port
|
|
Discovery does not discover non-ONVIF devices
|
|
Camera credentials are encrypted at rest
|
|
Credentials never appear in API responses
|
|
Site-level default credentials apply to all cameras
|
|
Camera-specific credentials override site defaults
|
|
```
|
|
|
|
## Architecture
|
|
|
|
```csharp
|
|
public interface IOnvifDiscoveryService
|
|
{
|
|
Task<IReadOnlyList<DiscoveredCamera>> DiscoverAsync(
|
|
TimeSpan timeout, CancellationToken ct);
|
|
|
|
Task<DiscoveredCamera?> DiscoverByIpAsync(
|
|
string ip, int port,
|
|
string? username, string? password,
|
|
CancellationToken ct);
|
|
}
|
|
|
|
public record DiscoveredCamera(
|
|
string Host,
|
|
int Port,
|
|
string Manufacturer,
|
|
string Model,
|
|
string FirmwareVersion,
|
|
string RtspUrl,
|
|
string? SnapshotUrl,
|
|
bool HasPtz,
|
|
bool AuthRequired); // ← Nouveau : la caméra demande une auth
|
|
|
|
// Résolution des credentials au moment de la connexion
|
|
public interface ICameraCredentialResolver
|
|
{
|
|
Task<CameraCredentials> GetCredentialsAsync(
|
|
Guid cameraId, CancellationToken ct);
|
|
Task<CameraCredentials> GetDefaultCredentialsAsync(
|
|
Guid siteId, CancellationToken ct);
|
|
}
|
|
```
|
|
|
|
## Limites techniques
|
|
|
|
- WS-Discovery utilise **multicast UDP** → même VLAN uniquement
|
|
- Si caméras sur VLAN différent → discovery manuelle obligatoire
|
|
- Certaines caméras bloquent ONVIF si le firmware est récent (Dahua/Imou)
|
|
- Stocker les credentials ONVIF chiffrés avec `IDataProtector`
|
|
- Les credentials ne sont jamais exposés dans les logs ni les réponses API
|
|
|
|
## Protocole Imou — Spécificités
|
|
|
|
### Activation du RTSP
|
|
|
|
Les caméras Imou (et les marques Dahua/Lorex associées) sont configurées
|
|
**cloud-first** par défaut. Le flux RTSP local est désactivé.
|
|
|
|
**Procédure d'activation :**
|
|
|
|
1. Installer l'app **Imou Life** sur smartphone
|
|
2. Ajouter la caméra (compte Imou requis)
|
|
3. Aller dans **Paramètres → Appareil → Paramètres avancés**
|
|
4. Activer **"RTSP"** (ou "Flux local" selon firmware)
|
|
5. Définir un **mot de passe RTSP** dédié (différent du compte cloud)
|
|
6. Noter l'URL RTSP : `rtsp://user:password@IP:554/onvif1`
|
|
|
|
### URLs RTSP connues
|
|
|
|
| Modèle | RTSP URL |
|
|
|---|---|
|
|
| Imou IPC-T2A30P | `rtsp://user:pass@IP:554/onvif1` |
|
|
| Imou Ranger 2 | `rtsp://user:pass@IP:554/live/ch0` |
|
|
| Imou Cruiser | `rtsp://user:pass@IP:554/onvif1` |
|
|
| Dahua générique | `rtsp://user:pass@IP:554/cam/realmonitor?channel=1&subtype=0` |
|
|
|
|
### Problèmes connus
|
|
|
|
| Problème | Cause | Solution |
|
|
|---|---|---|
|
|
| ONVIF bloqué après maj firmware | Dahua bloque l'accès 3rd party | Désactiver les mises à jour auto, utiliser RTSP direct |
|
|
| RTSP désactivé après reboot | Paramètre perdu par maj | Vérifier RTSP actif après chaque mise à jour |
|
|
| Flux RTSP lent (1fps) | Sous-flux activé | Ajouter `?subtype=0` à l'URL pour le flux principal |
|
|
| Connexion refuse après 5 tentatives | Blocage temporaire (bruteforce) | Attendre 5 min, vérifier les identifiants |
|
|
| WS-Discovery ne trouve pas la caméra | VLAN différent / multicast bloqué | Découverte manuelle par IP fixe
|
|
|
|
---
|
|
|
|
# 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 + profil détection |
|
|
| `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 |
|
|
| `GET` | `/api/cameras/{id}/detection-profile` | JWT | Obtenir profil détection |
|
|
| `PUT` | `/api/cameras/{id}/detection-profile` | JWT/Admin | Modifier profil détection |
|
|
| `POST` | `/api/cameras/{id}/detection-profile/reset` | JWT/Admin | Réinitialiser profil par défaut (selon type) |
|
|
|
|
---
|
|
|
|
# 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 via **CodeProject.AI Server** v2.9.5.
|
|
|
|
## Service IA — CodeProject.AI
|
|
|
|
Serveur IA auto-hébergé avec API REST exposant des modules de vision
|
|
par snapshot. Voir `docs/codeproject-ai.md` pour la référence complète.
|
|
|
|
### Modules utilisés
|
|
|
|
| Module | Endpoint | Usage dans Heimdall |
|
|
|---|---|---|
|
|
| **Object Detection (YOLOv8)** | `POST /v1/vision/detection` | Détection personnes, véhicules, animaux |
|
|
| **License Plate Reader** | `POST /v1/vision/alpr` | Lecture plaques (PaddleOCR) |
|
|
| **Face Processing** | `POST /v1/vision/face/recognize` | Reconnaissance faciale |
|
|
| **Face Detection** | `POST /v1/vision/face` | Détection visages |
|
|
| **Custom Detector (ipcam-general)** | `POST /v1/vision/custom/ipcam-general` | Détection optimisée vidéosurveillance |
|
|
|
|
### Pipeline complet
|
|
|
|
Voir `docs/codeproject-ai.md` §4 pour le pipeline détaillé avec
|
|
diagramme et code C# de filtrage par DetectionProfile.
|
|
|
|
### Performances (GPU RTX 3060)
|
|
|
|
| Module | Inférence |
|
|
|---|---|
|
|
| Object Detection YOLOv8 | 25-50ms |
|
|
| License Plate Reader | 150-250ms |
|
|
| Face Recognition | 30-50ms |
|
|
|
|
**Total pipeline complet : ~200-350ms par snapshot.**
|
|
|
|
## Per-Camera Detection Profile
|
|
|
|
**Chaque caméra a son propre profil de détection.** Une caméra dans un
|
|
escalier ne va pas chercher des plaques d'immatriculation ou des véhicules.
|
|
Une caméra de parking ne fait pas de reconnaissance faciale.
|
|
|
|
### Modèle
|
|
|
|
```csharp
|
|
public class CameraDetectionProfile
|
|
{
|
|
public Guid CameraId { get; set; }
|
|
|
|
// Types d'objets à détecter
|
|
public bool DetectPerson { get; set; } = true;
|
|
public bool DetectVehicle { get; set; } = true;
|
|
public bool DetectAnimal { get; set; } = false;
|
|
public bool DetectPackage { get; set; } = false;
|
|
public bool DetectMotion { get; set; } = true; // mouvement simple
|
|
|
|
// IA lourde (Central GPU)
|
|
public bool FaceRecognition { get; set; } = true;
|
|
public bool LicensePlateRecognition { get; set; } = true;
|
|
|
|
// Paramètres
|
|
public int SnapshotIntervalMs { get; set; } = 200;
|
|
public double MotionThreshold { get; set; } = 0.3;
|
|
public string YoloModel { get; set; } = "yolov8n"; // nano, small, medium
|
|
}
|
|
```
|
|
|
|
### Configuration par défaut selon le type de caméra
|
|
|
|
```csharp
|
|
public static class DetectionDefaults
|
|
{
|
|
public static CameraDetectionProfile ForIndoor() => new()
|
|
{
|
|
DetectPerson = true,
|
|
DetectVehicle = false,
|
|
DetectAnimal = false,
|
|
DetectPackage = true,
|
|
FaceRecognition = true,
|
|
LicensePlateRecognition = false, // Pas de plaque à l'intérieur
|
|
MotionThreshold = 0.25
|
|
};
|
|
|
|
public static CameraDetectionProfile ForOutdoor() => new()
|
|
{
|
|
DetectPerson = true,
|
|
DetectVehicle = true,
|
|
DetectAnimal = true,
|
|
DetectPackage = false,
|
|
FaceRecognition = true,
|
|
LicensePlateRecognition = true, // Plaques sur parking/entrée
|
|
MotionThreshold = 0.35 // Plus de seuil (vent/arbres)
|
|
};
|
|
|
|
public static CameraDetectionProfile ForStairwell() => new()
|
|
{
|
|
DetectPerson = true,
|
|
DetectVehicle = false, // Pas de véhicule dans un escalier
|
|
DetectAnimal = false,
|
|
DetectPackage = false,
|
|
FaceRecognition = true,
|
|
LicensePlateRecognition = false, // Inutile
|
|
MotionThreshold = 0.20 // Faible seuil (espace réduit)
|
|
};
|
|
|
|
public static CameraDetectionProfile ForParking() => new()
|
|
{
|
|
DetectPerson = true,
|
|
DetectVehicle = true,
|
|
DetectAnimal = false,
|
|
DetectPackage = false,
|
|
FaceRecognition = false, // Visages peu visibles depuis parking
|
|
LicensePlateRecognition = true, // Plaques obligatoires
|
|
MotionThreshold = 0.30
|
|
};
|
|
}
|
|
```
|
|
|
|
### Architecture two-tier avec profil
|
|
|
|
```text
|
|
AGENT (CPU léger) CENTRAL (GPU)
|
|
───────────────── ──────────────
|
|
Snapshot JPEG toutes les 200ms
|
|
↓
|
|
Filtre par DetectionProfile :
|
|
├── DetectPerson? → YOLO classe "person"
|
|
├── DetectVehicle? → YOLO classe "car/truck/bicycle"
|
|
├── DetectAnimal? → YOLO classe "cat/dog/bird"
|
|
├── DetectPackage? → YOLO classe "package"
|
|
└── DetectMotion → pixel diff
|
|
↓
|
|
Rien d'intéressant ? → ignore (pas de snapshot envoyé)
|
|
↓
|
|
Alerte + snapshot → HTTPS → CodeProject.AI
|
|
├── DetectPerson + FaceRecognition ?
|
|
│ → Reconnaissance faciale
|
|
├── DetectVehicle + LicensePlateRecognition ?
|
|
│ → LPR (lecture plaque)
|
|
└── → Création événement + notification
|
|
```
|
|
|
|
### Gains
|
|
|
|
| Caméra | Sans profil | Avec profil | Économie |
|
|
|---|---|---|---|
|
|
| Escalier (intérieur) | Vérifie plaques, véhicules → waste | Uniquement personnes | -60% snapshots CPU |
|
|
| Parking | Reconnaissance faciale → 100% échec | Plaques seulement | -40% GPU CodeProject.AI |
|
|
| Jardin | Vérifie colis, colis jamais là | Personnes + animaux | -30% CPU Agent |
|
|
|
|
### Tests
|
|
|
|
```
|
|
Agent detects only enabled detection types per camera
|
|
Camera in stairwell does NOT detect vehicles
|
|
Camera in parking DOES detect license plates
|
|
Disabling face recognition skips CodeProject.AI call
|
|
Profile can be changed without restarting Agent
|
|
Profile change takes effect on next snapshot
|
|
Default profiles apply on camera creation
|
|
Indoor default has LicensePlateRecognition = false
|
|
Parking default has FaceRecognition = false
|
|
```
|
|
|
|
### UI — Configuration par caméra
|
|
|
|
```text
|
|
┌──────────────────────────────────────────────┐
|
|
│ Caméra : Escalier RDC │
|
|
│ │
|
|
│ Détection IA : │
|
|
│ [✅] Personnes │
|
|
│ [ ] Véhicules ← grisé : escalier │
|
|
│ [ ] Animaux │
|
|
│ [✅] Colis / Paquet │
|
|
│ [✅] Mouvement │
|
|
│ │
|
|
│ IA avancée (serveur central) : │
|
|
│ [✅] Reconnaissance faciale │
|
|
│ [ ] Lecture de plaques ← inutile ici │
|
|
│ │
|
|
│ Profil recommandé : [Intérieur ▼] │
|
|
│ (applique les réglages par défaut) │
|
|
│ │
|
|
│ Seuil de mouvement : [══════●══════] 0.25 │
|
|
└──────────────────────────────────────────────┘
|
|
```
|
|
|
|
---
|
|
|
|
# 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 (Kotlin + Jetpack Compose)
|
|
|
|
## Objectif
|
|
|
|
Application Android lecture seule pour les utilisateurs.
|
|
|
|
## Stack
|
|
|
|
| Technologie | Version | Usage |
|
|
|---|---|---|
|
|
| **Kotlin** | 2.1+ | Langage |
|
|
| **Jetpack Compose** | 1.7+ | UI déclarative Material 3 |
|
|
| **Clean Architecture** | — | data / domain / presentation |
|
|
| **Ktor** | 3.0+ | HTTP client |
|
|
| **Hilt** | 2.53+ | Injection de dépendances |
|
|
| **SignalR** | 8.0+ | Temps réel (client Java Microsoft) |
|
|
| **WebRTC** | 1.0+ | WebRTC natif Android (SurfaceViewRenderer) |
|
|
| **FCM** | 24.1+ | Notifications push |
|
|
| **Room** | 2.7+ | Cache local offline |
|
|
|
|
## Architecture
|
|
|
|
```text
|
|
app/
|
|
├── data/ ← Ktor API client, SignalR, Room cache, DataStore
|
|
├── domain/ ← Modèles métier, interfaces repository, use cases
|
|
├── presentation/ ← Compose screens, ViewModels, navigation
|
|
└── di/ ← Hilt modules
|
|
```
|
|
|
|
## Pages
|
|
|
|
| Page | Composant | ViewModel |
|
|
|---|---|---|
|
|
| Login | `LoginScreen.kt` | `LoginViewModel.kt` |
|
|
| Dashboard | `DashboardScreen.kt` | `DashboardViewModel.kt` |
|
|
| Sites List | `SiteListScreen.kt` | `SiteListViewModel.kt` |
|
|
| Site Detail | `SiteDetailScreen.kt` | `SiteDetailViewModel.kt` |
|
|
| Camera Live | `CameraLiveScreen.kt` | `CameraLiveViewModel.kt` |
|
|
| Events List | `EventListScreen.kt` | `EventListViewModel.kt` |
|
|
| Event Detail | `EventDetailScreen.kt` | `EventDetailViewModel.kt` |
|
|
| Settings | `SettingsScreen.kt` | `SettingsViewModel.kt` |
|
|
|
|
## Tests
|
|
|
|
```
|
|
LoginUseCase: valid credentials returns Success
|
|
LoginUseCase: invalid credentials returns Error
|
|
LoginUseCase: 2FA enabled returns Requires2fa
|
|
LoginViewModel: empty email shows validation error
|
|
LoginViewModel: successful login calls onSuccess
|
|
LoginScreen: login button disabled when fields empty
|
|
LoginScreen: error displayed on invalid email
|
|
DashboardViewModel: loading state emits Loading
|
|
DashboardViewModel: error state emits Error with message
|
|
GetSitesUseCase: returns sites list
|
|
GetSitesUseCase: network error returns Error
|
|
CameraLiveViewModel: WebRTC starts on init
|
|
CameraLiveViewModel: WebRTC stops on dispose
|
|
EventListViewModel: pagination loads more events
|
|
SignalR: streaming hub connects and relays SDP
|
|
```
|
|
|
|
**Voir `docs/mobile-app.md` pour l'architecture complète, tous les écrans,
|
|
WebRTC natif, SignalR signaling, FCM, cache Room, CI/CD Gradle.**
|
|
|
|
---
|
|
|
|
# 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
|