ChirpPairViewModel.kt

6.8 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.PairedDeviceStore18import com.peachpasswords.sync.SocketFrameIO19import com.peachpasswords.sync.buildLocalIdentity20import com.peachpasswords.sync.openAndroidAudioIO21import com.peachpasswords.sync.runChirpPairing22import com.peachpasswords.vault.VaultCrypto23import com.peachpasswords.vault.VaultRepository24import dagger.hilt.android.lifecycle.HiltViewModel25import dagger.hilt.android.qualifiers.ApplicationContext26import kotlinx.coroutines.CompletableDeferred27import kotlinx.coroutines.Dispatchers28import kotlinx.coroutines.delay29import kotlinx.coroutines.flow.MutableStateFlow30import kotlinx.coroutines.flow.StateFlow31import kotlinx.coroutines.flow.asStateFlow32import kotlinx.coroutines.launch33import kotlinx.coroutines.withContext34import java.net.ServerSocket35import java.net.Socket36import javax.inject.Inject3738/** TCP connect timeout for the initiator's pairing socket. */39private const val CONNECT_TIMEOUT_MS = 5_0004041/**42 * Drives the Chirp pairing flow and surfaces its phase + SAS code to43 * [ChirpPairScreen]. The real audio bridge ([openAndroidAudioIO]) lands in44 * Phase 12; until then [startPairing] runs the genuine orchestrator and45 * surfaces the audio-unavailable phase honestly, while [runDemo] (DEBUG only)46 * steps the visuals through all three acts so the animation and SAS screen can47 * be verified on a single device.48 */49@HiltViewModel50class ChirpPairViewModel @Inject constructor(51    @ApplicationContext private val context: Context,52    private val vault: VaultRepository,53    private val deviceStore: PairedDeviceStore,54) : ViewModel() {5556    private val _progress = MutableStateFlow(PairingProgress(PairingPhase.IDLE))57    val progress: StateFlow<PairingProgress> = _progress.asStateFlow()5859    private val _sasCode = MutableStateFlow<String?>(null)60    val sasCode: StateFlow<String?> = _sasCode.asStateFlow()6162    val isDebug: Boolean = BuildConfig.DEBUG6364    private var sasGate: CompletableDeferred<Boolean>? = null6566    fun startPairing() {67        val master = vault.syncMasterKey() ?: run {68            _progress.value = PairingProgress(PairingPhase.HANDSHAKE_FAILED, errorMessage = "vault_locked")69            return70        }71        _progress.value = PairingProgress(PairingPhase.LISTENING)72        viewModelScope.launch {73            try {74                runChirpPairing(deps(master), role = PairingRole.INITIATOR)75            } catch (e: Exception) {76                if (_progress.value.phase.let { it != PairingPhase.TIMEOUT && it != PairingPhase.MIC_DENIED }) {77                    _progress.value = PairingProgress(78                        PairingPhase.HANDSHAKE_FAILED,79                        errorMessage = e.message ?: "pairing_failed",80                    )81                }82            } finally {83                VaultCrypto.zero(master)84            }85        }86    }8788    fun confirmSas(accepted: Boolean) {89        sasGate?.complete(accepted)90        _sasCode.value = null91    }9293    fun reset() {94        sasGate?.complete(false)95        sasGate = null96        _sasCode.value = null97        _progress.value = PairingProgress(PairingPhase.IDLE)98    }99100    /** DEBUG: walk the three acts so the screen can be exercised without a peer. */101    fun runDemo() {102        if (!isDebug) return103        viewModelScope.launch {104            _progress.value = PairingProgress(PairingPhase.IDLE)105            delay(700)106            _progress.value = PairingProgress(PairingPhase.LISTENING)107            delay(1800)108            _progress.value = PairingProgress(PairingPhase.HANDSHAKE, peerDeviceName = "June's Laptop")109            _sasCode.value = "418 207"110        }111    }112113    /** DEBUG: complete the demo into the paired act after SAS confirmation. */114    fun demoComplete() {115        _sasCode.value = null116        _progress.value = PairingProgress(PairingPhase.PAIRED, peerDeviceName = "June's Laptop")117    }118119    private fun deps(masterKey: ByteArray): ChirpPairingDeps = object : ChirpPairingDeps {120        override val chirpTimeoutMs: Long = 15_000121122        override suspend fun fetchLocalIdentity(): LocalChirpIdentity =123            buildLocalIdentity(context, masterKey)124125        override suspend fun completePairing(paired: PairedDevice) {126            // Persist the newly-trusted peer so Sync can dial it later (C7 wiring).127            deviceStore.upsert(paired)128        }129130        override suspend fun confirmSAS(sas: String): Boolean {131            val gate = CompletableDeferred<Boolean>()132            sasGate = gate133            _sasCode.value = sas134            return gate.await()135        }136137        override suspend fun cacheLastKnownIp(pubkeyHex: String, ip: String) {138            deviceStore.getAll().firstOrNull { it.longTermPublicKeyHex == pubkeyHex }?.let {139                deviceStore.updateLastSeen(it.deviceId, ip)140            }141        }142        override suspend fun getLocalSubnet(): String? = null143144        // Initiator side: dial the peer and frame the TCP socket as a PairingTransport.145        override suspend fun openPairingTransport(endpoint: PairingEndpoint): PairingTransport =146            withContext(Dispatchers.IO) {147                val socket = Socket()148                socket.connect(java.net.InetSocketAddress(endpoint.ip, endpoint.port), CONNECT_TIMEOUT_MS)149                SocketFrameIO(socket.getInputStream(), socket.getOutputStream(), onClose = {150                    withContext(Dispatchers.IO) { runCatching { socket.close() } }151                })152            }153154        // Responder side: bind an ephemeral port, accept one peer, frame it.155        override suspend fun openPairingServer(): PairingServer =156            withContext(Dispatchers.IO) {157                val server = ServerSocket(0)158                val socket = server.accept()159                val peerIp = socket.inetAddress?.hostAddress ?: ""160                PairingServer(161                    transport = SocketFrameIO(socket.getInputStream(), socket.getOutputStream(), onClose = {162                        withContext(Dispatchers.IO) { runCatching { socket.close() }; runCatching { server.close() } }163                    }),164                    peerIp = peerIp,165                )166            }167        override suspend fun openAudio(): AudioIO = openAndroidAudioIO()168        override fun onProgress(progress: PairingProgress) {169            _progress.value = progress170        }171    }172}