From 85d47204094e438879b9f77e806db5ed724b309e Mon Sep 17 00:00:00 2001 From: professorDeveloper <108933534+professorDeveloper@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:29:18 +0500 Subject: [PATCH] Release: a banner, a full release page and a Telegram post, through Cloudflare Brings the Android TV release up to the phone app's: - Banner: tools/release/release_banner.py draws release/banners/v.svg from the phone app's artwork (ANDROID TV, the version, a tagline, chips), committed with the bump. - Release page: release/notes/v.md when written, otherwise a page built from what was merged since the last tag, with the banner on top, the APK table and how to install it on a TV. - Telegram: the banner as a photo with an HTML caption and buttons, then the APK with what happened under it. Cloudflare answers GitHub's runners with a challenge page, which broke the version guard, the CDN upload and the updater. A challenge is now a warning, and the release carries sozo-tv--release.json so the backend takes the published release itself. The CDN row is updated in place (replacePrevious), so the download count carries on. The tag and bump are pushed with GITHUB_TOKEN; the RELEASE_PAT secret is refused by GitHub. --- .github/workflows/ci.yml | 3 + .github/workflows/release.yml | 240 ++++++++++++++++----- tools/release/banner-template.svg | 106 ++++++++++ tools/release/release_banner.py | 185 ++++++++++++++++ tools/release/release_page.py | 327 +++++++++++++++++++++++++++++ tools/release/release_page_test.py | 90 ++++++++ 6 files changed, 893 insertions(+), 58 deletions(-) create mode 100644 tools/release/banner-template.svg create mode 100644 tools/release/release_banner.py create mode 100644 tools/release/release_page.py create mode 100644 tools/release/release_page_test.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 609c16a8..ba351de9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -59,6 +59,9 @@ jobs: # only, on the screen that uses it. Nothing else in the build sees it. - name: Check the string resources run: python3 tools/check_strings.py + # The release page, banner and Telegram caption the release builds. + - name: Release page tools + run: python3 tools/release/release_page_test.py # The gate the phone app has and this repo did not. Its own job, not a step # inside the assemble, so that the check list on a pull request names "test" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index aa30cf21..6d286c4c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,14 +12,23 @@ run-name: >- # Secrets: # ANDROID_TV_KEYSTORE_B64 base64 of the release keystore (.jks) # ANDROID_TV_KEY_PROPERTIES key.properties: storeFile, storePassword, keyAlias, keyPassword -# RELEASE_PAT fine-grained PAT, Contents: read and write; the default -# branch blocks direct pushes from GITHUB_TOKEN # SOZO_RELEASE_TOKEN backend release token (X-Release-Token); without it the # CDN upload and updater are skipped with a warning # TELEGRAM_BOT_TOKEN bot token from @BotFather # TELEGRAM_CHAT_IDS comma-separated numeric chat ids # Optional variable: SOZO_API_BASE_URL overrides the API address baked into the app. # +# Cloudflare answers GitHub's runners with a challenge page, so the API calls +# below (version guard, CDN, updater) often cannot get through. None of them +# fails the release for that: the backend takes the published GitHub Release +# itself (sozo-backend src/services/appReleaseSync.service.js), using the +# sozo-tv--release.json attached to it. +# +# The release page is release/notes/v.md when somebody wrote one, or +# a page built from what was merged since the last tag, with the banner from +# tools/release/release_banner.py on top (committed with the bump under +# release/banners/). Telegram gets the banner, a caption and the APK. +# # The signing key was replaced on 22 Aug 2026 because the original was lost, and # the version line restarted at 1.0.0 with it. Builds signed by any other key are # refused — see EXPECTED_CERT_SHA256 below. @@ -186,6 +195,10 @@ jobs: HTTP="$(curl -sS --max-time 20 --retry 3 --retry-all-errors \ -A 'sozo-tv-release' -o version.json -w '%{http_code}' \ "${API}/app-version?platform=androidtv")" || HTTP=000 + if [ "${HTTP}" = 403 ] && grep -qiE 'just a moment|cf-chl|challenge-platform' version.json 2>/dev/null; then + echo "::warning title=Version guard skipped::Cloudflare challenged this runner. The backend never moves the updater to a lower versionCode, so a stale build is refused there." + exit 0 + fi PUBLISHED="" if [ "${HTTP}" = 200 ]; then PUBLISHED="$(jq -er '.version // 0' version.json 2>/dev/null)" || PUBLISHED="" @@ -336,7 +349,9 @@ jobs: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: fetch-depth: 0 - token: ${{ secrets.RELEASE_PAT || github.token }} + # GITHUB_TOKEN (contents: write above); master has no rule against it. + # The RELEASE_PAT secret is refused by GitHub (403) since November. + token: ${{ github.token }} - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: @@ -366,7 +381,17 @@ jobs: git config user.email "${GITHUB_ACTOR}@users.noreply.github.com" if [ "${BUMPED}" = yes ]; then python3 tools/release/stamp_version.py "${NAME}" "${CODE}" - git commit -m "chore: ${NAME} (${CODE})" -- app/build.gradle.kts + # The banner goes in with the bump, so the release page can show it + # from this exact commit. One already there is kept. + BANNER="release/banners/v${NAME}.svg" + PREV="$(git describe --tags --abbrev=0 HEAD 2>/dev/null || true)" + git log ${PREV:+"${PREV}..HEAD"} --first-parent --format=%s > "${RUNNER_TEMP}/changes.txt" + python3 tools/release/release_banner.py --version "${NAME}" --out "${BANNER}" \ + --log "${RUNNER_TEMP}/changes.txt" --keep \ + || echo "::warning title=No banner::the release page will have none" + [ -f "${BANNER}" ] && git add "${BANNER}" + git add app/build.gradle.kts + git commit -m "chore: ${NAME} (${CODE})" fi git tag "${TAG}" SHA="$(git rev-parse HEAD)" @@ -395,6 +420,7 @@ jobs: TAG: ${{ needs.version.outputs.tag }} SHA: ${{ steps.tag.outputs.sha }} NOTES: ${{ inputs.notes }} + UPDATER: ${{ inputs.updater }} run: | set -euo pipefail if [ "${MODE}" = skip ]; then @@ -402,11 +428,27 @@ jobs: exit 0 fi - FILES=(dist/*.apk dist/SHA256SUMS) + # What the backend reads when it takes this release from GitHub: the + # versionCode no file name states plainly, the APK, and whether to + # offer it to installed TVs. + APK_NAME="$(basename "$(find dist -name '*.apk' | head -1)")" + jq -n --arg version "${NAME}" --argjson build "${CODE}" --arg sha "${SHA}" \ + --arg notes "${NOTES}" --arg apk "${APK_NAME}" --arg updater "${UPDATER}" \ + '{version: $version, build: $build, sha: $sha, notes: $notes, + updater: ($updater == "publish"), files: [{name: $apk, arch: "universal"}]}' \ + > "dist/sozo-tv-${NAME}-release.json" + + FILES=(dist/*.apk dist/SHA256SUMS "dist/sozo-tv-${NAME}-release.json") if gh release view "${TAG}" >/dev/null 2>&1; then gh release upload "${TAG}" "${FILES[@]}" --clobber else - ARGS=(--target "${SHA}" --title "Sozo TV ${NAME}" --notes "${NOTES:-Sozo TV ${NAME} (versionCode ${CODE})}") + PREV="$(git describe --tags --abbrev=0 "${SHA}^" 2>/dev/null || true)" + git log ${PREV:+"${PREV}..${SHA}"} --first-parent --format=%s > changes.txt + python3 tools/release/release_page.py --version "${NAME}" --sha "${SHA}" \ + --repo "${GH_REPO}" --tag "${TAG}" --assets dist --previous "${PREV}" \ + --log changes.txt --intro "${NOTES}" --auto --out RELEASE_NOTES.md + echo "── notes ──"; cat RELEASE_NOTES.md + ARGS=(--target "${SHA}" --title "Sozo TV ${NAME}" --notes-file RELEASE_NOTES.md) if [ "${MODE}" = draft ]; then ARGS+=(--draft) fi @@ -441,9 +483,8 @@ jobs: name: sozo-tv-apk path: dist - # Not idempotent: re-running this job after the download row was created - # uploads again and adds a second active androidtv row; switch the extra - # one off in the admin panel. + # replacePrevious updates the TV's download row in place, so its download + # count carries on and a re-run does not add a second row. - name: Upload to the CDN id: cdn env: @@ -461,6 +502,17 @@ jobs: API="$(python3 tools/release/api_base.py)" echo "::add-mask::${API}" + # Cloudflare answers GitHub's runners with a challenge page. The + # backend takes the published GitHub Release itself, so step aside. + challenged() { + [ "$1" = 403 ] && grep -qiE 'just a moment|cf-chl|challenge-platform' "$2" 2>/dev/null + } + defer() { + echo "status=deferred" >> "$GITHUB_OUTPUT" + echo "::warning title=CDN deferred to the backend::Cloudflare challenged ${1}. The backend uploads the APK (and updates the updater when asked) within 10 minutes of the GitHub Release being published." + exit 0 + } + APK="$(find dist -name '*.apk' | head -1)" SIZE="$(stat -c%s "${APK}")" @@ -471,6 +523,7 @@ jobs: HTTP="$(curl -sS --max-time 30 -X POST "${API}/admin/downloads/upload-url" \ -H "X-Release-Token: ${SOZO_RELEASE_TOKEN}" -H 'Content-Type: application/json' \ --data @presign-req.json -o presign.json -w '%{http_code}')" || HTTP=000 + if challenged "${HTTP}" presign.json; then defer "POST /admin/downloads/upload-url"; fi if [ "${HTTP}" != 200 ]; then echo "::error title=CDN upload URL::POST /admin/downloads/upload-url returned HTTP ${HTTP}: $(head -c 300 presign.json 2>/dev/null)" exit 1 @@ -493,10 +546,11 @@ jobs: --argjson size "${SIZE}" --arg notes "${NOTES}" \ '{platform: "androidtv", version: $version, arch: "universal", format: "apk", fileUrl: $url, fileKey: $key, fileSize: $size, releaseNotes: $notes, - isBeta: false, active: true}' > download-req.json + active: true, replacePrevious: true}' > download-req.json HTTP="$(curl -sS --max-time 30 -X POST "${API}/admin/downloads" \ -H "X-Release-Token: ${SOZO_RELEASE_TOKEN}" -H 'Content-Type: application/json' \ --data @download-req.json -o download.json -w '%{http_code}')" || HTTP=000 + if challenged "${HTTP}" download.json; then defer "POST /admin/downloads"; fi if [ "${HTTP}" != 201 ]; then echo "::error title=Download row::POST /admin/downloads returned HTTP ${HTTP}: $(head -c 300 download.json 2>/dev/null). The file is on the CDN at ${PUBLIC_URL} but not listed." exit 1 @@ -527,6 +581,10 @@ jobs: echo "status=skipped" >> "$GITHUB_OUTPUT" exit 0 fi + if [ "${CDN}" = deferred ]; then + echo "status=deferred" >> "$GITHUB_OUTPUT" + exit 0 + fi if [ "${CDN}" != uploaded ]; then echo "status=skipped (no CDN upload)" >> "$GITHUB_OUTPUT" echo "::warning title=Updater skipped::updater=publish needs the CDN upload, which did not happen (SOZO_RELEASE_TOKEN missing)." @@ -538,6 +596,11 @@ jobs: HTTP="$(curl -sS --max-time 30 "${API}/admin/app-versions/androidtv" \ -H "X-Release-Token: ${SOZO_RELEASE_TOKEN}" \ -o current.json -w '%{http_code}')" || HTTP=000 + if [ "${HTTP}" = 403 ] && grep -qiE 'just a moment|cf-chl|challenge-platform' current.json; then + echo "status=deferred" >> "$GITHUB_OUTPUT" + echo "::warning title=Updater deferred to the backend::Cloudflare challenged the runner; the backend offers this build once the GitHub Release is published." + exit 0 + fi case "${HTTP}" in 200) ;; 404) echo '{"minVersion": 1, "forceUpdate": false, "active": true}' > current.json ;; @@ -562,6 +625,11 @@ jobs: HTTP="$(curl -sS --max-time 30 -X PUT "${API}/admin/app-versions/androidtv" \ -H "X-Release-Token: ${SOZO_RELEASE_TOKEN}" -H 'Content-Type: application/json' \ --data @updater-req.json -o updated.json -w '%{http_code}')" || HTTP=000 + if [ "${HTTP}" = 403 ] && grep -qiE 'just a moment|cf-chl|challenge-platform' updated.json; then + echo "status=deferred" >> "$GITHUB_OUTPUT" + echo "::warning title=Updater deferred to the backend::Cloudflare challenged the runner; the backend offers this build once the GitHub Release is published." + exit 0 + fi if [ "${HTTP}" != 200 ]; then echo "::error title=Updater write::PUT /admin/app-versions/androidtv returned HTTP ${HTTP}: $(head -c 300 updated.json 2>/dev/null)" exit 1 @@ -577,6 +645,12 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 15 steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + fetch-depth: 0 + ref: ${{ needs.git.outputs.sha || github.sha }} + # Not fatal: when the build failed there is no artifact, and the message # saying so is what this job is for. - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 @@ -585,13 +659,44 @@ jobs: name: sozo-tv-apk path: dist + # The banner as a picture (Telegram cannot show SVG) and the caption. + # Neither is fatal: without them the announcement goes out as text. + - name: Banner and caption for Telegram + continue-on-error: true + env: + NAME: ${{ needs.version.outputs.name }} + NOTES: ${{ inputs.notes }} + run: | + set -uo pipefail + [ -n "${NAME}" ] || exit 0 + PREV="$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || true)" + git log ${PREV:+"${PREV}..HEAD"} --first-parent --format=%s > changes.txt + python3 tools/release/release_page.py --version "${NAME}" --log changes.txt \ + --intro "${NOTES}" --telegram caption.html + python3 tools/release/release_banner.py --version "${NAME}" --still --log changes.txt --out banner.svg + timeout 120 sudo apt-get install -y -qq fonts-inter >/dev/null 2>&1 || true + CHROME="$(command -v google-chrome || command -v chromium || command -v chromium-browser || true)" + if [ -n "${CHROME}" ]; then + "${CHROME}" --headless=new --no-sandbox --disable-gpu --hide-scrollbars \ + --window-size=1280,640 --force-device-scale-factor=2 \ + --screenshot="${PWD}/banner.png" "file://${PWD}/banner.svg" >/dev/null 2>&1 || true + fi + if [ ! -s banner.png ]; then + timeout 120 sudo apt-get install -y -qq librsvg2-bin >/dev/null 2>&1 \ + && rsvg-convert -w 2560 -h 1280 banner.svg -o banner.png || true + fi + ls -l banner.png caption.html || true + echo "── caption ──"; cat caption.html || true + - name: Send to Telegram env: TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }} TELEGRAM_CHAT_IDS: ${{ secrets.TELEGRAM_CHAT_IDS }} VERSION_NAME: ${{ needs.version.outputs.name }} VERSION_CODE: ${{ needs.version.outputs.code }} + TAG: ${{ needs.version.outputs.tag }} RELEASE_NOTES: ${{ inputs.notes }} + UPDATER_MODE: ${{ inputs.updater }} GIT_RESULT: ${{ needs.git.result }} PUBLISH_RESULT: ${{ needs.publish.result }} CDN_STATUS: ${{ needs.publish.outputs.cdn }} @@ -609,6 +714,7 @@ jobs: API="https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}" MAX=$((49 * 1024 * 1024)) # Bot API sendDocument limit is 50 MB RUN_URL="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" + REL_URL="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/releases/tag/${TAG}" IFS=',' read -ra CHATS <<< "${TELEGRAM_CHAT_IDS}" if ! ls dist/*.apk >/dev/null 2>&1; then @@ -626,66 +732,84 @@ jobs: exit 0 fi - if [ "${PUBLISH_RESULT}" = success ]; then - case "${CDN_STATUS}" in - uploaded) CDN_LINE="⬇️ CDN: ${CDN_URL}" ;; - *) CDN_LINE="⬇️ CDN: o'tkazib yuborildi (SOZO_RELEASE_TOKEN yo'q)" ;; - esac - case "${UPDATER_STATUS}" in - published) UPD_LINE="🔄 Updater: versionCode ${VERSION_CODE} e'lon qilindi" ;; - *) UPD_LINE="🔄 Updater: e'lon qilinmadi (${UPDATER_STATUS:-skipped})" ;; - esac - else - CDN_LINE="⚠️ CDN/updater: bajarilmadi (${PUBLISH_RESULT})" - UPD_LINE="" - fi - if [ "${GIT_RESULT}" = success ]; then - GH_LINE="🏷 GitHub Release: ${RELEASE_STATUS:-skipped}" + # 1. The announcement: banner, caption, buttons. A draft's page is + # not public, so only a published release gets its button. + BUTTONS="$(jq -cn --arg cdn "${CDN_URL}" --arg rel "${REL_URL}" \ + --arg cdnok "${CDN_STATUS}" --arg rs "${RELEASE_STATUS}" ' + [ (if $cdnok == "uploaded" and $cdn != "" then [{text: "⬇️ APK yuklab olish", url: $cdn}] else empty end), + (if $rs == "published" then [{text: "📦 Release sahifasi", url: $rel}] else empty end), + [{text: "📣 Kanal", url: "https://t.me/sozoapp"}, {text: "💬 Discord", url: "https://discord.gg/n22URhYvMR"}] ] + | {inline_keyboard: .}')" + PLAIN="$(printf '📺 Sozo TV %s (versionCode %s)' "${VERSION_NAME}" "${VERSION_CODE}")" + if [ -n "${RELEASE_NOTES}" ]; then PLAIN="$(printf '%s\n\n📝 %s' "${PLAIN}" "${RELEASE_NOTES}")"; fi + + # 2. Under the APK: how it gets to TVs, and what happened. + FOOT="$(printf '📺 Sozo TV %s · versionCode %s' "${VERSION_NAME}" "${VERSION_CODE}")" + if [ "${PUBLISH_RESULT}" != success ]; then + FOOT="${FOOT}$(printf '\n❌ CDN/updater yiqildi: %s' "${RUN_URL}")" else - GH_LINE="⚠️ Tag/GitHub Release: bajarilmadi (${GIT_RESULT})" - fi - - HEAD="$(printf '📺 Sozo TV %s (versionCode %s)' "${VERSION_NAME}" "${VERSION_CODE}")" - if [ -n "${RELEASE_NOTES}" ]; then - HEAD="$(printf '%s\n\n📝 %s' "${HEAD}" "${RELEASE_NOTES}")" + case "${CDN_STATUS}:${UPDATER_STATUS}" in + deferred:*|uploaded:deferred) + if [ "${UPDATER_MODE}" = publish ]; then + FOOT="${FOOT}$(printf '\n🔄 Yuklab olish sahifasi va TV ichidagi yangilanish: release Publish qilingach server o‘zi yangilaydi (10 daqiqa ichida).')" + else + FOOT="${FOOT}$(printf '\n🔄 Yuklab olish sahifasi: release Publish qilingach server o‘zi yangilaydi. TV ichidagi yangilanish taklif qilinmaydi.')" + fi ;; + uploaded:published) FOOT="${FOOT}$(printf '\n🔄 Yuklab olish sahifasi va TV ichidagi yangilanish yangilandi.')" ;; + uploaded:*) FOOT="${FOOT}$(printf '\n⬇️ Yuklab olish sahifasi yangilandi; TV ichidagi yangilanish taklif qilinmadi.')" ;; + skipped:*) FOOT="${FOOT}$(printf '\n⚠️ CDN o‘tkazib yuborildi (SOZO_RELEASE_TOKEN yo‘q).')" ;; + esac fi - HEAD="$(printf '%s\n\n%s' "${HEAD}" "${CDN_LINE}")" - if [ -n "${UPD_LINE}" ]; then - HEAD="$(printf '%s\n%s' "${HEAD}" "${UPD_LINE}")" + if [ "${GIT_RESULT}" != success ]; then + FOOT="${FOOT}$(printf '\n⚠️ Teg/GitHub Release bajarilmadi: %s' "${RUN_URL}")" + elif [ "${RELEASE_STATUS}" = draft ]; then + FOOT="${FOOT}$(printf '\n🏷 GitHub Release: draft — Publish qilinmaguncha server uni ko‘rmaydi.')" fi - HEAD="$(printf '%s\n%s\n\n🧰 Run: %s' "${HEAD}" "${GH_LINE}" "${RUN_URL}")" - - fail=0 - for raw in "${CHATS[@]}"; do - chat="$(echo "${raw}" | xargs)" - [ -z "${chat}" ] && continue - echo "──▶ ${chat}" + FOOT="${FOOT}$(printf '\n\n💡 O‘rnatish: TV’da Downloader ilovasi orqali APK havolasini oching yoki USB orqali.')" + announce() { + local chat="$1" + if [ -s banner.png ] && [ -s caption.html ]; then + curl -sS --fail-with-body -X POST "${API}/sendPhoto" \ + -F "chat_id=${chat}" -F "photo=@banner.png" -F "caption= +Sozo v3.2.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NEW RELEASE · SEPTEMBER 2026 + Sozo + v3.2.0 + Light novels you can actually read, + a home for the whole household. + 284 novel sourcesProfiles & medalsTrakt · JellyfinDesktop + + \ No newline at end of file diff --git a/tools/release/release_banner.py b/tools/release/release_banner.py new file mode 100644 index 00000000..d1af8c0a --- /dev/null +++ b/tools/release/release_banner.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +"""Draws the Android TV release banner for one version. + +The artwork and its animation are the phone app's v3.2.0 banner +(banner-template.svg, copied from the sozo repository's tool/release_banner.py +setup). Only the right-hand column changes: the eyebrow, the version badge, +two tagline lines and up to four chips. + +The words come from a comment in release/notes/v.md: + + + +Every key is optional. Without the comment, the eyebrow says ANDROID TV and +the month, the tagline is a generic one, and the chips name the areas of the +merged changes (see banner_text). + +--still writes a copy without animation, the frame a viewer with reduced motion +sees. It is the one rendered to PNG for Telegram, which cannot show SVG. +""" +import argparse +import datetime as dt +import html +import re +import sys +from pathlib import Path + +TEMPLATE = Path("tools/release/banner-template.svg") +RIGHT = '' +COLUMN = 600 # room to the right of x=640 before the 40px margin +MAX_CHIPS = 4 + +# Advance widths of Inter, in em. Close enough to size pills and badges; text +# that might still overflow is squeezed with textLength. +WIDE = {"m": .87, "w": .79, "M": .85, "W": .95, "@": .95, "%": .8, "&": .66} +NARROW = {c: .26 for c in "ijlI.,:;'|!·()[] "} +NARROW.update({"f": .36, "t": .36, "r": .37, "-": .4, "/": .4}) + + +def text_width(text, size, spacing=0.0): + em = 0.0 + for ch in text: + if ch in WIDE: + em += WIDE[ch] + elif ch in NARROW: + em += NARROW[ch] + elif ch.isdigit(): + em += .62 + elif ch.isupper(): + em += .68 + else: + em += .56 + return em * size + spacing * len(text) + + +def parse_block(notes_text): + """The `` comment as a dict; empty when there is none.""" + match = re.search(r"", notes_text or "", re.S) + if not match: + return {} + out = {} + for line in match.group(1).splitlines(): + key, sep, value = line.partition(":") + if sep and key.strip(): + out[key.strip().lower()] = value.strip() + return out + + +def kind_of(version): + parts = (version.split(".") + ["0", "0"])[:3] + return "PATCH RELEASE" if parts[2] not in ("", "0") else "NEW RELEASE" + + +def banner_text(version, notes_text="", areas=(), today=None): + today = today or dt.date.today() + block = parse_block(notes_text) + patch = kind_of(version) == "PATCH RELEASE" + eyebrow = block.get("eyebrow") or "ANDROID TV" + if "·" not in eyebrow: + eyebrow = f"{eyebrow} · {today.strftime('%B %Y')}" + line1 = block.get("line1") or ("Fixes for what you reported," if patch + else f"Everything new in Sozo TV {version},") + line2 = block.get("line2") or "on the big screen." + if block.get("chips"): + chips = [c.strip() for c in block["chips"].split("|") if c.strip()] + else: + chips = list(dict.fromkeys(a for a in areas if a)) + if not chips: + chips = ["Android TV", "Google TV · Shield"] + return {"eyebrow": eyebrow.upper(), "version": f"v{version}", "line1": line1, + "line2": line2, "chips": chips[:MAX_CHIPS]} + + +def fitted(x, y, cls, text, size, extra=""): + attrs = f'x="{x}" y="{y}" class="{cls}"{extra}' + if text_width(text, size) > COLUMN: + attrs += f' textLength="{COLUMN}" lengthAdjust="spacingAndGlyphs"' + return f"{html.escape(text)}" + + +def right_column(t): + badge_w = max(150, round(text_width(t["version"], 30) + 62)) + chips, x = [], 0 + for chip in t["chips"]: + w = max(64, round(text_width(chip, 14.5) + 30)) + if x + w > COLUMN: + break + chips.append( + f'' + f'' + f"{html.escape(chip)}") + x += w + 10 + eyebrow = html.escape(t["eyebrow"]) + return "\n".join([ + RIGHT, + f' {eyebrow}', + ' Sozo', + f' ' + f'' + f'' + f'{html.escape(t["version"])}', + f' {fitted(0, 378, "tag", t["line1"], 25)}', + f' {fitted(0, 412, "tag2", t["line2"], 25)}', + f' {"".join(chips)}', + "", + "", + "", + ]) + + +def render(template_svg, t, still_frame=False): + cut = template_svg.find(RIGHT) + if cut < 0: + raise ValueError(f"the template has no {RIGHT}") + svg = template_svg[:cut] + right_column(t) + svg = re.sub(r".*?", f"Sozo TV {html.escape(t['version'])}", svg, count=1) + return still(svg) if still_frame else svg + + +def still(svg): + """The template's reduced-motion rule, applied to everyone: no pen strokes + or ring, the painted mark and every line of text in place.""" + return svg.replace("@media (prefers-reduced-motion: reduce){", "@media all{", 1) + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--version", required=True) + p.add_argument("--out", required=True) + p.add_argument("--still", action="store_true") + p.add_argument("--root", default=".") + p.add_argument("--log", default="", help="`git log --format=%%s` since the last tag; its areas are the chips when the notes name none") + p.add_argument("--keep", action="store_true", help="leave an existing banner alone") + a = p.parse_args() + root = Path(a.root) + out = Path(a.out) + if a.keep and out.is_file(): + print(f"{out} already exists; left as it is") + return 0 + notes = root / "release" / "notes" / f"v{a.version}.md" + notes_text = notes.read_text(encoding="utf-8") if notes.is_file() else "" + committed = root / "release" / "banners" / f"v{a.version}.svg" + if a.still and committed.is_file(): + # A banner already in the repository, drawn or hand-edited, is the one + # people saw on the release page; the PNG shows the same. + svg = still(committed.read_text(encoding="utf-8")) + t = {"from": str(committed)} + else: + from release_page import areas, changes + log = Path(a.log).read_text(encoding="utf-8").splitlines() if a.log else [] + t = banner_text(a.version, notes_text, areas(changes(log))) + svg = render((root / TEMPLATE).read_text(encoding="utf-8"), t, a.still) + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(svg, encoding="utf-8") + print(f"{out}: {t}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/release/release_page.py b/tools/release/release_page.py new file mode 100644 index 00000000..a6928f12 --- /dev/null +++ b/tools/release/release_page.py @@ -0,0 +1,327 @@ +#!/usr/bin/env python3 +"""Builds the Android TV release body from release/notes/v.md. + +A copy of the phone app's tool/compose_release_notes.py (sozo repository), +adapted to one APK and the TV's paths. + +Images may be written relative to the notes file. They become links to the +exact commit being released, so they work in a draft before anything reaches +the default branch. An image that is not in the repository is removed and +reported, so a release never shows a broken picture. + + becomes a table of the files actually attached. + +The version's banner (tool/release_banner.py) goes on top when the notes do not +already show one. + +With --auto, a version that has no notes file still gets a full page in the +same layout, built from the titles of what was merged since the last tag. + +--telegram writes the caption of the Telegram announcement (HTML, at most 1024 +characters): the Uzbek summary of the notes when they have one, otherwise the +merged changes. + +Exit codes: 0 written, 3 no notes file for this version and no --auto. +""" +import argparse +import html +import posixpath +import re +import sys +from pathlib import Path + +from release_banner import banner_text, kind_of + + +IMAGE_BLOCK = re.compile(r']*>\s*(]*>)\s*

