208 lines
7.3 KiB
Python
208 lines
7.3 KiB
Python
#!/usr/bin/env python3
|
|
# /// script
|
|
# requires-python = ">=3.13"
|
|
# dependencies = ["pillow", "lottie", "cairosvg", "pydantic>=2", "typer", "httpx"]
|
|
# ///
|
|
# How to run: prefer Nix wrapper (README.md); python import_pack.py --help.
|
|
"""Import a Telegram sticker pack without disclosing bot credentials."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import signal
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
from typing import TYPE_CHECKING, Annotated, Final
|
|
|
|
import typer
|
|
from PIL import Image
|
|
|
|
from cache import load_catalog, transaction
|
|
from models import (
|
|
ASSET_BYTES,
|
|
PACK_LIMIT,
|
|
STICKER_LIMIT,
|
|
TOTAL_BYTES,
|
|
Envelope,
|
|
FailureReason,
|
|
ImportFailureError,
|
|
Pack,
|
|
RemoteFile,
|
|
RemotePack,
|
|
Sticker,
|
|
)
|
|
from telegram import Telegram, pack_name, read_token
|
|
|
|
if TYPE_CHECKING:
|
|
from types import FrameType
|
|
|
|
ROOT: Final = Path(__file__).resolve().parent
|
|
|
|
|
|
class JobTimeoutError(Exception):
|
|
"""Import exceeded server-compatible whole-job deadline."""
|
|
|
|
|
|
def deadline_expired(_signum: int, _frame: FrameType | None) -> None:
|
|
"""Interrupt the CLI when its whole-job timer expires."""
|
|
raise JobTimeoutError
|
|
|
|
|
|
def render_atlas(source: Path, kind: str, destination: Path) -> int:
|
|
"""Run the bounded conversion worker and reap its entire process group."""
|
|
with subprocess.Popen(
|
|
[
|
|
sys.executable,
|
|
str(ROOT / "convert.py"),
|
|
str(source),
|
|
kind,
|
|
str(destination),
|
|
],
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.DEVNULL,
|
|
start_new_session=True,
|
|
) as worker:
|
|
try:
|
|
stdout, _ = worker.communicate(timeout=45)
|
|
finally:
|
|
# Kill entire worker group, including a still-running decoder.
|
|
try:
|
|
os.killpg(worker.pid, signal.SIGKILL)
|
|
except ProcessLookupError:
|
|
_ = worker.poll()
|
|
if worker.returncode != 0:
|
|
raise ImportFailureError(FailureReason.CONVERSION_FAILED)
|
|
return int(stdout)
|
|
|
|
|
|
def import_pack(api: Telegram, name: str, output: Path) -> Pack:
|
|
"""Download, convert and atomically publish one credential-free pack."""
|
|
stickers: list[Sticker] = []
|
|
seen: set[str] = set()
|
|
generated_bytes = 0
|
|
with transaction(output) as cache:
|
|
stage = cache.stage
|
|
remote = (
|
|
Envelope[RemotePack]
|
|
.model_validate_json(api.method("getStickerSet", "name", name))
|
|
.result
|
|
)
|
|
if remote.name.casefold() != name.casefold():
|
|
raise ImportFailureError(FailureReason.BOT_API_RETURNED_A_DIFFERENT_PACK)
|
|
old = load_catalog(output / "catalog.json")
|
|
remaining = [p for p in old.packs if p.id != remote.name]
|
|
if (
|
|
len(remaining) >= PACK_LIMIT
|
|
or sum(len(p.stickers) for p in remaining) >= STICKER_LIMIT
|
|
):
|
|
raise ImportFailureError(FailureReason.CATALOG_HAS_NO_ROOM_FOR_ANOTHER_PACK)
|
|
for completed, item in enumerate(remote.stickers):
|
|
info = (
|
|
Envelope[RemoteFile]
|
|
.model_validate_json(
|
|
api.method("getFile", "file_id", item.file_id),
|
|
)
|
|
.result
|
|
)
|
|
kind = "tgs" if item.is_animated else "webm" if item.is_video else "webp"
|
|
if not info.file_path.lower().endswith("." + kind):
|
|
raise ImportFailureError(FailureReason.BOT_API_FILE_FORMAT_MISMATCH)
|
|
data = api.download(info.file_path)
|
|
if any(
|
|
size is not None and size != len(data)
|
|
for size in (info.file_size, item.file_size)
|
|
):
|
|
raise ImportFailureError(FailureReason.BOT_API_FILE_SIZE_MISMATCH)
|
|
source = stage / ("input." + kind)
|
|
_ = source.write_bytes(data)
|
|
typer.echo(
|
|
json.dumps(
|
|
{
|
|
"status": "converting",
|
|
"completed": completed,
|
|
"total": len(remote.stickers),
|
|
}
|
|
)
|
|
)
|
|
atlas_path = stage / "atlas.png"
|
|
frames = render_atlas(source, kind, atlas_path)
|
|
png = atlas_path.read_bytes()
|
|
generated_bytes += len(png)
|
|
if len(png) > ASSET_BYTES or generated_bytes > TOTAL_BYTES:
|
|
raise ImportFailureError(
|
|
FailureReason.GENERATED_ASSET_SIZE_LIMIT_EXCEEDED
|
|
)
|
|
sticker = Sticker(
|
|
id=hashlib.sha256(png).hexdigest(), emoji=item.emoji, frames=frames
|
|
)
|
|
columns = min(8, frames)
|
|
with Image.open(atlas_path) as image:
|
|
if image.format != "PNG" or image.size != (
|
|
columns * 128,
|
|
((frames + columns - 1) // columns) * 128,
|
|
):
|
|
raise ImportFailureError(FailureReason.INVALID_ATLAS_DIMENSIONS)
|
|
image.verify()
|
|
if sticker.id not in seen:
|
|
seen.add(sticker.id)
|
|
_ = atlas_path.rename(stage / (sticker.id + ".png"))
|
|
stickers.append(sticker)
|
|
pack = Pack(id=remote.name, title=remote.title, stickers=stickers)
|
|
if api.token in pack.model_dump_json() or api.token in old.model_dump_json():
|
|
raise ImportFailureError(FailureReason.CATALOG_CREDENTIAL_SAFETY_VIOLATION)
|
|
# Do not turn a committed catalog into a reported timeout during cleanup.
|
|
_ = signal.setitimer(signal.ITIMER_REAL, 0)
|
|
cache.publish(pack)
|
|
return pack
|
|
|
|
|
|
def main(
|
|
token_file: Annotated[
|
|
Path, typer.Option(help="Explicit bot token file; never read from environment.")
|
|
],
|
|
pack: Annotated[
|
|
str, typer.Option(help="Telegram short name or HTTPS addstickers URL.")
|
|
],
|
|
output: Annotated[
|
|
Path, typer.Option(help="Catalog and content-addressed asset cache.")
|
|
],
|
|
api_base: Annotated[
|
|
str, typer.Option(help="Bot API origin; HTTP only for loopback local servers.")
|
|
] = "https://api.telegram.org",
|
|
) -> None:
|
|
"""Emit the CLI status protocol without exposing credential-bearing errors."""
|
|
# Transport and validation errors can contain secrets; never echo their text.
|
|
previous = signal.signal(signal.SIGALRM, deadline_expired)
|
|
try:
|
|
_ = signal.setitimer(signal.ITIMER_REAL, 270)
|
|
name = pack_name(pack)
|
|
token = read_token(token_file)
|
|
typer.echo('{"status":"fetching"}')
|
|
with Telegram(api_base, token) as api:
|
|
imported = import_pack(api, name, output)
|
|
typer.echo(
|
|
json.dumps(
|
|
{
|
|
"status": "complete",
|
|
"pack": imported.id,
|
|
"stickers": len(imported.stickers),
|
|
}
|
|
)
|
|
)
|
|
except JobTimeoutError:
|
|
typer.echo('{"status":"error","code":"job_timeout"}', err=True)
|
|
raise typer.Exit(1) from None
|
|
except Exception: # noqa: BLE001 # noqa: BROAD_EXCEPT_OK (credential-safe CLI boundary)
|
|
typer.echo('{"status":"error","code":"import_failed"}', err=True)
|
|
raise typer.Exit(1) from None
|
|
finally:
|
|
_ = signal.setitimer(signal.ITIMER_REAL, 0)
|
|
_ = signal.signal(signal.SIGALRM, previous)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
typer.run(main)
|