Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1385,12 +1385,19 @@ jobs:
SHA: ${{ needs.version.outputs.sha }}
TAG: ${{ needs.version.outputs.tag }}
NOTES: ${{ inputs.notes }}
MODE: ${{ inputs.release || 'publish' }}
TV_REPO: ${{ vars.TV_REPO || 'professorDeveloper/sozo-tv' }}
GH_TOKEN: ${{ github.token }}
run: |
set -uo pipefail
PREV="$(git tag --merged "${SHA}" --sort=-v:refname --list 'v*' | grep -vx "${TAG}" | head -1 || true)"
git log ${PREV:+"${PREV}..${SHA}"} --first-parent --format=%s > changes.txt
# A draft's page is not public yet, so only a published release links to it.
REL=""
if [ "${MODE}" = publish ]; then REL="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/releases/tag/${TAG}"; fi
TV="$(gh api "repos/${TV_REPO}/releases/latest" --jq .html_url 2>/dev/null || true)"
python3 tool/compose_release_notes.py --version "${V}" --log changes.txt \
--intro "${NOTES}" --telegram caption.html
--intro "${NOTES}" --telegram caption.html --release-url "${REL}" --tv-url "${TV}"
python3 tool/release_banner.py --version "${V}" --still --log changes.txt --out banner.svg
# The banner is set in Inter; without it the runner falls back to Liberation Sans.
timeout 120 sudo apt-get install -y -qq fonts-inter >/dev/null 2>&1 || true
Expand Down Expand Up @@ -1544,3 +1551,34 @@ jobs:
send_files "${chat}" || { echo "::error::files ${chat}: $(cat /tmp/tg_doc.json)"; fail=1; }
done
exit "${fail}"

# The public post: the banner with the caption, nothing else. Only for a
# release that was published, since the post links to its page.
- name: Announce on the channel
if: ${{ always() && (inputs.release || 'publish') == 'publish' && needs.publish.result == 'success' }}
continue-on-error: true
env:
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_CHANNEL_BOT_TOKEN || secrets.TELEGRAM_BOT_TOKEN }}
CHANNEL: ${{ vars.TELEGRAM_CHANNEL }}
run: |
set -uo pipefail
if [ -z "${CHANNEL}" ] || [ -z "${TELEGRAM_BOT_TOKEN}" ]; then
echo "::notice title=Channel post skipped::Set the TELEGRAM_CHANNEL variable (for example @sozoapp) and make the bot an admin of that channel."
exit 0
fi
if [ ! -s caption.html ]; then
echo "::warning title=Channel post skipped::No caption was built."
exit 0
fi
API="https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}"
if [ -s banner.png ]; then
curl -sS --fail-with-body -X POST "${API}/sendPhoto" -F "chat_id=${CHANNEL}" \
-F "photo=@banner.png" -F "caption=<caption.html" -F "parse_mode=HTML" \
-o /tmp/tg_channel.json && { echo "Posted to ${CHANNEL}"; exit 0; }
echo "::warning::sendPhoto ${CHANNEL}: $(cat /tmp/tg_channel.json) β€” posting the text alone"
fi
curl -sS --fail-with-body -X POST "${API}/sendMessage" \
--data-urlencode "chat_id=${CHANNEL}" --data-urlencode "text=$(cat caption.html)" \
--data "parse_mode=HTML" --data "disable_web_page_preview=true" -o /tmp/tg_channel.json \
&& echo "Posted to ${CHANNEL} without the banner" \
|| echo "::error title=Channel post failed::$(cat /tmp/tg_channel.json)"
113 changes: 79 additions & 34 deletions tool/compose_release_notes.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
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.
visible characters): the notes' hidden `<!-- telegram -->` block when they have
one, else the bold titles of the notes, else the merged changes.

Exit codes: 0 written, 3 no notes file for this version and no --auto.
"""
Expand Down Expand Up @@ -251,7 +251,10 @@ def generate(version, sha, repo, tag, previous, assets, repo_root, log_lines, in
# ---------------------------------------------------------------- Telegram ----

CAPTION_LIMIT = 1024
UZ_SUMMARY = re.compile(r"<summary>[^<]*πŸ‡ΊπŸ‡Ώ.*?</summary>(.*?)</details>", re.S)
DISCORD = "https://discord.gg/n22URhYvMR"
TG_BLOCK = re.compile(r"<!--\s*telegram\s*\n(.*?)-->", re.S)
HEADLINE = re.compile(r"^\s*(?:\|\s*|[-*]\s+)(?:[^\w\s*|]+\s*)?\*\*(.+?)\*\*(:?)")
NOT_NEWS = re.compile(r"(?i)\bdownload\s*$|community")


def md_to_tg(text):
Expand All @@ -262,46 +265,86 @@ def md_to_tg(text):
return re.sub(r"`([^`]+)`", r"<code>\1</code>", 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 visible_length(caption):
"""What Telegram counts against the limit: text without tags, in UTF-16 units."""
text = html.unescape(re.sub(r"<[^>]+>", "", caption))
return len(text.encode("utf-16-le")) // 2


def telegram_lines(notes_text):
"""(tagline, bullets) from a hidden `<!-- telegram -->` block in the notes.

