CodexViewModel.kt

13.2 KB · raw

1package com.peachpasswords.ui.codex23import android.content.Context4import android.net.Uri5import androidx.core.content.FileProvider6import android.util.Log7import com.peachpasswords.BuildConfig8import androidx.lifecycle.ViewModel9import androidx.lifecycle.viewModelScope10import androidx.camera.core.ImageProxy11import com.peachpasswords.codex.ChunkEnvelope12import com.peachpasswords.codex.CodexAztecFrame13import com.peachpasswords.codex.CodexCodec14import com.peachpasswords.codex.CodexErrorCode15import com.peachpasswords.codex.CodexException16import com.peachpasswords.codex.CodexGenerator17import com.peachpasswords.codex.CodexManifest18import com.peachpasswords.codex.CodexPayload19import com.peachpasswords.codex.CodexRestore20import com.peachpasswords.codex.CodexStep21import com.peachpasswords.license.LicenseRepository22import com.peachpasswords.vault.UnlockResult23import com.peachpasswords.vault.VaultRepository24import dagger.hilt.android.lifecycle.HiltViewModel25import dagger.hilt.android.qualifiers.ApplicationContext26import kotlinx.coroutines.Dispatchers27import kotlinx.coroutines.flow.MutableStateFlow28import kotlinx.coroutines.flow.StateFlow29import kotlinx.coroutines.flow.asStateFlow30import kotlinx.coroutines.launch31import kotlinx.coroutines.withContext32import java.io.File33import javax.inject.Inject3435sealed interface GenerateState {36    data object Idle : GenerateState37    data class Running(val step: CodexStep, val current: Int, val total: Int) : GenerateState38    data class Done(val manifest: CodexManifest, val pdf: ByteArray) : GenerateState39    data class Error(val message: String) : GenerateState40}4142sealed interface RestoreState {43    data object Idle : RestoreState44    data class Scanning(val page: Int, val pages: Int) : RestoreState45    data class Shortfall(val found: Int, val missing: Int, val ready: Int, val total: Int) : RestoreState46    data class Decoded(val payload: CodexPayload, val codesFound: Int) : RestoreState47    data object Restoring : RestoreState48    data object Restored : RestoreState49    data class Error(val message: String) : RestoreState50}5152/**53 * D10 camera-scan phase. `Choosing` is the restore landing (two option cards);54 * `Scanning` runs while the camera analyzes frames; `Timeout` shows the55 * no-detection overlay after 10s. The decode handoff reuses [RestoreState].56 */57sealed interface CameraScanState {58    data object Choosing : CameraScanState59    data class Scanning(val codesFound: Int) : CameraScanState60    data class Timeout(val codesFound: Int) : CameraScanState61}6263@HiltViewModel64class CodexViewModel @Inject constructor(65    @ApplicationContext private val context: Context,66    private val vault: VaultRepository,67    private val license: LicenseRepository,68) : ViewModel() {6970    private val _generate = MutableStateFlow<GenerateState>(GenerateState.Idle)71    val generate: StateFlow<GenerateState> = _generate.asStateFlow()7273    /** D9 gate: Codex generation is allowed only once recovery words are set up. */74    val recoveryWordsSet: Boolean get() = vault.isRecoveryWordsSet()7576    /** Browser parity: Codex generation is Pro-only, while restore remains free. */77    val isPro: Boolean get() = license.isProActive()7879    /** See VaultRepository.expectTransientBackground — call before launching a SAF picker/save dialog. */80    fun expectTransientBackground() = vault.expectTransientBackground()8182    private val recoveryWords: List<String> by lazy {83        vault.sessionRootKey()?.let { k ->84            try { com.peachpasswords.vault.rootKeyToWords(k) }85            finally { com.peachpasswords.vault.VaultCrypto.zero(k) }86        } ?: emptyList()87    }8889    /** True when the three challenge words (positions 3, 7, 11) match the vault's recovery words. */90    fun gateMatches(w3: String, w7: String, w11: String): Boolean {91        val ws = recoveryWords92        if (ws.size < 11) return false93        return w3.trim().lowercase() == ws[2] &&94            w7.trim().lowercase() == ws[6] &&95            w11.trim().lowercase() == ws[10]96    }9798    private val _restore = MutableStateFlow<RestoreState>(RestoreState.Idle)99    val restore: StateFlow<RestoreState> = _restore.asStateFlow()100101    fun startGenerate(now: Long) {102        if (!isPro) {103            _generate.value = GenerateState.Error("Codex generation is a Pro feature.")104            return105        }106        _generate.value = GenerateState.Running(CodexStep.COMPRESS, 0, 1)107        viewModelScope.launch {108            try {109                val (pdf, manifest) = withContext(Dispatchers.Default) {110                    CodexGenerator.generate(vault, now) { step, cur, total ->111                        _generate.value = GenerateState.Running(step, cur, total)112                    }113                }114                _generate.value = GenerateState.Done(manifest, pdf)115            } catch (e: CodexException) {116                _generate.value = GenerateState.Error(e.message ?: e.code.name)117            } catch (e: Exception) {118                _generate.value = GenerateState.Error(e.message ?: "generation_failed")119            }120        }121    }122123    fun writePdf(uri: Uri): Boolean = try {124        val pdf = (_generate.value as? GenerateState.Done)?.pdf ?: return false125        context.contentResolver.openOutputStream(uri)?.use { it.write(pdf) } != null126    } catch (_: Exception) {127        false128    }129130    fun sharePdfUri(fileName: String = codexPdfFileName()): Uri? = try {131        val pdf = (_generate.value as? GenerateState.Done)?.pdf ?: return null132        val dir = File(context.cacheDir, "codex").apply { mkdirs() }133        val file = File(dir, fileName)134        file.outputStream().use { it.write(pdf) }135        FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)136    } catch (_: Exception) {137        null138    }139140    fun scan(uri: Uri) {141        _restore.value = RestoreState.Scanning(0, 0)142        viewModelScope.launch {143            try {144                val payload = withContext(Dispatchers.Default) {145                    val result = CodexRestore.decodeFromUri(context, uri) { page, pages ->146                        _restore.value = RestoreState.Scanning(page, pages)147                    }148                    if (result.envelopes.isEmpty()) {149                        throw CodexException(150                            CodexErrorCode.INSUFFICIENT_CHUNKS,151                            "No Aztec codes could be read from this file",152                        )153                    }154                    try {155                        CodexRestore.reconstructPayload(result.envelopes) to result.envelopes.size156                    } catch (e: CodexException) {157                        val shortfall = codexRestoreShortfall(result.envelopes)158                        if (e.code == CodexErrorCode.INSUFFICIENT_CHUNKS && shortfall != null) {159                            _restore.value = RestoreState.Shortfall(160                                found = shortfall.found,161                                missing = shortfall.missing,162                                ready = shortfall.ready,163                                total = shortfall.total,164                            )165                            return@withContext null166                        }167                        throw e168                    }169                }170                if (payload != null) {171                    _restore.value = RestoreState.Decoded(payload.first, payload.second)172                }173            } catch (e: CodexException) {174                _restore.value = RestoreState.Error(codexRestoreErrorMessage(e.code, e.message))175            } catch (e: Exception) {176                _restore.value = RestoreState.Error(e.message ?: "restore_failed")177            }178        }179    }180181    fun confirmRestore(password: String, onDone: () -> Unit) {182        val payload = (_restore.value as? RestoreState.Decoded)?.payload ?: return183        _restore.value = RestoreState.Restoring184        viewModelScope.launch {185            when (val r = vault.restoreFromCodex(payload.vaultBlob, password)) {186                is UnlockResult.Success -> { _restore.value = RestoreState.Restored; onDone() }187                is UnlockResult.WrongPassword -> {188                    // The three outcomes below look nearly identical on screen but189                    // mean completely different things (bad password vs. a slot190                    // shape neither reader understands). Codex screens are191                    // FLAG_SECURE, so a screenshot can't be used to tell them192                    // apart — this line is the only way to see which one happened.193                    if (BuildConfig.DEBUG) Log.w("PeachCodex", "restore rejected: WRONG_PASSPHRASE")194                    _restore.value = RestoreState.Error(195                        codexRestoreErrorMessage(CodexErrorCode.RESTORE_FAILED, "WRONG_PASSPHRASE"),196                    )197                }198                is UnlockResult.Error -> {199                    if (BuildConfig.DEBUG) Log.w("PeachCodex", "restore failed: ${r.reason}")200                    _restore.value = RestoreState.Error(201                        codexRestoreErrorMessage(CodexErrorCode.RESTORE_FAILED, r.reason),202                    )203                }204            }205        }206    }207208    fun resetRestore() { _restore.value = RestoreState.Idle }209210    // ---- D10 camera scan --------------------------------------------------211    private val _camera = MutableStateFlow<CameraScanState>(CameraScanState.Choosing)212    val camera: StateFlow<CameraScanState> = _camera.asStateFlow()213214    // Envelopes collected this session, deduped by stripe:index (mirrors decodeFromUri).215    private val cameraEnvelopes = LinkedHashMap<String, ChunkEnvelope>()216217    /** Show the two-card choose surface (default restore landing). */218    fun chooseRestore() {219        cameraEnvelopes.clear()220        _camera.value = CameraScanState.Choosing221        _restore.value = RestoreState.Idle222    }223224    /** Begin (or restart after a timeout) live camera scanning. */225    fun startCameraScan() {226        cameraEnvelopes.clear()227        _camera.value = CameraScanState.Scanning(0)228        _restore.value = RestoreState.Idle229    }230231    /** UI reports 10s elapsed with no successful reconstruction. */232    fun cameraTimedOut() {233        val s = _camera.value234        if (s is CameraScanState.Scanning) _camera.value = CameraScanState.Timeout(s.codesFound)235    }236237    /**238     * Analyze one camera frame: decode one Aztec, accumulate, and on a successful239     * reconstruction transition to [RestoreState.Decoded] — the same entry point240     * the PDF path uses. Returns true once decoded (caller stops analysis). The241     * analyzer owns closing the [ImageProxy]; this does not close it.242     */243    fun onCameraFrame(image: ImageProxy): Boolean {244        if (_camera.value !is CameraScanState.Scanning) return _restore.value is RestoreState.Decoded245        val text = CodexAztecFrame.decode(image) ?: return false246        val env = CodexRestore.parseEnvelope(text) ?: return false247        cameraEnvelopes.putIfAbsent("${env.s}:${env.i}", env)248        _camera.value = CameraScanState.Scanning(cameraEnvelopes.size)249        return try {250            val payload = CodexRestore.reconstructPayload(cameraEnvelopes.values.toList())251            _restore.value = RestoreState.Decoded(payload, cameraEnvelopes.size)252            true253        } catch (_: Exception) {254            false255        }256    }257}258259internal data class CodexShortfall(val found: Int, val missing: Int, val ready: Int, val total: Int)260261internal fun codexRestoreShortfall(envelopes: List<ChunkEnvelope>): CodexShortfall? {262    val good = envelopes263        .filter { CodexCodec.verifyChunkIntegrity(it) }264        .distinctBy { "${it.s}:${it.i}" }265    if (good.isEmpty()) return null266    val stripeCount = good.maxOf { it.capS.coerceAtLeast(1) }267    val byStripe = good.groupBy { it.s }268    var ready = 0269    var missing = 0270    for (stripe in 0 until stripeCount) {271        val stripeEnvelopes = byStripe[stripe].orEmpty()272        if (stripeEnvelopes.isEmpty()) continue273        val total = stripeEnvelopes.first().t274        val (dataShards, _) = com.peachpasswords.codex.deriveShardCounts(total)275        val found = stripeEnvelopes.count { it.i in 0 until total }276        if (found >= dataShards) ready++ else missing += dataShards - found277    }278    return CodexShortfall(found = good.size, missing = missing, ready = ready, total = stripeCount)279}280281internal fun codexRestoreErrorMessage(code: CodexErrorCode, raw: String?): String {282    val message = raw.orEmpty()283    return when {284        message.contains("WRONG_PASSPHRASE", ignoreCase = true) ||285            message.contains("wrong", ignoreCase = true) ->286            "wrong master password. try again."287        message.contains("INVALID_VAULT_BLOB", ignoreCase = true) ||288            code == CodexErrorCode.INVALID_VAULT_BLOB ->289            "the reconstructed vault is unreadable. please re-scan the Codex."290        message.contains("FINGERPRINT_MISMATCH", ignoreCase = true) ||291            code == CodexErrorCode.RECONSTRUCTION_FINGERPRINT_MISMATCH ->292            "vault integrity check failed. please re-scan the Codex."293        code == CodexErrorCode.INSUFFICIENT_CHUNKS && message.contains("No Aztec", ignoreCase = true) ->294            "no Codex codes found in this PDF. make sure you're selecting a Peach Codex PDF, not a different document."295        message.isNotBlank() -> message296        else -> "restoration failed. please try again."297    }298}