1package com.peachpasswords.ui.sync23import android.content.Context4import androidx.lifecycle.ViewModel5import androidx.lifecycle.viewModelScope6import com.peachpasswords.sync.BackgroundSyncCoordinator7import com.peachpasswords.sync.BackgroundSyncPreference8import com.peachpasswords.sync.SyncVaultAdapter9import com.peachpasswords.sync.PairedDevice10import com.peachpasswords.sync.PairedDeviceStore11import com.peachpasswords.sync.PendingVouchedDevice12import com.peachpasswords.sync.PendingVouchedDeviceStore13import com.peachpasswords.sync.PeachSyncService14import com.peachpasswords.sync.RelayDecision15import com.peachpasswords.sync.RelaySettingsStore16import com.peachpasswords.sync.SyncMode17import com.peachpasswords.sync.SyncAlertStore18import com.peachpasswords.sync.SyncOutcomeReason19import com.peachpasswords.sync.SyncOutcomeStore20import com.peachpasswords.sync.SyncOutcomeSummary21import com.peachpasswords.sync.VaultSyncAdapter22import com.peachpasswords.sync.loadOrCreateLocalIdentity23import com.peachpasswords.vault.VaultRepository24import dagger.hilt.android.lifecycle.HiltViewModel25import dagger.hilt.android.qualifiers.ApplicationContext26import kotlinx.coroutines.flow.MutableStateFlow27import kotlinx.coroutines.flow.SharingStarted28import kotlinx.coroutines.flow.StateFlow29import kotlinx.coroutines.flow.asStateFlow30import kotlinx.coroutines.flow.combine31import kotlinx.coroutines.flow.stateIn32import kotlinx.coroutines.delay33import kotlinx.coroutines.Job34import kotlinx.coroutines.launch35import javax.inject.Inject36373839404142434445464748@HiltViewModel49class SyncViewModel @Inject constructor(50 @ApplicationContext private val context: Context,51 private val vault: VaultRepository,52 private val deviceStore: PairedDeviceStore,53 private val pendingVouchedStore: PendingVouchedDeviceStore,54 private val syncAlertStore: SyncAlertStore,55 private val backgroundSync: BackgroundSyncPreference,56 private val relaySettings: RelaySettingsStore,57 private val syncOutcomes: SyncOutcomeStore,58) : ViewModel() {5960 61 val status: StateFlow<SyncOutcomeSummary> =62 combine(syncOutcomes.summary, vault.isUnlocked) { summary, unlocked ->63 if (unlocked && vault.syncVaultId() == null) SyncOutcomeSummary() else summary64 }.stateIn(65 viewModelScope,66 SharingStarted.WhileSubscribed(5_000),67 if (vault.isUnlocked.value && vault.syncVaultId() == null) {68 SyncOutcomeSummary()69 } else {70 syncOutcomes.summary.value71 },72 )7374 757677787980 private val backgroundSyncCoordinator = BackgroundSyncCoordinator(81 start = { PeachSyncService.start(context) },82 stop = { PeachSyncService.stop(context) },83 isUnlocked = vault.isUnlocked,84 preferenceEnabled = backgroundSync.enabled,85 syncVaultId = vault::syncVaultId,86 )8788 init {89 90 91 92 93 backgroundSyncCoordinator.observe(viewModelScope)94 }9596 fun setBackgroundSyncEnabled(enabled: Boolean) {97 if (isDecoySession()) return98 backgroundSync.setEnabled(enabled)99 backgroundSyncCoordinator.setEnabled(enabled)100 }101 val backgroundSyncEnabled: StateFlow<Boolean> = backgroundSync.enabled102103 104 private val _privateRelayUrl = MutableStateFlow(relaySettings.privateRelayUrl())105 val privateRelayUrl: StateFlow<String> = _privateRelayUrl.asStateFlow()106107108 private val _syncMode = MutableStateFlow(relaySettings.syncMode())109 val syncMode: StateFlow<SyncMode> = _syncMode.asStateFlow()110111 fun setSyncMode(mode: SyncMode) {112 if (isDecoySession()) return113 relaySettings.setSyncMode(mode)114 _syncMode.value = relaySettings.syncMode()115 _privateRelayUrl.value = relaySettings.privateRelayUrl()116 }117118 119 fun setRelayUrl(input: String): Boolean {120 if (isDecoySession()) return false121 return runCatching {122 relaySettings.setRelayUrl(input)123 _privateRelayUrl.value = relaySettings.privateRelayUrl()124 _syncMode.value = relaySettings.syncMode()125 true126 }.getOrDefault(false)127 }128129130 131 val pairedDevices: StateFlow<List<PairedDevice>> =132 combine(deviceStore.observeAll(), vault.isUnlocked) { devices, unlocked ->133 if (unlocked && vault.syncVaultId() == null) emptyList() else devices134 }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())135136 val pendingVouched: StateFlow<List<PendingVouchedDevice>> =137 combine(pendingVouchedStore.observeAll(), vault.isUnlocked) { pending, unlocked ->138 if (unlocked && vault.syncVaultId() == null) emptyList() else pending139 }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())140141 142143144145146 fun unpairDevice(id: String) = viewModelScope.launch {147 if (isDecoySession()) return@launch148 deviceStore.revoke(id, loadOrCreateLocalIdentity(context).deviceId)149 PeachSyncService.start(context)150 }151152 fun renameDevice(id: String, name: String) = viewModelScope.launch {153 if (isDecoySession()) return@launch154 deviceStore.rename(id, name)155 }156157 fun confirmVouchedDevice(id: String) = viewModelScope.launch {158 if (isDecoySession()) return@launch159 val pending = pendingVouchedStore.get(id) ?: return@launch160 161 162 if (deviceStore.isRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {163 pendingVouchedStore.removeBatch(setOf(id))164 return@launch165 }166 167 168 169 if (deviceStore.get(pending.deviceId) != null) {170 pendingVouchedStore.removeBatch(setOf(id))171 return@launch172 }173 174 175 176 if (!pendingVouchedStore.removeBatch(setOf(id))) return@launch177 if (deviceStore.isRevoked(pending.deviceId, pending.longTermPublicKeyHex)) return@launch178 deviceStore.upsert(179 PairedDevice(180 deviceId = pending.deviceId,181 deviceName = pending.deviceName,182 deviceType = pending.deviceType,183 longTermPublicKeyHex = pending.longTermPublicKeyHex,184 signingPublicKeyHex = pending.signingPublicKeyHex,185 trustSource = "vouched",186 wsPort = pending.wsPort,187 pairedAt = pending.pairedAt,188 ),189 )190 }191192 fun rejectVouchedDevice(id: String) = viewModelScope.launch {193 if (isDecoySession()) return@launch194 pendingVouchedStore.remove(id)195 }196197198 199 suspend fun rotateSyncIdentity(): Boolean {200 if (isDecoySession()) return false201 val ok = vault.rotateSyncIdentity()202 if (ok) {203 deviceStore.clear()204 syncOutcomes.reset()205 }206 return ok207 }208209 210 fun buildAdapter(): SyncVaultAdapter? {211 if (!vault.isUnlocked.value || isDecoySession()) return null212 val credentials = loadOrCreateLocalIdentity(context)213 return VaultSyncAdapter(214 repo = vault,215 ourDeviceId = credentials.deviceId,216 pairedDevices = deviceStore,217 pendingVouched = pendingVouchedStore,218 syncAlerts = syncAlertStore,219 localCredentials = credentials,220 )221 }222223 224225226227228229230231232 fun syncNow() {233 234 235 if (isDecoySession()) return236237 val decision = relaySettings.relayInForce()238 if (decision is RelayDecision.Refuse) {239 syncOutcomes.report(SyncOutcomeSummary(reason = decision.reason))240 return241 }242 if (!vault.isUnlocked.value) {243 syncOutcomes.report(SyncOutcomeSummary(reason = SyncOutcomeReason.VAULT_LOCKED))244 return245 }246247 248 249 250 251 val devices = deviceStore.getAll()252 if (devices.isEmpty()) {253 syncOutcomes.report(SyncOutcomeSummary(reason = SyncOutcomeReason.NO_PAIRED_DEVICES))254 return255 }256 257 258 259 260 if (devices.none { it.rendezvousSecretHex != null }) {261 syncOutcomes.report(262 SyncOutcomeSummary(263 reason = SyncOutcomeReason.NO_ELIGIBLE_HOST,264 detail = devices.joinToString("; ") {265 "${it.deviceName ?: it.deviceId} [type=${it.deviceType ?: "unset"}, trust=${it.trustSource ?: "unset"}]"266 },267 ),268 )269 return270 }271272 syncOutcomes.begin()273 PeachSyncService.start(context)274 275 276 277 278 279 attemptTimeout?.cancel()280 attemptTimeout = viewModelScope.launch {281 delay(SYNC_ATTEMPT_TIMEOUT_MS)282 if (syncOutcomes.summary.value.syncing) {283 syncOutcomes.report(284 SyncOutcomeSummary(285 reason = SyncOutcomeReason.RELAY_UNREACHABLE,286 detail = "no peer answered within ${SYNC_ATTEMPT_TIMEOUT_MS / 1000}s",287 ),288 )289 }290 }291 }292 private fun isDecoySession(): Boolean =293 vault.isUnlocked.value && vault.syncVaultId() == null294295 296297298299 fun triggerSync() = syncNow()300301 private var attemptTimeout: Job? = null302303 private companion object {304 const val SYNC_ATTEMPT_TIMEOUT_MS = 20_000L305 }306}