\n?', re.I) +HTML_IMG = re.compile(r']*?\bsrc="([^"]+)"[^>]*>', re.I) +MD_IMG = re.compile(r'!\[[^\]]*\]\(([^)\s]+)\)') + + +def is_relative(src): + return not re.match(r'^(?:[a-z][a-z0-9+.-]*:|//|#|/)', src, re.I) + + +def rewrite_images(text, notes_path, repo_root, repo, sha, warn): + base = f"https://raw.githubusercontent.com/{repo}/{sha}/" + notes_dir = notes_path.parent.relative_to(repo_root).as_posix() + + def target(src): + path = posixpath.normpath(posixpath.join(notes_dir, src)) + if path.startswith("../") or not (repo_root / path).is_file(): + warn(f"image not found, removed: {src}") + return None + return base + path + + def block(match): + src = HTML_IMG.search(match.group(1)) + if src and is_relative(src.group(1)) and target(src.group(1)) is None: + return "" + return match.group(0) + + def html(match): + src = match.group(1) + if not is_relative(src): + return match.group(0) + url = target(src) + return match.group(0).replace(src, url, 1) if url else "" + + def markdown(match): + src = match.group(1) + if not is_relative(src): + return match.group(0) + url = target(src) + return match.group(0).replace(src, url, 1) if url else "" + + text = IMAGE_BLOCK.sub(block, text) + # A missing image in a block was already removed and warned about once. + return MD_IMG.sub(markdown, HTML_IMG.sub(html, text)) + + +def downloads_table(assets, repo, tag, version): + names = sorted(p.name for p in assets.iterdir()) if assets.is_dir() else [] + rows = [] + for name in names: + if name.startswith(f"sozo-tv-{version}-") and name.endswith(".apk"): + url = f"https://github.com/{repo}/releases/download/{tag}/{name}" + rows.append(f"| 📺 Android TV, Google TV, Shield, TV boxes | [`{name}`]({url}) |") + if not rows: + return "The files are attached to this release." + lines = ["| Device | File |", "|---|---|", *rows] + sums = "SHA256SUMS" + if sums in names: + url = f"https://github.com/{repo}/releases/download/{tag}/{sums}" + lines += ["", f"🔐 To check a download, compare it with [`{sums}`]({url})."] + return "\n".join(lines) + + +SITE = "https://github.com/professorDeveloper/sozo-tv" +BANNER_BLOCK = re.compile(r"\n*", re.S) + +# Merged-change titles read "Area: what changed (#12)". These areas are about +# the repository, not the app, and stay out of the notes. +INTERNAL = {"release", "ci", "chore", "docs", "doc", "issue forms", "build", "test", + "tests", "deps", "workflow", "readme", "merge"} +AREA_ICONS = {"player": "▶️", "desktop player": "🖥️", "desktop": "🖥️", "sources": "🧩", + "source": "🧩", "downloads": "⬇️", "download": "⬇️", "novels": "📚", + "manga": "📖", "tv": "📺", "ios": "📱", "android": "🤖", "settings": "⚙️", + "search": "🔎", "home": "🏠", "profiles": "👨‍👩‍👧", "subtitles": "💬", + "languages": "🌍", "highlights": "⭐"} +TITLE = re.compile(r"^(?P[^:]{1,30}):\s*(?P.+?)(?:\s*\(#(?P\d+)\))?$") + + +def changes(log_lines): + """[(area, text, pr)] from `git log --format=%s`, oldest first, app-facing only.""" + out = [] + for line in reversed([l.strip() for l in log_lines if l.strip()]): + m = TITLE.match(line) + if m: + area, text, pr = m.group("area").strip(), m.group("text"), m.group("pr") + else: + pr_m = re.search(r"\s*\(#(\d+)\)$", line) + area, text, pr = "", line[:pr_m.start()] if pr_m else line, pr_m and pr_m.group(1) + if area.lower() in INTERNAL or re.match(r"(?i)^(merge|revert|bump)\b", line): + continue + if re.match(r"(?i)^sozo\s+v?\d", area): + area = "Highlights" + text = text[:1].upper() + text[1:] + out.append((area or "Improvements", text, pr)) + return out + + +def ordered(items): + """Grouped by area: Highlights first, then in order of appearance, Improvements last.""" + order = list(dict.fromkeys(a for a, _, _ in items)) + rank = lambda a: 0 if a == "Highlights" else 2 if a == "Improvements" else 1 + order.sort(key=rank) + return [(area, [i for i in items if i[0] == area]) for area in order] + + +def areas(items): + return [a for a, _ in ordered(items) if a not in ("Highlights", "Improvements")] + + +def icon(area): + return AREA_ICONS.get(area.lower(), "✨") + + +def add_banner(text, version, repo, sha, repo_root): + path = f"release/banners/v{version}.svg" + text = BANNER_BLOCK.sub("", text) + if "banner.svg" in text or not (repo_root / path).is_file(): + return text + url = f"https://raw.githubusercontent.com/{repo}/{sha}/{path}" + return (f'

