ChirpPairViewModel.kt

5.4 KB · raw

1package com.peachpasswords.ui.pairing23import android.content.Context4import androidx.lifecycle.ViewModel5import androidx.lifecycle.viewModelScope6import com.peachpasswords.BuildConfig7import com.peachpasswords.sync.AudioIO8import com.peachpasswords.sync.ChirpPairingDeps9import com.peachpasswords.sync.LocalChirpIdentity10import com.peachpasswords.sync.PairedDevice11import com.peachpasswords.sync.PairingEndpoint12import com.peachpasswords.sync.PairingPhase13import com.peachpasswords.sync.PairingProgress14import com.peachpasswords.sync.PairingRole15import com.peachpasswords.sync.PairingServer16import com.peachpasswords.sync.PairingTransport17import com.peachpasswords.sync.buildLocalIdentity18import com.peachpasswords.sync.openAndroidAudioIO19import com.peachpasswords.sync.runChirpPairing20import com.peachpasswords.vault.VaultCrypto21import com.peachpasswords.vault.VaultRepository22import dagger.hilt.android.lifecycle.HiltViewModel23import dagger.hilt.android.qualifiers.ApplicationContext24import kotlinx.coroutines.CompletableDeferred25import kotlinx.coroutines.delay26import kotlinx.coroutines.flow.MutableStateFlow27import kotlinx.coroutines.flow.StateFlow28import kotlinx.coroutines.flow.asStateFlow29import kotlinx.coroutines.launch30import javax.inject.Inject3132/**33 * Drives the Chirp pairing flow and surfaces its phase + SAS code to34 * [ChirpPairScreen]. The real audio bridge ([openAndroidAudioIO]) lands in35 * Phase 12; until then [startPairing] runs the genuine orchestrator and36 * surfaces the audio-unavailable phase honestly, while [runDemo] (DEBUG only)37 * steps the visuals through all three acts so the animation and SAS screen can38 * be verified on a single device.39 */40@HiltViewModel41class ChirpPairViewModel @Inject constructor(42    @ApplicationContext private val context: Context,43    private val vault: VaultRepository,44) : ViewModel() {4546    private val _progress = MutableStateFlow(PairingProgress(PairingPhase.IDLE))47    val progress: StateFlow<PairingProgress> = _progress.asStateFlow()4849    private val _sasCode = MutableStateFlow<String?>(null)50    val sasCode: StateFlow<String?> = _sasCode.asStateFlow()5152    val isDebug: Boolean = BuildConfig.DEBUG5354    private var sasGate: CompletableDeferred<Boolean>? = null5556    fun startPairing() {57        val master = vault.syncMasterKey() ?: run {58            _progress.value = PairingProgress(PairingPhase.HANDSHAKE_FAILED, errorMessage = "vault_locked")59            return60        }61        _progress.value = PairingProgress(PairingPhase.LISTENING)62        viewModelScope.launch {63            try {64                runChirpPairing(deps(master), role = PairingRole.INITIATOR)65            } catch (e: Exception) {66                if (_progress.value.phase.let { it != PairingPhase.TIMEOUT && it != PairingPhase.MIC_DENIED }) {67                    _progress.value = PairingProgress(68                        PairingPhase.HANDSHAKE_FAILED,69                        errorMessage = e.message ?: "pairing_failed",70                    )71                }72            } finally {73                VaultCrypto.zero(master)74            }75        }76    }7778    fun confirmSas(accepted: Boolean) {79        sasGate?.complete(accepted)80        _sasCode.value = null81    }8283    fun reset() {84        sasGate?.complete(false)85        sasGate = null86        _sasCode.value = null87        _progress.value = PairingProgress(PairingPhase.IDLE)88    }8990    /** DEBUG: walk the three acts so the screen can be exercised without a peer. */91    fun runDemo() {92        if (!isDebug) return93        viewModelScope.launch {94            _progress.value = PairingProgress(PairingPhase.IDLE)95            delay(700)96            _progress.value = PairingProgress(PairingPhase.LISTENING)97            delay(1800)98            _progress.value = PairingProgress(PairingPhase.HANDSHAKE, peerDeviceName = "June's Laptop")99            _sasCode.value = "418 207"100        }101    }102103    /** DEBUG: complete the demo into the paired act after SAS confirmation. */104    fun demoComplete() {105        _sasCode.value = null106        _progress.value = PairingProgress(PairingPhase.PAIRED, peerDeviceName = "June's Laptop")107    }108109    private fun deps(masterKey: ByteArray): ChirpPairingDeps = object : ChirpPairingDeps {110        override val chirpTimeoutMs: Long = 15_000111112        override suspend fun fetchLocalIdentity(): LocalChirpIdentity =113            buildLocalIdentity(context, masterKey)114115        override suspend fun completePairing(paired: PairedDevice) {116            // A paired-device registry lands with sync persistence; the flow's117            // success is reflected through the PAIRED progress phase for now.118        }119120        override suspend fun confirmSAS(sas: String): Boolean {121            val gate = CompletableDeferred<Boolean>()122            sasGate = gate123            _sasCode.value = sas124            return gate.await()125        }126127        override suspend fun cacheLastKnownIp(pubkeyHex: String, ip: String) {}128        override suspend fun getLocalSubnet(): String? = null129        override suspend fun openPairingTransport(endpoint: PairingEndpoint): PairingTransport =130            throw UnsupportedOperationException("pairing transport not wired until sync persistence")131        override suspend fun openPairingServer(): PairingServer =132            throw UnsupportedOperationException("pairing server not wired until sync persistence")133        override suspend fun openAudio(): AudioIO = openAndroidAudioIO()134        override fun onProgress(progress: PairingProgress) {135            _progress.value = progress136        }137    }138}