<!-- telegram
tagline: Fixes for what you reported.
- No more endless "Video loading".
-->
"""
m = TG_BLOCK.search(notes_text or "")
if not m:
return "", []
tagline, bullets = "", []
for line in m.group(1).splitlines():
line = line.strip()
if line.lower().startswith("tagline:"):
tagline = line.split(":", 1)[1].strip()
elif line.startswith("- "):
bullets.append(line[2:].strip())
return tagline, bullets


def headlines(notes_text, most=7):
"""The bold titles of the notes' rows and bullets: one per section in turn.

A bold label such as `**Windows:**` names a platform, not a change, and the
download and community sections are not news; both are left out.
"""
sections, skip = [[]], False
for line in (notes_text or "").splitlines():
if line.startswith("## "):
sections.append([])
skip = bool(NOT_NEWS.search(line))
continue
m = HEADLINE.match(line)
if m and not skip and not m.group(2) and not m.group(1).rstrip().endswith(":"):
title = m.group(1).strip().rstrip(".")
if title and all(title not in s for s in sections):
sections[-1].append(title)
out = []
for i in range(max(len(s) for s in sections)):
out += [s[i] for s in sections if i < len(s)]
return out[:most]


def telegram_caption(version, notes_text, log_lines, intro=""):
def telegram_caption(version, notes_text, log_lines, intro="", release_url="", tv_url=""):
t = banner_text(version, notes_text, areas(changes(log_lines)))
kind = "yamoq (patch)" if kind_of(version) == "PATCH RELEASE" else "yangi versiya"
head = [f"πŸ‰ <b>Sozo v{html.escape(version)}</b> Β· {kind}",
f"<i>{html.escape(t['line1'])} {html.escape(t['line2'])}</i>"]
if intro.strip():
head += ["", f"πŸ“ {html.escape(intro.strip())}"]
head += ["", "✨ <b>Nima yangi</b>"]
tail = ["", "⬇️ Fayllar 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("- ")]
tagline, bullets = telegram_lines(notes_text)
tagline = intro.strip() or tagline or f"{t['line1']} {t['line2']}"
if not bullets:
bullets = headlines(notes_text)
if not bullets:
bullets = [f"{icon(a)} **{a}**: {txt}" for a, group in ordered(changes(log_lines))
for _, txt, _ in group]
bullets = [txt for _, group in ordered(changes(log_lines)) for _, txt, _ in group]
if not bullets:
bullets = ["Tuzatishlar va kichik yaxshilanishlar."]
bullets = ["Fixes and small improvements."]

head = [f"πŸ‰ <b>Sozo {html.escape(version)} is out!</b>", "",
f"<i>{html.escape(tagline)}</i>"]
tail = [""]
if release_url:
tail.append(f'<b>All files</b> (<i>Windows, macOS, Linux, iOS, Android</i>): '
f'<a href="{html.escape(release_url)}">Link</a>')
if tv_url:
tail += ["", f'<b>TV Side</b>: <a href="{html.escape(tv_url)}">Link</a>']
tail += ["", f"πŸ’¬ Discord: {DISCORD}", "πŸ›Ÿ <b>Need help? Profile β†’ Help &amp; Support</b>"]

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:
line = "- " + md_to_tg(b)
if visible_length("\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] + "…")
room = CAPTION_LIMIT - visible_length("\n".join(head + tail)) - 4
out.append("- " + html.escape(re.sub(r"[*`]", "", bullets[0]))[:max(room, 0)] + "…")
return "\n".join(out + tail)


Expand All @@ -312,7 +355,8 @@ def read_log(path):
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--version", required=True)
for name in ("sha", "repo", "tag", "assets", "out", "telegram", "previous", "log"):
for name in ("sha", "repo", "tag", "assets", "out", "telegram", "previous", "log",
"release-url", "tv-url"):
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")
Expand All @@ -325,7 +369,8 @@ def main():
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")
telegram_caption(args.version, text, log_lines, args.intro,
args.release_url, args.tv_url), encoding="utf-8")
if not args.out:
return 0

Expand Down
78 changes: 55 additions & 23 deletions tool/compose_release_notes_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import datetime as dt
import re

from compose_release_notes import changes, compose, generate, telegram_caption
from compose_release_notes import changes, compose, generate, telegram_caption, visible_length
from release_banner import banner_text, render, still

SHA = "abc123"
Expand Down Expand Up @@ -128,43 +128,75 @@ def test_generated_page_shows_the_committed_banner(self):
self.assertNotIn("compare/", out)


UZ_NOTES = """<!-- banner
NOTES = """<!-- banner
line1: Playback that recovers,
line2: downloads that finish.
-->
<details>
<summary>πŸ‡ΊπŸ‡Ώ <b>O'zbekcha qisqacha</b></summary>

**Sozo v3.2.1: tuzatishlar.**
| | |
|---|---|
| ⏱️ **No more endless "Video loading"** | A server now has about 25 seconds. |
| πŸ”Œ **Dropped connections** | The player reconnects. |

## ✨ Added
- 🌍 **Vietnamese and Hindi**, so Sozo now has 16 languages.
- πŸ“‹ **Sort My List** by recently added.
- **Windows:** Anime4K no longer goes black.

## πŸ’¬ Join the community
- πŸ“£ **Telegram**: [@sozoapp](https://telegram.me/sozoapp) for news.
"""

