package tv.tivilux.nativeplayer.data import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import android.provider.Settings import androidx.core.content.FileProvider import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.json.JSONObject import tv.tivilux.nativeplayer.BuildConfig import java.io.File import java.io.FileOutputStream import java.net.HttpURLConnection import java.net.URL import java.security.MessageDigest /** * Small self-update client for the sideloaded TiviLux APK. * * The manifest is intentionally tiny so launch-time update checks put almost no load on * the APK hosting server. Android still owns the final install confirmation screen. */ data class AppUpdateInfo( val versionCode: Int, val versionName: String, val apkUrl: String, val required: Boolean = false, val notes: List = emptyList(), val sha256: String = "", ) class AppUpdateManager(private val context: Context) { private val prefs = context.getSharedPreferences("tivilux_update_check", Context.MODE_PRIVATE) private val checkIntervalMs = 4L * 60L * 60L * 1000L suspend fun checkForUpdate(force: Boolean = false): AppUpdateInfo? = withContext(Dispatchers.IO) { val manifestUrl = BuildConfig.UPDATE_MANIFEST_URL.trim() if (manifestUrl.isBlank()) return@withContext null val now = System.currentTimeMillis() val cachedText = prefs.getString("cached_manifest", null) val lastCheck = prefs.getLong("last_successful_check", 0L) if (!force && cachedText != null && now - lastCheck < checkIntervalMs) { return@withContext parseManifest(cachedText) } var connection: HttpURLConnection? = null try { connection = (URL(manifestUrl).openConnection() as HttpURLConnection).apply { requestMethod = "GET" connectTimeout = 3_500 readTimeout = 5_000 useCaches = true setRequestProperty("Accept", "application/json") setRequestProperty("User-Agent", "TiviLux-Native/${BuildConfig.VERSION_NAME} AndroidTV") } val code = connection.responseCode if (code !in 200..299) { if (cachedText != null) return@withContext parseManifest(cachedText) if (force) throw IllegalStateException("Update server returned HTTP $code") return@withContext null } val text = connection.inputStream.bufferedReader().use { it.readText() } prefs.edit() .putString("cached_manifest", text) .putLong("last_successful_check", now) .apply() parseManifest(text) } catch (t: Throwable) { if (cachedText != null) parseManifest(cachedText) else if (force) throw t else null } finally { connection?.disconnect() } } private fun parseManifest(text: String): AppUpdateInfo? = runCatching { val root = JSONObject(text) val remoteCode = root.optInt("versionCode", 0) val remoteName = root.optString("versionName", remoteCode.toString()) val apkUrl = root.optString("apkUrl").trim() if (remoteCode <= BuildConfig.VERSION_CODE || apkUrl.isBlank()) return@runCatching null val notes = buildList { val array = root.optJSONArray("notes") if (array != null) { for (i in 0 until array.length()) { array.optString(i).trim().takeIf { it.isNotBlank() }?.let { add(it) } } } else { root.optString("notes").trim().takeIf { it.isNotBlank() }?.let { add(it) } } } AppUpdateInfo( versionCode = remoteCode, versionName = remoteName, apkUrl = apkUrl, required = root.optBoolean("required", false), notes = notes, sha256 = root.optString("sha256").trim().lowercase(), ) }.getOrNull() fun canInstallPackages(): Boolean = Build.VERSION.SDK_INT < Build.VERSION_CODES.O || context.packageManager.canRequestPackageInstalls() fun openInstallPermission() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return val intent = Intent( Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:${context.packageName}") ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(intent) } suspend fun downloadUpdate( update: AppUpdateInfo, onProgress: (Int) -> Unit, ): File = withContext(Dispatchers.IO) { val updateDir = File(context.cacheDir, "updates").apply { mkdirs() } updateDir.listFiles()?.forEach { if (it.name.endsWith(".apk")) it.delete() } val temp = File(updateDir, "TiviLux-${update.versionName}.apk.part") val output = File(updateDir, "TiviLux-${update.versionName}.apk") var lastProgress = -1 suspend fun reportProgress(value: Int) { val normalized = value.coerceIn(0, 100) if (normalized == lastProgress) return lastProgress = normalized withContext(Dispatchers.Main.immediate) { onProgress(normalized) } } val connection = (URL(update.apkUrl).openConnection() as HttpURLConnection).apply { requestMethod = "GET" connectTimeout = 10_000 readTimeout = 60_000 instanceFollowRedirects = true useCaches = false setRequestProperty("Accept", "application/vnd.android.package-archive,*/*") setRequestProperty("User-Agent", "TiviLux-Native/${BuildConfig.VERSION_NAME} AndroidTV") } try { val code = connection.responseCode if (code !in 200..299) throw IllegalStateException("Update server returned HTTP $code") val total = connection.getHeaderField("Content-Length")?.toLongOrNull()?.coerceAtLeast(0L) ?: 0L var copied = 0L connection.inputStream.buffered(128 * 1024).use { input -> FileOutputStream(temp).buffered(128 * 1024).use { out -> val buffer = ByteArray(128 * 1024) while (true) { val count = input.read(buffer) if (count <= 0) break out.write(buffer, 0, count) copied += count if (total > 0L) reportProgress(((copied * 100L) / total).toInt()) } } } if (temp.length() <= 0L) throw IllegalStateException("Downloaded update was empty") if (update.sha256.isNotBlank()) { val actual = sha256(temp) if (!actual.equals(update.sha256, ignoreCase = true)) { temp.delete() throw IllegalStateException("Update integrity check failed") } } if (output.exists()) output.delete() if (!temp.renameTo(output)) { temp.copyTo(output, overwrite = true) temp.delete() } reportProgress(100) output } finally { connection.disconnect() } } fun launchInstaller(apk: File) { val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", apk) val intent = Intent(Intent.ACTION_VIEW).apply { setDataAndType(uri, "application/vnd.android.package-archive") addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) } context.startActivity(intent) } private fun sha256(file: File): String { val digest = MessageDigest.getInstance("SHA-256") file.inputStream().buffered(128 * 1024).use { input -> val buffer = ByteArray(128 * 1024) while (true) { val count = input.read(buffer) if (count <= 0) break digest.update(buffer, 0, count) } } return digest.digest().joinToString("") { "%02x".format(it) } } }