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