Clavem

Software update checks and downloads in a Python app

GET /v1/releases/<product id>/latest with the license key in the X-License-Key header, compare versions with packaging.version, and stream the installer to a .part file with Range resume. Request the download link when the user confirms, because it lasts one hour.

Clavem stores your builds and answers GET /v1/releases/:productId/latest. A license that is valid for the product gets release notes and files with signed download links. Any other key gets only version and published_at. The release docs list the fields. This page is the Python side: the check, the version comparison, a download that can resume, and what to do with the file. The key comes from the keyring, as on the validation page.

Check

import json
import platform
import sys
import urllib.error
import urllib.parse
import urllib.request

from packaging.version import InvalidVersion, Version

BASE = "https://clavem.io"


def platform_label() -> str:
    """The label you chose at upload, for example darwin-arm64, win32-amd64 or linux-x86_64."""
    return f"{sys.platform}-{platform.machine().lower()}"


def _get(url: str, headers: dict | None = None, timeout: float = 8):
    request = urllib.request.Request(url, headers={"User-Agent": "Inkwell/3.2", **(headers or {})})
    return urllib.request.urlopen(request, timeout=timeout)


def check_for_update(current: str, product_id: int, license_key: str | None, *, base: str = BASE) -> dict:
    """{'state': 'up-to-date' | 'available' | 'locked' | 'failed', ...}"""
    query = urllib.parse.urlencode({"platform": platform_label()})
    headers = {"X-License-Key": license_key} if license_key else None   # a header keeps the key out of logs
    try:
        with _get(f"{base}/v1/releases/{product_id}/latest?{query}", headers) as response:
            release = json.load(response)
    except urllib.error.HTTPError as error:
        if error.code == 404:
            return {"state": "up-to-date"}                              # nothing published yet
        if error.code == 429:
            return {"state": "failed", "reason": f"rate limited, retry in {error.headers.get('Retry-After', '60')} s"}
        return {"state": "failed", "reason": f"HTTP {error.code}"}
    except (OSError, ValueError):
        return {"state": "failed", "reason": "offline"}
    try:
        newer = Version(release["version"]) > Version(current)
    except (InvalidVersion, KeyError):
        return {"state": "failed", "reason": "version is not valid"}
    if not newer:
        return {"state": "up-to-date"}
    file = next((f for f in release.get("files", []) if f.get("url")), None)
    if file is None:
        return {"state": "locked", "version": release["version"]}      # newer, but the key is missing or not valid
    return {"state": "available", "version": release["version"], "notes": release.get("notes"), "file": file}

HTTPError is raised for every 4xx and 5xx, so the 404 for “no release yet” and the 429 arrive as exceptions with headers. Against a local stub with release 3.2.1, and one live call, the function returned:

label: darwin-arm64
with key: available 3.2.1 inkwell-3.2.1.zip
without key: {'state': 'locked', 'version': '3.2.1'}
app 3.2.1rc1: available | app 3.10.0: {'state': 'up-to-date'}
other product: {'state': 'up-to-date'}
live demo product: {'state': 'up-to-date'}

The live call is real: the demo product has no published release, and the API answers 404 with not_found, which the code maps to nothing to offer. An app on 3.2.1rc1 is offered 3.2.1, because packaging sorts a release candidate below its release. The first line shows a label trap. The stub’s files were labelled macos and windows, one had no label, and the app asked for darwin-arm64, so only the unlabelled .zip came back. Make your upload labels match what the app sends.

locked deserves its own message. A lapsed customer learns that 3.2.1 exists and can be sent to renew. Only a valid key adds download links.

Download, with resume

Do not store the link from the check. It lasts one hour. Check again when the user clicks Update, then download from that fresh response:

import os
from pathlib import Path


def download(file: dict, destination: Path, on_percent=lambda pct: None) -> Path:
    part = destination.with_name(destination.name + ".part")
    have = part.stat().st_size if part.exists() else 0
    if have > file["size"]:
        part.unlink()
        have = 0
    if have < file["size"]:
        headers = {"Range": f"bytes={have}-"} if have else {}
        try:
            response = _get(file["url"], headers, timeout=30)  # a socket timeout, not a limit on the whole download
        except urllib.error.HTTPError as error:
            if error.code == 403:
                raise RuntimeError("The download link expired. Check for updates again.") from error
            raise
        with response:
            if response.status == 200:
                have = 0                                       # the server ignored Range: start over
            last = -1
            with open(part, "ab" if response.status == 206 else "wb") as out:
                while chunk := response.read(1 << 16):
                    out.write(chunk)
                    have += len(chunk)
                    if (pct := have * 100 // file["size"]) != last:
                        last = pct
                        on_percent(pct)
                out.flush()
                os.fsync(out.fileno())
    if part.stat().st_size != file["size"]:
        raise RuntimeError("Size does not match. Keep the .part file and resume.")
    os.replace(part, destination)                              # atomic on the same filesystem
    return destination

With 1 MiB already in the .part file of a 3 MiB download it resumed, finished at 3,145,728 bytes and reported 32 percent events from 35 to 100. A link with a bad signature raised the expired-link error, which is the 403 path, and a file declared 10 bytes too large raised the size error. The timeout on urlopen is a socket timeout, so a long download is fine as long as bytes keep arriving. The response has no checksum field, so size is the only integrity check Clavem provides. Sign what you ship and let the operating system check the signature.

What to do with the file

  • A package or a script. Update through pip, or replace the files, and ask the user to restart.
  • A frozen executable on macOS or Linux. os.replace the new file over the old one, mark it executable with os.chmod, and restart.
  • A frozen executable on Windows. A running .exe cannot be overwritten. Download the installer or the new executable, start it with os.startfile, and exit.
  • A desktop app on macOS. Download the DMG and open it with subprocess.run(["open", path]). The customer drags the new app over the old one.

Run the update code in a worker thread so a GUI stays responsive, and stream progress to it through on_percent.

Limits and timing

The releases endpoint allows 120 requests a minute per IP address, counted apart from validation. Check once at launch or once a day. “Latest” means the most recently published release, not the highest version number, so a backport published after 3.2.1 becomes the answer. See the release docs for storage and file limits.

Doing this with Clavem

Upload each build once in the dashboard, give it a platform label and publish. The same key that turns the app on fetches the download. Licenses imported from Lemon Squeezy have no order page, so for them this endpoint is how builds are delivered.

Questions

How do I compare version strings in Python?

Use packaging.version.Version. It parses 3.10.0, orders it above 3.9.0, and puts pre-releases such as 3.2.1rc1 below 3.2.1. Plain string comparison gets 3.10.0 wrong, and comparing tuples of ints cannot read pre-release tags.

Can a Python program update itself in place?

A script or a package can be updated by pip or by replacing files. A frozen executable cannot overwrite itself while it runs on Windows, so download the new installer or executable and start it. Replace files with os.replace, which is atomic on one filesystem.

What platform label should I request?

The label you used when uploading each file. A label built from sys.platform and platform.machine, such as darwin-arm64, is simple to keep consistent. Files with no label are offered to every platform.