docs: restructure with README index, trim specs.md, replace Refit with Kiota

- 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
This commit is contained in:
Arnaud Dartois committed 2026-07-16 19:33:11 +00:00
1 parent 2428e0ec2a
commit 3adb44449e
3 files changed
+491 -1518

No files matched your search

+69
View File
@@ -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<TId>, 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**
+235 -111
View File
@@ -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/
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.0" />
<!-- API -->
<PackageReference Include="Refit" Version="7.2.1" />
<PackageReference Include="Refit.HttpClientFactory" Version="7.2.1" />
<!-- API Client (Kiota — généré depuis OpenAPI) -->
<PackageReference Include="Microsoft.Kiota.Abstractions" Version="1.15.0" />
<PackageReference Include="Microsoft.Kiota.Http.HttpClientLibrary" Version="1.15.0" />
<PackageReference Include="Microsoft.Kiota.Serialization.Json" Version="1.15.0" />
<PackageReference Include="Microsoft.Kiota.Serialization.Text" Version="1.15.0" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.0" />
<!-- Logging -->
@@ -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<LoginResponse> 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<LoginResponse> 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<List<SiteDto>> GetMySitesAsync(
[Authorize] string token);
services.AddSingleton<IAuthenticationProvider, JwtAuthProvider>();
services.AddSingleton<ApiClientService>();
[Get("/api/mobile/sites/{siteId}")]
Task<SiteDetailDto> GetSiteDetailAsync(
Guid siteId, [Authorize] string token);
return services;
}
// ─── Cameras ───────────────────────────────────────
[Get("/api/mobile/sites/{siteId}/cameras")]
Task<List<CameraDto>> 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<CameraDetailDto> 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<StreamInfoDto> 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<PagedResult<EventDto>> 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<EventDetailDto> 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<List<PersonDto>> 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<PersonDetailDto> 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<IceServerDto> 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<LoginResult> 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<bool> 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;
}
}
```
+187 -1407
View File
File diff suppressed because it is too large. Load diff