Files
Heimdall/docs/notifications.md
T

464 lines
17 KiB
Markdown
Raw Normal View History

# 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
```