From 3adb44449effc3c9fb151e41be9e39dccbadcbdb Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 16 Jul 2026 19:33:11 +0000 Subject: [PATCH] docs: restructure with README index, trim specs.md, replace Refit with Kiota MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Create docs/README.md as central navigation index with quick links - Rewrite specs.md from 1473 to 253 lines — remove all content now duplicated in dedicated files, keep only unique content (vision, architecture, domain model, features, Docker, quality) - Replace Refit with Kiota (Microsoft) in mobile-app.md: - Kiota generates API client from OpenAPI spec - IAuthenticationProvider for JWT - CI/CD regeneration step - Comparison table Kiota vs Refit - All NuGet deps updated --- docs/README.md | 69 ++ docs/mobile-app.md | 346 +++++++--- docs/specs.md | 1594 ++++++-------------------------------------- 3 files changed, 491 insertions(+), 1518 deletions(-) create mode 100644 docs/README.md diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..9e1ad3b --- /dev/null +++ b/docs/README.md @@ -0,0 +1,69 @@ +# Heimdall — Documentation + +Bienvenue dans la documentation technique de Heimdall, plateforme de +vidéosurveillance IA locale, multi-site, auto-hébergée. + +--- + +## 🧭 Par où commencer + +| Si vous cherchez... | Allez voir | +|---|---| +| **Vue d'ensemble** du projet | `docs/specs.md` (Vision, Architecture, Stack) | +| **Plan d'implémentation** (23 phases) | `docs/implementation.md` | +| **Maquettes UI Blazor** détaillées | `docs/ui-pages.md` | +| **Application Android** (Avalonia UI) | `docs/mobile-app.md` | + +## 🏗️ Domaines fonctionnels + +| Domaine | Document | Contenu | +|---|---|---| +| **Sites & Agents** | `docs/specs.md` (§11-12) | Sites, tokens, registration, heartbeat, bootstrap | +| **Caméras & IA** | `docs/specs.md` (§14-19) | ONVIF, Imou, FFmpeg, GPU, AI Pipeline, détection | +| **Streaming live** | `docs/specs.md` (§13) + `docs/signalr-usage.md` | WebRTC, SIPSorcery, SFU, signaling, JS Interop | +| **Enregistrements** | `docs/specs.md` (§20-21) + `docs/hangfire-usage.md` | MinIO/S3, rétention, stockage local | +| **Événements** | `docs/specs.md` (§16-19) | Personnes, véhicules, plaques, notifications | +| **Notifications** | `docs/notifications.md` | Email SMTP, Gotify, templates Markdown i18n | + +## 🔧 Domaines techniques + +| Domaine | Document | Contenu | +|---|---|---| +| **Auth & Rôles** | `docs/auth-roles.md` | Identity, JWT, permissions, UI par rôle, site-scope | +| **Hangfire (jobs)** | `docs/hangfire-usage.md` | Central PostgreSQL, Agent InMemory, tous les jobs | +| **SignalR (temps réel)** | `docs/signalr-usage.md` | 5 hubs, events, streaming, monitoring, notifications | +| **Déploiement Docker** | `docs/specs.md` (§30) | Containers, GPU passthrough, docker-compose | + +## 📐 Structure du projet + +``` +Heimdall/ +├── src/ +│ ├── Heimdall.Domain # Entités, Value Objects, Enums +│ ├── Heimdall.Domain.Primitives # Types de base (Entity, ValueObject) +│ ├── Heimdall.Contracts # DTOs partagés, constantes +│ ├── Heimdall.Application # CQRS (Command/Query/Handler) +│ ├── Heimdall.Infrastructure # EF Core, PostgreSQL, S3, Identity +│ ├── Heimdall.Api # API REST + SignalR Hubs +│ ├── Heimdall.Web # Blazor Web App (MudBlazor) +│ ├── Heimdall.Agent # Worker + SIPSorcery + FFmpeg +│ └── Heimdall.Workers # Hangfire jobs +├── tests/ # xUnit + Shouldly + NSubstitute +├── docker/ # Docker Compose + Dockerfiles +└── docs/ # Documentation (ce dossier) +``` + +## 📋 Fichiers de documentation + +| Fichier | Description | +|---|---| +| `specs.md` | Spécification complète : vision, architecture, features, déploiement | +| `implementation.md` | Plan d'implémentation en 23 phases ordonnées | +| `ui-pages.md` | Pages Blazor (MudBlazor) : maquettes ASCII, composants, états | +| `mobile-app.md` | App Android (Avalonia UI) : 6 pages, WebRTC, offline, push | +| `auth-roles.md` | Auth : 2 user types, permissions, site-scope, UI visibility | +| `notifications.md` | Email (SMTP), Gotify, templates Markdown i18n, hangfile queue | +| `hangfire-usage.md` | Jobs Central (PostgreSQL) + Agent (InMemory) complets | +| `signalr-usage.md` | 5 hubs SignalR : events, streaming, monitoring, notifications, admin | + +**Total : ~5 600 lignes de documentation** diff --git a/docs/mobile-app.md b/docs/mobile-app.md index cf6f70b..bbfa626 100644 --- a/docs/mobile-app.md +++ b/docs/mobile-app.md @@ -35,7 +35,7 @@ Elle permet uniquement de **consulter** — aucune configuration. | **Microsoft.AspNetCore.SignalR.Client** | 10.x | SignalR pour temps réel | | **CommunityToolkit.Mvvm** | 8.x+ | MVVM pattern | | **ReactiveUI** | 19.x+ | Bindings réactifs (optionnel) | -| **Refit** | 7.x+ | Typed HTTP API client | +| **Kiota** | 1.15+ | Client API généré depuis OpenAPI (Microsoft) | | **Serilog** | 3.x+ | Logging mobile | ### Pourquoi Avalonia et pas MAUI ? @@ -76,8 +76,8 @@ Heimdall.Mobile/ │ ├── EventListViewModel.cs │ └── EventDetailViewModel.cs ├── Services/ # Services -│ ├── IApiClient.cs # Interface Refit -│ ├── ApiClient.cs # Implémentation Refit +│ ├── ApiClient/ # Généré par Kiota (OpenAPI) +│ ├── IAuthenticationProvider.cs # Provider JWT pour Kiota │ ├── IAuthService.cs # JWT token management │ ├── AuthService.cs │ ├── ISignalRService.cs # SignalR connection @@ -111,9 +111,11 @@ Heimdall.Mobile/ - - - + + + + + @@ -124,161 +126,283 @@ Heimdall.Mobile/ --- -## 4. API Client — Refit +## 4. API Client — Kiota (Microsoft) + +[Kiota](https://learn.microsoft.com/en-us/kiota/) est le générateur de client +API officiel Microsoft. Il génère un client typé, asynchrone et compatible +.NET AOT à partir d'un fichier OpenAPI. + +### Installation + +```bash +# Installer le CLI Kiota (une fois) +dotnet tool install --global Microsoft.OpenApi.Kiota + +# Vérifier +kiota --version +``` + +### Génération du client mobile + +L'API Heimdall expose un endpoint OpenAPI (`/openapi/v1.json`). +On génère un client dédié à la partie mobile : + +```bash +# Depuis le dossier de la solution Heimdall +kiota generate \ + --language csharp \ + --openapi https://localhost:5001/openapi/v1.json \ + --namespace-name Heimdall.Mobile.ApiClient \ + --output src/Heimdall.Mobile/ApiClient \ + --include-path "/api/auth/**" \ + --include-path "/api/mobile/**" \ + --clean-output +``` + +> **Filtrage** : on inclut uniquement `/api/auth/*` et `/api/mobile/*` +> (pas les endpoints d'admin). Cela réduit la taille du client généré +> et évite d'exposer des endpoints non-accessibles au mobile. + +### Arborescence générée + +``` +Heimdall.Mobile/ +└── ApiClient/ + ├── ApiClientService.cs # Client principal (HttpClient wrapper) + ├── IAuthenticationProvider.cs # Interface pour le token JWT + ├── Models/ + │ ├── SiteDto.cs # DTOs générés depuis OpenAPI + │ ├── CameraDto.cs + │ ├── EventDto.cs + │ ├── LoginRequest.cs + │ └── LoginResponse.cs + ├── Auth/ + │ ├── AuthRequestBuilder.cs # POST /api/auth/login + │ └── AuthRequestExecutor.cs + └── Mobile/ + ├── SitesRequestBuilder.cs # GET /api/mobile/sites + ├── CamerasRequestBuilder.cs + └── EventsRequestBuilder.cs +``` + +### Utilisation du client généré ```csharp -public interface IHeimdallApi +// ─── Configuration DI ───────────────────────────────────── +public static IServiceCollection AddHeimdallApiClient( + this IServiceCollection services, string baseUrl) { - // ─── Auth ────────────────────────────────────────── - [Post("/api/auth/login")] - Task LoginAsync([Body] LoginRequest request); + // Le client Kiota a besoin de 2 choses : + // 1. Un HttpClient pointant vers le Central + // 2. Un IAuthenticationProvider pour le Bearer JWT - [Post("/api/auth/refresh")] - Task RefreshTokenAsync([Body] RefreshRequest request); + services.AddHttpClient("HeimdallApi", client => + { + client.BaseAddress = new Uri(baseUrl); + }); - // ─── Sites (uniquement ceux auxquels l'user a accès) ─ - [Get("/api/mobile/sites")] - Task> GetMySitesAsync( - [Authorize] string token); + services.AddSingleton(); + services.AddSingleton(); - [Get("/api/mobile/sites/{siteId}")] - Task GetSiteDetailAsync( - Guid siteId, [Authorize] string token); + return services; +} - // ─── Cameras ─────────────────────────────────────── - [Get("/api/mobile/sites/{siteId}/cameras")] - Task> GetCamerasAsync( - Guid siteId, [Authorize] string token); +// ─── Authentication Provider ────────────────────────────── +public class JwtAuthProvider : IAuthenticationProvider, IDisposable +{ + private readonly IPreferences _prefs; + private readonly HttpClient _httpClient; + private string? _accessToken; - [Get("/api/mobile/cameras/{cameraId}")] - Task GetCameraDetailAsync( - Guid cameraId, [Authorize] string token); + public JwtAuthProvider(IPreferences prefs, IHttpClientFactory httpFactory) + { + _prefs = prefs; + _httpClient = httpFactory.CreateClient("HeimdallApi"); + _accessToken = _prefs.Get("access_token", ""); + } - // ─── Live stream signaling (WebRTC) ─────────────── - [Get("/api/mobile/cameras/{cameraId}/stream-info")] - Task GetStreamInfoAsync( - Guid cameraId, [Authorize] string token); - // Retourne : { cameraId, agentEndpoint, iceServers[] } + public async Task AuthenticateRequestAsync(HttpRequestMessage request) + { + // Vérifier si le token est expiré et le refresh si nécessaire + var expiresAt = _prefs.Get("token_expires_at", ""); + if (DateTime.TryParse(expiresAt, out var expiry) && expiry < DateTime.UtcNow) + { + await RefreshTokenAsync(); + } - // ─── Events ──────────────────────────────────────── - [Get("/api/mobile/sites/{siteId}/events")] - Task> GetEventsAsync( - Guid siteId, - [Query] int page = 1, - [Query] int pageSize = 20, - [Query] string? type = null, - [Authorize] string token); + request.Headers.Authorization = + new AuthenticationHeaderValue("Bearer", _accessToken); + } - [Get("/api/mobile/events/{eventId}")] - Task GetEventDetailAsync( - Guid eventId, [Authorize] string token); + private async Task RefreshTokenAsync() + { + // Appel à /api/auth/refresh via Kiota + var authClient = new AuthRequestBuilder(_httpClient); + var refreshToken = _prefs.Get("refresh_token", ""); + var response = await authClient.Refresh.PostAsync(new RefreshRequest(refreshToken)); - // ─── Persons ─────────────────────────────────────── - [Get("/api/mobile/persons")] - Task> GetPersonsAsync( - [Authorize] string token); + _accessToken = response?.AccessToken; + _prefs.Set("access_token", response!.AccessToken); + _prefs.Set("refresh_token", response.RefreshToken); + _prefs.Set("token_expires_at", response.ExpiresAt.ToString("O")); + } - [Get("/api/mobile/persons/{personId}")] - Task GetPersonDetailAsync( - Guid personId, [Authorize] string token); + public void Dispose() => _httpClient.Dispose(); +} + +// ─── Exemple d'appel dans un ViewModel ──────────────────── +public class SiteListViewModel : ObservableObject +{ + private readonly ApiClientService _client; + + public SiteListViewModel(ApiClientService client) + { + _client = client; + } + + public async Task LoadSitesAsync() + { + // L'appel est typé, asynchrone, et l'auth est automatique + var sites = await _client.Mobile.Sites.GetAsync(); + + Sites.Clear(); + foreach (var site in sites ?? []) + { + Sites.Add(new SiteItemViewModel + { + Id = site.Id, + Name = site.Name, + CameraCount = site.CameraCount, + OnlineCount = site.OnlineCameraCount, + ThumbnailUrl = site.ThumbnailUrl + }); + } + } } ``` +### Avantages de Kiota vs Refit + +| Critère | Kiota | Refit | +|---|---|---| +| Génération | Depuis OpenAPI (contrat) | Attributs C# manuels | +| Synchronisation | `kiota generate` = contrat à jour | Manuelle | +| Compatibilité AOT | ✅ Native | ❌ Génération dynamique | +| Maintenance | Microsoft (actif) | Communauté (ralenti) | +| Langages supportés | C#, Java, Python, Go, Ruby, TS | C# uniquement | +| Filtrage endpoints | ✅ `--include-path` | ❌ Tout ou rien | + ### Endpoints API Mobile dédiés Les endpoints mobiles sont préfixés `/api/mobile/` et retournent des DTOs optimisés pour l'affichage mobile (payload réduit, images redimensionnées). -```csharp -public record SiteDto( - Guid Id, - string Name, - int CameraCount, - int OnlineCameraCount, - int UnreadEventCount, - string? ThumbnailUrl); // petite vignette +```yaml +# openapi.yml — endpoint mobile example +/api/mobile/sites: + get: + summary: Liste des sites accessibles à l'utilisateur + security: [{ bearerAuth: [] }] + responses: + 200: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SiteMobileDto' -public record CameraDto( - Guid Id, - string Name, - string Status, // "Online", "Offline", "Disabled" - string? ThumbnailUrl, // dernier snapshot (taille réduite) - bool HasLiveAccess); // l'user peut voir le live +SiteMobileDto: + type: object + properties: + id: { type: string, format: uuid } + name: { type: string } + cameraCount: { type: integer } + onlineCameraCount: { type: integer } + unreadEventCount: { type: integer } + thumbnailUrl: { type: string, format: uri, nullable: true } -public record EventDto( - Guid Id, - string EventType, - string CameraName, - string SiteName, - DateTime Timestamp, - string? ThumbnailUrl, // snapshot redimensionné (320x240) - bool IsRead); // déjà consulté sur mobile +CameraMobileDto: + type: object + properties: + id: { type: string, format: uuid } + name: { type: string } + status: { type: string, enum: [Online, Offline, Disabled] } + thumbnailUrl: { type: string, format: uri, nullable: true } + hasLiveAccess: { type: boolean } -public record StreamInfoDto( - Guid CameraId, - string IceEndpoint, // Agent public endpoint ou SFU - List IceServers); +EventMobileDto: + type: object + properties: + id: { type: string, format: uuid } + eventType: { type: string } + cameraName: { type: string } + siteName: { type: string } + timestamp: { type: string, format: date-time } + thumbnailUrl: { type: string, format: uri, nullable: true } + isRead: { type: boolean } +``` -public record IceServerDto( - string Urls, // "stun:...", "turn:..." - string? Username, - string? Credential); +### Mise à jour du client (CI/CD) + +Le client Kiota est régénéré automatiquement à chaque modification de l'API : + +```yaml +# .github/workflows/mobile.yml (extrait) +- name: Generate API client + run: | + # Démarrer l'API, générer l'OpenAPI, puis générer le client + dotnet run --project src/Heimdall.Api & + sleep 5 + kiota generate \ + --language csharp \ + --openapi http://localhost:5000/openapi/v1.json \ + --namespace-name Heimdall.Mobile.ApiClient \ + --output src/Heimdall.Mobile/ApiClient \ + --include-path "/api/auth/**" \ + --include-path "/api/mobile/**" \ + --clean-output ``` --- ## 5. Authentification — JWT Token +L'authentification est gérée par le `JwtAuthProvider` (implémente +`IAuthenticationProvider` Kiota). Voir §4 pour le code complet. + +Le service de login utilise directement le builder généré par Kiota : + ```csharp public class AuthService : IAuthService { - private readonly IPreferences _prefs; // stockage local sécurisé - private readonly IHeimdallApi _api; + private readonly IPreferences _prefs; + private readonly IHttpClientFactory _httpFactory; public async Task LoginAsync(string email, string password) { - var response = await _api.LoginAsync(new LoginRequest(email, password)); + var client = _httpFactory.CreateClient("HeimdallApi"); - // Stocker le token dans les préférences sécurisées Android + var authBuilder = new AuthRequestBuilder(client); + var response = await authBuilder.Login.PostAsync( + new LoginRequest { Email = email, Password = password }); + + if (response?.AccessToken == null) + return LoginResult.Failure("Identifiants invalides"); + + // Stocker dans les préférences sécurisées Android _prefs.Set("access_token", response.AccessToken); _prefs.Set("refresh_token", response.RefreshToken); _prefs.Set("token_expires_at", response.ExpiresAt.ToString("O")); - _httpClient.DefaultRequestHeaders.Authorization = - new AuthenticationHeaderValue("Bearer", response.AccessToken); - return LoginResult.Success; } - public async Task TryRefreshTokenAsync() - { - var refreshToken = _prefs.Get("refresh_token", string.Empty); - if (string.IsNullOrEmpty(refreshToken)) return false; - - try - { - var response = await _api.RefreshTokenAsync( - new RefreshRequest(refreshToken)); - - _prefs.Set("access_token", response.AccessToken); - _prefs.Set("refresh_token", response.RefreshToken); - _prefs.Set("token_expires_at", response.ExpiresAt.ToString("O")); - return true; - } - catch - { - // Token refresh failed → déconnexion - await LogoutAsync(); - return false; - } - } - public async Task LogoutAsync() { _prefs.Remove("access_token"); _prefs.Remove("refresh_token"); _prefs.Remove("token_expires_at"); - _httpClient.DefaultRequestHeaders.Authorization = null; } } ``` diff --git a/docs/specs.md b/docs/specs.md index bc837c1..93daea8 100644 --- a/docs/specs.md +++ b/docs/specs.md @@ -1,1473 +1,253 @@ -> **Documentation associée :** -> - `docs/ui-pages.md` — Description détaillée de toutes les pages UI (Blazor) -> - `docs/mobile-app.md` — Application Android (Avalonia UI) — consultation uniquement -> - `docs/auth-roles.md` — Authentification, rôles, permissions, visibilité UI -> - `docs/notifications.md` — Email SMTP, Gotify, templates Markdown i18n -> - `docs/hangfire-usage.md` — Tous les jobs Hangfire (Central + Agent) -> - `docs/signalr-usage.md` — Tous les hubs SignalR (events, streaming, monitoring) -> - `docs/implementation.md` — Plan d'implémentation complet par phases +# Heimdall — Spécification technique -````markdown -# Heimdall -## Intelligent Local AI Video Surveillance Platform - -**Version:** 1.0 -**Target Framework:** .NET 10+ -**Architecture:** Clean Architecture / CQRS / Multi-site / Local AI +> **Version :** 1.0 | **Target :** .NET 10+ | **Architecture :** Clean Architecture / CQRS / Multi-site / Local AI --- # 1. Vision -## Overview +Heimdall is a modern self-hosted intelligent video surveillance platform. +100% local AI, no cloud dependency, multi-site distributed architecture. -Heimdall is a modern self-hosted intelligent video surveillance platform designed around: +## Pourquoi Heimdall ? -- Local AI processing -- Multi-site architecture -- ONVIF camera discovery -- RTSP video management -- Face recognition -- License plate recognition -- Local LLM analysis -- Enterprise security model -- Full configuration through Web UI - -Heimdall does not depend on cloud services. - -All business configuration is stored in PostgreSQL and managed through the application interface. +- **Privacy first** — tout l'IA tourne en local (CodeProject.AI + Ollama) +- **Multi-site** — un Central + N Agents distants +- **Économique** — pas d'abonnement cloud, hardware standard +- **Pérenne** — .NET 10, Clean Architecture, open source --- -# 2. Main Objectives +# 2. Objectifs techniques -## Functional Objectives - -- Manage multiple sites -- Automatically discover ONVIF cameras -- Support Imou cameras at minimum -- Record and manage video streams -- Detect people, vehicles and objects -- Recognize known persons -- Detect and read license plates -- Associate vehicles with persons -- Generate AI summaries using Ollama -- Provide secure API access -- Provide complete administration through Blazor UI +- Clean Architecture / CQRS / MédiatR +- Multi-site : 1 serveur Central + N Agents Docker distants +- Live vidéo : WebRTC P2P (SIPSorcery), latence < 500 ms +- IA locale : CodeProject.AI (GPU) + Ollama (LLM résumés) +- Espace utilisateur : Admin (global) + User (site-scope) +- Stockage : MinIO/S3 centralisé +- Temps réel : SignalR (5 hubs) +- Jobs planifiés : Hangfire (Central PGSQL + Agent InMemory) +- Stack : .NET 10, Blazor MudBlazor, PostgreSQL +- Pas de cloud, pas de dépendance externe --- -## Technical Objectives - -- 100% Docker deployment -- .NET 10+ -- PostgreSQL as unique source of configuration -- No business configuration files -- Local-first architecture -- GPU acceleration when available -- Enterprise logging and monitoring - ---- - -# 3. Naming - -## Heimdall - -Inspired by Norse mythology. - -Heimdall is the guardian watching the Bifröst bridge. - -Mission: - -> Protect and monitor your infrastructure. - ---- - -# 4. Global Architecture +# 3. Architecture globale ```text - Heimdall Central - (ASP.NET Core + Blazor) - | - ┌───────────┼──────────────┐ - │ Signaling │ HTTPS API │ - │ (SignalR) │ (REST) │ - └─────┬─────┴──────┬────────┘ - │ │ - │ ┌─────────┴──────────┐ - │ │ PostgreSQL │ - │ │ + STUN/TURN │ - │ │ (coturn - Docker) │ - │ └────────────────────┘ - │ - ┌────────────┴────────────┐ - │ WebRTC P2P Signaling │ - │ (SDP + ICE via SignalR)│ - └────────────┬────────────┘ - │ - ┌─────┴──────┐ - │ │ - ┌──────────┴──────┐ ┌──┴────────────────┐ - │ Heimdall Agent │ │ Heimdall Agent │ - │ (Site A) │ │ (Site B) │ - │ │ │ │ - │ SIPSorcery │ │ SIPSorcery │ - │ WebRTC Peer │ │ WebRTC Peer │ - │ FFmpeg → H264 │ │ FFmpeg → H264 │ - └──┬───────────────┘ └───┬────────────────┘ - │ │ - │ Flux WebRTC P2P │ Flux WebRTC P2P - │ ◄══════════════════► │ ◄══════════════► - │ (SRTP/SCTP direct) │ (SRTP/SCTP) - └──────────────────────┘ - │ - ┌────────┴────────┐ - │ STUN/TURN │ - │ (si double NAT)│ - └─────────────────┘ - -```` - ---- - -# 5. Solution Structure - -```text -Heimdall.sln - -src/ - -├── Heimdall.Domain -├── Heimdall.Application -├── Heimdall.Infrastructure -├── Heimdall.Api -├── Heimdall.Web -├── Heimdall.Agent -├── Heimdall.Workers -├── Heimdall.Contracts -└── Heimdall.Shared +┌──────────────────────────────────────────────────────────────────┐ +│ HEIMDALL CENTRAL │ +│ │ +│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │ +│ │ API │ │ Web │ │ Workers │ │ CodeProject.AI │ │ +│ │ REST + │ │ Blazor │ │ Hangfire │ │ Ollama │ │ +│ │ SignalR │ │ MudBlazor│ │ Jobs │ │ MinIO │ │ +│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └──────────────────┘ │ +│ │ │ │ │ +│ └──────────────┴─────────────┘ │ +│ │ PostgreSQL / MinIO │ +└─────────────────────────┼────────────────────────────────────────┘ + │ + HTTPS REST + SignalR (signaling) + │ + ┌───────────┴───────────┐ + │ │ + ┌────────┴────────┐ ┌────────┴────────┐ + │ Agent A │ │ Agent B │ + │ (site distant) │ │ (site distant) │ + │ │ │ │ + │ SIPSorcery │ │ SIPSorcery │ + │ WebRTC Peer │ │ WebRTC Peer │ + │ FFmpeg capture │ │ FFmpeg capture │ + │ Hangfire memory │ │ Hangfire memory │ + └────────┬────────┘ └────────┬────────┘ + │ │ + P2P WebRTC (SRTP/H264) │ + ◄══════════════════════════════►│ + Navigateur ``` --- -# 6. Technology Stack +# 4. Domain Model — Entités principales -## Backend +``` +Site Agent Camera +├── Id (Guid) ├── Id (Guid) ├── Id (Guid) +├── Name ├── SiteId (FK) ├── SiteId (FK) +├── Address ├── Name ├── Name +├── Timezone ├── Hostname ├── Manufacturer +├── Enabled ├── Version ├── Model +└── Registration ├── Status ├── RtspUrl + Token (hash) │ (Online/Offline/Err) ├── Status + TokenPlain ├── LastHeartbeat ├── Capabilities + TokenExpiresAt ├── PublicIp │ (Ptz, Audio, Motion) + └── Capabilities ├── Credentials (encrypted) + HasGpu, CpuCores └── StoragePolicyId -* .NET 10+ -* C# -* ASP.NET Core -* Blazor Web App -* Clean Architecture -* CQRS -* MediatR -* FluentValidation -* Entity Framework Core -* Hangfire -* Serilog -* OpenTelemetry ready -* Sentry SDK compatible with GlitchTip -* **SignalR** — WebRTC signaling (SDP + ICE exchange) -* **SIPSorcery** — WebRTC peer (ICE, STUN, TURN, DTLS, SRTP) -* **SIPSorceryMedia.FFmpeg** — Codec H264 via FFmpeg -* **coturn** — TURN relay (optionnel, double NAT) +Person Vehicle Event +├── Id ├── Id ├── Id +├── Name ├── LicensePlate ├── SiteId +├── Photo ├── PersonId (FK) ├── CameraId +├── IsUnknown ├── Make ├── Type (enum) +├── FaceSamples ├── Model ├── Timestamp +└── Notes └── Color ├── SnapshotPath + └── Metadata (jsonb) ---- - -## Frontend - -* Blazor Web App -* Interactive Server Rendering -* MudBlazor -* Material Design principles - ---- - -## Database - -PostgreSQL - -ORM: - -* Entity Framework Core - -Database configuration: - -* IEntityTypeConfiguration -* Specification Pattern - -No generic repository pattern. - ---- - -# 7. Coding Rules - -All code must follow Microsoft .NET recommendations. - -## Language - -Source code: - -* English only - -Comments: - -* English only - -XML documentation: - -* English only - ---- - -## C# Rules - -Enabled: - -* Nullable Reference Types -* Implicit Usings -* File Scoped Namespace - -Rules: - -* Async everywhere -* No blocking calls -* Strong typing -* No magic strings -* No duplicated business logic - ---- - -# 8. Domain Model Design - -## Enum First Approach - -Heimdall maximizes strongly typed enums. - -Business states must never be represented by strings. - ---- - -## Examples - -### Camera Status - -```csharp -public enum CameraStatus -{ - Unknown, - Online, - Offline, - Disabled, - Error -} +Enum: CameraStatus, AgentStatus, EventType, StorageProvider +Enum: GpuAcceleration, ThemeMode ``` --- -### Event Type +# 5. Fonctionnalités par domaine -```csharp -public enum EventType -{ - MotionDetected, - PersonDetected, - VehicleDetected, - UnknownPerson, - FaceRecognized, - LicensePlateDetected -} -``` +> Chaque domaine est détaillé dans un fichier dédié. ---- +## Sites & Agents — `docs/auth-roles.md`, `docs/specs.md` (§11-12) -### Storage Provider +- Création de Site avec token d'enregistrement Agent +- Agent bootstrap : token → register → heartbeat +- Cycle de vie : Registration → Heartbeat (30s) → Offline (90s) +- API dédiée : POST /api/agents/register +- Voir `docs/auth-roles.md` §11 pour le détail complet -```csharp -public enum StorageProvider -{ - Local, - S3 -} -``` +## Authentification — `docs/auth-roles.md` ---- +- 2 types d'utilisateurs : Admin (tout) + User (N sites) +- ASP.NET Core Identity + JWT + Refresh tokens +- Permissions par Policy : Camera.Read, Admin.Manage... +- Scope site : un User ne voit que ses sites assignés +- Visibilité UI adaptée au rôle (menus, boutons) +- Voir `docs/auth-roles.md` pour le détail complet -### Theme Mode +## Caméras & IA — `docs/specs.md` (§14-19) -```csharp -public enum ThemeMode -{ - Light, - Dark, - Auto -} -``` +- ONVIF WS-Discovery (même VLAN) + discovery manuelle (IP) +- Protocole Imou : activation RTSP manuelle requise +- FFmpeg capture : RTSP → H264, GPU auto-détection (NVENC/QSV/VAAPI/CPU) +- AI Pipeline two-tier : Agent CPU (YOLOv8 nano) → Central GPU (CodeProject.AI) +- Détection : objets, visages, plaques (LPR), véhicules +- Stockage credentials caméras chiffré (IDataProtector) ---- +## Streaming live — `docs/signalr-usage.md` -# 9. Authentication and Security +- WebRTC P2P via SIPSorcery (latence < 500ms) +- Signaling via SignalR hub /hubs/streaming (SDP + ICE) +- SFU (MediaMTX) pour multi-utilisateurs (>2 viewers) +- Blazor Server + JS module autonome pour