Files
WeekFocus/app/src/main/java/de/schanbro/weekfocus/update/UpdateChecker.kt
T
2026-10-30 13:34:34 +01:00

88 lines
3.1 KiB
Kotlin

package de.schanbro.weekfocus.update
import android.content.Context
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
import org.json.JSONArray
data class ReleaseInfo(
val version: String,
val notes: String,
val apkUrl: String
)
object UpdateChecker {
private const val RELEASES_URL =
"https://git.schamagusa.de/api/v1/repos/robin/WeekFocus/releases"
suspend fun fetchLatestRelease(includePrereleases: Boolean = false): ReleaseInfo? =
withContext(Dispatchers.IO) {
try {
if (includePrereleases) {
val body = httpGet("$RELEASES_URL?limit=10") ?: return@withContext null
val array = JSONArray(body)
(0 until array.length())
.map { array.getJSONObject(it) }
.firstNotNullOfOrNull { toRelease(it) }
} else {
val body = httpGet("$RELEASES_URL/latest") ?: return@withContext null
toRelease(JSONObject(body))
}
} catch (e: Exception) {
null
}
}
private fun httpGet(url: String): String? {
val conn = URL(url).openConnection() as HttpURLConnection
conn.connectTimeout = 10_000
conn.readTimeout = 10_000
conn.setRequestProperty("Accept", "application/json")
return try {
if (conn.responseCode == HttpURLConnection.HTTP_OK) {
conn.inputStream.bufferedReader().use { it.readText() }
} else null
} finally {
conn.disconnect()
}
}
private fun toRelease(json: JSONObject): ReleaseInfo? {
if (json.optBoolean("draft", false)) return null
val assets = json.getJSONArray("assets")
val apk = (0 until assets.length())
.map { assets.getJSONObject(it) }
.firstOrNull { it.getString("name").endsWith(".apk", ignoreCase = true) }
?: return null
return ReleaseInfo(
version = json.getString("tag_name"),
notes = json.optString("body", ""),
apkUrl = apk.getString("browser_download_url")
)
}
@Suppress("DEPRECATION")
fun currentVersion(context: Context): String =
context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: "0"
/** Numerischer Vergleich pro Segment, damit 1.2.11 > 1.2.9 gilt. */
fun isNewer(remote: String, local: String): Boolean {
val r = parse(remote)
val l = parse(local)
for (i in 0 until maxOf(r.size, l.size)) {
val a = r.getOrElse(i) { 0 }
val b = l.getOrElse(i) { 0 }
if (a != b) return a > b
}
// Gleiche Nummer: stabiles Release ist neuer als eine installierte Beta
return local.contains("-") && !remote.contains("-")
}
private fun parse(version: String): List<Int> =
version.trim().removePrefix("v").substringBefore("-")
.split(".").map { it.toIntOrNull() ?: 0 }
}