# Heimdall — Application Mobile Android (Avalonia UI) **Stack :** Avalonia UI (.NET 10) — Mobile Android uniquement (lecture seule) --- ## 1. Périmètre L'application mobile est **réservée aux utilisateurs** (pas Admin complet). Elle permet uniquement de **consulter** — aucune configuration. | Fonctionnalité | Mobile | Web | |---|---|---| | Voir ses sites | ✅ | ✅ | | Voir les caméras | ✅ | ✅ | | Voir le flux live | ✅ (WebRTC) | ✅ | | Voir les événements | ✅ | ✅ | | Voir les personnes | ✅ | ✅ | | Recevoir notifications push | ✅ (Gotify/FCM) | ✅ | | Configurer sites | ❌ | ✅ | | Gérer utilisateurs | ❌ | ✅ | | Gérer templates notifications | ❌ | ✅ | | Voir jobs Hangfire | ❌ | ✅ | --- ## 2. Stack technique | Technologie | Version | Usage | |---|---|---| | **Avalonia UI** | 11.x+ | Framework UI cross-platform Android | | **Avalonia.Android** | 11.x+ | Platform target Android | | **Avalonia.WebRTC** | — | WebRTC dans Avalonia (via native WebView ou lib) | | **System.Net.Http** | — | API Client | | **Microsoft.AspNetCore.SignalR.Client** | 10.x | SignalR pour temps réel | | **CommunityToolkit.Mvvm** | 8.x+ | MVVM pattern | | **ReactiveUI** | 19.x+ | Bindings réactifs (optionnel) | | **Refit** | 7.x+ | Typed HTTP API client | | **Serilog** | 3.x+ | Logging mobile | ### Pourquoi Avalonia et pas MAUI ? | Critère | Avalonia UI | .NET MAUI | |---|---|---| | Maturité Android | ✅ Stable | 🟠 Encore instable | | Performance | ✅ Bonne | 🟠 Variable | | WebRTC support | ✅ WebView + JS interop | 🟠 Limité | | Même codebase Desktop/Mobile | ✅ | ✅ (MAUI aussi) | | Contrôle total rendu | ✅ (Skia) | ❌ (natif) | --- ## 3. Architecture MVVM ```text Heimdall.Mobile/ ├── App.axaml # Entry point ├── App.axaml.cs # Application lifecycle ├── Avalonia.WebRTC/ # WebRTC interop │ ├── WebRTCView.axaml # Custom control │ └── WebRTCView.axaml.cs # Android WebView bridge ├── Views/ # UI Pages │ ├── LoginView.axaml │ ├── DashboardView.axaml │ ├── SiteListView.axaml │ ├── SiteDetailView.axaml │ ├── CameraLiveView.axaml │ ├── EventListView.axaml │ └── EventDetailView.axaml ├── ViewModels/ # MVVM ViewModels │ ├── LoginViewModel.cs │ ├── DashboardViewModel.cs │ ├── SiteListViewModel.cs │ ├── SiteDetailViewModel.cs │ ├── CameraLiveViewModel.cs │ ├── EventListViewModel.cs │ └── EventDetailViewModel.cs ├── Services/ # Services │ ├── IApiClient.cs # Interface Refit │ ├── ApiClient.cs # Implémentation Refit │ ├── IAuthService.cs # JWT token management │ ├── AuthService.cs │ ├── ISignalRService.cs # SignalR connection │ ├── SignalRService.cs │ ├── INavigationService.cs # Navigation │ └── NavigationService.cs ├── Models/ # DTOs │ ├── SiteDto.cs │ ├── CameraDto.cs │ ├── EventDto.cs │ ├── PersonDto.cs │ ├── LoginRequest.cs │ └── LoginResponse.cs └── Converters/ # Value converters ├── StatusToColorConverter.cs ├── EventTypeToIconConverter.cs └── DateTimeToRelativeConverter.cs ``` ### NuGet Dependencies ```xml ``` --- ## 4. API Client — Refit ```csharp public interface IHeimdallApi { // ─── Auth ────────────────────────────────────────── [Post("/api/auth/login")] Task LoginAsync([Body] LoginRequest request); [Post("/api/auth/refresh")] Task RefreshTokenAsync([Body] RefreshRequest request); // ─── Sites (uniquement ceux auxquels l'user a accès) ─ [Get("/api/mobile/sites")] Task> GetMySitesAsync( [Authorize] string token); [Get("/api/mobile/sites/{siteId}")] Task GetSiteDetailAsync( Guid siteId, [Authorize] string token); // ─── Cameras ─────────────────────────────────────── [Get("/api/mobile/sites/{siteId}/cameras")] Task> GetCamerasAsync( Guid siteId, [Authorize] string token); [Get("/api/mobile/cameras/{cameraId}")] Task GetCameraDetailAsync( Guid cameraId, [Authorize] string token); // ─── Live stream signaling (WebRTC) ─────────────── [Get("/api/mobile/cameras/{cameraId}/stream-info")] Task GetStreamInfoAsync( Guid cameraId, [Authorize] string token); // Retourne : { cameraId, agentEndpoint, iceServers[] } // ─── Events ──────────────────────────────────────── [Get("/api/mobile/sites/{siteId}/events")] Task> GetEventsAsync( Guid siteId, [Query] int page = 1, [Query] int pageSize = 20, [Query] string? type = null, [Authorize] string token); [Get("/api/mobile/events/{eventId}")] Task GetEventDetailAsync( Guid eventId, [Authorize] string token); // ─── Persons ─────────────────────────────────────── [Get("/api/mobile/persons")] Task> GetPersonsAsync( [Authorize] string token); [Get("/api/mobile/persons/{personId}")] Task GetPersonDetailAsync( Guid personId, [Authorize] string token); } ``` ### Endpoints API Mobile dédiés Les endpoints mobiles sont préfixés `/api/mobile/` et retournent des DTOs optimisés pour l'affichage mobile (payload réduit, images redimensionnées). ```csharp public record SiteDto( Guid Id, string Name, int CameraCount, int OnlineCameraCount, int UnreadEventCount, string? ThumbnailUrl); // petite vignette public record CameraDto( Guid Id, string Name, string Status, // "Online", "Offline", "Disabled" string? ThumbnailUrl, // dernier snapshot (taille réduite) bool HasLiveAccess); // l'user peut voir le live public record EventDto( Guid Id, string EventType, string CameraName, string SiteName, DateTime Timestamp, string? ThumbnailUrl, // snapshot redimensionné (320x240) bool IsRead); // déjà consulté sur mobile public record StreamInfoDto( Guid CameraId, string IceEndpoint, // Agent public endpoint ou SFU List IceServers); public record IceServerDto( string Urls, // "stun:...", "turn:..." string? Username, string? Credential); ``` --- ## 5. Authentification — JWT Token ```csharp public class AuthService : IAuthService { private readonly IPreferences _prefs; // stockage local sécurisé private readonly IHeimdallApi _api; public async Task LoginAsync(string email, string password) { var response = await _api.LoginAsync(new LoginRequest(email, password)); // Stocker le token dans les préférences sécurisées Android _prefs.Set("access_token", response.AccessToken); _prefs.Set("refresh_token", response.RefreshToken); _prefs.Set("token_expires_at", response.ExpiresAt.ToString("O")); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", response.AccessToken); return LoginResult.Success; } public async Task TryRefreshTokenAsync() { var refreshToken = _prefs.Get("refresh_token", string.Empty); if (string.IsNullOrEmpty(refreshToken)) return false; try { var response = await _api.RefreshTokenAsync( new RefreshRequest(refreshToken)); _prefs.Set("access_token", response.AccessToken); _prefs.Set("refresh_token", response.RefreshToken); _prefs.Set("token_expires_at", response.ExpiresAt.ToString("O")); return true; } catch { // Token refresh failed → déconnexion await LogoutAsync(); return false; } } public async Task LogoutAsync() { _prefs.Remove("access_token"); _prefs.Remove("refresh_token"); _prefs.Remove("token_expires_at"); _httpClient.DefaultRequestHeaders.Authorization = null; } } ``` ### Écran Login ```text ┌──────────────────────────────────────┐ │ │ │ HEIMDALL │ │ Surveillance Mobile │ │ │ │ ┌────────────────────────────────┐ │ │ │ ✉️ entreprise@email.com │ │ │ └────────────────────────────────┘ │ │ │ │ ┌────────────────────────────────┐ │ │ │ 🔒 Mot de passe │ │ │ └────────────────────────────────┘ │ │ │ │ ┌────────────────────────────────┐ │ │ │ Se connecter │ │ │ └────────────────────────────────┘ │ │ │ │ [▼] Serveur : https://... │ │ │ │ Version 1.0.0 │ └──────────────────────────────────────┘ ``` **Comportement :** - Champ "Serveur" : URL du Central (mémorisée après 1e connexion) - Token stocké dans `Android.KeyStore` (chiffré) - Auto-refresh silencieux en arrière-plan - Déconnexion automatique si refresh échoue --- ## 6. Pages détaillées ### 6.1 Dashboard — Accueil ```text ┌──────────────────────────────────────┐ │ ☰ Accueil 🔔 3 │ │ │ │ ┌──────┐ ┌──────┐ ┌──────┐ │ │ │ 📷 12 │ │ 📹 8 │ │ 🚗 5 │ │ │ │ Sites │ │ Cams │ │ Auj │ │ │ │ │ │ en │ │ │ │ │ │ │ │ ligne │ │ │ │ │ └──────┘ └──────┘ └──────┘ │ │ │ │ ─── Derniers événements ──── │ │ │ │ 🟢 14:23 Entrée │ │ Personne détectée │ │ │ │ 🟡 14:20 Parking │ │ AA-123-XX détectée │ │ │ │ 🔴 14:15 Entrée │ │ Visage inconnu │ │ │ │ ─── Mes sites ──────────────── │ │ │ │ ┌────────────────────────────────┐ │ │ │ Entrepôt A ▶ 5/8 │ │ │ │ Paris 🟢 │ │ │ └────────────────────────────────┘ │ │ ┌────────────────────────────────┐ │ │ │ Entrepôt B ▶ 0/3 │ │ │ │ Lyon 🔴 │ │ │ └────────────────────────────────┘ │ │ │ │ [Voir tous les sites →] │ └──────────────────────────────────────┘ ``` **Components Avalonia :** - `UserControl` + `DockPanel` - `Border` pour les cartes KPI (style Material) - `ItemsRepeater` pour la liste des événements - `ListBox` pour la liste des sites - `Button` navigation ### 6.2 Sites List ```text ┌──────────────────────────────────────┐ │ ☰ Mes Sites 🔍 │ │ │ │ ┌────────────────────────────────┐ │ │ │ Entrepôt A ▶ 5/8 │ │ │ │ Paris, 75012 🟢 │ │ │ │ Agent en ligne │ │ │ └────────────────────────────────┘ │ │ ┌────────────────────────────────┐ │ │ │ Entrepôt B ▶ 0/3 │ │ │ │ Lyon, 69003 🟠 │ │ │ │ Agent hors ligne │ │ │ └────────────────────────────────┘ │ │ │ │ pull-to-refresh ↓ │ └──────────────────────────────────────┘ ``` ### 6.3 Site Detail ```text ┌──────────────────────────────────────┐ │ ◀ Entrepôt A 🔔 │ │ │ │ ┌────────────────────────────────┐ │ │ │ Agent: agent-01 │ │ │ │ Statut: 🟢 En ligne │ │ │ │ Dernier heartbeat: il y a 12s │ │ │ └────────────────────────────────┘ │ │ │ │ ─── Caméras ──────────────────── │ │ │ │ ┌────────────────────────────────┐ │ │ │ 📷 Entrée 🟢 ▶ │ │ │ │ 1080p · H264 │ │ │ │ ┌──────┐ │ │ │ │ │ │ Dernier snapshot │ │ │ │ └──────┘ │ │ │ └────────────────────────────────┘ │ │ ┌────────────────────────────────┐ │ │ │ 📷 Parking 🟢 ▶ │ │ │ │ 1080p · H264 │ │ │ │ ┌──────┐ │ │ │ │ │ │ Dernier snapshot │ │ │ │ └──────┘ │ │ │ └────────────────────────────────┘ │ │ ┌────────────────────────────────┐ │ │ │ 📷 Jardin 🔴 │ │ │ │ Hors ligne │ │ │ │ ┌──────┐ │ │ │ │ │ ⚠️ │ Aucun signal │ │ │ │ └──────┘ │ │ │ └────────────────────────────────┘ │ │ │ │ ─── Événements récents ──────── │ │ 🟢 14:23 Personne détectée ▶ │ │ 🟡 14:20 Véhicule détecté ▶ │ │ 🔴 14:15 Visage inconnu ▶ │ │ │ │ [Voir tous les événements →] │ └──────────────────────────────────────┘ ``` ### 6.4 Camera Live View ```text ┌──────────────────────────────────────┐ │ ◀ Entrée — Live │ │ │ │ ┌────────────────────────────────┐ │ │ │ │ │ │ │ FLUX VIDÉO WEBRTC │ │ │ │ │ │ │ │ WebView + JS WebRTC client │ │ │ │ │ │ │ │ 🟢 Live ● 14:23:05 │ │ │ │ │ │ │ └────────────────────────────────┘ │ │ │ │ [📷 Snapshot] [⟳ Refresh] │ │ │ │ ─── Derniers événements ───── │ │ 🟢 14:23 Personne détectée │ │ 🟡 14:20 Véhicule détecté │ └──────────────────────────────────────┘ ``` ### 6.5 Events List ```text ┌──────────────────────────────────────┐ │ ◀ Événements [Filtres ▼] │ │ │ │ ┌────────────────────────────────┐ │ │ │ 🔴 14:23 Personne ▶ │ │ │ │ Entrée · Entrepôt A │ │ │ │ ┌──────┐ │ │ │ │ │ img │ Inconnue │ │ │ │ └──────┘ │ │ │ └────────────────────────────────┘ │ │ ┌────────────────────────────────┐ │ │ │ 🟡 14:20 Véhicule ▶ │ │ │ │ Parking · Entrepôt A │ │ │ │ ┌──────┐ │ │ │ │ │ img │ AA-123-XX │ │ │ │ └──────┘ │ │ │ └────────────────────────────────┘ │ │ ┌────────────────────────────────┐ │ │ │ 🟢 14:10 Mouvement ▶ │ │ │ │ Jardin · Entrepôt B │ │ │ └────────────────────────────────┘ │ │ │ │ pull-to-refresh ↓ │ │ │ │ ─── Page 1/5 ─── [>] │ └──────────────────────────────────────┘ ``` **Filtres disponibles :** - Type : Tous, Personne, Véhicule, Visage inconnu, Mouvement - Site : Tous, [site spécifique] (dropdown) - Date : Aujourd'hui, 7 jours, 30 jours ### 6.6 Event Detail ```text ┌──────────────────────────────────────┐ │ ◀ Événement │ │ │ │ ┌────────────────────────────────┐ │ │ │ │ │ │ │ SNAPSHOT IMAGE │ │ │ │ (pleine largeur) │ │ │ │ │ │ │ └────────────────────────────────┘ │ │ │ │ 🔴 Personne détectée │ │ │ │ Site Entrepôt A │ │ Caméra Entrée │ │ Date 14/07/2026 14:23:05 │ │ │ │ Détection │ │ ┌────────────────────────────────┐ │ │ │ Confiance: 87% │ │ │ │ Type: Personne │ │ │ │ Visage: ❌ Inconnu │ │ │ └────────────────────────────────┘ │ │ │ │ ─── Événements similaires ───── │ │ 🟢 13/07 Personne détectée ▶ │ │ 🟢 12/07 Personne détectée ▶ │ └──────────────────────────────────────┘ ``` --- ## 7. WebRTC Live — Implémentation Avalonia Le WebRTC dans Avalonia Android utilise une **WebView** qui charge une page HTML minimale contenant le client WebRTC JavaScript. ```text ┌──────────────────────────────────────┐ │ Avalonia WebRTCView │ │ │ │ ┌────────────────────────────────┐ │ │ │ WebView (Android) │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ``` ### Contrôle Avalonia ```csharp public class WebRTCView : NativeControlHost { private Android.Webkit.WebView? _webView; private readonly SignalRService _signalR; public async Task StartStreamAsync(StreamInfoDto streamInfo) { // 1. Initialiser SignalR pour le signaling await _signalR.ConnectAsync(); // 2. S'abonner aux événements signaling _signalR.OnSdpOffer += async (offer) => { // Envoyer l'offre à la WebView (JS) await _webView!.EvaluateJavascriptAsync( $"startStream('{offer}', '{Json.Serialize(streamInfo.IceServers)}')"); }; _signalR.OnIceCandidate += async (candidate) => { await _webView!.EvaluateJavascriptAsync( $"addIceCandidate('{candidate}')"); }; // 3. Demander le flux await _signalR.RequestStreamAsync(streamInfo.CameraId); } public async Task StopStreamAsync() { await _webView!.EvaluateJavascriptAsync("stopStream()"); await _signalR.DisconnectAsync(); } // Bridge JS → C# (appelé depuis la WebView) public void OnSdpAnswer(string sdp) { _signalR.SendAnswerAsync(sdp); } public void OnIceCandidate(string candidate) { _signalR.SendIceCandidateAsync(candidate); } } ``` --- ## 8. SignalR Mobile — Temps réel ```csharp public class SignalRService : ISignalRService, IDisposable { private HubConnection? _hub; public event Action? EventCreated; public event Action? CameraStatusChanged; public event Action? SdpOffer; public event Action? IceCandidate; public async Task ConnectAsync() { _hub = new HubConnectionBuilder() .WithUrl($"{_baseUrl}/hubs/events", options => { options.AccessTokenProvider = () => Task.FromResult(_tokenProvider.AccessToken); }) .WithAutomaticReconnect([0, 2000, 5000, 10000, 30000]) .Build(); // Événements de détection _hub.On("EventCreated", eventDto => { // Notification locale si l'app est en arrière-plan ShowLocalNotification(eventDto); EventCreated?.Invoke(eventDto); }); // Changement statut caméra _hub.On("CameraStatusChanged", status => { CameraStatusChanged?.Invoke(status); }); await _hub.StartAsync(); } // Signaling WebRTC — connecté au hub /hubs/streaming public async Task ConnectStreamingAsync(Guid cameraId) { var streamingHub = new HubConnectionBuilder() .WithUrl($"{_baseUrl}/hubs/streaming", options => { options.AccessTokenProvider = () => Task.FromResult(_tokenProvider.AccessToken); }) .Build(); streamingHub.On("SdpOffer", offer => SdpOffer?.Invoke(offer)); streamingHub.On("IceCandidate", candidate => IceCandidate?.Invoke(candidate)); await streamingHub.StartAsync(); await streamingHub.InvokeAsync("RequestStream", cameraId); } // Notifications locales Android private void ShowLocalNotification(EventDto eventDto) { var channelId = "heimdall-events"; var notification = new NotificationCompat.Builder(this, channelId) .SetSmallIcon(Resource.Drawable.ic_notification) .SetContentTitle(GetEventTitle(eventDto.EventType)) .SetContentText($"{eventDto.CameraName} · {eventDto.SiteName}") .SetAutoCancel(true) .SetPriority(NotificationCompat.PRIORITY_HIGH) .Build(); var manager = GetSystemService(NotificationService) as NotificationManager; manager?.Notify(eventDto.Id.GetHashCode(), notification); } } ``` --- ## 9. Navigation & Layout ### Bottom Navigation (Android) ```text ┌──────────────────────────────────────┐ │ │ │ CONTENU PAGE │ │ │ │ │ │ │ ├──────────────────────────────────────┤ │ 🏠 📷 📋 👤 ⚙️ │ │ Accueil Sites Events Pers. Réglages │ └──────────────────────────────────────┘ ``` Implémenté avec `TabControl` en mode bottom : ```xml ``` ### Pull-to-Refresh Toutes les listes implémentent le pull-to-refresh via `RefreshContainer` : ```xml ``` --- ## 10. Notifications Push (FCM + Gotify) L'application mobile reçoit les notifications via : 1. **Gotify** (self-hosted) — le même que le web 2. **Firebase Cloud Messaging** (si Google Services disponibles) ### Gotify sur mobile ```csharp public class GotifyPushService { private readonly GotifyClient _client; public async Task RegisterForPushAsync() { // L'utilisateur entre son token Gotify dans les réglages var token = await _prefs.GetAsync("gotify_token", ""); _client = new GotifyClient(_gotifyServerUrl, token); // Polling ou WebSocket Gotify pour les messages _client.OnMessage += (msg) => { ShowLocalNotification(msg); }; await _client.ConnectAsync(); } } ``` ### Écran Réglages ```text ┌──────────────────────────────────────┐ │ ⚙️ Réglages │ │ │ │ Compte │ │ Connecté en tant que Jean Dupont │ │ [Se déconnecter] │ │ │ │ Serveur │ │ URL: https://heimdall.exemple.com │ │ │ │ Notifications push │ │ Gotify Server: [http://... ] │ │ Gotify Token: [**************] │ │ [Tester la connexion] │ │ │ │ Notifications locales │ │ [✅] Personnes détectées │ │ [✅] Visages inconnus │ │ [ ] Véhicules │ │ [✅] Caméra hors ligne │ │ │ │ Lecture automatique du live │ │ [✅] Wi-Fi uniquement │ │ [ ] Données mobiles aussi │ │ │ │ Qualité vidéo mobile │ │ [Automatique ▼] │ │ │ │ Thème │ │ [System ▼] │ │ │ │ Version : 1.0.0 │ └──────────────────────────────────────┘ ``` --- ## 11. Hors-ligne (Offline First) | Donnée | Stratégie | |---|---| | Sites list | Cache local (JSON) — mis à jour au démarrage | | Caméras par site | Cache local — rafraîchi au pull-to-refresh | | Événements | Cache local (50 derniers) + SignalR temps réel | | Snapshots | Cache disque LRU (50 Mo max) | | Flux live | Pas de cache (temps réel uniquement) | ```csharp public class OfflineCacheService { private readonly string _cacheDir = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "cache"); public async Task GetAsync(string key) where T : class { var path = Path.Combine(_cacheDir, $"{key}.json"); if (!File.Exists(path)) return null; var json = await File.ReadAllTextAsync(path); return JsonSerializer.Deserialize(json); } public async Task SetAsync(string key, T value) where T : class { var path = Path.Combine(_cacheDir, $"{key}.json"); Directory.CreateDirectory(Path.GetDirectoryName(path)!); var json = JsonSerializer.Serialize(value); await File.WriteAllTextAsync(path, json); } public void PurgeLRU(int maxSizeMb = 50) { // Supprime les fichiers les plus vieux si le cache dépasse 50 Mo } } ``` --- ## 12. Build & Déploiement ### Android SDK Requirements | Requirement | Version | |---|---| | Android SDK | 34+ (Android 14) | | Min SDK | 28 (Android 9) | | Target SDK | 34 (Android 14) | | .NET | 10.0+ | ### Fichier `.csproj` Android ```xml Exe net10.0-android 21 com.heimdall.mobile 1 1.0.0 ``` ### CI/CD — Build APK ```yaml # .github/workflows/mobile.yml jobs: build-android: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-dotnet@v4 with: dotnet-version: '10.0.x' - name: Install Android workload run: dotnet workload install android - name: Build APK run: | dotnet publish src/Heimdall.Mobile/Heimdall.Mobile.csproj \ -f net10.0-android \ -c Release \ -p:AndroidSigningKeyStore=${{ secrets.KEYSTORE }} \ -p:AndroidSigningKeyAlias=${{ secrets.KEY_ALIAS }} - name: Upload APK uses: actions/upload-artifact@v4 with: name: heimdall-mobile.apk path: bin/Release/net10.0-android/*-Signed.apk ``` --- ## 13. Tests ``` User can login with valid JWT credentials Login with invalid credentials shows error Token refresh works silently in background Dashboard shows user's sites only Site list shows only assigned sites Camera list shows correct online/offline status Live WebRTC stream starts on camera tap Live stream stops on back navigation Event list is paginated (20 per page) Event detail shows full snapshot Pull-to-refresh updates data Offline cache shows stale data when offline Notifications arrive via SignalR in real-time Gotify push notification triggers local notification User can logout from settings Logout clears all cached data Bottom navigation switches pages correctly ```