Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions face/capture/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ dependencies {
implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))

implementation(project(":infra:orchestrator-data"))
implementation(project(":infra:auth-store"))
implementation(project(":infra:config-store"))
implementation(project(":infra:config-sync"))
implementation(project(":infra:enrolment-records-store"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.simprints.core.DeviceID
import com.simprints.core.livedata.LiveDataEvent
import com.simprints.core.livedata.LiveDataEventWithContent
import com.simprints.core.livedata.send
Expand All @@ -15,29 +16,37 @@ import com.simprints.face.capture.usecases.BitmapToByteArrayUseCase
import com.simprints.face.capture.usecases.SaveFaceImageUseCase
import com.simprints.face.capture.usecases.SimpleCaptureEventReporter
import com.simprints.face.infra.biosdkresolver.ResolveFaceBioSdkUseCase
import com.simprints.infra.authstore.AuthStore
import com.simprints.infra.config.sync.ConfigManager
import com.simprints.infra.license.LicenseRepository
import com.simprints.infra.license.LicenseState
import com.simprints.infra.license.LicenseStatus
import com.simprints.infra.license.SaveLicenseCheckEventUseCase
import com.simprints.infra.license.Vendor
import com.simprints.infra.license.determineLicenseStatus
import com.simprints.infra.license.remote.License
import com.simprints.infra.logging.LoggingConstants.CrashReportTag
import com.simprints.infra.logging.Simber
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.last
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Inject

@HiltViewModel
internal class FaceCaptureViewModel @Inject constructor(
private val authStore: AuthStore,
private val configManager: ConfigManager,
private val saveFaceImage: SaveFaceImageUseCase,
private val eventReporter: SimpleCaptureEventReporter,
private val bitmapToByteArray: BitmapToByteArrayUseCase,
private val licenseRepository: LicenseRepository,
private val resolveFaceBioSdk: ResolveFaceBioSdkUseCase,
private val saveLicenseCheckEvent: SaveLicenseCheckEventUseCase,
@DeviceID private val deviceID: String,
) : ViewModel() {

// Updated in live feedback screen
Expand Down Expand Up @@ -77,26 +86,49 @@ internal class FaceCaptureViewModel @Inject constructor(
}

fun initFaceBioSdk(activity: Activity) = viewModelScope.launch {
val license = licenseRepository.getCachedLicense(Vendor.RANK_ONE)
val licenseVendor = Vendor.RANK_ONE
val license = licenseRepository.getCachedLicense(licenseVendor)
var licenseStatus = license.determineLicenseStatus()

if (licenseStatus == LicenseStatus.VALID) {
val initializer = resolveFaceBioSdk().initializer
if (!initializer.tryInitWithLicense(activity, license!!.data)) {
// License is valid but the SDK failed to initialize
// This is should reported as an error
licenseStatus = LicenseStatus.ERROR
}
licenseStatus = initialize(activity, license!!)
}

// In some cases license is invalidated on initialisation attempt
if (licenseStatus != LicenseStatus.VALID) {
Comment thread
luhmirin-s marked this conversation as resolved.
Simber.tag(CrashReportTag.LICENSE.name).i("Face license is $licenseStatus - attempting download")
licenseStatus = refreshLicenceAndRetry(activity, licenseVendor)
}
// Still invalid after attempted refresh
if (licenseStatus != LicenseStatus.VALID) {
Simber.tag(CrashReportTag.LICENSE.name).i("Face license is $licenseStatus")
licenseRepository.deleteCachedLicense(Vendor.RANK_ONE)
_invalidLicense.send()
}
saveLicenseCheckEvent(Vendor.RANK_ONE, licenseStatus)
}

private suspend fun initialize(activity: Activity, license: License): LicenseStatus {
val initializer = resolveFaceBioSdk().initializer
if (!initializer.tryInitWithLicense(activity, license.data)) {
// License is valid but the SDK failed to initialize
// This is should reported as an error
return LicenseStatus.ERROR
}
return LicenseStatus.VALID
}

private suspend fun refreshLicenceAndRetry(activity: Activity, licenseVendor: Vendor) = licenseRepository
.redownloadLicence(authStore.signedInProjectId, deviceID, licenseVendor)
.map { state ->
when (state) {
is LicenseState.FinishedWithSuccess -> initialize(activity, state.license)
is LicenseState.FinishedWithBackendMaintenanceError, is LicenseState.FinishedWithError -> LicenseStatus.MISSING
else -> null
}
}
.filterNotNull()
.last()

fun getSampleDetection() = faceDetections.firstOrNull()

fun flowFinished() {
Expand All @@ -108,9 +140,7 @@ internal class FaceCaptureViewModel @Inject constructor(

val items = faceDetections.mapIndexed { index, detection ->
FaceCaptureResult.Item(
captureEventId = detection.id,
index = index,
sample = FaceCaptureResult.Sample(
captureEventId = detection.id, index = index, sample = FaceCaptureResult.Sample(
faceId = detection.id,
template = detection.face?.template ?: ByteArray(0),
imageRef = detection.securedImageRef,
Expand Down Expand Up @@ -144,8 +174,7 @@ internal class FaceCaptureViewModel @Inject constructor(

private fun saveImage(faceDetection: FaceDetection, captureEventId: String) {
runBlocking {
faceDetection.securedImageRef =
saveFaceImage(bitmapToByteArray(faceDetection.bitmap), captureEventId)
faceDetection.securedImageRef = saveFaceImage(bitmapToByteArray(faceDetection.bitmap), captureEventId)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,17 @@ import com.simprints.face.capture.usecases.BitmapToByteArrayUseCase
import com.simprints.face.capture.usecases.SaveFaceImageUseCase
import com.simprints.face.capture.usecases.SimpleCaptureEventReporter
import com.simprints.face.infra.basebiosdk.initialization.FaceBioSdkInitializer
import com.simprints.infra.authstore.AuthStore
import com.simprints.infra.config.store.models.FaceConfiguration.ImageSavingStrategy
import com.simprints.infra.config.sync.ConfigManager
import com.simprints.infra.license.LicenseRepository
import com.simprints.infra.license.LicenseState
import com.simprints.infra.license.LicenseStatus
import com.simprints.infra.license.SaveLicenseCheckEventUseCase
import com.simprints.infra.license.Vendor
import com.simprints.infra.license.remote.License
import com.simprints.testtools.common.coroutines.TestCoroutineRule
import com.simprints.testtools.common.livedata.assertEventNotReceived
import com.simprints.testtools.common.livedata.assertEventReceived
import com.simprints.testtools.common.livedata.getOrAwaitValue
import io.mockk.MockKAnnotations
Expand All @@ -28,6 +31,7 @@ import io.mockk.impl.annotations.RelaxedMockK
import io.mockk.mockk
import io.mockk.slot
import io.mockk.verify
import kotlinx.coroutines.flow.flowOf
import org.junit.Before
import org.junit.Rule
import org.junit.Test
Expand All @@ -40,6 +44,9 @@ class FaceCaptureViewModelTest {
@get:Rule
val testCoroutineRule = TestCoroutineRule()

@MockK
private lateinit var authStore: AuthStore

@MockK
private lateinit var configManager: ConfigManager

Expand Down Expand Up @@ -75,8 +82,10 @@ class FaceCaptureViewModelTest {
MockKAnnotations.init(this, relaxed = true)
coEvery { faceImageUseCase.invoke(any(), any()) } returns null
every { bitmapToByteArrayUseCase.invoke(any()) } returns byteArrayOf()
every { authStore.signedInProjectId } returns "projectId"

viewModel = FaceCaptureViewModel(
authStore,
configManager,
faceImageUseCase,
eventReporter,
Expand All @@ -85,7 +94,8 @@ class FaceCaptureViewModelTest {
mockk {
coEvery { this@mockk().initializer } returns faceBioSdkInitializer
},
saveLicenseCheckEvent
saveLicenseCheckEvent,
"deviceId"
)
}

Expand Down Expand Up @@ -163,39 +173,115 @@ class FaceCaptureViewModelTest {
}

@Test
fun `test initFaceBioSdk should post invalid license when faceBioSdkInitializer returns false`() {
fun `test initFaceBioSdk should post invalid license when faceBioSdkInitializer always returns false`() {
// Given
val license = "license"
coEvery {
licenseRepository.getCachedLicense(Vendor.RANK_ONE)
} returns License("2133-12-30T17:32:28Z", license)
val licenseStatusSlot = slot<LicenseStatus>()
coJustRun { saveLicenseCheckEvent(Vendor.RANK_ONE, capture(licenseStatusSlot)) }

// Downloading not expired licence
coEvery {
licenseRepository.redownloadLicence(any(), any(), any())
} returns flowOf(
LicenseState.Started,
LicenseState.Downloading,
LicenseState.FinishedWithSuccess(License("2133-12-30T17:32:28Z", license))
)
coEvery { faceBioSdkInitializer.tryInitWithLicense(any(), license) } returns false

// When
viewModel.initFaceBioSdk(mockk())
// Then
viewModel.invalidLicense.assertEventReceived()
coVerify { licenseRepository.deleteCachedLicense(Vendor.RANK_ONE) }
coVerify { licenseRepository.redownloadLicence(any(), any(), any()) }
coVerify { licenseRepository.deleteCachedLicense(any()) }
assertThat(licenseStatusSlot.captured).isEqualTo(LicenseStatus.ERROR)
}

@Test
fun `test initFaceBioSdk should post invalid license when license is expired`() {
fun `test initFaceBioSdk should try re-downloading licence when expired`() {
// Given
val license = "license"
coEvery {
licenseRepository.getCachedLicense(Vendor.RANK_ONE)
} returns License("2011-12-30T17:32:28Z", license)
coEvery {
licenseRepository.redownloadLicence(any(), any(), any())
} returns flowOf(
LicenseState.Started,
LicenseState.Downloading,
LicenseState.FinishedWithSuccess(License("2133-12-30T17:32:28Z", license))
)
every { faceBioSdkInitializer.tryInitWithLicense(any(), license) } returns true

val licenseStatusSlot = slot<LicenseStatus>()
coJustRun { saveLicenseCheckEvent(Vendor.RANK_ONE, capture(licenseStatusSlot)) }

// When
viewModel.initFaceBioSdk(mockk())

// Then
viewModel.invalidLicense.assertEventNotReceived()
coVerify { licenseRepository.redownloadLicence(any(), any(), Vendor.RANK_ONE) }
coVerify { faceBioSdkInitializer.tryInitWithLicense(any(), license) }
assertThat(licenseStatusSlot.captured).isEqualTo(LicenseStatus.VALID)
}

@Test
fun `test initFaceBioSdk should try re-downloading licence when initially invalid`() {
// Given
val license = "license"
coEvery {
licenseRepository.getCachedLicense(Vendor.RANK_ONE)
} returns License("2133-12-30T17:32:28Z", license)
coEvery {
licenseRepository.redownloadLicence(any(), any(), any())
} returns flowOf(
LicenseState.Started,
LicenseState.Downloading,
LicenseState.FinishedWithSuccess(License("2133-12-30T17:32:28Z", license))
)
every { faceBioSdkInitializer.tryInitWithLicense(any(), license) } returnsMany listOf(false, true)

val licenseStatusSlot = slot<LicenseStatus>()
coJustRun { saveLicenseCheckEvent(Vendor.RANK_ONE, capture(licenseStatusSlot)) }

// When
viewModel.initFaceBioSdk(mockk())

// Then
viewModel.invalidLicense.assertEventNotReceived()
coVerify { licenseRepository.redownloadLicence(any(), any(), Vendor.RANK_ONE) }
coVerify(exactly = 2) { faceBioSdkInitializer.tryInitWithLicense(any(), license) }
assertThat(licenseStatusSlot.captured).isEqualTo(LicenseStatus.VALID)
}

@Test
fun `test initFaceBioSdk should return error when re-download fails`() {
// Given
val license = "license"
coEvery {
licenseRepository.getCachedLicense(Vendor.RANK_ONE)
} returns License("2011-12-30T17:32:28Z", license)
coEvery {
licenseRepository.redownloadLicence(any(), any(), any())
} returns flowOf(
LicenseState.Started,
LicenseState.Downloading,
LicenseState.FinishedWithError("error")
)

val licenseStatusSlot = slot<LicenseStatus>()
coJustRun { saveLicenseCheckEvent(Vendor.RANK_ONE, capture(licenseStatusSlot)) }

// When
viewModel.initFaceBioSdk(mockk())

// Then
viewModel.invalidLicense.assertEventReceived()
coVerify { licenseRepository.deleteCachedLicense(Vendor.RANK_ONE) }
assertThat(licenseStatusSlot.captured).isEqualTo(LicenseStatus.EXPIRED)
coVerify { licenseRepository.redownloadLicence(any(), any(), Vendor.RANK_ONE) }
assertThat(licenseStatusSlot.captured).isEqualTo(LicenseStatus.MISSING)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ import kotlinx.coroutines.flow.Flow

interface LicenseRepository {

fun redownloadLicence(
projectId: String,
deviceId: String,
licenseVendor: Vendor
): Flow<LicenseState>

fun getLicenseStates(
projectId: String,
deviceId: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import com.simprints.infra.license.remote.License
import com.simprints.infra.license.remote.LicenseRemoteDataSource
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.flow
import javax.inject.Inject

Expand All @@ -14,6 +15,14 @@ internal class LicenseRepositoryImpl @Inject constructor(
private val licenseRemoteDataSource: LicenseRemoteDataSource,
) : LicenseRepository {

override fun redownloadLicence(
projectId: String,
deviceId: String,
licenseVendor: Vendor
): Flow<LicenseState> = flow {
licenseLocalDataSource.deleteCachedLicense(licenseVendor)
emitAll(getLicenseStates(projectId, deviceId, licenseVendor))
}

override fun getLicenseStates(
projectId: String,
Expand Down Expand Up @@ -50,7 +59,7 @@ internal class LicenseRepositoryImpl @Inject constructor(
* @param licenseVendor
* @return cached license as [String]
*/
override suspend fun getCachedLicense(licenseVendor: Vendor)=
override suspend fun getCachedLicense(licenseVendor: Vendor) =
licenseLocalDataSource.getLicense(licenseVendor)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,40 @@ class LicenseRepositoryImplTest {
}
}

@Test
fun `re-download license flow `() = runTest {
coEvery { licenseLocalDataSource.getLicense(RANK_ONE_FACE) } returns null

val licenseStates = mutableListOf<LicenseState>()
licenseRepositoryImpl.redownloadLicence("validProject", "deviceId", RANK_ONE_FACE)
.toCollection(licenseStates)

with(licenseStates) {
assertThat(size).isEqualTo(3)
assertThat(get(0)).isEqualTo(LicenseState.Started)
assertThat(get(1)).isEqualTo(LicenseState.Downloading)
assertThat(get(2)).isEqualTo(LicenseState.FinishedWithSuccess(license))
}
coVerify { licenseLocalDataSource.deleteCachedLicense(any()) }
}

@Test
fun `get error if re-downloading go wrong`() = runTest {
coEvery { licenseLocalDataSource.getLicense(RANK_ONE_FACE) } returns null

val licenseStates = mutableListOf<LicenseState>()
licenseRepositoryImpl.redownloadLicence("invalidProject", "deviceId", RANK_ONE_FACE)
.toCollection(licenseStates)

with(licenseStates) {
assertThat(size).isEqualTo(3)
assertThat(get(0)).isEqualTo(LicenseState.Started)
assertThat(get(1)).isEqualTo(LicenseState.Downloading)
assertThat(get(2)).isEqualTo(LicenseState.FinishedWithError("001"))
}
coVerify { licenseLocalDataSource.deleteCachedLicense(any()) }
}

@Test
fun `get license flow from remote`() = runTest {
coEvery { licenseLocalDataSource.getLicense(RANK_ONE_FACE) } returns null
Expand Down