app: suggest recovery images with FirmwareCrawler

Add FirmwareCrawler in app:core to provide an extensible API for
crawling and suggesting firmware candidate download URLs in the
install flow.

Implement GooglebookProvider to query production_recovery.json via
NetworkService, filtering by matching Build.DEVICE or Build.MODEL to
suggest the latest official recovery image on supported devices.

Refactor InstallViewModel and InstallDialog to use the generic
FirmwareCrawler API without hardcoding device-specific logic,
presenting candidate suggestions alongside custom URL input.

Assisted-by: Gemini 3.8 Flash
This commit is contained in:
topjohnwu
2026-10-08 10:35:49 -07:00
committed by John Wu
parent 3ebcc3440d
commit 93e4023b8b
11 changed files with 252 additions and 36 deletions
@@ -20,7 +20,7 @@ val VMFactory: ViewModelProvider.Factory = viewModelFactory {
initializer { LogViewModel(ServiceLocator.logRepo) }
initializer { SuperuserViewModel(ServiceLocator.policyDB) }
initializer { SuperuserGrantViewModel(ServiceLocator.policyDB) }
initializer { InstallViewModel(ServiceLocator.networkService) }
initializer { InstallViewModel(ServiceLocator.networkService, ServiceLocator.firmwareCrawler) }
initializer { DenyListViewModel() }
initializer { FlashViewModel() }
initializer { ActionViewModel() }
@@ -4,13 +4,17 @@ import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
@@ -24,6 +28,7 @@ import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
@@ -35,8 +40,10 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
@@ -46,6 +53,7 @@ import androidx.core.net.toUri
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.topjohnwu.magisk.core.Config
import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.core.repository.FirmwareCrawler
import com.topjohnwu.magisk.ui.component.ConfirmResult
import com.topjohnwu.magisk.ui.component.MagiskDialog
import com.topjohnwu.magisk.ui.component.MarkdownText
@@ -99,6 +107,7 @@ fun InstallDialog(
if (showDownloadDialog) {
DownloadComposableDialog(
candidate = installUiState.candidate,
onDismiss = { showDownloadDialog = false },
onConfirm = { url ->
showDownloadDialog = false
@@ -251,8 +260,10 @@ private fun InstallOptionsSection(
fun DownloadComposableDialog(
onDismiss: () -> Unit,
onConfirm: (Uri) -> Unit,
modifier: Modifier = Modifier
modifier: Modifier = Modifier,
candidate: FirmwareCrawler.Candidate? = null,
) {
var selectedCandidate by rememberSaveable(candidate) { mutableStateOf(candidate != null) }
var url by rememberSaveable { mutableStateOf("") }
var isError by rememberSaveable { mutableStateOf(false) }
@@ -266,48 +277,119 @@ fun DownloadComposableDialog(
}
val submit = {
isValidUrl(url.trim())?.let {
onConfirm(it)
} ?: run {
isError = true
if (candidate != null && selectedCandidate) {
onConfirm(candidate.url.toUri())
} else {
isValidUrl(url.trim())?.let {
onConfirm(it)
} ?: run {
isError = true
}
}
}
MagiskDialog(
modifier = modifier,
onDismissRequest = onDismiss,
title = stringResource(CoreR.string.download_dialog_title),
title = stringResource(
if (candidate != null) CoreR.string.download_patch_file
else CoreR.string.download_dialog_title
),
confirmText = stringResource(android.R.string.ok),
onConfirm = submit,
dismissText = stringResource(android.R.string.cancel),
onDismiss = onDismiss,
) {
Column(modifier = Modifier.padding(top = 8.dp)) {
OutlinedTextField(
value = url,
onValueChange = {
url = it
isError = false
},
modifier = Modifier.fillMaxWidth(),
label = { Text(stringResource(CoreR.string.download_dialog_msg)) },
isError = isError,
singleLine = true,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Uri,
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(
onDone = { submit() }
)
)
if (isError) {
Text(
text = stringResource(CoreR.string.download_dialog_title),
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(start = 16.dp, top = 4.dp)
Column(
modifier = Modifier.padding(top = 8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
if (candidate != null) {
Column(modifier = Modifier.selectableGroup()) {
Row(
modifier = Modifier
.fillMaxWidth()
.selectable(
selected = selectedCandidate,
onClick = { selectedCandidate = true },
role = Role.RadioButton
)
.padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
selected = selectedCandidate,
onClick = null
)
Spacer(Modifier.width(16.dp))
Column {
Text(
text = candidate.title,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurface
)
if (candidate.description.isNotEmpty()) {
Text(
text = candidate.description,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
Row(
modifier = Modifier
.fillMaxWidth()
.selectable(
selected = !selectedCandidate,
onClick = { selectedCandidate = false },
role = Role.RadioButton
)
.padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
selected = !selectedCandidate,
onClick = null
)
Spacer(Modifier.width(16.dp))
Text(
text = stringResource(CoreR.string.download_dialog_title),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurface
)
}
}
}
if (candidate == null || !selectedCandidate) {
OutlinedTextField(
value = url,
onValueChange = {
url = it
isError = false
},
modifier = Modifier.fillMaxWidth(),
label = { Text(stringResource(CoreR.string.download_dialog_msg)) },
isError = isError,
singleLine = true,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Uri,
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(
onDone = { submit() }
)
)
if (isError) {
Text(
text = stringResource(CoreR.string.download_dialog_title),
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(start = 16.dp, top = 4.dp)
)
}
}
}
}
@@ -9,9 +9,11 @@ import com.topjohnwu.magisk.core.BuildConfig.APP_VERSION_CODE
import com.topjohnwu.magisk.core.Const
import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.core.ktx.toast
import com.topjohnwu.magisk.core.repository.FirmwareCrawler
import com.topjohnwu.magisk.core.repository.NetworkService
import com.topjohnwu.magisk.ui.navigation.Route
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
@@ -22,7 +24,10 @@ import java.io.File
import java.io.IOException
import com.topjohnwu.magisk.core.R as CoreR
class InstallViewModel(svc: NetworkService) : BaseViewModel() {
class InstallViewModel(
svc: NetworkService,
crawler: FirmwareCrawler,
) : BaseViewModel() {
enum class Method { NONE, PATCH, DIRECT, INACTIVE_SLOT, DOWNLOAD }
@@ -33,6 +38,7 @@ class InstallViewModel(svc: NetworkService) : BaseViewModel() {
val requestFilePicker: Boolean = false,
val showSecondSlotWarning: Boolean = false,
val showDownloadDialog: Boolean = false,
val candidate: FirmwareCrawler.Candidate? = null,
)
val isRooted get() = Info.isRooted
@@ -42,7 +48,13 @@ class InstallViewModel(svc: NetworkService) : BaseViewModel() {
private val _uiState = MutableStateFlow(UiState())
val uiState: StateFlow<UiState> = _uiState.asStateFlow()
private var candidateJob: Job? = null
init {
candidateJob = viewModelScope.launch(Dispatchers.IO) {
val candidate = crawler.crawl()
_uiState.update { it.copy(candidate = candidate) }
}
viewModelScope.launch(Dispatchers.IO) {
try {
val noteFile = File(AppContext.cacheDir, "${APP_VERSION_CODE}.md")
@@ -73,7 +85,15 @@ class InstallViewModel(svc: NetworkService) : BaseViewModel() {
_uiState.update { it.copy(showSecondSlotWarning = true) }
}
Method.DOWNLOAD -> {
_uiState.update { it.copy(showDownloadDialog = true) }
val job = candidateJob
if (job != null && job.isActive) {
viewModelScope.launch {
job.join()
_uiState.update { it.copy(showDownloadDialog = true) }
}
} else {
_uiState.update { it.copy(showDownloadDialog = true) }
}
}
else -> {}
}
@@ -2,7 +2,6 @@ package com.topjohnwu.magisk.core
import android.os.Build
import android.os.Process
import com.topjohnwu.magisk.core.BuildConfig.APP_VERSION_CODE
@Suppress("DEPRECATION")
object Const {
@@ -45,6 +44,8 @@ object Const {
const val GITHUB_API_URL = "https://api.github.com/"
const val GITHUB_PAGE_URL = "https://topjohnwu.github.io/magisk-files/"
const val INVALID_URL = "https://example.com/"
const val GOOGLEBOOK_RECOVERY_URL =
"https://dl.google.com/dl/edgedl/device/recovery/production_recovery.json"
}
object Key {
@@ -60,6 +60,9 @@ object Info {
|| getProperty("ro.kernel.qemu", "0") == "1"
|| getProperty("ro.boot.qemu", "0") == "1"
val isGooglebook get() =
AppContext.packageManager.hasSystemFeature("com.google.desktop.gms")
val isHeadlessSystemUser by lazy {
getProperty("ro.fw.mu.headless_system_user", "false").toBoolean()
}
@@ -1,6 +1,7 @@
package com.topjohnwu.magisk.core.data
import com.topjohnwu.magisk.core.model.ModuleJson
import com.topjohnwu.magisk.core.model.GooglebookRecoveryJson
import com.topjohnwu.magisk.core.model.Release
import com.topjohnwu.magisk.core.model.UpdateJson
import okhttp3.ResponseBody
@@ -26,6 +27,9 @@ interface RawUrl {
@GET
suspend fun fetchUpdateJson(@Url url: String): UpdateJson
@GET
suspend fun fetchGooglebookRecoveryJson(@Url url: String): List<GooglebookRecoveryJson>
}
interface GithubApiServices {
@@ -11,6 +11,7 @@ import com.topjohnwu.magisk.core.data.magiskdb.PolicyDao
import com.topjohnwu.magisk.core.data.magiskdb.SettingsDao
import com.topjohnwu.magisk.core.data.magiskdb.StringDao
import com.topjohnwu.magisk.core.ktx.deviceProtectedContext
import com.topjohnwu.magisk.core.repository.FirmwareCrawler
import com.topjohnwu.magisk.core.repository.LogRepository
import com.topjohnwu.magisk.core.repository.NetworkService
import io.noties.markwon.Markwon
@@ -38,6 +39,7 @@ object ServiceLocator {
createApiService(retrofit, Const.Url.GITHUB_API_URL),
)
}
val firmwareCrawler by lazy { FirmwareCrawler(networkService) }
}
private fun createSuLogDatabase(context: Context) =
@@ -0,0 +1,23 @@
package com.topjohnwu.magisk.core.model
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class GooglebookRecoveryJson(
val channel: String = "",
val device: String = "",
val file: String = "",
val filesize: Long = 0L,
val manufacturer: String = "",
val md5: String = "",
val model: String = "",
val name: String = "",
val url: String = "",
val zipfilesize: Long = 0L,
val buildexploreruri: String = "",
val buildidentifier: String = "",
val target: String = "",
val branch: String = "",
val dateupdated: String = "",
val previousVersionGeneration: Long = 0L,
)
@@ -0,0 +1,74 @@
package com.topjohnwu.magisk.core.repository
import android.os.Build
import com.topjohnwu.magisk.core.AppContext
import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.core.model.GooglebookRecoveryJson
import timber.log.Timber
import com.topjohnwu.magisk.core.R as CoreR
class FirmwareCrawler(
private val svc: NetworkService,
) {
private val providers: Map<() -> Boolean, Provider> = mapOf(
{ Info.isGooglebook } to GooglebookProvider,
)
data class Candidate(
val url: String,
val title: String,
val description: String = "",
)
fun interface Provider {
suspend fun crawl(svc: NetworkService): Candidate?
}
suspend fun crawl(): Candidate? {
for ((predicate, provider) in providers) {
try {
if (predicate()) {
val candidate = provider.crawl(svc)
if (candidate != null) return candidate
}
} catch (e: Exception) {
Timber.e(e)
}
}
return null
}
private object GooglebookProvider : Provider {
override suspend fun crawl(svc: NetworkService): Candidate? {
val list = svc.fetchGooglebookRecovery() ?: return null
val matching = list.filter {
it.device.equals(Build.DEVICE, ignoreCase = true) ||
it.model.equals(Build.MODEL, ignoreCase = true)
}
val recovery = matching.maxWithOrNull(
compareBy<GooglebookRecoveryJson> { it.dateupdated }
.thenBy { it.previousVersionGeneration }
) ?: return null
if (recovery.url.isEmpty()) return null
val details = buildString {
if (recovery.model.isNotEmpty()) {
append(recovery.model)
} else if (recovery.name.isNotEmpty()) {
append(recovery.name)
}
if (recovery.buildidentifier.isNotEmpty()) {
if (isNotEmpty()) append(" • ")
append(recovery.buildidentifier)
}
}
return Candidate(
url = recovery.url,
title = AppContext.getString(CoreR.string.download_googlebook_recovery_image),
description = details,
)
}
}
}
@@ -7,10 +7,12 @@ import com.topjohnwu.magisk.core.Config.Value.CUSTOM_CHANNEL
import com.topjohnwu.magisk.core.Config.Value.DEBUG_CHANNEL
import com.topjohnwu.magisk.core.Config.Value.DEFAULT_CHANNEL
import com.topjohnwu.magisk.core.Config.Value.STABLE_CHANNEL
import com.topjohnwu.magisk.core.Const
import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.core.data.GithubApiServices
import com.topjohnwu.magisk.core.data.RawUrl
import com.topjohnwu.magisk.core.ktx.dateFormat
import com.topjohnwu.magisk.core.model.GooglebookRecoveryJson
import com.topjohnwu.magisk.core.model.Release
import com.topjohnwu.magisk.core.model.ReleaseAssets
import com.topjohnwu.magisk.core.model.UpdateInfo
@@ -45,6 +47,10 @@ class NetworkService(
findRelease { it.versionCode == version }.asInfo()
}
suspend fun fetchGooglebookRecovery() = safe {
raw.fetchGooglebookRecoveryJson(Const.Url.GOOGLEBOOK_RECOVERY_URL)
}
// Keep going through all release pages until we find a match
private suspend inline fun findRelease(predicate: (Release) -> Boolean): Release? {
var page = 1
+1
View File
@@ -50,6 +50,7 @@
<string name="download_patch_file">Download and patch a file</string>
<string name="download_dialog_title">Enter image URL</string>
<string name="download_dialog_msg">Full OTA image or factory image</string>
<string name="download_googlebook_recovery_image">Download latest Googlebook recovery image</string>
<string name="reboot_delay_toast">Rebooting in 5 seconds…</string>
<string name="flash_screen_title">Installation</string>