SyncViewModel.kt

4.4 KB · raw

1package com.peachpasswords.ui.sync23import android.content.Context4import androidx.lifecycle.ViewModel5import androidx.lifecycle.viewModelScope6import com.peachpasswords.sync.ChirpSyncVaultAdapter7import com.peachpasswords.sync.SyncEndpoint8import com.peachpasswords.sync.SyncOutcomeStatus9import com.peachpasswords.sync.SyncStatus10import com.peachpasswords.sync.VaultSyncAdapter11import com.peachpasswords.sync.deriveSyncIdentityKeypair12import com.peachpasswords.sync.getOrCreateDeviceId13import com.peachpasswords.sync.openChirpSyncSession14import com.peachpasswords.sync.runChirpSyncInitiator15import com.peachpasswords.vault.VaultCrypto16import com.peachpasswords.vault.VaultRepository17import dagger.hilt.android.lifecycle.HiltViewModel18import dagger.hilt.android.qualifiers.ApplicationContext19import kotlinx.coroutines.flow.MutableStateFlow20import kotlinx.coroutines.flow.StateFlow21import kotlinx.coroutines.flow.asStateFlow22import kotlinx.coroutines.launch23import javax.inject.Inject2425/**26 * Drives a Chirp Sync round and surfaces its status to the Sync settings card.27 *28 * Trigger conditions (browser `sync-trigger.ts` parity):29 *   1. Vault mutation — a local add/update/delete should schedule a sync.30 *   2. App foreground — reconnect to nearby peers on resume.31 *   3. Manual — the "Sync now" control on the Sync card.32 *   4. mDNS peer discovery — a paired device appears on the LAN.33 *34 * Discovery, the WebSocket server role, and the paired-device store land with35 * the pairing UI (Phase 10); [syncWith] already performs a real initiator round36 * against a known endpoint so those wirings have a finished target to call.37 */38@HiltViewModel39class SyncViewModel @Inject constructor(40    @ApplicationContext private val context: Context,41    private val vault: VaultRepository,42) : ViewModel() {4344    private val _status = MutableStateFlow<SyncStatus>(SyncStatus.Idle)45    val status: StateFlow<SyncStatus> = _status.asStateFlow()4647    /** Adapter over the live vault; null while the vault is locked. */48    fun buildAdapter(): ChirpSyncVaultAdapter? {49        if (!vault.isUnlocked.value) return null50        return VaultSyncAdapter(vault, getOrCreateDeviceId(context))51    }5253    /**54     * Manual / discovery trigger. With no paired-device store yet, this reports55     * Offline when there is nothing to dial; pairing (Phase 10) supplies peers.56     */57    fun triggerSync() {58        if (!vault.isUnlocked.value) {59            _status.value = SyncStatus.Error("vault_locked")60            return61        }62        // No paired-device registry on Android yet — nothing reachable to dial.63        _status.value = SyncStatus.Offline64    }6566    /** Run one initiator round against a known peer endpoint. */67    fun syncWith(endpoint: SyncEndpoint, expectedRemotePubkeyHex: String) {68        val master = vault.syncMasterKey() ?: run {69            _status.value = SyncStatus.Error("vault_locked")70            return71        }72        val adapter = buildAdapter() ?: run {73            _status.value = SyncStatus.Error("vault_locked")74            master.fill(0)75            return76        }77        _status.value = SyncStatus.Syncing78        viewModelScope.launch {79            try {80                val deviceId = getOrCreateDeviceId(context)81                val identity = deriveSyncIdentityKeypair(master, deviceId)82                val session = openChirpSyncSession(83                    endpoint = endpoint,84                    ourLongTermPrivateKey = identity.secretKey,85                    ourLongTermPublicKey = identity.publicKey,86                    expectedRemotePubkeyHex = expectedRemotePubkeyHex,87                )88                val outcome = try {89                    runChirpSyncInitiator(session, adapter)90                } finally {91                    session.close()92                }93                _status.value = when (outcome.status) {94                    SyncOutcomeStatus.COMPLETED -> SyncStatus.LastSynced(System.currentTimeMillis())95                    SyncOutcomeStatus.VAULT_MISMATCH -> SyncStatus.Error("vault_id_mismatch")96                    SyncOutcomeStatus.TIMEOUT -> SyncStatus.Error("timeout")97                    SyncOutcomeStatus.ERRORED -> SyncStatus.Error(outcome.error ?: "sync_failed")98                }99            } catch (e: Exception) {100                _status.value = SyncStatus.Error(e.message ?: "sync_failed")101            } finally {102                VaultCrypto.zero(master)103            }104        }105    }106}