CodexViewModel.kt

12.3 KB · raw

1package com.peachpasswords.ui.codex23import android.content.Context4import android.net.Uri5import androidx.core.content.FileProvider6import androidx.lifecycle.ViewModel7import androidx.lifecycle.viewModelScope8import androidx.camera.core.ImageProxy9import com.peachpasswords.codex.ChunkEnvelope10import com.peachpasswords.codex.CodexAztecFrame11import com.peachpasswords.codex.CodexCodec12import com.peachpasswords.codex.CodexErrorCode13import com.peachpasswords.codex.CodexException14import com.peachpasswords.codex.CodexGenerator15import com.peachpasswords.codex.CodexManifest16import com.peachpasswords.codex.CodexPayload17import com.peachpasswords.codex.CodexRestore18import com.peachpasswords.codex.CodexStep19import com.peachpasswords.license.LicenseRepository20import com.peachpasswords.vault.UnlockResult21import com.peachpasswords.vault.VaultRepository22import dagger.hilt.android.lifecycle.HiltViewModel23import dagger.hilt.android.qualifiers.ApplicationContext24import kotlinx.coroutines.Dispatchers25import kotlinx.coroutines.flow.MutableStateFlow26import kotlinx.coroutines.flow.StateFlow27import kotlinx.coroutines.flow.asStateFlow28import kotlinx.coroutines.launch29import kotlinx.coroutines.withContext30import java.io.File31import javax.inject.Inject3233sealed interface GenerateState {34    data object Idle : GenerateState35    data class Running(val step: CodexStep, val current: Int, val total: Int) : GenerateState36    data class Done(val manifest: CodexManifest, val pdf: ByteArray) : GenerateState37    data class Error(val message: String) : GenerateState38}3940sealed interface RestoreState {41    data object Idle : RestoreState42    data class Scanning(val page: Int, val pages: Int) : RestoreState43    data class Shortfall(val found: Int, val missing: Int, val ready: Int, val total: Int) : RestoreState44    data class Decoded(val payload: CodexPayload, val codesFound: Int) : RestoreState45    data object Restoring : RestoreState46    data object Restored : RestoreState47    data class Error(val message: String) : RestoreState48}4950/**51 * D10 camera-scan phase. `Choosing` is the restore landing (two option cards);52 * `Scanning` runs while the camera analyzes frames; `Timeout` shows the53 * no-detection overlay after 10s. The decode handoff reuses [RestoreState].54 */55sealed interface CameraScanState {56    data object Choosing : CameraScanState57    data class Scanning(val codesFound: Int) : CameraScanState58    data class Timeout(val codesFound: Int) : CameraScanState59}6061@HiltViewModel62class CodexViewModel @Inject constructor(63    @ApplicationContext private val context: Context,64    private val vault: VaultRepository,65    private val license: LicenseRepository,66) : ViewModel() {6768    private val _generate = MutableStateFlow<GenerateState>(GenerateState.Idle)69    val generate: StateFlow<GenerateState> = _generate.asStateFlow()7071    /** D9 gate: Codex generation is allowed only once recovery words are set up. */72    val recoveryWordsSet: Boolean get() = vault.isRecoveryWordsSet()7374    /** Browser parity: Codex generation is Pro-only, while restore remains free. */75    val isPro: Boolean get() = license.isProActive()7677    private val recoveryWords: List<String> by lazy {78        vault.syncMasterKey()?.let { k ->79            try { com.peachpasswords.vault.rootKeyToWords(k) }80            finally { com.peachpasswords.vault.VaultCrypto.zero(k) }81        } ?: emptyList()82    }8384    /** True when the three challenge words (positions 3, 7, 11) match the vault's recovery words. */85    fun gateMatches(w3: String, w7: String, w11: String): Boolean {86        val ws = recoveryWords87        if (ws.size < 11) return false88        return w3.trim().lowercase() == ws[2] &&89            w7.trim().lowercase() == ws[6] &&90            w11.trim().lowercase() == ws[10]91    }9293    private val _restore = MutableStateFlow<RestoreState>(RestoreState.Idle)94    val restore: StateFlow<RestoreState> = _restore.asStateFlow()9596    fun startGenerate(now: Long) {97        if (!isPro) {98            _generate.value = GenerateState.Error("Codex generation is a Pro feature.")99            return100        }101        _generate.value = GenerateState.Running(CodexStep.COMPRESS, 0, 1)102        viewModelScope.launch {103            try {104                val (pdf, manifest) = withContext(Dispatchers.Default) {105                    CodexGenerator.generate(vault, now) { step, cur, total ->106                        _generate.value = GenerateState.Running(step, cur, total)107                    }108                }109                _generate.value = GenerateState.Done(manifest, pdf)110            } catch (e: CodexException) {111                _generate.value = GenerateState.Error(e.message ?: e.code.name)112            } catch (e: Exception) {113                _generate.value = GenerateState.Error(e.message ?: "generation_failed")114            }115        }116    }117118    fun writePdf(uri: Uri): Boolean = try {119        val pdf = (_generate.value as? GenerateState.Done)?.pdf ?: return false120        context.contentResolver.openOutputStream(uri)?.use { it.write(pdf) } != null121    } catch (_: Exception) {122        false123    }124125    fun sharePdfUri(fileName: String = codexPdfFileName()): Uri? = try {126        val pdf = (_generate.value as? GenerateState.Done)?.pdf ?: return null127        val dir = File(context.cacheDir, "codex").apply { mkdirs() }128        val file = File(dir, fileName)129        file.outputStream().use { it.write(pdf) }130        FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)131    } catch (_: Exception) {132        null133    }134135    fun scan(uri: Uri) {136        _restore.value = RestoreState.Scanning(0, 0)137        viewModelScope.launch {138            try {139                val payload = withContext(Dispatchers.Default) {140                    val result = CodexRestore.decodeFromUri(context, uri) { page, pages ->141                        _restore.value = RestoreState.Scanning(page, pages)142                    }143                    if (result.envelopes.isEmpty()) {144                        throw CodexException(145                            CodexErrorCode.INSUFFICIENT_CHUNKS,146                            "No Aztec codes could be read from this file",147                        )148                    }149                    try {150                        CodexRestore.reconstructPayload(result.envelopes) to result.envelopes.size151                    } catch (e: CodexException) {152                        val shortfall = codexRestoreShortfall(result.envelopes)153                        if (e.code == CodexErrorCode.INSUFFICIENT_CHUNKS && shortfall != null) {154                            _restore.value = RestoreState.Shortfall(155                                found = shortfall.found,156                                missing = shortfall.missing,157                                ready = shortfall.ready,158                                total = shortfall.total,159                            )160                            return@withContext null161                        }162                        throw e163                    }164                }165                if (payload != null) {166                    _restore.value = RestoreState.Decoded(payload.first, payload.second)167                }168            } catch (e: CodexException) {169                _restore.value = RestoreState.Error(codexRestoreErrorMessage(e.code, e.message))170            } catch (e: Exception) {171                _restore.value = RestoreState.Error(e.message ?: "restore_failed")172            }173        }174    }175176    fun confirmRestore(password: String, onDone: () -> Unit) {177        val payload = (_restore.value as? RestoreState.Decoded)?.payload ?: return178        _restore.value = RestoreState.Restoring179        viewModelScope.launch {180            when (val r = vault.restoreFromCodex(payload.vaultBlob, password)) {181                is UnlockResult.Success -> { _restore.value = RestoreState.Restored; onDone() }182                is UnlockResult.WrongPassword -> _restore.value = RestoreState.Error(183                    codexRestoreErrorMessage(CodexErrorCode.RESTORE_FAILED, "WRONG_PASSPHRASE"),184                )185                is UnlockResult.Error -> _restore.value = RestoreState.Error(186                    codexRestoreErrorMessage(CodexErrorCode.RESTORE_FAILED, r.reason),187                )188            }189        }190    }191192    fun resetRestore() { _restore.value = RestoreState.Idle }193194    // ---- D10 camera scan --------------------------------------------------195    private val _camera = MutableStateFlow<CameraScanState>(CameraScanState.Choosing)196    val camera: StateFlow<CameraScanState> = _camera.asStateFlow()197198    // Envelopes collected this session, deduped by stripe:index (mirrors decodeFromUri).199    private val cameraEnvelopes = LinkedHashMap<String, ChunkEnvelope>()200201    /** Show the two-card choose surface (default restore landing). */202    fun chooseRestore() {203        cameraEnvelopes.clear()204        _camera.value = CameraScanState.Choosing205        _restore.value = RestoreState.Idle206    }207208    /** Begin (or restart after a timeout) live camera scanning. */209    fun startCameraScan() {210        cameraEnvelopes.clear()211        _camera.value = CameraScanState.Scanning(0)212        _restore.value = RestoreState.Idle213    }214215    /** UI reports 10s elapsed with no successful reconstruction. */216    fun cameraTimedOut() {217        val s = _camera.value218        if (s is CameraScanState.Scanning) _camera.value = CameraScanState.Timeout(s.codesFound)219    }220221    /**222     * Analyze one camera frame: decode one Aztec, accumulate, and on a successful223     * reconstruction transition to [RestoreState.Decoded] — the same entry point224     * the PDF path uses. Returns true once decoded (caller stops analysis). The225     * analyzer owns closing the [ImageProxy]; this does not close it.226     */227    fun onCameraFrame(image: ImageProxy): Boolean {228        if (_camera.value !is CameraScanState.Scanning) return _restore.value is RestoreState.Decoded229        val text = CodexAztecFrame.decode(image) ?: return false230        val env = CodexRestore.parseEnvelope(text) ?: return false231        cameraEnvelopes.putIfAbsent("${env.s}:${env.i}", env)232        _camera.value = CameraScanState.Scanning(cameraEnvelopes.size)233        return try {234            val payload = CodexRestore.reconstructPayload(cameraEnvelopes.values.toList())235            _restore.value = RestoreState.Decoded(payload, cameraEnvelopes.size)236            true237        } catch (_: Exception) {238            false239        }240    }241}242243internal data class CodexShortfall(val found: Int, val missing: Int, val ready: Int, val total: Int)244245internal fun codexRestoreShortfall(envelopes: List<ChunkEnvelope>): CodexShortfall? {246    val good = envelopes247        .filter { CodexCodec.verifyChunkIntegrity(it) }248        .distinctBy { "${it.s}:${it.i}" }249    if (good.isEmpty()) return null250    val stripeCount = good.maxOf { it.capS.coerceAtLeast(1) }251    val byStripe = good.groupBy { it.s }252    var ready = 0253    var missing = 0254    for (stripe in 0 until stripeCount) {255        val stripeEnvelopes = byStripe[stripe].orEmpty()256        if (stripeEnvelopes.isEmpty()) continue257        val total = stripeEnvelopes.first().t258        val (dataShards, _) = com.peachpasswords.codex.deriveShardCounts(total)259        val found = stripeEnvelopes.count { it.i in 0 until total }260        if (found >= dataShards) ready++ else missing += dataShards - found261    }262    return CodexShortfall(found = good.size, missing = missing, ready = ready, total = stripeCount)263}264265internal fun codexRestoreErrorMessage(code: CodexErrorCode, raw: String?): String {266    val message = raw.orEmpty()267    return when {268        message.contains("WRONG_PASSPHRASE", ignoreCase = true) ||269            message.contains("wrong", ignoreCase = true) ->270            "wrong master password. try again."271        message.contains("INVALID_VAULT_BLOB", ignoreCase = true) ||272            code == CodexErrorCode.INVALID_VAULT_BLOB ->273            "the reconstructed vault is unreadable. please re-scan the Codex."274        message.contains("FINGERPRINT_MISMATCH", ignoreCase = true) ||275            code == CodexErrorCode.RECONSTRUCTION_FINGERPRINT_MISMATCH ->276            "vault integrity check failed. please re-scan the Codex."277        code == CodexErrorCode.INSUFFICIENT_CHUNKS && message.contains("No Aztec", ignoreCase = true) ->278            "no Codex codes found in this PDF. make sure you're selecting a Peach Codex PDF, not a different document."279        message.isNotBlank() -> message280        else -> "restoration failed. please try again."281    }282}