docs: distinguish shipped notification channels #376

Merged
arnaud.dartois merged 2 commits from docs/notification-guide-status-375 into main 2026-11-13 10:55:22 +01:00
2 changed files with 36 additions and 464 deletions

No files matched your search

+34 -464
View File
@@ -1,464 +1,34 @@
# 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<NotificationTemplate> _templates;
public async Task<string> RenderAsync(
EventType eventType,
string language,
string channel,
Dictionary<string, object> 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<SendNotificationJob>(j =>
j.ExecuteAsync(event.Id, "email", user.Language, CancellationToken.None));
BackgroundJob.Enqueue<SendNotificationJob>(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<EventType> 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<DailyDigestJob>(
"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<SendNotificationJob>(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
```
# Heimdall — Notifications
## État livré vérifié dans le dépôt
Les canaux externes déclarés par `NotificationChannel` sont `Email` et `Ntfy`;
les notifications in-app sont consultables séparément dans le centre
`/notifications`. L’interface utilise les endpoints authentifiés
`/api/notifications` et le hub `/hubs/notifications` pour le compteur non lu.
Voir [`signalr-usage.md`](signalr-usage.md) pour le contrat du hub.
Les réglages administrateur se trouvent dans `/settings` (policy
`Admin.Manage`) : configuration et test SMTP, configuration et test ntfy. Les
préférences de l’utilisateur, dont l’adresse email, l’activation ntfy, le topic,
les événements abonnés et les options de résumé, sont éditées dans `/profile`.
La livraison email utilise `EmailService`; les notifications push utilisent
`NtfyService` et Hangfire. `DailyDigestJob` envoie le résumé quotidien à 8 h;
`WeeklyDigestJob` envoie le résumé hebdomadaire le lundi à 8 h, selon les
expressions cron enregistrées dans `JobSetup`.
Ces constats sont une vérification statique des sources, pas une validation de
serveur SMTP, de serveur ntfy ni d’un déploiement. La configuration de ces
services dépend de l’opérateur.
Sources principales :
- [`NotificationChannel`](../src/Heimdall.Domain/Enums/NotificationChannel.cs)
- [`NotificationSettingsSection`](../src/Heimdall.Web/Components/Settings/NotificationSettingsSection.razor)
- [`NotificationsPage`](../src/Heimdall.Web/Components/Pages/NotificationsPage.razor)
- [`NotificationsController`](../src/Heimdall.Web/Controllers/NotificationsController.cs)
- [`NtfyService`](../src/Heimdall.Infrastructure/Services/NtfyService.cs)
- [`EmailService`](../src/Heimdall.Infrastructure/Services/EmailService.cs)
- [`DailyDigestJob`](../src/Heimdall.Infrastructure/Jobs/DailyDigestJob.cs)
- [`WeeklyDigestJob`](../src/Heimdall.Infrastructure/Jobs/WeeklyDigestJob.cs)
- [Planifications Hangfire](../src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs)
+2
View File
@@ -7,6 +7,8 @@ description: Implement and accept the authenticated Heimdall in-app notification
The header bell is rendered by `Components/Shared/NotificationBadge.razor`; it displays the unread count delivered by `NotificationsHubClient` and must navigate to `/notifications`. The page reads the signed-in user's list through `HeimdallApiClient` and the existing `GET /api/notifications` endpoint. Read actions use the existing per-user `POST /api/notifications/{id}/read` and `POST /api/notifications/mark-all-read` endpoints, then refresh the hub count. Keep authorization on the page and user scoping in the API/application handlers; never accept a user id from the browser.
When documenting delivery channels, verify `NotificationChannel`, `SendNotificationJob`, `NotificationSettingsSection.razor`, `Profile.razor`, the delivery services, and `BackgroundJobs/JobSetup.cs`. The shipped external channels are SMTP email and ntfy; do not describe Gotify as integrated. `/settings` owns global SMTP/ntfy settings and test actions, while `/profile` owns user preferences. Check both digest job implementations and their schedules before documenting cadence. Distinguish source inspection from validation against a real SMTP/ntfy deployment. Remove obsolete channel integrations, editor flows, and test claims from `docs/notifications.md`; if a historical example must remain, label that exact heading/table/snippet locally rather than relying on a broad notice elsewhere in the guide.
## Acceptance
1. Build `Heimdall.Web` with the SDK from `global.json` and run focused Web tests.