Files
Heimdall/docs/notifications.md
T
arnaud.dartois 8929f0e61c
Heimdall Gitea / Detect CI scope (pull_request) Successful in 35s
Heimdall Gitea / Build and tests (pull_request) Skipped
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Publish versioned installer release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Successful in 40s
docs: distinguish shipped notification channels (#375)
2026-11-13 10:51:34 +01:00

19 KiB
Raw Blame History

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 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 :

Conception historique — ne décrit pas l’état livré

Les sections qui suivent conservent des exemples de conception antérieurs à l’implémentation actuelle. Gotify, l’éditeur de templates, les bibliothèques proposées, les tableaux d’événements et les écrans maquetés ci-dessous ne sont pas une description contractuelle des fonctions livrées. Se référer à la section d’état livré ci-dessus avant d’appliquer un exemple.


1. Canaux de notification — conception historique

Canal proposé Usage prévu
Email (SMTP) Notifications et résumés
Gotify Push
In-app (SignalR) Notifications dans l’UI

2. SMTP — exemple de conception historique

La configuration ci-dessous est un modèle de conception, pas le schéma actuel de l’interface :

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 — conception historique, non livrée

Gotify est un serveur de notification push self-hosted (Docker).

Dépendances

dotnet add package Gotify.NET

Configuration

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

┌──────────────────────────────────────────────┐
│  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 — conception historique

Architecture

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

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)

=== 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

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

┌──────────────────────────────────────────────────────┐
│  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)
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

// 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 :

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 :

┌──────────────────────────────────────────────┐
│  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)

// 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