#!/usr/bin/env python3 """Generate the static download website for Asteria Qt releases. Stages built platform packages under /downloads/, optionally fetching missing assets from a Gitea Release, copies static resources from --template-dir (default: /site), substitutes {{PLACEHOLDER}} tokens in HTML templates, and writes manifest.json and downloads/SHA256SUMS. """ from __future__ import annotations import argparse import hashlib import html import json import os import shutil import sys import tarfile import urllib.error import urllib.request import zipfile from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path from typing import Optional @dataclass(frozen=True) class ArtifactSpec: id: str platform: str arch: str label: str archive_name: str raw_names: tuple[str, ...] required: bool format_badge: str install_hint: str ARTIFACT_SPECS: tuple[ArtifactSpec, ...] = ( ArtifactSpec( id="linux-x86_64", platform="Linux", arch="x86_64", label="Linux (x86_64)", archive_name="Asteria-x86_64.AppImage.tar.gz", raw_names=("Asteria-x86_64.AppImage",), required=True, format_badge="AppImage (.tar.gz)", install_hint="tar -xzf Asteria-x86_64.AppImage.tar.gz && ./Asteria-x86_64.AppImage", ), ArtifactSpec( id="linux-arm64", platform="Linux", arch="ARM64", label="Linux (ARM64)", archive_name="Asteria-arm64.AppImage.tar.gz", raw_names=("Asteria-arm64.AppImage",), required=True, format_badge="AppImage (.tar.gz)", install_hint="tar -xzf Asteria-arm64.AppImage.tar.gz && ./Asteria-arm64.AppImage", ), ArtifactSpec( id="windows-x86_64", platform="Windows", arch="x86_64", label="Windows (x86_64)", archive_name="asteria-qt-windows-x86_64.zip", raw_names=("asteria-qt-windows",), required=True, format_badge="Portable ZIP", install_hint="Extract archive and run asteria-qt.exe", ), ArtifactSpec( id="windows-arm64", platform="Windows", arch="ARM64", label="Windows (ARM64)", archive_name="asteria-qt-windows-arm64.zip", raw_names=("asteria-qt-windows-arm64",), required=True, format_badge="Portable ZIP", install_hint="Extract archive and run asteria-qt.exe", ), ArtifactSpec( id="macos", platform="macOS", arch="Universal / Apple Silicon", label="macOS", archive_name="Asteria.dmg", raw_names=(), required=False, format_badge="Disk Image (.dmg)", install_hint="Open Asteria.dmg and drag Asteria to Applications", ), ) TEMPLATE_PARTIALS = {"card.html", "card-unavailable.html"} def format_size(num_bytes: int) -> str: size = float(num_bytes) for unit in ("B", "KiB", "MiB", "GiB"): if size < 1024.0 or unit == "GiB": if unit == "B": return f"{int(size)} B" return f"{size:.1f} {unit}" size /= 1024.0 return f"{num_bytes} B" def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as fh: for chunk in iter(lambda: fh.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def zip_directory(src_dir: Path, dest_zip: Path) -> None: root_name = src_dir.name with zipfile.ZipFile(dest_zip, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zf: for item in sorted(src_dir.rglob("*")): if item.is_file(): arcname = Path(root_name) / item.relative_to(src_dir) zf.write(item, arcname.as_posix()) def targz_appimage(src_file: Path, dest_targz: Path) -> None: with tarfile.open(dest_targz, "w:gz") as tf: info = tf.gettarinfo(str(src_file), arcname=src_file.name) info.mode = 0o755 with src_file.open("rb") as fh: tf.addfile(info, fh) def read_token(token_file: Optional[Path]) -> str: env_token = os.environ.get("BUILD_TOKEN") or os.environ.get("GITEA_TOKEN") or "" if env_token.strip(): return env_token.strip() if token_file and token_file.is_file(): return token_file.read_text(encoding="utf-8").strip() return "" def fetch_missing_from_gitea( input_dir: Path, api_url: str, repo: str, version: str, token: str, ) -> None: needed = { spec.archive_name for spec in ARTIFACT_SPECS if not (input_dir / spec.archive_name).is_file() and not any((input_dir / raw).exists() for raw in spec.raw_names) } if not needed: return tag = version if version.startswith("v") else f"v{version}" release_url = f"{api_url.rstrip('/')}/repos/{repo}/releases/tags/{tag}" headers = {"Accept": "application/json"} if token: headers["Authorization"] = f"token {token}" req = urllib.request.Request(release_url, headers=headers) try: with urllib.request.urlopen(req, timeout=30) as resp: release_data = json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError as exc: raise RuntimeError( f"Failed to query Gitea release {tag} at {release_url}: HTTP {exc.code}" ) from exc except urllib.error.URLError as exc: raise RuntimeError( f"Failed to connect to Gitea release API {release_url}: {exc.reason}" ) from exc assets_by_name = { asset.get("name"): asset for asset in release_data.get("assets", []) if asset.get("name") } for name in sorted(needed): asset = assets_by_name.get(name) if not asset: continue dl_url = asset.get("browser_download_url") if not dl_url: continue dest = input_dir / name dl_headers = {"Accept": "application/octet-stream"} if token: dl_headers["Authorization"] = f"token {token}" dl_req = urllib.request.Request(dl_url, headers=dl_headers) print(f"Downloading {name} from {dl_url}...") with urllib.request.urlopen(dl_req, timeout=300) as resp, dest.open("wb") as out_fh: shutil.copyfileobj(resp, out_fh, length=1024 * 1024) def stage_artifact(spec: ArtifactSpec, input_dir: Path, downloads_dir: Path) -> Optional[dict]: dest_path = downloads_dir / spec.archive_name direct_src = input_dir / spec.archive_name if direct_src.is_file(): shutil.copy2(direct_src, dest_path) else: staged = False for raw_name in spec.raw_names: raw_path = input_dir / raw_name if raw_path.is_dir() and spec.archive_name.endswith(".zip"): zip_directory(raw_path, dest_path) staged = True break if raw_path.is_file() and spec.archive_name.endswith(".tar.gz"): targz_appimage(raw_path, dest_path) staged = True break if not staged: return None size_bytes = dest_path.stat().st_size checksum = sha256_file(dest_path) return { "id": spec.id, "platform": spec.platform, "arch": spec.arch, "label": spec.label, "filename": spec.archive_name, "url": f"downloads/{spec.archive_name}", "format": spec.format_badge, "install_hint": spec.install_hint, "size_bytes": size_bytes, "size_human": format_size(size_bytes), "sha256": checksum, "available": True, } def apply_placeholders(template: str, replacements: dict[str, str]) -> str: rendered = template for key, value in replacements.items(): rendered = rendered.replace(f"{{{{{key}}}}}", value) return rendered def copy_static_resources(template_dir: Path, output_dir: Path) -> None: for item in template_dir.iterdir(): if item.name in TEMPLATE_PARTIALS or item.name == "index.html": continue dest = output_dir / item.name if item.is_dir(): shutil.copytree(item, dest, dirs_exist_ok=True) elif item.is_file(): shutil.copy2(item, dest) def render_site_html(template_dir: Path, manifest: dict) -> str: index_tpl = (template_dir / "index.html").read_text(encoding="utf-8") card_tpl = (template_dir / "card.html").read_text(encoding="utf-8") card_unavail_tpl = (template_dir / "card-unavailable.html").read_text(encoding="utf-8") cards: list[str] = [] for item in manifest["artifacts"]: if item["available"]: cards.append( apply_placeholders( card_tpl, { "LABEL": html.escape(item["label"]), "FORMAT": html.escape(item["format"]), "SIZE": html.escape(item["size_human"]), "INSTALL_HINT": html.escape(item["install_hint"]), "URL": html.escape(item["url"]), "FILENAME": html.escape(item["filename"]), "SHA256": html.escape(item["sha256"]), }, ).rstrip("\n") ) else: cards.append( apply_placeholders( card_unavail_tpl, { "LABEL": html.escape(item["label"]), "FORMAT": html.escape(item["format"]), }, ).rstrip("\n") ) version = manifest["version"] repo_url = manifest["repo_url"] release_url = f"{repo_url.rstrip('/')}/releases/tag/v{version}" run_url = manifest["run_url"] or release_url return apply_placeholders( index_tpl, { "VERSION": html.escape(version), "BRANCH": html.escape(manifest["commit_branch"]), "COMMIT_SHA": html.escape(manifest["commit_sha"]), "BUILT_AT": html.escape(manifest["built_at"]), "RUN_ID": html.escape(str(manifest["run_id"])), "RUN_URL": html.escape(run_url), "RELEASE_URL": html.escape(release_url), "REPO_URL": html.escape(repo_url), "PLATFORM_CARDS": "\n".join(cards), }, ) def parse_args() -> argparse.Namespace: default_root = Path(__file__).resolve().parent.parent parser = argparse.ArgumentParser(description="Generate Asteria Qt static download website.") parser.add_argument("--input-dir", required=True, type=Path, help="Directory containing built packages.") parser.add_argument("--output-dir", required=True, type=Path, help="Output static site root directory.") parser.add_argument( "--template-dir", type=Path, default=default_root / "site", help="Directory containing static HTML/CSS/JS templates (default: /site).", ) parser.add_argument("--version", required=True, help="Asteria version string (e.g. 0.1.4).") parser.add_argument("--commit-sha", default="unknown", help="Short commit SHA.") parser.add_argument("--commit-branch", default="master", help="Git branch name.") parser.add_argument("--run-id", default="0", help="CI workflow run ID.") parser.add_argument("--run-url", default="", help="CI workflow run URL.") parser.add_argument("--repo-url", default="https://gitea.agel.dev/Asteria/asteria-qt", help="Repository web URL.") parser.add_argument( "--icon", type=Path, default=default_root / "packaging" / "icons" / "128x128" / "asteria-qt.png", help="PNG logo/favicon path copied to assets/logo.png.", ) parser.add_argument("--gitea-api-url", default="", help="Optional Gitea API base URL for fetching release assets.") parser.add_argument("--gitea-repo", default="", help="Optional owner/repo slug for Gitea Release API.") parser.add_argument("--gitea-token-file", type=Path, default=None, help="Optional file containing Gitea API token.") parser.add_argument("--require-core", action="store_true", help="Fail if any required Linux/Windows artifact is missing.") return parser.parse_args() def main() -> int: args = parse_args() input_dir: Path = args.input_dir output_dir: Path = args.output_dir template_dir: Path = args.template_dir for required_tpl in ("index.html", *TEMPLATE_PARTIALS): if not (template_dir / required_tpl).is_file(): print(f"ERROR: Missing static template file: {template_dir / required_tpl}", file=sys.stderr) return 1 input_dir.mkdir(parents=True, exist_ok=True) if args.gitea_api_url and args.gitea_repo: token = read_token(args.gitea_token_file) fetch_missing_from_gitea( input_dir=input_dir, api_url=args.gitea_api_url, repo=args.gitea_repo, version=args.version, token=token, ) if output_dir.exists(): shutil.rmtree(output_dir) downloads_dir = output_dir / "downloads" downloads_dir.mkdir(parents=True, exist_ok=True) copy_static_resources(template_dir, output_dir) if args.icon and args.icon.is_file(): assets_dir = output_dir / "assets" assets_dir.mkdir(parents=True, exist_ok=True) shutil.copy2(args.icon, assets_dir / "logo.png") artifacts: list[dict] = [] missing_required: list[str] = [] checksum_lines: list[str] = [] for spec in ARTIFACT_SPECS: entry = stage_artifact(spec, input_dir, downloads_dir) if entry is None: if spec.required: missing_required.append(spec.archive_name) artifacts.append( { "id": spec.id, "platform": spec.platform, "arch": spec.arch, "label": spec.label, "filename": spec.archive_name, "url": None, "format": spec.format_badge, "install_hint": spec.install_hint, "size_bytes": 0, "size_human": None, "sha256": None, "available": False, } ) else: artifacts.append(entry) checksum_lines.append(f"{entry['sha256']} {entry['filename']}") if args.require_core and missing_required: print( f"ERROR: Missing required core artifacts in {input_dir}: {', '.join(missing_required)}", file=sys.stderr, ) return 1 (downloads_dir / "SHA256SUMS").write_text( ("\n".join(checksum_lines) + "\n") if checksum_lines else "", encoding="utf-8", ) manifest = { "name": "Asteria Qt", "version": args.version, "commit_sha": args.commit_sha, "commit_branch": args.commit_branch, "run_id": args.run_id, "run_url": args.run_url, "repo_url": args.repo_url, "built_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "artifacts": artifacts, } (output_dir / "manifest.json").write_text( json.dumps(manifest, indent=2) + "\n", encoding="utf-8", ) (output_dir / "index.html").write_text( render_site_html(template_dir, manifest), encoding="utf-8", ) available_count = sum(1 for a in artifacts if a["available"]) print(f"Generated static site in {output_dir} for v{args.version} ({available_count}/{len(artifacts)} packages).") return 0 if __name__ == "__main__": sys.exit(main())