Skip to content

Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.

Update the app from its own releases

Lelonio57365fe0027d
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 9e3e073..90ac75c 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -10,6 +10,12 @@
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<!-- Required from API 33 for the playback notification to be visible. -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
+ <!--
+ Square updates itself: it re-implements Spotify's protocol, so the Play
+ Store is out and its own releases are the only channel there is. The user
+ still confirms every install in Android's own dialog.
+ -->
+ <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<application
android:name=".SquareApplication"
@@ -48,6 +54,10 @@
</intent-filter>
</service>
+ <receiver
+ android:name=".update.InstallReceiver"
+ android:exported="false" />
+
<meta-data
android:name="com.google.android.gms.car.application"
android:resource="@xml/automotive_app_desc" />
diff --git a/app/src/main/java/dev/lelonio/square/SquareApplication.kt b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
index d943aad..c2a2c27 100644
--- a/app/src/main/java/dev/lelonio/square/SquareApplication.kt
+++ b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
@@ -42,6 +42,11 @@ class SquareApplication : Application() {
val api: SpotifyApi by lazy { ApiFactory.create(webApi.tokens, debug = BuildConfig.DEBUG) }
+ /** Checks the project's own releases; there is no store to do it. */
+ val updater: dev.lelonio.square.update.Updater by lazy {
+ dev.lelonio.square.update.Updater(this)
+ }
+
/** The user's saved speed / pitch / reverb combinations. */
val effectPresets: EffectPresetStore by lazy { EffectPresetStore(this) }
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
index 4c2d066..cbabad4 100644
--- a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
@@ -28,7 +28,12 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.draw.clip
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalUriHandler
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import dev.lelonio.square.update.Updater
+import kotlinx.coroutines.launch
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
@@ -256,6 +261,8 @@ fun SettingsScreen(
Section(stringResource(R.string.about)) {
InfoRow(stringResource(R.string.version), "${BuildConfig.VERSION_NAME} (${BuildConfig.BUILD_TYPE})")
RowDivider()
+ UpdateRow()
+ RowDivider()
Licences()
}
}
@@ -270,6 +277,78 @@ fun SettingsScreen(
}
}
+/**
+ * Checking for, and installing, a new version.
+ *
+ * A button rather than something that happens on its own: the check is a
+ * request to GitHub carrying the user's address, made for the app's benefit
+ * rather than theirs, and nothing here needs it badly enough to make it
+ * automatic.
+ */
+@Composable
+private fun UpdateRow() {
+ val context = LocalContext.current
+ val updater = remember(context) {
+ (context.applicationContext as dev.lelonio.square.SquareApplication).updater
+ }
+ val state by updater.state.collectAsStateWithLifecycle()
+ val scope = rememberCoroutineScope()
+
+ val status = when (val current = state) {
+ is Updater.State.Idle -> null
+ is Updater.State.Checking -> stringResource(R.string.update_checking)
+ is Updater.State.UpToDate -> stringResource(R.string.update_none)
+ is Updater.State.Available -> stringResource(R.string.update_available, current.version)
+ is Updater.State.Downloading ->
+ current.progress?.let { "${(it * 100).toInt()}%" } ?: stringResource(R.string.update_downloading)
+ is Updater.State.Installing -> stringResource(R.string.update_installing)
+ is Updater.State.Failed ->
+ if (current.reason == Updater.REASON_PERMISSION) stringResource(R.string.update_needs_permission)
+ else stringResource(R.string.update_failed)
+ }
+
+ val busy = state is Updater.State.Checking || state is Updater.State.Downloading
+
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .clickable(enabled = !busy) {
+ when (val current = state) {
+ is Updater.State.Available -> scope.launch { updater.install(current) }
+ is Updater.State.Failed ->
+ if (current.reason == Updater.REASON_PERMISSION) {
+ context.startActivity(updater.permissionIntent())
+ updater.dismiss()
+ } else {
+ scope.launch { updater.check() }
+ }
+ else -> scope.launch { updater.check() }
+ }
+ }
+ .padding(horizontal = 18.dp, vertical = 14.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ ) {
+ Text(
+ stringResource(
+ if (state is Updater.State.Available) R.string.update_install
+ else R.string.check_for_updates,
+ ),
+ style = MaterialTheme.typography.bodyLarge,
+ fontWeight = if (state is Updater.State.Available) FontWeight.Medium else FontWeight.Normal,
+ modifier = Modifier.weight(1f),
+ )
+ if (status != null) {
+ Text(
+ status,
+ style = MaterialTheme.typography.bodyMedium,
+ color = InkDim,
+ textAlign = androidx.compose.ui.text.style.TextAlign.End,
+ )
+ }
+ }
+}
+
/**
* The third-party code this app ships, and under what.
*
diff --git a/app/src/main/java/dev/lelonio/square/update/InstallReceiver.kt b/app/src/main/java/dev/lelonio/square/update/InstallReceiver.kt
new file mode 100644
index 0000000..a7968c8
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/update/InstallReceiver.kt
@@ -0,0 +1,46 @@
+package dev.lelonio.square.update
+
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageInstaller
+
+/**
+ * Carries the installer's answer back.
+ *
+ * The first thing a session reports is [PackageInstaller.STATUS_PENDING_USER_ACTION],
+ * and the intent inside it *is* the confirmation dialog: without starting it the
+ * install waits for an approval nobody is ever asked for, which looks exactly
+ * like a download that silently did nothing.
+ */
+class InstallReceiver : BroadcastReceiver() {
+
+ override fun onReceive(context: Context, intent: Intent) {
+ when (intent.getIntExtra(PackageInstaller.EXTRA_STATUS, -1)) {
+ PackageInstaller.STATUS_PENDING_USER_ACTION -> {
+ val confirm = if (android.os.Build.VERSION.SDK_INT >= 33) {
+ intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
+ } else {
+ @Suppress("DEPRECATION")
+ intent.getParcelableExtra<Intent>(Intent.EXTRA_INTENT)
+ }
+ confirm?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ confirm?.let(context::startActivity)
+ }
+
+ PackageInstaller.STATUS_SUCCESS ->
+ android.util.Log.i(TAG, "update installed")
+
+ else -> {
+ // The message names the package and the failure, nothing the
+ // user typed.
+ val message = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE)
+ android.util.Log.w(TAG, "install did not complete: $message")
+ }
+ }
+ }
+
+ private companion object {
+ const val TAG = "InstallReceiver"
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/update/Updater.kt b/app/src/main/java/dev/lelonio/square/update/Updater.kt
new file mode 100644
index 0000000..5fe81df
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/update/Updater.kt
@@ -0,0 +1,232 @@
+package dev.lelonio.square.update
+
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageInstaller
+import android.net.Uri
+import android.os.Build
+import android.provider.Settings
+import dev.lelonio.square.BuildConfig
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import java.io.File
+
+/**
+ * Updates the app from its own GitHub releases.
+ *
+ * Square cannot go on the Play Store — it re-implements a protocol whose terms
+ * forbid it — so there is nothing to deliver an update but the app itself. The
+ * releases page is already the distribution channel; this reads it.
+ *
+ * Nothing here has to verify what it downloads. Android refuses an update
+ * signed with a different key than the installed copy, so an APK that is not
+ * the one built with the project's keystore simply fails to install. A hash
+ * check on top would look reassuring and add nothing the platform does not
+ * already enforce.
+ */
+class Updater(context: Context) {
+
+ private val app = context.applicationContext
+ private val json = Json { ignoreUnknownKeys = true }
+ private val client = OkHttpClient()
+
+ private val _state = MutableStateFlow<State>(State.Idle)
+ val state: StateFlow<State> = _state.asStateFlow()
+
+ sealed interface State {
+ data object Idle : State
+ data object Checking : State
+ data object UpToDate : State
+ data class Available(val version: String, val url: String, val bytes: Long) : State
+ /** 0f..1f, or null while the server sends no length to measure against. */
+ data class Downloading(val progress: Float?) : State
+ /** Handed to the system installer; the dialog is Android's, not ours. */
+ data object Installing : State
+ data class Failed(val reason: String) : State
+ }
+
+ /**
+ * Asks GitHub what the latest release is.
+ *
+ * Unauthenticated, which allows sixty requests an hour per address — far
+ * more than a button can spend. It is still a request the user did not ask
+ * for, which is why nothing here runs on its own: it is called when the
+ * button is pressed and at no other time.
+ */
+ suspend fun check() {
+ _state.value = State.Checking
+ val result = runCatching { withContext(Dispatchers.IO) { latestRelease() } }
+ .getOrElse {
+ android.util.Log.w(TAG, "check failed: $it")
+ _state.value = State.Failed(it.message ?: "network")
+ return
+ }
+
+ if (result == null || !isNewer(result.version, BuildConfig.VERSION_NAME)) {
+ _state.value = State.UpToDate
+ return
+ }
+ _state.value = State.Available(result.version, result.url, result.bytes)
+ }
+
+ private data class Release(val version: String, val url: String, val bytes: Long)
+
+ private fun latestRelease(): Release? {
+ val request = Request.Builder()
+ .url("https://api.github.com/repos/$REPO/releases/latest")
+ .header("Accept", "application/vnd.github+json")
+ .build()
+
+ client.newCall(request).execute().use { response ->
+ if (!response.isSuccessful) error("HTTP ${response.code}")
+ val body = json.parseToJsonElement(response.body?.string().orEmpty()) as? JsonObject
+ ?: return null
+ val tag = body["tag_name"]?.jsonPrimitive?.content?.removePrefix("v") ?: return null
+ val asset = (body["assets"] as? JsonArray)
+ ?.filterIsInstance<JsonObject>()
+ ?.firstOrNull { it["name"]?.jsonPrimitive?.content?.endsWith(".apk") == true }
+ ?: return null
+ val url = asset["browser_download_url"]?.jsonPrimitive?.content ?: return null
+ val size = asset["size"]?.jsonPrimitive?.content?.toLongOrNull() ?: 0L
+ return Release(tag, url, size)
+ }
+ }
+
+ /**
+ * Downloads the APK and hands it to the system installer.
+ *
+ * The confirmation dialog is Android's and cannot be skipped: only a system
+ * app installs silently. That is the right outcome — an app that could
+ * replace itself unattended is one the user has to trust rather more than
+ * this one asks to be trusted.
+ */
+ suspend fun install(update: State.Available) {
+ if (!canInstall()) {
+ _state.value = State.Failed(REASON_PERMISSION)
+ return
+ }
+
+ _state.value = State.Downloading(null)
+ val apk = runCatching { withContext(Dispatchers.IO) { download(update) } }
+ .getOrElse {
+ android.util.Log.w(TAG, "download failed: $it")
+ _state.value = State.Failed(it.message ?: "download")
+ return
+ }
+
+ runCatching { withContext(Dispatchers.IO) { commit(apk) } }
+ .onSuccess { _state.value = State.Installing }
+ .onFailure {
+ android.util.Log.w(TAG, "install failed: $it")
+ apk.delete()
+ _state.value = State.Failed(it.message ?: "install")
+ }
+ }
+
+ private fun download(update: State.Available): File {
+ // cacheDir, not filesDir: once the installer has read it the file is
+ // dead weight, and twenty megabytes is worth letting the system reclaim
+ // if the install never happens.
+ val target = File(app.cacheDir, "update.apk")
+ target.delete()
+
+ val request = Request.Builder().url(update.url).build()
+ client.newCall(request).execute().use { response ->
+ if (!response.isSuccessful) error("HTTP ${response.code}")
+ val body = response.body ?: error("empty body")
+ val total = body.contentLength().takeIf { it > 0 } ?: update.bytes
+ var written = 0L
+
+ body.byteStream().use { input ->
+ target.outputStream().use { output ->
+ val buffer = ByteArray(64 * 1024)
+ while (true) {
+ val read = input.read(buffer)
+ if (read < 0) break
+ output.write(buffer, 0, read)
+ written += read
+ if (total > 0) {
+ _state.value = State.Downloading(written.toFloat() / total)
+ }
+ }
+ }
+ }
+ }
+ return target
+ }
+
+ private fun commit(apk: File) {
+ val installer = app.packageManager.packageInstaller
+ val params = PackageInstaller.SessionParams(
+ PackageInstaller.SessionParams.MODE_FULL_INSTALL,
+ )
+ val sessionId = installer.createSession(params)
+ installer.openSession(sessionId).use { session ->
+ session.openWrite("square", 0, apk.length()).use { output ->
+ apk.inputStream().use { it.copyTo(output) }
+ session.fsync(output)
+ }
+ session.commit(
+ PendingIntent.getBroadcast(
+ app,
+ 0,
+ Intent(app, InstallReceiver::class.java)
+ .setPackage(app.packageName),
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE,
+ ).intentSender,
+ )
+ }
+ apk.delete()
+ }
+
+ /** Whether the user has allowed this app to install packages at all. */
+ fun canInstall(): Boolean =
+ Build.VERSION.SDK_INT < Build.VERSION_CODES.O || app.packageManager.canRequestPackageInstalls()
+
+ /** The settings page where that permission is granted. */
+ fun permissionIntent(): Intent =
+ Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
+ .setData(Uri.parse("package:${app.packageName}"))
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+
+ fun dismiss() {
+ _state.value = State.Idle
+ }
+
+ companion object {
+ private const val TAG = "Updater"
+
+ const val REPO = "Lelonio/Square"
+
+ /** Told apart from a network failure so the UI can offer the way out. */
+ const val REASON_PERMISSION = "permission"
+
+ /**
+ * Compares two dotted versions numerically.
+ *
+ * String comparison would put 1.10.0 before 1.9.0, which is exactly the
+ * release where a self-updater stops offering updates and nobody
+ * notices for a month.
+ */
+ fun isNewer(candidate: String, installed: String): Boolean {
+ val a = candidate.split('.').map { it.takeWhile(Char::isDigit).toIntOrNull() ?: 0 }
+ val b = installed.split('.').map { it.takeWhile(Char::isDigit).toIntOrNull() ?: 0 }
+ for (i in 0 until maxOf(a.size, b.size)) {
+ val left = a.getOrElse(i) { 0 }
+ val right = b.getOrElse(i) { 0 }
+ if (left != right) return left > right
+ }
+ return false
+ }
+ }
+}
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index 2c65caa..b6b62a2 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -168,4 +168,13 @@
<string name="language">Sprache</string>
<string name="system_language">Sprache des Telefons</string>
<string name="presets">VOREINSTELLUNGEN</string>
+ <string name="check_for_updates">Nach Updates suchen</string>
+ <string name="update_checking">Wird geprüft…</string>
+ <string name="update_none">Aktuell</string>
+ <string name="update_available">%1$s verfügbar</string>
+ <string name="update_install">Update installieren</string>
+ <string name="update_downloading">Wird geladen…</string>
+ <string name="update_installing">Warte auf deine Bestätigung</string>
+ <string name="update_needs_permission">Installation erlauben — tippen</string>
+ <string name="update_failed">Gerade nicht — zum Wiederholen tippen</string>
</resources>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 98a3097..d2baf04 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -168,4 +168,13 @@
<string name="language">Idioma</string>
<string name="system_language">Idioma del teléfono</string>
<string name="presets">AJUSTES</string>
+ <string name="check_for_updates">Buscar actualizaciones</string>
+ <string name="update_checking">Comprobando…</string>
+ <string name="update_none">Ya está al día</string>
+ <string name="update_available">%1$s disponible</string>
+ <string name="update_install">Instalar la actualización</string>
+ <string name="update_downloading">Descargando…</string>
+ <string name="update_installing">Esperando tu confirmación</string>
+ <string name="update_needs_permission">Permite la instalación — toca</string>
+ <string name="update_failed">Ahora no — toca para reintentar</string>
</resources>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index f960f98..5869eea 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -168,4 +168,13 @@
<string name="language">Langue</string>
<string name="system_language">Langue du téléphone</string>
<string name="presets">PRÉRÉGLAGES</string>
+ <string name="check_for_updates">Rechercher des mises à jour</string>
+ <string name="update_checking">Vérification…</string>
+ <string name="update_none">À jour</string>
+ <string name="update_available">%1$s disponible</string>
+ <string name="update_install">Installer la mise à jour</string>
+ <string name="update_downloading">Téléchargement…</string>
+ <string name="update_installing">En attente de votre confirmation</string>
+ <string name="update_needs_permission">Autorisez l\'installation — touchez</string>
+ <string name="update_failed">Pas maintenant — touchez pour réessayer</string>
</resources>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index de7503b..f340033 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -169,4 +169,13 @@
<string name="language">Lingua</string>
<string name="system_language">Lingua del telefono</string>
<string name="presets">PREIMPOSTAZIONI</string>
+ <string name="check_for_updates">Cerca aggiornamenti</string>
+ <string name="update_checking">Controllo…</string>
+ <string name="update_none">Già aggiornata</string>
+ <string name="update_available">%1$s disponibile</string>
+ <string name="update_install">Installa l\'aggiornamento</string>
+ <string name="update_downloading">Scarico…</string>
+ <string name="update_installing">Aspetto la tua conferma</string>
+ <string name="update_needs_permission">Consenti l\'installazione — tocca</string>
+ <string name="update_failed">Non adesso — tocca per riprovare</string>
</resources>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index bca8705..c606e0a 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -168,4 +168,13 @@
<string name="language">Idioma</string>
<string name="system_language">Idioma do telefone</string>
<string name="presets">PREDEFINIÇÕES</string>
+ <string name="check_for_updates">Procurar atualizações</string>
+ <string name="update_checking">A verificar…</string>
+ <string name="update_none">Já atualizada</string>
+ <string name="update_available">%1$s disponível</string>
+ <string name="update_install">Instalar a atualização</string>
+ <string name="update_downloading">A transferir…</string>
+ <string name="update_installing">À espera da tua confirmação</string>
+ <string name="update_needs_permission">Permite a instalação — toca</string>
+ <string name="update_failed">Agora não — toca para tentar de novo</string>
</resources>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 776ffcc..3da42ff 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -189,4 +189,13 @@
<string name="language">Language</string>
<string name="system_language">Phone language</string>
<string name="presets">PRESETS</string>
+ <string name="check_for_updates">Check for updates</string>
+ <string name="update_checking">Checking…</string>
+ <string name="update_none">Up to date</string>
+ <string name="update_available">%1$s available</string>
+ <string name="update_install">Install the update</string>
+ <string name="update_downloading">Downloading…</string>
+ <string name="update_installing">Waiting for you to confirm</string>
+ <string name="update_needs_permission">Allow installing — tap</string>
+ <string name="update_failed">Not now — tap to retry</string>
</resources>