\n Sozo v{version}\n' + f"

\n\n{text}") + + +def notes_path(repo_root, version): + return repo_root / "release" / "notes" / f"v{version}.md" + + +def compose(version, sha, repo, tag, assets, repo_root, warn): + notes = notes_path(repo_root, version) + if not notes.is_file(): + return None + text = notes.read_text(encoding="utf-8") + text = rewrite_images(text, notes, repo_root, repo, sha, warn) + text = add_banner(text, version, repo, sha, repo_root) + return text.replace("", downloads_table(assets, repo, tag, version)) + + +def generate(version, sha, repo, tag, previous, assets, repo_root, log_lines, intro=""): + """A page in the layout of the phone app's v3.2.0 notes, for a version nobody wrote up.""" + items = changes(log_lines) + t = banner_text(version, "", areas(items)) + patch = kind_of(version) == "PATCH RELEASE" + lines = [ + '

', + f" Sozo TV v{version} is a {'patch' if patch else 'new'} release.
", + f" {html.escape(t['line1'])} {html.escape(t['line2'])}", + "

", + "", + '

', + f' Download', + ' Telegram', + ' Discord', + f' Star Sozo TV', + "

", + "", + ] + if intro.strip(): + lines += [intro.strip(), ""] + lines += ["---", "", "## ✨ What's new", ""] + if items: + for area, group in ordered(items): + lines += [f"### {icon(area)} {area}", ""] + for _, text, pr in group: + link = f" ([#{pr}](https://github.com/{repo}/pull/{pr}))" if pr else "" + lines.append(f"- {text}{link}") + lines.append("") + else: + lines += ["Fixes and smaller improvements.", ""] + lines += [ + "---", "", "## ⬇ Download", "", + downloads_table(assets, repo, tag, version), "", + "
", + "📺 How to install it on a TV", + "", + "- **Updating:** if Sozo TV is already installed, it offers this version itself.", + "- **With Downloader:** install *Downloader* from the TV's app store, allow it to install", + " apps, and open the APK link above in it.", + "- **With a USB stick:** copy the APK onto it and open it with the TV's file manager.", + "", + "If the TV says the app is not installed, an older Sozo TV signed with a different key", + "is on it: uninstall that one first.", + "
", + "", + "---", "", "## 💬 Join the community", "", + f"- 📣 **Telegram**: [@sozoapp](https://telegram.me/sozoapp) for new versions and announcements first.", + "- 🎧 **Discord**: [discord.gg/n22URhYvMR](https://discord.gg/n22URhYvMR) to suggest ideas and report bugs.", + "- 🛟 **In the app**: Profile → **Help & Support**.", + f"- 🐛 **On GitHub**: [a source isn't working]({SITE}/issues/new?template=source_not_working.yml) · [bug report]({SITE}/issues/new?template=bug_report.yml) · [feature request]({SITE}/issues/new?template=feature_request.yml)", + f"- ⭐ **If Sozo is useful to you, [star the repo]({SITE})**.", + "", + ] + if previous: + lines.append(f'Full list of changes: ' + f"{previous}...{tag}") + body = "\n".join(lines) + "\n" + return add_banner(body, version, repo, sha, repo_root) + + +# ---------------------------------------------------------------- Telegram ---- + +CAPTION_LIMIT = 1024 +UZ_SUMMARY = re.compile(r"[^<]*🇺🇿.*?(.*?)", re.S) + + +def md_to_tg(text): + text = html.escape(text, quote=False) + text = re.sub(r"\[([^\]]+)\]\((https?://[^)\s]+)\)", r'\1', text) + text = re.sub(r"\*\*(.+?)\*\*", r"\1", text) + text = re.sub(r"(?\1", text) + return re.sub(r"`([^`]+)`", r"\1", text) + + +def shorten(md, limit=230): + """Cuts a markdown bullet at a sentence end, never inside **bold**.""" + if len(md) <= limit: + return md + for m in reversed(list(re.finditer(r"[.!?](?=\s)", md[:limit]))): + head = md[:m.end()] + if head.count("**") % 2 == 0 and head.count("[") == head.count("]"): + return head + return md + + +def telegram_caption(version, notes_text, log_lines, intro=""): + t = banner_text(version, notes_text, areas(changes(log_lines))) + kind = "yamoq (patch)" if kind_of(version) == "PATCH RELEASE" else "yangi versiya" + head = [f"📺 Sozo TV v{html.escape(version)} · {kind}", + f"{html.escape(t['line1'])} {html.escape(t['line2'])}"] + if intro.strip(): + head += ["", f"📝 {html.escape(intro.strip())}"] + head += ["", "✨ Nima yangi"] + tail = ["", "⬇️ APK shu xabar ostida · 📣 @sozoapp"] + + bullets = [] + uz = UZ_SUMMARY.search(notes_text or "") + if uz: + bullets = [shorten(l.strip()[2:]) for l in uz.group(1).splitlines() + if l.strip().startswith("- ")] + if not bullets: + bullets = [f"{icon(a)} **{a}**: {txt}" for a, group in ordered(changes(log_lines)) + for _, txt, _ in group] + if not bullets: + bullets = ["Tuzatishlar va kichik yaxshilanishlar."] + + out = list(head) + for b in bullets: + line = "• " + md_to_tg(b) if not re.match(r"^\W", b) else md_to_tg(b) + if len("\n".join(out + [line] + tail)) > CAPTION_LIMIT: + break + out.append(line) + if len(out) == len(head): + out.append(md_to_tg(bullets[0])[:CAPTION_LIMIT - len("\n".join(head + tail)) - 2] + "…") + return "\n".join(out + tail) + + +def read_log(path): + return Path(path).read_text(encoding="utf-8").splitlines() if path else [] + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--version", required=True) + for name in ("sha", "repo", "tag", "assets", "out", "telegram", "previous", "log"): + parser.add_argument(f"--{name}", default="") + parser.add_argument("--intro", default="", help="text from the release form, put on top") + parser.add_argument("--auto", action="store_true", help="generate a page when there are no notes") + parser.add_argument("--root", default=".") + args = parser.parse_args() + root = Path(args.root).resolve() + log_lines = read_log(args.log) + + if args.telegram: + notes = notes_path(root, args.version) + text = notes.read_text(encoding="utf-8") if notes.is_file() else "" + Path(args.telegram).write_text( + telegram_caption(args.version, text, log_lines, args.intro), encoding="utf-8") + if not args.out: + return 0 + + warn = lambda message: print(f"::warning::{message}") + body = compose(args.version, args.sha, args.repo, args.tag, Path(args.assets), root, warn) + if body is None and args.auto: + body = generate(args.version, args.sha, args.repo, args.tag, args.previous, + Path(args.assets), root, log_lines, args.intro) + if body is None: + print(f"No release/notes/v{args.version}.md") + return 3 + Path(args.out).write_text(body, encoding="utf-8") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/release/release_page_test.py b/tools/release/release_page_test.py new file mode 100644 index 00000000..a5185b0e --- /dev/null +++ b/tools/release/release_page_test.py @@ -0,0 +1,90 @@ +import datetime as dt +import re +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent)) +from release_banner import banner_text, render, still +from release_page import changes, compose, generate, telegram_caption + +SHA = "abc123" +REPO = "o/r" +RAW = f"https://raw.githubusercontent.com/{REPO}/{SHA}/" +LOG = [ + "Player: keep focus on the seek bar (#40)", + "chore: 1.0.4 (4)", + "Release: a banner and a Telegram post (#41)", + "Search: clearing the error is not an error", +] + + +class PageTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + (self.root / "release/notes").mkdir(parents=True) + (self.root / "release/banners").mkdir(parents=True) + self.assets = self.root / "dist" + self.assets.mkdir() + for name in ("sozo-tv-1.0.4-4.apk", "SHA256SUMS", "sozo-tv-1.0.4-release.json"): + (self.assets / name).write_bytes(b"x") + self.warnings = [] + + def test_written_notes_get_the_banner_and_the_apk(self): + (self.root / "release/banners/v1.0.4.svg").write_text("") + (self.root / "release/notes/v1.0.4.md").write_text("\nBody\n\n\n") + out = compose("1.0.4", SHA, REPO, "v1.0.4", self.assets, self.root, self.warnings.append) + self.assertTrue(out.startswith(f'

