# Heimdall — Application Mobile Android (Kotlin + Jetpack Compose) **Stack :** Kotlin, Jetpack Compose, Clean Architecture, MVVM, Ktor, Hilt --- ## 1. Périmètre Application Android **lecture seule** réservée aux utilisateurs (pas Admin). Configuration exclusivement depuis le web. | Fonctionnalité | Mobile | Web | |---|---|---| | Voir ses sites | ✅ | ✅ | | Voir les caméras | ✅ | ✅ | | Voir le flux live | ✅ (WebRTC natif) | ✅ | | Voir les événements | ✅ | ✅ | | Voir les personnes | ✅ | ✅ | | Recevoir notifications push | ✅ (FCM) | ✅ (in-app) | | Configurer sites | ❌ | ✅ | | Gérer utilisateurs | ❌ | ✅ | | Gérer templates notifications | ❌ | ✅ | --- ## 2. Stack technique | Technologie | Version | Usage | |---|---|---| | **Kotlin** | 2.1+ | Langage | | **Jetpack Compose** | 1.7+ | UI déclarative | | **Material 3** | 1.3+ | Design system | | **Clean Architecture** | — | data / domain / presentation | | **Ktor** | 3.0+ | HTTP client | | **Ktor Serialization (kotlinx)** | 3.0+ | JSON sérialisation | | **Hilt** | 2.53+ | Injection de dépendances | | **Coroutines + Flow** | 1.9+ | Async + state management | | **AndroidX WebRTC** | 1.0+ | WebRTC natif Android | | **Firebase Cloud Messaging** | 24.1+ | Notifications push | | **DataStore** | 1.1+ | Stockage local préférences | | **Room** | 2.7+ | Cache local (offline) | | **Coil** | 3.0+ | Chargement images | | **JUnit 5** | 5.11+ | Tests unitaires | | **MockK** | 1.13+ | Mocking | | **Turbine** | 1.2+ | Tests Flow | | **Compose UI Test** | 1.7+ | Tests UI | | **Gradle** | 8.10+ | Build | ### SignalR — Client Kotlin Microsoft fournit un [client SignalR pour Java](https://github.com/microsoft/signalr/tree/master/clients/java) qui fonctionne parfaitement avec Kotlin. Alternative : implémentation maison via WebSocket + JSON (protocole SignalR JSON). ```gradle // build.gradle.kts (app) dependencies { // SignalR Java client (compatible Kotlin) implementation("com.microsoft.signalr:signalr:8.0.0") // Ktor HTTP client implementation("io.ktor:ktor-client-android:3.0.0") implementation("io.ktor:ktor-client-content-negotiation:3.0.0") implementation("io.ktor:ktor-serialization-kotlinx-json:3.0.0") // WebRTC natif implementation("org.webrtc:google-webrtc:1.0.32006") // Dependency injection implementation("com.google.dagger:hilt-android:2.53") kapt("com.google.dagger:hilt-compiler:2.53") // Image loading implementation("io.coil-kt:coil-compose:3.0.0") // Local cache implementation("androidx.room:room-runtime:2.7.0") implementation("androidx.room:room-ktx:2.7.0") kapt("androidx.room:room-compiler:2.7.0") // DataStore implementation("androidx.datastore:datastore-preferences:1.1.0") // Navigation implementation("androidx.navigation:navigation-compose:2.8.0") // Firebase implementation(platform("com.google.firebase:firebase-bom:33.0.0")) implementation("com.google.firebase:firebase-messaging-ktx") // Lifecycle implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.0") implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.0") // Async implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0") // Serialization implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.0") // Tests testImplementation("org.junit.jupiter:junit-jupiter:5.11.0") testImplementation("io.mockk:mockk:1.13.0") testImplementation("app.cash.turbine:turbine:1.2.0") testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.9.0") androidTestImplementation("androidx.compose.ui:ui-test-junit4:1.7.0") } ``` --- ## 3. Architecture Clean Architecture ``` app/ ├── data/ ← Data layer │ ├── remote/ │ │ ├── api/ ← Ktor API client │ │ │ ├── HeimdallApi.kt ← Interface des endpoints │ │ │ └── HeimdallApiImpl.kt ← Implémentation Ktor │ │ ├── dto/ ← DTOs (réponses API) │ │ │ ├── SiteDto.kt │ │ │ ├── CameraDto.kt │ │ │ └── EventDto.kt │ │ └── signalr/ ← SignalR client │ │ ├── SignalRService.kt │ │ └── StreamingHub.kt │ ├── local/ │ │ ├── db/ ← Room database │ │ │ ├── AppDatabase.kt │ │ │ ├── SiteDao.kt │ │ │ └── EventDao.kt │ │ ├── datastore/ ← DataStore preferences │ │ │ └── AuthDataStore.kt │ │ └── cache/ ← Image cache (Coil) │ └── repository/ ← Implémentation des repositories │ ├── AuthRepositoryImpl.kt │ ├── SiteRepositoryImpl.kt │ ├── CameraRepositoryImpl.kt │ └── EventRepositoryImpl.kt │ ├── domain/ ← Domain layer (pure Kotlin) │ ├── model/ ← Modèles métier │ │ ├── Site.kt │ │ ├── Camera.kt │ │ ├── Event.kt │ │ └── User.kt │ ├── repository/ ← Interfaces repository │ │ ├── AuthRepository.kt │ │ ├── SiteRepository.kt │ │ ├── CameraRepository.kt │ │ └── EventRepository.kt │ └── usecase/ ← Cas d'utilisation │ ├── LoginUseCase.kt │ ├── GetSitesUseCase.kt │ ├── GetCamerasUseCase.kt │ ├── GetEventsUseCase.kt │ └── StartLiveStreamUseCase.kt │ ├── presentation/ ← Presentation layer │ ├── MainActivity.kt │ ├── HeimdallApp.kt ← Point d'entrée Compose │ ├── navigation/ │ │ ├── NavGraph.kt │ │ └── Screen.kt ← Routes scellées │ ├── theme/ │ │ ├── Theme.kt │ │ ├── Color.kt │ │ └── Type.kt │ ├── components/ ← Composants réutilisables │ │ ├── CameraCard.kt │ │ ├── EventItem.kt │ │ ├── SiteCard.kt │ │ └── LoadingIndicator.kt │ ├── auth/ │ │ ├── LoginScreen.kt │ │ └── LoginViewModel.kt │ ├── dashboard/ │ │ ├── DashboardScreen.kt │ │ └── DashboardViewModel.kt │ ├── sites/ │ │ ├── SiteListScreen.kt │ │ ├── SiteListViewModel.kt │ │ ├── SiteDetailScreen.kt │ │ └── SiteDetailViewModel.kt │ ├── camera/ │ │ ├── CameraLiveScreen.kt │ │ └── CameraLiveViewModel.kt │ ├── events/ │ │ ├── EventListScreen.kt │ │ ├── EventListViewModel.kt │ │ ├── EventDetailScreen.kt │ │ └── EventDetailViewModel.kt │ └── settings/ │ ├── SettingsScreen.kt │ └── SettingsViewModel.kt │ └── di/ ← Hilt modules ├── NetworkModule.kt ├── DatabaseModule.kt ├── RepositoryModule.kt └── SignalRModule.kt ``` --- ## 4. Data Layer — Ktor API Client ### Interface API (générée depuis OpenAPI Heimdall) ```kotlin // data/remote/api/HeimdallApi.kt interface HeimdallApi { // ─── Auth ───────────────────────────────── @Post("/api/auth/login") suspend fun login(@Body request: LoginRequest): LoginResponse @Post("/api/auth/refresh") suspend fun refreshToken(@Body request: RefreshRequest): LoginResponse // ─── Sites ──────────────────────────────── @Get("/api/mobile/sites") suspend fun getMySites(): List @Get("/api/mobile/sites/{siteId}") suspend fun getSiteDetail(@Path("siteId") siteId: String): SiteDetailDto // ─── Cameras ───────────────────────────── @Get("/api/mobile/sites/{siteId}/cameras") suspend fun getCameras(@Path("siteId") siteId: String): List @Get("/api/mobile/cameras/{cameraId}/stream-info") suspend fun getStreamInfo(@Path("cameraId") cameraId: String): StreamInfoDto // ─── Events ────────────────────────────── @Get("/api/mobile/sites/{siteId}/events") suspend fun getEvents( @Path("siteId") siteId: String, @Query("page") page: Int = 1, @Query("pageSize") pageSize: Int = 20, @Query("type") type: String? = null ): PagedResponse @Get("/api/mobile/events/{eventId}") suspend fun getEventDetail(@Path("eventId") eventId: String): EventDetailDto // ─── Persons ───────────────────────────── @Get("/api/mobile/persons") suspend fun getPersons(): List } ``` ### Implémentation Ktor avec token management ```kotlin // data/remote/api/HeimdallApiImpl.kt class HeimdallApiImpl( private val client: HttpClient, private val authDataStore: AuthDataStore ) : HeimdallApi { override suspend fun getMySites(): List { return client.get("${BASE_URL}/api/mobile/sites") { bearerAuth(authDataStore.getAccessToken()) }.body() } override suspend fun getCameras(siteId: String): List { return client.get("${BASE_URL}/api/mobile/sites/$siteId/cameras") { bearerAuth(authDataStore.getAccessToken()) }.body() } // Token refresh automatique sur 401 private fun HttpClient.configure() { defaultRequest { bearerAuth(authDataStore.getAccessToken()) } HttpResponseValidator { if (response.status == HttpStatusCode.Unauthorized) { val newToken = refreshToken() if (newToken != null) { bearerAuth(newToken) } else { throw SessionExpiredException() } } } } } // Hilt module @Module @InstallIn(SingletonComponent::class) object NetworkModule { @Provides @Singleton fun provideHttpClient(): HttpClient { return HttpClient(Android) { install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true isLenient = true }) } install(Logging) { level = LogLevel.BODY } } } @Provides @Singleton fun provideHeimdallApi(client: HttpClient, auth: AuthDataStore): HeimdallApi { return HeimdallApiImpl(client, auth) } } ``` --- ## 5. Domain Layer — Cas d'utilisation ```kotlin // domain/usecase/LoginUseCase.kt class LoginUseCase @Inject constructor( private val authRepository: AuthRepository ) { sealed class Result { data class Success(val user: User) : Result() data class Requires2fa(val token: String) : Result() data class Error(val message: String) : Result() } suspend operator fun invoke(email: String, password: String): Result { return try { val response = authRepository.login(email, password) if (response.requires2fa) { Result.Requires2fa(response.partialToken) } else { Result.Success(response.user) } } catch (e: UnauthorizedException) { Result.Error("Identifiants invalides") } catch (e: IOException) { Result.Error("Impossible de contacter le serveur") } } } // domain/usecase/GetSitesUseCase.kt class GetSitesUseCase @Inject constructor( private val siteRepository: SiteRepository ) { suspend operator fun invoke(): Flow>> { return siteRepository.getSites() .onStart { emit(Resource.Loading) } .catch { emit(Resource.Error(it.message ?: "Erreur")) } } } // domain/usecase/StartLiveStreamUseCase.kt class StartLiveStreamUseCase @Inject constructor( private val cameraRepository: CameraRepository ) { suspend operator fun invoke(cameraId: String): Flow { return cameraRepository.startLiveStream(cameraId) } } ``` --- ## 6. Presentation Layer — Jetpack Compose ### Navigation ```kotlin // presentation/navigation/Screen.kt sealed class Screen(val route: String) { object Login : Screen("login") object Dashboard : Screen("dashboard") object SiteList : Screen("sites") data class SiteDetail(val siteId: String) : Screen("sites/{siteId}") { companion object { const val ROUTE = "sites/{siteId}" fun createRoute(siteId: String) = "sites/$siteId" } } data class CameraLive(val cameraId: String) : Screen("cameras/{cameraId}/live") { companion object { const val ROUTE = "cameras/{cameraId}/live" fun createRoute(cameraId: String) = "cameras/$cameraId/live" } } object EventList : Screen("events") data class EventDetail(val eventId: String) : Screen("events/{eventId}") { companion object { const val ROUTE = "events/{eventId}" fun createRoute(eventId: String) = "events/$eventId" } } object Settings : Screen("settings") } // presentation/navigation/NavGraph.kt @Composable fun HeimdallNavGraph(navController: NavHostController) { NavHost(navController, startDestination = Screen.Login.route) { composable(Screen.Login.route) { LoginScreen( onLoginSuccess = { navController.navigate(Screen.Dashboard.route) { popUpTo(Screen.Login.route) { inclusive = true } } } ) } composable(Screen.Dashboard.route) { DashboardScreen( onSiteClick = { siteId -> navController.navigate(Screen.SiteDetail.createRoute(siteId)) } ) } composable(Screen.SiteList.route) { SiteListScreen( onSiteClick = { siteId -> navController.navigate(Screen.SiteDetail.createRoute(siteId)) } ) } composable( route = Screen.SiteDetail.ROUTE, arguments = listOf(navArgument("siteId") { type = NavType.StringType }) ) { backStackEntry -> val siteId = backStackEntry.arguments?.getString("siteId") ?: return@composable SiteDetailScreen( siteId = siteId, onCameraClick = { cameraId -> navController.navigate(Screen.CameraLive.createRoute(cameraId)) } ) } composable( route = Screen.CameraLive.ROUTE, arguments = listOf(navArgument("cameraId") { type = NavType.StringType }) ) { backStackEntry -> val cameraId = backStackEntry.arguments?.getString("cameraId") ?: return@composable CameraLiveScreen(cameraId = cameraId) } composable(Screen.EventList.route) { EventListScreen(onEventClick = { eventId -> navController.navigate(Screen.EventDetail.createRoute(eventId)) }) } composable(Screen.Settings.route) { SettingsScreen(onLogout = { navController.navigate(Screen.Login.route) { popUpTo(0) { inclusive = true } } }) } } } ``` ### Écran Login ```kotlin // presentation/auth/LoginScreen.kt @Composable fun LoginScreen( onLoginSuccess: () -> Unit, viewModel: LoginViewModel = hiltViewModel() ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() MaterialTheme { Column( modifier = Modifier .fillMaxSize() .padding(32.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { // Logo Text( text = "HEIMDALL", style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold ) Text( text = "Surveillance Mobile", style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant ) Spacer(modifier = Modifier.height(48.dp)) // Champ Email OutlinedTextField( value = uiState.email, onValueChange = viewModel::onEmailChanged, label = { Text("Email") }, leadingIcon = { Icon(Icons.Default.Email, "") }, isError = uiState.emailError != null, supportingText = uiState.emailError?.let { { Text(it) } }, singleLine = true, modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.height(12.dp)) // Champ Mot de passe OutlinedTextField( value = uiState.password, onValueChange = viewModel::onPasswordChanged, label = { Text("Mot de passe") }, leadingIcon = { Icon(Icons.Default.Lock, "") }, visualTransformation = PasswordVisualTransformation(), isError = uiState.passwordError != null, supportingText = uiState.passwordError?.let { { Text(it) } }, singleLine = true, modifier = Modifier.fillMaxWidth() ) // Champ 2FA (apparaît si requis) if (uiState.is2faRequired) { Spacer(modifier = Modifier.height(12.dp)) OutlinedTextField( value = uiState.twoFactorCode, onValueChange = viewModel::onTwoFactorCodeChanged, label = { Text("Code authenticator") }, leadingIcon = { Icon(Icons.Default.Shield, "") }, singleLine = true, modifier = Modifier.fillMaxWidth() ) } Spacer(modifier = Modifier.height(24.dp)) // Bouton Connexion Button( onClick = { viewModel.login(onLoginSuccess) }, enabled = !uiState.isLoading, modifier = Modifier .fillMaxWidth() .height(50.dp) ) { if (uiState.isLoading) { CircularProgressIndicator( modifier = Modifier.size(20.dp), strokeWidth = 2.dp, color = MaterialTheme.colorScheme.onPrimary ) } else { Text("Se connecter") } } // Message d'erreur uiState.errorMessage?.let { error -> Spacer(modifier = Modifier.height(16.dp)) Card( colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.errorContainer ) ) { Text( text = error, modifier = Modifier.padding(16.dp), color = MaterialTheme.colorScheme.onErrorContainer ) } } // Champ URL serveur Spacer(modifier = Modifier.height(24.dp)) OutlinedTextField( value = uiState.serverUrl, onValueChange = viewModel::onServerUrlChanged, label = { Text("Serveur") }, leadingIcon = { Icon(Icons.Default.Dns, "") }, singleLine = true, modifier = Modifier.fillMaxWidth() ) } } } ``` ### LoginViewModel ```kotlin // presentation/auth/LoginViewModel.kt @HiltViewModel class LoginViewModel @Inject constructor( private val loginUseCase: LoginUseCase, private val authDataStore: AuthDataStore ) : ViewModel() { data class UiState( val email: String = "", val password: String = "", val twoFactorCode: String = "", val serverUrl: String = "", // mémorisé val isLoading: Boolean = false, val is2faRequired: Boolean = false, val emailError: String? = null, val passwordError: String? = null, val errorMessage: String? = null ) private val _uiState = MutableStateFlow(UiState()) val uiState: StateFlow = _uiState.asStateFlow() init { viewModelScope.launch { val savedUrl = authDataStore.getServerUrl() _uiState.update { it.copy(serverUrl = savedUrl) } } } fun onEmailChanged(value: String) { _uiState.update { it.copy(email = value, emailError = null, errorMessage = null) } } fun onPasswordChanged(value: String) { _uiState.update { it.copy(password = value, passwordError = null, errorMessage = null) } } fun onTwoFactorCodeChanged(value: String) { _uiState.update { it.copy(twoFactorCode = value, errorMessage = null) } } fun onServerUrlChanged(value: String) { _uiState.update { it.copy(serverUrl = value) } } fun login(onSuccess: () -> Unit) { val state = _uiState.value // Validation if (state.email.isBlank() || !state.email.contains("@")) { _uiState.update { it.copy(emailError = "Email invalide") } return } if (state.password.isBlank()) { _uiState.update { it.copy(passwordError = "Mot de passe requis") } return } _uiState.update { it.copy(isLoading = true, errorMessage = null) } viewModelScope.launch { authDataStore.setServerUrl(state.serverUrl) when (val result = loginUseCase(state.email, state.password)) { is LoginUseCase.Result.Success -> { _uiState.update { it.copy(isLoading = false) } onSuccess() } is LoginUseCase.Result.Requires2fa -> { _uiState.update { it.copy(isLoading = false, is2faRequired = true) } } is LoginUseCase.Result.Error -> { _uiState.update { it.copy(isLoading = false, errorMessage = result.message) } } } } } } ``` ### DashboardScreen ```kotlin // presentation/dashboard/DashboardScreen.kt @Composable fun DashboardScreen( onSiteClick: (String) -> Unit, viewModel: DashboardViewModel = hiltViewModel() ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() Scaffold( topBar = { TopAppBar( title = { Text("Heimdall") }, actions = { IconButton(onClick = { /* notifications */ }) { BadgedBox(badge = { if (uiState.unreadCount > 0) { Badge { Text("${uiState.unreadCount}") } } }) { Icon(Icons.Default.Notifications, "Alertes") } } } ) }, bottomBar = { NavigationBar { NavigationBarItem( selected = true, onClick = { }, icon = { Icon(Icons.Default.Home, "") }, label = { Text("Accueil") } ) NavigationBarItem( selected = false, onClick = { /* vers sites */ }, icon = { Icon(Icons.Default.Videocam, "") }, label = { Text("Sites") } ) NavigationBarItem( selected = false, onClick = { /* vers events */ }, icon = { Icon(Icons.Default.Event, "") }, label = { Text("Événements") } ) NavigationBarItem( selected = false, onClick = { /* vers settings */ }, icon = { Icon(Icons.Default.Settings, "") }, label = { Text("Réglages") } ) } } ) { padding -> when (uiState) { is DashboardUiState.Loading -> LoadingIndicator() is DashboardUiState.Error -> ErrorMessage((uiState as DashboardUiState.Error).message) is DashboardUiState.Success -> { val data = (uiState as DashboardUiState.Success).data LazyColumn(modifier = Modifier.padding(padding)) { // KPIs item { Row(modifier = Modifier.padding(16.dp)) { KpiCard("📷 Sites", "${data.totalSites}") KpiCard("📹 En ligne", "${data.onlineCameras}") KpiCard("🚗 Aujourd'hui", "${data.todayEvents}") } } // Derniers événements item { Text( "Derniers événements", style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp) ) } data.recentEvents.forEach { event -> item { EventItem( event = event, onClick = { /* event detail */ } ) } } // Mes sites item { Text( "Mes sites", style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp) ) } data.sites.forEach { site -> item { SiteCard(site = site, onClick = { onSiteClick(site.id) }) } } } } } } } ``` ### Camera Live — WebRTC natif Android ```kotlin // presentation/camera/CameraLiveScreen.kt @Composable fun CameraLiveScreen( cameraId: String, viewModel: CameraLiveViewModel = hiltViewModel() ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() Scaffold( topBar = { TopAppBar( title = { Text(uiState.cameraName) }, navigationIcon = { IconButton(onClick = { /* back */ }) { Icon(Icons.Default.ArrowBack, "Retour") } }, actions = { IconButton(onClick = viewModel::takeSnapshot) { Icon(Icons.Default.CameraAlt, "Snapshot") } } ) } ) { padding -> Column(modifier = Modifier.fillMaxSize().padding(padding)) { // Surface d'affichage vidéo (SurfaceViewRenderer) AndroidView( factory = { ctx -> SurfaceViewRenderer(ctx).apply { viewModel.setVideoOutput(this) } }, modifier = Modifier .fillMaxWidth() .height(250.dp) ) // Contrôles Row( modifier = Modifier .fillMaxWidth() .padding(8.dp), horizontalArrangement = Arrangement.SpaceEvenly ) { FilterChip( selected = uiState.quality == "1080p", onClick = { viewModel.setQuality("1080p") }, label = { Text("1080p") } ) FilterChip( selected = uiState.quality == "720p", onClick = { viewModel.setQuality("720p") }, label = { Text("720p") } ) FilterChip( selected = uiState.quality == "480p", onClick = { viewModel.setQuality("480p") }, label = { Text("480p") } ) } // Événements récents de cette caméra Text( "Événements récents", style = MaterialTheme.typography.titleSmall, modifier = Modifier.padding(16.dp) ) LazyColumn { items(uiState.recentEvents) { event -> EventItem(event = event, onClick = {}) } } } } } ``` ### CameraLiveViewModel — WebRTC + SignalR Signaling ```kotlin @HiltViewModel class CameraLiveViewModel @Inject constructor( private val startLiveStreamUseCase: StartLiveStreamUseCase, savedStateHandle: SavedStateHandle ) : ViewModel() { private val cameraId: String = savedStateHandle["cameraId"] ?: "" data class UiState( val cameraName: String = "", val quality: String = "1080p", val recentEvents: List = emptyList() ) private val _uiState = MutableStateFlow(UiState()) val uiState: StateFlow = _uiState.asStateFlow() private var peerConnection: PeerConnection? = null private var surfaceRenderer: SurfaceViewRenderer? = null init { connectWebRTC() } private fun connectWebRTC() { viewModelScope.launch { startLiveStreamUseCase(cameraId).collect { state -> when (state) { is WebRtcState.Connecting -> { /* loading */ } is WebRtcState.Connected -> { /* stream actif */ } is WebRtcState.Disconnected -> { /* reconnect */ } is WebRtcState.Error -> { /* show error */ } } } } } fun setVideoOutput(renderer: SurfaceViewRenderer) { surfaceRenderer = renderer peerConnection?.addTrack(/* video track */) // Le rendu se fait via SurfaceViewRenderer.setMirror(false) // et en l'attachant au VideoTrack du PeerConnection } fun takeSnapshot() { // Capture via MediaCodec + Bitmap surfaceRenderer?.let { renderer -> val bitmap = renderer.getBitmap() // Sauvegarder ou envoyer } } fun setQuality(quality: String) { _uiState.update { it.copy(quality = quality) } // Renégocier le SDP avec la nouvelle résolution } override fun onCleared() { super.onCleared() peerConnection?.close() surfaceRenderer?.release() } } ``` ### WebRTC — PeerConnection avec SignalR ```kotlin // data/remote/signalr/StreamingHub.kt class StreamingHub( private val serverUrl: String, private val accessToken: String ) { private val hubConnection: HubConnection = HubConnectionBuilder .create("$serverUrl/hubs/streaming") .withAccessTokenProvider { CompletableFuture.completedFuture(accessToken) } .build() private val _onSdpOffer = MutableSharedFlow() val onSdpOffer: SharedFlow = _onSdpOffer.asSharedFlow() private val _onIceCandidate = MutableSharedFlow() val onIceCandidate: SharedFlow = _onIceCandidate.asSharedFlow() suspend fun start() { hubConnection.on("SdpOffer") { offer: String -> _onSdpOffer.emit(offer) } hubConnection.on("IceCandidate") { candidate: String -> _onIceCandidate.emit(candidate) } hubConnection.start().blockingAwait() } suspend fun requestStream(cameraId: String) { hubConnection.send("RequestStream", cameraId) } suspend fun sendSdpAnswer(sdp: String, targetId: String) { hubConnection.send("SendAnswer", sdp, targetId) } suspend fun sendIceCandidate(candidate: String, targetId: String) { hubConnection.send("SendIceCandidate", candidate, targetId) } fun stop() { hubConnection.stop() } } // WebRTC native PeerConnection factory class WebRTCFactory( private val context: Context ) { private val rootEglBase: EglBase = EglBase.create() fun createPeerConnection(observer: PeerConnection.Observer): PeerConnection { val iceServers = listOf( PeerConnection.IceServer.builder("stun:stun.l.google.com:19302").createIceServer() ) val config = PeerConnection.RTCConfiguration(iceServers).apply { sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN } val factory = PeerConnectionFactory.builder() .setVideoDecoderFactory(DefaultVideoDecoderFactory(rootEglBase.eglBaseContext)) .setVideoEncoderFactory(DefaultVideoEncoderFactory( rootEglBase.eglBaseContext, true, true)) .createPeerConnectionFactory() return factory.createPeerConnection(config, observer)!! } fun createSurfaceRenderer(context: Context): SurfaceViewRenderer { return SurfaceViewRenderer(context).apply { setMirror(false) setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT) init(rootEglBase.eglBaseContext, null) } } } ``` --- ## 7. Notifications Push — Firebase Cloud Messaging ```kotlin // presentation/heimdall/FirebaseMessagingService.kt @AndroidManifest (service dans AndroidManifest.xml) class HeimdallFcmService : FirebaseMessagingService() { override fun onNewToken(token: String) { // Envoyer le token FCM au serveur Heimdall // POST /api/mobile/push/register { token, platform: "android" } } override fun onMessageReceived(message: RemoteMessage) { val eventType = message.data["eventType"] val cameraName = message.data["cameraName"] val siteName = message.data["siteName"] val eventId = message.data["eventId"] val snapshotUrl = message.data["snapshotUrl"] // Notification locale val channelId = "heimdall_events" val notification = NotificationCompat.Builder(this, channelId) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(getEventTitle(eventType)) .setContentText("$cameraName · $siteName") .setStyle(NotificationCompat.BigPictureStyle() .bigPicture(fetchSnapshot(snapshotUrl))) .setAutoCancel(true) .setPriority(NotificationCompat.PRIORITY_HIGH) .build() val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager manager.notify(eventId.hashCode(), notification) } } ``` --- ## 8. Cache Local — Room ```kotlin // data/local/db/AppDatabase.kt @Database(entities = [SiteEntity::class, EventEntity::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun siteDao(): SiteDao abstract fun eventDao(): EventDao } @Entity(tableName = "sites") data class SiteEntity( @PrimaryKey val id: String, val name: String, val cameraCount: Int, val onlineCameraCount: Int, val thumbnailUrl: String?, val lastUpdated: Long = System.currentTimeMillis() ) @Dao interface SiteDao { @Query("SELECT * FROM sites ORDER BY name") fun getAll(): Flow> @Upsert suspend fun upsertAll(sites: List) @Query("DELETE FROM sites") suspend fun clear() } // Hilt module @Module @InstallIn(SingletonComponent::class) object DatabaseModule { @Provides @Singleton fun provideDatabase(@ApplicationContext context: Context): AppDatabase { return Room.databaseBuilder( context, AppDatabase::class.java, "heimdall_cache" ).build() } } ``` --- ## 9. Tests ### Structure des tests ``` app/src/ ├── test/ ← Tests unitaires (JUnit 5 + MockK) │ ├── domain/usecase/ │ │ ├── LoginUseCaseTest.kt │ │ └── GetSitesUseCaseTest.kt │ ├── data/repository/ │ │ ├── AuthRepositoryImplTest.kt │ │ └── SiteRepositoryImplTest.kt │ └── presentation/ │ ├── LoginViewModelTest.kt │ └── DashboardViewModelTest.kt └── androidTest/ ← Tests instrumentés (Compose UI) └── presentation/ └── LoginScreenTest.kt ``` ### Exemple — UseCase Test ```kotlin // LoginUseCaseTest.kt @OptIn(ExperimentalCoroutinesApi::class) class LoginUseCaseTest { private val authRepository: AuthRepository = mockk() private lateinit var loginUseCase: LoginUseCase @BeforeEach fun setup() { loginUseCase = LoginUseCase(authRepository) } @Test fun `login with valid credentials returns Success`() = runTest { // Given val email = "user@example.com" val password = "validPassword" coEvery { authRepository.login(email, password) } returns LoginResponse( user = User(id = "1", name = "Jean"), requires2fa = false, partialToken = "" ) // When val result = loginUseCase(email, password) // Then assertTrue(result is LoginUseCase.Result.Success) } @Test fun `login with invalid credentials returns Error`() = runTest { // Given coEvery { authRepository.login(any(), any()) } throws UnauthorizedException("Identifiants invalides") // When val result = loginUseCase("bad@email.com", "wrong") // Then assertTrue(result is LoginUseCase.Result.Error) assertEquals("Identifiants invalides", (result as LoginUseCase.Result.Error).message) } @Test fun `login when 2FA enabled returns Requires2fa`() = runTest { // Given coEvery { authRepository.login(any(), any()) } returns LoginResponse( user = User(id = "1", name = "Jean"), requires2fa = true, partialToken = "partial_jwt_..." ) // When val result = loginUseCase("user@example.com", "password") // Then assertTrue(result is LoginUseCase.Result.Requires2fa) } } ``` ### Exemple — ViewModel Test (Turbine) ```kotlin // LoginViewModelTest.kt @OptIn(ExperimentalCoroutinesApi::class) class LoginViewModelTest { private val loginUseCase: LoginUseCase = mockk() private val authDataStore: AuthDataStore = mockk(relaxed = true) private lateinit var viewModel: LoginViewModel @BeforeEach fun setup() { viewModel = LoginViewModel(loginUseCase, authDataStore) } @Test fun `empty email shows validation error`() = runTest { viewModel.onEmailChanged("") viewModel.onPasswordChanged("pass") viewModel.login {} // onSuccess = no-op viewModel.uiState.test { val state = awaitItem() assertNotNull(state.emailError) } } @Test fun `successful login calls onSuccess`() = runTest { coEvery { loginUseCase(any(), any()) } returns LoginUseCase.Result.Success(user) var successCalled = false viewModel.onEmailChanged("user@example.com") viewModel.onPasswordChanged("pass") viewModel.login { successCalled = true } advanceUntilIdle() assertTrue(successCalled) } } ``` ### Exemple — Compose UI Test ```kotlin // LoginScreenTest.kt @RunWith(AndroidJUnit4::class) class LoginScreenTest { @get:Rule val composeTestRule = createComposeRule() @Test fun loginButton_disabled_when_fields_empty() { composeTestRule.setContent { LoginScreen(onLoginSuccess = {}) } composeTestRule .onNodeWithText("Se connecter") .assertIsNotEnabled() } @Test fun error_displayed_on_invalid_email() { composeTestRule.setContent { LoginScreen(onLoginSuccess = {}) } composeTestRule.onNodeWithText("Email").performTextClearance() composeTestRule.onNodeWithText("Mot de passe").performTextInput("pass") composeTestRule.onNodeWithText("Se connecter").performClick() composeTestRule.onNodeWithText("Email invalide").assertIsDisplayed() } } ``` --- ## 10. Build & CI/CD ### Gradle (version catalogs) ```toml # gradle/libs.versions.toml [versions] kotlin = "2.1.0" compose = "1.7.0" hilt = "2.53" ktor = "3.0.0" signalr = "8.0.0" webrtc = "1.0.32006" [libraries] kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib", version.ref = "kotlin" } compose-ui = { module = "androidx.compose.ui:ui", version.ref = "compose" } compose-material3 = { module = "androidx.compose.material3:material3", version = "1.3.0" } hilt-android = { module = "com.google.dagger:hilt-android", version.ref = "hilt" } ktor-client-android = { module = "io.ktor:ktor-client-android", version.ref = "ktor" } signalr-client = { module = "com.microsoft.signalr:signalr", version.ref = "signalr" } webrtc-android = { module = "org.webrtc:google-webrtc", version.ref = "webrtc" } [plugins] kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } hilt = { id = "com.google.dagger.hilt.android", version.ref = "hilt" } compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } ``` ### GitHub Actions — Build APK dédié ```yaml # .github/workflows/mobile.yml name: Build Android App on: push: branches: [main, develop] paths: - 'src/Heimdall.Mobile/**' - '.github/workflows/mobile.yml' pull_request: paths: - 'src/Heimdall.Mobile/**' jobs: lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: '21' - name: Lint Kotlin run: ./gradlew lint working-directory: src/Heimdall.Mobile - name: Detekt (static analysis) run: ./gradlew detekt working-directory: src/Heimdall.Mobile test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: '21' - name: Unit tests run: ./gradlew testDebugUnitTest working-directory: src/Heimdall.Mobile - name: Upload coverage uses: actions/upload-artifact@v4 with: name: test-coverage path: src/Heimdall.Mobile/app/build/reports/ build: runs-on: ubuntu-latest needs: [lint, test] steps: - uses: actions/checkout@v4 - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: '21' - name: Build APK run: ./gradlew assembleDebug working-directory: src/Heimdall.Mobile - name: Sign APK (release) if: github.ref == 'refs/heads/main' env: KEYSTORE: ${{ secrets.ANDROID_KEYSTORE }} KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }} KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }} run: ./gradlew assembleRelease working-directory: src/Heimdall.Mobile - name: Upload APK uses: actions/upload-artifact@v4 with: name: heimdall-mobile path: src/Heimdall.Mobile/app/build/outputs/apk/**/*.apk ``` ### AndroidManifest.xml ```xml ``` --- ## 11. Tests — Résumé | Niveau | Technologie | Couverture | |---|---|---| | **Unitaires (UseCases)** | JUnit 5 + MockK | 100% des cas d'utilisation | | **Unitaires (ViewModels)** | JUnit 5 + Turbine | États UI, validation, erreurs | | **Unitaires (Repository)** | JUnit 5 + MockK | API + cache + offline | | **UI (Compose)** | Compose UI Test + JUnit 4 | Écrans critiques (Login, Live) | | **Intégration** | — | CI gate : lint + test + build |