- ▢️ **Pleer.** Endi <video> cheksiz turmaydi. *Save to Downloads* ishlaydi.
- 🌍 **Tillar** qo'shildi: [kanal](https://t.me/sozoapp).
</details>
TG_NOTES = NOTES + """<!-- telegram
tagline: Fixes for what you reported.
- No more endless <video> loading, see [the channel](https://t.me/sozoapp).
- **Corner player** on desktop: press **I**.
-->
"""
REL = "https://github.com/o/r/releases/tag/v3.2.1"
TV = "https://github.com/o/tv/releases/tag/v1.0.4"


class TelegramTest(unittest.TestCase):
def test_uses_the_uzbek_summary(self):
out = telegram_caption("3.2.1", UZ_NOTES, LOG)
self.assertIn("πŸ‰ <b>Sozo v3.2.1</b> Β· yamoq (patch)", out)
def test_hand_written_block_wins(self):
out = telegram_caption("3.2.1", TG_NOTES, LOG, release_url=REL, tv_url=TV)
self.assertTrue(out.startswith("πŸ‰ <b>Sozo 3.2.1 is out!</b>\n\n<i>Fixes for what you reported.</i>\n"))
self.assertIn('- No more endless &lt;video&gt; loading, see <a href="https://t.me/sozoapp">the channel</a>.', out)
self.assertIn("- <b>Corner player</b> on desktop: press <b>I</b>.", out)
self.assertNotIn("Dropped connections", out)
self.assertIn(f'<b>All files</b> (<i>Windows, macOS, Linux, iOS, Android</i>): <a href="{REL}">Link</a>', out)
self.assertIn(f'<b>TV Side</b>: <a href="{TV}">Link</a>', out)
self.assertTrue(out.endswith("πŸ›Ÿ <b>Need help? Profile β†’ Help &amp; Support</b>"))

def test_bold_titles_of_the_notes_otherwise(self):
out = telegram_caption("3.2.1", NOTES, LOG, release_url=REL)
self.assertIn("<i>Playback that recovers, downloads that finish.</i>", out)
self.assertIn("▢️ <b>Pleer.</b> Endi &lt;video&gt; cheksiz turmaydi. <i>Save to Downloads</i> ishlaydi.", out)
self.assertIn('<a href="https://t.me/sozoapp">kanal</a>', out)
self.assertNotIn("Matroska", out)
self.assertIn('- No more endless "Video loading"\n- Vietnamese and Hindi\n- Dropped connections\n- Sort My List\n\n', out)
self.assertNotIn("Windows", out.split("All files")[0])
self.assertNotIn("Telegram", out)
self.assertNotIn("TV Side", out)

def test_falls_back_to_the_merged_changes(self):
out = telegram_caption("3.3.0", "", LOG, "Bugun chiqdi")
self.assertIn("yangi versiya", out)
self.assertIn("πŸ“ Bugun chiqdi", out)
self.assertIn("▢️ <b>Player</b>: Skip Matroska on iPhone", out)
out = telegram_caption("3.3.0", "", LOG, "Out today")
self.assertIn("<i>Out today</i>", out)
self.assertIn("- Skip Matroska on iPhone", out)
self.assertNotIn("CDN", out)
self.assertNotIn("All files", out)

def test_never_longer_than_a_caption(self):
notes = UZ_NOTES.replace("</details>", "\n".join(f"- **N{i}.** " + "so'z " * 40 for i in range(40)) + "\n</details>")
out = telegram_caption("3.2.1", notes, LOG)
self.assertLessEqual(len(out), 1024)
notes = NOTES + "<!-- telegram\n" + "\n".join(f"- **N{i}** 🎬 " + "word " * 40 for i in range(40)) + "\n-->\n"
out = telegram_caption("3.2.1", notes, LOG, release_url=REL, tv_url=TV)
self.assertLessEqual(visible_length(out), 1024)
self.assertEqual(out.count("<b>"), out.count("</b>"))
self.assertTrue(out.endswith("@sozoapp"))
self.assertIn("TV Side", out)

def test_one_huge_bullet_is_cut_not_dropped(self):
notes = "<!-- telegram\n- " + "long " * 400 + "\n-->"
out = telegram_caption("3.2.1", notes, LOG, release_url=REL)
self.assertLessEqual(visible_length(out), 1024)
self.assertIn("…", out)

def test_length_counts_what_telegram_counts(self):
self.assertEqual(visible_length('<a href="https://x.y/very/long">Link</a> &amp; 🎬'), len("Link & ") + 2)


TEMPLATE = Path(__file__).resolve().parent.parent / "docs/images/v3.2.0/banner.svg"
Expand Down
Loading