mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 20:36:04 +00:00
feat: publish and consume update catalog
This commit is contained in:
1 parent
b3a87d3d73
commit
a5f2895a6a
11 files changed
+973
-205
No files matched your search
@@ -91,6 +91,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
||||
private fun install(r: AppUpdates.Release) {
|
||||
if (stage != null) return
|
||||
val apk = r.apk ?: run { error = "This build has no download for this copy of DroidDeck"; return }
|
||||
AppUpdates.installBlock(r)?.let { error = it; return }
|
||||
if (SessionState.running) { error = "Stop the running session first, then update"; return }
|
||||
if (!SelfInstaller.canInstall(activity)) { pending = r; askPermission = true; return }
|
||||
error = null
|
||||
|
||||
@@ -148,6 +148,7 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m
|
||||
val offer = if (me.updatable) catalog?.let { AppUpdates.offer(it, u.follow, me) } else null
|
||||
val name = channelName(u.follow)
|
||||
val offered = release != null && (offer == Offer.UPDATE || offer == Offer.SWITCH)
|
||||
val installBlock = release?.let { AppUpdates.installBlock(it, me) }
|
||||
class Look(val tint: Color, val status: String, val headline: String, val detail: String?)
|
||||
val look = when {
|
||||
!me.updatable -> Look(colors.onSurfaceVariant, "Signed differently", "Can't update in place",
|
||||
@@ -158,7 +159,7 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m
|
||||
offer == Offer.AHEAD -> Look(pal.signal, "Ahead of Stable", "You're ahead of Stable",
|
||||
"This build is newer than the last Stable release. You'll move onto Stable with its next one.")
|
||||
offer == Offer.GONE -> Look(AttentionAmber, "Test ended", "This test has ended",
|
||||
"Its fix was merged or dropped. Follow Nightly to keep getting the newest fixes.")
|
||||
"Its fix was merged or dropped. Follow Preview to keep getting the newest fixes.")
|
||||
else -> Look(pal.good, "Up to date", "You have the latest $name", null)
|
||||
}
|
||||
Column(
|
||||
@@ -174,8 +175,11 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m
|
||||
ReleaseNotes(changeTitle(release!!.title.ifBlank { release.tag }), release.summary, release.tag)
|
||||
}
|
||||
if (look.detail != null) Text(look.detail, fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 10.dp))
|
||||
if (installBlock != null && (offered || offer == Offer.AHEAD)) {
|
||||
Text(installBlock, fontSize = 13.sp, color = AttentionAmber, modifier = Modifier.padding(top = 10.dp))
|
||||
}
|
||||
if (u.error != null) Text(u.error, fontSize = 13.sp, color = pal.error, modifier = Modifier.padding(top = 12.dp))
|
||||
val installable = release?.apk != null && !s.sessionRunning
|
||||
val installable = release?.apk != null && installBlock == null && !s.sessionRunning
|
||||
val button = release?.apk?.size?.takeIf { it > 0 }?.let { " · ${megabytes(it)}" }.orEmpty()
|
||||
Box(Modifier.padding(top = 14.dp)) {
|
||||
when {
|
||||
@@ -186,8 +190,9 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m
|
||||
}
|
||||
offer == Offer.UPDATE -> PrimaryButton("Update$button", enabled = installable, main = true) { ua.onInstall(release!!) }
|
||||
offer == Offer.SWITCH -> PrimaryButton("Install$button", enabled = installable, main = true) { ua.onInstall(release!!) }
|
||||
offer == Offer.AHEAD -> SecondaryButton("Install Stable ${release?.version.orEmpty()} anyway", enabled = installable) { ua.onInstall(release!!) }
|
||||
offer == Offer.GONE -> PrimaryButton("Follow Nightly", main = true) { ua.onFollow(Follow(Channel.NIGHTLY)) }
|
||||
offer == Offer.AHEAD && installBlock == null ->
|
||||
SecondaryButton("Install Stable ${release?.version.orEmpty()} anyway", enabled = installable) { ua.onInstall(release!!) }
|
||||
offer == Offer.GONE -> PrimaryButton("Follow Preview", main = true) { ua.onFollow(Follow(Channel.NIGHTLY)) }
|
||||
}
|
||||
}
|
||||
if (s.sessionRunning && (offered || offer == Offer.AHEAD)) {
|
||||
@@ -226,10 +231,10 @@ private fun ReleaseNotes(title: String, notes: String, key: String) {
|
||||
}
|
||||
}
|
||||
|
||||
/** The headline for a build on offer: "DroidDeck 0.3.0", "New Nightly build", "PR #93 test build". */
|
||||
/** The headline for a build on offer: "DroidDeck 0.3.0", "New Preview build", "PR #93 test build". */
|
||||
private fun newBuild(f: Follow, r: Release) = when (f.channel) {
|
||||
Channel.STABLE -> "DroidDeck ${r.version ?: r.tag}"
|
||||
Channel.NIGHTLY -> "New Nightly build"
|
||||
Channel.NIGHTLY -> "New Preview build"
|
||||
Channel.TEST -> "PR #${r.pr} test build"
|
||||
}
|
||||
|
||||
@@ -259,8 +264,8 @@ private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions) {
|
||||
catalog?.stable?.let { "${it.version ?: it.tag} · ${ago(it.publishedAt)}" }, u.follow.channel == Channel.STABLE,
|
||||
) { ua.onFollow(Follow(Channel.STABLE)) }
|
||||
ChannelCard(
|
||||
Icons.Outlined.Bolt, "Nightly", "Newest fixes, the odd new bug",
|
||||
catalog?.nightly?.let { ago(it.publishedAt) }, u.follow.channel == Channel.NIGHTLY,
|
||||
Icons.Outlined.Bolt, "Preview", "Newest main-branch fixes, before Stable",
|
||||
catalog?.preview?.let { ago(it.publishedAt) }, u.follow.channel == Channel.NIGHTLY,
|
||||
) { ua.onFollow(Follow(Channel.NIGHTLY)) }
|
||||
ChannelCard(
|
||||
Icons.Outlined.Science, "Test builds", "Try a fix before it's released",
|
||||
@@ -343,7 +348,7 @@ private fun TestRow(t: Release, selected: Boolean, onClick: () -> Unit) {
|
||||
|
||||
private fun channelName(f: Follow) = when (f.channel) {
|
||||
Channel.STABLE -> "Stable"
|
||||
Channel.NIGHTLY -> "Nightly"
|
||||
Channel.NIGHTLY -> "Preview"
|
||||
Channel.TEST -> "the PR #${f.pr} test"
|
||||
}
|
||||
|
||||
|
||||
@@ -4,97 +4,118 @@ import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
import com.droiddeck.launcher.core.Hashes
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.IOException
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.security.MessageDigest
|
||||
import java.time.Instant
|
||||
|
||||
/**
|
||||
* DroidDeck's own builds, on three channels: Stable (the org repo's latest release), Nightly (the
|
||||
* newest `main-<sha>` release on DroidDeck-CI, one per merge to main) and Test (a `pr-<n>` release
|
||||
* on DroidDeck-CI, a signed build of an open PR). All three are signed with the release key, so any
|
||||
* of them installs over any other and keeps the app's data.
|
||||
* DroidDeck's published builds. CI turns GitHub Releases into one static catalog in DroidDeck-CI;
|
||||
* the app consumes that contract instead of inferring channels from tags and release-note prose.
|
||||
*
|
||||
* Which build is newer is decided without a diff of the repo (GitHub's compare answers in
|
||||
* megabytes): main is linear, so the newest main build is the newest; Stable is ordered by its
|
||||
* version; a test build is newer when its PR's head moved. The last check is remembered, so the
|
||||
* page shows it without going online.
|
||||
* [Channel.NIGHTLY] is intentionally kept as the internal enum/pref value for upgrades from older
|
||||
* DroidDeck versions. The channel is presented to users as Preview.
|
||||
*/
|
||||
object AppUpdates {
|
||||
private const val REPO = "Droid-Deck/DroidDeck"
|
||||
private const val CI_REPO = "Droid-Deck/DroidDeck-CI"
|
||||
private const val CATALOG_URL = "https://raw.githubusercontent.com/$CI_REPO/main/catalog.json"
|
||||
private const val PREFS = "app_updates"
|
||||
private const val KEY_CATALOG = "catalog"
|
||||
private const val KEY_CHANNEL = "channel"
|
||||
private const val CATALOG_SCHEMA = 1
|
||||
|
||||
enum class Channel { STABLE, NIGHTLY, TEST }
|
||||
|
||||
/** The channel the user follows; [pr] is the followed test build's PR, for [Channel.TEST]. */
|
||||
data class Follow(val channel: Channel, val pr: Int = 0)
|
||||
|
||||
class Apk(val name: String, val url: String, val size: Long, val sha256: String)
|
||||
|
||||
/**
|
||||
* One published build. [commit] is a full or short SHA of the source it was built from; [pr] is
|
||||
* 0 for a main or stable build. [apk] is the file for the package this app runs as, or null when
|
||||
* the build has none (a variant a release predates).
|
||||
*/
|
||||
class Release(
|
||||
val tag: String, val title: String, val summary: String, val commit: String, val pr: Int,
|
||||
val version: String?, val publishedAt: Long, val url: String, val apk: Apk?,
|
||||
class Apk(
|
||||
val name: String,
|
||||
val url: String,
|
||||
val size: Long,
|
||||
val sha256: String,
|
||||
val packageName: String,
|
||||
val versionCode: Int,
|
||||
val signerSha256: String,
|
||||
)
|
||||
|
||||
class Catalog(val stable: Release?, val nightly: Release?, val tests: List<Release>, val checkedAt: Long)
|
||||
class Release(
|
||||
val tag: String,
|
||||
val title: String,
|
||||
val summary: String,
|
||||
val commit: String,
|
||||
val pr: Int,
|
||||
val version: String?,
|
||||
val versionCode: Int,
|
||||
val publishedAt: Long,
|
||||
val url: String,
|
||||
val apk: Apk?,
|
||||
)
|
||||
|
||||
/**
|
||||
* What is running: the commit it was built from, its PR (0 for none), whether the builds here
|
||||
* install over it (it is signed with the release key), and when it was committed.
|
||||
*/
|
||||
class Installed(val commit: String, val pr: Int, val version: String, val updatable: Boolean, val committedAt: Long = 0L)
|
||||
class Catalog(
|
||||
val stable: Release?,
|
||||
val preview: Release?,
|
||||
val tests: List<Release>,
|
||||
val checkedAt: Long,
|
||||
)
|
||||
|
||||
class Installed(
|
||||
val commit: String,
|
||||
val pr: Int,
|
||||
val version: String,
|
||||
val versionCode: Int,
|
||||
val updatable: Boolean,
|
||||
val committedAt: Long = 0L,
|
||||
)
|
||||
|
||||
enum class Offer {
|
||||
/** This is the build the channel has. */
|
||||
CURRENT,
|
||||
/** The channel has a newer build of what is running. */
|
||||
UPDATE,
|
||||
/** The channel's build is a different line (a test build from Nightly, or back); installing moves over. */
|
||||
SWITCH,
|
||||
/** What is running is newer than the channel's build (a Nightly past the last Stable). */
|
||||
AHEAD,
|
||||
/** The followed test build is gone: its PR was merged or closed. */
|
||||
GONE,
|
||||
}
|
||||
|
||||
@Volatile private var releaseSigned = BuildConfig.CI_BUILD
|
||||
|
||||
/** From App.onCreate: whether this copy is signed with the release key, which a local build may be too. */
|
||||
fun init(context: Context) {
|
||||
releaseSigned = runCatching { signers(context).any { it.equals(BuildConfig.RELEASE_SIGNER, ignoreCase = true) } }
|
||||
.getOrDefault(BuildConfig.CI_BUILD)
|
||||
releaseSigned = runCatching {
|
||||
signers(context).any { it.equals(BuildConfig.RELEASE_SIGNER, ignoreCase = true) }
|
||||
}.getOrDefault(BuildConfig.CI_BUILD)
|
||||
}
|
||||
|
||||
/** SHA-256 of each certificate the package is signed with, including the ones a rotated key vouches for. */
|
||||
private fun signers(context: Context): List<String> {
|
||||
val pm = context.packageManager
|
||||
@Suppress("DEPRECATION")
|
||||
val certs = if (Build.VERSION.SDK_INT >= 28) {
|
||||
val info = pm.getPackageInfo(context.packageName, PackageManager.GET_SIGNING_CERTIFICATES).signingInfo ?: return emptyList()
|
||||
val info = pm.getPackageInfo(
|
||||
context.packageName,
|
||||
PackageManager.GET_SIGNING_CERTIFICATES,
|
||||
).signingInfo ?: return emptyList()
|
||||
if (info.hasMultipleSigners()) info.apkContentsSigners else info.signingCertificateHistory
|
||||
} else {
|
||||
pm.getPackageInfo(context.packageName, PackageManager.GET_SIGNATURES).signatures
|
||||
} ?: return emptyList()
|
||||
return certs.map { cert -> MessageDigest.getInstance("SHA-256").digest(cert.toByteArray()).joinToString("") { "%02x".format(it) } }
|
||||
return certs.map { cert ->
|
||||
MessageDigest.getInstance("SHA-256").digest(cert.toByteArray())
|
||||
.joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
}
|
||||
|
||||
fun installed(): Installed = Installed(BuildConfig.SOURCE_COMMIT, BuildConfig.PR_NUMBER, BuildConfig.VERSION_NAME, releaseSigned, BuildConfig.COMMIT_TIME)
|
||||
fun installed(): Installed = Installed(
|
||||
BuildConfig.SOURCE_COMMIT,
|
||||
BuildConfig.PR_NUMBER,
|
||||
BuildConfig.VERSION_NAME,
|
||||
BuildConfig.VERSION_CODE,
|
||||
releaseSigned,
|
||||
BuildConfig.COMMIT_TIME,
|
||||
)
|
||||
|
||||
fun release(catalog: Catalog, follow: Follow): Release? = when (follow.channel) {
|
||||
Channel.STABLE -> catalog.stable
|
||||
Channel.NIGHTLY -> catalog.nightly
|
||||
Channel.NIGHTLY -> catalog.preview
|
||||
Channel.TEST -> catalog.tests.firstOrNull { it.pr == follow.pr }
|
||||
}
|
||||
|
||||
@@ -112,19 +133,27 @@ object AppUpdates {
|
||||
}
|
||||
}
|
||||
|
||||
/** The dot on the rail: the followed channel has a newer build of what is running. */
|
||||
fun hasUpdate(catalog: Catalog?, follow: Follow): Boolean =
|
||||
catalog != null && installed().updatable && offer(catalog, follow) == Offer.UPDATE
|
||||
fun hasUpdate(catalog: Catalog?, follow: Follow): Boolean {
|
||||
if (catalog == null) return false
|
||||
val me = installed()
|
||||
val r = release(catalog, follow) ?: return false
|
||||
return me.updatable && offer(catalog, follow, me) == Offer.UPDATE && installBlock(r, me) == null
|
||||
}
|
||||
|
||||
fun isRunning(r: Release, me: Installed = installed()): Boolean {
|
||||
if (me.commit.length < 7 || r.commit.length < 7 || r.pr != me.pr) return false
|
||||
return me.commit.startsWith(r.commit, ignoreCase = true) || r.commit.startsWith(me.commit, ignoreCase = true)
|
||||
return me.commit.startsWith(r.commit, ignoreCase = true) ||
|
||||
r.commit.startsWith(me.commit, ignoreCase = true)
|
||||
}
|
||||
|
||||
/** Why Android cannot install this published build over [me], before downloading anything. */
|
||||
fun installBlock(r: Release, me: Installed = installed()): String? = when {
|
||||
r.apk == null -> "This build has no download for this copy of DroidDeck."
|
||||
r.apk.versionCode < me.versionCode ->
|
||||
"Android won't install it over this build because its versionCode ${r.apk.versionCode} is below the installed ${me.versionCode}."
|
||||
else -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* The channel followed. Until the user picks one it is worked out once from what is running and
|
||||
* kept: a test build follows its PR, the Stable release follows Stable, and a main build Nightly.
|
||||
*/
|
||||
fun follow(context: Context, catalog: Catalog?): Follow {
|
||||
stored(context)?.let { return it }
|
||||
val me = installed()
|
||||
@@ -140,7 +169,9 @@ object AppUpdates {
|
||||
}
|
||||
|
||||
fun setFollow(context: Context, follow: Follow) {
|
||||
val value = if (follow.channel == Channel.TEST) "test:${follow.pr}" else follow.channel.name.lowercase()
|
||||
// Keep "nightly" on disk so an older DroidDeck still understands the preference after rollback.
|
||||
val value = if (follow.channel == Channel.TEST) "test:${follow.pr}"
|
||||
else follow.channel.name.lowercase()
|
||||
prefs(context).edit().putString(KEY_CHANNEL, value).apply()
|
||||
}
|
||||
|
||||
@@ -148,129 +179,114 @@ object AppUpdates {
|
||||
val v = prefs(context).getString(KEY_CHANNEL, null) ?: return null
|
||||
return when {
|
||||
v == "stable" -> Follow(Channel.STABLE)
|
||||
v == "nightly" -> Follow(Channel.NIGHTLY)
|
||||
v.startsWith("test:") -> v.removePrefix("test:").toIntOrNull()?.let { Follow(Channel.TEST, it) }
|
||||
v == "nightly" || v == "preview" -> Follow(Channel.NIGHTLY)
|
||||
v.startsWith("test:") -> v.removePrefix("test:").toIntOrNull()?.let {
|
||||
Follow(Channel.TEST, it)
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
/** The last check, or null before the first. */
|
||||
fun cached(context: Context): Catalog? {
|
||||
val raw = prefs(context).getString(KEY_CATALOG, null) ?: return null
|
||||
return runCatching { readCatalog(JSONObject(raw)) }.getOrNull()
|
||||
return runCatching { readCachedCatalog(JSONObject(raw)) }.getOrNull()
|
||||
}
|
||||
|
||||
/** Read every channel now and remember the result: three small requests, four for an annotated tag. */
|
||||
/** One static request, rather than several unauthenticated GitHub API requests. */
|
||||
fun refresh(context: Context): Catalog {
|
||||
val suffix = variantSuffix(context.packageName)
|
||||
val stable = runCatching { stable(suffix) }.getOrElse { if (it is NoRelease) null else throw it }
|
||||
val ci = JSONArray(get("https://api.github.com/repos/$CI_REPO/releases?per_page=50"))
|
||||
var nightly: Release? = null
|
||||
val tests = ArrayList<Release>()
|
||||
for (i in 0 until ci.length()) {
|
||||
val r = ci.getJSONObject(i)
|
||||
if (r.optBoolean("draft")) continue
|
||||
val tag = r.getString("tag_name")
|
||||
when {
|
||||
tag.startsWith("main-") -> {
|
||||
val candidate = ciRelease(r, suffix, tag.removePrefix("main-"), 0)
|
||||
if (nightly == null || candidate.publishedAt > nightly.publishedAt) nightly = candidate
|
||||
}
|
||||
tag.startsWith("pr-") -> {
|
||||
val pr = tag.removePrefix("pr-").toIntOrNull() ?: continue
|
||||
val body = r.optString("body")
|
||||
// Only builds of this repo's PRs: a test build from before the org move names another.
|
||||
if (!body.contains("github.com/$REPO/pull/$pr")) continue
|
||||
val commit = Regex("""Commit: `?([0-9a-f]{7,40})""").find(body)?.groupValues?.get(1) ?: continue
|
||||
tests.add(ciRelease(r, suffix, commit, pr))
|
||||
}
|
||||
}
|
||||
}
|
||||
tests.sortByDescending { it.publishedAt }
|
||||
val catalog = Catalog(stable, nightly, tests, System.currentTimeMillis())
|
||||
val catalog = readPublishedCatalog(
|
||||
JSONObject(get(CATALOG_URL)),
|
||||
context.packageName,
|
||||
System.currentTimeMillis(),
|
||||
)
|
||||
prefs(context).edit().putString(KEY_CATALOG, writeCatalog(catalog).toString()).apply()
|
||||
return catalog
|
||||
}
|
||||
|
||||
private class NoRelease : IOException("no stable release")
|
||||
|
||||
private fun stable(suffix: String): Release {
|
||||
val r = try {
|
||||
JSONObject(get("https://api.github.com/repos/$REPO/releases/latest"))
|
||||
} catch (e: IOException) {
|
||||
if (e.message?.contains("HTTP 404") == true) throw NoRelease() else throw e
|
||||
internal fun readPublishedCatalog(
|
||||
root: JSONObject,
|
||||
packageName: String,
|
||||
checkedAt: Long,
|
||||
): Catalog {
|
||||
val schema = root.optInt("schema")
|
||||
val sourceRepo = root.optString("sourceRepo")
|
||||
val ciRepo = root.optString("ciRepo")
|
||||
if (schema != CATALOG_SCHEMA || sourceRepo != REPO || ciRepo != CI_REPO) {
|
||||
throw IOException(
|
||||
"The update catalog has an unsupported format (schema $schema, source $sourceRepo, CI $ciRepo)",
|
||||
)
|
||||
}
|
||||
val tag = r.getString("tag_name")
|
||||
// The tag's commit; an annotated tag points at a tag object first.
|
||||
var obj = JSONObject(get("https://api.github.com/repos/$REPO/git/ref/tags/$tag")).getJSONObject("object")
|
||||
if (obj.getString("type") == "tag") obj = JSONObject(get(obj.getString("url"))).getJSONObject("object")
|
||||
val (title, summary) = describeStable(r.optString("name").ifBlank { tag }, r.optString("body"))
|
||||
return Release(tag, title, summary, obj.getString("sha"), 0, tag.removePrefix("v"), published(r),
|
||||
r.optString("html_url"), apk(r, suffix))
|
||||
val tests = root.optJSONArray("tests") ?: JSONArray()
|
||||
return Catalog(
|
||||
root.optJSONObject("stable")?.let { readPublishedRelease(it, packageName) },
|
||||
root.optJSONObject("preview")?.let { readPublishedRelease(it, packageName) },
|
||||
(0 until tests.length())
|
||||
.map { readPublishedRelease(tests.getJSONObject(it), packageName) }
|
||||
.filter { it.pr > 0 }
|
||||
.sortedByDescending { it.publishedAt },
|
||||
checkedAt,
|
||||
)
|
||||
}
|
||||
|
||||
private fun ciRelease(r: JSONObject, suffix: String, commit: String, pr: Int): Release {
|
||||
val (title, summary) = describeCi(r.optString("name"), r.optString("body"))
|
||||
return Release(r.getString("tag_name"), title, summary, commit, pr, null, published(r), r.optString("html_url"), apk(r, suffix))
|
||||
}
|
||||
|
||||
private fun published(r: JSONObject): Long =
|
||||
runCatching { Instant.parse(r.optString("published_at")).toEpochMilli() }.getOrDefault(0L)
|
||||
|
||||
/** The apk for this package: `<name><suffix>.apk`, and for the standard app the one with no other variant's suffix. */
|
||||
private fun apk(r: JSONObject, suffix: String): Apk? {
|
||||
val others = variantSuffixes().values.filter { it.isNotEmpty() && it != suffix }
|
||||
val assets = r.optJSONArray("assets") ?: return null
|
||||
for (i in 0 until assets.length()) {
|
||||
val a = assets.getJSONObject(i)
|
||||
val name = a.getString("name")
|
||||
if (!name.endsWith("$suffix.apk") || others.any { name.endsWith("$it.apk") }) continue
|
||||
// Only a file GitHub has a sha256 for: the download is checked against it.
|
||||
val sha = Hashes.githubSha256(a.optString("digest")) ?: continue
|
||||
return Apk(name, a.getString("browser_download_url"), a.optLong("size"), sha)
|
||||
private fun readPublishedRelease(o: JSONObject, packageName: String): Release {
|
||||
val commit = o.getString("commit")
|
||||
if (!Regex("^[0-9a-fA-F]{7,40}$").matches(commit)) {
|
||||
throw IOException("The update catalog contains an invalid commit")
|
||||
}
|
||||
return null
|
||||
val versionCode = o.getInt("versionCode")
|
||||
if (versionCode <= 0) throw IOException("The update catalog contains an invalid versionCode")
|
||||
val apk = o.optJSONObject("apks")?.optJSONObject(packageName)?.let {
|
||||
readPublishedApk(it, packageName)
|
||||
}
|
||||
if (apk != null && apk.versionCode != versionCode) {
|
||||
throw IOException("The update catalog disagrees about the APK versionCode")
|
||||
}
|
||||
return Release(
|
||||
o.getString("tag"),
|
||||
o.optString("title"),
|
||||
o.optString("summary"),
|
||||
commit,
|
||||
o.optInt("pr"),
|
||||
if (o.isNull("version")) null else o.optString("version").ifEmpty { null },
|
||||
versionCode,
|
||||
o.optLong("publishedAt"),
|
||||
o.optString("url"),
|
||||
apk,
|
||||
)
|
||||
}
|
||||
|
||||
private fun variantSuffixes(): Map<String, String> = BuildConfig.VARIANT_SUFFIXES.split(';')
|
||||
.mapNotNull { e -> e.split('=', limit = 2).takeIf { it.size == 2 }?.let { it[0] to it[1] } }.toMap()
|
||||
|
||||
private fun variantSuffix(packageName: String): String = variantSuffixes()[packageName] ?: ""
|
||||
|
||||
/**
|
||||
* A CI release's notes open with what it is: "**Merged to main** - [PR #n](…): title (merged …)"
|
||||
* or "**Not merged** - a test build of open [PR #n](…): title", then a paragraph from the PR.
|
||||
*/
|
||||
internal fun describeCi(name: String, body: String): Pair<String, String> {
|
||||
val paragraphs = paragraphs(body)
|
||||
val head = paragraphs.firstOrNull().orEmpty()
|
||||
val title = head.substringAfter("): ", "").substringBeforeLast(" (merged").ifBlank { plain(head) }.ifBlank { name }
|
||||
val summary = paragraphs.getOrNull(1)?.takeUnless { it.startsWith("Signed build") || it.startsWith("Source:") }.orEmpty()
|
||||
return plain(title) to lines(summary)
|
||||
private fun readPublishedApk(o: JSONObject, packageName: String): Apk {
|
||||
val actualPackage = o.getString("packageName")
|
||||
val versionCode = o.getInt("versionCode")
|
||||
val signer = o.getString("signerSha256").lowercase()
|
||||
val sha = o.getString("sha256").lowercase()
|
||||
val url = o.getString("url")
|
||||
if (actualPackage != packageName) throw IOException("The update catalog names the wrong Android package")
|
||||
if (versionCode <= 0) throw IOException("The update catalog has an invalid APK versionCode")
|
||||
if (!Regex("^[0-9a-f]{64}$").matches(sha)) {
|
||||
throw IOException("The update catalog has an invalid checksum")
|
||||
}
|
||||
if (!signer.equals(BuildConfig.RELEASE_SIGNER, ignoreCase = true)) {
|
||||
throw IOException("The update catalog is not signed for DroidDeck's release key")
|
||||
}
|
||||
val allowed = listOf(
|
||||
"https://github.com/$REPO/releases/download/",
|
||||
"https://github.com/$CI_REPO/releases/download/",
|
||||
)
|
||||
if (allowed.none { url.startsWith(it) }) {
|
||||
throw IOException("The update catalog has an unexpected download URL")
|
||||
}
|
||||
return Apk(
|
||||
o.getString("name"),
|
||||
url,
|
||||
o.optLong("size"),
|
||||
sha,
|
||||
actualPackage,
|
||||
versionCode,
|
||||
signer,
|
||||
)
|
||||
}
|
||||
|
||||
/** A stable release: its name, and the first paragraph of its notes that is prose rather than a heading or picture. */
|
||||
private fun describeStable(name: String, body: String): Pair<String, String> =
|
||||
name to lines(paragraphs(body).firstOrNull { !it.startsWith("#") && !it.startsWith("![") && !it.startsWith("<") }.orEmpty())
|
||||
|
||||
private fun paragraphs(body: String): List<String> =
|
||||
body.replace("\r", "").split(Regex("\n\\s*\n")).map { it.trim() }.filter { it.isNotEmpty() }
|
||||
|
||||
/** A paragraph's lines as text, a list item's marker as a bullet: the page shows them collapsed or in full. */
|
||||
private fun lines(md: String): String = md.lines().map { line ->
|
||||
val item = Regex("""^\s*[-*]\s+""").find(line)
|
||||
if (item != null) "• " + plain(line.substring(item.range.last + 1)) else plain(line)
|
||||
}.filter { it.isNotEmpty() }.joinToString("\n")
|
||||
|
||||
/** Markdown down to text: links to their words, emphasis and code marks gone, on one line. */
|
||||
private fun plain(md: String): String = md
|
||||
.replace(Regex("""!\[[^]]*]\([^)]*\)"""), "")
|
||||
.replace(Regex("""\[([^]]*)]\([^)]*\)"""), "$1")
|
||||
.replace(Regex("""[*_`]{1,3}"""), "")
|
||||
.replace(Regex("""\s+"""), " ")
|
||||
.trim()
|
||||
|
||||
/** Dotted versions, number by number: "0.10.0" is past "0.9.2"; a missing part counts as 0. */
|
||||
fun compareVersions(a: String, b: String): Int {
|
||||
val x = a.removePrefix("v").split('.', '-').map { it.toIntOrNull() ?: 0 }
|
||||
val y = b.removePrefix("v").split('.', '-').map { it.toIntOrNull() ?: 0 }
|
||||
@@ -285,40 +301,79 @@ object AppUpdates {
|
||||
val c = URL(url).openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 15_000
|
||||
c.readTimeout = 20_000
|
||||
c.setRequestProperty("Accept", "application/vnd.github+json")
|
||||
c.setRequestProperty("Accept", "application/json")
|
||||
c.setRequestProperty("User-Agent", "DroidDeck-app")
|
||||
c.setRequestProperty("Cache-Control", "no-cache")
|
||||
try {
|
||||
val code = c.responseCode
|
||||
if (code == 403 || code == 429) throw IOException("GitHub's rate limit was hit - try again later")
|
||||
if (code != 200) throw IOException("GitHub answered HTTP $code")
|
||||
if (code != 200) throw IOException("The update catalog answered HTTP $code")
|
||||
return c.inputStream.bufferedReader().use { it.readText() }
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private fun writeRelease(r: Release): JSONObject = JSONObject()
|
||||
.put("tag", r.tag).put("title", r.title).put("summary", r.summary).put("commit", r.commit).put("pr", r.pr)
|
||||
.put("version", r.version).put("publishedAt", r.publishedAt).put("url", r.url)
|
||||
.put("apk", r.apk?.let { JSONObject().put("name", it.name).put("url", it.url).put("size", it.size).put("sha256", it.sha256) })
|
||||
private fun writeApk(a: Apk): JSONObject = JSONObject()
|
||||
.put("name", a.name)
|
||||
.put("url", a.url)
|
||||
.put("size", a.size)
|
||||
.put("sha256", a.sha256)
|
||||
.put("packageName", a.packageName)
|
||||
.put("versionCode", a.versionCode)
|
||||
.put("signerSha256", a.signerSha256)
|
||||
|
||||
private fun readRelease(o: JSONObject): Release = Release(
|
||||
o.getString("tag"), o.optString("title"), o.optString("summary"), o.getString("commit"), o.optInt("pr"),
|
||||
o.optString("version").ifEmpty { null }, o.optLong("publishedAt"), o.optString("url"),
|
||||
o.optJSONObject("apk")?.let { Apk(it.getString("name"), it.getString("url"), it.optLong("size"), it.getString("sha256")) },
|
||||
private fun writeRelease(r: Release): JSONObject = JSONObject()
|
||||
.put("tag", r.tag)
|
||||
.put("title", r.title)
|
||||
.put("summary", r.summary)
|
||||
.put("commit", r.commit)
|
||||
.put("pr", r.pr)
|
||||
.put("version", r.version)
|
||||
.put("versionCode", r.versionCode)
|
||||
.put("publishedAt", r.publishedAt)
|
||||
.put("url", r.url)
|
||||
.put("apk", r.apk?.let(::writeApk))
|
||||
|
||||
private fun readCachedRelease(o: JSONObject): Release = Release(
|
||||
o.getString("tag"),
|
||||
o.optString("title"),
|
||||
o.optString("summary"),
|
||||
o.getString("commit"),
|
||||
o.optInt("pr"),
|
||||
if (o.isNull("version")) null else o.optString("version").ifEmpty { null },
|
||||
o.getInt("versionCode"),
|
||||
o.optLong("publishedAt"),
|
||||
o.optString("url"),
|
||||
o.optJSONObject("apk")?.let {
|
||||
Apk(
|
||||
it.getString("name"),
|
||||
it.getString("url"),
|
||||
it.optLong("size"),
|
||||
it.getString("sha256"),
|
||||
it.getString("packageName"),
|
||||
it.getInt("versionCode"),
|
||||
it.getString("signerSha256"),
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
private fun writeCatalog(c: Catalog): JSONObject = JSONObject()
|
||||
.put("stable", c.stable?.let(::writeRelease)).put("nightly", c.nightly?.let(::writeRelease))
|
||||
.put("tests", JSONArray().apply { c.tests.forEach { put(writeRelease(it)) } }).put("checkedAt", c.checkedAt)
|
||||
.put("stable", c.stable?.let(::writeRelease))
|
||||
.put("preview", c.preview?.let(::writeRelease))
|
||||
.put("tests", JSONArray().apply { c.tests.forEach { put(writeRelease(it)) } })
|
||||
.put("checkedAt", c.checkedAt)
|
||||
|
||||
private fun readCatalog(o: JSONObject): Catalog {
|
||||
private fun readCachedCatalog(o: JSONObject): Catalog {
|
||||
val tests = o.optJSONArray("tests") ?: JSONArray()
|
||||
val preview = o.optJSONObject("preview") ?: o.optJSONObject("nightly")
|
||||
return Catalog(
|
||||
o.optJSONObject("stable")?.let(::readRelease), o.optJSONObject("nightly")?.let(::readRelease),
|
||||
(0 until tests.length()).map { readRelease(tests.getJSONObject(it)) }, o.optLong("checkedAt"),
|
||||
o.optJSONObject("stable")?.let(::readCachedRelease),
|
||||
preview?.let(::readCachedRelease),
|
||||
(0 until tests.length()).map { readCachedRelease(tests.getJSONObject(it)) },
|
||||
o.optLong("checkedAt"),
|
||||
)
|
||||
}
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
private fun prefs(context: Context) =
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
}
|
||||
@@ -4,9 +4,11 @@ import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageInstaller
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.core.Hashes
|
||||
import java.io.File
|
||||
@@ -14,6 +16,7 @@ import java.io.FileOutputStream
|
||||
import java.io.IOException
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* Installs one of DroidDeck's own builds over itself: download into the cache, check the file
|
||||
@@ -60,9 +63,13 @@ object SelfInstaller {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (apk.size > 0 && target.length() != apk.size) {
|
||||
throw IOException("The download size didn't match the published APK and was discarded - try again")
|
||||
}
|
||||
if (!apk.sha256.equals(Hashes.sha256(target), ignoreCase = true)) {
|
||||
throw IOException("The download didn't match its checksum and was discarded - try again")
|
||||
}
|
||||
validateDownloaded(context, target, apk)
|
||||
return target
|
||||
} catch (e: Exception) {
|
||||
FileUtils.delete(target)
|
||||
@@ -72,6 +79,48 @@ object SelfInstaller {
|
||||
}
|
||||
}
|
||||
|
||||
/** Inspect the actual downloaded APK before giving it to Android's installer. */
|
||||
private fun validateDownloaded(context: Context, file: File, apk: AppUpdates.Apk) {
|
||||
if (apk.packageName != context.packageName) {
|
||||
throw IOException("The update is for Android package ${apk.packageName}, not ${context.packageName}")
|
||||
}
|
||||
if (!apk.signerSha256.equals(BuildConfig.RELEASE_SIGNER, ignoreCase = true)) {
|
||||
throw IOException("The update metadata doesn't name DroidDeck's release signing key")
|
||||
}
|
||||
@Suppress("DEPRECATION")
|
||||
val flags = if (Build.VERSION.SDK_INT >= 28) {
|
||||
PackageManager.GET_SIGNING_CERTIFICATES
|
||||
} else {
|
||||
PackageManager.GET_SIGNATURES
|
||||
}
|
||||
val info = context.packageManager.getPackageArchiveInfo(file.absolutePath, flags)
|
||||
?: throw IOException("Android couldn't read the downloaded APK")
|
||||
if (info.packageName != context.packageName) {
|
||||
throw IOException("The downloaded APK is for ${info.packageName}, not ${context.packageName}")
|
||||
}
|
||||
@Suppress("DEPRECATION")
|
||||
val code = if (Build.VERSION.SDK_INT >= 28) info.longVersionCode else info.versionCode.toLong()
|
||||
if (code != apk.versionCode.toLong()) {
|
||||
throw IOException("The downloaded APK says versionCode $code, not the published ${apk.versionCode}")
|
||||
}
|
||||
if (code < BuildConfig.VERSION_CODE.toLong()) {
|
||||
throw IOException("Android won't install versionCode $code over the installed ${BuildConfig.VERSION_CODE}")
|
||||
}
|
||||
|
||||
// Before Android 9 this lineage intentionally presents the public legacy test key. Android
|
||||
// 9+ understands the v3 hand-over and must see DroidDeck's private release key as current.
|
||||
if (Build.VERSION.SDK_INT >= 28) {
|
||||
val signing = info.signingInfo ?: throw IOException("The downloaded APK has no signing information")
|
||||
val digests = signing.apkContentsSigners.orEmpty().map { cert ->
|
||||
MessageDigest.getInstance("SHA-256").digest(cert.toByteArray())
|
||||
.joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
if (digests.none { it.equals(BuildConfig.RELEASE_SIGNER, ignoreCase = true) }) {
|
||||
throw IOException("The downloaded APK isn't signed with DroidDeck's release key")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes [apk] into an install session and commits it; the answer comes as an [ACTION_STATUS] broadcast. */
|
||||
fun install(context: Context, apk: File) {
|
||||
val installer = context.packageManager.packageInstaller
|
||||
|
||||
Reference in new issue
Block a user