From 2428e0ec2aae77158727009cd37edfbfd78f8b34 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 16 Jul 2026 19:29:07 +0000 Subject: [PATCH] docs: add mobile app, auth roles, notifications, hangfire, signalr specs - Add mobile-app.md: Android Avalonia UI app spec with 6 pages, WebRTC via WebView bridge, SignalR real-time, offline cache, push notifications - Add auth-roles.md: 2 user types (Admin + User), site-scoped permissions, policy-based authorization, UI visibility per role - Add notifications.md: Email SMTP (FluentEmail), Gotify push, Scriban Markdown templates i18n editable from UI, per-user config - Add hangfire-usage.md: Central PostgreSQL jobs (retention, cleanup, digests) + Agent InMemory jobs (heartbeat, camera health, GPU watchdog) - Add signalr-usage.md: 5 hubs (events, streaming, monitoring, notifications, admin) with full hub code, group management, Agent SignalR connection - Update implementation.md: 23 phases with mobile app (phase 21) - Update specs.md: reference all new documentation files --- docs/auth-roles.md | 358 +++++++++++++++ docs/hangfire-usage.md | 532 ++++++++++++++++++++++ docs/implementation.md | 16 +- docs/mobile-app.md | 987 +++++++++++++++++++++++++++++++++++++++++ docs/notifications.md | 464 +++++++++++++++++++ docs/signalr-usage.md | 450 +++++++++++++++++++ docs/specs.md | 7 +- 7 files changed, 2807 insertions(+), 7 deletions(-) create mode 100644 docs/auth-roles.md create mode 100644 docs/hangfire-usage.md create mode 100644 docs/mobile-app.md create mode 100644 docs/notifications.md create mode 100644 docs/signalr-usage.md diff --git a/docs/auth-roles.md b/docs/auth-roles.md new file mode 100644 index 0000000..366ac67 --- /dev/null +++ b/docs/auth-roles.md @@ -0,0 +1,358 @@ +# Heimdall — Authentification, Rôles & Permissions + +**Stack :** ASP.NET Core Identity + JWT + Policy-based authorization + +--- + +## 1. Types d'utilisateurs + +### Admin + +| Propriété | Valeur | +|---|---| +| Accès | **Tous les sites** sans restriction | +| Configuration | Peut tout configurer (sites, caméras, IA, stockage, notifications) | +| Administration | Gère les users, les rôles, les clés API, les jobs Hangfire | +| Visibilité UI | **Toutes les pages** (y compris Admin) | +| Permissions | Toutes les permissions automatiquement | +| Sites | Non restreint — voit tous les sites, toutes les caméras | + +### User + +| Propriété | Valeur | +|---|---| +| Accès | **1 ou N sites** assignés par l'Admin | +| Configuration | Aucune — lecture seule ou actions limitées | +| Administration | Aucun accès | +| Visibilité UI | Pages selon ses permissions + uniquement ses sites | +| Permissions | Définies par rôle + site | +| Scope | Restreint aux sites qui lui sont assignés | + +--- + +## 2. Modèle de données + +```csharp +// IdentityUser de base — pas de modification +public class User : IdentityUser +{ + public string DisplayName { get; set; } = string.Empty; + public ThemeMode Theme { get; set; } = ThemeMode.Auto; + public string Language { get; set; } = "fr"; + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; +} + +// Relation User → Sites (N-N) +public class UserSite +{ + public Guid UserId { get; set; } + public User User { get; set; } = null!; + + public Guid SiteId { get; set; } + public Site Site { get; set; } = null!; +} + +// Rôles prédéfinis +public static class AppRoles +{ + public const string Admin = "Admin"; + public const string Superviseur = "Superviseur"; // peut voir + agir + public const string Viewer = "Viewer"; // lecture seule +} +``` + +--- + +## 3. Permissions (Policies) + +Hiérarchie plate, pas de hiérarchie implicite — chaque permission se vérifie indépendamment. + +```csharp +public static class AppPermissions +{ + // Sites + public const string SiteRead = "Site.Read"; + public const string SiteWrite = "Site.Write"; + public const string SiteDelete = "Site.Delete"; + + // Cameras + public const string CameraRead = "Camera.Read"; + public const string CameraWrite = "Camera.Write"; + public const string CameraLive = "Camera.Live"; // voir le flux live + public const string CameraRecord = "Camera.Record"; // déclencher enregistrement + public const string CameraSnapshot = "Camera.Snapshot"; // prendre snapshot + + // Events & Persons + public const string EventRead = "Event.Read"; + public const string PersonRead = "Person.Read"; + public const string PersonWrite = "Person.Write"; + + // Administration + public const string AdminManage = "Administration.Manage"; + public const string AdminUsers = "Administration.Users"; + public const string AdminApiKeys = "Administration.ApiKeys"; + public const string AdminJobs = "Administration.Jobs"; // Hangfire dashboard + public const string AdminNotifications = "Administration.Notifications"; // templates +} +``` + +### Mapping Rôle → Permissions + +| Permission | Admin | Superviseur | Viewer | +|---|---|---|---| +| Site.Read | ✅ | ✅ | ✅ | +| Site.Write | ✅ | ❌ | ❌ | +| Site.Delete | ✅ | ❌ | ❌ | +| Camera.Read | ✅ | ✅ | ✅ | +| Camera.Write | ✅ | ✅ (sur ses sites) | ❌ | +| Camera.Live | ✅ | ✅ | ✅ | +| Camera.Record | ✅ | ✅ | ❌ | +| Camera.Snapshot | ✅ | ✅ | ❌ | +| Event.Read | ✅ | ✅ | ✅ | +| Person.Read | ✅ | ✅ | ✅ | +| Person.Write | ✅ | ✅ | ❌ | +| Admin.Manage | ✅ | ❌ | ❌ | +| Admin.Users | ✅ | ❌ | ❌ | +| Admin.ApiKeys | ✅ | ❌ | ❌ | +| Admin.Jobs | ✅ | ❌ | ❌ | +| Admin.Notifications | ✅ | ❌ | ❌ | + +--- + +## 4. Implémentation des Policies + +### Enregistrement + +```csharp +// Program.cs +builder.Services.AddAuthorization(options => +{ + // Permission directe + foreach (var permission in typeof(AppPermissions).GetFields( + BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy) + .Where(f => f.IsLiteral && !f.IsInitOnly) + .Select(f => f.GetRawConstantValue() as string) + .Where(v => v != null)) + { + options.AddPolicy(permission!, policy => + policy.RequireClaim("permission", permission)); + } + + // Admin a toutes les permissions automatiquement + options.AddPolicy("AdminOnly", policy => + policy.RequireRole(AppRoles.Admin)); +}); +``` + +### Vérification site-scope + +Pour les Users non-Admin, chaque requête sur un site doit vérifier +que l'User a accès à ce site : + +```csharp +public class SiteAuthorizationHandler : AuthorizationHandler +{ + private readonly ApplicationDbContext _db; + + protected override async Task HandleRequirementAsync( + AuthorizationHandlerContext context, + SiteRequirement requirement, + Guid siteId) + { + if (context.User.IsInRole(AppRoles.Admin)) + { + context.Succeed(requirement); + return; + } + + var userId = context.User.GetUserId(); + var hasAccess = await _db.UserSites + .AnyAsync(us => us.UserId == userId && us.SiteId == siteId); + + if (hasAccess) context.Succeed(requirement); + } +} + +public record SiteRequirement : IAuthorizationRequirement; + +// Usage dans un endpoint : +[HttpGet("/api/sites/{siteId}/cameras")] +public async Task GetCameras( + Guid siteId, + [FromServices] IAuthorizationService auth) +{ + var authResult = await auth.AuthorizeAsync(User, siteId, "SiteAccess"); + if (!authResult.Succeeded) return Forbid(); + // ... +} +``` + +--- + +## 5. Visibilité UI par Rôle + +### Règles + +| Page | Route | Admin | Superviseur | Viewer | +|---|---|---|---|---| +| Login | `/login` | ✅ | ✅ | ✅ | +| Dashboard | `/` | ✅ Tous sites | ✅ Ses sites | ✅ Ses sites | +| Sites liste | `/sites` | ✅ Tous | ✅ Ses sites | ✅ Ses sites | +| Site détail | `/sites/{id}` | ✅ | ✅ (si assigné) | ✅ (si assigné) | +| Caméra live | `/cameras/{id}/live` | ✅ | ✅ (si site assigné) | ✅ (si site assigné) | +| Events | `/events` | ✅ Tous | ✅ Ses sites | ✅ Ses sites | +| Persons | `/persons` | ✅ | ✅ | ✅ | +| Admin | `/admin` | ✅ | ❌ Redirection | ❌ Redirection | +| Admin Users | `/admin/users` | ✅ | ❌ | ❌ | +| Admin API Keys | `/admin/api-keys` | ✅ | ❌ | ❌ | +| Admin Hangfire | `/admin/jobs` | ✅ | ❌ | ❌ | +| Admin Notifications | `/admin/notifications` | ✅ | ❌ | ❌ | + +### Implementation Blazor + +```csharp +// Layout — masquer le menu Admin si pas Admin +@if (await AuthorizeService.HasPermissionAsync(AppPermissions.AdminManage)) +{ + ⚙️ Administration +} + +// Page Events — filtrer par site si User non-Admin +@code { + protected override async Task OnInitializedAsync() + { + if (await AuthorizeService.IsAdminAsync()) + { + _sites = await SiteService.GetAllAsync(); + } + else + { + _sites = await SiteService.GetMySitesAsync(); + } + } +} +``` + +### AuthorizeView + +```razor + + + + + + + + + + +``` + +--- + +## 6. API — middleware de scope + +Un middleware applique le scope site automatiquement sur les requêtes API : + +```csharp +public class SiteScopeMiddleware +{ + public async Task InvokeAsync(HttpContext context) + { + if (context.User.Identity?.IsAuthenticated != true) return; + + // Admin bypass + if (context.User.IsInRole(AppRoles.Admin)) + { + context.Items["AllowedSiteIds"] = null; // all + return; + } + + // User scope + var userId = context.User.GetUserId(); + var siteIds = await _db.UserSites + .Where(us => us.UserId == userId) + .Select(us => us.SiteId) + .ToListAsync(); + + context.Items["AllowedSiteIds"] = siteIds; + } +} +``` + +Puis dans les repositories/query handlers, filtrer par `AllowedSiteIds` : + +```csharp +public class GetEventsQueryHandler : IRequestHandler> +{ + public async Task> Handle(GetEventsQuery request, CancellationToken ct) + { + var query = _db.Events.AsQueryable(); + + // Scope site + if (request.AllowedSiteIds != null) + query = query.Where(e => request.AllowedSiteIds.Contains(e.SiteId)); + + // Si siteId spécifique fourni, vérifier qu'il est dans les allowed + if (request.SiteId.HasValue) + { + if (request.AllowedSiteIds != null && + !request.AllowedSiteIds.Contains(request.SiteId.Value)) + return new PagedResult(); // vide + query = query.Where(e => e.SiteId == request.SiteId.Value); + } + + // ... pagination, filtres ... + } +} +``` + +--- + +## 7. JWT Claims + +```csharp +// À la génération du token JWT +var claims = new List +{ + new(ClaimTypes.NameIdentifier, user.Id.ToString()), + new(ClaimTypes.Name, user.DisplayName), + new(ClaimTypes.Role, role), // "Admin" +}; + +// Ajouter toutes les permissions du rôle +foreach (var permission in GetPermissionsForRole(role)) + claims.Add(new Claim("permission", permission)); + +// Ajouter les sites accessibles (si non-Admin) +if (role != AppRoles.Admin) +{ + var siteIds = await _db.UserSites + .Where(us => us.UserId == user.Id) + .Select(us => us.SiteId.ToString()) + .ToListAsync(); + foreach (var siteId in siteIds) + claims.Add(new Claim("site", siteId)); +} + +var token = new JwtSecurityToken( + claims: claims, + expires: DateTime.UtcNow.AddHours(8), + signingCredentials: credentials); +``` + +--- + +## 8. Tests + +``` +Admin can see all sites +User can only see assigned sites +User cannot access admin pages (redirect) +Superviseur can modify cameras on his sites +Viewer cannot record or snapshot +API respects site scope for non-admin users +JWT token contains permissions claims +UserSite assignment works correctly +Removing user from site revokes access immediately +``` \ No newline at end of file diff --git a/docs/hangfire-usage.md b/docs/hangfire-usage.md new file mode 100644 index 0000000..84a375f --- /dev/null +++ b/docs/hangfire-usage.md @@ -0,0 +1,532 @@ +# Heimdall — Hangfire : Tous les jobs, Central & Agent + +**Stack :** +- **Central :** `Hangfire.PostgreSql` (persistance PostgreSQL) +- **Agent :** `Hangfire.InMemory` (pas de config supplémentaire, les jobs Agent sont volatiles) +- **Dashboard :** Intégré à l'UI Admin (authentifié) + +--- + +## 1. Architecture Hangfire + +```text +┌─────────────────────────────────────────────────────────────┐ +│ SERVEUR CENTRAL │ +│ │ +│ Hangfire Server │ +│ ├── Storage: PostgreSQL (Hangfire.PostgreSql) │ +│ ├── Dashboard: /admin/jobs (authentifié, Admin only) │ +│ └── Jobs: │ +│ ├── RetentionCheck (Recurring, daily) │ +│ ├── S3Cleanup (Recurring, daily) │ +│ ├── CleanupUnknownFaces (Recurring, weekly) │ +│ ├── CleanupLicensePlates (Recurring, weekly) │ +│ ├── DatabaseMaintenance (Recurring, monthly) │ +│ ├── SendNotification (Fire-and-forget, many) │ +│ └── DailyDigest / WeeklyDigest (Recurring) │ +│ │ +└─────────────────────────────────────────────────────────────┘ + +┌─────────────────────────────────────────────────────────────┐ +│ HEIMDALL AGENT (site distant) │ +│ │ +│ Hangfire Server (léger) │ +│ ├── Storage: InMemory (volatile, pas de config SQLite) │ +│ ├── Pas de dashboard (pas exposé) │ +│ └── Jobs: │ +│ ├── CameraHealthCheck (Recurring, 30s) │ +│ ├── HeartbeatSender (Recurring, 30s) │ +│ ├── GpuWatchdog (Recurring, 60s) │ +│ └── LocalRetentionCleanup (Recurring, hourly) │ +│ │ +│ IMPORTANT: Les jobs Agent sont VOLATILES — ils disparaissent │ +│ au redémarrage de l'Agent. C'est voulu : l'Agent se │ +│ réenregistre et recrée ses jobs au démarrage. │ +└─────────────────────────────────────────────────────────────┘ +``` + +--- + +## 2. Central — Jobs détaillés + +### 2.1 RetentionCheck + +```csharp +[AutomaticRetry(Attempts = 2)] +public class RetentionCheckJob +{ + public async Task ExecuteAsync(CancellationToken ct) + { + var policies = await _db.StoragePolicies + .Include(p => p.Camera) + .ToListAsync(ct); + + foreach (var policy in policies) + { + var cutoff = DateTime.UtcNow.AddDays(-policy.RetentionDays); + var storageProvider = _storageFactory.GetProvider(policy.Provider); + + // 1. Supprimer les enregistrements expirés en DB + var expired = await _db.Recordings + .Where(r => r.CameraId == policy.CameraId + && r.Timestamp < cutoff) + .ToListAsync(ct); + + _db.Recordings.RemoveRange(expired); + + // 2. Supprimer les fichiers du storage (S3/MinIO) + foreach (var recording in expired) + { + await storageProvider.DeleteAsync(recording.StoragePath, ct); + } + + _logger.LogInformation( + "Retention: supprimé {Count} enregistrements pour caméra {CameraId}", + expired.Count, policy.CameraId); + } + + await _db.SaveChangesAsync(ct); + } +} + +// Schedule +RecurringJob.AddOrUpdate( + "retention-check", + j => j.ExecuteAsync(CancellationToken.None), + Cron.Daily); +``` + +### 2.2 S3Cleanup + +```csharp +public class S3CleanupJob +{ + public async Task ExecuteAsync(CancellationToken ct) + { + // 1. Lister les fichiers dans MinIO (prefix recordings/) + var allFiles = await _storage.ListAsync("recordings/", ct); + + // 2. Récupérer les chemins enregistrés en DB + var knownPaths = await _db.Recordings + .Select(r => r.StoragePath) + .ToHashSetAsync(ct); + + // 3. Supprimer les fichiers orphelins (dans S3 mais pas en DB) + var orphanCount = 0; + foreach (var file in allFiles) + { + if (!knownPaths.Contains(file)) + { + await _storage.DeleteAsync(file, ct); + orphanCount++; + } + } + + _logger.LogInformation("S3Cleanup: supprimé {Count} fichiers orphelins", orphanCount); + } +} + +// Schedule +RecurringJob.AddOrUpdate( + "s3-cleanup", + j => j.ExecuteAsync(CancellationToken.None), + Cron.Daily); +``` + +### 2.3 CleanupUnknownFaces + +```csharp +public class CleanupUnknownFacesJob +{ + public async Task ExecuteAsync(CancellationToken ct) + { + var cutoff = DateTime.UtcNow.AddDays(-30); + var oldUnknowns = await _db.Persons + .Where(p => p.IsUnknown && p.CreatedAt < cutoff) + .ToListAsync(ct); + + _db.Persons.RemoveRange(oldUnknowns); + await _db.SaveChangesAsync(ct); + + // Supprimer les snapshots associés + foreach (var person in oldUnknowns) + { + await _storage.DeleteAsync($"snapshots/unknown/{person.Id}", ct); + } + + _logger.LogInformation( + "CleanupUnknownFaces: supprimé {Count} visages inconnus", oldUnknowns.Count); + } +} + +// Schedule +RecurringJob.AddOrUpdate( + "cleanup-unknown-faces", + j => j.ExecuteAsync(CancellationToken.None), + Cron.Weekly); +``` + +### 2.4 CleanupLicensePlates + +```csharp +public class CleanupLicensePlatesJob +{ + public async Task ExecuteAsync(CancellationToken ct) + { + var cutoff = DateTime.UtcNow.AddDays(-30); + var unassociated = await _db.LicensePlates + .Where(lp => lp.PersonId == null && lp.CreatedAt < cutoff) + .ToListAsync(ct); + + _db.LicensePlates.RemoveRange(unassociated); + await _db.SaveChangesAsync(ct); + + _logger.LogInformation( + "CleanupLicensePlates: supprimé {Count} plaques non associées", + unassociated.Count); + } +} + +// Schedule +RecurringJob.AddOrUpdate( + "cleanup-license-plates", + j => j.ExecuteAsync(CancellationToken.None), + Cron.Weekly); +``` + +### 2.5 DatabaseMaintenance + +```csharp +public class DatabaseMaintenanceJob +{ + public async Task ExecuteAsync(CancellationToken ct) + { + await _db.Database.ExecuteSqlRawAsync( + "REINDEX DATABASE \"Heimdall\"", ct); + await _db.Database.ExecuteSqlRawAsync( + "VACUUM ANALYZE", ct); + + _logger.LogInformation("Database maintenance completed"); + } +} + +// Schedule +RecurringJob.AddOrUpdate( + "database-maintenance", + j => j.ExecuteAsync(CancellationToken.None), + Cron.Monthly); +``` + +### 2.6 SendNotification (Fire-and-forget) + +Voir `docs/notifications.md` §6. + +### 2.7 DailyDigest / WeeklyDigest + +Voir `docs/notifications.md` §8. + +--- + +## 3. Agent — Jobs détaillés + +### 3.1 Configuration Hangfire Agent + +```csharp +// Program.cs — Heimdall.Agent +builder.Services.AddHangfire(config => +{ + // InMemory : pas de persistance, pas de config supplémentaire + config.UseInMemoryStorage(); +}); + +builder.Services.AddHangfireServer(options => +{ + options.WorkerCount = 2; // 2 workers max (agent léger) + options.Queues = ["agent"]; // file dédiée + options.ServerName = $"agent-{hostname}"; +}); + +// Le dashboard Hangfire n'est PAS exposé sur l'Agent +// (pas de app.UseHangfireDashboard()) +``` + +**Pourquoi InMemory et pas SQLite ?** +- SQLite nécessite une lib native (`e_sqlite3`) ou un package (`Hangfire.Sqlite`) +- InMemory = zéro config, zéro fichier, zéro permission disque +- Les jobs Agent sont volatiles et recréés au démarrage — c'est voulu +- L'Agent n'a pas besoin de persister ses jobs entre redémarrages + +### 3.2 CameraHealthCheck + +```csharp +public class CameraHealthCheckJob +{ + public async Task ExecuteAsync(CancellationToken ct) + { + var cameras = await _localCameraRegistry.GetAllAsync(ct); + + foreach (var camera in cameras) + { + var wasOnline = camera.Status == CameraStatus.Online; + var isOnline = await _rtspService.PingAsync(camera.RtspUrl, ct); + + if (wasOnline && !isOnline) + { + camera.Status = CameraStatus.Offline; + _logger.LogWarning( + "Caméra {CameraName} est hors ligne", camera.Name); + + // Notifier le Central + await _centralApi.UpdateCameraStatusAsync( + camera.Id, CameraStatus.Offline, ct); + } + else if (!wasOnline && isOnline) + { + camera.Status = CameraStatus.Online; + _logger.LogInformation( + "Caméra {CameraName} est de nouveau en ligne", camera.Name); + + await _centralApi.UpdateCameraStatusAsync( + camera.Id, CameraStatus.Online, ct); + } + } + } +} + +// Schedule (démarré après registration) +RecurringJob.AddOrUpdate( + $"agent-{agentId}-camera-health", + j => j.ExecuteAsync(CancellationToken.None), + Cron.MinuteInterval(1)); +``` + +### 3.3 HeartbeatSender + +```csharp +public class HeartbeatSenderJob +{ + public async Task ExecuteAsync(CancellationToken ct) + { + await _centralApi.SendHeartbeatAsync(_agentId, ct); + + _logger.LogTrace("Heartbeat envoyé au Central"); + } +} + +// Schedule +RecurringJob.AddOrUpdate( + $"agent-{agentId}-heartbeat", + j => j.ExecuteAsync(CancellationToken.None), + Cron.MinuteInterval(1)); +``` + +### 3.4 GpuWatchdog + +```csharp +public class GpuWatchdogJob +{ + public async Task ExecuteAsync(CancellationToken ct) + { + var gpu = _gpuDetector.Detect(); + _currentGpu = gpu; + + if (gpu == GpuAcceleration.None) + { + _logger.LogWarning( + "Aucun GPU détecté — encodage CPU seulement"); + } + + // Reporter au Central + await _centralApi.UpdateAgentCapabilitiesAsync(_agentId, new() + { + HasGpu = gpu != GpuAcceleration.None, + GpuType = gpu.ToString(), + CpuCores = Environment.ProcessorCount, + FreeMemoryMb = GetFreeMemoryMb() + }, ct); + } +} + +// Schedule +RecurringJob.AddOrUpdate( + $"agent-{agentId}-gpu-watchdog", + j => j.ExecuteAsync(CancellationToken.None), + Cron.MinuteInterval(5)); +``` + +### 3.5 LocalRetentionCleanup + +Uniquement si le site utilise le stockage LOCAL (fallback bas-débit) : + +```csharp +public class LocalRetentionCleanupJob +{ + public async Task ExecuteAsync(CancellationToken ct) + { + var localPaths = await _localCameraRegistry.GetLocalRecordingPathsAsync(ct); + + foreach (var (cameraId, retentionDays, path) in localPaths) + { + var cutoff = DateTime.UtcNow.AddDays(-retentionDays); + + foreach (var file in Directory.GetFiles(path, "*.ts")) + { + var fileInfo = new FileInfo(file); + if (fileInfo.CreationTimeUtc < cutoff) + { + fileInfo.Delete(); + _logger.LogInformation( + "LocalRetention: supprimé {File}", file); + } + } + } + } +} + +// Schedule +RecurringJob.AddOrUpdate( + $"agent-{agentId}-local-retention", + j => j.ExecuteAsync(CancellationToken.None), + Cron.Hourly); +``` + +--- + +## 4. Initialisation des jobs au démarrage + +### Central + +```csharp +public static void InitializeHangfireJobs() +{ + // Jobs planifiés (Recurring) + RecurringJob.AddOrUpdate( + "retention-check", + j => j.ExecuteAsync(CancellationToken.None), + Cron.Daily(3)); // 3h du matin + + RecurringJob.AddOrUpdate( + "s3-cleanup", + j => j.ExecuteAsync(CancellationToken.None), + Cron.Daily(4)); // 4h du matin + + RecurringJob.AddOrUpdate( + "cleanup-unknown-faces", + j => j.ExecuteAsync(CancellationToken.None), + Cron.Weekly(DayOfWeek.Sunday, 5)); // Dimanche 5h + + RecurringJob.AddOrUpdate( + "cleanup-license-plates", + j => j.ExecuteAsync(CancellationToken.None), + Cron.Weekly(DayOfWeek.Sunday, 6)); // Dimanche 6h + + RecurringJob.AddOrUpdate( + "database-maintenance", + j => j.ExecuteAsync(CancellationToken.None), + Cron.Monthly(1, 7)); // 1er du mois à 7h + + RecurringJob.AddOrUpdate( + "daily-digest", + j => j.ExecuteAsync(CancellationToken.None), + Cron.Daily(8)); // 8h +} +``` + +### Agent + +```csharp +public class HangfireInitializer : IHostedService +{ + public Task StartAsync(CancellationToken ct) + { + var agentId = _stateManager.GetAgentId(); + + RecurringJob.AddOrUpdate( + $"agent-{agentId}-camera-health", + j => j.ExecuteAsync(CancellationToken.None), + Cron.MinuteInterval(1)); + + RecurringJob.AddOrUpdate( + $"agent-{agentId}-heartbeat", + j => j.ExecuteAsync(CancellationToken.None), + Cron.MinuteInterval(1)); + + RecurringJob.AddOrUpdate( + $"agent-{agentId}-gpu-watchdog", + j => j.ExecuteAsync(CancellationToken.None), + Cron.MinuteInterval(5)); + + return Task.CompletedTask; + } +} +``` + +--- + +## 5. Dashboard Hangfire (Central uniquement) + +Intégré à l'UI Admin, authentifié, pas exposé publiquement : + +```csharp +// Heimdall.Api / Program.cs +app.UseHangfireDashboard("/admin/jobs", new DashboardOptions +{ + Authorization = + [ + new HangfireAuthorizationFilter() // vérifie AppPermissions.AdminJobs + ], + StatsPollingInterval = 3000, // 3s + DisplayStorageConnectionString = false, + DashboardTitle = "Heimdall — Jobs", +}); + +public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter +{ + public bool Authorize(DashboardContext context) + { + var httpContext = context.GetHttpContext(); + return httpContext.User?.IsInRole(AppRoles.Admin) == true; + } +} +``` + +--- + +## 6. Librairies NuGet + +### Central (Heimdall.Api + Heimdall.Workers) + +``` +dotnet add package Hangfire # Core +dotnet add package Hangfire.PostgreSql # Storage PostgreSQL +dotnet add package Hangfire.AspNetCore # ASP.NET Core integration +``` + +### Agent (Heimdall.Agent) + +``` +dotnet add package Hangfire # Core +dotnet add package Hangfire.InMemory # Storage InMemory (aucune config) +dotnet add package Hangfire.AspNetCore # ASP.NET Core integration (pour HostedService) +``` + +--- + +## 7. Tests + +``` +RetentionCheckJob deletes expired recordings +S3CleanupJob removes orphaned files +CleanupUnknownFacesJob removes old unknown persons +SendNotificationJob retries on failure (3 attempts) +Agent CameraHealthCheckJob detects offline camera +Agent HeartbeatSenderJob sends heartbeat to Central +Agent GpuWatchdogJob detects GPU changes +Agent LocalRetentionCleanupJob deletes old local files +DailyDigestJob sends digest to subscribed users +DatabaseMaintenanceJob runs without error +Hangfire dashboard is accessible only to Admin +Hangfire dashboard returns 403 for non-Admin +Agent jobs are recreated after agent restart +Agent InMemory storage does not persist across restarts +``` \ No newline at end of file diff --git a/docs/implementation.md b/docs/implementation.md index 03a5f12..ecbf9a2 100644 --- a/docs/implementation.md +++ b/docs/implementation.md @@ -17,12 +17,16 @@ 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 : Hangfire (rétention) -Phase 15 : Blazor UI — Auth + Sites + Caméras -Phase 16 : WebRTC Streaming (Agent → Browser) -Phase 17 : Blazor UI — Live Vidéo (DERNIER) -Phase 18 : Dashboard KPI -Phase 19 : Production Hardening +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 ``` --- diff --git a/docs/mobile-app.md b/docs/mobile-app.md new file mode 100644 index 0000000..cf6f70b --- /dev/null +++ b/docs/mobile-app.md @@ -0,0 +1,987 @@ +# Heimdall — Application Mobile Android (Avalonia UI) + +**Stack :** Avalonia UI (.NET 10) — Mobile Android uniquement (lecture seule) + +--- + +## 1. Périmètre + +L'application mobile est **réservée aux utilisateurs** (pas Admin complet). +Elle permet uniquement de **consulter** — aucune configuration. + +| Fonctionnalité | Mobile | Web | +|---|---|---| +| Voir ses sites | ✅ | ✅ | +| Voir les caméras | ✅ | ✅ | +| Voir le flux live | ✅ (WebRTC) | ✅ | +| Voir les événements | ✅ | ✅ | +| Voir les personnes | ✅ | ✅ | +| Recevoir notifications push | ✅ (Gotify/FCM) | ✅ | +| Configurer sites | ❌ | ✅ | +| Gérer utilisateurs | ❌ | ✅ | +| Gérer templates notifications | ❌ | ✅ | +| Voir jobs Hangfire | ❌ | ✅ | + +--- + +## 2. Stack technique + +| Technologie | Version | Usage | +|---|---|---| +| **Avalonia UI** | 11.x+ | Framework UI cross-platform Android | +| **Avalonia.Android** | 11.x+ | Platform target Android | +| **Avalonia.WebRTC** | — | WebRTC dans Avalonia (via native WebView ou lib) | +| **System.Net.Http** | — | API Client | +| **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 | +| **Serilog** | 3.x+ | Logging mobile | + +### Pourquoi Avalonia et pas MAUI ? + +| Critère | Avalonia UI | .NET MAUI | +|---|---|---| +| Maturité Android | ✅ Stable | 🟠 Encore instable | +| Performance | ✅ Bonne | 🟠 Variable | +| WebRTC support | ✅ WebView + JS interop | 🟠 Limité | +| Même codebase Desktop/Mobile | ✅ | ✅ (MAUI aussi) | +| Contrôle total rendu | ✅ (Skia) | ❌ (natif) | + +--- + +## 3. Architecture MVVM + +```text +Heimdall.Mobile/ +├── App.axaml # Entry point +├── App.axaml.cs # Application lifecycle +├── Avalonia.WebRTC/ # WebRTC interop +│ ├── WebRTCView.axaml # Custom control +│ └── WebRTCView.axaml.cs # Android WebView bridge +├── Views/ # UI Pages +│ ├── LoginView.axaml +│ ├── DashboardView.axaml +│ ├── SiteListView.axaml +│ ├── SiteDetailView.axaml +│ ├── CameraLiveView.axaml +│ ├── EventListView.axaml +│ └── EventDetailView.axaml +├── ViewModels/ # MVVM ViewModels +│ ├── LoginViewModel.cs +│ ├── DashboardViewModel.cs +│ ├── SiteListViewModel.cs +│ ├── SiteDetailViewModel.cs +│ ├── CameraLiveViewModel.cs +│ ├── EventListViewModel.cs +│ └── EventDetailViewModel.cs +├── Services/ # Services +│ ├── IApiClient.cs # Interface Refit +│ ├── ApiClient.cs # Implémentation Refit +│ ├── IAuthService.cs # JWT token management +│ ├── AuthService.cs +│ ├── ISignalRService.cs # SignalR connection +│ ├── SignalRService.cs +│ ├── INavigationService.cs # Navigation +│ └── NavigationService.cs +├── Models/ # DTOs +│ ├── SiteDto.cs +│ ├── CameraDto.cs +│ ├── EventDto.cs +│ ├── PersonDto.cs +│ ├── LoginRequest.cs +│ └── LoginResponse.cs +└── Converters/ # Value converters + ├── StatusToColorConverter.cs + ├── EventTypeToIconConverter.cs + └── DateTimeToRelativeConverter.cs +``` + +### NuGet Dependencies + +```xml + + + + + + + + + + + + + + + + + + + + +``` + +--- + +## 4. API Client — Refit + +```csharp +public interface IHeimdallApi +{ + // ─── Auth ────────────────────────────────────────── + [Post("/api/auth/login")] + Task LoginAsync([Body] LoginRequest request); + + [Post("/api/auth/refresh")] + Task RefreshTokenAsync([Body] RefreshRequest request); + + // ─── Sites (uniquement ceux auxquels l'user a accès) ─ + [Get("/api/mobile/sites")] + Task> GetMySitesAsync( + [Authorize] string token); + + [Get("/api/mobile/sites/{siteId}")] + Task GetSiteDetailAsync( + Guid siteId, [Authorize] string token); + + // ─── Cameras ─────────────────────────────────────── + [Get("/api/mobile/sites/{siteId}/cameras")] + Task> GetCamerasAsync( + Guid siteId, [Authorize] string token); + + [Get("/api/mobile/cameras/{cameraId}")] + Task GetCameraDetailAsync( + Guid cameraId, [Authorize] string token); + + // ─── Live stream signaling (WebRTC) ─────────────── + [Get("/api/mobile/cameras/{cameraId}/stream-info")] + Task GetStreamInfoAsync( + Guid cameraId, [Authorize] string token); + // Retourne : { cameraId, agentEndpoint, iceServers[] } + + // ─── 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); + + [Get("/api/mobile/events/{eventId}")] + Task GetEventDetailAsync( + Guid eventId, [Authorize] string token); + + // ─── Persons ─────────────────────────────────────── + [Get("/api/mobile/persons")] + Task> GetPersonsAsync( + [Authorize] string token); + + [Get("/api/mobile/persons/{personId}")] + Task GetPersonDetailAsync( + Guid personId, [Authorize] string token); +} +``` + +### 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 + +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 + +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 + +public record StreamInfoDto( + Guid CameraId, + string IceEndpoint, // Agent public endpoint ou SFU + List IceServers); + +public record IceServerDto( + string Urls, // "stun:...", "turn:..." + string? Username, + string? Credential); +``` + +--- + +## 5. Authentification — JWT Token + +```csharp +public class AuthService : IAuthService +{ + private readonly IPreferences _prefs; // stockage local sécurisé + private readonly IHeimdallApi _api; + + public async Task LoginAsync(string email, string password) + { + var response = await _api.LoginAsync(new LoginRequest(email, password)); + + // Stocker le token 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; + } +} +``` + +### Écran Login + +```text +┌──────────────────────────────────────┐ +│ │ +│ HEIMDALL │ +│ Surveillance Mobile │ +│ │ +│ ┌────────────────────────────────┐ │ +│ │ ✉️ entreprise@email.com │ │ +│ └────────────────────────────────┘ │ +│ │ +│ ┌────────────────────────────────┐ │ +│ │ 🔒 Mot de passe │ │ +│ └────────────────────────────────┘ │ +│ │ +│ ┌────────────────────────────────┐ │ +│ │ Se connecter │ │ +│ └────────────────────────────────┘ │ +│ │ +│ [▼] Serveur : https://... │ +│ │ +│ Version 1.0.0 │ +└──────────────────────────────────────┘ +``` + +**Comportement :** +- Champ "Serveur" : URL du Central (mémorisée après 1e connexion) +- Token stocké dans `Android.KeyStore` (chiffré) +- Auto-refresh silencieux en arrière-plan +- Déconnexion automatique si refresh échoue + +--- + +## 6. Pages détaillées + +### 6.1 Dashboard — Accueil + +```text +┌──────────────────────────────────────┐ +│ ☰ Accueil 🔔 3 │ +│ │ +│ ┌──────┐ ┌──────┐ ┌──────┐ │ +│ │ 📷 12 │ │ 📹 8 │ │ 🚗 5 │ │ +│ │ Sites │ │ Cams │ │ Auj │ │ +│ │ │ │ en │ │ │ │ +│ │ │ │ ligne │ │ │ │ +│ └──────┘ └──────┘ └──────┘ │ +│ │ +│ ─── Derniers événements ──── │ +│ │ +│ 🟢 14:23 Entrée │ +│ Personne détectée │ +│ │ +│ 🟡 14:20 Parking │ +│ AA-123-XX détectée │ +│ │ +│ 🔴 14:15 Entrée │ +│ Visage inconnu │ +│ │ +│ ─── Mes sites ──────────────── │ +│ │ +│ ┌────────────────────────────────┐ │ +│ │ Entrepôt A ▶ 5/8 │ │ +│ │ Paris 🟢 │ │ +│ └────────────────────────────────┘ │ +│ ┌────────────────────────────────┐ │ +│ │ Entrepôt B ▶ 0/3 │ │ +│ │ Lyon 🔴 │ │ +│ └────────────────────────────────┘ │ +│ │ +│ [Voir tous les sites →] │ +└──────────────────────────────────────┘ +``` + +**Components Avalonia :** +- `UserControl` + `DockPanel` +- `Border` pour les cartes KPI (style Material) +- `ItemsRepeater` pour la liste des événements +- `ListBox` pour la liste des sites +- `Button` navigation + +### 6.2 Sites List + +```text +┌──────────────────────────────────────┐ +│ ☰ Mes Sites 🔍 │ +│ │ +│ ┌────────────────────────────────┐ │ +│ │ Entrepôt A ▶ 5/8 │ │ +│ │ Paris, 75012 🟢 │ │ +│ │ Agent en ligne │ │ +│ └────────────────────────────────┘ │ +│ ┌────────────────────────────────┐ │ +│ │ Entrepôt B ▶ 0/3 │ │ +│ │ Lyon, 69003 🟠 │ │ +│ │ Agent hors ligne │ │ +│ └────────────────────────────────┘ │ +│ │ +│ pull-to-refresh ↓ │ +└──────────────────────────────────────┘ +``` + +### 6.3 Site Detail + +```text +┌──────────────────────────────────────┐ +│ ◀ Entrepôt A 🔔 │ +│ │ +│ ┌────────────────────────────────┐ │ +│ │ Agent: agent-01 │ │ +│ │ Statut: 🟢 En ligne │ │ +│ │ Dernier heartbeat: il y a 12s │ │ +│ └────────────────────────────────┘ │ +│ │ +│ ─── Caméras ──────────────────── │ +│ │ +│ ┌────────────────────────────────┐ │ +│ │ 📷 Entrée 🟢 ▶ │ │ +│ │ 1080p · H264 │ │ +│ │ ┌──────┐ │ │ +│ │ │ │ Dernier snapshot │ │ +│ │ └──────┘ │ │ +│ └────────────────────────────────┘ │ +│ ┌────────────────────────────────┐ │ +│ │ 📷 Parking 🟢 ▶ │ │ +│ │ 1080p · H264 │ │ +│ │ ┌──────┐ │ │ +│ │ │ │ Dernier snapshot │ │ +│ │ └──────┘ │ │ +│ └────────────────────────────────┘ │ +│ ┌────────────────────────────────┐ │ +│ │ 📷 Jardin 🔴 │ │ +│ │ Hors ligne │ │ +│ │ ┌──────┐ │ │ +│ │ │ ⚠️ │ Aucun signal │ │ +│ │ └──────┘ │ │ +│ └────────────────────────────────┘ │ +│ │ +│ ─── Événements récents ──────── │ +│ 🟢 14:23 Personne détectée ▶ │ +│ 🟡 14:20 Véhicule détecté ▶ │ +│ 🔴 14:15 Visage inconnu ▶ │ +│ │ +│ [Voir tous les événements →] │ +└──────────────────────────────────────┘ +``` + +### 6.4 Camera Live View + +```text +┌──────────────────────────────────────┐ +│ ◀ Entrée — Live │ +│ │ +│ ┌────────────────────────────────┐ │ +│ │ │ │ +│ │ FLUX VIDÉO WEBRTC │ │ +│ │ │ │ +│ │ WebView + JS WebRTC client │ │ +│ │ │ │ +│ │ 🟢 Live ● 14:23:05 │ │ +│ │ │ │ +│ └────────────────────────────────┘ │ +│ │ +│ [📷 Snapshot] [⟳ Refresh] │ +│ │ +│ ─── Derniers événements ───── │ +│ 🟢 14:23 Personne détectée │ +│ 🟡 14:20 Véhicule détecté │ +└──────────────────────────────────────┘ +``` + +### 6.5 Events List + +```text +┌──────────────────────────────────────┐ +│ ◀ Événements [Filtres ▼] │ +│ │ +│ ┌────────────────────────────────┐ │ +│ │ 🔴 14:23 Personne ▶ │ │ +│ │ Entrée · Entrepôt A │ │ +│ │ ┌──────┐ │ │ +│ │ │ img │ Inconnue │ │ +│ │ └──────┘ │ │ +│ └────────────────────────────────┘ │ +│ ┌────────────────────────────────┐ │ +│ │ 🟡 14:20 Véhicule ▶ │ │ +│ │ Parking · Entrepôt A │ │ +│ │ ┌──────┐ │ │ +│ │ │ img │ AA-123-XX │ │ +│ │ └──────┘ │ │ +│ └────────────────────────────────┘ │ +│ ┌────────────────────────────────┐ │ +│ │ 🟢 14:10 Mouvement ▶ │ │ +│ │ Jardin · Entrepôt B │ │ +│ └────────────────────────────────┘ │ +│ │ +│ pull-to-refresh ↓ │ +│ │ +│ ─── Page 1/5 ─── [>] │ +└──────────────────────────────────────┘ +``` + +**Filtres disponibles :** +- Type : Tous, Personne, Véhicule, Visage inconnu, Mouvement +- Site : Tous, [site spécifique] (dropdown) +- Date : Aujourd'hui, 7 jours, 30 jours + +### 6.6 Event Detail + +```text +┌──────────────────────────────────────┐ +│ ◀ Événement │ +│ │ +│ ┌────────────────────────────────┐ │ +│ │ │ │ +│ │ SNAPSHOT IMAGE │ │ +│ │ (pleine largeur) │ │ +│ │ │ │ +│ └────────────────────────────────┘ │ +│ │ +│ 🔴 Personne détectée │ +│ │ +│ Site Entrepôt A │ +│ Caméra Entrée │ +│ Date 14/07/2026 14:23:05 │ +│ │ +│ Détection │ +│ ┌────────────────────────────────┐ │ +│ │ Confiance: 87% │ │ +│ │ Type: Personne │ │ +│ │ Visage: ❌ Inconnu │ │ +│ └────────────────────────────────┘ │ +│ │ +│ ─── Événements similaires ───── │ +│ 🟢 13/07 Personne détectée ▶ │ +│ 🟢 12/07 Personne détectée ▶ │ +└──────────────────────────────────────┘ +``` + +--- + +## 7. WebRTC Live — Implémentation Avalonia + +Le WebRTC dans Avalonia Android utilise une **WebView** qui charge une +page HTML minimale contenant le client WebRTC JavaScript. + +```text +┌──────────────────────────────────────┐ +│ Avalonia WebRTCView │ +│ │ +│ ┌────────────────────────────────┐ │ +│ │ WebView (Android) │ │ +│ │ │ │ +│ │ │ │ +│ │ │ │ +│ │ + + +``` + +### Contrôle Avalonia + +```csharp +public class WebRTCView : NativeControlHost +{ + private Android.Webkit.WebView? _webView; + private readonly SignalRService _signalR; + + public async Task StartStreamAsync(StreamInfoDto streamInfo) + { + // 1. Initialiser SignalR pour le signaling + await _signalR.ConnectAsync(); + + // 2. S'abonner aux événements signaling + _signalR.OnSdpOffer += async (offer) => + { + // Envoyer l'offre à la WebView (JS) + await _webView!.EvaluateJavascriptAsync( + $"startStream('{offer}', '{Json.Serialize(streamInfo.IceServers)}')"); + }; + + _signalR.OnIceCandidate += async (candidate) => + { + await _webView!.EvaluateJavascriptAsync( + $"addIceCandidate('{candidate}')"); + }; + + // 3. Demander le flux + await _signalR.RequestStreamAsync(streamInfo.CameraId); + } + + public async Task StopStreamAsync() + { + await _webView!.EvaluateJavascriptAsync("stopStream()"); + await _signalR.DisconnectAsync(); + } + + // Bridge JS → C# (appelé depuis la WebView) + public void OnSdpAnswer(string sdp) + { + _signalR.SendAnswerAsync(sdp); + } + + public void OnIceCandidate(string candidate) + { + _signalR.SendIceCandidateAsync(candidate); + } +} +``` + +--- + +## 8. SignalR Mobile — Temps réel + +```csharp +public class SignalRService : ISignalRService, IDisposable +{ + private HubConnection? _hub; + + public event Action? EventCreated; + public event Action? CameraStatusChanged; + public event Action? SdpOffer; + public event Action? IceCandidate; + + public async Task ConnectAsync() + { + _hub = new HubConnectionBuilder() + .WithUrl($"{_baseUrl}/hubs/events", options => + { + options.AccessTokenProvider = () => + Task.FromResult(_tokenProvider.AccessToken); + }) + .WithAutomaticReconnect([0, 2000, 5000, 10000, 30000]) + .Build(); + + // Événements de détection + _hub.On("EventCreated", eventDto => + { + // Notification locale si l'app est en arrière-plan + ShowLocalNotification(eventDto); + EventCreated?.Invoke(eventDto); + }); + + // Changement statut caméra + _hub.On("CameraStatusChanged", status => + { + CameraStatusChanged?.Invoke(status); + }); + + await _hub.StartAsync(); + } + + // Signaling WebRTC — connecté au hub /hubs/streaming + public async Task ConnectStreamingAsync(Guid cameraId) + { + var streamingHub = new HubConnectionBuilder() + .WithUrl($"{_baseUrl}/hubs/streaming", options => + { + options.AccessTokenProvider = () => + Task.FromResult(_tokenProvider.AccessToken); + }) + .Build(); + + streamingHub.On("SdpOffer", offer => SdpOffer?.Invoke(offer)); + streamingHub.On("IceCandidate", candidate => IceCandidate?.Invoke(candidate)); + + await streamingHub.StartAsync(); + await streamingHub.InvokeAsync("RequestStream", cameraId); + } + + // Notifications locales Android + private void ShowLocalNotification(EventDto eventDto) + { + var channelId = "heimdall-events"; + var notification = new NotificationCompat.Builder(this, channelId) + .SetSmallIcon(Resource.Drawable.ic_notification) + .SetContentTitle(GetEventTitle(eventDto.EventType)) + .SetContentText($"{eventDto.CameraName} · {eventDto.SiteName}") + .SetAutoCancel(true) + .SetPriority(NotificationCompat.PRIORITY_HIGH) + .Build(); + + var manager = GetSystemService(NotificationService) as NotificationManager; + manager?.Notify(eventDto.Id.GetHashCode(), notification); + } +} +``` + +--- + +## 9. Navigation & Layout + +### Bottom Navigation (Android) + +```text +┌──────────────────────────────────────┐ +│ │ +│ CONTENU PAGE │ +│ │ +│ │ +│ │ +├──────────────────────────────────────┤ +│ 🏠 📷 📋 👤 ⚙️ │ +│ Accueil Sites Events Pers. Réglages │ +└──────────────────────────────────────┘ +``` + +Implémenté avec `TabControl` en mode bottom : + +```xml + + + + + + + + + + + + + + + + + +``` + +### Pull-to-Refresh + +Toutes les listes implémentent le pull-to-refresh via `RefreshContainer` : + +```xml + + + + + + + +``` + +--- + +## 10. Notifications Push (FCM + Gotify) + +L'application mobile reçoit les notifications via : + +1. **Gotify** (self-hosted) — le même que le web +2. **Firebase Cloud Messaging** (si Google Services disponibles) + +### Gotify sur mobile + +```csharp +public class GotifyPushService +{ + private readonly GotifyClient _client; + + public async Task RegisterForPushAsync() + { + // L'utilisateur entre son token Gotify dans les réglages + var token = await _prefs.GetAsync("gotify_token", ""); + + _client = new GotifyClient(_gotifyServerUrl, token); + + // Polling ou WebSocket Gotify pour les messages + _client.OnMessage += (msg) => + { + ShowLocalNotification(msg); + }; + + await _client.ConnectAsync(); + } +} +``` + +### Écran Réglages + +```text +┌──────────────────────────────────────┐ +│ ⚙️ Réglages │ +│ │ +│ Compte │ +│ Connecté en tant que Jean Dupont │ +│ [Se déconnecter] │ +│ │ +│ Serveur │ +│ URL: https://heimdall.exemple.com │ +│ │ +│ Notifications push │ +│ Gotify Server: [http://... ] │ +│ Gotify Token: [**************] │ +│ [Tester la connexion] │ +│ │ +│ Notifications locales │ +│ [✅] Personnes détectées │ +│ [✅] Visages inconnus │ +│ [ ] Véhicules │ +│ [✅] Caméra hors ligne │ +│ │ +│ Lecture automatique du live │ +│ [✅] Wi-Fi uniquement │ +│ [ ] Données mobiles aussi │ +│ │ +│ Qualité vidéo mobile │ +│ [Automatique ▼] │ +│ │ +│ Thème │ +│ [System ▼] │ +│ │ +│ Version : 1.0.0 │ +└──────────────────────────────────────┘ +``` + +--- + +## 11. Hors-ligne (Offline First) + +| Donnée | Stratégie | +|---|---| +| Sites list | Cache local (JSON) — mis à jour au démarrage | +| Caméras par site | Cache local — rafraîchi au pull-to-refresh | +| Événements | Cache local (50 derniers) + SignalR temps réel | +| Snapshots | Cache disque LRU (50 Mo max) | +| Flux live | Pas de cache (temps réel uniquement) | + +```csharp +public class OfflineCacheService +{ + private readonly string _cacheDir = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + "cache"); + + public async Task GetAsync(string key) where T : class + { + var path = Path.Combine(_cacheDir, $"{key}.json"); + if (!File.Exists(path)) return null; + + var json = await File.ReadAllTextAsync(path); + return JsonSerializer.Deserialize(json); + } + + public async Task SetAsync(string key, T value) where T : class + { + var path = Path.Combine(_cacheDir, $"{key}.json"); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + var json = JsonSerializer.Serialize(value); + await File.WriteAllTextAsync(path, json); + } + + public void PurgeLRU(int maxSizeMb = 50) + { + // Supprime les fichiers les plus vieux si le cache dépasse 50 Mo + } +} +``` + +--- + +## 12. Build & Déploiement + +### Android SDK Requirements + +| Requirement | Version | +|---|---| +| Android SDK | 34+ (Android 14) | +| Min SDK | 28 (Android 9) | +| Target SDK | 34 (Android 14) | +| .NET | 10.0+ | + +### Fichier `.csproj` Android + +```xml + + + Exe + net10.0-android + 21 + com.heimdall.mobile + 1 + 1.0.0 + + + + + + +``` + +### CI/CD — Build APK + +```yaml +# .github/workflows/mobile.yml +jobs: + build-android: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + + - name: Install Android workload + run: dotnet workload install android + + - name: Build APK + run: | + dotnet publish src/Heimdall.Mobile/Heimdall.Mobile.csproj \ + -f net10.0-android \ + -c Release \ + -p:AndroidSigningKeyStore=${{ secrets.KEYSTORE }} \ + -p:AndroidSigningKeyAlias=${{ secrets.KEY_ALIAS }} + + - name: Upload APK + uses: actions/upload-artifact@v4 + with: + name: heimdall-mobile.apk + path: bin/Release/net10.0-android/*-Signed.apk +``` + +--- + +## 13. Tests + +``` +User can login with valid JWT credentials +Login with invalid credentials shows error +Token refresh works silently in background +Dashboard shows user's sites only +Site list shows only assigned sites +Camera list shows correct online/offline status +Live WebRTC stream starts on camera tap +Live stream stops on back navigation +Event list is paginated (20 per page) +Event detail shows full snapshot +Pull-to-refresh updates data +Offline cache shows stale data when offline +Notifications arrive via SignalR in real-time +Gotify push notification triggers local notification +User can logout from settings +Logout clears all cached data +Bottom navigation switches pages correctly +``` \ No newline at end of file diff --git a/docs/notifications.md b/docs/notifications.md new file mode 100644 index 0000000..17c4978 --- /dev/null +++ b/docs/notifications.md @@ -0,0 +1,464 @@ +# Heimdall — Notifications (Email + Gotify + Templates) + +**Stack :** `FluentEmail.Smtp`, `Gotify.NET`, `RazorTemplating` / `Scriban` (Markdown → HTML) + +--- + +## 1. Canaux de notification + +| Canal | Usage | Priorité | Bibliothèque | +|---|---|---|---| +| **Email** (SMTP) | Notifications importantes, résumés | 🔴 Requis | `FluentEmail.Smtp` + `FluentEmail.Razor` | +| **Gotify** (push) | Alertes temps réel, notifications rapides | 🟠 Recommandé | `Gotify.NET` | +| **In-app** (SignalR) | Notifications silencieuses dans l'UI | 🟢 Requis | SignalR (intégré) | + +--- + +## 2. SMTP — Configuration + +Configurable depuis l'UI Admin : + +```csharp +public class SmtpConfig +{ + public string Host { get; set; } = "smtp.example.com"; + public int Port { get; set; } = 587; + public string Username { get; set; } = string.Empty; + public string Password { get; set; } = string.Empty; // chiffré + public bool UseSsl { get; set; } = true; + public string FromAddress { get; set; } = "heimdall@example.com"; + public string FromName { get; set; } = "Heimdall"; +} +``` + +Stockée en base (table `AppConfig`), champ `Password` chiffré avec `IDataProtector`. + +Test depuis l'UI : "Envoyer un email de test". + +### Librairies NuGet + +``` +dotnet add package FluentEmail.Smtp +dotnet add package FluentEmail.Razor // templates Razor → HTML +// ou +dotnet add package Scriban // templates Markdown alternatif +``` + +--- + +## 3. Gotify — Configuration + +Gotify est un serveur de notification push self-hosted (Docker). + +### Dépendances + +``` +dotnet add package Gotify.NET +``` + +### Configuration + +```csharp +public class GotifyConfig +{ + public string ServerUrl { get; set; } = "http://gotify:8080"; + public string AppToken { get; set; } = string.Empty; // chiffré + public int Priority { get; set; } = 5; // 0-10 +} +``` + +### UI Admin + +```text +┌──────────────────────────────────────────────┐ +│ Notifications │ +│ │ +│ ┌──── Email (SMTP) ───────────────────────┐ │ +│ │ Serveur: [smtp.example.com ] │ │ +│ │ Port: [587 ] │ │ +│ │ SSL: [x] │ │ +│ │ Utilisateur: [notifications@... ] │ │ +│ │ Mot de passe: [******** ] │ │ +│ │ De: [heimdall@example.com ] │ │ +│ │ │ │ +│ │ [Tester la connexion] │ │ +│ └───────────────────────────────────────────┘ │ +│ │ +│ ┌──── Gotify ──────────────────────────────┐ │ +│ │ Serveur: [http://gotify:8080 ] │ │ +│ │ Token: [******** ] │ │ +│ │ Priorité: [5 ▼] │ │ +│ │ │ │ +│ │ [Tester la connexion] │ │ +│ └───────────────────────────────────────────┘ │ +│ │ +│ ┌──── Templates ───────────────────────────┐ │ +│ │ [Modifier les templates ▼] │ │ +│ └───────────────────────────────────────────┘ │ +└──────────────────────────────────────────────┘ +``` + +--- + +## 4. Templates de notification (Markdown) + +### Architecture + +```text +Base de données +└── NotificationTemplate + ├── EventType (enum) + ├── Language ("fr", "en", "de"...) + ├── Channel ("email", "gotify", "inapp") + ├── Subject (string, avec variables) + └── Body (string, Markdown avec variables) +``` + +### Template Entity + +```csharp +public class NotificationTemplate +{ + public Guid Id { get; set; } + public EventType EventType { get; set; } // PersonDetected, etc. + public string Language { get; set; } = "fr"; // "fr", "en", "de" + public string Channel { get; set; } = "email"; // "email", "gotify", "inapp" + public string Subject { get; set; } = string.Empty; + public string BodyMarkdown { get; set; } = string.Empty; + public bool IsDefault { get; set; } // template par défaut +} +``` + +### Variables disponibles dans les templates + +| Variable | Description | Exemple | +|---|---|---| +| `{{SiteName}}` | Nom du site | "Entrepôt A" | +| `{{CameraName}}` | Nom de la caméra | "Entrée principale" | +| `{{EventType}}` | Type d'événement | "PersonDetected" | +| `{{EventTime}}` | Horodatage | "14/07/2026 14:23:05" | +| `{{EventTimeAgo}}` | Relatif | "il y a 2 minutes" | +| `{{PersonName}}` | Nom de la personne | "Jean Dupont" | +| `{{PersonPhotoUrl}}` | Lien photo | `https://heimdall/...` | +| `{{VehiclePlate}}` | Plaque | "AA-123-XX" | +| `{{VehicleModel}}` | Modèle | "Renault Clio" | +| `{{SnapshotUrl}}` | Lien snapshot | `https://heimdall/...` | +| `{{EventUrl}}` | Lien vers l'événement | `https://heimdall/events/...` | +| `{{SiteUrl}}` | URL du Central | `https://heimdall.example.com` | +| `{{AlertCount}}` | Nombre d'alertes (résumé) | "12" | + +### Templates par défaut (fr) + +```markdown +=== PersonDetected — email — fr === +Subject: [Heimdall] Personne détectée — {{CameraName}} +Body: +**🔴 Alerte — Personne détectée** + +| | | +|---|---| +| **Site** | {{SiteName}} | +| **Caméra** | {{CameraName}} | +| **Date** | {{EventTime}} | +| **Personne** | {{PersonName}} | + +Voir l'événement : [{{EventUrl}}]({{EventUrl}}) + +--- + +=== PersonDetected — email — en === +Subject: [Heimdall] Person detected — {{CameraName}} +Body: +**🔴 Alert — Person detected** + +| | | +|---|---| +| **Site** | {{SiteName}} | +| **Camera** | {{CameraName}} | +| **Time** | {{EventTime}} | +| **Person** | {{PersonName}} | + +View event: [{{EventUrl}}]({{EventUrl}}) + +--- + +=== UnknownPerson — gotify — fr === +Subject: Visage inconnu — {{CameraName}} +Body: +Visage inconnu détecté sur {{CameraName}} ({{SiteName}}) +à {{EventTime}}. + +--- + +=== DailySummary — email — fr === +Subject: [Heimdall] Résumé quotidien — {{SiteName}} — {{EventTime}} +Body: +**📊 Résumé quotidien — {{SiteName}}** + +Période: {{DateStart}} → {{DateEnd}} + +| Type | Nombre | +|---|---| +| Personnes détectées | {{PersonCount}} | +| Dont connues | {{KnownPersonCount}} | +| Dont inconnues | {{UnknownPersonCount}} | +| Véhicules détectés | {{VehicleCount}} | +| Événements total | {{TotalEventCount}} | + +[Voir le tableau de bord]({{SiteUrl}}) +``` + +### Rendu du template + +```csharp +public class NotificationService : INotificationService +{ + private readonly ScribanTemplateEngine _scriban; + private readonly IRepository _templates; + + public async Task RenderAsync( + EventType eventType, + string language, + string channel, + Dictionary variables) + { + // 1. Chercher template spécifique (eventType + language + channel) + var template = await _templates.FirstOrDefaultAsync(t => + t.EventType == eventType && + t.Language == language && + t.Channel == channel); + + // 2. Fallback : template par défaut de cette langue + template ??= await _templates.FirstOrDefaultAsync(t => + t.EventType == eventType && + t.Language == language && + t.IsDefault); + + // 3. Fallback : template anglais + template ??= await _templates.FirstOrDefaultAsync(t => + t.EventType == eventType && + t.Language == "en" && + t.IsDefault); + + if (template == null) return string.Empty; + + // 4. Rendre avec Scriban + var parsed = Template.Parse(template.BodyMarkdown); + var result = await parsed.RenderAsync(variables); + return result; + } +} +``` + +### UI d'édition des templates + +```text +┌──────────────────────────────────────────────────────┐ +│ Templates de notification [Langue: français ▼] +│ │ +│ Événement: [Personne détectée ▼] Canal: [Email ▼] │ +│ │ +│ Sujet: │ +│ ┌──────────────────────────────────────────────────┐ │ +│ │ [Heimdall] Personne détectée — {{CameraName}} │ │ +│ └──────────────────────────────────────────────────┘ │ +│ │ +│ Corps (Markdown): │ +│ ┌──────────────────────────────────────────────────┐ │ +│ │ **🔴 Alerte — Personne détectée** │ │ +│ │ │ │ +│ │ | | | │ │ +│ │ |---|---| │ │ +│ │ | **Site** | {{SiteName}} | │ │ +│ │ | **Caméra** | {{CameraName}} | │ │ +│ │ │ │ +│ │ Voir : [{{EventUrl}}]({{EventUrl}}) │ │ +│ └──────────────────────────────────────────────────┘ │ +│ │ +│ [Aperçu] [Réinitialiser] [Enregistrer] │ +│ │ +│ ── Aperçu ────────────────────────────────────────── │ +│ De: heimdall@example.com │ +│ À: test@example.com │ +│ Sujet: [Heimdall] Personne détectée — Entrée │ +│ ──────────────────────────────────────────────────── │ +│ 🔴 Alerte — Personne détectée │ +│ Site: Entrepôt A | Caméra: Entrée | Date: 14/07... │ +└──────────────────────────────────────────────────────┘ +``` + +### Librairies + +``` +dotnet add package Scriban # Moteur de templates Markdown +dotnet add package Scriban.Signed # (si besoin strong name) +// ou +dotnet add package FluentEmail.Razor # Alternative Razor → HTML +dotnet add package FluentEmail.Smtp # Envoi SMTP +dotnet add package Gotify.NET # Gotify push +``` + +--- + +## 5. Types d'événements notifiables + +| EventType | Email | Gotify | In-App (SignalR) | Template dispo | +|---|---|---|---|---| +| `PersonDetected` | ✅ | ✅ | ✅ | Oui | +| `UnknownPerson` | ✅ (haut) | ✅ | ✅ | Oui | +| `FaceRecognized` | 🟡 (option) | 🟡 | ✅ | Oui | +| `VehicleDetected` | ✅ | ✅ | ✅ | Oui | +| `LicensePlateDetected` | 🟡 | ✅ | ✅ | Oui | +| `MotionDetected` | ❌ (trop) | ❌ | ✅ (silencieux) | Non | +| `CameraOffline` | ✅ | ✅ | ✅ | Oui | +| `CameraOnline` | 🟡 | 🟡 | ✅ | Oui | +| `DailySummary` | ✅ | ❌ | ❌ | Oui | +| `WeeklySummary` | ✅ | ❌ | ❌ | Oui | + +--- + +## 6. File d'attente des notifications (Hangfire) + +Toutes les notifications passent par Hangfire pour : + +1. Fiabilité (retry si échec SMTP) +2. File d'attente (ne pas bloquer le thread de détection) +3. Rate limiting (max N emails/min) + +```csharp +public class SendNotificationJob +{ + [AutomaticRetry(Attempts = 3, DelaysInSeconds = [60, 300, 900])] + public async Task ExecuteAsync( + Guid eventId, + string channel, // "email", "gotify", "inapp" + string language, + CancellationToken ct) + { + var event = await _db.Events.FindAsync(new object[] { eventId }, ct); + var variables = await BuildVariablesAsync(event, ct); + + var rendered = await _notificationService.RenderAsync( + event.Type, language, channel, variables); + + await channel switch + { + "email" => await SendEmailAsync(event, rendered, ct), + "gotify" => await SendGotifyAsync(event, rendered, ct), + "inapp" => await SendInAppAsync(event, rendered, ct), + _ => Task.CompletedTask + }; + } +} +``` + +### Déclenchement depuis le pipeline IA + +```csharp +// Dans le handler de détection +if (shouldNotify) +{ + BackgroundJob.Enqueue(j => + j.ExecuteAsync(event.Id, "email", user.Language, CancellationToken.None)); + BackgroundJob.Enqueue(j => + j.ExecuteAsync(event.Id, "gotify", user.Language, CancellationToken.None)); +} + +// Notification in-app = temps réel via SignalR (pas Hangfire) +await _signalrHub.SendEventAsync(event); +``` + +--- + +## 7. Configuration par User + +Chaque utilisateur peut configurer ses notifications : + +```csharp +public class UserNotificationConfig +{ + public Guid UserId { get; set; } + public bool EmailEnabled { get; set; } = true; + public bool GotifyEnabled { get; set; } = false; + public string EmailAddress { get; set; } = string.Empty; + public List SubscribedEvents { get; set; } = new(); + public string Language { get; set; } = "fr"; + public bool DailyDigest { get; set; } = true; + public bool WeeklyDigest { get; set; } = false; +} +``` + +UI User : + +```text +┌──────────────────────────────────────────────┐ +│ Mes notifications │ +│ │ +│ Recevoir les notifications par : │ +│ [✅] Email : jean@example.com │ +│ [ ] Gotify │ +│ │ +│ M'alerter pour : │ +│ [✅] Personnes détectées │ +│ [✅] Visages inconnus │ +│ [ ] Véhicules │ +│ [✅] Caméra hors ligne │ +│ [ ] Mouvement seul │ +│ │ +│ Résumés : │ +│ [✅] Résumé quotidien │ +│ [ ] Résumé hebdomadaire │ +│ │ +│ Langue des notifications : [Français ▼] │ +└──────────────────────────────────────────────┘ +``` + +--- + +## 8. Résumés quotidiens/hebdomadaires (Hangfire) + +```csharp +// Planifié dans Hangfire +RecurringJob.AddOrUpdate( + "daily-digest", + j => j.ExecuteAsync(CancellationToken.None), + Cron.Daily(8)); // 8h00 + +public class DailyDigestJob +{ + public async Task ExecuteAsync(CancellationToken ct) + { + var users = await _db.Users + .Where(u => u.NotificationConfig.DailyDigest) + .ToListAsync(ct); + + foreach (var user in users) + { + var stats = await BuildDailyStatsAsync(user.Id, ct); + BackgroundJob.Enqueue(j => + j.ExecuteAsync(stats, "email", user.NotificationConfig.Language, ct)); + } + } +} +``` + +--- + +## 9. Tests + +``` +Notification is sent when person detected +SMTP failure retries 3 times via Hangfire +Gotify notification is sent correctly +User can disable email notifications +Template rendering replaces all variables +Missing variable does not crash (Scriban safe) +Template editing in UI saves correctly +Template preview shows correct rendering +Fallback to default template works +Fallback to English template works +Daily digest is generated at configured hour +User language changes template language +Admin can test SMTP connection from UI +Admin can test Gotify connection from UI +``` \ No newline at end of file diff --git a/docs/signalr-usage.md b/docs/signalr-usage.md new file mode 100644 index 0000000..5b4eacf --- /dev/null +++ b/docs/signalr-usage.md @@ -0,0 +1,450 @@ +# Heimdall — SignalR : Tous les hubs, events temps réel + +**Stack :** SignalR (intégré à ASP.NET Core) — pas de lib externe supplémentaire + +--- + +## 1. Architecture générale + +```text +┌─────────────────────────────────────────────────────────────┐ +│ SIGNALR CENTRAL │ +│ │ +│ /hubs/events → Événements de détection │ +│ /hubs/streaming → Signaling WebRTC │ +│ /hubs/monitoring → Status (agents, caméras, alertes) │ +│ /hubs/notifications→ Notifications in-app │ +│ /hubs/admin → Changements config (admin broadcast) │ +│ │ +└─────────────────────────────────────────────────────────────┘ +``` + +Chaque hub est authentifié (JWT ou API Key). Les connexions sont groupées +par Site et par User pour ne recevoir que les events pertinents. + +--- + +## 2. Hub /hubs/events — Événements de détection + +### Connexion + +```csharp +[Authorize] +public class EventsHub : Hub +{ + public override async Task OnConnectedAsync() + { + // L'User rejoint automatiquement les groupes de ses sites + var userId = Context.User.GetUserId(); + var isAdmin = Context.User.IsInRole(AppRoles.Admin); + + if (isAdmin) + { + await Groups.AddToGroupAsync(Context.ConnectionId, "all-sites"); + } + else + { + var siteIds = await _db.UserSites + .Where(us => us.UserId == userId) + .Select(us => us.SiteId.ToString()) + .ToListAsync(); + + foreach (var siteId in siteIds) + await Groups.AddToGroupAsync(Context.ConnectionId, $"site-{siteId}"); + } + } +} +``` + +### Événements émis + +| Nom | Payload | Destinataires | Quand | +|---|---|---|---| +| `EventCreated` | `EventDto` | Groupe du site | Nouvel événement de détection | +| `PersonDetected` | `PersonEventDto` | Groupe du site | Personne reconnue | +| `UnknownPerson` | `UnknownPersonDto` | Groupe du site + Admins | Visage inconnu | +| `VehicleDetected` | `VehicleEventDto` | Groupe du site | Véhicule détecté | +| `LicensePlateRead` | `PlateEventDto` | Groupe du site | Plaque lue | +| `MotionDetected` | `MotionDto` | Groupe du site (silencieux) | Mouvement simple | + +### Exemple d'envoi + +```csharp +// Dans le handler de détection IA +public class DetectionResultHandler +{ + private readonly IHubContext _hub; + + public async Task HandleAsync(DetectionResult result, CancellationToken ct) + { + var dto = _mapper.Map(result); + + // Envoyer au groupe du site + await _hub.Clients + .Group($"site-{result.SiteId}") + .SendAsync("EventCreated", dto, ct); + + // Si visage inconnu, envoyer aussi aux admins + if (result.EventType == EventType.UnknownPerson) + { + await _hub.Clients + .Group("all-sites") + .SendAsync("UnknownPerson", dto, ct); + } + } +} +``` + +--- + +## 3. Hub /hubs/streaming — Signaling WebRTC + +**Voir `docs/specs.md` §13 pour le protocole complet.** + +```csharp +[Authorize] +public class StreamingHub : Hub +{ + /// + /// Agent : s'enregistre comme source de flux pour une caméra + /// + public async Task RegisterSource(Guid agentId, Guid cameraId) + { + await Groups.AddToGroupAsync( + Context.ConnectionId, $"camera-{cameraId}"); + } + + /// + /// Browser : demande un flux pour une caméra + /// + public async Task RequestStream(Guid cameraId) + { + await Groups.AddToGroupAsync( + Context.ConnectionId, $"viewer-{cameraId}"); + + // Notifier l'Agent qu'un viewer arrive + await Clients.Group($"camera-{cameraId}") + .SendAsync("ViewerConnected", Context.ConnectionId); + } + + /// + /// Agent → Browser : offre SDP + /// + public async Task SendSdp(string sdp, string targetConnectionId) + { + await Clients.Client(targetConnectionId) + .SendAsync("SdpOffer", sdp); + } + + /// + /// Browser → Agent : réponse SDP + /// + public async Task SendAnswer(string sdp, string targetConnectionId) + { + await Clients.Client(targetConnectionId) + .SendAsync("SdpAnswer", sdp); + } + + /// + /// Échange ICE candidates (Agent ↔ Browser) + /// + public async Task SendIceCandidate(string candidate, string targetConnectionId) + { + await Clients.Client(targetConnectionId) + .SendAsync("IceCandidate", candidate); + } + + /// + /// Browser : arrête de regarder le flux + /// + public async Task StopStreaming(Guid cameraId) + { + await Groups.RemoveFromGroupAsync( + Context.ConnectionId, $"viewer-{cameraId}"); + + await Clients.Group($"camera-{cameraId}") + .SendAsync("ViewerDisconnected", Context.ConnectionId); + } +} +``` + +### Participants + +| Type | Se connecte en tant que | Envoie | Reçoit | +|---|---|---|---| +| **Agent** (SIPSorcery) | `RegisterSource` | SendSdp, SendIceCandidate | ViewerConnected, ViewerDisconnected, SdpAnswer, IceCandidate | +| **Browser** (Blazor) | `RequestStream` | SendAnswer, SendIceCandidate, StopStreaming | SdpOffer, IceCandidate | + +--- + +## 4. Hub /hubs/monitoring — Status temps réel + +```csharp +[Authorize] +public class MonitoringHub : Hub +{ + public override async Task OnConnectedAsync() + { + var userId = Context.User.GetUserId(); + var isAdmin = Context.User.IsInRole(AppRoles.Admin); + + if (isAdmin) + { + await Groups.AddToGroupAsync(Context.ConnectionId, "admin-monitoring"); + } + else + { + var siteIds = await _db.UserSites + .Where(us => us.UserId == userId) + .Select(us => us.SiteId.ToString()) + .ToListAsync(); + + foreach (var siteId in siteIds) + await Groups.AddToGroupAsync( + Context.ConnectionId, $"monitoring-site-{siteId}"); + } + } +} +``` + +### Événements émis + +| Nom | Payload | Destinataires | Quand | +|---|---|---|---| +| `AgentStatusChanged` | `AgentStatusDto` | Groupe monitoring du site | Agent online/offline | +| `CameraStatusChanged` | `CameraStatusDto` | Groupe monitoring du site | Caméra online/offline | +| `StorageUsageUpdated` | `StorageDto` | Admin | Espace MinIO mis à jour | +| `GpuUsageUpdated` | `GpuDto` | Admin | Utilisation GPU CodeProject.AI | +| `JobStatusChanged` | `JobDto` | Admin | Un job Hangfire échoue | +| `SystemHealthChanged` | `HealthDto` | Admin | Health check global | + +### Exemple — Agent offline détecté + +```csharp +// Déclenché par le heartbeat timeout +BackgroundJob.Schedule( + j => j.ExecuteAsync(agentId, CancellationToken.None), + TimeSpan.FromSeconds(90)); + +public class AgentTimeoutJob +{ + public async Task ExecuteAsync(Guid agentId, CancellationToken ct) + { + var agent = await _db.Agents.FindAsync(new object[] { agentId }, ct); + if (agent == null) return; + + if (agent.LastHeartbeat < DateTime.UtcNow.AddSeconds(-90)) + { + agent.Status = AgentStatus.Offline; + await _db.SaveChangesAsync(ct); + + // Broadcast en temps réel + await _hub.Clients + .Group($"monitoring-site-{agent.SiteId}") + .SendAsync("AgentStatusChanged", new AgentStatusDto + { + AgentId = agent.Id, + Status = "Offline", + LastHeartbeat = agent.LastHeartbeat + }, ct); + } + } +} +``` + +--- + +## 5. Hub /hubs/notifications — Notifications in-app + +```csharp +[Authorize] +public class NotificationsHub : Hub +{ + public override async Task OnConnectedAsync() + { + // L'User rejoint son groupe de notifications personnel + var userId = Context.User.GetUserId().ToString(); + await Groups.AddToGroupAsync(Context.ConnectionId, $"notif-{userId}"); + } + + /// + /// L'User marque une notification comme lue + /// + public async Task MarkAsRead(Guid notificationId) + { + await _db.Notifications + .Where(n => n.Id == notificationId) + .ExecuteUpdateAsync(setters => + setters.SetProperty(n => n.ReadAt, DateTime.UtcNow)); + } + + /// + /// L'User marque toutes ses notifications comme lues + /// + public async Task MarkAllAsRead() + { + var userId = Context.User.GetUserId(); + await _db.Notifications + .Where(n => n.UserId == userId && n.ReadAt == null) + .ExecuteUpdateAsync(setters => + setters.SetProperty(n => n.ReadAt, DateTime.UtcNow)); + + // Mettre à jour le badge + await Clients.Caller.SendAsync("UnreadCount", 0); + } +} +``` + +### Événements émis + +| Nom | Payload | Destinataires | Quand | +|---|---|---|---| +| `NewNotification` | `NotificationDto` | Groupe notif-{userId} | Alerte pour cet user | +| `UnreadCount` | `int` | Groupe notif-{userId} | Mise à jour badge | +| `NotificationRead` | `Guid` | Groupe notif-{userId} | Confirmé par l'user | + +--- + +## 6. Hub /hubs/admin — Changements configuration + +```csharp +[Authorize(Policy = "AdminOnly")] +public class AdminHub : Hub +{ + /// + /// L'Admin rejoint le groupe admin-broadcast + /// + public override async Task OnConnectedAsync() + { + await Groups.AddToGroupAsync( + Context.ConnectionId, "admin-broadcast"); + } +} +``` + +### Événements émis + +| Nom | Payload | Destinataires | Quand | +|---|---|---|---| +| `ConfigChanged` | `ConfigChangeDto` | Admin broadcast | Modification config globale | +| `TemplateUpdated` | `TemplateDto` | Admin broadcast | Template notification modifié | +| `UserRoleChanged` | `UserRoleDto` | Admin broadcast | Permission utilisateur modifiée | +| `SiteUpdated` | `SiteDto` | Tous les users du site | Site modifié | +| `CameraAdded` | `CameraDto` | Tous les users du site | Nouvelle caméra | +| `CameraRemoved` | `Guid` | Tous les users du site | Caméra supprimée | + +### Usage côté Blazor + +```csharp +// Dans le Layout ou un service injecté +public class ConfigChangeListener : IDisposable +{ + private HubConnection? _hub; + + public async Task StartAsync() + { + _hub = new HubConnectionBuilder() + .WithUrl("/hubs/admin", options => + { + options.AccessTokenProvider = () => + _tokenProvider.GetTokenAsync(); + }) + .WithAutomaticReconnect() + .Build(); + + _hub.On("ConfigChanged", change => + { + // Recharger la config concernée + _invokeRequired(() => + { + switch (change.Type) + { + case "site": _navigation.Refresh(); break; + case "template": _notifService.ReloadTemplates(); break; + } + }); + }); + + await _hub.StartAsync(); + } + + public void Dispose() => _hub?.DisposeAsync(); +} +``` + +--- + +## 7. Hub Agent — Communication Agent → Central + +Les Agents se connectent aussi via SignalR (pas seulement HTTP REST) : + +```csharp +// Côté Agent +public class AgentSignalRService : BackgroundService +{ + private HubConnection? _hub; + + protected override async Task ExecuteAsync(CancellationToken ct) + { + _hub = new HubConnectionBuilder() + .WithUrl($"{_centralUrl}/hubs/events", options => + { + options.AccessTokenProvider = () => + Task.FromResult(_apiKey); + }) + .WithAutomaticReconnect() + .Build(); + + _hub.On("CameraStatusRequest", async request => + { + // Le Central demande le statut d'une caméra + var status = await _cameraService.CheckStatusAsync(request.CameraId, ct); + await _hub.InvokeAsync("CameraStatusResponse", status, ct); + }); + + _hub.On("SnapshotRequest", async request => + { + var snapshot = await _cameraService.CaptureSnapshotAsync( + request.CameraId, ct); + await _hub.InvokeAsync("SnapshotResponse", snapshot, ct); + }); + + await _hub.StartAsync(ct); + } +} +``` + +--- + +## 8. Résumé — Tous les hubs + +| Hub | Route | Auth | Clients | Usage | +|---|---|---|---|---| +| **EventsHub** | `/hubs/events` | JWT + API Key | Browser + Agent | Événements détection temps réel | +| **StreamingHub** | `/hubs/streaming` | JWT + API Key | Browser + Agent | Signaling WebRTC | +| **MonitoringHub** | `/hubs/monitoring` | JWT | Browser + Admin | Status agents, caméras, stockage | +| **NotificationsHub** | `/hubs/notifications` | JWT | Browser | Notifications in-app | +| **AdminHub** | `/hubs/admin` | JWT (Admin only) | Browser (Admin) | Broadcast changements config | + +--- + +## 9. Tests + +``` +EventsHub emits EventCreated to correct site group +EventsHub sends UnknownPerson to admin group too +StreamingHub relays SDP offer from Agent to Browser +StreamingHub relays ICE candidates bidirectionally +MonitoringHub sends AgentStatusChanged on timeout +MonitoringHub sends CameraStatusChanged on status change +NotificationsHub sends NewNotification to correct user +NotificationsHub MarkAsRead updates database +NotificationsHub MarkAllAsRead resets badge to 0 +AdminHub ConfigChanged reaches all connected admins +AdminHub CameraAdded reaches all users of the site +Agent can connect to EventsHub with API key +Agent receives SnapshotRequest and responds +Hub groups are correctly created per site +User without permission receives 403 on connect +Disconnected users are removed from groups +``` \ No newline at end of file diff --git a/docs/specs.md b/docs/specs.md index e0f8af3..bc837c1 100644 --- a/docs/specs.md +++ b/docs/specs.md @@ -1,5 +1,10 @@ > **Documentation associée :** -> - `docs/ui-pages.md` — Description détaillée de toutes les pages UI +> - `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 ````markdown