This commit is contained in:
1 parent
881ad48066
commit
4b954be09c
73 files changed
+4054
-1357
No files matched your search
@@ -0,0 +1,26 @@
|
||||
# Gradle
|
||||
.gradle/
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!gradle/wrapper/gradle-wrapper.properties
|
||||
|
||||
# Android
|
||||
/local.properties
|
||||
*.apk
|
||||
*.aab
|
||||
*.dex
|
||||
*.class
|
||||
/captures
|
||||
.externalNativeBuild/
|
||||
.cxx/
|
||||
google-services.json
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
*.iml
|
||||
*.iws
|
||||
*.ipr
|
||||
.vscode/
|
||||
|
||||
# macOS
|
||||
.DS_Store
|
||||
@@ -0,0 +1,106 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.kotlin.android)
|
||||
alias(libs.plugins.kotlin.compose)
|
||||
alias(libs.plugins.kotlin.serialization)
|
||||
alias(libs.plugins.hilt)
|
||||
alias(libs.plugins.ksp)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.heimdall.mobile"
|
||||
compileSdk = libs.versions.compileSdk.get().toInt()
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.heimdall.mobile"
|
||||
minSdk = libs.versions.minSdk.get().toInt()
|
||||
targetSdk = libs.versions.targetSdk.get().toInt()
|
||||
versionCode = 1
|
||||
versionName = "1.0.0"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
|
||||
vectorDrawables { useSupportLibrary = true }
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = true
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro"
|
||||
)
|
||||
}
|
||||
debug {
|
||||
isMinifyEnabled = false
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = "17"
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
compose = true
|
||||
buildConfig = true
|
||||
}
|
||||
|
||||
packaging {
|
||||
resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" }
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":data"))
|
||||
implementation(project(":domain"))
|
||||
implementation(project(":presentation"))
|
||||
|
||||
implementation(libs.core.ktx)
|
||||
implementation(libs.activity.compose)
|
||||
|
||||
// Compose
|
||||
implementation(platform(libs.compose.bom))
|
||||
implementation(libs.compose.ui)
|
||||
implementation(libs.compose.ui.graphics)
|
||||
implementation(libs.compose.ui.tooling.preview)
|
||||
implementation(libs.compose.material3)
|
||||
implementation(libs.compose.material.icons)
|
||||
implementation(libs.compose.runtime)
|
||||
debugImplementation(libs.compose.ui.tooling)
|
||||
debugImplementation(libs.compose.ui.test.manifest)
|
||||
|
||||
// Lifecycle
|
||||
implementation(libs.lifecycle.viewmodel.compose)
|
||||
implementation(libs.lifecycle.runtime.compose)
|
||||
|
||||
// Navigation
|
||||
implementation(libs.navigation.compose)
|
||||
implementation(libs.hilt.navigation.compose)
|
||||
|
||||
// Hilt
|
||||
implementation(libs.hilt.android)
|
||||
ksp(libs.hilt.compiler)
|
||||
|
||||
// Testing
|
||||
testImplementation(libs.junit5.api)
|
||||
testImplementation(libs.mockk)
|
||||
testImplementation(libs.turbine)
|
||||
testImplementation(libs.coroutines.test)
|
||||
androidTestImplementation(platform(libs.compose.bom))
|
||||
androidTestImplementation(libs.compose.ui.test)
|
||||
}
|
||||
|
||||
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
|
||||
compilerOptions {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType<Test> {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
# Heimdall Mobile ProGuard Rules
|
||||
|
||||
# Kotlin Serialization
|
||||
-keepattributes *Annotation*, InnerClasses
|
||||
-dontnote kotlinx.serialization.AnnotationsKt
|
||||
|
||||
-keepclassmembers class kotlinx.serialization.json.** {
|
||||
*** Companion;
|
||||
}
|
||||
-keepclasseswithmembers class kotlinx.serialization.json.** {
|
||||
kotlinx.serialization.KSerializer serializer(...);
|
||||
}
|
||||
|
||||
-keep,includedescriptorclasses class com.heimdall.mobile.**$$serializer { *; }
|
||||
-keepclassmembers class com.heimdall.mobile.** {
|
||||
*** Companion;
|
||||
}
|
||||
-keepclasseswithmembers class com.heimdall.mobile.** {
|
||||
kotlinx.serialization.KSerializer serializer(...);
|
||||
}
|
||||
|
||||
# Ktor
|
||||
-keep class io.ktor.** { *; }
|
||||
-dontwarn io.ktor.**
|
||||
|
||||
# Room
|
||||
-keep class * extends androidx.room.RoomDatabase
|
||||
-keep @androidx.room.Entity class *
|
||||
@@ -0,0 +1,35 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
|
||||
|
||||
<uses-feature android:name="android.hardware.camera" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
|
||||
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
|
||||
|
||||
<application
|
||||
android:name=".HeimdallApp"
|
||||
android:allowBackup="true"
|
||||
android:icon="@android:drawable/ic_lock_lock"
|
||||
android:label="@string/app_name"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.Heimdall">
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.heimdall.mobile
|
||||
|
||||
import android.app.Application
|
||||
import dagger.hilt.android.HiltAndroidApp
|
||||
|
||||
@HiltAndroidApp
|
||||
class HeimdallApp : Application()
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.heimdall.mobile
|
||||
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import com.heimdall.mobile.presentation.screens.HeimdallNavGraph
|
||||
import com.heimdall.mobile.presentation.ui.theme.HeimdallTheme
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
|
||||
@AndroidEntryPoint
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
setContent {
|
||||
HeimdallTheme {
|
||||
HeimdallNavGraph()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">Heimdall</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<style name="Theme.Heimdall" parent="android:Theme.Material.Light.NoActionBar" />
|
||||
</resources>
|
||||
@@ -0,0 +1,9 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.application) apply false
|
||||
alias(libs.plugins.android.library) apply false
|
||||
alias(libs.plugins.kotlin.android) apply false
|
||||
alias(libs.plugins.kotlin.compose) apply false
|
||||
alias(libs.plugins.kotlin.serialization) apply false
|
||||
alias(libs.plugins.hilt) apply false
|
||||
alias(libs.plugins.ksp) apply false
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.library)
|
||||
alias(libs.plugins.kotlin.android)
|
||||
alias(libs.plugins.kotlin.serialization)
|
||||
alias(libs.plugins.hilt)
|
||||
alias(libs.plugins.ksp)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.heimdall.mobile.data"
|
||||
compileSdk = libs.versions.compileSdk.get().toInt()
|
||||
|
||||
defaultConfig {
|
||||
minSdk = libs.versions.minSdk.get().toInt()
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
kotlinOptions { jvmTarget = "17" }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":domain"))
|
||||
|
||||
// Ktor
|
||||
implementation(libs.ktor.client.android)
|
||||
implementation(libs.ktor.client.content.negotiation)
|
||||
implementation(libs.ktor.client.serialization)
|
||||
implementation(libs.ktor.client.websockets)
|
||||
implementation(libs.ktor.client.logging)
|
||||
|
||||
// Serialization
|
||||
implementation(libs.serialization.json)
|
||||
|
||||
// Room
|
||||
implementation(libs.room.runtime)
|
||||
implementation(libs.room.ktx)
|
||||
ksp(libs.room.compiler)
|
||||
|
||||
// DataStore
|
||||
implementation(libs.datastore.preferences)
|
||||
|
||||
// Coil
|
||||
implementation(libs.coil.compose)
|
||||
|
||||
// Coroutines
|
||||
implementation(libs.coroutines.core)
|
||||
implementation(libs.coroutines.android)
|
||||
|
||||
// Hilt
|
||||
implementation(libs.hilt.android)
|
||||
ksp(libs.hilt.compiler)
|
||||
|
||||
// SignalR
|
||||
implementation(libs.signalr.client)
|
||||
|
||||
// Testing
|
||||
testImplementation(libs.junit5.api)
|
||||
testImplementation(libs.junit5.engine)
|
||||
testImplementation(libs.mockk)
|
||||
testImplementation(libs.turbine)
|
||||
testImplementation(libs.coroutines.test)
|
||||
testImplementation(libs.ktor.client.mock)
|
||||
}
|
||||
|
||||
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
|
||||
compilerOptions { }
|
||||
}
|
||||
|
||||
tasks.withType<Test> {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.heimdall.mobile.data.api
|
||||
|
||||
import com.heimdall.mobile.domain.model.AuthTokens
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class LoginRequest(
|
||||
val email: String,
|
||||
val password: String
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class LoginResponse(
|
||||
val accessToken: String,
|
||||
@SerialName("access_token") val accessTokenSnake: String? = null,
|
||||
val refreshToken: String,
|
||||
@SerialName("refresh_token") val refreshTokenSnake: String? = null,
|
||||
val expiresIn: Long
|
||||
) {
|
||||
fun toAuthTokens(): AuthTokens = AuthTokens(
|
||||
accessToken = accessToken.ifEmpty { accessTokenSnake ?: "" },
|
||||
refreshToken = refreshToken.ifEmpty { refreshTokenSnake ?: "" },
|
||||
expiresIn = expiresIn
|
||||
)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class TwoFactorRequest(
|
||||
val code: String
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class TwoFactorResponse(
|
||||
val accessToken: String,
|
||||
val refreshToken: String,
|
||||
val expiresIn: Long
|
||||
) {
|
||||
fun toAuthTokens(): AuthTokens = AuthTokens(
|
||||
accessToken = accessToken,
|
||||
refreshToken = refreshToken,
|
||||
expiresIn = expiresIn
|
||||
)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class RefreshRequest(
|
||||
val refreshToken: String
|
||||
)
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.heimdall.mobile.data.api
|
||||
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.call.body
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.client.request.parameter
|
||||
|
||||
class HeimdallApi(private val client: HttpClient) {
|
||||
|
||||
// Sites
|
||||
suspend fun getSites(): ApiResponse<SitesResponse> =
|
||||
client.get("api/sites").body()
|
||||
|
||||
// Cameras
|
||||
suspend fun getCamerasBySite(siteId: String): ApiResponse<CamerasResponse> =
|
||||
client.get("api/sites/$siteId/cameras").body()
|
||||
|
||||
// Events
|
||||
suspend fun getEvents(
|
||||
siteId: String? = null,
|
||||
limit: Int = 50
|
||||
): ApiResponse<EventsResponse> =
|
||||
client.get("api/events") {
|
||||
siteId?.let { parameter("siteId", it) }
|
||||
parameter("limit", limit)
|
||||
}.body()
|
||||
|
||||
// Camera snapshot
|
||||
suspend fun getCameraSnapshot(cameraId: String): ApiResponse<Map<String, String>> =
|
||||
client.get("api/cameras/$cameraId/snapshot").body()
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.heimdall.mobile.data.api
|
||||
|
||||
import com.heimdall.mobile.domain.model.Camera
|
||||
import com.heimdall.mobile.domain.model.CameraEvent
|
||||
import com.heimdall.mobile.domain.model.Site
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class ApiResponse<T>(
|
||||
val success: Boolean,
|
||||
val data: T? = null,
|
||||
val message: String? = null
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class SitesResponse(
|
||||
val sites: List<Site>
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class CamerasResponse(
|
||||
val cameras: List<Camera>
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class EventsResponse(
|
||||
val events: List<CameraEvent>
|
||||
)
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.heimdall.mobile.data.cache
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
@Entity(tableName = "cached_sites")
|
||||
data class CachedSiteEntity(
|
||||
@PrimaryKey val id: String,
|
||||
val name: String,
|
||||
val description: String?,
|
||||
val isOnline: Boolean,
|
||||
val cameraCount: Int,
|
||||
val agentCount: Int,
|
||||
val lastHeartbeat: String?,
|
||||
val cachedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
@Entity(tableName = "cached_cameras")
|
||||
data class CachedCameraEntity(
|
||||
@PrimaryKey val id: String,
|
||||
val name: String,
|
||||
val siteId: String,
|
||||
val rtspUrl: String?,
|
||||
val isOnline: Boolean,
|
||||
val snapshotUrl: String?,
|
||||
val webrtcEnabled: Boolean,
|
||||
val cachedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
@Entity(tableName = "cached_events")
|
||||
data class CachedEventEntity(
|
||||
@PrimaryKey val id: String,
|
||||
val cameraId: String,
|
||||
val cameraName: String?,
|
||||
val siteId: String,
|
||||
val type: String,
|
||||
val description: String?,
|
||||
val snapshotUrl: String?,
|
||||
val createdAt: String,
|
||||
val severity: String,
|
||||
val cachedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.heimdall.mobile.data.cache
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
|
||||
@Dao
|
||||
interface SiteDao {
|
||||
@Query("SELECT * FROM cached_sites ORDER BY name ASC")
|
||||
suspend fun getAll(): List<CachedSiteEntity>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertAll(sites: List<CachedSiteEntity>)
|
||||
|
||||
@Query("DELETE FROM cached_sites")
|
||||
suspend fun deleteAll()
|
||||
|
||||
@Query("SELECT * FROM cached_sites WHERE id = :id")
|
||||
suspend fun getById(id: String): CachedSiteEntity?
|
||||
}
|
||||
|
||||
@Dao
|
||||
interface CameraDao {
|
||||
@Query("SELECT * FROM cached_cameras WHERE siteId = :siteId ORDER BY name ASC")
|
||||
suspend fun getBySiteId(siteId: String): List<CachedCameraEntity>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertAll(cameras: List<CachedCameraEntity>)
|
||||
|
||||
@Query("DELETE FROM cached_cameras WHERE siteId = :siteId")
|
||||
suspend fun deleteBySiteId(siteId: String)
|
||||
|
||||
@Query("SELECT * FROM cached_cameras WHERE id = :id")
|
||||
suspend fun getById(id: String): CachedCameraEntity?
|
||||
}
|
||||
|
||||
@Dao
|
||||
interface EventDao {
|
||||
@Query("SELECT * FROM cached_events ORDER BY createdAt DESC LIMIT :limit")
|
||||
suspend fun getAll(limit: Int = 50): List<CachedEventEntity>
|
||||
|
||||
@Query("SELECT * FROM cached_events WHERE siteId = :siteId ORDER BY createdAt DESC LIMIT :limit")
|
||||
suspend fun getBySiteId(siteId: String, limit: Int = 50): List<CachedEventEntity>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertAll(events: List<CachedEventEntity>)
|
||||
|
||||
@Query("DELETE FROM cached_events")
|
||||
suspend fun deleteAll()
|
||||
|
||||
@Query("SELECT * FROM cached_events WHERE id = :id")
|
||||
suspend fun getById(id: String): CachedEventEntity?
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.heimdall.mobile.data.cache
|
||||
|
||||
import androidx.room.Database
|
||||
import androidx.room.RoomDatabase
|
||||
|
||||
@Database(
|
||||
entities = [
|
||||
CachedSiteEntity::class,
|
||||
CachedCameraEntity::class,
|
||||
CachedEventEntity::class
|
||||
],
|
||||
version = 1,
|
||||
exportSchema = false
|
||||
)
|
||||
abstract class HeimdallDatabase : RoomDatabase() {
|
||||
abstract fun siteDao(): SiteDao
|
||||
abstract fun cameraDao(): CameraDao
|
||||
abstract fun eventDao(): EventDao
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package com.heimdall.mobile.data.repository
|
||||
|
||||
import com.heimdall.mobile.data.api.HeimdallApi
|
||||
import com.heimdall.mobile.data.api.LoginRequest
|
||||
import com.heimdall.mobile.data.api.RefreshRequest
|
||||
import com.heimdall.mobile.data.api.TwoFactorRequest
|
||||
import com.heimdall.mobile.domain.model.AuthTokens
|
||||
import com.heimdall.mobile.domain.repository.AuthRepository
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.request.post
|
||||
import io.ktor.client.request.setBody
|
||||
import io.ktor.client.request.url
|
||||
import io.ktor.client.call.body
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.http.contentType
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Singleton
|
||||
class AuthRepositoryImpl @Inject constructor(
|
||||
private val client: HttpClient
|
||||
) : AuthRepository {
|
||||
|
||||
private var currentTokens: AuthTokens? = null
|
||||
private var serverUrl: String = ""
|
||||
|
||||
fun setServerUrl(url: String) {
|
||||
serverUrl = url.trimEnd('/')
|
||||
}
|
||||
|
||||
override suspend fun login(email: String, password: String): Result<AuthTokens> {
|
||||
return try {
|
||||
val response: Map<String, kotlinx.serialization.json.JsonElement> = client.post {
|
||||
url("$serverUrl/api/auth/login")
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(LoginRequest(email, password))
|
||||
}.body()
|
||||
|
||||
val accessToken = response["accessToken"]?.toString()?.trim('"') ?: ""
|
||||
val refreshToken = response["refreshToken"]?.toString()?.trim('"') ?: ""
|
||||
val expiresIn = response["expiresIn"]?.toString()?.toLongOrNull() ?: 3600L
|
||||
val requiresTwoFactor = response["requiresTwoFactor"]?.toString()?.toBooleanStrictOrNull() ?: false
|
||||
|
||||
if (requiresTwoFactor) {
|
||||
val partialToken = response["partialToken"]?.toString()?.trim('"') ?: ""
|
||||
Result.success(AuthTokens(accessToken = partialToken, refreshToken = "", expiresIn = 0))
|
||||
} else {
|
||||
val tokens = AuthTokens(accessToken = accessToken, refreshToken = refreshToken, expiresIn = expiresIn)
|
||||
currentTokens = tokens
|
||||
Result.success(tokens)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun verifyTwoFactor(code: String): Result<AuthTokens> {
|
||||
return try {
|
||||
val response: Map<String, kotlinx.serialization.json.JsonElement> = client.post {
|
||||
url("$serverUrl/api/auth/2fa/verify")
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(TwoFactorRequest(code))
|
||||
}.body()
|
||||
|
||||
val accessToken = response["accessToken"]?.toString()?.trim('"') ?: ""
|
||||
val refreshToken = response["refreshToken"]?.toString()?.trim('"') ?: ""
|
||||
val expiresIn = response["expiresIn"]?.toString()?.toLongOrNull() ?: 3600L
|
||||
val tokens = AuthTokens(accessToken = accessToken, refreshToken = refreshToken, expiresIn = expiresIn)
|
||||
currentTokens = tokens
|
||||
Result.success(tokens)
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun refreshToken(refreshToken: String): Result<AuthTokens> {
|
||||
return try {
|
||||
val response: Map<String, kotlinx.serialization.json.JsonElement> = client.post {
|
||||
url("$serverUrl/api/auth/refresh")
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(RefreshRequest(refreshToken))
|
||||
}.body()
|
||||
|
||||
val accessToken = response["accessToken"]?.toString()?.trim('"') ?: ""
|
||||
val newRefreshToken = response["refreshToken"]?.toString()?.trim('"') ?: ""
|
||||
val expiresIn = response["expiresIn"]?.toString()?.toLongOrNull() ?: 3600L
|
||||
val tokens = AuthTokens(accessToken = accessToken, refreshToken = newRefreshToken, expiresIn = expiresIn)
|
||||
currentTokens = tokens
|
||||
Result.success(tokens)
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun logout() {
|
||||
currentTokens = null
|
||||
}
|
||||
|
||||
override suspend fun isLoggedIn(): Boolean {
|
||||
return currentTokens?.accessToken?.isNotEmpty() == true
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.heimdall.mobile.data.repository
|
||||
|
||||
import com.heimdall.mobile.data.api.HeimdallApi
|
||||
import com.heimdall.mobile.data.cache.CameraDao
|
||||
import com.heimdall.mobile.data.cache.CachedCameraEntity
|
||||
import com.heimdall.mobile.domain.model.Camera
|
||||
import com.heimdall.mobile.domain.repository.CameraRepository
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.flow
|
||||
|
||||
class CameraRepositoryImpl(
|
||||
private val api: HeimdallApi,
|
||||
private val cameraDao: CameraDao
|
||||
) : CameraRepository {
|
||||
|
||||
override fun getCamerasBySite(siteId: String): Flow<List<Camera>> = flow {
|
||||
// Emit cache first
|
||||
val cached = cameraDao.getBySiteId(siteId).map { it.toDomain() }
|
||||
if (cached.isNotEmpty()) emit(cached)
|
||||
}
|
||||
|
||||
override suspend fun refreshCameras(siteId: String): Result<List<Camera>> {
|
||||
return try {
|
||||
val response = api.getCamerasBySite(siteId)
|
||||
if (response.success && response.data != null) {
|
||||
val cameras = response.data.cameras
|
||||
cameraDao.deleteBySiteId(siteId)
|
||||
cameraDao.insertAll(cameras.map { it.toCacheEntity(siteId) })
|
||||
Result.success(cameras)
|
||||
} else {
|
||||
Result.failure(Exception(response.message ?: "Failed to load cameras"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// Fallback to cache
|
||||
val cached = cameraDao.getBySiteId(siteId).map { it.toDomain() }
|
||||
if (cached.isNotEmpty()) Result.success(cached)
|
||||
else Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getCameraById(id: String): Camera? =
|
||||
cameraDao.getById(id)?.toDomain()
|
||||
}
|
||||
|
||||
private fun Camera.toCacheEntity(siteId: String) = CachedCameraEntity(
|
||||
id = id, name = name, siteId = siteId, rtspUrl = rtspUrl,
|
||||
isOnline = isOnline, snapshotUrl = snapshotUrl, webrtcEnabled = webrtcEnabled
|
||||
)
|
||||
|
||||
private fun CachedCameraEntity.toDomain() = Camera(
|
||||
id = id, name = name, siteId = siteId, rtspUrl = rtspUrl,
|
||||
isOnline = isOnline, snapshotUrl = snapshotUrl, webrtcEnabled = webrtcEnabled
|
||||
)
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.heimdall.mobile.data.repository
|
||||
|
||||
import com.heimdall.mobile.data.api.HeimdallApi
|
||||
import com.heimdall.mobile.data.cache.EventDao
|
||||
import com.heimdall.mobile.data.cache.CachedEventEntity
|
||||
import com.heimdall.mobile.domain.model.CameraEvent
|
||||
import com.heimdall.mobile.domain.repository.EventRepository
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.flow
|
||||
|
||||
class EventRepositoryImpl(
|
||||
private val api: HeimdallApi,
|
||||
private val eventDao: EventDao
|
||||
) : EventRepository {
|
||||
|
||||
override fun getEvents(siteId: String?, limit: Int): Flow<List<CameraEvent>> = flow {
|
||||
val cached = if (siteId != null) {
|
||||
eventDao.getBySiteId(siteId, limit).map { it.toDomain() }
|
||||
} else {
|
||||
eventDao.getAll(limit).map { it.toDomain() }
|
||||
}
|
||||
if (cached.isNotEmpty()) emit(cached)
|
||||
}
|
||||
|
||||
override suspend fun refreshEvents(siteId: String?, limit: Int): Result<List<CameraEvent>> {
|
||||
return try {
|
||||
val response = api.getEvents(siteId, limit)
|
||||
if (response.success && response.data != null) {
|
||||
val events = response.data.events
|
||||
eventDao.deleteAll()
|
||||
eventDao.insertAll(events.map { it.toCacheEntity() })
|
||||
Result.success(events)
|
||||
} else {
|
||||
Result.failure(Exception(response.message ?: "Failed to load events"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
val cached = if (siteId != null) {
|
||||
eventDao.getBySiteId(siteId, limit).map { it.toDomain() }
|
||||
} else {
|
||||
eventDao.getAll(limit).map { it.toDomain() }
|
||||
}
|
||||
if (cached.isNotEmpty()) Result.success(cached)
|
||||
else Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getEventById(id: String): CameraEvent? =
|
||||
eventDao.getById(id)?.toDomain()
|
||||
}
|
||||
|
||||
private fun CameraEvent.toCacheEntity() = CachedEventEntity(
|
||||
id = id, cameraId = cameraId, cameraName = cameraName, siteId = siteId,
|
||||
type = type, description = description, snapshotUrl = snapshotUrl,
|
||||
createdAt = createdAt, severity = severity
|
||||
)
|
||||
|
||||
private fun CachedEventEntity.toDomain() = CameraEvent(
|
||||
id = id, cameraId = cameraId, cameraName = cameraName, siteId = siteId,
|
||||
type = type, description = description, snapshotUrl = snapshotUrl,
|
||||
createdAt = createdAt, severity = severity
|
||||
)
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.heimdall.mobile.data.repository
|
||||
|
||||
import com.heimdall.mobile.data.api.HeimdallApi
|
||||
import com.heimdall.mobile.data.cache.SiteDao
|
||||
import com.heimdall.mobile.data.cache.CachedSiteEntity
|
||||
import com.heimdall.mobile.domain.model.Site
|
||||
import com.heimdall.mobile.domain.repository.SiteRepository
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.flow
|
||||
|
||||
class SiteRepositoryImpl(
|
||||
private val api: HeimdallApi,
|
||||
private val siteDao: SiteDao
|
||||
) : SiteRepository {
|
||||
|
||||
override fun getSites(): Flow<List<Site>> = flow {
|
||||
val cached = siteDao.getAll().map { it.toDomain() }
|
||||
if (cached.isNotEmpty()) emit(cached)
|
||||
}
|
||||
|
||||
override suspend fun refreshSites(): Result<List<Site>> {
|
||||
return try {
|
||||
val response = api.getSites()
|
||||
if (response.success && response.data != null) {
|
||||
val sites = response.data.sites
|
||||
siteDao.deleteAll()
|
||||
siteDao.insertAll(sites.map { it.toCacheEntity() })
|
||||
Result.success(sites)
|
||||
} else {
|
||||
Result.failure(Exception(response.message ?: "Failed to load sites"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
val cached = siteDao.getAll().map { it.toDomain() }
|
||||
if (cached.isNotEmpty()) Result.success(cached)
|
||||
else Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getSiteById(id: String): Site? =
|
||||
siteDao.getById(id)?.toDomain()
|
||||
}
|
||||
|
||||
private fun Site.toCacheEntity() = CachedSiteEntity(
|
||||
id = id, name = name, description = description, isOnline = isOnline,
|
||||
cameraCount = cameraCount, agentCount = agentCount, lastHeartbeat = lastHeartbeat
|
||||
)
|
||||
|
||||
private fun CachedSiteEntity.toDomain() = Site(
|
||||
id = id, name = name, description = description, isOnline = isOnline,
|
||||
cameraCount = cameraCount, agentCount = agentCount, lastHeartbeat = lastHeartbeat
|
||||
)
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.heimdall.mobile.di
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Room
|
||||
import com.heimdall.mobile.data.cache.CameraDao
|
||||
import com.heimdall.mobile.data.cache.EventDao
|
||||
import com.heimdall.mobile.data.cache.HeimdallDatabase
|
||||
import com.heimdall.mobile.data.cache.SiteDao
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
object DatabaseModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideDatabase(@ApplicationContext context: Context): HeimdallDatabase {
|
||||
return Room.databaseBuilder(
|
||||
context,
|
||||
HeimdallDatabase::class.java,
|
||||
"heimdall_cache.db"
|
||||
).build()
|
||||
}
|
||||
|
||||
@Provides fun provideSiteDao(db: HeimdallDatabase): SiteDao = db.siteDao()
|
||||
@Provides fun provideCameraDao(db: HeimdallDatabase): CameraDao = db.cameraDao()
|
||||
@Provides fun provideEventDao(db: HeimdallDatabase): EventDao = db.eventDao()
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.heimdall.mobile.di
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.engine.android.Android
|
||||
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
|
||||
import io.ktor.client.plugins.defaultRequest
|
||||
import io.ktor.client.plugins.logging.LogLevel
|
||||
import io.ktor.client.plugins.logging.Logger
|
||||
import io.ktor.client.plugins.logging.Logging
|
||||
import io.ktor.serialization.kotlinx.json.json
|
||||
import kotlinx.serialization.json.Json
|
||||
import javax.inject.Singleton
|
||||
|
||||
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
|
||||
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
object NetworkModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideJson(): Json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
isLenient = true
|
||||
coerceInputValues = true
|
||||
prettyPrint = false
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideHttpClient(json: Json, @ApplicationContext context: Context): HttpClient {
|
||||
return HttpClient(Android) {
|
||||
install(ContentNegotiation) {
|
||||
json(json)
|
||||
}
|
||||
install(Logging) {
|
||||
logger = object : Logger {
|
||||
override fun log(message: String) {
|
||||
android.util.Log.d("Ktor", message)
|
||||
}
|
||||
}
|
||||
level = LogLevel.BODY
|
||||
}
|
||||
defaultRequest {
|
||||
// Base URL will be configured from DataStore preferences
|
||||
// url("https://your-heimdall-instance.com/")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideDataStore(@ApplicationContext context: Context): DataStore<Preferences> {
|
||||
return context.dataStore
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.heimdall.mobile.di
|
||||
|
||||
import com.heimdall.mobile.data.api.HeimdallApi
|
||||
import com.heimdall.mobile.data.cache.CameraDao
|
||||
import com.heimdall.mobile.data.cache.EventDao
|
||||
import com.heimdall.mobile.data.cache.SiteDao
|
||||
import com.heimdall.mobile.data.repository.AuthRepositoryImpl
|
||||
import com.heimdall.mobile.data.repository.CameraRepositoryImpl
|
||||
import com.heimdall.mobile.data.repository.EventRepositoryImpl
|
||||
import com.heimdall.mobile.data.repository.SiteRepositoryImpl
|
||||
import com.heimdall.mobile.domain.repository.AuthRepository
|
||||
import com.heimdall.mobile.domain.repository.CameraRepository
|
||||
import com.heimdall.mobile.domain.repository.EventRepository
|
||||
import com.heimdall.mobile.domain.repository.SiteRepository
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import io.ktor.client.HttpClient
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
object RepositoryModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideHeimdallApi(client: HttpClient): HeimdallApi {
|
||||
return HeimdallApi(client)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideAuthRepository(client: HttpClient): AuthRepository {
|
||||
return AuthRepositoryImpl(client)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideSiteRepository(api: HeimdallApi, siteDao: SiteDao): SiteRepository {
|
||||
return SiteRepositoryImpl(api, siteDao)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideCameraRepository(api: HeimdallApi, cameraDao: CameraDao): CameraRepository {
|
||||
return CameraRepositoryImpl(api, cameraDao)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideEventRepository(api: HeimdallApi, eventDao: EventDao): EventRepository {
|
||||
return EventRepositoryImpl(api, eventDao)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.heimdall.mobile.di
|
||||
|
||||
import com.heimdall.mobile.domain.repository.AuthRepository
|
||||
import com.heimdall.mobile.domain.repository.CameraRepository
|
||||
import com.heimdall.mobile.domain.repository.EventRepository
|
||||
import com.heimdall.mobile.domain.repository.SiteRepository
|
||||
import com.heimdall.mobile.domain.usecase.*
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
object UseCaseModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideLoginUseCase(repository: AuthRepository): LoginUseCase =
|
||||
LoginUseCase(repository)
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideVerifyTwoFactorUseCase(repository: AuthRepository): VerifyTwoFactorUseCase =
|
||||
VerifyTwoFactorUseCase(repository)
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideLogoutUseCase(repository: AuthRepository): LogoutUseCase =
|
||||
LogoutUseCase(repository)
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideIsLoggedInUseCase(repository: AuthRepository): IsLoggedInUseCase =
|
||||
IsLoggedInUseCase(repository)
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideGetSitesUseCase(repository: SiteRepository): GetSitesUseCase =
|
||||
GetSitesUseCase(repository)
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideRefreshSitesUseCase(repository: SiteRepository): RefreshSitesUseCase =
|
||||
RefreshSitesUseCase(repository)
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideGetCamerasBySiteUseCase(repository: CameraRepository): GetCamerasBySiteUseCase =
|
||||
GetCamerasBySiteUseCase(repository)
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideRefreshCamerasUseCase(repository: CameraRepository): RefreshCamerasUseCase =
|
||||
RefreshCamerasUseCase(repository)
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideGetEventsUseCase(repository: EventRepository): GetEventsUseCase =
|
||||
GetEventsUseCase(repository)
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideRefreshEventsUseCase(repository: EventRepository): RefreshEventsUseCase =
|
||||
RefreshEventsUseCase(repository)
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package com.heimdall.mobile.data.repository
|
||||
|
||||
import com.heimdall.mobile.domain.model.AuthTokens
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.engine.mock.MockEngine
|
||||
import io.ktor.client.engine.mock.MockRequestHandleScope
|
||||
import io.ktor.client.engine.mock.respond
|
||||
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
|
||||
import io.ktor.client.request.HttpRequestData
|
||||
import io.ktor.client.request.HttpResponseData
|
||||
import io.ktor.http.HttpHeaders
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.http.headersOf
|
||||
import io.ktor.serialization.kotlinx.json.json
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertFalse
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class AuthRepositoryImplTest {
|
||||
|
||||
private fun buildClient(
|
||||
handler: suspend MockRequestHandleScope.(HttpRequestData) -> HttpResponseData
|
||||
): HttpClient {
|
||||
val json = Json { ignoreUnknownKeys = true; isLenient = true; coerceInputValues = true }
|
||||
return HttpClient(MockEngine { request -> handler(request) }) {
|
||||
install(ContentNegotiation) { json(json) }
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun MockRequestHandleScope.jsonOk(body: String): HttpResponseData =
|
||||
respond(
|
||||
content = body,
|
||||
status = HttpStatusCode.OK,
|
||||
headers = headersOf(HttpHeaders.ContentType, "application/json")
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `login_success_returns_tokens_and_sets_currentTokens`() = runTest {
|
||||
val client = buildClient { jsonOk("""{"accessToken":"abc","refreshToken":"def","expiresIn":3600}""") }
|
||||
val repo = AuthRepositoryImpl(client)
|
||||
|
||||
val result = repo.login("user@example.com", "pass")
|
||||
|
||||
assertTrue(result.isSuccess)
|
||||
assertEquals(AuthTokens("abc", "def", 3600L), result.getOrNull())
|
||||
assertTrue(repo.isLoggedIn())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `login_with_requires_two_factor_returns_partial_token_in_accessToken`() = runTest {
|
||||
val client = buildClient { jsonOk("""{"requiresTwoFactor":true,"partialToken":"partial_jwt"}""") }
|
||||
val repo = AuthRepositoryImpl(client)
|
||||
|
||||
val result = repo.login("user@example.com", "pass")
|
||||
|
||||
assertTrue(result.isSuccess)
|
||||
assertEquals("partial_jwt", result.getOrNull()?.accessToken)
|
||||
assertEquals("", result.getOrNull()?.refreshToken)
|
||||
assertEquals(0L, result.getOrNull()?.expiresIn)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `verify_two_factor_success_returns_tokens`() = runTest {
|
||||
val client = buildClient { jsonOk("""{"accessToken":"abc2fa","refreshToken":"def2fa","expiresIn":3600}""") }
|
||||
val repo = AuthRepositoryImpl(client)
|
||||
|
||||
val result = repo.verifyTwoFactor("123456")
|
||||
|
||||
assertTrue(result.isSuccess)
|
||||
assertEquals(AuthTokens("abc2fa", "def2fa", 3600L), result.getOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `refresh_token_success_returns_new_tokens`() = runTest {
|
||||
val client = buildClient { jsonOk("""{"accessToken":"new_access","refreshToken":"new_refresh","expiresIn":3600}""") }
|
||||
val repo = AuthRepositoryImpl(client)
|
||||
|
||||
val result = repo.refreshToken("old_refresh")
|
||||
|
||||
assertTrue(result.isSuccess)
|
||||
assertEquals(AuthTokens("new_access", "new_refresh", 3600L), result.getOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `login_network_error_returns_failure`() = runTest {
|
||||
val client = buildClient { throw java.io.IOException("connection refused") }
|
||||
val repo = AuthRepositoryImpl(client)
|
||||
|
||||
val result = repo.login("user@example.com", "pass")
|
||||
|
||||
assertTrue(result.isFailure)
|
||||
assertTrue(result.exceptionOrNull() is java.io.IOException)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `setServerUrl_used_in_request_path`() = runTest {
|
||||
var calledPath: String? = null
|
||||
val client = buildClient { request ->
|
||||
calledPath = request.url.toString()
|
||||
jsonOk("""{"accessToken":"a","refreshToken":"r","expiresIn":3600}""")
|
||||
}
|
||||
val repo = AuthRepositoryImpl(client)
|
||||
repo.setServerUrl("https://heimdall.example.com")
|
||||
|
||||
repo.login("u@e.com", "p")
|
||||
|
||||
assertTrue(calledPath!!.startsWith("https://heimdall.example.com/api/auth/login"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `logout_clears_tokens`() = runTest {
|
||||
val client = buildClient { jsonOk("""{"accessToken":"abc","refreshToken":"def","expiresIn":3600}""") }
|
||||
val repo = AuthRepositoryImpl(client)
|
||||
repo.login("u@e.com", "p")
|
||||
assertTrue(repo.isLoggedIn())
|
||||
|
||||
repo.logout()
|
||||
|
||||
assertFalse(repo.isLoggedIn())
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package com.heimdall.mobile.data.repository
|
||||
|
||||
import com.heimdall.mobile.data.api.ApiResponse
|
||||
import com.heimdall.mobile.data.api.CamerasResponse
|
||||
import com.heimdall.mobile.data.api.HeimdallApi
|
||||
import com.heimdall.mobile.data.cache.CachedCameraEntity
|
||||
import com.heimdall.mobile.data.cache.CameraDao
|
||||
import com.heimdall.mobile.domain.model.Camera
|
||||
import io.mockk.coEvery
|
||||
import io.mockk.coVerify
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class CameraRepositoryImplTest {
|
||||
|
||||
private val api: HeimdallApi = mockk()
|
||||
private val cameraDao: CameraDao = mockk()
|
||||
|
||||
private val domainCamera = Camera("c1", "Cam 1", "s1", "rtsp://x", true, "http://snap", true)
|
||||
private val cachedEntity = CachedCameraEntity(
|
||||
id = "c1", name = "Cam 1", siteId = "s1", rtspUrl = "rtsp://x",
|
||||
isOnline = true, snapshotUrl = "http://snap", webrtcEnabled = true
|
||||
)
|
||||
|
||||
@BeforeEach
|
||||
fun setUp() = io.mockk.clearAllMocks()
|
||||
|
||||
@Test
|
||||
fun `getCamerasBySite_emits_cached_from_dao`() = runTest {
|
||||
coEvery { cameraDao.getBySiteId("s1") } returns listOf(cachedEntity)
|
||||
val repo = CameraRepositoryImpl(api, cameraDao)
|
||||
|
||||
val result = repo.getCamerasBySite("s1").first()
|
||||
|
||||
assertEquals(listOf(domainCamera), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `refreshCameras_success_persists_and_returns`() = runTest {
|
||||
coEvery { api.getCamerasBySite("s1") } returns ApiResponse(true, CamerasResponse(listOf(domainCamera)))
|
||||
coEvery { cameraDao.getBySiteId("s1") } returns emptyList()
|
||||
coEvery { cameraDao.deleteBySiteId("s1") } returns Unit
|
||||
coEvery { cameraDao.insertAll(any()) } returns Unit
|
||||
val repo = CameraRepositoryImpl(api, cameraDao)
|
||||
|
||||
val result = repo.refreshCameras("s1")
|
||||
|
||||
assertTrue(result.isSuccess)
|
||||
assertEquals(listOf(domainCamera), result.getOrNull())
|
||||
coVerify { cameraDao.deleteBySiteId("s1") }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `refreshCameras_api_error_returns_failure`() = runTest {
|
||||
coEvery { api.getCamerasBySite("s1") } returns ApiResponse(false, message = "Failed")
|
||||
coEvery { cameraDao.getBySiteId("s1") } returns emptyList()
|
||||
val repo = CameraRepositoryImpl(api, cameraDao)
|
||||
|
||||
val result = repo.refreshCameras("s1")
|
||||
|
||||
assertTrue(result.isFailure)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `refreshCameras_network_exception_falls_back_to_cache`() = runTest {
|
||||
coEvery { api.getCamerasBySite("s1") } throws java.io.IOException("offline")
|
||||
coEvery { cameraDao.getBySiteId("s1") } returns listOf(cachedEntity)
|
||||
val repo = CameraRepositoryImpl(api, cameraDao)
|
||||
|
||||
val result = repo.refreshCameras("s1")
|
||||
|
||||
assertTrue(result.isSuccess)
|
||||
assertEquals(listOf(domainCamera), result.getOrNull())
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package com.heimdall.mobile.data.repository
|
||||
|
||||
import com.heimdall.mobile.data.api.ApiResponse
|
||||
import com.heimdall.mobile.data.api.EventsResponse
|
||||
import com.heimdall.mobile.data.api.HeimdallApi
|
||||
import com.heimdall.mobile.data.cache.CachedEventEntity
|
||||
import com.heimdall.mobile.data.cache.EventDao
|
||||
import com.heimdall.mobile.domain.model.CameraEvent
|
||||
import io.mockk.coEvery
|
||||
import io.mockk.coVerify
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class EventRepositoryImplTest {
|
||||
|
||||
private val api: HeimdallApi = mockk()
|
||||
private val eventDao: EventDao = mockk()
|
||||
|
||||
private val domainEvent = CameraEvent(
|
||||
id = "e1", cameraId = "c1", cameraName = "Cam 1", siteId = "s1",
|
||||
type = "motion", description = "Movement", snapshotUrl = null,
|
||||
createdAt = "2026-08-28T10:00:00Z", severity = "high"
|
||||
)
|
||||
private val cachedEntity = CachedEventEntity(
|
||||
id = "e1", cameraId = "c1", cameraName = "Cam 1", siteId = "s1",
|
||||
type = "motion", description = "Movement", snapshotUrl = null,
|
||||
createdAt = "2026-08-28T10:00:00Z", severity = "high"
|
||||
)
|
||||
|
||||
@BeforeEach
|
||||
fun setUp() = io.mockk.clearAllMocks()
|
||||
|
||||
@Test
|
||||
fun `getEvents_with_site_emits_cached_from_dao`() = runTest {
|
||||
coEvery { eventDao.getBySiteId("s1", 50) } returns listOf(cachedEntity)
|
||||
val repo = EventRepositoryImpl(api, eventDao)
|
||||
|
||||
val result = repo.getEvents("s1", 50).first()
|
||||
|
||||
assertEquals(listOf(domainEvent), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getEvents_without_site_uses_all`() = runTest {
|
||||
coEvery { eventDao.getAll(50) } returns listOf(cachedEntity)
|
||||
val repo = EventRepositoryImpl(api, eventDao)
|
||||
|
||||
val result = repo.getEvents(null, 50).first()
|
||||
|
||||
assertEquals(listOf(domainEvent), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `refreshEvents_success_persists_and_returns`() = runTest {
|
||||
coEvery { api.getEvents("s1", 50) } returns ApiResponse(true, EventsResponse(listOf(domainEvent)))
|
||||
coEvery { eventDao.getAll(50) } returns emptyList()
|
||||
coEvery { eventDao.deleteAll() } returns Unit
|
||||
coEvery { eventDao.insertAll(any()) } returns Unit
|
||||
val repo = EventRepositoryImpl(api, eventDao)
|
||||
|
||||
val result = repo.refreshEvents("s1", 50)
|
||||
|
||||
assertTrue(result.isSuccess)
|
||||
assertEquals(listOf(domainEvent), result.getOrNull())
|
||||
coVerify { eventDao.deleteAll() }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `refreshEvents_network_exception_falls_back_to_cache`() = runTest {
|
||||
coEvery { api.getEvents(null, 10) } throws java.io.IOException("offline")
|
||||
coEvery { eventDao.getAll(10) } returns listOf(cachedEntity)
|
||||
val repo = EventRepositoryImpl(api, eventDao)
|
||||
|
||||
val result = repo.refreshEvents(null, 10)
|
||||
|
||||
assertTrue(result.isSuccess)
|
||||
assertEquals(listOf(domainEvent), result.getOrNull())
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.heimdall.mobile.data.repository
|
||||
|
||||
import com.heimdall.mobile.data.api.ApiResponse
|
||||
import com.heimdall.mobile.data.api.HeimdallApi
|
||||
import com.heimdall.mobile.data.api.SitesResponse
|
||||
import com.heimdall.mobile.data.cache.CachedSiteEntity
|
||||
import com.heimdall.mobile.data.cache.SiteDao
|
||||
import com.heimdall.mobile.domain.model.Site
|
||||
import io.mockk.coEvery
|
||||
import io.mockk.coVerify
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class SiteRepositoryImplTest {
|
||||
|
||||
private val api: HeimdallApi = mockk()
|
||||
private val siteDao: SiteDao = mockk()
|
||||
|
||||
private val domainSite = Site("1", "Site A", "desc", true, 2, 1, null)
|
||||
private val cachedEntity = CachedSiteEntity(
|
||||
id = "1", name = "Site A", description = "desc", isOnline = true,
|
||||
cameraCount = 2, agentCount = 1, lastHeartbeat = null
|
||||
)
|
||||
|
||||
@BeforeEach
|
||||
fun setUp() = io.mockk.clearAllMocks()
|
||||
|
||||
@Test
|
||||
fun `getSites_emits_cached_domains_from_dao`() = runTest {
|
||||
coEvery { siteDao.getAll() } returns listOf(cachedEntity)
|
||||
val repo = SiteRepositoryImpl(api, siteDao)
|
||||
|
||||
val result = repo.getSites().first()
|
||||
|
||||
assertEquals(listOf(domainSite), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `refreshSites_success_persists_and_returns_domains`() = runTest {
|
||||
coEvery { api.getSites() } returns ApiResponse(success = true, data = SitesResponse(listOf(domainSite)))
|
||||
coEvery { siteDao.getAll() } returns emptyList()
|
||||
coEvery { siteDao.deleteAll() } returns Unit
|
||||
coEvery { siteDao.insertAll(any()) } returns Unit
|
||||
val repo = SiteRepositoryImpl(api, siteDao)
|
||||
|
||||
val result = repo.refreshSites()
|
||||
|
||||
assertTrue(result.isSuccess)
|
||||
assertEquals(listOf(domainSite), result.getOrNull())
|
||||
coVerify { siteDao.deleteAll() }
|
||||
coVerify { siteDao.insertAll(any()) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `refreshSites_api_error_returns_failure`() = runTest {
|
||||
coEvery { api.getSites() } returns ApiResponse(success = false, message = "Failed")
|
||||
coEvery { siteDao.getAll() } returns emptyList()
|
||||
val repo = SiteRepositoryImpl(api, siteDao)
|
||||
|
||||
val result = repo.refreshSites()
|
||||
|
||||
assertTrue(result.isFailure)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `refreshSites_network_exception_falls_back_to_cache`() = runTest {
|
||||
coEvery { api.getSites() } throws java.io.IOException("offline")
|
||||
coEvery { siteDao.getAll() } returns listOf(cachedEntity)
|
||||
val repo = SiteRepositoryImpl(api, siteDao)
|
||||
|
||||
val result = repo.refreshSites()
|
||||
|
||||
assertTrue(result.isSuccess)
|
||||
assertEquals(listOf(domainSite), result.getOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `refreshSites_network_exception_no_cache_returns_failure`() = runTest {
|
||||
coEvery { api.getSites() } throws java.io.IOException("offline")
|
||||
coEvery { siteDao.getAll() } returns emptyList()
|
||||
val repo = SiteRepositoryImpl(api, siteDao)
|
||||
|
||||
val result = repo.refreshSites()
|
||||
|
||||
assertTrue(result.isFailure)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.library)
|
||||
alias(libs.plugins.kotlin.android)
|
||||
alias(libs.plugins.kotlin.serialization)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.heimdall.mobile.domain"
|
||||
compileSdk = libs.versions.compileSdk.get().toInt()
|
||||
|
||||
defaultConfig {
|
||||
minSdk = libs.versions.minSdk.get().toInt()
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
kotlinOptions { jvmTarget = "17" }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(libs.coroutines.core)
|
||||
implementation(libs.serialization.json)
|
||||
|
||||
testImplementation(libs.junit5.api)
|
||||
testImplementation(libs.junit5.engine)
|
||||
testImplementation(libs.mockk)
|
||||
testImplementation(libs.coroutines.test)
|
||||
}
|
||||
|
||||
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
|
||||
compilerOptions { }
|
||||
}
|
||||
|
||||
tasks.withType<Test> {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.heimdall.mobile.domain.model
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class AuthTokens(
|
||||
val accessToken: String,
|
||||
val refreshToken: String,
|
||||
val expiresIn: Long
|
||||
)
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.heimdall.mobile.domain.model
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class Camera(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val siteId: String,
|
||||
val rtspUrl: String?,
|
||||
val isOnline: Boolean,
|
||||
val snapshotUrl: String?,
|
||||
val webrtcEnabled: Boolean
|
||||
)
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.heimdall.mobile.domain.model
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class CameraEvent(
|
||||
val id: String,
|
||||
val cameraId: String,
|
||||
val cameraName: String?,
|
||||
val siteId: String,
|
||||
val type: String,
|
||||
val description: String?,
|
||||
val snapshotUrl: String?,
|
||||
val createdAt: String,
|
||||
val severity: String
|
||||
)
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.heimdall.mobile.domain.model
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class Site(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val description: String?,
|
||||
val isOnline: Boolean,
|
||||
val cameraCount: Int,
|
||||
val agentCount: Int,
|
||||
val lastHeartbeat: String?
|
||||
)
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.heimdall.mobile.domain.model
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class User(
|
||||
val id: String,
|
||||
val email: String,
|
||||
val displayName: String,
|
||||
val role: String,
|
||||
val twoFactorEnabled: Boolean
|
||||
)
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.heimdall.mobile.domain.repository
|
||||
|
||||
import com.heimdall.mobile.domain.model.AuthTokens
|
||||
|
||||
interface AuthRepository {
|
||||
suspend fun login(email: String, password: String): Result<AuthTokens>
|
||||
suspend fun verifyTwoFactor(code: String): Result<AuthTokens>
|
||||
suspend fun refreshToken(refreshToken: String): Result<AuthTokens>
|
||||
suspend fun logout()
|
||||
suspend fun isLoggedIn(): Boolean
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.heimdall.mobile.domain.repository
|
||||
|
||||
import com.heimdall.mobile.domain.model.Camera
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
interface CameraRepository {
|
||||
fun getCamerasBySite(siteId: String): Flow<List<Camera>>
|
||||
suspend fun refreshCameras(siteId: String): Result<List<Camera>>
|
||||
suspend fun getCameraById(id: String): Camera?
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.heimdall.mobile.domain.repository
|
||||
|
||||
import com.heimdall.mobile.domain.model.CameraEvent
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
interface EventRepository {
|
||||
fun getEvents(siteId: String?, limit: Int = 50): Flow<List<CameraEvent>>
|
||||
suspend fun refreshEvents(siteId: String?, limit: Int = 50): Result<List<CameraEvent>>
|
||||
suspend fun getEventById(id: String): CameraEvent?
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.heimdall.mobile.domain.repository
|
||||
|
||||
import com.heimdall.mobile.domain.model.Site
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
interface SiteRepository {
|
||||
fun getSites(): Flow<List<Site>>
|
||||
suspend fun refreshSites(): Result<List<Site>>
|
||||
suspend fun getSiteById(id: String): Site?
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.heimdall.mobile.domain.usecase
|
||||
|
||||
import com.heimdall.mobile.domain.model.AuthTokens
|
||||
import com.heimdall.mobile.domain.repository.AuthRepository
|
||||
|
||||
class LoginUseCase(private val repository: AuthRepository) {
|
||||
suspend operator fun invoke(email: String, password: String): Result<AuthTokens> {
|
||||
return repository.login(email, password)
|
||||
}
|
||||
}
|
||||
|
||||
class VerifyTwoFactorUseCase(private val repository: AuthRepository) {
|
||||
suspend operator fun invoke(code: String): Result<AuthTokens> {
|
||||
return repository.verifyTwoFactor(code)
|
||||
}
|
||||
}
|
||||
|
||||
class LogoutUseCase(private val repository: AuthRepository) {
|
||||
suspend operator fun invoke() {
|
||||
repository.logout()
|
||||
}
|
||||
}
|
||||
|
||||
class IsLoggedInUseCase(private val repository: AuthRepository) {
|
||||
suspend operator fun invoke(): Boolean {
|
||||
return repository.isLoggedIn()
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.heimdall.mobile.domain.usecase
|
||||
|
||||
import com.heimdall.mobile.domain.model.Camera
|
||||
import com.heimdall.mobile.domain.repository.CameraRepository
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
class GetCamerasBySiteUseCase(private val repository: CameraRepository) {
|
||||
operator fun invoke(siteId: String): Flow<List<Camera>> = repository.getCamerasBySite(siteId)
|
||||
}
|
||||
|
||||
class RefreshCamerasUseCase(private val repository: CameraRepository) {
|
||||
suspend operator fun invoke(siteId: String): Result<List<Camera>> = repository.refreshCameras(siteId)
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.heimdall.mobile.domain.usecase
|
||||
|
||||
import com.heimdall.mobile.domain.model.CameraEvent
|
||||
import com.heimdall.mobile.domain.repository.EventRepository
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
class GetEventsUseCase(private val repository: EventRepository) {
|
||||
operator fun invoke(siteId: String? = null, limit: Int = 50): Flow<List<CameraEvent>> =
|
||||
repository.getEvents(siteId, limit)
|
||||
}
|
||||
|
||||
class RefreshEventsUseCase(private val repository: EventRepository) {
|
||||
suspend operator fun invoke(siteId: String? = null, limit: Int = 50): Result<List<CameraEvent>> =
|
||||
repository.refreshEvents(siteId, limit)
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.heimdall.mobile.domain.usecase
|
||||
|
||||
import com.heimdall.mobile.domain.model.Site
|
||||
import com.heimdall.mobile.domain.repository.SiteRepository
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
class GetSitesUseCase(private val repository: SiteRepository) {
|
||||
operator fun invoke(): Flow<List<Site>> = repository.getSites()
|
||||
}
|
||||
|
||||
class RefreshSitesUseCase(private val repository: SiteRepository) {
|
||||
suspend operator fun invoke(): Result<List<Site>> = repository.refreshSites()
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package com.heimdall.mobile.domain.usecase
|
||||
|
||||
import com.heimdall.mobile.domain.model.AuthTokens
|
||||
import com.heimdall.mobile.domain.repository.AuthRepository
|
||||
import io.mockk.coEvery
|
||||
import io.mockk.coVerify
|
||||
import io.mockk.mockk
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertFalse
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class AuthUseCasesTest {
|
||||
|
||||
private val repository: AuthRepository = mockk()
|
||||
|
||||
@BeforeEach
|
||||
fun setUp() {
|
||||
// Réinitialiser les mocks entre les tests (les coEvery sont cumulatifs sinon)
|
||||
io.mockk.clearAllMocks()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `LoginUseCase_returns_success_tokens_from_repository`() = runTest {
|
||||
val tokens = AuthTokens("access", "refresh", 3600L)
|
||||
coEvery { repository.login("user@example.com", "pass") } returns Result.success(tokens)
|
||||
val useCase = LoginUseCase(repository)
|
||||
|
||||
val result = useCase("user@example.com", "pass")
|
||||
|
||||
assertTrue(result.isSuccess)
|
||||
assertEquals(tokens, result.getOrNull())
|
||||
coVerify { repository.login("user@example.com", "pass") }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `LoginUseCase_propagates_repository_failure`() = runTest {
|
||||
val error = IllegalStateException("Identifiants invalides")
|
||||
coEvery { repository.login("bad@example.com", "wrong") } returns Result.failure(error)
|
||||
val useCase = LoginUseCase(repository)
|
||||
|
||||
val result = useCase("bad@example.com", "wrong")
|
||||
|
||||
assertTrue(result.isFailure)
|
||||
assertEquals(error, result.exceptionOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `VerifyTwoFactorUseCase_returns_success_tokens_from_repository`() = runTest {
|
||||
val tokens = AuthTokens("access2fa", "refresh2fa", 3600L)
|
||||
coEvery { repository.verifyTwoFactor("123456") } returns Result.success(tokens)
|
||||
val useCase = VerifyTwoFactorUseCase(repository)
|
||||
|
||||
val result = useCase("123456")
|
||||
|
||||
assertTrue(result.isSuccess)
|
||||
assertEquals(tokens, result.getOrNull())
|
||||
coVerify { repository.verifyTwoFactor("123456") }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `VerifyTwoFactorUseCase_propagates_repository_failure`() = runTest {
|
||||
val error = IllegalStateException("Code incorrect")
|
||||
coEvery { repository.verifyTwoFactor("000000") } returns Result.failure(error)
|
||||
val useCase = VerifyTwoFactorUseCase(repository)
|
||||
|
||||
val result = useCase("000000")
|
||||
|
||||
assertTrue(result.isFailure)
|
||||
assertEquals(error, result.exceptionOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `LogoutUseCase_calls_repository_logout`() = runTest {
|
||||
coEvery { repository.logout() } returns Unit
|
||||
val useCase = LogoutUseCase(repository)
|
||||
|
||||
useCase()
|
||||
|
||||
coVerify { repository.logout() }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `IsLoggedInUseCase_returns_true_when_repository_logged_in`() = runTest {
|
||||
coEvery { repository.isLoggedIn() } returns true
|
||||
val useCase = IsLoggedInUseCase(repository)
|
||||
|
||||
val result = useCase()
|
||||
|
||||
assertTrue(result)
|
||||
coVerify { repository.isLoggedIn() }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `IsLoggedInUseCase_returns_false_when_repository_not_logged_in`() = runTest {
|
||||
coEvery { repository.isLoggedIn() } returns false
|
||||
val useCase = IsLoggedInUseCase(repository)
|
||||
|
||||
val result = useCase()
|
||||
|
||||
assertFalse(result)
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.heimdall.mobile.domain.usecase
|
||||
|
||||
import com.heimdall.mobile.domain.model.Camera
|
||||
import com.heimdall.mobile.domain.repository.CameraRepository
|
||||
import io.mockk.coEvery
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class CameraUseCasesTest {
|
||||
|
||||
private val repository: CameraRepository = mockk()
|
||||
|
||||
@Test
|
||||
fun `GetCamerasBySiteUseCase_forwards_repository_flow_with_site_id`() = runTest {
|
||||
val cameras = listOf(
|
||||
Camera("c1", "Cam 1", "s1", "rtsp://x", true, "http://snap/1", true),
|
||||
Camera("c2", "Cam 2", "s1", null, false, "http://snap/2", false)
|
||||
)
|
||||
every { repository.getCamerasBySite("s1") } returns flowOf(cameras)
|
||||
val useCase = GetCamerasBySiteUseCase(repository)
|
||||
|
||||
val result = useCase("s1").first()
|
||||
|
||||
assertEquals(cameras, result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `RefreshCamerasUseCase_returns_success_cameras_from_repository`() = runTest {
|
||||
val cameras = listOf(Camera("c1", "Cam 1", "s1", null, true, null, true))
|
||||
coEvery { repository.refreshCameras("s1") } returns Result.success(cameras)
|
||||
val useCase = RefreshCamerasUseCase(repository)
|
||||
|
||||
val result = useCase("s1")
|
||||
|
||||
assertTrue(result.isSuccess)
|
||||
assertEquals(cameras, result.getOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `RefreshCamerasUseCase_propagates_repository_failure`() = runTest {
|
||||
val error = IllegalStateException("Timeout")
|
||||
coEvery { repository.refreshCameras("s1") } returns Result.failure(error)
|
||||
val useCase = RefreshCamerasUseCase(repository)
|
||||
|
||||
val result = useCase("s1")
|
||||
|
||||
assertTrue(result.isFailure)
|
||||
assertEquals(error, result.exceptionOrNull())
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.heimdall.mobile.domain.usecase
|
||||
|
||||
import com.heimdall.mobile.domain.model.CameraEvent
|
||||
import com.heimdall.mobile.domain.repository.EventRepository
|
||||
import io.mockk.coEvery
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class EventUseCasesTest {
|
||||
|
||||
private val repository: EventRepository = mockk()
|
||||
|
||||
private fun event(id: String) = CameraEvent(
|
||||
id = id, cameraId = "c1", cameraName = "Cam 1", siteId = "s1",
|
||||
type = "motion", description = "Movement", snapshotUrl = null,
|
||||
createdAt = "2026-08-28T10:00:00Z", severity = "high"
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `GetEventsUseCase_forwards_repository_flow_with_site_filter`() = runTest {
|
||||
val events = listOf(event("e1"), event("e2"))
|
||||
every { repository.getEvents("s1", 50) } returns flowOf(events)
|
||||
val useCase = GetEventsUseCase(repository)
|
||||
|
||||
val result = useCase("s1", 50).first()
|
||||
|
||||
assertEquals(events, result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `GetEventsUseCase_forwards_null_site_filter`() = runTest {
|
||||
val events = listOf(event("e1"))
|
||||
every { repository.getEvents(null, 50) } returns flowOf(events)
|
||||
val useCase = GetEventsUseCase(repository)
|
||||
|
||||
val result = useCase(null, 50).first()
|
||||
|
||||
assertEquals(events, result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `RefreshEventsUseCase_returns_success_events_from_repository`() = runTest {
|
||||
val events = listOf(event("e1"))
|
||||
coEvery { repository.refreshEvents("s1", 50) } returns Result.success(events)
|
||||
val useCase = RefreshEventsUseCase(repository)
|
||||
|
||||
val result = useCase("s1", 50)
|
||||
|
||||
assertTrue(result.isSuccess)
|
||||
assertEquals(events, result.getOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `RefreshEventsUseCase_propagates_repository_failure`() = runTest {
|
||||
val error = IllegalStateException("Server error")
|
||||
coEvery { repository.refreshEvents(null, 10) } returns Result.failure(error)
|
||||
val useCase = RefreshEventsUseCase(repository)
|
||||
|
||||
val result = useCase(null, 10)
|
||||
|
||||
assertTrue(result.isFailure)
|
||||
assertEquals(error, result.exceptionOrNull())
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.heimdall.mobile.domain.usecase
|
||||
|
||||
import com.heimdall.mobile.domain.model.Site
|
||||
import com.heimdall.mobile.domain.repository.SiteRepository
|
||||
import io.mockk.coEvery
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class SiteUseCasesTest {
|
||||
|
||||
private val repository: SiteRepository = mockk()
|
||||
|
||||
@Test
|
||||
fun `GetSitesUseCase_forwards_repository_flow`() = runTest {
|
||||
val sites = listOf(
|
||||
Site("1", "Site A", null, true, 2, 1, null),
|
||||
Site("2", "Site B", "desc", false, 5, 2, "2026-08-28T10:00:00Z")
|
||||
)
|
||||
every { repository.getSites() } returns flowOf(sites)
|
||||
val useCase = GetSitesUseCase(repository)
|
||||
|
||||
val result = useCase().first()
|
||||
|
||||
assertEquals(sites, result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `RefreshSitesUseCase_returns_success_sites_from_repository`() = runTest {
|
||||
val sites = listOf(Site("1", "Site A", null, true, 2, 1, null))
|
||||
coEvery { repository.refreshSites() } returns Result.success(sites)
|
||||
val useCase = RefreshSitesUseCase(repository)
|
||||
|
||||
val result = useCase()
|
||||
|
||||
assertTrue(result.isSuccess)
|
||||
assertEquals(sites, result.getOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `RefreshSitesUseCase_propagates_repository_failure`() = runTest {
|
||||
val error = IllegalStateException("Network error")
|
||||
coEvery { repository.refreshSites() } returns Result.failure(error)
|
||||
val useCase = RefreshSitesUseCase(repository)
|
||||
|
||||
val result = useCase()
|
||||
|
||||
assertTrue(result.isFailure)
|
||||
assertEquals(error, result.exceptionOrNull())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||
android.useAndroidX=true
|
||||
kotlin.code.style=official
|
||||
android.nonTransitiveRClass=true
|
||||
@@ -0,0 +1,97 @@
|
||||
[versions]
|
||||
agp = "8.7.3"
|
||||
kotlin = "2.1.0"
|
||||
ksp = "2.1.0-1.0.29"
|
||||
hilt = "2.53.1"
|
||||
ktor = "3.0.3"
|
||||
room = "2.7.0"
|
||||
coil = "3.0.4"
|
||||
lifecycle = "2.8.7"
|
||||
navigation = "2.8.4"
|
||||
compose-bom = "2024.12.01"
|
||||
material3 = "1.3.1"
|
||||
coroutines = "1.9.0"
|
||||
serialization = "1.7.3"
|
||||
datastore = "1.1.1"
|
||||
junit5 = "5.11.4"
|
||||
mockk = "1.13.13"
|
||||
turbine = "1.2.0"
|
||||
compileSdk = "35"
|
||||
minSdk = "26"
|
||||
targetSdk = "35"
|
||||
|
||||
[libraries]
|
||||
# Compose BOM
|
||||
compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "compose-bom" }
|
||||
compose-ui = { group = "androidx.compose.ui", name = "ui" }
|
||||
compose-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
|
||||
compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
|
||||
compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
|
||||
compose-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "material3" }
|
||||
compose-material-icons = { group = "androidx.compose.material", name = "material-icons-extended" }
|
||||
compose-runtime = { group = "androidx.compose.runtime", name = "runtime" }
|
||||
|
||||
# Lifecycle
|
||||
lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }
|
||||
lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" }
|
||||
|
||||
# Navigation
|
||||
navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigation" }
|
||||
hilt-navigation-compose = { group = "androidx.hilt", name = "hilt-navigation-compose", version = "1.2.0" }
|
||||
|
||||
# Activity
|
||||
activity-compose = { group = "androidx.activity", name = "activity-compose", version = "1.9.3" }
|
||||
|
||||
# Ktor
|
||||
ktor-client-android = { group = "io.ktor", name = "ktor-client-android", version.ref = "ktor" }
|
||||
ktor-client-content-negotiation = { group = "io.ktor", name = "ktor-client-content-negotiation", version.ref = "ktor" }
|
||||
ktor-client-serialization = { group = "io.ktor", name = "ktor-serialization-kotlinx-json", version.ref = "ktor" }
|
||||
ktor-client-websockets = { group = "io.ktor", name = "ktor-client-websockets", version.ref = "ktor" }
|
||||
ktor-client-logging = { group = "io.ktor", name = "ktor-client-logging", version.ref = "ktor" }
|
||||
ktor-client-mock = { group = "io.ktor", name = "ktor-client-mock", version.ref = "ktor" }
|
||||
|
||||
# Hilt
|
||||
hilt-android = { group = "com.google.dagger", name = "hilt-android", version.ref = "hilt" }
|
||||
hilt-compiler = { group = "com.google.dagger", name = "hilt-compiler", version.ref = "hilt" }
|
||||
|
||||
# Room
|
||||
room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }
|
||||
room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" }
|
||||
room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }
|
||||
|
||||
# DataStore
|
||||
datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastore" }
|
||||
|
||||
# Coil
|
||||
coil-compose = { group = "io.coil-kt.coil3", name = "coil-compose", version.ref = "coil" }
|
||||
|
||||
# Serialization
|
||||
serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "serialization" }
|
||||
|
||||
# Coroutines
|
||||
coroutines-core = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-core", version.ref = "coroutines" }
|
||||
coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" }
|
||||
|
||||
# Core
|
||||
core-ktx = { group = "androidx.core", name = "core-ktx", version = "1.15.0" }
|
||||
|
||||
# SignalR
|
||||
signalr-client = { group = "com.microsoft.signalr", name = "signalr", version = "8.0.1" }
|
||||
|
||||
# Testing
|
||||
junit5-api = { group = "org.junit.jupiter", name = "junit-jupiter-api", version.ref = "junit5" }
|
||||
junit5-engine = { group = "org.junit.jupiter", name = "junit-jupiter-engine", version.ref = "junit5" }
|
||||
mockk = { group = "io.mockk", name = "mockk", version.ref = "mockk" }
|
||||
turbine = { group = "app.cash.turbine", name = "turbine", version.ref = "turbine" }
|
||||
coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "coroutines" }
|
||||
compose-ui-test = { group = "androidx.compose.ui", name = "ui-test-junit4" }
|
||||
compose-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }
|
||||
|
||||
[plugins]
|
||||
android-application = { id = "com.android.application", version.ref = "agp" }
|
||||
android-library = { id = "com.android.library", version.ref = "agp" }
|
||||
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
|
||||
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
|
||||
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
|
||||
hilt = { id = "com.google.dagger.hilt.android", version.ref = "hilt" }
|
||||
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
|
||||
Binary file not shown.
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
+252
@@ -0,0 +1,252 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
|
||||
' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
+94
@@ -0,0 +1,94 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -0,0 +1,76 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.library)
|
||||
alias(libs.plugins.kotlin.android)
|
||||
alias(libs.plugins.kotlin.compose)
|
||||
alias(libs.plugins.hilt)
|
||||
alias(libs.plugins.ksp)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.heimdall.mobile.presentation"
|
||||
compileSdk = libs.versions.compileSdk.get().toInt()
|
||||
|
||||
defaultConfig {
|
||||
minSdk = libs.versions.minSdk.get().toInt()
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
kotlinOptions { jvmTarget = "17" }
|
||||
|
||||
buildFeatures { compose = true }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":domain"))
|
||||
|
||||
// Compose
|
||||
implementation(platform(libs.compose.bom))
|
||||
implementation(libs.compose.ui)
|
||||
implementation(libs.compose.ui.graphics)
|
||||
implementation(libs.compose.ui.tooling.preview)
|
||||
implementation(libs.compose.material3)
|
||||
implementation(libs.compose.material.icons)
|
||||
implementation(libs.compose.runtime)
|
||||
debugImplementation(libs.compose.ui.tooling)
|
||||
|
||||
// Lifecycle
|
||||
implementation(libs.lifecycle.viewmodel.compose)
|
||||
implementation(libs.lifecycle.runtime.compose)
|
||||
|
||||
// Navigation
|
||||
implementation(libs.navigation.compose)
|
||||
implementation(libs.hilt.navigation.compose)
|
||||
|
||||
// Hilt
|
||||
implementation(libs.hilt.android)
|
||||
ksp(libs.hilt.compiler)
|
||||
|
||||
// Coil
|
||||
implementation(libs.coil.compose)
|
||||
|
||||
// Coroutines
|
||||
implementation(libs.coroutines.core)
|
||||
implementation(libs.coroutines.android)
|
||||
|
||||
// Testing
|
||||
testImplementation(libs.junit5.api)
|
||||
testImplementation(libs.junit5.engine)
|
||||
testImplementation(libs.mockk)
|
||||
testImplementation(libs.turbine)
|
||||
testImplementation(libs.coroutines.test)
|
||||
androidTestImplementation(platform(libs.compose.bom))
|
||||
androidTestImplementation(libs.compose.ui.test)
|
||||
}
|
||||
|
||||
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
|
||||
compilerOptions { }
|
||||
}
|
||||
|
||||
tasks.withType<Test> {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
package com.heimdall.mobile.presentation.screens
|
||||
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.navigation.NavHostController
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import com.heimdall.mobile.presentation.screens.dashboard.DashboardScreen
|
||||
import com.heimdall.mobile.presentation.screens.events.EventsScreen
|
||||
import com.heimdall.mobile.presentation.screens.liveCamera.LiveCameraScreen
|
||||
import com.heimdall.mobile.presentation.screens.login.LoginScreen
|
||||
import com.heimdall.mobile.presentation.screens.settings.SettingsScreen
|
||||
import com.heimdall.mobile.presentation.screens.siteDetail.SiteDetailScreen
|
||||
|
||||
sealed class Screen(val route: String) {
|
||||
data object Login : Screen("login")
|
||||
data object Dashboard : Screen("dashboard")
|
||||
data object Sites : Screen("sites")
|
||||
data object Events : Screen("events")
|
||||
data object Settings : Screen("settings")
|
||||
data object SiteDetail : Screen("site/{siteId}/{siteName}") {
|
||||
fun createRoute(siteId: String, siteName: String) = "site/$siteId/$siteName"
|
||||
}
|
||||
data object LiveCamera : Screen("camera/{cameraId}") {
|
||||
fun createRoute(cameraId: String) = "camera/$cameraId"
|
||||
}
|
||||
data object EventDetail : Screen("event/{eventId}") {
|
||||
fun createRoute(eventId: String) = "event/$eventId"
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun HeimdallNavGraph(
|
||||
navController: NavHostController = rememberNavController(),
|
||||
startDestination: String = Screen.Login.route
|
||||
) {
|
||||
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
||||
val currentRoute = navBackStackEntry?.destination?.route
|
||||
|
||||
val showBottomBar = currentRoute in listOf(
|
||||
Screen.Dashboard.route,
|
||||
Screen.Events.route,
|
||||
Screen.Settings.route
|
||||
)
|
||||
|
||||
Scaffold(
|
||||
bottomBar = {
|
||||
if (showBottomBar) {
|
||||
NavigationBar {
|
||||
NavigationBarItem(
|
||||
icon = {},
|
||||
label = { Text("Sites") },
|
||||
selected = currentRoute == Screen.Dashboard.route,
|
||||
onClick = {
|
||||
navController.navigate(Screen.Dashboard.route) {
|
||||
popUpTo(Screen.Dashboard.route) { inclusive = true }
|
||||
}
|
||||
}
|
||||
)
|
||||
NavigationBarItem(
|
||||
icon = {},
|
||||
label = { Text("Événements") },
|
||||
selected = currentRoute == Screen.Events.route,
|
||||
onClick = {
|
||||
navController.navigate(Screen.Events.route) {
|
||||
popUpTo(Screen.Dashboard.route)
|
||||
}
|
||||
}
|
||||
)
|
||||
NavigationBarItem(
|
||||
icon = {},
|
||||
label = { Text("Réglages") },
|
||||
selected = currentRoute == Screen.Settings.route,
|
||||
onClick = {
|
||||
navController.navigate(Screen.Settings.route) {
|
||||
popUpTo(Screen.Dashboard.route)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
) { innerPadding ->
|
||||
NavHost(
|
||||
navController = navController,
|
||||
startDestination = startDestination,
|
||||
modifier = Modifier
|
||||
) {
|
||||
composable(Screen.Login.route) {
|
||||
LoginScreen(
|
||||
onLoginSuccess = {
|
||||
navController.navigate(Screen.Dashboard.route) {
|
||||
popUpTo(Screen.Login.route) { inclusive = true }
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
composable(Screen.Dashboard.route) {
|
||||
DashboardScreen(
|
||||
onSiteClick = { siteId, siteName ->
|
||||
navController.navigate(Screen.SiteDetail.createRoute(siteId, siteName))
|
||||
},
|
||||
onEventsClick = {
|
||||
navController.navigate(Screen.Events.route)
|
||||
},
|
||||
onSettingsClick = {
|
||||
navController.navigate(Screen.Settings.route)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
composable(Screen.SiteDetail.route) { backStackEntry ->
|
||||
val siteId = backStackEntry.arguments?.getString("siteId") ?: ""
|
||||
val siteName = backStackEntry.arguments?.getString("siteName") ?: ""
|
||||
SiteDetailScreen(
|
||||
siteId = siteId,
|
||||
siteName = siteName,
|
||||
onCameraClick = { cameraId ->
|
||||
navController.navigate(Screen.LiveCamera.createRoute(cameraId))
|
||||
},
|
||||
onBack = { navController.popBackStack() }
|
||||
)
|
||||
}
|
||||
|
||||
composable(Screen.LiveCamera.route) { backStackEntry ->
|
||||
val cameraId = backStackEntry.arguments?.getString("cameraId") ?: ""
|
||||
LiveCameraScreen(
|
||||
cameraId = cameraId,
|
||||
onBack = { navController.popBackStack() }
|
||||
)
|
||||
}
|
||||
|
||||
composable(Screen.Events.route) {
|
||||
EventsScreen(
|
||||
onEventClick = { eventId ->
|
||||
navController.navigate(Screen.EventDetail.createRoute(eventId))
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
composable(Screen.Settings.route) {
|
||||
SettingsScreen(
|
||||
onBack = { navController.popBackStack() },
|
||||
onLogout = {
|
||||
navController.navigate(Screen.Login.route) {
|
||||
popUpTo(0) { inclusive = true }
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
package com.heimdall.mobile.presentation.screens.dashboard
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Warning
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import com.heimdall.mobile.domain.model.Site
|
||||
import com.heimdall.mobile.presentation.viewmodel.DashboardViewModel
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun DashboardScreen(
|
||||
onSiteClick: (String, String) -> Unit,
|
||||
onEventsClick: () -> Unit,
|
||||
onSettingsClick: () -> Unit,
|
||||
viewModel: DashboardViewModel = hiltViewModel()
|
||||
) {
|
||||
val uiState by viewModel.uiState.collectAsState()
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text("Heimdall") },
|
||||
actions = {
|
||||
IconButton(onClick = { viewModel.refresh() }) {
|
||||
Icon(Icons.Default.Add, contentDescription = "Refresh")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
if (uiState.isLoading && uiState.sites.isEmpty()) {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
} else if (uiState.sites.isEmpty()) {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Icon(
|
||||
Icons.Default.Warning,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(48.dp),
|
||||
tint = MaterialTheme.colorScheme.outline
|
||||
)
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
Text("Aucun site configuré")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
items(uiState.sites) { site ->
|
||||
SiteCard(site = site, onClick = { onSiteClick(site.id, site.name) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
uiState.error?.let { error ->
|
||||
Snackbar(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
action = {
|
||||
TextButton(onClick = { viewModel.refresh() }) {
|
||||
Text("Réessayer")
|
||||
}
|
||||
}
|
||||
) {
|
||||
Text(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SiteCard(site: Site, onClick: () -> Unit) {
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onClick),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(
|
||||
text = site.name,
|
||||
style = MaterialTheme.typography.titleMedium
|
||||
)
|
||||
Surface(
|
||||
color = if (site.isOnline)
|
||||
MaterialTheme.colorScheme.primary
|
||||
else MaterialTheme.colorScheme.error,
|
||||
shape = MaterialTheme.shapes.small
|
||||
) {
|
||||
Text(
|
||||
text = if (site.isOnline) "En ligne" else "Hors ligne",
|
||||
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
|
||||
color = MaterialTheme.colorScheme.onPrimary,
|
||||
style = MaterialTheme.typography.labelSmall
|
||||
)
|
||||
}
|
||||
}
|
||||
val desc = site.description
|
||||
if (desc != null) {
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text = desc,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
|
||||
Text(
|
||||
text = "${site.cameraCount} caméras",
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
)
|
||||
Text(
|
||||
text = "${site.agentCount} agents",
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.heimdall.mobile.presentation.screens.eventDetail
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.heimdall.mobile.domain.model.CameraEvent
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun EventDetailScreen(
|
||||
event: CameraEvent?,
|
||||
onBack: () -> Unit
|
||||
) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text("Détail événement") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Retour")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
if (event == null) {
|
||||
Box(modifier = Modifier.fillMaxSize().padding(padding)) {
|
||||
Text("Événement introuvable", modifier = Modifier.padding(16.dp))
|
||||
}
|
||||
} else {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().padding(padding).padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
Text(text = event.type, style = MaterialTheme.typography.headlineSmall)
|
||||
Text(
|
||||
text = event.createdAt,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
HorizontalDivider()
|
||||
event.description?.let {
|
||||
Text(text = it, style = MaterialTheme.typography.bodyLarge)
|
||||
}
|
||||
event.cameraName?.let {
|
||||
Text(
|
||||
text = "Caméra: $it",
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = "Sévérité: ${event.severity}",
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package com.heimdall.mobile.presentation.screens.events
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Warning
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import com.heimdall.mobile.domain.model.CameraEvent
|
||||
import com.heimdall.mobile.presentation.viewmodel.EventsViewModel
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun EventsScreen(
|
||||
onEventClick: (String) -> Unit,
|
||||
viewModel: EventsViewModel = hiltViewModel()
|
||||
) {
|
||||
val uiState by viewModel.uiState.collectAsState()
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text("Événements") },
|
||||
actions = {
|
||||
IconButton(onClick = { viewModel.refresh() }) {
|
||||
Icon(Icons.Default.Warning, contentDescription = "Refresh")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
if (uiState.isLoading && uiState.events.isEmpty()) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
} else if (uiState.events.isEmpty()) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text("Aucun événement", style = MaterialTheme.typography.bodyLarge)
|
||||
}
|
||||
} else {
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize().padding(padding),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
items(uiState.events) { event ->
|
||||
EventCard(event = event, onClick = { onEventClick(event.id) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun EventCard(event: CameraEvent, onClick: () -> Unit) {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onClick),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Text(text = event.type, style = MaterialTheme.typography.titleSmall)
|
||||
Text(
|
||||
text = event.createdAt,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
event.description?.let {
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(text = it, style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
event.cameraName?.let {
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text = "Caméra: $it",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.heimdall.mobile.presentation.screens.liveCamera
|
||||
|
||||
import android.view.SurfaceView
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun LiveCameraScreen(
|
||||
cameraId: String,
|
||||
onBack: () -> Unit
|
||||
) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text("Caméra Live") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Retour")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
// WebRTC placeholder — will be connected to real WebRTC in subsequent steps
|
||||
AndroidView(
|
||||
factory = { context ->
|
||||
SurfaceView(context).apply {
|
||||
// TODO: Initialize WebRTC PeerConnection + SurfaceViewRenderer
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxSize()
|
||||
)
|
||||
Text(
|
||||
text = "Flux WebRTC en cours de chargement...",
|
||||
modifier = Modifier.padding(16.dp),
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
package com.heimdall.mobile.presentation.screens.login
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import com.heimdall.mobile.presentation.viewmodel.LoginUiState
|
||||
import com.heimdall.mobile.presentation.viewmodel.LoginViewModel
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun LoginScreen(
|
||||
onLoginSuccess: () -> Unit,
|
||||
viewModel: LoginViewModel = hiltViewModel()
|
||||
) {
|
||||
val uiState by viewModel.uiState.collectAsState()
|
||||
var email by remember { mutableStateOf("") }
|
||||
var password by remember { mutableStateOf("") }
|
||||
var twoFactorCode by remember { mutableStateOf("") }
|
||||
|
||||
LaunchedEffect(uiState) {
|
||||
if (uiState is LoginUiState.Success) onLoginSuccess()
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(title = { Text("Heimdall") })
|
||||
}
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
.padding(24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center
|
||||
) {
|
||||
Text(
|
||||
text = "Surveillance Vidéo IA",
|
||||
style = MaterialTheme.typography.headlineMedium
|
||||
)
|
||||
Spacer(modifier = Modifier.height(32.dp))
|
||||
|
||||
when (val state = uiState) {
|
||||
is LoginUiState.TwoFactorRequired -> {
|
||||
OutlinedTextField(
|
||||
value = twoFactorCode,
|
||||
onValueChange = { twoFactorCode = it },
|
||||
label = { Text("Code 2FA") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
|
||||
)
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
Button(
|
||||
onClick = { viewModel.verifyTwoFactor(twoFactorCode) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
enabled = twoFactorCode.length == 6
|
||||
) {
|
||||
Text("Vérifier")
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
OutlinedTextField(
|
||||
value = email,
|
||||
onValueChange = { email = it },
|
||||
label = { Text("Email") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email)
|
||||
)
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
OutlinedTextField(
|
||||
value = password,
|
||||
onValueChange = { password = it },
|
||||
label = { Text("Mot de passe") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)
|
||||
)
|
||||
Spacer(modifier = Modifier.height(24.dp))
|
||||
Button(
|
||||
onClick = { viewModel.login(email, password) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
enabled = email.isNotBlank() && password.isNotBlank() &&
|
||||
uiState !is LoginUiState.Loading
|
||||
) {
|
||||
if (uiState is LoginUiState.Loading) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(20.dp),
|
||||
strokeWidth = 2.dp
|
||||
)
|
||||
} else {
|
||||
Text("Se connecter")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (uiState is LoginUiState.Error) {
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
Text(
|
||||
text = (uiState as LoginUiState.Error).message,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.heimdall.mobile.presentation.screens.settings
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun SettingsScreen(
|
||||
onBack: () -> Unit,
|
||||
onLogout: () -> Unit
|
||||
) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text("Réglages") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Retour")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
Text("Paramètres", style = MaterialTheme.typography.headlineSmall)
|
||||
HorizontalDivider()
|
||||
OutlinedButton(
|
||||
onClick = onLogout,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Text("Se déconnecter")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package com.heimdall.mobile.presentation.screens.siteDetail
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import com.heimdall.mobile.domain.model.Camera
|
||||
import com.heimdall.mobile.presentation.viewmodel.SiteDetailViewModel
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun SiteDetailScreen(
|
||||
siteId: String,
|
||||
siteName: String,
|
||||
onCameraClick: (String) -> Unit,
|
||||
onBack: () -> Unit,
|
||||
viewModel: SiteDetailViewModel = hiltViewModel()
|
||||
) {
|
||||
LaunchedEffect(siteId) {
|
||||
viewModel.loadSite(siteId, siteName)
|
||||
}
|
||||
|
||||
val uiState by viewModel.uiState.collectAsState()
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(siteName) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Retour")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
if (uiState.isLoading && uiState.cameras.isEmpty()) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
} else {
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize().padding(padding),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
items(uiState.cameras) { camera ->
|
||||
CameraCard(camera = camera, onClick = { onCameraClick(camera.id) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun CameraCard(camera: Camera, onClick: () -> Unit) {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onClick),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(text = camera.name, style = MaterialTheme.typography.titleMedium)
|
||||
Surface(
|
||||
color = if (camera.isOnline) MaterialTheme.colorScheme.primary
|
||||
else MaterialTheme.colorScheme.error,
|
||||
shape = MaterialTheme.shapes.small
|
||||
) {
|
||||
Text(
|
||||
text = if (camera.isOnline) "En ligne" else "Hors ligne",
|
||||
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
|
||||
color = MaterialTheme.colorScheme.onPrimary,
|
||||
style = MaterialTheme.typography.labelSmall
|
||||
)
|
||||
}
|
||||
}
|
||||
if (camera.webrtcEnabled) {
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text = "WebRTC disponible",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package com.heimdall.mobile.presentation.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
// Heimdall brand colors
|
||||
val HeimdallPrimary = Color(0xFF1E88E5)
|
||||
val HeimdallOnPrimary = Color(0xFFFFFFFF)
|
||||
val HeimdallPrimaryContainer = Color(0xFFBBDEFB)
|
||||
val HeimdallOnPrimaryContainer = Color(0xFF0D47A1)
|
||||
|
||||
val HeimdallSecondary = Color(0xFF43A047)
|
||||
val HeimdallOnSecondary = Color(0xFFFFFFFF)
|
||||
val HeimdallSecondaryContainer = Color(0xFFC8E6C9)
|
||||
val HeimdallOnSecondaryContainer = Color(0xFF1B5E20)
|
||||
|
||||
val HeimdallTertiary = Color(0xFFFFA000)
|
||||
val HeimdallOnTertiary = Color(0xFFFFFFFF)
|
||||
val HeimdallTertiaryContainer = Color(0xFFFFECB3)
|
||||
val HeimdallOnTertiaryContainer = Color(0xFFE65100)
|
||||
|
||||
val HeimdallError = Color(0xFFD32F2F)
|
||||
val HeimdallOnError = Color(0xFFFFFFFF)
|
||||
val HeimdallErrorContainer = Color(0xFFFFCDD2)
|
||||
val HeimdallOnErrorContainer = Color(0xFFB71C1C)
|
||||
|
||||
val HeimdallBackground = Color(0xFFFAFAFA)
|
||||
val HeimdallOnBackground = Color(0xFF212121)
|
||||
val HeimdallSurface = Color(0xFFFFFFFF)
|
||||
val HeimdallOnSurface = Color(0xFF212121)
|
||||
val HeimdallSurfaceVariant = Color(0xFFF5F5F5)
|
||||
val HeimdallOnSurfaceVariant = Color(0xFF757575)
|
||||
|
||||
// Dark theme
|
||||
val HeimdallPrimaryDark = Color(0xFF64B5F6)
|
||||
val HeimdallOnPrimaryDark = Color(0xFF0D47A1)
|
||||
val HeimdallPrimaryContainerDark = Color(0xFF1565C0)
|
||||
val HeimdallOnPrimaryContainerDark = Color(0xFFBBDEFB)
|
||||
|
||||
val HeimdallSecondaryDark = Color(0xFF81C784)
|
||||
val HeimdallOnSecondaryDark = Color(0xFF1B5E20)
|
||||
val HeimdallSecondaryContainerDark = Color(0xFF2E7D32)
|
||||
val HeimdallOnSecondaryContainerDark = Color(0xFFC8E6C9)
|
||||
|
||||
val HeimdallTertiaryDark = Color(0xFFFFB74D)
|
||||
val HeimdallOnTertiaryDark = Color(0xFFE65100)
|
||||
val HeimdallTertiaryContainerDark = Color(0xFFEF6C00)
|
||||
val HeimdallOnTertiaryContainerDark = Color(0xFFFFECB3)
|
||||
|
||||
val HeimdallErrorDark = Color(0xFFEF5350)
|
||||
val HeimdallOnErrorDark = Color(0xFFB71C1C)
|
||||
val HeimdallErrorContainerDark = Color(0xFFC62828)
|
||||
val HeimdallOnErrorContainerDark = Color(0xFFFFCDD2)
|
||||
|
||||
val HeimdallBackgroundDark = Color(0xFF121212)
|
||||
val HeimdallOnBackgroundDark = Color(0xFFE0E0E0)
|
||||
val HeimdallSurfaceDark = Color(0xFF1E1E1E)
|
||||
val HeimdallOnSurfaceDark = Color(0xFFE0E0E0)
|
||||
val HeimdallSurfaceVariantDark = Color(0xFF2C2C2C)
|
||||
val HeimdallOnSurfaceVariantDark = Color(0xFFBDBDBD)
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.heimdall.mobile.presentation.ui.theme
|
||||
|
||||
import android.os.Build
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
|
||||
private val LightColorScheme = lightColorScheme(
|
||||
primary = HeimdallPrimary,
|
||||
onPrimary = HeimdallOnPrimary,
|
||||
primaryContainer = HeimdallPrimaryContainer,
|
||||
onPrimaryContainer = HeimdallOnPrimaryContainer,
|
||||
secondary = HeimdallSecondary,
|
||||
onSecondary = HeimdallOnSecondary,
|
||||
secondaryContainer = HeimdallSecondaryContainer,
|
||||
onSecondaryContainer = HeimdallOnSecondaryContainer,
|
||||
tertiary = HeimdallTertiary,
|
||||
onTertiary = HeimdallOnTertiary,
|
||||
tertiaryContainer = HeimdallTertiaryContainer,
|
||||
onTertiaryContainer = HeimdallOnTertiaryContainer,
|
||||
error = HeimdallError,
|
||||
onError = HeimdallOnError,
|
||||
errorContainer = HeimdallErrorContainer,
|
||||
onErrorContainer = HeimdallOnErrorContainer,
|
||||
background = HeimdallBackground,
|
||||
onBackground = HeimdallOnBackground,
|
||||
surface = HeimdallSurface,
|
||||
onSurface = HeimdallOnSurface,
|
||||
surfaceVariant = HeimdallSurfaceVariant,
|
||||
onSurfaceVariant = HeimdallOnSurfaceVariant,
|
||||
)
|
||||
|
||||
private val DarkColorScheme = darkColorScheme(
|
||||
primary = HeimdallPrimaryDark,
|
||||
onPrimary = HeimdallOnPrimaryDark,
|
||||
primaryContainer = HeimdallPrimaryContainerDark,
|
||||
onPrimaryContainer = HeimdallOnPrimaryContainerDark,
|
||||
secondary = HeimdallSecondaryDark,
|
||||
onSecondary = HeimdallOnSecondaryDark,
|
||||
secondaryContainer = HeimdallSecondaryContainerDark,
|
||||
onSecondaryContainer = HeimdallOnSecondaryContainerDark,
|
||||
tertiary = HeimdallTertiaryDark,
|
||||
onTertiary = HeimdallOnTertiaryDark,
|
||||
tertiaryContainer = HeimdallTertiaryContainerDark,
|
||||
onTertiaryContainer = HeimdallOnTertiaryContainerDark,
|
||||
error = HeimdallErrorDark,
|
||||
onError = HeimdallOnErrorDark,
|
||||
errorContainer = HeimdallErrorContainerDark,
|
||||
onErrorContainer = HeimdallOnErrorContainerDark,
|
||||
background = HeimdallBackgroundDark,
|
||||
onBackground = HeimdallOnBackgroundDark,
|
||||
surface = HeimdallSurfaceDark,
|
||||
onSurface = HeimdallOnSurfaceDark,
|
||||
surfaceVariant = HeimdallSurfaceVariantDark,
|
||||
onSurfaceVariant = HeimdallOnSurfaceVariantDark,
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun HeimdallTheme(
|
||||
darkTheme: Boolean = isSystemInDarkTheme(),
|
||||
dynamicColor: Boolean = true,
|
||||
content: @Composable () -> Unit
|
||||
) {
|
||||
val colorScheme = when {
|
||||
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
|
||||
val context = LocalContext.current
|
||||
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
|
||||
}
|
||||
darkTheme -> DarkColorScheme
|
||||
else -> LightColorScheme
|
||||
}
|
||||
|
||||
MaterialTheme(
|
||||
colorScheme = colorScheme,
|
||||
content = content
|
||||
)
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.heimdall.mobile.presentation.viewmodel
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.heimdall.mobile.domain.model.Site
|
||||
import com.heimdall.mobile.domain.usecase.GetSitesUseCase
|
||||
import com.heimdall.mobile.domain.usecase.RefreshSitesUseCase
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
data class DashboardUiState(
|
||||
val sites: List<Site> = emptyList(),
|
||||
val isLoading: Boolean = false,
|
||||
val isRefreshing: Boolean = false,
|
||||
val error: String? = null
|
||||
)
|
||||
|
||||
@HiltViewModel
|
||||
class DashboardViewModel @Inject constructor(
|
||||
private val getSitesUseCase: GetSitesUseCase,
|
||||
private val refreshSitesUseCase: RefreshSitesUseCase
|
||||
) : ViewModel() {
|
||||
|
||||
private val _uiState = MutableStateFlow(DashboardUiState())
|
||||
val uiState: StateFlow<DashboardUiState> = _uiState.asStateFlow()
|
||||
|
||||
init {
|
||||
loadSites()
|
||||
}
|
||||
|
||||
private fun loadSites() {
|
||||
viewModelScope.launch {
|
||||
_uiState.value = _uiState.value.copy(isLoading = true)
|
||||
getSitesUseCase().collect { sites ->
|
||||
_uiState.value = _uiState.value.copy(
|
||||
sites = sites,
|
||||
isLoading = false
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun refresh() {
|
||||
viewModelScope.launch {
|
||||
_uiState.value = _uiState.value.copy(isRefreshing = true, error = null)
|
||||
refreshSitesUseCase()
|
||||
.onFailure { e ->
|
||||
_uiState.value = _uiState.value.copy(
|
||||
error = e.message ?: "Refresh failed",
|
||||
isRefreshing = false
|
||||
)
|
||||
}
|
||||
.onSuccess { sites ->
|
||||
_uiState.value = _uiState.value.copy(
|
||||
sites = sites,
|
||||
isRefreshing = false
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.heimdall.mobile.presentation.viewmodel
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.heimdall.mobile.domain.model.CameraEvent
|
||||
import com.heimdall.mobile.domain.usecase.GetEventsUseCase
|
||||
import com.heimdall.mobile.domain.usecase.RefreshEventsUseCase
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
data class EventsUiState(
|
||||
val events: List<CameraEvent> = emptyList(),
|
||||
val isLoading: Boolean = false,
|
||||
val isRefreshing: Boolean = false,
|
||||
val error: String? = null,
|
||||
val siteFilter: String? = null
|
||||
)
|
||||
|
||||
@HiltViewModel
|
||||
class EventsViewModel @Inject constructor(
|
||||
private val getEventsUseCase: GetEventsUseCase,
|
||||
private val refreshEventsUseCase: RefreshEventsUseCase
|
||||
) : ViewModel() {
|
||||
|
||||
private val _uiState = MutableStateFlow(EventsUiState())
|
||||
val uiState: StateFlow<EventsUiState> = _uiState.asStateFlow()
|
||||
|
||||
init {
|
||||
loadEvents()
|
||||
}
|
||||
|
||||
private fun loadEvents() {
|
||||
viewModelScope.launch {
|
||||
_uiState.value = _uiState.value.copy(isLoading = true)
|
||||
getEventsUseCase(_uiState.value.siteFilter).collect { events ->
|
||||
_uiState.value = _uiState.value.copy(events = events, isLoading = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setSiteFilter(siteId: String?) {
|
||||
_uiState.value = _uiState.value.copy(siteFilter = siteId)
|
||||
loadEvents()
|
||||
}
|
||||
|
||||
fun refresh() {
|
||||
viewModelScope.launch {
|
||||
_uiState.value = _uiState.value.copy(isRefreshing = true, error = null)
|
||||
refreshEventsUseCase(_uiState.value.siteFilter)
|
||||
.onFailure { e ->
|
||||
_uiState.value = _uiState.value.copy(
|
||||
error = e.message ?: "Refresh failed",
|
||||
isRefreshing = false
|
||||
)
|
||||
}
|
||||
.onSuccess { events ->
|
||||
_uiState.value = _uiState.value.copy(
|
||||
events = events,
|
||||
isRefreshing = false
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.heimdall.mobile.presentation.viewmodel
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.heimdall.mobile.domain.usecase.LoginUseCase
|
||||
import com.heimdall.mobile.domain.usecase.VerifyTwoFactorUseCase
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
sealed interface LoginUiState {
|
||||
data object Idle : LoginUiState
|
||||
data object Loading : LoginUiState
|
||||
data object TwoFactorRequired : LoginUiState
|
||||
data object Success : LoginUiState
|
||||
data class Error(val message: String) : LoginUiState
|
||||
}
|
||||
|
||||
@HiltViewModel
|
||||
class LoginViewModel @Inject constructor(
|
||||
private val loginUseCase: LoginUseCase,
|
||||
private val verifyTwoFactorUseCase: VerifyTwoFactorUseCase
|
||||
) : ViewModel() {
|
||||
|
||||
private val _uiState = MutableStateFlow<LoginUiState>(LoginUiState.Idle)
|
||||
val uiState: StateFlow<LoginUiState> = _uiState.asStateFlow()
|
||||
|
||||
fun login(email: String, password: String) {
|
||||
viewModelScope.launch {
|
||||
_uiState.value = LoginUiState.Loading
|
||||
loginUseCase(email, password)
|
||||
.onSuccess { tokens ->
|
||||
if (tokens.accessToken.isEmpty()) {
|
||||
_uiState.value = LoginUiState.TwoFactorRequired
|
||||
} else {
|
||||
_uiState.value = LoginUiState.Success
|
||||
}
|
||||
}
|
||||
.onFailure { e ->
|
||||
_uiState.value = LoginUiState.Error(e.message ?: "Login failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun verifyTwoFactor(code: String) {
|
||||
viewModelScope.launch {
|
||||
_uiState.value = LoginUiState.Loading
|
||||
verifyTwoFactorUseCase(code)
|
||||
.onSuccess { _uiState.value = LoginUiState.Success }
|
||||
.onFailure { e ->
|
||||
_uiState.value = LoginUiState.Error(e.message ?: "2FA verification failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun resetState() {
|
||||
_uiState.value = LoginUiState.Idle
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.heimdall.mobile.presentation.viewmodel
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.heimdall.mobile.domain.model.Camera
|
||||
import com.heimdall.mobile.domain.usecase.GetCamerasBySiteUseCase
|
||||
import com.heimdall.mobile.domain.usecase.RefreshCamerasUseCase
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
data class SiteDetailUiState(
|
||||
val siteId: String = "",
|
||||
val siteName: String = "",
|
||||
val cameras: List<Camera> = emptyList(),
|
||||
val isLoading: Boolean = false,
|
||||
val error: String? = null
|
||||
)
|
||||
|
||||
@HiltViewModel
|
||||
class SiteDetailViewModel @Inject constructor(
|
||||
private val getCamerasBySiteUseCase: GetCamerasBySiteUseCase,
|
||||
private val refreshCamerasUseCase: RefreshCamerasUseCase
|
||||
) : ViewModel() {
|
||||
|
||||
private val _uiState = MutableStateFlow(SiteDetailUiState())
|
||||
val uiState: StateFlow<SiteDetailUiState> = _uiState.asStateFlow()
|
||||
|
||||
fun loadSite(siteId: String, siteName: String) {
|
||||
_uiState.value = _uiState.value.copy(siteId = siteId, siteName = siteName)
|
||||
viewModelScope.launch {
|
||||
_uiState.value = _uiState.value.copy(isLoading = true)
|
||||
getCamerasBySiteUseCase(siteId).collect { cameras ->
|
||||
_uiState.value = _uiState.value.copy(cameras = cameras, isLoading = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun refresh() {
|
||||
viewModelScope.launch {
|
||||
_uiState.value = _uiState.value.copy(isLoading = true, error = null)
|
||||
refreshCamerasUseCase(_uiState.value.siteId)
|
||||
.onFailure { e ->
|
||||
_uiState.value = _uiState.value.copy(
|
||||
error = e.message ?: "Refresh failed",
|
||||
isLoading = false
|
||||
)
|
||||
}
|
||||
.onSuccess { cameras ->
|
||||
_uiState.value = _uiState.value.copy(
|
||||
cameras = cameras,
|
||||
isLoading = false
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package com.heimdall.mobile.presentation.viewmodel
|
||||
|
||||
import com.heimdall.mobile.domain.model.Site
|
||||
import com.heimdall.mobile.domain.usecase.GetSitesUseCase
|
||||
import com.heimdall.mobile.domain.usecase.RefreshSitesUseCase
|
||||
import io.mockk.coEvery
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.test.StandardTestDispatcher
|
||||
import kotlinx.coroutines.test.advanceUntilIdle
|
||||
import kotlinx.coroutines.test.resetMain
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.coroutines.test.setMain
|
||||
import org.junit.jupiter.api.AfterEach
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertFalse
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class DashboardViewModelTest {
|
||||
|
||||
private val getSitesUseCase: GetSitesUseCase = mockk()
|
||||
private val refreshSitesUseCase: RefreshSitesUseCase = mockk()
|
||||
private val dispatcher = StandardTestDispatcher()
|
||||
|
||||
private val site = Site("1", "Site A", null, true, 2, 1, null)
|
||||
|
||||
@BeforeEach
|
||||
fun setUp() {
|
||||
Dispatchers.setMain(dispatcher)
|
||||
io.mockk.clearAllMocks()
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
fun tearDown() {
|
||||
Dispatchers.resetMain()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `init_loads_sites_from_getSitesUseCase`() = runTest(dispatcher) {
|
||||
every { getSitesUseCase() } returns flowOf(listOf(site))
|
||||
val vm = DashboardViewModel(getSitesUseCase, refreshSitesUseCase)
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals(listOf(site), vm.uiState.value.sites)
|
||||
assertFalse(vm.uiState.value.isLoading)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `refresh_success_updates_sites_and_stops_refreshing`() = runTest(dispatcher) {
|
||||
every { getSitesUseCase() } returns flowOf(listOf(site))
|
||||
val vm = DashboardViewModel(getSitesUseCase, refreshSitesUseCase)
|
||||
advanceUntilIdle()
|
||||
|
||||
val newSite = Site("2", "Site B", null, false, 3, 2, null)
|
||||
coEvery { refreshSitesUseCase() } returns Result.success(listOf(newSite))
|
||||
|
||||
vm.refresh()
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals(listOf(newSite), vm.uiState.value.sites)
|
||||
assertFalse(vm.uiState.value.isRefreshing)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `refresh_failure_sets_error_and_stops_refreshing`() = runTest(dispatcher) {
|
||||
every { getSitesUseCase() } returns flowOf(listOf(site))
|
||||
val vm = DashboardViewModel(getSitesUseCase, refreshSitesUseCase)
|
||||
advanceUntilIdle()
|
||||
|
||||
coEvery { refreshSitesUseCase() } returns Result.failure(IllegalStateException("Refresh failed"))
|
||||
|
||||
vm.refresh()
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals("Refresh failed", vm.uiState.value.error)
|
||||
assertFalse(vm.uiState.value.isRefreshing)
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package com.heimdall.mobile.presentation.viewmodel
|
||||
|
||||
import com.heimdall.mobile.domain.model.CameraEvent
|
||||
import com.heimdall.mobile.domain.usecase.GetEventsUseCase
|
||||
import com.heimdall.mobile.domain.usecase.RefreshEventsUseCase
|
||||
import io.mockk.coEvery
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.test.StandardTestDispatcher
|
||||
import kotlinx.coroutines.test.advanceUntilIdle
|
||||
import kotlinx.coroutines.test.resetMain
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.coroutines.test.setMain
|
||||
import org.junit.jupiter.api.AfterEach
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertFalse
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class EventsViewModelTest {
|
||||
|
||||
private val getEventsUseCase: GetEventsUseCase = mockk()
|
||||
private val refreshEventsUseCase: RefreshEventsUseCase = mockk()
|
||||
private val dispatcher = StandardTestDispatcher()
|
||||
|
||||
private val event = CameraEvent(
|
||||
id = "e1", cameraId = "c1", cameraName = "Cam 1", siteId = "s1",
|
||||
type = "motion", description = "Movement", snapshotUrl = null,
|
||||
createdAt = "2026-08-28T10:00:00Z", severity = "high"
|
||||
)
|
||||
|
||||
@BeforeEach
|
||||
fun setUp() {
|
||||
Dispatchers.setMain(dispatcher)
|
||||
io.mockk.clearAllMocks()
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
fun tearDown() {
|
||||
Dispatchers.resetMain()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `init_loads_events_from_getEventsUseCase`() = runTest(dispatcher) {
|
||||
every { getEventsUseCase(null) } returns flowOf(listOf(event))
|
||||
val vm = EventsViewModel(getEventsUseCase, refreshEventsUseCase)
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals(listOf(event), vm.uiState.value.events)
|
||||
assertFalse(vm.uiState.value.isLoading)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `refresh_success_updates_events_and_stops_refreshing`() = runTest(dispatcher) {
|
||||
every { getEventsUseCase(null) } returns flowOf(listOf(event))
|
||||
val vm = EventsViewModel(getEventsUseCase, refreshEventsUseCase)
|
||||
advanceUntilIdle()
|
||||
|
||||
val newEvent = event.copy(id = "e2", description = "New movement")
|
||||
coEvery { refreshEventsUseCase(null) } returns Result.success(listOf(newEvent))
|
||||
|
||||
vm.refresh()
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals(listOf(newEvent), vm.uiState.value.events)
|
||||
assertFalse(vm.uiState.value.isRefreshing)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `refresh_failure_sets_error_and_stops_refreshing`() = runTest(dispatcher) {
|
||||
every { getEventsUseCase(null) } returns flowOf(listOf(event))
|
||||
val vm = EventsViewModel(getEventsUseCase, refreshEventsUseCase)
|
||||
advanceUntilIdle()
|
||||
|
||||
coEvery { refreshEventsUseCase(null) } returns Result.failure(IllegalStateException("Refresh failed"))
|
||||
|
||||
vm.refresh()
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals("Refresh failed", vm.uiState.value.error)
|
||||
assertFalse(vm.uiState.value.isRefreshing)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `setSiteFilter_reloads_events_with_filter`() = runTest(dispatcher) {
|
||||
every { getEventsUseCase(null) } returns flowOf(listOf(event))
|
||||
every { getEventsUseCase("s1") } returns flowOf(listOf(event.copy(siteId = "s1")))
|
||||
val vm = EventsViewModel(getEventsUseCase, refreshEventsUseCase)
|
||||
advanceUntilIdle()
|
||||
assertEquals(listOf(event), vm.uiState.value.events)
|
||||
|
||||
vm.setSiteFilter("s1")
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals("s1", vm.uiState.value.siteFilter)
|
||||
assertEquals(listOf(event.copy(siteId = "s1")), vm.uiState.value.events)
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package com.heimdall.mobile.presentation.viewmodel
|
||||
|
||||
import com.heimdall.mobile.domain.model.AuthTokens
|
||||
import com.heimdall.mobile.domain.usecase.LoginUseCase
|
||||
import com.heimdall.mobile.domain.usecase.VerifyTwoFactorUseCase
|
||||
import io.mockk.coEvery
|
||||
import io.mockk.mockk
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.test.StandardTestDispatcher
|
||||
import kotlinx.coroutines.test.advanceUntilIdle
|
||||
import kotlinx.coroutines.test.resetMain
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.coroutines.test.setMain
|
||||
import org.junit.jupiter.api.AfterEach
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class LoginViewModelTest {
|
||||
|
||||
private val loginUseCase: LoginUseCase = mockk()
|
||||
private val verifyTwoFactorUseCase: VerifyTwoFactorUseCase = mockk()
|
||||
private val dispatcher = StandardTestDispatcher()
|
||||
|
||||
@BeforeEach
|
||||
fun setUp() {
|
||||
Dispatchers.setMain(dispatcher)
|
||||
io.mockk.clearAllMocks()
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
fun tearDown() {
|
||||
Dispatchers.resetMain()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `login_success_transitions_to_Success`() = runTest(dispatcher) {
|
||||
coEvery { loginUseCase("user@example.com", "pass") } returns
|
||||
Result.success(AuthTokens("access", "refresh", 3600L))
|
||||
val vm = LoginViewModel(loginUseCase, verifyTwoFactorUseCase)
|
||||
|
||||
vm.login("user@example.com", "pass")
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals(LoginUiState.Success, vm.uiState.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `login_two_factor_required_when_accessToken_empty`() = runTest(dispatcher) {
|
||||
coEvery { loginUseCase("u@e.com", "p") } returns
|
||||
Result.success(AuthTokens(accessToken = "", refreshToken = "", expiresIn = 0))
|
||||
val vm = LoginViewModel(loginUseCase, verifyTwoFactorUseCase)
|
||||
|
||||
vm.login("u@e.com", "p")
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals(LoginUiState.TwoFactorRequired, vm.uiState.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `login_failure_transitions_to_Error_with_message`() = runTest(dispatcher) {
|
||||
coEvery { loginUseCase("u@e.com", "p") } returns
|
||||
Result.failure(IllegalStateException("Identifiants invalides"))
|
||||
val vm = LoginViewModel(loginUseCase, verifyTwoFactorUseCase)
|
||||
|
||||
vm.login("u@e.com", "p")
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals(LoginUiState.Error("Identifiants invalides"), vm.uiState.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `verify_two_factor_success_transitions_to_Success`() = runTest(dispatcher) {
|
||||
coEvery { verifyTwoFactorUseCase("123456") } returns
|
||||
Result.success(AuthTokens("access", "refresh", 3600L))
|
||||
val vm = LoginViewModel(loginUseCase, verifyTwoFactorUseCase)
|
||||
|
||||
vm.verifyTwoFactor("123456")
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals(LoginUiState.Success, vm.uiState.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `resetState_returns_to_Idle`() = runTest(dispatcher) {
|
||||
val vm = LoginViewModel(loginUseCase, verifyTwoFactorUseCase)
|
||||
vm.resetState()
|
||||
assertEquals(LoginUiState.Idle, vm.uiState.value)
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package com.heimdall.mobile.presentation.viewmodel
|
||||
|
||||
import com.heimdall.mobile.domain.model.Camera
|
||||
import com.heimdall.mobile.domain.usecase.GetCamerasBySiteUseCase
|
||||
import com.heimdall.mobile.domain.usecase.RefreshCamerasUseCase
|
||||
import io.mockk.coEvery
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.test.StandardTestDispatcher
|
||||
import kotlinx.coroutines.test.advanceUntilIdle
|
||||
import kotlinx.coroutines.test.resetMain
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.coroutines.test.setMain
|
||||
import org.junit.jupiter.api.AfterEach
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertFalse
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class SiteDetailViewModelTest {
|
||||
|
||||
private val getCamerasBySiteUseCase: GetCamerasBySiteUseCase = mockk()
|
||||
private val refreshCamerasUseCase: RefreshCamerasUseCase = mockk()
|
||||
private val dispatcher = StandardTestDispatcher()
|
||||
|
||||
private val camera = Camera("c1", "Cam 1", "s1", "rtsp://x", true, "http://snap", true)
|
||||
|
||||
@BeforeEach
|
||||
fun setUp() {
|
||||
Dispatchers.setMain(dispatcher)
|
||||
io.mockk.clearAllMocks()
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
fun tearDown() {
|
||||
Dispatchers.resetMain()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `loadSite_loads_cameras_and_stops_loading`() = runTest(dispatcher) {
|
||||
every { getCamerasBySiteUseCase("s1") } returns flowOf(listOf(camera))
|
||||
val vm = SiteDetailViewModel(getCamerasBySiteUseCase, refreshCamerasUseCase)
|
||||
|
||||
vm.loadSite("s1", "Site A")
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals("s1", vm.uiState.value.siteId)
|
||||
assertEquals("Site A", vm.uiState.value.siteName)
|
||||
assertEquals(listOf(camera), vm.uiState.value.cameras)
|
||||
assertFalse(vm.uiState.value.isLoading)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `refresh_success_updates_cameras_and_stops_loading`() = runTest(dispatcher) {
|
||||
every { getCamerasBySiteUseCase("s1") } returns flowOf(listOf(camera))
|
||||
val vm = SiteDetailViewModel(getCamerasBySiteUseCase, refreshCamerasUseCase)
|
||||
vm.loadSite("s1", "Site A")
|
||||
advanceUntilIdle()
|
||||
|
||||
val newCamera = camera.copy(name = "Cam 1 (renamed)")
|
||||
coEvery { refreshCamerasUseCase("s1") } returns Result.success(listOf(newCamera))
|
||||
|
||||
vm.refresh()
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals(listOf(newCamera), vm.uiState.value.cameras)
|
||||
assertFalse(vm.uiState.value.isLoading)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `refresh_failure_sets_error_and_stops_loading`() = runTest(dispatcher) {
|
||||
every { getCamerasBySiteUseCase("s1") } returns flowOf(listOf(camera))
|
||||
val vm = SiteDetailViewModel(getCamerasBySiteUseCase, refreshCamerasUseCase)
|
||||
vm.loadSite("s1", "Site A")
|
||||
advanceUntilIdle()
|
||||
|
||||
coEvery { refreshCamerasUseCase("s1") } returns Result.failure(IllegalStateException("Refresh failed"))
|
||||
|
||||
vm.refresh()
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals("Refresh failed", vm.uiState.value.error)
|
||||
assertFalse(vm.uiState.value.isLoading)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
google {
|
||||
content {
|
||||
includeGroupByRegex("com\\.android.*")
|
||||
includeGroupByRegex("com\\.google.*")
|
||||
includeGroupByRegex("androidx.*")
|
||||
}
|
||||
}
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
|
||||
dependencyResolutionManagement {
|
||||
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = "Heimdall"
|
||||
include(":app")
|
||||
include(":data")
|
||||
include(":domain")
|
||||
include(":presentation")
|
||||
+59
-1357
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user