Check, compare, ask for the link later
The releases endpoint is public, and what it returns depends on the key. With a license that is valid for the product, the answer holds the version, the notes and signed download links. With no key, or a key that is expired or for another product, it holds only version and published_at. That is not an error: the code below reports canDownload = false and your app can say a new version exists.
The checker has no Android classes. It reuses ApiResponse from the validation page and needs no dependency beyond kotlinx-serialization-json. It never asks for a download link until the user accepts, because a link is valid for one hour and an update prompt can wait longer.
// UpdateChecker.kt: no Android classes. Pass BuildConfig.VERSION_NAME on Android.
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
/** SemVer precedence: 4.0.0 is newer than 4.0.0-beta.2, and 3.10.0 is newer than 3.9.0. */
class Version private constructor(private val core: List<Long>, private val pre: List<String>) : Comparable<Version> {
override fun compareTo(other: Version): Int {
for (i in 0..2) core[i].compareTo(other.core[i]).let { if (it != 0) return it }
if (pre.isEmpty() || other.pre.isEmpty()) return other.pre.size.compareTo(pre.size) // a release beats its prereleases
for (i in 0 until minOf(pre.size, other.pre.size)) {
val (a, b) = pre[i] to other.pre[i]
val (x, y) = a.toLongOrNull() to b.toLongOrNull()
val c = when {
x != null && y != null -> x.compareTo(y)
x != null -> -1 // numbers rank below words
y != null -> 1
else -> a.compareTo(b)
}
if (c != 0) return c
}
return pre.size.compareTo(other.pre.size)
}
companion object {
private val pattern = Regex("""^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$""")
/** Null for anything that is not x.y.z, such as "3.2". */
fun parse(text: String): Version? {
val m = pattern.matchEntire(text.trim()) ?: return null
val (major, minor, patch, pre) = m.destructured
return Version(listOf(major.toLong(), minor.toLong(), patch.toLong()), if (pre.isEmpty()) emptyList() else pre.split('.'))
}
}
}
@Serializable
private data class ReleaseFile(val filename: String, val size: Long = 0, val platform: String? = null, val url: String? = null)
@Serializable
private data class Release(
val version: String,
val notes: String? = null,
@SerialName("published_at") val publishedAt: String? = null,
val files: List<ReleaseFile>? = null, // absent unless the key is valid for this product
)
interface ReleasesApi {
/** GET /v1/releases/{productId}/latest?platform=..., with the key in the X-License-Key header when there is one. */
suspend fun latest(productId: Long, platform: String, licenseKey: String?): ApiResponse
}
data class Update(val version: String, val notes: String?, val canDownload: Boolean)
data class DownloadLink(val filename: String, val size: Long, val url: String)
class UpdateChecker(
private val api: ReleasesApi,
private val productId: Long,
private val currentVersion: String,
private val platform: String, // the label you gave your uploads, for example "android" or "macos"
) {
private val json = Json { ignoreUnknownKeys = true }
/** Null when there is nothing newer, nothing published, or no answer. Run it once a day. */
suspend fun check(licenseKey: String?): Update? {
val release = fetch(licenseKey) ?: return null
val next = Version.parse(release.version) ?: return null
val current = Version.parse(currentVersion) ?: return null
if (next <= current) return null
// Without a valid key the answer holds only the version: say an update exists, and why it cannot be fetched.
return Update(release.version, release.notes, release.files.orEmpty().any { it.url != null })
}
/** Call this when the user taps Update. The signed link lasts one hour, so ask for it now, not at check time. */
suspend fun downloadLink(licenseKey: String?): DownloadLink? {
val file = fetch(licenseKey)?.files?.firstOrNull { it.url != null } ?: return null
val url = file.url ?: return null
return DownloadLink(file.filename.substringAfterLast('/').substringAfterLast('\\'), file.size, url) // never trust a path
}
private suspend fun fetch(licenseKey: String?): Release? {
val reply = api.latest(productId, platform, licenseKey)
if (reply.status != 200) return null // 404: nothing published. 429, 5xx, 0: try again later
return runCatching { json.decodeFromString<Release>(reply.body) }.getOrNull()
}
}
The Android and OkHttp side
The adapter is a plain GET with the key in a header, which keeps it out of URLs and logs. For the once-a-day schedule on Android, a PeriodicWorkRequest with a network constraint is the idiomatic choice. Its minimum interval is 15 minutes, and the system decides the exact time, which suits a daily check. A desktop app can keep a timestamp in its license file.
// Adapters. OkHttp as on the validation page. Not run here.
class OkHttpReleasesApi(
private val client: OkHttpClient = OkHttpClient.Builder().callTimeout(5, TimeUnit.SECONDS).build(),
) : ReleasesApi {
override suspend fun latest(productId: Long, platform: String, licenseKey: String?): ApiResponse = withContext(Dispatchers.IO) {
val request = Request.Builder()
.url("$BASE/v1/releases/$productId/latest?platform=$platform")
.apply { if (licenseKey != null) header("X-License-Key", licenseKey) }
.build()
try {
client.newCall(request).execute().use {
ApiResponse(it.code, it.header("Retry-After")?.toLongOrNull(), it.body?.string().orEmpty())
}
} catch (e: IOException) {
ApiResponse(0, null, "") // offline, DNS failure or timeout
}
}
}
// Android: DownloadManager retries across failures, connectivity changes and reboots, so a large APK survives a tunnel.
fun startDownload(context: Context, link: DownloadLink): Long {
val request = DownloadManager.Request(Uri.parse(link.url))
.setTitle(link.filename)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, link.filename)
return (context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager).enqueue(request)
}
Installing the downloaded APK is the app’s job and the user’s decision. The manifest reference says apps targeting API 26 or higher must hold REQUEST_INSTALL_PACKAGES to use the install intent. If you ship on Google Play, Play delivers updates and none of this applies. On a desktop JVM, Desktop.getDesktop().open(file) opens the downloaded installer, and the label is macos, windows or linux.
Versions
BuildConfig.VERSION_NAME is a string such as 1.4.0, and the comparison must follow SemVer precedence. We ran the SemVer specification’s own ordering, from 1.0.0-alpha through 1.0.0-rc.1 to 1.0.0, and the Version class kept every pair in order. Other results:
| Running | Published | Offered? |
|---|---|---|
4.0.0-beta.2 |
4.0.0 |
yes |
3.9.0 |
3.10.0 |
yes |
3.2.1 |
3.2.1 |
no |
1.4.0-debug |
1.4.0 |
yes, because the suffix makes it a prerelease |
3.1.0 |
3.2 |
no: 3.2 does not parse as x.y.z |
Clavem accepts release versions such as 3.2 or 2026.11, which the parser rejects, so the checker reports no update. Publish three-part versions. Latest means the most recently published release, not the highest number: a backport published after 4.0.0 becomes latest.
What ran
The checker ran on a JVM 17 with Kotlin 2.4.21 against scripted responses. A valid key returned the notes with canDownload = true, no key returned canDownload = false, and the same version, 404, 429, status 0 and an HTML page from a captive portal all returned null. A file name of ../../evil\x.apk came back as x.apk. The live demo product has no release published, so its endpoint answers 404 with { "error": { "code": "not_found", "message": "This product has no published release yet." } }.
Doing this with Clavem
Upload a release once in the dashboard. Buyers download it from their order page, and your app uses this endpoint, which has its own budget of 120 requests per minute per IP, separate from validation. See releases and downloads for storage and link behavior.
Questions
Why does my debug build keep offering the release as an update?
A versionNameSuffix such as -debug turns 1.4.0 into 1.4.0-debug, which SemVer ranks below 1.4.0. The release therefore looks newer. Skip the check in debug builds, or compare against a version name without the suffix.
Can an Android app install the update it downloads?
Only if it declares REQUEST_INSTALL_PACKAGES, which the Android manifest reference requires for apps targeting API 26 or higher that use the install intent, and only with the user's consent. If the app is on Google Play, Play delivers updates and this check is not needed.