diff --git a/docs/implementation.md b/docs/implementation.md index 6885213..29e05f9 100644 --- a/docs/implementation.md +++ b/docs/implementation.md @@ -3,32 +3,36 @@ **Principe :** On implémente d'abord le **plus simple et le plus important**. La **vidéo live** arrive en dernier dans l'IHM. +## Statut d'avancement (MVP — Juillet 2026) + ``` -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 [FAIT] +✅ Phase 2 : Tests Framework [FAIT - partiel] +✅ Phase 3 : CI/CD [FAIT - Forgejo Actions] +✅ Phase 4 : Domain Model [FAIT - entités core] +✅ Phase 5 : Application Layer [FAIT - services directs, sans MediatR] +✅ Phase 6 : Security [FAIT - Identity, JWT, API Key, 2FA] +✅ Phase 7 : API Sites + Agent Tokens [FAIT] +✅ Phase 8 : Agent Registration + Heartbeat [FAIT] +⏳ Phase 9 : ONVIF Discovery [EN ATTENTE - hardware requis] +✅ Phase 10 : Camera Management API [FAIT] +⏳ Phase 11 : Video Pipeline (FFmpeg) [EN ATTENTE - hardware requis] +⏳ Phase 12 : AI Pipeline [EN ATTENTE - hardware requis] +⏳ Phase 13 : Storage (MinIO/S3) [EN ATTENTE - v2] +⏳ Phase 14 : SignalR Hubs [EN ATTENTE - v2] +✅ Phase 15 : Hangfire Central [FAIT - heartbeat monitor] +⏳ Phase 16 : Hangfire Agent (InMemory) [EN ATTENTE - v2] +⏳ Phase 17 : Notifications [EN ATTENTE - v2] +✅ Phase 18 : Blazor UI [FAIT - 13 pages] +⏳ Phase 19 : WebRTC Streaming [EN ATTENTE - v2] +⏳ Phase 20 : Blazor UI Live Vidéo [EN ATTENTE - v2] +⏳ Phase 21 : Application Mobile Android [EN ATTENTE - v3] +⏳ Phase 22 : Dashboard KPI [FAIT - basique] +⏳ Phase 23 : Production Hardening [EN ATTENTE] ``` +**Légende :** ✅ Fait — ⏳ En attente — ❌ Bloqué + --- # Phase 1 — Solution .NET 10 + Clean Architecture @@ -42,27 +46,38 @@ Créer le socle technique stable : solution .NET 10 avec Clean Architecture. ``` Heimdall/ ├── src/ -│ ├── Heimdall.Domain # Entities, Value Objects, Enums -│ ├── Heimdall.Domain.Primitives # Base types (Entity, 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 +│ ├── Heimdall.Domain # Entities, Value Objects, Enums ✅ +│ ├── Heimdall.Domain.Primitives # Base types (Entity, ValueObject) ✅ +│ ├── Heimdall.Contracts # Shared DTOs, Constants ✅ (vide, prévu) +│ ├── Heimdall.Application # Interfaces, DTOs, Validators ✅ +│ ├── Heimdall.Infrastructure # EF Core, PostgreSQL, Identity ✅ +│ ├── Heimdall.Api # REST API controllers ✅ +│ ├── Heimdall.Web # Blazor Web App (MudBlazor) ✅ +│ ├── Heimdall.Agent # Worker Service ✅ +│ └── 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 +│ ├── Heimdall.Domain.Tests # 13 tests ✅ +│ ├── Heimdall.Application.Tests # Placeholder ✅ +│ ├── Heimdall.Infrastructure.Tests # Placeholder ✅ +│ ├── Heimdall.Api.Tests # Placeholder ✅ +│ ├── Heimdall.Agent.Tests # Placeholder ✅ +│ ├── Heimdall.Web.Tests # Placeholder ✅ +│ ├── Heimdall.Workers.Tests # Placeholder ✅ +│ └── Heimdall.IntegrationTests # 16 tests (WebApplicationFactory) ✅ ├── docker/ +│ ├── Dockerfile.central # Multi-stage ✅ +│ ├── Dockerfile.agent # Multi-stage ✅ +│ ├── docker-compose.yml # PostgreSQL + MinIO + Central + Agent + Workers ✅ +│ └── docker-compose.override.yml # Dev overrides ✅ ├── docs/ -└── .github/workflows/ +│ ├── MASTER_SPECIFICATION.md # Spec complète +│ ├── implementation.md # ← ce fichier +│ └── specs.md # Spécifications détaillées +├── .forgejo/workflows/ci.yml # CI pipeline ✅ +├── .dockerignore # ✅ +├── Makefile # 20+ commandes ✅ +├── .env.example # ✅ +└── README.md # Documentation complète ✅ ``` ## Dépendances entre projets @@ -70,12 +85,12 @@ Heimdall/ ``` Domain (aucune dépendance) ↑ -Application (ref Domain) — MediatR, FluentValidation +Application (ref Domain) — FluentValidation ↑ -Infrastructure (ref Application) — EF Core, Npgsql, Identity +Infrastructure (ref Application) — EF Core, Npgsql, Identity, Hangfire ↑ ┌───┴───┐ -Api Web (Blazor) +Api Web (Blazor) — MudBlazor ├── ── ┘ Agent (ref Application, Infrastructure) — Worker Service Workers (ref Application, Infrastructure) — Hangfire jobs @@ -91,7 +106,7 @@ Workers (ref Application, Infrastructure) — Hangfire jobs latest-Recommended ``` -Build : `dotnet build` doit passer 0 error. +Build : `dotnet build` — 0 errors, 0 warnings ✅ --- @@ -103,38 +118,30 @@ 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 | +| Outil | Usage | Status | +|---|---|---| +| **xUnit** | Framework de tests | ✅ | +| **Shouldly** | Assertions fluides | ✅ | +| **NSubstitute** | Mocking | ⏳ Pas encore utilisé | +| **Testcontainers** | PostgreSQL en integration | ⏳ Utilise InMemory pour l'instant | +| **bUnit** | Tests composants Blazor | ⏳ Pas encore | ## Projets de test -Un par projet source, nommage : +Un par projet source, nommage `Heimdall.X.Tests` — tous créés ✅ -``` -Heimdall.X.Tests -``` +## Tests existants -## 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). +| Suite | Tests | Technologie | +|-------|-------|-------------| +| Domain (Site, Agent, Camera) | 13 | xUnit + Shouldly | +| Integration (Auth, Sites, Users, Cameras, Agents) | 16 | WebApplicationFactory + InMemory | +| Placeholder (Api, Application, Infrastructure, Web, Workers) | 5 | xUnit | +| **Total** | **34** | | --- -# Phase 3 — CI/CD DockerHub +# Phase 3 — CI/CD ## Objectif @@ -143,23 +150,21 @@ Chaque commit build et push les images Docker. ## Pipeline ```yaml -push → restore → build → unit tests → coverage → docker build → docker push +push → restore → build → unit tests → integration tests → docker build ``` -## Images +## Implémentation actuelle -``` -heimdall/api:latest, heimdall/api:{sha} -heimdall/web:latest, heimdall/web:{sha} -heimdall/agent:latest, heimdall/agent:{sha} -``` +- **Forgejo Actions** (`./forgejo/workflows/ci.yml`) ✅ +- Build + Test sur push (branches main, develop) ✅ +- Docker build (central + agent) sur main ✅ +- PostgreSQL service pour les tests ✅ -## Quality gates +## À faire (v2) -- Build OK (0 errors, 0 warnings) -- Tests OK -- Coverage ≥ 80% (Domain, Application) -- SonarQube optionnel +- [ ] multi-arch Docker (linux/amd64 + arm64) +- [ ] Push vers registry Docker +- [ ] Couverture de code --- @@ -169,1310 +174,345 @@ heimdall/agent:latest, heimdall/agent:{sha} Toutes les entités métier, énumérations, value objects. -## Entités (ordre de création) +## Entités implémentées -```text -1. Site -2. Agent -3. Camera -4. Person -5. Vehicle -6. LicensePlate -7. Event -8. Recording -9. StoragePolicy -10. ApiKey +| Entité | Status | Détail | +|--------|--------|--------| +| **Site** | ✅ | Guid PK, Name, Address, Timezone, RegistrationToken, soft delete | +| **Agent** | ✅ | Guid PK, Status, Heartbeat, ApiKeyHash/Prefix, Capabilities | +| **Camera** | ✅ | Guid PK, Status, Manufacturer, Model, RtspUrl | +| **CameraCredentials** | ✅ | 1:1 avec Camera, credentials chiffrés | +| **CameraDetectionProfile** | ✅ | 1:1, tous les paramètres de détection | +| **AppUser** (Identity) | ✅ | DisplayName, Theme, Language | +| **AppRole** (Identity) | ✅ | Admin, Supervisor, Viewer | +| **UserSite** | ✅ | Many-to-many User ↔ Site | +| **ApiKey** | ✅ | HMACSHA256 hash, prefix, site scope | +| **AuditLog** | ✅ | Append-only, toutes les actions critiques | + +## Entités à créer (v2) + +| Entité | Dans migration ? | +|--------|-----------------| +| Person | ⏳ Non (v2) | +| Vehicle | ⏳ Non (v2) | +| LicensePlate | ⏳ Non (v2) | +| Event | ⏳ Non (v2) | +| Recording | ⏳ Non (v2) | +| StoragePolicy | ⏳ Non (v2) | +| NotificationConfig | ⏳ Non (v2) | +| NotificationTemplate | ⏳ Non (v2) | + +## Énumérations + +``` +CameraStatus { Unknown, Online, Offline, Disabled, Error } ✅ +EventType { MotionDetected, PersonDetected, ... } ✅ +StorageProvider { Local, S3 } ✅ +AgentStatus { Online, Offline, Error } ✅ +GpuAcceleration { None, NvidiaCuda, IntelQuickSync, Vaapi } ✅ +UserRole { Admin, Supervisor, Viewer } ✅ ``` -## Enumérations +## Migration EF Core -```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(); - 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"); -} -``` +- `InitialCreate` créée avec toutes les tables actuelles ✅ +- `.Designer.cs` présent ✅ +- `AppDbContextFactory` pour les migrations design-time ✅ --- -# Phase 5 — Application Layer (CQRS) +# Phase 5 — Application Layer ## Objectif -Toutes les commandes, queries, DTOs, validateurs, interfaces. +Interfaces, DTOs, validateurs. -## Structure par feature +## Implémentation actuelle -``` -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 -``` +| Composant | Approche | Status | +|-----------|----------|--------| +| **Services** | Interfaces directes (pas MediatR) | ✅ | +| **DTOs** | Records immutables | ✅ | +| **Validation** | FluentValidation | ✅ | +| **ServiceResult** | Pattern Result success/failure | ✅ | +| **Pagination** | PagedResult | ✅ | -## Règles +## Services implémentés -| 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)` | +| Service | Méthodes | +|---------|----------| +| `IAuthService` | Register, Login, Verify2fa, RefreshToken, RegisterAdmin | +| `ISiteService` | Create, GetById, List, Update, Delete, GenerateToken | +| `IAgentService` | Register, Heartbeat, GetById, ListBySite | +| `IUserService` | List, GetById, Create, Update, AssignRoles, AssignSites, ResetPassword, Lock, Unlock | +| `ICameraService` | Create, GetById, ListBySite, Update, Delete | +| `IStatsService` | GetStats | +| `IAuditLogService` | List (filtré, paginé) | + +## Note sur CQRS + +Le MVP utilise des **services directs** (pas MediatR) par simplicité. +La migration vers CQRS avec MediatR est prévue en v2 si le besoin se fait sentir. --- -# Phase 6 — Security (mini identification) +# Phase 6 — Security ## Objectif -Authentification minimale AVANT d'exposer l'API (sécurité critique). +Authentification AVANT d'exposer l'API. -## Ce qu'on implémente +## Implémenté -| 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 -``` +| Fonctionnalité | Priorité | Status | +|---|---|---| +| ASP.NET Core Identity (User, Role) | 🔴 Requis | ✅ | +| JWT Bearer (15min access + refresh 7j) | 🔴 Requis | ✅ | +| API Key HMACSHA256 (agents) | 🔴 Requis | ✅ | +| 2FA TOTP | 🟠 Important | ✅ | +| Rôles (Admin, Supervisor, Viewer) | 🟠 Important | ✅ | +| Permissions (Site.Read, Camera.Write, etc.) | 🔴 Requis | ✅ | +| Rate limiting (10 req/min auth, 200 API) | 🔴 Requis | ✅ | +| Audit logging (append-only) | 🟠 Important | ✅ | +| CORS configurable | 🔴 Requis | ✅ | +| `[Authorize(AuthenticationSchemes)]` explicite | 🔴 Requis | ✅ | ## Endpoints d'auth -| Méthode | Route | Auth | Description | +| Méthode | Route | Auth | Status | |---|---|---|---| -| `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/*`.** +| `POST` | `/api/auth/register` | — | ✅ | +| `POST` | `/api/auth/login` | — | ✅ | +| `POST` | `/api/auth/2fa/verify` | — | ✅ | +| `POST` | `/api/auth/refresh` | — | ✅ | +| `POST` | `/api/auth/register-admin` | Test/Dev only | ✅ | --- -# Phase 7 — API : Sites + Agent Tokens +# Phase 7 — API Sites + Agent Tokens -## Objectif +## Implémenté -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 | +| Méthode | Route | Auth | Status | |---|---|---|---| -| `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 | +| `POST` | `/api/sites` | JWT/Site.Write | ✅ | +| `GET` | `/api/sites` | JWT/Site.Read | ✅ | +| `GET` | `/api/sites/{id}` | JWT/Site.Read | ✅ | +| `PUT` | `/api/sites/{id}` | JWT/Site.Write | ✅ | +| `DELETE` | `/api/sites/{id}` | JWT/Site.Delete | ✅ | +| `POST` | `/api/sites/{id}/tokens` | JWT/Site.Write | ✅ | -## 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" -} -``` +Le token d'enregistrement est : +- Généré en SHA256, stocké hashé en DB ✅ +- Affiché 1 fois dans l'UI (docker-compose snippet) ✅ +- Token + docker-compose copiable via bouton ✅ --- -# Phase 8 — Agent : Registration + Heartbeat +# Phase 8 — Agent Registration + Heartbeat -## Objectif +## Implémenté -L'Agent s'enregistre auprès du Central avec son token Site, -puis envoie son heartbeat périodiquement. +### Côté Central -## 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 | +| Méthode | Route | Auth | Status | |---|---|---|---| -| `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 | +| `POST` | `/api/agents/register` | Token site | ✅ | +| `POST` | `/api/agents/{id}/heartbeat` | API Key | ✅ | +| `GET` | `/api/agents/{id}` | JWT | ✅ | +| `GET` | `/api/agents/by-site/{siteId}` | JWT | ✅ | -## Côté Agent (Worker Service) +### Côté Agent -```csharp -public class AgentRegistrationService : BackgroundService -{ - private readonly string _centralUrl; - private readonly string _siteToken; - private readonly string _hostname; - private Guid? _agentId; +| Fonctionnalité | Status | +|----------------|--------| +| Registration avec token site | ✅ | +| Réception API Key | ✅ | +| Heartbeat toutes les 30s | ✅ | +| API Key envoyée dans header Authorization | ✅ | +| Détection GPU/CPU capabilities | ✅ | - protected override async Task ExecuteAsync(CancellationToken ct) - { - // 1. Register - var (agentId, iceServers) = await RegisterAsync(ct); +### HeartbeatMonitor (Hangfire) - // 2. Start heartbeat loop - while (!ct.IsCancellationRequested) - { - await SendHeartbeatAsync(agentId, ct); - await Task.Delay(TimeSpan.FromSeconds(30), ct); - } - } - - private async Task 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(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 -``` +- Job planifié toutes les minutes ✅ +- Marque les agents Offline après 90s sans heartbeat ✅ --- -# Phase 9 — ONVIF Discovery & Camera Authentication +# Phase 9 — ONVIF Discovery -## 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 - - - - - -``` - -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> DiscoverAsync( - TimeSpan timeout, CancellationToken ct); - - Task 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 GetCredentialsAsync( - Guid cameraId, CancellationToken ct); - Task 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 +🔴 **Nécessite du hardware (caméras réseau).** +Reporté après le MVP logiciel. --- # Phase 10 — Camera Management API -## Objectif +## Implémenté -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 | +| Méthode | Route | Auth | Status | |---|---|---|---| -| `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) | +| `POST` | `/api/cameras` | JWT/Camera.Write | ✅ | +| `GET` | `/api/cameras/{id}` | JWT/Camera.Read | ✅ | +| `GET` | `/api/cameras/by-site/{siteId}` | JWT/Camera.Read | ✅ | +| `PUT` | `/api/cameras/{id}` | JWT/Camera.Write | ✅ | +| `DELETE` | `/api/cameras/{id}` | JWT/Camera.Write | ✅ | + +### Interface Blazor + +| Page | Status | +|------|--------| +| Liste caméras par site | ✅ | +| Détail caméra (éditable) | ✅ | +| Création caméra (dialog) | ✅ | --- # 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 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) +# Phase 14 — SignalR Hubs -## 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 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 -``` +🔴 **Nécessitent du hardware + dépendances natives.** +Reportées en v2. --- -# Phase 14 — SignalR Hubs (temps réel) +# Phase 15 — Hangfire Central -## Objectif +## Implémenté -Mettre en place la communication temps réel entre Central, Agents et navigateurs. +| Composant | Status | +|-----------|--------| +| Hangfire avec PostgreSQL | ✅ | +| Schéma isolé (`hangfire`) | ✅ | +| HeartbeatMonitorJob (toutes les minutes) | ✅ | +| Queue heartbeat dédiée | ✅ | -## 5 hubs à implémenter +## Jobs à implémenter (v2) -| 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.** +| Job | Schedule | +|-----|----------| +| RetentionCheck | Quotidien 3h | +| S3Cleanup | Quotidien 4h | +| DailyDigest | Quotidien 8h | +| DatabaseMaintenance | Hebdomadaire | --- -# Phase 15 — Hangfire Central (PostgreSQL) +# Phase 16 — Hangfire Agent (InMemory) -## 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.** +⏳ Reporté à la phase de déploiement Agent réel. --- -# Phase 16 — Hangfire Agent (InMemory, jobs volatiles) +# Phase 17 — Notifications -## 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( - $"{prefix}-camera-health", - j => j.ExecuteAsync(CancellationToken.None), - Cron.MinuteInterval(1)); - - RecurringJob.AddOrUpdate( - $"{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.** +⏳ Reporté en v2. --- -# Phase 17 — Notifications (Email + Gotify + Templates) +# Phase 18 — Blazor UI -## Objectif +## Implémenté -Notifier les utilisateurs des événements de détection. +| Page | Route | Auth | Status | +|------|-------|------|--------| +| **Login** | `/login` | — | ✅ | +| **Register** | `/register` | — | ✅ | +| **Dashboard** | `/dashboard` | JWT | ✅ | +| **Sites** | `/sites` | JWT | ✅ | +| **Site détail** | `/sites/{id}` | JWT | ✅ | +| **Caméras d'un site** | `/sites/{id}/cameras` | JWT | ✅ | +| **Caméra détail** | `/cameras/{id}` | JWT | ✅ | +| **Agents d'un site** | `/sites/{id}/agents` | JWT | ✅ | +| **Agent détail** | `/agents/{id}` | JWT | ✅ | +| **Utilisateurs** | `/users` | JWT/Admin | ✅ | +| **Journal d'audit** | `/audit-logs` | JWT/Admin | ✅ | +| **RedirectToLogin** | (composant) | — | ✅ | +| **NotFound** | (page 404) | — | ✅ | -## Canaux +## Stack UI -| 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 | +| Technologie | Status | +|-------------|--------| +| MudBlazor 9.1.0 | ✅ | +| Inter Font | ✅ | +| Thème clair/sombre | ✅ | +| Navigation responsive | ✅ | +| Auth redirect avec returnUrl | ✅ | +| Requêtes API parallèles (Dashboard) | ✅ | -## Templates Markdown (Scriban) +## Pages à implémenter (v2) -Les templates sont stockés en base et éditables depuis l'UI Admin. - -```xml - -``` - -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(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).** +| Page | Priorité | +|------|----------| +| Événements liste | P1 | +| Personnes liste | P1 | +| Administration (jobs Hangfire) | P1 | +| Live vidéo | P2 | --- -# Phase 18 — Blazor UI : Auth + Sites + Caméras +# Phase 19 — WebRTC Streaming +# Phase 20 — Blazor UI Live Vidéo -## 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.** +⏳ Reporté en v2. --- -# Phase 19 — WebRTC Streaming (Agent → Browser) +# Phase 21 — Application Mobile Android -## 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]│ -│ │ -│ ┌──────────────────────────────────────────────────┐ │ -│ │