Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.
Kotlin alternativeandroidandroid-applicationclientglassmorphisminnertubelibrespotliquid-glassspotifyspotify-connectspotifyapiyoutube-musicyoutube-playerytdlnis
Automate Telegram release notes and APK announcements
Lelonio06215167cf7e
diff --git a/.github/workflows/telegram-release.yml b/.github/workflows/telegram-release.ymlnew file mode 100644index 0000000..ec95f6f--- /dev/null+++ b/.github/workflows/telegram-release.yml@@ -0,0 +1,45 @@+name: Telegram release++on:+ release:+ types: [published]+ workflow_dispatch:+ inputs:+ tag:+ description: Published release tag to announce+ required: true+ type: string+ dry_run:+ description: Preview without sending to Telegram+ default: true+ type: boolean++permissions:+ contents: read++concurrency:+ group: telegram-release-${{ github.event.release.tag_name || inputs.tag }}+ cancel-in-progress: false++jobs:+ announce:+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@v7+ with:+ ref: master+ - name: Read published release+ env:+ GH_TOKEN: ${{ github.token }}+ RELEASE_TAG: ${{ github.event.release.tag_name || inputs.tag }}+ run: |+ gh api "repos/$GITHUB_REPOSITORY/releases/tags/$RELEASE_TAG" > "$RUNNER_TEMP/telegram-release.json"+ - name: Publish notes and APKs+ env:+ TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}+ TELEGRAM_CHANNEL: ${{ vars.TELEGRAM_CHANNEL || '@SquareAppOfficial' }}+ TELEGRAM_GROUP: ${{ vars.TELEGRAM_GROUP || '-1003964165935' }}+ TELEGRAM_THREAD_ID: ${{ vars.TELEGRAM_THREAD_ID }}+ DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}+ run: python3 scripts/telegram-release.py "$RUNNER_TEMP/telegram-release.json"diff --git a/docs/TELEGRAM.md b/docs/TELEGRAM.mdnew file mode 100644index 0000000..0970d35--- /dev/null+++ b/docs/TELEGRAM.md@@ -0,0 +1,59 @@+# Telegram release announcements++The `Telegram release` workflow announces a release after its GitHub draft is+published. It posts the full release notes, followed by the ARM64, ARMv7 and+universal APKs, to both `@SquareAppOfficial` and the community's News & Releases+topic. It checks that all three attachments are uploaded before posting.++## One-time setup++1. Create a dedicated bot with Telegram's verified `@BotFather` (`/newbot`).+2. Add it to `Square | Official` as an administrator with **Post messages**.+ It does not need permission to add administrators or delete messages.+3. Add it to `Square | Community` as an administrator, allowing messages and+ documents and **Manage topics**, so it can post in the closed announcement+ topic. It does not need permission to add administrators or delete messages.+4. In the repository's Settings → Secrets and variables → Actions, create the+ repository secret `TELEGRAM_BOT_TOKEN`. Paste the BotFather token there,+ never into source files, issues or chat messages.+5. Confirm these repository variables, or use their workflow defaults:++ | Variable | Default | Purpose |+ | --- | --- | --- |+ | `TELEGRAM_CHANNEL` | `@SquareAppOfficial` | Public announcement channel |+ | `TELEGRAM_GROUP` | `-1003964165935` | Square community supergroup |+ | `TELEGRAM_THREAD_ID` | Empty | Optional forum topic ID |++ News & Releases is currently the renamed **General** topic, so leave+ `TELEGRAM_THREAD_ID` empty. If announcements move to a regular topic later,+ set its message thread ID instead. The group ID is derived from its Telegram+ Web link; verify the bot's access with the first manual run.++## Verification and publishing++Run `Telegram release` from Actions with the tag of an existing published+release and **dry_run enabled**. This previews the exact notes, filenames and+destinations without contacting Telegram or requiring the token.++Once the bot and secret are configured, disable dry_run to publish that release+and verify that notes and all three APKs appear in both destinations. Future+releases publish automatically on the GitHub `release.published` event.+Pre-releases also trigger this event. Drafts and ordinary CI builds do not.++Do not rerun a successful announcement: rerunning sends it again. If a run+fails after some messages were sent, check Telegram before rerunning to avoid+partial duplicate announcements. Sending to two destinations is not atomic.++If publication is later automated using GitHub's default `GITHUB_TOKEN`, that+publication will not trigger another workflow. Publish with an appropriate+user/GitHub App token, or explicitly dispatch this workflow after publication.++## Local checks++```sh+python3 -m unittest discover -s scripts/tests -v+```++The script uses Python's standard library only. Bot API calls avoid printing+credential-bearing URLs, and the token is held only in the GitHub secret and+runner environment.diff --git a/scripts/telegram-release.py b/scripts/telegram-release.pynew file mode 100644index 0000000..db7e8b4--- /dev/null+++ b/scripts/telegram-release.py@@ -0,0 +1,133 @@+"""Send a published Square release to its announcement channel and forum topic."""+import json+import os+from pathlib import Path+import sys+import tempfile+from urllib import error, parse, request+import uuid++ABIS = ("arm64-v8a", "armeabi-v7a", "universal")+LABELS = {+ "arm64-v8a": "64-bit Android phones",+ "armeabi-v7a": "32-bit Android phones",+ "universal": "Universal — use this if unsure",+}+++def messages(release):+ title = release.get("name") or release["tag_name"]+ text = f"Square {title}\n\n{release['html_url']}\n\n{release.get('body') or 'Release notes are available on GitHub.'}"+ # Leave room below Telegram's 4096-character limit, including emoji pairs.+ chunks = []+ while len(text.encode("utf-16-le")) // 2 > 3500:+ end = 0+ units = 0+ for char in text:+ size = len(char.encode("utf-16-le")) // 2+ if units + size > 3500:+ break+ units += size+ end += 1+ newline = text.rfind("\n", 0, end)+ if newline > end // 2:+ end = newline + 1+ chunks.append(text[:end])+ text = text[end:]+ if text:+ chunks.append(text)+ return chunks+++def apks(release):+ version = release["tag_name"].removeprefix("v")+ result = []+ for abi in ABIS:+ name = f"square-{version}-{abi}.apk"+ found = [a for a in release.get("assets", []) if a["name"] == name]+ if len(found) != 1 or found[0].get("state") != "uploaded":+ raise ValueError(f"Missing uploaded APK: {name}")+ asset = found[0]+ if not 0 < asset["size"] < 50_000_000:+ raise ValueError(f"APK exceeds Telegram upload limit: {name}")+ url = parse.urlparse(asset["browser_download_url"])+ if url.scheme != "https" or url.hostname != "github.com":+ raise ValueError(f"Unexpected download source for {name}")+ result.append((asset, LABELS[abi]))+ return result+++def telegram(token, method, fields, file=None):+ if file is None:+ data = json.dumps(fields).encode()+ content_type = "application/json"+ else:+ boundary = uuid.uuid4().hex+ parts = []+ for key, value in fields.items():+ parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{key}"\r\n\r\n{value}\r\n'.encode())+ parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="document"; filename="{file.name}"\r\nContent-Type: application/vnd.android.package-archive\r\n\r\n'.encode())+ parts.extend((file.read_bytes(), f'\r\n--{boundary}--\r\n'.encode()))+ data = b"".join(parts)+ content_type = f"multipart/form-data; boundary={boundary}"+ req = request.Request(f"https://api.telegram.org/bot{token}/{method}", data=data,+ headers={"Content-Type": content_type})+ try:+ with request.urlopen(req, timeout=120) as response:+ result = json.load(response)+ except error.HTTPError as exc:+ # Never print request URLs: they contain the bot credential.+ raise RuntimeError(f"Telegram {method} failed (HTTP {exc.code}). Check bot permissions and destination settings.") from None+ except error.URLError:+ raise RuntimeError(f"Telegram {method} could not connect.") from None+ if not result.get("ok"):+ raise RuntimeError(f"Telegram {method} was not accepted.")+ return result["result"]+++def main():+ release = json.loads(Path(sys.argv[1]).read_text())+ if release.get("draft") or not release.get("published_at"):+ raise ValueError("Only published releases can be announced")+ assets = apks(release)+ notes = messages(release)+ channel = os.environ.get("TELEGRAM_CHANNEL", "@SquareAppOfficial")+ group = os.environ.get("TELEGRAM_GROUP", "-1003964165935")+ thread = os.environ.get("TELEGRAM_THREAD_ID", "")+ destinations = [{"chat_id": channel}, {"chat_id": group}]+ if thread:+ destinations[1]["message_thread_id"] = int(thread)+ if os.environ.get("DRY_RUN", "false").lower() == "true":+ print(json.dumps({"destinations": destinations, "notes": notes,+ "apks": [a["name"] for a, _ in assets]}, indent=2, ensure_ascii=False))+ return+ token = os.environ.get("TELEGRAM_BOT_TOKEN", "").strip()+ if not token:+ raise ValueError("Set the TELEGRAM_BOT_TOKEN repository secret first")+ # Download and validate every attachment before publishing anything.+ with tempfile.TemporaryDirectory() as tmp:+ files = []+ for asset, label in assets:+ path = Path(tmp) / asset["name"]+ with request.urlopen(asset["browser_download_url"], timeout=120) as source:+ path.write_bytes(source.read(50_000_000))+ if path.stat().st_size != asset["size"]:+ raise ValueError(f"Incomplete download: {asset['name']}")+ files.append((path, label))+ for destination in destinations:+ for text in notes:+ telegram(token, "sendMessage", {**destination, "text": text,+ "link_preview_options": {"is_disabled": True}})+ for path, label in files:+ telegram(token, "sendDocument", {**destination, "caption": label}, file=path)+ print(f"Published {release['tag_name']} notes and {len(files)} APKs to both Telegram destinations.")+++if __name__ == "__main__":+ try:+ main()+ except (ValueError, RuntimeError, error.URLError, OSError) as exc:+ # Network exception strings can include URLs. Keep those out of logs.+ print(f"::error::{exc}" if isinstance(exc, (ValueError, RuntimeError))+ else "::error::Release download or file access failed", file=sys.stderr)+ sys.exit(1)diff --git a/scripts/tests/test_telegram_release.py b/scripts/tests/test_telegram_release.pynew file mode 100644index 0000000..ed737bf--- /dev/null+++ b/scripts/tests/test_telegram_release.py@@ -0,0 +1,69 @@+import importlib.util+import json+import os+from pathlib import Path+import tempfile+import unittest+from unittest.mock import patch++spec = importlib.util.spec_from_file_location('telegram_release', Path(__file__).parents[1] / 'telegram-release.py')+module = importlib.util.module_from_spec(spec)+spec.loader.exec_module(module)+++def release():+ return {'tag_name': 'v2.4.5', 'name': '2.4.5', 'body': '## Fixed\nConnect and local files.',+ 'html_url': 'https://github.com/Lelonio/Square/releases/tag/v2.4.5',+ 'draft': False, 'published_at': '2026-10-07T10:42:26Z',+ 'assets': [{'name': f'square-2.4.5-{abi}.apk', 'state': 'uploaded', 'size': 20,+ 'browser_download_url': f'https://github.com/Lelonio/Square/releases/download/v2.4.5/square-2.4.5-{abi}.apk'} for abi in module.ABIS]}+++class ReleaseTests(unittest.TestCase):+ def test_notes_keep_every_character_and_respect_emoji_limit(self):+ value = release()+ value['body'] = '🧪 test\n' * 3000+ chunks = module.messages(value)+ self.assertTrue(all(len(c.encode('utf-16-le')) // 2 <= 3500 for c in chunks))+ self.assertEqual(''.join(chunks), f"Square 2.4.5\n\n{value['html_url']}\n\n{value['body']}")++ def test_all_three_apks_required(self):+ value = release()+ value['assets'].pop()+ with self.assertRaisesRegex(ValueError, 'universal'):+ module.apks(value)++ def test_unexpected_download_source_rejected(self):+ value = release()+ value['assets'][0]['browser_download_url'] = 'https://example.com/other.apk'+ with self.assertRaisesRegex(ValueError, 'Unexpected download source'):+ module.apks(value)++ def test_dry_run_never_downloads_or_posts(self):+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / 'release.json'+ path.write_text(json.dumps(release()))+ with patch.dict(os.environ, {'DRY_RUN': 'true', 'TELEGRAM_THREAD_ID': '12'}, clear=True), \+ patch('sys.argv', ['telegram-release.py', str(path)]), \+ patch.object(module.request, 'urlopen') as network, patch('builtins.print') as output:+ module.main()+ network.assert_not_called()+ preview = json.loads(output.call_args.args[0])+ self.assertEqual(preview['destinations'][1]['message_thread_id'], 12)+ self.assertNotIn('message_thread_id', preview['destinations'][0])+ self.assertEqual(len(preview['apks']), 3)++ def test_draft_never_posts(self):+ value = release()+ value['draft'] = True+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / 'release.json'+ path.write_text(json.dumps(value))+ with patch('sys.argv', ['telegram-release.py', str(path)]), patch.object(module.request, 'urlopen') as network:+ with self.assertRaisesRegex(ValueError, 'Only published'):+ module.main()+ network.assert_not_called()+++if __name__ == '__main__':+ unittest.main()