diff --git a/docs/specifications/detection-camera.md b/docs/specifications/detection-camera.md new file mode 100644 index 0000000..a0f1f57 --- /dev/null +++ b/docs/specifications/detection-camera.md @@ -0,0 +1,975 @@ +# Spécification — Détection & Découverte de Caméras + +> **Inspiré de**: [Strix](https://github.com/eduard256/Strix) v2.1 — Moteur de découverte de flux IP +> **Date**: 2026-07-18 +> **Statut**: Proposition d'architecture + +--- + +## 1. Résumé Exécutif + +Heimdall a besoin d'un système de **découverte automatique de caméras** sur le réseau local +pour remplacer la configuration manuelle actuelle (IP + URL RTSP saisis à la main). + +L'architecture s'inspire directement de **Strix** (Go), un moteur de découverte de flux +éprouvé qui supporte 3600+ marques, 100 000+ patterns d'URL et 20 protocoles — mais +réimplémenté en **.NET 10 Clean Architecture** avec une intégration profonde dans l'écosystème +Heimdall (PostgreSQL, Hangfire, SignalR, Blazor). + +--- + +## 2. Pipeline de Découverte + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ PIPELINE DE DÉCOUVERTE │ +│ │ +│ 1. SCAN RÉSEAU 2. PROBE DEVICE 3. RECHERCHE DB 4. TEST FLUX │ +│ ┌─────────┐ ┌──────────┐ ┌───────────┐ ┌─────────┐ │ +│ │ Nmap │────→│ ONVIF │────→│ Heimdall │────→│ RTSP │ │ +│ │ ARP │ │ WS-Disc │ │ CamDB │ │ HTTP │ │ +│ │ mDNS │ │ HTTP │ │ (brands │ │ ONVIF │ │ +│ │ (sous- │ │ mDNS/HAP │ │ + modèles)│ │ profil │ │ +│ │ réseau │ │ ARP/OUI │ │ │ │ capture │ │ +│ │ local) │ │ (100ms) │ │ │ │ écran │ │ +│ └─────────┘ └──────────┘ └───────────┘ └─────────┘ │ +│ │ │ │ │ │ +│ ▼ ▼ ▼ ▼ │ +│ ┌─────────────────────────────────────────────────────────┐ │ +│ │ SYNTHÈSE │ │ +│ │ - IP + MAC + Fabricant + Modèle │ │ +│ │ - Protocoles detectés (ONVIF, RTSP, HTTP, HomeKit) │ │ +│ │ - URL de flux testées + codecs + résolution │ │ +│ │ - Statut (en ligne/hors ligne/type détecté) │ │ +│ └─────────────────────────────────────────────────────────┘ │ +│ │ +│ ▼ │ +│ ┌─────────────────────────────────────────────────────────┐ │ +│ │ INTÉGRATION HEIMDALL │ │ +│ │ - Création automatique de l'entité Camera │ │ +│ │ - Sauvegarde des credentials (chiffrés) │ │ +│ │ - Envoi config à l'Agent via SignalR │ │ +│ │ - Notification UI (Blazor Hub) │ │ +│ └─────────────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +--- + +## 3. Scan Réseau (NetworkScanner) + +### 3.1. Découverte des hôtes + +Stratégie progressive avec timeouts agressifs : + +| Méthode | Port/Protocole | Timeout | Informations obtenues | +|---------|---------------|---------|----------------------| +| **ARP lookup** (table ARP locale) | Niveau 2 | 5ms | MAC, fabricant via OUI | +| **mDNS multicast** (`_hap._tcp.local`) | UDP 5353 | 1.5s | Caméras HomeKit (nom, modèle, device_id, catégorie) | +| **Ping ICMP** | ICMP | 500ms | Hôte joignable (nécessite `CAP_NET_RAW`) | +| **Scan ports ciblé** | 554,80,443,8080,34567,1935,81,88,8090,5544,10554,7070,7447,3702,8554,8001,8081,51826 | 100ms par port (parallèle 20 workers) | Ports ouverts typiques caméra | +| **WS-Discovery ONVIF** | UDP 3702 (unicast) | 100ms | Détection ONVIF — nom, hardware, XAddrs (URL device_service) | + +> **Note**: Le scan réseau est exécuté **uniquement** sur les sous-réseaux configurés +> dans le Site (site.NetworkCidr) par le **Heimdall.Workers** (pas l'Agent). +> Un background job Hangfire planifié (`NetworkScanJob`) lance le scan périodiquement. + +### 3.2. Architecture du scan + +``` +NetworkScanJob (Hangfire) + │ + ├── NetworkScannerService + │ ├── ArpLookup() → (MAC, Vendor) + │ ├── MulticastMdnsQuery() → (HomeKit cameras) + │ ├── PingSweep(cidr) → list joignables + │ └── PortScan(ip, ports) → list ports ouverts + │ + ├── OnvifProbeService + │ └── ProbeDevice(ip) → ONVIFResult (XAddrs, name, hardware) + │ + ├── HttpProbeService + │ └── Probe(ip, ports) → HTTPResult (status, server header) + │ + ├── StreamTestService + │ ├── TestRtsp(url, creds) → codecs, résolution, latence, screenshot + │ ├── TestHttp(url, creds) → MJPEG snapshot + │ └── TestOnvifProfile(url) → résolution profils → test RTSP + │ + └── DiscoveryResultProcessor + ├── MergeResults() → fusionne toutes les données + └── CreateOrUpdateCamera() → persiste l'entité Camera +``` + +--- + +## 4. Probe Device (ProbeService) + +### 4.1. ONVIF WS-Discovery + +Envoi d'un message SOAP `Probe` en UDP unicast sur le port 3702 : + +```xml + + + + http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe + urn:uuid:{uuid} + urn:schemas-xmlsoap-org:ws:2005:04:discovery + + + + + + + + +``` + +**Parsing de la réponse** — extraction depuis le XML SOAP : +- `XAddrs` → URL du `device_service` (correction bug `0.0.0.0` → IP réelle) +- `Scopes` → `name`, `hardware` (ex: `onvif://www.onvif.org/name/DS-2CD2032`) +- Port extrait du XAddrs (ou 80 par défaut) + +**Résultat**: +```csharp +public record OnvifProbeResult( + string DeviceServiceUrl, // ex: "http://192.168.1.100:8080/onvif/device_service" + int Port, // port du service + string? Name, // nom ONVIF du device + string? Hardware, // modèle matériel + string? Location); // emplacement (optionnel) +``` + +### 4.2. Détection HomeKit (mDNS/HAP) + +**Recherche** : Interrogation multicast `_hap._tcp.local` (PTR) sur UDP 5353. +**Filtre** : Ne conserve que les réponses avec `ci=17` (camera) ou `ci=18` (doorbell). + +**Parsing** des enregistrements TXT : + +| Clé TXT | Champ | Exemple | +|---------|-------|---------| +| `ci` | Category | `17` (camera), `18` (doorbell) | +| `id` | Device ID | `90:8C:0F:F2:EC:F3` | +| `md` | Model | `HomeKit Camera v2` | +| `sf` | Status Flags | `0` (non paired), `1` (paired) | +| `s#` | SRV port | `51826` ou dynamique | + +**Résultat**: +```csharp +public record HomeKitProbeResult( + string Name, + string DeviceId, + string Model, + string Category, // "camera" | "doorbell" + bool IsPaired, + int Port); +``` + +### 4.3. HTTP Probe + +HEAD/GET sur les ports HTTP courants (80, 8080, 443, 81, 88, 8090) : + +```csharp +public record HttpProbeResult( + int Port, + int StatusCode, + string? ServerHeader, // ex: "Hikvision-Webs", "DVRDVS-Webs" + bool SupportsDigestAuth); +``` + +Le `Server` header identifie le fabricant : `Hikvision-Webs` = Hikvision, +`DVRDVS-Webs` = Dahua, `Kguard` = Kguard, etc. + +### 4.4. ARP + OUI Lookup + +Consultation de la table ARP locale (`/proc/net/arp` ou `ip neigh show`) : +``` +192.168.1.100 dev eth0 lladdr c0:56:e3:aa:bb:cc REACHABLE +``` + +Extraction OUI (3 premiers octets) → lookup dans table SQLite intégrée : +- `C0:56:E3` → `Hikvision` +- `00:23:6A` → `Hikvision` +- `3C:08:F6` → `Dahua` +- `AC:CC:8E` → `Dahua` +- `00:12:1B` → `ACTi` +- `F4:08:8C` → `Reolink` + +**Résultat**: +```csharp +public record ArpProbeResult( + string MacAddress, + string? Vendor); +``` + +### 4.5. Port Scan Ciblé + +Scan de 17 ports connus des caméras, en parallèle (20 workers, 100ms timeout par port) : + +| Port | Protocole | Usage typique | +|------|-----------|---------------| +| 554 | RTSP | Flux vidéo standard | +| 80 | HTTP | Interface web, MJPEG, API ONVIF | +| 443 | HTTPS | Chiffré | +| 8080 | HTTP | Alternative, API ONVIF | +| 34567 | DVRIP | Dahua/Sofia protocol | +| 1935 | RTMP | Streaming, NVR chinois | +| 3702 | UDP | WS-Discovery ONVIF | +| 8554 | RTSP | Alternative | +| 5544 | RTSP | Alternative | +| 10554 | RTSP | Alternative | +| 81 | HTTP | Alternative | +| 88 | HTTP | Alternative | +| 8090 | HTTP | Alternative | +| 8001 | HTTP | Alternative | +| 8081 | HTTP | Alternative | +| 7070 | HTTP | Alternative | +| 7447 | HTTP | Alternative | +| 51826 | TCP | HomeKit (HAP) | + +--- + +## 5. Recherche Base de Données (CameraDatabase) + +### 5.1. Structure de la base + +Base SQLite intégrée au Central (téléchargée depuis StrixCamDB ou maintenue localement) : + +```sql +-- Marques +CREATE TABLE brands ( + brand_id TEXT PRIMARY KEY, -- ex: "hikvision" + brand TEXT NOT NULL -- ex: "Hikvision" +); + +-- Patterns d'URL par marque +CREATE TABLE streams ( + id INTEGER PRIMARY KEY, + brand_id TEXT NOT NULL REFERENCES brands(brand_id), + url TEXT NOT NULL, -- pattern avec placeholders + protocol TEXT NOT NULL, -- "rtsp", "http", "rtmp", "dvrip", "bubble" + port INTEGER DEFAULT 0 -- 0 = port par défaut du protocole +); + +-- Modèles spécifiques +CREATE TABLE stream_models ( + stream_id INTEGER REFERENCES streams(id), + model TEXT NOT NULL -- ex: "DS-2CD2032" +); + +-- Presets (collections curated) +CREATE TABLE presets ( + preset_id TEXT PRIMARY KEY, -- ex: "onvif", "popular-rtsp" + name TEXT NOT NULL +); + +CREATE TABLE preset_streams ( + preset_id TEXT REFERENCES presets(preset_id), + url TEXT NOT NULL, + protocol TEXT NOT NULL, + port INTEGER DEFAULT 0 +); + +-- Table OUI pour lookup MAC → Fabricant +CREATE TABLE oui ( + mac_prefix TEXT PRIMARY KEY, -- ex: "C056E3" + vendor TEXT NOT NULL +); +``` + +### 5.2. Types de résultats + +| Type | ID | Description | Exemple | +|------|-----|-------------|---------| +| `preset` | `p:{preset_id}` | Collection de patterns (ex: "ONVIF standard") | `p:onvif-global` | +| `brand` | `b:{brand_id}` | Tous les patterns d'une marque | `b:hikvision` | +| `model` | `m:{brand_id}:{model}` | Patterns d'un modèle spécifique | `m:hikvision:DS-2CD2032` | + +### 5.3. API Recherche + +```csharp +// Recherche textuelle (marque, modèle) +Task SearchAsync(string query, CancellationToken ct); + +// Construction des URL de flux à partir d'un ID +Task BuildStreamsAsync(StreamRequest request, CancellationToken ct); +``` + +```csharp +public record StreamRequest( + string[] Ids, // IDs de recherche (ex: "b:hikvision", "p:onvif") + string Ip, + string? Username, + string? Password, + int Channel = 0, + int[]? PortFilter = null); +``` + +**Placeholders supportés** (substitution dans les patterns SQLite) : + +| Placeholder | Remplacé par | +|---|---| +| `[CHANNEL]` / `[channel]` | Numéro de canal | +| `[USERNAME]` / `[user]` | Nom d'utilisateur (URL-encoded) | +| `[PASSWORD]` / `[pass]` / `[pwd]` | Mot de passe (URL-encoded) | +| `[IP]` / `[ip]` | Adresse IP | +| `[PORT]` / `[port]` | Port | +| `[WIDTH]` / `[width]` | `640` (défaut) | +| `[HEIGHT]` / `[height]` | `480` (défaut) | +| `[AUTH]` / `[auth]` | Basic auth base64 | + +--- + +## 6. Test de Flux (StreamTester) + +### 6.1. Architecture + +20 workers parallèles. Chaque worker : + +1. Reçoit une URL de flux (pool de workers) +2. Sélectionne le handler selon le protocole +3. Se connecte et négocie (timeout 10s) +4. Capture une image clé (keyframe) → screenshot JPEG +5. Extrait codecs, résolution, latence +6. Retourne le résultat + +### 6.2. Protocoles supportés + +| Protocole | Handler | Lib .NET | Exemple d'URL | +|-----------|---------|----------|---------------| +| **RTSP** | `RtspHandler` | `LibVLC` / `FFmpeg.Autogen` / `RtspClient` | `rtsp://admin:pass@192.168.1.100/Streaming/Channels/101` | +| **HTTP MJPEG** | `HttpMjpegHandler` | `HttpClient` + `ImageSharp` | `http://admin:pass@192.168.1.100/ISAPI/Streaming/channels/101/picture` | +| **HTTP JPEG** | `HttpJpegHandler` | `HttpClient` | `http://admin:pass@192.168.1.100/ snapshot.jpg` | +| **ONVIF** | `OnvifProfileHandler` | `Onvif.Client` (NuGet) | `onvif://admin:pass@192.168.1.100` | +| **DVRIP** | `DvripHandler` | Implémentation TCP/Sofia | `dvrip://admin:pass@192.168.1.100:34567` | +| **RTMP** | `RtmpHandler` | `FFmpeg.Autogen` | `rtmp://admin:pass@192.168.1.100:1935/live` | +| **HomeKit** | `HomeKitHandler` | HAP lib | `homekit://...?device_id=...&pin=...` | + +### 6.3. Résultat de test + +```csharp +public record StreamTestResult( + string SourceUrl, // URL testée (credentials masqués dans les logs) + string[] Codecs, // eg. ["H264", "PCMA"] + int Width, // Résolution largeur + int Height, // Résolution hauteur + long LatencyMs, // Latence de connexion + byte[]? ScreenshotJpeg, // Screenshot JPEG (optionnel) + bool IsAlive); // Flux fonctionnel +``` + +--- + +## 7. Modèle de Données — Entités Domain + +### 7.1. Nouveaux enums + +```csharp +// Dans Heimdall.Domain/Enums/ + +/// Méthode par laquelle la caméra a été détectée. +public enum CameraDiscoveryMethod +{ + Manual = 0, // Saisie manuelle (actuel) + OnvifWsDiscovery = 1, // WS-Discovery ONVIF + MdnsHomeKit = 2, // mDNS HomeKit + NetworkScan = 3, // Scan réseau générique + HttpProbe = 4, // Détection par en-tête HTTP + ArpProbe = 5, // ARP + OUI + Imported = 6 // Import depuis fichier +} + +/// Protocoles de flux supportés. +public enum StreamProtocol +{ + Rtsp, + Rtsps, + Http, + Https, + Rtmp, + Rtmps, + Dvrip, + Bubble, + HomeKit +} + +/// Type de caméra détecté. +public enum DetectedCameraType +{ + Standard, // Caméra IP standard + HomeKit, // Apple HomeKit + Nvr, // NVR (multiple canaux) + Doorbell, // Sonnette vidéo + Unknown +} +``` + +### 7.2. Entité Camera — Modifications + +```csharp +// Ajouts à Camera.cs existant + +// Méthode de découverte +public CameraDiscoveryMethod DiscoveryMethod { get; private set; } +public DetectedCameraType DetectedType { get; private set; } + +// MAC + Fabricant (ARP/OUI) +public string? MacAddress { get; private set; } + +// Protocoles supportés (flags) +public StreamProtocol SupportedProtocols { get; private set; } + +// Réseau +public string? IpAddress { get; private set; } // IP fixe si statique +public int? RtspPort { get; private set; } +public int? HttpPort { get; private set; } +public int? OnvifPort { get; private set; } + +// Dernière découverte +public DateTime? LastDiscoveredAt { get; private set; } + +// Dernier test de flux +public DateTime? LastStreamTestAt { get; private set; } +public string? LastTestedCodecs { get; private set; } // JSON array +public int? LastTestedWidth { get; private set; } +public int? LastTestedHeight { get; private set; } +public long? LastTestedLatencyMs { get; private set; } + +// Nouveaux sous-flux +public string? SubRtspUrl { get; private set; } // Flux secondaire (détection) + +// Méthodes +public void SetDiscoveryInfo( + CameraDiscoveryMethod method, + DetectedCameraType type, + string? macAddress, + string ipAddress); + +public void SetStreamTestResult( + string? subRtspUrl, + string codecsJson, + int width, + int height, + long latencyMs); + +public void SetPorts( + int? rtspPort, + int? httpPort, + int? onvifPort); +``` + +### 7.3. Nouvelles entités + +```csharp +/// +/// Résultat de probe — stocké temporairement pour le pipeline de découverte. +/// +public class CameraDiscoveryResult : Entity +{ + public Guid SiteId { get; private set; } + public string IpAddress { get; private set; } + public string? MacAddress { get; private set; } + public string? Vendor { get; private set; } + public string? Hostname { get; private set; } + public DetectedCameraType DetectedType { get; private set; } + public CameraDiscoveryMethod DiscoveryMethod { get; private set; } + + // Résultats des probes + public int[] OpenPorts { get; private set; } = []; + public string? OnvifDeviceServiceUrl { get; private set; } + public string? OnvifName { get; private set; } + public string? OnvifHardware { get; private set; } + public string? HttpServerHeader { get; private set; } + public int? HttpStatusCode { get; private set; } + public bool IsReachable { get; private set; } + + // Timestamp + public DateTime ProbedAt { get; private set; } = DateTime.UtcNow; + + // Navigation + public Site Site { get; private set; } = null!; + public ICollection DiscoveredStreams { get; private set; } = []; +} + +/// +/// Flux vidéo découvert lors du test. +/// +public class DiscoveredStream +{ + public Guid Id { get; private set; } + public Guid DiscoveryResultId { get; private set; } + public string Url { get; private set; } + public StreamProtocol Protocol { get; private set; } + public string[] Codecs { get; private set; } = []; + public int Width { get; private set; } + public int Height { get; private set; } + public long LatencyMs { get; private set; } + public bool IsMainStream { get; private set; } + public bool IsAlive { get; private set; } + + public CameraDiscoveryResult DiscoveryResult { get; private set; } = null!; +} +``` + +--- + +## 8. API REST — Endpoints de Découverte + +### 8.1. Probe (découverte initiale) + +``` +POST /api/discovery/probe +``` + +```json +{ + "siteId": "guid", + "ip": "192.168.1.100", + "subnetCidr": "192.168.1.0/24" +} +``` + +**Sans IP** → scan du sous-réseau entier : +``` +POST /api/discovery/scan +``` + +```json +{ + "siteId": "guid", + "subnetCidr": "192.168.1.0/24", + "timeoutMs": 30000 +} +``` + +### 8.2. Search database + +``` +GET /api/discovery/search?q=hikvision +``` + +```json +{ + "results": [ + { "type": "brand", "id": "b:hikvision", "name": "Hikvision" }, + { "type": "model", "id": "m:hikvision:DS-2CD2032", "name": "Hikvision: DS-2CD2032" } + ] +} +``` + +### 8.3. Build streams + +``` +POST /api/discovery/streams +``` + +```json +{ + "ids": ["b:hikvision", "p:onvif"], + "ip": "192.168.1.100", + "username": "admin", + "password": "pass", + "channel": 0 +} +``` + +### 8.4. Test streams + +``` +POST /api/discovery/test +``` + +```json +{ + "sourceId": "guid", + "streams": [ + "rtsp://admin:pass@192.168.1.100/Streaming/Channels/101", + "rtsp://admin:pass@192.168.1.100/Streaming/Channels/102" + ] +} +``` + +**Réponse**: +```json +{ + "sessionId": "uuid", + "status": "running", + "total": 2, + "tested": 0 +} +``` + +**Polling** → `GET /api/discovery/test/{sessionId}` + +```json +{ + "sessionId": "uuid", + "status": "done", + "total": 2, + "tested": 2, + "alive": 2, + "results": [ + { + "source": "rtsp://admin:***@192.168.1.100/Streaming/Channels/101", + "codecs": ["H264", "PCMA"], + "width": 1920, + "height": 1080, + "latencyMs": 45, + "screenshotUrl": "/api/discovery/test/{sessionId}/screenshot/0" + } + ] +} +``` + +### 8.5. Add discovered camera + +``` +POST /api/discovery/confirm +``` + +```json +{ + "siteId": "guid", + "name": "Entrée principale", + "discoveryResultId": "guid", + "mainStreamUrl": "rtsp://admin:pass@192.168.1.100/Streaming/Channels/101", + "subStreamUrl": "rtsp://admin:pass@192.168.1.100/Streaming/Channels/102", + "username": "admin", + "password": "encrypted", + "detectionProfile": { ... } +} +``` + +--- + +## 9. Interfaces Application + +```csharp +/// Service de découverte réseau pour les caméras. +public interface ICameraDiscoveryService +{ + // Probe une IP unique → résultats complets + Task ProbeIpAsync( + Guid siteId, string ip, CancellationToken ct); + + // Scan d'un sous-réseau → liste de résultats + Task> ScanSubnetAsync( + Guid siteId, string cidr, int timeoutMs, CancellationToken ct, + IProgress? progress = null); + + // Recherche dans la base de caméras + Task SearchDatabaseAsync(string query, CancellationToken ct); + + // Construction des URL de flux + Task BuildStreamUrlsAsync( + StreamRequest request, CancellationToken ct); + + // Test de flux + Task TestStreamsAsync( + Guid sourceId, string[] urls, CancellationToken ct); + + // Confirmation et création de la caméra + Task ConfirmDiscoveryAsync( + ConfirmDiscoveryRequest request, CancellationToken ct); +} + +/// Test de flux en temps réel. +public interface IStreamTesterService +{ + Task CreateSessionAsync( + string[] urls, CancellationToken ct); + + Task GetSessionAsync( + Guid sessionId, CancellationToken ct); + + Task GetScreenshotAsync( + Guid sessionId, int index, CancellationToken ct); + + Task CancelSessionAsync(Guid sessionId, CancellationToken ct); +} +``` + +--- + +## 10. Services Infrastructure + +### 10.1. NetworkScannerService + +```csharp +public class NetworkScannerService : INetworkScannerService +{ + // ARP table lookup (multi-plateforme) + Task LookupArpAsync(string ip, CancellationToken ct); + + // mDNS HomeKit query + Task QueryMdnsAsync(string ip, CancellationToken ct); + + // Ping ICMP + Task PingAsync(string ip, int timeoutMs, CancellationToken ct); + + // Port scan parallélisé + Task ScanPortsAsync(string ip, int[] ports, int timeoutMs, CancellationToken ct); + + // Sweep sous-réseau + IAsyncEnumerable SweepSubnetAsync( + string cidr, int timeoutMs, CancellationToken ct); +} +``` + +### 10.2. OnvifProbeService + +```csharp +public class OnvifProbeService : IOnvifProbeService +{ + // WS-Discovery unicast probe + Task ProbeDeviceAsync(string ip, int timeoutMs, CancellationToken ct); + + // Résolution des profils ONVIF + Task GetProfilesAsync(string deviceServiceUrl, + string? username, string? password, CancellationToken ct); + + // Obtention de l'URI RTSP pour un profil + Task GetStreamUriAsync(string deviceServiceUrl, + string profileToken, string? username, string? password, CancellationToken ct); +} +``` + +### 10.3. StreamTesterService + +```csharp +public class StreamTesterService : IStreamTesterService +{ + // Pool de workers parallèles (configurable) + // Support: RTSP, HTTP MJPEG/JPEG, ONVIF, RTMP, DVRIP + // Capture de screenshot via FFmpeg ou implémentation pure .NET + // Timeout par flux : 10s + // Session TTL : 30min après completion +} +``` + +### 10.4. OnvifClient (implémentation SOAP/XML) + +```csharp +public class OnvifClient +{ + // GetCapabilities() + // GetDeviceInformation() → manufacturer, model, firmware, serial + // GetProfiles() → liste des profils media + // GetStreamUri(token) → URI RTSP pour un profil + // GetServices() → services ONVIF disponibles + // SystemReboot() → si autorisé + // GetHostname() → nom d'hôte configuré +} +``` + +**NuGet candidates**: +- `Onvif.Client` (community) — basique +- `MJPEGStreamDecoder` — décodage MJPEG (HTTP) +- `FFmpeg.Autogen` — capture d'écran H264/H265 → JPEG +- `SharpPcap` ou `PacketDotNet` — ARP (Linux `CAP_NET_RAW`) + +--- + +## 11. Intégration Workers (Hangfire) + +### 11.1. NetworkScanJob + +```csharp +/// Job Hangfire planifié — scanne les sous-réseaux des sites actifs. +public class NetworkScanJob : IJob +{ + // Planifié toutes les 6h par site (cron) + // Découvre les nouvelles caméras + // Met à jour le statut des caméras existantes (Online/Offline) + // Envoie notification SignalR si nouveaux devices + + public async Task ExecuteAsync(CancellationToken ct) + { + var sites = await _db.Sites + .Where(s => s.IsActive && !s.IsDeleted) + .ToListAsync(ct); + + foreach (var site in sites.Where(s => s.NetworkCidr != null)) + { + var discovered = await _discoveryService.ScanSubnetAsync( + site.Id, site.NetworkCidr, 60000, ct); + + foreach (var result in discovered.Where(r => r.IsReachable)) + { + await _processor.ProcessDiscoveryResultAsync(result, ct); + } + } + } +} +``` + +### 11.2. CameraHealthCheckJob + +```csharp +/// Job Hangfire — vérifie l'état des flux toutes les 5min. +public class CameraHealthCheckJob : IJob +{ + // Pour chaque caméra Online : ping + RTSP describe (timeout 3s) + // Si échec → marque Offline, notifie + // Si succès après Offline → marque Online, notifie +} +``` + +### 11.3. StreamTestJob + +```csharp +/// Job Hangfire — test périodique des flux (codecs, résolution). +public class StreamTestJob : IJob +{ + // Planifié quotidiennement + // Re-test des flux découverts automatiquement + // Met à jour les métriques (latence, résolution, codecs) +} +``` + +--- + +## 12. Nouveaux Flags Camera (Enum) + +```csharp +[Flags] +public enum CameraCapability +{ + None = 0, + RtspStreaming = 1 << 0, // RTSP stream + HttpMjpeg = 1 << 1, // MJPEG over HTTP + HttpSnapshot = 1 << 2, // JPEG snapshot + Onvif = 1 << 3, // ONVIF protocol + OnvifPtz = 1 << 4, // PTZ over ONVIF + OnvifAudioIn = 1 << 5, // Audio input + OnvifAudioOut = 1 << 6, // Audio output + HomeKit = 1 << 7, // Apple HomeKit + Dvrip = 1 << 8, // Dahua DVRIP/Sofia + Rtmp = 1 << 9, // RTMP streaming + SubStream = 1 << 10, // Second flux (sous-flux) +} +``` + +--- + +## 13. DTOs Application + +```csharp +// Request/Response DTOs à ajouter + +public record ProbeRequest(Guid SiteId, string Ip); +public record ScanRequest(Guid SiteId, string SubnetCidr, int TimeoutMs = 30000); + +public record ProbeResponse( + string Ip, + bool IsReachable, + DetectedCameraType CameraType, + ArpInfo? Arp, + int[] OpenPorts, + OnvifInfo? Onvif, + HttpProbeInfo? Http, + HomeKitInfo? HomeKit, + string[]? MatchedBrands); + +public record ArpInfo(string MacAddress, string? Vendor); + +public record OnvifInfo( + string DeviceServiceUrl, + int Port, + string? Name, + string? Hardware, + string? Location); + +public record HttpProbeInfo(int Port, int StatusCode, string? ServerHeader); + +public record HomeKitInfo( + string Name, string DeviceId, string Model, + string Category, bool IsPaired, int Port); + +public record StreamTestSession( + Guid SessionId, + string Status, // "running" | "done" + int Total, + int Tested, + int Alive, + StreamTestResult[] Results); + +public record ConfirmDiscoveryRequest( + Guid SiteId, + string Name, + Guid DiscoveryResultId, + string MainStreamUrl, + string? SubStreamUrl, + string? Username, + string? Password, + CameraDetectionProfile? DetectionProfile); +``` + +--- + +## 14. Sécurité + +| Risque | Mitigation | +|--------|-----------| +| **Scan réseau non autorisé** | Limit aux sous-réseaux du Site ; nécessite rôle `Admin` ou `Supervisor` | +| **Credentials en clair dans les logs** | `ICredentialProtector` appliqué systématiquement ; masquage `****` dans logs | +| **WS-Discovery flood** | Rate limiting (10 probes/min/IP) ; timeout 100ms par requête | +| **Données OUI/StrixCamDB** | Base SQLite intégrée, pas d'appels réseau pour la résolution | +| **mDNS spoofing** | Validation de l'IP source ; ne fait pas confiance aux réponses non sollicitées | +| **RTSP brute force** | 3 tentatives max par IP + credentials ; cooldown 60s | + +--- + +## 15. Priorisation & Roadmap + +### Phase 1 — Probe & Découverte (🔴 P1) +- [ ] `NetworkScannerService` — ARP lookup, port scan, ping +- [ ] `OnvifProbeService` — WS-Discovery UDP +- [ ] `HttpProbeService` — détection par en-têtes HTTP +- [ ] Entités `CameraDiscoveryResult`, `DiscoveredStream` +- [ ] API `POST /api/discovery/probe` + `POST /api/discovery/scan` +- [ ] Nouveaux champs Camera (DiscoveryMethod, IpAddress, ports, MAC, capabilities) +- [ ] CameraCapability flags enum + +### Phase 2 — Base de Données Caméras (🟠 P2) +- [ ] Intégration de la base SQLite StrixCamDB (3600+ marques) +- [ ] Service de recherche `ICameraSearchService` +- [ ] API `GET /api/discovery/search` +- [ ] API `POST /api/discovery/streams` (construction URL) +- [ ] Substitution de placeholders (CHANNEL, USERNAME, IP, etc.) + +### Phase 3 — Test de Flux (🟠 P2) +- [ ] `StreamTesterService` — workers parallèles +- [ ] Handlers RTSP, HTTP MJPEG, HTTP snapshot +- [ ] Capture d'écran via FFmpeg +- [ ] API `POST /api/discovery/test` + polling +- [ ] API `GET /api/discovery/test/{id}/screenshot/{index}` + +### Phase 4 — Intégration Hangfire (🟡 P3) +- [ ] `NetworkScanJob` — scan planifié des sites +- [ ] `CameraHealthCheckJob` — heartbeat des flux +- [ ] `StreamTestJob` — re-test périodique +- [ ] Notification SignalR vers UI Blazor + +### Phase 5 — Fonctionnalités Avancées (🟡 P3) +- [ ] ONVIF profile resolution → RTSP URI extraction +- [ ] HomeKit pairing (`POST /api/discovery/homekit/pair`) +- [ ] DVRIP/Sofia protocol support +- [ ] ONVIF PTZ capabilities detection +- [ ] Export config Frigate/go2rtc + +--- + +## 16. Références + +- [Strix](https://github.com/eduard256/Strix) — Moteur de découverte Go (MIT) +- [ONVIF Feature Discovery Spec](https://www.onvif.org/wp-content/uploads/2016/12/ONVIF_Feature_Discovery_Specification_16.07.pdf) +- [ONVIF Core Spec](https://www.onvif.org/specs/core/ONVIF-Core-Specification-v221.pdf) — GetProfiles, GetStreamUri +- [go2rtc](https://github.com/AlexxIT/go2rtc) — Lib de streaming multi-protocole +- [StrixCamDB](https://github.com/eduard256/StrixCamDB) — Base SQLite 3600+ marques, 100K+ patterns +- [Strix HTTP API](https://github.com/eduard256/Strix/blob/main/DEVELOPERS.md) — Référence API REST +- [HAP Spec](https://developer.apple.com/homekit/) — HomeKit Accessory Protocol (mDNS) +- [RFC 6762](https://datatracker.ietf.org/doc/html/rfc6762) — Multicast DNS +- [OUI Database](https://standards-oui.ieee.org/) — IEEE Organizationally Unique Identifier diff --git a/src/Heimdall.Application/DTOs/CameraDto.cs b/src/Heimdall.Application/DTOs/CameraDto.cs index 839803e..3488a34 100644 --- a/src/Heimdall.Application/DTOs/CameraDto.cs +++ b/src/Heimdall.Application/DTOs/CameraDto.cs @@ -14,6 +14,7 @@ public record UpdateCameraRequest( string? RtspUrl, CameraStatus? Status); +/// Camera response including all discovery and stream test metadata. public record CameraResponse( Guid Id, Guid SiteId, @@ -22,7 +23,22 @@ public record CameraResponse( string? Manufacturer, string? Model, string? RtspUrl, + string? SubRtspUrl, CameraStatus Status, + CameraDiscoveryMethod DiscoveryMethod, + DetectedCameraType DetectedType, + CameraCapability Capabilities, + string? IpAddress, + string? MacAddress, + int? RtspPort, + int? HttpPort, + int? OnvifPort, + string? LastTestedCodecs, + int? LastTestedWidth, + int? LastTestedHeight, + long? LastTestedLatencyMs, + DateTime? LastDiscoveredAt, + DateTime? LastStreamTestAt, bool HasPtz, bool HasAudio, bool HasMotionDetection, diff --git a/src/Heimdall.Application/DTOs/DiscoveryDto.cs b/src/Heimdall.Application/DTOs/DiscoveryDto.cs new file mode 100644 index 0000000..abc8b91 --- /dev/null +++ b/src/Heimdall.Application/DTOs/DiscoveryDto.cs @@ -0,0 +1,140 @@ +using Heimdall.Domain.Enums; + +namespace Heimdall.Application.DTOs; + +// ──────────────────────────────────────────────────────────────────── +// Probe Requests +// ──────────────────────────────────────────────────────────────────── + +/// Probe a single IP address for camera services. +public record ProbeRequest(Guid SiteId, string Ip); + +/// Scan an entire subnet for cameras. +public record ScanRequest(Guid SiteId, string SubnetCidr, int TimeoutMs = 30000); + +// ──────────────────────────────────────────────────────────────────── +// Probe Responses +// ──────────────────────────────────────────────────────────────────── + +/// Full probe result for a single IP, combining all detection methods. +public record ProbeResponse( + string Ip, + bool IsReachable, + DetectedCameraType CameraType, + CameraDiscoveryMethod DiscoveryMethod, + ArpInfo? Arp, + int[] OpenPorts, + OnvifProbeInfo? Onvif, + HttpProbeInfo? Http, + HomeKitProbeInfo? HomeKit, + string[]? MatchedBrands); + +/// ARP table lookup result. +public record ArpInfo(string MacAddress, string? Vendor); + +/// ONVIF WS-Discovery probe result. +public record OnvifProbeInfo( + string DeviceServiceUrl, + int Port, + string? Name, + string? Hardware, + string? Location); + +/// HTTP probe result (server header analysis). +public record HttpProbeInfo(int Port, int StatusCode, string? ServerHeader); + +/// HomeKit / mDNS probe result. +public record HomeKitProbeInfo( + string Name, + string DeviceId, + string Model, + string Category, + bool IsPaired, + int Port); + +// ──────────────────────────────────────────────────────────────────── +// Scan Progress +// ──────────────────────────────────────────────────────────────────── + +/// Progress update emitted during a subnet scan. +public record ScanProgress( + int TotalHosts, + int Scanned, + int Discovered, + string? CurrentIp); + +// ──────────────────────────────────────────────────────────────────── +// Camera Database Search +// ──────────────────────────────────────────────────────────────────── + +/// Result from the camera database (preset, brand, or model). +public record CameraDbEntry( + string Type, // "preset" | "brand" | "model" + string Id, // "p:{id}" | "b:{id}" | "m:{brand}:{model}" + string Name); + +/// Search response. +public record SearchResponse(CameraDbEntry[] Results); + +/// Build stream URLs from database entries. +public record StreamBuildRequest( + string[] Ids, // e.g. ["b:hikvision", "p:onvif"] + string Ip, + string? Username, + string? Password, + int Channel = 0, + int[]? PortFilter = null); + +/// Stream build response. +public record StreamBuildResponse(string[] Streams); + +// ──────────────────────────────────────────────────────────────────── +// Stream Testing +// ──────────────────────────────────────────────────────────────────── + +/// Request to test a set of stream URLs. +public record StreamTestRequest(string SourceId, string[] Streams); + +/// A tested stream result. +public record StreamTestResult( + string SourceUrl, + string[] Codecs, + int Width, + int Height, + long LatencyMs, + string? ScreenshotUrl, + bool IsAlive); + +/// The session state for stream testing (polled). +public record StreamTestSession( + Guid SessionId, + string Status, // "running" | "done" + int Total, + int Tested, + int Alive, + StreamTestResult[] Results); + +// ──────────────────────────────────────────────────────────────────── +// Confirm Discovery +// ──────────────────────────────────────────────────────────────────── + +/// Confirm a discovery result and create a Camera entity. +public record ConfirmDiscoveryRequest( + Guid SiteId, + string Name, + Guid DiscoveryResultId, + string MainStreamUrl, + string? SubStreamUrl, + string? Username, + string? Password, + CameraDetectionProfileRequest? DetectionProfile); + +/// Inline detection profile during camera creation. +public record CameraDetectionProfileRequest( + bool DetectPerson = true, + bool DetectVehicle = true, + bool DetectAnimal = false, + bool DetectPackage = false, + bool DetectMotion = true, + bool FaceRecognition = true, + bool LicensePlateRecognition = true); diff --git a/src/Heimdall.Application/Services/ICameraDiscoveryService.cs b/src/Heimdall.Application/Services/ICameraDiscoveryService.cs new file mode 100644 index 0000000..849165b --- /dev/null +++ b/src/Heimdall.Application/Services/ICameraDiscoveryService.cs @@ -0,0 +1,75 @@ +using Heimdall.Application.Common; +using Heimdall.Application.DTOs; + +namespace Heimdall.Application.Services; + +/// +/// Camera discovery service — probes network devices, searches the camera +/// database, builds and tests stream URLs, and creates Camera entities. +/// Inspired by Strix (github.com/eduard256/Strix). +/// +public interface ICameraDiscoveryService +{ + /// + /// Probe a single IP address using all available methods in parallel + /// (ONVIF WS-Discovery, HTTP, mDNS, ARP, port scan). Returns within ~100ms. + /// + Task> ProbeIpAsync( + ProbeRequest request, CancellationToken ct); + + /// + /// Scan an entire subnet for camera devices. Runs port scans in parallel + /// with 20+ workers. Reports progress via IProgress{ScanProgress}. + /// + Task>> ScanSubnetAsync( + ScanRequest request, CancellationToken ct, + IProgress? progress = null); + + /// + /// Search the built-in camera database (StrixCamDB) by brand, model, or preset. + /// Supports multi-word queries (each word matches independently). + /// + Task> SearchDatabaseAsync( + string query, CancellationToken ct); + + /// + /// Build full stream URLs from camera database entries, substituting + /// placeholders ([CHANNEL], [USERNAME], [IP], etc.) with actual values. + /// + Task> BuildStreamUrlsAsync( + StreamBuildRequest request, CancellationToken ct); + + /// + /// Test stream URLs in parallel (20 workers) — connects to each, + /// extracts codecs, resolution, latency, and captures a screenshot. + /// Returns a session ID for polling. + /// + Task> TestStreamsAsync( + StreamTestRequest request, CancellationToken ct); + + /// + /// Poll a stream test session for updated results. + /// + Task> GetTestSessionAsync( + Guid sessionId, CancellationToken ct); + + /// + /// Get a screenshot from a stream test session. + /// + Task GetScreenshotAsync( + Guid sessionId, int index, CancellationToken ct); + + /// + /// Cancel a running stream test session. + /// + Task CancelTestSessionAsync( + Guid sessionId, CancellationToken ct); + + /// + /// Confirm a discovery result — creates a Camera entity with all + /// discovered metadata, credentials (encrypted), and an optional + /// detection profile. + /// + Task> ConfirmDiscoveryAsync( + ConfirmDiscoveryRequest request, CancellationToken ct); +} diff --git a/src/Heimdall.Domain/Entities/Camera.cs b/src/Heimdall.Domain/Entities/Camera.cs index a68bab4..303b892 100644 --- a/src/Heimdall.Domain/Entities/Camera.cs +++ b/src/Heimdall.Domain/Entities/Camera.cs @@ -5,6 +5,7 @@ namespace Heimdall.Domain.Entities; public class Camera : Entity, IAuditableEntity, ISoftDeletable { + // ── Core ──────────────────────────────────────────────────────── public Guid SiteId { get; private set; } public Guid? AgentId { get; private set; } public string Name { get; private set; } = string.Empty; @@ -13,12 +14,51 @@ public class Camera : Entity, IAuditableEntity, ISoftDeletable public string? RtspUrl { get; private set; } public CameraStatus Status { get; private set; } = CameraStatus.Disabled; - // Capabilities + // ── Discovery ─────────────────────────────────────────────────── + /// How this camera was discovered (manual, ONVIF, mDNS, etc.). + public CameraDiscoveryMethod DiscoveryMethod { get; private set; } = CameraDiscoveryMethod.Manual; + + /// High-level classification from the probe phase. + public DetectedCameraType DetectedType { get; private set; } = DetectedCameraType.Standard; + + // Network + public string? IpAddress { get; private set; } + public string? MacAddress { get; private set; } + + // Ports detected during probe + public int? RtspPort { get; private set; } + public int? HttpPort { get; private set; } + public int? OnvifPort { get; private set; } + + // Capabilities flags (bitmask) + public CameraCapability Capabilities { get; private set; } = CameraCapability.None; + + /// Timestamp of the last successful discovery probe. + public DateTime? LastDiscoveredAt { get; private set; } + + // ── Stream test results ───────────────────────────────────────── + /// Secondary / sub-stream URL (lower resolution for AI detection). + public string? SubRtspUrl { get; private set; } + + /// Last stream test results (JSON array of codecs). + public string? LastTestedCodecs { get; private set; } + + /// Resolution of the last successful stream test. + public int? LastTestedWidth { get; private set; } + public int? LastTestedHeight { get; private set; } + + /// Connection latency in ms (last test). + public long? LastTestedLatencyMs { get; private set; } + + /// Timestamp of the last stream test. + public DateTime? LastStreamTestAt { get; private set; } + + // ── Legacy capabilities (kept for backward compat) ────────────── public bool HasPtz { get; private set; } public bool HasAudio { get; private set; } public bool HasMotionDetection { get; private set; } - // Audit + // ── Audit ─────────────────────────────────────────────────────── public DateTime CreatedAt { get; set; } public DateTime UpdatedAt { get; set; } @@ -26,7 +66,7 @@ public class Camera : Entity, IAuditableEntity, ISoftDeletable public bool IsDeleted { get; private set; } public DateTime? DeletedAt { get; private set; } - // Navigation + // ── Navigation ────────────────────────────────────────────────── public Site Site { get; private set; } = null!; public Agent? Agent { get; private set; } public CameraCredentials? Credentials { get; private set; } @@ -34,7 +74,12 @@ public class Camera : Entity, IAuditableEntity, ISoftDeletable private Camera() { } // EF Core - public Camera(Guid siteId, string name, string? rtspUrl = null, string? manufacturer = null, string? model = null) + public Camera( + Guid siteId, + string name, + string? rtspUrl = null, + string? manufacturer = null, + string? model = null) : base(Guid.NewGuid()) { SiteId = siteId; @@ -44,6 +89,8 @@ public class Camera : Entity, IAuditableEntity, ISoftDeletable Model = model; } + // ── Behaviour ─────────────────────────────────────────────────── + public void AssignAgent(Guid agentId) => AgentId = agentId; public void Update(string name, string? manufacturer, string? model, string? rtspUrl) @@ -67,6 +114,58 @@ public class Camera : Entity, IAuditableEntity, ISoftDeletable public void SetDetectionProfile(CameraDetectionProfile profile) => DetectionProfile = profile; + /// + /// Populates discovery-related fields after a successful probe. + /// + public void SetDiscoveryInfo( + CameraDiscoveryMethod method, + DetectedCameraType type, + string? macAddress, + string ipAddress) + { + DiscoveryMethod = method; + DetectedType = type; + MacAddress = macAddress; + IpAddress = ipAddress; + LastDiscoveredAt = DateTime.UtcNow; + } + + /// + /// Updates known ports from probe results. + /// + public void SetPorts(int? rtspPort, int? httpPort, int? onvifPort) + { + RtspPort = rtspPort; + HttpPort = httpPort; + OnvifPort = onvifPort; + } + + /// + /// Updates capability bitmask from all probe data. + /// + public void SetCapabilityFlags(CameraCapability capabilities) + { + Capabilities = capabilities; + } + + /// + /// Records the result of a stream validation test. + /// + public void SetStreamTestResult( + string? subRtspUrl, + string codecsJson, + int width, + int height, + long latencyMs) + { + SubRtspUrl = subRtspUrl; + LastTestedCodecs = codecsJson; + LastTestedWidth = width; + LastTestedHeight = height; + LastTestedLatencyMs = latencyMs; + LastStreamTestAt = DateTime.UtcNow; + } + public void SoftDelete() { IsDeleted = true; diff --git a/src/Heimdall.Domain/Entities/CameraDiscoveryResult.cs b/src/Heimdall.Domain/Entities/CameraDiscoveryResult.cs new file mode 100644 index 0000000..ea6fb24 --- /dev/null +++ b/src/Heimdall.Domain/Entities/CameraDiscoveryResult.cs @@ -0,0 +1,120 @@ +using Heimdall.Domain.Enums; +using Heimdall.Domain.Primitives; + +namespace Heimdall.Domain.Entities; + +/// +/// Transient entity representing the outcome of probing a single IP address +/// during the camera discovery pipeline. Retained temporarily for the +/// discovery workflow (probe → search → test → confirm). +/// +public class CameraDiscoveryResult : Entity +{ + // ── Identification ────────────────────────────────────────────── + public Guid SiteId { get; private set; } + public Site Site { get; private set; } = null!; + + /// Probed IP address. + public string IpAddress { get; private set; } = string.Empty; + + /// MAC address from ARP table lookup. + public string? MacAddress { get; private set; } + + /// Vendor/manufacturer name resolved from OUI. + public string? Vendor { get; private set; } + + /// Reverse DNS hostname (if resolvable). + public string? Hostname { get; private set; } + + // ── Classification ────────────────────────────────────────────── + /// Device is reachable on the network. + public bool IsReachable { get; private set; } + + /// Detected camera type (standard / homekit / nvr / doorbell). + public DetectedCameraType DetectedType { get; private set; } = DetectedCameraType.Unknown; + + /// Primary discovery method that identified this device. + public CameraDiscoveryMethod DiscoveryMethod { get; private set; } + + // ── Probe results ─────────────────────────────────────────────── + /// Open ports discovered during port scan. + public int[] OpenPorts { get; private set; } = []; + + // ONVIF + public string? OnvifDeviceServiceUrl { get; private set; } + public string? OnvifName { get; private set; } + public string? OnvifHardware { get; private set; } + public int? OnvifPort { get; private set; } + + // HTTP + public string? HttpServerHeader { get; private set; } + public int? HttpStatusCode { get; private set; } + public int? HttpPort { get; private set; } + + // HomeKit + public bool? IsHomeKitCamera { get; private set; } + public string? HomeKitName { get; private set; } + public string? HomeKitDeviceId { get; private set; } + public string? HomeKitModel { get; private set; } + + // ── Status ────────────────────────────────────────────────────── + /// When this probe was performed. + public DateTime ProbedAt { get; private set; } = DateTime.UtcNow; + + /// True when this result has been processed (confirmed or rejected). + public bool IsProcessed { get; private set; } + + // ── Navigation ────────────────────────────────────────────────── + public ICollection DiscoveredStreams { get; private set; } = []; + + private CameraDiscoveryResult() { } // EF Core + + public CameraDiscoveryResult(Guid siteId, string ipAddress) + : base(Guid.NewGuid()) + { + SiteId = siteId; + IpAddress = ipAddress; + } + + // ── Behaviour ─────────────────────────────────────────────────── + + public void MarkReachable(DetectedCameraType type, CameraDiscoveryMethod method) + { + IsReachable = true; + DetectedType = type; + DiscoveryMethod = method; + } + + public void SetOpenPorts(int[] ports) => OpenPorts = ports; + + public void SetOnvifResult(string deviceServiceUrl, string? name, string? hardware, int port) + { + OnvifDeviceServiceUrl = deviceServiceUrl; + OnvifName = name; + OnvifHardware = hardware; + OnvifPort = port; + } + + public void SetHttpResult(int port, int statusCode, string? serverHeader) + { + HttpPort = port; + HttpStatusCode = statusCode; + HttpServerHeader = serverHeader; + } + + public void SetHomeKitResult(string name, string deviceId, string model) + { + IsHomeKitCamera = true; + HomeKitName = name; + HomeKitDeviceId = deviceId; + HomeKitModel = model; + } + + public void SetArpInfo(string mac, string? vendor) + { + MacAddress = mac; + Vendor = vendor; + } + + public void MarkProcessed() => IsProcessed = true; +} diff --git a/src/Heimdall.Domain/Entities/DiscoveredStreamUrl.cs b/src/Heimdall.Domain/Entities/DiscoveredStreamUrl.cs new file mode 100644 index 0000000..eecbdd1 --- /dev/null +++ b/src/Heimdall.Domain/Entities/DiscoveredStreamUrl.cs @@ -0,0 +1,63 @@ +using Heimdall.Domain.Enums; + +namespace Heimdall.Domain.Entities; + +/// +/// A single stream URL that was tested during the discovery pipeline. +/// Contains the test result (codecs, resolution, latency, screenshot). +/// +public class DiscoveredStreamUrl +{ + public Guid Id { get; private set; } + public Guid DiscoveryResultId { get; private set; } + + /// The full stream URL (credentials may be included). + public string Url { get; private set; } = string.Empty; + + /// Protocol scheme (rtsp, http, rtmp, dvrip, etc.). + public StreamProtocol Protocol { get; private set; } + + /// Detected codec names (e.g. ["H264", "PCMA"]). + public string[] Codecs { get; private set; } = []; + + /// Stream resolution. + public int Width { get; private set; } + public int Height { get; private set; } + + /// Connection latency in milliseconds. + public long LatencyMs { get; private set; } + + /// True if the stream is the main (highest-resolution) stream. + public bool IsMainStream { get; private set; } + + /// True if the stream responded successfully. + public bool IsAlive { get; private set; } + + // Navigation + public CameraDiscoveryResult DiscoveryResult { get; private set; } = null!; + + private DiscoveredStreamUrl() { } // EF Core + + public DiscoveredStreamUrl( + Guid discoveryResultId, + string url, + StreamProtocol protocol, + string[] codecs, + int width, + int height, + long latencyMs, + bool isMainStream, + bool isAlive) + { + Id = Guid.NewGuid(); + DiscoveryResultId = discoveryResultId; + Url = url; + Protocol = protocol; + Codecs = codecs; + Width = width; + Height = height; + LatencyMs = latencyMs; + IsMainStream = isMainStream; + IsAlive = isAlive; + } +} diff --git a/src/Heimdall.Domain/Enums/CameraCapability.cs b/src/Heimdall.Domain/Enums/CameraCapability.cs new file mode 100644 index 0000000..03dad33 --- /dev/null +++ b/src/Heimdall.Domain/Enums/CameraCapability.cs @@ -0,0 +1,44 @@ +namespace Heimdall.Domain.Enums; + +/// +/// Flags enum describing camera capabilities detected during discovery. +/// Stored as a bitmask in the database. +/// +[Flags] +public enum CameraCapability +{ + None = 0, + + /// RTSP streaming (H264/H265). + RtspStreaming = 1 << 0, + + /// MJPEG stream over HTTP. + HttpMjpeg = 1 << 1, + + /// Single JPEG snapshot over HTTP. + HttpSnapshot = 1 << 2, + + /// ONVIF protocol support (WS-Discovery responded). + Onvif = 1 << 3, + + /// PTZ control available via ONVIF. + OnvifPtz = 1 << 4, + + /// Audio input (microphone) available. + OnvifAudioIn = 1 << 5, + + /// Audio output (speaker) available. + OnvifAudioOut = 1 << 6, + + /// Apple HomeKit (HAP) support. + HomeKit = 1 << 7, + + /// Dahua DVRIP / Sofia protocol. + Dvrip = 1 << 8, + + /// RTMP streaming. + Rtmp = 1 << 9, + + /// Camera provides a sub-stream (secondary, lower-res stream). + SubStream = 1 << 10 +} diff --git a/src/Heimdall.Domain/Enums/CameraDiscoveryMethod.cs b/src/Heimdall.Domain/Enums/CameraDiscoveryMethod.cs new file mode 100644 index 0000000..57a2dda --- /dev/null +++ b/src/Heimdall.Domain/Enums/CameraDiscoveryMethod.cs @@ -0,0 +1,28 @@ +namespace Heimdall.Domain.Enums; + +/// +/// Method by which a camera was discovered on the network. +/// +public enum CameraDiscoveryMethod +{ + /// Manually configured by the user (existing flow). + Manual = 0, + + /// Discovered via ONVIF WS-Discovery (UDP probe on port 3702). + OnvifWsDiscovery = 1, + + /// Discovered via mDNS / HomeKit Accessory Protocol (_hap._tcp). + MdnsHomeKit = 2, + + /// Generic network scan (port scan + ping). + NetworkScan = 3, + + /// Detected via HTTP server header analysis. + HttpProbe = 4, + + /// Discovered via ARP table lookup + OUI vendor resolution. + ArpProbe = 5, + + /// Imported from external file or bulk operation. + Imported = 6 +} diff --git a/src/Heimdall.Domain/Enums/DetectedCameraType.cs b/src/Heimdall.Domain/Enums/DetectedCameraType.cs new file mode 100644 index 0000000..2e5a301 --- /dev/null +++ b/src/Heimdall.Domain/Enums/DetectedCameraType.cs @@ -0,0 +1,23 @@ +namespace Heimdall.Domain.Enums; + +/// +/// High-level classification of a detected camera's type. +/// Determined during the probe phase based on protocol signatures. +/// +public enum DetectedCameraType +{ + /// Standard IP camera (RTSP + HTTP). + Standard = 0, + + /// Apple HomeKit camera / doorbell (HAP over mDNS). + HomeKit = 1, + + /// NVR / DVR with multiple channels (DVRIP / Sofia protocol). + Nvr = 2, + + /// Video doorbell (HomeKit or proprietary). + Doorbell = 3, + + /// Device is reachable but camera type could not be determined. + Unknown = 4 +} diff --git a/src/Heimdall.Domain/Enums/StreamProtocol.cs b/src/Heimdall.Domain/Enums/StreamProtocol.cs new file mode 100644 index 0000000..db71783 --- /dev/null +++ b/src/Heimdall.Domain/Enums/StreamProtocol.cs @@ -0,0 +1,18 @@ +namespace Heimdall.Domain.Enums; + +/// +/// Streaming protocols supported by the discovery and test pipeline. +/// Maps directly to the protocol handlers in StreamTesterService. +/// +public enum StreamProtocol +{ + Rtsp, + Rtsps, + Http, + Https, + Rtmp, + Rtmps, + Dvrip, + Bubble, + HomeKit +} diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs index 2662db0..ae78016 100644 --- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs +++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs @@ -23,6 +23,10 @@ public class AppDbContext : IdentityDbContext public DbSet AppSettings => Set(); public DbSet AgentSettings => Set(); + // Discovery entities + public DbSet CameraDiscoveryResults => Set(); + public DbSet DiscoveredStreams => Set(); + protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); diff --git a/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs index 822dbe7..f5b8a57 100644 --- a/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs +++ b/src/Heimdall.Infrastructure/Data/Configurations/CameraConfiguration.cs @@ -1,4 +1,5 @@ using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; @@ -12,6 +13,7 @@ public class CameraConfiguration : IEntityTypeConfiguration builder.HasKey(c => c.Id); + // ── Core ──────────────────────────────────────────────────── builder.Property(c => c.Name) .HasMaxLength(200) .IsRequired() @@ -33,17 +35,67 @@ public class CameraConfiguration : IEntityTypeConfiguration .IsRequired() .IsUnicode(false); + // ── Discovery ─────────────────────────────────────────────── + builder.Property(c => c.DiscoveryMethod) + .HasConversion() + .HasMaxLength(20) + .IsUnicode(false); + + builder.Property(c => c.DetectedType) + .HasConversion() + .HasMaxLength(20) + .IsUnicode(false); + + builder.Property(c => c.IpAddress) + .HasMaxLength(45); // IPv6 max length + + builder.Property(c => c.MacAddress) + .HasMaxLength(17); // "XX:XX:XX:XX:XX:XX" + + builder.Property(c => c.RtspPort); + builder.Property(c => c.HttpPort); + builder.Property(c => c.OnvifPort); + + builder.Property(c => c.Capabilities) + .HasConversion() + .HasMaxLength(64) + .IsUnicode(false); + + builder.Property(c => c.LastDiscoveredAt); + + // ── Stream test ───────────────────────────────────────────── + builder.Property(c => c.SubRtspUrl) + .HasMaxLength(1000) + .IsUnicode(false); + + builder.Property(c => c.LastTestedCodecs) + .HasMaxLength(200) + .IsUnicode(false); + + builder.Property(c => c.LastTestedWidth); + builder.Property(c => c.LastTestedHeight); + builder.Property(c => c.LastTestedLatencyMs); + builder.Property(c => c.LastStreamTestAt); + + // ── Legacy capabilities ───────────────────────────────────── + builder.Property(c => c.HasPtz); + builder.Property(c => c.HasAudio); + builder.Property(c => c.HasMotionDetection); + + // ── Audit ─────────────────────────────────────────────────── builder.Property(c => c.CreatedAt) .HasDefaultValueSql("NOW()"); builder.Property(c => c.UpdatedAt) .HasDefaultValueSql("NOW()"); - // Indexes + // ── Indexes ───────────────────────────────────────────────── builder.HasIndex(c => c.SiteId); builder.HasIndex(c => c.AgentId); + builder.HasIndex(c => c.IpAddress); + builder.HasIndex(c => c.MacAddress); - // Relationships + // ── Relationships ─────────────────────────────────────────── builder.HasOne(c => c.Site) .WithMany(s => s.Cameras) .HasForeignKey(c => c.SiteId) diff --git a/src/Heimdall.Infrastructure/Data/Configurations/CameraDiscoveryResultConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/CameraDiscoveryResultConfiguration.cs new file mode 100644 index 0000000..696a490 --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/CameraDiscoveryResultConfiguration.cs @@ -0,0 +1,106 @@ +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public class CameraDiscoveryResultConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("camera_discovery_results"); + + builder.HasKey(r => r.Id); + + // ── Identification ────────────────────────────────────────── + builder.Property(r => r.IpAddress) + .HasMaxLength(45) + .IsRequired() + .IsUnicode(false); + + builder.Property(r => r.MacAddress) + .HasMaxLength(17) + .IsUnicode(false); + + builder.Property(r => r.Vendor) + .HasMaxLength(100) + .IsUnicode(false); + + builder.Property(r => r.Hostname) + .HasMaxLength(255) + .IsUnicode(false); + + // ── Classification ────────────────────────────────────────── + builder.Property(r => r.DetectedType) + .HasConversion() + .HasMaxLength(20) + .IsUnicode(false); + + builder.Property(r => r.DiscoveryMethod) + .HasConversion() + .HasMaxLength(20) + .IsUnicode(false); + + // ── Ports ─────────────────────────────────────────────────── + builder.Property(r => r.OpenPorts) + .HasColumnType("integer[]") + .IsUnicode(false); + + // ONVIF + builder.Property(r => r.OnvifDeviceServiceUrl) + .HasMaxLength(500) + .IsUnicode(false); + + builder.Property(r => r.OnvifName) + .HasMaxLength(200) + .IsUnicode(false); + + builder.Property(r => r.OnvifHardware) + .HasMaxLength(200) + .IsUnicode(false); + + builder.Property(r => r.OnvifPort); + + // HTTP + builder.Property(r => r.HttpServerHeader) + .HasMaxLength(200) + .IsUnicode(false); + + builder.Property(r => r.HttpStatusCode); + builder.Property(r => r.HttpPort); + + // HomeKit + builder.Property(r => r.HomeKitName) + .HasMaxLength(200) + .IsUnicode(false); + + builder.Property(r => r.HomeKitDeviceId) + .HasMaxLength(50) + .IsUnicode(false); + + builder.Property(r => r.HomeKitModel) + .HasMaxLength(200) + .IsUnicode(false); + + // ── Status ────────────────────────────────────────────────── + builder.Property(r => r.ProbedAt) + .HasDefaultValueSql("NOW()"); + + // ── Indexes ───────────────────────────────────────────────── + builder.HasIndex(r => r.SiteId); + builder.HasIndex(r => r.IpAddress); + builder.HasIndex(r => r.IsProcessed); + + // ── Relationships ─────────────────────────────────────────── + builder.HasOne(r => r.Site) + .WithMany() + .HasForeignKey(r => r.SiteId) + .OnDelete(DeleteBehavior.Cascade); + + builder.HasMany(r => r.DiscoveredStreams) + .WithOne(ds => ds.DiscoveryResult) + .HasForeignKey(ds => ds.DiscoveryResultId) + .OnDelete(DeleteBehavior.Cascade); + } +} diff --git a/src/Heimdall.Infrastructure/Data/Configurations/DiscoveredStreamConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/DiscoveredStreamConfiguration.cs new file mode 100644 index 0000000..2998c81 --- /dev/null +++ b/src/Heimdall.Infrastructure/Data/Configurations/DiscoveredStreamConfiguration.cs @@ -0,0 +1,40 @@ +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Heimdall.Infrastructure.Data.Configurations; + +public class DiscoveredStreamConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("discovered_streams"); + + builder.HasKey(ds => ds.Id); + + builder.Property(ds => ds.Url) + .HasMaxLength(2000) + .IsRequired() + .IsUnicode(false); + + builder.Property(ds => ds.Protocol) + .HasConversion() + .HasMaxLength(20) + .IsRequired() + .IsUnicode(false); + + builder.Property(ds => ds.Codecs) + .HasColumnType("text[]") + .IsUnicode(false); + + builder.Property(ds => ds.Width); + builder.Property(ds => ds.Height); + builder.Property(ds => ds.LatencyMs); + + // Indexes + builder.HasIndex(ds => ds.DiscoveryResultId); + builder.HasIndex(ds => ds.IsAlive); + builder.HasIndex(ds => ds.IsMainStream); + } +} diff --git a/src/Heimdall.Infrastructure/Services/CameraService.cs b/src/Heimdall.Infrastructure/Services/CameraService.cs index 1314a29..ddd5139 100644 --- a/src/Heimdall.Infrastructure/Services/CameraService.cs +++ b/src/Heimdall.Infrastructure/Services/CameraService.cs @@ -107,5 +107,10 @@ public class CameraService : ICameraService private static CameraResponse MapResponse(Camera c) => new( c.Id, c.SiteId, c.AgentId, c.Name, c.Manufacturer, c.Model, - c.RtspUrl, c.Status, c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt); + c.RtspUrl, c.SubRtspUrl, + c.Status, c.DiscoveryMethod, c.DetectedType, c.Capabilities, + c.IpAddress, c.MacAddress, c.RtspPort, c.HttpPort, c.OnvifPort, + c.LastTestedCodecs, c.LastTestedWidth, c.LastTestedHeight, c.LastTestedLatencyMs, + c.LastDiscoveredAt, c.LastStreamTestAt, + c.HasPtz, c.HasAudio, c.HasMotionDetection, c.CreatedAt); }