\n Sozo TV v1.0.4 · yamoq (patch)")) + self.assertIn("▶️ Player: Keep focus on the seek bar", out) + self.assertIn("📝 Bugun", out) + self.assertLessEqual(len(out), 1024) + self.assertEqual(changes(["chore: x"]), []) + + +TEMPLATE = Path(__file__).resolve().parent / "banner-template.svg" + + +class BannerTest(unittest.TestCase): + def test_tv_words(self): + t = banner_text("1.0.4", "", [], dt.date(2026, 11, 14)) + self.assertEqual(t["eyebrow"], "ANDROID TV · NOVEMBER 2026") + self.assertEqual(t["version"], "v1.0.4") + self.assertEqual(t["line2"], "on the big screen.") + self.assertEqual(t["chips"], ["Android TV", "Google TV · Shield"]) + self.assertEqual(banner_text("2.0.0", "", ["Player"])["line1"], "Everything new in Sozo TV 2.0.0,") + + def test_render(self): + template = TEMPLATE.read_text(encoding="utf-8") + svg = render(template, banner_text("1.0.4", "", ["Player"])) + cut = '' + self.assertEqual(svg[:svg.index(cut)], re.sub(r".*?", "Sozo TV v1.0.4", template[:template.index(cut)])) + self.assertIn(">v1.0.4", svg) + self.assertIn("ANDROID TV", svg) + self.assertIn("@media all{", still(svg)) + + +if __name__ == "__main__": + unittest.main()