feat: add provider login flow (#4)

## Summary

- replace the former three-provider model with two pre-login choices:
  - **ABox**: authenticate through the vendor ABSDK on the current local network
  - **Local experience**: establish a production simulation session without credentials, network access, or ABSDK calls
- remove the compatible-backend product/server scope and safely ignore legacy persisted compatible-provider values
- bind one process-wide `AbsdkBridge` for ABox session, socket, temperature/humidity, and infrared operations
- add production `:runtime:simulation` implementations and route device operations by the active provider
- retain provider-scoped username preferences, Keystore-encrypted automatic-login credentials, token recovery, logout, and session isolation
- add regression coverage for authentication gating, profile/session alignment, provider switching cleanup, routing, and simulation behavior
- align requirement, plan, architecture, and protocol documentation with LAN ABSDK access

## Verification

```text
./gradlew check testDebugUnitTest test
BUILD SUCCESSFUL (220 actionable tasks)

./gradlew :android:app:assembleDebug :android:app:assembleRelease
BUILD SUCCESSFUL (217 actionable tasks)

./gradlew :android:app:compileDebugAndroidTestKotlin
BUILD SUCCESSFUL

git diff --check
passed
```

Emulator smoke validation:

- provider selection displays ABox and Local experience only
- Local experience enters the authenticated route without credentials
- Local experience also enters while emulator Wi-Fi/data are disabled
- Local Sign out and Switch provider return to provider selection
- ABox opens the credential form; empty submission stays on login with the required-fields error

## Known constraints and accepted risks

- The vendor JAR uses cleartext HTTP and hardcodes `a-box.com.cn`; Debug and Release intentionally share the same ABox capability under the approved no-Release-exception decision. `@CleartextAbsdkTransport`, `usesCleartextTraffic`, and the architecture/protocol documents explicitly record this risk. This does not provide confidentiality or integrity.
- Real authenticated ABox and read-only hardware smoke validation is deferred because the gateway is currently unavailable locally. This PR does not claim that current-environment validation completed.
- The mapping from the vendor JAR's hardcoded hostname to the LAN gateway remains an external network/deployment prerequisite. The ABSDK JAR and bridge path remain identical to the previously hardware-validated `feat/moler-infrared-control` branch.
- `FakeDeviceCatalog` remains a temporary debug-only placeholder until the device-catalog module provides the production ABox catalog. ABox catalog requests are not routed to Local experience simulation.

Reviewed-on: #4
Co-authored-by: KremeCN <3265494849@qq.com>
This commit was merged in pull request #4.
This commit is contained in:
2026-08-25 01:59:00 +08:00
committed by KremeCN
parent 6f7d3248b0
commit 06ccfdf952
59 changed files with 4982 additions and 209 deletions
+18
View File
@@ -45,6 +45,15 @@ android {
kotlinOptions {
jvmTarget = "17"
}
packaging {
resources {
excludes += "/META-INF/{AL2.0,LGPL2.1}"
excludes += "/META-INF/DEPENDENCIES"
excludes += "/META-INF/LICENSE*"
excludes += "/META-INF/NOTICE*"
}
}
}
kapt {
@@ -54,12 +63,18 @@ kapt {
dependencies {
implementation(project(":domain"))
implementation(project(":android:core:designsystem"))
implementation(project(":android:core:session"))
implementation(project(":absdk-bridge"))
implementation(project(":runtime:simulation"))
debugImplementation(project(":testing:fakes"))
implementation(platform(libs.compose.bom))
implementation(libs.androidx.activity.compose)
implementation(libs.androidx.lifecycle.runtime.compose)
implementation(libs.androidx.lifecycle.viewmodel.ktx)
implementation(libs.androidx.lifecycle.viewmodel.compose)
implementation(libs.androidx.navigation.compose)
implementation(libs.datastore.preferences)
implementation(libs.androidx.hilt.navigation.compose)
implementation(libs.compose.ui)
implementation(libs.compose.ui.tooling.preview)
@@ -68,8 +83,11 @@ dependencies {
kapt(libs.hilt.compiler)
testImplementation(libs.junit)
testImplementation(libs.kotlinx.coroutines.test)
testImplementation(project(":testing:fakes"))
androidTestImplementation(platform(libs.compose.bom))
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.test.runner)
androidTestImplementation(libs.espresso.core)
androidTestImplementation(libs.compose.ui.test.junit4)
debugImplementation(libs.compose.ui.tooling)
@@ -0,0 +1,99 @@
package com.flagship.abox.manager.ui.login
import androidx.activity.ComponentActivity
import androidx.compose.ui.test.assertIsEnabled
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.flagship.abox.manager.designsystem.ABoxTheme
import com.flagship.abox.manager.domain.ProviderProfile
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.ProviderType
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class LoginScreenTest {
@get:Rule
val composeRule = createAndroidComposeRule<ComponentActivity>()
private val profile = ProviderProfile(
ProviderProfileId("abox"),
ProviderType.ABOX,
"ABox",
)
@Test
fun backControlsSwitchProviderBeforeLogin() {
var switches = 0
composeRule.setContent {
ABoxTheme {
LoginScreen(
profile = profile,
state = LoginUiState(),
onUsernameChange = {},
onPasswordChange = {},
onRememberUsernameChange = {},
onAutoLoginChange = {},
onSubmit = {},
onSwitchProvider = { switches++ },
)
}
}
composeRule.onNodeWithContentDescription("back-to-providers")
.assertIsEnabled()
.performClick()
composeRule.onNodeWithText("Back to providers").performClick()
assertEquals(2, switches)
}
@Test
fun systemBackIsConsumedWhileSubmitting() {
var switches = 0
composeRule.setContent {
ABoxTheme {
LoginScreen(
profile = profile,
state = LoginUiState(isSubmitting = true),
onUsernameChange = {},
onPasswordChange = {},
onRememberUsernameChange = {},
onAutoLoginChange = {},
onSubmit = {},
onSwitchProvider = { switches++ },
)
}
}
composeRule.activity.onBackPressedDispatcher.onBackPressed()
composeRule.waitForIdle()
assertEquals(0, switches)
}
@Test
fun backControlsAreDisabledWhileSubmitting() {
composeRule.setContent {
ABoxTheme {
LoginScreen(
profile = profile,
state = LoginUiState(isSubmitting = true),
onUsernameChange = {},
onPasswordChange = {},
onRememberUsernameChange = {},
onAutoLoginChange = {},
onSubmit = {},
onSwitchProvider = {},
)
}
}
composeRule.onNodeWithContentDescription("back-to-providers").assertIsNotEnabled()
composeRule.onNodeWithText("Back to providers").assertIsNotEnabled()
}
}
@@ -0,0 +1,46 @@
package com.flagship.abox.manager.ui.provider
import androidx.activity.ComponentActivity
import androidx.compose.ui.test.assertIsEnabled
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.flagship.abox.manager.designsystem.ABoxTheme
import com.flagship.abox.manager.domain.ProviderProfile
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.ProviderType
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ProviderSelectionScreenTest {
@get:Rule
val composeRule = createAndroidComposeRule<ComponentActivity>()
@Test
fun aboxAndLocalExperienceAreBothSelectableAndNoCompatibleOptionIsShown() {
val abox = ProviderProfile(ProviderProfileId("abox"), ProviderType.ABOX, "ABox")
val local = ProviderProfile(
ProviderProfileId("local"),
ProviderType.LOCAL_EXPERIENCE,
"Local",
)
var selected: ProviderProfile? = null
composeRule.setContent {
ABoxTheme {
ProviderSelectionScreen(
state = ProviderSelectionUiState(listOf(abox, local)),
onSelect = { selected = it },
)
}
}
composeRule.onNodeWithText("ABox").assertIsEnabled()
composeRule.onNodeWithText("Local experience").assertIsEnabled().performClick()
assertEquals(local, selected)
composeRule.onNodeWithText("Compatible backend").assertDoesNotExist()
}
}
@@ -1,15 +1,7 @@
package com.flagship.abox.manager.di
import com.flagship.abox.manager.domain.DeviceCatalog
import com.flagship.abox.manager.domain.InfraredGateway
import com.flagship.abox.manager.domain.SessionGateway
import com.flagship.abox.manager.domain.SocketGateway
import com.flagship.abox.manager.domain.TemperatureHumidityGateway
import com.flagship.abox.manager.testing.fakes.FakeDeviceCatalog
import com.flagship.abox.manager.testing.fakes.FakeInfraredGateway
import com.flagship.abox.manager.testing.fakes.FakeSessionGateway
import com.flagship.abox.manager.testing.fakes.FakeSocketGateway
import com.flagship.abox.manager.testing.fakes.FakeTemperatureHumidityGateway
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
@@ -19,24 +11,12 @@ import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object FoundationModule {
@Provides
@Singleton
fun provideSessionGateway(): SessionGateway = FakeSessionGateway()
// TEMPORARY boundary: ABSDK has no device catalog, and the provider-scoped production
// ABox catalog is owned by the device-catalog module. Until that exists, debug builds
// keep the fake ABox catalog here. Do NOT route ABox catalog requests to
// SimulationDeviceCatalog; release builds must not request a DeviceCatalog binding
// until a real release consumer appears.
@Provides
@Singleton
fun provideDeviceCatalog(): DeviceCatalog = FakeDeviceCatalog()
@Provides
@Singleton
fun provideSocketGateway(): SocketGateway = FakeSocketGateway()
@Provides
@Singleton
fun provideTemperatureHumidityGateway(): TemperatureHumidityGateway =
FakeTemperatureHumidityGateway()
@Provides
@Singleton
fun provideInfraredGateway(): InfraredGateway = FakeInfraredGateway()
}
+2
View File
@@ -1,9 +1,11 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".ABoxManagerApplication"
android:allowBackup="false"
android:label="@string/app_name"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="@style/Theme.ABoxManager">
<activity
android:name=".MainActivity"
@@ -0,0 +1,62 @@
package com.flagship.abox.manager.di
import com.flagship.abox.manager.absdk.bridge.AbsdkBridge
import com.flagship.abox.manager.domain.InfraredGateway
import com.flagship.abox.manager.domain.ProviderProfileStore
import com.flagship.abox.manager.domain.SocketGateway
import com.flagship.abox.manager.domain.TemperatureHumidityGateway
import com.flagship.abox.manager.simulation.SimulationInfraredGateway
import com.flagship.abox.manager.simulation.SimulationSocketGateway
import com.flagship.abox.manager.simulation.SimulationTemperatureHumidityGateway
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
/**
* Binds each public device gateway to a router that dispatches on the active provider:
* ABox goes to the shared real [AbsdkBridge] and local experience goes to the shared
* production simulation gateway.
*/
@Module
@InstallIn(SingletonComponent::class)
object DeviceGatewayModule {
@Provides
@Singleton
fun provideSimulationSocketGateway(): SimulationSocketGateway = SimulationSocketGateway()
@Provides
@Singleton
fun provideSimulationTemperatureHumidityGateway(): SimulationTemperatureHumidityGateway =
SimulationTemperatureHumidityGateway()
@Provides
@Singleton
fun provideSimulationInfraredGateway(): SimulationInfraredGateway = SimulationInfraredGateway()
@Provides
@Singleton
fun provideSocketGateway(
profileStore: ProviderProfileStore,
bridge: AbsdkBridge,
simulation: SimulationSocketGateway,
): SocketGateway = RoutingSocketGateway(profileStore, bridge, simulation)
@Provides
@Singleton
fun provideTemperatureHumidityGateway(
profileStore: ProviderProfileStore,
bridge: AbsdkBridge,
simulation: SimulationTemperatureHumidityGateway,
): TemperatureHumidityGateway =
RoutingTemperatureHumidityGateway(profileStore, bridge, simulation)
@Provides
@Singleton
fun provideInfraredGateway(
profileStore: ProviderProfileStore,
bridge: AbsdkBridge,
simulation: SimulationInfraredGateway,
): InfraredGateway = RoutingInfraredGateway(profileStore, bridge, simulation)
}
@@ -0,0 +1,140 @@
package com.flagship.abox.manager.di
import com.flagship.abox.manager.domain.DeviceName
import com.flagship.abox.manager.domain.DomainError
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.InfraredCode
import com.flagship.abox.manager.domain.InfraredCodeDownloadResult
import com.flagship.abox.manager.domain.InfraredGateway
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.ProviderProfileStore
import com.flagship.abox.manager.domain.ProviderType
import com.flagship.abox.manager.domain.SocketGateway
import com.flagship.abox.manager.domain.SocketPowerState
import com.flagship.abox.manager.domain.SocketStatus
import com.flagship.abox.manager.domain.TemperatureHumidityGateway
import com.flagship.abox.manager.domain.TemperatureHumidityReading
import kotlinx.coroutines.CancellationException
/**
* Resolves the provider type a device operation must be routed to.
*
* A device call is only valid for the currently active provider profile: a missing
* active profile or a mismatched [profileId] is rejected with [DomainError.InvalidRequest]
* before any gateway is invoked.
*/
internal class ActiveProviderGatewayResolver(
private val profileStore: ProviderProfileStore,
) {
suspend fun resolve(profileId: ProviderProfileId): DomainResult<ProviderType> = try {
val active = profileStore.activeProfile()
when {
active == null ->
DomainResult.Failure(DomainError.InvalidRequest(detail = "No active provider"))
active.id != profileId ->
DomainResult.Failure(
DomainError.InvalidRequest(detail = "Provider profile is not active"),
)
else -> DomainResult.Success(active.type)
}
} catch (error: CancellationException) {
throw error
} catch (error: Exception) {
DomainResult.Failure(
DomainError.Unknown(detail = error.message ?: error::class.java.simpleName),
)
}
}
/** Routes socket operations to the real ABSDK bridge or the simulation gateway by active provider. */
internal class RoutingSocketGateway(
profileStore: ProviderProfileStore,
private val real: SocketGateway,
private val simulation: SocketGateway,
) : SocketGateway {
private val resolver = ActiveProviderGatewayResolver(profileStore)
override suspend fun getStatus(
profileId: ProviderProfileId,
deviceName: DeviceName,
): DomainResult<SocketStatus> = when (val provider = resolver.resolve(profileId)) {
is DomainResult.Failure -> provider
is DomainResult.Success -> delegate(provider.value).getStatus(profileId, deviceName)
}
override suspend fun setPower(
profileId: ProviderProfileId,
deviceName: DeviceName,
powerState: SocketPowerState,
): DomainResult<SocketStatus> = when (val provider = resolver.resolve(profileId)) {
is DomainResult.Failure -> provider
is DomainResult.Success -> delegate(provider.value).setPower(profileId, deviceName, powerState)
}
private fun delegate(type: ProviderType): SocketGateway = when (type) {
ProviderType.ABOX -> real
ProviderType.LOCAL_EXPERIENCE -> simulation
}
}
/** Routes temperature/humidity operations by active provider, mirroring [RoutingSocketGateway]. */
internal class RoutingTemperatureHumidityGateway(
profileStore: ProviderProfileStore,
private val real: TemperatureHumidityGateway,
private val simulation: TemperatureHumidityGateway,
) : TemperatureHumidityGateway {
private val resolver = ActiveProviderGatewayResolver(profileStore)
override suspend fun getReading(
profileId: ProviderProfileId,
deviceName: DeviceName,
): DomainResult<TemperatureHumidityReading> = when (val provider = resolver.resolve(profileId)) {
is DomainResult.Failure -> provider
is DomainResult.Success -> delegate(provider.value).getReading(profileId, deviceName)
}
private fun delegate(type: ProviderType): TemperatureHumidityGateway = when (type) {
ProviderType.ABOX -> real
ProviderType.LOCAL_EXPERIENCE -> simulation
}
}
/** Routes infrared operations by active provider, mirroring [RoutingSocketGateway]. */
internal class RoutingInfraredGateway(
profileStore: ProviderProfileStore,
private val real: InfraredGateway,
private val simulation: InfraredGateway,
) : InfraredGateway {
private val resolver = ActiveProviderGatewayResolver(profileStore)
override suspend fun sendKey(
profileId: ProviderProfileId,
deviceName: DeviceName,
key: String,
): DomainResult<Unit> = when (val provider = resolver.resolve(profileId)) {
is DomainResult.Failure -> provider
is DomainResult.Success -> delegate(provider.value).sendKey(profileId, deviceName, key)
}
override suspend fun learnKey(
profileId: ProviderProfileId,
deviceName: DeviceName,
key: String,
): DomainResult<Unit> = when (val provider = resolver.resolve(profileId)) {
is DomainResult.Failure -> provider
is DomainResult.Success -> delegate(provider.value).learnKey(profileId, deviceName, key)
}
override suspend fun downloadCodes(
profileId: ProviderProfileId,
codes: List<InfraredCode>,
): DomainResult<List<InfraredCodeDownloadResult>> = when (val provider = resolver.resolve(profileId)) {
is DomainResult.Failure -> provider
is DomainResult.Success -> delegate(provider.value).downloadCodes(profileId, codes)
}
private fun delegate(type: ProviderType): InfraredGateway = when (type) {
ProviderType.ABOX -> real
ProviderType.LOCAL_EXPERIENCE -> simulation
}
}
@@ -0,0 +1,80 @@
package com.flagship.abox.manager.di
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import com.flagship.abox.manager.absdk.bridge.AbsdkBridge
import com.flagship.abox.manager.absdk.bridge.CleartextAbsdkTransport
import com.flagship.abox.manager.domain.CredentialStore
import com.flagship.abox.manager.domain.LocalSessionGateway
import com.flagship.abox.manager.domain.ProviderProfileStore
import com.flagship.abox.manager.domain.SessionCoordinator
import com.flagship.abox.manager.domain.SessionGateway
import com.flagship.abox.manager.session.credential.AndroidKeystoreCredentialCipher
import com.flagship.abox.manager.session.credential.CredentialCipher
import com.flagship.abox.manager.session.credential.KeystoreCredentialStore
import com.flagship.abox.manager.session.profile.ProviderProfileStoreImpl
import com.flagship.abox.manager.session.profile.sessionDataStore
import com.flagship.abox.manager.simulation.SimulationSessionGateway
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 SessionModule {
@Provides
@Singleton
fun provideSessionDataStore(
@ApplicationContext context: Context,
): DataStore<Preferences> = context.sessionDataStore
@Provides
@Singleton
fun provideProviderProfileStore(
dataStore: DataStore<Preferences>,
): ProviderProfileStore = ProviderProfileStoreImpl(dataStore)
@Provides
@Singleton
fun provideCredentialCipher(): CredentialCipher = AndroidKeystoreCredentialCipher()
@Provides
@Singleton
fun provideCredentialStore(
dataStore: DataStore<Preferences>,
cipher: CredentialCipher,
): CredentialStore = KeystoreCredentialStore(dataStore, cipher)
@Provides
@Singleton
@OptIn(CleartextAbsdkTransport::class)
fun provideAbsdkBridge(): AbsdkBridge = AbsdkBridge.create()
@Provides
@Singleton
fun provideRemoteSessionGateway(
bridge: AbsdkBridge,
): SessionGateway = bridge
@Provides
@Singleton
fun provideLocalSessionGateway(): LocalSessionGateway = SimulationSessionGateway()
@Provides
@Singleton
fun provideSessionCoordinator(
profileStore: ProviderProfileStore,
credentialStore: CredentialStore,
remoteGateway: SessionGateway,
localGateway: LocalSessionGateway,
): SessionCoordinator = SessionCoordinator(
profileStore,
credentialStore,
remoteGateway,
localGateway,
)
}
@@ -1,94 +1,77 @@
package com.flagship.abox.manager.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.flagship.abox.manager.R
import com.flagship.abox.manager.designsystem.ABoxButton
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.flagship.abox.manager.designsystem.ABoxLoadingIndicator
import com.flagship.abox.manager.designsystem.ABoxSurface
import com.flagship.abox.manager.designsystem.ABoxTheme
private const val FOUNDATION_ROUTE = "foundation"
private const val PLACEHOLDER_ROUTE = "placeholder"
import com.flagship.abox.manager.ui.authenticated.AuthenticatedPlaceholderScreen
import com.flagship.abox.manager.ui.login.LoginRoute
import com.flagship.abox.manager.ui.login.LoginViewModel
import com.flagship.abox.manager.ui.provider.ProviderSelectionRoute
import com.flagship.abox.manager.ui.session.AppSessionUiState
import com.flagship.abox.manager.ui.session.AppSessionViewModel
import com.flagship.abox.manager.ui.session.SessionActionsViewModel
@Composable
fun ABoxManagerApp() {
fun ABoxManagerApp(
appSessionViewModel: AppSessionViewModel = hiltViewModel(),
sessionActionsViewModel: SessionActionsViewModel = hiltViewModel(),
loginViewModel: LoginViewModel = hiltViewModel(),
) {
val actionState = sessionActionsViewModel.uiState.collectAsStateWithLifecycle().value
val sessionState = appSessionViewModel.uiState.collectAsStateWithLifecycle().value
val screenKey = sessionState.screenKey()
LaunchedEffect(screenKey) {
sessionActionsViewModel.dismissError()
if (sessionState !is AppSessionUiState.Login) {
loginViewModel.clearSensitiveState()
}
}
ABoxTheme {
ABoxSurface(modifier = Modifier.fillMaxSize()) {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = FOUNDATION_ROUTE,
) {
composable(FOUNDATION_ROUTE) {
FoundationScreen(onContinue = { navController.navigate(PLACEHOLDER_ROUTE) })
}
composable(PLACEHOLDER_ROUTE) {
MessageScreen(
title = stringResource(R.string.placeholder_title),
description = stringResource(R.string.placeholder_description),
)
when (val state = sessionState) {
AppSessionUiState.Loading -> Box(
modifier = Modifier
.fillMaxSize()
.windowInsetsPadding(WindowInsets.safeDrawing),
contentAlignment = Alignment.Center,
) {
ABoxLoadingIndicator()
}
AppSessionUiState.ProviderSelection -> ProviderSelectionRoute()
is AppSessionUiState.Login -> LoginRoute(
profile = state.profile,
bootstrapError = state.bootstrapError,
actionError = actionState.errorMessage,
actionInProgress = actionState.inProgress,
onSwitchProvider = sessionActionsViewModel::switchProvider,
viewModel = loginViewModel,
)
is AppSessionUiState.Authenticated -> AuthenticatedPlaceholderScreen(
profile = state.profile,
actionInProgress = actionState.inProgress,
errorMessage = actionState.errorMessage,
onLogout = sessionActionsViewModel::logout,
onSwitchProvider = sessionActionsViewModel::switchProvider,
)
}
}
}
}
@Composable
private fun FoundationScreen(onContinue: () -> Unit) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(32.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
MessageScreen(
title = stringResource(R.string.foundation_title),
description = stringResource(R.string.foundation_description),
)
ABoxButton(
onClick = onContinue,
modifier = Modifier
.fillMaxWidth()
.padding(top = 24.dp),
) {
Text(stringResource(R.string.continue_action))
}
}
}
@Composable
private fun MessageScreen(
title: String,
description: String,
) {
Column(
modifier = Modifier.padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Text(
text = title,
style = androidx.compose.material3.MaterialTheme.typography.headlineMedium,
textAlign = TextAlign.Center,
)
Text(
text = description,
style = androidx.compose.material3.MaterialTheme.typography.bodyLarge,
textAlign = TextAlign.Center,
)
}
private fun AppSessionUiState.screenKey(): String = when (this) {
AppSessionUiState.Loading -> "loading"
AppSessionUiState.ProviderSelection -> "providers"
is AppSessionUiState.Login -> "login:${profile.id.value}"
is AppSessionUiState.Authenticated -> "authenticated:${profile.id.value}"
}
@@ -0,0 +1,79 @@
package com.flagship.abox.manager.ui.authenticated
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.flagship.abox.manager.R
import com.flagship.abox.manager.designsystem.ABoxButton
import com.flagship.abox.manager.domain.ProviderProfile
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AuthenticatedPlaceholderScreen(
profile: ProviderProfile,
actionInProgress: Boolean,
errorMessage: String?,
onLogout: () -> Unit,
onSwitchProvider: () -> Unit,
) {
Scaffold(
topBar = {
TopAppBar(
title = { Text(stringResource(R.string.authenticated_title, profile.displayName)) },
)
},
) { contentPadding ->
Box(
modifier = Modifier
.fillMaxSize()
.padding(contentPadding),
contentAlignment = Alignment.Center,
) {
Column(
modifier = Modifier
.widthIn(max = 520.dp)
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
Text(
text = stringResource(R.string.authenticated_description),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
errorMessage?.let { Text(it, color = MaterialTheme.colorScheme.error) }
ABoxButton(
onClick = onLogout,
enabled = !actionInProgress,
modifier = Modifier.fillMaxWidth(),
) {
Text(stringResource(R.string.action_logout))
}
ABoxButton(
onClick = onSwitchProvider,
enabled = !actionInProgress,
modifier = Modifier.fillMaxWidth(),
) {
Text(stringResource(R.string.action_switch_provider))
}
}
}
}
}
@@ -0,0 +1,235 @@
package com.flagship.abox.manager.ui.login
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.flagship.abox.manager.R
import com.flagship.abox.manager.designsystem.ABoxButton
import com.flagship.abox.manager.designsystem.ABoxLoadingIndicator
import com.flagship.abox.manager.domain.ProviderProfile
import com.flagship.abox.manager.domain.ProviderType
@Composable
fun LoginRoute(
profile: ProviderProfile,
bootstrapError: String? = null,
actionError: String? = null,
actionInProgress: Boolean = false,
onSwitchProvider: () -> Unit,
viewModel: LoginViewModel = hiltViewModel(),
) {
LaunchedEffect(profile.id) { viewModel.loadProfile(profile) }
val state = viewModel.uiState.collectAsStateWithLifecycle().value
val errorText = state.errorMessage?.let { stringResource(it.stringResource()) }
?: actionError
?: bootstrapError
LoginScreen(
profile = profile,
state = state,
errorText = errorText,
onUsernameChange = viewModel::setUsername,
onPasswordChange = viewModel::setPassword,
onRememberUsernameChange = viewModel::setRememberUsername,
onAutoLoginChange = viewModel::setAutoLogin,
onSubmit = viewModel::submit,
onSwitchProvider = onSwitchProvider,
switchingProvider = actionInProgress,
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LoginScreen(
profile: ProviderProfile,
state: LoginUiState,
errorText: String? = null,
onUsernameChange: (String) -> Unit,
onPasswordChange: (String) -> Unit,
onRememberUsernameChange: (Boolean) -> Unit,
onAutoLoginChange: (Boolean) -> Unit,
onSubmit: () -> Unit,
onSwitchProvider: () -> Unit,
switchingProvider: Boolean = false,
) {
val formEnabled = !state.isSubmitting && !state.isLoadingPreferences
val navigationEnabled = formEnabled && !switchingProvider
BackHandler {
if (navigationEnabled) onSwitchProvider()
}
Scaffold(
topBar = {
TopAppBar(
title = { Text(stringResource(R.string.login_title, providerName(profile.type))) },
navigationIcon = {
IconButton(
onClick = onSwitchProvider,
enabled = navigationEnabled,
modifier = Modifier.semantics {
contentDescription = "back-to-providers"
},
) {
Text(
text = "‹",
style = MaterialTheme.typography.headlineMedium,
modifier = Modifier.padding(bottom = 4.dp),
)
}
},
)
},
) { contentPadding ->
Box(
modifier = Modifier
.fillMaxSize()
.padding(contentPadding),
contentAlignment = Alignment.TopCenter,
) {
Column(
modifier = Modifier
.widthIn(max = 520.dp)
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(horizontal = 24.dp, vertical = 16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
OutlinedCard(modifier = Modifier.fillMaxWidth()) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Text(
stringResource(R.string.login_provider_context, providerName(profile.type)),
style = MaterialTheme.typography.titleMedium,
)
Text(
providerDescription(profile.type),
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
OutlinedTextField(
value = state.username,
onValueChange = onUsernameChange,
label = { Text(stringResource(R.string.login_username)) },
enabled = formEnabled,
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = state.password,
onValueChange = onPasswordChange,
label = { Text(stringResource(R.string.login_password)) },
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Password,
imeAction = ImeAction.Done,
autoCorrect = false,
),
enabled = formEnabled,
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
ToggleRow(
label = stringResource(R.string.login_remember_username),
checked = state.rememberUsername,
enabled = formEnabled,
onCheckedChange = onRememberUsernameChange,
)
ToggleRow(
label = stringResource(R.string.login_auto_login),
checked = state.autoLogin,
enabled = formEnabled,
onCheckedChange = onAutoLoginChange,
)
errorText?.let { Text(it, color = MaterialTheme.colorScheme.error) }
ABoxButton(
onClick = onSubmit,
enabled = formEnabled && !switchingProvider,
modifier = Modifier.fillMaxWidth(),
) {
if (state.isSubmitting || state.isLoadingPreferences || switchingProvider) {
ABoxLoadingIndicator()
}
else Text(stringResource(R.string.action_login))
}
ABoxButton(
onClick = onSwitchProvider,
enabled = navigationEnabled,
modifier = Modifier.fillMaxWidth(),
) {
Text(stringResource(R.string.login_back_to_providers))
}
}
}
}
}
@Composable
private fun ToggleRow(
label: String,
checked: Boolean,
enabled: Boolean,
onCheckedChange: (Boolean) -> Unit,
) {
Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Checkbox(checked = checked, onCheckedChange = onCheckedChange, enabled = enabled)
Text(label)
}
}
private fun LoginErrorMessage.stringResource(): Int = when (this) {
LoginErrorMessage.REQUIRED_FIELDS -> R.string.login_error_required
LoginErrorMessage.INVALID_CREDENTIALS -> R.string.login_error_invalid_credentials
LoginErrorMessage.NETWORK_UNAVAILABLE -> R.string.login_error_network
LoginErrorMessage.SESSION_EXPIRED -> R.string.login_error_session_expired
LoginErrorMessage.PREFERENCES_UNAVAILABLE -> R.string.login_error_preferences
LoginErrorMessage.LOGIN_FAILED -> R.string.login_error_failed
}
@Composable
private fun providerName(type: ProviderType): String = stringResource(
when (type) {
ProviderType.ABOX -> R.string.provider_abox_name
ProviderType.LOCAL_EXPERIENCE -> R.string.provider_local_name
},
)
@Composable
private fun providerDescription(type: ProviderType): String = stringResource(
when (type) {
ProviderType.ABOX -> R.string.provider_abox_description
ProviderType.LOCAL_EXPERIENCE -> R.string.provider_local_description
},
)
@@ -0,0 +1,181 @@
package com.flagship.abox.manager.ui.login
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.flagship.abox.manager.domain.DomainError
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.LoginCredentials
import com.flagship.abox.manager.domain.Password
import com.flagship.abox.manager.domain.ProviderProfile
import com.flagship.abox.manager.domain.ProviderProfileStore
import com.flagship.abox.manager.domain.SessionCoordinator
import com.flagship.abox.manager.domain.Username
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
@HiltViewModel
class LoginViewModel @Inject constructor(
private val coordinator: SessionCoordinator,
private val profileStore: ProviderProfileStore,
) : ViewModel() {
private val _uiState = MutableStateFlow(LoginUiState())
val uiState: StateFlow<LoginUiState> = _uiState.asStateFlow()
private var profile: ProviderProfile? = null
private var loadingJob: Job? = null
private var submitJob: Job? = null
private var usernameEdited = false
private var rememberUsernameEdited = false
private var autoLoginEdited = false
private var loadedProfileId: com.flagship.abox.manager.domain.ProviderProfileId? = null
fun loadProfile(value: ProviderProfile) {
if (loadedProfileId == value.id ||
profile?.id == value.id &&
(loadingJob?.isActive == true || submitJob?.isActive == true)
) return
loadingJob?.cancel()
profile = value
usernameEdited = false
rememberUsernameEdited = false
autoLoginEdited = false
_uiState.value = LoginUiState(isLoadingPreferences = true)
loadingJob = viewModelScope.launch {
try {
val preferences = profileStore.loginPreferences(value.id)
if (profile?.id != value.id) return@launch
_uiState.value = _uiState.value.copy(
username = if (usernameEdited) {
_uiState.value.username
} else {
preferences.rememberedUsername?.value.orEmpty()
},
rememberUsername = if (rememberUsernameEdited) {
_uiState.value.rememberUsername
} else {
preferences.rememberUsername
},
autoLogin = if (autoLoginEdited) {
_uiState.value.autoLogin
} else {
preferences.autoLoginEnabled
},
isLoadingPreferences = false,
)
loadedProfileId = value.id
} catch (error: CancellationException) {
throw error
} catch (_: Exception) {
if (profile?.id == value.id) {
_uiState.value = _uiState.value.copy(
isLoadingPreferences = false,
errorMessage = LoginErrorMessage.PREFERENCES_UNAVAILABLE,
)
}
} finally {
loadingJob = null
}
}
}
fun clearSensitiveState() {
loadingJob?.cancel()
loadingJob = null
if (submitJob?.isActive == true) {
_uiState.value = _uiState.value.copy(
password = "",
errorMessage = null,
isSubmitting = true,
)
return
}
profile = null
loadedProfileId = null
usernameEdited = false
rememberUsernameEdited = false
autoLoginEdited = false
_uiState.value = LoginUiState()
}
fun setUsername(value: String) {
usernameEdited = true
_uiState.value = _uiState.value.copy(username = value, errorMessage = null)
}
fun setPassword(value: String) {
_uiState.value = _uiState.value.copy(password = value, errorMessage = null)
}
fun setRememberUsername(value: Boolean) {
rememberUsernameEdited = true
_uiState.value = _uiState.value.copy(rememberUsername = value)
}
fun setAutoLogin(value: Boolean) {
autoLoginEdited = true
_uiState.value = _uiState.value.copy(autoLogin = value)
}
fun submit() {
if (submitJob?.isActive == true) return
val activeProfile = profile ?: return
val state = _uiState.value
if (state.username.isBlank() ||
state.password.isEmpty() ||
state.isSubmitting ||
state.isLoadingPreferences
) {
_uiState.value = state.copy(errorMessage = LoginErrorMessage.REQUIRED_FIELDS)
return
}
submitJob = viewModelScope.launch {
try {
_uiState.value = state.copy(isSubmitting = true, errorMessage = null)
val result = coordinator.login(
activeProfile.id,
LoginCredentials(Username(state.username.trim()), Password(state.password)),
rememberUsername = state.rememberUsername,
autoLogin = state.autoLogin,
)
_uiState.value = _uiState.value.copy(
password = "",
isSubmitting = false,
errorMessage = (result as? DomainResult.Failure)?.error?.toUiMessage(),
)
} finally {
submitJob = null
}
}
}
private fun DomainError.toUiMessage(): LoginErrorMessage = when (this) {
is DomainError.Authentication -> LoginErrorMessage.INVALID_CREDENTIALS
is DomainError.Network -> LoginErrorMessage.NETWORK_UNAVAILABLE
is DomainError.TokenInvalid -> LoginErrorMessage.SESSION_EXPIRED
else -> LoginErrorMessage.LOGIN_FAILED
}
}
enum class LoginErrorMessage {
REQUIRED_FIELDS,
INVALID_CREDENTIALS,
NETWORK_UNAVAILABLE,
SESSION_EXPIRED,
PREFERENCES_UNAVAILABLE,
LOGIN_FAILED,
}
data class LoginUiState(
val username: String = "",
val password: String = "",
val rememberUsername: Boolean = false,
val autoLogin: Boolean = false,
val isLoadingPreferences: Boolean = false,
val isSubmitting: Boolean = false,
val errorMessage: LoginErrorMessage? = null,
)
@@ -0,0 +1,10 @@
package com.flagship.abox.manager.ui.navigation
object Routes {
const val STARTUP = "startup"
const val PROVIDER_SELECTION = "provider_selection"
const val LOGIN = "login"
/** Login-complete route contract; the device navigation owner replaces its placeholder. */
const val AUTHENTICATED = "authenticated"
}
@@ -0,0 +1,183 @@
package com.flagship.abox.manager.ui.provider
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.flagship.abox.manager.R
import com.flagship.abox.manager.designsystem.ABoxLoadingIndicator
import com.flagship.abox.manager.domain.ProviderProfile
import com.flagship.abox.manager.domain.ProviderType
@Composable
fun ProviderSelectionRoute(
viewModel: ProviderSelectionViewModel = hiltViewModel(),
) {
val state = viewModel.uiState.collectAsStateWithLifecycle().value
ProviderSelectionScreen(state = state, onSelect = viewModel::select)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProviderSelectionScreen(
state: ProviderSelectionUiState,
onSelect: (ProviderProfile) -> Unit,
) {
Scaffold(
topBar = {
TopAppBar(title = { Text(stringResource(R.string.provider_selection_title)) })
},
) { contentPadding ->
Box(
modifier = Modifier
.fillMaxSize()
.padding(contentPadding),
contentAlignment = Alignment.TopCenter,
) {
Column(
modifier = Modifier
.widthIn(max = 640.dp)
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(horizontal = 20.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
Text(
text = stringResource(R.string.provider_selection_description),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(bottom = 6.dp),
)
state.providers.forEach { profile ->
ProviderOptionCard(
profile = profile,
selecting = state.isSelecting,
onSelect = onSelect,
)
}
state.errorMessage?.let {
Text(it, color = MaterialTheme.colorScheme.error)
}
if (state.isSelecting) {
ABoxLoadingIndicator(
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(16.dp),
)
}
Spacer(Modifier.padding(bottom = 12.dp))
}
}
}
}
@Composable
private fun ProviderOptionCard(
profile: ProviderProfile,
selecting: Boolean,
onSelect: (ProviderProfile) -> Unit,
) {
val displayName = providerName(profile.type)
val description = providerDescription(profile.type)
OutlinedCard(
onClick = { onSelect(profile) },
enabled = !selecting,
shape = MaterialTheme.shapes.medium,
colors = CardDefaults.outlinedCardColors(
containerColor = MaterialTheme.colorScheme.surface,
),
modifier = Modifier
.fillMaxWidth()
.semantics {
role = Role.Button
contentDescription = displayName
},
) {
Row(
modifier = Modifier.padding(18.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(16.dp),
) {
Box(
modifier = Modifier
.size(48.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.primary.copy(alpha = 0.16f)),
contentAlignment = Alignment.Center,
) {
Text(
text = providerMark(profile.type),
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.primary,
)
}
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
Text(displayName, style = MaterialTheme.typography.titleMedium)
Text(
description,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Text(
"›",
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.primary,
)
}
}
}
@Composable
private fun providerName(type: ProviderType): String = stringResource(
when (type) {
ProviderType.ABOX -> R.string.provider_abox_name
ProviderType.LOCAL_EXPERIENCE -> R.string.provider_local_name
},
)
@Composable
private fun providerDescription(type: ProviderType): String = stringResource(
when (type) {
ProviderType.ABOX -> R.string.provider_abox_description
ProviderType.LOCAL_EXPERIENCE -> R.string.provider_local_description
},
)
private fun providerMark(type: ProviderType): String = when (type) {
ProviderType.ABOX -> "A"
ProviderType.LOCAL_EXPERIENCE -> "L"
}
@@ -0,0 +1,52 @@
package com.flagship.abox.manager.ui.provider
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.ProviderProfile
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.ProviderType
import com.flagship.abox.manager.domain.SessionCoordinator
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
@HiltViewModel
class ProviderSelectionViewModel @Inject constructor(
private val coordinator: SessionCoordinator,
) : ViewModel() {
private val _uiState = MutableStateFlow(ProviderSelectionUiState(providers = PROFILES))
val uiState: StateFlow<ProviderSelectionUiState> = _uiState.asStateFlow()
fun select(profile: ProviderProfile) {
if (_uiState.value.isSelecting) return
viewModelScope.launch {
_uiState.value = _uiState.value.copy(isSelecting = true, errorMessage = null)
val result = coordinator.selectProvider(profile)
_uiState.value = _uiState.value.copy(
isSelecting = false,
errorMessage = (result as? DomainResult.Failure)?.error?.detail,
)
}
}
companion object {
private val PROFILES = listOf(
ProviderProfile(ProviderProfileId("abox-default"), ProviderType.ABOX, "ABox"),
ProviderProfile(
ProviderProfileId("local-experience"),
ProviderType.LOCAL_EXPERIENCE,
"Local experience",
),
)
}
}
data class ProviderSelectionUiState(
val providers: List<ProviderProfile>,
val isSelecting: Boolean = false,
val errorMessage: String? = null,
)
@@ -0,0 +1,127 @@
package com.flagship.abox.manager.ui.session
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.ProviderProfile
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.ProviderProfileStore
import com.flagship.abox.manager.domain.Session
import com.flagship.abox.manager.domain.SessionCoordinator
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
@HiltViewModel
class AppSessionViewModel @Inject constructor(
private val coordinator: SessionCoordinator,
private val profileStore: ProviderProfileStore,
) : ViewModel() {
private val bootstrapResult = MutableStateFlow<ProviderBootstrapResult?>(null)
val uiState: StateFlow<AppSessionUiState> = combine(
bootstrapResult,
profileStore.observeActiveProfile(),
coordinator.observeActiveSession(),
) { bootstrap, profile, session ->
if (bootstrap == null) AppSessionUiState.Loading
else stateFor(
profile = profile,
session = session,
bootstrapError = bootstrap.errorFor(profile?.id),
)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = AppSessionUiState.Loading,
)
init {
viewModelScope.launch {
try {
val activeProfile = profileStore.activeProfile()
bootstrapResult.value = ProviderBootstrapResult(
profileId = activeProfile?.id,
result = coordinator.bootstrap(),
)
} catch (error: kotlinx.coroutines.CancellationException) {
throw error
} catch (error: Exception) {
bootstrapResult.value = ProviderBootstrapResult(
profileId = null,
result = DomainResult.Failure(
com.flagship.abox.manager.domain.DomainError.Unknown(
detail = error.message ?: "Unable to load provider settings",
),
),
)
}
}
viewModelScope.launch {
coordinator.observeActiveSession()
.map { it?.profileId }
.distinctUntilChanged()
.collect { sessionProfileId ->
if (sessionProfileId != null && bootstrapResult.value?.profileId == sessionProfileId) {
bootstrapResult.value = ProviderBootstrapResult(
profileId = sessionProfileId,
result = DomainResult.Success(null),
)
}
}
}
viewModelScope.launch {
profileStore.observeActiveProfile()
.map { it?.id }
.distinctUntilChanged()
.collect { activeProfileId ->
val currentBootstrap = bootstrapResult.value
if (currentBootstrap != null && currentBootstrap.profileId != activeProfileId) {
bootstrapResult.value = ProviderBootstrapResult(
profileId = activeProfileId,
result = DomainResult.Success(null),
)
}
}
}
}
private fun stateFor(
profile: ProviderProfile?,
session: Session?,
bootstrapError: String?,
): AppSessionUiState = when {
profile == null -> AppSessionUiState.ProviderSelection
session?.profileId == profile.id -> AppSessionUiState.Authenticated(profile)
else -> AppSessionUiState.Login(profile, bootstrapError)
}
}
private data class ProviderBootstrapResult(
val profileId: ProviderProfileId?,
val result: DomainResult<Session?>,
) {
fun errorFor(currentProfileId: ProviderProfileId?): String? =
if (profileId == currentProfileId) {
(result as? DomainResult.Failure)?.error?.detail
} else {
null
}
}
sealed interface AppSessionUiState {
data object Loading : AppSessionUiState
data object ProviderSelection : AppSessionUiState
data class Login(
val profile: ProviderProfile,
val bootstrapError: String? = null,
) : AppSessionUiState
data class Authenticated(val profile: ProviderProfile) : AppSessionUiState
}
@@ -0,0 +1,44 @@
package com.flagship.abox.manager.ui.session
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.SessionCoordinator
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
@HiltViewModel
class SessionActionsViewModel @Inject constructor(
private val coordinator: SessionCoordinator,
) : ViewModel() {
private val _uiState = MutableStateFlow(SessionActionsUiState())
val uiState: StateFlow<SessionActionsUiState> = _uiState.asStateFlow()
fun logout() = runAction(coordinator::logout)
fun switchProvider() = runAction(coordinator::switchProvider)
fun dismissError() {
_uiState.value = _uiState.value.copy(errorMessage = null)
}
private fun runAction(action: suspend () -> DomainResult<Unit>) {
if (_uiState.value.inProgress) return
viewModelScope.launch {
_uiState.value = SessionActionsUiState(inProgress = true)
val result = action()
_uiState.value = SessionActionsUiState(
errorMessage = (result as? DomainResult.Failure)?.error?.detail,
)
}
}
}
data class SessionActionsUiState(
val inProgress: Boolean = false,
val errorMessage: String? = null,
)
@@ -1,8 +1,27 @@
<resources>
<string name="app_name">ABox Manager</string>
<string name="foundation_title">工程基础已就绪</string>
<string name="foundation_description">公共领域接口和本地开发提供方已经可用。</string>
<string name="continue_action">继续</string>
<string name="placeholder_title">功能模块可以开始开发</string>
<string name="placeholder_description">设备、红外和情景页面将由对应模块负责人实现。</string>
<string name="provider_selection_title">选择提供方</string>
<string name="provider_selection_description">选择当前配置的连接方式。不同提供方之间的会话、凭据和本地数据相互隔离。</string>
<string name="provider_abox_name">ABox</string>
<string name="provider_abox_description">通过 ABSDK 连接当前局域网中的 ABox 智能家居网关。</string>
<string name="provider_local_name">本地体验</string>
<string name="provider_local_description">无需网络,通过本地模拟设备体验应用。</string>
<string name="login_title">登录 %1$s</string>
<string name="login_provider_context">当前提供方:%1$s</string>
<string name="login_back_to_providers">返回提供方选择</string>
<string name="login_username">用户名</string>
<string name="login_password">密码</string>
<string name="login_remember_username">记住用户名</string>
<string name="login_auto_login">自动登录</string>
<string name="login_error_required">请输入用户名和密码。</string>
<string name="login_error_invalid_credentials">用户名或密码不正确。</string>
<string name="login_error_network">网络不可用,请重试。</string>
<string name="login_error_session_expired">会话已失效,请重新登录。</string>
<string name="login_error_preferences">无法加载已保存的登录设置。</string>
<string name="login_error_failed">登录失败,请重试。</string>
<string name="action_login">登录</string>
<string name="action_logout">退出登录</string>
<string name="action_switch_provider">切换提供方</string>
<string name="authenticated_title">已连接到 %1$s</string>
<string name="authenticated_description">登录后入口已经就绪,设备导航将由对应模块负责人接入。</string>
</resources>
+24 -5
View File
@@ -1,8 +1,27 @@
<resources>
<string name="app_name">ABox Manager</string>
<string name="foundation_title">Project foundation ready</string>
<string name="foundation_description">The shared domain contracts and local development providers are available.</string>
<string name="continue_action">Continue</string>
<string name="placeholder_title">Feature development can start</string>
<string name="placeholder_description">Device, infrared and scene screens will be added by their module owners.</string>
<string name="provider_selection_title">Choose a provider</string>
<string name="provider_selection_description">Choose how this profile connects. Sessions, credentials, and local data stay isolated between providers.</string>
<string name="provider_abox_name">ABox</string>
<string name="provider_abox_description">Connect to the ABox smart-home gateway through ABSDK on the current local network.</string>
<string name="provider_local_name">Local experience</string>
<string name="provider_local_description">Explore the app with simulated local devices and no network connection.</string>
<string name="login_title">Sign in to %1$s</string>
<string name="login_provider_context">Selected provider: %1$s</string>
<string name="login_back_to_providers">Back to providers</string>
<string name="login_username">Username</string>
<string name="login_password">Password</string>
<string name="login_remember_username">Remember username</string>
<string name="login_auto_login">Sign in automatically</string>
<string name="login_error_required">Username and password are required.</string>
<string name="login_error_invalid_credentials">Invalid username or password.</string>
<string name="login_error_network">Network unavailable. Try again.</string>
<string name="login_error_session_expired">Session expired. Sign in again.</string>
<string name="login_error_preferences">Unable to load saved login settings.</string>
<string name="login_error_failed">Sign-in failed. Try again.</string>
<string name="action_login">Sign in</string>
<string name="action_logout">Sign out</string>
<string name="action_switch_provider">Switch provider</string>
<string name="authenticated_title">Connected to %1$s</string>
<string name="authenticated_description">The authenticated route is ready. Device navigation will be added by its module owner.</string>
</resources>
@@ -0,0 +1,230 @@
package com.flagship.abox.manager.di
import com.flagship.abox.manager.domain.DeviceName
import com.flagship.abox.manager.domain.DomainError
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.InfraredCode
import com.flagship.abox.manager.domain.InfraredCodeDownloadResult
import com.flagship.abox.manager.domain.InfraredGateway
import com.flagship.abox.manager.domain.ProviderProfile
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.ProviderProfileStore
import com.flagship.abox.manager.domain.ProviderType
import com.flagship.abox.manager.domain.SocketGateway
import com.flagship.abox.manager.domain.SocketPowerState
import com.flagship.abox.manager.domain.SocketStatus
import com.flagship.abox.manager.domain.TemperatureHumidityGateway
import com.flagship.abox.manager.domain.TemperatureHumidityReading
import com.flagship.abox.manager.testing.fakes.FakeProviderProfileStore
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class ProviderRoutingGatewaysTest {
@Test
fun socketRoutesAboxToRealAndLocalToSimulation() = runTest {
val store = FakeProviderProfileStore()
val real = RecordingSocketGateway()
val simulation = RecordingSocketGateway()
val router = RoutingSocketGateway(store, real, simulation)
val aboxId = activate(store, ProviderType.ABOX)
router.getStatus(aboxId, DeviceName("socket-1"))
assertEquals(1, real.calls)
assertEquals(0, simulation.calls)
val localId = activate(store, ProviderType.LOCAL_EXPERIENCE)
router.getStatus(localId, DeviceName("socket-1"))
assertEquals(1, real.calls)
assertEquals(1, simulation.calls)
}
@Test
fun temperatureHumidityRoutesAboxToRealAndLocalToSimulation() = runTest {
val store = FakeProviderProfileStore()
val real = RecordingTemperatureHumidityGateway()
val simulation = RecordingTemperatureHumidityGateway()
val router = RoutingTemperatureHumidityGateway(store, real, simulation)
val aboxId = activate(store, ProviderType.ABOX)
router.getReading(aboxId, DeviceName("th-1"))
assertEquals(1, real.calls)
assertEquals(0, simulation.calls)
val localId = activate(store, ProviderType.LOCAL_EXPERIENCE)
router.getReading(localId, DeviceName("th-1"))
assertEquals(1, real.calls)
assertEquals(1, simulation.calls)
}
@Test
fun infraredRoutesAboxToRealAndLocalToSimulation() = runTest {
val store = FakeProviderProfileStore()
val real = RecordingInfraredGateway()
val simulation = RecordingInfraredGateway()
val router = RoutingInfraredGateway(store, real, simulation)
val aboxId = activate(store, ProviderType.ABOX)
router.sendKey(aboxId, DeviceName("ir-1"), "power")
assertEquals(1, real.calls)
assertEquals(0, simulation.calls)
val localId = activate(store, ProviderType.LOCAL_EXPERIENCE)
router.sendKey(localId, DeviceName("ir-1"), "power")
assertEquals(1, real.calls)
assertEquals(1, simulation.calls)
}
@Test
fun missingActiveProfileReturnsInvalidRequest() = runTest {
val router = RoutingSocketGateway(
FakeProviderProfileStore(),
RecordingSocketGateway(),
RecordingSocketGateway(),
)
val result = router.getStatus(ProviderProfileId("any"), DeviceName("socket-1"))
assertTrue(result is DomainResult.Failure)
assertTrue((result as DomainResult.Failure).error is DomainError.InvalidRequest)
}
@Test
fun mismatchedActiveProfileReturnsInvalidRequest() = runTest {
val store = FakeProviderProfileStore()
val real = RecordingSocketGateway()
val simulation = RecordingSocketGateway()
val router = RoutingSocketGateway(store, real, simulation)
activate(store, ProviderType.ABOX)
val result = router.getStatus(ProviderProfileId("other"), DeviceName("socket-1"))
assertTrue(result is DomainResult.Failure)
assertTrue((result as DomainResult.Failure).error is DomainError.InvalidRequest)
assertEquals(0, real.calls)
assertEquals(0, simulation.calls)
}
@Test
fun cancellationFromProfileStoreIsRethrown() = runTest {
val router = RoutingSocketGateway(
CancellingProviderProfileStore(),
RecordingSocketGateway(),
RecordingSocketGateway(),
)
try {
router.getStatus(ProviderProfileId("any"), DeviceName("socket-1"))
error("Expected CancellationException")
} catch (expected: CancellationException) {
// Rethrown so coroutine cancellation is never swallowed.
}
}
@Test
fun unexpectedProfileStoreErrorReturnsUnknown() = runTest {
val router = RoutingSocketGateway(
FailingProviderProfileStore(),
RecordingSocketGateway(),
RecordingSocketGateway(),
)
val result = router.getStatus(ProviderProfileId("any"), DeviceName("socket-1"))
assertTrue(result is DomainResult.Failure)
val error = (result as DomainResult.Failure).error
assertTrue(error is DomainError.Unknown)
assertEquals("storage exploded", error.detail)
}
private suspend fun activate(
store: FakeProviderProfileStore,
type: ProviderType,
): ProviderProfileId {
val id = ProviderProfileId(type.name.lowercase())
store.saveProfile(ProviderProfile(id, type, type.name))
store.setActiveProfile(id)
return id
}
}
private class RecordingSocketGateway : SocketGateway {
var calls: Int = 0
private set
override suspend fun getStatus(
profileId: ProviderProfileId,
deviceName: DeviceName,
): DomainResult<SocketStatus> {
calls += 1
return DomainResult.Success(SocketStatus(profileId, deviceName, SocketPowerState.OFF))
}
override suspend fun setPower(
profileId: ProviderProfileId,
deviceName: DeviceName,
powerState: SocketPowerState,
): DomainResult<SocketStatus> {
calls += 1
return DomainResult.Success(SocketStatus(profileId, deviceName, powerState))
}
}
private class RecordingTemperatureHumidityGateway : TemperatureHumidityGateway {
var calls: Int = 0
private set
override suspend fun getReading(
profileId: ProviderProfileId,
deviceName: DeviceName,
): DomainResult<TemperatureHumidityReading> {
calls += 1
return DomainResult.Success(TemperatureHumidityReading(profileId, deviceName, "0", "0"))
}
}
private class RecordingInfraredGateway : InfraredGateway {
var calls: Int = 0
private set
override suspend fun sendKey(
profileId: ProviderProfileId,
deviceName: DeviceName,
key: String,
): DomainResult<Unit> {
calls += 1
return DomainResult.Success(Unit)
}
override suspend fun learnKey(
profileId: ProviderProfileId,
deviceName: DeviceName,
key: String,
): DomainResult<Unit> {
calls += 1
return DomainResult.Success(Unit)
}
override suspend fun downloadCodes(
profileId: ProviderProfileId,
codes: List<InfraredCode>,
): DomainResult<List<InfraredCodeDownloadResult>> {
calls += 1
return DomainResult.Success(codes.map { InfraredCodeDownloadResult(it, successful = true) })
}
}
private class CancellingProviderProfileStore(
private val delegate: ProviderProfileStore = FakeProviderProfileStore(),
) : ProviderProfileStore by delegate {
override suspend fun activeProfile(): Nothing = throw CancellationException("cancelled")
}
private class FailingProviderProfileStore(
private val delegate: ProviderProfileStore = FakeProviderProfileStore(),
) : ProviderProfileStore by delegate {
override suspend fun activeProfile(): Nothing =
throw IllegalStateException("storage exploded")
}
@@ -0,0 +1,23 @@
package com.flagship.abox.manager.testing
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.rules.TestWatcher
import org.junit.runner.Description
@OptIn(ExperimentalCoroutinesApi::class)
class MainDispatcherRule(
val dispatcher: TestDispatcher = StandardTestDispatcher(),
) : TestWatcher() {
override fun starting(description: Description) {
Dispatchers.setMain(dispatcher)
}
override fun finished(description: Description) {
Dispatchers.resetMain()
}
}
@@ -0,0 +1,51 @@
package com.flagship.abox.manager.ui.provider
import com.flagship.abox.manager.domain.ProviderType
import com.flagship.abox.manager.domain.SessionCoordinator
import com.flagship.abox.manager.testing.MainDispatcherRule
import com.flagship.abox.manager.testing.fakes.FakeCredentialStore
import com.flagship.abox.manager.testing.fakes.FakeLocalSessionGateway
import com.flagship.abox.manager.testing.fakes.FakeProviderProfileStore
import com.flagship.abox.manager.testing.fakes.FakeSessionGateway
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class ProviderSelectionViewModelTest {
@get:Rule
val mainDispatcherRule = MainDispatcherRule()
private val coordinator = SessionCoordinator(
profileStore = FakeProviderProfileStore(),
credentialStore = FakeCredentialStore(),
remoteGateway = FakeSessionGateway(),
localGateway = FakeLocalSessionGateway(),
)
@Test
fun exposesExactlyAboxAndLocalExperience() {
val viewModel = ProviderSelectionViewModel(coordinator)
assertEquals(
listOf(ProviderType.ABOX, ProviderType.LOCAL_EXPERIENCE),
viewModel.uiState.value.providers.map { it.type },
)
}
@Test
fun selectingLocalExperienceEstablishesSessionImmediately() = runTest {
val viewModel = ProviderSelectionViewModel(coordinator)
val local = viewModel.uiState.value.providers
.single { it.type == ProviderType.LOCAL_EXPERIENCE }
viewModel.select(local)
advanceUntilIdle()
assertEquals(local.id, coordinator.observeActiveSession().first()?.profileId)
}
}
@@ -0,0 +1,126 @@
package com.flagship.abox.manager.ui.session
import com.flagship.abox.manager.domain.DomainError
import com.flagship.abox.manager.domain.LoginCredentials
import com.flagship.abox.manager.domain.Password
import com.flagship.abox.manager.domain.ProviderProfile
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.ProviderType
import com.flagship.abox.manager.domain.Session
import com.flagship.abox.manager.domain.SessionCoordinator
import com.flagship.abox.manager.domain.SessionGateway
import com.flagship.abox.manager.domain.Username
import com.flagship.abox.manager.testing.MainDispatcherRule
import com.flagship.abox.manager.testing.fakes.FakeCredentialStore
import com.flagship.abox.manager.testing.fakes.FakeLocalSessionGateway
import com.flagship.abox.manager.testing.fakes.FakeProviderProfileStore
import com.flagship.abox.manager.testing.fakes.FakeSessionGateway
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
/**
* Regression tests for real ABox login gating: the authenticated UI may appear only when the
* active provider profile owns a successful session, and a failed ABox login stays on Login.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class AppSessionViewModelTest {
@get:Rule
val mainDispatcherRule = MainDispatcherRule()
private val profiles = FakeProviderProfileStore()
private val remote = FakeSessionGateway()
private val local = FakeLocalSessionGateway()
private val credentials = LoginCredentials(
username = Username("user"),
password = Password("password"),
)
private fun newCoordinator(remoteGateway: SessionGateway = remote) = SessionCoordinator(
profileStore = profiles,
credentialStore = FakeCredentialStore(),
remoteGateway = remoteGateway,
localGateway = local,
)
private suspend fun saveAndActivateAboxProfile(id: ProviderProfileId) {
profiles.saveProfile(ProviderProfile(id, ProviderType.ABOX, id.value))
profiles.setActiveProfile(id)
}
@Test
fun failedAboxLoginLeavesUiOnLogin() = runTest {
saveAndActivateAboxProfile(aboxProfileId)
remote.failLogin(aboxProfileId, DomainError.Authentication())
val coordinator = newCoordinator()
val viewModel = AppSessionViewModel(coordinator, profiles)
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
viewModel.uiState.collect {}
}
advanceUntilIdle()
coordinator.login(
profileId = aboxProfileId,
credentials = credentials,
rememberUsername = false,
autoLogin = false,
)
advanceUntilIdle()
assertTrue(viewModel.uiState.value is AppSessionUiState.Login)
}
@Test
fun sessionForDifferentProfileCannotAuthenticateActiveProfile() = runTest {
profiles.saveProfile(ProviderProfile(otherProfileId, ProviderType.ABOX, otherProfileId.value))
remote.login(otherProfileId, credentials)
saveAndActivateAboxProfile(aboxProfileId)
// The gateway exposes the other profile's session no matter which profile is observed.
val crossProfileGateway = object : SessionGateway by remote {
override fun observeSession(profileId: ProviderProfileId): Flow<Session?> =
remote.observeSession(otherProfileId)
}
val viewModel = AppSessionViewModel(newCoordinator(crossProfileGateway), profiles)
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
viewModel.uiState.collect {}
}
advanceUntilIdle()
assertTrue(viewModel.uiState.value is AppSessionUiState.Login)
}
@Test
fun successfulAboxLoginAuthenticatesActiveProfile() = runTest {
saveAndActivateAboxProfile(aboxProfileId)
val coordinator = newCoordinator()
val viewModel = AppSessionViewModel(coordinator, profiles)
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
viewModel.uiState.collect {}
}
advanceUntilIdle()
coordinator.login(
profileId = aboxProfileId,
credentials = credentials,
rememberUsername = false,
autoLogin = false,
)
advanceUntilIdle()
val state = viewModel.uiState.value
assertTrue(state is AppSessionUiState.Authenticated)
}
private companion object {
val aboxProfileId = ProviderProfileId("abox-default")
val otherProfileId = ProviderProfileId("abox-other")
}
}
+34
View File
@@ -0,0 +1,34 @@
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.kotlin.android)
}
android {
namespace = "com.flagship.abox.manager.session"
compileSdk = 34
defaultConfig {
minSdk = 26
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
}
dependencies {
api(project(":domain"))
implementation(libs.kotlinx.coroutines.core)
implementation(libs.datastore.preferences)
testImplementation(libs.junit)
testImplementation(libs.kotlinx.coroutines.test)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.test.runner)
}
@@ -0,0 +1,34 @@
package com.flagship.abox.manager.session.credential
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.flagship.abox.manager.domain.ProviderProfileId
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertFalse
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class AndroidKeystoreCredentialCipherTest {
@Test
fun encryptsWithRandomIvAndProfileBoundAad() {
val cipher = AndroidKeystoreCredentialCipher(
keyAlias = "abox_manager_test_${System.nanoTime()}",
)
val profile = ProviderProfileId("profile")
val plaintext = "secret".toByteArray()
val first = cipher.encrypt(profile, plaintext)
val second = cipher.encrypt(profile, plaintext)
assertFalse(first.contentEquals(second))
assertArrayEquals(plaintext, cipher.decrypt(profile, first))
assertArrayEquals(plaintext, cipher.decrypt(profile, second))
}
@Test(expected = IllegalArgumentException::class)
fun rejectsTruncatedPayloadBeforeReadingHeader() {
AndroidKeystoreCredentialCipher(
keyAlias = "abox_manager_test_${System.nanoTime()}",
).decrypt(ProviderProfileId("profile"), byteArrayOf(1))
}
}
@@ -0,0 +1 @@
<manifest />
@@ -0,0 +1,75 @@
package com.flagship.abox.manager.session.credential
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import com.flagship.abox.manager.domain.ProviderProfileId
import java.nio.ByteBuffer
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
class AndroidKeystoreCredentialCipher(
private val keyAlias: String = KEY_ALIAS,
) : CredentialCipher {
override fun encrypt(profileId: ProviderProfileId, plaintext: ByteArray): ByteArray {
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.ENCRYPT_MODE, secretKey())
cipher.updateAAD(profileId.value.toByteArray(Charsets.UTF_8))
val ciphertext = cipher.doFinal(plaintext)
return ByteBuffer.allocate(2 + cipher.iv.size + ciphertext.size)
.put(VERSION)
.put(cipher.iv.size.toByte())
.put(cipher.iv)
.put(ciphertext)
.array()
}
override fun decrypt(profileId: ProviderProfileId, encrypted: ByteArray): ByteArray {
require(encrypted.size >= HEADER_SIZE) { "Credential payload is truncated" }
val buffer = ByteBuffer.wrap(encrypted)
require(buffer.get() == VERSION) { "Unsupported credential format" }
val ivLength = buffer.get().toInt() and 0xFF
require(ivLength in 12..16 && buffer.remaining() > ivLength) { "Invalid credential payload" }
val iv = ByteArray(ivLength).also(buffer::get)
val ciphertext = ByteArray(buffer.remaining()).also(buffer::get)
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(GCM_TAG_BITS, iv))
cipher.updateAAD(profileId.value.toByteArray(Charsets.UTF_8))
return cipher.doFinal(ciphertext)
}
override fun resetPermanentlyInvalidatedKey() {
val keyStore = KeyStore.getInstance(ANDROID_KEY_STORE).apply { load(null) }
if (keyStore.containsAlias(keyAlias)) keyStore.deleteEntry(keyAlias)
}
private fun secretKey(): SecretKey {
val keyStore = KeyStore.getInstance(ANDROID_KEY_STORE).apply { load(null) }
(keyStore.getKey(keyAlias, null) as? SecretKey)?.let { return it }
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE).run {
init(
KeyGenParameterSpec.Builder(
keyAlias,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
)
.setKeySize(KEY_SIZE_BITS)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build(),
)
generateKey()
}
}
companion object {
private const val ANDROID_KEY_STORE = "AndroidKeyStore"
private const val KEY_ALIAS = "abox_manager_credentials_v1"
private const val TRANSFORMATION = "AES/GCM/NoPadding"
private const val KEY_SIZE_BITS = 256
private const val GCM_TAG_BITS = 128
private const val HEADER_SIZE = 2
private const val VERSION: Byte = 1
}
}
@@ -0,0 +1,11 @@
package com.flagship.abox.manager.session.credential
import com.flagship.abox.manager.domain.ProviderProfileId
interface CredentialCipher {
fun encrypt(profileId: ProviderProfileId, plaintext: ByteArray): ByteArray
fun decrypt(profileId: ProviderProfileId, encrypted: ByteArray): ByteArray
fun resetPermanentlyInvalidatedKey()
}
@@ -0,0 +1,138 @@
package com.flagship.abox.manager.session.credential
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import com.flagship.abox.manager.domain.CredentialStore
import com.flagship.abox.manager.domain.DomainError
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.LoginCredentials
import com.flagship.abox.manager.domain.Password
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.Username
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
import java.io.DataOutputStream
import android.security.keystore.KeyPermanentlyInvalidatedException
import java.util.Base64
import javax.crypto.AEADBadTagException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.first
class KeystoreCredentialStore(
private val dataStore: DataStore<Preferences>,
private val cipher: CredentialCipher,
) : CredentialStore {
override suspend fun saveCredentials(
profileId: ProviderProfileId,
credentials: LoginCredentials,
): DomainResult<Unit> = operation {
val encrypted = cipher.encrypt(profileId, encode(credentials))
dataStore.edit { it[credentialKey(profileId)] = Base64.getEncoder().encodeToString(encrypted) }
}
override suspend fun loadCredentials(
profileId: ProviderProfileId,
): DomainResult<LoginCredentials?> {
return try {
val value = dataStore.data.first()[credentialKey(profileId)]
?: return DomainResult.Success(null)
val encrypted = Base64.getDecoder().decode(value)
DomainResult.Success(decode(cipher.decrypt(profileId, encrypted)))
} catch (error: CancellationException) {
throw error
} catch (error: Exception) {
if (error.isPermanentCredentialFailure()) {
try {
if (error.hasPermanentlyInvalidatedKey()) {
cipher.resetPermanentlyInvalidatedKey()
}
dataStore.edit { it.remove(credentialKey(profileId)) }
DomainResult.Success(null)
} catch (cleanupError: CancellationException) {
throw cleanupError
} catch (cleanupError: Exception) {
DomainResult.Failure(
DomainError.Unknown(
detail = cleanupError.message ?: cleanupError::class.java.simpleName,
),
)
}
} else {
DomainResult.Failure(
DomainError.Unknown(detail = error.message ?: error::class.java.simpleName),
)
}
}
}
override suspend fun clearCredentials(profileId: ProviderProfileId): DomainResult<Unit> = operation {
dataStore.edit { it.remove(credentialKey(profileId)) }
}
private fun encode(credentials: LoginCredentials): ByteArray = ByteArrayOutputStream().use { output ->
DataOutputStream(output).use { data ->
data.writeByte(CREDENTIAL_FORMAT_VERSION)
data.writeByteArray(credentials.username.value.toByteArray(Charsets.UTF_8))
data.writeByteArray(credentials.password.value.toByteArray(Charsets.UTF_8))
}
output.toByteArray()
}
private fun decode(value: ByteArray): LoginCredentials = DataInputStream(
ByteArrayInputStream(value),
).use { data ->
require(data.readUnsignedByte() == CREDENTIAL_FORMAT_VERSION) {
"Unsupported credential data format"
}
val username = data.readByteArray(MAX_CREDENTIAL_FIELD_BYTES).toString(Charsets.UTF_8)
val password = data.readByteArray(MAX_CREDENTIAL_FIELD_BYTES).toString(Charsets.UTF_8)
require(data.available() == 0) { "Unexpected credential data" }
LoginCredentials(Username(username), Password(password))
}
private suspend fun operation(block: suspend () -> Unit): DomainResult<Unit> = try {
block()
DomainResult.Success(Unit)
} catch (error: CancellationException) {
throw error
} catch (error: Exception) {
DomainResult.Failure(
DomainError.Unknown(detail = error.message ?: error::class.java.simpleName),
)
}
companion object {
private const val CREDENTIAL_FORMAT_VERSION = 1
private const val MAX_CREDENTIAL_FIELD_BYTES = 1_048_576
private fun credentialKey(profileId: ProviderProfileId) =
stringPreferencesKey("profile_${profileId.value}_credential")
}
}
private fun DataOutputStream.writeByteArray(value: ByteArray) {
require(value.size <= 1_048_576) { "Credential field is too large" }
writeInt(value.size)
write(value)
}
private fun DataInputStream.readByteArray(maxSize: Int): ByteArray {
val length = readInt()
require(length in 0..maxSize && length <= available()) { "Invalid credential field length" }
return ByteArray(length).also(::readFully)
}
private fun Throwable.hasPermanentlyInvalidatedKey(): Boolean =
this is KeyPermanentlyInvalidatedException || cause?.hasPermanentlyInvalidatedKey() == true
private fun Throwable.isPermanentCredentialFailure(): Boolean = when (this) {
is AEADBadTagException,
is KeyPermanentlyInvalidatedException,
is IllegalArgumentException,
-> true
else -> cause?.isPermanentCredentialFailure() == true
}
@@ -0,0 +1,138 @@
package com.flagship.abox.manager.session.profile
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.core.stringSetPreferencesKey
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.LoginPreferences
import com.flagship.abox.manager.domain.ProviderProfile
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.ProviderProfileStore
import com.flagship.abox.manager.domain.ProviderType
import com.flagship.abox.manager.domain.Username
import java.io.IOException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.retryWhen
class ProviderProfileStoreImpl(
private val dataStore: DataStore<Preferences>,
) : ProviderProfileStore {
private val safeData: Flow<Preferences>
get() = dataStore.data
.retryWhen { cause, attempt ->
val retry = cause is IOException && attempt < MAX_READ_RETRIES
if (retry) delay(READ_RETRY_DELAY_MILLIS)
retry
}
.distinctUntilChanged()
override fun observeProfiles(): Flow<List<ProviderProfile>> = safeData.map(::profilesFrom)
override fun observeActiveProfile(): Flow<ProviderProfile?> = safeData.map(::activeProfileFrom)
override fun observeLoginPreferences(profileId: ProviderProfileId): Flow<LoginPreferences> =
safeData.map { preferencesFrom(it, profileId) }
override suspend fun profiles(): List<ProviderProfile> = profilesFrom(safeData.first())
override suspend fun activeProfile(): ProviderProfile? = activeProfileFrom(safeData.first())
override suspend fun loginPreferences(profileId: ProviderProfileId): LoginPreferences =
preferencesFrom(safeData.first(), profileId)
override suspend fun saveProfile(profile: ProviderProfile): DomainResult<Unit> = operation {
dataStore.edit { preferences ->
preferences[PROFILE_IDS] = preferences[PROFILE_IDS].orEmpty() + profile.id.value
preferences[profileTypeKey(profile.id)] = profile.type.name
preferences[profileNameKey(profile.id)] = profile.displayName
}
}
override suspend fun setActiveProfile(profileId: ProviderProfileId?): DomainResult<Unit> = operation {
dataStore.edit { preferences ->
if (profileId == null) preferences.remove(ACTIVE_PROFILE_ID)
else preferences[ACTIVE_PROFILE_ID] = profileId.value
}
}
override suspend fun saveLoginPreferences(
preferences: LoginPreferences,
): DomainResult<Unit> = operation {
dataStore.edit { values ->
val profileId = preferences.profileId
values[rememberUsernameKey(profileId)] = preferences.rememberUsername
values[autoLoginKey(profileId)] = preferences.autoLoginEnabled
val username = preferences.rememberedUsername?.value
if (username == null) values.remove(usernameKey(profileId))
else values[usernameKey(profileId)] = username
}
}
private fun profilesFrom(preferences: Preferences): List<ProviderProfile> =
preferences[PROFILE_IDS].orEmpty().mapNotNull { idValue ->
val id = ProviderProfileId(idValue)
val type = preferences[profileTypeKey(id)]
?.let { runCatching { ProviderType.valueOf(it) }.getOrNull() }
?: return@mapNotNull null
val displayName = preferences[profileNameKey(id)] ?: return@mapNotNull null
ProviderProfile(id, type, displayName)
}.sortedBy { it.id.value }
private fun activeProfileFrom(preferences: Preferences): ProviderProfile? {
val activeId = preferences[ACTIVE_PROFILE_ID] ?: return null
return profilesFrom(preferences).firstOrNull { it.id.value == activeId }
}
private fun preferencesFrom(
preferences: Preferences,
profileId: ProviderProfileId,
): LoginPreferences = LoginPreferences(
profileId = profileId,
rememberedUsername = preferences[usernameKey(profileId)]?.let(::Username),
rememberUsername = preferences[rememberUsernameKey(profileId)] ?: false,
autoLoginEnabled = preferences[autoLoginKey(profileId)] ?: false,
)
private suspend fun operation(block: suspend () -> Unit): DomainResult<Unit> = try {
block()
DomainResult.Success(Unit)
} catch (error: CancellationException) {
throw error
} catch (error: Exception) {
DomainResult.Failure(
com.flagship.abox.manager.domain.DomainError.Unknown(
detail = error.message ?: error::class.java.simpleName,
),
)
}
companion object {
private const val MAX_READ_RETRIES = 2L
private const val READ_RETRY_DELAY_MILLIS = 100L
private val PROFILE_IDS = stringSetPreferencesKey("profile_ids")
private val ACTIVE_PROFILE_ID = stringPreferencesKey("active_profile_id")
private fun profileTypeKey(id: ProviderProfileId) =
stringPreferencesKey("profile_${id.value}_type")
private fun profileNameKey(id: ProviderProfileId) =
stringPreferencesKey("profile_${id.value}_name")
private fun usernameKey(id: ProviderProfileId) =
stringPreferencesKey("profile_${id.value}_username")
private fun rememberUsernameKey(id: ProviderProfileId) =
booleanPreferencesKey("profile_${id.value}_remember_username")
private fun autoLoginKey(id: ProviderProfileId) =
booleanPreferencesKey("profile_${id.value}_auto_login")
}
}
@@ -0,0 +1,15 @@
package com.flagship.abox.manager.session.profile
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.preferencesDataStore
private const val SESSION_DATA_STORE_NAME = "provider_session"
val Context.sessionDataStore: DataStore<Preferences> by preferencesDataStore(
name = SESSION_DATA_STORE_NAME,
corruptionHandler = ReplaceFileCorruptionHandler { emptyPreferences() },
)
@@ -0,0 +1,45 @@
package com.flagship.abox.manager.session
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.session.credential.CredentialCipher
import com.flagship.abox.manager.session.credential.KeystoreCredentialStore
import java.io.IOException
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class CredentialCleanupFailureTest {
@Test
fun cleanupFailureReturnsDomainFailureInsteadOfThrowing() = runTest {
val store = KeystoreCredentialStore(FailingCleanupDataStore(), UnusedCipher())
val result = store.loadCredentials(ProviderProfileId("profile"))
assertTrue(result is DomainResult.Failure)
assertEquals("disk unavailable", (result as DomainResult.Failure).error.detail)
}
private class FailingCleanupDataStore : DataStore<Preferences> {
override val data: Flow<Preferences> = flow {
throw IllegalArgumentException("corrupt credential")
}
override suspend fun updateData(
transform: suspend (t: Preferences) -> Preferences,
): Preferences = throw IOException("disk unavailable")
}
private class UnusedCipher : CredentialCipher {
override fun encrypt(profileId: ProviderProfileId, plaintext: ByteArray): ByteArray = plaintext
override fun decrypt(profileId: ProviderProfileId, encrypted: ByteArray): ByteArray = encrypted
override fun resetPermanentlyInvalidatedKey() = Unit
}
}
@@ -0,0 +1,89 @@
package com.flagship.abox.manager.session
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.LoginCredentials
import com.flagship.abox.manager.domain.Password
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.Username
import com.flagship.abox.manager.session.credential.CredentialCipher
import com.flagship.abox.manager.session.credential.KeystoreCredentialStore
import java.io.File
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class CredentialStoreTest {
@Test
fun storesClearsAndIsolatesCredentials() = runTest {
val file = File.createTempFile("credentials", ".preferences_pb").apply { delete() }
val dataStore = PreferenceDataStoreFactory.create(scope = backgroundScope) { file }
val store = KeystoreCredentialStore(dataStore, ReversingCipher())
val first = ProviderProfileId("alpha")
val second = ProviderProfileId("bravo")
val firstCredentials = LoginCredentials(Username("one"), Password("secret-one"))
val secondCredentials = LoginCredentials(Username("two"), Password("secret-two"))
store.saveCredentials(first, firstCredentials)
store.saveCredentials(second, secondCredentials)
store.clearCredentials(first)
assertNull((store.loadCredentials(first) as DomainResult.Success).value)
assertEquals(secondCredentials, (store.loadCredentials(second) as DomainResult.Success).value)
}
@Test
fun credentialsLargerThanWriteUtfLimitRoundTrip() = runTest {
val file = File.createTempFile("large-credentials", ".preferences_pb").apply { delete() }
val dataStore = PreferenceDataStoreFactory.create(scope = backgroundScope) { file }
val store = KeystoreCredentialStore(dataStore, ReversingCipher())
val profile = ProviderProfileId("large")
val credentials = LoginCredentials(
Username("u".repeat(70_000)),
Password("p".repeat(70_000)),
)
assertEquals(DomainResult.Success(Unit), store.saveCredentials(profile, credentials))
assertEquals(credentials, (store.loadCredentials(profile) as DomainResult.Success).value)
}
@Test
fun malformedCredentialIsRemoved() = runTest {
val file = File.createTempFile("malformed-credentials", ".preferences_pb").apply { delete() }
val dataStore = PreferenceDataStoreFactory.create(scope = backgroundScope) { file }
val profile = ProviderProfileId("profile")
val store = KeystoreCredentialStore(dataStore, RejectingCipher())
store.saveCredentials(
profile,
LoginCredentials(Username("demo"), Password("secret")),
)
assertNull((store.loadCredentials(profile) as DomainResult.Success).value)
assertNull((store.loadCredentials(profile) as DomainResult.Success).value)
}
private class RejectingCipher : CredentialCipher {
override fun encrypt(profileId: ProviderProfileId, plaintext: ByteArray): ByteArray = byteArrayOf(1)
override fun decrypt(profileId: ProviderProfileId, encrypted: ByteArray): ByteArray {
throw IllegalArgumentException("Credential payload is truncated")
}
override fun resetPermanentlyInvalidatedKey() = Unit
}
private class ReversingCipher : CredentialCipher {
override fun encrypt(profileId: ProviderProfileId, plaintext: ByteArray): ByteArray =
(profileId.value.toByteArray() + byteArrayOf(0) + plaintext).reversedArray()
override fun decrypt(profileId: ProviderProfileId, encrypted: ByteArray): ByteArray {
val decoded = encrypted.reversedArray()
val delimiter = decoded.indexOf(0)
require(decoded.copyOfRange(0, delimiter).decodeToString() == profileId.value)
return decoded.copyOfRange(delimiter + 1, decoded.size)
}
override fun resetPermanentlyInvalidatedKey() = Unit
}
}
@@ -0,0 +1,43 @@
package com.flagship.abox.manager.session
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.emptyPreferences
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.session.profile.ProviderProfileStoreImpl
import java.io.IOException
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withTimeout
import org.junit.Assert.assertFalse
import org.junit.Test
class ProviderProfileStoreFailureTest {
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
@Test
fun persistentIoFailureDoesNotEmitFalseEmptyState() = runTest {
val store = ProviderProfileStoreImpl(FailingReadDataStore())
var completed = false
backgroundScope.launch {
runCatching { withTimeout(250) { store.activeProfile() } }
completed = true
}
advanceTimeBy(200)
assertFalse(completed)
}
private class FailingReadDataStore : DataStore<Preferences> {
override val data: Flow<Preferences> = flow {
throw IOException("disk unavailable")
}
override suspend fun updateData(
transform: suspend (t: Preferences) -> Preferences,
): Preferences = transform(emptyPreferences())
}
}
@@ -0,0 +1,34 @@
package com.flagship.abox.manager.session
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.LoginPreferences
import com.flagship.abox.manager.domain.ProviderProfile
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.ProviderType
import com.flagship.abox.manager.domain.Username
import com.flagship.abox.manager.session.profile.ProviderProfileStoreImpl
import java.io.File
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Test
class ProviderProfileStoreTest {
@Test
fun persistsActiveProfileAndLoginPreferences() = runTest {
val file = File.createTempFile("profiles", ".preferences_pb").apply { delete() }
val dataStore = PreferenceDataStoreFactory.create(scope = backgroundScope) { file }
val store = ProviderProfileStoreImpl(dataStore)
val id = ProviderProfileId("abox")
val profile = ProviderProfile(id, ProviderType.ABOX, "ABox")
val preferences = LoginPreferences(id, Username("demo"), true, true)
assertEquals(DomainResult.Success(Unit), store.saveProfile(profile))
store.setActiveProfile(id)
store.saveLoginPreferences(preferences)
assertEquals(profile, store.observeActiveProfile().first())
assertEquals(preferences, store.observeLoginPreferences(id).first())
}
}
@@ -0,0 +1,32 @@
package com.flagship.abox.manager.session
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.core.stringSetPreferencesKey
import com.flagship.abox.manager.session.profile.ProviderProfileStoreImpl
import java.io.File
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class RemovedProviderProfileTest {
@Test
fun removedCompatibleProfileIsIgnoredAndCannotRemainActive() = runTest {
val file = File.createTempFile("removed-provider", ".preferences_pb").apply { delete() }
val dataStore = PreferenceDataStoreFactory.create(scope = backgroundScope) { file }
dataStore.edit { values ->
values[stringSetPreferencesKey("profile_ids")] = setOf("compatible-default")
values[stringPreferencesKey("profile_compatible-default_type")] = "COMPATIBLE_BACKEND"
values[stringPreferencesKey("profile_compatible-default_name")] = "Compatible backend"
values[stringPreferencesKey("active_profile_id")] = "compatible-default"
}
val store = ProviderProfileStoreImpl(dataStore)
assertTrue(store.profiles().isEmpty())
assertNull(store.activeProfile())
assertNull(store.observeActiveProfile().first())
}
}
+72 -24
View File
@@ -2,7 +2,7 @@
## 1. 文档范围
本文记录第一轮工程基础已经建立的模块边界、依赖方向和并行开发接口。ABSDK 0630 的初始化、协议、签名、连接重定向和会话清理等未确认内容不在本文中固化。
本文记录已建立的模块边界、依赖方向、提供方路由和并行开发接口,覆盖 ABox(局域网 ABSDK)与本地体验两条连接路径。ABSDK 0630 的初始化、签名细节和会话清理等未确认内容不在本文中固化,协议观测证据见 `docs/protocol/absdk-0630.md`。
产品范围和固定分工以 `docs/project_plan.md` 为准,原始简要需求继续保留在 `docs/requirement_spec.md`。
@@ -11,10 +11,14 @@
```text
abox-mgr/
├── android/
│ ├── app/ # Android 应用与依赖注入组合根
│ └── core/designsystem/ # Compose Material 3 设计系统基础
│ ├── app/ # Android 应用、提供方路由与依赖注入组合根
│ └── core/
│ ├── designsystem/ # Compose Material 3 设计系统基础
│ └── session/ # 提供方 profile、凭据 Keystore 持久化
├── domain/ # 纯 Kotlin 领域模型和公共端口
├── testing/fakes/ # 确定性的公共 Fake
├── absdk-bridge/ # ABSDK 0630 防腐层(生产)
├── runtime/simulation/ # 本地体验模拟运行时(生产)
├── testing/fakes/ # 测试专用 Fake(仅测试依赖)
├── docs/
└── samples/ # 历史示例,仅供参考
```
@@ -23,10 +27,13 @@ abox-mgr/
```text
android/app ────────────────┬──> android/core/designsystem
├──> android/core/session ──> domain
├──> domain
└──> testing/fakes ──> domain
├──> absdk-bridge ──> domain
└──> runtime/simulation ──> domain
android/core/designsystem ─────> Compose Material 3
testing/fakes(仅测试)────────> domain
domain ────────────────────────> Kotlin 与 Coroutines
```
@@ -34,21 +41,29 @@ domain ────────────────────────>
## 3. 提供方与数据隔离
应用计划支持 ABox、自有兼容后端和本地体验三种提供方。每个连接配置由 `ProviderProfileId` 标识,所有会话、设备目录和设备操作都显式携带该标识。
认证前应用只提供两种入口,两者在所有构建变体中始终可用:
1. **ABox**:通过进程内唯一的真实 `AbsdkBridge` 连接当前局域网中的智能家居网关,登录成功后进入应用;
2. **本地体验**:由 `:runtime:simulation` 直接建立模拟会话并进入应用,不请求凭据、不访问网络、不调用 ABSDK。
每个提供方 profile 由 `ProviderProfileId` 标识,所有会话、设备目录和设备操作都显式携带该标识。
约束:
- 任一时刻只启用一个提供方;
- 切换远端提供方前必须退出当前会话;
- 不同连接配置的数据、凭据和设备状态不得互相混用;
- 切换提供方前必须退出当前会话;
- 不同提供方的数据、凭据和设备状态不得互相混用;
- 本地体验不调用 ABSDK,也不启动本地 HTTP 服务;
- Fake 使用相同标识隔离规则,便于在没有真实环境时验证边界。
- Release 不是特殊情况:debug 与 release 暴露相同的提供方和路由行为。
## 4. 公共领域端口
`domain` 当前提供以下最小端口:
- `SessionGateway`:登录、观察会话、验证会话和退出;
- `LocalSessionGateway`:无凭据本地会话的标记端口,继承 `SessionGateway`;
- `ProviderProfileStore`:提供方 profile、活动 profile 和登录偏好持久化;
- `CredentialStore`:自动登录凭据的加密存取;
- `DeviceCatalog`:按提供方观察设备目录;
- `SocketGateway`:查询和设置插座状态;
- `TemperatureHumidityGateway`:读取温度和湿度;
@@ -63,9 +78,9 @@ domain ────────────────────────>
- `Success<T>` 携带类型化领域值;
- `Failure` 携带 `DomainError`;
- `DomainError.externalCode` 可以保留外部 SDK 错误码用于诊断;
- UI 不接触 `ABRet`、原始 `Map`、HTTP 表单或服务端数据库模型。
- UI 不接触 `ABRet`、原始 `Map`、HTTP 表单或任何服务端数据库模型。
真实 ABSDK 适配层必须在后续 `feat/absdk-bridge` 分支中完成同步阻塞调用的后台串行化、返回解析和错误映射。
ABSDK 防腐层已在 `:absdk-bridge` 中完成同步阻塞调用的后台串行化、返回解析和错误映射。
## 6. Fake 边界
@@ -77,42 +92,75 @@ domain ────────────────────────>
- 记录红外学习、发送和下载调用;
- 可直接用于其他模块的 ViewModel 与 UI 测试。
Fake 只用于开发和测试,不能作为真实 ABox 或真实硬件验收证据。
Fake 只用于开发和测试,不能作为真实 ABox 或真实硬件验收证据。`:testing:fakes` 是测试专用模块,不得加入应用生产依赖。
## 7. Android 组合根
一个例外是 `FakeDeviceCatalog`:ABSDK 不提供设备目录,而提供方作用域的生产 ABox 设备目录由设备目录模块负责,尚未落地。在该模块交付前,debug 构建的组合根暂时用 `FakeDeviceCatalog` 充当 ABox 目录占位。这是一个临时的目录所有权边界:不得把 ABox 目录请求路由到本地体验的模拟目录,release 构建在出现真实消费方之前不声明 `DeviceCatalog` 绑定。
## 7. 本地体验模拟运行时
`:runtime:simulation` 是生产 Kotlin/JVM 模块,为本地体验提供确定性实现:
- `SimulationSessionGateway`:直接建立无凭据的本地会话;
- `SimulationDeviceCatalog`:内置的本地体验设备目录;
- `SimulationSocketGateway`、`SimulationTemperatureHumidityGateway`、`SimulationInfraredGateway`:固定行为的模拟设备操作。
模拟实现不暴露脚本化失败注入、调用记录或断言辅助;这些能力只存在于 `:testing:fakes`。
## 8. Android 组合根与提供方路由
`android/app` 是单 Activity Compose 应用,负责:
- `ABoxManagerApplication` 与 Hilt 组合根;
- `MainActivity`;
- 根 `NavHost`;
- 仅在 debug 构建中将领域端口绑定到当前开发阶段的 Fake,release 构建不包含 Fake;
- 根 `NavHost` 与提供方选择、登录、认证后路由;
- 默认英文和简体中文资源;
- 使用 `android/core/designsystem` 的主题和基础组件。
组合根按端口绑定生产实现:
```text
SessionGateway -> AbsdkBridge(进程内单例)
LocalSessionGateway -> SimulationSessionGateway
SocketGateway -> RoutingSocketGateway
TemperatureHumidityGateway -> RoutingTemperatureHumidityGateway
InfraredGateway -> RoutingInfraredGateway
```
`AbsdkBridge` 以 Hilt 单例提供并在所有构建变体中相同:会话与插座/温湿度/红外操作共享同一个 Bridge 实例,使互斥锁和 Bridge 本地会话与厂商 SDK 单例状态保持一致。三个 Routing 网关读取活动 profile 并按提供方分发——ABox 转发到共享的 AbsdkBridge 实现,本地体验转发到模拟实现。任何功能 UI 都不直接选择真实或 Fake 实现。
设备目录导航、插座与温湿度页面、红外页面和情景页面由固定模块负责人实现,不放入工程基础层。
## 8. ABSDK Bridge
## 9. ABSDK Bridge
`:absdk-bridge` 是纯 Kotlin/JVM 防腐层,依赖 `domain` 并实现会话、插座、温湿度和红外 Gateway。该模块:
- 只在 `VendorAbsdkClient` 中接触 `ABSDK`、`ABRet` 和 `IrInfo`;
- 将所有同步调用移到后台并串行进入全局 SDK;
- 将返回值和错误码转换为 `DomainResult` 和领域模型;
- 不提供设备目录;
- 不调用未确认的 `setHostInfo`;
- logout 只清除 Bridge 本地会话,因为 JAR 没有公开 logout 或 Token setter;
- 生产工厂始终返回进程内同一个 Bridge,使互斥锁和本地会话与厂商单例保持一致;
- 真实工厂标记为 `@CleartextAbsdkTransport`,调用方必须显式 opt-in 承认厂商 JAR 的硬编码 HTTP 风险;
- 当前直接引用归档 Sample 目录中的唯一一份 JAR,不复制厂商二进制。
- 当前直接引用归档 Sample 目录中的唯一一份 JAR,不复制厂商二进制;
- ABSDK 0630 没有设备目录能力,Bridge 因此也不提供设备目录或设备发现。
Bridge 本轮尚未加入 `android/app` 依赖,App debug 仍绑定 Fake。提供方选择、安全凭据和真实 Bridge 绑定由后续 `feat/provider-login` 完成;在获批的传输控制方案明确前,不得在 App 中启用真实 Bridge。协议证据与限制记录在 `docs/protocol/absdk-0630.md`。
App 组合根已通过 Hilt 单例绑定该 Bridge,绑定处以 `@CleartextAbsdkTransport` 显式 opt-in 承认厂商 JAR 的硬编码明文 HTTP 风险;App 同时声明 `INTERNET` 权限并允许明文传输(`usesCleartextTraffic`),这是项目所有者对当前局域网集成约束的明确风险接受,不代表传输具备机密性或完整性。协议证据与限制记录在 `docs/protocol/absdk-0630.md`。
## 9. 后续边界
## 10. Provider Session
后续 KremeCN 工作保持为独立短期分支:
`:android:core:session` 负责提供方登录的持久化与 Android 安全边界:
- `feat/provider-login`:提供方入口、安全凭据、自动登录、重新登录和真实 Bridge 绑定;
- `feat/compatible-server`:在协议与连接方式确认后建立服务端、CLI 和 Docker 基础。
- `ProviderProfileStore` 使用 DataStore 保存 profile、当前活动 profile、记住用户名和自动登录开关;已移除的提供方类型(如历史兼容后端值)被忽略,不会成为活动 profile;
- `CredentialStore` 使用 Android Keystore 中的 AES-256-GCM 密钥加密自动登录凭据,DataStore 只保存带随机 IV 的密文;
- `ProviderProfileId` 作为 GCM AAD,防止不同 profile 的密文互换;
- 本地体验的会话由 `:runtime:simulation` 的 `SimulationSessionGateway` 提供,不调用 HTTP 或 ABSDK。
Room、DataStore 和 Android Keystore 的具体 schema/key 只在对应数据所有权明确后创建。历史示例中的 AsyncTask、明文密码存储、全局明文网络和散落 SDK 调用不得进入正式架构。
纯 Kotlin `SessionCoordinator` 统一处理启动恢复、提供方选择、登录偏好、自动登录、Token 失效重登、退出和切换提供方。ABox 登录成功必须来自注入的真实 Bridge 返回 `DomainResult.Success<Session>`;无效凭据和网络错误停留在登录页并显示本地化错误。ABox 远端退出清除密码和 Session,但保留 profile 与记住的用户名以便再次显示登录页;本地体验退出清除本地会话和活动 profile,回到提供方选择。
两个提供方在所有构建变体中始终可用,不存在按 debug/release 区分的可用性开关。
登录完成后进入 `authenticated` 协作路由。当前仅有占位页面,设备列表与主导航由 alZerNest 的设备导航模块接管。
## 11. 后续边界
Room 与设备业务 DataStore 的具体 schema/key 只在对应数据所有权明确后创建。生产 ABox 设备目录由设备目录模块交付后替换 debug 构建中的临时 `FakeDeviceCatalog` 占位。历史示例中的 AsyncTask、明文密码存储、全局明文网络和散落 SDK 调用不得进入正式架构。
+50 -58
View File
@@ -13,18 +13,20 @@
仓库目前主要包含:
- 产品需求概要;
- ABSDK 0630 接口文档;
- AsyncTask 登录示例;
- ABSDK 0630 接口文档与协议观测记录;
- 正式 Android 应用工程(含提供方登录与本地体验运行时);
- ABSDK 防腐层、领域接口、模拟运行时和测试 Fake;
- 清理归档后的 ABSDK Android Sample;
- Git 和 AI 工具协作规则。
当前还没有正式的 Android 应用工程、自有后端、自动化测试或 CI Runner。
当前还没有设备目录、插座温湿度、红外和情景模式的正式实现,也没有 CI Runner。
重要参考资料:
```text
docs/requirement_spec.md
docs/ABSDK接口部分_0630.md
docs/protocol/absdk-0630.md
docs/architecture.md
docs/examples/
samples/abox-sdk-sample/
```
@@ -49,42 +51,46 @@ ABox Manager 是面向 Android 手机和平板的智能家居管理应用,首
## 4. MVP 范围
### 4.1 登录
### 4.1 ABox 登录
以下登录要求只适用于 ABox 提供方;本地体验不需要凭据,也不显示登录页面。
- 支持用户名和密码登录;
- 支持记住用户名;
- 支持按连接配置独立开启自动登录;
- 支持独立开启自动登录;
- 自动登录所需密码必须通过 Android Keystore 安全保存;
- ABSDK Token 由 SDK 自身管理;进程重启或 Token 失效后,通过保存的凭据重新登录;
- 退出登录时保留非敏感连接信息和用户名,清除密码与会话;
- 切换后端提供方前必须退出当前会话。
- 退出登录时保留用户名,清除密码与会话。
### 4.2 提供方模式
应用计划兼容三种相互独立的模式:
应用提供两种入口,认证前必须选择其一:
1. **ABox 后端**:使用现有 ABSDK 0630 连接 ABox 服务;
2. **自有兼容后端**:连接自行实现的 ABSDK 0630 协议兼容服务;
3. **本地体验**:不连接远端服务,通过本地模拟数据体验完整应用流程。
1. **ABox**:通过 ABSDK 0630 连接当前局域网中的智能家居网关;
2. **本地体验**:不访问网络或 ABSDK,通过本地模拟数据直接进入完整应用流程。
首版不提供自有兼容后端入口,也不再规划兼容服务端。
约束:
- 任一时刻只使用一个提供方;
- 不要求同时连接两个后端;
- ABox 与自有后端的账号、会话和数据不互相绑定;
- 每个连接配置拥有独立的设备、遥控器、情景和凭据空间;
- 任一时刻只启用一个提供方;
- 切换提供方前必须退出当前会话;
- 每个提供方的会话、设备、遥控器、情景和凭据空间互不混用;
- 本地体验不启动 HTTP 服务,也不调用 ABSDK。
### 4.3 设备目录
ABSDK 0630 当前没有已确认的设备列表接口,因此首版设备目录采用:
ABSDK 0630 当前没有已确认的设备列表接口,也不提供设备目录。首版设备目录按提供方区分:
- ABox:由设备目录模块负责的本地持久化目录(二维码批量导入,用户手工添加、编辑和删除);
- 本地体验:由模拟运行时内置的模拟设备目录。
共同约束:
- 二维码批量导入;
- 用户手工添加、编辑和删除;
- 设备名称作为调用 ABSDK 的设备标识;
- 设备类型首版只包含插座、温湿度和红外。
不得假设存在尚未确认的新版 SDK 或设备发现接口。
不得假设存在尚未确认的新版 SDK 或远程设备发现接口。
### 4.4 插座
@@ -178,25 +184,15 @@ ABSDK 0630 当前没有已确认的设备列表接口,因此首版设备目录
- 切换提供方前必须结束当前会话;
- `docs/examples/` 和 `samples/abox-sdk-sample/` 只作为参考,不直接作为正式架构。
### 5.3 自有兼容后端
### 5.3 模拟运行时
自有后端目标是兼容 ABSDK 0630 的必要服务端行为。
本地体验由生产模块 `:runtime:simulation` 提供确定性模拟实现:
暂定方向:
- 不依赖网络、ABSDK 或 Android API;
- 内置固定的模拟设备目录和设备状态;
- 与 ABox 共用同一套领域端口,UI 不感知差异。
- Kotlin 和 Ktor;
- 旧协议只存在于兼容适配边界;
- 内部使用类型化领域模型;
- 密码使用强哈希保存;
- 酒店与房间作为数据隔离边界;
- 管理操作通过内置 CLI 完成;
- 提供模拟设备驱动;
- 为未来真实设备驱动预留统一接口;
- SQLite 用于轻量部署;
- PostgreSQL 用于较大规模部署;
- Docker 作为标准交付方式。
具体协议、签名和连接方式必须先验证,不在本文档中提前固化。
测试专用的脚本化 Fake 保留在 `:testing:fakes`,不进入生产依赖。
---
@@ -222,21 +218,20 @@ ABSDK 0630 当前没有已确认的设备列表接口,因此首版设备目录
- 建立 Compose、Navigation、Hilt、Room 和 DataStore 基础;
- 建立公共设计系统基础;
- 接入和封装 ABSDK 0630;
- 建立统一领域接口、错误模型和 Fake 实现;
- 实现 ABox、自有兼容后端和本地体验三个入口;
- 建立统一领域接口、错误模型和测试 Fake;
- 实现 ABox 和本地体验两个入口,以及按活动提供方的设备操作路由;
- 实现记住用户名、自动登录、Keystore 凭据保存和退出;
- 处理 Token 失效与重新登录;
- 研究 SDK 已确认行为和协议边界;
- 建立自有兼容后端基础、测试宿主、CLI 和 Docker 基础。
- 研究 SDK 已确认行为和协议边界。
主要交付:
```text
工程基础
SDK 适配层
SDK 适配层(AbsdkBridge)
本地体验模拟运行时
登录与提供方选择
公共领域接口与 Fake
兼容后端基础
公共领域接口与测试 Fake
```
### 6.2 alZerNest:设备列表导航
@@ -402,8 +397,7 @@ tzh:
退出条件:
- Android App 可以使用 Fake 完成主要页面导航;
- 服务端骨架可以独立启动;
- Android App 可以使用 Fake 或本地体验完成主要页面导航;
- 所有人拥有可独立测试的模块。
### 阶段 2:完整功能实现
@@ -412,8 +406,7 @@ tzh:
- 完成登录和提供方隔离;
- 完成设备目录导入和维护;
- 完成插座、温湿度和红外;
- 完成情景模式;
- 完成自有兼容后端的已确认协议范围。
- 完成情景模式。
退出条件:
@@ -423,8 +416,7 @@ tzh:
### 阶段 3:真实集成
- 连接真实 ABox 环境;
- 连接自有兼容后端;
- 在网关局域网内连接真实 ABox 环境;
- 使用真实插座、温湿度和红外设备;
- 验证 Token 失效、设备离线和错误码;
- 验证手机和平板布局。
@@ -432,7 +424,7 @@ tzh:
退出条件:
- 三类真实硬件核心流程通过;
- ABox 与自有后端连接行为明确;
- ABox 局域网连接行为明确;
- 已知限制完整记录。
### 阶段 4:发布验收
@@ -459,7 +451,6 @@ tzh:
feat/project-foundation
feat/absdk-bridge
feat/provider-login
feat/compatible-server
```
### alZerNest
@@ -530,17 +521,18 @@ feat/app-integration
- 领域模型和执行逻辑单元测试;
- SDK 返回和错误映射测试;
- 提供方选择、会话协调和设备操作路由测试;
- 模拟运行时行为测试;
- ViewModel 状态测试;
- Room 持久化测试;
- Compose 核心页面测试;
- 情景顺序执行和失败继续测试;
- 自有兼容后端认证、存储和模拟驱动测试;
- Docker 和 CLI 验证。
- 情景顺序执行和失败继续测试。
### 11.2 手工验收
- 登录、自动登录和退出;
- 三种提供方入口;
- ABox 登录、自动登录和退出;
- 本地体验直接进入应用;
- 两种提供方入口;
- 数据和凭据隔离;
- 设备目录导入和维护;
- 插座状态和控制;
@@ -573,11 +565,11 @@ Runner 就绪后,再将相同命令配置为受保护 `main` 的必要检查
- ABSDK 0630 的完整初始化流程;
- `setHostInfo` 的正式业务含义;
- ABox 官方部署所需参数;
- 自有后端与原始 JAR 的最终连接方式;
- SDK 的完整签名算法和参数规则;
- SDK 线程安全与会话清理行为;
- 真实测试账号、设备名称和硬件环境;
- 自有后端连接真实设备所使用的网关协议;
- 授权凭据下完整的 ABox 登录与设备操作冒烟验证;
- JAR 硬编码域名与局域网网关地址之间的映射机制(详见 `docs/protocol/absdk-0630.md`);
- ABSDK 二进制的生产分发许可。
上述事项必须通过厂商资料、授权分析、实验或真实环境验证后,再更新本文档或对应技术文档。
+28 -13
View File
@@ -11,7 +11,7 @@
- 历史 Sample:`samples/abox-sdk-sample/login-mac/`;
- 公开 API 使用 `javap` 验证,协议细节通过授权字节码分析验证。
本文不是自有兼容后端的最终规范。真实连接参数、部署行为和硬件结果仍须通过授权测试环境验证。
本文只记录厂商 JAR 与局域网环境的已确认行为,不定义任何兼容服务端规范。尚未验证的内容见文末清单,不得作为产品实现承诺。
## 2. JAR 公开类型
@@ -108,7 +108,7 @@ commons-logging-1.1.3.jar
JAR 内含宽松的 TLS 信任实现。正式产品不得把这一历史传输行为扩展为 App 其他网络请求的安全策略,也不得记录密码、Token、API Key 或敏感红外载荷。
真实 Bridge 工厂使用 `@CleartextAbsdkTransport` 作为编译期 opt-in 门禁,并且当前没有接入 Android App。该标记只防止误接入,不会为链路提供加密。生产集成前必须确定并批准 HTTPS、受控加密代理或其他能够提供机密性与完整性的传输控制;在此之前不得启用真实 ABox 入口。
App 组合根绑定真实 Bridge 时使用 `@CleartextAbsdkTransport` 作为编译期 opt-in 门禁,并声明 `INTERNET` 权限与明文传输许可。该标记只防止误接入,不会为链路提供加密;允许明文是项目所有者对当前局域网集成约束的明确风险接受,不代表传输具备机密性或完整性。
## 6. `setHostInfo` 的已确认行为
@@ -127,7 +127,7 @@ roomNo
apikey
```
其中第一个参数只写入请求字段 `url`,不会修改 SDK 的硬编码 HTTP 基础地址。因此原始 JAR 不能通过该公开 API 直接切换到任意自有后端。
其中第一个参数只写入请求字段 `url`,不会修改 SDK 的硬编码 HTTP 基础地址(见第 5 节)。因此该公开 API 不能用于切换请求目标。
仍未确认:
@@ -136,9 +136,23 @@ apikey
- hotel、room 和 API Key 的正式取值;
- 初始化失败对后续登录和设备操作的影响。
所以 `feat/absdk-bridge` 不实现或调用 `setHostInfo`。
Bridge 不实现或调用 `setHostInfo`。
## 7. MVP 端点与数据
## 7. 局域网网关观测证据(2026-08-24)
以下为 2026-08-24 在网关所在局域网内获得的观测结果,仅描述当天环境,不构成通用承诺:
- 网关地址 `192.168.100.1` 在端口 80 和 443 上可达;
- 未携带 Token 直接 `POST http://192.168.100.1/abox/index.php/abjhsdk/user/validate` 返回 `code=00000`、`status=0`;
- `feat/moler-infrared-control` 分支的真实硬件测试表明:当前网络环境下,厂商 JAR 能够到达真实网关并完成红外相关操作。
同时必须保留以下边界:
- JAR 仍然硬编码基础地址 `a-box.com.cn`;它在该环境中被映射到局域网网关的机制属于外部环境依赖,机制未知,且不受 `setHostInfo` 影响;
- 尚未建立 JAR 可用的通用基础地址或主机配置能力,也没有完成携带授权凭据的登录冒烟验证;
- 观测结果不能外推为“任意网络下均可连通”,后续环境变化须重新验证。
## 8. MVP 端点与数据
| SDK 方法 | 端点 | 关键参数或返回 |
|---|---|---|
@@ -154,7 +168,7 @@ apikey
`downloadIrCodes(List<IrInfo>)` 并不是单次批量 HTTP 请求。JAR 按输入顺序逐项调用下载端点,并返回每项 `status`。只要有任一项失败,总体代码为 `20204`,同时 `dicDatas["ret"]` 仍包含逐项结果。
## 8. 请求签名
## 9. 请求签名
字节码显示 SDK 会:
@@ -165,9 +179,9 @@ apikey
5. 按时间戳计算的位置插入时间片段并添加固定前缀;
6. 在请求的 `system` 数据中提交签名、时间戳和 Token。
这些事实用于判断协议边界,不在本轮重新实现签名算法或对外宣称兼容性。正式兼容后端开始前,必须建立脱敏签名测试向量并复核每个字段和编码细节。
这些事实用于判断协议边界,本轮不重新实现签名算法,也不对外宣称兼容性。任何需要复现该协议行为的工作开始前,必须先建立脱敏签名测试向量并复核每个字段和编码细节。
## 9. 响应结构
## 10. 响应结构
字节码解析的响应结构为:
@@ -183,7 +197,7 @@ apikey
当前 Bridge 对成功数据进行防御性解析:缺失字段、未知状态或错误类型不会导致 `ClassCastException` 泄漏到调用方。
## 10. 错误码来源
## 11. 错误码来源
完整错误码表来自厂商文档和历史 `AboxConstants.java`。Bridge 保留原始 `externalCode`,并映射为以下领域分类:
@@ -199,7 +213,7 @@ apikey
错误 `msg` 只作为诊断 detail,不直接作为最终 UI 文案。
## 11. 历史 Sample 观察
## 12. 历史 Sample 观察
历史 Sample:
@@ -212,14 +226,15 @@ apikey
正式实现只复用已确认的 SDK 调用事实,不复制 AsyncTask、明文凭据或全局明文网络配置。
## 12. 仍待确认
## 13. 仍待确认
- ABox 官方初始化的完整流程和参数;
- 文档所称 Token 两小时有效期在真实环境中的精确表现;
- Token 失效时各设备接口实际返回的代码;
- SDK 的厂商线程安全保证;
- 真实账号、设备名称和硬件环境;
- 原始 JAR 指向自有兼容后端的最终授权方案;
- 授权凭据下完整的 ABox 登录与设备操作冒烟验证;
- JAR 硬编码域名与局域网网关地址之间的映射机制(第 7 节);
- 网络环境变化(不同网段、DHCP、路由策略)下连通性是否保持;
- ABSDK 和附属 JAR 的生产分发许可;
- 所有端点的完整表单编码和可重复签名测试向量。
+8 -3
View File
@@ -1,8 +1,13 @@
## 需求规格
**登录**
1. 记住已登录用户信息功能:记住我
2. 自动登录:选中自动登录之后
**连接方式**
1. ABox:通过 ABSDK 连接当前局域网中的智能家居网关,登录成功后进入应用。
2. 本地体验:不访问网络或 ABSDK,直接建立模拟会话并进入应用。
3. 首版不提供自有兼容后端入口。
**ABox 登录**
1. 记住已登录用户信息功能:记住我(仅适用于 ABox)
2. 自动登录:选中自动登录之后(仅适用于 ABox)
**设备列表**
1. 设备列表:显示设备名称(插座、温湿度、红外)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,238 @@
# LAN ABSDK and Local Experience Design
## Status
Approved on 2026-08-24 by the project owner. This specification replaces the three-provider model in `feat/provider-login`.
## Goal
ABox Manager exposes exactly two choices before authentication:
1. **ABox** uses the real vendor ABSDK bridge to communicate with the smart-home gateway available on the current LAN.
2. **Local experience** uses production-safe simulation implementations, establishes a simulated session immediately, and enters the authenticated app without requesting credentials.
The app no longer offers or plans a self-hosted ABSDK-compatible backend.
## Confirmed Environment and Constraints
- The observed gateway address is `192.168.100.1`.
- The gateway responds to the ABSDK-compatible route `POST /abox/index.php/abjhsdk/user/validate`.
- `libABSDK0630.jar` hardcodes `a-box.com.cn/abox/index.php/` and does not expose a supported base-URL setter.
- `setHostInfo(url, hotelName, roomNo, apikey)` submits `url` as an initialization form field and does not change the HTTP target.
- Hardware testing on `feat/moler-infrared-control` confirms that the current network environment allows the vendor ABSDK to reach the real gateway.
- Debug and release builds expose the same provider choices and routing behavior. Release is not treated as a special case.
- The vendor JAR uses cleartext HTTP. The existing `@CleartextAbsdkTransport` opt-in remains mandatory, and the Android application must explicitly permit the required LAN transport.
- Fake and real sessions, devices, state, and credentials must never be mixed.
## Provider Model
`ProviderType` contains only:
```kotlin
enum class ProviderType {
ABOX,
LOCAL_EXPERIENCE,
}
```
The built-in profiles are:
```text
abox-default -> ProviderType.ABOX
local-experience -> ProviderType.LOCAL_EXPERIENCE
```
The persisted profile store remains tolerant of removed enum values. A stored `COMPATIBLE_BACKEND` profile is ignored. If it was active, the app returns to provider selection rather than attempting migration to another provider.
## User Flow
### ABox
```text
Provider selection
-> choose ABox
-> save and activate ABox profile
-> restore automatic-login preferences when available
-> otherwise show username/password login
-> SessionCoordinator delegates to the process-wide AbsdkBridge
-> enter authenticated app only after DomainResult.Success<Session>
```
Invalid credentials, network errors, and token failures remain on the login screen and display localized errors.
### Local experience
```text
Provider selection
-> choose Local experience
-> save and activate local profile
-> SimulationSessionGateway establishes Username("local") session
-> enter authenticated app immediately
```
Local experience:
- never displays the credential form;
- never calls ABSDK;
- never reads or writes Keystore credentials;
- uses production-safe simulation device gateways;
- can later be removed as a single provider/module boundary if the team decides not to ship it.
## Module Boundaries
### `:absdk-bridge`
Remains the anti-corruption layer around the vendor JAR and implements:
- `SessionGateway`;
- `SocketGateway`;
- `TemperatureHumidityGateway`;
- `InfraredGateway`.
A single process-wide `AbsdkBridge` instance is shared by session and device operations so the mutex and vendor singleton Token remain aligned.
### New `:runtime:simulation`
A production Kotlin/JVM module implementing:
- `LocalSessionGateway` as `SimulationSessionGateway`;
- `DeviceCatalog` as `SimulationDeviceCatalog`;
- `SocketGateway` as `SimulationSocketGateway`;
- `TemperatureHumidityGateway` as `SimulationTemperatureHumidityGateway`;
- `InfraredGateway` as `SimulationInfraredGateway`.
These implementations provide deterministic local experience behavior but do not expose test-only failure injection, mutable call-recording APIs, or assertion helpers.
### `:testing:fakes`
Remains test-only. It keeps scriptable errors, call recording, and other testing controls. It must not be added as an application runtime dependency.
### `:android:core:session`
Keeps provider/profile persistence, Keystore credential storage, and `LocalSessionGatewayImpl` only until the new simulation gateway replaces it. After migration, the old local gateway implementation is removed to prevent two production local-session implementations.
### `:android:app`
Owns the Hilt composition root and provider-aware routing. It injects:
```text
SessionGateway -> AbsdkBridge
LocalSessionGateway -> SimulationSessionGateway
```
For ABSDK-backed device operations, the app exposes provider-routing adapters:
```text
RoutingSocketGateway
RoutingTemperatureHumidityGateway
RoutingInfraredGateway
```
Each adapter reads the active `ProviderProfile` and delegates:
```text
ABOX -> real AbsdkBridge implementation
LOCAL_EXPERIENCE -> simulation implementation
```
`DeviceCatalog` is not implemented by ABSDK 0630. The ABox catalog remains a provider-scoped local persistence responsibility owned by the device-catalog module; `SimulationDeviceCatalog` supplies only the built-in local-experience catalog. This change does not invent a remote discovery API or take ownership of the final ABox catalog implementation from its module owner.
No feature UI selects Real or Fake directly.
## Session and Credential Rules
- `SessionCoordinator` continues to select the session gateway from `ProviderType`.
- ABox credentials can use remember-username and automatic-login settings.
- Automatic-login passwords are stored through Android Keystore.
- Local experience cannot persist credentials or login preferences requiring a password.
- Switching provider logs out the current gateway before activating another profile.
- Logging out of ABox clears credentials and the Bridge-local session but leaves the ABox profile active so the login page can be shown again.
- Logging out of local experience clears the local session and active profile, returning to provider selection.
- Only a session whose `profileId` matches the active profile can produce the authenticated UI state.
## Provider Availability
As implemented, `ProviderAvailability` was deleted entirely: both remaining options are always enabled, so an availability model with disabled states has no caller. The provider selection screen lists exactly ABox and local experience in every build type, with no per-provider availability state or disabled reason.
## Android Transport
The application declares:
```xml
<uses-permission android:name="android.permission.INTERNET" />
```
and permits the vendor cleartext transport required by the current ABSDK. This is an explicit acceptance of the current LAN integration constraint, not a claim that the transport is encrypted.
No password, Token, API key, raw vendor response, or infrared payload may be logged.
## UI and Copy
Provider selection presents exactly:
- **ABox** — connects to the ABox smart-home gateway through ABSDK on the current LAN;
- **Local experience** — uses simulated local devices without network access.
All compatibility-backend copy, status labels, and branches are removed from English and Simplified Chinese resources.
## Error Handling
- ABox authentication failure maps to the localized invalid-credentials message and does not create a session.
- Network failure maps to the localized network message and does not create a session.
- Token invalidation clears the Bridge-local session and returns the app to login.
- Selecting local experience fails visibly if profile persistence or simulated-session creation fails.
- Routing adapters return `DomainError.InvalidRequest` when no active profile exists or the profile type is unsupported.
- Cancellation is rethrown rather than converted to a normal failure.
## Testing Strategy
### Unit tests
- `ProviderType` and provider selection expose exactly ABox and local experience.
- Removed persisted compatible profiles are ignored and cannot become active.
- `SessionCoordinator` routes ABox to `SessionGateway` and local experience to `LocalSessionGateway`.
- Arbitrary ABox credentials do not succeed unless the injected real/fake test gateway returns success.
- Local experience selection creates a session without calling the ABox gateway or credential store.
- Each socket, temperature/humidity, and infrared routing adapter delegates ABox calls to the real test double and local calls to simulation.
- The local-experience device catalog is supplied by simulation without asserting that ABSDK provides ABox device discovery.
- Switching providers logs out the previous session and isolates state.
### Integration and build verification
- Debug and release compile with the same real ABSDK and simulation modules.
- Hilt resolves one binding for each public gateway.
- Android lint validates Internet/cleartext configuration.
- Full command: `./gradlew check testDebugUnitTest test`.
### Authorized hardware validation
On a device connected to the gateway LAN:
1. Choose ABox.
2. Enter a known-invalid credential pair and verify the app stays on login.
3. Enter an authorized valid credential pair and verify authenticated navigation.
4. Validate Token using the shared Bridge.
5. Perform one read-only device query before any control operation.
6. Choose local experience and verify no ABSDK call or network dependency is required.
Sensitive credentials and Tokens are never captured in test reports.
## Documentation Changes
The implementation updates:
- `docs/requirement_spec.md`;
- `docs/project_plan.md`;
- `docs/architecture.md`;
- `docs/protocol/absdk-0630.md`.
The documents must no longer state that the product connects to an ABox cloud service or a self-hosted compatible backend. They must distinguish confirmed LAN behavior from the JAR's still-hardcoded host behavior.
## Out of Scope
- Reimplementing the ABSDK HTTP/signature protocol;
- patching or rewriting the vendor JAR;
- adding a self-hosted compatibility server;
- adding an in-app gateway IP field that the current JAR cannot consume;
- merging the authenticated app shell PR;
- deciding whether local experience remains in the final product beyond preserving it as a removable module boundary.
@@ -15,6 +15,41 @@ interface SessionGateway {
suspend fun logout(profileId: ProviderProfileId): DomainResult<Unit>
}
interface ProviderProfileStore {
fun observeProfiles(): Flow<List<ProviderProfile>>
fun observeActiveProfile(): Flow<ProviderProfile?>
fun observeLoginPreferences(profileId: ProviderProfileId): Flow<LoginPreferences>
suspend fun profiles(): List<ProviderProfile>
suspend fun activeProfile(): ProviderProfile?
suspend fun loginPreferences(profileId: ProviderProfileId): LoginPreferences
suspend fun saveProfile(profile: ProviderProfile): DomainResult<Unit>
suspend fun setActiveProfile(profileId: ProviderProfileId?): DomainResult<Unit>
suspend fun saveLoginPreferences(preferences: LoginPreferences): DomainResult<Unit>
}
interface CredentialStore {
suspend fun saveCredentials(
profileId: ProviderProfileId,
credentials: LoginCredentials,
): DomainResult<Unit>
suspend fun loadCredentials(
profileId: ProviderProfileId,
): DomainResult<LoginCredentials?>
suspend fun clearCredentials(profileId: ProviderProfileId): DomainResult<Unit>
}
interface LocalSessionGateway : SessionGateway
interface DeviceCatalog {
fun observeDevices(
profileId: ProviderProfileId,
@@ -25,7 +25,6 @@ value class Password(val value: String) {
enum class ProviderType {
ABOX,
COMPATIBLE_BACKEND,
LOCAL_EXPERIENCE,
}
@@ -53,6 +52,13 @@ data class LoginCredentials(
val password: Password,
)
data class LoginPreferences(
val profileId: ProviderProfileId,
val rememberedUsername: Username? = null,
val rememberUsername: Boolean = false,
val autoLoginEnabled: Boolean = false,
)
data class Session(
val profileId: ProviderProfileId,
val username: Username,
@@ -0,0 +1,206 @@
package com.flagship.abox.manager.domain
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
@OptIn(ExperimentalCoroutinesApi::class)
class SessionCoordinator(
private val profileStore: ProviderProfileStore,
private val credentialStore: CredentialStore,
private val remoteGateway: SessionGateway,
private val localGateway: LocalSessionGateway,
) {
fun observeActiveSession(): Flow<Session?> = profileStore.observeActiveProfile()
.flatMapLatest { profile ->
profile?.gateway()?.observeSession(profile.id) ?: flowOf(null)
}
suspend fun bootstrap(): DomainResult<Session?> = storeOperation {
val profile = profileStore.activeProfile() ?: return@storeOperation DomainResult.Success(null)
if (profile.type == ProviderType.LOCAL_EXPERIENCE) {
return@storeOperation localGateway.login(profile.id, localCredentials())
.mapSuccess { it }
}
val preferences = profileStore.loginPreferences(profile.id)
if (!preferences.autoLoginEnabled) return@storeOperation DomainResult.Success(null)
when (val credentials = credentialStore.loadCredentials(profile.id)) {
is DomainResult.Failure -> credentials
is DomainResult.Success -> {
val savedCredentials = credentials.value ?: return@storeOperation DomainResult.Success(null)
if (profileStore.activeProfile()?.id != profile.id) {
return@storeOperation DomainResult.Success(null)
}
profile.gateway().login(profile.id, savedCredentials).mapSuccess { it }
}
}
}
suspend fun selectProvider(profile: ProviderProfile): DomainResult<Session?> = storeOperation {
val current = profileStore.activeProfile()
if (current?.id != profile.id && current != null) {
when (val switched = switchProvider()) {
is DomainResult.Failure -> return@storeOperation switched
is DomainResult.Success -> Unit
}
}
when (val saved = profileStore.saveProfile(profile)) {
is DomainResult.Failure -> return@storeOperation saved
is DomainResult.Success -> Unit
}
when (val activated = profileStore.setActiveProfile(profile.id)) {
is DomainResult.Failure -> return@storeOperation activated
is DomainResult.Success -> Unit
}
if (profile.type == ProviderType.LOCAL_EXPERIENCE) {
localGateway.login(profile.id, localCredentials()).mapSuccess { it }
} else {
DomainResult.Success(null)
}
}
suspend fun login(
profileId: ProviderProfileId,
credentials: LoginCredentials,
rememberUsername: Boolean,
autoLogin: Boolean,
): DomainResult<Session> = storeOperation {
val profile = profileStore.activeProfile()
?: return@storeOperation DomainResult.Failure(
DomainError.InvalidRequest(detail = "No active provider profile"),
)
if (profile.id != profileId || profile.type == ProviderType.LOCAL_EXPERIENCE) {
return@storeOperation DomainResult.Failure(
DomainError.InvalidRequest(detail = "The active provider does not require this login"),
)
}
when (val result = remoteGateway.login(profileId, credentials)) {
is DomainResult.Failure -> result
is DomainResult.Success -> {
val previousPreferences = profileStore.loginPreferences(profileId)
val previousCredentials = credentialStore.loadCredentials(profileId)
if (previousCredentials is DomainResult.Failure) {
remoteGateway.logout(profileId)
return@storeOperation previousCredentials
}
val preferences = LoginPreferences(
profileId = profileId,
rememberedUsername = credentials.username.takeIf { rememberUsername },
rememberUsername = rememberUsername,
autoLoginEnabled = autoLogin,
)
val credentialResult = if (autoLogin) {
credentialStore.saveCredentials(profileId, credentials)
} else {
credentialStore.clearCredentials(profileId)
}
if (credentialResult is DomainResult.Failure) {
remoteGateway.logout(profileId)
return@storeOperation credentialResult
}
when (val preferencesResult = profileStore.saveLoginPreferences(preferences)) {
is DomainResult.Success -> result
is DomainResult.Failure -> {
when (previousCredentials) {
is DomainResult.Success -> previousCredentials.value?.let {
credentialStore.saveCredentials(profileId, it)
} ?: credentialStore.clearCredentials(profileId)
is DomainResult.Failure -> Unit
}
profileStore.saveLoginPreferences(previousPreferences)
remoteGateway.logout(profileId)
preferencesResult
}
}
}
}
}
suspend fun recoverSession(profileId: ProviderProfileId): DomainResult<Session?> = storeOperation {
val profile = profileStore.activeProfile()
if (profile?.id != profileId || profile.type == ProviderType.LOCAL_EXPERIENCE) {
return@storeOperation DomainResult.Success(null)
}
val preferences = profileStore.loginPreferences(profileId)
if (!preferences.autoLoginEnabled) return@storeOperation DomainResult.Success(null)
when (val credentials = credentialStore.loadCredentials(profileId)) {
is DomainResult.Failure -> credentials
is DomainResult.Success -> {
val savedCredentials = credentials.value ?: return@storeOperation DomainResult.Success(null)
when (val result = remoteGateway.login(profileId, savedCredentials)) {
is DomainResult.Success -> result.mapSuccess { it }
is DomainResult.Failure -> {
if (result.error is DomainError.Authentication ||
result.error is DomainError.TokenInvalid
) {
credentialStore.clearCredentials(profileId)
profileStore.saveLoginPreferences(
preferences.copy(autoLoginEnabled = false),
)
}
result
}
}
}
}
}
suspend fun logout(): DomainResult<Unit> = storeOperation {
val profile = profileStore.activeProfile() ?: return@storeOperation DomainResult.Success(Unit)
when (val credentialResult = credentialStore.clearCredentials(profile.id)) {
is DomainResult.Failure -> return@storeOperation credentialResult
is DomainResult.Success -> Unit
}
val preferences = profileStore.loginPreferences(profile.id)
when (
val preferencesResult = profileStore.saveLoginPreferences(
preferences.copy(autoLoginEnabled = false),
)
) {
is DomainResult.Failure -> return@storeOperation preferencesResult
is DomainResult.Success -> Unit
}
when (val logoutResult = profile.gateway().logout(profile.id)) {
is DomainResult.Failure -> return@storeOperation logoutResult
is DomainResult.Success -> Unit
}
if (profile.type == ProviderType.LOCAL_EXPERIENCE) {
profileStore.setActiveProfile(null)
} else {
DomainResult.Success(Unit)
}
}
suspend fun switchProvider(): DomainResult<Unit> = storeOperation {
when (val logoutResult = logout()) {
is DomainResult.Failure -> logoutResult
is DomainResult.Success -> profileStore.setActiveProfile(null)
}
}
private fun ProviderProfile.gateway(): SessionGateway =
if (type == ProviderType.LOCAL_EXPERIENCE) localGateway else remoteGateway
private fun localCredentials(): LoginCredentials = LoginCredentials(
username = Username("local"),
password = Password(""),
)
private suspend fun <T> storeOperation(block: suspend () -> DomainResult<T>): DomainResult<T> =
try {
block()
} catch (error: CancellationException) {
throw error
} catch (error: Exception) {
DomainResult.Failure(
DomainError.Unknown(detail = error.message ?: error::class.java.simpleName),
)
}
}
private inline fun <T, R> DomainResult<T>.mapSuccess(transform: (T) -> R): DomainResult<R> = when (this) {
is DomainResult.Failure -> this
is DomainResult.Success -> DomainResult.Success(transform(value))
}
+3
View File
@@ -17,6 +17,8 @@ espresso = "3.6.1"
[libraries]
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" }
androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" }
androidx-lifecycle-viewmodel-ktx = { module = "androidx.lifecycle:lifecycle-viewmodel-ktx", version.ref = "lifecycle" }
androidx-lifecycle-viewmodel-compose = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "lifecycle" }
androidx-navigation-compose = { module = "androidx.navigation:navigation-compose", version.ref = "navigationCompose" }
androidx-hilt-navigation-compose = { module = "androidx.hilt:hilt-navigation-compose", version = "1.2.0" }
compose-bom = { module = "androidx.compose:compose-bom", version.ref = "composeBom" }
@@ -35,6 +37,7 @@ room-ktx = { module = "androidx.room:room-ktx", version.ref = "room" }
datastore-preferences = { module = "androidx.datastore:datastore-preferences", version.ref = "datastore" }
junit = { module = "junit:junit", version.ref = "junit" }
androidx-junit = { module = "androidx.test.ext:junit", version.ref = "androidxJunit" }
androidx-test-runner = { module = "androidx.test:runner", version = "1.6.1" }
espresso-core = { module = "androidx.test.espresso:espresso-core", version.ref = "espresso" }
[plugins]
+14
View File
@@ -0,0 +1,14 @@
plugins {
alias(libs.plugins.kotlin.jvm)
}
kotlin {
jvmToolchain(17)
}
dependencies {
api(project(":domain"))
implementation(libs.kotlinx.coroutines.core)
testImplementation(libs.junit)
testImplementation(libs.kotlinx.coroutines.test)
}
@@ -0,0 +1,50 @@
package com.flagship.abox.manager.simulation
import com.flagship.abox.manager.domain.DeviceCatalog
import com.flagship.abox.manager.domain.DeviceDescriptor
import com.flagship.abox.manager.domain.DeviceId
import com.flagship.abox.manager.domain.DeviceName
import com.flagship.abox.manager.domain.DeviceType
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.ProviderProfileId
import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
class SimulationDeviceCatalog : DeviceCatalog {
private val devices = ConcurrentHashMap<
ProviderProfileId,
MutableStateFlow<DomainResult<List<DeviceDescriptor>>>,
>()
override fun observeDevices(
profileId: ProviderProfileId,
): Flow<DomainResult<List<DeviceDescriptor>>> = deviceFlow(profileId)
private fun deviceFlow(
profileId: ProviderProfileId,
): MutableStateFlow<DomainResult<List<DeviceDescriptor>>> = devices.getOrPut(profileId) {
MutableStateFlow(DomainResult.Success(defaultDevices(profileId)))
}
private fun defaultDevices(profileId: ProviderProfileId): List<DeviceDescriptor> = listOf(
DeviceDescriptor(
id = DeviceId("${profileId.value}:socket-1"),
profileId = profileId,
name = DeviceName("socket-1"),
type = DeviceType.SOCKET,
),
DeviceDescriptor(
id = DeviceId("${profileId.value}:th-1"),
profileId = profileId,
name = DeviceName("th-1"),
type = DeviceType.TEMPERATURE_HUMIDITY,
),
DeviceDescriptor(
id = DeviceId("${profileId.value}:ir-1"),
profileId = profileId,
name = DeviceName("ir-1"),
type = DeviceType.INFRARED,
),
)
}
@@ -0,0 +1,75 @@
package com.flagship.abox.manager.simulation
import com.flagship.abox.manager.domain.DeviceName
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.InfraredCode
import com.flagship.abox.manager.domain.InfraredCodeDownloadResult
import com.flagship.abox.manager.domain.InfraredGateway
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.SocketGateway
import com.flagship.abox.manager.domain.SocketPowerState
import com.flagship.abox.manager.domain.SocketStatus
import com.flagship.abox.manager.domain.TemperatureHumidityGateway
import com.flagship.abox.manager.domain.TemperatureHumidityReading
import java.util.concurrent.ConcurrentHashMap
class SimulationSocketGateway : SocketGateway {
private val states = ConcurrentHashMap<DeviceKey, SocketPowerState>()
override suspend fun getStatus(
profileId: ProviderProfileId,
deviceName: DeviceName,
): DomainResult<SocketStatus> {
val key = DeviceKey(profileId, deviceName)
return DomainResult.Success(SocketStatus(profileId, deviceName, states[key] ?: SocketPowerState.OFF))
}
override suspend fun setPower(
profileId: ProviderProfileId,
deviceName: DeviceName,
powerState: SocketPowerState,
): DomainResult<SocketStatus> {
val key = DeviceKey(profileId, deviceName)
states[key] = powerState
return DomainResult.Success(SocketStatus(profileId, deviceName, powerState))
}
}
class SimulationTemperatureHumidityGateway : TemperatureHumidityGateway {
override suspend fun getReading(
profileId: ProviderProfileId,
deviceName: DeviceName,
): DomainResult<TemperatureHumidityReading> = DomainResult.Success(
TemperatureHumidityReading(
profileId = profileId,
deviceName = deviceName,
temperature = "23.5",
humidity = "45",
),
)
}
class SimulationInfraredGateway : InfraredGateway {
override suspend fun sendKey(
profileId: ProviderProfileId,
deviceName: DeviceName,
key: String,
): DomainResult<Unit> = DomainResult.Success(Unit)
override suspend fun learnKey(
profileId: ProviderProfileId,
deviceName: DeviceName,
key: String,
): DomainResult<Unit> = DomainResult.Success(Unit)
override suspend fun downloadCodes(
profileId: ProviderProfileId,
codes: List<InfraredCode>,
): DomainResult<List<InfraredCodeDownloadResult>> =
DomainResult.Success(codes.map { InfraredCodeDownloadResult(it, successful = true) })
}
private data class DeviceKey(
val profileId: ProviderProfileId,
val deviceName: DeviceName,
)
@@ -0,0 +1,38 @@
package com.flagship.abox.manager.simulation
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.LocalSessionGateway
import com.flagship.abox.manager.domain.LoginCredentials
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.Session
import com.flagship.abox.manager.domain.SessionValidity
import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
class SimulationSessionGateway : LocalSessionGateway {
private val sessions = ConcurrentHashMap<ProviderProfileId, MutableStateFlow<Session?>>()
override fun observeSession(profileId: ProviderProfileId): Flow<Session?> = flow(profileId)
override suspend fun login(
profileId: ProviderProfileId,
credentials: LoginCredentials,
): DomainResult<Session> = DomainResult.Success(
Session(profileId, credentials.username).also { flow(profileId).value = it },
)
override suspend fun validateSession(
profileId: ProviderProfileId,
): DomainResult<SessionValidity> = DomainResult.Success(
if (flow(profileId).value == null) SessionValidity.INVALID else SessionValidity.VALID,
)
override suspend fun logout(profileId: ProviderProfileId): DomainResult<Unit> {
flow(profileId).value = null
return DomainResult.Success(Unit)
}
private fun flow(profileId: ProviderProfileId): MutableStateFlow<Session?> =
sessions.getOrPut(profileId) { MutableStateFlow(null) }
}
@@ -0,0 +1,54 @@
package com.flagship.abox.manager.simulation
import com.flagship.abox.manager.domain.DeviceName
import com.flagship.abox.manager.domain.DeviceType
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.SocketPowerState
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class SimulationDeviceGatewaysTest {
@Test
fun catalogProvidesSocketTemperatureHumidityAndInfraredDevicesForEachProfile() = runTest {
val profile = ProviderProfileId("local")
val devices =
(SimulationDeviceCatalog().observeDevices(profile).first() as DomainResult.Success).value
assertEquals(
setOf(DeviceType.SOCKET, DeviceType.TEMPERATURE_HUMIDITY, DeviceType.INFRARED),
devices.map { it.type }.toSet(),
)
assertTrue(devices.all { it.profileId == profile })
}
@Test
fun socketStateIsMutableAndIsolatedByProfile() = runTest {
val gateway = SimulationSocketGateway()
val device = DeviceName("socket-1")
val first = ProviderProfileId("first")
val second = ProviderProfileId("second")
gateway.setPower(first, device, SocketPowerState.ON)
assertEquals(
SocketPowerState.ON,
(gateway.getStatus(first, device) as DomainResult.Success).value.powerState,
)
assertEquals(
SocketPowerState.OFF,
(gateway.getStatus(second, device) as DomainResult.Success).value.powerState,
)
}
@Test
fun sensorAndInfraredOperationsSucceedWithoutNetworkConfiguration() = runTest {
val profile = ProviderProfileId("local")
val th = SimulationTemperatureHumidityGateway().getReading(profile, DeviceName("th-1"))
assertTrue(th is DomainResult.Success)
assertEquals(
DomainResult.Success(Unit),
SimulationInfraredGateway().sendKey(profile, DeviceName("ir-1"), "power"),
)
}
}
@@ -0,0 +1,31 @@
package com.flagship.abox.manager.simulation
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.LoginCredentials
import com.flagship.abox.manager.domain.Password
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.SessionValidity
import com.flagship.abox.manager.domain.Username
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class SimulationSessionGatewayTest {
@Test
fun loginObserveValidateAndLogoutAreProfileScoped() = runTest {
val gateway = SimulationSessionGateway()
val first = ProviderProfileId("local-one")
val second = ProviderProfileId("local-two")
val result = gateway.login(first, LoginCredentials(Username("local"), Password("")))
assertEquals(Username("local"), (result as DomainResult.Success).value.username)
assertEquals(first, gateway.observeSession(first).first()?.profileId)
assertNull(gateway.observeSession(second).first())
assertEquals(DomainResult.Success(SessionValidity.VALID), gateway.validateSession(first))
gateway.logout(first)
assertEquals(DomainResult.Success(SessionValidity.INVALID), gateway.validateSession(first))
}
}
+2
View File
@@ -23,7 +23,9 @@ dependencyResolutionManagement {
rootProject.name = "abox-manager"
include(":domain")
include(":runtime:simulation")
include(":absdk-bridge")
include(":testing:fakes")
include(":android:core:designsystem")
include(":android:core:session")
include(":android:app")
@@ -0,0 +1,28 @@
package com.flagship.abox.manager.testing.fakes
import com.flagship.abox.manager.domain.CredentialStore
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.LoginCredentials
import com.flagship.abox.manager.domain.ProviderProfileId
import java.util.concurrent.ConcurrentHashMap
class FakeCredentialStore : CredentialStore {
private val values = ConcurrentHashMap<ProviderProfileId, LoginCredentials>()
override suspend fun saveCredentials(
profileId: ProviderProfileId,
credentials: LoginCredentials,
): DomainResult<Unit> {
values[profileId] = credentials
return DomainResult.Success(Unit)
}
override suspend fun loadCredentials(
profileId: ProviderProfileId,
): DomainResult<LoginCredentials?> = DomainResult.Success(values[profileId])
override suspend fun clearCredentials(profileId: ProviderProfileId): DomainResult<Unit> {
values.remove(profileId)
return DomainResult.Success(Unit)
}
}
@@ -0,0 +1,38 @@
package com.flagship.abox.manager.testing.fakes
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.LocalSessionGateway
import com.flagship.abox.manager.domain.LoginCredentials
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.Session
import com.flagship.abox.manager.domain.SessionValidity
import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
class FakeLocalSessionGateway : LocalSessionGateway {
private val sessions = ConcurrentHashMap<ProviderProfileId, MutableStateFlow<Session?>>()
override fun observeSession(profileId: ProviderProfileId): Flow<Session?> = flow(profileId)
override suspend fun login(
profileId: ProviderProfileId,
credentials: LoginCredentials,
): DomainResult<Session> = DomainResult.Success(
Session(profileId, credentials.username).also { flow(profileId).value = it },
)
override suspend fun validateSession(
profileId: ProviderProfileId,
): DomainResult<SessionValidity> = DomainResult.Success(
if (flow(profileId).value == null) SessionValidity.INVALID else SessionValidity.VALID,
)
override suspend fun logout(profileId: ProviderProfileId): DomainResult<Unit> {
flow(profileId).value = null
return DomainResult.Success(Unit)
}
private fun flow(profileId: ProviderProfileId): MutableStateFlow<Session?> =
sessions.getOrPut(profileId) { MutableStateFlow(null) }
}
@@ -0,0 +1,57 @@
package com.flagship.abox.manager.testing.fakes
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.LoginPreferences
import com.flagship.abox.manager.domain.ProviderProfile
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.ProviderProfileStore
import java.util.concurrent.ConcurrentHashMap
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
class FakeProviderProfileStore : ProviderProfileStore {
private val profileValues = ConcurrentHashMap<ProviderProfileId, ProviderProfile>()
private val preferenceValues = ConcurrentHashMap<ProviderProfileId, LoginPreferences>()
private val profilesFlow = MutableStateFlow<List<ProviderProfile>>(emptyList())
private val activeProfileFlow = MutableStateFlow<ProviderProfile?>(null)
private val preferenceFlows = ConcurrentHashMap<ProviderProfileId, MutableStateFlow<LoginPreferences>>()
override fun observeProfiles(): Flow<List<ProviderProfile>> = profilesFlow
override fun observeActiveProfile(): Flow<ProviderProfile?> = activeProfileFlow
override fun observeLoginPreferences(profileId: ProviderProfileId): Flow<LoginPreferences> =
preferenceFlow(profileId)
override suspend fun profiles(): List<ProviderProfile> = profilesFlow.value
override suspend fun activeProfile(): ProviderProfile? = activeProfileFlow.value
override suspend fun loginPreferences(profileId: ProviderProfileId): LoginPreferences =
preferenceFlow(profileId).value
override suspend fun saveProfile(profile: ProviderProfile): DomainResult<Unit> {
profileValues[profile.id] = profile
profilesFlow.value = profileValues.values.sortedBy { it.id.value }
if (activeProfileFlow.value?.id == profile.id) activeProfileFlow.value = profile
return DomainResult.Success(Unit)
}
override suspend fun setActiveProfile(profileId: ProviderProfileId?): DomainResult<Unit> {
activeProfileFlow.value = profileId?.let(profileValues::get)
return DomainResult.Success(Unit)
}
override suspend fun saveLoginPreferences(preferences: LoginPreferences): DomainResult<Unit> {
preferenceValues[preferences.profileId] = preferences
preferenceFlow(preferences.profileId).value = preferences
return DomainResult.Success(Unit)
}
private fun preferenceFlow(profileId: ProviderProfileId): MutableStateFlow<LoginPreferences> =
preferenceFlows.getOrPut(profileId) {
MutableStateFlow(
preferenceValues[profileId] ?: LoginPreferences(profileId),
)
}
}
@@ -0,0 +1,29 @@
package com.flagship.abox.manager.testing.fakes
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.LoginCredentials
import com.flagship.abox.manager.domain.Password
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.Username
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class FakeCredentialStoreTest {
@Test
fun credentialsAreIsolatedByProfileAndClearIndependently() = runTest {
val store = FakeCredentialStore()
val first = ProviderProfileId("first")
val second = ProviderProfileId("second")
val firstCredentials = LoginCredentials(Username("one"), Password("secret-one"))
val secondCredentials = LoginCredentials(Username("two"), Password("secret-two"))
store.saveCredentials(first, firstCredentials)
store.saveCredentials(second, secondCredentials)
store.clearCredentials(first)
assertNull((store.loadCredentials(first) as DomainResult.Success).value)
assertEquals(secondCredentials, (store.loadCredentials(second) as DomainResult.Success).value)
}
}
@@ -0,0 +1,30 @@
package com.flagship.abox.manager.testing.fakes
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.LoginPreferences
import com.flagship.abox.manager.domain.ProviderProfile
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.ProviderType
import com.flagship.abox.manager.domain.Username
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Test
class FakeProviderProfileStoreTest {
@Test
fun storesProfilesActiveSelectionAndPreferences() = runTest {
val store = FakeProviderProfileStore()
val id = ProviderProfileId("local")
val profile = ProviderProfile(id, ProviderType.LOCAL_EXPERIENCE, "Local")
val preferences = LoginPreferences(id, Username("demo"), true, false)
assertEquals(DomainResult.Success(Unit), store.saveProfile(profile))
store.setActiveProfile(id)
store.saveLoginPreferences(preferences)
assertEquals(listOf(profile), store.observeProfiles().first())
assertEquals(profile, store.observeActiveProfile().first())
assertEquals(preferences, store.observeLoginPreferences(id).first())
}
}
@@ -0,0 +1,242 @@
package com.flagship.abox.manager.testing.fakes
import com.flagship.abox.manager.domain.CredentialStore
import com.flagship.abox.manager.domain.DomainError
import com.flagship.abox.manager.domain.DomainResult
import com.flagship.abox.manager.domain.LoginCredentials
import com.flagship.abox.manager.domain.LoginPreferences
import com.flagship.abox.manager.domain.Password
import com.flagship.abox.manager.domain.ProviderProfile
import com.flagship.abox.manager.domain.ProviderProfileId
import com.flagship.abox.manager.domain.ProviderType
import com.flagship.abox.manager.domain.SessionCoordinator
import com.flagship.abox.manager.domain.SessionGateway
import com.flagship.abox.manager.domain.Session
import com.flagship.abox.manager.domain.Username
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class SessionCoordinatorTest {
private val remoteProfile = ProviderProfile(
ProviderProfileId("abox"),
ProviderType.ABOX,
"ABox",
)
private val localProfile = ProviderProfile(
ProviderProfileId("local"),
ProviderType.LOCAL_EXPERIENCE,
"Local",
)
private val credentials = LoginCredentials(Username("demo"), Password("secret"))
@Test
fun localProviderCreatesSessionWithoutRemoteLogin() = runTest {
val fixture = Fixture()
val result = fixture.coordinator.selectProvider(localProfile)
assertTrue(result is DomainResult.Success)
assertEquals(localProfile.id, fixture.coordinator.observeActiveSession().first()?.profileId)
assertNull(fixture.remote.observeSession(localProfile.id).first())
}
@Test
fun localSelectionCreatesSessionWithoutAboxOrCredentialAccess() = runTest {
val remote = CountingSessionGateway()
val credentialsStore = CountingCredentialStore()
val coordinator = SessionCoordinator(
FakeProviderProfileStore(),
credentialsStore,
remote,
FakeLocalSessionGateway(),
)
val result = coordinator.selectProvider(localProfile)
assertTrue(result is DomainResult.Success)
assertEquals(0, remote.loginCalls)
assertEquals(0, credentialsStore.loadCalls + credentialsStore.saveCalls)
assertEquals(localProfile.id, coordinator.observeActiveSession().first()?.profileId)
}
@Test
fun aboxAuthenticationFailureDoesNotCreateSession() = runTest {
val fixture = Fixture()
fixture.coordinator.selectProvider(remoteProfile)
fixture.remote.failLogin(remoteProfile.id, DomainError.Authentication())
val result = fixture.coordinator.login(remoteProfile.id, credentials, false, false)
assertTrue(result is DomainResult.Failure)
assertNull(fixture.coordinator.observeActiveSession().first())
}
@Test
fun loginPersistsIndependentUsernameAndAutoLoginChoices() = runTest {
val fixture = Fixture()
fixture.coordinator.selectProvider(remoteProfile)
fixture.coordinator.login(
remoteProfile.id,
credentials,
rememberUsername = false,
autoLogin = true,
)
val preferences = fixture.profiles.loginPreferences(remoteProfile.id)
assertNull(preferences.rememberedUsername)
assertTrue(preferences.autoLoginEnabled)
assertEquals(
credentials,
(fixture.credentials.loadCredentials(remoteProfile.id) as DomainResult.Success).value,
)
}
@Test
fun bootstrapUsesSavedAutoLoginCredentials() = runTest {
val fixture = Fixture()
fixture.profiles.saveProfile(remoteProfile)
fixture.profiles.setActiveProfile(remoteProfile.id)
fixture.profiles.saveLoginPreferences(
LoginPreferences(remoteProfile.id, autoLoginEnabled = true),
)
fixture.credentials.saveCredentials(remoteProfile.id, credentials)
val result = fixture.coordinator.bootstrap()
assertEquals(remoteProfile.id, (result as DomainResult.Success).value?.profileId)
}
@Test
fun remoteLogoutClearsPasswordButKeepsProfileAndUsername() = runTest {
val fixture = Fixture()
fixture.coordinator.selectProvider(remoteProfile)
fixture.coordinator.login(
remoteProfile.id,
credentials,
rememberUsername = true,
autoLogin = true,
)
fixture.coordinator.logout()
assertEquals(remoteProfile, fixture.profiles.activeProfile())
val preferences = fixture.profiles.loginPreferences(remoteProfile.id)
assertEquals(credentials.username, preferences.rememberedUsername)
assertTrue(!preferences.autoLoginEnabled)
assertNull(
(fixture.credentials.loadCredentials(remoteProfile.id) as DomainResult.Success).value,
)
}
@Test
fun authenticationFailureDuringRecoveryClearsSavedCredential() = runTest {
val fixture = Fixture()
fixture.profiles.saveProfile(remoteProfile)
fixture.profiles.setActiveProfile(remoteProfile.id)
fixture.profiles.saveLoginPreferences(
LoginPreferences(remoteProfile.id, autoLoginEnabled = true),
)
fixture.credentials.saveCredentials(remoteProfile.id, credentials)
fixture.remote.failLogin(remoteProfile.id, DomainError.Authentication())
val result = fixture.coordinator.recoverSession(remoteProfile.id)
assertTrue(result is DomainResult.Failure)
assertNull(
(fixture.credentials.loadCredentials(remoteProfile.id) as DomainResult.Success).value,
)
assertTrue(!fixture.profiles.loginPreferences(remoteProfile.id).autoLoginEnabled)
}
@Test
fun switchingFromAuthenticatedAboxToLocalClearsRemoteSessionAndIsolatesState() = runTest {
val fixture = Fixture()
fixture.coordinator.selectProvider(remoteProfile)
val loginResult = fixture.coordinator.login(
remoteProfile.id,
credentials,
rememberUsername = true,
autoLogin = true,
)
val switchResult = fixture.coordinator.selectProvider(localProfile)
assertTrue(loginResult is DomainResult.Success)
assertTrue(switchResult is DomainResult.Success)
assertEquals(
localProfile.id,
(switchResult as DomainResult.Success).value?.profileId,
)
assertEquals(localProfile.id, fixture.profiles.activeProfile()?.id)
assertEquals(
localProfile.id,
fixture.coordinator.observeActiveSession().first()?.profileId,
)
assertNull(fixture.remote.observeSession(remoteProfile.id).first())
assertNull(fixture.remote.observeSession(localProfile.id).first())
assertEquals(
localProfile.id,
fixture.local.observeSession(localProfile.id).first()?.profileId,
)
assertNull(
(fixture.credentials.loadCredentials(remoteProfile.id) as DomainResult.Success).value,
)
assertTrue(!fixture.profiles.loginPreferences(remoteProfile.id).autoLoginEnabled)
}
private class Fixture {
val profiles = FakeProviderProfileStore()
val credentials = FakeCredentialStore()
val remote = FakeSessionGateway()
val local = FakeLocalSessionGateway()
val coordinator = SessionCoordinator(profiles, credentials, remote, local)
}
private class CountingSessionGateway(
private val delegate: FakeSessionGateway = FakeSessionGateway(),
) : SessionGateway by delegate {
var loginCalls = 0
private set
override suspend fun login(
profileId: ProviderProfileId,
credentials: LoginCredentials,
): DomainResult<Session> {
loginCalls++
return delegate.login(profileId, credentials)
}
fun failLogin(profileId: ProviderProfileId, error: DomainError) {
delegate.failLogin(profileId, error)
}
}
private class CountingCredentialStore(
private val delegate: FakeCredentialStore = FakeCredentialStore(),
) : CredentialStore by delegate {
var loadCalls = 0
private set
var saveCalls = 0
private set
override suspend fun loadCredentials(
profileId: ProviderProfileId,
): DomainResult<LoginCredentials?> {
loadCalls++
return delegate.loadCredentials(profileId)
}
override suspend fun saveCredentials(
profileId: ProviderProfileId,
credentials: LoginCredentials,
): DomainResult<Unit> {
saveCalls++
return delegate.saveCredentials(profileId, credentials)
}
}
}