- Add mobile-app.md: Android Avalonia UI app spec with 6 pages, WebRTC via WebView bridge, SignalR real-time, offline cache, push notifications - Add auth-roles.md: 2 user types (Admin + User), site-scoped permissions, policy-based authorization, UI visibility per role - Add notifications.md: Email SMTP (FluentEmail), Gotify push, Scriban Markdown templates i18n editable from UI, per-user config - Add hangfire-usage.md: Central PostgreSQL jobs (retention, cleanup, digests) + Agent InMemory jobs (heartbeat, camera health, GPU watchdog) - Add signalr-usage.md: 5 hubs (events, streaming, monitoring, notifications, admin) with full hub code, group management, Agent SignalR connection - Update implementation.md: 23 phases with mobile app (phase 21) - Update specs.md: reference all new documentation files
36 KiB
36 KiB
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
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
<ItemGroup>
<!-- Avalonia UI -->
<PackageReference Include="Avalonia" Version="11.2.0" />
<PackageReference Include="Avalonia.Android" Version="11.2.0" />
<PackageReference Include="Avalonia.Desktop" Version="11.2.0" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.0" />
<!-- MVVM -->
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.0" />
<!-- API -->
<PackageReference Include="Refit" Version="7.2.1" />
<PackageReference Include="Refit.HttpClientFactory" Version="7.2.1" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.0" />
<!-- Logging -->
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
</ItemGroup>
4. API Client — Refit
public interface IHeimdallApi
{
// ─── Auth ──────────────────────────────────────────
[Post("/api/auth/login")]
Task<LoginResponse> LoginAsync([Body] LoginRequest request);
[Post("/api/auth/refresh")]
Task<LoginResponse> RefreshTokenAsync([Body] RefreshRequest request);
// ─── Sites (uniquement ceux auxquels l'user a accès) ─
[Get("/api/mobile/sites")]
Task<List<SiteDto>> GetMySitesAsync(
[Authorize] string token);
[Get("/api/mobile/sites/{siteId}")]
Task<SiteDetailDto> GetSiteDetailAsync(
Guid siteId, [Authorize] string token);
// ─── Cameras ───────────────────────────────────────
[Get("/api/mobile/sites/{siteId}/cameras")]
Task<List<CameraDto>> GetCamerasAsync(
Guid siteId, [Authorize] string token);
[Get("/api/mobile/cameras/{cameraId}")]
Task<CameraDetailDto> GetCameraDetailAsync(
Guid cameraId, [Authorize] string token);
// ─── Live stream signaling (WebRTC) ───────────────
[Get("/api/mobile/cameras/{cameraId}/stream-info")]
Task<StreamInfoDto> GetStreamInfoAsync(
Guid cameraId, [Authorize] string token);
// Retourne : { cameraId, agentEndpoint, iceServers[] }
// ─── Events ────────────────────────────────────────
[Get("/api/mobile/sites/{siteId}/events")]
Task<PagedResult<EventDto>> GetEventsAsync(
Guid siteId,
[Query] int page = 1,
[Query] int pageSize = 20,
[Query] string? type = null,
[Authorize] string token);
[Get("/api/mobile/events/{eventId}")]
Task<EventDetailDto> GetEventDetailAsync(
Guid eventId, [Authorize] string token);
// ─── Persons ───────────────────────────────────────
[Get("/api/mobile/persons")]
Task<List<PersonDto>> GetPersonsAsync(
[Authorize] string token);
[Get("/api/mobile/persons/{personId}")]
Task<PersonDetailDto> 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).
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<IceServerDto> IceServers);
public record IceServerDto(
string Urls, // "stun:...", "turn:..."
string? Username,
string? Credential);
5. Authentification — JWT Token
public class AuthService : IAuthService
{
private readonly IPreferences _prefs; // stockage local sécurisé
private readonly IHeimdallApi _api;
public async Task<LoginResult> 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<bool> 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
┌──────────────────────────────────────┐
│ │
│ 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
┌──────────────────────────────────────┐
│ ☰ 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+DockPanelBorderpour les cartes KPI (style Material)ItemsRepeaterpour la liste des événementsListBoxpour la liste des sitesButtonnavigation
6.2 Sites List
┌──────────────────────────────────────┐
│ ☰ 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
┌──────────────────────────────────────┐
│ ◀ 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
┌──────────────────────────────────────┐
│ ◀ 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
┌──────────────────────────────────────┐
│ ◀ É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
┌──────────────────────────────────────┐
│ ◀ É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.
┌──────────────────────────────────────┐
│ Avalonia WebRTCView │
│ │
│ ┌────────────────────────────────┐ │
│ │ WebView (Android) │ │
│ │ │ │
│ │ <html> │ │
│ │ <video id="live"></video> │ │
│ │ <script src="webrtc.js"/> │ │
│ │ </html> │ │
│ │ │ │
│ │ JS ↔ C# via WebView bridge │ │
│ └────────────────────────────────┘ │
└──────────────────────────────────────┘
Ressource embarquée : Assets/webrtc/player.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body { margin:0; background:#000; }
video { width:100vw; height:100vh; object-fit:contain; }
</style>
</head>
<body>
<video id="live" autoplay playsinline></video>
<script>
let pc = null;
// Appelé depuis C# via WebView bridge
function startStream(sdpOffer, iceServers) {
pc = new RTCPeerConnection({ iceServers: JSON.parse(iceServers) });
pc.ontrack = (evt) => {
document.getElementById('live').srcObject = evt.streams[0];
};
pc.onicecandidate = (evt) => {
if (evt.candidate) {
// Envoyer ICE candidate à C#
window.avaloniaBridge?.onIceCandidate(JSON.stringify(evt.candidate));
}
};
pc.setRemoteDescription(new RTCSessionDescription(JSON.parse(sdpOffer)))
.then(() => pc.createAnswer())
.then((answer) => pc.setLocalDescription(answer))
.then(() => {
window.avaloniaBridge?.onSdpAnswer(JSON.stringify(pc.localDescription));
});
}
function addIceCandidate(candidate) {
pc?.addIceCandidate(JSON.parse(candidate));
}
function stopStream() {
pc?.close();
pc = null;
}
</script>
</body>
</html>
Contrôle Avalonia
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
public class SignalRService : ISignalRService, IDisposable
{
private HubConnection? _hub;
public event Action<EventDto>? EventCreated;
public event Action<CameraStatusDto>? CameraStatusChanged;
public event Action<string>? SdpOffer;
public event Action<string>? 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<EventDto>("EventCreated", eventDto =>
{
// Notification locale si l'app est en arrière-plan
ShowLocalNotification(eventDto);
EventCreated?.Invoke(eventDto);
});
// Changement statut caméra
_hub.On<CameraStatusDto>("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<string>("SdpOffer", offer => SdpOffer?.Invoke(offer));
streamingHub.On<string>("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)
┌──────────────────────────────────────┐
│ │
│ CONTENU PAGE │
│ │
│ │
│ │
├──────────────────────────────────────┤
│ 🏠 📷 📋 👤 ⚙️ │
│ Accueil Sites Events Pers. Réglages │
└──────────────────────────────────────┘
Implémenté avec TabControl en mode bottom :
<TabControl TabStripPlacement="Bottom">
<TabItem Header="🏠 Accueil">
<views:DashboardView />
</TabItem>
<TabItem Header="📷 Sites">
<views:SiteListView />
</TabItem>
<TabItem Header="📋 Événements">
<views:EventListView />
</TabItem>
<TabItem Header="👤 Personnes">
<views:PersonListView />
</TabItem>
<TabItem Header="⚙️">
<views:SettingsView />
</TabItem>
</TabControl>
Pull-to-Refresh
Toutes les listes implémentent le pull-to-refresh via RefreshContainer :
<RefreshContainer IsRefreshing="{Binding IsRefreshing}"
RefreshRequested="{Binding RefreshCommand}">
<ListBox ItemsSource="{Binding Sites}">
<ListBox.ItemTemplate>
<!-- carte site -->
</ListBox.ItemTemplate>
</ListBox>
</RefreshContainer>
10. Notifications Push (FCM + Gotify)
L'application mobile reçoit les notifications via :
- Gotify (self-hosted) — le même que le web
- Firebase Cloud Messaging (si Google Services disponibles)
Gotify sur mobile
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
┌──────────────────────────────────────┐
│ ⚙️ 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) |
public class OfflineCacheService
{
private readonly string _cacheDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"cache");
public async Task<T?> GetAsync<T>(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<T>(json);
}
public async Task SetAsync<T>(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
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-android</TargetFramework>
<SupportedOSPlatformVersion>21</SupportedOSPlatformVersion>
<ApplicationId>com.heimdall.mobile</ApplicationId>
<ApplicationVersion>1</ApplicationVersion>
<ApplicationDisplayVersion>1.0.0</ApplicationDisplayVersion>
</PropertyGroup>
<ItemGroup>
<AndroidAsset Include="Assets/**/*" />
</ItemGroup>
</Project>
CI/CD — Build APK
# .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