diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..833f20a952f8d0f73994bf261354daf4e52d0c74 --- /dev/null +++ b/.env.example @@ -0,0 +1,25 @@ +# --- Telegram ------------------------------------------------------------- +API_ID= +API_HASH= +BOT_TOKEN= +# Numeric Telegram ids (ask @userinfobot). Owners can manage admins in the bot. +OWNER_IDS= + +# --- Database ------------------------------------------------------------- +# PostgreSQL, e.g. a free Neon database. Leave empty to use a local SQLite file (data/bot.db). +DATABASE_URL=postgresql://user:password@host/dbname?sslmode=require +# "null" = short-lived connections (lets serverless Postgres sleep); "queue" = normal pool for an always-on DB +DB_POOL=null + +# --- Optional ------------------------------------------------------------- +# Where the login session is kept. On hosts that wipe files on restart, run `python make_session.py` +# once and put the printed text in SESSION_STRING instead. +SESSION_PATH=data/bot +SESSION_STRING= +# Seconds between edits during /replace (Telegram rate limits: don't go much lower) +EDIT_DELAY=1.2 +# Also swap links that are typed as plain text in a post (not only hyperlinks and buttons) +REPLACE_TYPED_LINKS=true +# Some free hosts need an open port: set it and the bot answers "ok" on / +PORT= +LOG_LEVEL=INFO diff --git a/.gitattributes b/.gitattributes index c7d9f3332a950355d5a77d85000f05e6f45435ea..ce0ba8d6f17437c91df7fc08d5899d44a7a97d18 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,34 +1,8 @@ -*.7z filter=lfs diff=lfs merge=lfs -text -*.arrow filter=lfs diff=lfs merge=lfs -text -*.bin filter=lfs diff=lfs merge=lfs -text -*.bz2 filter=lfs diff=lfs merge=lfs -text -*.ckpt filter=lfs diff=lfs merge=lfs -text -*.ftz filter=lfs diff=lfs merge=lfs -text -*.gz filter=lfs diff=lfs merge=lfs -text -*.h5 filter=lfs diff=lfs merge=lfs -text -*.joblib filter=lfs diff=lfs merge=lfs -text -*.lfs.* filter=lfs diff=lfs merge=lfs -text -*.mlmodel filter=lfs diff=lfs merge=lfs -text -*.model filter=lfs diff=lfs merge=lfs -text -*.msgpack filter=lfs diff=lfs merge=lfs -text -*.npy filter=lfs diff=lfs merge=lfs -text -*.npz filter=lfs diff=lfs merge=lfs -text -*.onnx filter=lfs diff=lfs merge=lfs -text -*.ot filter=lfs diff=lfs merge=lfs -text -*.parquet filter=lfs diff=lfs merge=lfs -text -*.pb filter=lfs diff=lfs merge=lfs -text -*.pickle filter=lfs diff=lfs merge=lfs -text -*.pkl filter=lfs diff=lfs merge=lfs -text -*.pt filter=lfs diff=lfs merge=lfs -text -*.pth filter=lfs diff=lfs merge=lfs -text -*.rar filter=lfs diff=lfs merge=lfs -text -*.safetensors filter=lfs diff=lfs merge=lfs -text -saved_model/**/* filter=lfs diff=lfs merge=lfs -text -*.tar.* filter=lfs diff=lfs merge=lfs -text -*.tflite filter=lfs diff=lfs merge=lfs -text -*.tgz filter=lfs diff=lfs merge=lfs -text -*.wasm filter=lfs diff=lfs merge=lfs -text -*.xz filter=lfs diff=lfs merge=lfs -text -*.zip filter=lfs diff=lfs merge=lfs -text -*.zst filter=lfs diff=lfs merge=lfs -text -*tfevents* filter=lfs diff=lfs merge=lfs -text +*.webp filter=lfs diff=lfs merge=lfs -text +*.mp4 filter=lfs diff=lfs merge=lfs -text +*.mp3 filter=lfs diff=lfs merge=lfs -text +*.jpg filter=lfs diff=lfs merge=lfs -text +*.jpeg filter=lfs diff=lfs merge=lfs -text +*.png filter=lfs diff=lfs merge=lfs -text +*.ttf filter=lfs diff=lfs merge=lfs -text +*.otf filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..4efd6e5594ee6a53773dc7e884abf95daa13ed83 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.env +data/* +!data/.gitkeep +*.session +*.session-journal +__pycache__/ +.pytest_cache/ diff --git a/Dockerfile b/Dockerfile index 4cbd0811c1f68dac29329e28375ec76269b1b763..a29582babf908f26e2ec7b613b54c9bc3c23b65a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,16 +1,7 @@ -FROM python:3.11 - -WORKDIR /code - -COPY ./requirements.txt /code/requirements.txt -RUN python3 -m pip install --no-cache-dir --upgrade pip -RUN python3 -m pip install --no-cache-dir --upgrade -r /code/requirements.txt - +FROM python:3.12-slim +WORKDIR /app +ENV PYTHONUNBUFFERED=1 +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt COPY . . - -CMD ["panel", "serve", "/code/app.py", "--address", "0.0.0.0", "--port", "7860", "--allow-websocket-origin", "*"] - -RUN mkdir /.cache -RUN chmod 777 /.cache -RUN mkdir .chroma -RUN chmod 777 .chroma \ No newline at end of file +CMD python -m http.server 7860 & python bot.py diff --git a/app.py b/app.py deleted file mode 100644 index 80716243cc0125867750fa75049719e3a22eaf62..0000000000000000000000000000000000000000 --- a/app.py +++ /dev/null @@ -1,147 +0,0 @@ -import io -import random -from typing import List, Tuple - -import aiohttp -import panel as pn -from PIL import Image -from transformers import CLIPModel, CLIPProcessor - -pn.extension(design="bootstrap", sizing_mode="stretch_width") - -ICON_URLS = { - "brand-github": "https://github.com/holoviz/panel", - "brand-twitter": "https://twitter.com/Panel_Org", - "brand-linkedin": "https://www.linkedin.com/company/panel-org", - "message-circle": "https://discourse.holoviz.org/", - "brand-discord": "https://discord.gg/AXRHnJU6sP", -} - - -async def random_url(_): - pet = random.choice(["cat", "dog"]) - api_url = f"https://api.the{pet}api.com/v1/images/search" - async with aiohttp.ClientSession() as session: - async with session.get(api_url) as resp: - return (await resp.json())[0]["url"] - - -@pn.cache -def load_processor_model( - processor_name: str, model_name: str -) -> Tuple[CLIPProcessor, CLIPModel]: - processor = CLIPProcessor.from_pretrained(processor_name) - model = CLIPModel.from_pretrained(model_name) - return processor, model - - -async def open_image_url(image_url: str) -> Image: - async with aiohttp.ClientSession() as session: - async with session.get(image_url) as resp: - return Image.open(io.BytesIO(await resp.read())) - - -def get_similarity_scores(class_items: List[str], image: Image) -> List[float]: - processor, model = load_processor_model( - "openai/clip-vit-base-patch32", "openai/clip-vit-base-patch32" - ) - inputs = processor( - text=class_items, - images=[image], - return_tensors="pt", # pytorch tensors - ) - outputs = model(**inputs) - logits_per_image = outputs.logits_per_image - class_likelihoods = logits_per_image.softmax(dim=1).detach().numpy() - return class_likelihoods[0] - - -async def process_inputs(class_names: List[str], image_url: str): - """ - High level function that takes in the user inputs and returns the - classification results as panel objects. - """ - try: - main.disabled = True - if not image_url: - yield "##### ⚠️ Provide an image URL" - return - - yield "##### ⚙ Fetching image and running model..." - try: - pil_img = await open_image_url(image_url) - img = pn.pane.Image(pil_img, height=400, align="center") - except Exception as e: - yield f"##### 😔 Something went wrong, please try a different URL!" - return - - class_items = class_names.split(",") - class_likelihoods = get_similarity_scores(class_items, pil_img) - - # build the results column - results = pn.Column("##### 🎉 Here are the results!", img) - - for class_item, class_likelihood in zip(class_items, class_likelihoods): - row_label = pn.widgets.StaticText( - name=class_item.strip(), value=f"{class_likelihood:.2%}", align="center" - ) - row_bar = pn.indicators.Progress( - value=int(class_likelihood * 100), - sizing_mode="stretch_width", - bar_color="secondary", - margin=(0, 10), - design=pn.theme.Material, - ) - results.append(pn.Column(row_label, row_bar)) - yield results - finally: - main.disabled = False - - -# create widgets -randomize_url = pn.widgets.Button(name="Randomize URL", align="end") - -image_url = pn.widgets.TextInput( - name="Image URL to classify", - value=pn.bind(random_url, randomize_url), -) -class_names = pn.widgets.TextInput( - name="Comma separated class names", - placeholder="Enter possible class names, e.g. cat, dog", - value="cat, dog, parrot", -) - -input_widgets = pn.Column( - "##### 😊 Click randomize or paste a URL to start classifying!", - pn.Row(image_url, randomize_url), - class_names, -) - -# add interactivity -interactive_result = pn.panel( - pn.bind(process_inputs, image_url=image_url, class_names=class_names), - height=600, -) - -# add footer -footer_row = pn.Row(pn.Spacer(), align="center") -for icon, url in ICON_URLS.items(): - href_button = pn.widgets.Button(icon=icon, width=35, height=35) - href_button.js_on_click(code=f"window.open('{url}')") - footer_row.append(href_button) -footer_row.append(pn.Spacer()) - -# create dashboard -main = pn.WidgetBox( - input_widgets, - interactive_result, - footer_row, -) - -title = "Panel Demo - Image Classification" -pn.template.BootstrapTemplate( - title=title, - main=main, - main_max_width="min(50%, 698px)", - header_background="#F08080", -).servable(title=title) \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/autopost.py b/app/autopost.py new file mode 100644 index 0000000000000000000000000000000000000000..768d6c6437bc36de36741f7ba7482518b426f106 --- /dev/null +++ b/app/autopost.py @@ -0,0 +1,81 @@ +"""/autopost: the posts of a whole series - "Episodes 01 to 20", "Episodes 21 to 40", ... - each with a download button. + +The ranges are planned here (pure functions, easy to test); the handler in handlers/autopost.py sends them. +""" +from __future__ import annotations + +PLACEHOLDER_LINK = "https://t.me/English" # every button starts with this link; the real ones are asked for afterwards +MAX_POSTS = 200 # the most one /autopost run may post +MAX_EPISODES = 100_000 + +USAGE = ( + "Usage: /autopost <total episodes> <interval>\n" + "Example: /autopost 114 20 posts Episodes 01 to 20, 21 to 40 ... up to 114, each with a download " + "button, and then asks you for the real link of every button." +) + + +def parse_autopost_args(raw: str) -> tuple: + """'114 20' -> (114, 20). ValueError (with a message to show) when it can't be used.""" + parts = (raw or "").replace(",", " ").split() + if len(parts) != 2 or not all(p.isdigit() for p in parts): + raise ValueError("I need two numbers: the total number of episodes and the interval.") + total, interval = int(parts[0]), int(parts[1]) + if total < 1 or interval < 1: + raise ValueError("Both numbers must be at least 1.") + if total > MAX_EPISODES: + raise ValueError(f"The total can be at most {MAX_EPISODES}.") + return total, interval + + +def plan_ranges(total: int, interval: int) -> list: + """[(first, last), ...] covering 1..total in steps of `interval`. + + The last, shorter range gets its own post when it is longer than half an interval (114 with 20 -> 101 to 114); + when it is half an interval or less it is added to the post before it (102 with 20 -> 81 to 102).""" + if total < 1 or interval < 1: + raise ValueError("total and interval must be at least 1") + ranges, start = [], 1 + while start <= total: + end = min(start + interval - 1, total) + ranges.append((start, end)) + start = end + 1 + if len(ranges) >= 2: + a, b = ranges[-1] + size = b - a + 1 + if size < interval and size * 2 <= interval: + ranges.pop() + ranges[-1] = (ranges[-1][0], b) + return ranges + + +def pad(n: int) -> str: + return f"{n:02d}" + + +def span(a: int, b: int) -> str: + return f"{pad(a)} to {pad(b)}" + + +def title_of(a: int, b: int) -> str: + return f"Episodes {span(a, b)}" if a != b else f"Episode {pad(a)}" + + +def post_text(a: int, b: int) -> str: + return f"{title_of(a, b)}\n\nClick the button below to download 👇" + + +def button_label(a: int, b: int) -> str: + return f"Download {title_of(a, b)}" + + +def post_buttons(a: int, b: int, link: str = PLACEHOLDER_LINK) -> list: + return [[{"t": button_label(a, b), "u": link}]] + + +def ranges_summary(ranges: list, show: int = 8) -> str: + """'01–20 · 21–40 · 41–60 · … · 101–114' (the middle is left out of long lists).""" + parts = [f"{pad(a)}–{pad(b)}" if a != b else pad(a) for a, b in ranges] + if len(parts) > show: + parts = parts[: show - 2] + ["…"] + parts[-2:] + return " · ".join(parts) diff --git a/app/backup.py b/app/backup.py new file mode 100644 index 0000000000000000000000000000000000000000..67f67728423f3fa576d4638f3c4de7caad92adf2 --- /dev/null +++ b/app/backup.py @@ -0,0 +1,337 @@ +"""Putting a backup made by /export back into the bot (/import). + +The backup is a JSON file: {"exported_at", "channels": [...], "posts": [...], "ignored": [...]}. Importing only ADDS: + + * a channel the bot already has is left as it is (its title, username and access come from Telegram, which is newer + than the file); a channel it does not have is added; + * a post at a message id the bot already has is left as it is; every other published post is added, and so is every + draft that is not already here; + * a post the owner has made the bot forget (/posts -> Only forget it in the bot) is not brought back; + * nothing is ever deleted or overwritten. + +The file is read as data only: every value is checked before it goes near the database. +""" +from __future__ import annotations + +import json +import logging +from dataclasses import dataclass, field +from datetime import datetime, timezone +from typing import Optional + +from sqlalchemy import select +from sqlalchemy.exc import IntegrityError + +from .db import Channel, Database, IgnoredPost, Post, as_utc, utcnow + +log = logging.getLogger(__name__) + +MAX_BYTES = 40 * 1024 * 1024 # a backup of tens of thousands of posts is a few megabytes +CHUNK = 500 # rows saved in one go +POST_KINDS = ("draft", "sent") +SOURCES = ("bot", "adopted") + + +class BackupError(ValueError): + """The file can't be used; the message says why (and is safe to show).""" + + +# ------------------------------------------------------------------------------------------------ reading +def _int(value, what: str) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"{what} is not a whole number") + return value + + +def _text(value, what: str, limit: Optional[int] = None) -> str: + if value is None: + return "" + if not isinstance(value, str): + raise ValueError(f"{what} is not text") + return value[:limit] if limit else value + + +def _when(value, what: str, default: Optional[datetime] = None) -> Optional[datetime]: + if value in (None, ""): + return default + if not isinstance(value, str): + raise ValueError(f"{what} is not a date") + try: + d = datetime.fromisoformat(value.strip().replace("Z", "+00:00")) + except ValueError: + raise ValueError(f"{what} is not a date") + return as_utc(d) + + +def _rows_of(value, what: str) -> list: + if value is None: + return [] + if not isinstance(value, list): + raise BackupError(f"“{what}” should be a list.") + return value + + +def channel_row(row) -> dict: + """One channel of the file as the values for a Channel row (ValueError if it is not usable).""" + if not isinstance(row, dict): + raise ValueError("not an object") + cid = _int(row.get("id"), "id") + if cid == 0: + raise ValueError("id is 0") + username = _text(row.get("username"), "username", 64).strip().lstrip("@") or None + created = _when(row.get("created_at"), "created_at", utcnow()) + return dict( + id=cid, + access_hash=_int(row.get("access_hash", 0) or 0, "access_hash"), + title=_text(row.get("title"), "title", 256), + username=username, + active=bool(row.get("active", True)), + added_by=_int(row.get("added_by", 0) or 0, "added_by"), + created_at=created, + ) + + +def _buttons(value) -> list: + if value is None: + return [] + if not isinstance(value, list): + raise ValueError("buttons are not a list") + for line in value: + if not isinstance(line, list) or not all(isinstance(b, dict) for b in line): + raise ValueError("buttons are not rows of buttons") + return value + + +def _entities(value) -> list: + if value is None: + return [] + if not isinstance(value, list) or not all(isinstance(e, dict) for e in value): + raise ValueError("formatting is not a list") + return value + + +def post_row(row) -> dict: + """One post of the file as the values for a Post row (ValueError if it is not usable).""" + if not isinstance(row, dict): + raise ValueError("not an object") + cid = _int(row.get("channel_id"), "channel_id") + mid = row.get("message_id") + mid = None if mid is None else _int(mid, "message_id") + status = row.get("status") or ("sent" if mid else "draft") + if status not in POST_KINDS: + raise ValueError(f"status “{str(status)[:20]}” is unknown") + if status == "sent" and (mid is None or mid < 1): + raise ValueError("a published post without a message id") + if status == "draft": + mid = None + source = row.get("source") if row.get("source") in SOURCES else "bot" + kind = row.get("media_kind") + if kind is not None and (not isinstance(kind, str) or len(kind) > 16): + raise ValueError("media_kind is not usable") + ref = row.get("media_file_id") + if ref is not None and not isinstance(ref, str): + raise ValueError("media_file_id is not text") + created = _when(row.get("created_at"), "created_at", utcnow()) + return dict( + channel_id=cid, + message_id=mid, + status=status, + source=source, + text=_text(row.get("text"), "text"), + entities=_entities(row.get("entities")), + media_kind=kind or None, + media_file_id=ref or None, + buttons=_buttons(row.get("buttons")), + link_preview=bool(row.get("link_preview")), + created_by=_int(row.get("created_by", 0) or 0, "created_by"), + created_at=created, + updated_at=_when(row.get("updated_at"), "updated_at", created), + sent_at=_when(row.get("sent_at"), "sent_at"), + ) + + +@dataclass +class Backup: + exported_at: Optional[str] = None + channels: list = field(default_factory=list) # dicts for Channel(**d) + posts: list = field(default_factory=list) # dicts for Post(**d) + ignored: list = field(default_factory=list) # (channel id, message id) + bad_rows: int = 0 # entries of the file that were not usable and are left out + + +def parse_backup(raw: bytes) -> Backup: + """The file's bytes -> a Backup. BackupError (with a message for the person) when it is not an /export file.""" + if len(raw) > MAX_BYTES: + raise BackupError(f"it is larger than {MAX_BYTES // (1024 * 1024)} MB.") + try: + data = json.loads(raw.decode("utf-8-sig")) + except (UnicodeDecodeError, ValueError): + raise BackupError("it is not a JSON file. Send the file that /export made, unchanged.") + if not isinstance(data, dict) or ("channels" not in data and "posts" not in data): + raise BackupError("it does not look like a backup from /export (no channels and posts in it).") + bk = Backup(exported_at=data.get("exported_at") if isinstance(data.get("exported_at"), str) else None) + for row in _rows_of(data.get("channels"), "channels"): + try: + bk.channels.append(channel_row(row)) + except (ValueError, TypeError): + bk.bad_rows += 1 + for row in _rows_of(data.get("posts"), "posts"): + try: + bk.posts.append(post_row(row)) + except (ValueError, TypeError): + bk.bad_rows += 1 + for row in _rows_of(data.get("ignored"), "ignored"): + try: + if not isinstance(row, dict): + raise ValueError("not an object") + bk.ignored.append((_int(row.get("channel_id"), "channel_id"), _int(row.get("message_id"), "message_id"))) + except (ValueError, TypeError): + bk.bad_rows += 1 + if not (bk.channels or bk.posts): + raise BackupError("there is nothing in it that can be imported." + (" (All entries were unreadable.)" if bk.bad_rows else "")) + return bk + + +# ------------------------------------------------------------------------------------------------ the plan +@dataclass +class ImportPlan: + backup: Backup + new_channels: list = field(default_factory=list) # channel dicts that are not in the bot yet + channels_present: int = 0 # channels of the file the bot has already (left as they are) + new_posts: list = field(default_factory=list) # published posts and drafts to add + posts_present: int = 0 # published posts at a message id the bot already has + drafts_present: int = 0 # drafts that are here already + posts_forgotten: int = 0 # posts the owner made the bot forget: not brought back + posts_orphaned: int = 0 # posts of a channel that is neither in the bot nor in the file + new_ignored: list = field(default_factory=list) # "forgotten" marks to add + + @property + def sent_to_add(self) -> int: + return sum(1 for p in self.new_posts if p["status"] == "sent") + + @property + def drafts_to_add(self) -> int: + return sum(1 for p in self.new_posts if p["status"] == "draft") + + @property + def nothing_new(self) -> bool: + return not (self.new_channels or self.new_posts or self.new_ignored) + + +async def plan_import(db: Database, backup: Backup) -> ImportPlan: + """What importing would do - nothing is written.""" + plan = ImportPlan(backup=backup) + async with db.Session() as s: + have_channels = {int(c) for c in (await s.execute(select(Channel.id))).scalars()} + known_marks = {(int(c), int(m)) for c, m in (await s.execute(select(IgnoredPost.channel_id, IgnoredPost.message_id))).all()} + wanted = {p["channel_id"] for p in backup.posts} + have_posts: set = set() + have_drafts: set = set() + if wanted: + q = select(Post.channel_id, Post.message_id).where(Post.message_id.is_not(None)) + have_posts = {(int(c), int(m)) for c, m in (await s.execute(q)).all() if int(c) in wanted} + q = select(Post.channel_id, Post.text, Post.created_at).where(Post.status == "draft") + have_drafts = {(int(c), t, as_utc(at)) for c, t, at in (await s.execute(q)).all() if int(c) in wanted} + in_file: dict = {} + for ch in backup.channels: + if ch["id"] in have_channels: + plan.channels_present += 1 + elif ch["id"] not in in_file: + in_file[ch["id"]] = ch + plan.new_channels.append(ch) + marks = set(known_marks) + for mark in backup.ignored: + if mark[0] in have_channels or mark[0] in in_file: + if mark not in marks: + marks.add(mark) + plan.new_ignored.append(mark) + seen_posts: set = set() + seen_drafts: set = set() + for p in backup.posts: + cid = p["channel_id"] + if cid not in have_channels and cid not in in_file: + plan.posts_orphaned += 1 + elif p["status"] == "sent": + key = (cid, p["message_id"]) + if key in marks: + plan.posts_forgotten += 1 + elif key in have_posts or key in seen_posts: + plan.posts_present += 1 + else: + seen_posts.add(key) + plan.new_posts.append(p) + else: + key = (cid, p["text"], p["created_at"]) + if key in have_drafts or key in seen_drafts: + plan.drafts_present += 1 + else: + seen_drafts.add(key) + plan.new_posts.append(p) + return plan + + +# ----------------------------------------------------------------------------------------------- doing it +@dataclass +class ImportResult: + channels_added: int = 0 + posts_added: int = 0 + drafts_added: int = 0 + marks_added: int = 0 + skipped_meanwhile: int = 0 # posts that turned up in the bot while the import was running + + +async def _save_posts(db: Database, rows: list) -> list: + """Save these posts; returns the ones that were saved (one that is there already is skipped, never an error).""" + async with db.Session() as s: + s.add_all([Post(**r) for r in rows]) + try: + await s.commit() + return list(rows) + except IntegrityError: + await s.rollback() + saved = [] + for r in rows: # one is there already: one by one + async with db.Session() as s: + s.add(Post(**r)) + try: + await s.commit() + saved.append(r) + except IntegrityError: + await s.rollback() + return saved + + +async def apply_import(db: Database, plan: ImportPlan, progress=None) -> ImportResult: + """Write the plan: channels first (posts point at them), then the posts in pieces, then the "forgotten" marks.""" + res = ImportResult() + if plan.new_channels: + async with db.Session() as s: + for d in plan.new_channels: + if await s.get(Channel, d["id"]) is None: + s.add(Channel(**d)) + res.channels_added += 1 + await s.commit() + rows = plan.new_posts + for i in range(0, len(rows), CHUNK): + part = rows[i : i + CHUNK] + saved = await _save_posts(db, part) + res.posts_added += sum(1 for r in saved if r["status"] == "sent") + res.drafts_added += sum(1 for r in saved if r["status"] == "draft") + res.skipped_meanwhile += len(part) - len(saved) + if progress is not None: + await progress(min(i + CHUNK, len(rows)), len(rows)) + for cid, mid in plan.new_ignored: + await db.ignore_post(cid, mid) + res.marks_added += 1 + return res + + +def stamp(iso: Optional[str]) -> str: + """'2026-10-07T10:00:00+00:00' -> '07 Oct 2026, 10:00 UTC' (the text as it is when it can't be read).""" + if not iso: + return "" + try: + d = as_utc(datetime.fromisoformat(iso.replace("Z", "+00:00"))) + except ValueError: + return iso[:40] + return d.astimezone(timezone.utc).strftime("%d %b %Y, %H:%M UTC") diff --git a/app/buttons.py b/app/buttons.py new file mode 100644 index 0000000000000000000000000000000000000000..d2918ee670110de7ba444686da2c08f1ee63c85d --- /dev/null +++ b/app/buttons.py @@ -0,0 +1,150 @@ +"""Button model: rows of {'t': text, 'u': url} (URL buttons) or {'t', 'raw'} (other bots' buttons, kept as-is).""" +from __future__ import annotations + +import re +from typing import Optional + +MAX_ROW = 8 +MAX_TOTAL = 100 +_URL_RX = re.compile(r"(?:https?://|tg://|t\.me/|telegram\.me/)\S+", re.I) + + +def norm_url(u: str) -> Optional[str]: + u = (u or "").strip() + if re.match(r"(?i)^(t\.me|telegram\.me)/", u): + u = "https://" + u + if not re.match(r"(?i)^(https?://|tg://)\S+$", u) or len(u) > 2000: + return None + return u + + +def parse_buttons_text(text: str) -> list: + """One row per line, 'Text - link'. Several buttons in a row: separate them with ' | '.""" + rows: list = [] + total = 0 + for line in (text or "").strip().splitlines(): + line = line.strip() + if not line: + continue + row = [] + for part in re.split(r"\s+\|\s+|\s*&&\s*", line): + part = part.strip() + if not part: + continue + found = list(_URL_RX.finditer(part)) + if not found: + raise ValueError(f"No link found in: {part}") + m = found[-1] + label = part[: m.start()].strip().rstrip("-–—:|=").strip() + if not label: + raise ValueError(f"No button text before the link in: {part}") + url = norm_url(m.group(0)) + if not url: + raise ValueError(f"That link doesn't look valid: {m.group(0)}") + row.append({"t": label, "u": url}) + if len(row) > MAX_ROW: + raise ValueError(f"At most {MAX_ROW} buttons fit in one row.") + if row: + rows.append(row) + total += len(row) + if total > MAX_TOTAL: + raise ValueError(f"At most {MAX_TOTAL} buttons per post.") + return rows + + +def copy_rows(rows: list) -> list: + return [[dict(b) for b in row] for row in (rows or [])] + + +def count(rows: list) -> int: + return sum(len(r) for r in rows or []) + + +def missing_links(rows: list) -> int: + return sum(1 for r in rows or [] for b in r if not b.get("u") and not b.get("raw")) + + +def link_positions(rows: list) -> list: + """(row, column) of every button that has a link of its own. Other bots' buttons (reactions...) are left out: + they can't be edited.""" + return [(r, c) for r, row in enumerate(rows or []) for c, b in enumerate(row) if b.get("u") and not b.get("raw")] + + +def valid(rows: list, r: int, c: int) -> bool: + return 0 <= r < len(rows) and 0 <= c < len(rows[r]) + + +def add_button(rows: list, btn: dict, new_row: bool = True) -> list: + rows = copy_rows(rows) + if new_row or not rows or len(rows[-1]) >= MAX_ROW: + rows.append([btn]) + else: + rows[-1].append(btn) + return rows + + +def set_field(rows: list, r: int, c: int, **fields) -> list: + rows = copy_rows(rows) + if valid(rows, r, c): + rows[r][c].update(fields) + return rows + + +def delete_button(rows: list, r: int, c: int) -> list: + rows = copy_rows(rows) + if valid(rows, r, c): + rows[r].pop(c) + rows = [row for row in rows if row] + return rows + + +def move_button(rows: list, r: int, c: int, direction: str) -> tuple: + """direction: l | r | u | d. Returns (rows, new_r, new_c).""" + rows = copy_rows(rows) + if not valid(rows, r, c): + return rows, r, c + b = rows[r][c] + if direction == "l": + if c > 0: + rows[r][c - 1], rows[r][c] = rows[r][c], rows[r][c - 1] + c -= 1 + elif direction == "r": + if c < len(rows[r]) - 1: + rows[r][c + 1], rows[r][c] = rows[r][c], rows[r][c + 1] + c += 1 + elif direction == "u": + if r > 0 and len(rows[r - 1]) < MAX_ROW: + rows[r].pop(c) + pos = min(c, len(rows[r - 1])) + rows[r - 1].insert(pos, b) + nr, nc = r - 1, pos + if not rows[r]: + rows.pop(r) + r, c = nr, nc + elif direction == "d": + if r < len(rows) - 1: + if len(rows[r + 1]) < MAX_ROW: + rows[r].pop(c) + pos = min(c, len(rows[r + 1])) + rows[r + 1].insert(pos, b) + nr, nc = r + 1, pos + if not rows[r]: + rows.pop(r) + nr -= 1 + r, c = nr, nc + elif len(rows[r]) > 1: # last row with company: split off into a new row below + rows[r].pop(c) + rows.append([b]) + r, c = len(rows) - 1, 0 + return rows, r, c + + +def grid_label(b: dict) -> str: + t = (b.get("t") or "").strip() or "…" + if len(t) > 26: + t = t[:25] + "…" + if b.get("raw"): + return "🔒 " + t + if not b.get("u"): + return "⚠️ " + t + return t diff --git a/app/buttons_sync.py b/app/buttons_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..6a17bbe161a1357cc1fc5fdd38b06d964671f22e --- /dev/null +++ b/app/buttons_sync.py @@ -0,0 +1,186 @@ +"""Make sure the buttons shown in a channel are the ones we saved - and fix them when they are not. + +Used by /repost (every new post is read back right after it is created) and by "Check buttons" in My posts, +which repairs posts whose buttons are saved in the bot but are missing in the channel. +""" +from __future__ import annotations + +import asyncio +import logging +from dataclasses import dataclass, field +from typing import Awaitable, Callable, Optional + +from telethon import errors, types + +from .replace_engine import CHUNK, fetch_messages, is_skippable +from .tgutil import build_markup, button_url, edit_raw, flood_retry, peer_of + +log = logging.getLogger(__name__) + +ABORT_AFTER = 5 # stop repairing after this many failures in a row +# A throw-away keyboard. If Telegram answers "message not modified" to the real keyboard (it believes the post +# already has it), we first show this one, then the real one: two real changes. +NUDGE_ROWS = [[{"t": "…", "u": "https://t.me/telegram"}]] + + +class ButtonsNotShown(RuntimeError): + """Telegram accepted the edit, but the post still does not show the buttons it should.""" + + +def link_buttons(markup) -> list: + """[(text, url)] of the link buttons of a keyboard, in reading order.""" + out: list = [] + if isinstance(markup, types.ReplyInlineMarkup): + for row in markup.rows: + for b in row.buttons: + u = button_url(b) + if u is not None: + out.append((getattr(b, "text", ""), u)) + return out + + +def link_urls(markup) -> list: + return [u for _, u in link_buttons(markup)] + + +async def live_urls(client, peer, message_id: int) -> Optional[list]: + """The link-button URLs the channel shows on a post right now; None if the post is gone.""" + msgs = await fetch_messages(client, peer, [message_id]) + m = msgs[0] if msgs else None + if is_skippable(m): + return None + return link_urls(m.reply_markup) + + +async def ensure_markup(client, peer, message_id: int, markup, *, pause: float = 0.7) -> str: + """Make post `message_id` show the link buttons of `markup`, and check it by reading the post back. + + Returns "fine" (it already did), "set" (one edit was enough) or "nudged" (needed the two-step edit). + Raises ButtonsNotShown if the buttons still are not there, LookupError if the post no longer exists. + """ + want = link_urls(markup) + if not want: + return "fine" + live = await live_urls(client, peer, message_id) + if live is None: + raise LookupError(f"post {message_id} no longer exists") + if live == want: + return "fine" + + try: + await flood_retry(lambda: edit_raw(client, peer, message_id, markup=markup)) + except errors.MessageNotModifiedError: + pass # Telegram thinks the keyboard is already there - checked below + if pause: + await asyncio.sleep(pause) + if await live_urls(client, peer, message_id) == want: + return "set" + + log.info("post %s: the edit did not make the buttons show - trying the two-step edit", message_id) + for step in (build_markup(NUDGE_ROWS), markup): + try: + await flood_retry(lambda step=step: edit_raw(client, peer, message_id, markup=step)) + except errors.MessageNotModifiedError: + pass + if pause: + await asyncio.sleep(pause) + if await live_urls(client, peer, message_id) == want: + return "nudged" + raise ButtonsNotShown(f"post {message_id} still does not show its buttons") + + +# ------------------------------------------------------------------------------------ checking +@dataclass +class ButtonScan: + channel: object + total: int = 0 # saved posts that have link buttons + fine: int = 0 + bad: list = field(default_factory=list) # [(post, live urls, wanted urls)] + gone: list = field(default_factory=list) # posts that no longer exist in the channel + + +async def scan_buttons( + client, ch, posts: list, *, progress: Optional[Callable[[ButtonScan], Awaitable[None]]] = None +) -> ButtonScan: + """Compare the saved link buttons of `posts` with what the channel shows.""" + scan = ButtonScan(channel=ch) + peer = peer_of(ch) + wanted = [] + for p in posts: + if not p.message_id: + continue + urls = link_urls(build_markup(p.buttons)) + if urls: + wanted.append((p, urls)) + scan.total = len(wanted) + for i in range(0, len(wanted), CHUNK): + part = wanted[i : i + CHUNK] + msgs = await fetch_messages(client, peer, [p.message_id for p, _ in part]) + for (p, urls), m in zip(part, msgs): + if is_skippable(m): + scan.gone.append(p) + elif link_urls(m.reply_markup) == urls: + scan.fine += 1 + else: + scan.bad.append((p, link_urls(m.reply_markup), urls)) + if progress: + await progress(scan) + return scan + + +@dataclass +class FixResult: + fixed: int = 0 + nudged: int = 0 # of those, how many needed the two-step edit + already: int = 0 # turned out to be fine when looked at again + gone: int = 0 + failed: list = field(default_factory=list) # [(message id, error name)] + aborted: Optional[str] = None + stopped: bool = False + + +async def fix_buttons( + client, + ch, + bad: list, + *, + delay: float = 1.2, + pause: float = 0.7, + progress: Optional[Callable[[FixResult], Awaitable[None]]] = None, + should_stop: Optional[Callable[[], bool]] = None, +) -> FixResult: + """Put the saved buttons back on the posts in `bad` (the first item of each entry is the saved post).""" + res = FixResult() + peer = peer_of(ch) + streak = 0 + for entry in bad: + post = entry[0] + if should_stop and should_stop(): + res.stopped = True + break + try: + how = await ensure_markup(client, peer, post.message_id, build_markup(post.buttons), pause=pause) + except LookupError: + res.gone += 1 + continue + except Exception as e: # one bad post must not stop the others + name = type(e).__name__ + log.warning("could not fix the buttons of %s: %s %s", post.message_id, name, e) + res.failed.append((post.message_id, name)) + streak += 1 + if streak >= ABORT_AFTER: + res.aborted = name + break + await asyncio.sleep(delay) + continue + streak = 0 + if how == "fine": + res.already += 1 + else: + res.fixed += 1 + if how == "nudged": + res.nudged += 1 + if progress: + await progress(res) + await asyncio.sleep(delay) + return res diff --git a/app/channelref.py b/app/channelref.py new file mode 100644 index 0000000000000000000000000000000000000000..af18ef8c3cd8b61f03c0b424d937bda49cdafcdf --- /dev/null +++ b/app/channelref.py @@ -0,0 +1,119 @@ +"""Find a channel from what a person types: @username, t.me link, numeric id (-100...), or an invite link. + +Used by /shift. The bot can only talk to a channel it can see: registered channels (the database has their access +details), channels it has met in updates, public channels by @username, and channels it is a member of (invite link). +""" +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Optional + +from telethon import functions, types + +from .common import Ctx, UserError + +_REF_RX = re.compile(r"(?i)^(?:https?://)?(?:t\.me|telegram\.me)/(?:c/(\d+)|([A-Za-z0-9_]{3,32}))(?:/\d+)?/?$") +_INVITE_RX = re.compile(r"(?i)^(?:https?://)?(?:t\.me|telegram\.me|telegram\.dog)/(?:\+|joinchat/)([A-Za-z0-9_-]{6,})/?$") +_TG_INVITE_RX = re.compile(r"(?i)^tg://join\?invite=([A-Za-z0-9_-]{6,})$") + + +def parse_channel_ref(text: str): + """@name / t.me link / numeric id -> username (str) or channel id (int); None if unrecognised.""" + t = (text or "").strip() + m = _REF_RX.match(t) + if m: + return int(m.group(1)) if m.group(1) else m.group(2) + t = t.lstrip("@") + if re.fullmatch(r"-?\d+", t): + s = str(abs(int(t))) + return int(s[3:]) if s.startswith("100") and len(s) > 10 else int(s) + if re.fullmatch(r"[A-Za-z0-9_]{3,32}", t): + return t + return None + + +def classify_ref(text: str) -> tuple: + """-> ("invite", hash) | ("username", name) | ("id", int) | (None, None)""" + t = (text or "").strip() + m = _INVITE_RX.match(t) or _TG_INVITE_RX.match(t) + if m: + return "invite", m.group(1) + ref = parse_channel_ref(t) + if isinstance(ref, int): + return "id", ref + if isinstance(ref, str): + return "username", ref + return None, None + + +@dataclass +class ChannelRef: + """A channel as the bot can reach it.""" + + id: int + access_hash: int + title: str + username: Optional[str] + registered: bool # the bot's database knows it (it can be used with /new, /posts ...) + + +def _from_entity(ent, registered: bool) -> ChannelRef: + if not isinstance(ent, types.Channel): + raise UserError("That is not a channel (it looks like a user, bot or group). Only channels can be used here.") + if not ent.broadcast: + raise UserError("That is a group, not a channel. Only channels can be used here.") + if not ent.access_hash or getattr(ent, "min", False): + raise UserError( + "I can see that channel, but Telegram has not given me its access details. Use its @username, or add the " + "bot to the channel as an admin and post something there first." + ) + return ChannelRef(ent.id, ent.access_hash, ent.title or "", ent.username, registered) + + +async def _entity(client, what): + try: + return await client.get_entity(what) + except Exception: + return None + + +async def resolve_channel(ctx: Ctx, text: str) -> ChannelRef: + """The channel `text` points at, or a UserError that says what to do.""" + kind, value = classify_ref(text) + if kind is None: + raise UserError( + f"“{text}” is not a channel I understand. Use an @username, a t.me link, the channel id (-100…) or an invite link." + ) + db, client = ctx.db, ctx.client + if kind == "username": + for ch in await db.list_channels(active_only=False): + if ch.username and ch.username.lower() == value.lower(): + return ChannelRef(ch.id, ch.access_hash, ch.title, ch.username, ch.active) + ent = await _entity(client, value) + if ent is None: + raise UserError(f"I couldn't find a channel called @{value}. Check the name, or add the bot to it as an admin.") + elif kind == "id": + ch = await db.get_channel(value) + if ch is not None: + return ChannelRef(ch.id, ch.access_hash, ch.title, ch.username, ch.active) + ent = ctx.seen_channels.get(value) or await _entity(client, types.PeerChannel(value)) + if ent is None: + raise UserError( + f"I don't know a channel with the id {value}. A bot can only use an id for channels it is part of; " + "use the @username instead, or add the bot to the channel as an admin." + ) + else: # invite link: only tells which channel it is; the bot cannot join by itself + try: + info = await client(functions.messages.CheckChatInviteRequest(hash=value)) + except Exception as e: + raise UserError(f"That invite link doesn't work ({type(e).__name__}).") + chat = getattr(info, "chat", None) + if chat is None: + raise UserError( + "The bot is not a member of that channel, so it cannot use that invite link. Add the bot to the channel " + "as an admin first (a bot cannot join by itself)." + ) + ent = chat + known = await db.get_channel(getattr(ent, "id", 0)) + return _from_entity(ent, known is not None and known.active) diff --git a/app/common.py b/app/common.py new file mode 100644 index 0000000000000000000000000000000000000000..d37fe9bcf4279358652fcbc9ed78a1aee6c24eab --- /dev/null +++ b/app/common.py @@ -0,0 +1,406 @@ +"""Shared context, permission guard, message helpers and post send/edit operations.""" +from __future__ import annotations + +import asyncio +import functools +import logging +import shutil +import tempfile +import time +from dataclasses import dataclass, field +from types import SimpleNamespace +from typing import Any, Callable, Optional + +from telethon import TelegramClient, errors, events + +from .buttons_sync import ensure_markup, link_urls +from .config import Config +from .db import Database +from .replace_engine import fetch_messages, is_skippable +from .richmsg import rich_of, send_rich, with_rich +from .tgutil import build_markup, de_entities, edit_raw, esc, explain_rpc, fetch_media, media_info, peer_of, with_media +from .userbot import UserbotError, UserbotRefused, edit_problem_text + +log = logging.getLogger(__name__) + + +class UserError(Exception): + """An error whose message is safe and useful to show to the user.""" + + +@dataclass +class Ctx: + cfg: Config + db: Database + client: TelegramClient + admins: set = field(default_factory=set) + state: dict = field(default_factory=dict) # user id -> {"mode": ..., ...} + pending: dict = field(default_factory=dict) # tokens for confirm dialogs (replace, repost) + seen_channels: dict = field(default_factory=dict) # channel id -> Channel entity seen in updates + text_handlers: dict = field(default_factory=dict) # mode -> async fn(event, state) + callbacks: dict = field(default_factory=dict) # prefix -> async fn(event, parts) + pickers: dict = field(default_factory=dict) # channel chooser kind -> async fn(event, arg, page) that draws it again + lock: asyncio.Lock = field(default_factory=asyncio.Lock) # one long job (replace / repost) at a time + userbot: Any = None # app.userbot.Userbot or None + reporter: Any = None # app.errorlog.ErrorReporter or None + expirer: Any = None # app.expiry.Expirer (timed deletions of broadcasts) or None + syncer: Any = None # app.syncer.Syncer (keeps My posts in step with the channels) or None + sync_ignore: set = field(default_factory=set) # (channel id, message id) of posts the owner made the bot forget + + +def is_cb(event) -> bool: + return isinstance(event, events.CallbackQuery.Event) or getattr(event, "_is_callback", False) + + +def guard(ctx: Ctx, owner: bool = False) -> Callable: + """Only allowed users may use a handler; errors are turned into friendly messages.""" + + def deco(fn): + @functools.wraps(fn) + async def wrapper(event): + uid = event.sender_id + ok = ctx.cfg.is_owner(uid) if owner else (ctx.cfg.is_owner(uid) or uid in ctx.admins or uid in ctx.cfg.admins) + if not ok: + try: + if is_cb(event): + await event.answer("Not allowed.", alert=True) + elif getattr(event, "is_private", False): + await event.respond("⛔ This bot is private.") + except Exception: + pass + return + try: + await fn(event) + except events.StopPropagation: + raise + except errors.MessageNotModifiedError: + if is_cb(event): + try: + await event.answer() + except Exception: + pass + except UserError as e: + await notify_error(event, str(e)) + except errors.RPCError as e: + log.error("Telegram refused a request in handler %s (user %s)", fn.__name__, uid, exc_info=True) + await notify_error(event, "❌ " + explain_rpc(e)) + except Exception as e: + log.exception("Unhandled exception in handler %s (user %s)", fn.__name__, uid) + await notify_error(event, f"⚠️ Something went wrong: {type(e).__name__}: {str(e)[:200]}") + + return wrapper + + return deco + + +async def notify_error(event, text: str) -> None: + try: + if is_cb(event): + try: + await event.answer("That didn't work - see the message below.", alert=False) + except Exception: + pass + await event.respond(esc(text), link_preview=False) + except Exception: # pragma: no cover + log.exception("could not report an error") + + +async def say(event, text: str, buttons=None): + return await event.respond(text, buttons=buttons, link_preview=False) + + +async def edit_callback_message(event, text: str, buttons=None): + """Edit the message a button was pressed on. + + Telethon's CallbackQuery.edit() quietly starts a second `answer` task; the dispatcher has already + answered the query, so we call edit_message directly instead. + """ + query = getattr(event, "query", None) + if query is not None and hasattr(event, "client"): + return await event.client.edit_message( + await event.get_input_chat(), query.msg_id, text, buttons=buttons, link_preview=False + ) + return await event.edit(text, buttons=buttons, link_preview=False) # test doubles + + +async def show(event, text: str, buttons=None): + """Edit the message a button was pressed on; for normal messages send a new one.""" + if is_cb(event): + try: + return await edit_callback_message(event, text, buttons) + except errors.MessageNotModifiedError: + return None + return await say(event, text, buttons) + + +def require_owner(ctx: Ctx, event) -> None: + if not ctx.cfg.is_owner(event.sender_id): + raise UserError("⛔ Only the bot owner can do that.") + + +# ------------------------------------------------------------------ sending and editing +async def send_post(client, peer, post): + ents = de_entities(post.entities) + markup = build_markup(post.buttons) + rich = rich_of(post) + if rich is not None and not post.media_file_id: # a rich message: Telegram builds its blocks from what was kept + return await send_rich(client, peer, rich, markup=markup) + if post.media_file_id: + return await with_media( + post.media_file_id, + lambda media: client.send_file( + peer, media, caption=post.text or "", formatting_entities=ents, buttons=markup + ), + ) + return await client.send_message( + peer, post.text, formatting_entities=ents, buttons=markup, link_preview=bool(post.link_preview) + ) + + +async def push_edit(client, ch, p, *, replace_media: bool = False) -> None: + """Make the live channel message look like `p` (any object with the Post fields).""" + peer = peer_of(ch) + ents = de_entities(p.entities) + markup = build_markup(p.buttons) + rich = rich_of(p) + if rich is not None and not p.media_kind: + await with_rich(rich, lambda inp: edit_raw(client, peer, p.message_id, rich_message=inp, markup=markup)) + return + if replace_media and p.media_file_id: + await with_media( + p.media_file_id, + lambda media: client.edit_message( + peer, p.message_id, text=p.text or "", formatting_entities=ents, buttons=markup, file=media + ), + ) + else: + await edit_raw( + client, + peer, + p.message_id, + text=p.text or "", + entities=ents, + markup=markup, + preview=None if p.media_kind else bool(p.link_preview), + ) + + +# What the userbot can change in a post. It is a user account: it can't set buttons, and it fails the way the bot did +# when Telegram dislikes the text itself. +USERBOT_EDITS = {"text", "entities", "link_preview"} +NOT_THE_USERBOTS_JOB = { + "EntityBoundsInvalidError", "EntitiesTooLongError", "MessageTooLongError", "MediaCaptionTooLongError", + "MessageEmptyError", "ButtonUrlInvalidError", "ReplyMarkupInvalidError", +} + + +@dataclass +class EditReport: + """How the edit of a published post went (for the message the owner gets).""" + + by_userbot: bool = False # Telegram refused the bot, so the userbot made the edit + bot_error: Optional[str] = None # the name of the error Telegram gave the bot + buttons: Optional[str] = None # after the userbot's edit: "kept" | "restored" | "lost" (None: no link buttons saved) + notes: list = field(default_factory=list) # what the userbot had to do in the channel (joined, got a right ...) + media: Optional[tuple] = None # (kind, reference) of the photo / file the post shows now, as the bot sees it + + +def edit_report_text(report: Optional[EditReport]) -> str: + """The lines to add to the owner's message when the userbot had to make the edit (empty for an ordinary edit).""" + if report is None or not report.by_userbot: + return "" + lines = [f"🤖 Telegram refused the bot ({esc(report.bot_error or 'error')}), so the userbot made the edit."] + if report.buttons == "kept": + lines.append("The buttons are still on the post.") + elif report.buttons == "restored": + lines.append("Telegram dropped the buttons with that edit, so the bot put them back.") + elif report.buttons == "lost": + lines.append( + "Telegram dropped the buttons with that edit and the bot may not put them back. They stay saved in " + "My posts; 🔧 Check buttons tries again." + ) + if report.notes: + text = "; ".join(report.notes) + lines.append("ℹ️ " + esc(text[:1].upper() + text[1:]) + ".") + return "\n".join(lines) + + +async def put_buttons_back(client, ch, p) -> Optional[str]: + """After the userbot's edit: make the post show its saved link buttons again where Telegram dropped them. + + "kept" (they were there), "restored", "lost" (Telegram won't let the bot set them), None (none are saved).""" + markup = build_markup(p.buttons) + if not link_urls(markup): + return None + try: + how = await ensure_markup(client, peer_of(ch), p.message_id, markup) + except Exception as e: # noqa: BLE001 - the edit itself worked; only the buttons are missing + log.info("could not put the buttons back on %s: %s", p.message_id, type(e).__name__) + return "lost" + return "kept" if how == "fine" else "restored" + + +async def live_media(client, ch, message_id: int) -> Optional[tuple]: + """(kind, reference) of the photo / file the channel post shows now, as the bot sees it; None if it can't be read.""" + try: + msgs = await fetch_messages(client, peer_of(ch), [message_id]) + except Exception: # noqa: BLE001 + return None + m = msgs[0] if msgs else None + if is_skippable(m): + return None + kind, ref = media_info(m) + return (kind, ref) if kind else None + + +async def edit_by_userbot(ctx: Ctx, ch, p, *, replace_media: bool, bot_error: str, notify=None) -> Optional[EditReport]: + """The userbot makes the live post look like `p`. None when there is no userbot to ask; UserbotError when it fails. + + A new photo / file goes through the userbot's own chat with the bot: the bot sends it there and the userbot edits the + post with that copy, so nothing is downloaded or uploaded - a big file is as quick as a small one and keeps its + thumbnail. Only when that does not work does the bot download the file (with its thumbnail) and the userbot upload + it again, which is slow for a big file. `notify(text)` tells the owner what is going on.""" + ub = ctx.userbot + editor = await ub.editor_for(ch) if ub is not None else None + if editor is None: + return None + report = EditReport(by_userbot=True, bot_error=bot_error) + folder = None + + async def tell(text: str) -> None: + if notify is not None: + await notify(text) + + fields = dict( + text=p.text or "", + entities=de_entities(p.entities), + preview=None if p.media_kind or rich_of(p) else bool(p.link_preview), + rich=None if p.media_kind else rich_of(p), + ) + try: + await tell("⏳ Telegram refused the bot, so the userbot is making the edit.") + if not (replace_media and p.media_file_id): + await editor.edit(p.message_id, **fields) + else: + done = False + media = await editor.media_by_reference(p.media_file_id) + if media is not None: + try: + await editor.edit(p.message_id, media=media, **fields) + done = True + editor.notes.append("the new file went through the userbot's chat with the bot, so nothing was uploaded") + except UserbotRefused as e: + if not e.about_media: + raise + editor.dm_problem = f"Telegram would not take the userbot's copy of the file ({e.name})" + if not done: + why = editor.dm_problem or "that did not work" + editor.notes.append(f"the file was downloaded and uploaded again, because {why}") + await tell( + "⏳ The file can't go through the userbot's chat with the bot, so it is downloaded and uploaded " + f"again - a big file takes a while. (Reason: {esc(why)}.)" + ) + folder = tempfile.mkdtemp(prefix="cpb-media-") + try: + media = await fetch_media(ctx.client, p.media_file_id, p.media_kind, folder) + except (errors.RPCError, OSError, ValueError) as e: + raise UserbotError(f"I could not download the new media for the userbot ({type(e).__name__}).") + await editor.edit(p.message_id, media=media, **fields) + finally: + await editor.close() + report.notes = list(editor.notes) + if folder: + shutil.rmtree(folder, ignore_errors=True) + if replace_media: + report.media = await live_media(ctx.client, ch, p.message_id) + report.buttons = await put_buttons_back(ctx.client, ch, p) + return report + + +async def apply_edit_reported(ctx: Ctx, post, ch, *, replace_media: bool = False, notify=None, **changes): + """Edit the channel message first (if the post is published), and only then save the change. + + The bot edits. If Telegram refuses it (a post that belongs to another bot) and the change is to the text, caption + or media, the userbot makes the edit instead. Returns (the saved post, an EditReport).""" + report = EditReport() + if post.status == "sent" and post.message_id: + new = SimpleNamespace(**{**post.as_dict(), **changes}) + try: + await push_edit(ctx.client, ch, new, replace_media=replace_media) + except errors.MessageNotModifiedError: + pass + except errors.RPCError as e: + refused = "❌ " + explain_rpc(e) + if type(e).__name__ in NOT_THE_USERBOTS_JOB or not (replace_media or USERBOT_EDITS & set(changes)): + raise UserError(refused + "\nNothing was changed.") + try: + done = await edit_by_userbot( + ctx, ch, new, replace_media=replace_media, bot_error=type(e).__name__, notify=notify + ) + except UserbotError as ue: + log.info("the userbot could not make the edit either: %s", ue) + raise UserError(f"{refused} {edit_problem_text(ctx.userbot, fallback_error=str(ue))}\nNothing was changed.") + if done is None: + raise UserError(f"{refused} {edit_problem_text(ctx.userbot)}\nNothing was changed.") + report = done + if report.media: # the post now shows the userbot's upload: keep My posts in step with it + changes = {**changes, "media_kind": report.media[0], "media_file_id": report.media[1]} + return await ctx.db.update_post(post.id, **changes), report + + +async def apply_edit(ctx: Ctx, post, ch, *, replace_media: bool = False, **changes): + """apply_edit_reported for the callers that only want the saved post.""" + saved, _ = await apply_edit_reported(ctx, post, ch, replace_media=replace_media, **changes) + return saved + + +def purge_pending(ctx: Ctx, ttl: float = 3600.0) -> None: + """Forget confirm dialogs (replace plans, repost choices...) nobody answered for a while.""" + now = time.monotonic() + stale = [ + k + for k, v in ctx.pending.items() + if not getattr(v, "running", False) and now - getattr(v, "created", now) > ttl + ] + for k in stale: + ctx.pending.pop(k, None) + + +def on_cb(ctx: Ctx, prefix: str): + def deco(fn): + ctx.callbacks[prefix] = fn + return fn + + return deco + + +def on_text(ctx: Ctx, mode: str): + def deco(fn): + ctx.text_handlers[mode] = fn + return fn + + return deco + + +def set_state(ctx: Ctx, uid: int, mode: str, **data: Any) -> dict: + ctx.state[uid] = {"mode": mode, **data} + return ctx.state[uid] + + +def clear_state(ctx: Ctx, uid: int) -> Optional[dict]: + return ctx.state.pop(uid, None) + + +def cmd(name: str, args: bool = False): + """Event builder for a private-chat command such as /new or /replace .""" + pat = rf"(?is)^/{name}(?:@\w+)?" + (r"(?:\s+(.*))?$" if args else r"\s*$") + return events.NewMessage(incoming=True, pattern=pat, func=lambda e: e.is_private) + + +async def discard_temp(ctx: Ctx, uid: int) -> None: + """Drop a half-made draft when the user abandons the flow that was creating it.""" + st = ctx.state.get(uid) + if st and st.get("temp") and st.get("pid"): + p = await ctx.db.get_post(st["pid"]) + if p is not None and p.status == "draft": + await ctx.db.delete_post(p.id) diff --git a/app/config.py b/app/config.py new file mode 100644 index 0000000000000000000000000000000000000000..aaa4488d8dcb5dfae7c1acad23799c94d7f9ed99 --- /dev/null +++ b/app/config.py @@ -0,0 +1,133 @@ +"""Settings, read from environment variables (or a .env file).""" +from __future__ import annotations + +import math +import os +import tempfile +from dataclasses import dataclass +from typing import Optional + +try: # python-dotenv is optional; real env vars always win + from dotenv import load_dotenv + + load_dotenv() +except Exception: # pragma: no cover + pass + + +def _ints(name: str) -> frozenset: + raw = os.getenv(name, "") or "" + out = set() + for part in raw.replace(";", ",").replace(" ", ",").split(","): + part = part.strip() + if part.lstrip("-").isdigit(): + out.add(int(part)) + return frozenset(out) + + +def _bool(name: str, default: bool) -> bool: + raw = os.getenv(name) + if raw is None or raw.strip() == "": + return default + return raw.strip().lower() in {"1", "true", "yes", "on"} + + +DEFAULT_ERROR_LOG_CHAT_ID = -1002525172451 +_OFF = {"0", "off", "none", "false", "no", "disabled", "disable"} + + +def _chat_id(name: str, default: Optional[int]) -> Optional[int]: + """A chat id from the environment: unset or empty -> default, "0" / "off" -> None (switched off).""" + raw = (os.getenv(name) or "").strip() + if raw == "": + return default + if raw.lower() in _OFF: + return None + try: + return int(raw) + except ValueError: + raise SystemExit(f"{name} must be a chat id such as -1001234567890 (or 0 / off to switch it off), not {raw!r}") + + +def _float(name: str, default: float) -> float: + try: + return float(os.getenv(name, "") or default) + except ValueError: + return default + + +def _whole(name: str, default: int) -> int: + """A whole number from the environment; anything that is not a finite number gives the default.""" + value = _float(name, float(default)) + return int(value) if math.isfinite(value) else default + + +@dataclass(frozen=True) +class Config: + api_id: int + api_hash: str + bot_token: str + owners: frozenset + admins: frozenset + database_url: str + db_pool: str + session_path: str + session_string: str + edit_delay: float + replace_typed_links: bool + port: int + log_level: str + error_log_chat_id: Optional[int] = None # errors are sent to this chat; None = off + userbot_session: str = "" # session text of the helper account that deletes old posts + userbot_keep_admin: bool = False # keep the userbot an admin after a clean-up (default: take the right away) + delete_service_messages: bool = True # remove "channel name changed", "pinned a message", video chat ... notices + sync_interval_minutes: int = 60 # how often every channel is compared with My posts (0 = never on its own) + import_old_posts: bool = True # read the posts that were in a channel before the bot was added into My posts + markup_input: bool = True # text typed as HTML or Markdown (and sent without Telegram formatting) becomes real formatting + + def is_owner(self, uid) -> bool: + return uid in self.owners + + def is_allowed(self, uid) -> bool: + return uid in self.owners or uid in self.admins + + +def default_session_path() -> str: + """Outside the app folder on purpose: a host that publishes that folder (python -m http.server) must not + publish the login session. A bot can always log in again with its token, so losing it is harmless.""" + return os.path.join(tempfile.gettempdir(), "channel-post-bot", "bot") + + +def load_config() -> Config: + missing = [k for k in ("API_ID", "API_HASH", "BOT_TOKEN") if not os.getenv(k)] + owners = _ints("OWNER_IDS") + if not owners: + missing.append("OWNER_IDS") + if missing: + raise SystemExit("Missing required settings: " + ", ".join(missing) + " (see .env.example)") + try: + api_id = int(os.environ["API_ID"]) + except ValueError: + raise SystemExit("API_ID must be a number") + return Config( + api_id=api_id, + api_hash=os.environ["API_HASH"].strip(), + bot_token=os.environ["BOT_TOKEN"].strip(), + owners=owners, + admins=frozenset(), + database_url=(os.getenv("DATABASE_URL") or "sqlite+aiosqlite:///data/bot.db").strip(), + db_pool=(os.getenv("DB_POOL") or "null").strip().lower(), + session_path=(os.getenv("SESSION_PATH") or default_session_path()).strip(), + session_string=(os.getenv("SESSION_STRING") or "").strip(), + edit_delay=max(0.3, _float("EDIT_DELAY", 1.2)), + replace_typed_links=_bool("REPLACE_TYPED_LINKS", True), + port=int(os.getenv("PORT") or 0), + log_level=(os.getenv("LOG_LEVEL") or "INFO").upper(), + error_log_chat_id=_chat_id("ERROR_LOG_CHAT_ID", DEFAULT_ERROR_LOG_CHAT_ID), + userbot_session=(os.getenv("USERBOT_SESSION") or "").strip(), + userbot_keep_admin=_bool("USERBOT_KEEP_ADMIN", False), + delete_service_messages=_bool("DELETE_SERVICE_MESSAGES", True), + sync_interval_minutes=max(0, _whole("SYNC_INTERVAL_MINUTES", 60)), + import_old_posts=_bool("IMPORT_OLD_POSTS", True), + markup_input=_bool("MARKUP_INPUT", True), + ) diff --git a/app/crosslinks.py b/app/crosslinks.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d20238771fcef52775fab28a40bf139d60973e --- /dev/null +++ b/app/crosslinks.py @@ -0,0 +1,406 @@ +"""Links to posts that moved: pointed at their new place in EVERY connected channel. + +/repost gives every post of a channel a new message id, and /shift -c puts the posts into another channel. A link to +the old post - https://t.me/name/52, https://t.me/c/123/52, a hyperlink behind some text, a button - that sits in ANY +connected channel would lead nowhere once the old post is gone. relink_channels reads the connected channels, finds +those links and points them at the equivalent new post. Only the digits of the id change (for /shift also the channel +part of the link); the text around a link, the formatting and all other buttons stay exactly as they are. + +Rules + * only a link whose old post HAS a copy is changed: a link to a post that was not copied stays as it is; + * running it again changes nothing more - a link that already points at a copy is not an old link any more; + * a post is read again right before it is edited, so something an admin changed meanwhile is never overwritten; + * a post of somebody else is edited only if the bot has the "Edit messages of others" right; otherwise it is only + counted, so the report can say so; + * what Telegram holds back (a copyright notice instead of the post) and a channel Telegram restricts are not edited; + * nothing is deleted anywhere. +""" +from __future__ import annotations + +import asyncio +import logging +from dataclasses import dataclass, field +from typing import Any, Awaitable, Callable, Optional + +from telethon import errors, types + +from .buttons_sync import ensure_markup, link_urls +from .postlinks import PostLinks, relink_message +from .replace_engine import CHUNK, fetch_messages, is_skippable, preview_flag +from .restrictions import message_restriction, probe_channel +from .tgutil import FATAL, edit_raw, esc, flood_retry, get_rights, peer_of, ser_entities, ser_markup + +log = logging.getLogger(__name__) + +PAUSE = 0.25 # between two reads while a channel is scanned +ABORT_AFTER = 5 # the same refusal this many times in a row: leave the channel (the others are still done) + + +@dataclass +class ChannelLinks: + """What was found and done in one channel.""" + + channel: Any + scanned: int = 0 # message ids read so far + top: int = 0 # the last id that is read + checked: int = 0 # posts looked at + found: int = 0 # posts with a link to change + relinked: int = 0 # posts whose links were changed + links: int = 0 # links changed in total + not_allowed: int = 0 # posts with a link to change that the bot may not edit (somebody else's, no right) + held_back: int = 0 # posts Telegram holds back (copyright ...): left as they are + gone: int = 0 # posts that were deleted while we worked + failed: list = field(default_factory=list) # [(message id, error name)] + skipped: Optional[str] = None # why the channel was not looked at + aborted: Optional[str] = None # the refusal that made us give up on this channel + + +@dataclass +class CrossResult: + """What a run did in all the channels (also handed to `progress` while it works).""" + + channels: list = field(default_factory=list) # [ChannelLinks], in the order they were done + total: int = 0 # channels to look at + index: int = 0 # the number of the channel being worked on (1 = the first) + current: Optional[ChannelLinks] = None + phase: str = "" # scan | edit + stopped: bool = False + + @property + def relinked(self) -> int: + return sum(c.relinked for c in self.channels) + + @property + def links(self) -> int: + return sum(c.links for c in self.channels) + + @property + def failed(self) -> list: + return [(c.channel, mid, name) for c in self.channels for mid, name in c.failed] + + @property + def not_allowed(self) -> int: + return sum(c.not_allowed for c in self.channels) + + @property + def changed_channels(self) -> list: + return [c for c in self.channels if c.relinked] + + @property + def skipped(self) -> list: + return [c for c in self.channels if c.skipped] + + @property + def clean(self) -> bool: + """Everything that had to be done was done.""" + return not self.stopped and not self.failed and not self.not_allowed and not any(c.aborted for c in self.channels) + + +async def _edit(client, peer, m, rl) -> None: + if rl.text_changed: + await edit_raw(client, peer, m.id, text=rl.text, entities=rl.entities, markup=rl.markup, preview=preview_flag(m)) + else: # only buttons changed: the text is not sent again + await edit_raw(client, peer, m.id, markup=rl.markup) + + +async def _scan( + client, peer, top: int, links: PostLinks, leave: set, mine: set, can_edit_others: bool, res: ChannelLinks, *, + pause: float, tick: Callable[[], Awaitable[None]], should_stop: Optional[Callable[[], bool]], +) -> list: + """Read ids 1..top; the ids of the posts that have links to change (and may be changed) come back, oldest first.""" + todo: list = [] + a = 1 + while a <= top: + if should_stop and should_stop(): + break + hi = min(a + CHUNK - 1, top) + for m in await fetch_messages(client, peer, list(range(a, hi + 1))): + if m is None or isinstance(m, (types.MessageEmpty, types.MessageService)): + continue + res.checked += 1 + if m.id in leave: + continue + if message_restriction(m): + res.held_back += 1 + continue + if relink_message(m, links) is None: + continue + res.found += 1 + if not (getattr(m, "out", False) or m.id in mine) and not can_edit_others: + res.not_allowed += 1 + continue + todo.append(m.id) + res.scanned = hi + a = hi + 1 + await tick() + if pause and a <= top: + await asyncio.sleep(pause) + return todo + + +async def _apply( + client, db, ch, peer, ids: list, links: PostLinks, res: ChannelLinks, *, + delay: float, settle_pause: float, tick: Callable[[], Awaitable[None]], should_stop: Optional[Callable[[], bool]], +) -> bool: + """Edit the posts in `ids`, each one read again first. False when the run was stopped.""" + streak, last_name = 0, None + for mid in ids: + if should_stop and should_stop(): + return False + (m,) = await fetch_messages(client, peer, [mid]) + if is_skippable(m): + res.gone += 1 + continue + if message_restriction(m): + res.held_back += 1 + continue + rl = relink_message(m, links) + if rl is None: # somebody fixed it meanwhile + continue + try: + await flood_retry(lambda: _edit(client, peer, m, rl)) + if link_urls(rl.markup): + await ensure_markup(client, peer, m.id, rl.markup, pause=settle_pause) + except errors.MessageNotModifiedError: + continue + except Exception as e: # one bad post must not stop the others + name = type(e).__name__ + log.warning("could not update the links of %s/%s: %s %s", ch.id, m.id, name, e) + res.failed.append((m.id, name)) + streak = streak + 1 if name == last_name else 1 + last_name = name + if name in FATAL or streak >= ABORT_AFTER: + res.aborted = name + return True + continue + streak, last_name = 0, None + res.relinked += 1 + res.links += rl.links + fields: dict = {} + if rl.text_changed: + fields.update(text=rl.text, entities=ser_entities(rl.entities)) + if rl.markup_changed: + fields["buttons"] = ser_markup(rl.markup) + try: + await db.update_post_by_message(ch.id, m.id, **fields) + except Exception: # the channel is right; the next sync corrects the saved copy + log.warning("could not save the new links of %s/%s", ch.id, m.id, exc_info=True) + await tick() + await asyncio.sleep(delay) + return True + + +async def relink_channels( + client, + db, + links: PostLinks, + channels: list, + *, + leave: Optional[dict] = None, + delay: float = 1.2, + settle_pause: float = 0.7, + pause: float = PAUSE, + progress: Optional[Callable[[CrossResult], Awaitable[None]]] = None, + should_stop: Optional[Callable[[], bool]] = None, + result: Optional[CrossResult] = None, +) -> CrossResult: + """Point every link that `links` knows (old post -> its new place) at the new place, in each of `channels`. + + `leave` ({channel id: message ids}) are posts that must not be touched, such as the originals of a repost. + `result` may be given to watch a run from outside: it is filled in while the run goes on.""" + res = result if result is not None else CrossResult() + res.total = len(channels) + leave = leave or {} + if not links.ids: + return res + + async def tick() -> None: + if progress: + await progress(res) + + for n, ch in enumerate(channels, 1): + if should_stop and should_stop(): + res.stopped = True + break + one = ChannelLinks(channel=ch) + res.channels.append(one) + res.index, res.current, res.phase = n, one, "scan" + await tick() + peer = peer_of(ch) + rights = await get_rights(client, ch) + if rights is not None and not rights.admin: + one.skipped = "the bot is not an admin there" + continue + if rights is not None and not (rights.post or rights.edit): + one.skipped = "the bot has no right to post or edit there" + continue + can_others = True if rights is None else bool(rights.edit) + top, why, err = await probe_channel(client, peer) + if err: + one.skipped = err + continue + if why: + one.skipped = f"Telegram restricts this channel ({why})" + continue + one.top = top or 0 + try: + todo = await _scan( + client, peer, one.top, links, set(leave.get(ch.id, ())), await db.mine_message_ids(ch.id), can_others, + one, pause=pause, tick=tick, should_stop=should_stop, + ) + if should_stop and should_stop(): + res.stopped = True + break + res.phase = "edit" + await tick() + if not await _apply( + client, db, ch, peer, todo, links, one, delay=delay, settle_pause=settle_pause, tick=tick, + should_stop=should_stop, + ): + res.stopped = True + break + except errors.RPCError as e: # the channel can't be read (any more): the others still can + log.warning("could not read %s while pointing links at the new posts: %s", ch.id, type(e).__name__) + one.aborted = type(e).__name__ + res.phase, res.current = "", None + return res + + +# ------------------------------------------------------------------------------ the three ways to use it +async def relink_after_repost( + client, db, ch, mig, *, delay: float = 1.2, settle_pause: float = 0.7, pause: float = PAUSE, + progress=None, should_stop=None, result: Optional[CrossResult] = None, +) -> CrossResult: + """After /repost: every link to an old post of `ch`, in any connected channel, points at the copy of that post. + The originals themselves are not touched (they are deleted later, or kept if the repost is undone).""" + res = result if result is not None else CrossResult() + ids = dict(await db.migration_pairs(mid=mig.id)) + if not ids: + return res + await db.set_mark(mig.id, "links") # from now on an undo has to point the links back + return await relink_channels( + client, db, PostLinks.for_channel(ch, ids), await db.list_channels(), leave={ch.id: set(ids)}, delay=delay, + settle_pause=settle_pause, pause=pause, progress=progress, should_stop=should_stop, result=res, + ) + + +async def restore_after_undo( + client, db, ch, mig, *, delay: float = 1.2, settle_pause: float = 0.7, pause: float = PAUSE, + progress=None, should_stop=None, result: Optional[CrossResult] = None, +) -> CrossResult: + """Before the copies of a repost are removed: links that were pointed at them go back to the original posts.""" + res = result if result is not None else CrossResult() + if not await db.has_mark(mig.id, "links"): + return res # no link anywhere was changed for this repost + back = {new: old for old, new in await db.migration_pairs(mid=mig.id)} + return await relink_channels( + client, db, PostLinks.for_channel(ch, back), await db.list_channels(), leave={ch.id: set(back)}, delay=delay, + settle_pause=settle_pause, pause=pause, progress=progress, should_stop=should_stop, result=res, + ) + + +def shift_links(src, dst, ids: dict) -> PostLinks: + """Links to the posts of the source channel -> the equivalent posts of the destination (`ids`: source id -> copy).""" + return PostLinks( + username=src.username, channel_id=src.id, ids=ids, target_username=dst.username, target_id=dst.id + ) + + +async def relink_after_shift( + client, db, shift, src, dst, *, delay: float = 1.2, settle_pause: float = 0.7, pause: float = PAUSE, + progress=None, should_stop=None, result: Optional[CrossResult] = None, +) -> CrossResult: + """After /shift -c: a link to a post of the source channel, in any connected channel (the source itself is only + read, never changed), points at the copy of that post in the destination.""" + res = result if result is not None else CrossResult() + ids = dict(await db.shift_pairs(shift.id)) + if not ids: + return res + await db.set_mark(shift.id, "links") + chans = [c for c in await db.list_channels() if c.id != src.id] + return await relink_channels( + client, db, shift_links(src, dst, ids), chans, delay=delay, settle_pause=settle_pause, pause=pause, + progress=progress, should_stop=should_stop, result=res, + ) + + +async def restore_after_shift_undo( + client, db, shift, src, dst, *, delay: float = 1.2, settle_pause: float = 0.7, pause: float = PAUSE, + progress=None, should_stop=None, result: Optional[CrossResult] = None, +) -> CrossResult: + """Before the copies of a shift are removed: links that were pointed at them go back to the source posts.""" + res = result if result is not None else CrossResult() + if not await db.has_mark(shift.id, "links"): + return res + back = {new: old for old, new in await db.shift_pairs(shift.id)} + links = PostLinks( + username=dst.username, channel_id=dst.id, ids=back, target_username=src.username, target_id=src.id + ) + chans = [c for c in await db.list_channels() if c.id != src.id] + return await relink_channels( + client, db, links, chans, leave={dst.id: set(back)}, delay=delay, settle_pause=settle_pause, pause=pause, + progress=progress, should_stop=should_stop, result=res, + ) + + +# ------------------------------------------------------------------------------------------ the report +def _name(ch) -> str: + return esc(getattr(ch, "title", None) or str(getattr(ch, "id", "?"))) + + +def report_lines(res: CrossResult, *, what: str = "the new copies", back: bool = False) -> list: + """Lines (HTML) for the end of a repost / shift. `what`: where the links point now. `back`: they were pointed back.""" + out: list = [] + done = [c for c in res.channels if not c.skipped] + if res.relinked: + n = len(res.changed_channels) + out.append( + f"🔗 {res.links} link(s) in {res.relinked} post(s) of {n} channel(s) " + f"{'point back at the original posts' if back else 'now point at ' + what}." + ) + if n > 1 or (n == 1 and len(done) > 1): + for c in res.changed_channels[:12]: + out.append(f"• {_name(c.channel)}: {c.links} link(s) in {c.relinked} post(s)") + elif done and not res.stopped and not any(c.aborted or c.failed for c in done): + out.append(f"🔗 Checked {len(done)} channel(s): no link there needed changing.") + if res.not_allowed: + names = ", ".join(_name(c.channel) for c in res.channels if c.not_allowed) + out.append( + f"{res.not_allowed} post(s) with such a link were made by somebody else and the bot may not edit them " + f"({names}). Give the bot the “Edit messages of others” right and press “🔗 Update links again”." + ) + failed = res.failed + if failed: + sample = ", ".join(f"{_name(c)} #{mid} {esc(name)}" for c, mid, name in failed[:5]) + out.append(f"{len(failed)} post(s) could not get their links updated ({sample}{'…' if len(failed) > 5 else ''}).") + if any(name in ("MessageIdInvalidError", "MessageAuthorRequiredError") for _, _, name in failed): + out.append( + "Telegram refuses edits to posts that other bots (or other people) made or put buttons on: those " + "links have to be changed by their owner." + ) + for c in res.channels: + if c.aborted: + out.append(f"Gave up on {_name(c.channel)} ({esc(c.aborted)}).") + skipped = res.skipped + if skipped: + out.append("Not looked at: " + "; ".join(f"{_name(c.channel)} ({esc(c.skipped)})" for c in skipped[:8])) + held = sum(c.held_back for c in res.channels) + if held: + out.append(f"{held} post(s) are held back by Telegram (copyright notice) and were left alone.") + if res.stopped: + out.append("⏹ Stopped before every channel was done - press “🔗 Update links again” to finish.") + return out + + +def progress_text(res: CrossResult, *, title: str = "Pointing links at the new copies") -> str: + """The line shown while a run is going on.""" + cur = res.current + where = f" - {_name(cur.channel)}" if cur is not None else "" + step = f" ({res.index} of {res.total})" if res.total else "" + if cur is not None and res.phase == "scan" and cur.top: + detail = f"\nReading posts {cur.scanned} of {cur.top}…" + elif cur is not None and res.phase == "edit": + detail = f"\nChanging links: {cur.relinked} of {cur.found - cur.not_allowed} post(s) done…" + else: + detail = "" + return f"🔗 {title}{step}{where}{detail}\n{res.links} link(s) changed so far." diff --git a/app/db.py b/app/db.py new file mode 100644 index 0000000000000000000000000000000000000000..a8b9e3aebc2593cf06b658eaa672fa26ee5fb6f4 --- /dev/null +++ b/app/db.py @@ -0,0 +1,1067 @@ +"""Database layer (SQLAlchemy 2.0 async). PostgreSQL in production, SQLite for local tests.""" +from __future__ import annotations + +import asyncio +import logging +import os +from datetime import datetime, timezone +from typing import Any, Optional +from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit + +from sqlalchemy import ( + JSON, + BigInteger, + Boolean, + DateTime, + ForeignKey, + Integer, + String, + Text, + UniqueConstraint, + delete, + desc, + func, + select, + update, +) +from sqlalchemy.dialects.postgresql import JSONB +from sqlalchemy.exc import IntegrityError +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column +from sqlalchemy.pool import NullPool + +log = logging.getLogger(__name__) + +JSONType = JSON().with_variant(JSONB(), "postgresql") + + +def utcnow() -> datetime: + return datetime.now(timezone.utc) + + +class Base(DeclarativeBase): + pass + + +class Channel(Base): + __tablename__ = "channels" + + id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=False) + access_hash: Mapped[int] = mapped_column(BigInteger, default=0) + title: Mapped[str] = mapped_column(String(256), default="") + username: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + active: Mapped[bool] = mapped_column(Boolean, default=True) + added_by: Mapped[int] = mapped_column(BigInteger, default=0) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + + +class Post(Base): + __tablename__ = "posts" + __table_args__ = (UniqueConstraint("channel_id", "message_id", name="uq_post_channel_msg"),) + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + channel_id: Mapped[int] = mapped_column(BigInteger, ForeignKey("channels.id"), index=True) + message_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True) + status: Mapped[str] = mapped_column(String(16), default="draft", index=True) # draft | sent + source: Mapped[str] = mapped_column(String(16), default="bot") # bot | adopted + text: Mapped[str] = mapped_column(Text, default="") + entities: Mapped[list] = mapped_column(JSONType, default=list) + media_kind: Mapped[Optional[str]] = mapped_column(String(16), nullable=True) + media_file_id: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + buttons: Mapped[list] = mapped_column(JSONType, default=list) + link_preview: Mapped[bool] = mapped_column(Boolean, default=False) + created_by: Mapped[int] = mapped_column(BigInteger, default=0) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True) + + def as_dict(self) -> dict: + return {c.name: getattr(self, c.name) for c in self.__table__.columns} + + +class Batch(Base): + """One /swap run (so it can be undone).""" + + __tablename__ = "batches" + + id: Mapped[str] = mapped_column(String(32), primary_key=True) + old_username: Mapped[str] = mapped_column(String(64)) + new_username: Mapped[str] = mapped_column(String(64)) + created_by: Mapped[int] = mapped_column(BigInteger, default=0) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + undone: Mapped[bool] = mapped_column(Boolean, default=False) + + +class Change(Base): + __tablename__ = "changes" + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + batch_id: Mapped[str] = mapped_column(String(32), ForeignKey("batches.id"), index=True) + channel_id: Mapped[int] = mapped_column(BigInteger) + message_id: Mapped[int] = mapped_column(BigInteger) + old_state: Mapped[dict] = mapped_column(JSONType, default=dict) + new_state: Mapped[dict] = mapped_column(JSONType, default=dict) + reverted: Mapped[bool] = mapped_column(Boolean, default=False) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + + +class Migration(Base): + """One /repost run: a channel copied post by post, so it can be continued, undone or finished.""" + + __tablename__ = "migrations" + + id: Mapped[str] = mapped_column(String(32), primary_key=True) + channel_id: Mapped[int] = mapped_column(BigInteger, index=True) + old_username: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + new_username: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + include_typed: Mapped[bool] = mapped_column(Boolean, default=True) + include_posts: Mapped[bool] = mapped_column(Boolean, default=False) + first_id: Mapped[int] = mapped_column(BigInteger) + last_id: Mapped[int] = mapped_column(BigInteger) + partial: Mapped[bool] = mapped_column(Boolean, default=False) + # copying | stopped | incomplete | copied | old_deleted | copies_deleted + status: Mapped[str] = mapped_column(String(16), default="copying") + created_by: Mapped[int] = mapped_column(BigInteger, default=0) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + + +class MigrationItem(Base): + __tablename__ = "migration_items" + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + migration_id: Mapped[str] = mapped_column(String(32), ForeignKey("migrations.id"), index=True) + old_id: Mapped[int] = mapped_column(BigInteger) + new_id: Mapped[int] = mapped_column(BigInteger) + old_deleted: Mapped[bool] = mapped_column(Boolean, default=False) + new_deleted: Mapped[bool] = mapped_column(Boolean, default=False) + + +class Shift(Base): + """One /shift run: posts of a source channel copied into another channel (so it can be continued or undone).""" + + __tablename__ = "shifts" + + id: Mapped[str] = mapped_column(String(32), primary_key=True) + src_channel_id: Mapped[int] = mapped_column(BigInteger, index=True) + src_access_hash: Mapped[int] = mapped_column(BigInteger, default=0) + src_title: Mapped[str] = mapped_column(String(256), default="") + src_username: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + dst_channel_id: Mapped[int] = mapped_column(BigInteger, index=True) + first_id: Mapped[int] = mapped_column(BigInteger) + last_id: Mapped[int] = mapped_column(BigInteger) + # copying | stopped | incomplete | copied | copies_deleted + status: Mapped[str] = mapped_column(String(16), default="copying") + created_by: Mapped[int] = mapped_column(BigInteger, default=0) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + + +class ShiftItem(Base): + __tablename__ = "shift_items" + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + shift_id: Mapped[str] = mapped_column(String(32), ForeignKey("shifts.id"), index=True) + old_id: Mapped[int] = mapped_column(BigInteger) # message id in the source channel + new_id: Mapped[int] = mapped_column(BigInteger) # message id of the copy in the destination channel + new_deleted: Mapped[bool] = mapped_column(Boolean, default=False) + + +class ScheduledDelete(Base): + """A channel message the bot has to delete at a given time (a broadcast with an expiry).""" + + __tablename__ = "scheduled_deletes" + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + channel_id: Mapped[int] = mapped_column(BigInteger, index=True) + message_id: Mapped[int] = mapped_column(BigInteger) + delete_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True) + group_id: Mapped[str] = mapped_column(String(32), default="") # the broadcast it belongs to + status: Mapped[str] = mapped_column(String(12), default="pending") # pending | failed + attempts: Mapped[int] = mapped_column(Integer, default=0) + last_error: Mapped[Optional[str]] = mapped_column(String(160), nullable=True) + created_by: Mapped[int] = mapped_column(BigInteger, default=0) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + + +class ChannelSync(Base): + """Where the last look at a channel stopped, so the next one only has to read what is new.""" + + __tablename__ = "channel_sync" + + channel_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=False) + last_top: Mapped[int] = mapped_column(BigInteger, default=0) # the newest message id that existed then + last_pts: Mapped[int] = mapped_column(BigInteger, default=0) # the channel's event counter then + deferred: Mapped[int] = mapped_column(Integer, default=0) # new messages left for the next look (too fresh then) + last_run: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + last_deep: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True) # last look at every id + + +class ChannelHistory(Base): + """How far the older posts of a channel (the ones sent before the bot was there) have been read into My posts.""" + + __tablename__ = "channel_history" + + channel_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=False) + top: Mapped[int] = mapped_column(BigInteger, default=0) # the newest message id that counts as "older" + next_id: Mapped[int] = mapped_column(BigInteger, default=1) # where the reading goes on + imported: Mapped[int] = mapped_column(Integer, default=0) # older posts added to My posts so far + done: Mapped[bool] = mapped_column(Boolean, default=False) + started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True) + + +class IgnoredPost(Base): + """A post the owner made the bot forget: it stays in the channel, but the sync never takes it over again.""" + + __tablename__ = "ignored_posts" + __table_args__ = (UniqueConstraint("channel_id", "message_id", name="uq_ignored_channel_msg"),) + + id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) + channel_id: Mapped[int] = mapped_column(BigInteger, index=True) + message_id: Mapped[int] = mapped_column(BigInteger) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + + +class JobMark(Base): + """A fact about a /repost or /shift run that has to outlive a restart, e.g. that links in other channels were + pointed at its copies (so that Undo points them back), or which extras a shift was asked for.""" + + __tablename__ = "job_marks" + + job_id: Mapped[str] = mapped_column(String(32), primary_key=True) + mark: Mapped[str] = mapped_column(String(24), primary_key=True) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + + +class Admin(Base): + __tablename__ = "admins" + user_id: Mapped[int] = mapped_column(BigInteger, primary_key=True) + + +def as_utc(dt: Optional[datetime]) -> Optional[datetime]: + """A datetime from the database as an aware UTC one (SQLite hands back naive values).""" + if dt is None: + return None + return dt.replace(tzinfo=timezone.utc) if dt.tzinfo is None else dt.astimezone(timezone.utc) + + +def normalize_db_url(url: str) -> tuple: + """Turn a plain DATABASE_URL into a SQLAlchemy async URL + connect args.""" + connect_args: dict = {} + if url.startswith("postgres://"): + url = "postgresql://" + url[len("postgres://"):] + if url.startswith("postgresql://"): + url = "postgresql+asyncpg://" + url[len("postgresql://"):] + if url.startswith("postgresql+asyncpg://"): + parts = urlsplit(url) + keep = [] + for k, v in parse_qsl(parts.query, keep_blank_values=True): + if k == "sslmode": + if v in ("require", "verify-ca", "verify-full"): + connect_args["ssl"] = True + elif k in ("channel_binding", "options"): + continue + else: + keep.append((k, v)) + host = parts.hostname or "" + if "-pooler" in host or "pgbouncer" in host: + # PgBouncer in transaction mode does not support prepared statements + connect_args["statement_cache_size"] = 0 + keep.append(("prepared_statement_cache_size", "0")) + url = urlunsplit(parts._replace(query=urlencode(keep))) + elif url.startswith("sqlite:///"): + url = "sqlite+aiosqlite:///" + url[len("sqlite:///"):] + return url, connect_args + + +class Database: + def __init__(self, url: str, pool: str = "null"): + self.url, connect_args = normalize_db_url(url) + kwargs: dict = {"connect_args": connect_args} + if self.url.startswith("sqlite"): + path = self.url.split(":///", 1)[-1] + if path and path != ":memory:": + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + elif pool == "queue": + kwargs.update(pool_size=5, max_overflow=5, pool_pre_ping=True, pool_recycle=1800) + else: + # short-lived connections: lets serverless Postgres (e.g. Neon) go to sleep when idle + kwargs["poolclass"] = NullPool + self.engine = create_async_engine(self.url, **kwargs) + self.Session = async_sessionmaker(self.engine, expire_on_commit=False) + + async def init(self, retries: int = 6) -> None: + last: Optional[BaseException] = None + for i in range(retries): + try: + async with self.engine.begin() as conn: + await conn.run_sync(Base.metadata.create_all) + return + except Exception as e: # cold start of serverless DBs can fail once + last = e + log.warning("database not ready (%s) - retry %s/%s", e, i + 1, retries) + await asyncio.sleep(min(2 ** i, 15)) + assert last is not None + raise last + + async def close(self) -> None: + await self.engine.dispose() + + async def list_admins(self) -> set[int]: + async with self.Session() as s: + return set((await s.execute(select(Admin.user_id))).scalars()) + + async def add_admin(self, uid: int) -> bool: + async with self.Session() as s: + if await s.get(Admin, uid) is not None: + return False + s.add(Admin(user_id=uid)) + await s.commit() + return True + + async def remove_admin(self, uid: int) -> bool: + async with self.Session() as s: + row = await s.get(Admin, uid) + if row is None: + return False + await s.delete(row) + await s.commit() + return True + + # ------------------------------------------------------------------ channels + async def list_channels(self, active_only: bool = True) -> list: + async with self.Session() as s: + q = select(Channel).order_by(Channel.title) + if active_only: + q = q.where(Channel.active.is_(True)) + return list((await s.execute(q)).scalars()) + + async def get_channel(self, cid: int) -> Optional[Channel]: + async with self.Session() as s: + return await s.get(Channel, cid) + + async def save_channel(self, cid: int, access_hash: int, title: str, username: Optional[str], added_by: int) -> Channel: + async with self.Session() as s: + ch = await s.get(Channel, cid) + if ch is None: + ch = Channel(id=cid, access_hash=access_hash, title=title, username=username, added_by=added_by, active=True) + s.add(ch) + else: + ch.access_hash = access_hash or ch.access_hash + ch.title = title or ch.title + ch.username = username + ch.active = True + await s.commit() + return ch + + async def touch_channel_hash(self, cid: int, access_hash: int) -> None: + async with self.Session() as s: + ch = await s.get(Channel, cid) + if ch is not None and access_hash and ch.access_hash != access_hash: + ch.access_hash = access_hash + await s.commit() + + async def set_channel_active(self, cid: int, active: bool) -> None: + async with self.Session() as s: + ch = await s.get(Channel, cid) + if ch is not None: + ch.active = active + await s.commit() + + async def count_channel_posts(self, cid: int) -> int: + """Every post of the channel in My posts - published ones and drafts.""" + async with self.Session() as s: + return int((await s.execute(select(func.count()).select_from(Post).where(Post.channel_id == cid))).scalar_one()) + + async def delete_channel_data(self, cid: int) -> int: + """Everything My posts holds about a channel: its saved posts (published and drafts) and what the sync keeps + about them - the posts forgotten on purpose, where the last look and the reading of the older posts stopped - so a + channel that is added again starts from scratch. Nothing is touched in Telegram. The channel itself stays + registered (switched off) because reposts and shifts that name it still need it, and so do timed deletions. + Returns how many posts went.""" + async with self.Session() as s: + n = (await s.execute(select(func.count()).select_from(Post).where(Post.channel_id == cid))).scalar_one() + await s.execute(delete(Post).where(Post.channel_id == cid)) + for model in (IgnoredPost, ChannelSync, ChannelHistory): + await s.execute(delete(model).where(model.channel_id == cid)) + await s.commit() + return int(n) + + # --------------------------------------------------------------------- posts + async def create_post(self, **fields: Any) -> Post: + async with self.Session() as s: + p = Post(**fields) + s.add(p) + await s.commit() + return p + + async def get_post(self, pid: int) -> Optional[Post]: + async with self.Session() as s: + return await s.get(Post, pid) + + async def update_post(self, pid: int, **fields: Any) -> Optional[Post]: + async with self.Session() as s: + p = await s.get(Post, pid) + if p is None: + return None + for k, v in fields.items(): + setattr(p, k, v) + p.updated_at = utcnow() + await s.commit() + return p + + async def delete_post(self, pid: int) -> None: + async with self.Session() as s: + p = await s.get(Post, pid) + if p is not None: + await s.delete(p) + await s.commit() + + async def list_posts(self, channel_id: Optional[int], status: Optional[str], offset: int, limit: int) -> tuple: + cond = [] + if channel_id is not None: + cond.append(Post.channel_id == channel_id) + if status: + cond.append(Post.status == status) + async with self.Session() as s: + total = (await s.execute(select(func.count()).select_from(Post).where(*cond))).scalar_one() + q = ( + select(Post) + .where(*cond) + .order_by(Post.status.asc(), desc(Post.message_id), desc(Post.id)) + .offset(offset) + .limit(limit) + ) + rows = list((await s.execute(q)).scalars()) + return rows, total + + async def latest_sent(self, channel_id: int, limit: int = 30) -> list: + async with self.Session() as s: + q = ( + select(Post) + .where(Post.channel_id == channel_id, Post.status == "sent", Post.message_id.is_not(None)) + .order_by(desc(Post.message_id)) + .limit(limit) + ) + return list((await s.execute(q)).scalars()) + + async def sent_posts(self, channel_id: int) -> list: + """Every published post of a channel, oldest first.""" + async with self.Session() as s: + q = ( + select(Post) + .where(Post.channel_id == channel_id, Post.status == "sent", Post.message_id.is_not(None)) + .order_by(Post.message_id) + ) + return list((await s.execute(q)).scalars()) + + async def sent_posts_from(self, channel_id: int, first_message_id: int) -> list: + """Published posts of a channel from message id `first_message_id` on, oldest first.""" + async with self.Session() as s: + q = ( + select(Post) + .where( + Post.channel_id == channel_id, + Post.status == "sent", + Post.message_id.is_not(None), + Post.message_id >= first_message_id, + ) + .order_by(Post.message_id, Post.id) + ) + return list((await s.execute(q)).scalars()) + + async def mine_message_ids(self, channel_id: int) -> set: + async with self.Session() as s: + q = select(Post.message_id).where( + Post.channel_id == channel_id, Post.source == "bot", Post.message_id.is_not(None) + ) + return {r for r in (await s.execute(q)).scalars()} + + async def find_by_message(self, channel_id: int, message_id: int) -> Optional[Post]: + async with self.Session() as s: + q = select(Post).where(Post.channel_id == channel_id, Post.message_id == message_id) + return (await s.execute(q)).scalar_one_or_none() + + async def forget_posts(self, channel_id: int, message_ids: list) -> int: + """Remove the saved posts of these channel messages (they were deleted in the channel) and what hangs on them: + a timed deletion that is not needed any more, a "forgotten on purpose" mark. Returns how many posts went.""" + if not message_ids: + return 0 + ids = list(message_ids) + async with self.Session() as s: + rows = (await s.execute(select(Post).where(Post.channel_id == channel_id, Post.message_id.in_(ids)))).scalars().all() + for p in rows: + await s.delete(p) + for model in (ScheduledDelete, IgnoredPost): + extra = await s.execute(select(model).where(model.channel_id == channel_id, model.message_id.in_(ids))) + for r in extra.scalars().all(): + await s.delete(r) + await s.commit() + return len(rows) + + async def posts_at(self, channel_id: int, message_ids: list) -> list: + """The published posts that sit at these message ids.""" + if not message_ids: + return [] + async with self.Session() as s: + q = select(Post).where( + Post.channel_id == channel_id, Post.status == "sent", Post.message_id.in_(list(message_ids)) + ) + return list((await s.execute(q)).scalars()) + + async def release_slot(self, channel_id: int, message_id: int, keep_pid: Optional[int] = None) -> int: + """Drop any other saved post at this message id (the sync may have picked the message up a moment earlier).""" + async with self.Session() as s: + q = select(Post).where(Post.channel_id == channel_id, Post.message_id == message_id) + if keep_pid is not None: + q = q.where(Post.id != keep_pid) + rows = list((await s.execute(q)).scalars()) + for p in rows: + await s.delete(p) + if rows: + await s.commit() + return len(rows) + + async def _drop_slots(self, s, channel_id: int, message_ids: list) -> None: + """Inside a transaction: remove saved posts at these ids, so the posts about to be saved can take their place.""" + q = select(Post).where(Post.channel_id == channel_id, Post.message_id.in_(list(message_ids))) + rows = list((await s.execute(q)).scalars()) + for p in rows: + await s.delete(p) + if rows: + await s.flush() + + # ------------------------------------------------------- what happens outside the bot + async def get_sync(self, channel_id: int) -> Optional[ChannelSync]: + async with self.Session() as s: + return await s.get(ChannelSync, channel_id) + + async def max_saved_id(self, channel_id: int) -> int: + """The newest message id among the channel's published posts (0 if there is none).""" + async with self.Session() as s: + q = select(func.max(Post.message_id)).where( + Post.channel_id == channel_id, Post.status == "sent", Post.message_id.is_not(None) + ) + return int((await s.execute(q)).scalar_one_or_none() or 0) + + async def save_sync( + self, channel_id: int, *, last_top: int, last_pts: int, deferred: int = 0, deep: bool = False + ) -> None: + async with self.Session() as s: + row = await s.get(ChannelSync, channel_id) + if row is None: + row = ChannelSync(channel_id=channel_id) + s.add(row) + now = utcnow() + row.last_top, row.last_pts, row.deferred, row.last_run = last_top, last_pts, deferred, now + if deep: + row.last_deep = now + await s.commit() + + async def adopt_message(self, channel_id: int, message_id: int, fields: dict, sent_at: Optional[datetime] = None) -> tuple: + """Save a post somebody else made in the channel. Returns (post, True), or (None, False) when the bot already + has a post at that message id (also when another task saved it a moment ago).""" + async with self.Session() as s: + q = select(Post).where(Post.channel_id == channel_id, Post.message_id == message_id) + if (await s.execute(q)).scalar_one_or_none() is not None: + return None, False + p = Post(channel_id=channel_id, message_id=message_id, status="sent", source="adopted", created_by=0, + sent_at=sent_at or utcnow(), **fields) + s.add(p) + try: + await s.commit() + except IntegrityError: + await s.rollback() + return None, False + return p, True + + async def adopt_many(self, channel_id: int, items: list) -> list: + """items: [(message id, post fields, sent_at)] - save the posts somebody else made, many at once. Returns the + message ids that were new (the bot already had a post at the others).""" + if not items: + return [] + ids = [i[0] for i in items] + async with self.Session() as s: + have = set( + (await s.execute(select(Post.message_id).where(Post.channel_id == channel_id, Post.message_id.in_(ids)))).scalars() + ) + fresh = [i for i in items if i[0] not in have] + if not fresh: + return [] + s.add_all( + [ + Post(channel_id=channel_id, message_id=mid, status="sent", source="adopted", created_by=0, + sent_at=at or utcnow(), **fields) + for mid, fields, at in fresh + ] + ) + try: + await s.commit() + return [i[0] for i in fresh] + except IntegrityError: # somebody saved one of them a moment ago: one by one then + await s.rollback() + made = [] + for mid, fields, at in fresh: + _, created = await self.adopt_message(channel_id, mid, fields, sent_at=at) + if created: + made.append(mid) + return made + + # ------------------------------------------------------------- the channel's older posts + async def get_history(self, channel_id: int) -> Optional[ChannelHistory]: + async with self.Session() as s: + return await s.get(ChannelHistory, channel_id) + + async def start_history(self, channel_id: int, top: int) -> ChannelHistory: + """Note that the older posts of a channel (message ids 1 to `top`) are to be read in. Does nothing when that + has begun already.""" + async with self.Session() as s: + row = await s.get(ChannelHistory, channel_id) + if row is not None: + return row + row = ChannelHistory(channel_id=channel_id, top=max(0, top), next_id=1, imported=0) + if top < 1: # an empty channel: nothing to read + row.done, row.finished_at = True, utcnow() + s.add(row) + try: + await s.commit() + except IntegrityError: + await s.rollback() + row = await s.get(ChannelHistory, channel_id) + return row + + async def save_history(self, channel_id: int, *, next_id: int, imported: int = 0, done: bool = False) -> None: + async with self.Session() as s: + row = await s.get(ChannelHistory, channel_id) + if row is None: + return + row.next_id = max(row.next_id, next_id) + row.imported += imported + if done and not row.done: + row.done, row.finished_at = True, utcnow() + await s.commit() + + async def reset_history(self, channel_id: int) -> None: + """Read the channel's older posts again at the next look (the posts the bot already has are skipped).""" + async with self.Session() as s: + row = await s.get(ChannelHistory, channel_id) + if row is not None: + await s.delete(row) + await s.commit() + + # ------------------------------------------------------------ posts forgotten on purpose + async def ignore_post(self, channel_id: int, message_id: int) -> None: + async with self.Session() as s: + q = select(IgnoredPost).where(IgnoredPost.channel_id == channel_id, IgnoredPost.message_id == message_id) + if (await s.execute(q)).scalar_one_or_none() is not None: + return + s.add(IgnoredPost(channel_id=channel_id, message_id=message_id)) + try: + await s.commit() + except IntegrityError: + await s.rollback() + + async def ignored_ids(self, channel_id: int) -> set: + async with self.Session() as s: + q = select(IgnoredPost.message_id).where(IgnoredPost.channel_id == channel_id) + return {int(r) for r in (await s.execute(q)).scalars()} + + # ------------------------------------------------------------ facts about a repost / shift run + async def set_mark(self, job_id: str, mark: str) -> None: + async with self.Session() as s: + if await s.get(JobMark, (job_id, mark)) is not None: + return + s.add(JobMark(job_id=job_id, mark=mark)) + try: + await s.commit() + except IntegrityError: + await s.rollback() + + async def has_mark(self, job_id: str, mark: str) -> bool: + async with self.Session() as s: + return await s.get(JobMark, (job_id, mark)) is not None + + async def marks_of(self, job_id: str) -> set: + async with self.Session() as s: + q = select(JobMark.mark).where(JobMark.job_id == job_id) + return set((await s.execute(q)).scalars()) + + async def sync_update_post(self, pid: int, expected: Optional[datetime], fields: dict) -> bool: + """Save what the channel shows - but only if the saved post is still exactly as it was when it was read + (`expected` is its updated_at then), so a change made through the bot meanwhile is never overwritten.""" + async with self.Session() as s: + res = await s.execute( + update(Post).where(Post.id == pid, Post.updated_at == expected).values(**fields, updated_at=utcnow()) + ) + await s.commit() + return bool(res.rowcount) + + # ------------------------------------------------------------ timed deletions + async def schedule_deletes(self, rows: list) -> None: + """rows: dicts with channel_id, message_id, delete_at, group_id, created_by.""" + if not rows: + return + async with self.Session() as s: + s.add_all([ScheduledDelete(**r) for r in rows]) + await s.commit() + + async def due_deletes(self, now: datetime, limit: int = 500) -> list: + async with self.Session() as s: + q = ( + select(ScheduledDelete) + .where(ScheduledDelete.status == "pending", ScheduledDelete.delete_at <= now) + .order_by(ScheduledDelete.delete_at, ScheduledDelete.id) + .limit(limit) + ) + return list((await s.execute(q)).scalars()) + + async def next_delete_at(self) -> Optional[datetime]: + async with self.Session() as s: + q = select(func.min(ScheduledDelete.delete_at)).where(ScheduledDelete.status == "pending") + return as_utc((await s.execute(q)).scalar_one_or_none()) + + async def pending_deletes(self, group_id: Optional[str] = None, status: str = "pending") -> list: + async with self.Session() as s: + q = select(ScheduledDelete).where(ScheduledDelete.status == status).order_by(ScheduledDelete.id) + if group_id: + q = q.where(ScheduledDelete.group_id == group_id) + return list((await s.execute(q)).scalars()) + + async def finish_deletes(self, ids: list) -> None: + if not ids: + return + async with self.Session() as s: + for row in (await s.execute(select(ScheduledDelete).where(ScheduledDelete.id.in_(list(ids))))).scalars(): + await s.delete(row) + await s.commit() + + async def retry_delete(self, sid: int, *, at: datetime, error: str) -> None: + async with self.Session() as s: + row = await s.get(ScheduledDelete, sid) + if row is not None: + row.attempts += 1 + row.delete_at = at + row.last_error = error[:160] + await s.commit() + + async def fail_delete(self, sid: int, error: str) -> None: + async with self.Session() as s: + row = await s.get(ScheduledDelete, sid) + if row is not None: + row.attempts += 1 + row.status = "failed" + row.last_error = error[:160] + await s.commit() + + # ------------------------------------------------------------- replace history + async def create_batch(self, batch_id: str, old: str, new: str, user_id: int) -> None: + async with self.Session() as s: + s.add(Batch(id=batch_id, old_username=old, new_username=new, created_by=user_id)) + await s.commit() + + async def _adopt(self, s, channel_id: int, message_id: int, fields: dict, user_id: int) -> None: + q = select(Post).where(Post.channel_id == channel_id, Post.message_id == message_id) + p = (await s.execute(q)).scalar_one_or_none() + if p is not None: + for k, v in fields.items(): + setattr(p, k, v) + p.updated_at = utcnow() + else: + s.add( + Post( + channel_id=channel_id, + message_id=message_id, + status="sent", + source="adopted", + created_by=user_id, + sent_at=utcnow(), + **fields, + ) + ) + + async def record_changes(self, batch_id: str, channel_id: int, records: list, user_id: int) -> None: + """records: [{message_id, old_state, new_state, adopt: {post fields}}]""" + if not records: + return + async with self.Session() as s: + for r in records: + s.add( + Change( + batch_id=batch_id, + channel_id=channel_id, + message_id=r["message_id"], + old_state=r["old_state"], + new_state=r["new_state"], + ) + ) + await self._adopt(s, channel_id, r["message_id"], r["adopt"], user_id) + await s.commit() + + async def last_batch(self) -> Optional[Batch]: + async with self.Session() as s: + q = select(Batch).where(Batch.undone.is_(False)).order_by(desc(Batch.created_at)).limit(1) + return (await s.execute(q)).scalar_one_or_none() + + async def get_batch(self, batch_id: str) -> Optional[Batch]: + async with self.Session() as s: + return await s.get(Batch, batch_id) + + async def batch_changes(self, batch_id: str) -> list: + async with self.Session() as s: + q = select(Change).where(Change.batch_id == batch_id, Change.reverted.is_(False)).order_by(Change.id) + return list((await s.execute(q)).scalars()) + + async def count_batch_changes(self, batch_id: str) -> int: + async with self.Session() as s: + q = select(func.count()).select_from(Change).where(Change.batch_id == batch_id, Change.reverted.is_(False)) + return (await s.execute(q)).scalar_one() + + async def finish_undo(self, batch_id: str, change_ids: list, restored: list, all_done: bool) -> None: + """restored: [(channel_id, message_id, state)] -> refresh the saved post copies.""" + async with self.Session() as s: + for cid in change_ids: + c = await s.get(Change, cid) + if c is not None: + c.reverted = True + for channel_id, message_id, state in restored: + q = select(Post).where(Post.channel_id == channel_id, Post.message_id == message_id) + p = (await s.execute(q)).scalar_one_or_none() + if p is not None: + if not state.get("rich"): # a rich message's text was never changed: it stays as saved + p.text = state.get("text", "") + p.entities = state.get("entities", []) + p.buttons = state.get("buttons", []) + p.updated_at = utcnow() + if all_done: + b = await s.get(Batch, batch_id) + if b is not None: + b.undone = True + await s.commit() + + + # ------------------------------------------------------------------ /repost + OPEN_STATES = ("copying", "stopped", "incomplete", "copied") + + async def create_migration(self, mid: str, channel_id: int, *, old, new, include_typed: bool, include_posts: bool, + first_id: int, last_id: int, partial: bool, user_id: int) -> None: + async with self.Session() as s: + s.add(Migration(id=mid, channel_id=channel_id, old_username=old, new_username=new, + include_typed=include_typed, include_posts=include_posts, first_id=first_id, + last_id=last_id, partial=partial, created_by=user_id)) + await s.commit() + + async def get_migration(self, mid: str) -> Optional[Migration]: + async with self.Session() as s: + return await s.get(Migration, mid) + + async def open_migration(self, channel_id: Optional[int] = None) -> Optional[Migration]: + """The newest repost that is not finished yet (copies exist, old posts not deleted / copies not removed).""" + async with self.Session() as s: + q = select(Migration).where(Migration.status.in_(self.OPEN_STATES)) + if channel_id is not None: + q = q.where(Migration.channel_id == channel_id) + q = q.order_by(desc(Migration.created_at)).limit(1) + return (await s.execute(q)).scalar_one_or_none() + + async def set_migration_status(self, mid: str, status: str) -> None: + async with self.Session() as s: + m = await s.get(Migration, mid) + if m is not None: + m.status = status + await s.commit() + + async def migration_done_old_ids(self, mid: str) -> set: + async with self.Session() as s: + q = select(MigrationItem.old_id).where(MigrationItem.migration_id == mid) + return set((await s.execute(q)).scalars()) + + async def record_repost(self, mid: str, channel_id: int, rows: list, user_id: int) -> None: + """rows: [{old_id, new_id, post: {Post fields}}] - saves the mapping and registers the new posts.""" + if not rows: + return + async with self.Session() as s: + await self._drop_slots(s, channel_id, [r["new_id"] for r in rows]) + for r in rows: + s.add(MigrationItem(migration_id=mid, old_id=r["old_id"], new_id=r["new_id"])) + s.add(Post(channel_id=channel_id, message_id=r["new_id"], status="sent", source="bot", + created_by=user_id, sent_at=utcnow(), **r["post"])) + await s.commit() + + async def migration_pairs( + self, mid: Optional[str] = None, channel_id: Optional[int] = None, alive_only: bool = True + ) -> list: + """[(old id, new id)] of the copies of one repost (`mid`) or of every repost of a channel, oldest repost first. + alive_only: leave out copies that were removed again (undo).""" + async with self.Session() as s: + q = select(MigrationItem.old_id, MigrationItem.new_id).join(Migration, Migration.id == MigrationItem.migration_id) + if mid is not None: + q = q.where(MigrationItem.migration_id == mid) + if channel_id is not None: + q = q.where(Migration.channel_id == channel_id) + if alive_only: + q = q.where(MigrationItem.new_deleted.is_(False)) + q = q.order_by(Migration.created_at, MigrationItem.id) + return [(a, b) for a, b in (await s.execute(q)).all()] + + async def update_post_by_message(self, channel_id: int, message_id: int, **fields: Any) -> Optional[Post]: + """Change the saved copy of the post that sits at `message_id` (None if the bot does not know that post).""" + async with self.Session() as s: + q = select(Post).where(Post.channel_id == channel_id, Post.message_id == message_id) + p = (await s.execute(q)).scalar_one_or_none() + if p is None: + return None + for k, v in fields.items(): + setattr(p, k, v) + p.updated_at = utcnow() + await s.commit() + return p + + async def migration_pending_ids(self, mid: str, which: str, limit: int = 100) -> list: + col, flag = (MigrationItem.old_id, MigrationItem.old_deleted) if which == "old" else (MigrationItem.new_id, MigrationItem.new_deleted) + async with self.Session() as s: + q = select(col).where(MigrationItem.migration_id == mid, flag.is_(False)).order_by(col).limit(limit) + return list((await s.execute(q)).scalars()) + + async def mark_migration_deleted(self, mid: str, channel_id: int, which: str, ids: list) -> None: + """The messages are gone from Telegram: flag them and drop their saved post copies.""" + if not ids: + return + col, flag = ("old_id", "old_deleted") if which == "old" else ("new_id", "new_deleted") + async with self.Session() as s: + q = select(MigrationItem).where(MigrationItem.migration_id == mid, getattr(MigrationItem, col).in_(ids)) + for it in (await s.execute(q)).scalars(): + setattr(it, flag, True) + pq = select(Post).where(Post.channel_id == channel_id, Post.message_id.in_(ids)) + for p in (await s.execute(pq)).scalars(): + await s.delete(p) + await s.commit() + + async def migration_counts(self, mid: str) -> dict: + async with self.Session() as s: + total = (await s.execute(select(func.count()).select_from(MigrationItem).where(MigrationItem.migration_id == mid))).scalar_one() + old_left = (await s.execute(select(func.count()).select_from(MigrationItem).where( + MigrationItem.migration_id == mid, MigrationItem.old_deleted.is_(False)))).scalar_one() + new_left = (await s.execute(select(func.count()).select_from(MigrationItem).where( + MigrationItem.migration_id == mid, MigrationItem.new_deleted.is_(False)))).scalar_one() + lo = (await s.execute(select(func.min(MigrationItem.new_id)).where(MigrationItem.migration_id == mid))).scalar_one() + hi = (await s.execute(select(func.max(MigrationItem.new_id)).where(MigrationItem.migration_id == mid))).scalar_one() + return {"copied": total, "old_left": old_left, "new_left": new_left, "first_new": lo, "last_new": hi} + + # ------------------------------------------------------------------- /shift + SHIFT_OPEN = ("copying", "stopped", "incomplete") + + async def create_shift(self, sid: str, *, src, dst_channel_id: int, first_id: int, last_id: int, user_id: int) -> None: + """`src`: any object with id, access_hash, title and username (the source channel need not be registered).""" + async with self.Session() as s: + s.add(Shift(id=sid, src_channel_id=src.id, src_access_hash=src.access_hash or 0, src_title=src.title or "", + src_username=src.username, dst_channel_id=dst_channel_id, first_id=first_id, last_id=last_id, + created_by=user_id)) + await s.commit() + + async def get_shift(self, sid: str) -> Optional[Shift]: + async with self.Session() as s: + return await s.get(Shift, sid) + + async def open_shift(self, src_id: Optional[int] = None, dst_id: Optional[int] = None) -> Optional[Shift]: + """The newest shift that is not finished (still copying, stopped, or incomplete).""" + async with self.Session() as s: + q = select(Shift).where(Shift.status.in_(self.SHIFT_OPEN)) + if src_id is not None: + q = q.where(Shift.src_channel_id == src_id) + if dst_id is not None: + q = q.where(Shift.dst_channel_id == dst_id) + return (await s.execute(q.order_by(desc(Shift.created_at)).limit(1))).scalar_one_or_none() + + async def last_finished_shift(self) -> Optional[Shift]: + """The newest finished shift that still has copies in its destination - so its Undo can be offered again.""" + async with self.Session() as s: + alive = select(ShiftItem.id).where(ShiftItem.shift_id == Shift.id, ShiftItem.new_deleted.is_(False)).exists() + q = select(Shift).where(Shift.status == "copied", alive).order_by(desc(Shift.created_at)).limit(1) + return (await s.execute(q)).scalar_one_or_none() + + async def set_shift_status(self, sid: str, status: str) -> None: + async with self.Session() as s: + sh = await s.get(Shift, sid) + if sh is not None: + sh.status = status + await s.commit() + + async def shift_done_ids(self, sid: str) -> set: + async with self.Session() as s: + q = select(ShiftItem.old_id).where(ShiftItem.shift_id == sid) + return set((await s.execute(q)).scalars()) + + async def shift_pairs(self, sid: str, alive_only: bool = True) -> list: + """[(source id, id of the copy)] of one shift, in copy order.""" + async with self.Session() as s: + q = select(ShiftItem.old_id, ShiftItem.new_id).where(ShiftItem.shift_id == sid) + if alive_only: + q = q.where(ShiftItem.new_deleted.is_(False)) + return [(a, b) for a, b in (await s.execute(q.order_by(ShiftItem.id))).all()] + + async def shifted_ids(self, src_id: int, dst_id: int, first: int, last: int) -> set: + """Source ids in first..last that already have a live copy in `dst_id` from an earlier shift.""" + async with self.Session() as s: + q = ( + select(ShiftItem.old_id) + .join(Shift, Shift.id == ShiftItem.shift_id) + .where(Shift.src_channel_id == src_id, Shift.dst_channel_id == dst_id, ShiftItem.new_deleted.is_(False), + ShiftItem.old_id >= first, ShiftItem.old_id <= last) + ) + return set((await s.execute(q)).scalars()) + + async def record_shift(self, sid: str, dst_channel_id: int, rows: list, user_id: int) -> None: + """rows: [{old_id, new_id, post: {Post fields}}] - saves the mapping and registers the copies in My posts.""" + if not rows: + return + async with self.Session() as s: + await self._drop_slots(s, dst_channel_id, [r["new_id"] for r in rows]) + for r in rows: + s.add(ShiftItem(shift_id=sid, old_id=r["old_id"], new_id=r["new_id"])) + s.add(Post(channel_id=dst_channel_id, message_id=r["new_id"], status="sent", source="bot", + created_by=user_id, sent_at=utcnow(), **r["post"])) + await s.commit() + + async def shift_counts(self, sid: str) -> dict: + async with self.Session() as s: + base = ShiftItem.shift_id == sid + total = (await s.execute(select(func.count()).select_from(ShiftItem).where(base))).scalar_one() + left = (await s.execute(select(func.count()).select_from(ShiftItem).where(base, ShiftItem.new_deleted.is_(False)))).scalar_one() + lo = (await s.execute(select(func.min(ShiftItem.new_id)).where(base))).scalar_one() + hi = (await s.execute(select(func.max(ShiftItem.new_id)).where(base))).scalar_one() + return {"copied": total, "new_left": left, "first_new": lo, "last_new": hi} + + async def shift_pending_new(self, sid: str, limit: int = 100) -> list: + async with self.Session() as s: + q = select(ShiftItem.new_id).where(ShiftItem.shift_id == sid, ShiftItem.new_deleted.is_(False)).order_by(ShiftItem.new_id).limit(limit) + return list((await s.execute(q)).scalars()) + + async def mark_shift_deleted(self, sid: str, dst_channel_id: int, ids: list) -> None: + """The copies are gone from Telegram: flag them and drop their saved posts.""" + if not ids: + return + async with self.Session() as s: + q = select(ShiftItem).where(ShiftItem.shift_id == sid, ShiftItem.new_id.in_(ids)) + for it in (await s.execute(q)).scalars(): + it.new_deleted = True + pq = select(Post).where(Post.channel_id == dst_channel_id, Post.message_id.in_(ids)) + for p in (await s.execute(pq)).scalars(): + await s.delete(p) + await s.commit() + + # -------------------------------------------------------------------- export + async def export_all(self) -> dict: + def clean(d: dict) -> dict: + return {k: (v.isoformat() if isinstance(v, datetime) else v) for k, v in d.items()} + + async with self.Session() as s: + chans = list((await s.execute(select(Channel))).scalars()) + posts = list((await s.execute(select(Post).order_by(Post.id))).scalars()) + marks = (await s.execute(select(IgnoredPost.channel_id, IgnoredPost.message_id).order_by(IgnoredPost.id))).all() + return { + "exported_at": utcnow().isoformat(), + "channels": [ + clean({c.name: getattr(ch, c.name) for c in ch.__table__.columns}) for ch in chans + ], + "posts": [clean(p.as_dict()) for p in posts], + "ignored": [{"channel_id": int(c), "message_id": int(m)} for c, m in marks], # posts forgotten on purpose + } diff --git a/app/errorlog.py b/app/errorlog.py new file mode 100644 index 0000000000000000000000000000000000000000..01a4085f6f6a8ea28d1f150ee8808cffda3e5ce9 --- /dev/null +++ b/app/errorlog.py @@ -0,0 +1,300 @@ +"""Send errors to a Telegram chat (ERROR_LOG_CHAT_ID) as a `python` code block. + +What is reported: + * every log record of level ERROR or higher that carries a message / traceback (handler failures included), + * exceptions nobody caught in background tasks ("Unhandled exception in background task :"), + * a crash of the whole bot (sent right before it exits). +Long tracebacks are cut into several messages, never shortened. Secrets (bot token, API hash, session texts, +database password) are replaced by *** before anything leaves the bot. The reporter never raises, never blocks the +bot, and protects the chat from floods (identical reports are merged, at most a few per minute). +""" +from __future__ import annotations + +import asyncio +import hashlib +import logging +import re +import time +import traceback +from collections import deque +from typing import Optional + +from telethon import types + +from .tgutil import utf16_len + +log = logging.getLogger(__name__) + +PART_LIMIT = 3800 # characters per message (Telegram allows 4096; the rest is head-room for the part label) +PIECE = 1500 # a single line longer than a message is cut into pieces of this size +MUTE_SECONDS = 600 # after "can't write to the log chat" stay quiet this long +MIN_SECRET = 6 # shorter secrets are not redacted (they would mangle ordinary text) + + +# ----------------------------------------------------------------------------- text helpers +def split_report(text: str, limit: int = PART_LIMIT) -> list: + """Cut a report into messages of at most `limit` characters at line breaks. Nothing is dropped.""" + if len(text) <= limit: + return [text] + room = limit - 40 # space for the "(part 3/12)" label + pieces: list = [] + for line in text.split("\n"): + while len(line) > room: # a single huge line: cut it + size = min(PIECE, room) + pieces.append(line[:size]) + line = line[size:] + pieces.append(line) + parts: list = [] + cur: list = [] # the lines of the part being built + used = 0 + for piece in pieces: + add = len(piece) + (1 if cur else 0) + if cur and used + add > room: + parts.append("\n".join(cur)) + cur, used = [piece], len(piece) + else: + cur.append(piece) + used += add + if cur: + parts.append("\n".join(cur)) + n = len(parts) + return [f"(part {i}/{n})\n{p}" for i, p in enumerate(parts, 1)] + + +def redact(text: str, secrets) -> str: + for s in sorted({s for s in secrets if s and len(s) >= MIN_SECRET}, key=len, reverse=True): + text = text.replace(s, "***") + return text + + +def format_exception(exc: BaseException) -> str: + return "".join(traceback.format_exception(type(exc), exc, exc.__traceback__)) + + +def _task_label(task) -> str: + name = getattr(task, "get_name", lambda: "")() if task is not None else "" + if not name or re.fullmatch(r"Task-\d+", name): + return "" + return name + + +# ---------------------------------------------------------------------------------- reporter +class ErrorReporter: + def __init__( + self, + client, + chat_id: Optional[int], + *, + bot_token: str = "", + secrets=(), + per_minute: int = 12, + dedupe_seconds: float = 60.0, + gap: float = 1.0, + part_gap: float = 0.6, + ): + self.client = client + self.chat_id = chat_id + self.bot_token = bot_token + self.secrets = [s for s in (*secrets, bot_token) if s] # the login token is always hidden too + self.per_minute = per_minute + self.dedupe_seconds = dedupe_seconds + self.gap = gap + self.part_gap = part_gap + self._loop: Optional[asyncio.AbstractEventLoop] = None + self._queue: Optional[asyncio.Queue] = None + self._task: Optional[asyncio.Task] = None + self._peer = None + self._muted_until = 0.0 + self._recent: dict = {} # report key -> [time of the first, number suppressed since] + self._times: deque = deque() # when reports were accepted (for the per-minute limit) + self._skipped = 0 # reports dropped by the limit since the last one that went out + + @property + def enabled(self) -> bool: + return bool(self.chat_id) + + # ------------------------------------------------------------------ life cycle + def start(self) -> None: + if not self.enabled or self._task is not None: + return + self._loop = asyncio.get_running_loop() + self._queue = asyncio.Queue(maxsize=100) + self._task = self._loop.create_task(self._worker(), name="error-reporter") + + async def stop(self, wait: float = 5.0) -> None: + """Let queued reports go out (for a few seconds at most), then stop.""" + task, self._task = self._task, None + if task is None: + return + try: + await asyncio.wait_for(self._queue.join(), wait) + except Exception: + pass + task.cancel() + try: + await task + except BaseException: + pass + + # ---------------------------------------------------------------------- input + def submit(self, title: str, tb: str = "") -> None: + """Queue a report. Safe to call from any thread; never raises.""" + try: + loop = self._loop + if not self.enabled or loop is None or loop.is_closed(): + return + try: + here = asyncio.get_running_loop() + except RuntimeError: + here = None + if here is loop: + self._enqueue(title, tb) + else: + loop.call_soon_threadsafe(self._enqueue, title, tb) + except Exception: + pass + + def _enqueue(self, title: str, tb: str) -> None: + try: + now = time.monotonic() + if now < self._muted_until or self._queue is None: + return + last_line = next((ln for ln in reversed(tb.splitlines()) if ln.strip()), "") + key = hashlib.sha1(f"{title}|{last_line}".encode("utf-8", "replace")).hexdigest() + prev = self._recent.get(key) + merged = 0 + if prev is not None: + if now - prev[0] < self.dedupe_seconds: + prev[1] += 1 # same error again: counted, reported with the next one + return + merged = prev[1] + self._recent[key] = [now, 0] + if len(self._recent) > 200: + for k in sorted(self._recent, key=lambda k: self._recent[k][0])[:100]: + self._recent.pop(k, None) + while self._times and now - self._times[0] > 60: + self._times.popleft() + if len(self._times) >= self.per_minute: + self._skipped += 1 + return + self._times.append(now) + skipped, self._skipped = self._skipped, 0 + try: + self._queue.put_nowait((title, tb, merged, skipped)) + except asyncio.QueueFull: + self._skipped += 1 + skipped + except Exception: + pass + + def loop_exception_handler(self, loop, context) -> None: + """asyncio calls this for exceptions nobody retrieved (set it with loop.set_exception_handler).""" + try: + exc = context.get("exception") + task = context.get("task") or context.get("future") + if task is not None and exc is not None: + title = f"Unhandled exception in background task {_task_label(task)}:" + else: + title = (context.get("message") or "Unhandled error in the event loop") + ":" + tb = format_exception(exc) if exc is not None else "" + self.submit(title, tb) + except Exception: + pass + finally: + loop.default_exception_handler(context) # keep the normal log line too + + # --------------------------------------------------------------------- output + async def _worker(self) -> None: + assert self._queue is not None + while True: + item = await self._queue.get() + try: + await self._deliver(*item) + except asyncio.CancelledError: + raise + except Exception as e: + name = type(e).__name__ + log.warning("could not write to the error log chat: %s %s", name, str(e)[:150]) + if isinstance(e, (ValueError, PermissionError)) or "Forbidden" in name or "Private" in name: + # the bot is not a member of that chat (or may not write there): stop trying for a while + self._muted_until = time.monotonic() + MUTE_SECONDS + self._peer = None + finally: + self._queue.task_done() + await asyncio.sleep(self.gap) + + async def _deliver(self, title: str, tb: str, merged: int = 0, skipped: int = 0) -> None: + if self._peer is None: + self._peer = await self.client.get_input_entity(self.chat_id) + text = title + (("\n\n" + tb.rstrip("\n")) if tb else "") + notes = [] + if merged: + notes.append(f"(+{merged} identical report(s) suppressed)") + if skipped: + notes.append(f"({skipped} report(s) were skipped because too many errors came in)") + if notes: + text += "\n\n" + "\n".join(notes) + text = redact(text, self.secrets) + parts = split_report(text) + for i, part in enumerate(parts): + await self.client.send_message( + self._peer, + part, + formatting_entities=[types.MessageEntityPre(0, utf16_len(part), "python")], + link_preview=False, + ) + if i < len(parts) - 1: + await asyncio.sleep(self.part_gap) + + async def check(self) -> Optional[str]: + """None when the log chat can be reached, otherwise a short reason (used once at start-up).""" + if not self.enabled: + return None + try: + self._peer = await self.client.get_input_entity(self.chat_id) + return None + except Exception as e: + return ( + f"{type(e).__name__}: {str(e)[:120]} - add the bot to that chat " + "(as a member, or as an admin who may post)" + ) + + async def report_fatal(self, title: str, exc: BaseException) -> None: + """The bot is going down: send the crash straight away (the queue may not get the time).""" + if not self.enabled: + return + try: + + async def go() -> None: + if not self.client.is_connected(): + await self.client.connect() + if self.bot_token and not await self.client.is_user_authorized(): + await self.client.sign_in(bot_token=self.bot_token) + await self._deliver(title + ":", format_exception(exc)) + + await asyncio.wait_for(go(), 20) + except Exception as e: + log.warning("could not send the crash report: %s %s", type(e).__name__, str(e)[:150]) + + +# ------------------------------------------------------------------------------ logging +class TelegramLogHandler(logging.Handler): + """Forwards log records (ERROR and up) to the reporter.""" + + def __init__(self, reporter: ErrorReporter, level: int = logging.ERROR): + super().__init__(level) + self.reporter = reporter + + def emit(self, record: logging.LogRecord) -> None: + try: + if record.name.startswith("app.errorlog") or record.name == "asyncio": + return # our own messages would loop; asyncio's go through loop_exception_handler + title = record.getMessage() + tb = "" + if record.exc_info and record.exc_info[0] is not None: + tb = "".join(traceback.format_exception(*record.exc_info)) + title += ":" + if not record.name.startswith(("app", "bot", "__main__")): + title = f"[{record.name}] {title}" + self.reporter.submit(title, tb) + except Exception: + pass diff --git a/app/expiry.py b/app/expiry.py new file mode 100644 index 0000000000000000000000000000000000000000..045d537d1877a7cf28aa015b89d7bdef72c0c490 --- /dev/null +++ b/app/expiry.py @@ -0,0 +1,208 @@ +"""Timed deletion: a broadcast with an expiry ("/broadcast 1h") is removed from every channel - and from My posts - +when its time is up. + +The deletions are saved in the database (table scheduled_deletes), so a restart loses nothing: posts that came due while +the bot was off are deleted as soon as it is back. The Expirer wakes up only when something is due; it does not poll the +database, so a sleeping serverless database stays asleep. +""" +from __future__ import annotations + +import asyncio +import logging +import re +from datetime import datetime, timedelta +from typing import Optional + +from .db import as_utc, utcnow +from .repost_engine import delete_batch +from .tgutil import esc, peer_of + +log = logging.getLogger(__name__) + +MIN_SECONDS = 60 +MAX_SECONDS = 366 * 86400 +MAX_ATTEMPTS = 5 +RETRY_AFTER = 600 # seconds between attempts, times the attempt number +LOCK_WAIT = 60 # a long job (repost...) is running: look again in a minute + +_UNITS = { + "m": 60, "min": 60, "mins": 60, "minute": 60, "minutes": 60, + "h": 3600, "hr": 3600, "hrs": 3600, "hour": 3600, "hours": 3600, + "d": 86400, "day": 86400, "days": 86400, + "w": 604800, "week": 604800, "weeks": 604800, +} # fmt: skip +_PART = re.compile(r"(\d+)\s*([a-z]+)") +DURATION_HELP = "Use minutes, hours or days: 50m, 1h, 5d (or 1d12h). Leave the time out to keep the message forever." + + +def parse_duration(text: str) -> int: + """'50m' -> 3000, '1h' -> 3600, '5d' -> 432000, '1d12h' -> 129600 (seconds). ValueError with a message if unusable.""" + t = (text or "").strip().lower().replace(",", " ") + if not t or not re.fullmatch(r"(?:\d+\s*[a-z]+\s*)+", t): + raise ValueError(f"I can't read “{(text or '').strip()[:30]}” as a time. {DURATION_HELP}") + total = 0 + for n, unit in _PART.findall(t): + if unit not in _UNITS: + raise ValueError(f"“{n}{unit}” - I don't know the unit “{unit}”. {DURATION_HELP}") + total += int(n) * _UNITS[unit] + if total < MIN_SECONDS: + raise ValueError("The shortest time is 1 minute.") + if total > MAX_SECONDS: + raise ValueError("The longest time is 1 year (365d).") + return total + + +def human(seconds: int) -> str: + """3000 -> '50 minutes', 3600 -> '1 hour', 129600 -> '1 day 12 hours'.""" + seconds = int(seconds) + days, rest = divmod(seconds, 86400) + hours, rest = divmod(rest, 3600) + minutes = rest // 60 + parts = [] + for n, word in ((days, "day"), (hours, "hour"), (minutes, "minute")): + if n: + parts.append(f"{n} {word}" + ("s" if n != 1 else "")) + return " ".join(parts[:2]) or "under a minute" + + +def stamp(dt: datetime) -> str: + return as_utc(dt).strftime("%d %b %Y, %H:%M UTC") + + +class Expirer: + """Deletes scheduled messages when they come due. `start()` runs it in the background.""" + + def __init__(self, ctx, *, notify=None): + self.ctx = ctx + self._next: Optional[datetime] = None + self._wake = asyncio.Event() + self._task: Optional[asyncio.Task] = None + self._notify = notify # async fn(user_id, text) used to tell someone a deletion failed for good + + # ------------------------------------------------------------------------- running + def start(self) -> None: + if self._task is None: + self._task = asyncio.create_task(self.run(), name="expirer") + + async def stop(self) -> None: + if self._task is not None: + self._task.cancel() + try: + await self._task + except (asyncio.CancelledError, Exception): + pass + self._task = None + + def notify(self, when: datetime) -> None: + """Something was scheduled for `when`: make sure the loop wakes up in time.""" + when = as_utc(when) + if self._next is None or when < self._next: + self._next = when + self._wake.set() + + async def load(self) -> None: + """The one look at the database (when the bot starts): when is the first deletion due?""" + try: + self._next = await self.ctx.db.next_delete_at() + except Exception: + log.exception("could not read the scheduled deletions") + + async def run(self) -> None: + await self.load() + while True: + delay = None if self._next is None else max(0.0, (self._next - utcnow()).total_seconds()) + try: + await asyncio.wait_for(self._wake.wait(), timeout=delay) + except asyncio.TimeoutError: + pass + self._wake.clear() + if self._next is not None and self._next <= utcnow(): + try: + await self.sweep() + except asyncio.CancelledError: + raise + except Exception: + log.exception("deleting scheduled messages failed") + self._next = utcnow() + timedelta(seconds=RETRY_AFTER) + + # --------------------------------------------------------------------------- work + async def sweep(self, now: Optional[datetime] = None) -> dict: + """Delete everything that is due at `now`. Returns {'deleted': n, 'retry': n, 'failed': n}.""" + ctx, db = self.ctx, self.ctx.db + now = now or utcnow() + stats = {"deleted": 0, "retry": 0, "failed": 0, "waiting": False} + due = await db.due_deletes(now) + if due and ctx.lock.locked(): # a repost / shift is running: don't pull posts out from under it + stats["waiting"] = True + self._next = now + timedelta(seconds=LOCK_WAIT) + return stats + by_channel: dict = {} + for row in due: + by_channel.setdefault(row.channel_id, []).append(row) + for cid, rows in by_channel.items(): + await self._sweep_channel(cid, rows, now, stats) + self._next = await db.next_delete_at() + return stats + + async def _sweep_channel(self, cid: int, rows: list, now: datetime, stats: dict) -> None: + ctx, db = self.ctx, self.ctx.db + ch = await db.get_channel(cid) + if ch is None: + for r in rows: + await db.fail_delete(r.id, "the channel was removed from the bot") + stats["failed"] += 1 + return + peer = peer_of(ch) + ids = sorted({r.message_id for r in rows}) + gone: set = set() + error: Optional[str] = None + try: + for i in range(0, len(ids), 100): + out = await delete_batch(ctx.client, peer, ids[i : i + 100], None) + gone |= out.gone + error = error or out.bot_error + left = [m for m in ids if m not in gone] + ub = getattr(ctx, "userbot", None) + if left and ub is not None and ub.enabled: # the bot may not delete old posts: the userbot tries + fallback, deleter = await ub.fallback_for(ch) + try: + if fallback is not None: + for i in range(0, len(left), 100): + out = await delete_batch(ctx.client, peer, left[i : i + 100], fallback) + gone |= out.gone + error = out.fallback_error or error + finally: + if deleter is not None: + await deleter.close() + except Exception as e: + log.exception("deleting scheduled messages of channel %s failed", cid) + error = type(e).__name__ + done = [r for r in rows if r.message_id in gone] + await db.finish_deletes([r.id for r in done]) + await db.forget_posts(cid, sorted(gone)) + stats["deleted"] += len(done) + for r in rows: + if r.message_id in gone: + continue + why = error or "Telegram did not delete it" + if r.attempts + 1 >= MAX_ATTEMPTS: + await db.fail_delete(r.id, why) + stats["failed"] += 1 + await self._tell(r, ch, why) + else: + await db.retry_delete(r.id, at=now + timedelta(seconds=RETRY_AFTER * (r.attempts + 1)), error=why) + stats["retry"] += 1 + + async def _tell(self, row, ch, why: str) -> None: + """A deletion failed for good: tell the person who sent the broadcast.""" + text = ( + f"⚠️ I could not delete the expired broadcast post {row.message_id} in {esc(ch.title)} " + f"({esc(why)}). Delete it by hand, then use “Only forget it in the bot” in /posts." + ) + try: + if self._notify is not None: + await self._notify(row.created_by, text) + elif row.created_by: + await self.ctx.client.send_message(row.created_by, text, link_preview=False) + except Exception: + log.warning("could not tell user %s about the failed deletion", row.created_by, exc_info=True) diff --git a/app/handlers/__init__.py b/app/handlers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/handlers/autopost.py b/app/handlers/autopost.py new file mode 100644 index 0000000000000000000000000000000000000000..ca0f2c49eac2de4de617ec00c6520eb87fff7d8b --- /dev/null +++ b/app/handlers/autopost.py @@ -0,0 +1,203 @@ +"""/autopost : post "Episodes 01 to 20", "Episodes 21 to 40", ... with a download button each, +then ask for the real link of every button. Owners and admins.""" +from __future__ import annotations + +import asyncio +import logging +import re +import secrets +import time +from dataclasses import dataclass, field +from types import SimpleNamespace + +from telethon import Button, errors + +from .. import picker +from ..autopost import ( + MAX_POSTS, + PLACEHOLDER_LINK, + USAGE, + button_label, + parse_autopost_args, + plan_ranges, + post_buttons, + post_text, + ranges_summary, + title_of, +) +from ..common import ( + Ctx, + UserError, + clear_state, + cmd, + discard_temp, + edit_callback_message, + guard, + on_cb, + purge_pending, + say, + send_post, + show, +) +from ..db import utcnow +from ..tgutil import esc, explain_rpc, flood_retry, get_rights, peer_of +from .masslinks import begin_queue + +log = logging.getLogger(__name__) + + +@dataclass +class AutoChoice: + """/autopost was typed with good numbers; the channel still has to be picked.""" + + user: int + total: int + interval: int + ranges: list + created: float = field(default_factory=time.monotonic) + + +@dataclass +class AutoResult: + posts: list = field(default_factory=list) # the saved Post rows, in the order they were posted + failure: str = "" # why it stopped before the end (empty = all posted) + + +async def post_series(ctx: Ctx, ch, ranges: list, user_id: int, *, delay: float = 1.0, progress=None) -> AutoResult: + """Send one post per range to `ch` and save each in My posts. Stops at the first post Telegram refuses.""" + res = AutoResult() + for n, (a, b) in enumerate(ranges, 1): + text, buttons = post_text(a, b), post_buttons(a, b) + shape = SimpleNamespace(text=text, entities=[], buttons=buttons, media_file_id=None, link_preview=False) + try: + sent = await flood_retry(lambda: send_post(ctx.client, peer_of(ch), shape)) + except errors.RPCError as e: + res.failure = f"{title_of(a, b)}: {explain_rpc(e)}" + break + except Exception as e: + log.exception("autopost: posting %s failed", title_of(a, b)) + res.failure = f"{title_of(a, b)}: {type(e).__name__}" + break + res.posts.append( + await ctx.db.create_post( + channel_id=ch.id, + message_id=sent.id, + status="sent", + source="bot", + created_by=user_id, + text=text, + entities=[], + buttons=buttons, + link_preview=False, + sent_at=utcnow(), + ) + ) + if progress: + await progress(n) + if n < len(ranges): + await asyncio.sleep(delay) + return res + + +def register(ctx: Ctx) -> None: + client, db, cfg = ctx.client, ctx.db, ctx.cfg + + @client.on(cmd("autopost", args=True)) + @guard(ctx) + async def h_autopost(event): + purge_pending(ctx) + raw = (event.pattern_match.group(1) or "").strip() + if not raw: + await say(event, USAGE) + return + try: + total, interval = parse_autopost_args(raw) + except ValueError as e: + raise UserError(f"{e}\n\n" + re.sub(r"<[^>]+>", "", USAGE).replace("<", "<").replace(">", ">")) + ranges = plan_ranges(total, interval) + if len(ranges) > MAX_POSTS: + raise UserError(f"That would be {len(ranges)} posts - at most {MAX_POSTS} at once. Use a bigger interval.") + chans = await db.list_channels() + if not chans: + raise UserError("No channels yet. Register one with /addchannel first.") + uid = event.sender_id + await discard_temp(ctx, uid) + clear_state(ctx, uid) + token = secrets.token_hex(4) + ctx.pending[token] = AutoChoice(user=uid, total=total, interval=interval, ranges=ranges) + await show_picker(event, token, 0) + + async def show_picker(event, token: str, page: int) -> None: + choice = ctx.pending.get(token) + if not isinstance(choice, AutoChoice) or choice.user != event.sender_id: + raise UserError("That list has expired. Run /autopost again.") + chans = await db.list_channels() + if not chans: + raise UserError("No channels yet. Register one with /addchannel first.") + first = choice.ranges[0] + head = ( + f"📋 Autopost: {len(choice.ranges)} post(s) for {choice.total} episodes (every {choice.interval})\n" + f"{ranges_summary(choice.ranges)}\n\n" + f"Each post says “{esc(title_of(*first))}” with the button “{esc(button_label(*first))}”. The buttons get " + f"the link {esc(PLACEHOLDER_LINK)} for now; when everything is posted I ask you for the real link of " + "each button, one after the other.\n\n" + "📢 Which channel should I post them in?" + ) + text, kb = picker.render( + chans, + page, + head=head, + kind="ap", + arg=token, + choose=lambda c: f"apc:{token}:{c.id}", + extra_rows=[[Button.inline("✖️ Cancel", f"apx:{token}")]], + ) + await show(event, text, kb) + + ctx.pickers["ap"] = show_picker + + @on_cb(ctx, "apc") + async def cb_pick(event, parts): + token, cid = parts[0], int(parts[1]) + choice = ctx.pending.get(token) + if not isinstance(choice, AutoChoice) or choice.user != event.sender_id: + raise UserError("That list has expired. Run /autopost again.") + ch = await db.get_channel(cid) + if ch is None or not ch.active: + raise UserError("That channel is not registered any more. Run /autopost again.") + rights = await get_rights(client, ch) + if rights is not None and not (rights.admin and rights.post): + raise UserError("The bot needs the “Post messages” admin right in that channel.") + if ctx.lock.locked(): + raise UserError("Another long job (replace / repost / shift) is still running. Try again in a minute.") + ctx.pending.pop(token, None) # a second press on the list can't post everything twice + last = [0.0] + + async def prog(n): + if time.monotonic() - last[0] < 3: + return + last[0] = time.monotonic() + try: + await edit_callback_message(event, f"📤 Posting in {esc(ch.title)}: {n} of {len(choice.ranges)}…") + except Exception: + pass + + async with ctx.lock: + res = await post_series(ctx, ch, choice.ranges, event.sender_id, delay=cfg.edit_delay, progress=prog) + if not res.posts: + raise UserError(f"Nothing was posted. {res.failure}") + done = [(p.id, 0, 0) for p in res.posts] + lines = [ + f"✅ Posted {len(res.posts)} of {len(choice.ranges)} in {esc(ch.title)}", + ranges_summary(choice.ranges[: len(res.posts)]), + f"Their buttons open {esc(PLACEHOLDER_LINK)} until you send the real links.", + ] + if res.failure: + lines.append(f"\n⚠️ Stopped early - {esc(res.failure)}\nThe rest was not posted; run /autopost again for it.") + await edit_callback_message(event, "\n".join(lines)) + await begin_queue(ctx, event, kind="auto", cid=ch.id, items=done, new=True) + + @on_cb(ctx, "apx") + async def cb_cancel(event, parts): + ctx.pending.pop(parts[0], None) + await edit_callback_message(event, "Cancelled - nothing was posted.") diff --git a/app/handlers/backup.py b/app/handlers/backup.py new file mode 100644 index 0000000000000000000000000000000000000000..ccad3560e4727495362920f3b2cf97fc0d8e0200 --- /dev/null +++ b/app/handlers/backup.py @@ -0,0 +1,173 @@ +"""/import (owner only): put a backup made by /export back. + +The steps: /import → send the file → a preview of what would be added → ✅ Import. Importing only adds, it never +changes or deletes anything that is here (see app/backup.py for the rules). +""" +from __future__ import annotations + +import logging +import secrets +import time +from dataclasses import dataclass, field + +from telethon import Button + +from ..backup import MAX_BYTES, BackupError, ImportPlan, ImportResult, apply_import, parse_backup, plan_import, stamp +from ..common import ( + Ctx, + UserError, + clear_state, + cmd, + guard, + on_cb, + on_text, + purge_pending, + require_owner, + say, + set_state, + show, +) + +log = logging.getLogger(__name__) + +ASK = ( + "📥 Import a backup\n" + "Send me the file that /export made (channel-posts-export.json) as your next message - the file " + "itself, unchanged.\n\n" + "Importing only adds: channels and posts that are here already are left exactly as they are, and nothing is " + "deleted. You see what would be added before anything happens. /cancel stops." +) + + +@dataclass +class PendingImport: + """A backup that was read and is waiting for the owner's OK (or is being imported).""" + + user: int + plan: ImportPlan + running: bool = False + created: float = field(default_factory=time.monotonic) + + +def preview_text(plan: ImportPlan) -> str: + bk = plan.backup + sent_total = sum(1 for p in bk.posts if p["status"] == "sent") + drafts_total = len(bk.posts) - sent_total + made = f" (made {stamp(bk.exported_at)})" if bk.exported_at else "" + lines = [f"📥 Backup file read{made}", ""] + lines.append(f"📢 Channels: {len(bk.channels)} in the file - {len(plan.new_channels)} new, {plan.channels_present} here already") + lines.append(f"📝 Published posts: {sent_total} in the file - {plan.sent_to_add} to add, {plan.posts_present} here already") + if drafts_total: + lines.append(f"🗒 Drafts: {drafts_total} in the file - {plan.drafts_to_add} to add, {plan.drafts_present} here already") + if plan.new_ignored: + lines.append(f"🙈 {len(plan.new_ignored)} post(s) that were made to be forgotten stay forgotten here too") + if plan.posts_forgotten: + lines.append(f"🙈 {plan.posts_forgotten} post(s) you made this bot forget are not brought back") + if plan.posts_orphaned: + lines.append(f"• {plan.posts_orphaned} post(s) belong to a channel that is neither here nor in the file - left out") + if bk.bad_rows: + lines.append(f"• {bk.bad_rows} entr{'y' if bk.bad_rows == 1 else 'ies'} of the file could not be read - left out") + lines.append("") + if plan.nothing_new: + lines.append("There is nothing new in this file - everything in it is here already.") + else: + lines.append("Nothing that is here now is changed or deleted.") + if plan.new_channels: + lines.append( + "A channel that is new here works only if this bot is an admin there. On a different bot, send " + "/addchannel for it once afterwards - its posts stay." + ) + return "\n".join(lines) + + +def result_text(res: ImportResult) -> str: + lines = ["✅ Imported", ""] + if res.channels_added: + lines.append( + f"📢 {res.channels_added} channel(s) added - check them in /channels " + "(on a different bot, send /addchannel for each one once so the bot gets its own access)" + ) + lines.append(f"📝 {res.posts_added} published post(s) added to My posts") + if res.drafts_added: + lines.append(f"🗒 {res.drafts_added} draft(s) added") + if res.marks_added: + lines.append(f"🙈 {res.marks_added} “forgotten” mark(s) added") + if res.skipped_meanwhile: + lines.append(f"• {res.skipped_meanwhile} post(s) turned up here meanwhile and were left as they are") + return "\n".join(lines) + + +def register(ctx: Ctx) -> None: + client, db = ctx.client, ctx.db + + @client.on(cmd("import")) + @guard(ctx, owner=True) + async def h_import(event): + set_state(ctx, event.sender_id, "import") + await say(event, ASK, [[Button.inline("✖️ Cancel", "cx")]]) + + @on_text(ctx, "import") + async def got_file(event, st): + require_owner(ctx, event) + msg = event.message + f = getattr(msg, "file", None) + if f is None: + raise UserError("Please send the backup FILE (the one /export made), not text. /cancel stops.") + if (getattr(f, "size", None) or 0) > MAX_BYTES: + raise UserError(f"That file is larger than {MAX_BYTES // (1024 * 1024)} MB - it is not a backup from /export. Send the right file, or /cancel.") + note = await say(event, "📥 Reading the file…") + data = await msg.download_media(file=bytes) + if not isinstance(data, (bytes, bytearray)): + raise UserError("I could not download that file. Send it again, or /cancel.") + try: + plan = await plan_import(db, parse_backup(bytes(data))) + except BackupError as e: + raise UserError(f"That file can't be imported: {e}\nSend the right file, or /cancel.") + clear_state(ctx, event.sender_id) + purge_pending(ctx) + if plan.nothing_new: + await note.edit(preview_text(plan), buttons=None) + return + token = secrets.token_hex(4) + ctx.pending[token] = PendingImport(user=event.sender_id, plan=plan) + kb = [[Button.inline("✅ Import", f"imy:{token}"), Button.inline("✖️ Cancel", f"imx:{token}")]] + await note.edit(preview_text(plan), buttons=kb) + + @on_cb(ctx, "imx") + async def cb_cancel(event, parts): + require_owner(ctx, event) + pend = ctx.pending.get(parts[0]) + if isinstance(pend, PendingImport) and not pend.running: + ctx.pending.pop(parts[0], None) + await show(event, "Cancelled - nothing was imported.") + + @on_cb(ctx, "imy") + async def cb_import(event, parts): + require_owner(ctx, event) + pend = ctx.pending.get(parts[0]) + if not isinstance(pend, PendingImport): + raise UserError("This import has expired (or was done already). Send /import again.") + if pend.running: + raise UserError("This import is already running.") + if ctx.lock.locked(): + raise UserError("Another long job (replace, repost, shift, sync ...) is still running - try again when it has finished.") + last = [0.0] + + async def prog(done: int, total: int) -> None: + if time.monotonic() - last[0] < 3: + return + last[0] = time.monotonic() + try: + await show(event, f"📥 Importing… {done} of {total} post(s)") + except Exception: + log.debug("progress update failed", exc_info=True) + + async with ctx.lock: + pend.running = True + try: + res = await apply_import(db, pend.plan, progress=prog) + finally: + ctx.pending.pop(parts[0], None) + if ctx.syncer is not None: + ctx.syncer.forget_cache() # the channels that came in are known to the live watch from now on + await show(event, result_text(res), [[Button.inline("📚 My posts", "pl")]]) diff --git a/app/handlers/basic.py b/app/handlers/basic.py new file mode 100644 index 0000000000000000000000000000000000000000..392bd6ceb758da16edd94635e637252447fff706 --- /dev/null +++ b/app/handlers/basic.py @@ -0,0 +1,201 @@ +"""/start /help /cancel /export /userbot, plus the routers for free text and inline-button presses (/import is in backup.py).""" +from __future__ import annotations + +import io +import json +import logging + +from telethon import events + +from ..common import Ctx, UserError, cmd, clear_state, discard_temp, guard, say, show +from ..picker import PAGE_CB +from ..richmsg import RICH_HELP, RICH_HELP_HTML +from ..richtext import CHEAT_SHEET +from ..tgutil import esc + +log = logging.getLogger(__name__) + +HELP = ( + "Channel Post Bot\n\n" + "Posts\n" + "/new - create a post (text or media, with buttons)\n" + "/posts - your posts and drafts: edit text, caption, media and buttons, or delete them - a published post is deleted in the channel and in My posts (a button post also has “Mass replace links”)\n" + "/autopost 114 20 - post “Episodes 01 to 20”, “21 to 40” ... up to 114, each with a download button, then fill in the links\n" + "/formatting - bold, italic, links, quotes ...: Telegram's own formatting is kept, or type HTML / Markdown instead\n" + "/rich - rich messages: headings, lists, tables, expandable sections, math, maps, pictures, buttons ... typed as HTML / Markdown, or sent as a Telegram rich message\n" + "/cancel - stop what you're doing\n\n" + "Channels\n" + "/addchannel - register a channel (the bot must be an admin there)\n" + "/channels - list your channels, or take one out (the bot asks whether its saved posts in My posts are deleted too)\n\n" + "Owner tools\n" + "/broadcast [time] - send one message to all channels; with a time (50m, 1h, 5d) it is deleted again from all channels and My posts afterwards\n" + "/replace - reply to a new media message to replace that post's media and caption (where Telegram refuses the bot, the userbot does it)\n" + "/swap @old @new - swap the username inside t.me links (button links and hyperlinks) in all channels\n" + "/handleswap @old @new - change the username @old written in posts (text, captions, button names) to @new in all channels; links stay\n" + "/undo - undo the last /swap or /handleswap\n" + "/repost @old @new - copy every post of a channel in order (links swapped, replies, pins and links between posts kept), then delete the old posts\n" + "/shift @source @destination [from_id] [to_id] [-c] [-all] [--no-media] - copy posts from one channel into another (buttons kept, listed in My posts); " + "a channel Telegram restricts (copyright strike) is copied from My posts; " + "-c: links to the source's posts in all your channels are changed to the copies; -all: the destination also gets the source's name, description and photo; " + "--no-media: no files, only the text and buttons\n" + "/sync - compare every channel with My posts right now (posts deleted, edited or added by others, the older posts from before the bot was added; service messages are deleted)\n" + "/userbot - status of the helper account that, by itself and without asking, deletes and edits the posts the bot is not allowed to\n" + "/export - download a JSON backup of your channels and posts\n" + "/import - put a backup made by /export back (only adds: nothing that exists is changed or deleted)" + "\n/admins - list admins (owner)\n/addadmin 123456789 - add an admin (owner)\n/removeadmin 123456789 - remove an admin (owner)" +) + + +def register(ctx: Ctx) -> None: + client, db = ctx.client, ctx.db + + @client.on(cmd("admins")) + @guard(ctx, owner=True) + async def h_admins(event): + ids = sorted(ctx.admins | set(ctx.cfg.admins)) + await say(event, "Admins: " + (", ".join(map(str, ids)) if ids else "none")) + + @client.on(cmd("addadmin")) + @guard(ctx, owner=True) + async def h_addadmin(event): + parts = (event.raw_text or "").split() + if len(parts) != 2 or not parts[1].isdigit() or int(parts[1]) <= 0: + raise UserError("Use /addadmin followed by a numeric Telegram user ID.") + uid = int(parts[1]) + if ctx.cfg.is_owner(uid): + raise UserError("That user is already an owner.") + if not await db.add_admin(uid): + await say(event, f"{uid} is already an admin.") + return + ctx.admins.add(uid) + await say(event, f"Added {uid} as an admin.") + + @client.on(cmd("removeadmin")) + @guard(ctx, owner=True) + async def h_removeadmin(event): + parts = (event.raw_text or "").split() + if len(parts) != 2 or not parts[1].isdigit() or int(parts[1]) <= 0: + raise UserError("Use /removeadmin followed by a numeric Telegram user ID.") + uid = int(parts[1]) + if not await db.remove_admin(uid): + await say(event, f"{uid} is not an admin.") + return + ctx.admins.discard(uid) + await say(event, f"Removed {uid} as an admin.") + + @client.on(cmd("start")) + @client.on(cmd("help")) + @guard(ctx) + async def h_help(event): + await say(event, HELP) + + @client.on(cmd("formatting")) + @guard(ctx) + async def h_formatting(event): + await say(event, CHEAT_SHEET) + + @client.on(cmd("rich")) + @guard(ctx) + async def h_rich(event): + await say(event, RICH_HELP) + await say(event, RICH_HELP_HTML) + + @client.on(cmd("cancel")) + @guard(ctx) + async def h_cancel(event): + await discard_temp(ctx, event.sender_id) + clear_state(ctx, event.sender_id) + await say(event, "Cancelled.") + + @client.on(cmd("export")) + @guard(ctx, owner=True) + async def h_export(event): + data = await db.export_all() + buf = io.BytesIO(json.dumps(data, ensure_ascii=False, indent=1).encode("utf-8")) + buf.name = "channel-posts-export.json" + await event.respond( + f"📦 Backup: {len(data['channels'])} channel(s), {len(data['posts'])} post(s). " + "To put it back (on this bot or a new one), send /import and then this file.", + file=buf, + ) + + @client.on(cmd("userbot")) + @guard(ctx, owner=True) + async def h_userbot(event): + ub = ctx.userbot + if ub is None or not ub.enabled: + await say( + event, + "🤖 Userbot: not set up.\n" + "The bot does its work itself first. If Telegram refuses - deleting posts older than 48 hours, or " + "editing a post that belongs to another bot (/replace, text and caption edits) - a helper account, " + "the userbot, takes over by itself, without asking you each time: it joins the channel through an " + "invite link the bot makes, the bot gives it the “Delete messages” or “Edit messages of others” right " + "if it has the “Add new admins” right, and gives the rights back afterwards.\n\n" + "To set it up: on your own computer run python make_userbot_session.py with a " + "separate Telegram account, and put the printed text into the bot's secrets as " + "USERBOT_SESSION. Then send /start to this bot from that account (new media reaches the " + "userbot through its chat with the bot - that is what makes a replace quick). See the README.", + ) + return + if not ub.ready: + await ub.connect() + kept = "stays an admin" if ub.keep_admin else "is made admin only while it deletes or edits" + await say( + event, + f"🤖 Userbot: {esc(ub.describe())}\nIt {kept} (USERBOT_KEEP_ADMIN).\n" + "It must have started this bot (/start from that account): new media for an edit goes through its chat " + "with the bot, which is what makes a big file as quick as a small one.", + ) + + @client.on( + events.NewMessage(incoming=True, func=lambda e: e.is_private and not (e.raw_text or "").startswith("/")) + ) + @guard(ctx) + async def h_free_text(event): + st = ctx.state.get(event.sender_id) + if not st: + await say(event, "Use /new to create a post or /posts to manage your posts. /help lists everything.") + return + fn = ctx.text_handlers.get(st["mode"]) + if fn is None: + clear_state(ctx, event.sender_id) + await say(event, "That step is no longer active. Start again with /new.") + return + await fn(event, st) + + @client.on(events.CallbackQuery()) + @guard(ctx) + async def h_callback(event): + try: + await event.answer() # stop the loading spinner right away + except Exception: + pass + data = event.data.decode("utf-8", "replace") + prefix, *parts = data.split(":") + fn = ctx.callbacks.get(prefix) + if fn is None: + await event.respond("This button is no longer active. Use /new or /posts.") + return + await fn(event, parts) + + async def cb_noop(event, parts): + await event.answer() + + async def cb_cancel(event, parts): + uid = event.sender_id + await discard_temp(ctx, uid) + clear_state(ctx, uid) + await show(event, "Cancelled.") + + async def cb_channel_page(event, parts): + """◀ ▶ under a channel chooser: draw the same chooser again on another page.""" + kind, arg, page = parts[0], parts[1], int(parts[2]) + draw = ctx.pickers.get(kind) + if draw is None: + raise UserError("This list is no longer active. Start the command again.") + await draw(event, arg, page) + + ctx.callbacks["noop"] = cb_noop + ctx.callbacks["cx"] = cb_cancel + ctx.callbacks[PAGE_CB] = cb_channel_page diff --git a/app/handlers/broadcast.py b/app/handlers/broadcast.py new file mode 100644 index 0000000000000000000000000000000000000000..1187bb211ad892c092412b38ea440622f5d81a9d --- /dev/null +++ b/app/handlers/broadcast.py @@ -0,0 +1,268 @@ +"""/broadcast [time] (also spelled /boardcast): one message to every connected channel. Owner only. + +With a time (50m, 1h, 5d) the message is deleted again from all the channels - and from My posts - when the time is up; +without one it stays. +""" +from __future__ import annotations + +import asyncio +import logging +import secrets +import time +from dataclasses import dataclass, field +from datetime import datetime, timedelta +from types import SimpleNamespace +from typing import Optional + +from telethon import Button, errors + +from ..buttons import parse_buttons_text +from ..common import ( + Ctx, + UserError, + clear_state, + cmd, + discard_temp, + edit_callback_message, + guard, + on_cb, + on_text, + purge_pending, + require_owner, + say, + send_post, + set_state, + show, +) +from ..db import utcnow +from ..expiry import human, parse_duration, stamp +from ..richmsg import block_count, block_labels, is_block_invalid, refused_blocks, rich_of +from ..tgutil import esc, explain_rpc, flood_retry, peer_of +from ..ui import CANCEL +from .panel import markup_note, read_content + +log = logging.getLogger(__name__) + +BUTTON_HELP = ( + "➕ Buttons? Send one row per line as Button text - link " + "(several in one row: separate them with | ), or skip." +) + + +@dataclass +class BroadcastDraft: + """The message is made and previewed; the owner still has to confirm.""" + + user: int + content: dict # text, entities, media_kind, media_file_id + buttons: list + ttl: Optional[int] # seconds until it is deleted again; None = it stays + created: float = field(default_factory=time.monotonic) + + +@dataclass +class BroadcastResult: + group_id: str + delete_at: Optional[datetime] + ttl: Optional[int] = None # seconds it stays; None = for good + sent: list = field(default_factory=list) # [(channel, message id)] + failed: list = field(default_factory=list) # [(channel, reason)] + + +def shape_of(draft: BroadcastDraft) -> SimpleNamespace: + c = draft.content + return SimpleNamespace( + text=c.get("text") or "", + entities=c.get("entities") or [], + buttons=draft.buttons, + media_kind=c.get("media_kind"), + media_file_id=c.get("media_file_id"), + link_preview=False, + ) + + +async def send_broadcast(ctx: Ctx, chans: list, draft: BroadcastDraft, *, delay: float = 1.0, progress=None) -> BroadcastResult: + """Post the message in every channel, save each copy in My posts and, if it expires, schedule its deletion.""" + db = ctx.db + delete_at = utcnow() + timedelta(seconds=draft.ttl) if draft.ttl else None + res = BroadcastResult(group_id=secrets.token_hex(6), delete_at=delete_at, ttl=draft.ttl) + shape = shape_of(draft) + for n, ch in enumerate(chans, 1): + try: + sent = await flood_retry(lambda: send_post(ctx.client, peer_of(ch), shape)) + except errors.RPCError as e: + res.failed.append((ch, explain_rpc(e))) + continue + except Exception as e: + log.exception("broadcast: posting in channel %s failed", ch.id) + res.failed.append((ch, type(e).__name__)) + continue + await db.create_post( + channel_id=ch.id, + message_id=sent.id, + status="sent", + source="bot", + created_by=draft.user, + text=shape.text, + entities=shape.entities, + media_kind=shape.media_kind, + media_file_id=shape.media_file_id, + buttons=shape.buttons, + link_preview=False, + sent_at=utcnow(), + ) + res.sent.append((ch, sent.id)) + if delete_at is not None: # saved at once, so a restart in the middle loses nothing + await db.schedule_deletes( + [dict(channel_id=ch.id, message_id=sent.id, delete_at=delete_at, group_id=res.group_id, created_by=draft.user)] + ) + if ctx.expirer is not None: + ctx.expirer.notify(delete_at) + if progress: + await progress(n) + if n < len(chans): + await asyncio.sleep(delay) + return res + + +def report(res: BroadcastResult, total: int) -> str: + lines = [f"📣 Broadcast sent to {len(res.sent)} of {total} channel(s)"] + lines += [f"✅ {esc(ch.title)}" for ch, _ in res.sent] + lines += [f"❌ {esc(ch.title)} - {esc(why)}" for ch, why in res.failed] + if res.delete_at is not None and res.sent: + lines += ["", f"🕒 It is deleted from these channels and from My posts in {human(res.ttl)} ({stamp(res.delete_at)})."] + elif res.sent: + lines += ["", "📌 No time was given, so it stays in the channels."] + return "\n".join(lines) + + +def register(ctx: Ctx) -> None: + client, db, cfg = ctx.client, ctx.db, ctx.cfg + + @client.on(cmd("broadcast", args=True)) + @client.on(cmd("boardcast", args=True)) + @guard(ctx, owner=True) + async def h_broadcast(event): + purge_pending(ctx) + raw = (event.pattern_match.group(1) or "").strip() + ttl = None + if raw: + try: + ttl = parse_duration(raw) + except ValueError as e: + raise UserError(str(e)) + chans = await db.list_channels() + if not chans: + raise UserError("No channels yet. Register one with /addchannel first.") + uid = event.sender_id + await discard_temp(ctx, uid) + set_state(ctx, uid, "bc_content", ttl=ttl) + when = ( + f"⏳ It is deleted from all channels - and from My posts - {human(ttl)} after it is sent." + if ttl + else "📌 No time given: it stays in the channels for good. (For a timed one use e.g. /broadcast 1h.)" + ) + await say( + event, + f"📣 Broadcast to {len(chans)} channel(s)\n{when}\n\n" + "✍️ Send the message now. Text, or a photo / video / GIF / file with a caption. Formatting is kept " + "(or type HTML / Markdown - /formatting shows how; rich blocks: /rich).", + CANCEL, + ) + + @on_text(ctx, "bc_content") + async def h_content(event, st): + m = event.message + if m.grouped_id and st.get("group") == m.grouped_id: + return # the other items of an album: only the first one is used + if m.grouped_id: + st["group"] = m.grouped_id + content = await read_content(ctx, event) + set_state(ctx, event.sender_id, "bc_buttons", ttl=st["ttl"], content=content) + await say(event, markup_note(content.how) + BUTTON_HELP, [[Button.inline("⏭ No buttons", "brs")], CANCEL[0]]) + + async def confirm_step(event, st, rows: list) -> None: + uid = event.sender_id + draft = BroadcastDraft(user=uid, content=st["content"], buttons=rows, ttl=st["ttl"]) + chans = await db.list_channels() + if not chans: + clear_state(ctx, uid) + raise UserError("No channels any more. Register one with /addchannel first.") + shape = shape_of(draft) + try: + await send_post(client, await event.get_input_chat(), shape) # the preview + except errors.RPCError as e: + rich, which = rich_of(shape), "" + if rich is not None and rich.fmt == "blocks" and is_block_invalid(e): # name the blocks Telegram won't take + bad = await refused_blocks(client, await event.get_input_chat(), rich) + if bad: + which = f"\nIt won't take these blocks (of {block_count(rich)}): {block_labels(rich, bad)}." + raise UserError("❌ " + explain_rpc(e) + which + "\nThe message can't be sent like this - send it again.") + token = secrets.token_hex(4) + ctx.pending[token] = draft + clear_state(ctx, uid) + names = "\n".join(f"• {esc(c.title)}" for c in chans[:15]) + (f"\n• … and {len(chans) - 15} more" if len(chans) > 15 else "") + when = ( + f"⏳ Deleted again {human(draft.ttl)} after sending." + if draft.ttl + else "📌 Permanent (no time given)." + ) + await say( + event, + f"👆 That is the message. Send it to {len(chans)} channel(s)?\n{names}\n\n{when}", + [[Button.inline("📣 Send to all channels", f"brc:{token}")], [Button.inline("✖️ Cancel", f"brn:{token}")]], + ) + + @on_text(ctx, "bc_buttons") + async def h_buttons(event, st): + if event.message.grouped_id: + return + try: + rows = parse_buttons_text(event.raw_text or "") + except ValueError as e: + raise UserError(f"❌ {e}\n\nTry again, or tap “No buttons”.") + if not rows: + raise UserError("Send at least one button as “Text - link”, or tap “No buttons”.") + await confirm_step(event, st, rows) + + @on_cb(ctx, "brs") + async def cb_no_buttons(event, parts): + require_owner(ctx, event) + st = ctx.state.get(event.sender_id) + if not st or st.get("mode") != "bc_buttons": + raise UserError("That step is no longer active. Start again with /broadcast.") + await confirm_step(event, st, []) + + @on_cb(ctx, "brn") + async def cb_cancel(event, parts): + require_owner(ctx, event) + ctx.pending.pop(parts[0], None) + await show(event, "Cancelled - nothing was sent.") + + @on_cb(ctx, "brc") + async def cb_send(event, parts): + require_owner(ctx, event) + token = parts[0] + draft = ctx.pending.get(token) + if not isinstance(draft, BroadcastDraft) or draft.user != event.sender_id: + raise UserError("That broadcast has expired. Start again with /broadcast.") + chans = await db.list_channels() + if not chans: + raise UserError("No channels any more. Register one with /addchannel first.") + if ctx.lock.locked(): + raise UserError("Another long job (replace / repost / shift) is still running. Try again in a minute.") + ctx.pending.pop(token, None) # a second press can't send it twice + last = [0.0] + + async def prog(n): + if time.monotonic() - last[0] < 3: + return + last[0] = time.monotonic() + try: + await edit_callback_message(event, f"📣 Sending… {n} of {len(chans)} channel(s)") + except Exception: + pass + + async with ctx.lock: + res = await send_broadcast(ctx, chans, draft, delay=cfg.edit_delay, progress=prog) + await edit_callback_message(event, report(res, len(chans))) diff --git a/app/handlers/channels.py b/app/handlers/channels.py new file mode 100644 index 0000000000000000000000000000000000000000..627a51e45f30d6d483ed0e0af9f33e95a98bb708 --- /dev/null +++ b/app/handlers/channels.py @@ -0,0 +1,182 @@ +"""Channel registration: /addchannel, /channels.""" +from __future__ import annotations + +import logging +import re + +from telethon import Button, events, types + +from .. import picker +from ..channelref import parse_channel_ref +from ..common import Ctx, UserError, clear_state, cmd, guard, on_cb, on_text, require_owner, say, set_state, show +from ..tgutil import esc, get_rights +from ..ui import CANCEL + +log = logging.getLogger(__name__) + +ADD_HELP = ( + "📢 Add a channel\n" + "1. Make the bot an admin of the channel with the rights Post messages, Edit messages of others " + "and Delete messages.\n" + "2. Then forward any post from that channel to me, or send its @username (public channels).\n\n" + "Tip for private channels: if forwarding doesn't work, post something in the channel while the bot is " + "running, then forward that post." +) +NEEDS_ACCESS = ( + "I can see the channel, but Telegram hasn't given me its access details yet. Post something in the " + "channel while the bot is running (or send the @username if it's public), then forward a post again." +) + + +def rights_line(r) -> str: + if r is None: + return "rights unknown" + if not r.admin: + return "⚠️ not an admin there" + ok = lambda v: "✅" if v else "❌" # noqa: E731 + return f"post {ok(r.post)} · edit others' posts {ok(r.edit)} · delete {ok(r.delete)}" + + +def register(ctx: Ctx) -> None: + client, db = ctx.client, ctx.db + + # remember channels whose full details (access hash) we have seen in updates + @client.on(events.NewMessage(func=lambda e: bool(e.is_channel) and not e.is_group)) + async def watch_channels(event): + try: + chat = await event.get_chat() + if isinstance(chat, types.Channel) and chat.access_hash and not getattr(chat, "min", False): + prev = ctx.seen_channels.get(chat.id) + ctx.seen_channels[chat.id] = chat + if prev is None or prev.access_hash != chat.access_hash: + await db.touch_channel_hash(chat.id, chat.access_hash) + except Exception: # pragma: no cover + log.debug("channel watcher failed", exc_info=True) + + @client.on(cmd("addchannel")) + @guard(ctx, owner=True) + async def h_addchannel(event): + set_state(ctx, event.sender_id, "add_channel") + await say(event, ADD_HELP, CANCEL) + + @on_text(ctx, "add_channel") + async def h_add_channel(event, st): + m = event.message + ent = None + fwd = m.forward + if fwd is not None and isinstance(getattr(fwd, "chat", None), types.Channel): + ent = fwd.chat + if getattr(ent, "min", False) or not getattr(ent, "access_hash", None): + ent = ctx.seen_channels.get(ent.id, ent) + else: + ref = parse_channel_ref(m.raw_text or "") + if ref is None: + raise UserError("Forward a post from the channel to me, or send its @username.") + if isinstance(ref, int): + ent = ctx.seen_channels.get(ref) + if ent is None: + try: + ent = await client.get_entity(ref if isinstance(ref, str) else types.PeerChannel(ref)) + except Exception: + ent = None + if not isinstance(ent, types.Channel): + raise UserError("I couldn't find that channel.\n\n" + re.sub(r"<[^>]+>", "", ADD_HELP)) + if not ent.broadcast: + raise UserError("That is a group, not a channel. Only channels are supported.") + if not ent.access_hash or getattr(ent, "min", False): + raise UserError(NEEDS_ACCESS) + rights = await get_rights(client, ent) + if rights is not None and not rights.admin: + raise UserError("The bot is not an admin of that channel yet. Add it as an admin, then try again.") + await db.save_channel(ent.id, ent.access_hash, ent.title or "", ent.username, event.sender_id) + clear_state(ctx, event.sender_id) + warn = "" + if rights is not None and not (rights.post and rights.edit and rights.delete): + warn = "\n\n⚠️ Missing rights: give the bot Post, Edit messages of others and Delete so everything works." + await say( + event, + f"✅ Added {esc(ent.title or '')}\n{rights_line(rights)}{warn}\n\nCreate a post with /new.", + ) + + async def show_channels(event, arg: str = "", page: int = 0) -> None: + """The list of channels; the owner's number buttons choose one to remove.""" + chans = await db.list_channels() + if not chans: + raise UserError("No channels yet. Use /addchannel.") + owner = ctx.cfg.is_owner(event.sender_id) + text, kb = picker.render( + chans, + page, + head="📢 Your channels", + kind="ch", + choose=(lambda c: f"chd:{c.id}") if owner else None, + with_username=True, + hint="To take a channel out of the bot, tap its number.", + ) + await show(event, text, kb or None) + + ctx.pickers["ch"] = show_channels + + @client.on(cmd("channels")) + @guard(ctx) + async def h_channels(event): + await show_channels(event) + + @on_cb(ctx, "chd") + async def cb_remove_channel(event, parts): + """A number was tapped: ask what becomes of the channel's saved posts before it is taken out of the bot.""" + require_owner(ctx, event) + ch = await db.get_channel(int(parts[0])) + if ch is None or not ch.active: + await show_channels(event) + return + back = Button.inline("🔙 Back", f"{picker.PAGE_CB}:ch::0") + n = await db.count_channel_posts(ch.id) + if not n: # nothing saved: nothing to ask about + await show( + event, + f"➖ Take {esc(ch.title)} out of the bot?\nIt has no saved posts. You can add it again with /addchannel.", + [[Button.inline("✅ Yes, remove it", f"chy:{ch.id}:0"), back]], + ) + return + await show( + event, + f"➖ Take {esc(ch.title)} out of the bot.\n\n" + f"Do you also want to delete its saved posts - the {n} post(s) My posts holds for this channel? " + "Nothing is deleted in the channel itself.", + [ + [Button.inline("🗑 Yes, delete them too", f"chy:{ch.id}:1"), Button.inline("📦 No, keep them", f"chy:{ch.id}:0")], + [back], + ], + ) + + @on_cb(ctx, "chy") + async def cb_remove_channel_yes(event, parts): + """chy::1 removes the channel and deletes its saved posts, chy::0 (or an old button without the + second part) removes only the channel and keeps them.""" + require_owner(ctx, event) + cid = int(parts[0]) + wipe = len(parts) > 1 and parts[1] == "1" + ch = await db.get_channel(cid) + name = f"{esc(ch.title)}" if ch is not None else "The channel" + await db.set_channel_active(cid, False) + gone = 0 + sy = ctx.syncer + if sy is not None: + sy.forget_cache() + if wipe: + await show(event, f"⏳ Deleting the saved posts of {name}…") + # no look at the channel may be saving posts while they are deleted (it would bring some back) + if sy is not None: + async with sy.exclusive(): + gone = await db.delete_channel_data(cid) + else: + gone = await db.delete_channel_data(cid) + ctx.sync_ignore.difference_update({k for k in ctx.sync_ignore if k[0] == cid}) + text = ( + f"✅ {name} was removed from the bot, and its {gone} saved post(s) were deleted from My posts. Nothing was deleted " + "in the channel. If you add it again with /addchannel, its posts are read in again." + ) + else: + text = f"✅ {name} was removed from the bot. Its saved posts are kept; add it again with /addchannel and they are there again." + await show(event, text) diff --git a/app/handlers/checkbtn.py b/app/handlers/checkbtn.py new file mode 100644 index 0000000000000000000000000000000000000000..1e61d50870f8fe609a3d0f84bdc815f8efdd83b5 --- /dev/null +++ b/app/handlers/checkbtn.py @@ -0,0 +1,115 @@ +"""Check buttons (owner only): compare the buttons saved in the bot with what a channel really shows, and repair.""" +from __future__ import annotations + +import logging +import time + +from telethon import Button, errors + +from ..buttons_sync import fix_buttons, scan_buttons +from ..common import Ctx, UserError, on_cb, require_owner, show +from ..tgutil import esc + +log = logging.getLogger(__name__) +SAMPLE = 12 + + +def register(ctx: Ctx) -> None: + client, db, cfg = ctx.client, ctx.db, ctx.cfg + + async def load(parts): + ch = await db.get_channel(int(parts[0])) + if ch is None: + raise UserError("That channel is not registered.") + if ctx.lock.locked(): + raise UserError("Another long job (replace / repost) is still running.") + return ch + + def throttled(event, make_text, every: float = 3.0): + last = [0.0] + + async def upd(obj, force: bool = False) -> None: + now = time.monotonic() + if not force and now - last[0] < every: + return + last[0] = now + try: + await show(event, make_text(obj)) + except errors.MessageNotModifiedError: + pass + except Exception: + log.debug("progress update failed", exc_info=True) + + return upd + + @on_cb(ctx, "pk") + async def cb_check(event, parts): + require_owner(ctx, event) + ch = await load(parts) + title = esc(ch.title) + async with ctx.lock: + await show(event, f"🔧 Checking the buttons of {title}…") + posts = await db.sent_posts(ch.id) + scan = await scan_buttons( + client, ch, posts, progress=throttled(event, lambda s: f"🔧 Checking {title}: {s.fine + len(s.bad) + len(s.gone)}/{s.total}…") + ) + lines = [f"🔧 {title} - checked {scan.total} post(s) that have link buttons."] + kb = [] + if not scan.total: + lines.append("None of the saved posts has link buttons, so there is nothing to check.") + else: + lines.append(f"✅ {scan.fine} show their buttons correctly.") + if scan.bad: + ids = ", ".join(f"#{p.message_id}" for p, _, _ in scan.bad[:SAMPLE]) + more = "…" if len(scan.bad) > SAMPLE else "" + lines.append( + f"⚠️ {len(scan.bad)} are saved with buttons here, but the channel shows them without those buttons " + f"(or with different links): {ids}{more}" + ) + kb.append([Button.inline(f"🔧 Fix {len(scan.bad)} post(s)", f"pkf:{ch.id}")]) + elif scan.total: + lines.append("Everything matches.") + if scan.gone: + ids = ", ".join(f"#{p.message_id}" for p in scan.gone[:SAMPLE]) + lines.append( + f"ℹ️ {len(scan.gone)} saved post(s) no longer exist in the channel ({ids}{'…' if len(scan.gone) > SAMPLE else ''})." + ) + kb.append([Button.inline("🔙 Back", f"pc:{ch.id}:0")]) + await show(event, "\n".join(lines), kb) + + @on_cb(ctx, "pkf") + async def cb_fix(event, parts): + require_owner(ctx, event) + ch = await load(parts) + title = esc(ch.title) + async with ctx.lock: + await show(event, f"🔧 Looking again at {title}…") + scan = await scan_buttons(client, ch, await db.sent_posts(ch.id)) + if not scan.bad: + res = None + else: + total = len(scan.bad) + res = await fix_buttons( + client, + ch, + scan.bad, + delay=cfg.edit_delay, + progress=throttled(event, lambda r: f"🔧 Fixing {title}: {r.fixed + r.already}/{total}…"), + ) + if res is None: + text = f"✅ {title}: all buttons match now - nothing to fix." + else: + lines = [f"🔧 {title} - put the saved buttons back on {res.fixed} post(s)."] + if res.nudged: + lines.append(f"{res.nudged} of them needed a second edit before Telegram showed the buttons.") + if res.already: + lines.append(f"{res.already} were already fine when I got to them.") + if res.gone: + lines.append(f"{res.gone} no longer exist in the channel.") + if res.failed: + sample = ", ".join(f"#{m} {esc(n)}" for m, n in res.failed[:8]) + lines.append(f"⚠️ {len(res.failed)} failed ({sample}{'…' if len(res.failed) > 8 else ''}).") + if res.aborted: + lines.append(f"Stopped early: Telegram refused {esc(res.aborted)} several times in a row.") + text = "\n".join(lines) + await show(event, text, [[Button.inline("🔧 Check again", f"pk:{ch.id}"), Button.inline("🔙 Back", f"pc:{ch.id}:0")]]) diff --git a/app/handlers/create.py b/app/handlers/create.py new file mode 100644 index 0000000000000000000000000000000000000000..dca0c790590ff0f29d001588596760443a9c5c44 --- /dev/null +++ b/app/handlers/create.py @@ -0,0 +1,191 @@ +"""/new: create a post, with the episode-range auto-suggestion.""" +from __future__ import annotations + +import logging + +from telethon import Button + +from .. import picker +from ..buttons import norm_url, parse_buttons_text, set_field +from ..common import Ctx, UserError, clear_state, cmd, discard_temp, guard, on_cb, on_text, say, set_state, show +from ..suggest import make_suggestion +from ..tgutil import esc, short +from ..ui import CANCEL, KIND_NAME +from .panel import markup_note, read_content, show_panel + +log = logging.getLogger(__name__) + +BUTTON_HELP = ( + "➕ Now the buttons\n" + "Send one row per line as Button text - link.\n" + "Several buttons in one row: separate them with | .\n\n" + "Example:\nDownload Episodes 01 to 20 - https://t.me/yourbot?start=abc\n\n" + "Or send /skip to post without buttons." +) + + +def register(ctx: Ctx) -> None: + client, db = ctx.client, ctx.db + + async def ask_content(event, cid: int) -> None: + set_state(ctx, event.sender_id, "new_content", cid=cid) + await show( + event, + "✍️ Send the post now.\nText, or a photo / video / GIF / file with a caption. " + "Formatting (bold, links, spoilers...) is kept. No Telegram editor at hand? Type HTML or Markdown - /formatting shows how; " + "headings, lists, tables, math and the other rich blocks: /rich.", + CANCEL, + ) + + async def start_for_channel(event, cid: int) -> None: + ch = await db.get_channel(cid) + if ch is None: + raise UserError("That channel is not registered. Use /addchannel.") + sug = await make_suggestion(db, cid) + if sug is None: + await ask_content(event, cid) + return + lines = [ + f"💡 Suggestion for {esc(ch.title)}", + f"Your last button post: {esc(sug.prev_label)}", + "The next one would be:", + ] + if (sug.text or "").strip(): + lines.append(f"• Message: {esc(short(sug.text, 120))}") + lines.append(f"• Button: {esc(sug.new_label)}") + if sug.media_kind: + lines.append(f"• Media: same {KIND_NAME.get(sug.media_kind, 'file')} as that post (you can change it before publishing)") + lines.append("\nUse it and I'll only ask for the button link.") + kb = [ + [Button.inline("✅ Use suggestion", f"ns:{cid}"), Button.inline("✏️ Customize", f"nn:{cid}")], + CANCEL[0], + ] + await show(event, "\n".join(lines), kb) + + async def ask_link(event, post, pos) -> None: + r, c = pos + label = post.buttons[r][c]["t"] + await say( + event, + f"🔗 Send the link for the button {esc(label)}\n" + "(for example https://t.me/yourbot?start=abc)", + CANCEL, + ) + + @client.on(cmd("new")) + @guard(ctx) + async def h_new(event): + uid = event.sender_id + await discard_temp(ctx, uid) + clear_state(ctx, uid) + chans = await db.list_channels() + if not chans: + raise UserError("No channels yet. Register one with /addchannel first.") + if len(chans) == 1: + await start_for_channel(event, chans[0].id) + return + await show_picker(event, "", 0) + + async def show_picker(event, arg: str, page: int) -> None: + chans = await db.list_channels() + if not chans: + raise UserError("No channels yet. Register one with /addchannel first.") + text, kb = picker.render( + chans, page, head="📢 Which channel is this post for?", kind="nc", choose=lambda c: f"nc:{c.id}", extra_rows=CANCEL + ) + await show(event, text, kb) + + ctx.pickers["nc"] = show_picker + + @on_cb(ctx, "nc") + async def cb_channel(event, parts): + await discard_temp(ctx, event.sender_id) + await start_for_channel(event, int(parts[0])) + + @on_cb(ctx, "nn") + async def cb_customize(event, parts): + await ask_content(event, int(parts[0])) + + @on_cb(ctx, "ns") + async def cb_use_suggestion(event, parts): + uid, cid = event.sender_id, int(parts[0]) + sug = await make_suggestion(db, cid) + if sug is None: + raise UserError("There is nothing to suggest any more - send the post yourself with /new.") + await discard_temp(ctx, uid) + post = await db.create_post( + channel_id=cid, + created_by=uid, + status="draft", + source="bot", + text=sug.text, + entities=sug.entities, + buttons=sug.buttons, + media_kind=sug.media_kind, + media_file_id=sug.media_file_id, + link_preview=False, + ) + set_state(ctx, uid, "new_link", pid=post.id, pending=list(sug.pending), temp=True) + await show(event, f"✅ Using the suggestion: {esc(sug.new_label)}") + await ask_link(event, post, sug.pending[0]) + + @on_text(ctx, "new_link") + async def h_new_link(event, st): + url = norm_url(event.raw_text or "") + if not url: + raise UserError("That doesn't look like a link. Send something like https://t.me/yourbot?start=abc") + post = await db.get_post(st["pid"]) + if post is None: + clear_state(ctx, event.sender_id) + raise UserError("That draft is gone. Start again with /new.") + r, c = st["pending"][0] + post = await db.update_post(post.id, buttons=set_field(post.buttons, r, c, u=url)) + st["pending"] = st["pending"][1:] + if st["pending"]: + await ask_link(event, post, st["pending"][0]) + return + clear_state(ctx, event.sender_id) + await show_panel(ctx, event, post.id, note="✅ Ready. Preview it, or tap Publish.", new=True) + + @on_text(ctx, "new_content") + async def h_new_content(event, st): + m = event.message + if m.grouped_id and st.get("group") == m.grouped_id: + return # the other items of an album: only the first one is used + if m.grouped_id: + st["group"] = m.grouped_id + content = await read_content(ctx, event) + post = await db.create_post( + channel_id=st["cid"], + created_by=event.sender_id, + status="draft", + source="bot", + buttons=[], + link_preview=False, + **content, + ) + set_state(ctx, event.sender_id, "new_buttons", pid=post.id, temp=True) + await say(event, markup_note(content.how) + BUTTON_HELP, CANCEL) + + @on_text(ctx, "new_buttons") + async def h_new_buttons(event, st): + if event.message.grouped_id: + return + try: + rows = parse_buttons_text(event.raw_text or "") + except ValueError as e: + raise UserError(f"❌ {e}\n\nTry again, or send /skip.") + if not rows: + raise UserError("Send at least one button as “Text - link”, or /skip.") + await db.update_post(st["pid"], buttons=rows) + clear_state(ctx, event.sender_id) + await show_panel(ctx, event, st["pid"], note="✅ Ready. Preview it, or tap Publish.", new=True) + + @client.on(cmd("skip")) + @guard(ctx) + async def h_skip(event): + st = ctx.state.get(event.sender_id) + if not st or st["mode"] != "new_buttons": + raise UserError("There is nothing to skip right now.") + clear_state(ctx, event.sender_id) + await show_panel(ctx, event, st["pid"], note="✅ Ready (no buttons). Preview it, or tap Publish.", new=True) diff --git a/app/handlers/masslinks.py b/app/handlers/masslinks.py new file mode 100644 index 0000000000000000000000000000000000000000..b7a870742e27d5cfb9a036ea805b79aa621f241f --- /dev/null +++ b/app/handlers/masslinks.py @@ -0,0 +1,159 @@ +"""New links, one button after the other. + +* "Mass replace links" in the panel of a published button post: the bot asks for a new link for that post's button and, + after each answer, for the next button post of the channel (posts without a link button are skipped). +* /autopost uses the same steps to ask for the real link of every button it posted. + +The position in the list lives in the user's state; each answer changes the button in the channel at once. +""" +from __future__ import annotations + +import logging + +from telethon import Button, errors + +from ..buttons import link_positions, norm_url, set_field +from ..common import Ctx, UserError, clear_state, is_cb, on_cb, on_text, say, set_state, show +from ..tgutil import build_markup, edit_raw, esc, explain_rpc, flood_retry, peer_of, post_link, short +from .panel import load_post + +log = logging.getLogger(__name__) + +MODE = "link_queue" +HEADINGS = {"mass": "🔗 Mass replace links", "auto": "🔗 Links for the new posts"} + + +async def set_link(ctx: Ctx, post, ch, r: int, c: int, url: str): + """Point button (r, c) of a published post at `url`: the buttons of the channel message change (only the buttons, + the text stays as it is), then the saved post follows.""" + rows = set_field(post.buttons, r, c, u=url) + if post.status == "sent" and post.message_id: + try: + await flood_retry(lambda: edit_raw(ctx.client, peer_of(ch), post.message_id, markup=build_markup(rows))) + except errors.MessageNotModifiedError: + pass # it already had that link + except errors.RPCError as e: + raise UserError("❌ " + explain_rpc(e) + "\nThe link of this button was NOT changed.") + return await ctx.db.update_post(post.id, buttons=rows) + + +def mass_items(posts) -> list: + """[(post id, row, column)] of every link button in `posts`, in the order given.""" + return [[p.id, r, c] for p in posts for r, c in link_positions(p.buttons)] + + +async def current_target(ctx: Ctx, st: dict): + """(post, channel, row, column) the list is at, moving past buttons that are gone; None when the list is finished.""" + while st["i"] < len(st["items"]): + pid, r, c = st["items"][st["i"]] + post = await ctx.db.get_post(pid) + if post is not None and post.status == "sent" and post.message_id and (r, c) in link_positions(post.buttons): + ch = await ctx.db.get_channel(post.channel_id) + if ch is not None: + return post, ch, r, c + st["i"] += 1 + st["gone"] += 1 + return None + + +def summary(st: dict, stopped: bool) -> str: + left = max(0, len(st["items"]) - st["i"]) if stopped else 0 + bits = [f"{st['done']} link(s) replaced"] + if st["skipped"]: + bits.append(f"{st['skipped']} skipped") + if st["gone"]: + bits.append(f"{st['gone']} button(s) no longer there") + if left: + bits.append(f"{left} not asked") + return ("Stopped. " if stopped else "✅ All done. ") + ", ".join(bits) + "." + + +def prompt_for(st: dict, post, ch, r: int, c: int) -> str: + total = len(st["items"]) + b = post.buttons[r][c] + lines = [f"{HEADINGS[st['kind']]} · {esc(ch.title)} ({st['i'] + 1} of {total})", ""] + where = f"Post #{post.id}" + if post.message_id: + where = f'Post #{post.id}' + several = len(link_positions(post.buttons)) + label = f"“{esc(short(b.get('t') or '', 60))}”" + lines.append(f"{where} · button {label}" + (f" (button {r + 1}.{c + 1} of {several} links)" if several > 1 else "")) + lines.append(f"Now: {esc(b.get('u') or '')}") + lines += ["", "🔗 Send the new link for this button."] + return "\n".join(lines) + + +async def ask(ctx: Ctx, event, st: dict, lead: str = "", *, new: bool = True) -> None: + """Ask for the next link, or finish. `lead` (what just happened) goes in front, in the same message.""" + tgt = await current_target(ctx, st) + kb_done = [[Button.inline("📚 My posts", "pl")]] + send = say if (new or not is_cb(event)) else show + if tgt is None: + clear_state(ctx, event.sender_id) + await send(event, (lead + "\n\n" if lead else "") + summary(st, False), kb_done) + return + post, ch, r, c = tgt + kb = [[Button.inline("⏭ Skip this one", f"lqs:{st['i']}"), Button.inline("✖️ Cancel", "lqx")]] + await send(event, (lead + "\n\n" if lead else "") + prompt_for(st, post, ch, r, c), kb) + + +async def begin_queue(ctx: Ctx, event, *, kind: str, cid: int, items: list, lead: str = "", new: bool = True) -> None: + """Start asking: `items` is [(post id, row, column)] in the order the links are wanted.""" + st = set_state(ctx, event.sender_id, MODE, kind=kind, cid=cid, items=[list(i) for i in items], i=0, done=0, skipped=0, gone=0) + await ask(ctx, event, st, lead, new=new) + + +def register(ctx: Ctx) -> None: + db = ctx.db + + # ------------------------------------------------------------- the panel option + @on_cb(ctx, "mlp") + async def cb_mass_start(event, parts): + post, ch = await load_post(ctx, parts[0]) + if post.status != "sent" or not post.message_id: + raise UserError("Mass replace works on published posts only.") + if not link_positions(post.buttons): + raise UserError("This post has no button with a link.") + posts = await db.sent_posts_from(ch.id, post.message_id) + await begin_queue(ctx, event, kind="mass", cid=ch.id, items=mass_items(posts), new=False) + + # ---------------------------------------------------------------- the answers + @on_text(ctx, MODE) + async def h_link(event, st): + url = norm_url(event.raw_text or "") + if not url: + raise UserError("That doesn't look like a link. Send something like https://t.me/yourbot?start=abc") + tgt = await current_target(ctx, st) + if tgt is None: # everything this list was about has vanished meanwhile + await ask(ctx, event, st) + return + post, ch, r, c = tgt + label = post.buttons[r][c].get("t") or "" + await set_link(ctx, post, ch, r, c, url) + st["i"] += 1 + st["done"] += 1 + await ask(ctx, event, st, f"✅ {esc(short(label, 40))} now opens {esc(url)}") + + def live(event, parts): + st = ctx.state.get(event.sender_id) + if not st or st.get("mode") != MODE: + raise UserError("That list is no longer active.") + if parts and parts[0].isdigit() and int(parts[0]) != st["i"]: + raise UserError("That button belongs to an earlier step - use the newest message.") + return st + + @on_cb(ctx, "lqs") + async def cb_skip(event, parts): + st = live(event, parts) + st["i"] += 1 + st["skipped"] += 1 + await ask(ctx, event, st, "⏭ Skipped.", new=False) + + @on_cb(ctx, "lqx") + async def cb_stop(event, parts): + st = ctx.state.get(event.sender_id) + if not st or st.get("mode") != MODE: + await show(event, "Cancelled.") + return + clear_state(ctx, event.sender_id) + await show(event, summary(st, True), [[Button.inline("📚 My posts", "pl")]]) diff --git a/app/handlers/panel.py b/app/handlers/panel.py new file mode 100644 index 0000000000000000000000000000000000000000..c2059858a5811a1d6e303650023af54f85c6e681 --- /dev/null +++ b/app/handlers/panel.py @@ -0,0 +1,135 @@ +"""Helpers shared by the create and post-management handlers (not a handler module itself).""" +from __future__ import annotations + +from typing import Optional + +from telethon import types + +from ..buttons import valid +from ..common import Ctx, UserError, is_cb, say, show +from ..richmsg import Rich, RichError, check as check_rich, entry as rich_entry, plain_of, read_typed, received +from ..richtext import message_text +from ..tgutil import classify_media, pack_file_id, ser_entities, utf16_len +from ..ui import button_keyboard, button_text, panel_keyboard, panel_text + +CAPTION_MAX = 1024 +TEXT_MAX = 4096 + + +async def load_post(ctx: Ctx, pid): + post = await ctx.db.get_post(int(pid)) + if post is None: + raise UserError("That post no longer exists.") + ch = await ctx.db.get_channel(post.channel_id) + if ch is None: + raise UserError("Its channel was removed from the bot. Add it again with /addchannel.") + return post, ch + + +async def show_panel(ctx: Ctx, event, pid, note=None, new: bool = False) -> None: + post, ch = await load_post(ctx, pid) + text, kb = panel_text(post, ch, note), panel_keyboard(post) + if new or not is_cb(event): + await say(event, text, kb) + else: + await show(event, text, kb) + + +async def show_button_screen(ctx: Ctx, event, pid, r: int, c: int, new: bool = False) -> None: + post, _ = await load_post(ctx, pid) + if not valid(post.buttons or [], r, c): + await show_panel(ctx, event, pid, new=new) + return + text, kb = button_text(post, r, c), button_keyboard(post, r, c) + if new or not is_cb(event): + await say(event, text, kb) + else: + await show(event, text, kb) + + +def check_lengths(text: str, has_media: bool) -> None: + n = utf16_len(text or "") + if has_media and n > CAPTION_MAX: + raise UserError(f"A caption can have at most {CAPTION_MAX} characters (yours has {n}).") + if not has_media and n > TEXT_MAX: + raise UserError(f"A text post can have at most {TEXT_MAX} characters (yours has {n}).") + + +class Content(dict): + """Post fields (text, entities, media_kind, media_file_id). + + `how` says what the text was read as: "html" or "markdown" (turned into formatting), "rich" (a rich message sent + natively, kept as it is), "rich-html" / "rich-markdown" (typed, and Telegram builds the blocks), or None.""" + + how = None + + +def markup_note(how, sep: str = "\n\n") -> str: + """A line for the owner when their text was read as HTML or Markdown, followed by `sep` (empty otherwise).""" + if not how: + return "" + if how == "rich": + return f"🧩 Rich message kept as it is - 👁 Preview shows it.{sep}" + if how.startswith("rich-"): + lang = "HTML" if how == "rich-html" else "Markdown" + return f"🧩 Rich message read from {lang} - 👁 Preview shows what Telegram makes of it (/rich).{sep}" + return f"🎨 Formatting read from {'HTML' if how == 'html' else 'Markdown'} - see /formatting.{sep}" + + +def is_rich_how(how) -> bool: + return bool(how) and how.startswith("rich") + + +def read_text(m, markup: bool = True, rich: Optional[Rich] = None, allow_rich: bool = True) -> tuple: + """(text, entities, how) of what the owner sent - see Content.how. + + A rich message (`rich`: sent natively, kept block for block) or text typed as HTML / Markdown that needs blocks + becomes a rich post: `text` is its plain-text version and its only entity is the rich entry. Otherwise it is an + ordinary text with Telegram's own formatting, or HTML / Markdown turned into formatting. A message that has + Telegram formatting of its own is used as it is. `allow_rich` is False where a rich message can't be (a caption).""" + how = None + if rich is not None: + if not allow_rich: + raise UserError("A caption can't be a rich message. Rich messages are for text posts.") + how = "rich" + elif allow_rich and markup and not ser_entities(m.entities): + rich = read_typed(m.raw_text or "") + how = f"rich-{rich.fmt}" if rich is not None else None + if rich is None: + return message_text(m, markup) + try: + check_rich(rich) + except RichError as e: + raise UserError(str(e)) + return plain_of(rich), [rich_entry(rich)], how + + +async def read_native(ctx: Ctx, event) -> Optional[Rich]: + """The rich message the owner sent natively (or forwarded), or None for an ordinary message.""" + try: + return await received(ctx.client, event) + except RichError as e: + raise UserError(str(e)) + + +def extract_content(m, markup: bool = True, rich: Optional[Rich] = None) -> Content: + """A message from the user -> post fields (text, entities, media). + + Telegram's own formatting is kept as it is; without any, `markup` lets HTML or Markdown in the text become formatting + (or a rich message, when it has blocks only those have). `rich`: the message is a rich message sent natively.""" + kind = classify_media(m) + if m.media and kind is None and not isinstance(m.media, types.MessageMediaWebPage): + raise UserError("That kind of message can't be used in a post. Send text, a photo, video, GIF, audio or a file.") + text, entities, how = read_text(m, markup, rich if not kind else None, allow_rich=not kind) + if not kind and not text.strip() and not is_rich_how(how): + raise UserError("Send some text, or a photo / video / GIF / file.") + if not is_rich_how(how): + check_lengths(text, bool(kind)) + content = Content(text=text, entities=entities, media_kind=kind, media_file_id=pack_file_id(m) if kind else None) + content.how = how + return content + + +async def read_content(ctx: Ctx, event) -> Content: + """extract_content for a message that just arrived (a rich message sent natively is read, in full, first).""" + return extract_content(event.message, ctx.cfg.markup_input, await read_native(ctx, event)) diff --git a/app/handlers/posts.py b/app/handlers/posts.py new file mode 100644 index 0000000000000000000000000000000000000000..83a459eba73204ebd9eda254297963705fd08253 --- /dev/null +++ b/app/handlers/posts.py @@ -0,0 +1,534 @@ +"""/posts: list, open and edit posts (text, caption, media, buttons), publish drafts, delete.""" +from __future__ import annotations + +import logging + +from telethon import Button, errors + +from .. import picker +from ..buttons import ( + MAX_ROW, + add_button, + count, + delete_button, + missing_links, + move_button, + norm_url, + parse_buttons_text, + set_field, + valid, +) +from ..common import ( + Ctx, + UserError, + apply_edit, + apply_edit_reported, + clear_state, + cmd, + edit_report_text, + guard, + on_cb, + on_text, + say, + send_post, + set_state, + show, +) +from ..db import utcnow +from ..repost_engine import delete_batch +from ..richmsg import ( + block_count, + block_labels, + digest, + entry as rich_entry, + is_block_invalid, + is_rich, + pack_blocks, + plain_of, + refused_blocks, + rich_of, + unpack_blocks, + without_blocks, +) +from ..tgutil import classify_media, esc, explain_rpc, pack_file_id, peer_of, post_link +from ..ui import CANCEL, post_label +from ..userbot import delete_problem_text +from .panel import ( + check_lengths, + is_rich_how, + load_post, + markup_note, + read_native, + read_text, + show_button_screen, + show_panel, +) + +log = logging.getLogger(__name__) +PAGE = 8 +UPDATED = "✅ Updated in the channel." + + +def register(ctx: Ctx) -> None: + client, db = ctx.client, ctx.db + + def note_for(post, report=None) -> str: + extra = edit_report_text(report) + return (UPDATED if post.status == "sent" else "✅ Saved.") + (f"\n{extra}" if extra else "") + + # ------------------------------------------------------------------ lists + async def channel_chooser(event, arg: str = "", page: int = 0) -> None: + chans = await db.list_channels() + drafts = [[Button.inline("💾 Drafts (all channels)", "pc:d:0")]] + if not chans: + await show(event, "📚 My posts\n\nNo channels yet. Add one with /addchannel.", drafts) + return + text, kb = picker.render( + chans, page, head="📚 My posts - pick a channel:", kind="ps", choose=lambda c: f"pc:{c.id}:0", extra_rows=drafts + ) + await show(event, text, kb) + + ctx.pickers["ps"] = channel_chooser + + @client.on(cmd("posts")) + @guard(ctx) + async def h_posts(event): + await channel_chooser(event) + + @on_cb(ctx, "pl") + async def cb_channel_chooser(event, parts): + await channel_chooser(event) + + @on_cb(ctx, "pc") + async def cb_list(event, parts): + key, page = parts[0], int(parts[1]) + if key == "d": + cid, status, title = None, "draft", "Drafts" + else: + cid, status = int(key), None + ch = await db.get_channel(cid) + title = ch.title if ch else "Channel" + rows, total = await db.list_posts(cid, status, page * PAGE, PAGE) + pages = max(1, -(-total // PAGE)) + if page >= pages: + page = pages - 1 + rows, total = await db.list_posts(cid, status, page * PAGE, PAGE) + kb = [[Button.inline(post_label(p), f"po:{p.id}")] for p in rows] + if pages > 1: + # "Prev" is always there: on the first page it jumps to the last one + nav = [Button.inline("⬅️ Prev", f"pc:{key}:{(page - 1) % pages}"), Button.inline(f"{page + 1}/{pages}", "noop")] + if page < pages - 1: + nav.append(Button.inline("Next ➡️", f"pc:{key}:{page + 1}")) + kb.append(nav) + if cid is not None and ctx.cfg.is_owner(event.sender_id): + kb.append([Button.inline("🔧 Check buttons", f"pk:{cid}")]) + kb.append([Button.inline("🔙 Channels", "pl")]) + head = f"📚 {esc(title)} - {total} post(s)" + if not rows: + head += "\n\nNothing here yet. Create a post with /new." + await show(event, head, kb) + + @on_cb(ctx, "po") + async def cb_open(event, parts): + clear_state(ctx, event.sender_id) + await show_panel(ctx, event, parts[0]) + + # ------------------------------------------------------------ text / caption + @on_cb(ctx, "et") + async def cb_edit_text(event, parts): + post, _ = await load_post(ctx, parts[0]) + set_state(ctx, event.sender_id, "edit_text", pid=post.id) + what = "caption" if post.media_kind else "text" + more = "" if post.media_kind else " Rich messages (headings, lists, tables ...) too: /rich." + await say(event, f"✏️ Send the new {what}. Formatting is kept - or type HTML / Markdown (/formatting shows how).{more}", CANCEL) + + @on_text(ctx, "edit_text") + async def h_edit_text(event, st): + m = event.message + if classify_media(m): + raise UserError("Send text only here. To change the media, use 🖼 Media.") + post, ch = await load_post(ctx, st["pid"]) + native = await read_native(ctx, event) + text, entities, how = read_text(m, ctx.cfg.markup_input, native, allow_rich=not post.media_kind) + if not post.media_kind and not text.strip() and not is_rich_how(how): + raise UserError("A text post can't be empty.") + if not is_rich_how(how): + check_lengths(text, bool(post.media_kind)) + post, report = await apply_edit_reported(ctx, post, ch, text=text, entities=entities) + clear_state(ctx, event.sender_id) + await show_panel(ctx, event, post.id, note=markup_note(how, "\n") + note_for(post, report), new=True) + + # ------------------------------------------------------------------- media + @on_cb(ctx, "em") + async def cb_edit_media(event, parts): + post, _ = await load_post(ctx, parts[0]) + if is_rich(post): + raise UserError( + "A rich message has no media slot. Put pictures into the text itself (see /rich), " + "or send new text without rich blocks first." + ) + set_state(ctx, event.sender_id, "edit_media", pid=post.id) + extra = "" if post.media_kind else "\nThe current text becomes its caption." + await say(event, f"🖼 Send the new photo / video / GIF / audio / file.{extra}", CANCEL) + + @on_text(ctx, "edit_media") + async def h_edit_media(event, st): + m = event.message + if m.grouped_id and st.get("group") == m.grouped_id: + return + if m.grouped_id: + st["group"] = m.grouped_id + kind = classify_media(m) + if not kind: + raise UserError("Send a photo, video, GIF, audio file or document.") + post, ch = await load_post(ctx, st["pid"]) + check_lengths(post.text or "", True) + + async def notify(text: str) -> None: + await say(event, text) + + post, report = await apply_edit_reported( + ctx, post, ch, replace_media=True, notify=notify, media_kind=kind, media_file_id=pack_file_id(m) + ) + clear_state(ctx, event.sender_id) + await show_panel(ctx, event, post.id, note=note_for(post, report), new=True) + + @on_cb(ctx, "rm") + async def cb_remove_media(event, parts): + post, ch = await load_post(ctx, parts[0]) + if post.status != "draft": + raise UserError("Media can't be removed from a published post - Telegram doesn't allow it.") + if not (post.text or "").strip(): + raise UserError("Add some text first, then remove the media (a post needs text or media).") + await db.update_post(post.id, media_kind=None, media_file_id=None) + await show_panel(ctx, event, post.id, note="✅ Media removed.") + + @on_cb(ctx, "lp") + async def cb_link_preview(event, parts): + post, ch = await load_post(ctx, parts[0]) + post = await apply_edit(ctx, post, ch, link_preview=not post.link_preview) + await show_panel(ctx, event, post.id) + + # ----------------------------------------------------------------- buttons + async def commit_buttons(event, post, ch, rows, *, new_msg: bool = True, note: str = None): + post = await apply_edit(ctx, post, ch, buttons=rows) + await show_panel(ctx, event, post.id, note=note or note_for(post), new=new_msg) + return post + + @on_cb(ctx, "ba") + async def cb_add_button(event, parts): + post, _ = await load_post(ctx, parts[0]) + if count(post.buttons) >= 100: + raise UserError("A post can have at most 100 buttons.") + set_state(ctx, event.sender_id, "btn_add_text", pid=post.id) + await say( + event, + "➕ Send the button as Button text - link, or just the button text and I'll ask for the link.", + CANCEL, + ) + + async def place_button(event, pid, btn: dict) -> None: + post, ch = await load_post(ctx, pid) + if post.buttons and len(post.buttons[-1]) < MAX_ROW: + set_state(ctx, event.sender_id, "btn_place", pid=post.id, btn=btn) + await say( + event, + f"Where should {esc(btn['t'])} go?", + [ + [Button.inline("⬇️ New row", f"bk:{post.id}:n"), Button.inline("➡️ Same row", f"bk:{post.id}:s")], + CANCEL[0], + ], + ) + return + clear_state(ctx, event.sender_id) + await commit_buttons(event, post, ch, add_button(post.buttons, btn, True)) + + @on_text(ctx, "btn_add_text") + async def h_btn_add_text(event, st): + txt = (event.raw_text or "").strip() + if not txt: + raise UserError("Send the button text.") + try: + rows = parse_buttons_text(txt) + except ValueError: + rows = [] + if rows: + if len(rows) == 1 and len(rows[0]) == 1: + await place_button(event, st["pid"], rows[0][0]) + return + raise UserError("That's several buttons. Send one at a time, or use 📋 Set buttons to replace them all.") + if len(txt) > 64: + raise UserError("Keep the button text under 64 characters.") + set_state(ctx, event.sender_id, "btn_add_url", pid=st["pid"], text=txt) + await say(event, f"🔗 Now send the link for {esc(txt)}.", CANCEL) + + @on_text(ctx, "btn_add_url") + async def h_btn_add_url(event, st): + url = norm_url(event.raw_text or "") + if not url: + raise UserError("That doesn't look like a link. Send something like https://t.me/yourbot?start=abc") + await place_button(event, st["pid"], {"t": st["text"], "u": url}) + + @on_cb(ctx, "bk") + async def cb_place(event, parts): + st = ctx.state.get(event.sender_id) + if not st or st.get("mode") != "btn_place" or str(st.get("pid")) != parts[0]: + raise UserError("That step expired. Tap ➕ Button again.") + post, ch = await load_post(ctx, parts[0]) + rows = add_button(post.buttons, st["btn"], new_row=(parts[1] == "n")) + clear_state(ctx, event.sender_id) + await commit_buttons(event, post, ch, rows, new_msg=False) + + @on_cb(ctx, "bp") + async def cb_paste(event, parts): + post, _ = await load_post(ctx, parts[0]) + set_state(ctx, event.sender_id, "btn_paste", pid=post.id) + warn = "" + if any(b.get("raw") for r in post.buttons for b in r): + warn = "\n⚠️ This also removes buttons made by other bots (like reactions)." + await say( + event, + "📋 Send all the buttons - one row per line as Text - link, " + "with | between buttons in one row. This replaces the current buttons." + warn, + CANCEL, + ) + + @on_text(ctx, "btn_paste") + async def h_btn_paste(event, st): + try: + rows = parse_buttons_text(event.raw_text or "") + except ValueError as e: + raise UserError(f"❌ {e}\n\nTry again.") + if not rows: + raise UserError("Send at least one button as “Text - link”.") + post, ch = await load_post(ctx, st["pid"]) + clear_state(ctx, event.sender_id) + await commit_buttons(event, post, ch, rows) + + @on_cb(ctx, "bc") + async def cb_clear(event, parts): + await show( + event, + "Remove all buttons from this post?", + [[Button.inline("🧹 Yes, remove", f"bcy:{parts[0]}"), Button.inline("↩️ Back", f"po:{parts[0]}")]], + ) + + @on_cb(ctx, "bcy") + async def cb_clear_yes(event, parts): + post, ch = await load_post(ctx, parts[0]) + await commit_buttons(event, post, ch, [], new_msg=False) + + @on_cb(ctx, "bs") + async def cb_select(event, parts): + clear_state(ctx, event.sender_id) + await show_button_screen(ctx, event, parts[0], int(parts[1]), int(parts[2])) + + @on_cb(ctx, "bt") + async def cb_btn_text(event, parts): + set_state(ctx, event.sender_id, "btn_text", pid=parts[0], r=int(parts[1]), c=int(parts[2])) + await say(event, "✏️ Send the new button text.", CANCEL) + + @on_text(ctx, "btn_text") + async def h_btn_text(event, st): + txt = (event.raw_text or "").strip() + if not txt: + raise UserError("Send the new button text.") + if len(txt) > 64: + raise UserError("Keep the button text under 64 characters.") + post, ch = await load_post(ctx, st["pid"]) + if not valid(post.buttons, st["r"], st["c"]): + raise UserError("That button no longer exists.") + post = await apply_edit(ctx, post, ch, buttons=set_field(post.buttons, st["r"], st["c"], t=txt)) + clear_state(ctx, event.sender_id) + await show_button_screen(ctx, event, post.id, st["r"], st["c"], new=True) + + @on_cb(ctx, "bu") + async def cb_btn_url(event, parts): + set_state(ctx, event.sender_id, "btn_url", pid=parts[0], r=int(parts[1]), c=int(parts[2])) + await say(event, "🔗 Send the new link for this button.", CANCEL) + + @on_text(ctx, "btn_url") + async def h_btn_url(event, st): + url = norm_url(event.raw_text or "") + if not url: + raise UserError("That doesn't look like a link. Send something like https://t.me/yourbot?start=abc") + post, ch = await load_post(ctx, st["pid"]) + if not valid(post.buttons, st["r"], st["c"]): + raise UserError("That button no longer exists.") + post = await apply_edit(ctx, post, ch, buttons=set_field(post.buttons, st["r"], st["c"], u=url)) + clear_state(ctx, event.sender_id) + await show_button_screen(ctx, event, post.id, st["r"], st["c"], new=True) + + @on_cb(ctx, "bm") + async def cb_move(event, parts): + pid, r, c, d = parts[0], int(parts[1]), int(parts[2]), parts[3] + post, ch = await load_post(ctx, pid) + rows, nr, nc = move_button(post.buttons, r, c, d) + if rows == post.buttons: + return # already at the edge + post = await apply_edit(ctx, post, ch, buttons=rows) + await show_button_screen(ctx, event, post.id, nr, nc) + + @on_cb(ctx, "bd") + async def cb_btn_delete(event, parts): + post, ch = await load_post(ctx, parts[0]) + rows = delete_button(post.buttons, int(parts[1]), int(parts[2])) + await commit_buttons(event, post, ch, rows, new_msg=False) + + # ------------------------------------------------------- preview / publish + async def rich_refusal(event, post, e, typed: str, tail: str = "") -> None: + """Telegram refused to make a rich message of the post: say why. + + A rich message that was typed (HTML / Markdown) is Telegram's to read: `typed` tells the owner to check the syntax. One + that was made in Telegram and sent to the bot is kept block by block, and Telegram does not say which block it + dislikes - so the blocks are tried out, in the owner's chat and quietly, to tell which ones it won't take (see + richmsg.refused_blocks). A draft can then go on without those: the ✂️ button. `tail` closes the message.""" + rich = rich_of(post) + head = "❌ " + explain_rpc(e) + if rich is None or rich.fmt != "blocks": + raise UserError(f"{head}\n{typed}") + if not is_block_invalid(e): + raise UserError(f"{head}\nTelegram could not make that rich message.\n{tail}".strip()) + bad = await refused_blocks(client, await event.get_input_chat(), rich) + if not bad: + raise UserError( + f"{head}\nI could not tell which block it is - /rich shows how to type the message as HTML / Markdown instead.\n{tail}".strip() + ) + if len(bad) >= block_count(rich): + raise UserError( + f"{head}\nIt won't take any block of that message as it is - /rich shows how to type it as HTML / Markdown instead.\n{tail}".strip() + ) + lines = [ + esc(head), + f"It won't take these blocks (of {block_count(rich)}): {esc(block_labels(rich, bad))}. The others are fine.", + ] + if tail: + lines.append(esc(tail)) + buttons = [] + if post.status == "draft": + lines.append("✂️ Leave those out keeps the rest of the message as the post.") + buttons.append([Button.inline("✂️ Leave those out", f"rx:{post.id}:{digest(rich)}:{pack_blocks(bad)}")]) + buttons.append([Button.inline("↩️ Back", f"po:{post.id}")]) + await say(event, "\n".join(lines), buttons) + + @on_cb(ctx, "rx") + async def cb_leave_out(event, parts): + post, ch = await load_post(ctx, parts[0]) + rich = rich_of(post) + if post.status != "draft" or rich is None or rich.fmt != "blocks" or parts[1] != digest(rich): + raise UserError("The post is not the one that was checked any more - press 👁 Preview again.") + total = block_count(rich) + drop = [i for i in unpack_blocks(parts[2]) if i < total] + if not drop: + raise UserError("Those blocks are not in the post any more.") + if len(drop) >= total: + raise UserError("Nothing would be left of the message. Send it again in another form, or as HTML / Markdown (/rich).") + kept = without_blocks(rich, drop) + post = await apply_edit(ctx, post, ch, text=plain_of(kept), entities=[rich_entry(kept)]) + await show_panel(ctx, event, post.id, note=f"✂️ Left out: {esc(block_labels(rich, drop))}.\n👁 Preview shows what is left.") + + @on_cb(ctx, "pv") + async def cb_preview(event, parts): + post, _ = await load_post(ctx, parts[0]) + if not (post.text or "").strip() and not post.media_file_id and not is_rich(post): + raise UserError("The post is empty.") + try: + await send_post(client, await event.get_input_chat(), post) + except errors.RPCError as e: + if not is_rich(post): + raise + await rich_refusal(event, post, e, typed="Telegram could not make that rich message - see /rich for the syntax.") + return + miss = missing_links(post.buttons) + if miss: + await say(event, f"👆 Preview. ⚠️ {miss} button(s) without a link are not shown.") + + @on_cb(ctx, "pb") + async def cb_publish(event, parts): + post, ch = await load_post(ctx, parts[0]) + if post.status != "draft": + raise UserError("This post is already published.") + if missing_links(post.buttons): + raise UserError("Some buttons (⚠️) have no link yet. Open them and add a link first.") + if not (post.text or "").strip() and not post.media_file_id and not is_rich(post): + raise UserError("The post is empty.") + await show( + event, + f"Publish this post to {esc(ch.title)}?", + [[Button.inline("🚀 Yes, publish", f"pby:{post.id}"), Button.inline("↩️ Back", f"po:{post.id}")]], + ) + + @on_cb(ctx, "pby") + async def cb_publish_yes(event, parts): + post, ch = await load_post(ctx, parts[0]) + if post.status != "draft": + raise UserError("This post is already published.") + try: + sent = await send_post(client, peer_of(ch), post) + except errors.RPCError as e: + if is_rich(post): + await rich_refusal(event, post, e, typed="The post was NOT published.", tail="The post was NOT published.") + return + raise UserError("❌ " + explain_rpc(e) + "\nThe post was NOT published.") + await db.release_slot(ch.id, sent.id, keep_pid=post.id) # the sync may have picked the message up a moment ago + post = await db.update_post(post.id, status="sent", message_id=sent.id, sent_at=utcnow()) + await show( + event, + f"✅ Published in {esc(ch.title)}\nOpen the post", + [ + [Button.inline("📝 Manage this post", f"po:{post.id}")], + [Button.inline("➕ New post", f"nc:{ch.id}")], + ], + ) + + # ----------------------------------------------------------------- delete + @on_cb(ctx, "dl") + async def cb_delete(event, parts): + post, ch = await load_post(ctx, parts[0]) + back = Button.inline("↩️ Back", f"po:{post.id}") + if post.status == "draft": + await show(event, "Discard this draft?", [[Button.inline("🗑 Yes, discard", f"dly:{post.id}:b"), back]]) + return + await show( + event, + f"Delete this post from {esc(ch.title)}?\n\n" + "🗑 Delete from channel - deletes it in the channel and removes it, with its data, from My posts.\n" + "🧹 Only forget it in the bot - the post stays in the channel; only My posts forgets it.", + [ + [Button.inline("🗑 Delete from channel", f"dly:{post.id}:a")], + [Button.inline("🧹 Only forget it in the bot", f"dly:{post.id}:b")], + [back], + ], + ) + + @on_cb(ctx, "dly") + async def cb_delete_yes(event, parts): + post, ch = await load_post(ctx, parts[0]) + note = "🗑 Done." + if post.status == "sent" and parts[1] == "a": + # The bot deletes the post; where Telegram refuses it (an age limit on old posts, a missing right) the userbot + # takes over at once - nothing is asked first. + fallback, deleter = await ctx.userbot.fallback_for(ch) if ctx.userbot is not None else (None, None) + try: + out = await delete_batch(client, peer_of(ch), [post.message_id], fallback) + finally: + if deleter is not None: + await deleter.close() + if post.message_id not in out.gone: + why = delete_problem_text( + ctx.userbot, bot_error=out.bot_error, fallback_error=out.fallback_error, tried=out.tried_userbot + ) + raise UserError( + f"Telegram did not delete that message. {why}\n" + "The post is still in My posts. Delete it by hand in the channel, then use “Only forget it in the bot”." + ) + # gone from the channel: it goes from My posts too, with what hangs on it (a timed deletion ...) + await db.forget_posts(post.channel_id, [post.message_id]) + note = "🗑 Done - deleted in the channel and removed from My posts." + if out.by_userbot: + note += "\nThe bot was not allowed to delete it, so the userbot did." + if post.status == "sent" and post.message_id and parts[1] == "b": + ctx.sync_ignore.add((post.channel_id, post.message_id)) # forgotten on purpose: the sync must not bring it back + await db.ignore_post(post.channel_id, post.message_id) # ... not even after a restart + await db.delete_post(post.id) + await show(event, note, [[Button.inline("📚 My posts", "pl")]]) diff --git a/app/handlers/replace.py b/app/handlers/replace.py new file mode 100644 index 0000000000000000000000000000000000000000..3e63e0cbfb4b57bf01c19cc245435f5cf5647c14 --- /dev/null +++ b/app/handlers/replace.py @@ -0,0 +1,502 @@ +"""/replace media, /swap links, /handleswap and /undo (owner only).""" +from __future__ import annotations + +import logging +import re +import secrets +import time +from dataclasses import dataclass, field +from urllib.parse import urlparse + +from telethon import Button, errors + +from ..common import ( + Ctx, + UserError, + apply_edit_reported, + cmd, + edit_callback_message, + edit_report_text, + guard, + on_cb, + purge_pending, + require_owner, + say, + show, +) +from ..linkswap import normalize_username +from ..replace_engine import ApplyResult, ChannelScan, ScanOptions, apply_channel, scan_channel, undo_batch +from ..richmsg import is_rich +from ..richtext import message_text +from ..sync_engine import SyncOptions, sync_ids +from ..tgutil import classify_media, esc, explain_rpc, get_rights, pack_file_id +from ..channelref import parse_channel_ref +from .panel import check_lengths, markup_note + +log = logging.getLogger(__name__) + +USAGE = ( + "Usage: /swap @old @new\n" + "Options: --channel @name (only that channel), --last 200 (only the newest 200 " + "post ids), --posts (also change t.me/old/123 post links), --no-typed (don't touch " + "links typed in the text)." +) + + +USAGE_HANDLES = ( + "Usage: /handleswap @old @new\n" + "Finds the posts that mention the username @old (in their text or caption, and in button names) in all " + "channels and changes it to @new. Only usernames change: links, hyperlinks and button links are left alone.\n" + "Options: --channel @name (only that channel), --last 200 (only the newest 200 post ids)." +) +HANDLE_PREFIX = "hs" # ids of /handleswap runs start with this, so /undo can word its question right + + +@dataclass +class Job: + user: int + opts: ScanOptions + scans: list + running: bool = False + created: float = field(default_factory=time.monotonic) + + +def parse_replace_args(raw: str, *, handles: bool = False) -> tuple: + toks = (raw or "").split() + flags = {"channel": None, "last": None, "posts": False, "typed": None} + pos: list = [] + i = 0 + while i < len(toks): + t = toks[i] + if t == "--channel" and i + 1 < len(toks): + flags["channel"] = toks[i + 1] + i += 2 + elif t == "--last" and i + 1 < len(toks): + if not toks[i + 1].isdigit() or int(toks[i + 1]) < 1: + raise ValueError("--last needs a number, for example --last 200") + flags["last"] = int(toks[i + 1]) + i += 2 + elif t == "--posts" and not handles: + flags["posts"] = True + i += 1 + elif t == "--no-typed" and not handles: + flags["typed"] = False + i += 1 + elif t.startswith("--"): + raise ValueError(f"Unknown option {t}") + else: + pos.append(t) + i += 1 + if len(pos) != 2: + raise ValueError("Give the old and the new username.") + old, new = normalize_username(pos[0]), normalize_username(pos[1]) + if not old or not new: + raise ValueError("Usernames look like @name (letters, digits and underscores).") + if old.lower() == new.lower(): + raise ValueError("The old and the new username are the same.") + return old, new, flags + + +def pick_channels(chans: list, ref) -> list: + if not ref: + return chans + r = parse_channel_ref(ref) + out = [c for c in chans if (isinstance(r, int) and c.id == r) or (isinstance(r, str) and (c.username or "").lower() == r.lower())] + if not out: + raise ValueError("That channel isn't registered (see /channels).") + return out + + +def parse_post_link(value: str): + """Return (public username or private channel id, message id) for Telegram post links.""" + try: + u = urlparse(value if "://" in value else "https://" + value) + bits = [x for x in u.path.strip("/").split("/") if x] + if u.netloc.lower() not in {"t.me", "www.t.me", "telegram.me", "www.telegram.me"}: + return None + if bits and bits[0] == "c" and len(bits) == 3 and bits[1].isdigit() and bits[2].isdigit(): + # Telegram's t.me/c URL uses the same positive channel ID stored by Telethon and in our database. + return int(bits[1]), int(bits[2]) + if bits and bits[0] == "s": + bits = bits[1:] + if len(bits) == 2 and bits[1].isdigit() and re.fullmatch(r"[A-Za-z][A-Za-z0-9_]{3,}", bits[0]): + return bits[0].lower(), int(bits[1]) + except Exception: + pass + return None + + +def handles_summary(job: Job) -> str: + o = job.opts + lines = [f"🔎 Scan finished - swap the username @{esc(o.old)} → @{esc(o.new)}"] + total = 0 + for s in job.scans: + head = f"\n{esc(s.channel.title)}" + if s.error: + lines.append(f"{head}\n⚠️ {esc(s.error)}") + continue + block = f"{head} - looked at post ids {s.first}-{s.scanned}" + if s.total == 0: + block += "\nNothing to change." + else: + t = sum(i.typed for i in s.infos.values()) + b = sum(i.buttons for i in s.infos.values()) + what = f"{t} mention(s) in the text" + (f", {b} in button names" if b else "") + block += f"\n{s.total} post(s) to change: {what}" + if s.foreign: + block += f"\n• {s.foreign} of them were not posted by this bot" + cb = sum(1 for i in s.infos.values() if i.callbacks) + if cb: + block += f"\n• {cb} carry other bots' buttons (e.g. reactions) - those stay as they are" + if s.skipped_post_links: + block += f"\n• left {s.skipped_post_links} mention(s) that are part of a link alone" + if s.not_editable: + block += f"\n⚠️ {s.not_editable} post(s) by others can't be edited: the bot lacks “Edit messages of others” here" + total += s.total + lines.append(block) + lines.append(f"\nTotal: {total} post(s).") + if total: + lines.append("Nothing has been changed yet. Every edit is logged, so /undo can restore the old versions.") + return "\n".join(lines) + + +def summary_text(job: Job) -> str: + if job.opts.mode == "handles": + return handles_summary(job) + o = job.opts + lines = [f"🔎 Scan finished - replace @{esc(o.old)} → @{esc(o.new)}"] + total = 0 + for s in job.scans: + head = f"\n{esc(s.channel.title)}" + if s.error: + lines.append(f"{head}\n⚠️ {esc(s.error)}") + continue + block = f"{head} - looked at post ids {s.first}-{s.scanned}" + if s.total == 0: + block += "\nNothing to change." + else: + b = sum(i.buttons for i in s.infos.values()) + h = sum(i.links for i in s.infos.values()) + t = sum(i.typed for i in s.infos.values()) + block += f"\n{s.total} post(s) to change: {b} button link(s), {h} hyperlink(s), {t} typed link(s)" + if s.foreign: + block += f"\n• {s.foreign} of them were not posted by this bot" + fb = sum(1 for i in s.infos.values() if not i.mine and i.buttons) + if fb: + block += f"\n• {fb} are button posts made by someone else - Telegram may refuse to edit those; /repost can re-post them with the new links instead" + cb = sum(1 for i in s.infos.values() if i.callbacks) + if cb: + block += f"\n• {cb} carry other bots' buttons (e.g. reactions) - those stay as they are" + if s.skipped_post_links: + block += f"\n• skipped {s.skipped_post_links} link(s) to channel posts (t.me/{o.old}/123) - use --posts to change them too" + if s.not_editable: + block += f"\n⚠️ {s.not_editable} post(s) by others can't be edited: the bot lacks “Edit messages of others” here" + total += s.total + lines.append(block) + lines.append(f"\nTotal: {total} post(s).") + if total: + lines.append("Nothing has been changed yet. Every edit is logged, so /undo can restore the old versions.") + return "\n".join(lines) + + +def register(ctx: Ctx) -> None: + client, db, cfg = ctx.client, ctx.db, ctx.cfg + lock = ctx.lock + + def make_updater(event): + last = [0.0] + + async def upd(text: str, force: bool = False) -> None: + now = time.monotonic() + if not force and now - last[0] < 3: + return + last[0] = now + try: + await edit_callback_message(event, text) + except errors.MessageNotModifiedError: + pass + except Exception: + log.debug("progress update failed", exc_info=True) + + return upd + + # ------------------------------------------------------------------ /replace media + @client.on(cmd("replace", args=True)) + @guard(ctx, owner=True) + async def h_replace(event): + purge_pending(ctx) + raw = (event.pattern_match.group(1) or "").strip() + if not raw: + await say(event, "Reply to a new photo, video, or file with /replace <channel post link>.") + return + # File replacement mode: reply to a media message with /replace . + link_bits = parse_post_link(raw) if len(raw.split()) == 1 else None + if link_bits: + reply = await event.get_reply_message() + if reply is None: + raise UserError("Reply to the new photo, video, or file, then send /replace .") + kind = classify_media(reply) + if not kind: + raise UserError("The replied-to message must contain a photo, video, GIF, audio file, or document.") + ref, message_id = link_bits + channels = await db.list_channels() + channel = next((c for c in channels if c.id == ref), None) if isinstance(ref, int) else next( + (c for c in channels if (c.username or "").lower() == ref), None + ) + if channel is None: + raise UserError("That post link is not from a registered channel. Check /channels.") + post = await db.find_by_message(channel.id, message_id) + if post is None: + report = await sync_ids( + ctx.client, + db, + channel, + [message_id], + SyncOptions(history=False, grace=0, delete_services=False, ignore=ctx.sync_ignore), + adopt_ids={message_id}, + ) + post = await db.find_by_message(channel.id, message_id) + if post is None: + if report.error: + raise UserError(f"I couldn't read that post: {report.error}") + if report.restricted: + raise UserError("Telegram is currently holding that post back, so I can't replace its media.") + if report.unsupported: + raise UserError("That post can't be saved in My posts, so its media can't be replaced here.") + raise UserError("That post no longer exists in the channel, or I can't add it to My posts.") + if post.status != "sent": + raise UserError("That post is not published yet.") + if is_rich(post): + raise UserError("That post is a rich message - it has no media or caption to replace. Edit its text in My posts.") + caption, entities, how = message_text(reply, cfg.markup_input) # Telegram's formatting, or HTML / Markdown + check_lengths(caption, True) + + async def notify(text: str) -> None: + await say(event, text) + + _, report = await apply_edit_reported( + ctx, post, channel, replace_media=True, notify=notify, media_kind=kind, media_file_id=pack_file_id(reply), + text=caption, entities=entities, + ) + extra = edit_report_text(report) + await say( + event, + markup_note(how) + + f"✅ Replaced the media in {esc(channel.title)} and updated My posts." + + (f"\n{extra}" if extra else ""), + ) + return + raise UserError("Use /replace with a channel post link, replying to the new media. Username swaps use /swap.") + + # ------------------------------------------------------------------ /swap usernames in links + @client.on(cmd("swap", args=True)) + @guard(ctx, owner=True) + async def h_swap(event): + purge_pending(ctx) + raw = (event.pattern_match.group(1) or "").strip() + if not raw: + await say(event, USAGE) + return + try: + old, new, flags = parse_replace_args(raw) + chans = pick_channels(await db.list_channels(), flags["channel"]) + except ValueError as e: + raise UserError(f"{e}\n\n" + re.sub(r"<[^>]+>", "", USAGE)) + if not chans: + raise UserError("No channels registered yet. Use /addchannel.") + opts = ScanOptions( + old=old, + new=new, + include_typed=cfg.replace_typed_links if flags["typed"] is None else flags["typed"], + include_posts=flags["posts"], + last=flags["last"], + ) + await begin_scan(event, opts, chans) + + # ---------------------------------------------------------------- /handleswap + @client.on(cmd("handleswap", args=True)) + @guard(ctx, owner=True) + async def h_handleswap(event): + purge_pending(ctx) + raw = (event.pattern_match.group(1) or "").strip() + if not raw: + await say(event, USAGE_HANDLES) + return + try: + old, new, flags = parse_replace_args(raw, handles=True) + chans = pick_channels(await db.list_channels(), flags["channel"]) + except ValueError as e: + raise UserError(f"{e}\n\n" + re.sub(r"<[^>]+>", "", USAGE_HANDLES)) + if not chans: + raise UserError("No channels registered yet. Use /addchannel.") + await begin_scan(event, ScanOptions(old=old, new=new, last=flags["last"], mode="handles"), chans) + + async def begin_scan(event, opts, chans) -> None: + """Read the channels, show what would change and wait for the owner's yes.""" + if lock.locked(): + raise UserError("Another /swap, /handleswap or /undo is still running - wait for it to finish.") + async with lock: + status = await say(event, f"🔍 Scanning {len(chans)} channel(s)…") + last_edit = [0.0] + scans = [] + for ch in chans: + rights = await get_rights(client, ch) + if rights is not None and not rights.admin: + s = await _empty_scan(ch, "The bot is not an admin here any more.") + scans.append(s) + continue + can_edit = True if rights is None else rights.edit + + async def prog(scan, title=ch.title): + now = time.monotonic() + if now - last_edit[0] < 3: + return + last_edit[0] = now + try: + await status.edit(f"🔍 Scanning {esc(title)}: post id {scan.scanned} of {scan.top or '?'}…") + except Exception: + pass + + try: + scan = await scan_channel( + client, ch, opts, can_edit_others=can_edit, mine_ids=await db.mine_message_ids(ch.id), progress=prog + ) + except errors.RPCError as e: + scan = await _empty_scan(ch, explain_rpc(e)) + scan.rights = rights + scans.append(scan) + job = Job(user=event.sender_id, opts=opts, scans=scans) + token = secrets.token_hex(4) + ctx.pending[token] = job + total = sum(s.total for s in scans) + kb = None + if total: + kb = [[Button.inline(f"✅ Apply to {total} post(s)", f"rp:{token}:y"), Button.inline("✖️ Cancel", f"rp:{token}:n")]] + try: + await status.edit(summary_text(job), buttons=kb, link_preview=False) + except Exception: + await say(event, summary_text(job), kb) + + async def _empty_scan(ch, error: str): + return ChannelScan(channel=ch, error=error) + + @on_cb(ctx, "rp") + async def cb_replace(event, parts): + require_owner(ctx, event) + token, action = parts[0], parts[1] + job = ctx.pending.get(token) + if not isinstance(job, Job) or job.user != event.sender_id: + raise UserError("That scan has expired. Run /swap again.") + if action == "n": + ctx.pending.pop(token, None) + await show(event, "Cancelled - nothing was changed.") + return + if job.running or lock.locked(): + raise UserError("It is already running.") + job.running = True + upd = make_updater(event) + o = job.opts + batch_id = (HANDLE_PREFIX if o.mode == "handles" else "") + secrets.token_hex(6) + totals = ApplyResult() + stopped: list = [] + async with lock: + await db.create_batch(batch_id, o.old, o.new, event.sender_id) + todo = sum(s.total for s in job.scans) + done_before = 0 + for s in job.scans: + if not s.infos: + continue + + async def prog(res, s=s, base=done_before): + await upd(f"⏳ {esc(s.channel.title)} - {base + res.edited}/{todo} edited…") + + try: + res = await apply_channel( + client, db, s, o, batch_id, event.sender_id, edit_delay=cfg.edit_delay, progress=prog + ) + except Exception as e: + log.exception("apply failed in %s", s.channel.id) + totals.failed.append((0, f"{s.channel.title}: {type(e).__name__}")) + continue + done_before += res.edited + totals.edited += res.edited + totals.unchanged += res.unchanged + totals.missing += res.missing + totals.no_perm += res.no_perm + totals.failed += res.failed + if res.aborted: + stopped.append((s.channel.title, res.aborted)) + ctx.pending.pop(token, None) + what = "username swap " if o.mode == "handles" else "" + lines = [f"✅ Done - {what}@{esc(o.old)} → @{esc(o.new)}", f"• edited: {totals.edited}"] + if totals.unchanged: + lines.append(f"• already fine / changed meanwhile: {totals.unchanged}") + if totals.missing: + lines.append(f"• deleted meanwhile: {totals.missing}") + if totals.no_perm: + lines.append(f"• skipped (no permission): {totals.no_perm}") + if totals.failed: + sample = ", ".join(f"#{m} {esc(n)}" for m, n in totals.failed[:8]) + lines.append(f"• failed: {len(totals.failed)} ({sample}{'…' if len(totals.failed) > 8 else ''})") + names = {n for _, n in totals.failed} + if names & {"MessageAuthorRequiredError", "InlineBotRequiredError", "ChatAdminRequiredError", "MessageIdInvalidError"}: + lines.append( + " Telegram doesn't let this bot edit those posts." + + ("" if o.mode == "handles" else " Use /repost to post them again with the new links.") + ) + for title, name in stopped: + lines.append(f"⚠️ Stopped early in {esc(title)}: Telegram refused 5 edits in a row ({esc(name)}).") + undo_label = "↩️ Undo this swap" if o.mode == "handles" else "↩️ Undo this replace" + kb = [[Button.inline(undo_label, f"ruc:{batch_id}")]] if totals.edited else None + if kb: + try: + await edit_callback_message(event, "\n".join(lines), kb) + except errors.MessageNotModifiedError: + pass + else: + await upd("\n".join(lines), force=True) + + # -------------------------------------------------------------------- /undo + async def ask_undo(event, batch) -> None: + n = await db.count_batch_changes(batch.id) + what = "username swap" if batch.id.startswith(HANDLE_PREFIX) else "replace" + await say( + event, + f"↩️ Undo the {what} @{esc(batch.old_username)} → @{esc(batch.new_username)}?\n" + f"{n} post(s) will be put back exactly as they were before.", + [[Button.inline("✅ Yes, undo", f"ru:{batch.id}"), Button.inline("✖️ No", "cx")]], + ) + + @client.on(cmd("undo")) + @guard(ctx, owner=True) + async def h_undo(event): + batch = await db.last_batch() + if batch is None: + raise UserError("There is nothing to undo - no /swap or /handleswap run yet.") + await ask_undo(event, batch) + + @on_cb(ctx, "ruc") + async def cb_undo_ask(event, parts): + require_owner(ctx, event) + batch = await db.get_batch(parts[0]) + if batch is None or batch.undone: + raise UserError("That replace was already undone.") + await ask_undo(event, batch) + + @on_cb(ctx, "ru") + async def cb_undo(event, parts): + require_owner(ctx, event) + if lock.locked(): + raise UserError("Another /swap, /handleswap or /undo is still running.") + upd = make_updater(event) + async with lock: + await upd("⏳ Restoring…", force=True) + + async def prog(res): + await upd(f"⏳ Restoring… {res.restored} done") + + res = await undo_batch(client, db, parts[0], edit_delay=cfg.edit_delay, progress=prog) + text = f"↩️ Restored {res.restored} post(s)." + if res.failed: + text += f"\n⚠️ {len(res.failed)} could not be restored (" + ", ".join(f"#{m} {esc(n)}" for m, n in res.failed[:6]) + ")." + await upd(text, force=True) diff --git a/app/handlers/repost.py b/app/handlers/repost.py new file mode 100644 index 0000000000000000000000000000000000000000..31011aa3670a4ffab9e4da6bcb8dc99ec59cfe84 --- /dev/null +++ b/app/handlers/repost.py @@ -0,0 +1,820 @@ +"""/repost: copy a whole channel in order (links swapped on the way), then remove the old posts. Owner only.""" +from __future__ import annotations + +import logging +import re +import secrets +import time +from dataclasses import dataclass, field + +from telethon import Button, errors + +from .. import picker +from ..common import Ctx, UserError, cmd, edit_callback_message, guard, on_cb, purge_pending, require_owner, say, show +from ..crosslinks import CrossResult, progress_text, relink_after_repost, report_lines, restore_after_undo +from ..linkswap import normalize_username +from ..profile_copy import profile_lines +from ..repost_engine import RepostOptions, RepostPlan, delete_copies, plan_repost, run_repost, saved_lookup +from ..tgutil import esc, get_rights, post_link +from ..userbot import delete_problem_text + +log = logging.getLogger(__name__) + +USAGE = ( + "Usage: /repost @old @new\n" + "Copies every post of a channel, in order, to the end of the channel and swaps the username inside " + "t.me links on the way. Leave out the usernames to copy without changing links. " + "You pick the channel with buttons afterwards.\n" + "Options: --last 5 (trial: only the newest 5 post ids), " + "--posts (also change t.me/old/123 post links), --no-typed.\n\n" + "Links to the old posts - in this channel and in all your other connected channels - are pointed at the copies " + "afterwards.\n" + "Nothing is deleted by /repost itself: you decide about the old posts after checking the copies." +) + + +@dataclass +class RepostChoice: + """/repost was typed; the owner still has to pick the channel.""" + + user: int + opts: RepostOptions + created: float = field(default_factory=time.monotonic) + + +@dataclass +class RepostJob: + user: int + ch: object + opts: RepostOptions + plan: object = None + running: bool = False + stop: bool = False + mig_id: str = "" + created: float = field(default_factory=time.monotonic) + + +def parse_repost_args(raw: str) -> tuple: + toks = (raw or "").split() + flags = {"last": None, "posts": False, "typed": None} + pos: list = [] + i = 0 + while i < len(toks): + t = toks[i] + if t == "--channel": + raise ValueError("/repost no longer takes --channel: send the command without it and pick the channel with the buttons.") + elif t == "--last" and i + 1 < len(toks): + if not toks[i + 1].isdigit() or int(toks[i + 1]) < 1: + raise ValueError("--last needs a number, for example --last 5") + flags["last"] = int(toks[i + 1]) + i += 2 + elif t == "--posts": + flags["posts"] = True + i += 1 + elif t == "--no-typed": + flags["typed"] = False + i += 1 + elif t.startswith("--"): + raise ValueError(f"Unknown option {t}") + else: + pos.append(t) + i += 1 + old = new = None + if pos: + if len(pos) != 2: + raise ValueError("Give both usernames (@old @new), or none to copy without changing links.") + old, new = normalize_username(pos[0]), normalize_username(pos[1]) + if not old or not new: + raise ValueError("Usernames look like @name (letters, digits and underscores).") + if old.lower() == new.lower(): + raise ValueError("The old and the new username are the same.") + return old, new, flags + + +def plan_text(p: RepostPlan, o: RepostOptions, title: str, delay: float) -> str: + kinds = f"{p.text} text, {p.media} media" + if p.polls: + kinds += f", {p.polls} poll(s)" + if p.other: + kinds += f", {p.other} other" + lines = [ + f"🧱 Repost plan - {esc(title)}", + f"Post ids {p.first}-{p.last}: {p.units} posts to copy ({p.messages} messages, {p.albums} album(s)) - {kinds}", + ] + if p.service: + lines.append(f"• {p.service} service message(s) (like “pinned a message”) can't be copied and are skipped") + if p.polls: + lines.append("• polls are copied without their votes") + if o.swaps: + lines.append( + f"• @{esc(o.old)} → @{esc(o.new)} in {p.link_posts} post(s): " + f"{p.n_buttons} button link(s), {p.n_links} hyperlink(s), {p.n_typed} typed link(s)" + ) + if p.dropped_posts: + lines.append(f"• {p.dropped_posts} post(s) carry other bots' buttons (reactions...) - those are not copied") + lines += held_plan_lines(p, title) + if p.post_links: + lines.append( + f"• {p.post_links} link(s) in {p.post_link_posts} post(s) point at other posts of this channel: " + "they are pointed at the new copies (a link to a post that doesn't exist stays as it is)" + ) + lines.append( + "• afterwards every link to an old post - a hyperlink, a typed link or a button, in ANY of your connected " + "channels - is pointed at the copy (the old posts themselves are not touched)" + ) + if p.replies: + lines.append(f"• {p.replies} post(s) answer another post: each copy answers the copy of that post") + if p.pinned: + lines.append( + f"• {p.pinned} pinned post(s): their copies are pinned at the end " + "(the bot needs the “Edit messages of others” right for that)" + ) + minutes = max(1, round(p.eta_seconds(delay) / 60)) + lines += [ + "", + "How: posts without buttons, replies or links to change are copied by Telegram itself, so they stay " + "exactly as they are. Posts with buttons, links to change or a reply are posted again with their text, " + "formatting, media and buttons in one go, and each one is read back to make sure its buttons are really " + "there. Copies go to the end of the channel silently, in the original order, and are registered in My posts.", + "", + "Not kept: original dates, view counts, reactions, comments and poll votes.", + f"Time: about {minutes} min. Please don't post in the channel meanwhile.", + "Nothing is deleted in this step.", + ] + if p.partial: + lines.append("Trial run: afterwards you can remove the copies again.") + return "\n".join(lines) + + +def held_plan_lines(p: RepostPlan, title: str, *, shift: bool = False) -> list: + """Plan lines about posts Telegram restricts (a copyright strike: the channel is "unavailable", or its posts are + marked or shown as a notice).""" + lines = [] + name = esc(title) + said = f" (“{esc(p.held_why)}”)" if p.held_why else "" + if p.channel_restricted and shift: + lines.append(f"• ⚠️ Telegram restricts {name} itself: “{esc(p.channel_restricted)}”") + elif p.channel_restricted: + lines.append( + f"• ⚠️ Telegram restricts {name} itself: “{esc(p.channel_restricted)}”. Telegram may hide what is posted into " + "such a channel as well, so a repost here may not bring the posts back. To save a struck channel use " + "/shift: it copies the posts from My posts into another channel." + ) + if p.held_saved and p.no_media: + lines.append( + f"• 📋 {p.held_saved} post(s) of {name} are restricted by Telegram{said}. They are copied from what My posts " + "saved of them - text, formatting and buttons - not from what Telegram shows now." + ) + elif p.held_saved: + lines.append( + f"• 📋 {p.held_saved} post(s) of {name} are restricted by Telegram{said}. They are copied from what My posts " + "saved of them - text, formatting, buttons and media - not from what Telegram shows now (a file that " + "Telegram refuses goes out without it)." + ) + if p.live_restricted and shift: + lines.append( + f"• ⚠️ {p.live_restricted} restricted post(s) of {name} have no saved copy in My posts, but Telegram still " + "hands out their content, so they are copied as they are now." + ) + elif p.live_restricted: + lines.append( + f"• ⚠️ Telegram marks {p.live_restricted} post(s) of {name} as restricted but still hands out their content, " + "so they are copied as they are now." + ) + if p.held_skipped and shift: + lines.append( + f"• ⚠️ Telegram shows only its notice for {p.held_skipped} more post(s) of {name}{said} and My posts has no " + "saved copy of them, so they are skipped and the shift will show as not complete. If you have a backup made " + "before that, put it back with /import and run /shift again." + ) + elif p.held_skipped: + lines.append( + f"• ⚠️ Telegram holds back {p.held_skipped} post(s) of {name}{said} - it shows a notice instead of them. " + "Copying the notice would be wrong, so they are skipped, and the old posts can't be deleted afterwards " + "(the repost will show as not complete)." + ) + if p.channel_restricted or p.held_saved or p.live_restricted: + lines.append("• The new posts are read back: if Telegram itself hides them, the report says so.") + return lines + + +def held_notes(res) -> list: + """Lines about the posts Telegram restricts, for the end of a repost or shift.""" + notes = [] + + def sample(ids, n=8): + return ", ".join(f"#{i}" for i in ids[:n]) + ("…" if len(ids) > n else "") + + what = "text, formatting and buttons" if getattr(res, "no_media", False) else "text, formatting, buttons and media" + if res.from_db: + if res.from_saved: + notes.append( + f"📋 The source can't be read, so {res.from_saved} post(s) were copied from what My posts saved of them: " + f"{what} - without replies, pins and albums." + ) + elif res.from_saved: + notes.append( + f"📋 {res.from_saved} post(s) are restricted by Telegram. They were copied from what My posts saved of " + f"them: {what}." + ) + if res.media_lost: + notes.append( + f"⚠️ {len(res.media_lost)} of them went out without their media, because Telegram refuses the saved file " + f"({sample(res.media_lost)})." + ) + if res.live_restricted and res.used_saved: + notes.append( + f"⚠️ {res.live_restricted} restricted post(s) had no saved copy in My posts, so they were copied as Telegram " + "hands them out (their content was intact)." + ) + elif res.live_restricted: + notes.append( + f"⚠️ Telegram marks {res.live_restricted} post(s) as restricted but still handed out their content, so they " + "were copied as they are." + ) + if res.held_back and res.used_saved: + notes.append( + f"⚠️ {len(res.held_back)} post(s): Telegram shows only its notice and My posts has no saved copy of them, so " + f"they were not copied ({sample(res.held_back)}). Put a backup made before that back with /import, then use " + "“Try the rest again”." + ) + elif res.held_back: + notes.append( + f"⚠️ {len(res.held_back)} post(s) are held back by Telegram - it shows a notice instead of them " + f"({sample(res.held_back)}). Copying the notice would be wrong, so they were not copied and the old posts are " + "not deleted." + ) + return notes + + +def no_media_notes(res) -> list: + """Lines about the files that /shift --no-media left out.""" + if not getattr(res, "no_media", False): + return [] + notes = [] + if res.files_left_out: + notes.append(f"🚫 {res.files_left_out} post(s) were copied as text only - their file was left out (--no-media).") + if res.file_only: + ids = ", ".join(f"#{i}" for i in res.file_only[:8]) + ("…" if len(res.file_only) > 8 else "") + notes.append(f"🚫 {len(res.file_only)} post(s) are only a file, so there was nothing to copy of them ({ids}).") + return notes + + +def hidden_notes(res, *, shift: bool = False) -> list: + """Lines about new posts that TELEGRAM itself hides (they were read back after posting).""" + if not getattr(res, "hidden", None): + return [] + k, n = len(res.hidden), res.checked + with_file = sum(1 for _, has in res.hidden if has) + plain = k - with_file + why = f" (“{esc(res.hidden_why)}”)" if res.hidden_why else "" + lines = [ + f"⚠️ Telegram itself hides {k} of the {n} new post(s) I read back{why}: right after they were created they " + "carry its restriction mark, so its apps show the notice instead of them. The bot did not copy a notice - it " + "never posts one: Telegram marks these posts itself, because of something in them or because of the destination." + ] + if with_file: + hint = ( + " /shift … --no-media copies the text and buttons without the files." + if shift + else "" + ) + lines.append( + f"• {with_file} post(s) of these carry a file. Telegram may hide a message that carries a file it has " + f"blocked for copyright, wherever it is posted.{hint}" + ) + if plain: + lines.append( + f"• {plain} post(s) of these have no file: Telegram hides them for their text or links, or because it " + "restricts the new channel too." + ) + if getattr(res, "dst_restricted", None): + lines.append(f"• Telegram restricts the destination channel itself: “{esc(res.dst_restricted)}”.") + if getattr(res, "hidden_stop", False): + lines.append( + f"⏹ I stopped after {res.copied_units} post(s): Telegram hides every new copy I read back, so going on " + "would only add more posts nobody can see. Nothing else was posted. ▶️ Continue anyway copies the rest; " + "↩️ Undo removes the copies." + ) + lines.append("The saved posts in My posts are intact. Undo removes the new copies again.") + return lines + + +def hidden_progress(res) -> str: + """One line for the running progress message when Telegram hides what was just posted.""" + if not getattr(res, "hidden", None): + return "" + why = f" (“{esc(res.hidden_why)}”)" if res.hidden_why else "" + return f"\n⚠️ Telegram itself hides {len(res.hidden)} of the {res.checked} new posts checked so far{why}. ⏹ Stop is below." + + +def finishing_notes(res, *, shift: bool = False) -> list: + """Lines about answers, links and pins for the end of a repost or shift.""" + notes = held_notes(res) + no_media_notes(res) + hidden_notes(res, shift=shift) + if res.replies: + notes.append(f"↩️ {res.replies} post(s) answer the copy of the post they answered.") + if res.reply_lost: + notes.append(f"{res.reply_lost} post(s) could only be copied without their reply (their media can't be rebuilt).") + if res.reply_dropped: + notes.append(f"{res.reply_dropped} post(s) answered a post that is not there any more, so they answer nothing.") + fin = res.final + if fin is not None: + if fin.relinked: + notes.append(f"🔗 {fin.links} link(s) in {fin.relinked} post(s) now point at the new copies.") + if fin.failed: + sample = ", ".join(f"#{i} {esc(n)}" for i, n in fin.failed[:5]) + notes.append(f"{len(fin.failed)} post(s) could not get their links updated ({sample}).") + if fin.pinned: + notes.append(f"📌 {fin.pinned} pinned post(s) are pinned again.") + if fin.pin_error: + notes.append( + f"📌 {fin.pin_wanted - fin.pinned} copy/copies could not be pinned ({esc(fin.pin_error)}). Give the bot the " + "“Edit messages of others” right, or pin them by hand." + ) + if res.final_error: + notes.append(f"Links and pins could not be finished ({esc(res.final_error)}).") + if res.profile is not None: + notes += profile_lines(res.profile) + if res.profile_error: + notes.append(f"The name, description and photo could not be copied ({esc(res.profile_error)}).") + if res.cross is not None: + notes += report_lines(res.cross) + if res.cross_error: + notes.append( + f"Links in your other channels could not be updated ({esc(res.cross_error)}). " + "Press “🔗 Update links again” to try once more." + ) + return notes + + +def register(ctx: Ctx) -> None: + client, db, cfg = ctx.client, ctx.db, ctx.cfg + + # ---------------------------------------------------------------- views + async def view_for(mig): + """Text and buttons describing where a repost stands.""" + ch = await db.get_channel(mig.channel_id) + c = await db.migration_counts(mig.id) + name = esc(ch.title) if ch else str(mig.channel_id) + swap = f" (@{esc(mig.old_username)} → @{esc(mig.new_username)})" if mig.old_username else "" + first_copy = "" + if ch and c["first_new"]: + first_copy = f'\nFirst copy' + undo = [Button.inline("↩️ Undo - remove the copies", f"rpu:{mig.id}")] + links = [Button.inline("🔗 Update links again", f"rpl:{mig.id}")] + if mig.status == "copied" and not mig.partial: + text = ( + f"✅ {name}: all posts copied in order{swap}\n{c['copied']} messages are now at the end of the channel " + f"and in My posts.{first_copy}\n\nLook at the end of the channel and check a few posts: formatting, " + "buttons, media. If it looks right, delete the old posts. If not, undo: the copies are removed and the " + "originals were never touched." + ) + kb = [[Button.inline("🗑 Delete the old posts", f"rpd:{mig.id}")], links, undo] + elif mig.status == "copied": + text = ( + f"✅ {name}: trial finished{swap}\n{c['copied']} message(s) copied.{first_copy}\n" + "Check them. Remove them again, or close this trial and keep them." + ) + kb = [links, undo, [Button.inline("✅ Close, keep the copies", f"rpk:{mig.id}")]] + elif mig.status == "stopped": + text = f"⏹ {name}: stopped{swap}\n{c['copied']} message(s) copied so far.{first_copy}" + kb = [[Button.inline("▶️ Continue", f"rpc:{mig.id}")], undo] + elif mig.status == "copying": + text = f"⏳ {name}: a repost was running when the bot stopped. {c['copied']} message(s) copied.{first_copy}" + kb = [[Button.inline("▶️ Continue", f"rpc:{mig.id}")], undo] + else: # incomplete + text = ( + f"⚠️ {name}: not everything was copied{swap}\n{c['copied']} message(s) copied.{first_copy}\n" + "Old posts are only deleted once everything is copied, so nothing is lost. Try the rest again, " + "or undo." + ) + kb = [[Button.inline("🔁 Try the rest again", f"rpc:{mig.id}")], undo] + return text, kb + + # --------------------------------------------------------------- /repost + @client.on(cmd("repost", args=True)) + @guard(ctx, owner=True) + async def h_repost(event): + purge_pending(ctx) + raw = (event.pattern_match.group(1) or "").strip() + if not raw: + mig = await db.open_migration() + if mig is not None: + text, kb = await view_for(mig) + await say(event, "Unfinished repost:\n\n" + text, kb) + else: + await say(event, USAGE) + return + try: + old, new, flags = parse_repost_args(raw) + except ValueError as e: + raise UserError(f"{e}\n\n" + re.sub(r"<[^>]+>", "", USAGE)) + chans = await db.list_channels() + if not chans: + raise UserError("No channels registered yet. Use /addchannel.") + opts = RepostOptions( + old=old, + new=new, + include_typed=cfg.replace_typed_links if flags["typed"] is None else flags["typed"], + include_posts=flags["posts"], + last=flags["last"], + ) + token = secrets.token_hex(4) + ctx.pending[token] = RepostChoice(user=event.sender_id, opts=opts) + await show_picker(event, token, 0) + + async def show_picker(event, token: str, page: int) -> None: + require_owner(ctx, event) + choice = ctx.pending.get(token) + if not isinstance(choice, RepostChoice) or choice.user != event.sender_id: + raise UserError("That list has expired. Run /repost again.") + chans = await db.list_channels() + if not chans: + raise UserError("No channels registered yet. Use /addchannel.") + opts = choice.opts + what = ( + f"swap @{esc(opts.old)} → @{esc(opts.new)} in the links" + if opts.swaps + else "copy without changing any link" + ) + if opts.last: + what += f", trial: only the newest {opts.last} post ids" + text, kb = picker.render( + chans, + page, + head=f"📢 Which channel should I repost?\nPlan: {what}.", + kind="rp", + arg=token, + choose=lambda c: f"rpch:{token}:{c.id}", + extra_rows=[[Button.inline("✖️ Cancel", f"rpn:{token}")]], + ) + await show(event, text, kb) + + ctx.pickers["rp"] = show_picker + + @on_cb(ctx, "rpch") + async def cb_pick(event, parts): + require_owner(ctx, event) + token, cid = parts[0], int(parts[1]) + choice = ctx.pending.get(token) + if not isinstance(choice, RepostChoice) or choice.user != event.sender_id: + raise UserError("That list has expired. Run /repost again.") + ch = await db.get_channel(cid) + if ch is None or not ch.active: + raise UserError("That channel is not registered any more. Run /repost again.") + mig = await db.open_migration(ch.id) + if mig is not None: + ctx.pending.pop(token, None) + text, kb = await view_for(mig) + await edit_callback_message( + event, "There is an unfinished repost for this channel. Finish or undo it first.\n\n" + text, kb + ) + return + rights = await get_rights(client, ch) + if rights is not None and not (rights.admin and rights.post): + raise UserError("The bot needs the “Post messages” admin right in that channel.") + if ctx.lock.locked(): + raise UserError("Another long job (replace / repost) is still running.") + ctx.pending.pop(token, None) # a second press on the list can't start a second plan + opts = choice.opts + last = [0.0] + + async def prog(p): + if time.monotonic() - last[0] < 3: + return + last[0] = time.monotonic() + try: + await edit_callback_message(event, f"🔍 Reading {esc(ch.title)}: post id {p.scanned}…") + except Exception: + pass + + async with ctx.lock: + await edit_callback_message(event, f"🔍 Reading {esc(ch.title)}…") + plan = await plan_repost(client, ch, opts, progress=prog, saved=saved_lookup(db, ch.id)) + if plan.error: + await edit_callback_message(event, f"⚠️ {esc(plan.error)}") + return + job = RepostJob(user=event.sender_id, ch=ch, opts=opts, plan=plan) + ctx.pending[token] = job + kb = [[Button.inline("▶️ Start copying", f"rpa:{token}"), Button.inline("✖️ Cancel", f"rpn:{token}")]] + await edit_callback_message(event, plan_text(plan, opts, ch.title, cfg.edit_delay), kb) + + @on_cb(ctx, "rpn") + async def cb_cancel(event, parts): + require_owner(ctx, event) + ctx.pending.pop(parts[0], None) + await edit_callback_message(event, "Cancelled - nothing was copied or deleted.") + + # ------------------------------------------------------------------ copy + async def run_copy(event, job: RepostJob) -> None: + mig = await db.get_migration(job.mig_id) + ch = job.ch + job.running, job.stop = True, False + ctx.pending[f"job:{mig.id}"] = job + total = job.plan.units if job.plan else None + last = [0.0] + + async def prog(res): + if res.phase in ("copy", "links") and time.monotonic() - last[0] < 4: + return + last[0] = time.monotonic() + done = res.copied_units + res.skipped_done + of = f"/{total}" if total else "" + if res.phase == "links" and res.cross is not None: + body = f"✅ Copied {done}{of} posts.\n" + progress_text(res.cross) + elif res.phase == "finish": + body = f"🔗 Copied {done}{of} posts. Now pointing links at the new copies and pinning…" + else: + body = f"⏳ Copying {esc(ch.title)}: {done}{of} posts…\nThe old posts stay untouched." + body += hidden_progress(res) + try: + await edit_callback_message(event, body, [[Button.inline("⏹ Stop", f"rps:{mig.id}")]]) + except errors.MessageNotModifiedError: + pass + except Exception: + log.debug("progress update failed", exc_info=True) + + try: + async with ctx.lock: + await db.set_migration_status(mig.id, "copying") + res = await run_repost( + client, db, ch, mig, event.sender_id, delay=cfg.edit_delay, progress=prog, should_stop=lambda: job.stop + ) + finally: + job.running = False + status = "stopped" if res.stopped else ("incomplete" if (res.failed or res.aborted or res.held_back) else "copied") + await db.set_migration_status(mig.id, status) + mig = await db.get_migration(mig.id) + text, kb = await view_for(mig) + notes = [] + if res.copied_units: + notes.append( + f"{res.forwarded} post(s) were copied by Telegram, {res.rebuilt} were posted again with their buttons." + ) + if res.repaired: + notes.append(f"{res.repaired} post(s) needed their buttons set again after posting - they show them now.") + if res.failed: + sample = ", ".join(f"#{i} {esc(n)}" for i, n in res.failed[:6]) + notes.append(f"{len(res.failed)} post(s) failed ({sample}{'…' if len(res.failed) > 6 else ''}).") + if any(n == "ButtonsNotShown" for _, n in res.failed): + notes.append( + "ButtonsNotShown: Telegram did not show the buttons on the new post, so that copy was removed again. " + "The original is untouched - use “Try the rest again”." + ) + if res.aborted: + notes.append(f"Stopped early because of {esc(res.aborted)}.") + notes += finishing_notes(res) + await edit_callback_message(event, text + ("\n\n" + "\n".join(notes) if notes else ""), kb) + + @on_cb(ctx, "rpa") + async def cb_start(event, parts): + require_owner(ctx, event) + job = ctx.pending.get(parts[0]) + if not isinstance(job, RepostJob) or job.user != event.sender_id: + raise UserError("That plan has expired. Run /repost again.") + if job.running or ctx.lock.locked(): + raise UserError("A long job is already running.") + if await db.open_migration(job.ch.id) is not None: + raise UserError("There is already an unfinished repost for this channel.") + p, o = job.plan, job.opts + job.mig_id = secrets.token_hex(6) + await db.create_migration( + job.mig_id, job.ch.id, old=o.old, new=o.new, include_typed=o.include_typed, include_posts=o.include_posts, + first_id=p.first, last_id=p.last, partial=p.partial, user_id=event.sender_id, + ) + ctx.pending.pop(parts[0], None) + await run_copy(event, job) + + @on_cb(ctx, "rpc") + async def cb_continue(event, parts): + require_owner(ctx, event) + mig = await db.get_migration(parts[0]) + if mig is None or mig.status not in ("stopped", "incomplete", "copying"): + raise UserError("There is nothing to continue.") + if ctx.lock.locked(): + raise UserError("A long job is already running.") + ch = await db.get_channel(mig.channel_id) + if ch is None: + raise UserError("That channel is not registered any more.") + opts = RepostOptions(old=mig.old_username, new=mig.new_username, include_typed=mig.include_typed, include_posts=mig.include_posts) + await run_copy(event, RepostJob(user=event.sender_id, ch=ch, opts=opts, mig_id=mig.id)) + + @on_cb(ctx, "rps") + async def cb_stop(event, parts): + require_owner(ctx, event) + job = ctx.pending.get(f"job:{parts[0]}") + if isinstance(job, RepostJob) and job.running: + job.stop = True + await event.respond("⏹ Stopping after the post that is being worked on…") + else: + await event.respond("Nothing is running.") + + # ------------------------------------------------------------ links again + @on_cb(ctx, "rpl") + async def cb_links(event, parts): + """Look through every connected channel once more for links to the old posts and point them at the copies.""" + require_owner(ctx, event) + mig, ch = await load(parts) + if mig.status not in ("copied", "old_deleted"): + raise UserError("Links can be updated once everything is copied.") + if ctx.lock.locked(): + raise UserError("A long job is already running.") + job = RepostJob(user=event.sender_id, ch=ch, opts=RepostOptions(), mig_id=mig.id, running=True) + ctx.pending[f"job:{mig.id}"] = job + cross, last = CrossResult(), [0.0] + + async def prog(c): + if time.monotonic() - last[0] < 4: + return + last[0] = time.monotonic() + try: + await edit_callback_message(event, progress_text(c), [[Button.inline("⏹ Stop", f"rps:{mig.id}")]]) + except errors.MessageNotModifiedError: + pass + except Exception: + log.debug("progress update failed", exc_info=True) + + error = None + try: + async with ctx.lock: + await edit_callback_message(event, "🔗 Looking for links to the old posts in your channels…") + await relink_after_repost( + client, db, ch, mig, delay=cfg.edit_delay, progress=prog, should_stop=lambda: job.stop, result=cross + ) + except Exception as e: # the posts are fine; only the links were not (all) updated + log.exception("pointing the links at the copies failed") + error = type(e).__name__ + finally: + job.running = False + ctx.pending.pop(f"job:{mig.id}", None) + notes = report_lines(cross) + if error: + notes.append(f"Links could not be updated ({esc(error)}).") + if not notes: + notes.append("🔗 There is nothing to change.") + again = [Button.inline("🔗 Update links again", f"rpl:{mig.id}")] + if mig.status == "copied": + text, kb = await view_for(mig) + await edit_callback_message(event, text + "\n\n" + "\n".join(notes), kb) + else: + await edit_callback_message(event, f"🔗 {esc(ch.title)}\n" + "\n".join(notes), [again]) + + # ----------------------------------------------------- delete old / undo + async def load(parts): + mig = await db.get_migration(parts[0]) + if mig is None: + raise UserError("I don't know that repost any more.") + ch = await db.get_channel(mig.channel_id) + if ch is None: + raise UserError("That channel is not registered any more.") + return mig, ch + + @on_cb(ctx, "rpb") + async def cb_back(event, parts): + mig, _ = await load(parts) + text, kb = await view_for(mig) + await edit_callback_message(event, text, kb) + + @on_cb(ctx, "rpd") + async def cb_delete_ask(event, parts): + require_owner(ctx, event) + mig, ch = await load(parts) + if mig.status != "copied" or mig.partial: + raise UserError("Old posts can only be deleted after a complete, successful copy.") + c = await db.migration_counts(mig.id) + await edit_callback_message( + event, + f"🗑 Delete {c['old_left']} old message(s) from {esc(ch.title)}?\n" + "Only originals that have a copy are deleted. This can't be undone. The copies stay and become the channel: " + "nothing is lost, they are already there.", + [[Button.inline(f"🗑 Yes, delete {c['old_left']}", f"rpdy:{mig.id}"), Button.inline("↩️ Back", f"rpb:{mig.id}")]], + ) + + def userbot_lines(deleter) -> str: + notes = getattr(deleter, "notes", None) or [] + return ("\n" + "\n".join(f"• {esc(n)}" for n in notes)) if notes else "" + + @on_cb(ctx, "rpdy") + async def cb_delete_old(event, parts): + require_owner(ctx, event) + mig, ch = await load(parts) + if mig.status not in ("copied", "old_deleted") or mig.partial: + raise UserError("Old posts can only be deleted after a complete, successful copy.") + if ctx.lock.locked(): + raise UserError("A long job is already running.") + last = [0.0] + + async def prog(r): + if time.monotonic() - last[0] < 3: + return + last[0] = time.monotonic() + try: + await edit_callback_message(event, f"🗑 Deleting old posts… {r.deleted} done") + except Exception: + pass + + fallback, deleter = await ctx.userbot.fallback_for(ch) if ctx.userbot is not None else (None, None) + try: + async with ctx.lock: + res = await delete_copies(client, db, ch, mig, "old", delay=0.5, progress=prog, fallback=fallback) + finally: + if deleter is not None: + await deleter.close() + c = await db.migration_counts(mig.id) + extra = userbot_lines(deleter) + by = f" ({res.by_userbot} of them by the userbot)" if res.by_userbot else "" + if res.remaining == 0 and not res.error: + await db.set_migration_status(mig.id, "old_deleted") + await edit_callback_message( + event, + f"✅ Done. {res.deleted} old message(s) deleted{by}. The channel now consists of the copies " + f"(from here), and they are all in My posts.{extra}", + [[Button.inline("🔗 Update links again", f"rpl:{mig.id}")]], + ) + return + why = esc( + delete_problem_text( + ctx.userbot, bot_error=res.error, fallback_error=res.fallback_error, tried=res.tried_userbot + ) + ) + await edit_callback_message( + event, + f"⚠️ Deleted {res.deleted}{by}, {res.remaining} old message(s) are still there. {why}{extra}\n" + f"The copies are complete. You can delete the rest by hand: they are the messages with an id below " + f"{c['first_new']}. Then close this repost.", + [[Button.inline("🔁 Try again", f"rpdy:{mig.id}")], [Button.inline("✅ Close this repost", f"rpk:{mig.id}")]], + ) + + @on_cb(ctx, "rpu") + async def cb_undo_ask(event, parts): + require_owner(ctx, event) + mig, ch = await load(parts) + c = await db.migration_counts(mig.id) + if mig.status in ("old_deleted", "copies_deleted", "closed") or c["old_left"] < c["copied"]: + raise UserError("Some originals are already deleted, so removing the copies would delete your content. Undo is not possible any more.") + await edit_callback_message( + event, + f"↩️ Remove the {c['new_left']} copied message(s) from {esc(ch.title)}?\nThe original posts stay as they are.", + [[Button.inline("↩️ Yes, remove the copies", f"rpuy:{mig.id}"), Button.inline("Back", f"rpb:{mig.id}")]], + ) + + @on_cb(ctx, "rpuy") + async def cb_undo(event, parts): + require_owner(ctx, event) + mig, ch = await load(parts) + c = await db.migration_counts(mig.id) + if mig.status in ("old_deleted", "copies_deleted", "closed") or c["old_left"] < c["copied"]: + raise UserError("Undo is not possible any more.") + if ctx.lock.locked(): + raise UserError("A long job is already running.") + fallback, deleter = await ctx.userbot.fallback_for(ch) if ctx.userbot is not None else (None, None) + back = CrossResult() + last = [0.0] + + async def prog(c): + if time.monotonic() - last[0] < 4: + return + last[0] = time.monotonic() + try: + await edit_callback_message(event, progress_text(c, title="Pointing links back at the original posts")) + except Exception: + log.debug("progress update failed", exc_info=True) + + try: + async with ctx.lock: + try: # links that were pointed at the copies would be left without a post: point them back first + await restore_after_undo(client, db, ch, mig, delay=cfg.edit_delay, progress=prog, result=back) + except Exception: + log.exception("pointing the links back at the original posts failed") + back.stopped = True + res = await delete_copies(client, db, ch, mig, "new", delay=0.5, fallback=fallback) + finally: + if deleter is not None: + await deleter.close() + link_notes = report_lines(back, back=True) + link_text = ("\n" + "\n".join(link_notes)) if link_notes else "" + if res.remaining == 0 and not res.error: + await db.set_migration_status(mig.id, "copies_deleted") + await edit_callback_message( + event, + f"↩️ Done. {res.deleted} copied message(s) removed; the original posts were not touched." + f"{userbot_lines(deleter)}{link_text}", + ) + else: + why = esc( + delete_problem_text( + ctx.userbot, bot_error=res.error, fallback_error=res.fallback_error, tried=res.tried_userbot + ) + ) + await edit_callback_message( + event, + f"⚠️ Removed {res.deleted}, {res.remaining} copy/copies are still there. {why}{link_text}", + [[Button.inline("🔁 Try again", f"rpuy:{mig.id}")]], + ) + + @on_cb(ctx, "rpk") + async def cb_close(event, parts): + require_owner(ctx, event) + mig, _ = await load(parts) + await db.set_migration_status(mig.id, "closed") + await edit_callback_message(event, "✅ Closed. Nothing else will be changed in that channel by this repost.") diff --git a/app/handlers/shift.py b/app/handlers/shift.py new file mode 100644 index 0000000000000000000000000000000000000000..21486b15108e7a7163040b0bf3ecf9b7f69b6e42 --- /dev/null +++ b/app/handlers/shift.py @@ -0,0 +1,618 @@ +"""/shift [from_id] [to_id]: copy posts from one channel into another. Owner only.""" +from __future__ import annotations + +import logging +import re +import secrets +import time +from dataclasses import dataclass, field +from typing import Optional + +from telethon import Button, errors + +from ..channelref import ChannelRef, resolve_channel +from ..common import Ctx, UserError, cmd, edit_callback_message, guard, on_cb, purge_pending, require_owner, say +from ..crosslinks import CrossResult, progress_text, relink_after_shift, report_lines, restore_after_shift_undo +from ..profile_copy import profile_lines +from ..repost_engine import RepostOptions, RepostPlan, RepostResult, plan_repost, saved_lookup +from ..shift_engine import delete_shift_copies, plan_from_my_posts, run_shift, shift_profile, source_of +from ..tgutil import esc, explain_rpc, get_rights, post_link +from ..userbot import delete_problem_text +from .repost import finishing_notes, held_plan_lines, hidden_progress + +log = logging.getLogger(__name__) + +USAGE = ( + "Usage: /shift <source> <destination> [from_id] [to_id]\n" + "Copies posts from one channel into another - text, formatting, media, albums, buttons, replies - and registers " + "the copies in My posts. The source is only read: nothing in it is changed or deleted.\n\n" + "A channel can be given as @username, a t.me link, its id (-100…) or an invite link " + "(the bot must be a member). The bot must be an admin of the destination (Post messages).\n\n" + "/shift @source @destination - every post\n" + "/shift @source @destination 15 20 - only the posts with message ids 15 to 20\n" + "/shift @source @destination 15 - only post 15\n\n" + "A channel that Telegram restricts (a copyright strike: “This channel is unavailable due to copyright " + "infringement”, its posts shown as “This message couldn't be displayed on your device due to copyright " + "infringement”) is copied from what My posts saved of it - every post that has a saved copy, however intact " + "Telegram's version looks. Telegram's notice is never copied. A post without a saved copy is copied as Telegram " + "hands it out if it is still the post itself, and skipped if only the notice is left.\n\n" + "Three extras, each optional, in any order, with or without a range:\n" + "-c - afterwards every link to a post of the source - in ANY of your connected channels - is pointed " + "at the copy in the destination\n" + "-all - afterwards the destination gets the source's name, description and profile photo\n" + "--no-media - no file is copied: every post goes out as its text with its formatting and buttons " + "(use it when Telegram hides the copies because of their files)\n" + "/shift @source @destination -c -all does the first two." +) + + +@dataclass +class ShiftFlags: + """The optional extras of /shift.""" + + links: bool = False # -c: links to the source's posts, in all connected channels, follow the copies + profile: bool = False # -all: the destination gets the source's name, description and profile photo + no_media: bool = False # --no-media: the copies get no files (text, formatting and buttons only) + + +@dataclass +class ShiftJob: + """A shift that was planned and is waiting for the owner's OK (or is running).""" + + user: int + src: ChannelRef + dst: ChannelRef + plan: RepostPlan + already: int = 0 # posts of the range that an earlier shift copied into this destination + flags: ShiftFlags = field(default_factory=ShiftFlags) + running: bool = False + stop: bool = False + shift_id: str = "" + created: float = field(default_factory=time.monotonic) + + +_OPTION = re.compile(r"^[-\u2013\u2014]{1,2}([A-Za-z][A-Za-z0-9_-]*)$") # phone keyboards turn "--" into a long dash + + +def parse_shift_args(raw: str) -> tuple: + """-> (source text, destination text, first id or None, last id or None, ShiftFlags). + + -c, -all and --no-media can stand anywhere, in any order ("- all" with a space is understood too, and so are + -nomedia and a long dash in place of --); a channel id such as -1001234567890 is not an option.""" + text = re.sub(r"(? 4: + raise ValueError("Give the source and the destination channel, and optionally the first and the last message id.") + nums: list = [] + for t in toks[2:]: + if not t.isdigit() or int(t) < 1: + raise ValueError(f"“{t}” is not a message id. Message ids are positive numbers, for example 15 20.") + nums.append(int(t)) + first = last = None + if len(nums) == 1: + first = last = nums[0] + elif len(nums) == 2: + first, last = min(nums), max(nums) + return toks[0], toks[1], first, last, flags + + +def plan_text( + p: RepostPlan, src: ChannelRef, dst: ChannelRef, already: int, delay: float, flags: Optional[ShiftFlags] = None, + others: int = 0, info_right: bool = True, +) -> str: + kinds = f"{p.text} text, {p.media} media" + if p.polls: + kinds += f", {p.polls} poll(s)" + if p.other: + kinds += f", {p.other} other" + lines = [ + "📦 Shift plan", + f"From {esc(src.title)} → {esc(dst.title)}", + f"Post ids {p.first}-{p.last}: {p.units} posts to copy ({p.messages} messages, {p.albums} album(s)) - {kinds}", + ] + if p.service: + lines.append(f"• {p.service} service message(s) (like “pinned a message”) can't be copied and are skipped") + if p.polls: + lines.append("• polls are copied without their votes") + if p.dropped_posts: + lines.append(f"• {p.dropped_posts} post(s) carry other bots' buttons (reactions...) - those are not copied") + lines += held_plan_lines(p, src.title, shift=True) + if p.no_media: + note = "• 🚫 --no-media: no file is copied - every post goes out as its text with its formatting and buttons" + if p.files_left_out: + note += f". {p.files_left_out} post(s) carry a file that stays out" + if p.file_only: + note += f"; {p.file_only} post(s) are only a file, so there is nothing to copy of them and they are skipped" + lines.append(note + ".") + if p.post_links: + lines.append( + f"• {p.post_links} link(s) in {p.post_link_posts} post(s) point at other posts of {esc(src.title)}: those that " + "are shifted too will point at their copies" + ) + if p.replies: + lines.append(f"• {p.replies} post(s) answer another post: the copy answers the copy (if that post is shifted too)") + if already: + lines.append( + f"• ⚠️ {already} of these posts were already shifted into {esc(dst.title)} before: they would be copied again" + ) + flags = flags or ShiftFlags() + if p.from_db: + lines.insert( + 2, + f"⚠️ I can't read {esc(src.title)}: {esc(p.unreadable or 'Telegram refuses')}. My posts has the saved " + "posts of it, so they are copied from there.", + ) + if flags.links: + where = f"your {others} other connected channel(s)" if others else "your connected channels" + lines.append( + f"• 🔗 -c: afterwards every link to a post of {esc(src.title)} - a hyperlink, a typed link or a " + f"button - in {where} is pointed at the copy in {esc(dst.title)} (links to posts that are not shifted stay " + f"as they are). {esc(src.title)} itself is not changed." + ) + if flags.profile: + lines.append( + f"• 🖼 -all: afterwards {esc(dst.title)} gets the name, description and profile photo of " + f"{esc(src.title)}. Its own are replaced - undo does not bring them back. A part the source does not have " + "is left as it is." + ) + if not info_right: + lines.append( + f"• ⚠️ The bot does not have the “Change channel info” admin right in {esc(dst.title)} yet - give it " + "before the copying is finished, or use the “copy again” button afterwards." + ) + minutes = max(1, round(p.eta_seconds(delay) / 60)) + if p.from_db: + what = "its text, formatting and buttons" if p.no_media else ( + "its text, formatting, buttons and media (a file that Telegram refuses goes out without it)" + ) + how = ( + f"How: every post is posted again from what My posts saved of it - {what} - and every button is read " + "back to make sure it is there. Copies go to the end of the destination silently, in the original order, and " + "are registered in My posts." + ) + kept = "Not kept: original dates, view counts, reactions, comments, poll votes, pins, replies and albums (every picture of an album becomes a post of its own)." + elif p.no_media: + how = ( + "How: every post is posted again as its text with its formatting and buttons - no file is copied - and " + "every button is read back to make sure it is there. Copies go to the end of the destination silently, in the " + "original order, and are registered in My posts." + ) + kept = "Not kept: the files, albums (a caption becomes a post of its own), original dates, view counts, reactions, comments, poll votes and pins." + elif p.channel_restricted: + how = ( + "How: Telegram copies nothing out of a restricted channel, so every post is posted again - from what " + "My posts saved of it, or as Telegram hands it out when there is no saved copy - with its text, formatting, " + "media and buttons in one go, and every button is read back to make sure it is there. Copies go to the end of " + "the destination silently, in the original order, and are registered in My posts." + ) + kept = "Not kept: original dates, view counts, reactions, comments, poll votes and pins." + else: + how = ( + "How: posts are copied by Telegram itself where possible (exactly as they are); posts with buttons or " + "replies are posted again with their text, formatting, media and buttons in one go, and every button is read " + "back to make sure it is there. Copies go to the end of the destination silently, in the original order, and " + "are registered in My posts." + ) + if p.held_saved or p.live_restricted: + how += " Posts that Telegram restricts are never copied by Telegram itself: they are posted again." + kept = "Not kept: original dates, view counts, reactions, comments, poll votes and pins." + lines += [ + "", + how, + "", + kept, + f"Time: about {minutes} min. Nothing is changed in {esc(src.title)}.", + ] + return "\n".join(lines) + + +def register(ctx: Ctx) -> None: + client, db, cfg = ctx.client, ctx.db, ctx.cfg + + # ---------------------------------------------------------------- views + async def view_for(sh): + """Text and buttons describing where a shift stands.""" + dst = await db.get_channel(sh.dst_channel_id) + c = await db.shift_counts(sh.id) + src_name = esc(sh.src_title or str(sh.src_channel_id)) + dst_name = esc(dst.title) if dst else str(sh.dst_channel_id) + route = f"{src_name} → {dst_name}" + first_copy = "" + if dst and c["first_new"]: + first_copy = f'\nFirst copy' + undo = [Button.inline("↩️ Undo - remove the copies", f"sfu:{sh.id}")] + marks = await db.marks_of(sh.id) + if "nomedia" in marks: + route += " (without files)" + extras = [] + if "relink" in marks: + extras.append([Button.inline("🔗 Update links again", f"sfl:{sh.id}")]) + if "profile" in marks and "profile_done" not in marks: + extras.append([Button.inline("🖼 Copy name, description, photo again", f"sfp:{sh.id}")]) + if sh.status == "copied": + text = ( + f"✅ {route}: {c['copied']} message(s) copied (source ids {sh.first_id}-{sh.last_id}) and " + f"registered in My posts.{first_copy}\nThe source was not changed. Look at the end of the destination; " + "if something is wrong, undo removes just these copies." + ) + kb = extras + [undo] + elif sh.status == "copies_deleted": + text = f"↩️ {route}: the copies were removed again." + kb = [] + elif sh.status == "stopped": + text = f"⏹ {route}: stopped. {c['copied']} message(s) copied so far.{first_copy}" + go = "▶️ Continue anyway" if "hiddenok" in marks else "▶️ Continue" + kb = [[Button.inline(go, f"sfc:{sh.id}")], undo] + elif sh.status == "copying": + text = f"⏳ {route}: a shift was running when the bot stopped. {c['copied']} message(s) copied.{first_copy}" + kb = [[Button.inline("▶️ Continue", f"sfc:{sh.id}")], undo] + else: # incomplete + text = ( + f"⚠️ {route}: not everything was copied. {c['copied']} message(s) copied.{first_copy}\n" + "Nothing was changed in the source." + ) + kb = [[Button.inline("🔁 Try the rest again", f"sfc:{sh.id}")], undo] + return text, kb + + # --------------------------------------------------------------- /shift + @client.on(cmd("shift", args=True)) + @guard(ctx, owner=True) + async def h_shift(event): + purge_pending(ctx) + raw = (event.pattern_match.group(1) or "").strip() + if not raw: + sh = await db.open_shift() + if sh is not None: + text, kb = await view_for(sh) + await say(event, "Unfinished shift:\n\n" + text, kb) + return + await say(event, USAGE) + # a finished shift keeps its Undo: offer it again, so it can be found without scrolling up to its old message + last = await db.last_finished_shift() + if last is not None: + text, kb = await view_for(last) + await say(event, "Latest finished shift - you can still undo it:\n\n" + text, kb) + return + try: + src_text, dst_text, first, last, flags = parse_shift_args(raw) + except ValueError as e: + raise UserError(f"{e}\n\n" + re.sub(r"<[^>]+>", "", USAGE).replace("<", "<").replace(">", ">")) + src = await resolve_channel(ctx, src_text) + dst = await resolve_channel(ctx, dst_text) + if src.id == dst.id: + raise UserError("The source and the destination are the same channel. To rebuild one channel in order, use /repost.") + sh = await db.open_shift(src.id, dst.id) + if sh is not None: + text, kb = await view_for(sh) + await say(event, "There is an unfinished shift between these two channels. Finish or undo it first.\n\n" + text, kb) + return + rights = await get_rights(client, dst) + if rights is not None and not (rights.admin and rights.post): + raise UserError(f"The bot needs the “Post messages” admin right in {dst.title}.") + if ctx.lock.locked(): + raise UserError("Another long job (replace / repost / shift) is still running.") + note = await say(event, f"🔍 Reading {esc(src.title)}…") + last_edit = [0.0] + + async def prog(p): + if time.monotonic() - last_edit[0] < 3: + return + last_edit[0] = time.monotonic() + try: + await note.edit(f"🔍 Reading {esc(src.title)}: post id {p.scanned}…") + except Exception: + pass + + try: + async with ctx.lock: + plan = await plan_repost( + client, src, RepostOptions(), progress=prog, first_id=first, last_id=last, + saved=saved_lookup(db, src.id), use_saved=True, no_media=flags.no_media, + ) + except errors.RPCError as e: + why = explain_rpc(e) + # a channel that can't be read any more (banned, private ...) may still be in My posts: copy it from there + plan = await plan_from_my_posts(db, src, first, last, unreadable=why, no_media=flags.no_media) + if plan is None: + raise UserError( + f"I can't read {src.title}: {why}\nThe bot has to be a member of the source channel " + "(an admin is best; it only reads). My posts has no saved posts of it to copy from instead." + ) + if plan.error: + await note.edit(f"⚠️ {esc(plan.error)}") + return + already = len(await db.shifted_ids(src.id, dst.id, plan.first, plan.last)) + others = 0 + if flags.links: # the channels the links are looked for in: all connected ones, the source itself excluded + known = {c.id for c in await db.list_channels()} | {dst.id} + others = len(known - {src.id}) + info_right = rights is None or bool(getattr(rights, "change_info", True)) + token = secrets.token_hex(4) + ctx.pending[token] = ShiftJob(user=event.sender_id, src=src, dst=dst, plan=plan, already=already, flags=flags) + kb = [[Button.inline("▶️ Start copying", f"sfa:{token}"), Button.inline("✖️ Cancel", f"sfn:{token}")]] + await note.edit(plan_text(plan, src, dst, already, cfg.edit_delay, flags, others, info_right), buttons=kb) + + @on_cb(ctx, "sfn") + async def cb_cancel(event, parts): + require_owner(ctx, event) + ctx.pending.pop(parts[0], None) + await edit_callback_message(event, "Cancelled - nothing was copied.") + + # ------------------------------------------------------------------ copy + async def run_copy(event, sid: str, job: Optional[ShiftJob] = None) -> None: + sh = await db.get_shift(sid) + dst = await db.get_channel(sh.dst_channel_id) + if dst is None: + raise UserError("The destination channel is not registered any more.") + job = job or ShiftJob(user=event.sender_id, src=None, dst=None, plan=None) # type: ignore[arg-type] + job.running, job.stop, job.shift_id = True, False, sid + ctx.pending[f"job:{sid}"] = job + total = job.plan.units if job.plan else None + last = [0.0] + names = f"{esc(sh.src_title)} → {esc(dst.title)}" + + async def prog(res): + if res.phase in ("copy", "links") and time.monotonic() - last[0] < 4: + return + last[0] = time.monotonic() + done = res.copied_units + res.skipped_done + of = f"/{total}" if total else "" + if res.phase == "links" and res.cross is not None: + body = f"✅ Copied {done}{of} posts.\n" + progress_text(res.cross, title="Pointing links of your channels at the copies") + elif res.phase == "profile": + body = f"🖼 Copied {done}{of} posts. Now copying the name, description and photo of {esc(sh.src_title)}…" + elif res.phase == "finish": + body = f"🔗 Copied {done}{of} posts. Now pointing links at the new copies…" + else: + body = f"⏳ Shifting {names}: {done}{of} posts…\nThe source stays untouched." + body += hidden_progress(res) + try: + await edit_callback_message(event, body, [[Button.inline("⏹ Stop", f"sfs:{sid}")]]) + except errors.MessageNotModifiedError: + pass + except Exception: + log.debug("progress update failed", exc_info=True) + + try: + async with ctx.lock: + await db.set_shift_status(sid, "copying") + res = await run_shift( + client, db, sh, dst, event.sender_id, delay=cfg.edit_delay, progress=prog, should_stop=lambda: job.stop + ) + finally: + job.running = False + status = "stopped" if res.stopped else ("incomplete" if (res.failed or res.aborted or res.held_back) else "copied") + await db.set_shift_status(sid, status) + if res.hidden_stop: # stopped because Telegram hides the copies: pressing Continue means "go on anyway" + await db.set_mark(sid, "hiddenok") + sh = await db.get_shift(sid) + text, kb = await view_for(sh) + notes = [] + if res.copied_units: + notes.append(f"{res.forwarded} post(s) were copied by Telegram, {res.rebuilt} were posted again with their buttons.") + if res.repaired: + notes.append(f"{res.repaired} post(s) needed their buttons set again after posting - they show them now.") + if res.failed: + sample = ", ".join(f"#{i} {esc(n)}" for i, n in res.failed[:6]) + notes.append(f"{len(res.failed)} post(s) failed ({sample}{'…' if len(res.failed) > 6 else ''}).") + if any(n == "ButtonsNotShown" for _, n in res.failed): + notes.append( + "ButtonsNotShown: Telegram did not show the buttons on the new post, so that copy was removed again. " + "The original is untouched - use “Try the rest again”." + ) + if any(n == "ReplyParentMissing" for _, n in res.failed): + notes.append("ReplyParentMissing: that post answers a post whose copy failed; it follows when you try again.") + if res.aborted: + notes.append(f"Stopped early because of {esc(res.aborted)}.") + notes += finishing_notes(res, shift=True) + await edit_callback_message(event, text + ("\n\n" + "\n".join(notes) if notes else ""), kb) + + @on_cb(ctx, "sfa") + async def cb_start(event, parts): + require_owner(ctx, event) + job = ctx.pending.get(parts[0]) + if not isinstance(job, ShiftJob) or job.user != event.sender_id: + raise UserError("That plan has expired. Run /shift again.") + if job.running or ctx.lock.locked(): + raise UserError("A long job is already running.") + if await db.open_shift(job.src.id, job.dst.id) is not None: + raise UserError("There is already an unfinished shift between these two channels.") + rights = await get_rights(client, job.dst) + if rights is not None and not (rights.admin and rights.post): + raise UserError(f"The bot needs the “Post messages” admin right in {job.dst.title}.") + # the copies are registered in My posts, so the destination has to be one of the bot's channels + await db.save_channel(job.dst.id, job.dst.access_hash, job.dst.title, job.dst.username, event.sender_id) + sid = secrets.token_hex(6) + p = job.plan + await db.create_shift(sid, src=job.src, dst_channel_id=job.dst.id, first_id=p.first, last_id=p.last, user_id=event.sender_id) + if job.flags.links: + await db.set_mark(sid, "relink") + if job.flags.profile: + await db.set_mark(sid, "profile") + if job.flags.no_media: # continuing the shift later goes on without files as well + await db.set_mark(sid, "nomedia") + if p.from_db: # the source can't be read: continuing the shift goes on from My posts as well + await db.set_mark(sid, "fromdb") + ctx.pending.pop(parts[0], None) + await run_copy(event, sid, job) + + @on_cb(ctx, "sfc") + async def cb_continue(event, parts): + require_owner(ctx, event) + sh = await db.get_shift(parts[0]) + if sh is None or sh.status not in ("stopped", "incomplete", "copying"): + raise UserError("There is nothing to continue.") + if ctx.lock.locked(): + raise UserError("A long job is already running.") + await run_copy(event, sh.id) + + @on_cb(ctx, "sfs") + async def cb_stop(event, parts): + require_owner(ctx, event) + job = ctx.pending.get(f"job:{parts[0]}") + if isinstance(job, ShiftJob) and job.running: + job.stop = True + await event.respond("⏹ Stopping after the post that is being worked on…") + else: + await event.respond("Nothing is running.") + + # ------------------------------------------------------------ the extras again + @on_cb(ctx, "sfl") + async def cb_links(event, parts): + """-c once more: look through every connected channel for links to the source's posts.""" + require_owner(ctx, event) + sh, dst = await load(parts) + if sh.status != "copied": + raise UserError("Links can be updated once everything is copied.") + if ctx.lock.locked(): + raise UserError("A long job is already running.") + job = ShiftJob(user=event.sender_id, src=None, dst=None, plan=None, running=True, shift_id=sh.id) # type: ignore[arg-type] + ctx.pending[f"job:{sh.id}"] = job + cross, last = CrossResult(), [0.0] + + async def prog(c): + if time.monotonic() - last[0] < 4: + return + last[0] = time.monotonic() + try: + await edit_callback_message( + event, progress_text(c, title="Pointing links at the copies"), [[Button.inline("⏹ Stop", f"sfs:{sh.id}")]] + ) + except errors.MessageNotModifiedError: + pass + except Exception: + log.debug("progress update failed", exc_info=True) + + error = None + try: + async with ctx.lock: + await edit_callback_message(event, "🔗 Looking for links to the source's posts in your channels…") + await relink_after_shift( + client, db, sh, source_of(sh), dst, delay=cfg.edit_delay, progress=prog, + should_stop=lambda: job.stop, result=cross, + ) + except Exception as e: # the copies are fine; only the links were not (all) updated + log.exception("pointing the links at the shifted posts failed") + error = type(e).__name__ + finally: + job.running = False + ctx.pending.pop(f"job:{sh.id}", None) + notes = report_lines(cross, what=f"the copies in {esc(dst.title)}") + if error: + notes.append(f"Links could not be updated ({esc(error)}).") + if not notes: + notes.append("🔗 There is nothing to change.") + text, kb = await view_for(sh) + await edit_callback_message(event, text + "\n\n" + "\n".join(notes), kb) + + @on_cb(ctx, "sfp") + async def cb_profile(event, parts): + """-all once more: the name, description and photo of the source.""" + require_owner(ctx, event) + sh, dst = await load(parts) + if "profile" not in await db.marks_of(sh.id): + raise UserError("This shift was not started with -all.") + if sh.status not in ("copied", "stopped", "incomplete"): + raise UserError("There is nothing to copy it to any more.") + if ctx.lock.locked(): + raise UserError("A long job is already running.") + holder = RepostResult() + async with ctx.lock: + await edit_callback_message(event, f"🖼 Copying the name, description and photo of {esc(sh.src_title)}…") + await shift_profile(client, db, sh, dst, event.sender_id, holder) + dst = await db.get_channel(sh.dst_channel_id) or dst # it may have a new name now + notes = profile_lines(holder.profile, dst.title) if holder.profile is not None else [] + if holder.profile_error: + notes.append(f"The name, description and photo could not be copied ({esc(holder.profile_error)}).") + text, kb = await view_for(sh) + await edit_callback_message(event, text + "\n\n" + "\n".join(notes), kb) + + # ------------------------------------------------------------------ undo + async def load(parts): + sh = await db.get_shift(parts[0]) + if sh is None: + raise UserError("I don't know that shift any more.") + dst = await db.get_channel(sh.dst_channel_id) + if dst is None: + raise UserError("The destination channel is not registered any more.") + return sh, dst + + @on_cb(ctx, "sfb") + async def cb_back(event, parts): + sh, _ = await load(parts) + text, kb = await view_for(sh) + await edit_callback_message(event, text, kb) + + @on_cb(ctx, "sfu") + async def cb_undo_ask(event, parts): + require_owner(ctx, event) + sh, dst = await load(parts) + c = await db.shift_counts(sh.id) + if not c["new_left"]: + raise UserError("There is nothing to remove.") + await edit_callback_message( + event, + f"↩️ Remove the {c['new_left']} copied message(s) from {esc(dst.title)}?\n" + f"The posts in {esc(sh.src_title)} are not touched.", + [[Button.inline("↩️ Yes, remove the copies", f"sfuy:{sh.id}"), Button.inline("Back", f"sfb:{sh.id}")]], + ) + + @on_cb(ctx, "sfuy") + async def cb_undo(event, parts): + require_owner(ctx, event) + sh, dst = await load(parts) + if ctx.lock.locked(): + raise UserError("A long job is already running.") + fallback, deleter = await ctx.userbot.fallback_for(dst) if ctx.userbot is not None else (None, None) + back, last = CrossResult(), [0.0] + + async def prog(c): + if time.monotonic() - last[0] < 4: + return + last[0] = time.monotonic() + try: + await edit_callback_message(event, progress_text(c, title="Pointing links back at the source's posts")) + except Exception: + log.debug("progress update failed", exc_info=True) + + try: + async with ctx.lock: + try: # links that were pointed at the copies would be left without a post: point them back first + await restore_after_shift_undo(client, db, sh, source_of(sh), dst, delay=cfg.edit_delay, progress=prog, result=back) + except Exception: + log.exception("pointing the links back at the source's posts failed") + back.stopped = True + res = await delete_shift_copies(client, db, dst, sh, delay=0.5, fallback=fallback) + finally: + if deleter is not None: + await deleter.close() + link_notes = report_lines(back, back=True) + link_text = ("\n" + "\n".join(link_notes)) if link_notes else "" + if res.remaining == 0 and not res.error: + await db.set_shift_status(sh.id, "copies_deleted") + await edit_callback_message( + event, + f"↩️ Done. {res.deleted} copied message(s) removed from {esc(dst.title)}; the source was not touched.{link_text}", + ) + else: + why = esc(delete_problem_text(ctx.userbot, bot_error=res.error, fallback_error=res.fallback_error, tried=res.tried_userbot)) + await edit_callback_message( + event, + f"⚠️ Removed {res.deleted}, {res.remaining} copy/copies are still there. {why}{link_text}", + [[Button.inline("🔁 Try again", f"sfuy:{sh.id}")]], + ) + diff --git a/app/handlers/sync.py b/app/handlers/sync.py new file mode 100644 index 0000000000000000000000000000000000000000..b25616cf3bbe6b2a77fde54c327a4f81eea9f367 --- /dev/null +++ b/app/handlers/sync.py @@ -0,0 +1,223 @@ +"""/sync (owner only) and the live watch over the channels. + +The live part listens to Telegram's updates: a post deleted, edited or added in a connected channel is recorded in My +posts a few seconds later, and service messages ("pinned a message", "channel photo changed" ...) are deleted at once. +The same comparison runs on a timer for everything the bot was not there to see (SYNC_INTERVAL_MINUTES). +""" +from __future__ import annotations + +import logging +import re +import time +from typing import Optional + +from telethon import events, types + +from ..common import Ctx, UserError, cmd, guard, say +from ..sync_engine import SyncReport +from ..syncer import Syncer +from ..tgutil import esc +from .replace import pick_channels + +log = logging.getLogger(__name__) + +USAGE = ( + "Usage: /sync\n" + "Compares every channel with My posts right now: posts that were deleted or edited in the channel by someone else " + "are updated here (a post deleted in the channel leaves My posts), new posts that were not made with this bot are " + "added, and service messages (“pinned a message”, “channel photo changed” ...) that appeared meanwhile are deleted. " + "The posts that were in a channel before the bot was added are read into My posts too (a long channel takes a few " + "checks; /sync goes on where the last one stopped).\n" + "Options: --channel @name (only that channel), --history (read the channel's older posts " + "again and add the ones that are missing; posts you made the bot forget stay forgotten)." +) + + +def parse_sync_args(raw: str) -> tuple: + """(channel reference or None for every channel, read the older posts again) - ValueError for anything else.""" + toks = (raw or "").split() + ref: Optional[str] = None + history = False + i = 0 + while i < len(toks): + t = toks[i] + if t == "--channel" and i + 1 < len(toks): + ref = toks[i + 1] + i += 2 + elif t == "--history": + history = True + i += 1 + else: + raise ValueError(f"I don't know “{t}”.") + return ref, history + + +def ids_text(ids, limit: int = 8) -> str: + ids = sorted(ids) + shown = ", ".join(str(i) for i in ids[:limit]) + return shown + (f" and {len(ids) - limit} more" if len(ids) > limit else "") + + +def channel_block(rep: SyncReport) -> str: + lines = [f"{esc(rep.channel.title)}"] + if rep.error: + return "\n".join(lines + [f"⚠️ {esc(rep.error)}"]) + if rep.restricted_channel: + return "\n".join( + lines + + [ + f"🚫 Telegram has restricted this channel ({esc(rep.restricted_channel)}). Nothing was changed in My posts - " + "the saved posts stay exactly as they are, whatever the channel shows now." + ] + ) + nothing = True + if rep.first_look: + lines.append("👀 First look at this channel. From now on, posts made, edited or deleted outside this bot are recorded here.") + if rep.checked: + lines.append(f"✓ {rep.checked} saved post(s) compared with the channel") + if rep.deleted: + nothing = False + lines.append(f"🗑 {len(rep.deleted)} deleted in the channel → removed from My posts (message {ids_text(rep.deleted)})") + if rep.edited: + nothing = False + lines.append(f"✏️ {len(rep.edited)} edited in the channel → updated in My posts (message {ids_text(rep.edited)})") + if rep.adopted: + nothing = False + lines.append(f"➕ {len(rep.adopted)} new post(s) made outside the bot → added to My posts (message {ids_text(rep.adopted)})") + if rep.history_top: + if rep.imported: + nothing = False + skipped = f" ({rep.history_unsupported} of a kind My posts can't hold - poll, sticker ... - skipped)" if rep.history_unsupported else "" + if rep.history_done: + if rep.imported: + lines.append(f"📥 {rep.imported} older post(s), sent before the bot was added → added to My posts{skipped}") + else: + lines.append(f"📥 The older posts were looked through: nothing to add{skipped}") + else: + lines.append( + f"📥 Older posts: {rep.imported} added so far, read up to message {rep.history_to} of {rep.history_top}{skipped} - " + "the next check goes on, or send /sync again to go on right away" + ) + if rep.restricted: + nothing = False + lines.append( + f"🚫 {len(rep.restricted)} post(s) are held back by Telegram ({esc(rep.restricted_why or 'restricted')}) - " + f"left exactly as saved in My posts (message {ids_text(rep.restricted)})" + ) + if rep.refreshed: + lines.append(f"• {rep.refreshed} saved post(s) tidied up (spaces at the ends of the text)") + if rep.services_deleted: + nothing = False + lines.append(f"🧹 {rep.services_deleted} service message(s) deleted") + if rep.services_failed: + nothing = False + lines.append( + f"⚠️ {rep.services_failed} service message(s) could not be deleted ({esc(rep.services_error or 'refused')}) - " + "the bot needs the “Delete messages” right, and Telegram lets bots delete only recent messages" + ) + if rep.buttons_missing: + nothing = False + lines.append( + f"⚠️ {len(rep.buttons_missing)} saved post(s) show no buttons in the channel (message {ids_text(rep.buttons_missing)}). " + "The saved buttons were kept: /posts → the channel → 🔧 Check buttons puts them back" + ) + if rep.unsupported: + lines.append(f"• {rep.unsupported} new message(s) of a kind My posts can't hold (poll, sticker ...) were left alone") + fresh = len(rep.young) + len(rep.young_new) + if fresh: + lines.append(f"⏳ {fresh} too fresh to judge - the next check will see them") + if rep.changed_meanwhile: + lines.append(f"• {rep.changed_meanwhile} saved post(s) were changed through the bot meanwhile - left as they are") + if rep.anomaly: + nothing = False + lines.append(f"⚠️ {esc(rep.anomaly)}") + if rep.busy: + lines.append("⏸ A long job started, so this check stopped early.") + if nothing and not rep.busy and not rep.first_look: + lines.append("Everything matches.") + return "\n".join(lines) + + +def report_text(reports: list) -> str: + head = "🔄 Sync finished" + if not reports: + return head + "\nNothing to look at." + return head + "\n\n" + "\n\n".join(channel_block(r) for r in reports) + + +def channel_id_of(msg) -> Optional[int]: + peer = getattr(msg, "peer_id", None) + return peer.channel_id if isinstance(peer, types.PeerChannel) else None + + +def register(ctx: Ctx) -> None: + client, db = ctx.client, ctx.db + if ctx.syncer is None: + ctx.syncer = Syncer(ctx) + sy = ctx.syncer + + # ----------------------------------------------------------------------------------------- /sync + @client.on(cmd("sync", args=True)) + @guard(ctx, owner=True) + async def h_sync(event): + raw = (event.pattern_match.group(1) or "").strip() + try: + ref, history = parse_sync_args(raw) + chans = pick_channels(await db.list_channels(), ref) + except ValueError as e: + raise UserError(f"{e}\n\n" + re.sub(r"<[^>]+>", "", USAGE)) + if not chans: + raise UserError("No channels registered yet. Use /addchannel.") + if ctx.lock.locked(): + raise UserError("Another long job (replace, repost, shift ...) is still running - try again when it has finished.") + async with ctx.lock: + if history: + for ch in chans: + await db.reset_history(ch.id) + status = await say(event, f"🔄 Looking at {len(chans)} channel(s)…") + last = [0.0] + + async def prog(ch, rep) -> None: + now = time.monotonic() + if now - last[0] < 3: + return + last[0] = now + try: + await status.edit(f"🔄 {esc(ch.title)}: {rep.phase} (message {rep.scanned_to})…") + except Exception: + pass + + reports = await sy.run_all(chans, explicit=True, history=True if history else None, progress=prog) + await say(event, report_text(reports)) + + # ------------------------------------------------------------------- what Telegram tells while we run + @client.on(events.Raw(types.UpdateNewChannelMessage)) + async def on_channel_message(update): + try: + m = update.message + cid = channel_id_of(m) + if cid is None: + return + if isinstance(m, types.MessageService): + await sy.on_service(cid, m) + elif not isinstance(m, types.MessageEmpty): + sy.note_new(cid, m) + except Exception: + log.warning("could not handle a new channel message", exc_info=True) + + @client.on(events.Raw(types.UpdateEditChannelMessage)) + async def on_channel_edit(update): + try: + m = update.message + cid = channel_id_of(m) + if cid is not None and not isinstance(m, (types.MessageService, types.MessageEmpty)): + sy.note_edit(cid, m) + except Exception: + log.warning("could not handle an edited channel message", exc_info=True) + + @client.on(events.Raw(types.UpdateDeleteChannelMessages)) + async def on_channel_delete(update): + try: + await sy.note_deleted(update.channel_id, list(update.messages)) + except Exception: + log.warning("could not handle deleted channel messages", exc_info=True) diff --git a/app/handleswap.py b/app/handleswap.py new file mode 100644 index 0000000000000000000000000000000000000000..434540a5ed7eeb726ba96022d92de76383e024db --- /dev/null +++ b/app/handleswap.py @@ -0,0 +1,97 @@ +"""/handleswap: change a username written in a post - "@bro" -> "@sis" - and nothing else. + +Only usernames are touched: the words "@bro" in the text or caption (and in button names). Links, hyperlinks and the +links behind buttons are left exactly as they are, and so is "@bro" when it is part of a link or an e-mail address. +""" +from __future__ import annotations + +import copy +import re +from typing import Optional + +from telethon import types +from telethon.helpers import add_surrogate, del_surrogate + +from .linkswap import MsgChange, apply_span_replacements +from .richmsg import is_rich_message +from .tgutil import button_url, is_callback_button, with_text + +# a "@name" that follows one of these is part of something else: an e-mail (a@bro), a link (t.me/x@bro, ?u=@bro) ... +_NOT_BEFORE = r"\w@./=?&#%" +_PROTECTED = tuple( + getattr(types, n) for n in ("MessageEntityUrl", "MessageEntityTextUrl", "MessageEntityEmail") if hasattr(types, n) +) + + +def mention_regex(name: str): + """'@name' as a whole word (case does not matter): not '@name_bot', not 'x@name'.""" + return re.compile(rf"(? tuple: + """([(start, end)], skipped) - where '@name' stands in `sur` (UTF-16 units). Mentions that sit inside a link or a + hyperlink are not changed; `skipped` counts them.""" + guarded = [(e.offset, e.offset + e.length) for e in entities or [] if isinstance(e, _PROTECTED)] + spans, skipped = [], 0 + for m in mention_regex(name).finditer(sur): + s, e = m.span() + if any(gs < e and s < ge for gs, ge in guarded): + skipped += 1 + continue + spans.append((s, e)) + return spans, skipped + + +def compute_handle_changes(msg, old: str, new: str) -> tuple: + """(MsgChange or None, number of mentions skipped because they are part of a link) - same shape as + linkswap.compute_message_changes, so the /swap engine can apply it.""" + rich = is_rich_message(msg) # the text of a rich message is blocks: only its buttons are changed + text = "" if rich else (msg.message or "") + ents = [] if rich else list(msg.entities or []) + sur = add_surrogate(text) + spans, skipped = find_mention_spans(sur, ents, old) if text else ([], 0) + new_sur, new_ents = sur, [copy.copy(e) for e in ents] + if spans: + new_sur, new_ents = apply_span_replacements(sur, ents, [(s, e, "@" + new) for s, e in spans]) + + # the names on link buttons (their links stay) + new_markup: Optional[types.ReplyInlineMarkup] = None + n_btn, has_cb = 0, False + mk = msg.reply_markup + if isinstance(mk, types.ReplyInlineMarkup): + rx = mention_regex(old) + rows = [] + for row in mk.rows: + btns = [] + for b in row.buttons: + if button_url(b) is not None: + label, n = rx.subn("@" + new, getattr(b, "text", "") or "") + if n: + btns.append(with_text(b, label)) + n_btn += n + continue + elif is_callback_button(b): + has_cb = True + btns.append(b) + rows.append(types.KeyboardButtonRow(btns)) + if n_btn: + new_markup = types.ReplyInlineMarkup(rows) + + if not (spans or n_btn): + return None, skipped + return ( + MsgChange( + message_id=msg.id, + new_text=del_surrogate(new_sur), + new_entities=new_ents, + new_markup=new_markup, + text_changed=bool(spans), + entities_changed=bool(spans), + n_buttons=n_btn, + n_links=0, + n_typed=len(spans), + mine=bool(getattr(msg, "out", False)), + callbacks=has_cb, + ), + skipped, + ) diff --git a/app/health.py b/app/health.py new file mode 100644 index 0000000000000000000000000000000000000000..1bcd9c8573bcf05b40ba4ffb788938075b52e001 --- /dev/null +++ b/app/health.py @@ -0,0 +1,26 @@ +"""Optional tiny HTTP endpoint for hosts that insist on an open port (set PORT).""" +import asyncio +import logging + +log = logging.getLogger(__name__) + + +async def start_health_server(port: int): + async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + try: + await asyncio.wait_for(reader.read(1024), timeout=5) + except Exception: + pass + try: + writer.write(b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + await writer.drain() + finally: + writer.close() + + try: + server = await asyncio.start_server(handle, "0.0.0.0", port) + except OSError as e: # e.g. something else (python -m http.server) already uses the port + log.warning("could not open the health endpoint on :%s (%s) - continuing without it", port, e) + return None + log.info("health endpoint listening on :%s", port) + return server diff --git a/app/linkswap.py b/app/linkswap.py new file mode 100644 index 0000000000000000000000000000000000000000..a77c6d17a0fc4c003aebd85747d7fcb53ffc9ffb --- /dev/null +++ b/app/linkswap.py @@ -0,0 +1,236 @@ +"""Swap a username inside t.me links: button links, hyperlinks and typed links in message text. + +Only the username part of a link changes; everything after it (?start=...) is left untouched. +Offsets of message entities are UTF-16 based, so text is handled in Telethon's 'surrogate' form. +""" +from __future__ import annotations + +import copy +import re +from dataclasses import dataclass +from typing import Optional + +from telethon import types +from telethon.helpers import add_surrogate, del_surrogate + +from .richmsg import is_rich_message +from .tgutil import button_url, is_callback_button, with_url + +USERNAME_RX = re.compile(r"^[A-Za-z0-9_]{1,32}$") + + +def normalize_username(s: str) -> Optional[str]: + s = (s or "").strip() + m = re.match(r"(?i)^(?:https?://)?(?:t\.me|telegram\.me)/([A-Za-z0-9_]+)/?$", s) + if m: + s = m.group(1) + s = s.lstrip("@") + return s if USERNAME_RX.match(s) else None + + +# ------------------------------------------------------------------------------- urls +_HTTP_RX = re.compile( + r"^(?P
(?:https?://)?(?:www\.)?(?:t\.me|telegram\.me|telegram\.dog)/)(?P[A-Za-z0-9_]+)(?P[/?#].*)?$",
+    re.I | re.S,
+)
+_TG_RX = re.compile(r"^(?P
tg://resolve\?(?:[^#]*&)?domain=)(?P[A-Za-z0-9_]+)(?P[&#].*)?$", re.I | re.S)
+
+
+def _split(url: str):
+    for rx in (_HTTP_RX, _TG_RX):
+        m = rx.match(url)
+        if m:
+            return m
+    return None
+
+
+def _is_post_tail(tail: str) -> bool:
+    return bool(re.match(r"/\d", tail)) or bool(re.match(r"&post=\d", tail))
+
+
+def classify_url(url: str, old: str) -> Optional[str]:
+    """'link' (t.me/old?start=..), 'post' (t.me/old/123 - a channel post) or None."""
+    m = _split(url or "")
+    if not m or m.group("name").lower() != old.lower():
+        return None
+    return "post" if _is_post_tail(m.group("rest") or "") else "link"
+
+
+def swap_url(url: str, old: str, new: str) -> str:
+    m = _split(url or "")
+    if not m or m.group("name").lower() != old.lower():
+        return url
+    return url[: m.start("name")] + new + url[m.end("name"):]
+
+
+# ------------------------------------------------------------------- typed links in text
+def _typed_regexes(old: str) -> list:
+    n = re.escape(old)
+    return [
+        re.compile(
+            r"(?" + n + r")(?![A-Za-z0-9_])",
+            re.I,
+        ),
+        re.compile(r"(?" + n + r")(?![A-Za-z0-9_])", re.I),
+    ]
+
+
+def find_typed_spans(sur: str, old: str, include_posts: bool) -> tuple:
+    spans: list = []
+    skipped = 0
+    for rx in _typed_regexes(old):
+        for m in rx.finditer(sur):
+            s, e = m.span("name")
+            if _is_post_tail(sur[e:e + 8]) and not include_posts:
+                skipped += 1
+                continue
+            spans.append((s, e))
+    spans.sort()
+    return spans, skipped
+
+
+def apply_span_replacements(sur: str, entities: list, repls: list) -> tuple:
+    """repls: sorted, non-overlapping (start, end, new_text) in UTF-16 units.
+    Returns (new_text, new_entities) with every entity offset/length kept consistent."""
+    parts: list = []
+    last = 0
+    for s, e, nt in repls:
+        parts.append(sur[last:s])
+        parts.append(nt)
+        last = e
+    parts.append(sur[last:])
+    new_text = "".join(parts)
+
+    def mp(x: int) -> int:
+        acc = 0
+        for s, e, nt in repls:
+            if x >= e:
+                acc += len(nt) - (e - s)
+            elif x > s:
+                return s + acc + min(x - s, len(nt))
+            else:
+                break
+        return x + acc
+
+    out = []
+    for ent in entities:
+        cp = copy.copy(ent)
+        o = mp(ent.offset)
+        end = mp(ent.offset + ent.length)
+        cp.offset = o
+        cp.length = max(0, end - o)
+        out.append(cp)
+    return new_text, out
+
+
+# --------------------------------------------------------------------- whole message
+@dataclass
+class MsgChange:
+    message_id: int
+    new_text: str
+    new_entities: list
+    new_markup: Optional[types.ReplyInlineMarkup]
+    text_changed: bool
+    entities_changed: bool
+    n_buttons: int
+    n_links: int
+    n_typed: int
+    mine: bool
+    callbacks: bool
+
+
+def compute_message_changes(msg, old: str, new: str, *, include_typed: bool = True, include_posts: bool = False) -> tuple:
+    """Returns (MsgChange or None, number_of_skipped_post_links)."""
+    rich = is_rich_message(msg)  # the text of a rich message is blocks: only its buttons are changed
+    text = "" if rich else (msg.message or "")
+    ents = [] if rich else list(msg.entities or [])
+    skipped = 0
+    n_typed = n_links = n_btn = 0
+
+    # 1) links typed as plain text (this changes the text itself)
+    sur = add_surrogate(text)
+    new_sur = sur
+    new_ents = [copy.copy(e) for e in ents]
+    if include_typed and text:
+        spans, sk = find_typed_spans(sur, old, include_posts)
+        skipped += sk
+        if spans:
+            new_sur, new_ents = apply_span_replacements(sur, ents, [(s, e, new) for s, e in spans])
+            n_typed = len(spans)
+
+    # 2) hyperlinks (text with a link behind it)
+    for e in new_ents:
+        if isinstance(e, types.MessageEntityTextUrl):
+            kind = classify_url(e.url, old)
+            if kind == "link" or (kind == "post" and include_posts):
+                e.url = swap_url(e.url, old, new)
+                n_links += 1
+            elif kind == "post":
+                skipped += 1
+
+    # 3) buttons
+    new_markup = None
+    has_cb = False
+    mk = msg.reply_markup
+    if isinstance(mk, types.ReplyInlineMarkup):
+        rows = []
+        for row in mk.rows:
+            btns = []
+            for b in row.buttons:
+                url = button_url(b)
+                if url is not None:
+                    kind = classify_url(url, old)
+                    if kind == "link" or (kind == "post" and include_posts):
+                        btns.append(with_url(b, swap_url(url, old, new)))
+                        n_btn += 1
+                        continue
+                    if kind == "post":
+                        skipped += 1
+                elif is_callback_button(b):
+                    has_cb = True
+                btns.append(b)
+            rows.append(types.KeyboardButtonRow(btns))
+        if n_btn:
+            new_markup = types.ReplyInlineMarkup(rows)
+
+    if not (n_typed or n_links or n_btn):
+        return None, skipped
+    return (
+        MsgChange(
+            message_id=msg.id,
+            new_text=del_surrogate(new_sur),
+            new_entities=new_ents,
+            new_markup=new_markup,
+            text_changed=bool(n_typed),
+            entities_changed=bool(n_typed or n_links),
+            n_buttons=n_btn,
+            n_links=n_links,
+            n_typed=n_typed,
+            mine=bool(getattr(msg, "out", False)),
+            callbacks=has_cb,
+        ),
+        skipped,
+    )
+
+
+def url_only_markup(markup, old: Optional[str] = None, new: Optional[str] = None, include_posts: bool = False):
+    """Buttons for a copy of a post: link buttons only (other bots' buttons would be dead), with the username
+    swapped when `old`/`new` are given. Returns (markup or None, number_of_buttons_not_copied)."""
+    if not isinstance(markup, types.ReplyInlineMarkup):
+        return None, 0
+    rows, dropped = [], 0
+    for row in markup.rows:
+        btns = []
+        for b in row.buttons:
+            url = button_url(b)
+            if url is None:
+                dropped += 1
+                continue
+            if old and new:
+                kind = classify_url(url, old)
+                if kind == "link" or (kind == "post" and include_posts):
+                    b = with_url(b, swap_url(url, old, new))
+            btns.append(b)
+        if btns:
+            rows.append(types.KeyboardButtonRow(btns))
+    return (types.ReplyInlineMarkup(rows) if rows else None), dropped
diff --git a/app/picker.py b/app/picker.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4bf2a4ee504512634f6347bbac20a49f9c32e67
--- /dev/null
+++ b/app/picker.py
@@ -0,0 +1,104 @@
+"""The channel chooser used by every command that needs one of the connected channels.
+
+The names are written out in the message as a numbered list (A to Z, 20 to a page); the buttons only carry the numbers
+(5 to a row), and ◀ ▶ underneath move to the previous / next 20. Pressing "3" means the third name of the list.
+Each button carries the channel's id, never its position, so a list that changed meanwhile can't pick the wrong one.
+"""
+from __future__ import annotations
+
+import re
+from collections import Counter
+from typing import Callable, Optional, Sequence
+
+from telethon import Button
+
+from .tgutil import esc, short
+
+PER_PAGE = 20  # channel names in one message
+PER_ROW = 5  # number buttons in one row
+NAME_MAX = 60  # a longer name is cut in the list
+PAGE_CB = "cpg"  # callback prefix of the ◀ ▶ buttons: cpg:::
+
+_DIGITS = re.compile(r"(\d+)")
+
+
+def natural_key(title: Optional[str]) -> tuple:
+    """A to Z, numbers by value ("Anime 2" before "Anime 10"), upper and lower case alike."""
+    parts = _DIGITS.split(" ".join((title or "").split()).casefold())
+    return tuple((0, int(p), "") if p.isdigit() else (1, 0, p) for p in parts if p != "")
+
+
+def ordered(chans: Sequence) -> list:
+    """The channels in the order they are listed: by name, ascending (the id breaks ties)."""
+    return sorted(chans, key=lambda c: (natural_key(c.title), c.id))
+
+
+def page_count(total: int) -> int:
+    return max(1, -(-total // PER_PAGE))
+
+
+def clamp(page: int, total: int) -> int:
+    return max(0, min(int(page), page_count(total) - 1))
+
+
+def names_of(chans: Sequence, *, with_username: bool = False) -> list:
+    """Display names (not yet escaped). Two channels with the same name get their @username (or id) added."""
+    keys = [" ".join((c.title or "").split()).casefold() for c in chans]
+    twins = Counter(keys)
+    out = []
+    for c, key in zip(chans, keys):
+        name = short(c.title or "", NAME_MAX) or "Channel"
+        if with_username and c.username:
+            name += f" (@{c.username})"
+        elif twins[key] > 1:
+            name += f" (@{c.username})" if c.username else f" ({c.id})"
+        out.append(name)
+    return out
+
+
+def render(
+    chans: Sequence,
+    page: int,
+    *,
+    head: str,
+    kind: str,
+    arg: str = "",
+    choose: Optional[Callable] = None,
+    extra_rows: Sequence = (),
+    with_username: bool = False,
+    hint: Optional[str] = "Tap the number of the channel.",
+) -> tuple:
+    """(text, button rows) of one page.
+
+    head       the question, already HTML
+    kind, arg  which screen this is - the ◀ ▶ buttons carry them so the same screen can be drawn again
+    choose     channel -> callback data of its number button (None: a list to read, no number buttons)
+    extra_rows buttons under the arrows (Cancel ...)
+    hint       the line under the list that says what the number buttons do (None: leave it out)
+    """
+    chans = ordered(chans)
+    total = len(chans)
+    pages = page_count(total)
+    page = clamp(page, total)
+    first = page * PER_PAGE
+    shown = chans[first : first + PER_PAGE]
+    names = names_of(chans, with_username=with_username)[first : first + PER_PAGE]
+    lines = [f"{first + i}. {esc(name)}" for i, name in enumerate(names, 1)]
+    text = f"{head}\n\n" + "\n".join(lines)
+    if pages > 1:
+        text += f"\n\nPage {page + 1} of {pages} - channels {first + 1} to {first + len(shown)} of {total}"
+    if choose is not None and hint:
+        text += f"\n\n{hint}"
+    rows: list = []
+    if choose is not None:
+        nums = [Button.inline(str(first + i), choose(c)) for i, c in enumerate(shown, 1)]
+        rows += [nums[i : i + PER_ROW] for i in range(0, len(nums), PER_ROW)]
+    if pages > 1:  # always both arrows: on the first page ◀ goes to the last page, on the last page ▶ to the first
+        rows.append(
+            [
+                Button.inline("◀", f"{PAGE_CB}:{kind}:{arg}:{(page - 1) % pages}"),
+                Button.inline("▶", f"{PAGE_CB}:{kind}:{arg}:{(page + 1) % pages}"),
+            ]
+        )
+    rows += [list(r) for r in extra_rows]
+    return text, rows
diff --git a/app/postlinks.py b/app/postlinks.py
new file mode 100644
index 0000000000000000000000000000000000000000..471e4615aeda1998b06f1f651bdc2aecc7320cc1
--- /dev/null
+++ b/app/postlinks.py
@@ -0,0 +1,226 @@
+"""Links that point at other posts of the same channel (t.me/name/115, t.me/c/123456/115, tg://...&post=115).
+
+When a channel is reposted its posts get new message ids, so a link to post 115 has to point at the copy of post 115.
+Only the digits of the message id change; everything around them (?single, ?comment=3, the visible text) stays.
+Links can sit in three places: a hyperlink behind text, a link typed into the text, and a button.
+"""
+from __future__ import annotations
+
+import copy
+import re
+from dataclasses import dataclass, field
+from typing import Optional
+
+from telethon import types
+from telethon.helpers import add_surrogate, del_surrogate
+
+from .linkswap import apply_span_replacements
+from .richmsg import is_rich_message
+from .tgutil import button_url, with_url
+
+_HOST = r"(?:t\.me|telegram\.me|telegram\.dog)"
+_NAME = r"[A-Za-z][A-Za-z0-9_]{2,31}"
+# https://t.me/name/115   https://t.me/c/123456/115   (also t.me/s/name/115, the web preview)
+_WEB = re.compile(
+    rf"^(?:https?://)?(?:www\.)?{_HOST}/(?:s/)?(?Pc/(?P\d+)|(?P{_NAME}))/(?P\d+)(?![A-Za-z0-9_])", re.I
+)
+_TYPED = re.compile(
+    rf"(?resolve|privatepost)\?(?P[^#]*)", re.I)
+_POST_PARAM = re.compile(r"(?<=[?&])post=(\d+)")
+
+
+@dataclass(frozen=True)
+class Ref:
+    """A link to a post: which channel (username in lower case, or the numeric id) and where the id's digits sit."""
+
+    name: Optional[str]
+    cid: Optional[int]
+    msg_id: int
+    start: int  # the digits of the message id ...
+    end: int
+    seg_start: Optional[int] = None  # ... and the channel part in front of them ("name" or "c/123"); web links only
+
+
+def parse_ref(url: str) -> Optional[Ref]:
+    """What `url` points at, if it is a link to a post of some channel; None for every other link."""
+    url = url or ""
+    m = _WEB.match(url)
+    if m:
+        return Ref(
+            name=m.group("name").lower() if m.group("name") else None,
+            cid=int(m.group("cid")) if m.group("cid") else None,
+            msg_id=int(m.group("id")),
+            start=m.start("id"),
+            end=m.end("id"),
+            seg_start=m.start("seg"),
+        )
+    m = _TG.match(url)
+    if m:
+        params = dict(p.split("=", 1) for p in m.group("query").split("&") if "=" in p)
+        post = _POST_PARAM.search(url)
+        if post is None:
+            return None
+        if m.group("kind").lower() == "resolve" and re.fullmatch(r"[A-Za-z0-9_]+", params.get("domain", "")):
+            return Ref(params["domain"].lower(), None, int(post.group(1)), post.start(1), post.end(1))
+        if m.group("kind").lower() == "privatepost" and params.get("channel", "").isdigit():
+            return Ref(None, int(params["channel"]), int(post.group(1)), post.start(1), post.end(1))
+    return None
+
+
+@dataclass
+class PostLinks:
+    """The links that point into one channel, and where its posts went: `ids` maps old message id -> new one.
+
+    By default the copies are in the same channel (/repost): only the message id changes. With `target_id` the
+    copies are in another channel (/shift): the channel part of the link changes too."""
+
+    username: Optional[str]
+    channel_id: int
+    ids: dict = field(default_factory=dict)
+    target_username: Optional[str] = None
+    target_id: Optional[int] = None
+
+    @classmethod
+    def for_channel(cls, ch, ids: Optional[dict] = None) -> "PostLinks":
+        return cls(username=(ch.username or None), channel_id=int(ch.id), ids=ids if ids is not None else {})
+
+    # -------------------------------------------------------------------------------------- one url
+    def ref_of(self, url: str) -> Optional[Ref]:
+        """The reference in `url` if it points at a post of THIS channel."""
+        r = parse_ref(url)
+        if r is None:
+            return None
+        if r.name is not None and self.username and r.name == self.username.lower():
+            return r
+        if r.cid is not None and r.cid == self.channel_id:
+            return r
+        return None
+
+    def edit_of(self, url: str) -> Optional[tuple]:
+        """(start, end, new text) to apply to `url` so it points at the copy of its post; None if it stays as it is."""
+        r = self.ref_of(url)
+        if r is None or r.msg_id not in self.ids:
+            return None
+        new_id = str(self.ids[r.msg_id])
+        if self.target_id is None:
+            return r.start, r.end, new_id
+        if r.seg_start is None:  # tg:// links are not moved to another channel
+            return None
+        channel = self.target_username or f"c/{self.target_id}"
+        return r.seg_start, r.end, f"{channel}/{new_id}"
+
+    def remap_url(self, url: str) -> str:
+        e = self.edit_of(url)
+        return url if e is None else url[: e[0]] + e[2] + url[e[1] :]
+
+    # --------------------------------------------------------------------------------- whole message
+    def count(self, text: str, entities, markup) -> int:
+        """How many links in a message point at a post of this channel (whether or not the post has a new id)."""
+        n = 0
+        sur = add_surrogate(text or "")
+        for m in _TYPED.finditer(sur):
+            if self.ref_of(m.group(0)):
+                n += 1
+        for e in entities or []:
+            if isinstance(e, types.MessageEntityTextUrl) and self.ref_of(e.url):
+                n += 1
+        if isinstance(markup, types.ReplyInlineMarkup):
+            for row in markup.rows:
+                for b in row.buttons:
+                    u = button_url(b)
+                    if u is not None and self.ref_of(u):
+                        n += 1
+        return n
+
+    def remap_text(self, text: str, entities) -> tuple:
+        """-> (text, entities, typed_links_changed, hyperlinks_changed). Offsets of all entities stay right."""
+        ents = list(entities or [])
+        sur = add_surrogate(text or "")
+        repls = []
+        for m in _TYPED.finditer(sur):
+            e = self.edit_of(m.group(0))
+            if e is not None:
+                repls.append((m.start() + e[0], m.start() + e[1], e[2]))
+        if repls:
+            new_sur, new_ents = apply_span_replacements(sur, ents, repls)
+        else:
+            new_sur, new_ents = sur, [copy.copy(e) for e in ents]
+        hyper = 0
+        for e in new_ents:
+            if isinstance(e, types.MessageEntityTextUrl):
+                new_url = self.remap_url(e.url)
+                if new_url != e.url:
+                    e.url = new_url
+                    hyper += 1
+        return del_surrogate(new_sur), new_ents, len(repls), hyper
+
+    def remap_markup(self, markup) -> tuple:
+        """-> (markup, buttons_changed); the keyboard object is only rebuilt when a button changes."""
+        if not isinstance(markup, types.ReplyInlineMarkup):
+            return markup, 0
+        rows, changed = [], 0
+        for row in markup.rows:
+            btns = []
+            for b in row.buttons:
+                u = button_url(b)
+                new = self.remap_url(u) if u is not None else None
+                if new is not None and new != u:
+                    btns.append(with_url(b, new))
+                    changed += 1
+                else:
+                    btns.append(b)
+            rows.append(types.KeyboardButtonRow(btns))
+        return (types.ReplyInlineMarkup(rows) if changed else markup), changed
+
+
+@dataclass
+class Relinked:
+    """A message whose links to other posts of the channel were pointed at the copies."""
+
+    text: str
+    entities: list
+    markup: Optional[types.ReplyInlineMarkup]
+    text_changed: bool  # the text or its entities differ
+    markup_changed: bool
+    n_typed: int
+    n_hyper: int
+    n_buttons: int
+
+    @property
+    def links(self) -> int:
+        return self.n_typed + self.n_hyper + self.n_buttons
+
+
+def relink_message(msg, links: PostLinks) -> Optional[Relinked]:
+    """The new text / entities / buttons of `msg` once its links are remapped; None when nothing changes."""
+    if is_rich_message(msg):  # the text of a rich message is blocks: only its buttons are changed
+        text, entities, n_typed, n_hyper = "", [], 0, 0
+    else:
+        text, entities, n_typed, n_hyper = links.remap_text(msg.message or "", msg.entities)
+    markup, n_buttons = links.remap_markup(msg.reply_markup)
+    if not (n_typed or n_hyper or n_buttons):
+        return None
+    return Relinked(
+        text=text,
+        entities=entities,
+        markup=markup,
+        text_changed=bool(n_typed or n_hyper),
+        markup_changed=bool(n_buttons),
+        n_typed=n_typed,
+        n_hyper=n_hyper,
+        n_buttons=n_buttons,
+    )
+
+
+def resolve_chain(step: dict) -> dict:
+    """Several reposts in a row: {1: 5, 5: 9} -> {1: 9, 5: 9} (a post that moved twice points at its latest copy)."""
+    out = {}
+    for old in step:
+        cur, seen = old, 0
+        while cur in step and seen < 100:
+            cur, seen = step[cur], seen + 1
+        out[old] = cur
+    return out
diff --git a/app/profile_copy.py b/app/profile_copy.py
new file mode 100644
index 0000000000000000000000000000000000000000..12338365e74a9d1bca74e6d28579ceffbe40825e
--- /dev/null
+++ b/app/profile_copy.py
@@ -0,0 +1,170 @@
+"""/shift -all: the destination channel gets the name, description and profile photo of the source channel.
+
+Each part is done on its own, so one that fails (a missing admin right, a photo Telegram refuses) does not stop the
+others. A part the source does not have (no description, no photo) is left as it is in the destination: nothing is ever
+wiped. The notices Telegram adds to a channel when its name or photo changes are deleted again right away.
+"""
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass, field
+from types import SimpleNamespace
+from typing import Optional
+
+from telethon import errors, functions, types
+
+from .repost_engine import delete_ids, new_messages_from
+from .tgutil import esc, flood_retry, peer_of
+
+log = logging.getLogger(__name__)
+
+PARTS = ("name", "description", "photo")
+LABELS = {"name": "Name", "description": "Description", "photo": "Profile photo"}
+NEEDS_RIGHT = "the bot needs the “Change channel info” admin right in the destination"
+
+
+@dataclass
+class ProfileResult:
+    """What happened to each part: part -> (status, detail). Status: done | same | none | failed."""
+
+    outcome: dict = field(default_factory=dict)
+    title: Optional[str] = None  # the destination's name after the run (None: it did not change)
+
+    @property
+    def ok(self) -> bool:
+        return all(s != "failed" for s, _ in self.outcome.values())
+
+    @property
+    def done(self) -> list:
+        return [p for p in PARTS if self.outcome.get(p, ("", ""))[0] == "done"]
+
+    @property
+    def failed(self) -> list:
+        return [(p, d) for p in PARTS for s, d in [self.outcome.get(p, ("", ""))] if s == "failed"]
+
+
+def _real(photo):
+    return None if photo is None or isinstance(photo, types.PhotoEmpty) else photo
+
+
+async def read_profile(client, ch) -> SimpleNamespace:
+    """The name, the description and the profile photo a channel shows right now."""
+    full = await flood_retry(lambda: client(functions.channels.GetFullChannelRequest(peer_of(ch))))
+    chat = next((c for c in getattr(full, "chats", None) or [] if getattr(c, "id", None) == ch.id), None)
+    fc = full.full_chat
+    return SimpleNamespace(
+        title=getattr(chat, "title", None), about=getattr(fc, "about", None) or "", photo=_real(getattr(fc, "chat_photo", None))
+    )
+
+
+def _failure(e: BaseException) -> str:
+    name = type(e).__name__
+    if name == "ChatAdminRequiredError":
+        return NEEDS_RIGHT
+    return name
+
+
+async def _set_name(client, dst, title: str) -> tuple:
+    try:
+        out = await flood_retry(lambda: client(functions.channels.EditTitleRequest(channel=peer_of(dst), title=title)))
+    except errors.ChatNotModifiedError:
+        return "same", ""
+    except errors.RPCError as e:
+        return "failed", _failure(e)
+    await _drop_notices(client, dst, out)
+    return "done", title
+
+
+async def _set_description(client, dst, about: str) -> tuple:
+    try:
+        await flood_retry(lambda: client(functions.messages.EditChatAboutRequest(peer=peer_of(dst), about=about)))
+    except (errors.ChatAboutNotModifiedError, errors.ChatNotModifiedError):
+        return "same", ""
+    except errors.RPCError as e:
+        return "failed", _failure(e)
+    return "done", ""
+
+
+async def _set_photo(client, dst, photo) -> tuple:
+    try:
+        data = await client.download_media(photo, file=bytes)
+        if not data:
+            return "failed", "the photo could not be downloaded"
+        uploaded = await client.upload_file(data, file_name="channel_photo.jpg")
+        out = await flood_retry(
+            lambda: client(
+                functions.channels.EditPhotoRequest(channel=peer_of(dst), photo=types.InputChatUploadedPhoto(file=uploaded))
+            )
+        )
+    except errors.ChatNotModifiedError:
+        return "same", ""
+    except errors.RPCError as e:
+        return "failed", _failure(e)
+    except Exception as e:  # a download or upload problem is not a reason to stop the shift
+        log.warning("copying the profile photo failed: %s %s", type(e).__name__, e)
+        return "failed", type(e).__name__
+    await _drop_notices(client, dst, out)
+    return "done", ""
+
+
+async def _drop_notices(client, ch, result) -> None:
+    """Remove the "channel name / photo changed" notices Telegram put into the channel."""
+    ids = [m.id for m in new_messages_from(result) if isinstance(m, types.MessageService)]
+    if ids:
+        await delete_ids(client, peer_of(ch), ids)
+
+
+async def copy_profile(client, src, dst) -> ProfileResult:
+    """Give `dst` the name, the description and the profile photo of `src`. Nothing is wiped: a part that the source
+    does not have stays as the destination has it. Both arguments need `id` and `access_hash`."""
+    res = ProfileResult()
+    try:
+        s = await read_profile(client, src)
+    except errors.RPCError as e:
+        for p in PARTS:
+            res.outcome[p] = ("failed", f"the source can't be read ({type(e).__name__})")
+        return res
+    try:
+        d = await read_profile(client, dst)
+    except errors.RPCError:
+        d = SimpleNamespace(title=None, about=None, photo=None)  # unknown: every part is simply tried
+
+    if not s.title:
+        res.outcome["name"] = ("none", "")
+    elif s.title == d.title:
+        res.outcome["name"] = ("same", "")
+    else:
+        res.outcome["name"] = await _set_name(client, dst, s.title)
+        if res.outcome["name"][0] == "done":
+            res.title = s.title
+
+    if not s.about:
+        res.outcome["description"] = ("none", "")
+    elif s.about == d.about:
+        res.outcome["description"] = ("same", "")
+    else:
+        res.outcome["description"] = await _set_description(client, dst, s.about)
+
+    if s.photo is None:
+        res.outcome["photo"] = ("none", "")
+    else:
+        res.outcome["photo"] = await _set_photo(client, dst, s.photo)
+    return res
+
+
+def profile_lines(res: ProfileResult, dst_title: str = "") -> list:
+    """Lines (HTML) about what was copied, for the end of a shift."""
+    shown = {"done": "copied", "same": "already the same", "none": "the source has none - left as it is"}
+    parts, bad = [], []
+    for p in PARTS:
+        status, detail = res.outcome.get(p, ("", ""))
+        if status == "failed":
+            bad.append(f"{LABELS[p]}: {esc(detail)}")
+        elif status:
+            parts.append(f"{LABELS[p].lower()} {shown[status]}")
+    out = []
+    if parts:
+        out.append("🖼 " + ("" + esc(dst_title) + ": " if dst_title else "") + ", ".join(parts) + ".")
+    if bad:
+        out.append("⚠️ Not copied - " + "; ".join(bad) + ".")
+    return out
diff --git a/app/replace_engine.py b/app/replace_engine.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ba208b6e0737595e059f497df00fd9509481a03
--- /dev/null
+++ b/app/replace_engine.py
@@ -0,0 +1,343 @@
+"""/swap engine: scan channels message by message, rewrite links, log every change, undo."""
+from __future__ import annotations
+
+import asyncio
+import logging
+from dataclasses import dataclass, field
+from typing import Any, Awaitable, Callable, Optional
+
+from telethon import errors, functions, types
+
+from .handleswap import compute_handle_changes
+from .linkswap import compute_message_changes
+from .richmsg import entry as rich_entry, is_rich_message, plain_of_message, rich_from_received, rich_of
+from .tgutil import (
+    build_markup,
+    de_entities,
+    edit_raw,
+    flood_retry,
+    media_info,
+    peer_of,
+    ser_entities,
+    ser_markup,
+    state_of,
+)
+
+log = logging.getLogger(__name__)
+
+CHUNK = 100  # Telegram returns at most 100 messages per request
+FALLBACK_EMPTY_BATCHES = 15  # used only when the newest message id can't be determined
+ABORT_AFTER = 5  # stop a channel after this many identical Telegram refusals in a row
+
+
+@dataclass
+class ScanOptions:
+    old: str
+    new: str
+    include_typed: bool = True
+    include_posts: bool = False
+    last: Optional[int] = None
+    mode: str = "links"  # "links": the username inside t.me links (/swap); "handles": '@name' written in a post (/handleswap)
+
+
+def compute_changes(m, opts: ScanOptions) -> tuple:
+    """What this run would change in message `m`: (MsgChange or None, skipped)."""
+    if opts.mode == "handles":
+        return compute_handle_changes(m, opts.old, opts.new)
+    return compute_message_changes(
+        m, opts.old, opts.new, include_typed=opts.include_typed, include_posts=opts.include_posts
+    )
+
+
+@dataclass
+class ChangeInfo:
+    message_id: int
+    buttons: int = 0
+    links: int = 0
+    typed: int = 0
+    mine: bool = False
+    callbacks: bool = False
+
+
+@dataclass
+class ChannelScan:
+    channel: Any
+    can_edit_others: bool = True
+    top: int = 0
+    first: int = 1
+    scanned: int = 0
+    infos: dict = field(default_factory=dict)
+    skipped_post_links: int = 0
+    not_editable: int = 0
+    error: Optional[str] = None
+    rights: Any = None
+
+    @property
+    def total(self) -> int:
+        return len(self.infos)
+
+    @property
+    def foreign(self) -> int:
+        return sum(1 for i in self.infos.values() if not i.mine)
+
+
+@dataclass
+class ApplyResult:
+    edited: int = 0
+    unchanged: int = 0
+    missing: int = 0
+    no_perm: int = 0
+    failed: list = field(default_factory=list)
+    aborted: Optional[str] = None  # error name that made us stop early
+
+
+@dataclass
+class UndoResult:
+    restored: int = 0
+    failed: list = field(default_factory=list)
+
+
+async def fetch_messages(client, peer, ids: list) -> list:
+    res = await flood_retry(lambda: client.get_messages(peer, ids=ids))
+    return list(res)
+
+
+async def get_top_id(client, peer) -> Optional[int]:
+    """Upper bound for the newest message id: the channel's event counter (pts) is never lower."""
+    try:
+        full = await flood_retry(lambda: client(functions.channels.GetFullChannelRequest(peer)))
+        pts = getattr(full.full_chat, "pts", None)
+        if pts:
+            return int(pts)
+    except Exception as e:
+        log.info("could not read channel counter: %s", e)
+    return None
+
+
+def is_skippable(m) -> bool:
+    return m is None or isinstance(m, (types.MessageEmpty, types.MessageService))
+
+
+async def scan_channel(
+    client,
+    ch,
+    opts: ScanOptions,
+    *,
+    can_edit_others: bool = True,
+    mine_ids: Optional[set] = None,
+    progress: Optional[Callable[[ChannelScan], Awaitable[None]]] = None,
+) -> ChannelScan:
+    scan = ChannelScan(channel=ch, can_edit_others=can_edit_others)
+    peer = peer_of(ch)
+    mine_ids = mine_ids or set()
+    top = await get_top_id(client, peer)
+    first = 1
+    if opts.last and top:
+        first = max(1, top - opts.last + 1)
+    scan.first, scan.top = first, top or 0
+    a, empty_run = first, 0
+    while True:
+        if top is not None and a > top:
+            break
+        hi = a + CHUNK - 1 if top is None else min(a + CHUNK - 1, top)
+        msgs = await fetch_messages(client, peer, list(range(a, hi + 1)))
+        found = False
+        for m in msgs:
+            if m is None or isinstance(m, types.MessageEmpty):
+                continue
+            found = True
+            if isinstance(m, types.MessageService):
+                continue
+            change, skipped = compute_changes(m, opts)
+            scan.skipped_post_links += skipped
+            if not change:
+                continue
+            mine = change.mine or m.id in mine_ids
+            if not mine and not can_edit_others:
+                scan.not_editable += 1
+                continue
+            scan.infos[m.id] = ChangeInfo(
+                m.id, change.n_buttons, change.n_links, change.n_typed, mine, change.callbacks
+            )
+        scan.scanned = hi
+        if top is None:
+            empty_run = 0 if found else empty_run + 1
+            if empty_run >= FALLBACK_EMPTY_BATCHES:
+                break
+        if progress:
+            await progress(scan)
+        a = hi + 1
+    if top is None:
+        scan.top = scan.scanned
+    return scan
+
+
+def preview_flag(m):
+    if isinstance(m.media, types.MessageMediaWebPage):
+        return True
+    return False if m.media is None else None
+
+
+async def _do_edit(client, peer, m, change, markup, preview) -> None:
+    if change.text_changed or change.entities_changed:
+        await edit_raw(
+            client, peer, m.id, text=change.new_text, entities=change.new_entities, markup=markup, preview=preview
+        )
+    else:  # only button links changed: leave the text untouched
+        await edit_raw(client, peer, m.id, markup=markup)
+
+
+async def apply_channel(
+    client,
+    db,
+    scan: ChannelScan,
+    opts: ScanOptions,
+    batch_id: str,
+    user_id: int,
+    *,
+    edit_delay: float = 1.2,
+    progress: Optional[Callable[[ApplyResult], Awaitable[None]]] = None,
+) -> ApplyResult:
+    ch = scan.channel
+    peer = peer_of(ch)
+    mine_ids = await db.mine_message_ids(ch.id)
+    res = ApplyResult()
+    ids = sorted(scan.infos)
+    buf: list = []
+    streak, last_name = 0, None
+
+    async def flush() -> None:
+        nonlocal buf
+        if buf:
+            batch, buf = buf, []
+            await db.record_changes(batch_id, ch.id, batch, user_id)
+
+    try:
+        for i in range(0, len(ids), CHUNK):
+            chunk = ids[i:i + CHUNK]
+            msgs = await fetch_messages(client, peer, chunk)
+            for mid, m in zip(chunk, msgs):
+                if is_skippable(m):
+                    res.missing += 1
+                    continue
+                # re-check against the live message: it may have been edited since the scan
+                change, _ = compute_changes(m, opts)
+                if not change:
+                    res.unchanged += 1
+                    continue
+                if not (change.mine or m.id in mine_ids) and not scan.can_edit_others:
+                    res.no_perm += 1
+                    continue
+                preview = preview_flag(m)
+                markup = change.new_markup if change.new_markup is not None else m.reply_markup
+                old_state = state_of(m.message, m.entities, m.reply_markup, preview)
+                rich = is_rich_message(m)
+                if rich:  # its text is blocks this run never touches: undo puts the buttons back and nothing else
+                    old_state["rich"] = True
+                try:
+                    await flood_retry(lambda: _do_edit(client, peer, m, change, markup, preview))
+                except errors.MessageNotModifiedError:
+                    res.unchanged += 1
+                    continue
+                except errors.RPCError as e:
+                    name = type(e).__name__
+                    log.warning("edit of %s/%s failed: %s", ch.id, m.id, name)
+                    res.failed.append((m.id, name))
+                    streak = streak + 1 if name == last_name else 1
+                    last_name = name
+                    if streak >= ABORT_AFTER:
+                        res.aborted = name
+                        break
+                    continue
+                streak, last_name = 0, None
+                res.edited += 1
+                kind, fid = media_info(m)
+                adopt = {
+                    "text": change.new_text,
+                    "entities": ser_entities(change.new_entities),
+                    "buttons": ser_markup(markup),
+                    "link_preview": bool(preview),
+                }
+                if kind:
+                    adopt["media_kind"], adopt["media_file_id"] = kind, fid
+                new_state = state_of(change.new_text, change.new_entities, markup, preview)
+                if rich:
+                    new_state["rich"] = True
+                    saved = await db.find_by_message(ch.id, m.id)
+                    if saved is not None and rich_of(saved) is not None:
+                        del adopt["text"], adopt["entities"]  # the saved copy keeps what it was sent from
+                    else:  # a rich message nobody saved yet: it is taken over as its blocks
+                        adopt["text"] = plain_of_message(m)
+                        adopt["entities"] = [rich_entry(rich_from_received(m.rich_message))]
+                buf.append(
+                    {
+                        "message_id": m.id,
+                        "old_state": old_state,
+                        "new_state": new_state,
+                        "adopt": adopt,
+                    }
+                )
+                if len(buf) >= 10:
+                    await flush()
+                if progress:
+                    await progress(res)
+                await asyncio.sleep(edit_delay)
+            if res.aborted:
+                break
+    finally:
+        await flush()
+    return res
+
+
+async def undo_batch(
+    client,
+    db,
+    batch_id: str,
+    *,
+    edit_delay: float = 1.2,
+    progress: Optional[Callable[[UndoResult], Awaitable[None]]] = None,
+) -> UndoResult:
+    """Put every post touched by a /swap run back exactly as it was."""
+    res = UndoResult()
+    channels: dict = {}
+    done_ids: list = []
+    restored: list = []
+    for c in await db.batch_changes(batch_id):
+        if c.channel_id not in channels:
+            channels[c.channel_id] = await db.get_channel(c.channel_id)
+        ch = channels[c.channel_id]
+        if ch is None:
+            res.failed.append((c.message_id, "ChannelRemoved"))
+            continue
+        old = c.old_state or {}
+        try:
+            if old.get("rich"):  # a rich message: only its buttons were changed, so only they are put back
+                markup = build_markup(old.get("buttons"))
+                if markup is not None:
+                    await flood_retry(lambda: edit_raw(client, peer_of(ch), c.message_id, markup=markup))
+            else:
+                await flood_retry(
+                    lambda: edit_raw(
+                        client,
+                        peer_of(ch),
+                        c.message_id,
+                        text=old.get("text", ""),
+                        entities=de_entities(old.get("entities")),
+                        markup=build_markup(old.get("buttons")),
+                        preview=old.get("preview"),
+                    )
+                )
+        except errors.MessageNotModifiedError:
+            pass
+        except errors.RPCError as e:
+            log.warning("undo of %s/%s failed: %s", c.channel_id, c.message_id, e)
+            res.failed.append((c.message_id, type(e).__name__))
+            continue
+        res.restored += 1
+        done_ids.append(c.id)
+        restored.append((c.channel_id, c.message_id, old))
+        if progress:
+            await progress(res)
+        await asyncio.sleep(edit_delay)
+    await db.finish_undo(batch_id, done_ids, restored, all_done=not res.failed)
+    return res
diff --git a/app/repost_engine.py b/app/repost_engine.py
new file mode 100644
index 0000000000000000000000000000000000000000..63903fc2d18053a0b030f48fb5e7b0d59b337b32
--- /dev/null
+++ b/app/repost_engine.py
@@ -0,0 +1,1372 @@
+"""Repost a whole channel in order.
+
+Every post is copied to the end of the channel (silently), in the same order as the original:
+  1. a post that needs no change (no buttons, no link to swap) is copied by Telegram itself
+     (messages.forwardMessages with drop_author): text, formatting, quotes, media and albums stay exact;
+  2. a post with buttons, or with links to swap, is created again in ONE request that carries its final
+     text, formatting and buttons - exactly how the bot publishes a post of its own - and is then read back
+     to make sure the buttons really are there (a copy that is edited afterwards can end up without them);
+  3. if the channel forbids forwarding, every post is created like in 2.
+Links can be swapped on the way, the new posts are registered in the database, and the old posts are removed
+later in a separate step. Nothing here deletes anything unless asked to (delete_copies).
+
+What a plain copy would lose is put back as well:
+  * a post that answers another post is posted as an answer to the COPY of that post (a reply can only be set
+    when a post is created, so such a post is always created again instead of copied);
+  * a link to another post of the channel (t.me/name/115) is pointed at the copy of that post - at once when the
+    copy already exists, afterwards (finalize_repost) for posts that are copied later;
+  * a post that was pinned has its copy pinned at the end.
+
+A post that TELEGRAM restricts (a copyright strike: the whole channel is "unavailable due to copyright infringement",
+or the post carries a restriction mark, or Telegram's apps show "This message couldn't be displayed on your device due
+to copyright infringement" instead of the post) is not copied as Telegram hands it out now. /shift rebuilds such a post
+from what My posts saved of it (text, formatting, buttons, media) - for a restricted CHANNEL every post that has a saved
+copy, however intact Telegram's version looks. A post without a saved copy is copied as Telegram hands it out when that
+is the post itself, and skipped (and reported) when it is only Telegram's notice. Telegram's notice is never posted, from
+whichever source. /repost leaves a post whose content Telegram holds back alone.
+Every copy of a restricted source is read back: if Telegram itself hides the new post, that is reported (copy_loop).
+"""
+from __future__ import annotations
+
+import asyncio
+import copy
+import logging
+from dataclasses import dataclass, field
+from typing import Any, AsyncIterator, Awaitable, Callable, Optional
+
+from telethon import errors, functions, types, utils
+
+from .buttons_sync import ButtonsNotShown, ensure_markup, link_urls
+from .crosslinks import CrossResult, relink_after_repost
+from .linkswap import compute_message_changes, url_only_markup
+from .postlinks import PostLinks, relink_message
+from .replace_engine import CHUNK, FALLBACK_EMPTY_BATCHES, fetch_messages, is_skippable, preview_flag
+from .restrictions import PLACEHOLDER_NOTE, is_placeholder_text, message_restriction, probe_channel
+from .richmsg import Rich, entry as rich_entry, is_rich_message, plain_of, rich_from_received, rich_of, with_rich
+from .tgutil import (
+    FATAL,
+    build_markup,
+    classify_media,
+    de_entities,
+    edit_raw,
+    flood_retry,
+    media_from_ref,
+    media_ref,
+    peer_of,
+    ser_entities,
+    ser_markup,
+)
+
+log = logging.getLogger(__name__)
+
+ABORT_AFTER = 8  # consecutive posts that could not be copied -> stop
+
+
+@dataclass
+class RepostOptions:
+    old: Optional[str] = None
+    new: Optional[str] = None
+    include_typed: bool = True
+    include_posts: bool = False
+    last: Optional[int] = None  # trial run: only the newest N post ids
+
+    @property
+    def swaps(self) -> bool:
+        return bool(self.old and self.new)
+
+
+@dataclass
+class Final:
+    """What a copy of a post should look like."""
+
+    text: str
+    entities: list
+    markup: Optional[types.ReplyInlineMarkup]
+    preview: Optional[bool]
+    text_changed: bool
+    n_buttons: int = 0
+    n_links: int = 0
+    n_typed: int = 0
+    dropped: int = 0  # other bots' buttons that are not copied
+    n_post_links: int = 0  # links to other posts of the same channel (whatever their new id will be)
+    n_relinked: int = 0  # of those, how many were already pointed at a copy
+    rich: Optional[Rich] = None  # the post is a rich message: this is what the copy is made from (text / entities are empty)
+
+
+def rich_for(src) -> Optional[Rich]:
+    """The rich message that `src` is - a live post, or a stand-in made from a saved post - or None for an ordinary post."""
+    saved = getattr(src, "rich_saved", None)
+    if saved is not None:
+        return saved
+    rm = getattr(src, "rich_message", None)
+    return rich_from_received(rm) if rm is not None else None
+
+
+def final_state(src, opts: RepostOptions, links: Optional[PostLinks] = None) -> Final:
+    """What the copy of `src` should look like. `links` (optional) points links to other posts of the channel at
+    the copies that exist so far (links.ids: old message id -> new one)."""
+    change = None
+    if opts.swaps:
+        change, _ = compute_message_changes(
+            src, opts.old, opts.new, include_typed=opts.include_typed, include_posts=opts.include_posts
+        )
+    rich = rich_for(src)
+    text = change.new_text if change else (src.message or "")
+    entities = list(change.new_entities) if change else list(src.entities or [])
+    if rich is not None:  # a rich message's text is blocks: nothing of it is changed here, only its buttons
+        text, entities = "", []
+    # text mentions need an access hash to be re-sent; they are rare in channel posts
+    entities = [e for e in entities if not isinstance(e, types.MessageEntityMentionName)]
+    markup, dropped = url_only_markup(
+        src.reply_markup, opts.old if opts.swaps else None, opts.new if opts.swaps else None, opts.include_posts
+    )
+    n_post_links = n_relinked = 0
+    text_changed = bool(change and change.entities_changed)
+    if links is not None:
+        n_post_links = links.count(text, entities, markup)
+        if n_post_links and links.ids:
+            text, entities, n_typed, n_hyper = links.remap_text(text, entities)
+            markup, n_buttons = links.remap_markup(markup)
+            n_relinked = n_typed + n_hyper + n_buttons
+            text_changed = text_changed or bool(n_typed or n_hyper)
+    # Send exactly what is saved: go through the stored form that "My posts" also uses to build its edits.
+    markup = build_markup(ser_markup(markup)) if markup is not None else None
+    entities = de_entities(ser_entities(entities))
+    return Final(
+        text=text,
+        entities=entities,
+        markup=markup,
+        preview=preview_flag(src),
+        text_changed=text_changed,
+        n_buttons=change.n_buttons if change else 0,
+        n_links=change.n_links if change else 0,
+        n_typed=change.n_typed if change else 0,
+        dropped=dropped,
+        n_post_links=n_post_links,
+        n_relinked=n_relinked,
+        rich=rich,
+    )
+
+
+# ---------------------------------------------------------------------------- replies and pins
+class ReplyParentMissing(RuntimeError):
+    """A post answers another post whose copy does not exist (yet): copying it now would lose the answer."""
+
+
+def reply_parent(msg) -> Optional[int]:
+    """The message id a post answers (in the same channel), or None."""
+    h = getattr(msg, "reply_to", None)
+    if h is None or getattr(h, "reply_to_peer_id", None) is not None or getattr(h, "forum_topic", None):
+        return None
+    return getattr(h, "reply_to_msg_id", None) or None
+
+
+def new_parent(msg, idmap: dict, seen: set) -> Optional[int]:
+    """The copy of the post `msg` answers. None when it answers nothing, or the post it answered is gone / outside
+    the range being copied. Raises ReplyParentMissing when that post was read in this run but has no copy."""
+    pid = reply_parent(msg)
+    if pid is None:
+        return None
+    if pid in idmap:
+        return idmap[pid]
+    if pid in seen:
+        raise ReplyParentMissing(f"post {msg.id} answers post {pid}, which has not been copied")
+    return None
+
+
+def new_messages_from(result) -> list:
+    """The messages created by a send / forward request, oldest first."""
+    out = []
+    for u in getattr(result, "updates", None) or []:
+        if isinstance(u, (types.UpdateNewChannelMessage, types.UpdateNewMessage)):
+            out.append(u.message)
+    out.sort(key=lambda m: m.id)
+    return out
+
+
+# ------------------------------------------------------ posts Telegram holds back (copyright strike ...)
+SavedLookup = Callable[[list], Awaitable[dict]]  # message ids -> {message id: the saved post of My posts}
+
+
+def saved_lookup(db, channel_id: int) -> SavedLookup:
+    """How the copy loop and the plan look up what My posts saved of the posts of one channel."""
+
+    async def lookup(ids: list) -> dict:
+        return {p.message_id: p for p in await db.posts_at(channel_id, ids)}
+
+    return lookup
+
+
+def usable_row(row) -> bool:
+    """A saved post that can take the place of a restricted post: it has something to post, and what it says is not
+    Telegram's notice (a saved copy that an older version made from a restricted post can hold the notice)."""
+    if row is None:
+        return False
+    text = row.text or ""
+    if is_placeholder_text(text):
+        return False
+    return bool(text.strip() or row.media_file_id)
+
+
+def copy_source(unit: list, rows: dict, *, restricted: Optional[str] = None, use_saved: bool = False) -> tuple:
+    """Where the copy of this post (or album) comes from -> (source, why).
+
+      "live"  - as Telegram hands the post out: nothing restricts it, or Telegram restricts it but still hands out the
+                post itself and there is no saved copy to use instead;
+      "saved" - from what My posts saved of it: Telegram restricts the channel (`restricted`) or the post (a copyright
+                strike) and My posts has every part of it. Only when `use_saved` (/shift) - the saved copy wins even when
+                Telegram's version still looks intact, because that is the owner's rule for a struck channel;
+      "skip"  - not copied: what Telegram hands out is its notice - or nothing - and My posts can't take over.
+
+    `why` is Telegram's own wording about the restriction, None when nothing restricts the post."""
+    marked = next((w for w in (message_restriction(m) for m in unit) if w), None)
+    why = marked or restricted
+    if why is None:
+        return "live", None
+    if use_saved and all(usable_row(rows.get(m.id)) for m in unit):
+        return "saved", why
+    for m in unit:
+        live = m.message or ""
+        if is_placeholder_text(live) or (
+            not live.strip() and getattr(m, "media", None) is None and rich_for(m) is None
+        ):
+            return "skip", why
+    return "live", why
+
+
+def stand_in(m, row):
+    """A copy of the live message `m` that shows what My posts saved for it - text, formatting, buttons, media. It takes
+    the place of a post Telegram holds back (the live message keeps what Telegram still tells: id, album, reply)."""
+    s = copy.copy(m)
+    s.message = row.text or ""
+    s.entities = de_entities(row.entities)
+    s.rich_message = None  # what it shows is what My posts saved ...
+    s.rich_saved = rich_of(row)  # ... which is a rich message when the saved post is one
+    s.reply_markup = build_markup(row.buttons)
+    s.media = None
+    s.saved_ref = None  # the saved media reference (resend_saved may need it again without its file reference)
+    if row.media_file_id:
+        try:
+            s.media = media_from_ref(row.media_file_id)
+            s.saved_ref = row.media_file_id
+        except ValueError:  # a reference that can't be read: the post goes out without media
+            log.warning("the saved media of post %s can't be read", m.id)
+    if s.media is None and row.link_preview:
+        s.media = types.MessageMediaWebPage(webpage=types.WebPageEmpty(id=0))
+    return s
+
+
+def stand_ins(unit: list, rows: dict) -> Optional[list]:
+    """The saved copies that stand in for a restricted post, or None when My posts does not have all of them (or one of
+    them has nothing to post, or holds only Telegram's notice)."""
+    out = []
+    for m in unit:
+        row = rows.get(m.id)
+        if not usable_row(row):
+            return None
+        out.append(stand_in(m, row))
+    return out
+
+
+FILE_MEDIA = (types.MessageMediaPhoto, types.MessageMediaDocument)  # a photo, video, document, voice, sticker ...
+
+
+def has_file(m) -> bool:
+    """The post carries a file. A link preview, a poll, a location or a contact is not a file."""
+    return isinstance(getattr(m, "media", None), FILE_MEDIA)
+
+
+def without_files(unit: list) -> tuple:
+    """/shift --no-media: the posts of `unit` as they look without their files -> (those that still have a text, the
+    number of files left out). A post that was only a file has nothing left to post and is dropped."""
+    out, lost = [], 0
+    for m in unit:
+        c = m
+        if has_file(m):
+            c = copy.copy(m)
+            c.media, c.saved_ref, c.invert_media = None, None, None
+            lost += 1
+        if (c.message or "").strip() or rich_for(c) is not None:
+            out.append(c)
+    return out, lost
+
+
+async def single_posts(units: AsyncIterator[list]) -> AsyncIterator[list]:
+    """/shift --no-media: an album can't be rebuilt without its pictures, so every message of it is a post of its own."""
+    async for unit in units:
+        for m in unit:
+            yield [m]
+
+
+def saved_message(row, channel_id: int):
+    """A post built from its saved copy alone, for a channel that can't be read at all. Only the saved parts exist: no
+    album, no reply, no pin."""
+    base = types.Message(
+        id=row.message_id, peer_id=types.PeerChannel(channel_id), date=row.sent_at or row.created_at, message=""
+    )
+    return stand_in(base, row)
+
+
+def saved_rows_between(rows: list, first: Optional[int], last: Optional[int]) -> list:
+    """The saved posts (oldest first, one per message id) that can be posted - they have something to post that is not
+    Telegram's notice - between two message ids."""
+    out, seen = [], set()
+    for row in sorted(rows, key=lambda r: (r.message_id or 0, r.id)):
+        mid = row.message_id
+        if mid is None or mid in seen or (first and mid < first) or (last and mid > last):
+            continue
+        if usable_row(row):
+            seen.add(mid)
+            out.append(row)
+    return out
+
+
+async def saved_units(db, channel_id: int, first: int, last: int) -> AsyncIterator[list]:
+    """The saved posts of a channel between two message ids, oldest first - each one a unit of its own."""
+    for row in saved_rows_between(await db.sent_posts_from(channel_id, first), first, last):
+        yield [saved_message(row, channel_id)]
+
+
+# ------------------------------------------------------------------------------- planning
+@dataclass
+class RepostPlan:
+    channel: Any
+    first: int = 1
+    last: int = 0  # newest existing message id when the plan was made
+    scanned: int = 0
+    units: int = 0  # posts (an album counts once)
+    messages: int = 0
+    albums: int = 0
+    text: int = 0
+    media: int = 0
+    polls: int = 0
+    other: int = 0
+    service: int = 0
+    link_posts: int = 0
+    n_buttons: int = 0
+    n_links: int = 0
+    n_typed: int = 0
+    dropped_posts: int = 0
+    post_link_posts: int = 0  # posts with a link to another post of this channel
+    post_links: int = 0
+    pinned: int = 0  # pinned posts (their copies get pinned)
+    replies: int = 0  # posts that answer another post
+    held_saved: int = 0  # restricted posts that are copied from what My posts saved of them (counted in units)
+    held_skipped: int = 0  # restricted posts that can't be copied: only Telegram's notice is left (not counted in units)
+    live_restricted: int = 0  # restricted posts without a saved copy that are copied as Telegram hands them out
+    no_media: bool = False  # /shift --no-media: the files are left out
+    files_left_out: int = 0  # ... posts that are copied as text without their file (counted in units)
+    file_only: int = 0  # ... posts that are only a file: nothing to copy (not counted in units)
+    held_why: Optional[str] = None  # what Telegram says about them
+    channel_restricted: Optional[str] = None  # what Telegram says when it restricts the whole channel
+    from_db: bool = False  # the channel can't be read: the plan (and the copy) is made from My posts alone
+    unreadable: Optional[str] = None  # ... because of this
+    partial: bool = False
+    error: Optional[str] = None
+
+    def eta_seconds(self, delay: float) -> int:
+        return int(self.units * (delay + 1.0))
+
+
+def tally(plan: RepostPlan, m, opts: RepostOptions, links: PostLinks) -> None:
+    """Count one message (as it will be copied) into the plan."""
+    plan.messages += 1
+    media = m.media
+    if media is None or isinstance(media, types.MessageMediaWebPage):
+        plan.text += 1
+    elif isinstance(media, (types.MessageMediaPhoto, types.MessageMediaDocument)):
+        plan.media += 1
+    elif isinstance(media, types.MessageMediaPoll):
+        plan.polls += 1
+    else:
+        plan.other += 1
+    f = final_state(m, opts, links)
+    if f.n_buttons or f.n_links or f.n_typed:
+        plan.link_posts += 1
+        plan.n_buttons += f.n_buttons
+        plan.n_links += f.n_links
+        plan.n_typed += f.n_typed
+    if f.dropped:
+        plan.dropped_posts += 1
+    if f.n_post_links:
+        plan.post_link_posts += 1
+        plan.post_links += f.n_post_links
+    if getattr(m, "pinned", False):
+        plan.pinned += 1
+    if reply_parent(m) is not None:
+        plan.replies += 1
+
+
+def plan_from_saved(
+    ch, rows: list, opts: RepostOptions, *, first_id=None, last_id=None, unreadable=None, no_media: bool = False
+) -> RepostPlan:
+    """The plan of a copy made from My posts alone (the channel can't be read): one post per saved message."""
+    plan = RepostPlan(
+        channel=ch, partial=bool(first_id or last_id), from_db=True, unreadable=unreadable, no_media=no_media
+    )
+    links = PostLinks.for_channel(ch)
+    chosen = saved_rows_between(rows, first_id, last_id)
+    for row in chosen:
+        m = saved_message(row, ch.id)
+        if no_media:
+            kept, lost = without_files([m])
+            if not kept:
+                plan.file_only += 1
+                continue
+            m, plan.files_left_out = kept[0], plan.files_left_out + lost
+        plan.units += 1
+        tally(plan, m, opts, links)
+    if chosen:
+        plan.first, plan.last = chosen[0].message_id, chosen[-1].message_id
+        plan.scanned = plan.last
+    else:
+        plan.first, plan.last = first_id or 1, last_id or 0
+    if not plan.units:
+        plan.error = "There is nothing to copy."
+        if plan.file_only:
+            plan.error = "Every saved post in this range is only a file, so without files there is nothing to copy."
+    return plan
+
+
+async def find_last_id(client, peer, top: int) -> Optional[int]:
+    """Newest existing message id, searching backwards from the channel counter."""
+    a = top
+    for _ in range(300):
+        lo = max(1, a - CHUNK + 1)
+        msgs = await fetch_messages(client, peer, list(range(lo, a + 1)))
+        ids = [m.id for m in msgs if m is not None and not isinstance(m, types.MessageEmpty)]
+        if ids:
+            return max(ids)
+        if lo == 1:
+            return None
+        a = lo - 1
+    return None
+
+
+async def plan_repost(
+    client,
+    ch,
+    opts: RepostOptions,
+    *,
+    progress: Optional[Callable[[RepostPlan], Awaitable[None]]] = None,
+    first_id: Optional[int] = None,
+    last_id: Optional[int] = None,
+    saved: Optional[SavedLookup] = None,
+    use_saved: bool = False,
+    no_media: bool = False,
+) -> RepostPlan:
+    """Read the channel and count what a copy would do. first_id / last_id limit the range (used by /shift).
+    `saved` looks up My posts' copies of the channel's posts; with `use_saved` a post Telegram holds back is counted as
+    the saved post it will be copied from (/shift), without it such a post is left out (/repost). With `no_media` the
+    files are left out of the copies (/shift --no-media): a post that is only a file has nothing left to copy."""
+    peer = peer_of(ch)
+    plan = RepostPlan(channel=ch, partial=bool(opts.last), no_media=no_media)
+    try:
+        top, plan.channel_restricted, _ = await probe_channel(client, peer)
+    except Exception as e:  # the counter is only a help: without it the ids are read until nothing more turns up
+        log.info("could not read channel counter: %s", e)
+        top = None
+    first = 1
+    if opts.last:
+        if top is None:
+            plan.error = "I can't tell which post is the newest, so --last can't be used here."
+            return plan
+        newest = await find_last_id(client, peer, top)
+        if newest is None:
+            plan.error = "The channel has no posts."
+            return plan
+        first, top = max(1, newest - opts.last + 1), newest
+    if first_id:
+        first = max(first, first_id)
+        plan.partial = True
+    if last_id:
+        top = last_id if top is None else min(top, last_id)
+        plan.partial = True
+    plan.first = first
+    links = PostLinks.for_channel(ch)
+    a, empty_run, prev_gid, max_seen = first, 0, None, 0
+    while True:
+        if top is not None and a > top:
+            break
+        hi = a + CHUNK - 1 if top is None else min(a + CHUNK - 1, top)
+        found = False
+        rows = await saved(list(range(a, hi + 1))) if saved else {}
+        for m in await fetch_messages(client, peer, list(range(a, hi + 1))):
+            if m is None or isinstance(m, types.MessageEmpty):
+                continue
+            found = True
+            max_seen = max(max_seen, m.id)
+            if isinstance(m, types.MessageService):
+                plan.service += 1
+                continue
+            gid = getattr(m, "grouped_id", None)
+            new_unit = no_media or gid is None or gid != prev_gid  # without files an album is a post per message
+            row = rows.get(m.id)
+            # a struck channel changes how /shift copies (My posts first); /repost copies as before, post by post
+            source, why = copy_source(
+                [m], rows, restricted=plan.channel_restricted if use_saved else None, use_saved=use_saved
+            )
+            if why:
+                plan.held_why = plan.held_why or why
+            if source == "skip":
+                plan.held_skipped += 1 if new_unit else 0  # nothing to copy it from
+                prev_gid = gid
+                continue
+            if source == "saved":
+                m = stand_in(m, row)  # counted as the saved post it will be copied from
+            if no_media:
+                kept, lost = without_files([m])
+                if not kept:  # nothing but a file: nothing to copy without it
+                    plan.file_only += 1
+                    prev_gid = gid
+                    continue
+                m, plan.files_left_out = kept[0], plan.files_left_out + lost
+            if source == "saved":
+                plan.held_saved += 1 if new_unit else 0
+            elif why:
+                plan.live_restricted += 1 if new_unit else 0
+            if new_unit:
+                plan.units += 1
+                if gid is not None and not no_media:
+                    plan.albums += 1
+            prev_gid = gid
+            tally(plan, m, opts, links)
+        plan.scanned = hi
+        if top is None:
+            empty_run = 0 if found else empty_run + 1
+            if empty_run >= FALLBACK_EMPTY_BATCHES:
+                break
+        if progress:
+            await progress(plan)
+        a = hi + 1
+    plan.last = max_seen
+    if not plan.units:
+        plan.error = "There is nothing to copy."
+        if plan.held_skipped:
+            plan.error = (
+                "Telegram holds back every post in this range (it shows a notice instead of the post) and My posts has "
+                "no saved copy of them, so there is nothing to copy."
+            )
+        elif plan.file_only:
+            plan.error = "Every post in this range is only a file, so without files there is nothing to copy."
+    return plan
+
+
+# ---------------------------------------------------------------------------------- copying
+async def iter_units(client, peer, first: int, last: int) -> AsyncIterator[list]:
+    """The posts between two ids, oldest first. An album is one unit (a list of messages)."""
+    group: list = []
+    a = first
+    while a <= last:
+        hi = min(a + CHUNK - 1, last)
+        for m in await fetch_messages(client, peer, list(range(a, hi + 1))):
+            if is_skippable(m):
+                continue
+            gid = getattr(m, "grouped_id", None)
+            if group and gid != group[0].grouped_id:
+                yield group
+                group = []
+            group.append(m)
+            if gid is None:
+                yield group
+                group = []
+        a = hi + 1
+    if group:
+        yield group
+
+
+async def delete_ids(client, peer, ids: list) -> None:
+    if not ids:
+        return
+    try:
+        await flood_retry(lambda: client(functions.channels.DeleteMessagesRequest(channel=peer, id=list(ids))))
+    except errors.RPCError as e:
+        log.warning("could not remove messages %s: %s", ids, type(e).__name__)
+
+
+async def forward_unit(client, src_peer, unit: list, dst_peer=None) -> list:
+    """Let Telegram copy the posts (no "forwarded from" header). `dst_peer` defaults to the same channel."""
+    ids = [m.id for m in unit]
+    to_peer = dst_peer if dst_peer is not None else src_peer
+    result = await flood_retry(
+        lambda: client(
+            functions.messages.ForwardMessagesRequest(
+                from_peer=src_peer, id=ids, to_peer=to_peer, silent=True, drop_author=True
+            )
+        )
+    )
+    return new_messages_from(result)
+
+
+def _inverted(m) -> Optional[bool]:
+    return True if getattr(m, "invert_media", False) else None
+
+
+def reply_header(reply_to: Optional[int]):
+    """The `reply_to` argument of the send requests: answer message `reply_to` of the same channel."""
+    return types.InputReplyToMessage(reply_to_msg_id=reply_to) if reply_to else None
+
+
+async def resend_unit(client, peer, unit: list, finals: list, reply_to: Optional[int] = None) -> list:
+    """Rebuild a post from its parts (used when copying is not allowed, or the copy must differ from the original).
+    `reply_to`: message id (in the channel `peer`) the new post answers."""
+    reply = reply_header(reply_to)
+    sender = None
+    if len(unit) == 1 and getattr(finals[0], "rich", None) is not None:
+        rich_final = finals[0]  # a rich message: Telegram builds it again from its blocks (or its HTML / Markdown)
+
+        async def send_rich_final():
+            return await with_rich(
+                rich_final.rich,
+                lambda inp: client(
+                    functions.messages.SendMessageRequest(
+                        peer=peer, message="", rich_message=inp, reply_markup=rich_final.markup, silent=True, reply_to=reply
+                    )
+                ),
+            )
+
+        sender = send_rich_final
+    elif len(unit) > 1:
+        singles = [
+            types.InputSingleMedia(media=utils.get_input_media(m.media), message=f.text, entities=f.entities or None)
+            for m, f in zip(unit, finals)
+        ]
+
+        def make():
+            return functions.messages.SendMultiMediaRequest(
+                peer=peer, multi_media=singles, silent=True, invert_media=_inverted(unit[0]), reply_to=reply
+            )
+
+    else:
+        m, f = unit[0], finals[0]
+        if m.media is None or isinstance(m.media, types.MessageMediaWebPage):
+
+            def make():
+                return functions.messages.SendMessageRequest(
+                    peer=peer,
+                    message=f.text,
+                    entities=f.entities or None,
+                    reply_markup=f.markup,
+                    no_webpage=True if f.preview is False else None,
+                    invert_media=_inverted(m),
+                    silent=True,
+                    reply_to=reply,
+                )
+
+        else:
+            media = utils.get_input_media(m.media)
+
+            def make():
+                return functions.messages.SendMediaRequest(
+                    peer=peer,
+                    media=media,
+                    message=f.text,
+                    entities=f.entities or None,
+                    reply_markup=f.markup,
+                    invert_media=_inverted(m),
+                    silent=True,
+                    reply_to=reply,
+                )
+
+    result = await flood_retry(sender if sender is not None else (lambda: client(make())))
+    news = new_messages_from(result)
+    if len(news) != len(unit):
+        await delete_ids(client, peer, [n.id for n in news])
+        raise RuntimeError(f"Telegram created {len(news)} messages instead of {len(unit)}")
+    return news
+
+
+@dataclass
+class _State:
+    mode: str = "forward"  # becomes "resend" when the channel forbids forwarding
+    forwarded: int = 0
+    rebuilt: int = 0
+    repaired: int = 0  # new posts whose buttons had to be set again after posting
+    replies: int = 0  # new posts created as an answer to the copy of the post the original answered
+    reply_lost: int = 0  # answers that could only be copied without the reply
+    from_saved: int = 0  # posts Telegram holds back that were rebuilt from their saved copy in My posts
+    media_lost: list = field(default_factory=list)  # old ids of those that had to go out without their media
+
+
+def is_pure(src, f: Final, reply_to: Optional[int] = None) -> bool:
+    """True when a server-side copy is already the final post: nothing to swap, no keyboard to rebuild and no
+    reply to set (a reply can only be given when a post is created)."""
+    return not f.text_changed and src.reply_markup is None and not reply_to
+
+
+def _has_media(unit: list) -> bool:
+    return any(m.media is not None and not isinstance(m.media, types.MessageMediaWebPage) for m in unit)
+
+
+def _without_reference(unit: list) -> list:
+    """The same saved posts with the file reference of their media left out (it may have expired)."""
+    out = []
+    for m in unit:
+        b = copy.copy(m)
+        if getattr(m, "saved_ref", None):
+            b.media = media_from_ref(m.saved_ref, blank_reference=True)
+        out.append(b)
+    return out
+
+
+async def resend_saved(client, dst_peer, unit: list, finals: list, st: _State, reply_to: Optional[int] = None) -> list:
+    """Create the copies of posts that Telegram holds back, from the saved posts that stand in for them (stand_in).
+    Their media is sent from the saved reference: when Telegram says the reference is out of date it is tried without
+    it, and a single post whose text is saved goes out without its media when Telegram still refuses the file
+    (a file taken down for copyright is refused) - counted in st.media_lost."""
+    failure: Optional[BaseException] = None
+    for attempt in (unit, None):
+        if attempt is None:
+            if failure is None or not _has_media(unit):
+                break
+            attempt = _without_reference(unit)
+        try:
+            return await resend_unit(client, dst_peer, attempt, finals, reply_to)
+        except (TypeError, ValueError, errors.RPCError) as e:
+            if isinstance(e, errors.RPCError) and type(e).__name__ in FATAL:
+                raise
+            failure = failure or e
+            if not _has_media(unit):
+                raise
+    if len(unit) == 1 and (finals[0].text or "").strip():
+        unit[0].media = None  # what goes out now has no media, and neither has its entry in My posts
+        news = await resend_unit(client, dst_peer, unit, finals, reply_to)
+        st.media_lost.append(unit[0].id)
+        return news
+    raise failure  # type: ignore[misc]
+
+
+async def copy_unit(
+    client,
+    peer,
+    unit: list,
+    finals: list,
+    st: _State,
+    reply_to: Optional[int] = None,
+    dst_peer=None,
+    *,
+    from_saved: bool = False,
+    no_forward: bool = False,
+) -> list:
+    """Create the copy of one post (or album) at the end of `dst_peer` (default: the same channel `peer`).
+    `from_saved`: the posts in `unit` are saved copies standing in for posts Telegram restricts - never forwarded.
+    `no_forward`: Telegram restricts these posts and refuses to copy them itself: they are rebuilt from their parts."""
+    dst = dst_peer if dst_peer is not None else peer
+    if from_saved:
+        news = await resend_saved(client, dst, unit, finals, st, reply_to)
+        st.rebuilt += 1
+        st.from_saved += 1
+        if reply_to:
+            st.replies += 1
+        return news
+    pure = all(is_pure(m, f, reply_to) for m, f in zip(unit, finals))
+    if st.mode == "forward" and pure and not no_forward:
+        try:
+            news = await forward_unit(client, peer, unit, dst)
+            if len(news) == len(unit):
+                st.forwarded += 1
+                return news
+            await delete_ids(client, dst, [n.id for n in news])
+        except errors.ChatForwardsRestrictedError:
+            st.mode = "resend"
+            log.info("this channel restricts forwarding - rebuilding posts from their parts instead")
+        except errors.RPCError as e:
+            if type(e).__name__ in FATAL:
+                raise
+            log.info("copy failed (%s) - rebuilding the post", type(e).__name__)
+    try:
+        news = await resend_unit(client, dst, unit, finals, reply_to)
+    except (TypeError, ValueError, errors.RPCError) as e:
+        # A kind of media a post cannot be rebuilt from (or a reply Telegram refuses). If only the reply made a
+        # rebuild necessary, a plain copy by Telegram still works - without the reply.
+        if isinstance(e, errors.RPCError) and type(e).__name__ in FATAL:
+            raise
+        if reply_to and st.mode == "forward" and not no_forward and all(is_pure(m, f) for m, f in zip(unit, finals)):
+            news = await forward_unit(client, peer, unit, dst)
+            if len(news) != len(unit):
+                await delete_ids(client, dst, [n.id for n in news])
+                raise
+            st.reply_lost += 1
+            st.forwarded += 1
+            return news
+        raise
+    st.rebuilt += 1
+    if reply_to:
+        st.replies += 1
+    return news
+
+
+async def settle_buttons(client, peer, finals: list, news: list, st: _State, *, pause: float) -> None:
+    """Read the new posts back: each must show the link buttons it should. Repairs it, or removes the copies."""
+    for f, new in zip(finals, news):
+        if not link_urls(f.markup):
+            continue
+        try:
+            how = await ensure_markup(client, peer, new.id, f.markup, pause=pause)
+        except errors.RPCError as e:
+            await delete_ids(client, peer, [n.id for n in news])
+            if type(e).__name__ in FATAL:
+                raise
+            raise ButtonsNotShown(f"could not set the buttons ({type(e).__name__})") from e
+        except (ButtonsNotShown, LookupError) as e:
+            await delete_ids(client, peer, [n.id for n in news])
+            raise ButtonsNotShown(str(e)) from e
+        if how != "fine":
+            st.repaired += 1
+
+
+@dataclass
+class FinalizeResult:
+    """The finishing touches after the copies exist: links to other posts, pins."""
+
+    checked: int = 0  # copies read back
+    relinked: int = 0  # copies whose links to other posts now point at the new copies
+    links: int = 0  # links changed in total
+    missing: int = 0  # copies that do not exist any more
+    failed: list = field(default_factory=list)  # [(message id, error name)]
+    pin_wanted: int = 0  # copies of pinned posts that still had to be pinned
+    pinned: int = 0
+    pin_error: Optional[str] = None
+    aborted: Optional[str] = None
+    stopped: bool = False
+
+
+@dataclass
+class RepostResult:
+    copied_units: int = 0
+    copied_messages: int = 0
+    skipped_done: int = 0
+    failed: list = field(default_factory=list)  # [(first old id, error name)]
+    forwarded: int = 0
+    rebuilt: int = 0
+    repaired: int = 0
+    replies: int = 0  # copies created as an answer to the copy of the post the original answered
+    reply_lost: int = 0  # answers that could only be copied without the reply
+    reply_dropped: int = 0  # answers to a post that no longer exists (nothing to answer)
+    from_saved: int = 0  # restricted posts that were copied from their saved copy in My posts
+    media_lost: list = field(default_factory=list)  # ... of which these (old ids) went out without their media
+    held_back: list = field(default_factory=list)  # posts that were not copied: only Telegram's notice was left (old id)
+    held_why: Optional[str] = None  # what Telegram says about the restricted posts
+    live_restricted: int = 0  # restricted posts without a saved copy, copied as Telegram hands them out
+    no_media: bool = False  # /shift --no-media: no file was copied
+    files_left_out: int = 0  # ... posts that were copied as text, without their file
+    file_only: list = field(default_factory=list)  # ... posts that are only a file: nothing to copy (old id)
+    used_saved: bool = False  # the run could take restricted posts from My posts (/shift)
+    from_db: bool = False  # the channel can't be read: every post was copied from My posts alone
+    checked: int = 0  # new posts that were read back to see whether Telegram itself hides them
+    hidden: list = field(default_factory=list)  # [(old id, had media)] new posts Telegram itself hides (restriction mark)
+    hidden_why: Optional[str] = None  # what Telegram says about them
+    dst_restricted: Optional[str] = None  # what Telegram says about the destination channel (when copies were hidden)
+    hidden_stop: bool = False  # the run stopped by itself: Telegram hides every copy it read back
+    aborted: Optional[str] = None
+    stopped: bool = False
+    first_new: Optional[int] = None
+    last_new: Optional[int] = None
+    phase: str = "copy"  # copy | finish | profile | links
+    final: Optional[FinalizeResult] = None
+    final_error: Optional[str] = None
+    cross: Optional[CrossResult] = None  # links to the old posts in ALL connected channels, pointed at the copies
+    cross_error: Optional[str] = None
+    profile: Any = None  # /shift -all: what happened to the name, description and photo (profile_copy.ProfileResult)
+    profile_error: Optional[str] = None
+
+
+def _rows(unit: list, finals: list, news: list) -> list:
+    rows = []
+    for src, f, new in zip(unit, finals, news):
+        kind = classify_media(src)
+        ref = (media_ref(new) or media_ref(src)) if kind else None
+        rows.append(
+            {
+                "old_id": src.id,
+                "new_id": new.id,
+                "post": {
+                    "text": plain_of(f.rich) if f.rich is not None else f.text,
+                    "entities": [rich_entry(f.rich)] if f.rich is not None else ser_entities(f.entities),
+                    "buttons": ser_markup(f.markup),
+                    "media_kind": kind,
+                    "media_file_id": ref,
+                    "link_preview": bool(f.preview),
+                },
+            }
+        )
+    return rows
+
+
+CHECK_FIRST = 3  # the first copies of any run are read back ...
+CHECK_EVERY = 10  # ... then every tenth (all of them when Telegram restricts the source)
+STOP_IF_HIDDEN = 3  # /shift stops when Telegram hides this many new copies and not one of those read back is shown
+
+
+async def check_copies(client, dst_peer, unit: list, news: list, res: RepostResult) -> None:
+    """Read the new posts back: does TELEGRAM itself hide them (a restriction mark, or its notice as the text)? That
+    is not the bot copying a notice - Telegram restricts the new post as well, usually because of a file or a link in
+    it. What is found goes into `res` (checked, hidden, hidden_why). Never fails the copy: it is only a look."""
+    try:
+        got = await fetch_messages(client, dst_peer, [n.id for n in news])
+    except Exception as e:  # a look that fails is not a failed copy (the post exists and is registered already)
+        log.info("could not read the new posts back: %s", type(e).__name__)
+        return
+    for old, new in zip(unit, got):
+        if is_skippable(new):
+            continue
+        res.checked += 1
+        why = message_restriction(new)
+        if why:
+            res.hidden.append((old.id, _has_media([old])))
+            res.hidden_why = res.hidden_why or why
+
+
+@dataclass
+class CopyJob:
+    """Everything the copy loop needs to know; /repost and /shift each fill it in their own way."""
+
+    src_peer: Any
+    dst_peer: Any  # the same as src_peer for /repost
+    opts: RepostOptions
+    links: PostLinks  # links.ids is `idmap`: old message id -> id of its copy, grows as we go
+    first_id: int
+    last_id: int
+    done: set  # old ids that already have a copy
+    idmap: dict
+    record: Callable[[list], Awaitable[None]]  # saves [{old_id, new_id, post}] (and registers the posts)
+    saved: Optional[SavedLookup] = None  # what My posts saved of the source's posts
+    use_saved: bool = False  # a post Telegram holds back is rebuilt from its saved copy (otherwise it is left out)
+    units: Optional[Callable[[], AsyncIterator[list]]] = None  # where the posts come from (default: read the channel)
+    from_db: bool = False  # `units` are saved posts: they are all rebuilt, none is read from Telegram
+    restricted: Optional[str] = None  # what Telegram says about the source channel itself (a copyright strike), if anything
+    no_media: bool = False  # the copies get no files: text, formatting and buttons only (/shift --no-media)
+    stop_if_hidden: int = 0  # stop when this many copies were read back and Telegram hides every one (0: never)
+
+
+async def copy_loop(
+    client,
+    job: CopyJob,
+    *,
+    delay: float = 1.2,
+    progress: Optional[Callable[[RepostResult], Awaitable[None]]] = None,
+    should_stop: Optional[Callable[[], bool]] = None,
+    settle_pause: float = 0.7,
+) -> RepostResult:
+    """Copy the posts first_id..last_id of `job.src_peer` to the end of `job.dst_peer`, in order.
+    Safe to run again to continue: posts in `job.done` are skipped."""
+    src, dst = job.src_peer, job.dst_peer
+    seen: set = set()  # old ids read in this run (a reply to one of them needs its copy)
+    res, st, streak = RepostResult(used_saved=job.use_saved or job.from_db, from_db=job.from_db), _State(), 0
+    res.no_media = job.no_media
+    units = job.units() if job.units is not None else iter_units(client, src, job.first_id, job.last_id)
+    if job.no_media:
+        units = single_posts(units)
+    async for unit in units:
+        if should_stop and should_stop():
+            res.stopped = True
+            break
+        ids = [m.id for m in unit]
+        seen.update(ids)
+        if all(i in job.done for i in ids):
+            res.skipped_done += 1
+            continue
+        rows = await job.saved(ids) if (job.saved and not job.from_db) else {}
+        if job.from_db:
+            source, why = "saved", None
+        else:
+            source, why = copy_source(unit, rows, restricted=job.restricted, use_saved=job.use_saved)
+        if why:  # Telegram restricts this post (or the whole channel): what it hands out now is not trusted
+            res.held_why = res.held_why or why
+        from_saved = job.from_db  # saved posts already
+        standing = None
+        if source == "saved" and not job.from_db:
+            standing = stand_ins(unit, rows)
+            if standing is None:
+                source = "skip"
+        if source == "skip":
+            log.info("post %s: Telegram shows only its notice (%s) and My posts has no saved copy to use", ids[0], why)
+            res.held_back.append(ids[0])
+            continue
+        if standing is not None:
+            unit, from_saved = standing, True
+        no_forward, left_out = bool(why), 0
+        if job.no_media:  # the copy is the text with its formatting and buttons; its file stays where it is
+            unit, left_out = without_files(unit)
+            if not unit:  # nothing but a file: there is nothing to post without it, and nothing waits for it
+                res.file_only.append(ids[0])
+                seen.difference_update(ids)
+                continue
+            no_forward = no_forward or bool(left_out)  # a copy by Telegram would carry the file
+        finals = [final_state(m, job.opts, job.links) for m in unit]
+        if any(is_placeholder_text(f.text) for f in finals):  # Telegram's notice is never posted, whatever it came from
+            log.info("post %s: its text is Telegram's notice - not copied", ids[0])
+            res.held_back.append(ids[0])
+            res.held_why = res.held_why or PLACEHOLDER_NOTE
+            continue
+        try:
+            reply_to = new_parent(unit[0], job.idmap, seen)
+            news = await copy_unit(
+                client, src, unit, finals, st, reply_to, dst, from_saved=from_saved, no_forward=no_forward
+            )
+            await settle_buttons(client, dst, finals, news, st, pause=settle_pause)
+        except Exception as e:  # one bad post must not stop the others
+            name = type(e).__name__
+            log.warning("copying %s failed: %s %s", ids, name, e)
+            res.failed.append((ids[0], name))
+            streak += 1
+            if name in FATAL or streak >= ABORT_AFTER:
+                res.aborted = name
+                break
+            await asyncio.sleep(delay)
+            continue
+        try:
+            await job.record(_rows(unit, finals, news))
+        except Exception as e:  # keep the channel and the database consistent
+            log.exception("could not save the copy of %s", ids)
+            await delete_ids(client, dst, [n.id for n in news])
+            res.failed.append((ids[0], type(e).__name__))
+            res.aborted = type(e).__name__
+            break
+        streak = 0
+        job.done.update(ids)
+        for old, new in zip(unit, news):
+            job.idmap[old.id] = new.id
+        if reply_parent(unit[0]) is not None and reply_to is None:
+            res.reply_dropped += 1
+        if why and not from_saved:
+            res.live_restricted += 1
+        res.files_left_out += left_out
+        if why or res.copied_units < CHECK_FIRST or res.copied_units % CHECK_EVERY == 0:
+            await check_copies(client, dst, unit, news, res)
+        res.copied_units += 1
+        res.copied_messages += len(unit)
+        res.first_new = res.first_new or news[0].id
+        res.last_new = news[-1].id
+        if progress:
+            await progress(res)
+        if job.stop_if_hidden and res.checked >= job.stop_if_hidden and len(res.hidden) == res.checked:
+            log.info("Telegram hides every copy read back (%s): stopping", res.checked)
+            res.stopped = res.hidden_stop = True  # more copies would only be more posts that nobody can see
+            break
+        await asyncio.sleep(delay)
+    if res.hidden:  # Telegram hides copies: is the destination itself restricted too?
+        try:
+            _top, res.dst_restricted, _err = await probe_channel(client, dst)
+        except Exception:  # only an extra for the report
+            log.debug("could not ask Telegram about the destination channel", exc_info=True)
+    res.forwarded, res.rebuilt, res.repaired = st.forwarded, st.rebuilt, st.repaired
+    res.replies, res.reply_lost = st.replies, st.reply_lost
+    res.from_saved, res.media_lost = st.from_saved, st.media_lost
+    return res
+
+
+async def run_repost(
+    client,
+    db,
+    ch,
+    mig,
+    user_id: int,
+    *,
+    delay: float = 1.2,
+    progress: Optional[Callable[[RepostResult], Awaitable[None]]] = None,
+    should_stop: Optional[Callable[[], bool]] = None,
+    settle_pause: float = 0.7,
+) -> RepostResult:
+    """Copy the posts of migration `mig` (ids first_id..last_id) in order; safe to run again to continue.
+
+    When every post is copied (not stopped, no fatal error) the finishing touches follow: links to posts that were
+    copied later are pointed at their copies, the copies of pinned posts are pinned, and then every connected channel
+    is searched for links to the old posts (crosslinks.relink_after_repost)."""
+    opts = RepostOptions(
+        old=mig.old_username, new=mig.new_username, include_typed=mig.include_typed, include_posts=mig.include_posts
+    )
+    peer = peer_of(ch)
+    idmap = dict(await db.migration_pairs(mid=mig.id, alive_only=False))
+    job = CopyJob(
+        src_peer=peer,
+        dst_peer=peer,
+        opts=opts,
+        links=PostLinks.for_channel(ch, idmap),
+        first_id=mig.first_id,
+        last_id=mig.last_id,
+        done=await db.migration_done_old_ids(mig.id),
+        idmap=idmap,
+        record=lambda rows: db.record_repost(mig.id, ch.id, rows, user_id),
+        saved=saved_lookup(db, ch.id),  # a post Telegram holds back is left alone (and so is not deleted)
+    )
+    res = await copy_loop(client, job, delay=delay, progress=progress, should_stop=should_stop, settle_pause=settle_pause)
+    if not res.stopped and not res.aborted:
+        res.phase = "finish"
+        if progress:
+            await progress(res)
+        try:
+            res.final = await finalize_repost(
+                client, db, ch, mig, delay=delay, settle_pause=settle_pause, should_stop=should_stop
+            )
+        except Exception as e:  # the copies are fine; only the finishing touches failed
+            log.exception("finishing the repost (links, pins) failed")
+            res.final_error = type(e).__name__
+        if not (res.final is not None and res.final.stopped):
+            res.phase = "links"
+            res.cross = CrossResult()
+
+            async def watch(_cross) -> None:
+                if progress:
+                    await progress(res)
+
+            if progress:
+                await progress(res)
+            try:
+                await relink_after_repost(
+                    client, db, ch, mig, delay=delay, settle_pause=settle_pause, progress=watch,
+                    should_stop=should_stop, result=res.cross,
+                )
+            except Exception as e:  # the copies are fine; only the links in the other channels were not updated
+                log.exception("pointing the links of the other channels at the copies failed")
+                res.cross_error = type(e).__name__
+    return res
+
+
+# --------------------------------------------------------------------- links to copies, pins
+async def relink_copies(
+    client,
+    db,
+    ch,
+    ids: dict,
+    targets: list,
+    *,
+    delay: float = 1.2,
+    settle_pause: float = 0.7,
+    dry_run: bool = False,
+    progress: Optional[Callable[[FinalizeResult], Awaitable[None]]] = None,
+    should_stop: Optional[Callable[[], bool]] = None,
+    links: Optional[PostLinks] = None,
+) -> FinalizeResult:
+    """Point every link to a post of this channel at the copy of that post (`ids`: old message id -> new one).
+
+    `targets` are the message ids of `ch` to look at (the copies). Idempotent: a link that already points at a copy
+    is left alone, because only OLD ids are replaced. With dry_run nothing is edited, the result only counts.
+    `links` (optional) says which links to follow; the default is "links to posts of `ch` itself" (/repost)."""
+    res = FinalizeResult()
+    peer = peer_of(ch)
+    links = links if links is not None else PostLinks.for_channel(ch, ids)
+    targets = sorted(set(targets))
+    streak, last_name = 0, None
+    for i in range(0, len(targets), CHUNK):
+        chunk = targets[i : i + CHUNK]
+        for mid, m in zip(chunk, await fetch_messages(client, peer, chunk)):
+            if is_skippable(m):
+                res.missing += 1
+                continue
+            res.checked += 1
+            rl = relink_message(m, links)
+            if rl is None:
+                continue
+            if dry_run:
+                res.relinked += 1
+                res.links += rl.links
+                continue
+            if should_stop and should_stop():
+                res.stopped = True
+                return res
+            rich = is_rich_message(m)  # a rich message's text is blocks: only its buttons change, the text is not sent again
+            try:
+                if rich:
+                    await flood_retry(lambda: edit_raw(client, peer, m.id, markup=rl.markup))
+                else:
+                    await flood_retry(
+                        lambda: edit_raw(
+                            client, peer, m.id, text=rl.text, entities=rl.entities, markup=rl.markup, preview=preview_flag(m)
+                        )
+                    )
+                if link_urls(rl.markup):
+                    await ensure_markup(client, peer, m.id, rl.markup, pause=settle_pause)
+            except errors.MessageNotModifiedError:
+                continue
+            except Exception as e:  # one bad post must not stop the others
+                name = type(e).__name__
+                log.warning("could not update the links of %s: %s %s", m.id, name, e)
+                res.failed.append((m.id, name))
+                streak = streak + 1 if name == last_name else 1
+                last_name = name
+                if name in FATAL or streak >= ABORT_AFTER:
+                    res.aborted = name
+                    return res
+                continue
+            streak, last_name = 0, None
+            res.relinked += 1
+            res.links += rl.links
+            try:
+                saved = dict(buttons=ser_markup(rl.markup))
+                if not rich:
+                    saved.update(text=rl.text, entities=ser_entities(rl.entities))
+                await db.update_post_by_message(ch.id, m.id, **saved)
+            except Exception:  # the channel is right; the saved copy will be corrected by the next sync
+                log.warning("could not save the new links of %s", m.id, exc_info=True)
+            if progress:
+                await progress(res)
+            await asyncio.sleep(delay)
+    return res
+
+
+async def pin_copies(client, ch, pairs: list, res: FinalizeResult, *, delay: float = 1.2) -> None:
+    """Pin the copy of every post that is pinned among the originals (oldest first, so the newest pin is on top).
+
+    The "pinned a message" notices Telegram adds to the channel are deleted again right away."""
+    peer = peer_of(ch)
+    pairs = sorted(pairs)
+    todo: list = []
+    for i in range(0, len(pairs), CHUNK):
+        chunk = pairs[i : i + CHUNK]
+        olds = await fetch_messages(client, peer, [o for o, _ in chunk])
+        news = await fetch_messages(client, peer, [n for _, n in chunk])
+        for (_, new_id), src, cur in zip(chunk, olds, news):
+            if is_skippable(src) or is_skippable(cur):
+                continue
+            if getattr(src, "pinned", False) and not getattr(cur, "pinned", False):
+                todo.append(new_id)
+    res.pin_wanted = len(todo)
+    for new_id in todo:
+        try:
+            out = await flood_retry(
+                lambda: client(functions.messages.UpdatePinnedMessageRequest(peer=peer, id=new_id, silent=True))
+            )
+        except errors.MessageNotModifiedError:
+            continue  # already pinned
+        except errors.RPCError as e:
+            res.pin_error = type(e).__name__
+            return
+        res.pinned += 1
+        await delete_ids(client, peer, [m.id for m in new_messages_from(out) if isinstance(m, types.MessageService)])
+        await asyncio.sleep(delay)
+
+
+async def finalize_repost(
+    client,
+    db,
+    ch,
+    mig,
+    *,
+    delay: float = 1.2,
+    settle_pause: float = 0.7,
+    progress: Optional[Callable[[FinalizeResult], Awaitable[None]]] = None,
+    should_stop: Optional[Callable[[], bool]] = None,
+) -> FinalizeResult:
+    """After the copies exist: links that point at old posts get the copies' ids, copies of pinned posts get pinned."""
+    pairs = sorted(await db.migration_pairs(mid=mig.id))
+    res = await relink_copies(
+        client, db, ch, dict(pairs), [n for _, n in pairs], delay=delay, settle_pause=settle_pause,
+        progress=progress, should_stop=should_stop,
+    )
+    if not res.stopped and not res.aborted:
+        await pin_copies(client, ch, pairs, res, delay=delay)
+    return res
+
+
+# ----------------------------------------------------------------------------- deleting
+@dataclass
+class DeleteResult:
+    deleted: int = 0
+    by_userbot: int = 0  # of those, how many only the userbot could delete
+    remaining: int = 0
+    blocked: bool = False  # some messages are still there although Telegram did not report an error
+    error: Optional[str] = None  # the bot's Telegram error that stopped the run
+    fallback_error: Optional[str] = None  # why the userbot could not help
+    tried_userbot: bool = False
+
+
+async def gone_ids(client, peer, ids: list) -> set:
+    """Which of `ids` no longer exist in the channel."""
+    msgs = await fetch_messages(client, peer, ids)
+    return {i for i, m in zip(ids, msgs) if m is None or isinstance(m, types.MessageEmpty)}
+
+
+@dataclass
+class BatchOutcome:
+    gone: set = field(default_factory=set)  # message ids that no longer exist afterwards
+    bot_error: Optional[str] = None
+    by_userbot: int = 0
+    fallback_error: Optional[str] = None
+    tried_userbot: bool = False
+
+
+async def delete_batch(client, peer, ids: list, fallback: Optional[Callable[[list], Awaitable[Any]]] = None) -> BatchOutcome:
+    """Delete up to 100 messages: the bot tries first, the result is checked by reading the messages back, and
+    whatever is still there goes to `fallback(ids)` (the userbot), followed by a second check."""
+    out = BatchOutcome()
+    try:
+        await flood_retry(lambda: client(functions.channels.DeleteMessagesRequest(channel=peer, id=list(ids))))
+    except errors.RPCError as e:
+        out.bot_error = type(e).__name__
+    out.gone = await gone_ids(client, peer, ids)
+    left = [x for x in ids if x not in out.gone]
+    if left and fallback is not None:
+        out.tried_userbot = True
+        try:
+            await fallback(left)
+        except Exception as e:  # a userbot problem must not hide what the bot already did
+            log.warning("the userbot could not delete %s message(s): %s", len(left), e)
+            out.fallback_error = str(e) or type(e).__name__
+        again = await gone_ids(client, peer, left)
+        out.by_userbot = len(again)
+        out.gone |= again
+    return out
+
+
+async def delete_pending(
+    client,
+    peer,
+    todo: list,
+    mark: Callable[[list], Awaitable[None]],
+    *,
+    delay: float = 0.5,
+    progress: Optional[Callable[[DeleteResult], Awaitable[None]]] = None,
+    fallback: Optional[Callable[[list], Awaitable[Any]]] = None,
+) -> DeleteResult:
+    """Delete the messages `todo` (oldest first, 100 per request). `mark(ids)` records the ones that are gone.
+
+    The bot tries first and the result is always checked by reading the messages back. Whatever the bot could not
+    delete (Telegram may refuse old posts) goes to `fallback(ids)` - the userbot - if there is one, and is checked
+    again. A batch the bot cannot delete does not stop the run: newer posts may still be deletable."""
+    res = DeleteResult()
+    use_fallback = fallback
+    for i in range(0, len(todo), 100):
+        ids = todo[i : i + 100]
+        out = await delete_batch(client, peer, ids, use_fallback)
+        res.tried_userbot = res.tried_userbot or out.tried_userbot
+        res.by_userbot += out.by_userbot
+        if out.fallback_error:
+            res.fallback_error = out.fallback_error
+            use_fallback = None  # it will not work for the next batches either
+        left = [x for x in ids if x not in out.gone]
+        if out.gone:
+            await mark(sorted(out.gone))
+            res.deleted += len(out.gone)
+        if left and out.bot_error:
+            res.error = res.error or out.bot_error  # remembered for the report
+            if out.bot_error in FATAL and use_fallback is None:
+                break  # e.g. no "Delete messages" right: the next batch would fail the same way
+        if progress:
+            await progress(res)
+        await asyncio.sleep(delay)
+    return res
+
+
+async def delete_copies(
+    client,
+    db,
+    ch,
+    mig,
+    which: str,
+    *,
+    delay: float = 0.5,
+    progress: Optional[Callable[[DeleteResult], Awaitable[None]]] = None,
+    fallback: Optional[Callable[[list], Awaitable[Any]]] = None,
+) -> DeleteResult:
+    """which='old': remove the original posts; which='new': remove the copies (undo). Oldest first, 100 per request."""
+    todo = await db.migration_pending_ids(mig.id, which, 1_000_000)
+
+    async def mark(ids: list) -> None:
+        await db.mark_migration_deleted(mig.id, ch.id, which, ids)
+
+    res = await delete_pending(client, peer_of(ch), todo, mark, delay=delay, progress=progress, fallback=fallback)
+    counts = await db.migration_counts(mig.id)
+    res.remaining = counts["old_left"] if which == "old" else counts["new_left"]
+    res.blocked = res.remaining > 0 and not res.error
+    return res
diff --git a/app/restrictions.py b/app/restrictions.py
new file mode 100644
index 0000000000000000000000000000000000000000..219ba5453868450abf63cede5ea69ee1a67316df
--- /dev/null
+++ b/app/restrictions.py
@@ -0,0 +1,77 @@
+"""What TELEGRAM does to a channel (not what an admin does): the copyright notice and its relatives.
+
+A channel that gets a copyright strike shows "This message couldn't be displayed on your device due to copyright
+infringement." in place of its posts. That is not an edit by an admin, so nothing here ever treats it as one: the sync
+leaves My posts as saved, and the link fixer does not edit such posts.
+"""
+from __future__ import annotations
+
+import re
+from typing import Optional
+
+from telethon import errors, functions
+
+from .tgutil import explain_rpc, flood_retry
+
+PLACEHOLDER_NOTE = "Telegram shows a notice instead of the post"
+
+# "This message couldn't be displayed on your device due to copyright infringement." and its relatives
+_NOTICE = re.compile(
+    r"^this (?:message|post|channel|media|content|file|video)\b.{0,80}?"
+    r"\b(?:can.?t|cannot|can not|couldn.?t|could not|isn.?t|is not|won.?t|will not)\b.{0,40}?"
+    r"\b(?:displayed|shown|viewed|available|accessible)\b.{0,160}$",
+    re.I,
+)
+_NOTICE_WHY = re.compile(r"copyright|infring|device|country|region|terms of service|violat|restrict|\blaw\b", re.I)
+
+
+def norm_text(text: Optional[str]) -> str:
+    return " ".join((text or "").split())
+
+
+def is_placeholder_text(text: Optional[str]) -> bool:
+    """The notice Telegram's apps show in place of a post it holds back (copyright, terms of service, region ...)."""
+    t = norm_text(text)
+    return 0 < len(t) <= 260 and bool(_NOTICE.match(t)) and bool(_NOTICE_WHY.search(t))
+
+
+def restriction_of(obj) -> Optional[str]:
+    """What Telegram says about a restricted channel or message (its own words), or None when nothing is restricted."""
+    reasons = getattr(obj, "restriction_reason", None)
+    if reasons:
+        texts = [norm_text(str(getattr(r, "text", "") or getattr(r, "reason", "") or "")) for r in reasons]
+        return "; ".join(dict.fromkeys(t for t in texts if t))[:240] or "restricted by Telegram"
+    if getattr(obj, "restricted", None):
+        return "restricted by Telegram"
+    return None
+
+
+def message_restriction(m, saved_text: Optional[str] = None) -> Optional[str]:
+    """Why this message must not be taken over as it looks now, or None. Telegram marks a message it holds back
+    (restriction_reason); some places hand out its notice as the text instead. `saved_text` is the saved copy's text: a
+    text that the saved copy already has is the owner's own wording, not a notice."""
+    why = restriction_of(m)
+    if why:
+        return why
+    live = m.message or ""
+    if is_placeholder_text(live) and (saved_text is None or norm_text(live) != norm_text(saved_text)):
+        return PLACEHOLDER_NOTE
+    return None
+
+
+async def probe_channel(client, peer) -> tuple:
+    """(the channel's event counter, why Telegram restricts the channel or None, None) - or (None, None, why not).
+    The counter is never lower than the newest message id."""
+    try:
+        full = await flood_retry(lambda: client(functions.channels.GetFullChannelRequest(peer)))
+    except errors.RPCError as e:
+        return None, None, explain_rpc(e)
+    pts = getattr(getattr(full, "full_chat", None), "pts", None)
+    if pts is None:
+        return None, None, "Telegram did not say how far the channel has come."
+    cid = getattr(peer, "channel_id", None)
+    why = None
+    for chat in getattr(full, "chats", None) or []:
+        if getattr(chat, "id", None) == cid:
+            why = restriction_of(chat)
+    return int(pts), why, None
diff --git a/app/richmsg.py b/app/richmsg.py
new file mode 100644
index 0000000000000000000000000000000000000000..b512b12ed0f879e4e53c712598a18549a53aab1e
--- /dev/null
+++ b/app/richmsg.py
@@ -0,0 +1,698 @@
+"""Telegram rich messages: headings, lists, tables, details, math, maps, media blocks, buttons ...
+
+A rich message is not text plus entities: it is a tree of blocks. Telegram builds that tree itself from HTML or Markdown
+(InputRichMessageHTML / InputRichMessageMarkdown), so text typed in those languages is handed over unchanged - every block
+and every formatting Telegram knows is supported without this bot having to know it. A rich message that is sent to the
+bot natively (or forwarded to it) is kept block for block (InputRichMessage).
+
+How the bot keeps one: as a single entry in the post's `entities` list - ``{"k": "rich", "f": "html" | "markdown" |
+"blocks", "s": source, ...}`` - next to a plain-text version in `text` (for lists, panels and the like). Whatever sends or
+edits a post looks for that entry with `rich_of`. No database change is needed, and exports, backups and the undo log carry
+it like any other formatting.
+"""
+from __future__ import annotations
+
+import asyncio
+import copy
+import hashlib
+import logging
+import re
+from dataclasses import dataclass, replace
+from html.parser import HTMLParser
+from types import SimpleNamespace
+from typing import List, Optional
+
+from telethon import errors, functions, types, utils
+from telethon.tl.tlobject import TLObject
+
+from .tgutil import _b64, _unb64, flood_retry
+
+log = logging.getLogger(__name__)
+
+KIND = "rich"  # the "k" of the entry in a post's entities
+MAX_SOURCE = 32768  # characters Telegram allows in a rich message (500 blocks, 16 levels and 50 media as well)
+
+
+class RichError(ValueError):
+    """A rich message that can't be used; the text is safe to show to the owner."""
+
+
+@dataclass(frozen=True)
+class Rich:
+    """A rich message as the bot keeps it."""
+
+    fmt: str  # "html" | "markdown" (typed: Telegram reads it) | "blocks" (received: base64 of an InputRichMessage)
+    source: str
+    rtl: bool = False
+    noautolink: bool = False  # links, @mentions, #tags ... in the text are not made clickable by Telegram
+    fp: Optional[str] = None  # fingerprint of the blocks Telegram showed last time (what the sync compares)
+
+
+def entry(r: Rich) -> dict:
+    """The entry that stands for `r` in a post's entities."""
+    e: dict = {"k": KIND, "f": r.fmt, "s": r.source}
+    if r.rtl:
+        e["r"] = 1
+    if r.noautolink:
+        e["n"] = 1
+    if r.fp:
+        e["p"] = r.fp
+    return e
+
+
+def rich_of(obj) -> Optional[Rich]:
+    """The rich message a post (or anything with a post's `entities`) holds, or None."""
+    for d in getattr(obj, "entities", None) or []:
+        if isinstance(d, dict) and d.get("k") == KIND and d.get("f") in ("html", "markdown", "blocks") and d.get("s"):
+            return Rich(d["f"], d["s"], bool(d.get("r")), bool(d.get("n")), d.get("p") or None)
+    return None
+
+
+def is_rich(obj) -> bool:
+    return rich_of(obj) is not None
+
+
+def real_entities(entities) -> list:
+    """The formatting entries of a stored entities list, without the rich message's."""
+    return [d for d in entities or [] if not (isinstance(d, dict) and d.get("k") == KIND)]
+
+
+# ------------------------------------------------------------------------------------ what Telegram takes
+def to_input(r: Rich):
+    """The InputRichMessage* object to send for `r`."""
+    flags = dict(rtl=True if r.rtl else None, noautolink=True if r.noautolink else None)
+    if r.fmt == "html":
+        return types.InputRichMessageHTML(html=r.source, **flags)
+    if r.fmt == "markdown":
+        return types.InputRichMessageMarkdown(markdown=r.source, **flags)
+    inp = copy.copy(_unb64(r.source))
+    # (a message saved by an older version may still hold blocks in Telegram's own form)
+    inp.blocks = inputify(inp.blocks, _user_ids(inp.users))
+    return inp
+
+
+def _input_geo(geo):
+    if isinstance(geo, types.GeoPoint):
+        return types.InputGeoPoint(lat=geo.lat, long=geo.long, accuracy_radius=geo.accuracy_radius)
+    if isinstance(geo, types.InputGeoPoint):
+        return geo
+    return types.InputGeoPointEmpty()
+
+
+def _user_ids(users) -> set:
+    return {u.user_id for u in users or [] if isinstance(getattr(u, "user_id", None), int)}
+
+
+def inputify(o, users: Optional[set] = None):
+    """Blocks the way Telegram wants them SENT. What it hands out and what it takes are the same blocks except where a
+    block holds something only Telegram can make: a map holds a stored point (with an access hash) when it comes in, and
+    must hold an input point (latitude and longitude) when it goes out.
+
+    `users`: the ids of the accounts that the message may mention (it carries their access data). A text mention of
+    anybody else would be refused, so it stays as the plain name; None leaves all mentions alone.
+
+    A thinking block (the "thinking ..." part of a message that is being streamed) is for drafts only - the Bot API says so
+    of  - and a message that is sent can't hold one: it goes out as an expandable section called "Thinking"."""
+    if isinstance(o, types.PageBlockMap):
+        return types.InputPageBlockMap(
+            geo=_input_geo(o.geo), zoom=o.zoom, w=o.w, h=o.h, caption=inputify(o.caption, users)
+        )
+    if isinstance(o, types.PageBlockThinking):
+        return types.PageBlockDetails(
+            blocks=[types.PageBlockParagraph(inputify(o.text, users))], title=types.TextPlain("Thinking")
+        )
+    if users is not None and isinstance(o, types.TextMentionName) and o.user_id not in users:
+        return inputify(o.text, users)
+    if isinstance(o, list):
+        return [inputify(x, users) for x in o]
+    if isinstance(o, TLObject):
+        new = copy.copy(o)
+        for key, value in vars(o).items():
+            if isinstance(value, (list, TLObject)):
+                setattr(new, key, inputify(value, users))
+        return new
+    return o
+
+
+def blank_references(inp):
+    """The same InputRichMessage with the file references of its photos and files left out (they may have expired)."""
+    if not isinstance(inp, types.InputRichMessage):
+        return inp
+    out = copy.copy(inp)
+    out.photos = [types.InputPhoto(p.id, p.access_hash, b"") for p in inp.photos or []] or None
+    out.documents = [types.InputDocument(d.id, d.access_hash, b"") for d in inp.documents or []] or None
+    return out
+
+
+async def with_rich(r: Rich, call):
+    """call(InputRichMessage*): first as saved, then (if Telegram says a saved file reference expired) without them."""
+    try:
+        return await call(to_input(r))
+    except errors.RPCError as e:
+        if r.fmt != "blocks" or "FileReference" not in type(e).__name__:
+            raise
+        log.info("stored file reference of a rich message rejected (%s) - retrying without it", type(e).__name__)
+        return await call(blank_references(to_input(r)))
+
+
+def sent_message(result):
+    """The message a send request created (something with an `id`)."""
+    for u in getattr(result, "updates", None) or []:
+        if isinstance(u, (types.UpdateNewChannelMessage, types.UpdateNewMessage)):
+            return u.message
+    if getattr(result, "id", None) is not None and not isinstance(result, (list, tuple)):
+        return SimpleNamespace(id=result.id)  # UpdateShortSentMessage
+    raise RuntimeError("Telegram did not say which message it created")
+
+
+async def send_rich(client, peer, r: Rich, *, markup=None, silent=None):
+    """Send `r` as a new message to `peer`; the message that was created comes back."""
+    result = await with_rich(
+        r,
+        lambda inp: client(
+            functions.messages.SendMessageRequest(
+                peer=peer, message="", rich_message=inp, reply_markup=markup, silent=True if silent else None
+            )
+        ),
+    )
+    return sent_message(result)
+
+
+# --------------------------------------------------------------------------------- rich messages that are received
+def is_rich_message(m) -> bool:
+    """The message carries a rich message (blocks) instead of plain text."""
+    return getattr(m, "rich_message", None) is not None
+
+
+def fingerprint(rm) -> str:
+    """Identifies what a rich message shows (its blocks; the file references of its pictures change from fetch to fetch)."""
+    h = hashlib.sha1()
+    for b in getattr(rm, "blocks", None) or []:
+        h.update(bytes(inputify(b)))  # (a map's access hash is not part of what it shows)
+    h.update(b"r" if getattr(rm, "rtl", None) else b"-")
+    return h.hexdigest()[:20]
+
+
+def _input_files(items, getter, empty) -> list:
+    out = []
+    for item in items or []:
+        try:
+            inp = getter(item)
+        except (TypeError, ValueError):
+            continue
+        if not isinstance(inp, empty):
+            out.append(inp)
+    return out
+
+
+def input_of(rm, users: Optional[list] = None):
+    """The InputRichMessage that sends a received RichMessage again: same blocks, same pictures and files."""
+    photos = _input_files(getattr(rm, "photos", None), utils.get_input_photo, types.InputPhotoEmpty)
+    docs = _input_files(getattr(rm, "documents", None), utils.get_input_document, types.InputDocumentEmpty)
+    return types.InputRichMessage(
+        blocks=inputify(list(rm.blocks), _user_ids(users)),
+        rtl=True if getattr(rm, "rtl", None) else None,
+        photos=photos or None,
+        documents=docs or None,
+        users=users or None,
+    )
+
+
+def rich_from_received(rm, users: Optional[list] = None) -> Rich:
+    return Rich("blocks", _b64(input_of(rm, users)), bool(getattr(rm, "rtl", None)), False, fingerprint(rm))
+
+
+def mention_ids(blocks) -> list:
+    """User ids that the blocks mention by link (a text mention needs the account's access data to be sent again)."""
+    found: list = []
+
+    def walk(o) -> None:
+        if isinstance(o, dict):
+            if o.get("_") == "TextMentionName" and isinstance(o.get("user_id"), int):
+                found.append(o["user_id"])
+            for v in o.values():
+                walk(v)
+        elif isinstance(o, list):
+            for v in o:
+                walk(v)
+
+    for b in blocks or []:
+        walk(b.to_dict())
+    return list(dict.fromkeys(found))
+
+
+async def input_users(client, ids: list) -> list:
+    out = []
+    for uid in ids:
+        try:
+            peer = await client.get_input_entity(uid)
+        except Exception as e:  # noqa: BLE001 - a mention that can't be resolved is sent as the plain name
+            log.info("could not resolve the mentioned user %s: %s", uid, type(e).__name__)
+            continue
+        if isinstance(peer, types.InputPeerUser):
+            out.append(types.InputUser(peer.user_id, peer.access_hash))
+    return out
+
+
+async def received(client, event) -> Optional[Rich]:
+    """The rich message that `event`'s message is (sent natively or forwarded to the bot), or None for an ordinary message."""
+    m = event.message
+    rm = getattr(m, "rich_message", None)
+    if rm is None:
+        return None
+    if getattr(rm, "part", None):  # Telegram sent a part of it; the rest has to be asked for
+        full = None
+        try:
+            got = await client(functions.messages.GetRichMessageRequest(peer=await event.get_input_chat(), id=m.id))
+            full = got if isinstance(got, types.RichMessage) else getattr(got, "rich_message", None)
+        except errors.RPCError as e:
+            log.info("could not read the whole rich message: %s", type(e).__name__)
+        if full is None or getattr(full, "part", None):
+            raise RichError("Telegram only handed me a part of that rich message. Send it again, or type it as HTML / Markdown.")
+        rm = full
+    if not getattr(rm, "blocks", None):
+        raise RichError("That rich message has no content.")
+    return rich_from_received(rm, await input_users(client, mention_ids(rm.blocks)))
+
+
+# --------------------------------------------------------------- when Telegram refuses a block of a received message
+_BLOCK_NAMES = {
+    "Heading1": "heading", "Heading2": "heading", "Heading3": "heading", "Heading4": "heading", "Heading5": "heading",
+    "Heading6": "heading", "Title": "heading", "Subtitle": "heading", "Header": "heading", "Subheader": "heading",
+    "Paragraph": "paragraph", "Preformatted": "code", "Blockquote": "quote", "BlockquoteBlocks": "quote",
+    "Pullquote": "pull quote", "List": "list", "OrderedList": "numbered list", "Details": "expandable section",
+    "Math": "math", "Map": "map", "ButtonRow": "buttons", "Photo": "picture", "Video": "video", "Audio": "audio",
+    "Document": "file", "Collage": "collage", "Slideshow": "slideshow", "Table": "table", "Divider": "rule",
+    "Anchor": "anchor", "Footer": "footer", "Unsupported": "a block this version does not know",
+    "Thinking": "thinking block", "Embed": "embedded page", "EmbedPost": "embedded post", "Channel": "channel card",
+    "RelatedArticles": "related articles", "AuthorDate": "author line", "Kicker": "kicker", "Cover": "cover",
+}
+MAX_PROBES = 60  # blocks that are looked through one by one (at most) when Telegram refuses a message
+
+
+def block_name(b) -> str:
+    """What a block is called to the owner: "map", "table" ..."""
+    raw = re.sub(r"^(?:Input)?PageBlock", "", type(b).__name__)
+    return _BLOCK_NAMES.get(raw, raw.lower() or "block")
+
+
+def is_block_invalid(e: BaseException) -> bool:
+    """Telegram says one of the blocks it was given is not acceptable (RICH_MESSAGE_BLOCK_INVALID)."""
+    return "RICH_MESSAGE_BLOCK_INVALID" in (getattr(e, "message", None) or str(e))
+
+
+async def refused_blocks(client, peer, r: Rich, *, pause: float = 0.4) -> Optional[List[int]]:
+    """The numbers (0, 1, 2 ...) of the top-level blocks of a received rich message that Telegram will not take back.
+
+    Called once the whole message has been refused. Found by sending groups of the blocks to `peer` - a chat with the
+    owner - quietly, and deleting them again straight away. None when it can't be told: the message is typed (Telegram
+    reads that itself), it has too many blocks to look through, no single block is at fault (every part is taken), or
+    something else than a refused block went wrong."""
+    if r.fmt != "blocks":
+        return None
+    whole = to_input(r)
+    blocks = list(whole.blocks)
+    if not blocks or len(blocks) > MAX_PROBES:
+        return None
+
+    async def accepted(idx: List[int]) -> bool:
+        part = copy.copy(whole)
+        part.blocks = [blocks[i] for i in idx]
+        try:
+            made = await flood_retry(
+                lambda: client(
+                    functions.messages.SendMessageRequest(peer=peer, message="", rich_message=part, silent=True)
+                )
+            )
+        except errors.RPCError as e:
+            if is_block_invalid(e):
+                return False
+            raise
+        try:
+            await client(functions.messages.DeleteMessagesRequest(id=[sent_message(made).id], revoke=True))
+        except Exception:  # noqa: BLE001 - a test message that stays is only clutter
+            log.info("could not delete a test message of the rich-message check")
+        await asyncio.sleep(pause)
+        return True
+
+    async def find(idx: List[int], known: bool = False) -> List[int]:
+        if not known and await accepted(idx):
+            return []
+        if len(idx) == 1:
+            return list(idx)
+        mid = len(idx) // 2
+        return await find(idx[:mid]) + await find(idx[mid:])
+
+    try:
+        bad = await find(list(range(len(blocks))), known=True)  # (the whole message was refused: no need to ask again)
+    except Exception as e:  # noqa: BLE001 - this is only a help for the owner
+        log.info("could not find the refused blocks: %s", type(e).__name__)
+        return None
+    return bad or None
+
+
+def block_labels(r: Rich, idx: List[int]) -> str:
+    """"4 (map), 9 (table)": the blocks numbered `idx` (from 0), counted from 1 and named."""
+    blocks = to_input(r).blocks
+    return ", ".join(f"{i + 1} ({block_name(blocks[i])})" for i in sorted(set(idx)) if 0 <= i < len(blocks))
+
+
+def block_count(r: Rich) -> int:
+    return len(to_input(r).blocks) if r.fmt == "blocks" else 0
+
+
+def digest(r: Rich) -> str:
+    """Short mark of what `r` holds (so a button made for one message is not used on another)."""
+    return hashlib.sha1(f"{r.fmt}:{r.source}".encode()).hexdigest()[:6]
+
+
+def pack_blocks(idx: List[int]) -> str:
+    """Block numbers as one short word (the bits of a number, in base 36) - small enough for a button."""
+    n, out = sum(1 << i for i in set(idx)), ""
+    while n:
+        n, d = divmod(n, 36)
+        out = "0123456789abcdefghijklmnopqrstuvwxyz"[d] + out
+    return out or "0"
+
+
+def unpack_blocks(word: str) -> List[int]:
+    n = int(word, 36)
+    return [i for i in range(n.bit_length()) if n >> i & 1]
+
+
+def without_blocks(r: Rich, drop: List[int]) -> Rich:
+    """The received rich message `r` without the top-level blocks numbered `drop` (what Telegram saw of it changes, so the
+    fingerprint is forgotten)."""
+    inp = to_input(r)
+    inp.blocks = [b for i, b in enumerate(inp.blocks) if i not in set(drop)]
+    return Rich("blocks", _b64(inp), r.rtl, r.noautolink, None)
+
+
+# ------------------------------------------------------------------------- plain text (lists, panels, previews)
+_BLOCKY = ("h1", "h2", "h3", "h4", "h5", "h6", "p", "ul", "ol", "li", "table", "tr", "details", "summary", "figure",
+           "figcaption", "aside", "blockquote", "pre", "footer", "hr", "br", "tg-math-block", "tg-button-row", "tg-collage",
+           "tg-slideshow", "tg-map", "img", "video", "audio", "tg-document", "caption", "cite")
+
+
+class _Plain(HTMLParser):
+    def __init__(self) -> None:
+        super().__init__(convert_charrefs=True)
+        self.out: List[str] = []
+        self.skip = 0
+
+    def _break(self, tag: str) -> None:
+        """A line break for a block; two blocks in a row are only one line apart (a 
is always a break).""" + if tag == "br" or (self.out and not self.out[-1].endswith("\n")): + self.out.append("\n") + + def handle_starttag(self, tag, attrs): + if tag in ("script", "style"): + self.skip += 1 + if tag in _BLOCKY: + self._break(tag) + if tag == "li": + self.out.append("• ") + elif tag in ("td", "th"): + self.out.append(" | " if self.out and not self.out[-1].endswith(("\n", " | ")) else "") + elif tag == "input" and any(k == "type" and v == "checkbox" for k, v in attrs): + self.out.append("☑ " if any(k == "checked" for k, _ in attrs) else "☐ ") + + def handle_startendtag(self, tag, attrs): + self.handle_starttag(tag, attrs) + + def handle_endtag(self, tag): + if tag in ("script", "style") and self.skip: + self.skip -= 1 + if tag in _BLOCKY: + self._break(tag) + + def handle_data(self, data): + if not self.skip: + self.out.append(data) + + +def _tidy(text: str) -> str: + lines = [" ".join(line.split()) for line in text.replace("\r", "").split("\n")] + return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip() + + +def _plain_html(source: str) -> str: + p = _Plain() + try: + p.feed(source) + p.close() + except Exception: # noqa: BLE001 - a snippet is not worth failing for + return _tidy(re.sub(r"<[^>]*>", " ", source)) + return _tidy("".join(p.out)) + + +_MD_EMPHASIS = re.compile(r"(\*\*|__|~~|\|\||==)(?=\S)(.+?)(?<=\S)\1") +_MD_SINGLE = re.compile(r"(? str: + out: List[str] = [] + fenced = False + for line in source.replace("\r", "").split("\n"): + if re.match(r"^\s*(```|~~~)", line): + fenced = not fenced + continue + if fenced: + out.append(line) + continue + if re.match(r"^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$", line): # a table's delimiter row + continue + if re.match(r"^\s*(-{3,}|\*{3,}|_{3,})\s*$", line): + out.append("") + continue + line = re.sub(r"^\s{0,3}#{1,6}\s+", "", line) + line = re.sub(r"^(\s*)(?:>\s?)+", r"\1", line) + line = re.sub(r"^(\s*)[-*+]\s+\[[xX]\]\s+", r"\1☑ ", line) + line = re.sub(r"^(\s*)[-*+]\s+\[ \]\s+", r"\1☐ ", line) + line = re.sub(r"^(\s*)[-*+]\s+", r"\1• ", line) + if "|" in line and line.count("|") >= 2: + line = " | ".join(c.strip() for c in line.strip().strip("|").split("|")) + line = re.sub(r"!\[([^\]]*)\]\([^)]*?(?:\s+\"([^\"]*)\")?\)", lambda m: m.group(2) or m.group(1), line) + line = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", line) + line = re.sub(r"^\[\^([^\]\s]+)\]:[ \t]*", r"\1: ", line) # a footnote's text, led by its mark + line = re.sub(r"\[\^[^\]]+\]", "", line) + line = _MD_EMPHASIS.sub(r"\2", line) + line = _MD_SINGLE.sub(r"\2", line) + line = line.replace("`", "") + line = re.sub(r"\\([\\`*_{}\[\]()#+\-.!|~>$=])", r"\1", line) + out.append(line) + return _tidy("\n".join(out)) + + +def _plain_blocks(blocks) -> str: + out: List[str] = [] + + def brk() -> None: + if out and not out[-1].endswith("\n"): + out.append("\n") + + def walk(o) -> None: + if isinstance(o, dict): + name = str(o.get("_", "")) + if name == "PageTableRow": + brk() + for n, cell in enumerate(o.get("cells") or []): + if n: + out.append(" | ") + walk(cell) + brk() + return + item = name.startswith(("PageListItem", "PageListOrderedItem")) + if name.startswith("PageBlock") or item: + brk() + if item: + out.append(("☑ " if o.get("checked") else "☐ ") if o.get("checkbox") else "• ") + for key in sorted(o, key=lambda k: k != "title"): # a title (of a
, a table) is read first + v = o[key] + if key in ("text", "source") and isinstance(v, str): + out.append(v) + elif isinstance(v, (dict, list)): + walk(v) + if name.startswith("PageBlock") or item: + brk() + elif isinstance(o, list): + for v in o: + walk(v) + + for b in blocks or []: + try: + walk(b.to_dict()) + except Exception: # noqa: BLE001 + continue + return _tidy("".join(out)) + + +def plain_of(r: Rich) -> str: + """What the rich message says, as plain text (what My posts shows and searches).""" + if r.fmt == "html": + return _plain_html(r.source) + if r.fmt == "markdown": + return _plain_markdown(r.source) + try: + inp = _unb64(r.source) + return _plain_blocks(getattr(inp, "blocks", None)) + except Exception: # noqa: BLE001 + return "" + + +def plain_of_message(m) -> str: + return _plain_blocks(getattr(getattr(m, "rich_message", None), "blocks", None)) + + +# ---------------------------------------------------------------------------- reading what the owner typed +_FORCE = re.compile(r"\A[ \t]*[ \t]*(?:\r?\n|\Z)", re.I) + +# HTML only rich messages have: headings, paragraphs, lists, tables, details, figures, media, maps, math, buttons, marks ... +_RICH_TAGS = ( + r"h[1-6]", "p", "ul", "ol", "li", "table", "thead", "tbody", "tfoot", "tr", "td", "th", "caption", "details", "summary", + "figure", "figcaption", "aside", "hr", "img", "video", "audio", "footer", "cite", "input", "mark", "sub", "sup", + "tg-document", "tg-map", "tg-collage", "tg-slideshow", "tg-math", "tg-math-block", "tg-button", "tg-button-row", + "tg-time", "tg-reference", +) +_RICH_HTML = re.compile( + r"<(?:" + "|".join(t if t.startswith("h[") else re.escape(t) for t in _RICH_TAGS) + r")(?=[\s/>])[^<>]*>" + r"|]*?\b(?:name\s*=|href\s*=\s*[\"']?#)", + re.I, +) +_BASIC_HTML = re.compile(r"<(?:b|strong|i|em|u|ins|s|strike|del|a|code|pre|blockquote|tg-spoiler|tg-emoji)(?=[\s/>])[^<>]*>", re.I) + +# Markdown only rich messages have (a bullet list or a rule alone does not count: plain posts use those as decoration) +_MD_RICH = ( + re.compile(r"^ {0,3}#{1,6}[ \t]+\S", re.M), # # heading + re.compile(r"^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]+\[[ xX]\](?:[ \t]+\S|[ \t]*$)", re.M), # - [x] task + re.compile(r"^[^\n]*\|[^\n]*\n[ \t]*\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)+\|?[ \t]*$", re.M), # | table | + re.compile(r"\$\$.+?\$\$", re.S), # $$ block math $$ + re.compile(r"^\[\^[^\]\s]+\]:[ \t]+\S", re.M), # [^1]: footnote + re.compile(r"(?||`[^`\n]+`", re.S | re.I) + + +def _blank(m: "re.Match") -> str: + return re.sub(r"[^\n]", " ", m.group()) + + +def detect(text: str, forced: bool = False) -> Optional[str]: + """"html" or "markdown" when `text` needs a rich message (or `forced` says it is one), else None.""" + bare = _CODE.sub(_blank, text) # what stands in code is not markup + html_hit = bool(_RICH_HTML.search(bare)) + if html_hit and bare.lstrip().startswith("<"): + return "html" + if any(rx.search(bare) for rx in _MD_RICH): + return "markdown" + if html_hit: + return "html" + if forced: + return "html" if _BASIC_HTML.search(bare) else "markdown" + return None + + +def read_typed(text: str) -> Optional[Rich]: + """The rich message that text typed as HTML or Markdown stands for, or None when it is an ordinary text. + + It is a rich message when it has something only rich messages have (a heading, a table, a task list, math, a picture, +
...), or when its first line is ```` (````, ````). Telegram reads the + language itself; what is passed on is exactly what was typed (without that first line).""" + text = text or "" + force = _FORCE.match(text) + body = text[force.end():] if force else text + fmt = detect(body, forced=bool(force)) + if fmt is None or not body.strip(): + return None + words = (force.group(1) or "").lower().split() if force else [] + return Rich(fmt, body.strip(), rtl="rtl" in words, noautolink="noautolink" in words) + + +def check(r: Rich) -> None: + """RichError when Telegram would not take it (only the limit that is cheap to check here).""" + if r.fmt != "blocks" and len(r.source) > MAX_SOURCE: + raise RichError(f"A rich message can have at most {MAX_SOURCE} characters (yours has {len(r.source)}).") + + +def with_fingerprint(r: Rich, fp: Optional[str]) -> Rich: + return replace(r, fp=fp) + + +# --------------------------------------------------------------------------------------- the /rich help pages +RICH_HELP = ( + "🧩 Rich messages\n\n" + "Telegram's newer message type: headings, lists, tables, expandable sections, math, maps, pictures and buttons in one " + "message (up to 32768 characters, 500 blocks, 16 nesting levels, 50 pictures/files, 20 table columns). The bot " + "publishes your text as one when\n" + "• you send it a rich message made in Telegram, or forward one: it is kept block for block, or\n" + "• you type HTML or Markdown that has something only rich messages have: a heading, a table, a task list, math, a " + "picture, <details>, <h1>, <table> ... or\n" + "• the first line is just <rich> (<rich rtl> for right-to-left text, " + "<rich noautolink> so links, @names and #tags are not made clickable).\n\n" + "Telegram reads the text itself, so everything it supports works. 👁 Preview shows what it made of your text before " + "you publish. Rich messages are for text posts - a photo's caption can't be rich. The post's own link buttons " + "(➕ Button) work with them.\n\n" + "Markdown\n" + "**bold** *italic* ~~strike~~ ||spoiler|| ==marked== `code` (underline, subscript and superscript: HTML " + "<u> <sub> <sup>)\n" + "# Heading … ###### Heading\n" + "- item 1. item lists, - [ ] task - [x] done, --- a rule\n" + "> quote (a bare > line is a new paragraph inside it)\n" + "```python … ``` a code block with a language\n" + "$x^2$ inline math, $$E = mc^2$$ or a ```math block: a formula block\n" + "| a | b | then |:--|--:| then rows: a table (colons set the alignment; cells hold inline " + "formatting only)\n" + "text[^1] and a line [^1]: the note: a footnote\n" + "![](https://…/pic.jpg \"caption\") alone on a line: a picture, video, audio, GIF or file (https links " + "only); put several such lines inside <tg-collage> or <tg-slideshow>\n" + "![22:45 tomorrow](tg://time?unix=1647531900&format=wDT) a date shown in the reader's time\n" + "![](tg://emoji?id=5368324170671202286) a custom emoji\n" + "[name](tg://user?id=123) [mail](mailto:a@b.c) [call](tel:+123)\n" + "Raw HTML works inside Markdown, but Markdown is not read inside block tags (only inside <details>, " + "<tg-collage> and <tg-slideshow>)." +) + +RICH_HELP_HTML = ( + "🧩 Rich HTML\n\n" + "<h1> … <h6> <p> <hr> " + "<footer> <b> <i> <u> <s> <mark> <sub> <sup> " + "<code> <tg-spoiler> <br>\n" + "<pre><code class=\"language-python\"> a code block\n" + "<ul> <ol start=\"3\" type=\"a\" reversed> " + "<li value=\"7\" type=\"i\"> (type: a, A, i, I, 1) " + "<input type=\"checkbox\" checked>\n" + "<blockquote expandable>text<cite>who</cite></blockquote> and " + "<aside>pull quote<cite>who</cite></aside>\n" + "<details open><summary>Title</summary>…</details> an expandable section\n" + "<table bordered striped compact><caption>…</caption><tr><th colspan=\"2\" " + "align=\"center\" valign=\"middle\">… (td and th: colspan, rowspan, align left/center/right, valign " + "top/middle/bottom)\n" + "<tg-math>x^2</tg-math> <tg-math-block>E = mc^2</tg-math-block> " + "(raw LaTeX)\n" + "<tg-time unix=\"1647531900\" format=\"wDT\">22:45 tomorrow</tg-time>\n" + "<tg-emoji emoji-id=\"5368324170671202286\">🙂</tg-emoji>\n" + "<a name=\"top\"></a> and <a href=\"#top\"> anchors; " + "<tg-reference name=\"n1\">text</tg-reference> with <a href=\"#n1\"> " + "a footnote\n" + "<img src=\"https://…\"> <video src=…> <audio src=…> " + "<tg-document src=…>, each on its own or in " + "<figure>…<figcaption>caption<cite>credit</cite></figcaption></figure> " + "(https links only; tg-spoiler on img/video hides it); several inside " + "<tg-collage> or <tg-slideshow>\n" + "<tg-map lat=\"41.9\" long=\"12.5\" zoom=\"14\"/> a map\n" + "<tg-button-row align=\"center\"><tg-button type=\"url\" url=\"https://t.me\" " + "style=\"success\">Open</tg-button></tg-button-row> buttons in the text. Types: url, " + "web_app and login_url (url=), callback_data (data=), copy_text (text=), switch_inline_query, " + "switch_inline_query_current_chat, switch_inline_query_chosen_chat (query=), disabled. Styles: primary, success, " + "danger, link.\n" + "&lt; &gt; &amp; stand for < > & when they must stay as they are.\n\n" + "Good to know\n" + "• A picture or video typed into a rich message must be a public https link. To use a file that exists only on " + "Telegram, send the bot a rich message that already contains it.\n" + "• A button inside the text that needs the bot (callback_data) only works for the bot that made it - for a forwarded " + "rich message that is another bot.\n" + "• /swap, /handleswap and the post-link changes of /repost change a rich post's buttons, not the links inside its text.\n" + "• Older Telegram apps may not show rich messages." +) diff --git a/app/richtext.py b/app/richtext.py new file mode 100644 index 0000000000000000000000000000000000000000..3ca75cd707ae16cc5861ae8eb0165b3ed4805566 --- /dev/null +++ b/app/richtext.py @@ -0,0 +1,552 @@ +"""Telegram formatting from text typed as HTML or Markdown - for when Telegram's own editor is not at hand. + +A message the owner sends can carry Telegram's own formatting: that is used exactly as it is. When it carries none, the +text is read as HTML (when it holds a supported tag together with its closing tag) or else as Markdown, and what is +recognised becomes real formatting. Whatever is not recognised stays as it was typed, so ordinary text (``5 * 3``, +``snake_case_names``, ``<3``, ``[Group] Title``, ``Sub | Dub``) is left alone. + +HTML, like Telegram's own HTML mode: + , , , , or , , +
 (
..
names a language), ,
and +
, 🙂,
for a line break. + ``<`` ``>`` ``&`` stand for those characters. Any other tag is left as typed. + +Markdown: + **bold** *italic* _italic_ __underline__ ~~strikethrough~~ ||spoiler|| `code` ```code block``` + [text](https://link) ![🙂](tg://emoji?id=123) a line that starts with ``>`` is quoted (``**>`` starts an + expandable quote that ends with ``||``) and a backslash before a punctuation mark keeps it as it is. + As in CommonMark, a mark must touch the text it formats (``**bold**``, not ``** bold **``), and a lone ``*`` or + ``_`` inside a word does nothing. A link typed as it is (https://...) is never cut up by marks inside it. + +Entities come out in the form the bot stores them (see ``tgutil.ser_entities``), with UTF-16 offsets like Telegram's. +""" +from __future__ import annotations + +import logging +import re +import unicodedata +from html.parser import HTMLParser +from typing import List, Optional, Tuple + +from .tgutil import ser_entities, utf16_len + +log = logging.getLogger(__name__) + +Span = Tuple[str, int, int, object] # (kind, offset, length, arg) - offsets in UTF-16 units, like Telegram's own + + +def _entity(kind: str, offset: int, length: int, arg=None) -> dict: + """One entity as the bot stores it; `arg` is the pre block's language, the link, the emoji id or "expandable".""" + e = {"k": kind, "o": offset, "l": length} + if kind == "pre": + e["g"] = arg or "" + elif kind == "url": + e["u"] = arg + elif kind == "quote": + e["c"] = bool(arg) + elif kind == "emoji": + e["d"] = arg + return e + + +_NO_NEST = {"bold", "italic", "underline", "strike", "spoiler", "code", "quote", "url"} # a second one inside the first adds nothing + + +def _entities(spans: List[Span]) -> list: + """Entities for the spans, outer ones first (same start: the longer one). + + A span of a kind that lies wholly inside another of the same kind (``a b``, a quote in a quote) is left + out: it changes nothing on screen, and Telegram does not want such entities nested.""" + out: list = [] + kept: List[Tuple[str, int, int]] = [] + for kind, offset, length, arg in sorted((s for s in spans if s[2] > 0), key=lambda s: (s[1], -s[2])): + if kind in _NO_NEST and any(k == kind and offset >= a and offset + length <= b for k, a, b in kept): + continue + kept.append((kind, offset, offset + length)) + out.append(_entity(kind, offset, length, arg)) + return out + + +# ------------------------------------------------------------------------------------------------------ links +_SCHEMES = ("http://", "https://", "tg://", "ton://") +_DOMAIN = re.compile(r"(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,}(?::\d{1,5})?(?:[/?#]\S*)?") + + +def clean_url(raw: Optional[str]) -> Optional[str]: + """The link as Telegram wants it, or None when it is no link (``t.me/x`` gets its https://).""" + url = (raw or "").strip() + if not url or len(url) > 2000 or any(c.isspace() for c in url): + return None + low = url.lower() + for scheme in _SCHEMES: + if low.startswith(scheme): + return url if len(url) > len(scheme) else None + return "https://" + url if _DOMAIN.fullmatch(url) else None + + +# ------------------------------------------------------------------------------------------------------- HTML +_TAGS = ("b", "strong", "i", "em", "u", "ins", "s", "strike", "del", "a", "code", "pre", "blockquote", "tg-spoiler", "tg-emoji", "span") +_HTML_PAIR = re.compile(r"<(" + "|".join(re.escape(t) for t in _TAGS) + r")(?:\s[^<>]*)?>.*?", re.I | re.S) +_KIND_OF_TAG = { + "b": "bold", "strong": "bold", "i": "italic", "em": "italic", "u": "underline", "ins": "underline", + "s": "strike", "strike": "strike", "del": "strike", "tg-spoiler": "spoiler", "span": "spoiler", +} + + +def looks_like_html(text: str) -> bool: + """A supported tag with its closing tag is there (a lone ```` in a sentence is just text).""" + return bool(_HTML_PAIR.search(text)) + + +class _Html(HTMLParser): + """Collects the text and the formatting of an HTML message; what it does not know is kept as it was typed.""" + + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.parts: List[str] = [] + self.pos = 0 # UTF-16 length of the text so far + self.open: List[dict] = [] + self.spans: List[Span] = [] + + def text(self, s: str) -> None: + if s: + self.parts.append(s) + self.pos += utf16_len(s) + + def literal_zone(self) -> bool: + """Inside
 /  everything is code, so a tag there is shown as typed."""
+        return any(o["tag"] in ("pre", "code") for o in self.open)
+
+    # --- tags
+    def handle_starttag(self, tag, attrs):
+        t, a = tag.lower(), {k: (v or "") for k, v in attrs}
+        raw = self.get_starttag_text() or ""
+        if t == "br" and not self.literal_zone():
+            self.text("\n")
+            return
+        if self.literal_zone():
+            top = self.open[-1]
+            if t == "code" and top["tag"] == "pre" and self.pos == top["start"] and "lang" not in top:
+                cls = a.get("class", "")
+                top["lang"] = cls[len("language-"):] if cls.startswith("language-") else ""
+                self.open.append({"tag": "code", "start": self.pos, "holder": True})
+            else:
+                self.text(raw)
+            return
+        if t == "span" and "tg-spoiler" not in a.get("class", "").split():
+            self.text(raw)
+        elif t in _TAGS:
+            self.open.append({"tag": t, "start": self.pos, "attrs": a})
+        else:
+            self.text(raw)
+
+    def handle_startendtag(self, tag, attrs):
+        if tag.lower() == "br" and not self.literal_zone():
+            self.text("\n")
+        else:
+            self.text(self.get_starttag_text() or "")
+
+    def handle_endtag(self, tag):
+        t = tag.lower()
+        if t == "br":
+            return
+        idx = next((i for i in range(len(self.open) - 1, -1, -1) if self.open[i]["tag"] == t), None)
+        if idx is None:
+            self.text(f"")
+            return
+        while len(self.open) > idx:  # a tag opened inside it and never closed ends with it
+            self.close_tag(self.open.pop())
+
+    def close_tag(self, o: dict) -> None:
+        length = self.pos - o["start"]
+        if length <= 0 or o.get("holder"):
+            return
+        t, a = o["tag"], o.get("attrs", {})
+        if t in _KIND_OF_TAG:
+            self.spans.append((_KIND_OF_TAG[t], o["start"], length, None))
+        elif t == "code":
+            self.spans.append(("code", o["start"], length, None))
+        elif t == "pre":
+            self.spans.append(("pre", o["start"], length, o.get("lang", "")))
+        elif t == "a":
+            url = clean_url(a.get("href"))
+            if url:
+                self.spans.append(("url", o["start"], length, url))
+        elif t == "blockquote":
+            self.spans.append(("quote", o["start"], length, "expandable" in a))
+        elif t == "tg-emoji":
+            emoji_id = a.get("emoji-id", "")
+            if emoji_id.isdigit():
+                self.spans.append(("emoji", o["start"], length, int(emoji_id)))
+
+    # --- text and the rest
+    def handle_data(self, data):
+        self.text(data)
+
+    def handle_comment(self, data):
+        self.text(f"")
+
+    def handle_decl(self, decl):
+        self.text(f"")
+
+    def handle_pi(self, data):
+        self.text(f"")
+
+    def finish(self) -> Tuple[str, List[Span]]:
+        self.close()
+        while self.open:  # a tag that was never closed ends with the text
+            self.close_tag(self.open.pop())
+        return "".join(self.parts), self.spans
+
+
+def from_html(source: str) -> Tuple[str, list]:
+    """(text, entities) of an HTML message."""
+    parser = _Html()
+    parser.feed(source)
+    text, spans = parser.finish()
+    return text, _entities(spans)
+
+
+# --------------------------------------------------------------------------------------------------- Markdown
+_FENCE = re.compile(r"```(?:([A-Za-z0-9_+#.-]{1,30})\n)?(.+?)```", re.S)
+_EMOJI = re.compile(r"!\[([^\[\]\n]{1,16})\]\(tg://emoji\?id=(\d{1,20})\)")
+_BARE_URL = re.compile(r"(?:https?|tg|ton)://[^\s<>]+", re.I)
+_URL_END = "?!.,:;*_~|\"'"  # what may follow a link without being part of it (a mark, or the end of a sentence)
+_KIND_OF_MARK = {("*", 2): "bold", ("*", 1): "italic", ("_", 2): "underline", ("_", 1): "italic", ("~", 2): "strike", ("|", 2): "spoiler"}
+MAX_MARKS = 400  # a message with more marks than this is left as typed (keeps the matching fast)
+
+
+def _punct(ch: str) -> bool:
+    return unicodedata.category(ch)[0] in "PS"
+
+
+def _flanking(mark: str, run: int, prev: Optional[str], nxt: Optional[str]) -> Tuple[bool, bool]:
+    """(can open, can close) for a run of `run` marks between the characters `prev` and `nxt`, by the CommonMark rules:
+    it opens when text follows it and closes when text comes before it. A lone ``*`` and ``_`` also need a space or
+    punctuation outside, so ``snake_case`` and a censored f*ck ... s*it stay as typed (``**bold**text`` still works)."""
+    prev_space, next_space = prev is None or prev.isspace(), nxt is None or nxt.isspace()
+    prev_punct, next_punct = prev is not None and _punct(prev), nxt is not None and _punct(nxt)
+    left = not next_space and (not next_punct or prev_space or prev_punct)
+    right = not prev_space and (not prev_punct or next_space or next_punct)
+    if mark == "_" or (mark == "*" and run == 1):
+        return left and (not right or prev_punct), right and (not left or next_punct)
+    return left, right
+
+
+def _bare_url(s: str, i: int) -> Optional[str]:
+    """A link typed as it is (https://...) that starts at s[i], without what ends the sentence or closes a mark."""
+    if i and s[i - 1].isalnum():
+        return None
+    m = _BARE_URL.match(s, i)
+    if not m:
+        return None
+    url = m.group()
+    while url:
+        last = url[-1]
+        if last in _URL_END or (last in ")]" and url.count(last) > url.count("(" if last == ")" else "[")):
+            url = url[:-1]
+        else:
+            break
+    return url if len(url) > url.index("//") + 2 else None
+
+
+def _link_at(s: str, i: int) -> Optional[Tuple[str, str, int]]:
+    """``[label](url)`` that starts at s[i]: (label, url, end) or None."""
+    depth, j, limit = 0, i, min(len(s), i + 600)
+    while j < limit:
+        ch = s[j]
+        if ch == "\\":
+            j += 2
+            continue
+        if ch == "[":
+            depth += 1
+        elif ch == "]":
+            depth -= 1
+            if depth == 0:
+                break
+        j += 1
+    else:
+        return None
+    if j + 1 >= len(s) or s[j + 1] != "(":
+        return None
+    k, depth, limit = j + 2, 1, min(len(s), j + 2 + 2000)
+    while k < limit:
+        ch = s[k]
+        if ch.isspace():
+            return None
+        if ch == "(":
+            depth += 1
+        elif ch == ")":
+            depth -= 1
+            if depth == 0:
+                break
+        k += 1
+    else:
+        return None
+    url, label = clean_url(s[j + 2:k]), s[i + 1:j]
+    return (label, url, k + 1) if url and label.strip() else None
+
+
+class _Node:
+    """A piece of a paragraph: plain text, a code span, an emoji, a link, or a run of marks ("d")."""
+
+    __slots__ = ("kind", "text", "spans", "arg", "ch", "orig", "left", "can_open", "can_close", "start")
+
+    def __init__(self, kind, text="", spans=None, arg=None, ch="", orig=0, can_open=False, can_close=False):
+        self.kind, self.text, self.spans, self.arg = kind, text, spans or [], arg
+        self.ch, self.orig, self.left, self.can_open, self.can_close = ch, orig, orig, can_open, can_close
+        self.start = 0
+
+
+def _inline(s: str, nested: bool = False) -> Tuple[str, List[Span]]:
+    """Text and formatting of Markdown inside one paragraph (or one quote)."""
+    nodes: List[_Node] = []
+    buf: List[str] = []
+
+    def flush() -> None:
+        if buf:
+            nodes.append(_Node("t", "".join(buf)))
+            buf.clear()
+
+    i, n = 0, len(s)
+    while i < n:
+        c = s[i]
+        if c == "\\" and i + 1 < n and s[i + 1].isascii() and _punct(s[i + 1]):
+            buf.append(s[i + 1])
+            i += 2
+            continue
+        if c == "`":
+            run = 1
+            while i + run < n and s[i + run] == "`":
+                run += 1
+            close = re.compile(r"(? i + run:
+                flush()
+                nodes.append(_Node("code", s[i + run:close.start()]))
+                i = close.end()
+            else:
+                buf.append("`" * run)
+                i += run
+            continue
+        if c == "!" and s.startswith("![", i):
+            m = _EMOJI.match(s, i)
+            if m:
+                flush()
+                nodes.append(_Node("emoji", m.group(1), arg=int(m.group(2))))
+                i = m.end()
+                continue
+        if c == "[" and not nested:
+            link = _link_at(s, i)
+            if link:
+                flush()
+                label, url, end = link
+                inner, spans = _inline(label, nested=True)
+                nodes.append(_Node("link", inner, spans, url))
+                i = end
+                continue
+        if c in "hHtT":
+            url = _bare_url(s, i)
+            if url:
+                buf.append(url)
+                i += len(url)
+                continue
+        if c in "*_~|":
+            run = 1
+            while i + run < n and s[i + run] == c:
+                run += 1
+            if c in "~|" and run != 2:
+                buf.append(c * run)
+            else:
+                flush()
+                can_open, can_close = _flanking(c, run, s[i - 1] if i else None, s[i + run] if i + run < n else None)
+                nodes.append(_Node("d", ch=c, orig=run, can_open=can_open, can_close=can_close))
+            i += run
+            continue
+        buf.append(c)
+        i += 1
+    flush()
+    return _assemble(nodes)
+
+
+def _assemble(nodes: List[_Node]) -> Tuple[str, List[Span]]:
+    """Match the marks (CommonMark's delimiter-stack way), then lay out the text and the spans."""
+    marks = [k for k, nd in enumerate(nodes) if nd.kind == "d"]
+    if len(marks) > MAX_MARKS:
+        for k in marks:
+            nodes[k].can_open = nodes[k].can_close = False
+    pairs: List[Tuple[int, int, str]] = []
+    for pos, j in enumerate(marks):
+        closer = nodes[j]
+        while closer.can_close and closer.left > 0:
+            found = None
+            for kk in range(pos - 1, -1, -1):
+                opener = nodes[marks[kk]]
+                if opener.ch != closer.ch or not opener.can_open or opener.left <= 0:
+                    continue
+                # a mark that could do both: runs whose lengths add up to a multiple of 3 do not pair (unless each is one)
+                both = (opener.can_close or closer.can_open) and (opener.orig + closer.orig) % 3 == 0
+                if closer.ch in "*_" and both and not (opener.orig % 3 == 0 and closer.orig % 3 == 0):
+                    continue
+                found = kk
+                break
+            if found is None:
+                break
+            opener = nodes[marks[found]]
+            use = 2 if opener.left >= 2 and closer.left >= 2 else 1
+            pairs.append((marks[found], j, _KIND_OF_MARK[(closer.ch, use)]))
+            opener.left -= use
+            closer.left -= use
+            for between in marks[found + 1:pos]:  # what lies between the two can no longer pair across them
+                nodes[between].can_open = nodes[between].can_close = False
+    out: List[str] = []
+    pos = 0
+    for nd in nodes:
+        nd.start = pos
+        piece = nd.ch * nd.left if nd.kind == "d" else nd.text  # marks that found no partner stay as typed
+        out.append(piece)
+        pos += utf16_len(piece)
+    spans: List[Span] = []
+    for a, b, kind in pairs:
+        begin = nodes[a].start + nodes[a].left
+        spans.append((kind, begin, nodes[b].start - begin, None))
+    for nd in nodes:
+        length = utf16_len(nd.text)
+        if nd.kind == "code":
+            spans.append(("code", nd.start, length, None))
+        elif nd.kind == "emoji":
+            spans.append(("emoji", nd.start, length, nd.arg))
+        elif nd.kind == "link":
+            spans.append(("url", nd.start, length, nd.arg))
+            spans.extend((k, nd.start + o, ln, arg) for k, o, ln, arg in nd.spans)
+    return "".join(out), spans
+
+
+def _quote_line(line: str) -> Optional[Tuple[str, bool]]:
+    """(the line without its mark, whether it starts an expandable quote) when `line` is part of a quote."""
+    expandable = line.startswith("**>")
+    if expandable or (line.startswith(">") and not line.startswith(">>")):  # ">> Download <<" is decoration, not a quote
+        body = line[3:] if expandable else line[1:]
+        return (body[1:] if body.startswith(" ") else body), expandable
+    return None
+
+
+def _blocks(seg: str) -> Tuple[str, List[Span]]:
+    """A stretch of Markdown without code blocks: paragraphs and quotes."""
+    runs: List[list] = []  # [is_quote, expandable, lines]
+    for line in seg.split("\n"):
+        q = _quote_line(line)
+        if q is None:
+            if runs and not runs[-1][0]:
+                runs[-1][2].append(line)
+            else:
+                runs.append([False, False, [line]])
+        elif runs and runs[-1][0] and not q[1]:
+            runs[-1][2].append(q[0])
+        else:
+            runs.append([True, q[1], [q[0]]])
+    out: List[str] = []
+    spans: List[Span] = []
+    pos = 0
+    for is_quote, expandable, lines in runs:
+        if is_quote and expandable and lines[-1].endswith("||"):
+            lines[-1] = lines[-1][:-2]
+        text, inner = _inline("\n".join(lines))
+        spans.extend((kind, pos + o, n, arg) for kind, o, n, arg in inner)
+        if is_quote and text.strip():
+            spans.append(("quote", pos, utf16_len(text), expandable))
+        out.append(text)
+        pos += utf16_len(text) + 1  # + the line break that separates it from the next run
+    return "\n".join(out), spans
+
+
+def from_markdown(source: str) -> Tuple[str, list]:
+    """(text, entities) of a Markdown message."""
+    out: List[str] = []
+    spans: List[Span] = []
+    pos = 0
+
+    def add(text: str, found: List[Span]) -> None:
+        nonlocal pos
+        spans.extend((kind, pos + o, n, arg) for kind, o, n, arg in found)
+        out.append(text)
+        pos += utf16_len(text)
+
+    last = 0
+    for m in _FENCE.finditer(source):
+        code = m.group(2)
+        if m.group(1) is None and code.startswith("\n"):
+            code = code[1:]
+        if code.endswith("\n"):
+            code = code[:-1]
+        if not code:
+            continue
+        add(*_blocks(source[last:m.start()]))
+        add(code, [("pre", 0, utf16_len(code), m.group(1) or "")])
+        last = m.end()
+    add(*_blocks(source[last:]))
+    return "".join(out), _entities(spans)
+
+
+# ------------------------------------------------------------------------------------------- what the bot uses
+def convert(text: str) -> Tuple[str, list, Optional[str]]:
+    """(text, entities, "html" | "markdown" | None) for text that carries no Telegram formatting.
+
+    Text with nothing to read comes back as it was (the third value None). It never raises: text the readers choke
+    on is simply used as typed, so a post is never lost to a formatting quirk.
+    """
+    try:
+        if looks_like_html(text):
+            new, ents = from_html(text)
+            return new, ents, "html"
+        new, ents = from_markdown(text)
+    except Exception:  # noqa: BLE001
+        log.warning("could not read the formatting of a text - using it as typed", exc_info=True)
+        return text, [], None
+    return (new, ents, "markdown") if (ents or new != text) else (text, [], None)
+
+
+def message_text(m, enabled: bool = True) -> Tuple[str, list, Optional[str]]:
+    """(text, entities in the form the bot stores, "html" | "markdown" | None) of a message the owner sent.
+
+    Telegram's own formatting wins: a message that has some is kept exactly as it is. Otherwise HTML or Markdown in
+    the text becomes formatting (unless `enabled` is False). The last value says which one was read.
+    """
+    text = m.raw_text or ""
+    own = ser_entities(m.entities)  # (links, @mentions, #tags ... that Telegram finds by itself are not formatting)
+    if own or not enabled or not text:
+        return text, own, None
+    return convert(text)
+
+
+CHEAT_SHEET = (
+    "✍️ Formatting\n\n"
+    "Send a post with Telegram's own formatting (bold, italic, quote, spoiler, links ...) and it is published exactly "
+    "like that. When you can't use Telegram's editor, type Markdown or HTML instead - the bot turns it "
+    "into real formatting. A message that already has Telegram formatting is used as it is, and text the bot doesn't "
+    "recognise stays as you typed it. 👁 Preview shows the result before you publish.\n\n"
+    "Markdown\n"
+    "**bold** *italic* _italic_ __underline__ "
+    "~~strike~~ ||spoiler||\n"
+    "`code` and ```code block``` (```python and a line break names the language)\n"
+    "[text](https://t.me/name) - a link\n"
+    "> quote - a line that starts with > is quoted (**> on the first line and "
+    "|| at the end of the last one make it expandable)\n"
+    "\\* - a backslash keeps the next mark as it is. As in any Markdown, the marks must touch the text "
+    "(**bold**, not ** bold **) and _ inside a word does nothing.\n\n"
+    "HTML\n"
+    "<b>bold</b> <i>italic</i> "
+    "<u>underline</u> <s>strike</s> "
+    "<tg-spoiler>spoiler</tg-spoiler>\n"
+    "<code>code</code> <pre>block</pre> "
+    "<a href=\"https://t.me/name\">link</a>\n"
+    "<blockquote>quote</blockquote> (<blockquote expandable> for an "
+    "expandable one) and <br> for a line break.\n"
+    "Write &lt; for a < that must stay. A text that has an HTML tag with its closing tag is read "
+    "as HTML only.\n\n"
+    "Example\n"
+    "
**Attack on Titan** - Episode 12\n"
+    "__Hindi__ | ||spoiler||\n"
+    "[Watch here](https://t.me/yourchannel)
\n\n" + "🧩 Headings, lists, tables, expandable sections, math, maps, pictures and buttons are rich messages - " + "see /rich." +) diff --git a/app/servicemsg.py b/app/servicemsg.py new file mode 100644 index 0000000000000000000000000000000000000000..ec76da4667723cdeec5bd84dbd35dff618140d27 --- /dev/null +++ b/app/servicemsg.py @@ -0,0 +1,55 @@ +"""Service messages: the notices Telegram puts into a channel by itself - "channel name changed", "channel photo +updated", " pinned a message", "live stream started" ... The bot removes them from every connected channel. +""" +from __future__ import annotations + +import logging +from dataclasses import dataclass +from typing import Optional + +from telethon import errors, functions, types + +from .tgutil import flood_retry + +log = logging.getLogger(__name__) + +# Telegram refusals that mean "the bot has no right to delete here" (worth telling the owner about) +RIGHTS_ERRORS = ("ChatAdminRequiredError", "ChatWriteForbiddenError", "ChannelPrivateError", "UserNotParticipantError") + + +def is_service(m) -> bool: + return isinstance(m, types.MessageService) + + +def action_label(m) -> str: + """'PinMessage', 'ChatEditTitle', 'GroupCall' ... - for the log.""" + name = type(getattr(m, "action", None)).__name__ + return name[len("MessageAction"):] if name.startswith("MessageAction") else name + + +@dataclass +class Removed: + deleted: int = 0 + failed: int = 0 + error: Optional[BaseException] = None # the first thing Telegram refused with + + @property + def error_name(self) -> Optional[str]: + return type(self.error).__name__ if self.error is not None else None + + +async def remove(client, peer, ids: list) -> Removed: + """Delete these messages, 100 per request. A refusal is reported in the result, never raised.""" + out = Removed() + ids = sorted(set(ids)) + for i in range(0, len(ids), 100): + part = ids[i : i + 100] + try: + res = await flood_retry(lambda part=part: client(functions.channels.DeleteMessagesRequest(channel=peer, id=part))) + except errors.RPCError as e: + out.failed += len(part) + out.error = out.error or e + continue + n = getattr(res, "pts_count", None) + out.deleted += len(part) if n is None else min(len(part), int(n)) + return out diff --git a/app/shift_engine.py b/app/shift_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..69930c38817aabb3c809557172f2c7bf92f0bdcd --- /dev/null +++ b/app/shift_engine.py @@ -0,0 +1,187 @@ +"""/shift: copy posts of one channel into another channel - text, formatting, media, albums, buttons and replies +- and register the copies in My posts. The source is only read, never changed or deleted. + +It is the /repost copy loop pointed at two channels. Links from a shifted post to another post of the source channel +follow the content: when that post was shifted too, the link points at its copy in the destination. + +Three optional extras are remembered with the shift (job marks), so that continuing a stopped shift keeps them: + -c afterwards every link to a post of the source, in ANY connected channel, is pointed at the copy + (crosslinks.relink_after_shift; the source itself is only read); + -all afterwards the destination gets the source's name, description and profile photo + (profile_copy.copy_profile); + --no-media the copies get no files: every post is copied as its text, with its formatting and buttons (mark "nomedia"; + repost_engine.without_files). A post that is only a file has nothing to copy and is left out. + +When Telegram hides the first new copies (read back right after posting) the shift stops by itself - more copies would +only be more posts nobody can see - and goes on only when the owner presses Continue (mark "hiddenok"). + +A source that Telegram restricts (a copyright strike: "This channel is unavailable due to copyright infringement", its +posts marked or shown as a notice) is copied from what My posts saved of its posts - every post that has a saved copy, +however intact Telegram's version looks (repost_engine.copy_source). A post without a saved copy is copied as Telegram +hands it out if that is the post itself, and skipped if it is only the notice. A source that can't be read at all (a +banned or private channel) is copied from My posts alone: mark "fromdb", set when the plan was made that way. +""" +from __future__ import annotations + +import logging +from types import SimpleNamespace +from typing import Any, Awaitable, Callable, Optional + +from .crosslinks import CrossResult, relink_after_shift, shift_links +from .profile_copy import copy_profile +from .repost_engine import ( + STOP_IF_HIDDEN, + CopyJob, + DeleteResult, + RepostOptions, + RepostPlan, + RepostResult, + copy_loop, + delete_pending, + plan_from_saved, + relink_copies, + saved_lookup, + saved_units, +) +from .restrictions import probe_channel +from .tgutil import peer_of + +log = logging.getLogger(__name__) + + +def source_of(shift) -> SimpleNamespace: + """The source channel as stored with the shift (it need not be registered in the bot).""" + return SimpleNamespace( + id=shift.src_channel_id, access_hash=shift.src_access_hash, username=shift.src_username, title=shift.src_title + ) + + +async def plan_from_my_posts( + db, src, first_id=None, last_id=None, unreadable=None, no_media: bool = False +) -> Optional[RepostPlan]: + """The plan of a shift made from My posts alone, for a source that can't be read; None when My posts has nothing + of that channel (in that range).""" + plan = plan_from_saved( + src, await db.sent_posts_from(src.id, first_id or 1), RepostOptions(), first_id=first_id, last_id=last_id, + unreadable=unreadable, no_media=no_media, + ) + return None if plan.error else plan + + +async def run_shift( + client, + db, + shift, + dst, + user_id: int, + *, + delay: float = 1.2, + settle_pause: float = 0.7, + progress: Optional[Callable[[RepostResult], Awaitable[None]]] = None, + should_stop: Optional[Callable[[], bool]] = None, +) -> RepostResult: + """Copy the posts shift.first_id..shift.last_id of the source into `dst` (a registered channel), in order. + Safe to run again to continue: posts that already have a copy are skipped.""" + src = source_of(shift) + idmap = dict(await db.shift_pairs(shift.id, alive_only=False)) + links = shift_links(src, dst, idmap) + marks = await db.marks_of(shift.id) + from_db = "fromdb" in marks # the source can't be read: its posts come from My posts alone + restricted = None + if not from_db: # does Telegram restrict the source channel itself (a copyright strike)? Then My posts is used + try: + _top, restricted, _err = await probe_channel(client, peer_of(src)) + except Exception: # unknown is treated as "not restricted": marks on single posts and the read-back still guard + log.warning("could not ask Telegram whether the source channel is restricted", exc_info=True) + job = CopyJob( + src_peer=peer_of(src), + dst_peer=peer_of(dst), + opts=RepostOptions(), + links=links, + first_id=shift.first_id, + last_id=shift.last_id, + done=await db.shift_done_ids(shift.id), + idmap=idmap, + record=lambda rows: db.record_shift(shift.id, dst.id, rows, user_id), + saved=saved_lookup(db, src.id), # posts Telegram holds back (a copyright strike) are copied from My posts + use_saved=True, + units=(lambda: saved_units(db, src.id, shift.first_id, shift.last_id)) if from_db else None, + from_db=from_db, + restricted=restricted, + no_media="nomedia" in marks, + stop_if_hidden=0 if "hiddenok" in marks else STOP_IF_HIDDEN, # the owner said to go on although Telegram hides them + ) + res = await copy_loop(client, job, delay=delay, progress=progress, should_stop=should_stop, settle_pause=settle_pause) + if not res.stopped and not res.aborted: + res.phase = "finish" + if progress: + await progress(res) + try: + pairs = await db.shift_pairs(shift.id) + res.final = await relink_copies( + client, db, dst, dict(pairs), [n for _, n in pairs], links=links, delay=delay, + settle_pause=settle_pause, should_stop=should_stop, + ) + except Exception as e: # the copies are fine; only the links between them were not updated + log.exception("pointing the links of a shift at the copies failed") + res.final_error = type(e).__name__ + marks = await db.marks_of(shift.id) + if "profile" in marks and "profile_done" not in marks: + await shift_profile(client, db, shift, dst, user_id, res, progress) + if "relink" in marks and not (res.final is not None and res.final.stopped): + res.phase = "links" + res.cross = CrossResult() + + async def watch(_cross) -> None: + if progress: + await progress(res) + + if progress: + await progress(res) + try: + await relink_after_shift( + client, db, shift, src, dst, delay=delay, settle_pause=settle_pause, progress=watch, + should_stop=should_stop, result=res.cross, + ) + except Exception as e: # the copies are fine; only the links in the other channels were not updated + log.exception("pointing the links of the other channels at the shifted posts failed") + res.cross_error = type(e).__name__ + return res + + +async def shift_profile(client, db, shift, dst, user_id: int, res: RepostResult, progress=None) -> None: + """-all: the destination takes over the source's name, description and photo (the outcome goes into `res`).""" + res.phase = "profile" + if progress: + await progress(res) + try: + res.profile = await copy_profile(client, source_of(shift), dst) + if res.profile.title: # the destination has a new name: keep the bot's own list right + await db.save_channel(dst.id, dst.access_hash, res.profile.title, dst.username, user_id) + if res.profile.ok: + await db.set_mark(shift.id, "profile_done") + except Exception as e: # the copies are fine; only the channel's name / description / photo were not copied + log.exception("copying the channel profile failed") + res.profile_error = type(e).__name__ + + +async def delete_shift_copies( + client, + db, + dst, + shift, + *, + delay: float = 0.5, + progress: Optional[Callable[[DeleteResult], Awaitable[None]]] = None, + fallback: Optional[Callable[[list], Awaitable[Any]]] = None, +) -> DeleteResult: + """Undo: remove the copies of this shift from the destination channel (the source is not touched).""" + todo = await db.shift_pending_new(shift.id, 1_000_000) + + async def mark(ids: list) -> None: + await db.mark_shift_deleted(shift.id, dst.id, ids) + + res = await delete_pending(client, peer_of(dst), todo, mark, delay=delay, progress=progress, fallback=fallback) + res.remaining = (await db.shift_counts(shift.id))["new_left"] + res.blocked = res.remaining > 0 and not res.error + return res diff --git a/app/suggest.py b/app/suggest.py new file mode 100644 index 0000000000000000000000000000000000000000..8bf9dcc43b200aad44060e02cc14b325f587ace6 --- /dev/null +++ b/app/suggest.py @@ -0,0 +1,127 @@ +"""Auto-suggest the next episode batch: 'Download Episodes 01 to 20' -> 'Download Episodes 21 to 40'.""" +from __future__ import annotations + +import copy +import re +from dataclasses import dataclass, field +from typing import Optional + +from telethon.helpers import add_surrogate, del_surrogate + +from .linkswap import apply_span_replacements +from .richmsg import is_rich +from .tgutil import de_entities, ser_entities + +RANGE_RX = re.compile(r"(?P
\d+)(?P\s*(?:to|[-–—~&])\s*)(?P
(?:ep?\.?\s*)?)(?P\d+)", re.I)
+SINGLE_RX = re.compile(r"(?episodes?|eps?\.?|e)(?P\s*[-:#]?\s*)(?P\d+)(?!\d)", re.I)
+
+
+@dataclass
+class Advance:
+    new_text: str  # the whole string with the numbers moved on
+    old_span: str  # e.g. "01 to 20"
+    new_span: str  # e.g. "21 to 40"
+
+
+def advance_plain(s: str) -> Optional[Advance]:
+    """Move the first episode range (or single episode) in `s` on to the next batch."""
+    for m in RANGE_RX.finditer(s or ""):
+        a_s, b_s = m.group("a"), m.group("b")
+        a, b = int(a_s), int(b_s)
+        if a > b or b - a > 5000:
+            continue
+        step = b - a + 1
+        width = max(len(a_s), len(b_s)) if (a_s.startswith("0") or b_s.startswith("0")) else 0
+        na, nb = str(b + 1).zfill(width), str(b + step).zfill(width)
+        new_span = na + s[m.end("a"):m.start("b")] + nb
+        return Advance(
+            new_text=s[: m.start("a")] + new_span + s[m.end("b"):],
+            old_span=s[m.start("a"):m.end("b")],
+            new_span=new_span,
+        )
+    for m in SINGLE_RX.finditer(s or ""):
+        n_s = m.group("n")
+        width = len(n_s) if n_s.startswith("0") else 0
+        nn = str(int(n_s) + 1).zfill(width)
+        return Advance(
+            new_text=s[: m.start("n")] + nn + s[m.end("n"):],
+            old_span=s[m.start("label"):m.end("n")],
+            new_span=s[m.start("label"):m.start("n")] + nn,
+        )
+    return None
+
+
+@dataclass
+class Suggestion:
+    text: str
+    entities: list
+    buttons: list
+    media_kind: Optional[str]
+    media_file_id: Optional[str]
+    pending: list = field(default_factory=list)  # [(row, col)] of buttons that still need a link
+    prev_label: str = ""
+    new_label: str = ""
+    source_post_id: int = 0
+
+
+def build_suggestion(post) -> Optional[Suggestion]:
+    if is_rich(post):  # its text lives in blocks Telegram made: the numbers can't be moved on in them
+        return None
+    rows: list = []
+    pending: list = []
+    first: Optional[Advance] = None
+    prev_label = ""
+    for row in post.buttons or []:
+        new_row: list = []
+        for b in row:
+            if b.get("raw"):  # other bots' buttons (e.g. reactions) are not carried over
+                continue
+            b = dict(b)
+            b.pop("s", None)
+            adv = advance_plain(b.get("t", "")) if b.get("u") else None
+            if adv:
+                if first is None:
+                    first, prev_label = adv, b["t"]
+                b["t"] = adv.new_text
+                b["u"] = None
+                pending.append((len(rows), len(new_row)))
+            new_row.append(b)
+        if new_row:
+            rows.append(new_row)
+    if not pending or first is None:
+        return None
+
+    text = post.text or ""
+    entities = copy.deepcopy(post.entities or [])
+    sur = add_surrogate(text)
+    repls: list = []
+    pos = 0
+    while first.old_span:
+        i = sur.find(first.old_span, pos)
+        if i < 0:
+            break
+        repls.append((i, i + len(first.old_span), first.new_span))
+        pos = i + len(first.old_span)
+    if repls:
+        new_sur, new_ents = apply_span_replacements(sur, de_entities(entities), repls)
+        text, entities = del_surrogate(new_sur), ser_entities(new_ents)
+
+    return Suggestion(
+        text=text,
+        entities=entities,
+        buttons=rows,
+        media_kind=post.media_kind,
+        media_file_id=post.media_file_id,
+        pending=pending,
+        prev_label=prev_label,
+        new_label=rows[pending[0][0]][pending[0][1]]["t"],
+        source_post_id=post.id,
+    )
+
+
+async def make_suggestion(db, channel_id: int) -> Optional[Suggestion]:
+    for p in await db.latest_sent(channel_id, 30):
+        s = build_suggestion(p)
+        if s:
+            return s
+    return None
diff --git a/app/sync_engine.py b/app/sync_engine.py
new file mode 100644
index 0000000000000000000000000000000000000000..930d245fe0b51827b367624ed2a99d4688663da7
--- /dev/null
+++ b/app/sync_engine.py
@@ -0,0 +1,600 @@
+"""Keeps My posts in step with the channels: what admins do outside the bot is noticed and recorded.
+
+What a look at a channel does
+  * every post the bot has saved is read back from Telegram: a post that is gone is removed here, a post that was edited
+    gets its saved copy updated (text, formatting, buttons, media);
+  * messages that appeared since the last look are saved as new posts (source "adopted");
+  * the posts that were in the channel BEFORE the bot was added are read into My posts too, oldest first, up to the
+    newest message that existed at the first look. Where the reading stopped is saved, so a long channel takes a few
+    looks. Posts the owner told the bot to forget are skipped for good;
+  * service messages ("channel name changed", "pinned a message", video chat ...) found on the way are deleted.
+
+Safety rules
+  * posts the bot touched a moment ago, and messages that appeared a moment ago, are left for the next look (the bot may
+    still be saving them);
+  * a saved copy is only changed if nobody changed it since it was read (optimistic check in the database);
+  * buttons that are missing in the channel are never removed from the saved copy (Telegram sometimes hides a keyboard
+    for a while - the saved buttons are what "Check buttons" restores from);
+  * if EVERY saved post of a channel looks deleted, the bot first makes sure it can read the channel at all: when it
+    still sees other messages there (or the channel's event counter moved by at least that many events, which is what
+    really deleting them looks like) the posts are really gone and leave My posts; only when it sees nothing at all
+    - more likely the bot lost access - is nothing removed;
+  * what TELEGRAM does to a channel is not an admin's edit: a channel it restricts (a copyright strike turns every post
+    into "This message couldn't be displayed on your device due to copyright infringement"), a single post it holds
+    back, a notice shown instead of a post, or many posts that suddenly all show one and the same text are left exactly
+    as saved - nothing is edited, removed or added for them.
+"""
+from __future__ import annotations
+
+import asyncio
+import logging
+import time
+from dataclasses import dataclass, field
+from typing import Any, Optional
+
+from telethon import errors, types
+
+from .db import as_utc, utcnow
+from .replace_engine import fetch_messages
+from .repost_engine import delete_batch
+from .restrictions import message_restriction, norm_text, probe_channel
+from .richmsg import Rich, entry as rich_entry, is_rich_message, plain_of_message, rich_from_received, rich_of, with_fingerprint
+from .tgutil import classify_media, explain_rpc, media_from_ref, media_info, peer_of, ser_entities, ser_markup
+
+log = logging.getLogger(__name__)
+
+CHUNK = 100  # Telegram returns at most 100 messages per request
+GRACE = 120.0  # seconds a post or message must be old before it is judged
+PAUSE = 0.25  # between two requests of a scan
+SLACK_CAP = 300  # a quick look reads this many ids beyond the most likely end of the new messages
+DEEP_EVERY = 24 * 3600  # the automatic looks read every possible id at least this often
+MIN_FOR_ANOMALY = 5
+MASS_SAME = 5  # this many posts that suddenly show the very same new text are not edits by a person
+MAX_PROBE = 300  # requests spent finding the newest message the first time (30 000 ids)
+
+
+# ----------------------------------------------------------------------------------------------- options
+@dataclass
+class SyncOptions:
+    deep: bool = False  # read every possible id for new messages, not only the likely ones
+    delete_services: bool = True
+    adopt: bool = True  # save new posts of others
+    history: bool = True  # also read the posts from before the bot was added into My posts
+    history_seconds: Optional[float] = None  # ... for at most this long per look (None: as long as it takes)
+    grace: float = GRACE
+    pause: float = PAUSE
+    ignore: Any = field(default_factory=set)  # (channel id, message id) of posts the owner told the bot to forget
+
+
+@dataclass
+class SyncReport:
+    channel: Any
+    phase: str = ""
+    checked: int = 0  # saved posts compared with the channel
+    deleted: list = field(default_factory=list)  # message ids that were gone: removed from My posts
+    edited: list = field(default_factory=list)  # message ids whose saved copy was brought up to date
+    refreshed: int = 0  # saved copies corrected for trifles (a trailing space ...)
+    adopted: list = field(default_factory=list)  # message ids of new posts that were saved
+    imported: int = 0  # older posts (from before the bot was added) that were added to My posts
+    history_unsupported: int = 0  # older messages My posts can't hold (polls, stickers ...)
+    history_top: int = 0  # the newest message that counts as older (0: the older posts were not looked at)
+    history_to: int = 0  # the older posts have been read up to this message id
+    history_done: bool = False  # ... and that was all of them
+    unsupported: int = 0  # new messages of a kind My posts can't show (polls, stickers ...)
+    buttons_missing: list = field(default_factory=list)  # saved buttons that the channel shows no keyboard for
+    services_deleted: int = 0
+    services_failed: int = 0
+    services_error: Optional[str] = None  # name of the refusal
+    restricted: list = field(default_factory=list)  # message ids Telegram holds back (copyright ...): left as saved
+    restricted_why: Optional[str] = None  # what Telegram says about them
+    restricted_channel: Optional[str] = None  # the whole channel is restricted: nothing was looked at
+    young: list = field(default_factory=list)  # saved posts the bot touched a moment ago: judge them later
+    young_new: list = field(default_factory=list)  # new messages that appeared a moment ago: save them later
+    changed_meanwhile: int = 0  # saved posts that were changed through the bot while we looked (left alone)
+    first_look: bool = False
+    busy: bool = False  # a long job started: the look was cut short
+    anomaly: Optional[str] = None
+    error: Optional[str] = None
+    scanned_to: int = 0
+
+    @property
+    def changed(self) -> bool:
+        return bool(self.deleted or self.edited or self.adopted or self.imported or self.services_deleted)
+
+
+# ------------------------------------------------------------------------------------- comparing a post
+def age(dt, now) -> float:
+    """Seconds since `dt` (never negative); unknown = very old."""
+    if dt is None:
+        return float("inf")
+    return max(0.0, (now - as_utc(dt)).total_seconds())
+
+
+def media_key(media) -> Optional[tuple]:
+    """Which photo / file a message carries (its id - the file reference changes from fetch to fetch)."""
+    if isinstance(media, types.MessageMediaPhoto) and getattr(media, "photo", None):
+        return ("photo", media.photo.id)
+    if isinstance(media, types.MessageMediaDocument) and getattr(media, "document", None):
+        return ("doc", media.document.id)
+    return None
+
+
+def stored_media_key(ref: Optional[str]) -> Optional[tuple]:
+    if not ref:
+        return None
+    try:
+        return media_key(media_from_ref(ref))
+    except Exception:
+        return ("unreadable", ref[:40])  # differs from anything real: the saved reference gets replaced
+
+
+def live_rich(m) -> Optional[Rich]:
+    """The rich message the live message is (as blocks), or None for an ordinary post."""
+    rm = getattr(m, "rich_message", None)
+    return rich_from_received(rm) if rm is not None else None
+
+
+def live_fields(m) -> dict:
+    """The saved-post fields of a message as it is in the channel now."""
+    kind, ref = media_info(m)
+    rich = live_rich(m)
+    return {
+        "text": plain_of_message(m) if rich is not None else (m.message or ""),
+        "entities": [rich_entry(rich)] if rich is not None else ser_entities(m.entities),
+        "buttons": ser_markup(m.reply_markup),
+        "media_kind": kind,
+        "media_file_id": ref,
+    }
+
+
+def message_supported(m) -> bool:
+    """Something My posts can show and edit: text, a rich message, or a photo / video / GIF / audio / file."""
+    return bool((m.message or "").strip()) or classify_media(m) is not None or is_rich_message(m)
+
+
+def adopt_fields(m) -> dict:
+    f = live_fields(m)
+    f["link_preview"] = isinstance(getattr(m, "media", None), types.MessageMediaWebPage)
+    return f
+
+
+# ------------------------------------------------------------------- what Telegram itself does to a channel
+MASS_NOTE = "many posts suddenly show one and the same text - that is Telegram's notice, not an edit"
+
+
+def split_mass_text(edits: list) -> tuple:
+    """(edits to save, edits to hold back). Five or more saved posts that had five different texts and now all show the
+    very same text at once: nobody edits like that - Telegram does it to a channel it restricts."""
+    groups: dict = {}
+    for item in edits:
+        new = norm_text(item[1].fields.get("text"))
+        if new:
+            groups.setdefault(new, []).append(item)
+    bad: set = set()
+    for items in groups.values():
+        if len(items) >= MASS_SAME and len({norm_text(p.text) for p, _ in items}) >= MASS_SAME:
+            bad.update(id(i) for i in items)
+    return [i for i in edits if id(i) not in bad], [i for i in edits if id(i) in bad]
+
+
+def hold_back(rep: "SyncReport", ids, why: Optional[str]) -> None:
+    rep.restricted.extend(ids)
+    rep.restricted_why = rep.restricted_why or why
+
+
+@dataclass
+class Diff:
+    fields: dict = field(default_factory=dict)  # what to save
+    buttons_missing: bool = False
+    quiet: bool = False  # only a trifle differs (surrounding spaces): fix it without counting it as an edit
+
+
+def diff_post(p, m) -> Diff:
+    """What differs between the saved post `p` and the live message `m`."""
+    live = live_fields(m)
+    fields: dict = {}
+    saved_rich, now_rich = rich_of(p), live_rich(m) if is_rich_message(m) else None
+    first_look = False
+    if saved_rich is None and now_rich is None:
+        if (p.text or "") != live["text"]:
+            fields["text"] = live["text"]
+        if list(p.entities or []) != live["entities"]:
+            fields["entities"] = live["entities"]
+    elif now_rich is not None:
+        # A rich message is compared by what Telegram shows of it (a fingerprint of its blocks), never by its text: the
+        # saved copy keeps the source the bot sent. A post that became rich in the channel is taken over as its blocks.
+        if saved_rich is None or (saved_rich.fp is not None and saved_rich.fp != now_rich.fp):
+            fields["text"], fields["entities"] = live["text"], live["entities"]
+        elif saved_rich.fp is None:  # the bot's own rich post, seen for the first time: remember what Telegram shows
+            fields["entities"] = [rich_entry(with_fingerprint(saved_rich, now_rich.fp))]
+            first_look = True
+    elif live["text"].strip() or live["media_kind"] is not None:
+        # the channel shows an ordinary post where a rich message was saved (an empty answer is not trusted)
+        fields["text"], fields["entities"] = live["text"], live["entities"]
+    # media: replaced media is taken over; media that seems to have vanished is not (a message can't lose its media)
+    if live["media_kind"] is not None:
+        if p.media_kind != live["media_kind"] or stored_media_key(p.media_file_id) != media_key(m.media):
+            fields["media_kind"], fields["media_file_id"] = live["media_kind"], live["media_file_id"]
+    missing = False
+    if live["buttons"]:
+        if list(p.buttons or []) != live["buttons"]:
+            fields["buttons"] = live["buttons"]
+    elif p.buttons:
+        missing = True
+    quiet = (set(fields) == {"text"} and (p.text or "").strip() == live["text"].strip()) or (
+        first_look and set(fields) == {"entities"}
+    )
+    return Diff(fields, missing, quiet)
+
+
+# --------------------------------------------------------------------------------------- talking to Telegram
+def is_gone(m) -> bool:
+    return m is None or isinstance(m, types.MessageEmpty)
+
+
+async def find_top(client, peer, pts: int, floor: int, *, pause: float = PAUSE) -> int:
+    """The newest message id that exists. Only the event counter is known (never lower), so look downwards from it;
+    `floor` (the newest saved post) is where the looking can stop."""
+    hi = pts
+    for _ in range(MAX_PROBE):
+        if hi <= floor:
+            break
+        lo = max(floor + 1, hi - CHUNK + 1)
+        msgs = await fetch_messages(client, peer, list(range(lo, hi + 1)))
+        alive = [m.id for m in msgs if not is_gone(m)]
+        if alive:
+            return max(alive)
+        hi = lo - 1
+        await asyncio.sleep(pause)
+    return max(floor, hi)
+
+
+async def sees_live_messages(client, peer, pts: Optional[int], *, pause: float = PAUSE, tries: int = MAX_PROBE) -> bool:
+    """True when the bot can read at least one message of the channel (a post or a service message). Then a saved post
+    that is missing from the channel really is gone - the bot is not just blind. Looks downwards from the event counter."""
+    if not pts or pts < 1:
+        return False
+    hi = pts
+    for _ in range(tries):
+        if hi < 1:
+            return False
+        lo = max(1, hi - CHUNK + 1)
+        msgs = await fetch_messages(client, peer, list(range(lo, hi + 1)))
+        if any(not is_gone(m) for m in msgs):
+            return True
+        hi = lo - 1
+        await asyncio.sleep(pause)
+    return False
+
+
+async def delete_services(client, peer, ids: list, rep: SyncReport) -> None:
+    """Delete service messages and count what happened (the bot only: Telegram may refuse the old ones)."""
+    ids = sorted(set(ids))
+    for i in range(0, len(ids), CHUNK):
+        part = ids[i : i + CHUNK]
+        out = await delete_batch(client, peer, part)
+        rep.services_deleted += len(out.gone)
+        left = len(part) - len(out.gone)
+        if left:
+            rep.services_failed += left
+            rep.services_error = rep.services_error or out.bot_error or "NotDeleted"
+
+
+# ------------------------------------------------------------------------------------- the three steps
+async def _save_edits(db, rep: SyncReport, edits: list, busy) -> None:
+    for p, d in edits:
+        if busy():
+            rep.busy = True
+            return
+        if await db.sync_update_post(p.id, p.updated_at, d.fields):
+            if d.quiet:
+                rep.refreshed += 1
+            else:
+                rep.edited.append(p.message_id)
+        else:
+            rep.changed_meanwhile += 1
+
+
+async def _adopt(db, ch, rep: SyncReport, fresh: list, opts: SyncOptions, busy, now) -> None:
+    """Save messages the bot does not know (ascending ids); too fresh ones are left for the next look."""
+    known: set = set()
+    ids = [m.id for m in fresh]
+    for i in range(0, len(ids), 500):
+        known |= {p.message_id for p in await db.posts_at(ch.id, ids[i : i + 500])}
+    forgotten = await db.ignored_ids(ch.id) if fresh else set()
+    todo = []
+    for m in fresh:
+        if m.id in known or m.id in forgotten or (ch.id, m.id) in opts.ignore:
+            continue
+        why = message_restriction(m)
+        if why:  # Telegram holds it back: what it shows now is not what the post says
+            hold_back(rep, [m.id], why)
+        elif age(m.date, now) < opts.grace:
+            rep.young_new.append(m.id)
+        elif not message_supported(m):
+            rep.unsupported += 1
+        else:
+            todo.append(m)
+    for m in todo:
+        if busy():
+            rep.busy = True
+            return
+        _, created = await db.adopt_message(ch.id, m.id, adopt_fields(m), sent_at=m.date)
+        if created:
+            rep.adopted.append(m.id)
+
+
+async def _compare_saved(
+    client, db, ch, rep: SyncReport, opts: SyncOptions, busy, progress, moved=None, pts: Optional[int] = None
+) -> None:
+    """Every saved post against the channel. `moved`: how far the channel's event counter has come since the last look
+    (None: unknown) - deleting posts is an event each, which tells "everything was deleted" from "I can't see anything".
+    `pts`: the channel's event counter now - where the bot looks for other messages to prove that it can read the channel."""
+    rep.phase = "comparing the saved posts"
+    peer = peer_of(ch)
+    posts = await db.sent_posts(ch.id)  # the saved copies are read BEFORE the channel is, never after
+    now = utcnow()
+    judge = []
+    for p in posts:
+        if min(age(p.updated_at, now), age(p.sent_at, now)) < opts.grace:
+            rep.young.append(p.message_id)
+        else:
+            judge.append(p)
+    rep.checked = len(judge)
+    by_id = {p.message_id: p for p in judge}
+    ids = sorted(by_id)
+    gone, edits = [], []
+    for i in range(0, len(ids), CHUNK):
+        if busy():
+            rep.busy = True
+            return
+        chunk = ids[i : i + CHUNK]
+        msgs = await fetch_messages(client, peer, chunk)
+        for mid, m in zip(chunk, msgs):
+            p = by_id[mid]
+            if is_gone(m):
+                gone.append(p)
+            elif isinstance(m, types.MessageService):
+                continue  # not a post any more (cannot happen: ids are never reused)
+            else:
+                why = message_restriction(m, p.text)
+                if why:  # Telegram's doing, not an admin's: the saved copy stays exactly as it is
+                    hold_back(rep, [mid], why)
+                    continue
+                d = diff_post(p, m)
+                if d.buttons_missing:
+                    rep.buttons_missing.append(mid)
+                if d.fields:
+                    edits.append((p, d))
+        rep.scanned_to = chunk[-1]
+        if progress:
+            await progress(rep)
+        await asyncio.sleep(opts.pause)
+    edits, held = split_mass_text(edits)
+    if held:
+        hold_back(rep, [p.message_id for p, _ in held], MASS_NOTE)
+    if gone:
+        really = moved is not None and moved >= len(gone)  # at least one event for each post that vanished
+        everything = len(ids) >= MIN_FOR_ANOMALY and len(gone) == len(ids)
+        if everything and not really:
+            # No earlier look to compare with (or too few events): is the bot blind, or are the posts really gone? If it
+            # can read other messages of the channel it is not blind.
+            if busy():
+                rep.busy = True
+                return
+            really = await sees_live_messages(client, peer, pts, pause=opts.pause)
+        if everything and not really:
+            rep.anomaly = (
+                f"All {len(ids)} saved posts look deleted, and I can't read any other message of the channel either, "
+                "so none was removed here - check that the bot is still an admin of the channel."
+            )
+        else:
+            gone_ids = [p.message_id for p in gone]
+            await db.forget_posts(ch.id, gone_ids)
+            rep.deleted.extend(gone_ids)
+    await _save_edits(db, rep, edits, busy)
+
+
+async def _look_for_new(client, db, ch, rep: SyncReport, opts: SyncOptions, state, pts: int, busy, progress) -> None:
+    """Messages that appeared since the last look: new posts are saved, service messages deleted."""
+    rep.phase = "looking for new posts"
+    peer = peer_of(ch)
+    now = utcnow()
+    if state is None:  # the first look: only note where the channel stands
+        floor = await db.max_saved_id(ch.id)
+        top = await find_top(client, peer, pts, floor, pause=opts.pause)
+        rep.first_look, rep.scanned_to = True, top
+        await db.save_sync(ch.id, last_top=top, last_pts=pts, deferred=0, deep=True)
+        return
+    deep = opts.deep or age(state.last_deep, now) > DEEP_EVERY
+    if pts == state.last_pts and not state.deferred and not deep:
+        return  # not a single event since the last look: a quick look would read exactly what it read then
+    delta = max(0, pts - state.last_pts)
+    slack = min(max(0, state.last_pts - state.last_top), SLACK_CAP)
+    soft = pts if deep else min(pts, state.last_top + delta + slack)
+    a, highest, had_live = state.last_top + 1, state.last_top, True
+    fresh, services = [], []
+    while a <= pts:
+        if a > soft and not had_live:
+            break  # past the likely end and the last stretch was empty
+        if busy():
+            rep.busy = True
+            return
+        hi = min(a + CHUNK - 1, pts)
+        msgs = await fetch_messages(client, peer, list(range(a, hi + 1)))
+        had_live = False
+        for m in msgs:
+            if is_gone(m):
+                continue
+            had_live = True
+            highest = max(highest, m.id)
+            if isinstance(m, types.MessageService):
+                services.append(m)
+            else:
+                fresh.append(m)
+        rep.scanned_to = hi
+        if progress:
+            await progress(rep)
+        a = hi + 1
+        await asyncio.sleep(opts.pause)
+    services_ids = [m.id for m in services]
+    if opts.delete_services and services_ids:
+        await delete_services(client, peer, services_ids, rep)
+    if opts.adopt and fresh:
+        await _adopt(db, ch, rep, fresh, opts, busy, now)
+        if rep.busy:
+            return
+    new_top = highest
+    if rep.young_new:  # these have to be looked at again: don't move the mark past them
+        new_top = min(new_top, min(rep.young_new) - 1)
+    await db.save_sync(
+        ch.id, last_top=max(state.last_top, new_top), last_pts=pts, deferred=len(rep.young_new), deep=deep
+    )
+
+
+async def _import_history(client, db, ch, rep: SyncReport, opts: SyncOptions, busy, progress, state=None) -> None:
+    """The posts that were in the channel before the bot was added are read into My posts: from message 1 up to the newest
+    message that existed at the first look (what came after is the business of _look_for_new). The place where the
+    reading stopped is saved - a long channel takes a few looks, and a restart loses nothing. `state`: where the look
+    before this one stopped (None at the very first look: the mark that look has just set is used)."""
+    hist = await db.get_history(ch.id)
+    if hist is None:
+        base = state if state is not None else await db.get_sync(ch.id)
+        if base is None:
+            return
+        hist = await db.start_history(ch.id, base.last_top)
+    if hist.done:
+        return
+    rep.phase = "reading the older posts"
+    peer = peer_of(ch)
+    began = time.monotonic()
+    forgotten = await db.ignored_ids(ch.id)
+    rep.history_top = hist.top
+    a = hist.next_id
+    rep.history_to = a - 1
+    while a <= hist.top:
+        if busy():
+            rep.busy = True
+            return
+        if opts.history_seconds is not None and time.monotonic() - began > opts.history_seconds:
+            return  # the next look goes on from here
+        hi = min(a + CHUNK - 1, hist.top)
+        msgs = await fetch_messages(client, peer, list(range(a, hi + 1)))
+        now = utcnow()
+        stop = None
+        todo = []
+        # posts the bot has saved already are none of the reading's business: the comparison of the saved posts looks
+        # after them (and counts the ones Telegram holds back there - not a second time here)
+        have = {p.message_id for p in await db.posts_at(ch.id, [m.id for m in msgs if not is_gone(m)])}
+        for m in msgs:
+            if is_gone(m) or isinstance(m, types.MessageService):
+                continue
+            if age(m.date, now) < opts.grace:  # the bot may still be saving it: the next look reads it
+                stop = m.id
+                break
+            if m.id in forgotten or m.id in have or (ch.id, m.id) in opts.ignore:
+                continue
+            why = message_restriction(m)
+            if why:
+                hold_back(rep, [m.id], why)
+            elif not message_supported(m):
+                rep.history_unsupported += 1
+            else:
+                todo.append(m)
+        made = await db.adopt_many(ch.id, [(m.id, adopt_fields(m), m.date) for m in todo])  # (skips what is saved)
+        rep.imported += len(made)
+        a = hi + 1 if stop is None else stop
+        rep.history_done = stop is None and a > hist.top
+        await db.save_history(ch.id, next_id=a, imported=len(made), done=rep.history_done)
+        rep.history_to = rep.scanned_to = a - 1
+        if stop is not None:
+            return
+        if progress:
+            await progress(rep)
+        await asyncio.sleep(opts.pause)
+    rep.history_done = True  # (also the case when the channel had nothing to read)
+
+
+# ----------------------------------------------------------------------------------------- entry points
+async def sync_channel(client, db, ch, opts: Optional[SyncOptions] = None, *, busy=None, progress=None) -> SyncReport:
+    """One full look at a channel (see the module text). Never raises Telegram's refusals: they end up in `report.error`."""
+    opts = opts or SyncOptions()
+    busy = busy or (lambda: False)
+    rep = SyncReport(channel=ch)
+    pts, restricted, err = await probe_channel(client, peer_of(ch))
+    if pts is None:
+        rep.error = err
+        return rep
+    if restricted:  # Telegram restricted the channel (a copyright strike ...): My posts stay untouched
+        rep.restricted_channel = restricted
+        return rep
+    try:
+        state = await db.get_sync(ch.id)
+        moved = None if state is None else max(0, pts - state.last_pts)
+        await _compare_saved(client, db, ch, rep, opts, busy, progress, moved, pts)
+        if not rep.busy:
+            await _look_for_new(client, db, ch, rep, opts, state, pts, busy, progress)
+        if not rep.busy and opts.history:
+            await _import_history(client, db, ch, rep, opts, busy, progress, state)
+    except errors.RPCError as e:
+        rep.error = explain_rpc(e)
+    return rep
+
+
+async def sync_ids(client, db, ch, ids, opts: Optional[SyncOptions] = None, *, adopt_ids=(), busy=None) -> SyncReport:
+    """A look at these messages only - the ones an update told about. `adopt_ids`: the ones that are new posts, so a
+    message the bot does not know may be saved (an edited message the bot does not know is history: left alone)."""
+    opts = opts or SyncOptions()
+    busy = busy or (lambda: False)
+    rep = SyncReport(channel=ch)
+    peer = peer_of(ch)
+    ids = sorted(set(ids))
+    adopt_set = set(adopt_ids)
+    try:
+        rows = {p.message_id: p for p in await db.posts_at(ch.id, ids)}  # saved copies first, the channel second
+        now = utcnow()
+        gone, edits, fresh, services = [], [], [], []
+        for i in range(0, len(ids), CHUNK):
+            if busy():
+                rep.busy = True
+                return rep
+            chunk = ids[i : i + CHUNK]
+            msgs = await fetch_messages(client, peer, chunk)
+            for mid, m in zip(chunk, msgs):
+                row = rows.get(mid)
+                recent = row is not None and min(age(row.updated_at, now), age(row.sent_at, now)) < opts.grace
+                if is_gone(m):
+                    if row is not None and not recent:
+                        gone.append(row)
+                elif isinstance(m, types.MessageService):
+                    services.append(mid)
+                elif row is not None:
+                    why = message_restriction(m, row.text)
+                    if why:  # Telegram's doing, not an admin's: the saved copy stays exactly as it is
+                        hold_back(rep, [mid], why)
+                        continue
+                    if recent:
+                        rep.young.append(mid)
+                        continue
+                    d = diff_post(row, m)
+                    if d.buttons_missing:
+                        rep.buttons_missing.append(mid)
+                    if d.fields:
+                        edits.append((row, d))
+                elif mid in adopt_set:
+                    fresh.append(m)
+        if opts.delete_services and services:
+            await delete_services(client, peer, services, rep)
+        edits, held = split_mass_text(edits)
+        if held:
+            hold_back(rep, [p.message_id for p, _ in held], MASS_NOTE)
+        if gone:
+            gone_ids = [p.message_id for p in gone]
+            await db.forget_posts(ch.id, gone_ids)
+            rep.deleted.extend(gone_ids)
+        await _save_edits(db, rep, edits, busy)
+        if opts.adopt and fresh and not rep.busy:
+            await _adopt(db, ch, rep, fresh, opts, busy, now)
+    except errors.RPCError as e:
+        rep.error = explain_rpc(e)
+    return rep
diff --git a/app/syncer.py b/app/syncer.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8f2dea9ad5fb297a93525030a60b23ed2a56af9
--- /dev/null
+++ b/app/syncer.py
@@ -0,0 +1,319 @@
+"""The background side of the sync.
+
+* a timer: every SYNC_INTERVAL_MINUTES each connected channel is compared with My posts (app/sync_engine.py);
+* a queue for what Telegram tells the bot while it runs: a post deleted / edited / added in a channel is looked at a few
+  seconds later (the wait lets a burst of changes settle, and lets the bot finish saving its own posts first);
+* service messages ("pinned a message", "channel photo changed" ...) are deleted the moment they appear.
+
+Nothing here holds the bot's one-long-job lock: a running /repost, /shift, /swap ... always wins, and what happens
+while it runs is picked up by the next timed check.
+"""
+from __future__ import annotations
+
+import asyncio
+import logging
+import time
+from typing import Optional
+
+from .servicemsg import RIGHTS_ERRORS, action_label, remove
+from .sync_engine import SyncOptions, SyncReport, sync_channel, sync_ids
+from .tgutil import esc, peer_of
+
+log = logging.getLogger(__name__)
+
+
+class Syncer:
+    def __init__(self, ctx):
+        self.ctx = ctx
+        # timings (seconds) - the tests make them small
+        self.start_delay = 90.0  # after the bot starts, before the first timed check
+        self.debounce = 5.0  # quiet time needed before the queue is worked off
+        self.max_debounce = 30.0  # ... but never wait longer than this
+        self.lock_wait = 30.0  # a long job runs: look again after this
+        self.rt_grace = 10.0  # live changes: posts the bot touched / messages younger than this are judged next round
+        self.pause = 0.25  # between two requests
+        self.cache_ttl = 60.0  # how long "is this channel connected?" is remembered
+        self.tell_every = 86400.0  # the same warning goes to the owners at most this often
+        self.tell_restricted_every = 7 * 86400.0  # ... a restriction by Telegram can last for weeks: once a week
+        self.max_ids = 300  # more changed ids than this in one channel: look at the whole channel instead
+        self.max_tries = 8  # a message that stays "too fresh" is given up after this many rounds
+        self.history_seconds = 150.0  # a timed check reads a channel's older posts for this long, then goes on next time
+        self._busy = asyncio.Lock()  # one look at a time
+        self._edits: dict = {}  # channel id -> message ids edited
+        self._news: dict = {}  # channel id -> message ids that are new posts
+        self._tries: dict = {}
+        self._stamp = 0
+        self._wake = asyncio.Event()
+        self._tasks: list = []
+        self._cache: dict = {}
+        self._told: dict = {}
+        self.last_reports: dict = {}  # channel id -> its latest SyncReport
+
+    # ----------------------------------------------------------------------------------------- running
+    @property
+    def enabled(self) -> bool:
+        return self.ctx.cfg.sync_interval_minutes > 0
+
+    def start(self) -> None:
+        if self._tasks or not self.enabled:
+            return
+        self._tasks = [
+            asyncio.create_task(self._periodic(), name="sync-timer"),
+            asyncio.create_task(self._events(), name="sync-live"),
+        ]
+
+    async def stop(self) -> None:
+        tasks, self._tasks = self._tasks, []
+        for t in tasks:
+            t.cancel()
+        for t in tasks:
+            try:
+                await t
+            except (asyncio.CancelledError, Exception):
+                pass
+
+    async def _periodic(self) -> None:
+        await asyncio.sleep(self.start_delay)
+        while True:
+            try:
+                await self.run_all()
+            except asyncio.CancelledError:
+                raise
+            except Exception:
+                log.exception("the timed check of the channels failed")
+            await asyncio.sleep(max(5, self.ctx.cfg.sync_interval_minutes) * 60)
+
+    async def _events(self) -> None:
+        while True:
+            await self._wake.wait()
+            self._wake.clear()
+            try:
+                await self.flush_events()
+            except asyncio.CancelledError:
+                raise
+            except Exception:
+                log.exception("working off the channel changes failed")
+
+    # ----------------------------------------------------------------------------------------- helpers
+    async def channel(self, cid: int):
+        """The connected channel with this id, or None (remembered for a minute: busy channels cost no database reads)."""
+        now = time.monotonic()
+        hit = self._cache.get(cid)
+        if hit is not None and now - hit[0] < self.cache_ttl:
+            return hit[1]
+        ch = await self.ctx.db.get_channel(cid)
+        if ch is not None and not ch.active:
+            ch = None
+        self._cache[cid] = (now, ch)
+        return ch
+
+    def forget_cache(self) -> None:
+        self._cache.clear()
+
+    def exclusive(self):
+        """Held (`async with`) while no look at any channel runs - for a change that must not race with one."""
+        return self._busy
+
+    def options(self, **kw) -> SyncOptions:
+        ctx = self.ctx
+        base = dict(
+            delete_services=ctx.cfg.delete_service_messages,
+            history=ctx.cfg.import_old_posts,
+            ignore=ctx.sync_ignore,
+            pause=self.pause,
+        )
+        base.update(kw)
+        return SyncOptions(**base)
+
+    async def tell_owners(self, ch, key: str, text: str, every: Optional[float] = None) -> None:
+        """A warning for the owners - the same one (per channel and kind) at most once a day (or every `every` seconds)."""
+        now = time.monotonic()
+        k = (ch.id, key)
+        if now - self._told.get(k, -1e12) < (self.tell_every if every is None else every):
+            return
+        self._told[k] = now
+        for uid in sorted(self.ctx.cfg.owners):
+            try:
+                await self.ctx.client.send_message(uid, text, link_preview=False)
+            except Exception:
+                log.warning("could not warn user %s about %s", uid, ch.id, exc_info=True)
+
+    async def _after(self, ch, rep: SyncReport) -> None:
+        self.last_reports[ch.id] = rep
+        if rep.changed or rep.error or rep.anomaly:
+            log.info(
+                "channel %s: %s removed, %s updated, %s new, %s service messages deleted%s",
+                ch.id, len(rep.deleted), len(rep.edited), len(rep.adopted), rep.services_deleted,
+                f" - {rep.error or rep.anomaly}" if (rep.error or rep.anomaly) else "",
+            )
+        if rep.services_failed and rep.services_error in RIGHTS_ERRORS:
+            await self.tell_owners(ch, "rights", self._rights_text(ch, rep.services_error))
+        if rep.restricted_channel:
+            log.info("channel %s is restricted by Telegram (%s): My posts left untouched", ch.id, rep.restricted_channel)
+            text = self._restricted_text(ch, rep.restricted_channel)
+            await self.tell_owners(ch, "restricted", text, every=self.tell_restricted_every)
+        elif rep.restricted:
+            log.info("channel %s: %s post(s) held back by Telegram (%s): left untouched", ch.id, len(rep.restricted), rep.restricted_why)
+            text = self._held_back_text(ch, len(rep.restricted), rep.restricted_why)
+            await self.tell_owners(ch, "held-back", text, every=self.tell_restricted_every)
+
+    @staticmethod
+    def _restricted_text(ch, why: str) -> str:
+        return (
+            f"🚫 Telegram has restricted {esc(ch.title)} ({esc(why)}). While that lasts I don't change anything in "
+            "My posts for this channel - the saved posts stay exactly as they are, whatever the channel shows now."
+        )
+
+    @staticmethod
+    def _held_back_text(ch, n: int, why: Optional[str]) -> str:
+        return (
+            f"🚫 Telegram holds back {n} post(s) of {esc(ch.title)} ({esc(why or 'restricted')}). "
+            "Their saved copies in My posts stay exactly as they are."
+        )
+
+    @staticmethod
+    def _rights_text(ch, why: Optional[str]) -> str:
+        return (
+            f"⚠️ I can't delete the service messages (name changes, “pinned a message” ...) in {esc(ch.title)} "
+            f"({esc(why or 'refused')}). Give the bot the Delete messages right there, or set "
+            "DELETE_SERVICE_MESSAGES=false to stop trying."
+        )
+
+    # ------------------------------------------------------------------------------------ full looks
+    async def run_all(
+        self, chans: Optional[list] = None, *, explicit: bool = False, history: Optional[bool] = None, progress=None
+    ) -> list:
+        """Look at the connected channels one after the other. `explicit` (the /sync command): the caller holds the
+        one-long-job lock and everything is read; the timed check gives way to any long job instead. `history`: True
+        reads the channels' older posts even if IMPORT_OLD_POSTS is off (/sync --history)."""
+        ctx = self.ctx
+        if chans is None:
+            chans = await ctx.db.list_channels()
+        busy = (lambda: False) if explicit else ctx.lock.locked
+        reports: list = []
+        for ch in chans:
+            if busy():
+                break
+
+            async def prog(rep, ch=ch):
+                if progress is not None:
+                    await progress(ch, rep)
+
+            try:
+                async with self._busy:
+                    extra = {} if history is None else {"history": history}
+                    opts = self.options(deep=explicit, history_seconds=None if explicit else self.history_seconds, **extra)
+                    rep = await sync_channel(ctx.client, ctx.db, ch, opts, busy=busy, progress=prog)
+            except asyncio.CancelledError:
+                raise
+            except Exception as e:
+                log.exception("looking at channel %s failed", ch.id)
+                rep = SyncReport(channel=ch, error=f"{type(e).__name__}: {str(e)[:120]}")
+            await self._after(ch, rep)
+            reports.append(rep)
+        return reports
+
+    # ----------------------------------------------------------------------------- live: what updates say
+    def _touch(self) -> None:
+        self._stamp += 1
+        self._wake.set()
+
+    def note_new(self, cid: int, msg) -> None:
+        """A post appeared in a channel. The bot's own posts are skipped (it saves them itself)."""
+        if not self.enabled or self.ctx.lock.locked() or getattr(msg, "out", False):
+            return
+        self._news.setdefault(cid, set()).add(msg.id)
+        self._touch()
+
+    def note_edit(self, cid: int, msg) -> None:
+        if not self.enabled or self.ctx.lock.locked():
+            return
+        self._edits.setdefault(cid, set()).add(msg.id)
+        self._touch()
+
+    async def note_deleted(self, cid: int, ids) -> None:
+        """Posts were deleted in a channel: they leave My posts at once (nothing to read from Telegram for that)."""
+        if not self.enabled:
+            return
+        ch = await self.channel(cid)
+        if ch is None:
+            return
+        for pending in (self._edits, self._news):
+            if cid in pending:
+                pending[cid].difference_update(ids)
+        n = await self.ctx.db.forget_posts(cid, list(ids))
+        if n:
+            log.info("%s post(s) were deleted in channel %s: removed from My posts", n, cid)
+
+    async def on_service(self, cid: int, msg) -> None:
+        """A service message appeared: delete it."""
+        if not self.ctx.cfg.delete_service_messages:
+            return
+        ch = await self.channel(cid)
+        if ch is None:
+            return
+        out = await remove(self.ctx.client, peer_of(ch), [msg.id])
+        if out.error is None:
+            log.info("removed the “%s” notice %s from channel %s", action_label(msg), msg.id, cid)
+            return
+        log.warning("could not delete the “%s” notice %s in channel %s: %s", action_label(msg), msg.id, cid, out.error_name)
+        if out.error_name in RIGHTS_ERRORS:
+            await self.tell_owners(ch, "rights", self._rights_text(ch, out.error_name))
+
+    def _pending(self) -> bool:
+        return bool(self._edits or self._news)
+
+    async def flush_events(self) -> None:
+        """Work off the queue once it has been quiet for a moment (and no long job is running)."""
+        first = time.monotonic()
+        while self._pending():
+            stamp = self._stamp
+            await asyncio.sleep(self.debounce)
+            if stamp != self._stamp and time.monotonic() - first < self.max_debounce:
+                continue  # more is still coming in: let it settle
+            if self.ctx.lock.locked():
+                await asyncio.sleep(self.lock_wait)
+                continue
+            edits, news = self._edits, self._news
+            self._edits, self._news = {}, {}
+            await self._process(edits, news)
+            first = time.monotonic()
+
+    def _requeue(self, pending: dict, cid: int, mid: int) -> None:
+        key = (cid, mid)
+        self._tries[key] = self._tries.get(key, 0) + 1
+        if self._tries[key] > self.max_tries:
+            self._tries.pop(key, None)
+            return
+        pending.setdefault(cid, set()).add(mid)
+
+    async def _process(self, edits: dict, news: dict) -> None:
+        ctx = self.ctx
+        for cid in sorted(set(edits) | set(news)):
+            ch = await self.channel(cid)
+            if ch is None:
+                continue
+            e_ids, n_ids = set(edits.get(cid, ())), set(news.get(cid, ()))
+            opts = self.options(grace=self.rt_grace, history=False)  # live: the older posts wait for the timed check
+            try:
+                async with self._busy:
+                    if len(e_ids | n_ids) > self.max_ids:  # a burst: one look at the whole channel is cheaper
+                        rep = await sync_channel(ctx.client, ctx.db, ch, opts, busy=ctx.lock.locked)
+                    else:
+                        rep = await sync_ids(
+                            ctx.client, ctx.db, ch, e_ids | n_ids, opts, adopt_ids=n_ids, busy=ctx.lock.locked
+                        )
+            except asyncio.CancelledError:
+                raise
+            except Exception as e:
+                log.exception("looking at the changes in channel %s failed", cid)
+                rep = SyncReport(channel=ch, error=f"{type(e).__name__}: {str(e)[:120]}")
+            await self._after(ch, rep)
+            if rep.busy:  # a long job started in the meantime: let the next timed check have it
+                continue
+            for mid in set(rep.young):
+                self._requeue(self._edits, cid, mid)
+            for mid in set(rep.young_new):
+                self._requeue(self._news, cid, mid)
+            for mid in (e_ids | n_ids) - set(rep.young) - set(rep.young_new):
+                self._tries.pop((cid, mid), None)
diff --git a/app/tgutil.py b/app/tgutil.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad743898da2ca6c6ebb8570992a5c9f766cce5c9
--- /dev/null
+++ b/app/tgutil.py
@@ -0,0 +1,482 @@
+"""Helpers around Telethon types: entity/button (de)serialisation, media info, raw edits, rights."""
+from __future__ import annotations
+
+import asyncio
+import base64
+import copy
+import html
+import logging
+import os
+from dataclasses import dataclass, field
+from types import SimpleNamespace
+from typing import Any, Awaitable, Callable, Optional
+
+from telethon import errors, functions, types
+from telethon.extensions import BinaryReader
+
+log = logging.getLogger(__name__)
+esc = html.escape
+
+# Telegram refusals that do not go away with the next message: the bot has no access (or no right) in that channel
+FATAL = {
+    "ChatAdminRequiredError",
+    "ChatWriteForbiddenError",
+    "ChannelPrivateError",
+    "UserBannedInChannelError",
+    "ChannelInvalidError",
+    "ChatRestrictedError",
+}
+
+# ----------------------------------------------------------------------------- entities
+_SIMPLE = {
+    "bold": types.MessageEntityBold,
+    "italic": types.MessageEntityItalic,
+    "underline": types.MessageEntityUnderline,
+    "strike": types.MessageEntityStrike,
+    "code": types.MessageEntityCode,
+}
+if hasattr(types, "MessageEntitySpoiler"):
+    _SIMPLE["spoiler"] = types.MessageEntitySpoiler
+
+# entities Telegram works out by itself from the text - never stored
+_AUTO = tuple(
+    getattr(types, n)
+    for n in (
+        "MessageEntityUrl",
+        "MessageEntityMention",
+        "MessageEntityHashtag",
+        "MessageEntityCashtag",
+        "MessageEntityBotCommand",
+        "MessageEntityEmail",
+        "MessageEntityPhone",
+        "MessageEntityBankCard",
+    )
+    if hasattr(types, n)
+)
+
+
+def _b64(obj: Any) -> str:
+    return base64.b64encode(bytes(obj)).decode()
+
+
+def _unb64(data: str) -> Any:
+    return BinaryReader(base64.b64decode(data)).tgread_object()
+
+
+def ser_entities(entities) -> list:
+    """Message entities -> JSON-friendly list (UTF-16 offsets, as Telegram uses)."""
+    out: list = []
+    for e in entities or []:
+        if isinstance(e, _AUTO):
+            continue
+        done = False
+        for key, cls in _SIMPLE.items():
+            if isinstance(e, cls):
+                out.append({"k": key, "o": e.offset, "l": e.length})
+                done = True
+                break
+        if done:
+            continue
+        if isinstance(e, types.MessageEntityPre):
+            out.append({"k": "pre", "o": e.offset, "l": e.length, "g": e.language or ""})
+        elif isinstance(e, types.MessageEntityTextUrl):
+            out.append({"k": "url", "o": e.offset, "l": e.length, "u": e.url})
+        elif isinstance(e, types.MessageEntityBlockquote):
+            out.append({"k": "quote", "o": e.offset, "l": e.length, "c": bool(getattr(e, "collapsed", False))})
+        elif isinstance(e, types.MessageEntityCustomEmoji):
+            out.append({"k": "emoji", "o": e.offset, "l": e.length, "d": e.document_id})
+        else:
+            try:  # anything else is kept byte-for-byte
+                out.append({"k": "raw", "b": _b64(e)})
+            except Exception:  # pragma: no cover
+                log.warning("cannot store entity %r", e)
+    return out
+
+
+def de_entities(data) -> list:
+    out: list = []
+    for d in data or []:
+        k = d.get("k")
+        try:
+            if k in _SIMPLE:
+                out.append(_SIMPLE[k](d["o"], d["l"]))
+            elif k == "pre":
+                out.append(types.MessageEntityPre(d["o"], d["l"], d.get("g", "")))
+            elif k == "url":
+                out.append(types.MessageEntityTextUrl(d["o"], d["l"], d["u"]))
+            elif k == "quote":
+                out.append(types.MessageEntityBlockquote(d["o"], d["l"], True if d.get("c") else None))
+            elif k == "emoji":
+                out.append(types.MessageEntityCustomEmoji(d["o"], d["l"], d["d"]))
+            elif k == "raw":
+                out.append(_unb64(d["b"]))
+        except Exception:  # pragma: no cover
+            log.warning("bad stored entity %r", d)
+    return out
+
+
+# ------------------------------------------------------------------------------ buttons
+_LEGACY = hasattr(types, "KeyboardButtonUrl")  # Telethon < 1.45 used one class per button kind
+
+
+def button_url(b) -> Optional[str]:
+    """The link of a URL button, else None."""
+    if _LEGACY:
+        return b.url if isinstance(b, types.KeyboardButtonUrl) else None
+    t = getattr(b, "type", None)
+    return t.url if isinstance(t, types.InlineButtonTypeUrl) else None
+
+
+def is_callback_button(b) -> bool:
+    if _LEGACY:
+        return isinstance(b, types.KeyboardButtonCallback)
+    return isinstance(getattr(b, "type", None), types.InlineButtonTypeCallback)
+
+
+def make_url_button(text: str, url: str, style=None):
+    if _LEGACY:
+        return types.KeyboardButtonUrl(text, url)
+    return types.KeyboardButton(text=text, type=types.InlineButtonTypeUrl(url), style=style)
+
+
+def with_url(b, new_url: str):
+    """Copy of URL button `b` pointing to `new_url`; every other attribute (colour, ...) is kept."""
+    nb = copy.copy(b)
+    if _LEGACY:
+        nb.url = new_url
+    else:
+        nb.type = copy.copy(b.type)
+        nb.type.url = new_url
+    return nb
+
+
+def with_text(b, new_text: str):
+    """Copy of button `b` with another name; the link, colour ... are kept."""
+    nb = copy.copy(b)
+    nb.text = new_text
+    return nb
+
+
+def _style_dump(b) -> Optional[str]:
+    st = getattr(b, "style", None)
+    if st is None:
+        return None
+    if not any(getattr(st, f, None) for f in ("bg_primary", "bg_danger", "bg_success", "icon")):
+        return None
+    try:
+        return _b64(st)
+    except Exception:  # pragma: no cover
+        return None
+
+
+def ser_markup(markup) -> list:
+    """Inline keyboard -> rows of {'t': text, 'u': url} (URL buttons) or {'t', 'raw'} (any other kind)."""
+    rows: list = []
+    if isinstance(markup, types.ReplyInlineMarkup):
+        for row in markup.rows:
+            r = []
+            for b in row.buttons:
+                url = button_url(b)
+                if url is not None:
+                    item = {"t": b.text, "u": url}
+                    s = _style_dump(b)
+                    if s:
+                        item["s"] = s
+                    r.append(item)
+                else:
+                    try:
+                        r.append({"t": getattr(b, "text", ""), "raw": _b64(b)})
+                    except Exception:  # pragma: no cover
+                        log.warning("cannot store button %r", b)
+            if r:
+                rows.append(r)
+    return rows
+
+
+def build_markup(rows) -> Optional[types.ReplyInlineMarkup]:
+    out = []
+    for row in rows or []:
+        btns = []
+        for b in row:
+            if b.get("raw"):
+                try:
+                    btns.append(_unb64(b["raw"]))
+                except Exception:  # pragma: no cover
+                    continue
+            elif b.get("u"):
+                style = None
+                if b.get("s"):
+                    try:
+                        style = _unb64(b["s"])
+                    except Exception:  # pragma: no cover
+                        style = None
+                btns.append(make_url_button(b["t"], b["u"], style))
+        if btns:
+            out.append(types.KeyboardButtonRow(btns))
+    return types.ReplyInlineMarkup(out) if out else None
+
+
+def state_of(text, entities, markup, preview) -> dict:
+    """Snapshot used for the undo log."""
+    return {
+        "text": text or "",
+        "entities": ser_entities(entities),
+        "buttons": ser_markup(markup),
+        "preview": preview,  # True/False for text messages, None for media messages
+    }
+
+
+# --------------------------------------------------------------------------------- media
+def classify_media(m) -> Optional[str]:
+    """photo | video | animation | audio | document, or None (text / unsupported)."""
+    media = getattr(m, "media", None)
+    if isinstance(media, types.MessageMediaPhoto) and getattr(media, "photo", None):
+        return "photo"
+    if isinstance(media, types.MessageMediaDocument) and getattr(media, "document", None):
+        if m.gif:
+            return "animation"
+        if m.video:
+            return "video"
+        if m.audio:
+            return "audio"
+        if m.voice or m.video_note or m.sticker:
+            return None
+        return "document"
+    return None
+
+
+# Media is stored as the serialised Telegram media object ("tl:"). Telethon's Bot-API style
+# file_id helper cannot pack photos with the current Telegram schema, so we don't rely on it.
+_REF_PREFIX = "tl:"
+
+
+def media_ref(m) -> Optional[str]:
+    """A storable reference to the photo / document attached to message `m` (None if it has none)."""
+    media = getattr(m, "media", None)
+    if isinstance(media, (types.MessageMediaPhoto, types.MessageMediaDocument)):
+        try:
+            return _REF_PREFIX + _b64(media)
+        except Exception:  # pragma: no cover
+            log.warning("cannot store media reference", exc_info=True)
+    return None
+
+
+pack_file_id = media_ref  # older name, kept for the callers
+
+
+def media_from_ref(ref: str, *, blank_reference: bool = False):
+    """Rebuild the media object; `blank_reference` drops the (possibly expired) file reference."""
+    media = _unb64(ref[len(_REF_PREFIX):]) if ref.startswith(_REF_PREFIX) else None
+    if media is None:
+        raise ValueError("unknown media reference")
+    if blank_reference:
+        media = copy.copy(media)
+        inner = copy.copy(media.photo if isinstance(media, types.MessageMediaPhoto) else media.document)
+        inner.file_reference = b""
+        if isinstance(media, types.MessageMediaPhoto):
+            media.photo = inner
+        else:
+            media.document = inner
+    return media
+
+
+async def with_media(ref: str, call):
+    """call(media): first with the stored file reference, then (if Telegram says it expired) without it."""
+    try:
+        return await call(media_from_ref(ref))
+    except errors.RPCError as e:
+        if "FileReference" not in type(e).__name__ and type(e).__name__ != "MediaEmptyError":
+            raise
+        log.info("stored file reference rejected (%s) - retrying without it", type(e).__name__)
+        return await call(media_from_ref(ref, blank_reference=True))
+
+
+def media_info(m) -> tuple:
+    kind = classify_media(m)
+    return kind, (media_ref(m) if kind else None)
+
+
+def media_key(media) -> Optional[tuple]:
+    """("photo" | "doc", id) of the photo / file in a message's media; the id is the same on every account."""
+    if isinstance(media, types.MessageMediaPhoto) and getattr(media, "photo", None):
+        return "photo", media.photo.id
+    if isinstance(media, types.MessageMediaDocument) and getattr(media, "document", None):
+        return "doc", media.document.id
+    return None
+
+
+@dataclass
+class MediaFile:
+    """A photo or file downloaded from Telegram, with what is needed to upload it again as the same kind of post."""
+
+    path: str
+    kind: str  # photo | video | animation | audio | document
+    name: str
+    mime_type: Optional[str] = None
+    attributes: list = field(default_factory=list)  # the file's name, video size and length, GIF mark ... as it had them
+    thumb_path: Optional[str] = None  # the picture Telegram shows for the file (JPEG); None: it has none
+
+
+async def fetch_media(client, ref: str, kind: str, folder: str) -> MediaFile:
+    """Download the photo / file behind the stored media reference `ref` (as `client` sees it) into `folder`.
+
+    A file's thumbnail comes along: without it the file would be uploaded again with a plain file icon."""
+    path = await with_media(ref, lambda media: client.download_media(media, file=folder + os.sep))
+    if not path:
+        raise ValueError("Telegram gave me nothing to download for that media")
+    doc = getattr(media_from_ref(ref), "document", None)
+    return MediaFile(
+        path=str(path),
+        kind=kind,
+        name=os.path.basename(str(path)),
+        mime_type=getattr(doc, "mime_type", None),
+        attributes=list(getattr(doc, "attributes", None) or []),
+        thumb_path=await fetch_thumb(client, ref, folder) if doc is not None else None,
+    )
+
+
+async def fetch_thumb(client, ref: str, folder: str) -> Optional[str]:
+    """The thumbnail of the file behind `ref` (the largest one Telegram has) as a JPEG in `folder`, or None.
+
+    Best effort: a file that goes out without its thumbnail is better than an edit that fails."""
+    where = os.path.join(folder, "thumb")
+    try:
+        os.makedirs(where, exist_ok=True)
+        path = await with_media(ref, lambda media: client.download_media(media, file=where + os.sep, thumb=-1))
+    except (errors.RPCError, OSError, ValueError, TypeError) as e:
+        log.info("could not download the thumbnail: %s", type(e).__name__)
+        return None
+    return str(path) if path and os.path.isfile(str(path)) else None
+
+
+def utf16_len(s: str) -> int:
+    return len(s.encode("utf-16-le")) // 2
+
+
+# --------------------------------------------------------------------------------- misc
+def peer_of(ch) -> types.InputPeerChannel:
+    return types.InputPeerChannel(ch.id, ch.access_hash)
+
+
+def post_link(ch, message_id: int) -> str:
+    if ch.username:
+        return f"https://t.me/{ch.username}/{message_id}"
+    return f"https://t.me/c/{ch.id}/{message_id}"
+
+
+def short(s: str, n: int) -> str:
+    s = " ".join((s or "").split())
+    return s if len(s) <= n else s[: n - 1] + "…"
+
+
+async def flood_retry(factory: Callable[[], Awaitable[Any]], tries: int = 4) -> Any:
+    for _ in range(tries):
+        try:
+            return await factory()
+        except errors.FloodWaitError as e:
+            wait = int(getattr(e, "seconds", 5)) + 1
+            log.warning("flood wait %ss", wait)
+            await asyncio.sleep(min(wait, 900))
+    return await factory()
+
+
+async def edit_raw(
+    client,
+    peer,
+    message_id: int,
+    *,
+    text: Optional[str] = None,
+    entities=None,
+    markup=None,
+    preview=None,
+    media=None,
+    rich_message=None,
+):
+    """messages.editMessage with every field explicit.
+
+    `markup=None` together with `text` (or `rich_message`) removes the keyboard (that is how Telegram behaves);
+    a markup-only edit (text=None) leaves the text alone. `media` (an InputMedia) replaces the photo / file.
+    `rich_message` (an InputRichMessage*) makes the message that rich message instead of text.
+    """
+    kw: dict = {"peer": peer, "id": message_id}
+    if markup is not None:
+        kw["reply_markup"] = markup
+    if media is not None:
+        kw["media"] = media
+    if rich_message is not None:
+        kw["rich_message"] = rich_message
+    elif text is not None:
+        kw["message"] = text
+        kw["entities"] = list(entities or [])
+        if preview is not None:
+            kw["no_webpage"] = not preview
+    return await client(functions.messages.EditMessageRequest(**kw))
+
+
+async def get_rights(client, ch):
+    """The bot's own admin rights in a channel, or None if Telegram won't tell us."""
+    try:
+        res = await client(
+            functions.channels.GetParticipantRequest(channel=peer_of(ch), participant=types.InputPeerSelf())
+        )
+    except Exception as e:
+        log.info("could not read own rights in %s: %s", ch.id, e)
+        return None
+    p = res.participant
+    if isinstance(p, (types.ChannelParticipantCreator, types.ChannelParticipantAdmin)):
+        r = getattr(p, "admin_rights", None)
+        creator = isinstance(p, types.ChannelParticipantCreator)
+
+        def has(name: str) -> bool:
+            return True if (creator and r is None) else bool(getattr(r, name, False))
+
+        return SimpleNamespace(
+            admin=True,
+            post=has("post_messages"),
+            edit=has("edit_messages"),
+            delete=has("delete_messages"),
+            invite=has("invite_users"),
+            add_admins=has("add_admins"),
+            change_info=has("change_info"),
+        )
+    return SimpleNamespace(
+        admin=False, post=False, edit=False, delete=False, invite=False, add_admins=False, change_info=False
+    )
+
+
+_HINTS = {
+    "ChatAdminRequiredError": "The bot needs admin rights in that channel (post / edit / delete messages).",
+    "MessageAuthorRequiredError": "Telegram wants the message author. Give the bot the 'Edit messages of others' right.",
+    "InlineBotRequiredError": "That post was sent through another bot's inline mode, so only that bot can edit it.",
+    "MessageEditTimeExpiredError": "Telegram no longer allows editing that message.",
+    "MessageIdInvalidError": (
+        "Telegram won't let the bot change that message (or it was deleted). If the post is still there, "
+        "the usual reason is that its buttons were added by another bot: only that bot may change them."
+    ),
+    "ButtonUrlInvalidError": "Telegram rejected one of the button links.",
+    "ReplyMarkupInvalidError": "Telegram rejected the buttons.",
+    "ChatWriteForbiddenError": "The bot can't post in that channel - check its admin rights.",
+    "ChannelPrivateError": "The bot can't access that channel any more (removed or banned?).",
+    "UserBannedInChannelError": "The bot is banned in that channel.",
+    "FileReferenceExpiredError": "The saved media expired - send the media again.",
+    "MediaEmptyError": "Telegram could not use that media - send it again.",
+    "EntityBoundsInvalidError": "The text formatting doesn't fit the text.",
+    "EntitiesTooLongError": "The text has too many formatted pieces (bold, links ...) for Telegram - use less formatting.",
+    "MessageTooLongError": "The text is too long for Telegram.",
+    "MediaCaptionTooLongError": "The caption is too long for Telegram.",
+}
+
+
+# Telegram's own error codes (the name of the Python class is only "BadRequestError" for the ones Telethon doesn't know)
+_CODE_HINTS = {
+    "RICH_MESSAGE_BLOCK_INVALID": "Telegram would not take one of the blocks of that rich message.",
+}
+
+
+def explain_rpc(e: BaseException) -> str:
+    name = type(e).__name__
+    code = getattr(e, "message", None) or ""
+    hint = _HINTS.get(name)
+    if hint is None and code in _CODE_HINTS:
+        hint = f"{_CODE_HINTS[code]} ({code})"
+    return f"Telegram refused ({name}). " + (hint if hint is not None else str(e)[:200])
diff --git a/app/ui.py b/app/ui.py
new file mode 100644
index 0000000000000000000000000000000000000000..88e743d2dc565b6e49e4d8dee0b369944a4026e6
--- /dev/null
+++ b/app/ui.py
@@ -0,0 +1,114 @@
+"""Texts and inline keyboards for the post panel."""
+from __future__ import annotations
+
+from telethon import Button
+
+from .buttons import count, grid_label, link_positions, missing_links
+from .richmsg import rich_of
+from .tgutil import esc, post_link, short
+
+CANCEL = [[Button.inline("✖️ Cancel", "cx")]]
+KIND_ICON = {None: "📝", "photo": "🖼", "video": "🎬", "animation": "🎞", "audio": "🎵", "document": "📎"}
+KIND_NAME = {None: "text", "photo": "photo", "video": "video", "animation": "GIF", "audio": "audio", "document": "file"}
+
+
+def post_title(p) -> str:
+    for row in p.buttons or []:
+        for b in row:
+            if b.get("t"):
+                return b["t"]
+    text = (p.text or "").strip()
+    return text.splitlines()[0] if text else (KIND_NAME.get(p.media_kind) or "post")
+
+
+def post_label(p) -> str:
+    icon = "📝" if p.status == "draft" else "✅"
+    return f"{icon} #{p.id} {short(post_title(p), 34)}"
+
+
+def panel_text(p, ch, note=None) -> str:
+    state = "draft (not published yet)" if p.status == "draft" else "published"
+    lines = [f"Post #{p.id} · {state}", f"Channel: {esc(ch.title)}"]
+    if p.status == "sent" and p.message_id:
+        lines.append(f'Open in the channel')
+    rich = rich_of(p)
+    if rich is not None:
+        origin = {"html": "typed as HTML", "markdown": "typed as Markdown"}.get(rich.fmt, "made in Telegram")
+        lines.append(f"Type: 🧩 rich message ({origin})")
+    else:
+        lines.append(f"Type: {KIND_ICON.get(p.media_kind, '📎')} {KIND_NAME.get(p.media_kind, p.media_kind)}")
+    n, miss = count(p.buttons), missing_links(p.buttons)
+    lines.append(f"Buttons: {n}" + (f" (⚠️ {miss} without a link)" if miss else ""))
+    if p.source == "adopted":
+        lines.append("Picked up from the channel - it was not made with this bot.")
+    snippet = short(p.text or "", 220) or "(no text)"
+    lines += ["", f"{esc(snippet)}"]
+    if note:
+        lines += ["", note]
+    return "\n".join(lines)
+
+
+def panel_keyboard(p) -> list:
+    pid = p.id
+    kb = []
+    for r, row in enumerate(p.buttons or []):
+        kb.append([Button.inline(grid_label(b), f"bs:{pid}:{r}:{c}") for c, b in enumerate(row)])
+    rich = rich_of(p) is not None
+    kb.append(
+        [Button.inline("✏️ Caption" if p.media_kind else "✏️ Text", f"et:{pid}")]
+        + ([] if rich else [Button.inline("🖼 Media", f"em:{pid}")])  # a rich message has no media slot
+    )
+    row3 = [Button.inline("➕ Button", f"ba:{pid}"), Button.inline("📋 Set buttons", f"bp:{pid}")]
+    if p.buttons:
+        row3.append(Button.inline("🧹 Clear", f"bc:{pid}"))
+    kb.append(row3)
+    extra = []
+    if not p.media_kind and not rich:
+        extra.append(Button.inline(f"🔗 Link preview: {'on' if p.link_preview else 'off'}", f"lp:{pid}"))
+    if p.media_kind and p.status == "draft":
+        extra.append(Button.inline("🚫 Remove media", f"rm:{pid}"))
+    if extra:
+        kb.append(extra)
+    if p.status == "sent" and p.message_id and link_positions(p.buttons):
+        kb.append([Button.inline("🔗 Mass replace links", f"mlp:{pid}")])
+    if p.status == "draft":
+        kb.append([Button.inline("👁 Preview", f"pv:{pid}"), Button.inline("🚀 Publish", f"pb:{pid}")])
+        kb.append([Button.inline("🗑 Discard", f"dl:{pid}"), Button.inline("📚 My posts", "pc:d:0")])
+    else:
+        kb.append([Button.inline("👁 Preview", f"pv:{pid}"), Button.inline("🗑 Delete", f"dl:{pid}")])
+        kb.append([Button.inline("📚 My posts", f"pc:{p.channel_id}:0")])
+    return kb
+
+
+def button_text(p, r: int, c: int) -> str:
+    b = p.buttons[r][c]
+    if b.get("raw"):
+        return (
+            f"🔒 Button from another bot (row {r + 1}, position {c + 1})\n"
+            f"Text: {esc(b.get('t') or '')}\n"
+            "Buttons like reactions only work with the bot that made them, so you can move or delete it, "
+            "but not edit it."
+        )
+    return (
+        f"🔘 Button (row {r + 1}, position {c + 1})\n"
+        f"Text: {esc(b.get('t') or '')}\n"
+        f"Link: {esc(b.get('u') or '- none yet -')}"
+    )
+
+
+def button_keyboard(p, r: int, c: int) -> list:
+    pid, at = p.id, f"{p.id}:{r}:{c}"
+    b = p.buttons[r][c]
+    kb = []
+    if not b.get("raw"):
+        kb.append([Button.inline("✏️ Change text", f"bt:{at}"), Button.inline("🔗 Change link", f"bu:{at}")])
+    kb.append(
+        [
+            Button.inline("⬅️", f"bm:{at}:l"),
+            Button.inline("⬆️", f"bm:{at}:u"),
+            Button.inline("⬇️", f"bm:{at}:d"),
+            Button.inline("➡️", f"bm:{at}:r"),
+        ]
+    )
+    kb.append([Button.inline("🗑 Delete", f"bd:{at}"), Button.inline("🔙 Back", f"po:{pid}")])
+    return kb
diff --git a/app/userbot.py b/app/userbot.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6180c605c149bf9aebb6b58ce6a07fcf2ea7435
--- /dev/null
+++ b/app/userbot.py
@@ -0,0 +1,669 @@
+"""A userbot - a normal Telegram account - that does what the bot is not allowed to do in a channel.
+
+Deleting: Telegram's documentation says bots can only delete messages younger than 48 hours. The bot always tries
+first; whatever is left goes to the userbot.
+Editing: Telegram refuses the bot an edit of a post that belongs to another bot (its buttons were added by that bot,
+or it was posted through it). The bot always tries first; when Telegram refuses, the userbot makes the edit (text,
+caption or a new photo / file). A user account can't set inline buttons, so Telegram may drop them with that edit -
+the bot puts them back where it can.
+A new photo / file goes to the userbot through the userbot's own chat with the bot: the bot sends it there (Telegram
+just points to the file it already has - nothing is uploaded), the userbot finds it in that chat and edits the post
+with that copy, again by reference. So a big file is as quick as a small one and keeps its thumbnail. Only when that
+chat does not work (the userbot account never started the bot) is the file downloaded and uploaded again.
+
+How it gets into the channel:
+  1. the bot makes a one-time invite link (or reads the channel's own link) and the userbot joins with it
+     (public channels without a usable link: the userbot joins by name);
+  2. if the userbot is not allowed to do the job there yet and the bot has the "Add new admins" right, the bot
+     makes the userbot an admin with that one right ("Delete messages" / "Edit messages of others");
+  3. the userbot does the job, and afterwards the bot gives the admin rights back as they were
+     (USERBOT_KEEP_ADMIN=true keeps the new right).
+The session lives in USERBOT_SESSION (made on your own computer with make_userbot_session.py).
+"""
+from __future__ import annotations
+
+import asyncio
+import datetime
+import logging
+import re
+from typing import Optional
+
+from telethon import TelegramClient, errors, functions, types, utils
+from telethon.sessions import StringSession
+
+from .richmsg import with_rich
+from .tgutil import MediaFile, edit_raw, flood_retry, get_rights, media_from_ref, media_key, peer_of, with_media
+
+log = logging.getLogger(__name__)
+
+_INVITE_RX = re.compile(
+    r"(?i)(?:https?://)?(?:t\.me|telegram\.me|telegram\.dog)/(?:\+|joinchat/)([A-Za-z0-9_-]{8,})"
+    r"|tg://join\?invite=([A-Za-z0-9_-]{8,})"
+)
+
+
+class UserbotError(Exception):
+    """Something the owner can fix; the text is meant to be shown."""
+
+
+class UserbotRefused(UserbotError):
+    """Telegram refused what the userbot tried; `name` is the Telegram error (e.g. MediaInvalidError)."""
+
+    def __init__(self, text: str, name: str = ""):
+        super().__init__(text)
+        self.name = name
+
+    @property
+    def about_media(self) -> bool:
+        """The refusal is about the photo / file the userbot used (so trying it another way may help)."""
+        return self.name in _MEDIA_REFUSED
+
+
+# What Telegram answers when the photo / file the userbot points to can't be used for an edit
+_MEDIA_REFUSED = {
+    "MediaInvalidError", "MediaEmptyError", "DocumentInvalidError", "PhotoInvalidError",
+    "FileReferenceExpiredError", "FileReferenceInvalidError", "FileReferenceEmptyError",
+}
+# What Telegram answers when the bot may not write to the userbot account (it never started the bot, or blocked it)
+_NOT_STARTED = {
+    "UserIsBlockedError", "PeerIdInvalidError", "InputUserDeactivatedError", "UserDeactivatedError", "UserIdInvalidError",
+}
+_DM_POLLS = 10  # how often, and how long apart, the userbot looks in its chat with the bot for the file it was sent
+_DM_WAIT = 0.5
+
+
+def parse_invite_hash(link: str) -> Optional[str]:
+    m = _INVITE_RX.search(link or "")
+    return (m.group(1) or m.group(2)) if m else None
+
+
+def _default_factory(cfg) -> TelegramClient:
+    return TelegramClient(StringSession(cfg.userbot_session), cfg.api_id, cfg.api_hash, receive_updates=False)
+
+
+class Userbot:
+    def __init__(self, bot_client, cfg, client_factory=None):
+        self.bot = bot_client
+        self.cfg = cfg
+        self._factory = client_factory or _default_factory
+        self.client = None
+        self.me = None
+        self.last_error: Optional[str] = None
+        self.lock = asyncio.Lock()  # one channel job at a time (join / promote / delete or edit / demote)
+
+    @property
+    def enabled(self) -> bool:
+        return bool(getattr(self.cfg, "userbot_session", ""))
+
+    @property
+    def ready(self) -> bool:
+        return self.client is not None
+
+    @property
+    def keep_admin(self) -> bool:
+        return bool(getattr(self.cfg, "userbot_keep_admin", False))
+
+    async def connect(self) -> bool:
+        """Log the userbot in. True when it is usable; otherwise the reason is in `last_error`."""
+        if not self.enabled:
+            self.last_error = "USERBOT_SESSION is not set."
+            return False
+        if self.client is not None:
+            return True
+        client = None
+        try:
+            client = self._factory(self.cfg)
+            await client.connect()
+            if not await client.is_user_authorized():
+                raise UserbotError(
+                    "The userbot session is not logged in any more (or it was revoked). "
+                    "Make a new one with make_userbot_session.py."
+                )
+            me = await client.get_me()
+            if getattr(me, "bot", False):
+                raise UserbotError("USERBOT_SESSION belongs to a bot. The userbot has to be a normal user account.")
+        except Exception as e:
+            self.last_error = str(e) if isinstance(e, UserbotError) else f"{type(e).__name__}: {str(e)[:200]}"
+            log.warning("the userbot is not available: %s", self.last_error)
+            if client is not None:
+                try:
+                    await client.disconnect()
+                except Exception:
+                    pass
+            return False
+        self.client, self.me, self.last_error = client, me, None
+        log.info("userbot logged in as %s (id %s)", getattr(me, "username", None) or getattr(me, "first_name", ""), me.id)
+        return True
+
+    async def close(self) -> None:
+        client, self.client = self.client, None
+        if client is not None:
+            try:
+                await client.disconnect()
+            except Exception:
+                pass
+
+    def describe(self) -> str:
+        if not self.enabled:
+            return "not set up (USERBOT_SESSION is empty)"
+        if self.ready:
+            name = getattr(self.me, "username", None)
+            who = f"@{name}" if name else (getattr(self.me, "first_name", "") or "the account")
+            return f"connected as {who} (id {self.me.id})"
+        return f"set up, but not connected: {self.last_error or 'unknown reason'}"
+
+    def deleter(self, ch) -> "UserbotDeleter":
+        return UserbotDeleter(self, ch)
+
+    def editor(self, ch) -> "UserbotEditor":
+        return UserbotEditor(self, ch)
+
+    async def fallback_for(self, ch):
+        """(delete function, deleter) to hand to the delete step, or (None, None) when no userbot is usable.
+
+        Nothing happens in the channel until the bot has failed to delete something and the function is called;
+        the caller must always `await deleter.close()` afterwards.
+        """
+        if not self.enabled:
+            return None, None
+        if not self.ready:
+            await self.connect()
+        if not self.ready:
+            return None, None
+        d = self.deleter(ch)
+        return d.delete, d
+
+    async def editor_for(self, ch) -> Optional["UserbotEditor"]:
+        """An editor for posts in `ch`, or None when no userbot is usable. The caller must always `await editor.close()`."""
+        if not self.enabled:
+            return None
+        if not self.ready:
+            await self.connect()
+        return self.editor(ch) if self.ready else None
+
+
+def _rights_dict(rights) -> dict:
+    return {k: v for k, v in rights.to_dict().items() if k != "_"} if rights is not None else {}
+
+
+class _ChannelJob:
+    """Everything needed to do ONE job in ONE channel with the userbot. Call close() when done, whatever happened.
+
+    What the job needs is named by RIGHT (the field of ChatAdminRights) and RIGHT_NAME (what the Telegram apps call it).
+    """
+
+    RIGHT = "delete_messages"
+    RIGHT_NAME = "Delete messages"
+    WHAT = "delete messages"  # what the userbot may not do without the right (as the owner is told)
+    VERB = "delete"
+
+    def __init__(self, ub: Userbot, ch):
+        self.ub = ub
+        self.ch = ch
+        self.peer = None  # the channel as the userbot sees it
+        self.notes: list = []
+        self._ready = False
+        self._holds_lock = False
+        self._promoted = False
+        self._before = None  # (admin rights, rank) the userbot had before the bot changed them; None = a plain member
+        self._bot_user = None  # the userbot account as the bot sees it (InputUser)
+        self._link: Optional[str] = None  # the temporary invite link we made
+
+    # ------------------------------------------------------------------ public
+    async def _begin(self) -> None:
+        """Get the channel ready (joined, with the right). The userbot's lock is kept until close()."""
+        if not self.ub.ready:
+            raise UserbotError(f"The userbot is not connected: {self.ub.last_error or 'unknown reason'}")
+        if not self._ready:
+            if not self._holds_lock:  # released again in close()
+                await self.ub.lock.acquire()
+                self._holds_lock = True
+            await self._prepare()
+            self._ready = True
+
+    async def close(self) -> None:
+        """Undo what this job changed: give the admin rights back as they were, revoke the temporary link."""
+        bot, ch = self.ub.bot, self.ch
+        try:
+            if self._promoted and self._bot_user is not None and not self.ub.keep_admin:
+                rights, rank = self._before or (types.ChatAdminRights(), "")
+                try:
+                    await bot(
+                        functions.channels.EditAdminRequest(
+                            channel=peer_of(ch), user_id=self._bot_user, admin_rights=rights, rank=rank
+                        )
+                    )
+                    self.notes.append(
+                        "took the admin right away from the userbot again"
+                        if self._before is None
+                        else "put the userbot's admin rights back as they were"
+                    )
+                except Exception as e:
+                    log.warning("could not demote the userbot in %s: %s", ch.id, type(e).__name__)
+                    self.notes.append("could not take the admin right away from the userbot - please do it by hand")
+            if self._link:
+                try:
+                    await bot(
+                        functions.messages.EditExportedChatInviteRequest(peer=peer_of(ch), link=self._link, revoked=True)
+                    )
+                except Exception as e:
+                    log.info("could not revoke the temporary invite link: %s", type(e).__name__)
+        finally:
+            self._promoted, self._link = False, None
+            if self._holds_lock:
+                self._holds_lock = False
+                self.ub.lock.release()
+
+    # ----------------------------------------------------------------- prepare
+    async def _prepare(self) -> None:
+        peer = await self._member_peer()
+        if peer is None:
+            peer = await self._join()
+        self.peer = peer
+        await self._ensure_right()
+
+    async def _member_peer(self):
+        """The channel as the userbot sees it, if the userbot is in it already."""
+        ub = self.ub.client
+        try:
+            peer = await ub.get_input_entity(types.PeerChannel(self.ch.id))
+            if not isinstance(peer, types.InputPeerChannel):
+                return None
+            await ub(functions.channels.GetParticipantRequest(peer, types.InputPeerSelf()))
+        except (errors.RPCError, ValueError, TypeError):
+            return None
+        return peer
+
+    async def _invite_link(self) -> Optional[str]:
+        bot, peer = self.ub.bot, peer_of(self.ch)
+        try:
+            expires = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1)
+            res = await bot(
+                functions.messages.ExportChatInviteRequest(peer=peer, expire_date=expires, usage_limit=1, title="Cleanup helper")
+            )
+            link = getattr(res, "link", None)
+            if link:
+                self._link = link
+                self.notes.append("made a one-time invite link for the userbot")
+                return link
+        except errors.RPCError as e:
+            log.info("could not create an invite link in %s: %s", self.ch.id, type(e).__name__)
+        try:
+            full = await bot(functions.channels.GetFullChannelRequest(peer))
+            link = getattr(getattr(full.full_chat, "exported_invite", None), "link", None)
+            if link:
+                self.notes.append("used the channel's own invite link")
+                return link
+        except errors.RPCError as e:
+            log.info("could not read the invite link of %s: %s", self.ch.id, type(e).__name__)
+        return None
+
+    async def _join(self):
+        link = await self._invite_link()
+        h = parse_invite_hash(link) if link else None
+        if h:
+            peer = await self._import_invite(h)
+            if peer is not None:
+                self.notes.append("the userbot joined the channel")
+                return peer
+        if self.ch.username:
+            peer = await self._join_public(self.ch.username)
+            self.notes.append("the userbot joined the channel by its public name")
+            return peer
+        raise UserbotError(
+            "I could not get the userbot into this private channel: Telegram gave me no invite link. "
+            "Give the bot the “Invite users via link” admin right, or add the userbot to the channel yourself "
+            f"(with the “{self.RIGHT_NAME}” admin right)."
+        )
+
+    async def _import_invite(self, h: str):
+        ub = self.ub.client
+        try:
+            res = await flood_retry(lambda: ub(functions.messages.ImportChatInviteRequest(h)))
+        except errors.UserAlreadyParticipantError:
+            return await self._peer_when_already_in(h)
+        except errors.InviteRequestSentError:
+            raise UserbotError(
+                "This channel's invite link needs an admin to approve new members. Approve the userbot's join request "
+                "(or add the userbot yourself) and try again."
+            )
+        except (errors.InviteHashExpiredError, errors.InviteHashInvalidError, errors.InviteHashEmptyError):
+            return None
+        except (errors.ChannelsTooMuchError, errors.UserChannelsTooMuchError):
+            raise UserbotError("The userbot account is in too many channels. Leave a few with that account and try again.")
+        except errors.UserBannedInChannelError:
+            raise UserbotError("The userbot account is banned in this channel. Unban it first.")
+        return self._peer_from_updates(res)
+
+    def _peer_from_updates(self, res):
+        chats = [c for c in (getattr(res, "chats", None) or []) if isinstance(c, types.Channel)]
+        for c in chats:
+            if c.id == self.ch.id:
+                return utils.get_input_peer(c)
+        if len(chats) == 1:
+            return utils.get_input_peer(chats[0])
+        raise UserbotError("The userbot joined, but Telegram did not tell me which channel it is. Try again.")
+
+    async def _peer_when_already_in(self, h: str):
+        ub = self.ub.client
+        try:
+            info = await ub(functions.messages.CheckChatInviteRequest(h))
+            if isinstance(info, types.ChatInviteAlready):
+                return utils.get_input_peer(info.chat)
+        except errors.RPCError:
+            pass
+        async for d in ub.iter_dialogs():
+            if getattr(d.entity, "id", None) == self.ch.id and isinstance(d.entity, types.Channel):
+                return utils.get_input_peer(d.entity)
+        raise UserbotError("The userbot is in the channel, but I could not find it in its chat list.")
+
+    async def _join_public(self, username: str):
+        ub = self.ub.client
+        try:
+            peer = await ub.get_input_entity(username)
+            try:
+                await flood_retry(lambda: ub(functions.channels.JoinChannelRequest(peer)))
+            except errors.UserAlreadyParticipantError:
+                pass
+        except (errors.ChannelsTooMuchError, errors.UserChannelsTooMuchError):
+            raise UserbotError("The userbot account is in too many channels. Leave a few with that account and try again.")
+        except errors.UserBannedInChannelError:
+            raise UserbotError("The userbot account is banned in this channel. Unban it first.")
+        except (errors.UsernameNotOccupiedError, errors.UsernameInvalidError, errors.ChannelPrivateError):
+            raise UserbotError(f"The userbot could not open @{username}. Has the channel's name changed?")
+        return peer
+
+    # ------------------------------------------------------------------ rights
+    async def _userbot_status(self):
+        """(is the creator, its admin rights or None, its rank) as the channel shows the userbot; None if unknown."""
+        try:
+            res = await self.ub.client(functions.channels.GetParticipantRequest(self.peer, types.InputPeerSelf()))
+        except errors.RPCError:
+            return None
+        p = res.participant
+        if isinstance(p, types.ChannelParticipantCreator):
+            return True, None, ""
+        if isinstance(p, types.ChannelParticipantAdmin):
+            return False, p.admin_rights, getattr(p, "rank", None) or ""
+        return False, None, ""
+
+    async def _userbot_has_right(self) -> bool:
+        status = await self._userbot_status()
+        if status is None:
+            return False
+        creator, rights, _ = status
+        return creator or bool(getattr(rights, self.RIGHT, False))
+
+    async def _ensure_right(self) -> None:
+        if await self._userbot_has_right():
+            return
+        rights = await get_rights(self.ub.bot, self.ch)
+        if rights is None or not (rights.admin and rights.add_admins):
+            raise UserbotError(
+                f"The userbot is in the channel but may not {self.WHAT} there, and the bot may not add admins. "
+                "Give the bot the “Add new admins” right (it then promotes the userbot by itself), or make the userbot "
+                f"an admin with “{self.RIGHT_NAME}” yourself."
+            )
+        user = await self._bot_view_of_userbot()
+        status = await self._userbot_status()
+        had = _rights_dict(status[1]) if status else {}
+        rank = status[2] if status else ""
+        try:
+            await self.ub.bot(
+                functions.channels.EditAdminRequest(
+                    channel=peer_of(self.ch),
+                    user_id=user,
+                    admin_rights=types.ChatAdminRights(**{**had, self.RIGHT: True}),  # what it had, plus this one right
+                    rank=rank,
+                )
+            )
+        except errors.RPCError as e:
+            name = type(e).__name__
+            hint = {
+                "RightForbiddenError": "The bot may not give that right.",
+                "UserAdminInvalidError": "The bot may not change that user's admin status.",
+                "AdminsTooMuchError": "The channel already has the maximum number of admins.",
+                "ChatAdminRequiredError": "The bot needs the “Add new admins” right.",
+            }.get(name, str(e)[:150])
+            raise UserbotError(f"I could not make the userbot an admin ({name}). {hint}")
+        self._promoted, self._bot_user = True, user
+        if any(had.values()):
+            self._before = (status[1], rank)
+            self.notes.append(f"gave the userbot the “{self.RIGHT_NAME}” right on top of the ones it had")
+        else:
+            self.notes.append(f"made the userbot an admin with only “{self.RIGHT_NAME}”")
+        for _ in range(12):  # the new right can take a moment to show up for the other account
+            if await self._userbot_has_right():
+                return
+            await asyncio.sleep(0.5)
+        raise UserbotError(
+            f"I made the userbot an admin, but Telegram still does not let it {self.VERB} there. Check its rights."
+        )
+
+    async def _bot_view_of_userbot(self):
+        """The userbot account as an InputUser the BOT can use (needs the bot's own access hash for that user)."""
+        bot, me = self.ub.bot, self.ub.me
+        uid = me.id
+        try:
+            ent = await bot.get_input_entity(uid)
+            if isinstance(ent, types.InputPeerUser):
+                return types.InputUser(ent.user_id, ent.access_hash)
+        except Exception:
+            pass
+        queries = [types.ChannelParticipantsRecent()]
+        for q in (getattr(me, "username", None), getattr(me, "first_name", None)):
+            if q:
+                queries.append(types.ChannelParticipantsSearch(q))
+        for flt in queries:
+            try:
+                res = await bot(
+                    functions.channels.GetParticipantsRequest(channel=peer_of(self.ch), filter=flt, offset=0, limit=200, hash=0)
+                )
+            except errors.RPCError:
+                continue
+            for u in getattr(res, "users", None) or []:
+                if getattr(u, "id", None) == uid and getattr(u, "access_hash", None) is not None:
+                    return types.InputUser(u.id, u.access_hash)
+        if getattr(me, "username", None):
+            try:
+                ent = await bot.get_input_entity(me.username)
+                if isinstance(ent, types.InputPeerUser):
+                    return types.InputUser(ent.user_id, ent.access_hash)
+            except Exception:
+                pass
+        raise UserbotError(
+            "The userbot joined, but the bot cannot find that account in the channel's member list, so it cannot "
+            f"promote it. Make the userbot an admin with “{self.RIGHT_NAME}” yourself."
+        )
+
+
+class UserbotDeleter(_ChannelJob):
+    """Deletes messages in ONE channel with the userbot. Call close() when done, whatever happened."""
+
+    async def delete(self, ids: list) -> None:
+        await self._begin()
+        client = self.ub.client
+        for i in range(0, len(ids), 100):
+            part = list(ids[i : i + 100])
+            await flood_retry(
+                lambda part=part: client(functions.channels.DeleteMessagesRequest(channel=self.peer, id=part))
+            )
+
+
+_EDIT_HINTS = {
+    "ChatAdminRequiredError": "It needs the “Edit messages of others” admin right in that channel.",
+    "MessageAuthorRequiredError": "It needs the “Edit messages of others” admin right in that channel.",
+    "MessageIdInvalidError": "The post may be gone, or Telegram does not let anyone edit it.",
+    "InlineBotRequiredError": "That post was sent through another bot's inline mode, so only that bot can edit it.",
+    "MessageEditTimeExpiredError": "Telegram no longer allows editing that message.",
+}
+
+
+class UserbotEditor(_ChannelJob):
+    """Edits posts in ONE channel as the userbot. Call close() when done, whatever happened.
+
+    The userbot is a user account: it can't set inline buttons, so its edit carries none and Telegram may drop the ones
+    the post had. The caller puts them back afterwards."""
+
+    RIGHT = "edit_messages"
+    RIGHT_NAME = "Edit messages of others"
+    WHAT = "edit other people's posts"
+    VERB = "edit"
+
+    def __init__(self, ub: Userbot, ch):
+        super().__init__(ub, ch)
+        self._handed: list = []  # (the userbot account as the bot addresses it, the bot's id of the message): files put in its chat
+        self.dm_problem: Optional[str] = None  # why a file could not go through that chat (None: it did, or it was not tried)
+
+    async def close(self) -> None:
+        """Clean up the channel (rights, link) and the files the bot put into the userbot's chat with the bot."""
+        handed, self._handed = self._handed, []
+        for peer, message_id in handed:
+            try:
+                await self.ub.bot.delete_messages(peer, [message_id])
+            except Exception as e:  # noqa: BLE001 - at worst a message is left in the helper account's chat
+                log.info("could not delete the helper message in the userbot's chat: %s", type(e).__name__)
+        await super().close()
+
+    async def edit(self, message_id: int, *, text: str, entities: list, media=None, preview=None, rich=None) -> None:
+        """Make the post show `text` (with `entities`) and, when given, `media`: what media_by_reference() returned (the
+        file does not move at all) or a MediaFile (uploaded again). `rich` (a richmsg.Rich) makes it that rich message."""
+        await self._begin()
+        client = self.ub.client
+        try:
+            if isinstance(media, MediaFile):
+                media = await self._upload(media)
+            if rich is not None:
+                await flood_retry(
+                    lambda: with_rich(rich, lambda inp: edit_raw(client, self.peer, message_id, rich_message=inp))
+                )
+            else:
+                await flood_retry(
+                    lambda: edit_raw(
+                        client, self.peer, message_id, text=text, entities=entities, preview=preview, media=media
+                    )
+                )
+        except errors.MessageNotModifiedError:
+            return  # it already looks like that
+        except errors.RPCError as e:
+            name = type(e).__name__
+            raise UserbotRefused(
+                f"Telegram refused the userbot as well ({name}). {_EDIT_HINTS.get(name) or str(e)[:200]}", name
+            )
+
+    # ----------------------------------------------------------- a file by way of the userbot's chat with the bot
+    async def media_by_reference(self, ref: str):
+        """The new photo / file as the userbot's own account holds it, ready to edit the post with - or None.
+
+        The bot sends it to the userbot's chat with the bot (Telegram reuses the file it already has, nothing is
+        downloaded or uploaded) and the userbot picks the message up there. The access data of a file belongs to one
+        account, so the bot's own reference would be useless to the userbot: this is how the userbot gets its own.
+        None when it does not work; `dm_problem` says why, and the caller uploads the file instead."""
+        await self._begin()
+        self.dm_problem = None
+        try:
+            return await self._hand_over(ref)
+        except (errors.RPCError, ValueError, TypeError, OSError) as e:
+            self.dm_problem = f"it failed with {type(e).__name__}"
+            log.info("could not hand the file to the userbot: %s", type(e).__name__, exc_info=True)
+            return None
+
+    async def _hand_over(self, ref: str):
+        bot, client = self.ub.bot, self.ub.client
+        want = media_key(media_from_ref(ref))
+        if want is None:
+            raise ValueError("not a photo or a file")
+        try:  # both ends of the chat first: nothing is sent when one of them can't be found
+            user = await self._bot_view_of_userbot()
+        except UserbotError:
+            self.dm_problem = "the bot cannot find the userbot account"
+            return None
+        try:
+            bot_peer = await self._userbot_view_of_bot()
+        except UserbotError as e:
+            self.dm_problem = str(e)
+            return None
+        peer = types.InputPeerUser(user.user_id, user.access_hash)
+        try:
+            sent = await with_media(ref, lambda media: flood_retry(lambda: bot.send_file(peer, media, silent=True)))
+        except errors.RPCError as e:
+            name = type(e).__name__
+            self.dm_problem = (
+                "the userbot account has not started the bot yet (send /start to the bot from that account)"
+                if name in _NOT_STARTED
+                else f"Telegram would not let the bot send the file to the userbot ({name})"
+            )
+            return None
+        self._handed.append((peer, sent.id))  # deleted again in close()
+        for i in range(_DM_POLLS):  # the message has to reach the userbot's side first
+            if i:
+                await asyncio.sleep(_DM_WAIT)
+            try:
+                msgs = await flood_retry(lambda: client.get_messages(bot_peer, limit=10))
+            except errors.RPCError as e:
+                self.dm_problem = f"the userbot could not read its chat with the bot ({type(e).__name__})"
+                return None
+            for m in msgs:  # newest first; the same photo / file has the same id on both accounts
+                if media_key(getattr(m, "media", None)) == want:
+                    return utils.get_input_media(m.media)
+        self.dm_problem = "the file did not show up in the userbot's chat with the bot"
+        return None
+
+    async def _userbot_view_of_bot(self):
+        """The bot as the userbot account addresses it (found by the bot's username)."""
+        me = await self.ub.bot.get_me()
+        name = getattr(me, "username", None)
+        if not name:
+            raise UserbotError("the bot has no username, so the userbot cannot find its chat with it")
+        try:
+            return await self.ub.client.get_input_entity(name)
+        except (errors.RPCError, ValueError):
+            raise UserbotError("the userbot could not find the bot by its username")
+
+    # --------------------------------------------------------------------------------- the slow way
+    async def _upload(self, f: MediaFile):
+        """Upload a downloaded photo / file (with its thumbnail) as the new media of the post."""
+        client = self.ub.client
+        handle = await flood_retry(lambda: client.upload_file(f.path, file_name=f.name))
+        if f.kind == "photo":
+            return types.InputMediaUploadedPhoto(file=handle)
+        thumb = None
+        if f.thumb_path:
+            try:
+                thumb = await flood_retry(lambda: client.upload_file(f.thumb_path))
+            except (errors.RPCError, OSError) as e:  # the file goes without it rather than not at all
+                log.info("could not upload the thumbnail: %s", type(e).__name__)
+        return types.InputMediaUploadedDocument(
+            file=handle,
+            mime_type=f.mime_type or "application/octet-stream",
+            attributes=list(f.attributes),
+            thumb=thumb,
+            force_file=True if f.kind == "document" else None,  # a file sent "as a file" stays one
+        )
+
+
+def delete_problem_text(ub, *, bot_error: Optional[str] = None, fallback_error: Optional[str] = None, tried: bool = False) -> str:
+    """Why some messages could not be deleted, in words for the owner."""
+    parts = []
+    if bot_error:
+        parts.append(f"Telegram refused the bot ({bot_error}).")
+    if fallback_error:
+        parts.append(f"The userbot could not help: {fallback_error}")
+    elif tried:
+        parts.append("The userbot tried as well, but the posts are still there.")
+    elif ub is None or not getattr(ub, "enabled", False):
+        parts.append("Posts older than 48 hours may need a userbot - see /userbot.")
+    elif not ub.ready:
+        parts.append(f"The userbot is not connected: {ub.last_error or 'unknown reason'}")
+    return " ".join(parts) or "Telegram did not delete them (the bot's “Delete messages” right, or an age limit on old posts)."
+
+
+def edit_problem_text(ub, *, fallback_error: Optional[str] = None) -> str:
+    """What to add when Telegram refused the bot's edit and the userbot could not take over (empty: nothing to add)."""
+    if fallback_error:
+        return f"The userbot could not do it either: {fallback_error}"
+    if ub is None or not getattr(ub, "enabled", False):
+        return "A userbot can edit such posts for you - see /userbot."
+    if not ub.ready:
+        return f"The userbot is not connected: {ub.last_error or 'unknown reason'}"
+    return ""
diff --git a/bot.py b/bot.py
new file mode 100644
index 0000000000000000000000000000000000000000..016184c7651be4b7b70e4b35c24853c11fab3314
--- /dev/null
+++ b/bot.py
@@ -0,0 +1,164 @@
+"""Channel Post Bot - entry point.  Run:  python bot.py"""
+from __future__ import annotations
+
+import asyncio
+import logging
+import os
+from urllib.parse import unquote, urlsplit
+
+from telethon import TelegramClient, functions, types
+from telethon.sessions import StringSession
+
+from app.common import Ctx
+from app.config import Config, load_config
+from app.db import Database
+from app.errorlog import ErrorReporter, TelegramLogHandler
+from app.expiry import Expirer
+from app.handlers import (
+    autopost,
+    backup,
+    basic,
+    broadcast,
+    channels,
+    checkbtn,
+    create,
+    masslinks,
+    posts,
+    replace,
+    repost,
+    shift,
+    sync,
+)
+from app.health import start_health_server
+from app.syncer import Syncer
+from app.userbot import Userbot
+
+log = logging.getLogger("bot")
+
+COMMANDS = [
+    ("new", "Create a post"),
+    ("posts", "My posts and drafts"),
+    ("autopost", "Post a series of episode download buttons"),
+    ("formatting", "How to format text: bold, links, quotes ... (HTML / Markdown)"),
+    ("addchannel", "Register a channel"),
+    ("channels", "List channels"),
+    ("broadcast", "Send one message to all channels, optionally timed (owner)"),
+    ("replace", "Replace a post's media and caption (owner)"),
+    ("swap", "Swap a username in links (owner)"),
+    ("handleswap", "Swap a @username written in posts (owner)"),
+    ("repost", "Copy a whole channel in order (owner)"),
+    ("shift", "Copy posts from one channel to another (owner)"),
+    ("sync", "Compare channels with My posts now (owner)"),
+    ("undo", "Undo the last replace (owner)"),
+    ("userbot", "Status of the helper account that deletes and edits what the bot can't (owner)"),
+    ("export", "Backup as JSON (owner)"),
+    ("import", "Restore a backup made by /export (owner)"),
+    ("admins", "List admins (owner)"),
+    ("addadmin", "Add an admin by numeric ID (owner)"),
+    ("removeadmin", "Remove an admin by numeric ID (owner)"),
+    ("cancel", "Cancel what I'm doing"),
+    ("help", "Show help"),
+]
+
+
+def build_client(cfg: Config) -> TelegramClient:
+    if cfg.session_string:
+        session = StringSession(cfg.session_string)
+    else:
+        os.makedirs(os.path.dirname(cfg.session_path) or ".", exist_ok=True)
+        session = cfg.session_path
+    client = TelegramClient(session, cfg.api_id, cfg.api_hash)
+    client.parse_mode = "html"
+    return client
+
+
+def register_all(ctx: Ctx) -> None:
+    for module in (basic, backup, channels, create, posts, masslinks, autopost, broadcast, checkbtn, replace, repost, shift, sync):
+        module.register(ctx)
+
+
+async def set_commands(client: TelegramClient) -> None:
+    try:
+        await client(
+            functions.bots.SetBotCommandsRequest(
+                scope=types.BotCommandScopeDefault(),
+                lang_code="",
+                commands=[types.BotCommand(command=c, description=d) for c, d in COMMANDS],
+            )
+        )
+    except Exception as e:  # cosmetic only
+        log.warning("could not set the command menu: %s", e)
+
+
+def secrets_of(cfg: Config) -> list:
+    """Texts that must never appear in the error log."""
+    out = [cfg.bot_token, cfg.api_hash, cfg.session_string, cfg.userbot_session]
+    try:
+        parts = urlsplit(cfg.database_url)
+        if parts.password:
+            out += [parts.password, unquote(parts.password)]
+    except Exception:
+        pass
+    return [s for s in out if s]
+
+
+async def main() -> None:
+    cfg = load_config()
+    logging.basicConfig(level=cfg.log_level, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
+    logging.getLogger("telethon").setLevel(logging.WARNING)
+
+    client = build_client(cfg)
+    reporter = ErrorReporter(client, cfg.error_log_chat_id, bot_token=cfg.bot_token, secrets=secrets_of(cfg))
+    reporter.start()
+    logging.getLogger().addHandler(TelegramLogHandler(reporter))
+    asyncio.get_running_loop().set_exception_handler(reporter.loop_exception_handler)
+
+    db = None
+    ctx = None
+    userbot = Userbot(client, cfg)
+    try:
+        db = Database(cfg.database_url, cfg.db_pool)
+        await db.init()
+        ctx = Ctx(cfg=cfg, db=db, client=client, userbot=userbot, reporter=reporter)
+        ctx.admins = await db.list_admins()
+        ctx.expirer = Expirer(ctx)
+        ctx.syncer = Syncer(ctx)
+        register_all(ctx)
+        await client.start(bot_token=cfg.bot_token)
+        me = await client.get_me()
+        log.info("Logged in as @%s (owners: %s)", me.username, ", ".join(map(str, sorted(cfg.owners))))
+        await set_commands(client)
+        if cfg.port:
+            await start_health_server(cfg.port)
+        problem = await reporter.check()
+        if reporter.enabled:
+            if problem:
+                log.warning("errors cannot be sent to chat %s yet: %s", cfg.error_log_chat_id, problem)
+            else:
+                log.info("errors are sent to chat %s", cfg.error_log_chat_id)
+        else:
+            log.info("error log chat: off")
+        if userbot.enabled:
+            await userbot.connect()  # never fatal: the userbot is only needed for old posts
+        ctx.expirer.start()  # deletes timed broadcasts when their time is up
+        ctx.syncer.start()  # compares the channels with My posts now and then (and notices changes made meanwhile)
+        await client.run_until_disconnected()
+    except Exception as e:
+        await reporter.report_fatal("The bot stopped because of an unhandled exception", e)
+        raise
+    finally:
+        if ctx is not None and ctx.syncer is not None:
+            await ctx.syncer.stop()
+        if ctx is not None and ctx.expirer is not None:
+            await ctx.expirer.stop()
+        await userbot.close()
+        if db is not None:
+            await db.close()
+        await reporter.stop()
+
+
+if __name__ == "__main__":
+    try:
+        asyncio.run(main())
+    except KeyboardInterrupt:
+        pass
diff --git a/data/.gitkeep b/data/.gitkeep
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/make_session.py b/make_session.py
new file mode 100644
index 0000000000000000000000000000000000000000..4dd20447cca6069fd89e740a966a20ab33a0bf04
--- /dev/null
+++ b/make_session.py
@@ -0,0 +1,17 @@
+"""Prints a SESSION_STRING for hosts that lose local files on restart:  python make_session.py"""
+import asyncio
+
+from telethon import TelegramClient
+from telethon.sessions import StringSession
+
+from app.config import load_config
+
+
+async def main() -> None:
+    cfg = load_config()
+    async with TelegramClient(StringSession(), cfg.api_id, cfg.api_hash) as client:
+        await client.start(bot_token=cfg.bot_token)
+        print("\nSESSION_STRING=" + client.session.save())
+
+
+asyncio.run(main())
diff --git a/make_userbot_session.py b/make_userbot_session.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd38bd6346b1e4765196ccfdb240017665f1cb97
--- /dev/null
+++ b/make_userbot_session.py
@@ -0,0 +1,28 @@
+"""Makes the USERBOT_SESSION text. Run it on YOUR OWN computer, never on the server:
+
+    pip install telethon
+    python make_userbot_session.py
+
+It asks for the phone number of the account, the login code Telegram sends to that account and, if the account has
+one, its two-step password. Then it prints  USERBOT_SESSION=...  - put that line into the bot's secrets.
+
+Use a separate Telegram account for this, not your main one: whoever has the session text can act as that account.
+"""
+import asyncio
+import os
+
+from telethon import TelegramClient
+from telethon.sessions import StringSession
+
+
+async def main() -> None:
+    api_id = int(os.getenv("API_ID") or input("API_ID (from my.telegram.org): ").strip())
+    api_hash = os.getenv("API_HASH") or input("API_HASH: ").strip()
+    async with TelegramClient(StringSession(), api_id, api_hash) as client:  # prompts for phone, code, password
+        me = await client.get_me()
+        print(f"\nLogged in as {me.first_name} (id {me.id}).")
+        print("\nUSERBOT_SESSION=" + client.session.save())
+        print("\nKeep this text secret. Telegram > Settings > Devices shows the session; end it there to cancel it.")
+
+
+asyncio.run(main())
diff --git a/requirements-dev.txt b/requirements-dev.txt
new file mode 100644
index 0000000000000000000000000000000000000000..71d56c1f4c36a9f76d4aa1b8ddb078c9aaa68b3e
--- /dev/null
+++ b/requirements-dev.txt
@@ -0,0 +1,4 @@
+-r requirements.txt
+pytest>=8
+pyflakes
+pyyaml
diff --git a/requirements.txt b/requirements.txt
index ce1f54e87ea5bd7ac886941573287b18941a2eb5..830ae8431fabe64ee1c08c1650aea5afc9aa640c 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,6 +1,5 @@
-panel
-jupyter
-transformers
-numpy
-torch
-aiohttp
\ No newline at end of file
+telethon>=1.45,<1.46
+SQLAlchemy[asyncio]>=2.0.30,<2.1
+asyncpg>=0.29
+aiosqlite>=0.20
+python-dotenv>=1.0
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tests/dbutil.py b/tests/dbutil.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c23dd7fde6917db788b59828a1bb3af80793106
--- /dev/null
+++ b/tests/dbutil.py
@@ -0,0 +1,16 @@
+"""Tests run on SQLite by default; set TEST_DATABASE_URL to run the very same tests on PostgreSQL."""
+import os
+
+from app.db import Base, Database
+
+
+def db_url_for(tmp_path, name="t.db"):
+    return os.getenv("TEST_DATABASE_URL") or f"sqlite+aiosqlite:///{tmp_path}/{name}"
+
+
+async def fresh_db(url: str) -> Database:
+    db = Database(url)
+    async with db.engine.begin() as conn:
+        await conn.run_sync(Base.metadata.drop_all)
+    await db.init()
+    return db
diff --git a/tests/fakes.py b/tests/fakes.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef4c130791a87cc277c488b8b79f410607761cc5
--- /dev/null
+++ b/tests/fakes.py
@@ -0,0 +1,938 @@
+"""Tiny in-memory stand-ins for Telethon, good enough to exercise the engine offline."""
+import datetime
+import itertools
+import os
+from types import SimpleNamespace
+
+from telethon import errors, functions, types
+from telethon.tl.custom import Message
+
+from app.tgutil import make_url_button, media_key
+
+
+def make_msg(i, text="", entities=None, markup=None, out=False, media=None, grouped_id=None, reply_to=None, pinned=False):
+    return Message(
+        id=i,
+        peer_id=types.PeerChannel(1),
+        date=datetime.datetime.now(datetime.timezone.utc),
+        message=text,
+        out=out,
+        entities=entities,
+        reply_markup=markup,
+        media=media,
+        grouped_id=grouped_id,
+        reply_to=types.MessageReplyHeader(reply_to_msg_id=reply_to) if reply_to else None,
+        pinned=True if pinned else None,
+    )
+
+
+def url_btn(text, url):
+    return make_url_button(text, url)
+
+
+def cb_btn(text, data):
+    return types.KeyboardButton(text=text, type=types.InlineButtonTypeCallback(data))
+
+
+def markup(*rows):
+    return types.ReplyInlineMarkup([types.KeyboardButtonRow(list(r)) for r in rows])
+
+
+class FakeClient:
+    def __init__(self, msgs, pts=None):
+        self.msgs = dict(msgs)
+        self.pts = pts
+        self.edits = []
+        self.fail = {}  # message id -> exception to raise on edit
+
+    async def __call__(self, req):
+        if isinstance(req, functions.channels.GetFullChannelRequest):
+            return SimpleNamespace(full_chat=SimpleNamespace(pts=self.pts))
+        if isinstance(req, functions.messages.EditMessageRequest):
+            if req.id in self.fail:
+                raise self.fail[req.id]
+            m = self.msgs[req.id]
+            self.edits.append(req)
+            if req.message is not None:
+                m.message = req.message
+                m.entities = list(req.entities or [])
+                m.reply_markup = req.reply_markup  # like Telegram: no markup sent -> keyboard removed
+            elif req.reply_markup is not None:
+                m.reply_markup = req.reply_markup
+            return None
+        raise NotImplementedError(type(req))
+
+    async def get_messages(self, peer, ids=None):
+        return [self.msgs.get(i) for i in ids]
+
+
+def rpc(name):
+    return getattr(errors, name)(request=None)
+
+
+# ======================================================================================================
+# A fake Telegram "channel": enough of the API for the repost / delete / buttons / userbot code, offline.
+# ======================================================================================================
+NOW = datetime.datetime.now(datetime.timezone.utc)
+USER_HASH = 424242  # the channel's access hash as the userbot account sees it (differs from the bot's)
+
+
+def photo_media(pid=11):
+    photo = types.Photo(pid, pid * 7, b"ref%d" % pid, NOW, [types.PhotoSize("x", 100, 100, 999)], 2)
+    return types.MessageMediaPhoto(photo=photo)
+
+
+def video_media(did=21, thumb=False):
+    """A video; `thumb`: Telegram shows a picture for it (its bytes: b"THUMB OF " unless the test sets `_media_data`)."""
+    thumbs = [types.PhotoStrippedSize("i", b"\x01\x28\x28"), types.PhotoSize("m", 320, 180, 1234)] if thumb else None
+    doc = types.Document(
+        did, did * 7, b"fr%d" % did, NOW, "video/mp4", 1000, 2, [types.DocumentAttributeVideo(5.0, 320, 240)], thumbs=thumbs
+    )
+    return types.MessageMediaDocument(document=doc)
+
+
+def as_the_userbot_holds_it(media):
+    """The same photo / file with the access data of ANOTHER account: its id is the same everywhere, its access_hash and
+    file_reference belong to one account (so one account's copy is refused when another presents it)."""
+    if isinstance(media, types.MessageMediaPhoto):
+        p = media.photo
+        return types.MessageMediaPhoto(
+            photo=types.Photo(p.id, p.access_hash + 1000, b"ub-" + p.file_reference, p.date, p.sizes, p.dc_id)
+        )
+    d = media.document
+    return types.MessageMediaDocument(
+        document=types.Document(
+            d.id, d.access_hash + 1000, b"ub-" + d.file_reference, d.date, d.mime_type, d.size, d.dc_id, d.attributes,
+            thumbs=d.thumbs,
+        )
+    )
+
+
+class FakeDM:
+    """The chat between the bot and the userbot account: what the bot put there and what the account holds of it."""
+
+    def __init__(self):
+        self.bot_user = types.User(id=9100, access_hash=31337, first_name="Post Bot", username="the_post_bot", bot=True)
+        self.userbot_id = None  # the userbot account (set when its FakeUserClient is made) ...
+        self.userbot_user = None  # ... and its types.User
+        self.msgs = []  # the chat as the userbot sees it, oldest first
+        self.sent = []  # (the bot's id of the message, its kwargs) for everything the bot sent there
+        self.bot_ids = {}  # the bot's id of a message -> the userbot's message
+        self.deleted = []  # the bot's ids of the messages it deleted
+        self.error = None  # raised when the bot sends there (the account never started the bot, or blocked it)
+        self.read_error = None  # raised when the userbot reads the chat
+        self.reference_error = None  # raised when the userbot edits a post with a file it holds (not with an upload)
+        self.late = 0  # the next N reads find nothing: the message has not reached the userbot yet
+        self.known = {}  # ("photo" | "doc", id) -> (access_hash, file_reference) the userbot account holds
+        self._ids = itertools.count(500)  # the userbot's message ids
+        self._bot_ids = itertools.count(1000)  # the bot's message ids
+
+
+def service_msg(i):
+    return types.MessageService(id=i, peer_id=types.PeerChannel(1), date=NOW, action=types.MessageActionPinMessage())
+
+
+def quote(offset, length, collapsed=None):
+    return types.MessageEntityBlockquote(offset, length, collapsed)
+
+
+def _bytes(obj):
+    return bytes(obj) if obj is not None else None
+
+
+def _empty_rights(r):
+    return not any(v for k, v in r.to_dict().items() if k != "_")
+
+
+class FakeChannelClient:
+    """Telegram's side of ONE channel (peer id 1) as seen by the bot, with switches for the odd things Telegram does."""
+
+    def __init__(self, msgs=None, *, username=None, cid=1, title="Test"):
+        self.cid = cid  # this simulation is the channel with this id; add_channel() puts more channels next to it
+        self.title = title
+        self.registry = {cid: self}
+        self.invite_hash = None  # a t.me/+hash invite link of this channel the bot "is in" (for CheckChatInvite)
+        self.msgs = dict(msgs or {})
+        self.username = username
+        self.requests = []  # every request received, in order
+        self.edits = []  # EditMessageRequests Telegram accepted
+        self.delete_requests = []  # the id lists of channels.deleteMessages calls
+        self._top = max(self.msgs, default=0)
+        self._pts = self._top  # the channel's event counter: new messages, edits, deletes and pins all move it
+        self._gid = 7000
+        self._media = {}
+        for m in self.msgs.values():
+            self._remember_media(m)
+        # --- switches
+        self.restrict_forwards = False  # "Restrict saving content" is on
+        self.hide_keyboard_on_create = 0  # the next N created posts show no keyboard until a real change (suspected bug)
+        self.forward_hides_keyboard = False  # a forwarded copy keeps its keyboard "hidden": edits to the same keyboard are no-ops
+        self.drop_all_markup = False  # Telegram never shows a keyboard (to test giving up)
+        self.undeletable = set()  # ids the BOT may not delete (like posts older than 48 hours)
+        self.delete_error = None  # raised by every delete request of the bot
+        self.fail = {}  # request class name -> exception to raise
+        self.rights = dict(admin=True, post=True, edit=True, delete=True, invite=False, add_admins=False)
+        self.participants_visible = True
+        self.known_users = {}  # user id -> types.User the bot has "met"
+        self.members = set()  # user ids (other than the bot) that are in the channel
+        self.admins = {}  # user id -> ChatAdminRights
+        self.invites = {}  # hash -> dict(limit, uses, revoked)
+        self.primary_invite = None  # the channel's own invite link
+        self.require_approval = False
+        self.users = {}  # user id -> types.User, for participant lists
+        self.cant_delete_at_all = set()  # ids nobody can delete (userbot included)
+        self.restriction = None  # text: Telegram restricts the whole channel (a copyright strike)
+        self.restrict_new = None  # f(new message) -> text or None: Telegram itself restricts a NEW post (a blocked file ...)
+        self.about = ""  # the channel's description
+        self.photo_id = None  # the channel's profile photo (its bytes are in _photo_data)
+        self._photo_data = {}  # photo id -> bytes; shared by all channels next to each other
+        self._media_data = {}  # ("photo" | "doc", id) -> bytes of a message's photo or file; shared as well
+        self._uploads = {}  # uploaded file id -> bytes; shared as well
+        self.user_edit_keeps_markup = False  # an edit by a user account leaves the keyboard alone (else it is dropped)
+        self.user_edit_frees_message = False  # after a user account edited it, the bot may edit the post again
+        self.user_edits = []  # the EditMessageRequests the userbot account made
+        self._counter = [9000]  # ids for photos and uploads; shared
+        self._dm = FakeDM()  # the chat between the bot and the userbot account; shared
+        self.pinned_order = []  # message ids in the order they were pinned
+        self._n_invites = 0
+
+    # ----------------------------------------------------------------------------------- helpers
+    def add_channel(self, other):
+        """Put another channel next to this one: requests that name it (by channel id) are answered by it."""
+        other.registry = self.registry
+        self.registry[other.cid] = other
+        self._media.update(other._media)
+        other._media = self._media  # a photo or file is known to the account, whichever channel it is sent to
+        self._photo_data.update(other._photo_data)
+        other._photo_data, other._uploads, other._counter = self._photo_data, self._uploads, self._counter
+        self._media_data.update(other._media_data)
+        other._media_data = self._media_data
+        other._dm = self._dm
+        return other
+
+    def set_photo(self, data: bytes) -> int:
+        """Give the channel a profile photo (what it looks like is the bytes)."""
+        self._counter[0] += 1
+        self.photo_id = self._counter[0]
+        self._photo_data[self.photo_id] = data
+        return self.photo_id
+
+    def photo_bytes(self):
+        return self._photo_data.get(self.photo_id) if self.photo_id else None
+
+    def _chat_photo(self):
+        if not self.photo_id:
+            return types.PhotoEmpty(0)
+        return types.Photo(self.photo_id, 1, b"ref", NOW, [types.PhotoSize("x", 100, 100, 999)], 2)
+
+    def media_bytes(self, media):
+        """What a photo / file of a message looks like (its bytes): set in `_media_data`, else made up from its id."""
+        if isinstance(media, types.MessageMediaPhoto) and media.photo:
+            key = ("photo", media.photo.id)
+        elif isinstance(media, types.MessageMediaDocument) and media.document:
+            key = ("doc", media.document.id)
+        else:
+            raise ValueError("this fake only has the bytes of a photo or a file")
+        return self._media_data.get(key, b"bytes of %s %d" % (key[0].encode(), key[1]))
+
+    async def download_media(self, media, file=None, thumb=None):
+        if thumb is not None:  # the thumbnail of a file: None when Telegram has none
+            doc = getattr(media, "document", None)
+            if not isinstance(doc, types.Document) or not doc.thumbs:
+                return None
+            data = self._media_data.get(("thumb", doc.id), b"THUMB OF %d" % doc.id)
+            if file is None or file is bytes:
+                return data
+            path = str(file) + f"photo_{doc.id}.jpg" if str(file).endswith(os.sep) else str(file)
+            with open(path, "wb") as f:
+                f.write(data)
+            return path
+        if isinstance(media, types.Photo) and media.id in self._photo_data:
+            return self._photo_data[media.id]
+        data = self.media_bytes(media)
+        if file is None or file is bytes:
+            return data
+        if isinstance(media, types.MessageMediaPhoto):
+            name = f"photo_{media.photo.id}.jpg"
+        else:  # a file keeps the name it was sent with
+            name = next(
+                (a.file_name for a in media.document.attributes if isinstance(a, types.DocumentAttributeFilename)),
+                f"file_{media.document.id}",
+            )
+        path = str(file) + name if str(file).endswith(os.sep) else str(file)
+        with open(path, "wb") as f:
+            f.write(data)
+        return path
+
+    async def upload_file(self, data, file_name=None):
+        self._counter[0] += 1
+        self._uploads[self._counter[0]] = bytes(data)
+        return types.InputFile(id=self._counter[0], parts=1, name=file_name or "file", md5_checksum="")
+
+    def _target(self, req):
+        """The channel a request is about (a forward is carried out by its destination)."""
+        peer = getattr(req, "to_peer", None) or getattr(req, "peer", None) or getattr(req, "channel", None)
+        cid = getattr(peer, "channel_id", None)
+        return self.registry.get(cid, self) if cid is not None else self
+
+    def _remember_media(self, m):
+        md = getattr(m, "media", None)
+        if isinstance(md, types.MessageMediaPhoto) and md.photo:
+            self._media[("photo", md.photo.id)] = md
+        elif isinstance(md, types.MessageMediaDocument) and md.document:
+            self._media[("doc", md.document.id)] = md
+
+    def _media_for(self, inp):
+        if isinstance(inp, types.InputMediaPhoto):
+            key = ("photo", inp.id.id)
+        elif isinstance(inp, types.InputMediaDocument):
+            key = ("doc", inp.id.id)
+        else:
+            raise rpc("MediaInvalidError")
+        if key not in self._media:
+            raise rpc("MediaEmptyError")
+        return self._media[key]
+
+    def _effective(self, m):
+        hidden = getattr(m, "_hidden", None)
+        return hidden if hidden is not None else m.reply_markup
+
+    def _set_markup(self, m, markup, *, hide=False):
+        if markup is not None and (hide or self.drop_all_markup):
+            m._hidden, m.reply_markup = markup, None
+        else:
+            m._hidden, m.reply_markup = None, markup
+
+    def _check_blocks(self, inp):
+        """What Telegram refuses in the blocks of an InputRichMessage (RICH_MESSAGE_BLOCK_INVALID), as far as it is known: a
+        map that holds a stored point (the blocks it hands out hold those; it wants an input point back), a block that its
+        layer doesn't know, a thinking block (the Bot API: drafts only) and a text mention of somebody the message carries
+        no access data for.
+        `refuse_blocks`: further block classes (names) a test wants refused."""
+        users = {getattr(u, "user_id", None) for u in inp.users or []}
+        refused = (types.PageBlockMap, types.PageBlockUnsupported, types.PageBlockThinking)
+        extra = set(getattr(self, "refuse_blocks", ()))
+
+        def walk(o):
+            if (
+                isinstance(o, refused)
+                or type(o).__name__ in extra
+                or (isinstance(o, types.TextMentionName) and o.user_id not in users)
+            ):
+                raise errors.BadRequestError(
+                    functions.messages.SendMessageRequest(peer=types.InputPeerSelf(), message=""),
+                    "RICH_MESSAGE_BLOCK_INVALID",
+                    400,
+                )
+            if isinstance(o, (list, tuple)):
+                for x in o:
+                    walk(x)
+            elif hasattr(o, "to_dict") and not isinstance(o, (str, bytes)):
+                for v in vars(o).values():
+                    walk(v)
+
+        walk(list(inp.blocks))
+
+    def _rich(self, inp):
+        """What Telegram makes of an InputRichMessage*: for HTML / Markdown the "parse" is one paragraph holding the source
+        (the same source always gives the same blocks); a message sent as blocks keeps them, with its pictures and files."""
+        if isinstance(inp, (types.InputRichMessageHTML, types.InputRichMessageMarkdown)):
+            src = inp.html if isinstance(inp, types.InputRichMessageHTML) else inp.markdown
+            if not src.strip():
+                raise rpc("MessageEmptyError")
+            kind = "html" if isinstance(inp, types.InputRichMessageHTML) else "markdown"
+            return types.RichMessage(
+                blocks=[types.PageBlockParagraph(types.TextPlain(f"[{kind}]{src}"))], photos=[], documents=[], rtl=inp.rtl
+            )
+        if isinstance(inp, types.InputRichMessage):
+            self._check_blocks(inp)
+            photos = [
+                types.Photo(p.id, p.access_hash, p.file_reference, NOW, [], 1) for p in inp.photos or []
+            ]
+            docs = [
+                types.Document(d.id, d.access_hash, d.file_reference, NOW, "video/mp4", 1, 1, []) for d in inp.documents or []
+            ]
+            return types.RichMessage(blocks=list(inp.blocks), photos=photos, documents=docs, rtl=inp.rtl)
+        raise rpc("MediaInvalidError")
+
+    def _new(self, text, entities, markup, media=None, gid=None, invert=None, hide=False, reply_to=None, rich=None):
+        self._top += 1
+        self._pts += 1
+        m = Message(
+            id=self._top,
+            peer_id=types.PeerChannel(self.cid),
+            date=NOW,
+            message=text,
+            out=True,
+            entities=list(entities) if entities else None,
+            media=media,
+            grouped_id=gid,
+            invert_media=invert,
+            reply_to=types.MessageReplyHeader(reply_to_msg_id=reply_to) if reply_to else None,
+            rich_message=rich,
+        )
+        if self.hide_keyboard_on_create > 0 and markup is not None:
+            hide = True
+            self.hide_keyboard_on_create -= 1
+        self._set_markup(m, markup, hide=hide)
+        if self.restrict_new is not None:
+            why = self.restrict_new(m)
+            if why:
+                m.restriction_reason = [types.RestrictionReason(platform="all", reason="copyright", text=why)]
+        self.msgs[m.id] = m
+        self._remember_media(m)
+        return m
+
+    def _updates(self, msgs):
+        return types.Updates(
+            updates=[types.UpdateNewChannelMessage(message=m, pts=m.id, pts_count=1) for m in msgs],
+            users=[],
+            chats=[],
+            date=NOW,
+            seq=0,
+        )
+
+    def _channel_obj(self):
+        extra = {}
+        if self.restriction:
+            extra = dict(
+                restricted=True,
+                restriction_reason=[types.RestrictionReason(platform="all", reason="copyright", text=self.restriction)],
+            )
+        return types.Channel(
+            id=self.cid, title=self.title, photo=types.ChatPhotoEmpty(), date=NOW, access_hash=USER_HASH,
+            username=self.username, broadcast=True, **extra,
+        )
+
+    # --------------------------------------------------------------------------------- dispatcher
+    async def __call__(self, req):
+        target = self._target(req)
+        if target is not self:
+            return await target(req)
+        bytes(req)  # every request the bot builds must serialise
+        self.requests.append(req)
+        name = type(req).__name__
+        err = self.fail.get(name)
+        if err is not None:
+            raise err
+        handler = getattr(self, "_do_" + name, None)
+        if handler is None:
+            raise NotImplementedError(name)
+        return handler(req)
+
+    async def get_messages(self, peer, ids=None):
+        chan = self.registry.get(getattr(peer, "channel_id", None), self)
+        err = chan.fail.get("GetMessagesRequest")  # reading a channel the bot may not read (a real client sends this request)
+        if err is not None:
+            raise err
+        return [chan.msgs.get(i) for i in ids]
+
+    async def get_input_entity(self, peer):
+        if isinstance(peer, int) and peer in self.known_users:
+            u = self.known_users[peer]
+            return types.InputPeerUser(u.id, u.access_hash)
+        raise ValueError(f"Could not find the input entity for {peer!r}")
+
+    # ------------------------------------------------------ the bot and its chat with the userbot account
+    async def get_me(self):
+        return self._dm.bot_user
+
+    def _is_dm(self, peer):
+        """Is `peer` the userbot account (the only user this simulation sends files to)?"""
+        return isinstance(peer, types.InputPeerUser) and peer.user_id == self._dm.userbot_id
+
+    async def send_file(self, peer, file, **kw):
+        """The bot sends a photo / file to the userbot account: Telegram reuses the file, the account gets its own copy."""
+        dm = self._dm
+        if not self._is_dm(peer):
+            raise NotImplementedError("this fake only sends files to the userbot account")
+        if dm.error is not None:
+            raise dm.error
+        if peer.access_hash != dm.userbot_user.access_hash:  # the bot has to know the account (its access hash)
+            raise rpc("PeerIdInvalidError")
+        key = media_key(file)
+        if key is None:
+            raise rpc("MediaInvalidError")
+        mine = as_the_userbot_holds_it(file)
+        inner = mine.photo if key[0] == "photo" else mine.document
+        dm.known[key] = (inner.access_hash, inner.file_reference)
+        self._media[key] = file  # the file as the bot holds it: what the channel shows after an edit by reference
+        msg = Message(id=next(dm._ids), peer_id=types.PeerUser(dm.bot_user.id), date=NOW, message="", out=False, media=mine)
+        dm.msgs.append(msg)
+        bot_id = next(dm._bot_ids)
+        dm.bot_ids[bot_id] = msg
+        dm.sent.append((bot_id, kw))
+        return SimpleNamespace(id=bot_id)
+
+    async def delete_messages(self, peer, ids, **kw):
+        dm = self._dm
+        if not self._is_dm(peer):
+            raise NotImplementedError("this fake only deletes in the chat with the userbot account")
+        for i in ids:
+            dm.deleted.append(i)
+            msg = dm.bot_ids.pop(i, None)
+            dm.msgs = [m for m in dm.msgs if m is not msg]  # (identity: Telethon's Message has no usable ==)
+        return [SimpleNamespace(pts_count=len(ids))]
+
+    # ------------------------------------------------------------------------- message requests
+    def _do_GetMessagesRequest(self, req):
+        """channels.getMessages as Telegram answers it: the posts as they are now, MessageEmpty for missing ones.
+        (Used when a real Telethon client sits in front of this simulation; get_messages() above serves the plain fakes.)"""
+        out = []
+        for ref in req.id:
+            m = self.msgs.get(ref.id)
+            if m is None:
+                out.append(types.MessageEmpty(id=ref.id, peer_id=types.PeerChannel(self.cid)))
+            elif isinstance(m, (types.MessageService, types.MessageEmpty)):
+                out.append(m)
+            else:
+                out.append(
+                    types.Message(
+                        id=m.id, peer_id=m.peer_id, date=m.date, message=m.message, out=m.out, entities=m.entities,
+                        reply_markup=m.reply_markup, media=m.media, grouped_id=m.grouped_id,
+                        invert_media=getattr(m, "invert_media", None), reply_to=m.reply_to, pinned=m.pinned,
+                        restriction_reason=getattr(m, "restriction_reason", None),
+                    )
+                )
+        return types.messages.ChannelMessages(
+            pts=self._top, count=len(out), messages=out, topics=[], chats=[self._channel_obj()], users=[]
+        )
+
+    def _do_ForwardMessagesRequest(self, req):
+        origin = self.registry.get(getattr(req.from_peer, "channel_id", None), self)
+        if origin.restrict_forwards:  # "Restrict saving content" is a setting of the channel the posts come from
+            raise rpc("ChatForwardsRestrictedError")
+        out, gids = [], {}
+        for i in req.id:
+            src = origin.msgs.get(i)
+            if src is None:
+                continue
+            gid = gids.setdefault(src.grouped_id, self._next_gid()) if src.grouped_id else None
+            out.append(
+                self._new(
+                    src.message, src.entities, src.reply_markup, src.media, gid, getattr(src, "invert_media", None),
+                    hide=self.forward_hides_keyboard, rich=getattr(src, "rich_message", None),
+                )
+            )
+        if not out:
+            raise rpc("MessageIdInvalidError")
+        return self._updates(out)
+
+    def _next_gid(self):
+        self._gid += 1
+        return self._gid
+
+    @staticmethod
+    def _reply_id(req):
+        r = getattr(req, "reply_to", None)
+        return r.reply_to_msg_id if r is not None else None
+
+    def _check_reply(self, req):
+        rid = self._reply_id(req)
+        if rid is not None and rid not in self.msgs:
+            raise rpc("MessageIdInvalidError")  # REPLY_MESSAGE_ID_INVALID
+        return rid
+
+    def _do_SendMessageRequest(self, req):
+        rid = self._check_reply(req)
+        if req.rich_message is not None:
+            rich = self._rich(req.rich_message)
+            m = self._new("", None, req.reply_markup, None, None, None, reply_to=rid, rich=rich)
+            m.rich_input = req.rich_message  # what the bot asked for (the tests look at it)
+            return self._updates([m])
+        return self._updates([self._new(req.message, req.entities, req.reply_markup, None, None, req.invert_media, reply_to=rid)])
+
+    def _do_SendMediaRequest(self, req):
+        media = self._media_for(req.media)
+        rid = self._check_reply(req)
+        return self._updates([self._new(req.message, req.entities, req.reply_markup, media, None, req.invert_media, reply_to=rid)])
+
+    def _do_SendMultiMediaRequest(self, req):
+        gid = self._next_gid()
+        rid = self._check_reply(req)
+        out = [
+            self._new(s.message, s.entities, None, self._media_for(s.media), gid, req.invert_media, reply_to=rid)
+            for s in req.multi_media
+        ]
+        return self._updates(out)
+
+    def _do_UpdatePinnedMessageRequest(self, req):
+        """Pinning in a channel needs the "Edit messages of others" right; Telegram adds a "pinned" notice to the channel."""
+        if not self.rights.get("edit"):
+            raise rpc("ChatAdminRequiredError")
+        m = self.msgs.get(req.id)
+        if m is None or isinstance(m, types.MessageService):
+            raise rpc("MessageIdInvalidError")
+        if req.unpin:
+            m.pinned = None
+            return self._updates([])
+        if m.pinned:
+            raise rpc("MessageNotModifiedError")
+        m.pinned = True
+        self.pinned_order.append(req.id)
+        self._top += 1
+        self._pts += 2
+        note = types.MessageService(
+            id=self._top, peer_id=types.PeerChannel(self.cid), date=NOW, action=types.MessageActionPinMessage(),
+            reply_to=types.MessageReplyHeader(reply_to_msg_id=req.id),
+        )
+        self.msgs[note.id] = note
+        return self._updates([note])
+
+    def _do_EditMessageRequest(self, req):
+        m = self.msgs.get(req.id)
+        if m is None:
+            raise rpc("MessageIdInvalidError")
+        if not getattr(m, "out", False) and not self.rights.get("edit"):  # somebody else's post needs that right
+            raise rpc("MessageAuthorRequiredError")
+        if getattr(m, "via_other_bot", False):  # buttons or a post made through another bot: only that bot may edit
+            raise rpc("MessageIdInvalidError")
+        if req.rich_message is not None:  # the post becomes this rich message; no keyboard sent = keyboard removed
+            rich = self._rich(req.rich_message)
+            if (
+                m.rich_message is not None
+                and bytes(m.rich_message) == bytes(rich)
+                and _bytes(req.reply_markup) == _bytes(self._effective(m))
+            ):
+                raise rpc("MessageNotModifiedError")
+            m.message, m.entities, m.rich_message, m.rich_input = "", None, rich, req.rich_message
+            self._set_markup(m, req.reply_markup)
+            self.edits.append(req)
+            self._pts += 1
+            return self._updates([])
+        if req.message is None:  # markup-only edit
+            text, ents = m.message, list(m.entities or [])
+            markup = req.reply_markup if req.reply_markup is not None else self._effective(m)
+        else:
+            text, ents, markup = req.message, list(req.entities or []), req.reply_markup  # None = keyboard removed
+        if (
+            text == m.message
+            and [_bytes(e) for e in ents] == [_bytes(e) for e in (m.entities or [])]
+            and _bytes(markup) == _bytes(self._effective(m))
+        ):
+            raise rpc("MessageNotModifiedError")
+        m.message, m.entities = text, (ents or None)
+        if req.message is not None:
+            m.rich_message = None
+        self._set_markup(m, markup)
+        self.edits.append(req)
+        self._pts += 1
+        return self._updates([])
+
+    def _do_GetRichMessageRequest(self, req):
+        """messages.getRichMessage: the whole rich message of a post (the tests may put a longer one in `full_rich`)."""
+        full = getattr(self, "full_rich", {}).get(req.id)
+        m = self.msgs.get(req.id)
+        if full is None and (m is None or m.rich_message is None):
+            raise rpc("MessageIdInvalidError")
+        return full if full is not None else m.rich_message
+
+    def _do_DeleteMessagesRequest(self, req):
+        ids = list(req.id)
+        self.delete_requests.append(ids)
+        if self.delete_error is not None:
+            raise self.delete_error
+        n = 0
+        for i in ids:
+            if i in self.undeletable or i in self.cant_delete_at_all or i not in self.msgs:
+                continue
+            del self.msgs[i]
+            n += 1
+        self._pts += n
+        return types.messages.AffectedMessages(pts=self._pts, pts_count=n)
+
+    # ------------------------------------------------------------------------ channel / rights
+    def _do_GetFullChannelRequest(self, req):
+        inv = types.ChatInviteExported(link=self.primary_invite, admin_id=1, date=NOW) if self.primary_invite else None
+        return SimpleNamespace(
+            full_chat=SimpleNamespace(
+                pts=max(self._pts, self._top), exported_invite=inv, about=self.about, chat_photo=self._chat_photo()
+            ),
+            chats=[self._channel_obj()],
+        )
+
+    def _notice(self, action):
+        """The service message Telegram puts into a channel when its name or photo changes."""
+        self._top += 1
+        self._pts += 1
+        note = types.MessageService(id=self._top, peer_id=types.PeerChannel(self.cid), date=NOW, action=action)
+        self.msgs[note.id] = note
+        return note
+
+    def _need_info_right(self):
+        if not self.rights.get("change_info", True):
+            raise rpc("ChatAdminRequiredError")
+
+    def _do_EditTitleRequest(self, req):
+        self._need_info_right()
+        if req.title == self.title:
+            raise rpc("ChatNotModifiedError")
+        self.title = req.title
+        return self._updates([self._notice(types.MessageActionChatEditTitle(req.title))])
+
+    def _do_EditChatAboutRequest(self, req):
+        self._need_info_right()
+        if req.about == self.about:
+            raise rpc("ChatAboutNotModifiedError")
+        self.about = req.about
+        return True
+
+    def _do_EditPhotoRequest(self, req):
+        self._need_info_right()
+        data = self._uploads[req.photo.file.id]
+        self.set_photo(data)
+        return self._updates([self._notice(types.MessageActionChatEditPhoto(self._chat_photo()))])
+
+    def _do_GetParticipantRequest(self, req):
+        r = self.rights
+        if r is None:
+            raise rpc("UserNotParticipantError")
+        if not r.get("admin", True):
+            return SimpleNamespace(participant=types.ChannelParticipant(user_id=1, date=NOW))
+        rights = types.ChatAdminRights(
+            post_messages=r.get("post"), edit_messages=r.get("edit"), delete_messages=r.get("delete"),
+            invite_users=r.get("invite"), add_admins=r.get("add_admins"), change_info=r.get("change_info", True),
+        )
+        return SimpleNamespace(participant=types.ChannelParticipantAdmin(user_id=1, promoted_by=1, date=NOW, admin_rights=rights))
+
+    def _do_ExportChatInviteRequest(self, req):
+        if not self.rights.get("invite"):
+            raise rpc("ChatAdminRequiredError")
+        self._n_invites += 1
+        h = f"AbCdEfGh{self._n_invites:04d}"
+        self.invites[h] = dict(limit=req.usage_limit, uses=0, revoked=False, title=req.title, expire=req.expire_date)
+        return types.ChatInviteExported(
+            link=f"https://t.me/+{h}", admin_id=1, date=NOW, usage_limit=req.usage_limit, expire_date=req.expire_date, title=req.title
+        )
+
+    def _do_EditExportedChatInviteRequest(self, req):
+        h = req.link.rsplit("+", 1)[-1]
+        if h in self.invites and req.revoked:
+            self.invites[h]["revoked"] = True
+        return SimpleNamespace(invite=None)
+
+    def _do_EditAdminRequest(self, req):
+        if not self.rights.get("add_admins"):
+            raise rpc("ChatAdminRequiredError")
+        uid = req.user_id.user_id
+        known = self.users.get(uid)
+        if known is None or req.user_id.access_hash != known.access_hash:
+            raise rpc("UserIdInvalidError")
+        if _empty_rights(req.admin_rights):
+            self.admins.pop(uid, None)
+        else:
+            self.admins[uid] = req.admin_rights
+        return self._updates([])
+
+    def _do_GetParticipantsRequest(self, req):
+        if not self.participants_visible:
+            raise rpc("ChatAdminRequiredError")
+        users = [self.users[u] for u in sorted(self.members) if u in self.users]
+        if isinstance(req.filter, types.ChannelParticipantsSearch):
+            q = req.filter.q.lower()
+            users = [u for u in users if q in (u.username or "").lower() or q in (u.first_name or "").lower()]
+        return types.channels.ChannelParticipants(count=len(users), participants=[], chats=[], users=users)
+
+
+class FakeUserClient:
+    """The userbot account's own Telegram connection, sharing one FakeChannelClient with the bot."""
+
+    def __init__(self, chan, *, user_id=777, authorized=True, bot=False, username="helper_acct", first_name="Helper"):
+        self.chan = chan
+        self.me = types.User(id=user_id, access_hash=555, first_name=first_name, username=username, bot=bot or None)
+        chan.users[user_id] = self.me
+        chan._dm.userbot_id, chan._dm.userbot_user = user_id, self.me
+        self.authorized = authorized
+        self.connected = False
+        self.known_channel = False
+        self.requests = []
+        self.deleted = []
+        self.uploads = []  # (path, file name, size) of everything uploaded
+
+    async def connect(self):
+        self.connected = True
+
+    async def disconnect(self):
+        self.connected = False
+
+    async def is_user_authorized(self):
+        return self.authorized
+
+    async def get_me(self):
+        return self.me
+
+    async def get_input_entity(self, peer):
+        if isinstance(peer, types.PeerChannel) and self.known_channel:
+            return types.InputPeerChannel(peer.channel_id, USER_HASH)
+        if isinstance(peer, str) and self.chan.username and peer.lstrip("@").lower() == self.chan.username.lower():
+            return types.InputPeerChannel(1, USER_HASH)
+        bot = self.chan._dm.bot_user
+        if isinstance(peer, str) and peer.lstrip("@").lower() == bot.username.lower():
+            return types.InputPeerUser(bot.id, bot.access_hash)
+        raise ValueError(f"Could not find the input entity for {peer!r}")
+
+    async def get_messages(self, peer, limit=None, **kw):
+        """The newest messages of this account's chat with the bot (newest first, like Telethon)."""
+        dm, bot = self.chan._dm, self.chan._dm.bot_user
+        err = self.chan.fail.get("user:GetHistoryRequest")
+        if err is not None:
+            raise err
+        if not (isinstance(peer, types.InputPeerUser) and peer.user_id == bot.id and peer.access_hash == bot.access_hash):
+            raise ValueError(f"Could not find the input entity for {peer!r}")
+        if dm.read_error is not None:
+            raise dm.read_error
+        if dm.late > 0:
+            dm.late -= 1
+            return []
+        return list(reversed(dm.msgs))[: limit or 1]
+
+    async def iter_dialogs(self):
+        if self.known_channel and self.me.id in self.chan.members:
+            yield SimpleNamespace(entity=self.chan._channel_obj())
+
+    def _join(self):
+        self.chan.members.add(self.me.id)
+        self.known_channel = True
+
+    async def upload_file(self, path, file_name=None):
+        with open(path, "rb") as f:
+            data = f.read()
+        chan = self.chan
+        chan._counter[0] += 1
+        chan._uploads[chan._counter[0]] = data
+        self.uploads.append((path, file_name, len(data)))
+        return types.InputFile(id=chan._counter[0], parts=1, name=file_name or os.path.basename(path), md5_checksum="")
+
+    def _uploaded_media(self, inp):
+        """The photo / file Telegram makes out of an upload: new ids, the bytes that were sent."""
+        chan = self.chan
+        data = chan._uploads[inp.file.id]
+        chan._counter[0] += 1
+        n = chan._counter[0]
+        if isinstance(inp, types.InputMediaUploadedPhoto):
+            chan._media_data[("photo", n)] = data
+            photo = types.Photo(n, n * 7, b"up%d" % n, NOW, [types.PhotoSize("x", 100, 100, len(data))], 2)
+            return types.MessageMediaPhoto(photo=photo)
+        if isinstance(inp, types.InputMediaUploadedDocument):
+            chan._media_data[("doc", n)] = data
+            thumbs = None
+            if inp.thumb is not None:  # an uploaded picture becomes the file's thumbnail
+                chan._media_data[("thumb", n)] = chan._uploads[inp.thumb.id]
+                thumbs = [types.PhotoSize("m", 320, 180, len(chan._uploads[inp.thumb.id]))]
+            doc = types.Document(n, n * 7, b"up%d" % n, NOW, inp.mime_type, len(data), 2, list(inp.attributes), thumbs=thumbs)
+            return types.MessageMediaDocument(document=doc)
+        raise rpc("MediaInvalidError")
+
+    def _by_reference(self, inp):
+        """An InputMediaPhoto / InputMediaDocument: only a photo / file this account holds, with ITS OWN access data."""
+        chan = self.chan
+        if chan._dm.reference_error is not None:
+            raise chan._dm.reference_error
+        key = ("photo", inp.id.id) if isinstance(inp, types.InputMediaPhoto) else ("doc", inp.id.id)
+        mine = chan._dm.known.get(key)
+        if mine is None:
+            raise rpc("MediaEmptyError")  # this account has never seen that file
+        if (inp.id.access_hash, inp.id.file_reference) != mine:
+            raise rpc("FileReferenceExpiredError")  # somebody else's access data
+        return chan._media[key]  # the file as the channel shows it (as the bot sees it)
+
+    def _edit(self, req):
+        """messages.editMessage by a user account: it needs the "Edit messages of others" right and can't set a keyboard."""
+        chan, uid = self.chan, self.me.id
+        if uid not in chan.members:
+            raise rpc("ChannelPrivateError")
+        admin = chan.admins.get(uid)
+        if admin is None or not admin.edit_messages:
+            raise rpc("ChatAdminRequiredError")
+        m = chan.msgs.get(req.id)
+        if m is None:
+            raise rpc("MessageIdInvalidError")
+        if req.media is None:
+            media = None
+        elif isinstance(req.media, (types.InputMediaPhoto, types.InputMediaDocument)):
+            media = self._by_reference(req.media)
+        else:
+            media = self._uploaded_media(req.media)
+        if req.rich_message is not None:
+            rich = chan._rich(req.rich_message)
+            if m.rich_message is not None and bytes(m.rich_message) == bytes(rich):
+                raise rpc("MessageNotModifiedError")
+            m.message, m.entities, m.rich_message, m.rich_input = "", None, rich, req.rich_message
+            if not chan.user_edit_keeps_markup:
+                chan._set_markup(m, None)
+            if chan.user_edit_frees_message:
+                m.via_other_bot = False
+            chan.user_edits.append(req)
+            chan._pts += 1
+            return chan._updates([])
+        text = m.message if req.message is None else req.message
+        ents = list(m.entities or []) if req.message is None else list(req.entities or [])
+        if media is None and text == m.message and [_bytes(e) for e in ents] == [_bytes(e) for e in (m.entities or [])]:
+            raise rpc("MessageNotModifiedError")
+        m.message, m.entities = text, (ents or None)
+        if media is not None:
+            m.media = media
+            chan._remember_media(m)
+        if not chan.user_edit_keeps_markup:
+            chan._set_markup(m, None)  # no keyboard sent: Telegram drops it
+        if chan.user_edit_frees_message:
+            m.via_other_bot = False
+        chan.user_edits.append(req)
+        chan._pts += 1
+        return chan._updates([])
+
+    async def __call__(self, req):
+        bytes(req)
+        self.requests.append(req)
+        name = type(req).__name__
+        chan = self.chan
+        err = chan.fail.get("user:" + name)
+        if err is not None:
+            raise err
+        uid = self.me.id
+        if name == "ImportChatInviteRequest":
+            inv = chan.invites.get(req.hash)
+            if inv is None:
+                raise rpc("InviteHashInvalidError")
+            if inv["revoked"] or (inv["limit"] and inv["uses"] >= inv["limit"]):
+                raise rpc("InviteHashExpiredError")
+            if uid in chan.members:
+                raise rpc("UserAlreadyParticipantError")
+            if chan.require_approval:
+                raise rpc("InviteRequestSentError")
+            inv["uses"] += 1
+            self._join()
+            return types.Updates(updates=[], users=[], chats=[chan._channel_obj()], date=NOW, seq=0)
+        if name == "CheckChatInviteRequest":
+            if uid in chan.members:
+                return types.ChatInviteAlready(chat=chan._channel_obj())
+            return types.ChatInvite(title="Test", photo=types.PhotoEmpty(0), participants_count=1, color=0)
+        if name == "JoinChannelRequest":
+            if uid in chan.members:
+                raise rpc("UserAlreadyParticipantError")
+            self._join()
+            return types.Updates(updates=[], users=[], chats=[chan._channel_obj()], date=NOW, seq=0)
+        if name == "GetParticipantRequest":
+            if uid not in chan.members:
+                raise rpc("UserNotParticipantError")
+            if uid in chan.admins:
+                return SimpleNamespace(
+                    participant=types.ChannelParticipantAdmin(user_id=uid, promoted_by=1, date=NOW, admin_rights=chan.admins[uid])
+                )
+            return SimpleNamespace(participant=types.ChannelParticipant(user_id=uid, date=NOW))
+        if name == "EditMessageRequest":
+            return self._edit(req)
+        if name == "DeleteMessagesRequest":
+            ids = list(req.id)
+            self.deleted.append(ids)
+            adm = chan.admins.get(uid)
+            if adm is None or not adm.delete_messages:
+                raise rpc("ChatAdminRequiredError")
+            n = 0
+            for i in ids:
+                if i in chan.msgs and i not in chan.cant_delete_at_all:
+                    del chan.msgs[i]
+                    n += 1
+            return types.messages.AffectedMessages(pts=chan._top, pts_count=n)
+        raise NotImplementedError(name)
+
diff --git a/tests/harness.py b/tests/harness.py
new file mode 100644
index 0000000000000000000000000000000000000000..33db6bb1a3bb1b2bf4bd23a75fa63b4311288afd
--- /dev/null
+++ b/tests/harness.py
@@ -0,0 +1,250 @@
+"""Drive the real handlers with fake events and a fake Telegram client (no network)."""
+import itertools
+import re
+from types import SimpleNamespace
+
+from telethon import events, functions, types
+
+from app.common import Ctx
+from app.config import Config
+from app.db import Database
+
+from bot import register_all
+
+from .dbutil import db_url_for
+from .fakes import FakeChannelClient, rpc
+
+
+class FakeSent:
+    """A message the bot sent to the user (so `.edit()` works on it)."""
+
+    def __init__(self, out, text, buttons):
+        self.out, self.text, self.buttons = out, text, buttons
+
+    async def edit(self, text=None, buttons=None, **kw):
+        if text is not None:
+            self.text = text
+        self.buttons = buttons
+        self.out.log.append(("edit", self.text, buttons))
+
+
+class FakeEvent:
+    def __init__(self, uid, out, text="", data=None, message=None, reply=None):
+        self.sender_id, self.out = uid, out
+        self.is_private = True
+        self.is_channel = False
+        self.is_group = False
+        self.raw_text = text
+        self.text = text
+        self.message = message or SimpleNamespace(
+            raw_text=text, entities=[], media=None, grouped_id=None, forward=None
+        )
+        self.pattern_match = None
+        self._reply = reply
+        self._is_callback = data is not None
+        if data is not None:
+            self.data = data.encode()
+
+    async def respond(self, text=None, buttons=None, file=None, **kw):
+        self.out.log.append(("say", text, buttons))
+        return FakeSent(self.out, text, buttons)
+
+    async def edit(self, text=None, buttons=None, **kw):
+        self.out.log.append(("edit", text, buttons))
+
+    async def answer(self, *a, **kw):
+        return None
+
+    async def get_input_chat(self):
+        return types.InputPeerUser(self.sender_id, 0)
+
+    async def get_reply_message(self):
+        return self._reply
+
+
+class Outbox:
+    def __init__(self):
+        self.log = []
+
+    @property
+    def last_text(self):
+        return self.log[-1][1] if self.log else None
+
+    def last_buttons(self):
+        b = self.log[-1][2]
+        return [[getattr(x, "text", None) for x in row] for row in (b or [])]
+
+    def _data_of(self, btn):
+        t = btn.type if hasattr(btn, "type") else btn
+        return t.data.decode()
+
+    def callback_data(self, label_part):
+        """Data of the first inline button (in the last message) whose label contains `label_part`.
+
+        A channel chooser writes the names in the message and puts only numbers on its buttons: when no button has
+        the label, `label_part` is looked for in the numbered list and the button with that number is taken - what a
+        person does when they find the channel in the list and tap its number."""
+        for row in self.log[-1][2] or []:
+            for btn in row:
+                if label_part in btn.text:
+                    return self._data_of(btn)
+        listed = re.search(rf"(?m)^(\d+)\. [^\n]*{re.escape(label_part)}", norm(self.last_text))
+        if listed:
+            for row in self.log[-1][2] or []:
+                for btn in row:
+                    if btn.text == listed.group(1):
+                        return self._data_of(btn)
+        raise AssertionError(f"no button {label_part!r} in {self.last_buttons()}")
+
+    def callback_exact(self, label):
+        """Data of the button whose label is exactly `label` (the number buttons of a chooser, ◀ ▶ ...)."""
+        for row in self.log[-1][2] or []:
+            for btn in row:
+                if btn.text == label:
+                    return self._data_of(btn)
+        raise AssertionError(f"no button {label!r} in {self.last_buttons()}")
+
+
+class FakeTG(FakeChannelClient):
+    """The bot's Telegram connection: a simulated channel plus a log of what the bot sent to the user."""
+
+    def __init__(self):
+        super().__init__()
+        self.handlers = []
+        self.sent = []
+        self.edits = []
+        self.deleted = []
+        self.ids = itertools.count(100)
+        self.dm_rich_ids = []  # ids of the rich messages the bot sent to a person (previews and checks)
+        self.parse_mode = "html"
+        self.rights = dict(admin=True, post=True, edit=True, delete=True, invite=False, add_admins=False)
+
+    def on(self, builder):
+        def deco(fn):
+            self.handlers.append((builder, fn))
+            return fn
+
+        return deco
+
+    async def send_message(self, peer, message="", **kw):
+        m = SimpleNamespace(id=next(self.ids))
+        self.sent.append(("text", peer, message, kw))
+        return m
+
+    async def send_file(self, peer, file, **kw):
+        if self._is_dm(peer):  # to the userbot account: the chat simulation
+            return await super().send_file(peer, file, **kw)
+        m = SimpleNamespace(id=next(self.ids))
+        self.sent.append(("file", peer, file, kw))
+        return m
+
+    async def edit_message(self, peer, message, **kw):
+        self.edits.append(("edit_message", message, kw))
+        err = self.fail.get("edit_message")  # Telegram refuses the bot's high-level edit (text / caption / new media)
+        if err is not None:
+            raise err
+        chan = self.registry.get(getattr(peer, "channel_id", None), self)
+        m = chan.msgs.get(message)
+        if m is not None and getattr(m, "via_other_bot", False):  # its keyboard belongs to another bot: only that bot may edit
+            raise rpc("MessageIdInvalidError")
+
+    async def delete_messages(self, peer, ids, **kw):
+        if self._is_dm(peer):
+            return await super().delete_messages(peer, ids, **kw)
+        self.deleted.append(list(ids))
+        return [SimpleNamespace(pts_count=len(ids))]
+
+    async def get_entity(self, what):
+        """Public channels by @username, or any channel by PeerChannel - the ones put next to this one."""
+        for chan in self.registry.values():
+            if isinstance(what, str) and chan.username and chan.username.lower() == what.lstrip("@").lower():
+                return chan._channel_obj()
+            if isinstance(what, types.PeerChannel) and what.channel_id == chan.cid:
+                return chan._channel_obj()
+        raise ValueError(f"Cannot find any entity corresponding to {what!r}")
+
+    async def __call__(self, req):
+        if isinstance(req, functions.messages.CheckChatInviteRequest):
+            for chan in self.registry.values():
+                if chan.invite_hash == req.hash:
+                    return types.ChatInviteAlready(chat=chan._channel_obj())
+            raise ValueError("INVITE_HASH_INVALID")
+        target = self._target(req)
+        if target is not self:
+            return await target(req)
+        if isinstance(req, functions.messages.EditMessageRequest):
+            self.edits.append(("raw", req.id, req))
+            err = self.fail.get("EditMessageRequest")
+            if err is not None:
+                raise err
+            if req.id not in self.msgs:  # a post the simulation doesn't hold: just note the edit
+                return None
+        if isinstance(req, functions.channels.DeleteMessagesRequest):
+            self.deleted.append(list(req.id))
+        if isinstance(req, functions.messages.SendMessageRequest) and req.rich_message is not None:
+            self.sent.append(("rich", req.peer, req.rich_message, {"reply_markup": req.reply_markup, "silent": req.silent}))
+            if isinstance(req.peer, types.InputPeerUser):  # a chat with a person (the preview): nothing lands in a channel
+                if self.fail.get("SendMessageRequest") is not None:
+                    raise self.fail["SendMessageRequest"]
+                bytes(req)  # it must serialise
+                self._rich(req.rich_message)  # Telegram has to be able to make blocks of it
+                mid = next(self.ids)
+                self.dm_rich_ids.append(mid)
+                return types.UpdateShortSentMessage(id=mid, pts=0, pts_count=0, date=None, out=True)
+        return await super().__call__(req)
+
+
+class App:
+    def __init__(self, tmp_path, owner=1, **cfg_overrides):
+        base = dict(api_id=1, api_hash="x", bot_token="1:x", owners=frozenset({owner}), admins=frozenset(),
+                    database_url=db_url_for(tmp_path, "h.db"), db_pool="null", session_path="x", session_string="",
+                    edit_delay=0.3, replace_typed_links=True, port=0, log_level="INFO")
+        base.update(cfg_overrides)
+        cfg = Config(**base)
+        self.tg = FakeTG()
+        self.db = Database(cfg.database_url)
+        self.ctx = Ctx(cfg=cfg, db=self.db, client=self.tg)
+        self.uid = owner
+        self.out = Outbox()
+
+    async def start(self):
+        from app.db import Base
+
+        async with self.db.engine.begin() as conn:
+            await conn.run_sync(Base.metadata.drop_all)
+        await self.db.init()
+        register_all(self.ctx)
+
+    async def text(self, s, message=None, reply=None):
+        ev = FakeEvent(self.uid, self.out, s, message=message, reply=reply)
+        for builder, cb in self.tg.handlers:
+            if not isinstance(builder, events.NewMessage):
+                continue
+            if builder.pattern:
+                m = builder.pattern(s)
+                if not m:
+                    continue
+                ev.pattern_match = m
+            if builder.func and not builder.func(ev):
+                continue
+            await cb(ev)
+        return ev
+
+    async def raw(self, update):
+        """Hand a raw Telegram update (a new / edited / deleted channel message ...) to the handlers that listen for it."""
+        for builder, cb in self.tg.handlers:
+            if isinstance(builder, events.Raw) and builder.filter(update) is not None:
+                await cb(update)
+
+    async def press(self, data):
+        ev = FakeEvent(self.uid, self.out, data=data)
+        for builder, cb in self.tg.handlers:
+            if isinstance(builder, events.CallbackQuery):
+                await cb(ev)
+        return ev
+
+
+def norm(s):
+    import html
+
+    return html.unescape(re.sub(r"<[^>]+>", "", s or ""))
diff --git a/tests/test_autopost.py b/tests/test_autopost.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba8aaa2efb1f9c04dc579e2b63b65871a9f2fcba
--- /dev/null
+++ b/tests/test_autopost.py
@@ -0,0 +1,495 @@
+"""/autopost (a series of episode posts, then the real links) and "Mass replace links" in a post's panel."""
+import asyncio
+
+import pytest
+from telethon import errors
+
+from app.autopost import (
+    PLACEHOLDER_LINK,
+    button_label,
+    parse_autopost_args,
+    plan_ranges,
+    post_text,
+    ranges_summary,
+)
+from app.tgutil import button_url
+
+from .harness import App, norm
+
+
+def run(coro):
+    return asyncio.run(coro)
+
+
+async def make_app(tmp_path, **cfg):
+    app = App(tmp_path, edit_delay=0, **cfg)
+    await app.start()
+    await app.db.save_channel(1, 5, "Anime Channel", "animech", 1)
+    return app
+
+
+def sent_markup(entry):
+    return entry[3]["buttons"]
+
+
+def link_edits(app):
+    """(message id, new link) for every keyboard-only edit the bot made."""
+    out = []
+    for kind, mid, req in app.tg.edits:
+        if kind == "raw" and req.message is None and req.reply_markup is not None:
+            out.append((mid, button_url(req.reply_markup.rows[0].buttons[0])))
+    return out
+
+
+# ------------------------------------------------------------------------------- the plan
+def test_the_ranges_follow_the_interval():
+    assert plan_ranges(114, 20) == [(1, 20), (21, 40), (41, 60), (61, 80), (81, 100), (101, 114)]
+    assert plan_ranges(100, 20) == [(1, 20), (21, 40), (41, 60), (61, 80), (81, 100)]
+    assert plan_ranges(20, 20) == [(1, 20)]
+
+
+def test_a_short_end_is_added_to_the_post_before_it():
+    assert plan_ranges(102, 20)[-2:] == [(61, 80), (81, 102)]  # 2 left over: less than half of 20
+    assert plan_ranges(110, 20)[-1] == (81, 110)  # exactly half of 20: still added
+    assert plan_ranges(111, 20)[-2:] == [(81, 100), (101, 111)]  # 11 is more than half: its own post
+    assert plan_ranges(114, 20)[-1] == (101, 114)  # 14 is more than half
+    assert plan_ranges(22, 15) == [(1, 22)]  # half of 15 is 7.5: 7 left over is added ...
+    assert plan_ranges(23, 15) == [(1, 15), (16, 23)]  # ... 8 is not
+
+
+def test_a_total_below_the_interval_is_one_post_and_small_intervals_work():
+    assert plan_ranges(14, 20) == [(1, 14)]
+    assert plan_ranges(3, 20) == [(1, 3)]
+    assert plan_ranges(3, 1) == [(1, 1), (2, 2), (3, 3)]
+    assert plan_ranges(5, 2) == [(1, 2), (3, 5)]  # one left over = half of 2: added to the post before it
+    with pytest.raises(ValueError):
+        plan_ranges(0, 20)
+
+
+def test_every_episode_is_in_exactly_one_post():
+    for total in range(1, 130):
+        for interval in (1, 2, 3, 7, 10, 15, 20, 25):
+            ranges = plan_ranges(total, interval)
+            flat = [n for a, b in ranges for n in range(a, b + 1)]
+            assert flat == list(range(1, total + 1)), (total, interval)
+            assert all(b - a + 1 <= interval + interval // 2 for a, b in ranges)
+
+
+def test_texts_are_the_ones_asked_for():
+    assert post_text(1, 20) == "Episodes 01 to 20\n\nClick the button below to download 👇"
+    assert post_text(101, 114) == "Episodes 101 to 114\n\nClick the button below to download 👇"
+    assert button_label(21, 40) == "Download Episodes 21 to 40"
+    assert button_label(5, 5) == "Download Episode 05"
+    assert ranges_summary(plan_ranges(114, 20)) == "01–20 · 21–40 · 41–60 · 61–80 · 81–100 · 101–114"
+    assert ranges_summary([(i, i) for i in range(1, 40)]).endswith("… · 38 · 39")
+
+
+def test_the_arguments():
+    assert parse_autopost_args("114 20") == (114, 20)
+    assert parse_autopost_args("  12,  5 ") == (12, 5)
+    for bad in ("", "114", "114 20 3", "a b", "0 20", "20 0", "-5 3", "1.5 2", "999999999 20"):
+        with pytest.raises(ValueError):
+            parse_autopost_args(bad)
+
+
+# ------------------------------------------------------------------------------- the command
+def test_the_whole_autopost_flow(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        await app.text("/autopost 114 20")
+        shown = norm(app.out.last_text)
+        assert "6 post(s)" in shown and "01–20 · 21–40 · 41–60 · 61–80 · 81–100 · 101–114" in shown
+        assert "Which channel" in shown and "1. Anime Channel" in shown and app.out.last_buttons()[0] == ["1"]
+
+        await app.press(app.out.callback_data("Anime Channel"))
+        posted = [e for e in app.tg.sent if e[0] == "text" and e[1].channel_id == 1]
+        assert len(posted) == 6
+        assert [e[2] for e in posted] == [post_text(a, b) for a, b in plan_ranges(114, 20)]
+        for (a, b), entry in zip(plan_ranges(114, 20), posted):
+            row = sent_markup(entry).rows[0].buttons
+            assert len(row) == 1 and row[0].text == f"Download Episodes {a:02d} to {b:02d}"
+            assert button_url(row[0]) == PLACEHOLDER_LINK == "https://t.me/English"
+            assert entry[3]["link_preview"] is False
+
+        # all six are in My posts, as published posts of this channel
+        posts = await app.db.sent_posts(1)
+        assert [p.message_id for p in posts] == [100, 101, 102, 103, 104, 105]
+        assert posts[0].source == "bot" and posts[0].buttons == [[{"t": "Download Episodes 01 to 20", "u": PLACEHOLDER_LINK}]]
+
+        # the first link is asked for at once, with a cancel button
+        ask = norm(app.out.last_text)
+        assert "1 of 6" in ask and "Download Episodes 01 to 20" in ask and PLACEHOLDER_LINK in ask
+        assert "Cancel" in str(app.out.last_buttons()) and "Skip" in str(app.out.last_buttons())
+
+        links = [f"https://t.me/mybot?start=part{i}" for i in range(1, 7)]
+        for i, url in enumerate(links):
+            await app.text(url)
+            if i < 5:
+                nxt = norm(app.out.last_text)
+                assert f"{i + 2} of 6" in nxt and "now opens" in nxt and url in nxt
+                a, b = plan_ranges(114, 20)[i + 1]
+                assert f"Download Episodes {a:02d} to {b:02d}" in nxt
+        assert "All done" in app.out.last_text and "6 link(s) replaced" in app.out.last_text
+
+        # each answer changed only the keyboard of its own message, at once
+        assert link_edits(app) == [(100 + i, links[i]) for i in range(6)]
+        assert [button_url(app.tg.edits[i][2].reply_markup.rows[0].buttons[0]) for i in range(6)] == links
+        posts = await app.db.sent_posts(1)
+        assert [p.buttons[0][0]["u"] for p in posts] == links
+        assert [p.buttons[0][0]["t"] for p in posts][-1] == "Download Episodes 101 to 114"
+        assert 1 not in app.ctx.state  # nothing left to answer
+        await app.db.close()
+
+    run(go())
+
+
+def test_the_short_end_gets_its_own_post_or_joins_the_last(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        await app.text("/autopost 102 20")
+        await app.press(app.out.callback_data("Anime Channel"))
+        texts = [e[2].splitlines()[0] for e in app.tg.sent if e[0] == "text" and e[1].channel_id == 1]
+        assert texts == ["Episodes 01 to 20", "Episodes 21 to 40", "Episodes 41 to 60", "Episodes 61 to 80", "Episodes 81 to 102"]
+        await app.db.close()
+
+    run(go())
+
+
+def test_admins_may_use_it_and_strangers_may_not(tmp_path):
+    async def go():
+        app = await make_app(tmp_path, admins=frozenset({7}))
+        app.uid = 7
+        await app.text("/autopost 40 20")
+        assert "Which channel" in norm(app.out.last_text)
+        await app.press(app.out.callback_data("Anime Channel"))
+        assert len([e for e in app.tg.sent if e[0] == "text" and e[1].channel_id == 1]) == 2
+        app.uid = 99
+        before = len(app.tg.sent)
+        await app.text("/autopost 40 20")
+        assert "private" in app.out.last_text and len(app.tg.sent) == before
+        await app.db.close()
+
+    run(go())
+
+
+def test_wrong_numbers_and_no_channels_are_explained(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        await app.text("/autopost")
+        assert "Usage" in norm(app.out.last_text) and "/autopost 114 20" in norm(app.out.last_text)
+        for bad in ("114", "x y", "0 5", "114 20 5"):
+            await app.text(f"/autopost {bad}")
+            assert "Usage: /autopost  " in norm(app.out.last_text), bad
+        await app.text("/autopost 5000 1")
+        assert "at most 200" in app.out.last_text
+        assert not [e for e in app.tg.sent if e[0] == "text"]  # nothing was posted by any of those
+
+        (tmp_path / "empty").mkdir()
+        empty = App(tmp_path / "empty", edit_delay=0)
+        await empty.start()
+        await empty.text("/autopost 114 20")
+        assert "No channels yet" in empty.out.last_text
+        await empty.db.close()
+        await app.db.close()
+
+    run(go())
+
+
+def test_cancelling_the_channel_choice_posts_nothing(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        await app.text("/autopost 114 20")
+        await app.press(app.out.callback_data("Cancel"))
+        assert "Cancelled" in app.out.last_text
+        assert not [e for e in app.tg.sent if e[0] == "text"]
+        # an old button does nothing any more
+        await app.press("apc:" + "0" * 8 + ":1")
+        assert "expired" in app.out.last_text
+        await app.db.close()
+
+    run(go())
+
+
+def test_a_double_press_posts_once(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        await app.text("/autopost 40 20")
+        data = app.out.callback_data("Anime Channel")
+        await app.press(data)
+        await app.press(data)
+        assert "expired" in app.out.last_text
+        assert len([e for e in app.tg.sent if e[0] == "text" and e[1].channel_id == 1]) == 2
+        await app.db.close()
+
+    run(go())
+
+
+def test_the_bot_needs_the_post_right_and_a_free_hand(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        app.tg.rights = dict(admin=True, post=False, edit=True, delete=True, invite=False, add_admins=False)
+        await app.text("/autopost 40 20")
+        pick = app.out.callback_data("Anime Channel")
+        await app.press(pick)
+        assert "Post messages" in app.out.last_text
+        assert not [e for e in app.tg.sent if e[0] == "text"]
+        # the plan is still there: with the right given, the same button works - but not while a long job runs
+        app.tg.rights["post"] = True
+        await app.ctx.lock.acquire()
+        await app.press(pick)
+        assert "still running" in app.out.last_text
+        app.ctx.lock.release()
+        await app.press(pick)
+        assert len([e for e in app.tg.sent if e[0] == "text" and e[1].channel_id == 1]) == 2
+        await app.db.close()
+
+    run(go())
+
+
+def test_when_telegram_stops_midway_the_posts_made_still_get_their_links(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        real = app.tg.send_message
+        calls = []
+
+        async def flaky(peer, message="", **kw):
+            calls.append(message)
+            if len(calls) == 3:
+                raise errors.ChatWriteForbiddenError(request=None)
+            return await real(peer, message, **kw)
+
+        app.tg.send_message = flaky
+        await app.text("/autopost 114 20")
+        await app.press(app.out.callback_data("Anime Channel"))
+        # the summary (an edit of the picker) tells where it stopped; the next message asks for the first link
+        summary = [norm(t) for k, t, _ in app.out.log if k == "edit" and t and "Stopped early" in t]
+        assert summary and "Posted 2 of 6" in summary[0] and "Episodes 41 to 60" in summary[0]
+        assert "1 of 2" in norm(app.out.last_text)
+        assert len(await app.db.sent_posts(1)) == 2
+        await app.text("https://t.me/mybot?start=1")
+        await app.text("https://t.me/mybot?start=2")
+        assert "All done" in app.out.last_text and "2 link(s) replaced" in app.out.last_text
+        await app.db.close()
+
+    run(go())
+
+
+def test_nothing_posted_means_a_plain_error(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+
+        async def refuse(peer, message="", **kw):
+            raise errors.ChatWriteForbiddenError(request=None)
+
+        app.tg.send_message = refuse
+        await app.text("/autopost 40 20")
+        await app.press(app.out.callback_data("Anime Channel"))
+        assert "Nothing was posted" in app.out.last_text and "Episodes 01 to 20" in app.out.last_text
+        assert await app.db.sent_posts(1) == []
+        await app.db.close()
+
+    run(go())
+
+
+def test_skipping_and_stopping_while_the_links_are_asked(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        await app.text("/autopost 80 20")
+        await app.press(app.out.callback_data("Anime Channel"))
+        await app.text("https://t.me/mybot?start=1")
+        assert "2 of 4" in norm(app.out.last_text)
+        await app.press(app.out.callback_data("Skip"))  # keeps the placeholder
+        assert "Skipped" in app.out.last_text and "3 of 4" in norm(app.out.last_text)
+        cancel = app.out.callback_data("Cancel")
+        # the Skip button of the earlier message is stale now
+        await app.press("lqs:1")
+        assert "earlier step" in app.out.last_text
+        await app.press(cancel)
+        shown = norm(app.out.last_text)
+        assert "Stopped" in shown and "1 link(s) replaced" in shown and "1 skipped" in shown and "2 not asked" in shown
+        assert 1 not in app.ctx.state
+        posts = await app.db.sent_posts(1)
+        assert [p.buttons[0][0]["u"] for p in posts] == ["https://t.me/mybot?start=1", PLACEHOLDER_LINK, PLACEHOLDER_LINK, PLACEHOLDER_LINK]
+        # nothing more is expected from the user
+        await app.text("https://t.me/whatever")
+        assert "Use /new" in app.out.last_text
+        await app.db.close()
+
+    run(go())
+
+
+def test_something_that_is_not_a_link_is_asked_again_and_a_refusal_keeps_the_step(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        await app.text("/autopost 40 20")
+        await app.press(app.out.callback_data("Anime Channel"))
+        await app.text("hello there")
+        assert "doesn't look like a link" in norm(app.out.last_text)
+        # Telegram refuses the keyboard edit: the saved link is unchanged and the same post is asked again
+        app.tg.fail["EditMessageRequest"] = errors.ChatAdminRequiredError(request=None)
+        await app.text("t.me/mybot?start=1")
+        assert "NOT changed" in app.out.last_text
+        assert (await app.db.sent_posts(1))[0].buttons[0][0]["u"] == PLACEHOLDER_LINK
+        app.tg.fail.clear()
+        await app.text("t.me/mybot?start=1")
+        assert "now opens" in app.out.last_text and "https://t.me/mybot?start=1" in app.out.last_text
+        assert (await app.db.sent_posts(1))[0].buttons[0][0]["u"] == "https://t.me/mybot?start=1"
+        await app.db.close()
+
+    run(go())
+
+
+# ------------------------------------------------------------------- mass replace links
+def sent(app, pid_text, message_id, buttons, channel_id=1, text=None):
+    return app.db.create_post(
+        channel_id=channel_id, message_id=message_id, status="sent", source="bot", text=text or pid_text,
+        entities=[], buttons=buttons, link_preview=False,
+    )
+
+
+def one(label, url):
+    return [[{"t": label, "u": url}]]
+
+
+async def channel_with_posts(app):
+    """#1 text, #2 button, #3 text, #4 only another bot's button, #5 button, #6 two buttons, #7 button in ANOTHER channel."""
+    await app.db.save_channel(2, 6, "Other", "other", 1)
+    posts = {}
+    posts[1] = await sent(app, "just text", 10, [])
+    posts[2] = await sent(app, "Episodes 01 to 20", 11, one("Download Episodes 01 to 20", "https://t.me/old?start=a"))
+    posts[3] = await sent(app, "plain again", 12, [])
+    posts[4] = await sent(app, "reactions only", 13, [[{"t": "👍 3", "raw": "AAAA"}]])
+    posts[5] = await sent(app, "Episodes 21 to 40", 14, one("Download Episodes 21 to 40", "https://t.me/old?start=b"))
+    posts[6] = await sent(
+        app, "Choose", 15, [[{"t": "480p", "u": "https://t.me/old?start=c"}, {"t": "720p", "u": "https://t.me/old?start=d"}]],
+    )
+    posts[7] = await sent(app, "elsewhere", 5, one("Other channel", "https://t.me/old?start=z"), channel_id=2)
+    return posts
+
+
+def test_only_published_posts_with_a_link_button_get_the_option(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        posts = await channel_with_posts(app)
+        draft = await app.db.create_post(channel_id=1, status="draft", source="bot", text="d", entities=[], buttons=one("Get", "https://t.me/x"))
+        for key, expected in ((1, False), (2, True), (4, False), (5, True), (6, True)):
+            await app.press(f"po:{posts[key].id}")
+            assert ("Mass replace links" in str(app.out.last_buttons())) is expected, key
+        await app.press(f"po:{draft.id}")
+        assert "Mass replace links" not in str(app.out.last_buttons())
+        await app.press(f"mlp:{draft.id}")
+        assert "published posts only" in app.out.last_text
+        await app.press(f"mlp:{posts[1].id}")
+        assert "no button with a link" in app.out.last_text
+        await app.db.close()
+
+    run(go())
+
+
+def test_mass_replace_walks_through_the_button_posts_of_the_channel(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        posts = await channel_with_posts(app)
+        await app.press(f"po:{posts[2].id}")
+        await app.press(app.out.callback_data("Mass replace links"))
+        ask = norm(app.out.last_text)
+        assert "Mass replace links" in ask and "1 of 4" in ask and "Download Episodes 01 to 20" in ask
+        assert "https://t.me/old?start=a" in ask and f"Post #{posts[2].id}" in ask
+        assert "Cancel" in str(app.out.last_buttons())
+
+        await app.text("https://t.me/new?start=1")
+        ask = norm(app.out.last_text)  # the text posts (#3) and the reactions-only post (#4) are skipped
+        assert "2 of 4" in ask and "Download Episodes 21 to 40" in ask and f"Post #{posts[5].id}" in ask
+        assert "now opens https://t.me/new?start=1" in ask
+        await app.text("https://t.me/new?start=2")
+        ask = norm(app.out.last_text)
+        assert "3 of 4" in ask and "480p" in ask and "https://t.me/old?start=c" in ask
+        await app.text("https://t.me/new?start=3")
+        assert "4 of 4" in norm(app.out.last_text) and "720p" in norm(app.out.last_text)
+        await app.text("https://t.me/new?start=4")
+        assert "All done" in app.out.last_text and "4 link(s) replaced" in app.out.last_text
+
+        # keyboard-only edits: the text of the posts was never sent again
+        edits = [(mid, req) for kind, mid, req in app.tg.edits if kind == "raw"]
+        assert [mid for mid, _ in edits] == [11, 14, 15, 15]
+        assert all(req.message is None for _, req in edits)
+        last = edits[-1][1].reply_markup.rows[0].buttons
+        assert [button_url(b) for b in last] == ["https://t.me/new?start=3", "https://t.me/new?start=4"]
+        assert [b.text for b in last] == ["480p", "720p"]
+
+        fresh = {k: await app.db.get_post(p.id) for k, p in posts.items()}
+        assert fresh[2].buttons == one("Download Episodes 01 to 20", "https://t.me/new?start=1")
+        assert fresh[5].buttons[0][0]["u"] == "https://t.me/new?start=2"
+        assert [b["u"] for b in fresh[6].buttons[0]] == ["https://t.me/new?start=3", "https://t.me/new?start=4"]
+        assert fresh[4].buttons == [[{"t": "👍 3", "raw": "AAAA"}]]  # another bot's button: untouched
+        assert fresh[7].buttons[0][0]["u"] == "https://t.me/old?start=z"  # another channel: untouched
+        assert fresh[2].text == "Episodes 01 to 20"
+        await app.db.close()
+
+    run(go())
+
+
+def test_it_starts_at_the_chosen_post_and_goes_towards_the_newest(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        posts = await channel_with_posts(app)
+        await app.press(f"mlp:{posts[5].id}")  # #2 is older: not asked
+        assert "1 of 3" in norm(app.out.last_text) and "Download Episodes 21 to 40" in norm(app.out.last_text)
+        await app.press(app.out.callback_data("Skip"))
+        assert "2 of 3" in norm(app.out.last_text) and "480p" in norm(app.out.last_text)
+        await app.press(app.out.callback_data("Cancel"))
+        shown = norm(app.out.last_text)
+        assert "Stopped" in shown and "1 skipped" in shown and "2 not asked" in shown
+        assert (await app.db.get_post(posts[5].id)).buttons[0][0]["u"] == "https://t.me/old?start=b"
+        assert not [1 for kind, mid, req in app.tg.edits if kind == "raw"]
+        await app.db.close()
+
+    run(go())
+
+
+def test_a_post_that_disappears_meanwhile_is_passed_over(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        posts = await channel_with_posts(app)
+        await app.press(f"mlp:{posts[2].id}")
+        await app.db.delete_post(posts[5].id)  # forgotten in the bot while the list is open
+        await app.text("https://t.me/new?start=1")
+        assert "3 of 4" in norm(app.out.last_text) and "480p" in norm(app.out.last_text)  # #5 was passed over
+        await app.text("https://t.me/new?start=2")
+        await app.text("https://t.me/new?start=3")
+        assert "All done" in app.out.last_text
+        assert "3 link(s) replaced" in app.out.last_text and "1 button(s) no longer there" in app.out.last_text
+        await app.db.close()
+
+    run(go())
+
+
+def test_telegram_refusing_a_link_keeps_the_same_step(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        posts = await channel_with_posts(app)
+        await app.press(f"mlp:{posts[2].id}")
+        skip = app.out.callback_data("Skip")
+        app.tg.fail["EditMessageRequest"] = errors.MessageIdInvalidError(request=None)
+        await app.text("https://t.me/new?start=1")
+        assert "NOT changed" in app.out.last_text
+        assert (await app.db.get_post(posts[2].id)).buttons[0][0]["u"] == "https://t.me/old?start=a"
+        app.tg.fail.clear()
+        await app.press(skip)
+        assert "2 of 4" in norm(app.out.last_text)
+        await app.db.close()
+
+    run(go())
+
+
+def test_the_last_button_post_ends_the_list(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        p = await sent(app, "only one", 3, one("Get", "https://t.me/old"))
+        await app.press(f"mlp:{p.id}")
+        assert "1 of 1" in norm(app.out.last_text)
+        await app.text("https://t.me/new")
+        assert "All done" in app.out.last_text and "1 link(s) replaced" in app.out.last_text
+        await app.db.close()
+
+    run(go())
diff --git a/tests/test_backup.py b/tests/test_backup.py
new file mode 100644
index 0000000000000000000000000000000000000000..958c2c3319a2e04252f408a0b00b066a89f299e2
--- /dev/null
+++ b/tests/test_backup.py
@@ -0,0 +1,479 @@
+"""/export and /import: a backup can be put back, only adds, and never trusts what is in the file."""
+import asyncio
+import datetime
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from app.backup import (
+    MAX_BYTES,
+    BackupError,
+    apply_import,
+    channel_row,
+    parse_backup,
+    plan_import,
+    post_row,
+    stamp,
+)
+from app.db import utcnow
+
+from .dbutil import db_url_for, fresh_db
+from .harness import App, FakeEvent, norm
+
+T0 = datetime.datetime(2026, 10, 1, 12, 0, 0, tzinfo=datetime.timezone.utc)
+
+
+def run(coro):
+    return asyncio.run(coro)
+
+
+def backup_bytes(**parts):
+    data = {"exported_at": T0.isoformat(), "channels": [], "posts": [], "ignored": []}
+    data.update(parts)
+    return json.dumps(data).encode()
+
+
+def chan(cid=1, **kw):
+    return {"id": cid, "access_hash": 5, "title": f"Channel {cid}", "username": f"ch{cid}", "active": True,
+            "added_by": 1, "created_at": T0.isoformat(), **kw}
+
+
+def post(cid=1, mid=10, **kw):
+    base = {"channel_id": cid, "message_id": mid, "status": "sent", "source": "bot", "text": f"post {mid}", "entities": [],
+            "media_kind": None, "media_file_id": None, "buttons": [], "link_preview": False, "created_by": 1,
+            "created_at": T0.isoformat(), "updated_at": T0.isoformat(), "sent_at": T0.isoformat()}
+    base.update(kw)
+    return base
+
+
+async def fresh(tmp_path, name="a"):
+    d = tmp_path / name
+    d.mkdir(exist_ok=True)
+    return await fresh_db(db_url_for(d))
+
+
+# ================================================================================================ reading the file
+def test_a_good_file_is_read_completely():
+    posts = [
+        post(1, 10, entities=[{"k": "bold", "o": 0, "l": 4}], buttons=[[{"t": "Watch", "u": "https://t.me/a/1"}]]),
+        post(1, None, status="draft", text="not sent yet"),
+        post(2, 7, source="adopted", media_kind="photo", media_file_id="abc"),
+    ]
+    bk = parse_backup(backup_bytes(channels=[chan(1), chan(2, username=None, active=False)], posts=posts, ignored=[{"channel_id": 1, "message_id": 4}]))
+    assert [c["id"] for c in bk.channels] == [1, 2] and bk.channels[1]["active"] is False and bk.channels[1]["username"] is None
+    assert [(p["channel_id"], p["message_id"], p["status"]) for p in bk.posts] == [(1, 10, "sent"), (1, None, "draft"), (2, 7, "sent")]
+    assert bk.posts[0]["buttons"] == [[{"t": "Watch", "u": "https://t.me/a/1"}]] and bk.posts[2]["source"] == "adopted"
+    assert bk.posts[0]["created_at"] == T0 and bk.ignored == [(1, 4)] and bk.bad_rows == 0
+    assert bk.exported_at == T0.isoformat()
+
+
+def test_a_file_with_a_byte_order_mark_and_old_style_still_reads():
+    raw = b"\xef\xbb\xbf" + json.dumps({"channels": [chan(1)], "posts": [post(1, 3)]}).encode()  # no "ignored", no "exported_at"
+    bk = parse_backup(raw)
+    assert len(bk.channels) == 1 and len(bk.posts) == 1 and bk.ignored == [] and bk.exported_at is None
+
+
+@pytest.mark.parametrize(
+    "raw,why",
+    [
+        (b"not json at all", "not a JSON file"),
+        (b"\xff\xfe\x00", "not a JSON file"),
+        (b"[1, 2, 3]", "does not look like a backup"),
+        (b'{"hello": "world"}', "does not look like a backup"),
+        (b'{"channels": "x", "posts": []}', "“channels” should be a list"),
+        (b'{"channels": [], "posts": {}}', "“posts” should be a list"),
+        (b'{"channels": [], "posts": []}', "nothing in it that can be imported"),
+        (b'{"channels": [5], "posts": ["x"]}', "All entries were unreadable"),
+        (b"x" * (MAX_BYTES + 1), "larger than"),
+    ],
+)
+def test_a_file_that_is_not_a_backup_is_refused_with_the_reason(raw, why):
+    with pytest.raises(BackupError) as e:
+        parse_backup(raw)
+    assert why in str(e.value)
+
+
+def test_unusable_entries_are_counted_and_left_out():
+    rows = [
+        post(1, 10),
+        post(1, 11, status="weird"),  # unknown status
+        post(1, None),  # published without a message id
+        post(1, 12, text=5),  # text is not text
+        post(1, 13, entities="bold"),  # formatting is not a list
+        post(1, 14, buttons=[["not a button"]]),  # buttons are not dicts
+        post(1, 15, media_kind="x" * 40),
+        post(1, 16, created_at="yesterday"),
+        post("one", 17),
+        post(True, 18),  # a boolean is not a channel id
+        "junk",
+        None,
+    ]
+    bk = parse_backup(backup_bytes(channels=[chan(1), chan(0), {"title": "no id"}], posts=rows, ignored=[{"channel_id": 1}, "x", {"channel_id": 1, "message_id": 3}]))
+    assert [p["message_id"] for p in bk.posts] == [10]
+    assert [c["id"] for c in bk.channels] == [1] and bk.ignored == [(1, 3)]
+    assert bk.bad_rows == 11 + 2 + 2 - 1 + 1  # 11 bad posts (one of them None counts too), 2 channels, 2 marks
+
+
+def test_rows_are_cleaned_while_they_are_read():
+    p = post_row({"channel_id": 3, "message_id": 4, "status": "draft", "created_at": "2026-10-01T12:00:00Z"})
+    assert p["message_id"] is None and p["status"] == "draft" and p["created_at"] == T0 and p["updated_at"] == T0
+    p = post_row({"channel_id": 3, "message_id": 4, "source": "somebody"})
+    assert p["status"] == "sent" and p["source"] == "bot" and p["text"] == "" and p["entities"] == [] and p["buttons"] == []
+    naive = post_row({"channel_id": 3, "message_id": 4, "created_at": "2026-10-01T12:00:00"})  # no zone: UTC
+    assert naive["created_at"] == T0
+    c = channel_row({"id": -100123, "username": "@Name", "title": "t" * 400})
+    assert c["username"] == "Name" and len(c["title"]) == 256 and c["active"] is True and c["access_hash"] == 0
+
+
+def test_the_date_of_the_backup_is_written_for_people():
+    assert stamp("2026-10-01T12:00:00+00:00") == "01 Oct 2026, 12:00 UTC"
+    assert stamp("2026-10-01T17:30:00+05:30") == "01 Oct 2026, 12:00 UTC"
+    assert stamp("not a date") == "not a date" and stamp(None) == ""
+
+
+# =================================================================================================== the round trip
+async def filled(db):
+    await db.save_channel(1, 11, "Anime One", "animeone", 7)
+    await db.save_channel(2, 22, "Movies", None, 7)
+    await db.set_channel_active(2, False)
+    a = await db.create_post(
+        channel_id=1, message_id=10, status="sent", source="bot", text="Episode 1", created_by=7, sent_at=T0,
+        entities=[{"k": "bold", "o": 0, "l": 7}], buttons=[[{"t": "Watch", "u": "https://t.me/animeone/9"}]],
+        media_kind="photo", media_file_id="ref-1", link_preview=False,
+    )
+    b = await db.create_post(channel_id=1, message_id=11, status="sent", source="adopted", text="From the app", sent_at=T0)
+    c = await db.create_post(channel_id=2, status="draft", text="a draft", created_by=7)
+    await db.ignore_post(1, 99)
+    return a, b, c
+
+
+def same_post(x, y):
+    keys = ("channel_id", "message_id", "status", "source", "text", "entities", "media_kind", "media_file_id", "buttons",
+            "link_preview", "created_by")
+    return all(getattr(x, k) == getattr(y, k) for k in keys)
+
+
+def test_what_export_writes_import_puts_back_on_a_new_bot(tmp_path):
+    async def go():
+        old = await fresh(tmp_path, "old")
+        made = await filled(old)
+        data = await old.export_all()
+        assert data["ignored"] == [{"channel_id": 1, "message_id": 99}]
+        raw = json.dumps(data, ensure_ascii=False, indent=1).encode("utf-8")  # exactly what /export sends
+
+        new = await fresh(tmp_path, "new")
+        plan = await plan_import(new, parse_backup(raw))
+        assert (len(plan.new_channels), plan.sent_to_add, plan.drafts_to_add, len(plan.new_ignored)) == (2, 2, 1, 1)
+        res = await apply_import(new, plan)
+        assert (res.channels_added, res.posts_added, res.drafts_added, res.marks_added, res.skipped_meanwhile) == (2, 2, 1, 1, 0)
+
+        chans = {c.id: c for c in await new.list_channels(active_only=False)}
+        assert (chans[1].title, chans[1].username, chans[1].access_hash, chans[1].active) == ("Anime One", "animeone", 11, True)
+        assert (chans[2].title, chans[2].username, chans[2].active) == ("Movies", None, False)
+        for original in made:
+            if original.status == "sent":
+                back = await new.find_by_message(original.channel_id, original.message_id)
+                assert back is not None and same_post(original, back)
+                assert back.id != original.id or True  # the new database numbers its own posts
+            else:
+                rows, _ = await new.list_posts(2, "draft", 0, 10)
+                assert len(rows) == 1 and same_post(original, rows[0])
+        assert await new.ignored_ids(1) == {99}
+        await old.close()
+        await new.close()
+
+    run(go())
+
+
+def test_importing_the_same_file_twice_adds_nothing_the_second_time(tmp_path):
+    async def go():
+        old = await fresh(tmp_path, "old")
+        await filled(old)
+        raw = json.dumps(await old.export_all()).encode()
+        new = await fresh(tmp_path, "new")
+        await apply_import(new, await plan_import(new, parse_backup(raw)))
+        again = await plan_import(new, parse_backup(raw))
+        assert again.nothing_new and again.channels_present == 2 and again.posts_present == 2 and again.drafts_present == 1
+        res = await apply_import(new, again)
+        assert (res.channels_added, res.posts_added, res.drafts_added, res.marks_added) == (0, 0, 0, 0)
+        assert len((await new.list_posts(None, None, 0, 50))[0]) == 3
+        await old.close()
+        await new.close()
+
+    run(go())
+
+
+def test_importing_only_adds_and_never_changes_what_is_here(tmp_path):
+    async def go():
+        db = await fresh(tmp_path)
+        await db.save_channel(1, 99, "Renamed Since", "newname", 7)
+        mine = await db.create_post(channel_id=1, message_id=10, status="sent", text="the edit I made after the backup", sent_at=T0)
+        raw = backup_bytes(channels=[chan(1, title="Old Name", username="oldname")], posts=[post(1, 10, text="the old text"), post(1, 11), post(1, 12)])
+        plan = await plan_import(db, parse_backup(raw))
+        assert plan.channels_present == 1 and plan.posts_present == 1 and plan.sent_to_add == 2
+        await apply_import(db, plan)
+        c = await db.get_channel(1)
+        assert (c.title, c.username, c.access_hash) == ("Renamed Since", "newname", 99)
+        assert (await db.find_by_message(1, 10)).text == "the edit I made after the backup"
+        assert [p.message_id for p in await db.sent_posts(1)] == [10, 11, 12]
+        assert (await db.get_post(mine.id)) is not None
+        await db.close()
+
+    run(go())
+
+
+def test_posts_the_owner_made_the_bot_forget_are_not_brought_back(tmp_path):
+    async def go():
+        db = await fresh(tmp_path)
+        await db.save_channel(1, 5, "Chan", "chan", 7)
+        await db.ignore_post(1, 11)  # forgotten here after the backup was made
+        raw = backup_bytes(channels=[chan(1)], posts=[post(1, 10), post(1, 11), post(1, 12)], ignored=[{"channel_id": 1, "message_id": 12}])
+        plan = await plan_import(db, parse_backup(raw))
+        assert plan.posts_forgotten == 2 and plan.sent_to_add == 1  # 11 (forgotten here) and 12 (forgotten in the backup)
+        await apply_import(db, plan)
+        assert [p.message_id for p in await db.sent_posts(1)] == [10]
+        assert await db.ignored_ids(1) == {11, 12}
+        await db.close()
+
+    run(go())
+
+
+def test_posts_of_an_unknown_channel_are_left_out(tmp_path):
+    async def go():
+        db = await fresh(tmp_path)
+        raw = backup_bytes(channels=[chan(1)], posts=[post(1, 10), post(2, 20), post(2, None, status="draft")], ignored=[{"channel_id": 2, "message_id": 5}])
+        plan = await plan_import(db, parse_backup(raw))
+        assert plan.posts_orphaned == 2 and plan.sent_to_add == 1 and plan.new_ignored == []
+        await apply_import(db, plan)
+        assert await db.get_channel(2) is None and len((await db.list_posts(None, None, 0, 10))[0]) == 1
+        await db.close()
+
+    run(go())
+
+
+def test_a_post_that_turns_up_between_the_preview_and_the_import_is_skipped_not_an_error(tmp_path):
+    async def go():
+        db = await fresh(tmp_path)
+        raw = backup_bytes(channels=[chan(1)], posts=[post(1, 10), post(1, 11), post(1, 12)])
+        plan = await plan_import(db, parse_backup(raw))
+        await db.save_channel(1, 5, "Chan", "chan", 7)
+        await db.adopt_message(1, 11, {"text": "the sync was quicker"})  # while the owner was reading the preview
+        res = await apply_import(db, plan)
+        assert res.posts_added == 2 and res.skipped_meanwhile == 1 and res.channels_added == 0
+        assert (await db.find_by_message(1, 11)).text == "the sync was quicker"
+        assert [p.message_id for p in await db.sent_posts(1)] == [10, 11, 12]
+        await db.close()
+
+    run(go())
+
+
+def test_a_big_backup_is_saved_in_pieces(tmp_path):
+    async def go():
+        db = await fresh(tmp_path)
+        posts = [post(1, i, text=f"post {i}") for i in range(1, 1202)]
+        plan = await plan_import(db, parse_backup(backup_bytes(channels=[chan(1)], posts=posts)))
+        seen = []
+
+        async def progress(done, total):
+            seen.append((done, total))
+
+        res = await apply_import(db, plan, progress=progress)
+        assert res.posts_added == 1201 and seen == [(500, 1201), (1000, 1201), (1201, 1201)]
+        assert len(await db.sent_posts(1)) == 1201
+        await db.close()
+
+    run(go())
+
+
+def test_two_drafts_with_the_same_text_but_made_at_different_times_are_both_kept(tmp_path):
+    async def go():
+        db = await fresh(tmp_path)
+        d1 = post(1, None, status="draft", text="same", created_at=T0.isoformat())
+        d2 = post(1, None, status="draft", text="same", created_at=(T0 + datetime.timedelta(minutes=5)).isoformat())
+        raw = backup_bytes(channels=[chan(1)], posts=[d1, d2, d1])  # the third is a copy of the first
+        plan = await plan_import(db, parse_backup(raw))
+        assert plan.drafts_to_add == 2 and plan.drafts_present == 1
+        await apply_import(db, plan)
+        assert len((await db.list_posts(1, "draft", 0, 10))[0]) == 2
+        await db.close()
+
+    run(go())
+
+
+# ===================================================================================== the commands, as a person uses them
+def backup_file(raw: bytes, *, size=None):
+    async def download_media(file=None):
+        assert file is bytes
+        return raw
+
+    return SimpleNamespace(
+        raw_text="", entities=[], media=object(), grouped_id=None, forward=None,
+        file=SimpleNamespace(size=len(raw) if size is None else size, name="channel-posts-export.json"),
+        download_media=download_media,
+    )
+
+
+async def started(tmp_path, **kw):
+    app = App(tmp_path, **kw)
+    await app.start()
+    return app
+
+
+def test_export_sends_the_file_and_tells_how_to_put_it_back(tmp_path, monkeypatch):
+    async def go():
+        app = await started(tmp_path)
+        await app.db.save_channel(1, 5, "Chan", "chan", 1)
+        await app.db.create_post(channel_id=1, message_id=3, status="sent", text="hello", sent_at=utcnow())
+        await app.db.ignore_post(1, 8)
+        files = []
+        real = FakeEvent.respond
+
+        async def respond(self, text=None, buttons=None, file=None, **kw):
+            files.append(file)
+            return await real(self, text, buttons, file, **kw)
+
+        monkeypatch.setattr(FakeEvent, "respond", respond)
+        await app.text("/export")
+        text = app.out.log[-1][1]
+        assert "1 channel(s), 1 post(s)" in text and "/import" in text
+        (buf,) = files
+        assert buf.name == "channel-posts-export.json"
+        data = json.loads(buf.getvalue().decode("utf-8"))
+        assert set(data) == {"exported_at", "channels", "posts", "ignored"} and data["ignored"] == [{"channel_id": 1, "message_id": 8}]
+        back = parse_backup(buf.getvalue())  # what /import reads is what /export wrote
+        assert len(back.channels) == 1 and [p["message_id"] for p in back.posts] == [3] and back.ignored == [(1, 8)]
+        await app.db.close()
+
+    run(go())
+
+
+def test_import_asks_for_the_file_and_the_owner_only(tmp_path):
+    async def go():
+        app = await started(tmp_path)
+        await app.text("/import")
+        assert "Send me the file that /export made" in norm(app.out.last_text) and "only adds" in norm(app.out.last_text)
+        assert app.ctx.state[1]["mode"] == "import"
+        await app.text("/cancel")
+        assert 1 not in app.ctx.state
+
+        app.uid = 2  # not an owner, not an admin
+        await app.text("/import")
+        assert "private" in norm(app.out.last_text) and 2 not in app.ctx.state
+        await app.db.close()
+
+    run(go())
+
+
+def test_sending_text_or_the_wrong_file_keeps_the_import_waiting(tmp_path):
+    async def go():
+        app = await started(tmp_path)
+        await app.text("/import")
+        await app.text("here you go")
+        assert "backup FILE" in norm(app.out.last_text) and app.ctx.state[1]["mode"] == "import"
+        await app.text("", message=backup_file(b"this is not json"))
+        assert "can't be imported" in norm(app.out.last_text) and "not a JSON file" in norm(app.out.last_text)
+        assert app.ctx.state[1]["mode"] == "import"  # the right file can still be sent
+        await app.text("", message=backup_file(b"{}", size=MAX_BYTES + 1))
+        assert "larger than" in norm(app.out.last_text) and app.ctx.state[1]["mode"] == "import"
+        await app.db.close()
+
+    run(go())
+
+
+def test_the_whole_import_as_a_person_does_it(tmp_path):
+    async def go():
+        app = await started(tmp_path)
+        await app.db.save_channel(1, 5, "Chan", "chan", 1)
+        await app.db.create_post(channel_id=1, message_id=10, status="sent", text="already here", sent_at=utcnow())
+        raw = backup_bytes(
+            channels=[chan(1), chan(2, title="Movies")],
+            posts=[post(1, 10), post(1, 11), post(2, 5), post(2, None, status="draft", text="a draft"), post(9, 1)],
+            ignored=[{"channel_id": 2, "message_id": 77}],
+        )
+        await app.text("/import")
+        await app.text("", message=backup_file(raw))
+        text = norm(app.out.last_text)
+        assert "Backup file read" in text and "01 Oct 2026, 12:00 UTC" in text
+        assert "Channels: 2 in the file - 1 new, 1 here already" in text
+        assert "Published posts: 4 in the file - 2 to add, 1 here already" in text  # the fourth is left out (below)
+        assert "Drafts: 1 in the file - 1 to add, 0 here already" in text
+        assert "belong to a channel that is neither here nor in the file" in text
+        assert "Nothing that is here now is changed or deleted" in text and "admin there" in text
+        assert 1 not in app.ctx.state  # waiting for the OK, not for another file
+        assert await app.db.get_channel(2) is None  # nothing happened yet
+
+        await app.press(app.out.callback_data("Import"))
+        text = norm(app.out.last_text)
+        assert "Imported" in text and "1 channel(s) added" in text and "2 published post(s) added" in text and "1 draft(s) added" in text
+        assert (await app.db.get_channel(2)).title == "Movies"
+        assert [p.message_id for p in await app.db.sent_posts(1)] == [10, 11]
+        assert (await app.db.find_by_message(1, 10)).text == "already here"
+        assert await app.db.ignored_ids(2) == {77}
+        assert not app.ctx.lock.locked() and not [k for k in app.ctx.pending]
+
+        await app.press(f"imy:{'deadbeef'}")
+        assert "expired" in norm(app.out.last_text)
+        await app.db.close()
+
+    run(go())
+
+
+def test_cancelling_the_preview_imports_nothing(tmp_path):
+    async def go():
+        app = await started(tmp_path)
+        await app.text("/import")
+        await app.text("", message=backup_file(backup_bytes(channels=[chan(1)], posts=[post(1, 3)])))
+        cancel = app.out.callback_data("Cancel")
+        await app.press(cancel)
+        assert "nothing was imported" in norm(app.out.last_text)
+        assert await app.db.get_channel(1) is None and app.ctx.pending == {}
+        await app.press(cancel.replace("imx", "imy"))  # the old Import button does not work any more
+        assert "expired" in norm(app.out.last_text)
+        await app.db.close()
+
+    run(go())
+
+
+def test_a_file_with_nothing_new_says_so_and_offers_no_button(tmp_path):
+    async def go():
+        app = await started(tmp_path)
+        await app.db.save_channel(1, 5, "Chan", "chan", 1)
+        await app.db.create_post(channel_id=1, message_id=3, status="sent", text="x", sent_at=utcnow())
+        await app.text("/import")
+        await app.text("", message=backup_file(backup_bytes(channels=[chan(1)], posts=[post(1, 3)])))
+        assert "nothing new in this file" in norm(app.out.last_text)
+        assert app.out.log[-1][2] is None and app.ctx.pending == {}
+        await app.db.close()
+
+    run(go())
+
+
+def test_the_import_waits_while_another_long_job_runs(tmp_path):
+    async def go():
+        app = await started(tmp_path)
+        await app.text("/import")
+        await app.text("", message=backup_file(backup_bytes(channels=[chan(1)], posts=[post(1, 3)])))
+        data = app.out.callback_data("Import")
+        async with app.ctx.lock:
+            await app.press(data)
+        assert "still running" in norm(app.out.last_text) and await app.db.get_channel(1) is None
+        await app.press(data)  # now it is free
+        assert "Imported" in norm(app.out.last_text) and (await app.db.get_channel(1)) is not None
+        await app.db.close()
+
+    run(go())
+
+
+def test_an_admin_who_is_not_an_owner_cannot_press_the_import_button(tmp_path):
+    async def go():
+        app = await started(tmp_path, admins=frozenset({2}))
+        await app.text("/import")
+        await app.text("", message=backup_file(backup_bytes(channels=[chan(1)], posts=[post(1, 3)])))
+        data = app.out.callback_data("Import")
+        app.uid = 2
+        await app.press(data)
+        assert await app.db.get_channel(1) is None  # refused: only owners
+        await app.db.close()
+
+    run(go())
diff --git a/tests/test_broadcast.py b/tests/test_broadcast.py
new file mode 100644
index 0000000000000000000000000000000000000000..07ffd2c9f725d954fe61726b230df88f10896aaa
--- /dev/null
+++ b/tests/test_broadcast.py
@@ -0,0 +1,473 @@
+"""/broadcast (and its spelling /boardcast): one message to every channel, optionally deleted again after a time."""
+import asyncio
+from datetime import timedelta
+from types import SimpleNamespace
+
+import pytest
+from telethon import errors, types
+
+from app.db import Channel, as_utc, utcnow
+from app.expiry import MAX_ATTEMPTS, Expirer, human, parse_duration
+from app.tgutil import button_url
+
+from .fakes import FakeChannelClient, photo_media
+from .harness import App, norm
+
+
+def run(coro):
+    return asyncio.run(coro)
+
+
+def posted(app):
+    """Messages the bot sent to channels (not to people)."""
+    return [e for e in app.tg.sent if isinstance(e[1], types.InputPeerChannel)]
+
+
+async def make_app(tmp_path, channels=2, **cfg):
+    """Channel 1 "Anime Channel" is the app's own fake; channel 2 "Movie Channel" sits next to it. Posts the bot sends
+    to a channel really appear in it, so deleting them really deletes."""
+    app = App(tmp_path, edit_delay=0, **cfg)
+    await app.start()
+    app.tg.username, app.tg.title = "animech", "Anime Channel"
+    await app.db.save_channel(1, 5, "Anime Channel", "animech", 1)
+    if channels > 1:
+        app.tg.add_channel(FakeChannelClient({}, username="moviech", cid=2, title="Movie Channel"))
+        await app.db.save_channel(2, 6, "Movie Channel", "moviech", 1)
+
+    async def send_message(peer, message="", **kw):
+        if not isinstance(peer, types.InputPeerChannel):  # a person (the preview)
+            app.tg.sent.append(("text", peer, message, kw))
+            return SimpleNamespace(id=next(app.tg.ids))
+        app.tg.sent.append(("text", peer, message, kw))
+        return app.tg.registry[peer.channel_id]._new(message, kw.get("formatting_entities"), kw.get("buttons"))
+
+    async def send_file(peer, file, **kw):
+        app.tg.sent.append(("file", peer, file, kw))
+        if not isinstance(peer, types.InputPeerChannel):
+            return SimpleNamespace(id=next(app.tg.ids))
+        return app.tg.registry[peer.channel_id]._new(kw.get("caption"), kw.get("formatting_entities"), kw.get("buttons"), media=file)
+
+    app.tg.send_message, app.tg.send_file = send_message, send_file
+    app.ctx.expirer = Expirer(app.ctx)
+    return app
+
+
+async def broadcast(app, command="/broadcast 1h", text="Hello everyone", buttons=None, message=None):
+    await app.text(command)
+    await app.text(text, message=message)
+    if buttons is None:
+        await app.press(app.out.callback_data("No buttons"))
+    else:
+        await app.text(buttons)
+    await app.press(app.out.callback_data("Send to all channels"))
+
+
+# ----------------------------------------------------------------------------------- the time
+def test_times_are_minutes_hours_days():
+    assert parse_duration("50m") == 3000
+    assert parse_duration("1h") == 3600
+    assert parse_duration("5d") == 5 * 86400
+    assert parse_duration("1d12h") == 129600
+    assert parse_duration("90 min") == 5400
+    assert parse_duration("2 Hours") == 7200
+    assert parse_duration("1w") == 604800
+    for bad in ("", "soon", "10", "h", "0m", "30s", "5x", "400d", "1h 5"):
+        with pytest.raises(ValueError):
+            parse_duration(bad)
+
+
+def test_times_are_spelled_out():
+    assert human(3000) == "50 minutes"
+    assert human(3600) == "1 hour"
+    assert human(5400) == "1 hour 30 minutes"
+    assert human(129600) == "1 day 12 hours"
+    assert human(5 * 86400) == "5 days"
+    assert human(90061) == "1 day 1 hour"
+    assert human(20) == "under a minute"
+
+
+# ----------------------------------------------------------------------------------- sending
+def test_a_timed_broadcast_goes_to_every_channel_and_is_remembered(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        before = utcnow()
+        await app.text("/broadcast 1h")
+        assert "2 channel(s)" in norm(app.out.last_text) and "1 hour" in norm(app.out.last_text)
+        await app.text("Hello everyone")
+        assert "Buttons?" in norm(app.out.last_text)
+        await app.press(app.out.callback_data("No buttons"))
+        shown = norm(app.out.last_text)
+        assert "Send it to 2 channel(s)" in shown and "Anime Channel" in shown and "Movie Channel" in shown
+        assert "Deleted again 1 hour after sending" in shown
+        # the preview went to the person, nothing to the channels yet
+        assert [e[2] for e in app.tg.sent if not isinstance(e[1], types.InputPeerChannel)] == ["Hello everyone"]
+        assert posted(app) == []
+
+        await app.press(app.out.callback_data("Send to all channels"))
+        report = norm(app.out.last_text)
+        assert "Broadcast sent to 2 of 2" in report and "✅ Anime Channel" in report and "✅ Movie Channel" in report
+        assert "deleted from these channels and from My posts in 1 hour" in report and "UTC" in report
+        assert [e[2] for e in posted(app)] == ["Hello everyone", "Hello everyone"]
+        assert app.tg.registry[1].msgs[1].message == "Hello everyone" and app.tg.registry[2].msgs[1].message == "Hello everyone"
+
+        for cid in (1, 2):  # in My posts, as published posts of the bot
+            (p,) = await app.db.sent_posts(cid)
+            assert (p.message_id, p.text, p.source, p.created_by) == (1, "Hello everyone", "bot", 1)
+        rows = await app.db.pending_deletes()
+        assert sorted((r.channel_id, r.message_id) for r in rows) == [(1, 1), (2, 1)]
+        for r in rows:
+            assert as_utc(r.delete_at) - before >= timedelta(hours=1) and as_utc(r.delete_at) - utcnow() <= timedelta(hours=1)
+        assert len({r.group_id for r in rows}) == 1
+        assert app.ctx.expirer._next is not None
+        await app.db.close()
+
+    run(go())
+
+
+def test_without_a_time_the_message_stays_and_the_other_spelling_works(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        await broadcast(app, "/boardcast")
+        report = norm(app.out.last_text)
+        assert "Broadcast sent to 2 of 2" in report and "stays in the channels" in report
+        assert await app.db.pending_deletes() == []
+        assert app.ctx.expirer._next is None
+        assert len(posted(app)) == 2
+        await app.db.close()
+
+    run(go())
+
+
+def test_buttons_and_formatting(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        bold = types.MessageEntityBold(0, 5)
+        msg = SimpleNamespace(raw_text="Hello all", entities=[bold], media=None, grouped_id=None, forward=None)
+        await app.text("/broadcast 2d")
+        await app.text("Hello all", message=msg)
+        await app.text("Join - https://t.me/animech | Site - https://example.com/x\nMore - t.me/moviech")
+        assert "Send it to 2 channel(s)" in norm(app.out.last_text) and "2 days" in norm(app.out.last_text)
+        await app.press(app.out.callback_data("Send to all channels"))
+        first = posted(app)[0]
+        assert first[2] == "Hello all"
+        assert [type(e).__name__ for e in first[3]["formatting_entities"]] == ["MessageEntityBold"]
+        rows = first[3]["buttons"].rows
+        assert [[b.text for b in r.buttons] for r in rows] == [["Join", "Site"], ["More"]]
+        assert button_url(rows[1].buttons[0]) == "https://t.me/moviech"
+        (p,) = await app.db.sent_posts(2)
+        assert p.buttons == [[{"t": "Join", "u": "https://t.me/animech"}, {"t": "Site", "u": "https://example.com/x"}], [{"t": "More", "u": "https://t.me/moviech"}]]
+        assert p.entities == [{"k": "bold", "o": 0, "l": 5}]
+        await app.db.close()
+
+    run(go())
+
+
+def test_a_photo_with_a_caption(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        msg = SimpleNamespace(raw_text="New poster", entities=[], media=photo_media(5), grouped_id=None, forward=None)
+        await broadcast(app, "/broadcast 30m", "New poster", message=msg)
+        files = [e for e in posted(app) if e[0] == "file"]
+        assert len(files) == 2 and files[0][3]["caption"] == "New poster"
+        got = app.tg.registry[2].msgs[1]
+        assert got.message == "New poster" and isinstance(got.media, types.MessageMediaPhoto)
+        (p,) = await app.db.sent_posts(2)
+        assert p.media_kind == "photo" and p.media_file_id.startswith("tl:") and p.text == "New poster"
+        await app.db.close()
+
+    run(go())
+
+
+def test_a_channel_that_refuses_does_not_stop_the_others(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        real = app.tg.send_message
+
+        async def picky(peer, message="", **kw):
+            if getattr(peer, "channel_id", None) == 2:
+                raise errors.ChatWriteForbiddenError(request=None)
+            return await real(peer, message, **kw)
+
+        app.tg.send_message = picky
+        await broadcast(app, "/broadcast 1h")
+        report = norm(app.out.last_text)
+        assert "sent to 1 of 2" in report and "✅ Anime Channel" in report
+        assert "❌ Movie Channel" in report and "ChatWriteForbiddenError" in report
+        assert [r.channel_id for r in await app.db.pending_deletes()] == [1]  # only what was sent expires
+        assert await app.db.sent_posts(2) == []
+        await app.db.close()
+
+    run(go())
+
+
+def test_only_the_owner_and_only_good_input(tmp_path):
+    async def go():
+        app = await make_app(tmp_path, admins=frozenset({7}))
+        app.uid = 7
+        await app.text("/broadcast 1h")
+        assert "private" in app.out.last_text and 7 not in app.ctx.state
+        app.uid = 1
+        await app.text("/broadcast soon")
+        assert "can't read" in norm(app.out.last_text) and 1 not in app.ctx.state
+        await app.text("/broadcast 20s")
+        assert "don't know the unit" in norm(app.out.last_text)
+        await app.text("/broadcast 400d")
+        assert "1 year" in app.out.last_text
+        # an admin cannot press the owner's buttons either
+        await app.text("/broadcast 1h")
+        await app.text("Hi")
+        await app.press(app.out.callback_data("No buttons"))
+        confirm = app.out.callback_data("Send to all channels")
+        app.uid = 7
+        await app.press(confirm)
+        assert "Only the bot owner" in app.out.last_text and posted(app) == []
+        await app.db.close()
+
+    run(go())
+
+
+def test_nothing_is_sent_without_a_yes_and_a_button_works_once(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        await app.text("/broadcast")
+        await app.text("Hi")
+        await app.press(app.out.callback_data("No buttons"))
+        await app.press(app.out.callback_data("Cancel"))
+        assert "Cancelled" in app.out.last_text and posted(app) == []
+
+        await app.text("/broadcast")
+        await app.text("Hi")
+        await app.press(app.out.callback_data("No buttons"))
+        send = app.out.callback_data("Send to all channels")
+        await app.press(send)
+        await app.press(send)
+        assert "expired" in app.out.last_text
+        assert len(posted(app)) == 2
+        await app.db.close()
+
+    run(go())
+
+
+def test_wrong_buttons_and_a_busy_bot_are_explained(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        await app.text("/broadcast 1h")
+        await app.text("Hi")
+        await app.text("no link here")
+        assert "Try again" in norm(app.out.last_text)
+        await app.text("Go - https://t.me/x")
+        send = app.out.callback_data("Send to all channels")
+        await app.ctx.lock.acquire()
+        await app.press(send)
+        assert "still running" in app.out.last_text and posted(app) == []
+        app.ctx.lock.release()
+        await app.press(send)
+        assert len(posted(app)) == 2
+        await app.db.close()
+
+    run(go())
+
+
+def test_no_channels_no_broadcast(tmp_path):
+    async def go():
+        app = App(tmp_path, edit_delay=0)
+        await app.start()
+        await app.text("/broadcast 1h")
+        assert "No channels yet" in app.out.last_text
+        await app.db.close()
+
+    run(go())
+
+
+# ------------------------------------------------------------------------------------ deleting
+async def timed_broadcast(app, command="/broadcast 1h"):
+    await broadcast(app, command)
+    return utcnow()
+
+
+def test_when_the_time_is_up_the_message_goes_from_the_channels_and_my_posts(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        now = await timed_broadcast(app)
+        ex = app.ctx.expirer
+
+        early = await ex.sweep(now=now + timedelta(minutes=59))
+        assert early["deleted"] == 0 and 1 in app.tg.registry[1].msgs
+        assert len(await app.db.sent_posts(1)) == 1
+
+        done = await ex.sweep(now=now + timedelta(hours=1, minutes=1))
+        assert done["deleted"] == 2 and done["retry"] == 0 and done["failed"] == 0
+        assert app.tg.registry[1].msgs == {} and app.tg.registry[2].msgs == {}
+        assert await app.db.sent_posts(1) == [] and await app.db.sent_posts(2) == []
+        assert await app.db.pending_deletes() == []
+        assert ex._next is None  # nothing left: the loop sleeps until something new is scheduled
+        await app.db.close()
+
+    run(go())
+
+
+def test_other_posts_are_not_touched_and_a_message_deleted_by_hand_is_fine(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        keep = await app.db.create_post(channel_id=1, message_id=50, status="sent", source="bot", text="keep me", entities=[], buttons=[])
+        now = await timed_broadcast(app)
+        app.tg.registry[2].msgs.pop(1)  # an admin deleted the broadcast in channel 2 already
+        done = await app.ctx.expirer.sweep(now=now + timedelta(hours=2))
+        assert done["deleted"] == 2
+        assert (await app.db.get_post(keep.id)) is not None
+        assert [p.message_id for p in await app.db.sent_posts(1)] == [50]
+        assert await app.db.sent_posts(2) == []
+        await app.db.close()
+
+    run(go())
+
+
+def test_a_restart_loses_nothing(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        now = await timed_broadcast(app, "/broadcast 5d")
+        due = now + timedelta(days=5)
+        fresh = Expirer(app.ctx)  # a new process: it knows nothing but the database
+        assert fresh._next is None
+        await fresh.load()
+        assert abs((fresh._next - due).total_seconds()) < 30
+        # it was off for a week: everything that came due is deleted when it is back
+        await fresh.sweep(now=now + timedelta(days=7))
+        assert app.tg.registry[1].msgs == {} and app.tg.registry[2].msgs == {}
+        assert await app.db.sent_posts(1) == []
+        await app.db.close()
+
+    run(go())
+
+
+def test_the_background_loop_wakes_when_something_is_scheduled_and_when_it_is_due(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        ex = app.ctx.expirer
+        ex.start()
+        await asyncio.sleep(0.05)  # idle: nothing to do, nothing polled
+        msg = app.tg._new("soon gone", None, None)
+        when = utcnow() + timedelta(seconds=0.4)
+        await app.db.schedule_deletes([dict(channel_id=1, message_id=msg.id, delete_at=when, group_id="g", created_by=1)])
+        ex.notify(when)
+        for _ in range(60):
+            if msg.id not in app.tg.msgs:
+                break
+            await asyncio.sleep(0.05)
+        assert msg.id not in app.tg.msgs
+        await ex.stop()
+        await app.db.close()
+
+    run(go())
+
+
+def test_something_already_overdue_is_deleted_at_start(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        msg = app.tg._new("overdue", None, None)
+        await app.db.schedule_deletes([dict(channel_id=1, message_id=msg.id, delete_at=utcnow() - timedelta(hours=3), group_id="g", created_by=1)])
+        ex = Expirer(app.ctx)
+        ex.start()
+        for _ in range(60):
+            if msg.id not in app.tg.msgs:
+                break
+            await asyncio.sleep(0.05)
+        assert msg.id not in app.tg.msgs
+        await ex.stop()
+        await app.db.close()
+
+    run(go())
+
+
+def test_a_running_job_makes_it_wait(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        now = await timed_broadcast(app)
+        ex = app.ctx.expirer
+        await app.ctx.lock.acquire()
+        later = now + timedelta(hours=2)
+        out = await ex.sweep(now=later)
+        assert out["waiting"] and out["deleted"] == 0 and 1 in app.tg.registry[1].msgs
+        assert 50 <= (ex._next - later).total_seconds() <= 70
+        app.ctx.lock.release()
+        out = await ex.sweep(now=later)
+        assert out["deleted"] == 2
+        await app.db.close()
+
+    run(go())
+
+
+def test_what_the_bot_cannot_delete_is_retried_then_reported(tmp_path):
+    async def go():
+        app = await make_app(tmp_path, channels=1)
+        now = await timed_broadcast(app)
+        app.tg.undeletable = {1}  # Telegram refuses (an old post)
+        ex = app.ctx.expirer
+        t = now + timedelta(hours=2)
+        for attempt in range(1, MAX_ATTEMPTS):
+            out = await ex.sweep(now=t)
+            assert out["retry"] == 1 and out["failed"] == 0, attempt
+            (row,) = await app.db.pending_deletes()
+            assert row.attempts == attempt and as_utc(row.delete_at) > t
+            t = as_utc(row.delete_at) + timedelta(seconds=1)
+        dms_before = len([e for e in app.tg.sent if not isinstance(e[1], types.InputPeerChannel)])
+        out = await ex.sweep(now=t)
+        assert out["failed"] == 1
+        assert await app.db.pending_deletes() == []
+        (row,) = await app.db.pending_deletes(status="failed")
+        assert row.attempts == MAX_ATTEMPTS and row.last_error
+        # the person who sent it is told; the post stays in My posts because it is still in the channel
+        told = [e for e in app.tg.sent if not isinstance(e[1], types.InputPeerChannel)][dms_before:]
+        assert told and "could not delete the expired broadcast" in told[-1][2]
+        assert len(await app.db.sent_posts(1)) == 1
+        assert ex._next is None
+        await app.db.close()
+
+    run(go())
+
+
+def test_the_userbot_deletes_what_the_bot_may_not(tmp_path):
+    async def go():
+        app = await make_app(tmp_path, channels=1)
+        now = await timed_broadcast(app)
+        app.tg.undeletable = {1}
+        calls, closed = [], []
+
+        class StubUserbot:
+            enabled = True
+
+            async def fallback_for(self, ch):
+                async def fn(ids):
+                    calls.append(list(ids))
+                    for i in ids:
+                        app.tg.msgs.pop(i, None)
+
+                async def close():
+                    closed.append(1)
+
+                return fn, SimpleNamespace(close=close)
+
+        app.ctx.userbot = StubUserbot()
+        out = await app.ctx.expirer.sweep(now=now + timedelta(hours=2))
+        assert out["deleted"] == 1 and calls == [[1]] and closed == [1]
+        assert app.tg.msgs == {} and await app.db.sent_posts(1) == []
+        await app.db.close()
+
+    run(go())
+
+
+def test_a_channel_taken_out_of_the_bot_is_reported_not_retried_forever(tmp_path):
+    async def go():
+        app = await make_app(tmp_path, channels=1)
+        now = await timed_broadcast(app)
+        for post in await app.db.sent_posts(1):  # a real database refuses to drop a channel its posts still point at
+            await app.db.delete_post(post.id)
+        async with app.db.Session() as s:
+            await s.delete(await s.get(Channel, 1))
+            await s.commit()
+        out = await app.ctx.expirer.sweep(now=now + timedelta(hours=2))
+        assert out["failed"] == 1 and out["deleted"] == 0
+        assert await app.db.pending_deletes() == []
+        await app.db.close()
+
+    run(go())
diff --git a/tests/test_buttons_sync.py b/tests/test_buttons_sync.py
new file mode 100644
index 0000000000000000000000000000000000000000..2037c4fa93bba586a7943b7f82a33847519dfda4
--- /dev/null
+++ b/tests/test_buttons_sync.py
@@ -0,0 +1,196 @@
+"""Checking and repairing the buttons a channel really shows."""
+import asyncio
+
+import pytest
+
+from app.buttons_sync import ButtonsNotShown, ensure_markup, fix_buttons, link_urls, scan_buttons
+from app.tgutil import build_markup, button_url, peer_of
+
+from .dbutil import db_url_for, fresh_db
+from .fakes import FakeChannelClient, make_msg, markup, rpc, url_btn
+from .harness import App, norm
+
+A = "https://t.me/goku?start=A"
+B = "https://t.me/goku?start=B"
+ROWS = [[{"t": "Get", "u": A}], [{"t": "More", "u": B}]]
+
+
+def shown(chan, i):
+    m = chan.msgs[i]
+    return [button_url(b) for r in (m.reply_markup.rows if m.reply_markup else []) for b in r.buttons]
+
+
+class Peer:
+    id, access_hash = 1, 5
+
+
+def run(coro):
+    return asyncio.run(coro)
+
+
+def test_link_urls():
+    assert link_urls(None) == []
+    assert link_urls(markup([url_btn("x", A), url_btn("y", B)])) == [A, B]
+
+
+def test_ensure_markup_in_every_situation():
+    async def go():
+        want = build_markup(ROWS)
+        peer = peer_of(Peer)
+
+        chan = FakeChannelClient({1: make_msg(1, "ok", markup=want)})
+        assert await ensure_markup(chan, peer, 1, want, pause=0) == "fine"
+        assert chan.edits == []
+
+        chan = FakeChannelClient({1: make_msg(1, "no keyboard")})  # simply missing: one edit is enough
+        assert await ensure_markup(chan, peer, 1, want, pause=0) == "set"
+        assert shown(chan, 1) == [A, B] and len(chan.edits) == 1 and chan.msgs[1].message == "no keyboard"
+
+        chan = FakeChannelClient({1: make_msg(1, "hidden")})  # Telegram believes the keyboard is there already
+        chan.msgs[1]._hidden = want
+        assert await ensure_markup(chan, peer, 1, want, pause=0) == "nudged"
+        assert shown(chan, 1) == [A, B] and len(chan.edits) == 2
+
+        chan = FakeChannelClient({})
+        with pytest.raises(LookupError):
+            await ensure_markup(chan, peer, 1, want, pause=0)
+
+        chan = FakeChannelClient({1: make_msg(1, "x")})
+        chan.drop_all_markup = True  # edits are accepted but the keyboard never appears
+        with pytest.raises(ButtonsNotShown):
+            await ensure_markup(chan, peer, 1, want, pause=0)
+
+        chan = FakeChannelClient({1: make_msg(1, "x")})  # nothing to show -> nothing to do
+        assert await ensure_markup(chan, peer, 1, None, pause=0) == "fine" and chan.requests == []
+
+    run(go())
+
+
+async def seeded(tmp_path):
+    """Channel + database as /repost used to leave them: the database knows the buttons, the channel may not show them."""
+    db = await fresh_db(db_url_for(tmp_path))
+    await db.save_channel(1, 5, "Test", "testch", 99)
+    ch = await db.get_channel(1)
+    want = build_markup(ROWS)
+    msgs = {
+        10: make_msg(10, "fine", markup=want),
+        11: make_msg(11, "missing"),
+        12: make_msg(12, "hidden"),
+        13: make_msg(13, "other link", markup=markup([url_btn("Get", "https://t.me/other?start=Z")])),
+        15: make_msg(15, "no buttons saved"),
+    }
+    chan = FakeChannelClient(msgs)
+    chan.msgs[12]._hidden = want
+    for i in (10, 11, 12, 13, 14):  # 14 was deleted by hand
+        await db.create_post(channel_id=1, message_id=i, status="sent", source="bot", text="t", entities=[], buttons=ROWS)
+    await db.create_post(channel_id=1, message_id=15, status="sent", source="bot", text="t", entities=[], buttons=[])
+    await db.create_post(channel_id=1, message_id=None, status="draft", source="bot", text="draft", entities=[], buttons=ROWS)
+    return db, ch, chan
+
+
+def test_scan_finds_exactly_the_posts_with_wrong_buttons(tmp_path):
+    async def go():
+        db, ch, chan = await seeded(tmp_path)
+        scan = await scan_buttons(chan, ch, await db.sent_posts(1))
+        assert scan.total == 5  # 10..14 have saved link buttons; 15 and the draft do not count
+        assert scan.fine == 1
+        assert sorted(p.message_id for p, _, _ in scan.bad) == [11, 12, 13]
+        assert [p.message_id for p in scan.gone] == [14]
+        live13 = next(live for p, live, _ in scan.bad if p.message_id == 13)
+        assert live13 == ["https://t.me/other?start=Z"]
+        await db.close()
+
+    run(go())
+
+
+def test_fix_puts_the_saved_buttons_back(tmp_path):
+    async def go():
+        db, ch, chan = await seeded(tmp_path)
+        scan = await scan_buttons(chan, ch, await db.sent_posts(1))
+        res = await fix_buttons(chan, ch, scan.bad, delay=0, pause=0)
+        assert (res.fixed, res.nudged, res.already, res.gone, res.failed, res.aborted) == (3, 1, 0, 0, [], None)
+        for i in (10, 11, 12, 13):
+            assert shown(chan, i) == [A, B]
+        assert chan.msgs[11].message == "missing"  # texts untouched
+        again = await scan_buttons(chan, ch, await db.sent_posts(1))
+        assert again.bad == [] and again.fine == 4 and len(again.gone) == 1
+        await db.close()
+
+    run(go())
+
+
+def test_fix_gives_up_after_several_identical_refusals(tmp_path):
+    async def go():
+        db = await fresh_db(db_url_for(tmp_path))
+        await db.save_channel(1, 5, "Test", "testch", 99)
+        ch = await db.get_channel(1)
+        chan = FakeChannelClient({i: make_msg(i, "x") for i in range(1, 9)})
+        chan.fail["EditMessageRequest"] = rpc("MessageIdInvalidError")
+        for i in range(1, 9):
+            await db.create_post(channel_id=1, message_id=i, status="sent", source="bot", text="x", entities=[], buttons=ROWS)
+        scan = await scan_buttons(chan, ch, await db.sent_posts(1))
+        res = await fix_buttons(chan, ch, scan.bad, delay=0, pause=0)
+        assert res.fixed == 0 and len(res.failed) == 5 and res.aborted == "MessageIdInvalidError"
+        await db.close()
+
+    run(go())
+
+
+# ------------------------------------------------------------------------------------------ the button in My posts
+def test_check_buttons_in_my_posts(tmp_path):
+    async def go():
+        app = App(tmp_path)
+        await app.start()
+        db, ch, chan = await seeded_app(app)
+        await app.press("pc:1:0")
+        assert "Check buttons" in str(app.out.last_buttons())
+        await app.press("pk:1")
+        t = norm(app.out.last_text)
+        assert "checked 5 post(s)" in t and "1 show their buttons correctly" in t and "3 are saved with buttons" in t
+        assert "#11" in t and "#12" in t and "#13" in t and "1 saved post(s) no longer exist" in t
+        assert "Fix 3 post(s)" in str(app.out.last_buttons())
+        await app.press(app.out.callback_data("Fix 3"))
+        t = norm(app.out.last_text)
+        assert "put the saved buttons back on 3 post(s)" in t and "1 of them needed a second edit" in t
+        for i in (10, 11, 12, 13):
+            assert shown(app.tg, i) == [A, B]
+        await app.press("pk:1")
+        assert "Everything matches" in norm(app.out.last_text) and "Fix" not in str(app.out.last_buttons())
+        await app.db.close()
+
+    run(go())
+
+
+async def seeded_app(app):
+    await app.db.save_channel(1, 5, "Anime Channel", "animech", 1)
+    want = build_markup(ROWS)
+    app.tg.msgs.update(
+        {
+            10: make_msg(10, "fine", markup=want),
+            11: make_msg(11, "missing"),
+            12: make_msg(12, "hidden"),
+            13: make_msg(13, "other link", markup=markup([url_btn("Get", "https://t.me/other?start=Z")])),
+            15: make_msg(15, "no buttons saved"),
+        }
+    )
+    app.tg.msgs[12]._hidden = want
+    for i in (10, 11, 12, 13, 14):
+        await app.db.create_post(channel_id=1, message_id=i, status="sent", source="bot", text="t", entities=[], buttons=ROWS)
+    return app.db, None, app.tg
+
+
+def test_check_buttons_is_for_the_owner_only(tmp_path):
+    async def go():
+        app = App(tmp_path, owner=1, admins=frozenset({2}))
+        await app.start()
+        await seeded_app(app)
+        app.uid = 2  # an admin who may make posts but is not the owner
+        await app.press("pc:1:0")
+        assert "Check buttons" not in str(app.out.last_buttons())
+        await app.press("pk:1")
+        assert "Only the bot owner" in app.out.last_text
+        await app.press("pkf:1")
+        assert "Only the bot owner" in app.out.last_text
+        await app.db.close()
+
+    run(go())
diff --git a/tests/test_channel_data.py b/tests/test_channel_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..c28558cff5e0bd610b9093e15c4212eacfd4ad62
--- /dev/null
+++ b/tests/test_channel_data.py
@@ -0,0 +1,194 @@
+"""Taking a channel out of the bot: the bot asks whether the channel's saved posts (its data in My posts) are deleted as
+well - Yes removes the channel and the data, No removes only the channel and keeps the data."""
+import asyncio
+
+from app.db import utcnow
+from app.sync_engine import sync_channel
+
+from .harness import App, norm
+from .test_sync import old_msg, opts, world
+
+
+def run(coro):
+    return asyncio.run(coro)
+
+
+async def make_app(tmp_path, **cfg):
+    """Two channels: "Anime Channel" (id 1) has three published posts and a draft, "Other Channel" (id 2) has two posts;
+    channel 1 also has what the sync keeps (where it stopped, a post it must forget) and a timed deletion."""
+    app = App(tmp_path, edit_delay=0, **cfg)
+    await app.start()
+    await app.db.save_channel(1, 5, "Anime Channel", "animech", 1)
+    await app.db.save_channel(2, 6, "Other Channel", "otherch", 1)
+    for cid, n in ((1, 3), (2, 2)):
+        for i in range(1, n + 1):
+            await app.db.create_post(
+                channel_id=cid, message_id=i, status="sent", source="adopted", text=f"post {cid}/{i}", entities=[], buttons=[]
+            )
+    await app.db.create_post(channel_id=1, status="draft", source="bot", text="a draft", entities=[], buttons=[])
+    for cid in (1, 2):
+        await app.db.save_sync(cid, last_top=3, last_pts=3)
+        await app.db.start_history(cid, 3)
+        await app.db.ignore_post(cid, 9)
+        app.ctx.sync_ignore.add((cid, 9))
+    await app.db.schedule_deletes(
+        [dict(channel_id=1, message_id=2, delete_at=utcnow(), group_id="g", created_by=1)]
+    )
+    return app
+
+
+async def tap_channel(app, label_part="1"):
+    await app.text("/channels")
+    await app.press(app.out.callback_exact(label_part))
+
+
+# ============================================================================================ the question
+def test_the_owner_is_asked_whether_the_saved_posts_go_too(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        await tap_channel(app)
+        text = norm(app.out.last_text)
+        assert "Take Anime Channel out of the bot" in text
+        assert "Do you also want to delete its saved posts" in text and "4 post(s)" in text  # three published + a draft
+        assert "Nothing is deleted in the channel itself" in text
+        assert app.out.last_buttons() == [["🗑 Yes, delete them too", "📦 No, keep them"], ["🔙 Back"]]
+        # the question alone changes nothing
+        assert [c.id for c in await app.db.list_channels()] == [1, 2] and await app.db.count_channel_posts(1) == 4
+        await app.press(app.out.callback_exact("🔙 Back"))
+        assert "Your channels" in norm(app.out.last_text)
+        await app.db.close()
+
+    run(go())
+
+
+def test_a_channel_without_saved_posts_has_nothing_to_ask(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        await app.db.save_channel(3, 7, "Empty Channel", "emptych", 1)
+        await app.text("/channels")
+        await app.press(app.out.callback_exact("2"))  # Anime, Empty, Other: the second one
+        text = norm(app.out.last_text)
+        assert "Take Empty Channel out of the bot?" in text and "no saved posts" in text
+        assert app.out.last_buttons() == [["✅ Yes, remove it", "🔙 Back"]]
+        await app.press(app.out.callback_exact("✅ Yes, remove it"))
+        assert [c.id for c in await app.db.list_channels()] == [1, 2]
+        await app.db.close()
+
+    run(go())
+
+
+# ================================================================================================ yes
+def test_yes_removes_the_channel_and_deletes_its_saved_posts(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        await tap_channel(app)
+        await app.press(app.out.callback_data("Yes, delete them too"))
+        text = norm(app.out.last_text)
+        assert "Anime Channel was removed from the bot" in text and "4 saved post(s) were deleted from My posts" in text
+        assert "Nothing was deleted in the channel" in text
+        assert [c.id for c in await app.db.list_channels()] == [2]
+        row = await app.db.get_channel(1)
+        assert row is not None and not row.active  # switched off, not erased: a repost or shift that names it still finds it
+        assert await app.db.count_channel_posts(1) == 0 and await app.db.sent_posts(1) == []
+        _, total = await app.db.list_posts(1, "draft", 0, 10)
+        assert total == 0
+        # what the sync kept about the channel goes too, so it starts from scratch when it is added again
+        assert await app.db.get_sync(1) is None and await app.db.get_history(1) is None
+        assert await app.db.ignored_ids(1) == set() and not any(k[0] == 1 for k in app.ctx.sync_ignore)
+        # ... and nothing of the other channel is touched
+        assert await app.db.count_channel_posts(2) == 2
+        assert await app.db.get_sync(2) is not None and await app.db.get_history(2) is not None
+        assert await app.db.ignored_ids(2) == {9} and (2, 9) in app.ctx.sync_ignore
+        # a timed deletion is a promise about a message that is still in the channel: it stays
+        assert [r.message_id for r in await app.db.pending_deletes()] == [2]
+        await app.db.close()
+
+    run(go())
+
+
+def test_nothing_is_deleted_in_telegram_when_the_data_goes(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        before = len(app.tg.requests)
+        await tap_channel(app)
+        await app.press(app.out.callback_data("Yes, delete them too"))
+        assert app.tg.deleted == [] and len(app.tg.requests) == before
+        await app.db.close()
+
+    run(go())
+
+
+def test_the_posts_are_not_deleted_while_a_look_at_the_channels_is_running(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        lock = app.ctx.syncer.exclusive()
+        await lock.acquire()  # a look at the channels is in progress: it could save posts again
+        task = asyncio.create_task(app.press("chy:1:1"))
+        await asyncio.sleep(0.2)
+        assert not task.done() and await app.db.count_channel_posts(1) == 4
+        lock.release()
+        await task
+        assert await app.db.count_channel_posts(1) == 0
+        await app.db.close()
+
+    run(go())
+
+
+# =================================================================================================== no
+def test_no_removes_only_the_channel_and_keeps_its_saved_posts(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        await tap_channel(app)
+        await app.press(app.out.callback_data("No, keep them"))
+        text = norm(app.out.last_text)
+        assert "Anime Channel was removed from the bot" in text and "saved posts are kept" in text
+        assert [c.id for c in await app.db.list_channels()] == [2]
+        assert await app.db.count_channel_posts(1) == 4 and await app.db.get_sync(1) is not None
+        assert await app.db.ignored_ids(1) == {9} and (1, 9) in app.ctx.sync_ignore
+        # added again: everything is there again
+        await app.db.save_channel(1, 5, "Anime Channel", "animech", 1)
+        assert [c.id for c in await app.db.list_channels()] == [1, 2] and await app.db.count_channel_posts(1) == 4
+        await app.db.close()
+
+    run(go())
+
+
+def test_a_button_from_the_old_question_still_removes_only_the_channel(tmp_path):
+    async def go():
+        app = await make_app(tmp_path)
+        await app.press("chy:1")  # what the earlier version of the bot put on its button
+        assert [c.id for c in await app.db.list_channels()] == [2]
+        assert await app.db.count_channel_posts(1) == 4
+        assert "saved posts are kept" in norm(app.out.last_text)
+        await app.db.close()
+
+    run(go())
+
+
+# ============================================================================================ who may do it
+def test_only_an_owner_can_remove_a_channel_or_delete_its_data(tmp_path):
+    async def go():
+        app = await make_app(tmp_path, owner=7, admins=frozenset({1}))
+        app.uid = 1  # an admin, not an owner
+        for data in ("chd:1", "chy:1:1", "chy:1:0", "chy:1"):
+            await app.press(data)
+        assert [c.id for c in await app.db.list_channels()] == [1, 2] and await app.db.count_channel_posts(1) == 4
+        await app.db.close()
+
+    run(go())
+
+
+# ========================================================================================= coming back
+def test_a_channel_that_comes_back_after_its_data_was_deleted_is_read_in_again(tmp_path):
+    async def go():
+        chan, db, ch = await world(tmp_path, {i: old_msg(i, f"older post {i}") for i in range(1, 6)}, save=False)
+        rep = await sync_channel(chan, db, ch, opts())
+        assert rep.first_look and rep.imported == 5
+        assert await db.delete_channel_data(1) == 5
+        assert await db.sent_posts(1) == [] and await db.get_sync(1) is None and await db.get_history(1) is None
+        rep = await sync_channel(chan, db, ch, opts())  # as if it had never been looked at
+        assert rep.first_look and rep.imported == 5 and rep.history_done
+        assert len(await db.sent_posts(1)) == 5
+        await db.close()
+
+    run(go())
diff --git a/tests/test_config.py b/tests/test_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..328608f3af21829dad2d9066193bdb21a20295b6
--- /dev/null
+++ b/tests/test_config.py
@@ -0,0 +1,302 @@
+"""Settings from the environment, the deployment files, and that nothing the owner needs is left undocumented."""
+import asyncio
+import py_compile
+import re
+import socket
+import tempfile
+from pathlib import Path
+
+import pytest
+
+from app.config import DEFAULT_ERROR_LOG_CHAT_ID, Config, default_session_path, load_config
+from app.health import start_health_server
+from bot import COMMANDS, secrets_of
+
+from .harness import App
+
+ROOT = Path(__file__).resolve().parent.parent
+REQUIRED = {"API_ID": "12345", "API_HASH": "abcdef0123456789", "BOT_TOKEN": "123456:ABCdefGHIjklMNOpqrSTUvwxYZ", "OWNER_IDS": "1001484109"}
+
+
+def env_names() -> list:
+    """Every environment variable app/config.py reads."""
+    src = (ROOT / "app" / "config.py").read_text()
+    names = set(re.findall(r'(?:getenv|_ints|_bool|_chat_id|_float|_whole)\(\s*"([A-Z][A-Z0-9_]+)"', src))
+    names |= set(re.findall(r'environ\[\s*"([A-Z][A-Z0-9_]+)"', src))
+    return sorted(names)
+
+
+@pytest.fixture
+def env(monkeypatch):
+    for k in env_names():
+        monkeypatch.delenv(k, raising=False)
+    for k, v in REQUIRED.items():
+        monkeypatch.setenv(k, v)
+    return monkeypatch
+
+
+# ----------------------------------------------------------------------------------------- defaults
+def test_the_names_the_test_looks_for_are_all_found():
+    names = env_names()
+    for expected in ("API_ID", "BOT_TOKEN", "OWNER_IDS", "ERROR_LOG_CHAT_ID", "USERBOT_SESSION", "USERBOT_KEEP_ADMIN", "SESSION_PATH", "PORT"):
+        assert expected in names, names
+
+
+def test_defaults(env):
+    cfg = load_config()
+    assert cfg.error_log_chat_id == DEFAULT_ERROR_LOG_CHAT_ID == -1002525172451
+    assert cfg.userbot_session == "" and cfg.userbot_keep_admin is False
+    assert cfg.owners == frozenset({1001484109}) and cfg.admins == frozenset()
+    assert cfg.edit_delay == 1.2 and cfg.replace_typed_links is True and cfg.port == 0
+    assert cfg.database_url.startswith("sqlite")
+
+
+@pytest.mark.parametrize(
+    "raw,expected",
+    [
+        (None, -1002525172451),  # not set at all -> the default chat
+        ("", -1002525172451),
+        ("   ", -1002525172451),
+        ("-1001234567890", -1001234567890),
+        (" -1001234567890 ", -1001234567890),
+        ("123456789", 123456789),  # a private chat with a person
+        ("0", None),
+        ("off", None),
+        ("OFF", None),
+        ("None", None),
+        ("false", None),
+        ("no", None),
+        ("disabled", None),
+    ],
+)
+def test_error_log_chat_id(env, raw, expected):
+    if raw is not None:
+        env.setenv("ERROR_LOG_CHAT_ID", raw)
+    assert load_config().error_log_chat_id == expected
+
+
+@pytest.mark.parametrize("raw", ["abc", "-100 123", "@mychannel", "1.5"])
+def test_a_bad_error_log_chat_id_is_refused_with_its_name(env, raw):
+    env.setenv("ERROR_LOG_CHAT_ID", raw)
+    with pytest.raises(SystemExit) as e:
+        load_config()
+    assert "ERROR_LOG_CHAT_ID" in str(e.value) and repr(raw) in str(e.value)
+
+
+def test_userbot_settings(env):
+    env.setenv("USERBOT_SESSION", "  1BVtsOKwBu7abc  ")
+    env.setenv("USERBOT_KEEP_ADMIN", "true")
+    cfg = load_config()
+    assert cfg.userbot_session == "1BVtsOKwBu7abc" and cfg.userbot_keep_admin is True
+    for v, want in [("1", True), ("yes", True), ("ON", True), ("false", False), ("0", False), ("", False), ("nonsense", False)]:
+        env.setenv("USERBOT_KEEP_ADMIN", v)
+        assert load_config().userbot_keep_admin is want, v
+
+
+def test_missing_settings_are_listed(env):
+    env.delenv("API_HASH")
+    env.delenv("OWNER_IDS")
+    with pytest.raises(SystemExit) as e:
+        load_config()
+    assert "API_HASH" in str(e.value) and "OWNER_IDS" in str(e.value) and "API_ID" not in str(e.value)
+    env.setenv("OWNER_IDS", "not a number")
+    env.setenv("API_HASH", "x")
+    with pytest.raises(SystemExit) as e:
+        load_config()
+    assert "OWNER_IDS" in str(e.value)
+
+
+def test_api_id_must_be_a_number(env):
+    env.setenv("API_ID", "twelve")
+    with pytest.raises(SystemExit) as e:
+        load_config()
+    assert "API_ID must be a number" in str(e.value)
+
+
+def test_service_message_and_sync_settings(env):
+    cfg = load_config()
+    assert cfg.delete_service_messages is True and cfg.sync_interval_minutes == 60  # both are on unless somebody says otherwise
+    env.setenv("DELETE_SERVICE_MESSAGES", "false")
+    env.setenv("SYNC_INTERVAL_MINUTES", "15")
+    cfg = load_config()
+    assert cfg.delete_service_messages is False and cfg.sync_interval_minutes == 15
+    env.setenv("DELETE_SERVICE_MESSAGES", "yes")
+    assert load_config().delete_service_messages is True
+
+
+def test_the_older_posts_of_a_channel_are_imported_unless_somebody_says_otherwise(env):
+    assert load_config().import_old_posts is True
+    env.setenv("IMPORT_OLD_POSTS", "false")
+    assert load_config().import_old_posts is False
+    env.setenv("IMPORT_OLD_POSTS", "")
+    assert load_config().import_old_posts is True
+
+
+@pytest.mark.parametrize(
+    "raw,expected",
+    [("0", 0), ("-5", 0), ("30", 30), ("2.9", 2), ("  45 ", 45), ("", 60), ("abc", 60), ("inf", 60), ("-inf", 60), ("nan", 60)],
+)
+def test_sync_interval_minutes_never_stops_the_bot_from_starting(env, raw, expected):
+    env.setenv("SYNC_INTERVAL_MINUTES", raw)
+    assert load_config().sync_interval_minutes == expected  # 0 = no automatic checks; nonsense = the default
+
+
+def test_edit_delay_has_a_floor(env):
+    env.setenv("EDIT_DELAY", "0.1")
+    assert load_config().edit_delay == 0.3
+    env.setenv("EDIT_DELAY", "banana")
+    assert load_config().edit_delay == 1.2
+    env.setenv("EDIT_DELAY", "2.5")
+    assert load_config().edit_delay == 2.5
+
+
+def test_the_session_is_not_kept_in_the_app_folder_by_default(env):
+    path = Path(load_config().session_path).resolve()
+    assert str(path).startswith(str(Path(tempfile.gettempdir()).resolve()))
+    assert ROOT not in path.parents  # an app folder that a web server publishes must not contain the login
+    assert Path(default_session_path()).name == "bot"
+    env.setenv("SESSION_PATH", "data/bot")
+    assert load_config().session_path == "data/bot"  # still possible when somebody wants it
+
+
+# ------------------------------------------------------------------------------ secrets of the bot
+def test_every_secret_is_collected_for_redaction():
+    cfg = Config(
+        api_id=1, api_hash="HASHHASHHASH", bot_token="123:TOKEN-TOKEN", owners=frozenset({1}), admins=frozenset(),
+        database_url="postgresql://user:p%40ss%2Fword@host.example/db?sslmode=require", db_pool="null", session_path="x",
+        session_string="SESSIONSTRINGTEXT", edit_delay=1.0, replace_typed_links=True, port=0, log_level="INFO",
+        userbot_session="USERBOTSESSIONTEXT",
+    )
+    found = secrets_of(cfg)
+    for s in ("HASHHASHHASH", "123:TOKEN-TOKEN", "SESSIONSTRINGTEXT", "USERBOTSESSIONTEXT", "p%40ss%2Fword", "p@ss/word"):
+        assert s in found, (s, found)
+    assert "" not in found
+    plain = Config(**{**cfg.__dict__, "database_url": "sqlite+aiosqlite:///data/bot.db", "session_string": "", "userbot_session": ""})
+    assert set(secrets_of(plain)) == {"123:TOKEN-TOKEN", "HASHHASHHASH"}  # nothing else to hide, and no crash on SQLite
+
+
+# ------------------------------------------------------------------------------------- deployment files
+def test_dockerfile_is_exactly_the_one_that_was_asked_for():
+    lines = [ln.rstrip() for ln in (ROOT / "Dockerfile").read_text().splitlines() if ln.strip()]
+    assert lines == [
+        "FROM python:3.12-slim",
+        "WORKDIR /app",
+        "ENV PYTHONUNBUFFERED=1",
+        "COPY requirements.txt .",
+        "RUN pip install --no-cache-dir -r requirements.txt",
+        "COPY . .",
+        "CMD python -m http.server 7860 & python bot.py",
+    ]
+
+
+def test_github_workflow_syncs_to_the_space_without_a_hard_coded_token():
+    text = (ROOT / ".github" / "workflows" / "hf-sync.yml").read_text()
+    assert "huggingface.co/spaces/Mega-Evolutions/ButtonBot" in text
+    assert "${{ secrets.HF_TOKEN }}" in text and "branches: [main]" in text and "workflow_dispatch" in text
+    assert "--exclude='README.md'" in text and "--exclude='.github'" in text  # the Space keeps its own README
+    assert not re.search(r"hf_[A-Za-z0-9]{20,}", text)  # no real token pasted in
+    yaml = pytest.importorskip("yaml")
+    doc = yaml.safe_load(text)
+    assert doc["jobs"]["sync-to-hub"]["steps"][1]["env"]["HF_TOKEN"] == "${{ secrets.HF_TOKEN }}"
+
+
+def test_nothing_secret_can_end_up_in_the_image_or_the_repository():
+    docker = (ROOT / ".dockerignore").read_text().split()
+    for entry in (".env", "*.session", "data/*", "tests"):
+        assert entry in docker, entry
+    git = (ROOT / ".gitignore").read_text().split()
+    for entry in (".env", "*.session"):
+        assert entry in git, entry
+
+
+def test_env_example_documents_every_setting():
+    text = (ROOT / ".env.example").read_text()
+    listed = set(re.findall(r"^#?\s*([A-Z][A-Z0-9_]+)=", text, re.M))
+    missing = [n for n in env_names() if n not in listed]
+    assert not missing, f".env.example does not mention: {missing}"
+    unknown = sorted(listed - set(env_names()))
+    assert not unknown, f".env.example mentions settings the bot does not read: {unknown}"
+    assert re.search(r"^ERROR_LOG_CHAT_ID=-1002525172451$", text, re.M)
+
+
+def test_helper_scripts_compile_and_the_userbot_one_stands_alone():
+    for name in ("make_userbot_session.py", "make_session.py", "bot.py"):
+        py_compile.compile(str(ROOT / name), doraise=True)
+    src = (ROOT / "make_userbot_session.py").read_text()
+    assert "from app" not in src and "import app" not in src  # runs on its own computer with only telethon installed
+    assert "StringSession" in src and "USERBOT_SESSION=" in src
+
+
+def test_the_testing_commands_are_gone_everywhere():
+    names = [c for c, _ in COMMANDS]
+    assert "testedit" not in names and "selftest" not in names
+    assert {"new", "posts", "repost", "replace", "undo", "userbot", "help"} <= set(names)
+    assert {"autopost", "broadcast", "handleswap", "shift", "sync", "export", "import"} <= set(names)
+    assert "fixlinks" not in names
+    assert "testerror" not in names
+    for path in list((ROOT / "app").rglob("*.py")) + [ROOT / "bot.py"]:
+        text = path.read_text().lower()
+        assert "testedit" not in text and "selftest" not in text and "testerror" not in text, path
+
+
+def test_every_menu_command_has_a_handler(tmp_path):
+    async def go():
+        app = App(tmp_path)
+        await app.start()
+        patterns = [b.pattern for b, _ in app.tg.handlers if getattr(b, "pattern", None)]
+        for name, _ in COMMANDS:
+            assert any(p(f"/{name}") for p in patterns), f"/{name} is in the menu but nothing answers it"
+        await app.db.close()
+
+    asyncio.run(go())
+
+
+def test_the_help_text_lists_the_commands_that_exist():
+    from app.handlers.basic import HELP
+
+    for name in (
+        "new", "posts", "repost", "replace", "undo", "userbot", "export", "import", "addchannel", "channels",
+        "autopost", "broadcast", "handleswap", "shift", "sync",
+    ):
+        assert f"/{name}" in HELP, name
+    assert "--channel" not in HELP and "/testerror" not in HELP and "/fixlinks" not in HELP and "--clean" not in HELP
+
+
+# ------------------------------------------------------------------------------------------ health port
+def free_port() -> int:
+    with socket.socket() as s:
+        s.bind(("127.0.0.1", 0))
+        return s.getsockname()[1]
+
+
+def test_health_endpoint_answers_ok():
+    async def go():
+        port = free_port()
+        server = await start_health_server(port)
+        assert server is not None
+        reader, writer = await asyncio.open_connection("127.0.0.1", port)
+        writer.write(b"GET / HTTP/1.1\r\nHost: x\r\n\r\n")
+        await writer.drain()
+        data = await asyncio.wait_for(reader.read(), 5)
+        assert data.startswith(b"HTTP/1.1 200 OK") and data.endswith(b"ok")
+        writer.close()
+        server.close()
+        await server.wait_closed()
+
+    asyncio.run(go())
+
+
+def test_a_port_that_is_already_taken_does_not_stop_the_bot():
+    """The Dockerfile starts `python -m http.server 7860` first; if PORT=7860 is set too, the bot must carry on."""
+
+    async def go():
+        busy = socket.socket()
+        busy.bind(("0.0.0.0", 0))
+        busy.listen()
+        try:
+            assert await start_health_server(busy.getsockname()[1]) is None
+        finally:
+            busy.close()
+
+    asyncio.run(go())
+
diff --git a/tests/test_crosslinks.py b/tests/test_crosslinks.py
new file mode 100644
index 0000000000000000000000000000000000000000..4448762534cf643ae1e4e5f12cdfe609b1496840
--- /dev/null
+++ b/tests/test_crosslinks.py
@@ -0,0 +1,558 @@
+"""Links to old posts in OTHER connected channels follow the copies after a /repost (and go back when it is undone)."""
+import asyncio
+
+from telethon import functions, types
+
+from app.crosslinks import CrossResult, progress_text, relink_after_repost, relink_channels, report_lines, restore_after_undo
+from app.postlinks import PostLinks
+from app.repost_engine import delete_copies, run_repost
+from app.sync_engine import live_fields
+from app.tgutil import button_url, ser_entities, ser_markup
+
+from .dbutil import db_url_for, fresh_db
+from .fakes import FakeChannelClient, cb_btn, make_msg, markup, rpc, url_btn
+
+CH, SIDE = "testch", "sidech"  # the reposted channel (id 1) and another connected channel (id 2)
+N = 9  # posts in the reposted channel: post i gets the copy i + N
+NOTICE = "This message couldn't be displayed on your device due to copyright infringement."
+
+
+def run(coro):
+    return asyncio.run(coro)
+
+
+def plain_a(n=N):
+    return {i: make_msg(i, f"Post {i}", out=True) for i in range(1, n + 1)}
+
+
+T1 = "Read https://t.me/testch/2 now"
+
+
+def side_posts():
+    """What the other channel says about the posts of the reposted one: typed link, hyperlink, button, private form ..."""
+    return {
+        1: make_msg(1, T1, [types.MessageEntityBold(T1.index("now"), 3)], out=True),
+        2: make_msg(
+            2, "Part three",
+            [types.MessageEntityTextUrl(0, 4, f"https://t.me/{CH}/3?single"), types.MessageEntityItalic(5, 5)], out=True,
+        ),
+        3: make_msg(
+            3, "Pick one",
+            markup=markup(
+                [url_btn("Part 4", f"https://t.me/{CH}/4"), url_btn("Other", "https://example.com/x")], [cb_btn("👍 3", b"r1")]
+            ),
+            out=True,
+        ),
+        4: make_msg(4, f"Ghost https://t.me/{CH}/99", out=True),  # a post that has no copy: stays
+        5: make_msg(5, "Elsewhere https://t.me/other_chan/2", out=True),  # another channel: stays
+        6: make_msg(6, f"By a friend https://t.me/{CH}/5", out=False),  # somebody else's post
+        7: make_msg(7, "nothing here", out=True),
+        8: make_msg(8, "Private https://t.me/c/1/6 form", out=True),
+    }
+
+
+async def save_rows(db, cid, msgs):
+    for m in msgs.values():
+        if m.out:
+            await db.create_post(
+                channel_id=cid, message_id=m.id, status="sent", source="bot", created_by=99, link_preview=False,
+                **live_fields(m),
+            )
+
+
+async def world(tmp_path, a_msgs=None, b_msgs=None, *, first=1, last=None, save=True):
+    """The reposted channel A (id 1) with a repost registered, and the other channel B (id 2)."""
+    db = await fresh_db(db_url_for(tmp_path))
+    await db.save_channel(1, 5, "Test", CH, 99)
+    await db.save_channel(2, 6, "Side", SIDE, 99)
+    a = FakeChannelClient(plain_a() if a_msgs is None else a_msgs, username=CH, cid=1, title="Test")
+    b = a.add_channel(FakeChannelClient(side_posts() if b_msgs is None else b_msgs, username=SIDE, cid=2, title="Side"))
+    if save:
+        await save_rows(db, 2, b.msgs)
+    await db.create_migration(
+        "m1", 1, old=None, new=None, include_typed=True, include_posts=False, first_id=first, last_id=last or max(a.msgs),
+        partial=False, user_id=99,
+    )
+    return db, await db.get_channel(1), a, b, await db.get_migration("m1")
+
+
+def edits_of(chan):
+    return [r for r in chan.requests if isinstance(r, functions.messages.EditMessageRequest)]
+
+
+async def repost(db, ch, a, mig, **kw):
+    return await run_repost(a, db, ch, mig, 99, delay=0, settle_pause=0, **kw)
+
+
+# ============================================================================================ the main promise
+def test_links_in_another_channel_point_at_the_copies(tmp_path):
+    async def go():
+        db, ch, a, b, mig = await world(tmp_path)
+        res = await repost(db, ch, a, mig)
+        assert (res.copied_units, res.failed, res.aborted, res.cross_error) == (N, [], None, None)
+        assert res.phase == "links" and res.cross is not None
+        cross = res.cross
+
+        # a typed link: the digits change, the bold text after it moves along
+        assert b.msgs[1].message == "Read https://t.me/testch/11 now"
+        bold = b.msgs[1].entities[0]
+        assert isinstance(bold, types.MessageEntityBold) and bold.offset == T1.index("now") + 1 and bold.length == 3
+        assert b.msgs[1].message[bold.offset : bold.offset + bold.length] == "now"
+        # a hyperlink behind text: the url changes, the text and the other formatting stay
+        assert b.msgs[2].message == "Part three"
+        link, italic = b.msgs[2].entities
+        assert link.url == f"https://t.me/{CH}/12?single" and (link.offset, link.length) == (0, 4)
+        assert (italic.offset, italic.length) == (5, 5)
+        # a button: only that url changes; the other url button and the reaction button stay
+        rows = b.msgs[3].reply_markup.rows
+        assert button_url(rows[0].buttons[0]) == f"https://t.me/{CH}/13" and rows[0].buttons[0].text == "Part 4"
+        assert button_url(rows[0].buttons[1]) == "https://example.com/x" and rows[1].buttons[0].text == "👍 3"
+        # a post of somebody else (the bot may edit those here) and the private form of the link
+        assert b.msgs[6].message == f"By a friend https://t.me/{CH}/14"
+        assert b.msgs[8].message == "Private https://t.me/c/1/15 form"
+        # no copy, other channel, no link: untouched
+        assert b.msgs[4].message == f"Ghost https://t.me/{CH}/99"
+        assert b.msgs[5].message == "Elsewhere https://t.me/other_chan/2" and b.msgs[7].message == "nothing here"
+
+        edits = edits_of(b)
+        assert [r.id for r in edits] == [1, 2, 3, 6, 8]  # nothing else was edited
+        assert edits[2].message is None  # the button post: only its keyboard was sent, the text stays as it is
+        assert cross.relinked == 5 and cross.links == 5 and cross.failed == [] and cross.not_allowed == 0
+        assert [c.channel.id for c in cross.changed_channels] == [2] and cross.clean and not cross.stopped
+        # the originals in the reposted channel were not touched
+        assert all(a.msgs[i].message == f"Post {i}" for i in range(1, N + 1))
+        assert not edits_of(a)
+
+        # My posts shows what the channel shows now
+        for i in (1, 2, 3, 8):
+            row = await db.find_by_message(2, i)
+            live = b.msgs[i]
+            assert row.text == live.message and row.entities == ser_entities(live.entities)
+            assert row.buttons == ser_markup(live.reply_markup)
+        assert (await db.find_by_message(2, 3)).text == "Pick one"
+        assert await db.find_by_message(2, 6) is None  # somebody else's post was never saved, and still isn't
+        assert await db.has_mark("m1", "links")
+        await db.close()
+
+    run(go())
+
+
+def test_the_report_says_what_was_done(tmp_path):
+    async def go():
+        db, ch, a, b, mig = await world(tmp_path)
+        res = await repost(db, ch, a, mig)
+        text = "\n".join(report_lines(res.cross))
+        assert "5 link(s) in 5 post(s) of 1 channel(s) now point at the new copies" in text
+        assert "Side: 5 link(s) in 5 post(s)" in text
+        assert "Stopped" not in text and "could not" not in text
+        await db.close()
+
+    run(go())
+
+
+def test_running_it_again_changes_nothing(tmp_path):
+    async def go():
+        db, ch, a, b, mig = await world(tmp_path)
+        await repost(db, ch, a, mig)
+        before = len(edits_of(b))
+        again = await relink_after_repost(a, db, ch, mig, delay=0, settle_pause=0, pause=0)
+        assert again.relinked == 0 and again.links == 0 and again.clean
+        assert len(edits_of(b)) == before  # not one more edit
+        assert "no link there needed changing" in "\n".join(report_lines(again))
+        await db.close()
+
+    run(go())
+
+
+def test_a_link_that_appears_later_is_fixed_by_the_retry(tmp_path):
+    async def go():
+        db, ch, a, b, mig = await world(tmp_path)
+        await repost(db, ch, a, mig)
+        # an admin posts a new message that still links to an old post (the old post is deleted by now)
+        b._new(f"New: https://t.me/{CH}/7", None, None).out = False
+        newest = max(b.msgs)
+        again = await relink_after_repost(a, db, ch, mig, delay=0, settle_pause=0, pause=0)
+        assert again.relinked == 1 and b.msgs[newest].message == f"New: https://t.me/{CH}/16"
+        await db.close()
+
+    run(go())
+
+
+# ================================================================================ the reposted channel itself
+def test_older_posts_of_the_channel_itself_are_fixed_but_the_originals_are_not(tmp_path):
+    async def go():
+        msgs = plain_a()
+        msgs[2] = make_msg(2, f"Old post: https://t.me/{CH}/7", out=True)  # outside the copied range
+        msgs[7] = make_msg(7, f"Seven: https://t.me/{CH}/8", out=True)  # an original that is copied (and later deleted)
+        db, ch, a, b, mig = await world(tmp_path, msgs, first=5, last=9)
+        res = await repost(db, ch, a, mig)
+        assert res.copied_units == 5 and res.failed == []
+        # copies of 5..9 are 10..14 (7 -> 12, 8 -> 13)
+        assert a.msgs[2].message == f"Old post: https://t.me/{CH}/12"  # the post that stays points at the copy
+        assert a.msgs[7].message == f"Seven: https://t.me/{CH}/8"  # the original stays exactly as it was
+        assert a.msgs[12].message == f"Seven: https://t.me/{CH}/13"  # its copy points at the copy of 8
+        assert {r.id for r in edits_of(a)} == {2, 12}
+        # in the other channel only the links to the copied posts (5..9) change
+        assert b.msgs[1].message == "Read https://t.me/testch/2 now"  # 2 was not copied
+        assert button_url(b.msgs[3].reply_markup.rows[0].buttons[0]) == f"https://t.me/{CH}/4"  # neither was 4
+        assert b.msgs[6].message == f"By a friend https://t.me/{CH}/10"  # 5 -> 10
+        assert b.msgs[8].message == "Private https://t.me/c/1/11 form"  # 6 -> 11
+        await db.close()
+
+    run(go())
+
+
+# ==================================================================================== changes made meanwhile
+def test_a_post_changed_meanwhile_is_read_again_before_it_is_edited(tmp_path):
+    async def go():
+        db, ch, a, b, mig = await world(tmp_path, b_msgs={
+            1: make_msg(1, T1, [types.MessageEntityBold(T1.index("now"), 3)], out=True),
+            2: make_msg(2, "Part three", [types.MessageEntityTextUrl(0, 4, f"https://t.me/{CH}/3")], out=True),
+        })
+        for i in range(1, N + 1):
+            a._new(f"Copy {i}", None, None)  # the copies exist: ids 10..18
+        links = PostLinks.for_channel(ch, {i: i + N for i in range(1, N + 1)})
+        fired = []
+
+        async def watch(c):
+            if c.phase == "edit" and not fired and c.current.channel.id == 2:
+                fired.append(1)
+                # while the bot works an admin rewrites post 1 and fixes the link of post 2 by hand
+                b.msgs[1].message = "Read https://t.me/testch/2 now - updated"
+                b.msgs[2].entities = [types.MessageEntityTextUrl(0, 4, f"https://t.me/{CH}/12")]
+
+        res = await relink_channels(a, db, links, [await db.get_channel(2)], delay=0, settle_pause=0, pause=0, progress=watch)
+        assert fired
+        assert b.msgs[1].message == "Read https://t.me/testch/11 now - updated"  # the new wording is kept, link fixed
+        assert [r.id for r in edits_of(b)] == [1]  # post 2 was already right: not edited
+        assert res.relinked == 1 and res.links == 1
+        await db.close()
+
+    run(go())
+
+
+def test_a_post_deleted_meanwhile_is_not_a_problem(tmp_path):
+    async def go():
+        db, ch, a, b, mig = await world(tmp_path)
+        for i in range(1, N + 1):
+            a._new(f"Copy {i}", None, None)
+        links = PostLinks.for_channel(ch, {i: i + N for i in range(1, N + 1)})
+        fired = []
+
+        async def watch(c):
+            if c.phase == "edit" and not fired:
+                fired.append(1)
+                del b.msgs[1]
+
+        res = await relink_channels(a, db, links, [await db.get_channel(2)], delay=0, settle_pause=0, pause=0, progress=watch)
+        assert res.channels[0].gone == 1 and res.relinked == 4 and res.failed == []
+        await db.close()
+
+    run(go())
+
+
+# ======================================================================================== rights and refusals
+def test_somebody_elses_posts_need_the_edit_right(tmp_path):
+    async def go():
+        db, ch, a, b, mig = await world(tmp_path)
+        b.rights = dict(admin=True, post=True, edit=False, delete=True, invite=False, add_admins=False)
+        res = await repost(db, ch, a, mig)
+        cross = res.cross
+        assert b.msgs[6].message == f"By a friend https://t.me/{CH}/5"  # not touched
+        assert b.msgs[1].message == "Read https://t.me/testch/11 now"  # the bot's own posts are
+        assert cross.relinked == 4 and cross.not_allowed == 1 and not cross.clean
+        text = "\n".join(report_lines(cross))
+        assert "1 post(s) with such a link were made by somebody else" in text and "Side" in text
+        assert "Edit messages of others" in text and "Update links again" in text
+        await db.close()
+
+    run(go())
+
+
+def test_what_telegram_refuses_is_reported_and_the_rest_goes_on(tmp_path):
+    async def go():
+        db, ch, a, b, mig = await world(tmp_path)
+        b.msgs[2].via_other_bot = True  # its buttons / text belong to another bot: only that bot may edit it
+        res = await repost(db, ch, a, mig)
+        cross = res.cross
+        assert [(c.id, mid, name) for c, mid, name in cross.failed] == [(2, 2, "MessageIdInvalidError")]
+        assert b.msgs[2].entities[0].url == f"https://t.me/{CH}/3?single"
+        assert button_url(b.msgs[3].reply_markup.rows[0].buttons[0]) == f"https://t.me/{CH}/13"
+        assert cross.relinked == 4 and not cross.clean
+        text = "\n".join(report_lines(cross))
+        assert "1 post(s) could not get their links updated (Side #2 MessageIdInvalidError)" in text
+        assert "other bots" in text
+        await db.close()
+
+    run(go())
+
+
+def test_the_same_refusal_over_and_over_gives_up_on_that_channel_only(tmp_path):
+    async def go():
+        many = {i: make_msg(i, f"Link https://t.me/{CH}/{(i % N) + 1}", out=True) for i in range(1, 13)}
+        db, ch, a, b, mig = await world(tmp_path, b_msgs=many)
+        for m in b.msgs.values():
+            m.via_other_bot = True
+        res = await repost(db, ch, a, mig)
+        side = [c for c in res.cross.channels if c.channel.id == 2][0]
+        assert side.aborted == "MessageIdInvalidError" and len(side.failed) == 5  # not twelve useless tries
+        assert "Gave up on Side" in "\n".join(report_lines(res.cross))
+        await db.close()
+
+    run(go())
+
+
+def test_channels_that_cannot_be_used_are_skipped_and_named(tmp_path):
+    async def go():
+        db, ch, a, b, mig = await world(tmp_path)
+        specs = {
+            3: ("Not admin", dict(rights=dict(admin=False))),
+            4: ("Struck", dict(restriction=NOTICE)),
+            5: ("Private now", dict(fail={"GetFullChannelRequest": rpc("ChannelPrivateError")})),
+            6: ("No rights", dict(rights=dict(admin=True, post=False, edit=False))),
+        }
+        extra = {}
+        for cid, (title, sw) in specs.items():
+            await db.save_channel(cid, 7, title, None, 99)
+            c = a.add_channel(FakeChannelClient({1: make_msg(1, f"x https://t.me/{CH}/2", out=True)}, cid=cid, title=title))
+            for k, v in sw.items():
+                setattr(c, k, v)
+            extra[cid] = c
+        res = await repost(db, ch, a, mig)
+        skipped = {c.channel.id: c.skipped for c in res.cross.skipped}
+        assert set(skipped) == {3, 4, 5, 6}
+        assert "not an admin" in skipped[3] and "restricts" in skipped[4] and "copyright" in skipped[4]
+        assert skipped[5] and "no right" in skipped[6]
+        assert all(not edits_of(c) for c in extra.values())  # nothing was edited there
+        assert b.msgs[1].message == "Read https://t.me/testch/11 now"  # the usable channels were done
+        text = "\n".join(report_lines(res.cross))
+        assert "Not looked at:" in text and "Struck" in text and "Not admin" in text
+        await db.close()
+
+    run(go())
+
+
+def test_posts_telegram_holds_back_are_left_alone(tmp_path):
+    async def go():
+        held = make_msg(
+            9, NOTICE, markup=markup([url_btn("Part 2", f"https://t.me/{CH}/2")]), out=True
+        )
+        held.restriction_reason = [types.RestrictionReason(platform="all", reason="copyright", text=NOTICE)]
+        notice_only = make_msg(10, NOTICE, out=True)  # the notice as the text, no mark
+        msgs = side_posts()
+        msgs[9], msgs[10] = held, notice_only
+        db, ch, a, b, mig = await world(tmp_path, b_msgs=msgs)
+        res = await repost(db, ch, a, mig)
+        side = [c for c in res.cross.channels if c.channel.id == 2][0]
+        assert side.held_back == 2 and side.relinked == 5
+        assert button_url(b.msgs[9].reply_markup.rows[0].buttons[0]) == f"https://t.me/{CH}/2"
+        assert b.msgs[9].message == NOTICE and b.msgs[10].message == NOTICE
+        assert "2 post(s) are held back by Telegram" in "\n".join(report_lines(res.cross))
+        await db.close()
+
+    run(go())
+
+
+# ============================================================================================ stop and go on
+def test_stopping_leaves_the_rest_for_the_retry(tmp_path):
+    async def go():
+        db, ch, a, b, mig = await world(tmp_path)
+        await db.save_channel(3, 7, "Third", None, 99)
+        c3 = a.add_channel(FakeChannelClient({1: make_msg(1, f"see https://t.me/{CH}/2", out=True)}, cid=3, title="Third"))
+        for i in range(1, N + 1):
+            a._new(f"Copy {i}", None, None)
+        links = PostLinks.for_channel(ch, {i: i + N for i in range(1, N + 1)})
+        chans = [await db.get_channel(2), await db.get_channel(3)]
+        stop = []
+
+        async def watch(c):
+            if c.index == 2:
+                stop.append(1)
+
+        res = await relink_channels(
+            a, db, links, chans, delay=0, settle_pause=0, pause=0, progress=watch, should_stop=lambda: bool(stop)
+        )
+        assert res.stopped and not res.clean
+        assert b.msgs[1].message == "Read https://t.me/testch/11 now"  # the first channel was done
+        assert c3.msgs[1].message == f"see https://t.me/{CH}/2"  # the second was not
+        assert "Stopped before every channel was done" in "\n".join(report_lines(res))
+        again = await relink_channels(a, db, links, chans, delay=0, settle_pause=0, pause=0)
+        assert again.relinked == 1 and c3.msgs[1].message == f"see https://t.me/{CH}/11" and again.clean
+        await db.close()
+
+    run(go())
+
+
+def test_the_progress_text_names_the_channel_and_the_count(tmp_path):
+    async def go():
+        db, ch, a, b, mig = await world(tmp_path)
+        seen = []
+
+        async def watch(c):
+            seen.append(progress_text(c))
+
+        links = PostLinks.for_channel(ch, {2: 11})
+        await relink_channels(
+            a, db, links, await db.list_channels(), delay=0, settle_pause=0, pause=0, progress=watch, result=CrossResult()
+        )
+        joined = "\n".join(seen)
+        assert "Side" in joined and "Test" in joined and "(1 of 2)" in joined and "(2 of 2)" in joined
+        assert "Reading posts" in joined
+        await db.close()
+
+    run(go())
+
+
+def test_nothing_is_read_when_there_is_nothing_to_point_at(tmp_path):
+    async def go():
+        db, ch, a, b, mig = await world(tmp_path)
+        res = await relink_channels(
+            a, db, PostLinks.for_channel(ch, {}), await db.list_channels(), delay=0, settle_pause=0, pause=0
+        )
+        assert res.channels == [] and not a.requests and not b.requests
+        await db.close()
+
+    run(go())
+
+
+# ============================================================================================ undo goes back
+def test_undo_points_the_links_back_at_the_original_posts(tmp_path):
+    async def go():
+        db, ch, a, b, mig = await world(tmp_path)
+        original = {i: (m.message, ser_entities(m.entities), ser_markup(m.reply_markup)) for i, m in b.msgs.items()}
+        await repost(db, ch, a, mig)
+        assert b.msgs[1].message != original[1][0]
+        back = await restore_after_undo(a, db, ch, mig, delay=0, settle_pause=0, pause=0)
+        assert back.relinked == 5 and back.clean
+        for i, (text, ents, buttons) in original.items():
+            assert b.msgs[i].message == text, i
+            assert ser_entities(b.msgs[i].entities) == ents, i
+            assert ser_markup(b.msgs[i].reply_markup) == buttons, i
+        # and then the copies can go
+        res = await delete_copies(a, db, ch, mig, "new", delay=0)
+        assert res.remaining == 0 and res.deleted == N
+        await db.close()
+
+    run(go())
+
+
+def test_an_undo_without_changed_links_reads_nothing(tmp_path):
+    async def go():
+        db, ch, a, b, mig = await world(tmp_path)
+        back = await restore_after_undo(a, db, ch, mig, delay=0, settle_pause=0, pause=0)  # no mark: nothing was changed
+        assert back.channels == [] and not a.requests and not b.requests
+        await db.close()
+
+    run(go())
+
+
+# ======================================================================================== as the owner sees it
+async def make_app(tmp_path, a_msgs=None, b_msgs=None):
+    from .harness import App
+    from .test_repost_flow import fill
+
+    app = App(tmp_path, edit_delay=0.0)
+    await app.start()
+    await app.db.save_channel(1, 5, "Test", CH, 1)
+    await app.db.save_channel(2, 6, "Side", SIDE, 1)
+    fill(app.tg, plain_a() if a_msgs is None else a_msgs)
+    app.tg.username = CH
+    side = app.tg.add_channel(FakeChannelClient(side_posts() if b_msgs is None else b_msgs, cid=2, username=SIDE, title="Side"))
+    await save_rows(app.db, 2, side.msgs)
+    return app, side
+
+
+async def copy_everything(app):
+    await app.text("/repost --no-typed")  # no usernames to swap: only the posts are copied
+    await app.press(app.out.callback_data("Test"))
+    await app.press(app.out.callback_data("Start copying"))
+
+
+def test_the_plan_promises_the_links_of_all_channels(tmp_path):
+    from .harness import norm
+
+    async def go():
+        app, side = await make_app(tmp_path)
+        await app.text("/repost --no-typed")
+        assert "Which channel" in norm(app.out.last_text)
+        await app.press(app.out.callback_data("Test"))
+        text = norm(app.out.last_text)
+        assert "Repost plan" in text and "link to an old post" in text and "ANY of your connected channels" in text
+        await app.db.close()
+
+    run(go())
+
+
+def test_the_finished_repost_tells_what_happened_in_the_other_channels(tmp_path):
+    from .harness import norm
+
+    async def go():
+        app, side = await make_app(tmp_path)
+        await copy_everything(app)
+        text = norm(app.out.last_text)
+        assert "all posts copied in order" in text
+        assert "5 link(s) in 5 post(s) of 1 channel(s) now point at the new copies" in text and "Side: 5 link(s)" in text
+        labels = [t for row in app.out.last_buttons() for t in row]
+        assert any("Update links again" in t for t in labels) and any("Delete the old posts" in t for t in labels)
+        assert side.msgs[1].message == "Read https://t.me/testch/11 now"
+        await app.db.close()
+
+    run(go())
+
+
+def test_update_links_again_finds_what_came_later(tmp_path):
+    from .harness import norm
+
+    async def go():
+        app, side = await make_app(tmp_path)
+        await copy_everything(app)
+        again = app.out.callback_data("Update links again")
+        assert again.startswith("rpl:")
+        await app.press(again)  # nothing new: nothing to change
+        assert "no link there needed changing" in norm(app.out.last_text)
+        m = side._new(f"Late: https://t.me/{CH}/8", None, None)
+        m.out = False
+        await app.press(app.out.callback_data("Update links again"))
+        assert side.msgs[m.id].message == f"Late: https://t.me/{CH}/17"
+        assert "1 link(s) in 1 post(s) of 1 channel(s)" in norm(app.out.last_text)
+        await app.db.close()
+
+    run(go())
+
+
+def test_undo_points_the_links_back_and_says_so(tmp_path):
+    from .harness import norm
+
+    async def go():
+        app, side = await make_app(tmp_path)
+        await copy_everything(app)
+        assert side.msgs[1].message == "Read https://t.me/testch/11 now"
+        await app.press(app.out.callback_data("Undo"))
+        await app.press(app.out.callback_data("Yes, remove the copies"))
+        text = norm(app.out.last_text)
+        assert "Done" in text and "5 link(s) in 5 post(s) of 1 channel(s) point back at the original posts" in text
+        assert side.msgs[1].message == T1 and side.msgs[8].message == "Private https://t.me/c/1/6 form"
+        assert button_url(side.msgs[3].reply_markup.rows[0].buttons[0]) == f"https://t.me/{CH}/4"
+        assert sorted(app.tg.msgs) == list(range(1, N + 1))  # only the originals are left
+        await app.db.close()
+
+    run(go())
+
+
+def test_after_the_old_posts_are_deleted_the_links_can_still_be_updated(tmp_path):
+    from .harness import norm
+
+    async def go():
+        app, side = await make_app(tmp_path)
+        await copy_everything(app)
+        await app.press(app.out.callback_data("Delete the old posts"))
+        await app.press(app.out.callback_data("Yes, delete"))
+        assert "Done" in norm(app.out.last_text)
+        labels = [t for row in app.out.last_buttons() for t in row]
+        assert any("Update links again" in t for t in labels)
+        await app.press(app.out.callback_data("Update links again"))
+        text = norm(app.out.last_text)
+        assert "no link there needed changing" in text and "Test" in text
+        await app.db.close()
+
+    run(go())
diff --git a/tests/test_delete_post.py b/tests/test_delete_post.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc3132539d9bc618ee1e9c500c75f6e9a01cc34d
--- /dev/null
+++ b/tests/test_delete_post.py
@@ -0,0 +1,135 @@
+"""Deleting one published post from My posts: the bot first, the userbot when Telegram refuses, honest messages."""
+import asyncio
+import datetime
+
+from app.db import utcnow
+
+from .fakes import make_msg
+from .harness import App, norm
+from .test_repost_flow import fill, userbot_setup
+
+
+async def make_app(tmp_path, **cfg):
+    app = App(tmp_path, **cfg)
+    await app.start()
+    await app.db.save_channel(1, 5, "Anime Channel", "animech", 1)
+    fill(app.tg, {5: make_msg(5, "old post"), 6: make_msg(6, "newer post")})
+    post = await app.db.create_post(channel_id=1, message_id=5, status="sent", source="bot", text="old post", entities=[], buttons=[])
+    return app, post.id
+
+
+def test_the_bot_deletes_a_post_it_is_allowed_to(tmp_path):
+    async def run():
+        app, pid = await make_app(tmp_path)
+        await app.press(f"dl:{pid}")
+        text = norm(app.out.last_text)
+        # the screen says what each button does; it does not talk about a helper account or ask about one
+        assert "Delete this post" in text and "removes it, with its data, from My posts" in text
+        assert "userbot" not in text.lower() and "if you set one up" not in text
+        assert [t for row in app.out.last_buttons() for t in row] == ["🗑 Delete from channel", "🧹 Only forget it in the bot", "↩️ Back"]
+        await app.press(f"dly:{pid}:a")
+        assert "Done - deleted in the channel and removed from My posts" in norm(app.out.last_text)
+        assert 5 not in app.tg.msgs and 6 in app.tg.msgs
+        assert await app.db.get_post(pid) is None
+        await app.db.close()
+
+    asyncio.run(run())
+
+
+def test_a_post_too_old_for_the_bot_stays_registered_and_the_owner_is_told_why(tmp_path):
+    async def run():
+        app, pid = await make_app(tmp_path)
+        app.tg.undeletable = {5}
+        await app.press(f"dly:{pid}:a")
+        text = norm(app.out.last_text)
+        assert "Telegram did not delete that message" in text and "/userbot" in text and "Only forget it in the bot" in text
+        assert "still in My posts" in text
+        assert 5 in app.tg.msgs and await app.db.get_post(pid) is not None  # nothing is forgotten while it still exists
+        # after deleting by hand, "only forget it" removes just the bot's record
+        await app.press(f"dly:{pid}:b")
+        assert await app.db.get_post(pid) is None and 5 in app.tg.msgs
+        await app.db.close()
+
+    asyncio.run(run())
+
+
+def test_the_userbot_deletes_what_the_bot_may_not(tmp_path):
+    async def run():
+        app, pid = await make_app(tmp_path)
+        ub, holder = userbot_setup(app)
+        app.tg.undeletable = {5}
+        shown = len(app.out.log)
+        await app.press(f"dly:{pid}:a")
+        # one answer, no question on the way: the userbot simply took over where the bot was refused
+        assert len(app.out.log) - shown == 1
+        assert "Done - deleted in the channel and removed from My posts" in norm(app.out.last_text)
+        assert "the userbot did" in norm(app.out.last_text) and app.out.last_buttons() == [["📚 My posts"]]
+        assert 5 not in app.tg.msgs and 6 in app.tg.msgs and await app.db.get_post(pid) is None
+        assert holder["client"].deleted == [[5]]
+        assert app.tg.admins == {} and all(v["revoked"] for v in app.tg.invites.values())  # cleaned up again
+        await app.db.close()
+
+    asyncio.run(run())
+
+
+def test_a_userbot_that_cannot_get_the_right_is_explained(tmp_path):
+    async def run():
+        app, pid = await make_app(tmp_path)
+        userbot_setup(app, bot_rights=dict(admin=True, post=True, edit=True, delete=True, invite=True, add_admins=False))
+        app.tg.undeletable = {5}
+        await app.press(f"dly:{pid}:a")
+        text = norm(app.out.last_text)
+        assert "Telegram did not delete that message" in text and "Add new admins" in text
+        assert 5 in app.tg.msgs and await app.db.get_post(pid) is not None
+        await app.db.close()
+
+    asyncio.run(run())
+
+
+def test_discarding_a_draft_touches_nothing_in_telegram(tmp_path):
+    async def run():
+        app, _ = await make_app(tmp_path)
+        d = await app.db.create_post(channel_id=1, status="draft", source="bot", text="a draft", entities=[], buttons=[])
+        await app.press(f"dl:{d.id}")
+        assert "Discard this draft" in norm(app.out.last_text)
+        await app.press(f"dly:{d.id}:b")
+        assert await app.db.get_post(d.id) is None
+        assert app.tg.requests == [] and app.tg.deleted == []
+        await app.db.close()
+
+    asyncio.run(run())
+
+
+def test_deleting_from_the_channel_removes_the_post_and_what_hangs_on_it(tmp_path):
+    """The saved post, its timed deletion and a "forgotten on purpose" mark all go with the channel message."""
+    async def run():
+        app, pid = await make_app(tmp_path)
+        other = await app.db.create_post(channel_id=1, message_id=6, status="sent", source="bot", text="newer post", entities=[], buttons=[])
+        await app.db.schedule_deletes(
+            [
+                dict(channel_id=1, message_id=5, delete_at=utcnow() + datetime.timedelta(days=1), group_id="g", created_by=1),
+                dict(channel_id=1, message_id=6, delete_at=utcnow() + datetime.timedelta(days=1), group_id="g", created_by=1),
+            ]
+        )
+        await app.db.ignore_post(1, 5)
+        await app.press(f"dly:{pid}:a")
+        assert await app.db.get_post(pid) is None and 5 not in app.tg.msgs
+        left = await app.db.pending_deletes()
+        assert [r.message_id for r in left] == [6]  # only the timer of the message that is still there
+        assert 5 not in await app.db.ignored_ids(1)
+        assert (await app.db.get_post(other.id)) is not None  # the other post is untouched
+        await app.db.close()
+
+    asyncio.run(run())
+
+
+def test_only_forgetting_a_post_leaves_it_in_the_channel_and_keeps_the_sync_away_from_it(tmp_path):
+    async def run():
+        app, pid = await make_app(tmp_path)
+        await app.press(f"dly:{pid}:b")
+        assert await app.db.get_post(pid) is None and 5 in app.tg.msgs
+        assert 5 in await app.db.ignored_ids(1) and (1, 5) in app.ctx.sync_ignore
+        assert app.tg.deleted == [] and "Done" in norm(app.out.last_text)
+        await app.db.close()
+
+    asyncio.run(run())
diff --git a/tests/test_engine.py b/tests/test_engine.py
new file mode 100644
index 0000000000000000000000000000000000000000..e076f1092fba597b432e1360632d02e93a89d908
--- /dev/null
+++ b/tests/test_engine.py
@@ -0,0 +1,146 @@
+import asyncio
+from telethon import types
+
+from app.linkswap import compute_message_changes
+from app.replace_engine import ScanOptions, apply_channel, scan_channel, undo_batch
+from app.tgutil import button_url, is_callback_button
+
+from .dbutil import fresh_db, db_url_for
+from .fakes import FakeClient, cb_btn, make_msg, markup, rpc, url_btn
+
+OLD = "https://t.me/bharath?start=BBB"
+
+
+def build():
+    text3 = "Hi 😀 https://t.me/bharath?start=CCC done"
+    msgs = {
+        1: make_msg(1, "Get it now", [types.MessageEntityTextUrl(0, 3, "https://t.me/Bharath?start=AAA")]),
+        2: make_msg(
+            2,
+            "Episodes",
+            markup=markup([url_btn("Ep 1-20", OLD), cb_btn("👍 3", b"r1")], [url_btn("Join", "https://t.me/other")]),
+            out=True,
+        ),
+        3: make_msg(3, text3, [types.MessageEntityBold(37, 4)]),
+        4: make_msg(4, "see https://t.me/bharath_bot?start=1"),
+        5: make_msg(5, "https://t.me/bharath/123"),
+        7: types.MessageEmpty(id=7, peer_id=types.PeerChannel(1)),
+    }
+    return msgs, text3
+
+
+async def setup(tmp_path, msgs, pts=8):
+    db = await fresh_db(db_url_for(tmp_path))
+    await db.save_channel(1, 5, "Test", None, 99)
+    ch = await db.get_channel(1)
+    return db, ch, FakeClient(msgs, pts=pts)
+
+
+def test_scan_apply_undo(tmp_path):
+    async def run():
+        msgs, text3 = build()
+        db, ch, client = await setup(tmp_path, msgs)
+        opts = ScanOptions("bharath", "goku")
+        scan = await scan_channel(client, ch, opts, can_edit_others=True)
+        assert set(scan.infos) == {1, 2, 3}
+        assert scan.skipped_post_links == 1  # t.me/bharath/123 is a channel post, not a bot link
+        assert scan.foreign == 2 and scan.infos[2].mine and scan.infos[2].callbacks
+
+        await db.create_batch("b1", "bharath", "goku", 99)
+        res = await apply_channel(client, db, scan, opts, "b1", 99, edit_delay=0)
+        assert (res.edited, res.failed) == (3, [])
+
+        # hyperlink: only the username changed
+        assert msgs[1].entities[0].url == "https://t.me/goku?start=AAA"
+        # buttons: URL swapped, reaction button + other link untouched, text untouched
+        rows = msgs[2].reply_markup.rows
+        assert button_url(rows[0].buttons[0]) == "https://t.me/goku?start=BBB"
+        assert is_callback_button(rows[0].buttons[1])
+        assert button_url(rows[1].buttons[0]) == "https://t.me/other"
+        assert msgs[2].message == "Episodes"
+        # typed link after an emoji: text swapped and the following entity moved with it
+        assert msgs[3].message == "Hi 😀 https://t.me/goku?start=CCC done"
+        assert (msgs[3].entities[0].offset, msgs[3].entities[0].length) == (34, 4)
+        # untouched
+        assert msgs[4].message == "see https://t.me/bharath_bot?start=1"
+        assert msgs[5].message == "https://t.me/bharath/123"
+
+        # adopted into the database
+        p = await db.find_by_message(1, 3)
+        assert p.source == "adopted" and "goku" in p.text
+        assert (await db.find_by_message(1, 2)).buttons[0][0]["u"].endswith("goku?start=BBB")
+
+        # undo restores everything
+        ures = await undo_batch(client, db, "b1", edit_delay=0)
+        assert ures.restored == 3 and not ures.failed
+        assert msgs[1].entities[0].url == "https://t.me/Bharath?start=AAA"
+        assert msgs[3].message == text3 and msgs[3].entities[0].offset == 37
+        assert button_url(msgs[2].reply_markup.rows[0].buttons[0]) == OLD
+        assert is_callback_button(msgs[2].reply_markup.rows[0].buttons[1])
+        assert (await db.last_batch()) is None  # batch marked as undone
+        await db.close()
+
+    asyncio.run(run())
+
+
+def test_only_own_posts_without_edit_right(tmp_path):
+    async def run():
+        msgs, _ = build()
+        db, ch, client = await setup(tmp_path, msgs)
+        opts = ScanOptions("bharath", "goku")
+        scan = await scan_channel(client, ch, opts, can_edit_others=False)
+        assert set(scan.infos) == {2} and scan.not_editable == 2
+        await db.create_batch("b2", "bharath", "goku", 99)
+        res = await apply_channel(client, db, scan, opts, "b2", 99, edit_delay=0)
+        assert res.edited == 1 and len(client.edits) == 1
+        await db.close()
+
+    asyncio.run(run())
+
+
+def test_failures_are_reported_not_fatal(tmp_path):
+    async def run():
+        msgs, _ = build()
+        db, ch, client = await setup(tmp_path, msgs)
+        client.fail[1] = rpc("MessageAuthorRequiredError")
+        opts = ScanOptions("bharath", "goku")
+        scan = await scan_channel(client, ch, opts)
+        await db.create_batch("b3", "bharath", "goku", 99)
+        res = await apply_channel(client, db, scan, opts, "b3", 99, edit_delay=0)
+        assert res.edited == 2 and res.failed == [(1, "MessageAuthorRequiredError")]
+        await db.close()
+
+    asyncio.run(run())
+
+
+def test_scan_without_counter_falls_back_to_probing(tmp_path):
+    async def run():
+        msgs, _ = build()
+        db, ch, client = await setup(tmp_path, msgs, pts=None)
+        scan = await scan_channel(client, ch, ScanOptions("bharath", "goku"))
+        assert set(scan.infos) == {1, 2, 3}
+        await db.close()
+
+    asyncio.run(run())
+
+
+def test_post_links_can_be_included():
+    m = make_msg(5, "https://t.me/bharath/123")
+    assert compute_message_changes(m, "bharath", "goku")[0] is None
+    ch, skipped = compute_message_changes(m, "bharath", "goku", include_posts=True)
+    assert ch.new_text == "https://t.me/goku/123"
+
+
+def test_tg_scheme_and_hyperlink_and_text_flags():
+    m = make_msg(
+        6,
+        "open tg://resolve?domain=bharath&start=x",
+        [types.MessageEntityTextUrl(0, 4, "tg://resolve?domain=Bharath&start=y")],
+    )
+    ch, _ = compute_message_changes(m, "bharath", "goku")
+    assert ch.new_text == "open tg://resolve?domain=goku&start=x"
+    assert ch.new_entities[0].url == "tg://resolve?domain=goku&start=y"
+    assert ch.n_typed == 1 and ch.n_links == 1
+
+    ch2, _ = compute_message_changes(m, "bharath", "goku", include_typed=False)
+    assert ch2.new_text == m.message and ch2.n_typed == 0
diff --git a/tests/test_errorlog.py b/tests/test_errorlog.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2317f121ce2613ddc6fee363213653d220f5000
--- /dev/null
+++ b/tests/test_errorlog.py
@@ -0,0 +1,533 @@
+"""Errors go to the log chat as a `python` code block: full tracebacks, split not shortened, secrets removed, no floods."""
+import asyncio
+import gc
+import logging
+import threading
+from types import SimpleNamespace
+
+import pytest
+from telethon import errors, types
+
+from app import errorlog
+from app.errorlog import ErrorReporter, TelegramLogHandler, format_exception, redact, split_report
+from app.tgutil import utf16_len
+
+from .harness import App, norm
+
+CHAT = -1002525172451
+TOKEN = "123456:ABCdefGHIjklMNOpqrSTUvwxYZ"
+
+
+class FakeSender:
+    """The bot's Telegram connection, as far as the reporter uses it."""
+
+    def __init__(self, *, member=True, connected=True, authorized=True):
+        self.member, self.connected, self.authorized = member, connected, authorized
+        self.sent = []  # (peer, text, entities, link_preview)
+        self.lookups = []
+        self.signed_in = []
+        self.fail_send = None
+
+    async def get_input_entity(self, chat_id):
+        self.lookups.append(chat_id)
+        if not self.member:
+            raise ValueError(f"Could not find the input entity for {chat_id}")
+        return types.InputPeerChannel(2525172451, 1)
+
+    async def send_message(self, peer, text, *, formatting_entities=None, link_preview=None):
+        if self.fail_send is not None:
+            raise self.fail_send
+        self.sent.append((peer, text, formatting_entities, link_preview))
+
+    def is_connected(self):
+        return self.connected
+
+    async def connect(self):
+        self.connected = True
+
+    async def is_user_authorized(self):
+        return self.authorized
+
+    async def sign_in(self, bot_token=None):
+        self.signed_in.append(bot_token)
+        self.authorized = True
+
+    @property
+    def texts(self):
+        return [s[1] for s in self.sent]
+
+
+def reporter(client, **kw):
+    kw.setdefault("gap", 0)
+    kw.setdefault("part_gap", 0)
+    kw.setdefault("bot_token", TOKEN)
+    return ErrorReporter(client, kw.pop("chat_id", CHAT), **kw)
+
+
+async def drain(rep, timeout=5):
+    await asyncio.wait_for(rep._queue.join(), timeout)
+
+
+def boom(depth=0):
+    """An exception chain like the one in the screenshot: a cause, then the error it led to."""
+    try:
+        try:
+            raise KeyError("inner")
+        except KeyError as e:
+            raise RuntimeError("outer") from e
+    except RuntimeError as e:
+        return e
+
+
+# ------------------------------------------------------------------------------------ text helpers
+def test_short_reports_stay_in_one_piece():
+    assert split_report("hello") == ["hello"]
+    text = "x" * 3800
+    assert split_report(text) == [text]
+
+
+def test_long_reports_are_split_at_line_breaks_and_nothing_is_lost():
+    lines = [f"  File \"/app/module_{i}.py\", line {i}, in function_{i}" for i in range(300)]
+    text = "Unhandled exception:\n" + "\n".join(lines)
+    parts = split_report(text)
+    assert len(parts) > 1
+    assert all(len(p) <= 4096 for p in parts)
+    n = len(parts)
+    assert [p.split("\n", 1)[0] for p in parts] == [f"(part {i}/{n})" for i in range(1, n + 1)]
+    body = "\n".join(p.split("\n", 1)[1] for p in parts)
+    assert body == text  # the same lines in the same order, none dropped, none cut in half
+
+
+def test_one_enormous_line_is_cut_into_pieces_not_dropped():
+    text = "Error: " + "y" * 10000
+    parts = split_report(text)
+    assert len(parts) > 1 and all(len(p) <= 4096 for p in parts)
+    body = "".join(p.split("\n", 1)[1] for p in parts)
+    assert body.replace("\n", "") == text  # every character is there; the only addition is a line break at each cut
+
+
+def test_redact_removes_secrets_longest_first():
+    out = redact(f"token {TOKEN} and hunter2hunter2 and ab", [TOKEN, "hunter2hunter2", "ab", "", None])
+    assert out == "token *** and *** and ab"  # a 2-letter "secret" would mangle ordinary words, so it is left alone
+    assert redact("keep me", [TOKEN]) == "keep me"
+    assert redact("p@ssw0rd-long p@ssw0rd", ["p@ssw0rd", "p@ssw0rd-long"]) == "*** ***"
+
+
+def test_traceback_text_contains_the_whole_chain():
+    text = format_exception(boom())
+    assert text.startswith("Traceback (most recent call last):")
+    assert "KeyError: 'inner'" in text and "RuntimeError: outer" in text
+    assert "The above exception was the direct cause of the following exception:" in text
+
+
+# ---------------------------------------------------------------------------------------- delivery
+def test_a_report_is_sent_as_a_python_code_block():
+    async def go():
+        client = FakeSender()
+        rep = reporter(client)
+        rep.start()
+        rep.submit("Unhandled exception in background task :", format_exception(boom()))
+        await drain(rep)
+        (peer, text, ents, preview), = client.sent
+        assert text.startswith("Unhandled exception in background task :\n\nTraceback (most recent call last):")
+        assert "The above exception was the direct cause of the following exception:" in text
+        assert text.rstrip().endswith("RuntimeError: outer")
+        # one code block over the whole message, language "python"
+        (ent,) = ents
+        assert isinstance(ent, types.MessageEntityPre) and ent.language == "python"
+        assert (ent.offset, ent.length) == (0, utf16_len(text)) and preview is False
+        assert client.lookups == [CHAT]
+        await rep.stop()
+
+    asyncio.run(go())
+
+
+def test_the_code_block_length_counts_utf16_units():
+    async def go():
+        client = FakeSender()
+        rep = reporter(client)
+        rep.start()
+        rep.submit("Fehler 😀 in Aufgabe:", "Traceback:\n  ValueError: Größe ≠ 😀😀")
+        await drain(rep)
+        _, text, ents, _ = client.sent[0]
+        assert ents[0].length == utf16_len(text) and utf16_len(text) > len(text)  # emoji take two units
+        await rep.stop()
+
+    asyncio.run(go())
+
+
+def test_a_long_traceback_is_sent_in_several_messages_and_every_line_arrives():
+    async def go():
+        client = FakeSender()
+        rep = reporter(client)
+        rep.start()
+        tb = "Traceback (most recent call last):\n" + "\n".join(f'  File "/app/m{i}.py", line {i}, in f{i}' for i in range(400)) + "\nValueError: deep"
+        rep.submit("Unhandled exception in handler h_x (user 1):", tb)
+        await drain(rep)
+        assert len(client.sent) > 1
+        for _, text, ents, _ in client.sent:
+            assert len(text) <= 4096 and ents[0].length == utf16_len(text) and ents[0].language == "python"
+        joined = "\n".join(t.split("\n", 1)[1] for t in client.texts)
+        assert "ValueError: deep" in joined and joined.count("File \"/app/m") == 400
+        assert client.texts[0].startswith(f"(part 1/{len(client.sent)})")
+        await rep.stop()
+
+    asyncio.run(go())
+
+
+def test_secrets_never_leave_the_bot():
+    async def go():
+        client = FakeSender()
+        # the bot token is hidden even though it is only given as the login token, not in the list of secrets
+        rep = reporter(client, secrets=["hunter2hunter2", "SESSIONTEXT123456"])
+        rep.start()
+        rep.submit(f"login with {TOKEN} failed:", "OperationalError: password hunter2hunter2 wrong, session SESSIONTEXT123456")
+        await drain(rep)
+        text = client.texts[0]
+        assert TOKEN not in text and "hunter2hunter2" not in text and "SESSIONTEXT123456" not in text
+        assert text.count("***") == 3
+        await rep.stop()
+
+    asyncio.run(go())
+
+
+def test_secrets_are_removed_even_when_a_text_is_split_across_parts():
+    async def go():
+        client = FakeSender()
+        rep = reporter(client, secrets=["hunter2hunter2"])
+        rep.start()
+        lines = ["line %d hunter2hunter2" % i for i in range(500)]
+        rep.submit("Many lines:", "\n".join(lines))
+        await drain(rep)
+        assert len(client.sent) > 1 and not any("hunter2" in t for t in client.texts)
+        await rep.stop()
+
+    asyncio.run(go())
+
+
+# --------------------------------------------------------------------------------------- the sources
+def test_a_forgotten_background_task_is_reported_like_in_the_screenshot():
+    async def go():
+        client = FakeSender()
+        rep = reporter(client)
+        rep.start()
+        loop = asyncio.get_running_loop()
+        loop.set_exception_handler(rep.loop_exception_handler)
+
+        async def boom_task():
+            raise boom()
+
+        t = loop.create_task(boom_task())
+        await asyncio.sleep(0.05)  # it ran and failed; nobody looked at the result
+        del t
+        gc.collect()
+        await asyncio.sleep(0.05)
+        await drain(rep)
+        text = client.texts[0]
+        assert text.startswith("Unhandled exception in background task :\n\nTraceback")
+        assert "RuntimeError: outer" in text and "The above exception was the direct cause" in text
+        await rep.stop()
+
+    asyncio.run(go())
+
+
+def test_named_tasks_keep_their_name_and_other_loop_errors_their_message():
+    async def go():
+        client = FakeSender()
+        rep = reporter(client)
+        rep.start()
+        loop = asyncio.get_running_loop()
+
+        async def noop():
+            raise ValueError("x")
+
+        task = loop.create_task(noop(), name="cleanup-job")
+        await asyncio.sleep(0)
+        await asyncio.sleep(0)
+        calls = []
+        loop.default_exception_handler = lambda ctx: calls.append(ctx)  # the normal log line still happens
+        rep.loop_exception_handler(loop, {"message": "Task exception was never retrieved", "exception": task.exception(), "future": task})
+        rep.loop_exception_handler(loop, {"message": "Fatal error on transport", "exception": OSError("pipe closed")})
+        rep.loop_exception_handler(loop, {"message": "Something odd without an exception"})
+        await drain(rep)
+        assert client.texts[0].startswith("Unhandled exception in background task cleanup-job:")
+        assert client.texts[1] == "Fatal error on transport:\n\nOSError: pipe closed"
+        assert client.texts[2].startswith("Something odd without an exception:")
+        assert len(calls) == 3
+        await rep.stop()
+
+    asyncio.run(go())
+
+
+def test_the_logging_handler_forwards_errors_with_their_traceback():
+    async def go():
+        client = FakeSender()
+        rep = reporter(client)
+        rep.start()
+        handler = TelegramLogHandler(rep)
+        root = logging.getLogger()
+        root.addHandler(handler)
+        try:
+            try:
+                raise boom()
+            except RuntimeError:
+                logging.getLogger("app.common").exception("Unhandled exception in handler h_posts (user 1)")
+            logging.getLogger("app.common").error("Telegram refused a request")  # no traceback
+            logging.getLogger("app.common").warning("only a warning")  # below ERROR: not sent
+            logging.getLogger("telethon.network").error("Connection lost")  # other libraries get a tag
+            logging.getLogger("app.errorlog").error("our own message must not loop")
+            logging.getLogger("asyncio").error("asyncio has its own path")
+            await asyncio.sleep(0.05)
+            await drain(rep)
+        finally:
+            root.removeHandler(handler)
+        assert len(client.sent) == 3, client.texts
+        assert client.texts[0].startswith("Unhandled exception in handler h_posts (user 1):\n\nTraceback")
+        assert "The above exception was the direct cause of the following exception:" in client.texts[0]
+        assert client.texts[1] == "Telegram refused a request"
+        assert client.texts[2] == "[telethon.network] Connection lost"
+        await rep.stop()
+
+    asyncio.run(go())
+
+
+def test_a_failing_handler_in_the_bot_reaches_the_log_chat_end_to_end(tmp_path):
+    """A real handler fails; guard() logs it; the log handler sends it as a code block with the whole chain."""
+
+    async def go():
+        client = FakeSender()
+        rep = reporter(client)
+        rep.start()
+        handler = TelegramLogHandler(rep)
+        logging.getLogger().addHandler(handler)
+        app = App(tmp_path)
+        await app.start()
+        app.ctx.reporter = rep
+
+        async def broken():
+            raise boom()
+
+        app.db.list_channels = broken  # /channels now fails the way a database outage would
+        try:
+            await app.text("/channels")
+            await asyncio.sleep(0.05)
+            await drain(rep)
+        finally:
+            logging.getLogger().removeHandler(handler)
+        assert "Something went wrong: RuntimeError" in norm(app.out.last_text)  # the user is told too
+        text = client.texts[0]
+        assert text.startswith("Unhandled exception in handler h_channels (user 1):\n\nTraceback")
+        assert "KeyError: 'inner'" in text and "RuntimeError: outer" in text
+        assert "The above exception was the direct cause of the following exception:" in text
+        await app.db.close()
+        await rep.stop()
+
+    asyncio.run(go())
+
+
+def test_a_forgotten_background_task_that_fails_reaches_the_log_chat(tmp_path):
+    async def go():
+        client = FakeSender()
+        rep = reporter(client)
+        rep.start()
+        asyncio.get_running_loop().set_exception_handler(rep.loop_exception_handler)
+
+        async def fails():
+            raise RuntimeError("background failure")
+
+        asyncio.get_running_loop().create_task(fails())  # nobody awaits it
+        await asyncio.sleep(0.1)
+        gc.collect()
+        await asyncio.sleep(0.05)
+        await drain(rep)
+        assert client.texts[0].startswith("Unhandled exception in background task :")
+        assert "RuntimeError: background failure" in client.texts[0]
+        await rep.stop()
+
+    asyncio.run(go())
+
+
+def test_a_crash_of_the_whole_bot_is_sent_directly_even_when_disconnected():
+    async def go():
+        client = FakeSender(connected=False, authorized=False)
+        rep = reporter(client)  # never started: the crash path does not depend on the worker
+        await rep.report_fatal("The bot stopped because of an unhandled exception", boom())
+        assert client.connected and client.signed_in == [TOKEN]
+        (peer, text, ents, _), = client.sent
+        assert text.startswith("The bot stopped because of an unhandled exception:\n\nTraceback")
+        assert "RuntimeError: outer" in text and ents[0].language == "python"
+
+    asyncio.run(go())
+
+
+def test_a_failing_crash_report_never_raises():
+    async def go():
+        client = FakeSender()
+        client.fail_send = errors.ChatWriteForbiddenError(request=None)
+        rep = reporter(client)
+        await rep.report_fatal("The bot stopped", boom())  # must not raise (the bot is going down anyway)
+        await reporter(FakeSender(), chat_id=None).report_fatal("x", boom())
+
+    asyncio.run(go())
+
+
+# ------------------------------------------------------------------------------- flood protection
+def test_identical_errors_are_merged_and_counted(monkeypatch):
+    async def go():
+        now = [1000.0]
+        monkeypatch.setattr(errorlog, "time", SimpleNamespace(monotonic=lambda: now[0]))
+        client = FakeSender()
+        rep = reporter(client, dedupe_seconds=60)
+        rep.start()
+        for _ in range(5):
+            rep.submit("Unhandled exception in handler h:", "Traceback:\nValueError: same")
+            now[0] += 1
+        rep.submit("Unhandled exception in handler h:", "Traceback:\nValueError: different")  # another error: not merged
+        await drain(rep)
+        assert len(client.sent) == 2
+        now[0] += 100  # a minute and a half later the same error is news again, and says how often it came meanwhile
+        rep.submit("Unhandled exception in handler h:", "Traceback:\nValueError: same")
+        await drain(rep)
+        assert len(client.sent) == 3 and "(+4 identical report(s) suppressed)" in client.texts[2]
+        assert "suppressed" not in client.texts[0]
+        await rep.stop()
+
+    asyncio.run(go())
+
+
+def test_a_storm_of_different_errors_is_limited_per_minute(monkeypatch):
+    async def go():
+        now = [5000.0]
+        monkeypatch.setattr(errorlog, "time", SimpleNamespace(monotonic=lambda: now[0]))
+        client = FakeSender()
+        rep = reporter(client, per_minute=3)
+        rep.start()
+        for i in range(10):
+            rep.submit(f"error number {i}:", f"ValueError: {i}")
+        await drain(rep)
+        assert len(client.sent) == 3  # the first three, the other seven are counted
+        now[0] += 61
+        rep.submit("error after the storm:", "ValueError: later")
+        await drain(rep)
+        assert len(client.sent) == 4 and "(7 report(s) were skipped because too many errors came in)" in client.texts[3]
+        await rep.stop()
+
+    asyncio.run(go())
+
+
+def test_not_being_allowed_to_write_to_the_chat_silences_the_reporter(monkeypatch):
+    async def go():
+        now = [10.0]
+        monkeypatch.setattr(errorlog, "time", SimpleNamespace(monotonic=lambda: now[0]))
+        client = FakeSender()
+        client.fail_send = errors.ChatWriteForbiddenError(request=None)
+        rep = reporter(client)
+        rep.start()
+        rep.submit("first:", "ValueError: 1")
+        await drain(rep)
+        assert client.sent == [] and client.lookups == [CHAT]
+        rep.submit("second:", "ValueError: 2")  # muted: not even tried
+        await asyncio.sleep(0.05)
+        assert client.lookups == [CHAT] and rep._queue.qsize() == 0
+        now[0] += errorlog.MUTE_SECONDS + 1  # after the pause it tries again (the owner may have added the bot meanwhile)
+        client.fail_send = None
+        rep.submit("third:", "ValueError: 3")
+        await drain(rep)
+        assert client.texts == ["third:\n\nValueError: 3"]
+        await rep.stop()
+
+    asyncio.run(go())
+
+
+def test_other_sending_problems_do_not_silence_it():
+    async def go():
+        client = FakeSender()
+        client.fail_send = RuntimeError("temporary network trouble")
+        rep = reporter(client)
+        rep.start()
+        rep.submit("first:", "ValueError: 1")
+        await drain(rep)
+        client.fail_send = None
+        rep.submit("second:", "ValueError: 2")
+        await drain(rep)
+        assert client.texts == ["second:\n\nValueError: 2"]
+        await rep.stop()
+
+    asyncio.run(go())
+
+
+def test_a_chat_the_bot_is_not_in_is_noticed_at_start_up():
+    async def go():
+        rep = reporter(FakeSender(member=False))
+        problem = await rep.check()
+        assert "ValueError" in problem and "add the bot to that chat" in problem
+        good = reporter(FakeSender())
+        assert await good.check() is None
+        assert await reporter(FakeSender(), chat_id=None).check() is None
+
+    asyncio.run(go())
+
+
+def test_switched_off():
+    async def go():
+        client = FakeSender()
+        rep = reporter(client, chat_id=None)
+        assert not rep.enabled
+        rep.start()
+        rep.submit("x:", "y")
+        await rep.stop()
+        assert client.sent == [] and client.lookups == [] and rep._task is None
+
+    asyncio.run(go())
+
+
+def test_submitting_from_another_thread_is_safe():
+    async def go():
+        client = FakeSender()
+        rep = reporter(client)
+        rep.start()
+        t = threading.Thread(target=lambda: rep.submit("from a thread:", "ValueError: threaded"))
+        t.start()
+        t.join()
+        await asyncio.sleep(0.05)
+        await drain(rep)
+        assert client.texts == ["from a thread:\n\nValueError: threaded"]
+        # and before the reporter runs, or after it has stopped, nothing breaks
+        await rep.stop()
+        rep.submit("late:", "x")
+        reporter(FakeSender()).submit("never started:", "x")
+
+    asyncio.run(go())
+
+
+def test_stop_lets_queued_reports_go_out():
+    async def go():
+        client = FakeSender()
+        rep = reporter(client)
+        rep.start()
+        rep.submit("last words:", "ValueError: bye")
+        await rep.stop()
+        assert client.texts == ["last words:\n\nValueError: bye"]
+
+    asyncio.run(go())
+
+
+def test_the_peer_is_looked_up_once():
+    async def go():
+        client = FakeSender()
+        rep = reporter(client)
+        rep.start()
+        for i in range(3):
+            rep.submit(f"e{i}:", f"ValueError: {i}")
+        await drain(rep)
+        assert len(client.sent) == 3 and client.lookups == [CHAT]
+        await rep.stop()
+
+    asyncio.run(go())
+
+
+@pytest.mark.parametrize("raw,label", [("Task-12", ""), ("", ""), ("sender", "sender")])
+def test_task_labels(raw, label):
+    task = SimpleNamespace(get_name=lambda: raw)
+    assert errorlog._task_label(task) == label
+    assert errorlog._task_label(None) == ""
diff --git a/tests/test_flows.py b/tests/test_flows.py
new file mode 100644
index 0000000000000000000000000000000000000000..4de6b2d160297815edb6dad6de5770caf9f7b703
--- /dev/null
+++ b/tests/test_flows.py
@@ -0,0 +1,148 @@
+import asyncio
+
+from app.tgutil import button_url
+from .harness import App, norm
+
+SEEDED = [[{"t": "Download Episodes 01 to 20", "u": "https://t.me/oldbot?start=aaa"}]]
+
+
+async def make_app(tmp_path):
+    app = App(tmp_path)
+    await app.start()
+    await app.db.save_channel(1, 5, "Anime Channel", "animech", 1)
+    return app
+
+
+def sent_markup(app, i=-1):
+    return app.tg.sent[i][3]["buttons"]
+
+
+def test_suggestion_flow_end_to_end(tmp_path):
+    async def run():
+        app = await make_app(tmp_path)
+        await app.db.create_post(channel_id=1, message_id=10, status="sent", source="bot", text="Click the button below to download 👇", entities=[], buttons=SEEDED)
+
+        await app.text("/new")
+        assert "Suggestion" in app.out.last_text and "Download Episodes 21 to 40" in app.out.last_text
+        await app.press(app.out.callback_data("Use suggestion"))
+        assert "Send the link" in app.out.last_text
+        await app.text("https://t.me/newbot?start=zzz")
+        assert "Ready" in app.out.last_text and "Publish" in str(app.out.last_buttons())
+
+        pid = int(app.out.callback_data("Publish").split(":")[1])
+        await app.press(f"pb:{pid}")
+        assert "Publish this post" in app.out.last_text
+        await app.press(f"pby:{pid}")
+        assert "Published" in app.out.last_text
+        kind, peer, msg, kw = app.tg.sent[-1]
+        assert msg == "Click the button below to download 👇"
+        btn = sent_markup(app).rows[0].buttons[0]
+        assert btn.text == "Download Episodes 21 to 40" and button_url(btn) == "https://t.me/newbot?start=zzz"
+        p = await app.db.get_post(pid)
+        assert p.status == "sent" and p.message_id == 100
+
+        # the next suggestion moves on again
+        await app.text("/new")
+        assert "Download Episodes 41 to 60" in app.out.last_text
+        await app.db.close()
+
+    asyncio.run(run())
+
+
+def test_customize_new_post_with_buttons_and_edit_live(tmp_path):
+    async def run():
+        app = await make_app(tmp_path)
+        await app.text("/new")  # nothing to suggest yet -> asks for the post
+        assert "Send the post now" in app.out.last_text
+        await app.text("Hello *world*")  # typed as Markdown: read as formatting (MARKUP_INPUT=false would keep it literal)
+        assert "buttons" in app.out.last_text.lower()
+        await app.text("Get it - https://t.me/bot?start=1 | Join - t.me/animech\nMirror - https://example.com/x")
+        pid = int(app.out.callback_data("Publish").split(":")[1])
+        post = await app.db.get_post(pid)
+        assert post.text == "Hello world" and post.entities == [{"k": "italic", "o": 6, "l": 5}]
+        assert [len(r) for r in post.buttons] == [2, 1]
+        await app.press(f"pb:{pid}")
+        await app.press(f"pby:{pid}")
+        assert app.tg.sent[-1][2] == "Hello world"
+
+        # edit the live post: change a button's text, then its link
+        await app.press(f"bs:{pid}:0:0")
+        assert "Get it" in app.out.last_text
+        await app.press(f"bt:{pid}:0:0")
+        await app.text("Download now")
+        await app.press(f"bu:{pid}:0:0")
+        await app.text("https://t.me/goku?start=1")
+        last_edit = app.tg.edits[-1][2]
+        assert last_edit.message == "Hello world"
+        b = last_edit.reply_markup.rows[0].buttons[0]
+        assert b.text == "Download now" and button_url(b) == "https://t.me/goku?start=1"
+
+        # reorder: move the first button right, then down into its own row
+        await app.press(f"bm:{pid}:0:0:r")
+        rows = (await app.db.get_post(pid)).buttons
+        assert [b["t"] for b in rows[0]] == ["Join", "Download now"]
+        await app.press(f"bm:{pid}:0:1:d")
+        rows = (await app.db.get_post(pid)).buttons
+        assert [[b["t"] for b in r] for r in rows] == [["Join"], ["Mirror", "Download now"]]
+
+        # delete a button
+        await app.press(f"bd:{pid}:0:0")
+        assert [[b["t"] for b in r] for r in (await app.db.get_post(pid)).buttons] == [["Mirror", "Download now"]]
+        live = app.tg.edits[-1][2].reply_markup
+        assert [b.text for b in live.rows[0].buttons] == ["Mirror", "Download now"]
+
+        # edit text of the live post keeps the buttons
+        await app.press(f"et:{pid}")
+        await app.text("New text")
+        req = app.tg.edits[-1][2]
+        assert req.message == "New text" and len(req.reply_markup.rows[0].buttons) == 2
+
+        # delete from the channel
+        await app.press(f"dly:{pid}:a")
+        assert app.tg.deleted == [[100]] and await app.db.get_post(pid) is None
+        await app.db.close()
+
+    asyncio.run(run())
+
+
+def test_bad_input_and_permissions(tmp_path):
+    async def run():
+        app = await make_app(tmp_path)
+        await app.text("/new")
+        await app.text("A post")
+        await app.text("this has no link")
+        assert "No link found" in norm(app.out.last_text)
+        await app.text("/skip")
+        pid = int(app.out.callback_data("Publish").split(":")[1])
+        await app.press(f"ba:{pid}")
+        await app.text("Only text")  # asks for the link next
+        assert "send the link" in app.out.last_text.lower()
+        await app.text("not a link")
+        assert "doesn't look like a link" in norm(app.out.last_text)
+        await app.text("https://t.me/bot?start=q")
+        assert (await app.db.get_post(pid)).buttons[0][0]["u"] == "https://t.me/bot?start=q"
+
+        # a non-owner is rejected everywhere
+        app.uid = 999
+        await app.text("/swap @a @b")
+        assert "private" in app.out.last_text.lower()
+        await app.db.close()
+
+    asyncio.run(run())
+
+
+def test_drafts_list_and_discard(tmp_path):
+    async def run():
+        app = await make_app(tmp_path)
+        await app.text("/new")
+        await app.text("draft one")
+        await app.text("/skip")
+        await app.text("/posts")
+        await app.press("pc:d:0")
+        assert "Drafts" in app.out.last_text and "draft one" in str(app.out.last_buttons())
+        pid = int(app.out.callback_data("draft one").split(":")[1])
+        await app.press(f"dly:{pid}:b")
+        assert await app.db.get_post(pid) is None
+        await app.db.close()
+
+    asyncio.run(run())
diff --git a/tests/test_handleswap.py b/tests/test_handleswap.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ae692f4e6d1538c42ab08fd2a241a1d63c3274f
--- /dev/null
+++ b/tests/test_handleswap.py
@@ -0,0 +1,260 @@
+"""/handleswap @bro @sis: the username written in posts changes - links, hyperlinks and button links do not."""
+import asyncio
+
+import pytest
+from telethon import types
+
+from app.handleswap import compute_handle_changes, find_mention_spans, mention_regex
+from app.handlers.replace import parse_replace_args
+from app.replace_engine import ScanOptions, apply_channel, scan_channel, undo_batch
+from app.tgutil import button_url, is_callback_button
+from telethon.helpers import add_surrogate
+
+from .dbutil import db_url_for, fresh_db
+from .fakes import FakeClient, cb_btn, make_msg, markup, url_btn
+from .harness import App, norm
+
+
+def run(coro):
+    return asyncio.run(coro)
+
+
+def change(text, entities=None, mk=None):
+    return compute_handle_changes(make_msg(1, text, entities, mk), "bro", "sis")
+
+
+def utf16(s, start, length):
+    return s.encode("utf-16-le")[start * 2 : (start + length) * 2].decode("utf-16-le")
+
+
+# ------------------------------------------------------------------------------- what counts as a username
+def test_only_whole_usernames_are_found():
+    rx = mention_regex("bro")
+    found = lambda s: [m.group(0) for m in rx.finditer(s)]  # noqa: E731
+    assert found("Join @bro now") == ["@bro"]
+    assert found("@bro") == ["@bro"] and found("(@BRO)!") == ["@BRO"] and found("a,@bro.") == ["@bro"]
+    assert found("two: @bro @Bro") == ["@bro", "@Bro"]
+    assert found("Contact:@bro") == ["@bro"]
+    # parts of other things are not usernames
+    assert found("@bro_bot @brother @bro2") == []
+    assert found("mail me: a@bro.com") == []
+    assert found("https://example.com/x?u=@bro") == []
+    assert found("t.me/bro and https://t.me/bro?start=1") == []
+
+
+def test_a_username_in_text_is_swapped_and_the_rest_stays():
+    text = "Join @bro and @Bro_bot, mail a@bro.com, https://t.me/bro?x=@bro, see t.me/bro, (@BRO)!"
+    ch, skipped = change(text)
+    assert ch.n_typed == 2 and ch.n_links == 0 and ch.n_buttons == 0 and skipped == 0
+    assert ch.new_text == "Join @sis and @Bro_bot, mail a@bro.com, https://t.me/bro?x=@bro, see t.me/bro, (@sis)!"
+    assert change("nothing to see here")[0] is None
+    assert change("only links: t.me/bro https://t.me/bro?start=a")[0] is None
+
+
+def test_formatting_stays_in_place_when_the_name_gets_longer_or_shorter():
+    text = "Hi @bro, welcome to @bro's place 😀 and @bro"
+    ents = [
+        types.MessageEntityBold(3, 4),  # exactly the first @bro
+        types.MessageEntityMention(3, 4),
+        types.MessageEntityItalic(9, 7),  # ", welcome"[..] runs across text after it
+        types.MessageEntityCode(len(text.encode("utf-16-le")) // 2 - 4, 4),  # the last @bro
+    ]
+    ch, _ = compute_handle_changes(make_msg(1, text, ents), "bro", "sister")
+    assert ch.new_text == "Hi @sister, welcome to @sister's place 😀 and @sister"
+    bold, mention, italic, code = ch.new_entities
+    assert utf16(ch.new_text, bold.offset, bold.length) == "@sister" == utf16(ch.new_text, mention.offset, mention.length)
+    assert utf16(ch.new_text, code.offset, code.length) == "@sister"
+    assert italic.offset == 3 + 7 + 2 and italic.length == 7  # starts after the longer name: ", welcome" begins 3+7
+    # shorter name
+    ch, _ = compute_handle_changes(make_msg(1, "x @brother y", [types.MessageEntityBold(0, 1)]), "brother", "bo")
+    assert ch.new_text == "x @bo y" and ch.new_entities[0].offset == 0
+
+
+def test_links_hyperlinks_and_emails_are_left_alone():
+    text = "@bro writes: https://example.com/p?u=@bro, mail x@bro.com or see @bro"
+    url_start = len("@bro writes: ")
+    url = "https://example.com/p?u=@bro"
+    ents = [
+        types.MessageEntityUrl(url_start, len(url)),
+        types.MessageEntityEmail(text.index("x@bro.com"), len("x@bro.com")),
+        types.MessageEntityTextUrl(len(text) - 4, 4, "https://t.me/bro"),  # the last "@bro" is a hyperlink
+    ]
+    ch, skipped = compute_handle_changes(make_msg(1, text, ents), "bro", "sis")
+    assert ch.n_typed == 1 and ch.new_text.startswith("@sis writes: https://example.com/p?u=@bro, mail x@bro.com")
+    assert ch.new_text.endswith("or see @bro")  # the hyperlinked @bro is a hyperlink: not touched
+    assert skipped == 1
+    link = [e for e in ch.new_entities if isinstance(e, types.MessageEntityTextUrl)][0]
+    assert link.url == "https://t.me/bro"  # and its link is exactly as it was
+
+
+def test_button_names_change_but_their_links_do_not():
+    mk = markup(
+        [url_btn("Join @bro", "https://t.me/bro?start=1"), cb_btn("👍 @bro", b"r")],
+        [url_btn("Open https://t.me/bro", "https://t.me/bro")],
+    )
+    ch, _ = change("hello", mk=mk)
+    assert (ch.n_typed, ch.n_buttons, ch.text_changed, ch.callbacks) == (0, 1, False, True)
+    rows = ch.new_markup.rows
+    assert rows[0].buttons[0].text == "Join @sis" and button_url(rows[0].buttons[0]) == "https://t.me/bro?start=1"
+    assert is_callback_button(rows[0].buttons[1]) and rows[0].buttons[1].text == "👍 @bro"  # another bot's button
+    assert rows[1].buttons[0].text == "Open https://t.me/bro"
+    # no username anywhere: nothing to do and the keyboard object is not rebuilt
+    assert change("hello", mk=markup([url_btn("Go", "https://t.me/bro")]))[0] is None
+
+
+def test_find_mention_spans_counts_what_it_skips():
+    sur = add_surrogate("@bro and @bro")
+    spans, skipped = find_mention_spans(sur, [types.MessageEntityTextUrl(9, 4, "https://x.y")], "bro")
+    assert spans == [(0, 4)] and skipped == 1
+
+
+def test_the_arguments():
+    assert parse_replace_args("@bro @sis", handles=True)[:2] == ("bro", "sis")
+    assert parse_replace_args("bro sis --channel @a --last 50", handles=True)[2] == {"channel": "@a", "last": 50, "posts": False, "typed": None}
+    for bad in ("@bro", "@bro @bro", "@bro @sis --posts", "@bro @sis --no-typed", "@b!ro @sis"):
+        with pytest.raises(ValueError):
+            parse_replace_args(bad, handles=True)
+
+
+# ------------------------------------------------------------------------------- the engine
+def build():
+    return {
+        1: make_msg(1, "Join @bro today", [types.MessageEntityBold(5, 4)], out=True),
+        2: make_msg(2, "Episodes", markup=markup([url_btn("Download @bro", "https://t.me/bro?start=A"), cb_btn("👍 3", b"r")]), out=True),
+        3: make_msg(3, "link only https://t.me/bro?start=B", [types.MessageEntityUrl(10, 24)]),
+        4: make_msg(4, "by @bro_bot"),
+        5: make_msg(5, "@BRO wrote this", media=None),  # someone else's post
+        7: types.MessageEmpty(id=7, peer_id=types.PeerChannel(1)),
+    }
+
+
+async def engine_setup(tmp_path, msgs):
+    db = await fresh_db(db_url_for(tmp_path))
+    await db.save_channel(1, 5, "Test", None, 99)
+    return db, await db.get_channel(1), FakeClient(msgs, pts=8)
+
+
+def test_scan_apply_and_undo(tmp_path):
+    async def go():
+        msgs = build()
+        db, ch, client = await engine_setup(tmp_path, msgs)
+        opts = ScanOptions("bro", "sis", mode="handles")
+        scan = await scan_channel(client, ch, opts, can_edit_others=True)
+        assert set(scan.infos) == {1, 2, 5}
+        assert (scan.infos[1].typed, scan.infos[2].buttons, scan.infos[2].callbacks) == (1, 1, True)
+        assert scan.foreign == 1
+
+        await db.create_batch("hs1", "bro", "sis", 99)
+        res = await apply_channel(client, db, scan, opts, "hs1", 99, edit_delay=0)
+        assert (res.edited, res.failed) == (3, [])
+        assert msgs[1].message == "Join @sis today" and (msgs[1].entities[0].offset, msgs[1].entities[0].length) == (5, 4)
+        assert msgs[5].message == "@sis wrote this"
+        rows = msgs[2].reply_markup.rows
+        assert rows[0].buttons[0].text == "Download @sis" and button_url(rows[0].buttons[0]) == "https://t.me/bro?start=A"
+        assert is_callback_button(rows[0].buttons[1])  # the other bot's button survives the text edit
+        assert msgs[2].message == "Episodes"  # only the button name changed
+        assert msgs[3].message == "link only https://t.me/bro?start=B" and msgs[4].message == "by @bro_bot"
+
+        # My posts follows
+        p1 = await db.find_by_message(1, 1)
+        assert p1.text == "Join @sis today"
+        p2 = await db.find_by_message(1, 2)
+        assert p2.buttons[0][0] == {"t": "Download @sis", "u": "https://t.me/bro?start=A"}
+
+        back = await undo_batch(client, db, "hs1", edit_delay=0)
+        assert (back.restored, back.failed) == (3, [])
+        assert msgs[1].message == "Join @bro today" and msgs[5].message == "@BRO wrote this"
+        assert msgs[2].reply_markup.rows[0].buttons[0].text == "Download @bro"
+        await db.close()
+
+    run(go())
+
+
+# --------------------------------------------------------------------------------- the command
+async def flow_app(tmp_path, **cfg):
+    app = App(tmp_path, **cfg)
+    await app.start()
+    await app.db.save_channel(1, 5, "Anime Channel", "animech", 1)
+    app.tg.msgs = build()
+    app.tg._top = 8
+    return app
+
+
+def test_the_whole_command_with_undo(tmp_path):
+    async def go():
+        app = await flow_app(tmp_path)
+        await app.text("/handleswap")
+        assert "Usage: /handleswap @old @new" in norm(app.out.last_text)
+        await app.text("/handleswap @bro @sis --posts")
+        assert "Unknown option --posts" in app.out.last_text
+        await app.text("/handleswap @bro")
+        assert "old and the new username" in app.out.last_text
+
+        await app.text("/handleswap @bro @sis")
+        shown = norm(app.out.last_text)
+        assert "swap the username @bro → @sis" in shown and "3 post(s) to change" in shown
+        assert "3 mention(s) in the text" not in shown and "2 mention(s) in the text, 1 in button names" in shown
+        assert "Nothing has been changed yet" in shown and "Apply to 3 post(s)" in str(app.out.last_buttons())
+        assert app.tg.msgs[1].message == "Join @bro today"  # still untouched
+
+        await app.press(app.out.callback_data("Apply to 3"))
+        done = norm(app.out.last_text)
+        assert "Done - username swap @bro → @sis" in done and "edited: 3" in done
+        assert app.tg.msgs[1].message == "Join @sis today" and app.tg.msgs[5].message == "@sis wrote this"
+        assert app.tg.msgs[2].reply_markup.rows[0].buttons[0].text == "Download @sis"
+        assert "Undo this swap" in str(app.out.last_buttons())
+
+        await app.text("/undo")
+        assert "Undo the username swap @bro → @sis" in norm(app.out.last_text) and "3 post(s)" in norm(app.out.last_text)
+        await app.press(app.out.callback_data("Yes, undo"))
+        assert "Restored 3 post(s)" in norm(app.out.last_text)
+        assert app.tg.msgs[1].message == "Join @bro today" and app.tg.msgs[2].reply_markup.rows[0].buttons[0].text == "Download @bro"
+        await app.db.close()
+
+    run(go())
+
+
+def test_nothing_to_swap_and_only_the_owner(tmp_path):
+    async def go():
+        app = await flow_app(tmp_path)
+        await app.text("/handleswap @nobody @sis")
+        assert "Nothing to change" in app.out.last_text and "Apply" not in str(app.out.last_buttons())
+        app.uid = 99
+        await app.text("/handleswap @bro @sis")
+        assert "private" in app.out.last_text
+        app.uid = 1
+        await app.text("/undo")
+        assert "nothing to undo" in app.out.last_text
+        await app.db.close()
+
+    run(go())
+
+
+def test_it_can_be_limited_to_one_channel(tmp_path):
+    async def go():
+        app = await flow_app(tmp_path)
+        await app.text("/handleswap @bro @sis --channel @nosuchchannel")
+        assert "isn't registered" in norm(app.out.last_text)
+        await app.text("/handleswap @bro @sis --channel @animech")
+        assert "Apply to 3 post(s)" in str(app.out.last_buttons())
+        await app.db.close()
+
+    run(go())
+
+
+def test_replace_still_works_after_the_refactor(tmp_path):
+    async def go():
+        app = await flow_app(tmp_path)
+        app.tg.msgs[3].reply_markup = markup([url_btn("Get", "https://t.me/bro?start=1")])
+        await app.text("/swap @bro @sis")
+        shown = norm(app.out.last_text)
+        assert "replace @bro → @sis" in shown and "Apply to" in str(app.out.last_buttons())
+        await app.press(app.out.callback_data("Apply to"))
+        assert "Done - @bro → @sis" in norm(app.out.last_text)
+        assert button_url(app.tg.msgs[3].reply_markup.rows[0].buttons[0]) == "https://t.me/sis?start=1"
+        assert app.tg.msgs[1].message == "Join @bro today"  # /swap never touches a plain username
+        await app.text("/undo")
+        assert "Undo the replace @bro → @sis" in norm(app.out.last_text)
+        await app.db.close()
+
+    run(go())
diff --git a/tests/test_held_back.py b/tests/test_held_back.py
new file mode 100644
index 0000000000000000000000000000000000000000..26b1796002ace5068d6fe9ad6cce76d123900893
--- /dev/null
+++ b/tests/test_held_back.py
@@ -0,0 +1,644 @@
+"""A post Telegram holds back - a copyright strike shows "This message couldn't be displayed on your device due to
+copyright infringement" instead of the post: /shift builds the copy from what My posts saved of it, /repost leaves it
+alone. The notice itself is never copied."""
+import asyncio
+
+from telethon import functions, types
+
+from app.repost_engine import RepostOptions, plan_repost, saved_lookup
+from app.restrictions import PLACEHOLDER_NOTE
+from app.shift_engine import run_shift
+from app.tgutil import button_url
+
+from .dbutil import db_url_for, fresh_db
+from .fakes import FakeChannelClient, make_msg, markup, photo_media, rpc, service_msg, url_btn
+from .harness import norm
+from .test_repost_flow import fill, make_app
+from .test_restricted import CHANNEL_NOTICE, NOTICE, strike
+from .test_shift import SRC, old_posts, shift_app
+from .test_sync import saved
+
+
+def run(coro):
+    return asyncio.run(coro)
+
+
+def originals():
+    """The posts of the source channel as they were before the strike."""
+    return {
+        1: make_msg(1, "Welcome", [types.MessageEntityBold(0, 7)]),
+        2: make_msg(
+            2, "Episode 2 is out", [types.MessageEntityBold(0, 9)],
+            markup=markup([url_btn("Download", "https://t.me/goku?start=AAA")]),
+        ),
+        3: make_msg(3, "Caption with link", [types.MessageEntityTextUrl(13, 4, "https://t.me/srcch/5")], media=photo_media(31)),
+        4: service_msg(4),
+        5: make_msg(5, "Fifth", reply_to=2),
+        6: make_msg(6, "Sixth"),
+    }
+
+
+def held_version(m, flagged=True):
+    """What Telegram shows of post `m` after the strike: the notice in place of the post (and, if `flagged`, its own
+    restriction mark on the message). Id, album and reply are still there."""
+    h = make_msg(
+        m.id, NOTICE, out=m.out, grouped_id=m.grouped_id, reply_to=m.reply_to.reply_to_msg_id if m.reply_to else None
+    )
+    return strike(h) if flagged else h
+
+
+def live_posts(orig, held, flagged=True):
+    return {i: (held_version(m, flagged) if i in held else m) for i, m in orig.items()}
+
+
+async def save_rows(db, orig, skip=()):
+    for i, m in orig.items():
+        if i not in skip and not isinstance(m, types.MessageService):
+            await saved(db, m)
+
+
+async def held_setup(tmp_path, *, held=(2, 3, 5), no_row=(), flagged=True, file_available=True, orig=None, last=None):
+    """The source (id 1) after the strike, the destination (id 2) and a shift s1 over all of it; My posts has what the
+    source's posts looked like before."""
+    orig = originals() if orig is None else orig
+    src = FakeChannelClient(live_posts(orig, held, flagged), username="srcch", title="Anime Source")
+    dst = src.add_channel(FakeChannelClient(old_posts(), username="dstch", cid=2, title="Anime Backup"))
+    if file_available:  # Telegram still knows the files: they were not taken down
+        for m in orig.values():
+            src._remember_media(m)
+    db = await fresh_db(db_url_for(tmp_path))
+    await db.save_channel(1, 5, "Anime Source", "srcch", 1)
+    await db.save_channel(2, 6, "Anime Backup", "dstch", 1)
+    await save_rows(db, orig, no_row)
+    await db.create_shift("s1", src=SRC, dst_channel_id=2, first_id=1, last_id=last or max(orig), user_id=1)
+    return src, dst, db, await db.get_channel(2), await db.get_shift("s1")
+
+
+def forwarded_ids(chan):
+    return [i for r in chan.requests if isinstance(r, functions.messages.ForwardMessagesRequest) for i in r.id]
+
+
+def sent(chan, kind):
+    return [r for r in chan.requests if isinstance(r, kind)]
+
+
+def shown(chan):
+    return {i: m.message for i, m in chan.msgs.items() if i > 10}
+
+
+# ============================================================================================ /shift, engine
+def test_a_held_back_post_is_copied_from_my_posts_and_never_as_the_notice(tmp_path):
+    async def go():
+        for flagged in (True, False):  # Telegram's own mark on the message, or only the notice as its text
+            src, dst, db, dst_row, shift = await held_setup(tmp_path / str(flagged), flagged=flagged)
+            res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+            assert (res.failed, res.aborted, res.held_back, res.media_lost) == ([], None, [], [])
+            assert res.from_saved == 3 and res.copied_units == 5 and res.used_saved
+            # copies: 1->11 2->12 3->13 5->14 6->15 (4 is a service message)
+            assert shown(dst) == {
+                11: "Welcome", 12: "Episode 2 is out", 13: "Caption with link", 14: "Fifth", 15: "Sixth"
+            }
+            assert not any(NOTICE in (m.message or "") for m in dst.msgs.values())
+            # only the posts Telegram shows as they are were copied by Telegram itself
+            assert forwarded_ids(dst) == [1, 6]
+            # text, formatting and buttons come from My posts
+            assert [(e.offset, e.length) for e in dst.msgs[12].entities] == [(0, 9)]
+            btn = dst.msgs[12].reply_markup.rows[0].buttons[0]
+            assert (btn.text, button_url(btn)) == ("Download", "https://t.me/goku?start=AAA")
+            # the photo of the saved post is there, and the link to the post that was copied later points at its copy
+            assert dst.msgs[13].media.photo.id == 31
+            assert dst.msgs[13].entities[0].url == "https://t.me/dstch/14"
+            # a post that answered another answers the copy of it
+            assert dst.msgs[14].reply_to.reply_to_msg_id == 12
+            # My posts knows the copies as they are
+            row = await db.find_by_message(2, 13)
+            assert (row.text, row.media_kind) == ("Caption with link", "photo")
+            assert (await db.find_by_message(2, 12)).buttons == [[{"t": "Download", "u": "https://t.me/goku?start=AAA"}]]
+            # the source is only read
+            assert not [r for r in src.requests if type(r).__name__.startswith(("Edit", "Delete", "Send", "Forward"))]
+            await db.close()
+
+    run(go())
+
+
+def test_a_post_that_telegram_shows_as_it_is_still_comes_from_the_channel(tmp_path):
+    async def go():
+        src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(2,))
+        # My posts has an older text for post 1 (somebody edited it and the sync did not run yet): the channel wins
+        row = await db.find_by_message(1, 1)
+        await db.update_post(row.id, text="an older text")
+        res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+        assert res.from_saved == 1 and res.held_back == []
+        assert dst.msgs[11].message == "Welcome" and dst.msgs[12].message == "Episode 2 is out"
+        assert forwarded_ids(dst) == [1, 3, 6]  # post 5 answers a post, so it is posted again; 2 comes from My posts
+        await db.close()
+
+    run(go())
+
+
+def test_a_post_with_telegrams_mark_comes_from_my_posts_even_when_telegram_still_hands_it_out(tmp_path):
+    """The rule of a struck channel: what My posts saved wins over what Telegram hands out now - however intact that
+    looks. Only a post without a saved copy is copied as Telegram hands it out (it is the post itself, not a notice)."""
+
+    async def go():
+        orig = originals()
+        live = dict(orig)
+        live[2] = strike(make_msg(2, "Episode 2 is out", [types.MessageEntityBold(0, 9)], markup=orig[2].reply_markup))
+        live[3] = strike(make_msg(3, "Caption as Telegram hands it out", media=photo_media(31)))  # differs from My posts
+        src = FakeChannelClient(live, username="srcch", title="Anime Source")
+        dst = src.add_channel(FakeChannelClient(old_posts(), username="dstch", cid=2, title="Anime Backup"))
+        for m in orig.values():
+            src._remember_media(m)
+        db = await fresh_db(db_url_for(tmp_path))
+        await db.save_channel(1, 5, "Anime Source", "srcch", 1)
+        await db.save_channel(2, 6, "Anime Backup", "dstch", 1)
+        await save_rows(db, orig, skip=(2,))  # no saved copy of post 2; post 3 has one
+        await db.create_shift("s1", src=SRC, dst_channel_id=2, first_id=1, last_id=6, user_id=1)
+        res = await run_shift(src, db, await db.get_shift("s1"), await db.get_channel(2), 99, delay=0, settle_pause=0)
+        assert res.held_back == [] and res.failed == [] and res.copied_units == 5
+        assert res.from_saved == 1  # post 3
+        assert res.live_restricted == 1  # post 2: marked, but nothing saved to use instead and its content is intact
+        assert shown(dst) == {11: "Welcome", 12: "Episode 2 is out", 13: "Caption with link", 14: "Fifth", 15: "Sixth"}
+        assert forwarded_ids(dst) == [1, 6]  # a restricted post is never copied by Telegram itself
+        await db.close()
+
+    run(go())
+
+
+def test_a_post_that_telegram_empties_out_is_held_back_too(tmp_path):
+    async def go():
+        orig = originals()
+        live = dict(orig)
+        live[2] = strike(make_msg(2, ""), "Removed after a copyright complaint")  # nothing of the post is handed out
+        src = FakeChannelClient(live, username="srcch", title="Anime Source")
+        dst = src.add_channel(FakeChannelClient(old_posts(), username="dstch", cid=2, title="Anime Backup"))
+        db = await fresh_db(db_url_for(tmp_path))
+        await db.save_channel(1, 5, "Anime Source", "srcch", 1)
+        await db.save_channel(2, 6, "Anime Backup", "dstch", 1)
+        await save_rows(db, orig)
+        await db.create_shift("s1", src=SRC, dst_channel_id=2, first_id=1, last_id=6, user_id=1)
+        res = await run_shift(src, db, await db.get_shift("s1"), await db.get_channel(2), 99, delay=0, settle_pause=0)
+        assert res.from_saved == 1 and res.held_back == [] and res.failed == []
+        assert dst.msgs[12].message == "Episode 2 is out" and res.held_why == "Removed after a copyright complaint"
+        await db.close()
+
+    run(go())
+
+
+def test_telegrams_notice_is_never_posted_even_when_my_posts_holds_it_as_the_text(tmp_path):
+    """A saved copy made from a restricted post can hold Telegram's notice as its text (an older version did that), and a
+    post may really say it: either way it is indistinguishable from the notice, so it is not copied - and reported."""
+
+    async def go():
+        orig = originals()
+        orig[6] = make_msg(6, NOTICE)
+        src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(2, 3, 5), orig=orig, flagged=False)
+        res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+        assert res.from_saved == 3 and res.held_back == [6] and res.failed == []
+        assert shown(dst) == {11: "Welcome", 12: "Episode 2 is out", 13: "Caption with link", 14: "Fifth"}
+        assert not any(NOTICE in (m.message or "") for m in dst.msgs.values())
+        assert 6 not in forwarded_ids(dst) and res.held_why == PLACEHOLDER_NOTE
+        await db.close()
+
+    run(go())
+
+
+def test_a_saved_copy_that_holds_the_notice_is_not_used_for_a_restricted_post(tmp_path):
+    async def go():
+        orig = originals()
+        orig[5] = make_msg(5, "Fifth")  # answers nothing
+        src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(2, 3), no_row=(2,), orig=orig)
+        await db.create_post(  # what an older version saved when it synced the struck post
+            channel_id=1, message_id=2, status="sent", source="adopted", created_by=1, link_preview=False,
+            text=NOTICE, entities=[], buttons=[], media_kind=None, media_file_id=None,
+        )
+        res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+        # post 2: Telegram shows the notice and the saved copy is the notice too: nothing to copy; post 3 is fine
+        assert res.held_back == [2] and res.from_saved == 1 and res.failed == []
+        assert shown(dst) == {11: "Welcome", 12: "Caption with link", 13: "Fifth", 14: "Sixth"}
+        assert not any(NOTICE in (m.message or "") for m in dst.msgs.values())
+        await db.close()
+
+    run(go())
+
+
+def test_an_answer_to_a_post_that_could_not_be_copied_follows_when_that_post_has_its_copy(tmp_path):
+    async def go():
+        src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(2,), no_row=(2,))  # post 5 answers post 2
+        res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+        assert res.held_back == [2] and res.failed == [(5, "ReplyParentMissing")]  # it would answer nothing
+        assert shown(dst) == {11: "Welcome", 12: "Caption with link", 13: "Sixth"}
+        await save_rows(db, {2: originals()[2]})  # the saved copy arrives
+        again = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+        assert again.held_back == [] and again.failed == [] and again.copied_units == 2
+        assert dst.msgs[14].message == "Episode 2 is out" and dst.msgs[15].message == "Fifth"
+        assert dst.msgs[15].reply_to.reply_to_msg_id == 14  # the answer answers the copy
+        await db.close()
+
+    run(go())
+
+
+def test_a_held_back_post_without_a_saved_copy_is_skipped_and_reported(tmp_path):
+    async def go():
+        src, dst, db, dst_row, shift = await held_setup(tmp_path, no_row=(3,))
+        res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+        assert res.held_back == [3] and res.from_saved == 2 and res.failed == [] and res.aborted is None
+        assert shown(dst) == {11: "Welcome", 12: "Episode 2 is out", 13: "Fifth", 14: "Sixth"}
+        assert not any(NOTICE in (m.message or "") for m in dst.msgs.values())
+        assert res.held_why == NOTICE
+        # once My posts has it (a backup put back with /import) the rest can be done
+        await save_rows(db, {3: originals()[3]}, skip=())
+        again = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+        assert again.held_back == [] and again.from_saved == 1 and again.copied_units == 1 and again.skipped_done == 4
+        assert dst.msgs[15].message == "Caption with link" and dst.msgs[15].media.photo.id == 31
+        await db.close()
+
+    run(go())
+
+
+def test_a_channel_that_is_not_in_my_posts_at_all_has_nothing_to_copy_held_back_posts_from(tmp_path):
+    async def go():
+        src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(1, 2, 3, 5, 6), no_row=(1, 2, 3, 5, 6))
+        res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+        assert res.held_back == [1, 2, 3, 5, 6] and res.copied_units == 0 and res.failed == []
+        assert shown(dst) == {}
+        await db.close()
+
+    run(go())
+
+
+def test_a_post_with_nothing_saved_in_it_is_not_posted_empty(tmp_path):
+    async def go():
+        src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(6,), no_row=(6,))
+        await db.create_post(
+            channel_id=1, message_id=6, status="sent", source="adopted", created_by=1, link_preview=False,
+            text="  ", entities=[], buttons=[], media_kind=None, media_file_id=None,
+        )
+        res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+        assert res.held_back == [6] and 15 not in dst.msgs
+        await db.close()
+
+    run(go())
+
+
+# ------------------------------------------------------------------------------------------------ the media
+def test_a_file_reference_that_has_expired_is_tried_again_without_it(tmp_path):
+    async def go():
+        src, dst, db, dst_row, shift = await held_setup(tmp_path)
+        original = dst._do_SendMediaRequest
+        tries = []
+
+        def picky(req):
+            tries.append(req.media.id.file_reference)
+            if req.media.id.file_reference:  # the saved reference is old
+                raise rpc("FileReferenceExpiredError")
+            return original(req)
+
+        dst._do_SendMediaRequest = picky
+        res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+        assert tries == [b"ref31", b""] and res.media_lost == [] and res.failed == []
+        assert dst.msgs[13].media.photo.id == 31
+        await db.close()
+
+    run(go())
+
+
+def test_a_file_telegram_refuses_goes_out_without_it_and_is_reported(tmp_path):
+    async def go():
+        src, dst, db, dst_row, shift = await held_setup(tmp_path, file_available=False)  # taken down
+        res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+        assert res.media_lost == [3] and res.failed == [] and res.from_saved == 3 and res.aborted is None
+        assert dst.msgs[13].message == "Caption with link" and dst.msgs[13].media is None
+        assert len(sent(dst, functions.messages.SendMediaRequest)) == 2  # as saved, then without the file reference
+        # the entry in My posts says what the post really is
+        row = await db.find_by_message(2, 13)
+        assert (row.text, row.media_kind, row.media_file_id) == ("Caption with link", None, None)
+        await db.close()
+
+    run(go())
+
+
+def test_a_post_that_is_only_a_refused_file_fails_and_the_others_are_copied(tmp_path):
+    async def go():
+        orig = originals()
+        orig[7] = make_msg(7, "", media=photo_media(71))
+        src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(7,), orig=orig, file_available=False, last=7)
+        res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+        assert res.failed == [(7, "MediaEmptyError")] and res.media_lost == []
+        assert res.copied_units == 5 and 16 not in dst.msgs  # 1 2 3 5 6 were copied; 7 has no text to go out with
+        await db.close()
+
+    run(go())
+
+
+def test_a_held_back_album_is_rebuilt_as_an_album(tmp_path):
+    async def go():
+        orig = originals()
+        orig[8] = make_msg(8, "", media=photo_media(81), grouped_id=80)
+        orig[9] = make_msg(9, "album caption", [types.MessageEntityBold(0, 5)], media=photo_media(82), grouped_id=80)
+        src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(8, 9), orig=orig, last=9)
+        res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+        assert res.from_saved == 1 and res.held_back == [] and res.failed == []  # an album is one post
+        album = [dst.msgs[i] for i in (16, 17)]
+        assert album[0].grouped_id and album[0].grouped_id == album[1].grouped_id
+        assert [m.media.photo.id for m in album] == [81, 82]
+        assert album[1].message == "album caption" and [(e.offset, e.length) for e in album[1].entities] == [(0, 5)]
+        await db.close()
+
+    run(go())
+
+
+def test_an_album_of_which_one_picture_has_no_saved_copy_is_skipped_whole(tmp_path):
+    async def go():
+        orig = originals()
+        orig[8] = make_msg(8, "", media=photo_media(81), grouped_id=80)
+        orig[9] = make_msg(9, "album caption", media=photo_media(82), grouped_id=80)
+        src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(8, 9), no_row=(9,), orig=orig, last=9)
+        res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+        assert res.held_back == [8] and 16 not in dst.msgs
+        await db.close()
+
+    run(go())
+
+
+# ------------------------------------------------------------------------------------------------ the plan
+def test_the_plan_counts_what_is_copied_from_my_posts_and_what_is_skipped(tmp_path):
+    async def go():
+        src, dst, db, dst_row, shift = await held_setup(tmp_path, no_row=(5,))
+        lookup = saved_lookup(db, 1)
+        plan = await plan_repost(src, SRC, RepostOptions(), saved=lookup, use_saved=True)
+        # posts 1 2 3 6 are copied (2 and 3 from My posts); 5 is held back without a saved copy; 4 is a service message
+        assert (plan.units, plan.held_saved, plan.held_skipped, plan.service) == (4, 2, 1, 1)
+        assert plan.held_why == NOTICE and plan.channel_restricted is None
+        assert plan.media == 1 and plan.n_buttons == 0 and plan.error is None  # counted from the saved posts
+        # as /repost sees it: nothing held back is copied
+        plan = await plan_repost(src, SRC, RepostOptions(), saved=lookup)
+        assert (plan.units, plan.held_saved, plan.held_skipped) == (2, 0, 3)
+        await db.close()
+
+    run(go())
+
+
+def test_the_plan_says_so_when_the_whole_channel_is_restricted_and_nothing_can_be_copied(tmp_path):
+    async def go():
+        src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(1, 2, 3, 5, 6), no_row=(1, 2, 3, 5, 6))
+        src.restriction = NOTICE
+        plan = await plan_repost(src, SRC, RepostOptions(), saved=saved_lookup(db, 1), use_saved=True)
+        assert plan.channel_restricted == NOTICE and plan.units == 0 and plan.held_skipped == 5
+        assert "holds back every post" in plan.error and "no saved copy" in plan.error
+        await db.close()
+
+    run(go())
+
+
+def test_a_normal_channel_is_planned_as_before(tmp_path):
+    async def go():
+        src, dst, db, dst_row, shift = await held_setup(tmp_path, held=())
+        plan = await plan_repost(src, SRC, RepostOptions(), saved=saved_lookup(db, 1), use_saved=True)
+        assert (plan.units, plan.held_saved, plan.held_skipped, plan.held_why, plan.channel_restricted) == (5, 0, 0, None, None)
+        res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+        assert res.from_saved == 0 and res.held_back == [] and res.copied_units == 5
+        await db.close()
+
+    run(go())
+
+
+# ============================================================================================ the owner's view
+async def held_app(tmp_path, *, held=(2, 3, 5), no_row=(), file_available=True):
+    app, dst = await shift_app(tmp_path)
+    orig = originals()
+    app.tg._media.clear()  # the account knows no file yet (shift_app had filled the channel with other posts)
+    fill(app.tg, live_posts(orig, held))
+    if file_available:
+        for m in orig.values():
+            app.tg._remember_media(m)
+    await save_rows(app.db, orig, no_row)
+    return app, dst
+
+
+def buttons(app):
+    return [t for row in app.out.last_buttons() for t in row]
+
+
+def test_the_shift_plan_and_result_explain_what_comes_from_my_posts(tmp_path):
+    async def go():
+        app, dst = await held_app(tmp_path, no_row=(5,))
+        app.tg.restriction = CHANNEL_NOTICE  # the whole channel is struck: My posts is used for every post it has
+        await app.text("/shift @srcch @dstch")
+        plan = norm(app.out.last_text)
+        assert "Telegram restricts Anime Source itself" in plan and "unavailable due to copyright infringement" in plan
+        assert "4 post(s) of Anime Source are restricted by Telegram" in plan
+        assert "copied from what My posts saved of them" in plan and "not from what Telegram shows now" in plan
+        assert "Telegram shows only its notice for 1 more post(s)" in plan and "no saved copy" in plan and "/import" in plan
+        assert "4 posts" in plan  # 1, 2, 3 and 6 are copied
+        assert "The new posts are read back" in plan
+        assert not any(isinstance(r, functions.messages.SendMessageRequest) for r in dst.requests)  # a plan posts nothing
+
+        await app.press(app.out.callback_data("Start copying"))
+        done = norm(app.out.last_text)
+        assert "4 post(s) are restricted by Telegram" in done and "copied from what My posts saved of them" in done
+        assert "1 post(s): Telegram shows only its notice and My posts has no saved copy of them" in done and "#5" in done
+        assert "not everything was copied" in done  # so the rest can be tried again later
+        assert any("Try the rest again" in t for t in buttons(app))
+        assert "hides" not in done  # nothing the new posts show is restricted
+        assert not any(NOTICE in (m.message or "") for m in dst.msgs.values())
+        assert forwarded_ids(dst) == []  # a struck channel: nothing is copied by Telegram itself
+
+        # the missing copy arrives (a backup put back with /import): the rest can be copied
+        await save_rows(app.db, {5: originals()[5]})
+        await app.press(app.out.callback_data("Try the rest again"))
+        done = norm(app.out.last_text)
+        assert "message(s) copied" in done and "Undo" in " ".join(buttons(app))
+        assert dst.msgs[15].message == "Fifth"
+        await app.db.close()
+
+    run(go())
+
+
+def test_a_refused_file_is_named_in_the_result(tmp_path):
+    async def go():
+        app, dst = await held_app(tmp_path, file_available=False)
+        await app.text("/shift @srcch @dstch")
+        await app.press(app.out.callback_data("Start copying"))
+        done = norm(app.out.last_text)
+        assert "1 of them went out without their media" in done and "#3" in done
+        await app.db.close()
+
+    run(go())
+
+
+def test_the_usage_tells_about_posts_telegram_holds_back(tmp_path):
+    async def go():
+        app, _ = await shift_app(tmp_path)
+        await app.text("/shift")
+        text = norm(app.out.last_text)
+        assert "copyright infringement" in text and "copied from what My posts saved of it" in text
+        await app.db.close()
+
+    run(go())
+
+
+# ============================================================================================ /repost
+def repost_posts():
+    return {
+        1: make_msg(1, "First post"),
+        2: make_msg(2, "Second post", markup=markup([url_btn("Watch", "https://t.me/goku?start=BBB")])),
+        3: make_msg(3, "Third post"),
+    }
+
+
+def test_a_repost_never_copies_the_notice_and_never_deletes_what_it_could_not_copy(tmp_path):
+    async def go():
+        orig = repost_posts()
+        app = await make_app(tmp_path, msgs=live_posts(orig, (2,)))
+        await save_rows(app.db, orig)
+        await app.text("/repost --no-typed")
+        await app.press(app.out.callback_data("Test"))
+        plan = norm(app.out.last_text)
+        assert "Telegram holds back 1 post(s) of Test" in plan and "Copying the notice would be wrong" in plan
+        assert "2 posts" in plan  # posts 1 and 3
+        await app.press(app.out.callback_data("Start copying"))
+        done = norm(app.out.last_text)
+        assert "1 post(s) are held back by Telegram" in done and "#2" in done and "the old posts are not deleted" in done
+        assert "not everything was copied" in done
+        assert not any("Delete the old posts" in t for t in buttons(app))  # nothing may be deleted
+        # the channel: the three posts, the held back one stays as it is, two copies at the end - and no notice copy
+        texts = [m.message for _, m in sorted(app.tg.msgs.items())]
+        assert texts == ["First post", NOTICE, "Third post", "First post", "Third post"]
+        await app.db.close()
+
+    run(go())
+
+
+def test_a_repost_of_a_channel_without_held_back_posts_is_unchanged(tmp_path):
+    async def go():
+        app = await make_app(tmp_path, msgs=repost_posts())
+        await app.text("/repost --no-typed")
+        await app.press(app.out.callback_data("Test"))
+        assert "holds back" not in norm(app.out.last_text)
+        await app.press(app.out.callback_data("Start copying"))
+        done = norm(app.out.last_text)
+        assert "all posts copied in order" in done and "held back" not in done
+        assert any("Delete the old posts" in t for t in buttons(app))
+        await app.db.close()
+
+    run(go())
+
+
+# ============================================================================ a source that can't be read at all
+def unreadable(chan):
+    """The channel is banned or private for the bot: nothing in it can be read any more."""
+    chan.fail["GetMessagesRequest"] = rpc("ChannelPrivateError")
+    chan.fail["GetFullChannelRequest"] = rpc("ChannelPrivateError")
+
+
+def test_a_source_that_cannot_be_read_is_copied_from_my_posts_alone(tmp_path):
+    async def go():
+        src, dst, db, dst_row, shift = await held_setup(tmp_path, held=())
+        unreadable(src)
+        await db.set_mark("s1", "fromdb")
+        res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+        assert res.from_db and res.used_saved and res.failed == [] and res.aborted is None and res.held_back == []
+        assert res.from_saved == 5 and res.copied_units == 5
+        # copies: 1->11 2->12 3->13 5->14 6->15 (there is nothing saved of the service message 4)
+        assert shown(dst) == {11: "Welcome", 12: "Episode 2 is out", 13: "Caption with link", 14: "Fifth", 15: "Sixth"}
+        assert forwarded_ids(dst) == []  # nothing is copied by Telegram: the source can't be read
+        btn = dst.msgs[12].reply_markup.rows[0].buttons[0]
+        assert (btn.text, button_url(btn)) == ("Download", "https://t.me/goku?start=AAA")
+        assert dst.msgs[13].media.photo.id == 31
+        assert dst.msgs[13].entities[0].url == "https://t.me/dstch/14"  # the link to post 5 follows its copy
+        assert dst.msgs[14].reply_to is None  # My posts does not know what a post answered
+        assert (await db.find_by_message(2, 13)).media_kind == "photo"
+        await db.close()
+
+    run(go())
+
+
+def test_the_range_is_respected_and_a_stopped_shift_goes_on_from_my_posts(tmp_path):
+    async def go():
+        src, dst, db, dst_row, shift = await held_setup(tmp_path, held=())
+        unreadable(src)
+        await db.set_mark("s1", "fromdb")
+        calls = []
+
+        async def prog(r):
+            calls.append(r.copied_units)
+
+        res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0, progress=prog, should_stop=lambda: len(calls) >= 2)
+        assert res.stopped and res.copied_units == 2 and shown(dst) == {11: "Welcome", 12: "Episode 2 is out"}
+        again = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+        assert again.from_db and not again.stopped and again.copied_units == 3 and again.skipped_done == 2
+        assert shown(dst) == {11: "Welcome", 12: "Episode 2 is out", 13: "Caption with link", 14: "Fifth", 15: "Sixth"}
+        await db.close()
+
+    run(go())
+
+
+def test_a_post_with_nothing_to_post_is_not_taken_from_my_posts(tmp_path):
+    async def go():
+        src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(), no_row=(2,))
+        await db.create_post(
+            channel_id=1, message_id=2, status="sent", source="adopted", created_by=1, link_preview=False,
+            text="", entities=[], buttons=[], media_kind=None, media_file_id=None,
+        )
+        unreadable(src)
+        await db.set_mark("s1", "fromdb")
+        res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0)
+        assert res.copied_units == 4 and res.failed == []
+        assert shown(dst) == {11: "Welcome", 12: "Caption with link", 13: "Fifth", 14: "Sixth"}
+        await db.close()
+
+    run(go())
+
+
+def test_the_shift_command_offers_my_posts_when_the_source_can_not_be_read(tmp_path):
+    async def go():
+        app, dst = await held_app(tmp_path, held=())
+        unreadable(app.tg)
+        await app.text("/shift @srcch @dstch")
+        plan = norm(app.out.last_text)
+        assert "I can't read Anime Source" in plan and "My posts has the saved posts of it" in plan
+        assert "5 posts" in plan and "Post ids 1-6" in plan
+        assert "replies and albums" in plan and "from what My posts saved of it" in plan
+        assert dst.msgs.keys() == set(range(1, 11))  # a plan posts nothing
+
+        await app.press(app.out.callback_data("Start copying"))
+        done = norm(app.out.last_text)
+        assert "5 message(s) copied" in done and "The source can't be read, so 5 post(s) were copied" in done
+        sid = app.out.callback_data("Undo").split(":")[1]
+        assert await app.db.marks_of(sid) == {"fromdb"}
+        assert dst.msgs[12].message == "Episode 2 is out"
+
+        await app.press(app.out.callback_data("Undo"))
+        await app.press(app.out.callback_data("Yes, remove"))
+        assert "5 copied message(s) removed" in norm(app.out.last_text)
+        await app.db.close()
+
+    run(go())
+
+
+def test_the_range_of_a_shift_from_my_posts(tmp_path):
+    async def go():
+        app, dst = await held_app(tmp_path, held=())
+        unreadable(app.tg)
+        await app.text("/shift @srcch @dstch 2 3")
+        plan = norm(app.out.last_text)
+        assert "Post ids 2-3" in plan and "2 posts" in plan
+        await app.press(app.out.callback_data("Start copying"))
+        assert [m.message for i, m in sorted(dst.msgs.items()) if i > 10] == ["Episode 2 is out", "Caption with link"]
+        await app.db.close()
+
+    run(go())
+
+
+def test_an_unreadable_source_that_my_posts_does_not_know_is_still_an_error(tmp_path):
+    async def go():
+        app, dst = await shift_app(tmp_path)  # My posts has nothing of the source
+        unreadable(app.tg)
+        await app.text("/shift @srcch @dstch")
+        text = norm(app.out.last_text)
+        assert "I can't read Anime Source" in text and "no saved posts of it" in text
+        assert not any(isinstance(r, functions.messages.SendMessageRequest) for r in dst.requests)
+        await app.db.close()
+
+    run(go())
diff --git a/tests/test_history.py b/tests/test_history.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc1b7fca12f7a8a7d205919df10f675c67f6d9ab
--- /dev/null
+++ b/tests/test_history.py
@@ -0,0 +1,422 @@
+"""The posts that were in a channel before the bot was added are read into My posts - and what the sync does with a post
+that was deleted in the channel."""
+import datetime
+import itertools
+from types import SimpleNamespace
+
+from sqlalchemy import event
+from sqlalchemy.orm import Session as SyncSession
+from telethon import types
+
+from app import sync_engine
+from app.db import Post, as_utc, utcnow
+from app.sync_engine import live_fields, sync_channel
+
+from .fakes import markup, photo_media, service_msg, url_btn, video_media
+from .harness import norm
+from .test_restricted import NOTICE, strike
+from .test_sync import OLD, foreign, old_msg, opts, run, saved, world
+from .test_syncer import delete_update, make_app, three as three_posts
+
+
+def history(n, first=1):
+    return {i: old_msg(i, f"older post {i}") for i in range(first, first + n)}
+
+
+def ticking(monkeypatch, step=1.0):
+    """The sync engine's clock: every look at it is `step` seconds later than the one before."""
+    count = itertools.count(1)
+    monkeypatch.setattr(sync_engine, "time", SimpleNamespace(monotonic=lambda: next(count) * step))
+
+
+# ===================================================================================== what comes into My posts
+def test_the_older_posts_come_into_my_posts_with_everything_they_have(tmp_path):
+    async def go():
+        msgs = {
+            1: old_msg(1, "plain"),
+            2: old_msg(2, "bold", entities=[types.MessageEntityBold(0, 4)]),
+            3: old_msg(3, "with buttons", markup=markup([url_btn("Watch", "https://t.me/a/1")])),
+            4: old_msg(4, "a photo", media=photo_media(11)),
+            5: old_msg(5, "", media=video_media(21)),
+        }
+        chan, db, ch = await world(tmp_path, msgs, save=False)
+        rep = await sync_channel(chan, db, ch, opts())
+        assert rep.first_look and rep.imported == 5 and rep.history_done and rep.adopted == []
+        by = {p.message_id: p for p in await db.sent_posts(1)}
+        assert sorted(by) == [1, 2, 3, 4, 5]
+        assert by[2].entities == [{"k": "bold", "o": 0, "l": 4}]
+        assert by[3].buttons == [[{"t": "Watch", "u": "https://t.me/a/1"}]]
+        assert (by[4].media_kind, by[4].media_file_id) == (live_fields(msgs[4])["media_kind"], live_fields(msgs[4])["media_file_id"])
+        assert by[4].media_kind and by[5].media_kind and by[5].text == ""
+        assert all(p.source == "adopted" and p.created_by == 0 and p.status == "sent" for p in by.values())
+        assert as_utc(by[1].sent_at) == OLD  # when the post was sent, not when the bot found it
+        await db.close()
+
+    run(go())
+
+
+def test_service_messages_polls_and_stickers_among_the_older_posts_are_left_alone(tmp_path):
+    async def go():
+        msgs = {1: old_msg(1, "a"), 2: service_msg(2), 3: old_msg(3, ""), 4: old_msg(4, "b")}  # 3: nothing My posts can hold
+        chan, db, ch = await world(tmp_path, msgs, save=False)
+        rep = await sync_channel(chan, db, ch, opts())
+        assert rep.imported == 2 and rep.history_unsupported == 1
+        assert [p.message_id for p in await db.sent_posts(1)] == [1, 4]
+        assert 2 in chan.msgs and 3 in chan.msgs  # nothing is deleted from the channel
+        await db.close()
+
+    run(go())
+
+
+def test_posts_the_bot_already_has_are_not_taken_again(tmp_path):
+    async def go():
+        chan, db, ch = await world(tmp_path, {1: old_msg(1, "a"), 2: old_msg(2, "b"), 3: old_msg(3, "c")}, save=False)
+        await saved(db, chan.msgs[2])  # made through the bot
+        rep = await sync_channel(chan, db, ch, opts())
+        assert rep.imported == 2
+        assert (await db.find_by_message(1, 2)).source == "bot"
+        assert len(await db.sent_posts(1)) == 3
+        await db.close()
+
+    run(go())
+
+
+def test_a_restricted_old_post_and_the_notice_text_are_not_imported(tmp_path):
+    async def go():
+        msgs = {1: old_msg(1, "fine"), 2: strike(old_msg(2, "hidden")), 3: old_msg(3, NOTICE)}
+        chan, db, ch = await world(tmp_path, msgs, save=False)
+        rep = await sync_channel(chan, db, ch, opts())
+        assert rep.imported == 1 and sorted(rep.restricted) == [2, 3]
+        assert [p.message_id for p in await db.sent_posts(1)] == [1]
+        await db.close()
+
+    run(go())
+
+
+def test_a_restricted_channel_gets_no_older_posts_and_no_record(tmp_path):
+    async def go():
+        chan, db, ch = await world(tmp_path, history(5), save=False)
+        chan.restriction = NOTICE
+        rep = await sync_channel(chan, db, ch, opts())
+        assert rep.restricted_channel == NOTICE and rep.imported == 0
+        assert await db.sent_posts(1) == [] and await db.get_history(1) is None and await db.get_sync(1) is None
+        chan.restriction = None  # the strike is lifted: now the posts come in
+        rep = await sync_channel(chan, db, ch, opts())
+        assert rep.imported == 5
+        await db.close()
+
+    run(go())
+
+
+def test_switching_the_import_off_keeps_to_what_happens_from_now_on(tmp_path):
+    async def go():
+        chan, db, ch = await world(tmp_path, history(5), save=False)
+        rep = await sync_channel(chan, db, ch, opts(history=False))
+        assert rep.first_look and rep.imported == 0 and rep.history_top == 0
+        assert await db.sent_posts(1) == [] and await db.get_history(1) is None
+        await db.close()
+
+    run(go())
+
+
+# ===================================================================================== a long channel, in pieces
+def test_a_long_channel_is_read_over_several_looks_and_nothing_twice(tmp_path, monkeypatch):
+    async def go():
+        chan, db, ch = await world(tmp_path, history(450), save=False)
+        ticking(monkeypatch)
+        rep = await sync_channel(chan, db, ch, opts(history_seconds=2.5))  # two chunks of 100 fit into 2.5 "seconds"
+        assert rep.imported == 200 and not rep.history_done and (rep.history_to, rep.history_top) == (200, 450)
+        h = await db.get_history(1)
+        assert (h.top, h.next_id, h.imported, h.done) == (450, 201, 200, False)
+
+        rep = await sync_channel(chan, db, ch, opts(history_seconds=2.5))
+        assert rep.imported == 200 and rep.history_to == 400 and not rep.history_done and rep.first_look is False
+        rep = await sync_channel(chan, db, ch, opts(history_seconds=2.5))
+        assert rep.imported == 50 and rep.history_done
+        h = await db.get_history(1)
+        assert (h.next_id, h.imported, h.done) == (451, 450, True) and h.finished_at is not None
+        assert [p.message_id for p in await db.sent_posts(1)] == list(range(1, 451))
+        again = await sync_channel(chan, db, ch, opts(history_seconds=2.5))
+        assert again.imported == 0 and again.history_top == 0  # finished for good
+        await db.close()
+
+    run(go())
+
+
+def test_a_long_job_stops_the_reading_and_it_goes_on_later(tmp_path):
+    async def go():
+        chan, db, ch = await world(tmp_path, history(250), save=False)
+        long_job = {"running": False}
+
+        async def after_each_piece(rep):
+            long_job["running"] = True  # a /repost starts while the old posts are being read
+
+        rep = await sync_channel(chan, db, ch, opts(), busy=lambda: long_job["running"], progress=after_each_piece)
+        assert rep.busy and rep.imported == 100 and not rep.history_done
+        long_job["running"] = False
+        rep = await sync_channel(chan, db, ch, opts())
+        assert rep.imported == 150 and rep.history_done and not rep.busy
+        assert len(await db.sent_posts(1)) == 250
+        await db.close()
+
+    run(go())
+
+
+def test_the_reading_waits_for_a_message_that_is_too_fresh(tmp_path):
+    async def go():
+        chan, db, ch = await world(tmp_path, history(5), save=False)
+        late = foreign(chan, "sent a few seconds before the first look", age=5)  # id 6: the bot may still be saving it
+        rep = await sync_channel(chan, db, ch, opts(grace=120))
+        assert rep.imported == 5 and not rep.history_done and rep.history_to == 5
+        assert (await db.get_history(1)).next_id == 6 and await db.find_by_message(1, late.id) is None
+        late.date = OLD  # time passes
+        rep = await sync_channel(chan, db, ch, opts(grace=120))
+        assert rep.imported == 1 and rep.history_done and (await db.find_by_message(1, late.id)).text.startswith("sent a few")
+        await db.close()
+
+    run(go())
+
+
+def test_a_channel_the_bot_followed_before_the_import_existed_gets_its_older_posts_too(tmp_path):
+    async def go():
+        chan, db, ch = await world(tmp_path, history(10), save=False)
+        await db.save_sync(1, last_top=10, last_pts=10, deep=True)  # what the earlier version stored at its first look
+        later = foreign(chan, "made after that look")  # id 11
+        rep = await sync_channel(chan, db, ch, opts())
+        assert rep.first_look is False and rep.adopted == [later.id] and rep.imported == 10 and rep.history_done
+        assert (await db.get_history(1)).top == 10  # the new post belongs to the new posts, not to the older ones
+        assert len(await db.sent_posts(1)) == 11
+        await db.close()
+
+    run(go())
+
+
+def test_an_empty_channel_has_nothing_to_read(tmp_path):
+    async def go():
+        chan, db, ch = await world(tmp_path, {}, save=False)
+        rep = await sync_channel(chan, db, ch, opts())
+        assert rep.first_look and rep.imported == 0 and rep.history_top == 0  # nothing to say about the older posts
+        h = await db.get_history(1)
+        assert h.done and h.top == 0
+        await db.close()
+
+    run(go())
+
+
+def test_only_chunks_of_a_hundred_ids_are_asked_for_and_none_twice(tmp_path):
+    async def go():
+        chan, db, ch = await world(tmp_path, history(230), save=False)
+        asked = []
+        real = chan.get_messages
+
+        async def spy(peer, ids=None):
+            asked.append((min(ids), max(ids), len(ids)))
+            return await real(peer, ids=ids)
+
+        chan.get_messages = spy
+        await sync_channel(chan, db, ch, opts())
+        assert all(n <= 100 for _, _, n in asked)
+        for piece in ((1, 100, 100), (101, 200, 100), (201, 230, 30)):
+            assert asked.count(piece) == 1, (piece, asked)
+        await db.close()
+
+    run(go())
+
+
+# =================================================================================== the owner decides what comes back
+def test_forgotten_posts_stay_forgotten_even_after_a_restart(tmp_path):
+    async def go():
+        app = await make_app(tmp_path, posts=three_posts())
+        p = await app.db.find_by_message(1, 2)
+        await app.press(f"dly:{p.id}:b")  # "Only forget it in the bot"
+        assert await app.db.ignored_ids(1) == {2}
+        app.ctx.sync_ignore.clear()  # a restart forgets what was only in memory
+        await app.text("/sync")
+        assert await app.db.find_by_message(1, 2) is None
+        await app.text("/sync --history")
+        assert await app.db.find_by_message(1, 2) is None
+        assert 2 in app.tg.msgs  # it is still in the channel, the bot just does not list it
+        await app.db.close()
+
+    run(go())
+
+
+def test_sync_history_reads_the_older_posts_again(tmp_path):
+    async def go():
+        app = await make_app(tmp_path, posts=three_posts())
+        await app.text("/sync")
+        gone = await app.db.find_by_message(1, 3)
+        await app.db.delete_post(gone.id)  # removed from My posts without the "forget" mark (a mistake, a lost backup ...)
+        await app.text("/sync")  # the older posts were read already: not again
+        assert await app.db.find_by_message(1, 3) is None
+        await app.text("/sync --history")
+        text = norm(app.out.last_text)
+        assert "1 older post(s)" in text and "added to My posts" in text
+        back = await app.db.find_by_message(1, 3)
+        assert back is not None and back.source == "adopted" and back.text == "third"
+        await app.db.close()
+
+    run(go())
+
+
+def test_the_import_can_be_switched_off_but_sync_history_still_works(tmp_path):
+    async def go():
+        app = await make_app(tmp_path, posts=[], import_old_posts=False)
+        app.tg.msgs.update({i: old_msg(i, f"older {i}") for i in (1, 2, 3)})
+        app.tg._top = app.tg._pts = 3
+        await app.text("/sync")
+        assert await app.db.sent_posts(1) == [] and await app.db.get_history(1) is None
+        await app.text("/sync --history")
+        assert len(await app.db.sent_posts(1)) == 3 and norm(app.out.last_text).count("3 older post(s)") == 1
+        await app.db.close()
+
+    run(go())
+
+
+def test_the_timed_check_reads_for_a_limited_time_and_sync_reads_all_of_it(tmp_path, monkeypatch):
+    async def go():
+        app = await make_app(tmp_path, posts=[])
+        app.tg.msgs.update(history(250))
+        app.tg._top = app.tg._pts = 250
+        ticking(monkeypatch)
+        sy = app.ctx.syncer
+        sy.history_seconds = 1.5
+        await sy.run_all()  # the timed check: 100 ids
+        assert len(await app.db.sent_posts(1)) == 100
+        await app.text("/sync")  # nobody waits for a time limit here
+        assert len(await app.db.sent_posts(1)) == 250
+        assert "150 older post(s)" in norm(app.out.last_text)
+        await app.db.close()
+
+    run(go())
+
+
+def test_the_live_look_does_not_read_old_posts(tmp_path):
+    async def go():
+        app = await make_app(tmp_path, posts=[])
+        app.tg.msgs.update(history(10))
+        app.tg._top = app.tg._pts = 10
+        sy = app.ctx.syncer
+        await sy._process({1: {1, 2}}, {})  # an edit was noticed: only those ids are looked at
+        assert await app.db.sent_posts(1) == [] and await app.db.get_history(1) is None
+        await sy._process({1: set(range(1, 400))}, {})  # a burst of edits: one look at the whole channel, still no history
+        assert await app.db.get_history(1) is None
+        await app.db.close()
+
+    run(go())
+
+
+# ===================================================================================== what the sync reports
+def test_sync_reports_the_older_posts_that_came_in_and_the_ones_still_to_come(tmp_path):
+    async def go():
+        app = await make_app(tmp_path, posts=[])
+        app.tg.msgs.update(history(5))
+        app.tg._top = app.tg._pts = 5
+        late = app.tg._new("a few seconds old", None, None)  # id 6
+        late.out = False
+        late.date = utcnow() - datetime.timedelta(seconds=5)
+        await app.text("/sync")
+        text = norm(app.out.last_text)
+        assert "First look" in text and "Older posts: 5 added so far, read up to message 5 of 6" in text
+        assert "send /sync again" in text and "Everything matches" not in text
+        late.date = OLD
+        await app.text("/sync")
+        text = norm(app.out.last_text)
+        assert "1 older post(s), sent before the bot was added → added to My posts" in text
+        await app.text("/sync")
+        assert "Everything matches." in norm(app.out.last_text)
+        await app.db.close()
+
+    run(go())
+
+
+def test_sync_says_when_there_was_nothing_to_add(tmp_path):
+    async def go():
+        app = await make_app(tmp_path, posts=three_posts())
+        await app.text("/sync")
+        assert "The older posts were looked through: nothing to add" in norm(app.out.last_text)
+        await app.db.close()
+
+    run(go())
+
+
+# ============================================================================= deleted in the channel -> gone here
+def test_a_post_deleted_in_the_channel_takes_what_hangs_on_it_with_it(tmp_path):
+    async def go():
+        app = await make_app(tmp_path, posts=three_posts())
+        later = utcnow() + datetime.timedelta(hours=3)
+        await app.db.schedule_deletes(
+            [dict(channel_id=1, message_id=m, delete_at=later, group_id="g", created_by=1) for m in (2, 3)]
+        )
+        await app.db.ignore_post(1, 2)
+        await app.text("/sync")  # the first look
+        del app.tg.msgs[2]
+        app.tg._pts += 1
+        await app.text("/sync")
+        assert "1 deleted in the channel → removed from My posts (message 2)" in norm(app.out.last_text)
+        assert await app.db.find_by_message(1, 2) is None
+        assert [r.message_id for r in await app.db.pending_deletes()] == [3]  # the other post keeps its timer
+        assert await app.db.ignored_ids(1) == set()
+        await app.db.close()
+
+    run(go())
+
+
+def test_a_delete_the_bot_hears_about_while_it_runs_takes_the_same_with_it(tmp_path):
+    async def go():
+        app = await make_app(tmp_path, posts=three_posts())
+        later = utcnow() + datetime.timedelta(hours=3)
+        await app.db.schedule_deletes([dict(channel_id=1, message_id=3, delete_at=later, group_id="g", created_by=1)])
+        del app.tg.msgs[3]
+        await app.raw(delete_update(1, [3]))
+        assert await app.db.find_by_message(1, 3) is None
+        assert await app.db.pending_deletes() == [] and await app.db.pending_deletes(status="failed") == []
+        assert len(await app.db.sent_posts(1)) == 2
+        await app.db.close()
+
+    run(go())
+
+
+def test_forgetting_posts_counts_only_the_posts(tmp_path):
+    async def go():
+        chan, db, ch = await world(tmp_path, three_posts_dict())
+        later = utcnow() + datetime.timedelta(hours=1)
+        await db.schedule_deletes([dict(channel_id=1, message_id=9, delete_at=later, group_id="g", created_by=1)])  # no post there
+        assert await db.forget_posts(1, [9, 2]) == 1
+        assert await db.pending_deletes() == []
+        assert await db.forget_posts(1, []) == 0
+        await db.close()
+
+    run(go())
+
+
+def three_posts_dict():
+    return {m.id: m for m in three_posts()}
+
+
+# ================================================================================================== bulk saving
+def test_saving_many_posts_at_once_survives_a_post_saved_by_someone_else_a_moment_earlier(tmp_path):
+    async def go():
+        chan, db, ch = await world(tmp_path, {}, save=False)
+        items = [(i, {"text": f"post {i}", "entities": [], "buttons": []}, OLD) for i in (1, 2, 3)]
+        fired = []
+
+        def clash(session, flush_context, instances):
+            if fired:
+                return
+            fired.append(1)
+            first = next(o for o in session.new if isinstance(o, Post))
+            session.add(Post(channel_id=first.channel_id, message_id=first.message_id, status="sent", source="bot"))
+
+        event.listen(SyncSession, "before_flush", clash)  # the same message id twice in one save: the database refuses
+        try:
+            made = await db.adopt_many(1, items)
+        finally:
+            event.remove(SyncSession, "before_flush", clash)
+        assert fired and sorted(made) == [1, 2, 3]  # saved one by one instead
+        assert [p.text for p in await db.sent_posts(1)] == ["post 1", "post 2", "post 3"]
+        assert await db.adopt_many(1, items) == []  # and a second time there is nothing new
+        assert await db.adopt_many(1, []) == []
+        await db.close()
+
+    run(go())
diff --git a/tests/test_markup_flows.py b/tests/test_markup_flows.py
new file mode 100644
index 0000000000000000000000000000000000000000..e985664fe9dd82286ff6566b00a25218d66dca81
--- /dev/null
+++ b/tests/test_markup_flows.py
@@ -0,0 +1,272 @@
+"""Telegram formatting, HTML and Markdown in the flows that take a post's text: /new, the edits in My posts, /broadcast."""
+import asyncio
+from types import SimpleNamespace
+
+from telethon import types
+
+from app.tgutil import pack_file_id
+
+from .fakes import make_msg, photo_media
+from .harness import norm
+from .test_broadcast import broadcast, make_app as broadcast_app, posted
+from .test_flows import make_app
+
+
+def msg(text, entities=None):
+    return SimpleNamespace(raw_text=text, entities=entities or [], media=None, grouped_id=None, forward=None)
+
+
+def shapes(entities):
+    return [(type(e).__name__, e.offset, e.length) for e in entities or []]
+
+
+async def new_post(app, text, message=None, *, publish=True):
+    """/new, the text, no buttons - and publish. Returns the post id."""
+    await app.text("/new")
+    await app.text(text, message=message if message is not None else msg(text))
+    prompt = norm(app.out.last_text)
+    await app.text("/skip")
+    pid = int(app.out.callback_data("Publish").split(":")[1])
+    if publish:
+        await app.press(f"pb:{pid}")
+        await app.press(f"pby:{pid}")
+    return pid, prompt
+
+
+# ------------------------------------------------------------------------------------------------- /new
+def test_a_post_typed_in_markdown_is_published_with_the_formatting(tmp_path):
+    async def run():
+        app = await make_app(tmp_path)
+        pid, prompt = await new_post(app, "**Attack on Titan** - [watch](https://t.me/x)\n> quoted")
+        assert "Formatting read from Markdown" in prompt and "/formatting" in prompt and "buttons" in prompt.lower()
+        post = await app.db.get_post(pid)
+        assert post.text == "Attack on Titan - watch\nquoted"
+        assert post.entities == [
+            {"k": "bold", "o": 0, "l": 15},
+            {"k": "url", "o": 18, "l": 5, "u": "https://t.me/x"},
+            {"k": "quote", "o": 24, "l": 6, "c": False},
+        ]
+        kind, peer, text, kw = app.tg.sent[-1]
+        assert text == "Attack on Titan - watch\nquoted"
+        assert shapes(kw["formatting_entities"]) == [("MessageEntityBold", 0, 15), ("MessageEntityTextUrl", 18, 5), ("MessageEntityBlockquote", 24, 6)]
+        assert kw["formatting_entities"][1].url == "https://t.me/x"
+        await app.db.close()
+
+    asyncio.run(run())
+
+
+def test_a_post_typed_in_html_is_published_with_the_formatting(tmp_path):
+    async def run():
+        app = await make_app(tmp_path)
+        pid, prompt = await new_post(app, "Episode 12 & 13
secret") + assert "Formatting read from HTML" in prompt + kind, peer, text, kw = app.tg.sent[-1] + assert text == "Episode 12 & 13\nsecret" + assert shapes(kw["formatting_entities"]) == [("MessageEntityBold", 0, 10), ("MessageEntityItalic", 13, 2), ("MessageEntitySpoiler", 16, 6)] + await app.db.close() + + asyncio.run(run()) + + +def test_the_preview_shows_what_will_be_published(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await new_post(app, "**Hi** there", publish=False) + await app.press(f"pv:{pid}") + kind, peer, text, kw = [e for e in app.tg.sent if not isinstance(e[1], types.InputPeerChannel)][-1] + assert text == "Hi there" and shapes(kw["formatting_entities"]) == [("MessageEntityBold", 0, 2)] + await app.db.close() + + asyncio.run(run()) + + +def test_formatting_made_in_telegram_is_published_as_it_is(tmp_path): + async def run(): + app = await make_app(tmp_path) + ents = [types.MessageEntityBold(0, 5), types.MessageEntityTextUrl(6, 4, "https://x.com"), types.MessageEntityBlockquote(11, 3, True)] + text = "**x** y z" # looks like markup, but Telegram's own formatting wins and the text stays as typed + pid, prompt = await new_post(app, text, msg(text, ents)) + assert "Formatting read from" not in prompt + kind, peer, sent, kw = app.tg.sent[-1] + assert sent == text + assert shapes(kw["formatting_entities"]) == [("MessageEntityBold", 0, 5), ("MessageEntityTextUrl", 6, 4), ("MessageEntityBlockquote", 11, 3)] + assert kw["formatting_entities"][2].collapsed is True + await app.db.close() + + asyncio.run(run()) + + +def test_plain_text_is_published_untouched(tmp_path): + async def run(): + app = await make_app(tmp_path) + text = "5 * 3 = 15 - snake_case_name - 1 < 2 - Sub | Dub - https://example.com/a_b_c" + pid, prompt = await new_post(app, text) + assert "Formatting read from" not in prompt + kind, peer, sent, kw = app.tg.sent[-1] + assert sent == text and kw["formatting_entities"] == [] + await app.db.close() + + asyncio.run(run()) + + +def test_markup_input_off_keeps_everything_literal(tmp_path): + async def run(): + from .harness import App + + app = App(tmp_path, markup_input=False) + await app.start() + await app.db.save_channel(1, 5, "Anime Channel", "animech", 1) + pid, prompt = await new_post(app, "**kept** as typed") + assert "Formatting read from" not in prompt + kind, peer, sent, kw = app.tg.sent[-1] + assert sent == "**kept** as typed" and kw["formatting_entities"] == [] + await app.db.close() + + asyncio.run(run()) + + +def test_a_photo_with_a_markdown_caption(tmp_path): + async def run(): + app = await make_app(tmp_path) + await app.text("/new") + photo = SimpleNamespace(raw_text="**New** poster", entities=[], media=photo_media(5), grouped_id=None, forward=None) + await app.text("**New** poster", message=photo) + assert "Formatting read from Markdown" in norm(app.out.last_text) + await app.text("/skip") + pid = int(app.out.callback_data("Publish").split(":")[1]) + post = await app.db.get_post(pid) + assert post.media_kind == "photo" and post.text == "New poster" and post.entities == [{"k": "bold", "o": 0, "l": 3}] + await app.press(f"pb:{pid}") + await app.press(f"pby:{pid}") + kind, peer, media, kw = app.tg.sent[-1] + assert kind == "file" and kw["caption"] == "New poster" and shapes(kw["formatting_entities"]) == [("MessageEntityBold", 0, 3)] + await app.db.close() + + asyncio.run(run()) + + +# -------------------------------------------------------------------------------- editing in My posts +def test_the_text_of_a_published_post_can_be_changed_with_markdown(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await new_post(app, "first") + await app.press(f"et:{pid}") + assert "HTML / Markdown" in norm(app.out.last_text) and "/formatting" in norm(app.out.last_text) + await app.text("__new__ *text* here", message=msg("__new__ *text* here")) + req = app.tg.edits[-1][2] + assert req.message == "new text here" + assert shapes(req.entities) == [("MessageEntityUnderline", 0, 3), ("MessageEntityItalic", 4, 4)] + post = await app.db.get_post(pid) + assert post.text == "new text here" and [e["k"] for e in post.entities] == ["underline", "italic"] + assert "Formatting read from Markdown" in norm(app.out.last_text) + await app.db.close() + + asyncio.run(run()) + + +def test_the_text_of_a_draft_can_be_changed_with_html(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await new_post(app, "first", publish=False) + await app.press(f"et:{pid}") + await app.text("x = 1 and link", message=msg("x = 1 and link")) + post = await app.db.get_post(pid) + assert post.status == "draft" and post.text == "x = 1 and link" + assert post.entities == [{"k": "code", "o": 0, "l": 5}, {"k": "url", "o": 10, "l": 4, "u": "https://t.me/x"}] + assert "Formatting read from HTML" in norm(app.out.last_text) + await app.db.close() + + asyncio.run(run()) + + +def test_a_telegram_formatted_edit_is_kept_and_says_nothing_about_markup(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await new_post(app, "first") + await app.press(f"et:{pid}") + await app.text("*not italic*", message=msg("*not italic*", [types.MessageEntityBold(0, 12)])) + post = await app.db.get_post(pid) + assert post.text == "*not italic*" and post.entities == [{"k": "bold", "o": 0, "l": 12}] + assert "Formatting read from" not in norm(app.out.last_text) + await app.db.close() + + asyncio.run(run()) + + +def test_a_caption_edit_reads_markdown_too(tmp_path): + async def run(): + app = await make_app(tmp_path) + post = await app.db.create_post( + channel_id=1, message_id=7, status="sent", source="bot", text="old", entities=[], buttons=[], + media_kind="photo", media_file_id=pack_file_id(make_msg(1, "", media=photo_media(3))), + ) + await app.press(f"et:{post.id}") + assert "caption" in norm(app.out.last_text) + await app.text("||spoiler|| caption", message=msg("||spoiler|| caption")) + saved = await app.db.get_post(post.id) + assert saved.text == "spoiler caption" and saved.entities == [{"k": "spoiler", "o": 0, "l": 7}] + req = app.tg.edits[-1][2] + assert req.message == "spoiler caption" and shapes(req.entities) == [("MessageEntitySpoiler", 0, 7)] + await app.db.close() + + asyncio.run(run()) + + +def test_a_text_that_is_too_long_after_reading_is_refused(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await new_post(app, "first") + await app.press(f"et:{pid}") + before = len(app.tg.edits) + await app.text("x" * 4097) + assert "too long" in norm(app.out.last_text).lower() or "at most" in norm(app.out.last_text).lower() + assert len(app.tg.edits) == before and (await app.db.get_post(pid)).text == "first" + await app.db.close() + + asyncio.run(run()) + + +# ---------------------------------------------------------------------------------------- /broadcast +def test_a_broadcast_typed_in_html_reaches_every_channel_formatted(tmp_path): + async def run(): + app = await broadcast_app(tmp_path) + await app.text("/broadcast 1h") + text = "Maintenance tonight - details" + await app.text(text, message=msg(text)) + assert "Formatting read from HTML" in norm(app.out.last_text) + await app.press(app.out.callback_data("No buttons")) + await app.press(app.out.callback_data("Send to all channels")) + sent = posted(app) + assert len(sent) == 2 + for kind, peer, body, kw in sent: + assert body == "Maintenance tonight - details" + assert shapes(kw["formatting_entities"]) == [("MessageEntityBold", 0, 11), ("MessageEntityTextUrl", 22, 7)] + for cid in (1, 2): + (p,) = await app.db.sent_posts(cid) + assert p.text == "Maintenance tonight - details" and [e["k"] for e in p.entities] == ["bold", "url"] + await app.db.close() + + asyncio.run(run()) + + +def test_a_broadcast_keeps_telegram_formatting_and_plain_text(tmp_path): + async def run(): + app = await broadcast_app(tmp_path) + await broadcast(app, "/broadcast 1h", "**not read**", message=msg("**not read**", [types.MessageEntityItalic(0, 12)])) + (first, _) = posted(app) + assert first[2] == "**not read**" and shapes(first[3]["formatting_entities"]) == [("MessageEntityItalic", 0, 12)] + await app.db.close() + + asyncio.run(run()) + + +def test_a_broadcast_with_markup_input_off_stays_literal(tmp_path): + async def run(): + app = await broadcast_app(tmp_path, markup_input=False) + await broadcast(app, "/broadcast 1h", "**kept**", message=msg("**kept**")) + (first, _) = posted(app) + assert first[2] == "**kept**" and first[3]["formatting_entities"] == [] + assert "Formatting read from" not in norm(app.out.last_text) + await app.db.close() + + asyncio.run(run()) diff --git a/tests/test_no_media.py b/tests/test_no_media.py new file mode 100644 index 0000000000000000000000000000000000000000..f88ff59a47aa1486203e30bbf6b9067f23e00c17 --- /dev/null +++ b/tests/test_no_media.py @@ -0,0 +1,279 @@ +"""/shift --no-media: no file is copied - every post goes out as its text with its formatting and buttons. For a source +whose files Telegram blocks (a copyright strike), where a post that carries the file is hidden wherever it is posted.""" +import asyncio + +from telethon import functions, types + +from app.handlers.shift import USAGE, parse_shift_args +from app.repost_engine import RepostOptions, plan_repost, saved_lookup, without_files +from app.shift_engine import plan_from_my_posts, run_shift +from app.tgutil import button_url + +from .fakes import make_msg, photo_media +from .harness import norm +from .test_held_back import buttons, held_app, held_setup, forwarded_ids, originals, save_rows, shown, unreadable +from .test_restricted import CHANNEL_NOTICE +from .test_shift import SRC + + +def run(coro): + return asyncio.run(coro) + + +def with_files(): + """The source: text posts, a photo with a caption, a post that is only a photo, an album and an answer to the photo.""" + orig = originals() # 1 text, 2 text + button, 3 photo + caption, 4 service, 5 answers 2, 6 text + orig[7] = make_msg(7, "", media=photo_media(71)) # only a photo + orig[8] = make_msg(8, "", media=photo_media(81), grouped_id=80) # an album: no caption on the first picture ... + orig[9] = make_msg(9, "album caption", [types.MessageEntityBold(0, 5)], media=photo_media(82), grouped_id=80) + orig[10] = make_msg(10, "Reply to the photo", reply_to=7) + return orig + + +# ============================================================================================== the option +def test_the_option_is_understood_in_every_spelling(): + for raw in ( + "@a @b --no-media", + "@a @b -no-media", + "@a @b --nomedia", + "@a @b -nomedia", + "@a @b --NO-MEDIA", + "@a @b --no_media", + "@a @b —no-media", # a phone keyboard turns -- into a long dash + "@a @b –no-media", + "@a @b -- no-media", + "--no-media @a @b", + ): + a, b, first, last, flags = parse_shift_args(raw) + assert (a, b, first, last) == ("@a", "@b", None, None) and flags.no_media and not flags.links and not flags.profile, raw + a, b, first, last, flags = parse_shift_args("@a @b 5 9 -c --no-media -all") + assert (a, b, first, last) == ("@a", "@b", 5, 9) and flags.links and flags.profile and flags.no_media + # a channel id is not an option, and nothing is switched on by accident + a, b, first, last, flags = parse_shift_args("-1001234567890 @b") + assert (a, b) == ("-1001234567890", "@b") and not flags.no_media + try: + parse_shift_args("@a @b --nomediaa") + except ValueError as e: + assert "--no-media" in str(e) and "-all" in str(e) + else: + raise AssertionError("an unknown option must be refused") + + +def test_the_usage_describes_the_option(): + assert "--no-media" in USAGE and "no file is copied" in USAGE + + +def test_without_files_leaves_a_text_post_and_drops_a_post_that_was_only_a_file(): + photo_caption = make_msg(3, "Caption", media=photo_media(31)) + only_photo = make_msg(7, "", media=photo_media(71)) + plain = make_msg(1, "Welcome") + kept, lost = without_files([plain, photo_caption, only_photo]) + assert [m.id for m in kept] == [1, 3] and lost == 2 + assert kept[1].media is None and photo_caption.media is not None # the original message is not changed + assert without_files([only_photo]) == ([], 1) + + +# ======================================================================================== the copy loop +def test_the_files_stay_out_and_everything_else_is_copied(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(), orig=with_files(), last=10) + await db.set_mark("s1", "nomedia") + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert (res.failed, res.aborted, res.held_back) == ([], None, []) and res.no_media + assert res.copied_units == 7 and res.files_left_out == 2 and res.file_only == [7, 8] + # copies: 1->11 2->12 3->13 5->14 6->15 9->16 10->17 (4 is a service message, 7 and 8 are only files) + assert shown(dst) == { + 11: "Welcome", 12: "Episode 2 is out", 13: "Caption with link", 14: "Fifth", 15: "Sixth", + 16: "album caption", 17: "Reply to the photo", + } + assert all(m.media is None for i, m in dst.msgs.items() if i > 10) # no file anywhere + assert not sent_media(dst) + # a post without a file is still copied by Telegram itself - the answer to a post that is only a file too: it has + # no reply to keep any more + assert forwarded_ids(dst) == [1, 6, 10] + # text, formatting, buttons and the links between the copies are kept + assert [(e.offset, e.length) for e in dst.msgs[16].entities] == [(0, 5)] + btn = dst.msgs[12].reply_markup.rows[0].buttons[0] + assert (btn.text, button_url(btn)) == ("Download", "https://t.me/goku?start=AAA") + assert dst.msgs[13].entities[0].url == "https://t.me/dstch/14" + assert dst.msgs[14].reply_to.reply_to_msg_id == 12 + # the answer to a post that is only a file answers nothing - and does not wait for a copy that never comes + assert dst.msgs[17].reply_to is None and res.reply_dropped == 1 + # My posts knows the copies as they are: text, no file + row = await db.find_by_message(2, 13) + assert (row.text, row.media_kind, row.media_file_id) == ("Caption with link", None, None) + # the source was only read + assert not [r for r in src.requests if type(r).__name__.startswith(("Edit", "Delete", "Send", "Forward"))] + await db.close() + + run(go()) + + +def sent_media(chan): + return [r for r in chan.requests if isinstance(r, (functions.messages.SendMediaRequest, functions.messages.SendMultiMediaRequest))] + + +def test_without_the_option_the_files_are_copied_as_before(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(), orig=with_files(), last=10) + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert not res.no_media and res.files_left_out == 0 and res.file_only == [] + assert dst.msgs[13].media.photo.id == 31 + await db.close() + + run(go()) + + +def test_a_struck_channel_is_copied_from_my_posts_without_files(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(1, 2, 3, 5, 6, 7), orig=with_files(), last=7) + src.restriction = CHANNEL_NOTICE + await db.set_mark("s1", "nomedia") + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert (res.failed, res.aborted, res.held_back) == ([], None, []) + assert res.from_saved == 5 and res.files_left_out == 1 and res.file_only == [7] + assert shown(dst) == {11: "Welcome", 12: "Episode 2 is out", 13: "Caption with link", 14: "Fifth", 15: "Sixth"} + assert all(m.media is None for i, m in dst.msgs.items() if i > 10) and not sent_media(dst) and not forwarded_ids(dst) + await db.close() + + run(go()) + + +def test_a_source_that_cannot_be_read_is_copied_from_my_posts_without_files(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(), orig=with_files(), last=10) + unreadable(src) + await db.set_mark("s1", "fromdb") + await db.set_mark("s1", "nomedia") + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert res.from_db and res.failed == [] and res.aborted is None + # My posts has no album: its two pictures are two saved posts - the one with the caption goes out as text + assert res.files_left_out == 2 and res.file_only == [7, 8] # 3 and 9 lost their file; 7 and 8 are only files + assert shown(dst) == { + 11: "Welcome", 12: "Episode 2 is out", 13: "Caption with link", 14: "Fifth", 15: "Sixth", + 16: "album caption", 17: "Reply to the photo", + } + assert not sent_media(dst) + await db.close() + + run(go()) + + +def test_a_media_only_post_is_skipped_but_never_makes_the_shift_incomplete(tmp_path): + async def go(): + orig = {1: make_msg(1, "Welcome"), 2: make_msg(2, "", media=photo_media(21)), 3: make_msg(3, "Third")} + src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(), orig=orig, last=3) + await db.set_mark("s1", "nomedia") + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert res.file_only == [2] and res.held_back == [] and res.failed == [] and res.copied_units == 2 + await db.close() + + run(go()) + + +# ================================================================================================ the plan +def test_the_plan_counts_posts_without_their_files(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(), orig=with_files(), last=10) + lookup = saved_lookup(db, 1) + plan = await plan_repost(src, SRC, RepostOptions(), saved=lookup, use_saved=True, no_media=True) + # 1 2 3 5 6 9 10 are copied (3 and 9 without their file); 7 and 8 are only files; 4 is a service message + assert (plan.units, plan.files_left_out, plan.file_only, plan.service) == (7, 2, 2, 1) + assert (plan.media, plan.albums, plan.messages, plan.no_media) == (0, 0, 7, True) + full = await plan_repost(src, SRC, RepostOptions(), saved=lookup, use_saved=True) + assert (full.units, full.media, full.albums, full.files_left_out, full.file_only) == (8, 4, 1, 0, 0) + await db.close() + + run(go()) + + +def test_the_plan_from_my_posts_counts_posts_without_their_files(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(), orig=with_files(), last=10) + ch = await db.get_channel(1) + plan = await plan_from_my_posts(db, ch, no_media=True) + assert (plan.units, plan.files_left_out, plan.file_only, plan.media) == (7, 2, 2, 0) + await db.close() + + run(go()) + + +def test_a_range_of_nothing_but_files_is_an_error_not_an_empty_plan(tmp_path): + async def go(): + orig = {1: make_msg(1, "Welcome"), 2: make_msg(2, "", media=photo_media(21)), 3: make_msg(3, "", media=photo_media(31))} + src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(), orig=orig, last=3) + plan = await plan_repost(src, SRC, RepostOptions(), first_id=2, last_id=3, saved=saved_lookup(db, 1), use_saved=True, no_media=True) + assert plan.units == 0 and plan.file_only == 2 and "only a file" in plan.error + await db.close() + + run(go()) + + +# ========================================================================================= the owner's view +def test_the_command_plans_runs_and_reports_a_shift_without_files(tmp_path): + async def go(): + app, dst = await held_app(tmp_path, held=()) + await app.text("/shift @srcch @dstch --no-media") + plan = norm(app.out.last_text) + assert "--no-media" in plan and "no file is copied" in plan + assert "1 post(s) carry a file that stays out" in plan and "5 posts" in plan + assert not any(isinstance(r, functions.messages.SendMessageRequest) for r in dst.requests) # a plan posts nothing + + await app.press(app.out.callback_data("Start copying")) + done = norm(app.out.last_text) + assert "5 message(s) copied" in done and "(without files)" in done + assert "1 post(s) were copied as text only" in done and "their file was left out" in done + assert all(m.media is None for i, m in dst.msgs.items() if i > 10) + sid = app.out.callback_data("Undo").split(":")[1] + assert await app.db.marks_of(sid) == {"nomedia"} + await app.db.close() + + run(go()) + + +def test_a_shift_that_is_continued_goes_on_without_files(tmp_path): + async def go(): + app, dst = await held_app(tmp_path, no_row=(5,)) + app.tg.restriction = CHANNEL_NOTICE + await app.text("/shift @srcch @dstch --no-media") + await app.press(app.out.callback_data("Start copying")) + assert any("Try the rest again" in t for t in buttons(app)) # post 5: only the notice, nothing saved + await save_rows(app.db, {5: make_msg(5, "Fifth", reply_to=2, media=photo_media(51))}) # the saved copy has a photo + await app.press(app.out.callback_data("Try the rest again")) + assert dst.msgs[15].message == "Fifth" and dst.msgs[15].media is None # the mark kept the option + assert not sent_media(dst) + await app.db.close() + + run(go()) + + +def test_the_whole_story_telegram_hides_posts_with_files_and_without_them_it_does_not(tmp_path): + """The case behind the option: the new copies are hidden by Telegram because of their files.""" + + async def go(): + for no_media in (False, True): + app, dst = await held_app(tmp_path / str(no_media), held=()) + app.tg.restriction = CHANNEL_NOTICE + dst.restrict_new = lambda m: CHANNEL_NOTICE if m.media is not None else None # the photo is blocked + await app.text("/shift @srcch @dstch" + (" --no-media" if no_media else "")) + await app.press(app.out.callback_data("Start copying")) + done = norm(app.out.last_text) + if no_media: + assert "hides" not in done and "(without files)" in done + else: + assert "Telegram itself hides 1 of the 5 new post(s) I read back" in done and "--no-media" in done + await app.db.close() + + run(go()) + + +def test_the_repost_command_does_not_take_the_option(tmp_path): + async def go(): + from .test_repost_flow import make_app + + app = await make_app(tmp_path, msgs={1: make_msg(1, "First post")}) + await app.text("/repost --no-media") + assert "Unknown" in norm(app.out.last_text) or "unknown" in norm(app.out.last_text).lower() + await app.db.close() + + run(go()) diff --git a/tests/test_paging.py b/tests/test_paging.py new file mode 100644 index 0000000000000000000000000000000000000000..f21af0f93a0125a19d7fbc15db9c8e1b9e053e38 --- /dev/null +++ b/tests/test_paging.py @@ -0,0 +1,116 @@ +"""My posts: "Prev" is always there, and on the first page it goes to the last page.""" +import asyncio + +from .harness import App + + +async def make_app(tmp_path, n_posts, uid_owner=1): + app = App(tmp_path, owner=uid_owner) + await app.start() + await app.db.save_channel(1, 5, "Anime Channel", "animech", 1) + for i in range(n_posts): + await app.db.create_post( + channel_id=1, message_id=100 + i, status="sent", source="bot", text=f"Post number {i}", entities=[], buttons=[] + ) + return app + + +def nav_row(app): + """Labels of the navigation row (the one with the page counter), or None.""" + for row in app.out.log[-1][2] or []: + labels = [b.text for b in row] + if any("/" in t and t.replace("/", "").isdigit() for t in labels): + return labels + return None + + +def data_of(app, label_part): + return app.out.callback_data(label_part) + + +def test_prev_on_the_first_page_goes_to_the_last_page(tmp_path): + async def run(): + app = await make_app(tmp_path, 83) # 8 per page -> 11 pages, like "1/11" in the screenshot + await app.text("/posts") + await app.press(app.out.callback_data("Anime Channel")) + assert nav_row(app) == ["⬅️ Prev", "1/11", "Next ➡️"] # Prev is shown on page 1 as well + + await app.press(app.out.callback_data("Prev")) + assert nav_row(app) == ["⬅️ Prev", "11/11"] # the last page has no Next + assert "83 post(s)" in app.out.last_text + # the last page holds the 3 remaining posts + posts = [r for r in app.out.log[-1][2] if r and r[0].text.startswith("✅")] + assert len(posts) == 3 + + await app.press(app.out.callback_data("Prev")) + assert nav_row(app) == ["⬅️ Prev", "10/11", "Next ➡️"] + await app.db.close() + + asyncio.run(run()) + + +def test_next_walks_forward_and_stops_at_the_end(tmp_path): + async def run(): + app = await make_app(tmp_path, 20) # 3 pages + await app.text("/posts") + await app.press(app.out.callback_data("Anime Channel")) + assert nav_row(app) == ["⬅️ Prev", "1/3", "Next ➡️"] + await app.press(app.out.callback_data("Next")) + assert nav_row(app) == ["⬅️ Prev", "2/3", "Next ➡️"] + await app.press(app.out.callback_data("Next")) + assert nav_row(app) == ["⬅️ Prev", "3/3"] + await app.press(app.out.callback_data("Prev")) + await app.press(app.out.callback_data("Prev")) + assert nav_row(app) == ["⬅️ Prev", "1/3", "Next ➡️"] + await app.press(app.out.callback_data("Prev")) # and around again + assert nav_row(app) == ["⬅️ Prev", "3/3"] + await app.db.close() + + asyncio.run(run()) + + +def test_a_single_page_has_nothing_to_turn(tmp_path): + async def run(): + app = await make_app(tmp_path, 5) + await app.text("/posts") + await app.press(app.out.callback_data("Anime Channel")) + assert nav_row(app) is None + assert "5 post(s)" in app.out.last_text + await app.db.close() + + asyncio.run(run()) + + +def test_drafts_list_wraps_too(tmp_path): + async def run(): + app = await make_app(tmp_path, 0) + for i in range(10): + await app.db.create_post(channel_id=1, status="draft", source="bot", text=f"draft {i}", entities=[], buttons=[]) + await app.press("pc:d:0") + assert nav_row(app) == ["⬅️ Prev", "1/2", "Next ➡️"] + await app.press(app.out.callback_data("Prev")) + assert nav_row(app) == ["⬅️ Prev", "2/2"] + await app.db.close() + + asyncio.run(run()) + + +def test_check_buttons_row_is_for_the_owner_and_for_channel_lists_only(tmp_path): + async def run(): + app = await make_app(tmp_path, 3) + await app.press("pc:1:0") + assert "Check buttons" in str(app.out.last_buttons()) + await app.press("pc:d:0") # drafts belong to no channel: nothing to check + assert "Check buttons" not in str(app.out.last_buttons()) + await app.db.close() + + # an allowed non-owner does not get the repair tool + app2 = App(tmp_path, owner=1, admins=frozenset({7})) + await app2.start() + await app2.db.save_channel(1, 5, "Anime Channel", "animech", 1) + app2.uid = 7 + await app2.press("pc:1:0") + assert "Check buttons" not in str(app2.out.last_buttons()) + await app2.db.close() + + asyncio.run(run()) diff --git a/tests/test_picker.py b/tests/test_picker.py new file mode 100644 index 0000000000000000000000000000000000000000..3ece27b619b643f05d1377c87df59c247fba907d --- /dev/null +++ b/tests/test_picker.py @@ -0,0 +1,254 @@ +"""The channel chooser: names written out as a numbered list (A to Z, 20 to a page), buttons that carry only numbers +(5 to a row), ◀ ▶ underneath - and every command that needs a channel uses it.""" +import asyncio +from types import SimpleNamespace + +from app import picker +from app.picker import PER_PAGE, PER_ROW, names_of, natural_key, ordered, render + +from .harness import App, norm + + +def run(coro): + return asyncio.run(coro) + + +def chan(i, title, username=None): + return SimpleNamespace(id=i, title=title, username=username) + + +def data_of(btn): + t = btn.type if hasattr(btn, "type") else btn + return t.data.decode() + + +def lines_of(text): + """The numbered lines of a message: ['1. Naruto', ...].""" + return [ln for ln in norm(text).splitlines() if ln[:1].isdigit() and ". " in ln[:5]] + + +# ------------------------------------------------------------------------------------------ the list itself +def test_names_are_sorted_a_to_z_ignoring_case_and_numbers_count_by_value(): + chans = [chan(1, "One piece"), chan(2, "naruto"), chan(3, "Dragon ball"), chan(4, "Anime 10"), chan(5, "Anime 2")] + assert [c.title for c in ordered(chans)] == ["Anime 2", "Anime 10", "Dragon ball", "naruto", "One piece"] + assert natural_key(" Anime 2 ") == natural_key("anime 2") + # the same name twice: the id decides, so the order never changes between two looks + assert [c.id for c in ordered([chan(9, "Same"), chan(4, "same")])] == [4, 9] + + +def test_the_message_lists_the_names_and_the_buttons_only_carry_numbers(): + chans = [chan(10, "One piece"), chan(20, "Naruto"), chan(30, "Dragon ball")] + text, rows = render(chans, 0, head="Which one?", kind="x", choose=lambda c: f"go:{c.id}") + assert lines_of(text) == ["1. Dragon ball", "2. Naruto", "3. One piece"] + assert [[b.text for b in row] for row in rows] == [["1", "2", "3"]] + # pressing 3 means One piece - the button carries the channel's id, not its place in the list + assert [data_of(b) for b in rows[0]] == ["go:30", "go:20", "go:10"] + assert text.startswith("Which one?") and "Tap the number of the channel." in text + assert "Page" not in text # one page: no page line, no arrows + + +def test_a_row_has_at_most_five_buttons_and_the_extra_rows_come_last(): + chans = [chan(i, f"Channel {i:02d}") for i in range(1, 13)] + text, rows = render(chans, 0, head="h", kind="x", choose=lambda c: f"go:{c.id}", extra_rows=[["cancel-row"]]) + assert [len(r) for r in rows[:-1]] == [5, 5, 2] + assert rows[-1] == ["cancel-row"] + assert PER_ROW == 5 and PER_PAGE == 20 + + +def test_twenty_names_to_a_page_with_arrows_that_wrap_around(): + chans = [chan(i, f"Channel {i:02d}") for i in range(1, 46)] + text0, rows0 = render(chans, 0, head="h", kind="x", arg="tok", choose=lambda c: f"go:{c.id}", extra_rows=[["cancel-row"]]) + assert [ln.split(". ")[0] for ln in lines_of(text0)] == [str(n) for n in range(1, 21)] + assert "Page 1 of 3 - channels 1 to 20 of 45" in norm(text0) + assert [[b.text for b in r] for r in rows0[:4]] == [[str(n) for n in range(s, s + 5)] for s in (1, 6, 11, 16)] + assert [b.text for b in rows0[4]] == ["◀", "▶"] # the arrows sit under the number buttons + assert rows0[5] == ["cancel-row"] + assert data_of(rows0[4][1]) == "cpg:x:tok:1" and data_of(rows0[4][0]) == "cpg:x:tok:2" # ◀ on the first page = the last page + + text1, rows1 = render(chans, 1, head="h", kind="x", arg="tok", choose=lambda c: f"go:{c.id}") + assert lines_of(text1)[0] == "21. Channel 21" and lines_of(text1)[-1] == "40. Channel 40" + assert [[b.text for b in r] for r in rows1[:4]] == [[str(n) for n in range(s, s + 5)] for s in (21, 26, 31, 36)] + assert data_of(rows1[0][0]) == "go:21" and data_of(rows1[3][4]) == "go:40" + assert data_of(rows1[4][0]) == "cpg:x:tok:0" and data_of(rows1[4][1]) == "cpg:x:tok:2" + + text2, rows2 = render(chans, 2, head="h", kind="x", arg="tok", choose=lambda c: f"go:{c.id}") + assert lines_of(text2) == [f"{n}. Channel {n:02d}" for n in range(41, 46)] + assert [[b.text for b in r] for r in rows2[:1]] == [["41", "42", "43", "44", "45"]] + assert data_of(rows2[1][1]) == "cpg:x:tok:0" # ▶ on the last page = the first page + # a page number that no longer exists (channels were removed meanwhile) shows the last page + assert lines_of(render(chans, 99, head="h", kind="x", choose=lambda c: "go")[0])[0] == "41. Channel 41" + + +def test_a_list_to_read_has_no_number_buttons_but_still_pages(): + chans = [chan(i, f"Channel {i:02d}") for i in range(1, 26)] + text, rows = render(chans, 0, head="h", kind="ch", choose=None) + assert [[b.text for b in r] for r in rows] == [["◀", "▶"]] + assert "Tap the number" not in text + assert render(chans[:3], 0, head="h", kind="ch", choose=None)[1] == [] + + +def test_equal_names_get_the_username_or_id_and_odd_names_are_safe(): + chans = [chan(1, "Anime", "animech"), chan(2, "ANIME"), chan(3, "Other", "otherch")] + assert names_of(ordered(chans)) == ["Anime (@animech)", "ANIME (2)", "Other"] + assert names_of(ordered(chans), with_username=True) == ["Anime (@animech)", "ANIME (2)", "Other (@otherch)"] + long = chan(4, "x" * 200) + assert len(names_of([long])[0]) == picker.NAME_MAX + text, _ = render([chan(5, "Bold & co")], 0, head="h", kind="x", choose=lambda c: "go") + assert "<b>Bold & co</b>" in text and "Bold" not in text.split("\n\n", 1)[1] + assert names_of([chan(6, "")]) == ["Channel"] + + +# ------------------------------------------------------------------------------ the commands that use it +async def make_app(tmp_path, n, *, owner=1, **cfg): + app = App(tmp_path, owner=owner, edit_delay=0, **cfg) + await app.start() + for i in reversed(range(1, n + 1)): # saved in reverse: the list has to sort them + await app.db.save_channel(i, 5, f"Channel {i:02d}", f"ch{i:02d}", 1) + return app + + +def test_new_lists_the_channels_and_a_number_starts_a_post_for_that_channel(tmp_path): + async def go(): + app = await make_app(tmp_path, 45) + await app.text("/new") + text = norm(app.out.last_text) + assert "Which channel is this post for?" in text + assert lines_of(app.out.last_text)[0] == "1. Channel 01" and len(lines_of(app.out.last_text)) == 20 + assert [len(r) for r in app.out.last_buttons()] == [5, 5, 5, 5, 2, 1] # 4 rows of numbers, the arrows, Cancel + await app.press(app.out.callback_exact("▶")) # edits the same message + assert lines_of(app.out.last_text)[0] == "21. Channel 21" and lines_of(app.out.last_text)[-1] == "40. Channel 40" + assert app.out.last_buttons()[0] == ["21", "22", "23", "24", "25"] + await app.press(app.out.callback_exact("▶")) + assert lines_of(app.out.last_text) == [f"{n}. Channel {n:02d}" for n in range(41, 46)] + await app.press(app.out.callback_exact("▶")) # wraps round to the first page + assert lines_of(app.out.last_text)[0] == "1. Channel 01" + await app.press(app.out.callback_exact("◀")) # ... and back to the last one + assert lines_of(app.out.last_text)[0] == "41. Channel 41" + await app.press(app.out.callback_exact("43")) + assert app.ctx.state[1]["mode"] == "new_content" and app.ctx.state[1]["cid"] == 43 + await app.db.close() + + run(go()) + + +def test_new_with_a_single_channel_still_goes_straight_to_the_post(tmp_path): + async def go(): + app = await make_app(tmp_path, 1) + await app.text("/new") + assert app.ctx.state[1]["cid"] == 1 and "Send the post now" in norm(app.out.last_text) + await app.db.close() + + run(go()) + + +def test_posts_offers_the_channels_and_the_drafts(tmp_path): + async def go(): + app = await make_app(tmp_path, 25) + await app.text("/posts") + assert "My posts" in norm(app.out.last_text) and lines_of(app.out.last_text)[0] == "1. Channel 01" + assert app.out.last_buttons()[-1] == ["💾 Drafts (all channels)"] + assert app.out.callback_exact("💾 Drafts (all channels)") == "pc:d:0" + assert app.out.callback_exact("3") == "pc:3:0" + await app.press(app.out.callback_exact("▶")) + assert lines_of(app.out.last_text) == [f"{n}. Channel {n:02d}" for n in range(21, 26)] + assert app.out.last_buttons()[-1] == ["💾 Drafts (all channels)"] + await app.press(app.out.callback_exact("24")) + assert "Channel 24" in norm(app.out.last_text) and "post(s)" in norm(app.out.last_text) + await app.press("pl") # 🔙 Channels + assert lines_of(app.out.last_text)[0] == "1. Channel 01" + await app.db.close() + + run(go()) + + +def test_posts_without_a_channel_still_offers_the_drafts(tmp_path): + async def go(): + app = await make_app(tmp_path, 0) + await app.text("/posts") + assert "No channels yet" in norm(app.out.last_text) and app.out.callback_exact("💾 Drafts (all channels)") == "pc:d:0" + await app.db.close() + + run(go()) + + +def test_channels_owner_taps_a_number_and_confirms_before_a_channel_is_removed(tmp_path): + async def go(): + app = await make_app(tmp_path, 3) + await app.text("/channels") + assert lines_of(app.out.last_text) == ["1. Channel 01 (@ch01)", "2. Channel 02 (@ch02)", "3. Channel 03 (@ch03)"] + assert app.out.last_buttons() == [["1", "2", "3"]] + await app.press(app.out.callback_exact("2")) + assert "Take Channel 02 out of the bot?" in norm(app.out.last_text) + assert [c.id for c in await app.db.list_channels()] == [1, 2, 3] # nothing is removed by the number alone + await app.press(app.out.callback_exact("🔙 Back")) + assert lines_of(app.out.last_text)[1] == "2. Channel 02 (@ch02)" + await app.press(app.out.callback_exact("2")) + await app.press(app.out.callback_exact("✅ Yes, remove it")) + assert "removed from the bot" in norm(app.out.last_text) + assert [c.id for c in await app.db.list_channels()] == [1, 3] + await app.db.close() + + run(go()) + + +def test_channels_for_an_admin_is_only_a_list(tmp_path): + async def go(): + app = await make_app(tmp_path, 3, owner=7, admins=frozenset({1})) + app.uid = 1 # an admin, not an owner + await app.text("/channels") + assert lines_of(app.out.last_text)[0] == "1. Channel 01 (@ch01)" and app.out.last_buttons() == [] + assert "tap its number" not in norm(app.out.last_text) + await app.press("chd:2") # a made-up press does nothing for a non-owner + assert [c.id for c in await app.db.list_channels()] == [1, 2, 3] + await app.db.close() + + run(go()) + + +def test_autopost_and_repost_page_through_the_channels_and_a_number_picks_one(tmp_path): + async def go(): + app = await make_app(tmp_path, 45) + await app.text("/autopost 20 10") + assert "Which channel should I post them in?" in norm(app.out.last_text) and "2 post(s)" in norm(app.out.last_text) + assert lines_of(app.out.last_text)[0] == "1. Channel 01" + await app.press(app.out.callback_exact("▶")) + assert "2 post(s)" in norm(app.out.last_text) and lines_of(app.out.last_text)[0] == "21. Channel 21" # same question + assert app.out.callback_exact("21").startswith("apc:") and app.out.callback_exact("21").endswith(":21") + assert app.out.last_buttons()[-1] == ["✖️ Cancel"] + + await app.text("/repost") + await app.text("/repost --last 3") + assert "Which channel should I repost?" in norm(app.out.last_text) and "newest 3" in norm(app.out.last_text) + await app.press(app.out.callback_exact("▶")) + await app.press(app.out.callback_exact("▶")) + assert lines_of(app.out.last_text)[0] == "41. Channel 41" and "newest 3" in norm(app.out.last_text) + data = app.out.callback_exact("45") + assert data.startswith("rpch:") and data.endswith(":45") + await app.db.close() + + run(go()) + + +def test_an_old_arrow_of_a_list_that_has_expired_says_so(tmp_path): + async def go(): + app = await make_app(tmp_path, 25) + await app.press("cpg:rp:deadbeef:1") + assert "expired" in norm(app.out.last_text) + await app.press("cpg:ap:deadbeef:1") + assert "expired" in norm(app.out.last_text) + await app.press("cpg:zz::1") + assert "no longer active" in norm(app.out.last_text) + await app.db.close() + + run(go()) + + +def test_the_channel_pickers_of_the_owner_tools_refuse_everybody_else(tmp_path): + async def go(): + app = await make_app(tmp_path, 25, owner=7, admins=frozenset({1})) + app.uid = 1 + await app.press("cpg:rp:deadbeef:1") + assert "Only the bot owner" in norm(app.out.last_text) + await app.db.close() + + run(go()) diff --git a/tests/test_postlinks.py b/tests/test_postlinks.py new file mode 100644 index 0000000000000000000000000000000000000000..852f9e3d66e7da203802fd8bcbc242aa0ba6b8a6 --- /dev/null +++ b/tests/test_postlinks.py @@ -0,0 +1,155 @@ +"""Links to other posts of the same channel: found in all three places and pointed at the new message ids.""" +from telethon import types +from telethon.helpers import add_surrogate + +from app.postlinks import PostLinks, parse_ref, relink_message, resolve_chain +from app.tgutil import button_url + +from .fakes import make_msg, markup, url_btn + + +def links(ids=None, username="One_Piece_inEnglish", cid=1234567): + return PostLinks(username=username, channel_id=cid, ids=dict(ids or {})) + + +def utf16(text, ent): + raw = text.encode("utf-16-le") + return raw[ent.offset * 2 : (ent.offset + ent.length) * 2].decode("utf-16-le") + + +# ------------------------------------------------------------------------------------------- parsing +def test_the_forms_of_a_post_link_are_recognised(): + r = parse_ref("https://t.me/One_Piece_inEnglish/115") + assert (r.name, r.cid, r.msg_id) == ("one_piece_inenglish", None, 115) + assert "https://t.me/One_Piece_inEnglish/115"[r.start : r.end] == "115" + r = parse_ref("t.me/c/1234567/56?single") + assert (r.name, r.cid, r.msg_id) == (None, 1234567, 56) + assert parse_ref("http://telegram.me/somechan/7#x").msg_id == 7 + assert parse_ref("https://t.me/s/somechan/7").msg_id == 7 + assert parse_ref("https://telegram.dog/somechan/7/2").msg_id == 7 # only the first number is the post + r = parse_ref("tg://resolve?domain=somechan&post=9") + assert (r.name, r.msg_id) == ("somechan", 9) + r = parse_ref("tg://resolve?post=9&domain=somechan") + assert (r.name, r.msg_id) == ("somechan", 9) + r = parse_ref("tg://privatepost?channel=1234567&post=9") + assert (r.cid, r.msg_id) == (1234567, 9) + + +def test_links_that_are_not_post_links_are_not_touched(): + for url in ( + "https://t.me/somechan", + "https://t.me/somechan?start=ABC123", + "https://t.me/+AbCdEfGhIj", + "https://t.me/addstickers/pack", + "https://example.com/somechan/12", + "https://t.me/c/1234567", + "tg://resolve?domain=somechan", + "", + None, + ): + assert parse_ref(url) is None, url + + +def test_only_links_into_this_channel_count(): + pl = links({115: 400}) + assert pl.ref_of("https://t.me/one_piece_inenglish/115") # a username is not case sensitive + assert pl.ref_of("https://t.me/c/1234567/115") + assert pl.ref_of("https://t.me/c/999/115") is None + assert pl.ref_of("https://t.me/another_channel/115") is None + private = PostLinks(username=None, channel_id=1234567, ids={115: 400}) + assert private.ref_of("https://t.me/One_Piece_inEnglish/115") is None + assert private.remap_url("https://t.me/c/1234567/115") == "https://t.me/c/1234567/400" + + +def test_only_the_digits_of_the_post_id_change(): + pl = links({115: 1042, 7: 8}) + assert pl.remap_url("https://t.me/One_Piece_inEnglish/115") == "https://t.me/One_Piece_inEnglish/1042" + assert pl.remap_url("https://t.me/One_Piece_inEnglish/115?single") == "https://t.me/One_Piece_inEnglish/1042?single" + assert pl.remap_url("t.me/c/1234567/7?comment=7") == "t.me/c/1234567/8?comment=7" + assert pl.remap_url("tg://resolve?domain=One_Piece_inEnglish&post=115") == "tg://resolve?domain=One_Piece_inEnglish&post=1042" + assert pl.remap_url("tg://resolve?post=115&domain=One_Piece_inEnglish&x=1") == "tg://resolve?post=1042&domain=One_Piece_inEnglish&x=1" + assert pl.remap_url("tg://privatepost?channel=1234567&post=7") == "tg://privatepost?channel=1234567&post=8" + # a post nobody copied, another channel, a bot link: unchanged + assert pl.remap_url("https://t.me/One_Piece_inEnglish/116") == "https://t.me/One_Piece_inEnglish/116" + assert pl.remap_url("https://t.me/other/115") == "https://t.me/other/115" + assert pl.remap_url("https://t.me/goku?start=115") == "https://t.me/goku?start=115" + + +# --------------------------------------------------------------------------------------- the text +def test_typed_links_are_rewritten_and_the_formatting_after_them_moves_along(): + text = "😀 see https://t.me/One_Piece_inEnglish/9 and bold t.me/c/1234567/10?single end" + bold = types.MessageEntityBold(text.index("bold") + 0, 4) + bold.offset = len(text[: text.index("bold")].encode("utf-16-le")) // 2 # offsets count UTF-16 units, the emoji is 2 + url_ent = types.MessageEntityUrl(len("😀 see ".encode("utf-16-le")) // 2, len("https://t.me/One_Piece_inEnglish/9")) + pl = links({9: 1234, 10: 12}) + new_text, ents, n_typed, n_hyper = pl.remap_text(text, [bold, url_ent]) + assert new_text == "😀 see https://t.me/One_Piece_inEnglish/1234 and bold t.me/c/1234567/12?single end" + assert (n_typed, n_hyper) == (2, 0) + b, u = ents + assert utf16(new_text, b) == "bold" # the bold span moved with its text + assert utf16(new_text, u) == "https://t.me/One_Piece_inEnglish/1234" # the link entity grew with the link + assert bold.offset != b.offset # the originals were not modified + + +def test_a_link_typed_inside_another_word_or_url_is_not_a_post_link(): + pl = links({9: 99}) + text = "x https://example.com/?u=t.me/One_Piece_inEnglish/9 and email@t.me/One_Piece_inEnglish/9" + assert pl.remap_text(text, [])[0] == text + + +def test_hyperlinks_are_changed_without_touching_their_text(): + text = "Click here and there" + ents = [ + types.MessageEntityTextUrl(0, 10, "https://t.me/One_Piece_inEnglish/115"), + types.MessageEntityTextUrl(11, 3, "https://t.me/another/115"), + types.MessageEntityBold(15, 5), + ] + new_text, new_ents, n_typed, n_hyper = links({115: 2000}).remap_text(text, ents) + assert new_text == text and (n_typed, n_hyper) == (0, 1) + assert new_ents[0].url == "https://t.me/One_Piece_inEnglish/2000" and new_ents[1].url == "https://t.me/another/115" + assert ents[0].url.endswith("/115") # the message's own entity objects are left alone + + +def test_buttons_with_a_link_to_a_post_are_rebuilt_other_buttons_are_kept_as_they_are(): + mk = markup([url_btn("Episode 1", "https://t.me/One_Piece_inEnglish/115"), url_btn("Bot", "https://t.me/goku?start=A")]) + new, n = links({115: 300}).remap_markup(mk) + assert n == 1 + assert [button_url(b) for b in new.rows[0].buttons] == ["https://t.me/One_Piece_inEnglish/300", "https://t.me/goku?start=A"] + assert [b.text for b in new.rows[0].buttons] == ["Episode 1", "Bot"] + same, n = links({999: 1}).remap_markup(mk) + assert n == 0 and same is mk # nothing to change: the very same keyboard comes back + assert links().remap_markup(None) == (None, 0) + + +def test_links_are_counted_even_before_the_new_ids_are_known(): + text = "https://t.me/One_Piece_inEnglish/5 and https://t.me/other/5" + ents = [types.MessageEntityTextUrl(0, 5, "https://t.me/c/1234567/6")] + mk = markup([url_btn("x", "https://t.me/One_Piece_inEnglish/7")]) + assert links().count(text, ents, mk) == 3 + + +def test_a_whole_message_is_relinked_or_reported_unchanged(): + msg = make_msg( + 5, "Next: https://t.me/One_Piece_inEnglish/115", [types.MessageEntityBold(0, 4)], + markup([url_btn("Go", "https://t.me/One_Piece_inEnglish/116")]), + ) + assert relink_message(msg, links({1: 2})) is None + rl = relink_message(msg, links({115: 900, 116: 901})) + assert rl.text == "Next: https://t.me/One_Piece_inEnglish/900" and (rl.n_typed, rl.n_hyper, rl.n_buttons, rl.links) == (1, 0, 1, 2) + assert rl.text_changed and rl.markup_changed + assert button_url(rl.markup.rows[0].buttons[0]).endswith("/901") + # running it again on the result changes nothing: the new ids are not old ids + again = make_msg(5, rl.text, rl.entities, rl.markup) + assert relink_message(again, links({115: 900, 116: 901})) is None + + +def test_posts_that_moved_twice_point_at_their_latest_copy(): + assert resolve_chain({1: 5, 5: 9, 2: 6}) == {1: 9, 5: 9, 2: 6} + assert resolve_chain({}) == {} + + +def test_offsets_use_utf16_units(): + text = "😀😀 https://t.me/One_Piece_inEnglish/3" + assert len(add_surrogate(text)) == 4 + 1 + len("https://t.me/One_Piece_inEnglish/3") + new_text, _, n, _ = links({3: 30}).remap_text(text, []) + assert new_text == "😀😀 https://t.me/One_Piece_inEnglish/30" and n == 1 diff --git a/tests/test_replace_userbot.py b/tests/test_replace_userbot.py new file mode 100644 index 0000000000000000000000000000000000000000..aee907eb9e5ae57800b16b79a59e1d964b8a0adb --- /dev/null +++ b/tests/test_replace_userbot.py @@ -0,0 +1,511 @@ +"""/replace and the edits in My posts when Telegram refuses the bot: the userbot makes the edit instead.""" +import asyncio + +import pytest +from telethon import types + +import app.userbot as userbot_module +from app.common import UserError, apply_edit_reported +from app.tgutil import media_info, pack_file_id +from app.userbot import Userbot + +from .fakes import FakeChannelClient, FakeUserClient, make_msg, markup, photo_media, rpc, url_btn, video_media +from .harness import App, norm + +CID, MID = 1723201445, 9084 +FULL = dict(admin=True, post=True, edit=True, delete=True, invite=True, add_admins=True) +LINK = "https://t.me/otherbot?start=abc" +BUTTONS = [[{"t": "Download", "u": LINK}]] + + +async def make_app(tmp_path, *, userbot=True, foreign=True, rights=FULL, **cfg): + """A channel with a button post. `foreign`: the post belongs to another bot, so Telegram refuses our bot's edits. + + Returns (app, the simulated channel, the userbot account's connection).""" + app = App(tmp_path, userbot_session="S" if userbot else "", **cfg) + await app.start() + old = make_msg(MID, "old caption", media=photo_media(10), markup=markup([url_btn("Download", LINK)])) + old.via_other_bot = foreign + chan = app.tg.add_channel(FakeChannelClient({MID: old}, cid=CID, title="Database Channel")) + chan.rights = dict(rights) + await app.db.save_channel(CID, 5, "Database Channel", None, 1) + user = FakeUserClient(chan) + if userbot: + app.ctx.userbot = Userbot(app.tg, app.ctx.cfg, client_factory=lambda c: user) + app.tg._media_data[("photo", 20)] = b"NEW PHOTO" # what the owner's new photo looks like + return app, chan, user + + +def replacement(caption="new caption", entities=None): + return make_msg(1, caption, entities, media=photo_media(20)) + + +def video_replacement(caption="new caption", did=31, thumb=True): + return make_msg(1, caption, None, media=video_media(did, thumb=thumb)) + + +def said(app): + return [norm(t) for kind, t, _ in app.out.log if kind == "say"] + + +def waiting(app): + """The "⏳ ..." messages the owner got while the userbot worked.""" + return [t for t in said(app) if t.startswith("⏳")] + + +def user_edits(user): + return [r for r in user.requests if type(r).__name__ == "EditMessageRequest"] + + +async def replace(app, message=None, **kw): + await app.text(f"/replace https://t.me/c/{CID}/{MID}", reply=message or replacement(**kw)) + + +async def the_post(app): + return await app.db.find_by_message(CID, MID) + + +# ------------------------------------------------------------------------------- the userbot steps in +def test_when_telegram_refuses_the_bot_the_userbot_replaces_media_and_caption(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path) + await replace(app) + m = chan.msgs[MID] + assert m.message == "new caption" and m.media.photo.id == 20 # the very file the owner sent: nothing was copied + # the file went bot -> the userbot's chat with the bot -> the post: nothing downloaded, nothing uploaded + assert user.uploads == [] and len(chan._dm.sent) == 1 and len(user_edits(user)) == 1 + assert chan._dm.msgs == [] and len(chan._dm.deleted) == 1 # the helper message is gone again + # the post in My posts shows what the channel shows now, and keeps its saved buttons + post = await the_post(app) + assert post.text == "new caption" and post.buttons == BUTTONS and post.media_kind == "photo" + assert post.media_file_id == media_info(m)[1] + # the owner is told what happened, in order - one waiting message, no "big file" warning + assert len(waiting(app)) == 1 and "Telegram refused the bot, so the userbot is making the edit" in waiting(app)[0] + assert "big file" not in waiting(app)[0] + last = said(app)[-1] + assert "Replaced the media in Database Channel" in last and "Telegram refused the bot (MessageIdInvalidError)" in last + assert "the new file went through the userbot's chat with the bot, so nothing was uploaded" in last + # the helper left things as it found them + assert chan.admins == {} and all(i["revoked"] for i in chan.invites.values()) and not app.ctx.userbot.lock.locked() + await app.db.close() + + asyncio.run(run()) + + +def test_telegram_drops_the_buttons_and_the_bot_may_not_put_them_back(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path) + await replace(app) + assert chan.msgs[MID].reply_markup is None # a user account sets no keyboard + last = said(app)[-1] + assert "Telegram dropped the buttons with that edit and the bot may not put them back" in last + assert "My posts" in last and "Check buttons" in last + assert (await the_post(app)).buttons == BUTTONS # still saved: Check buttons can try again + await app.db.close() + + asyncio.run(run()) + + +def test_the_bot_puts_the_buttons_back_when_it_may(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path) + chan.user_edit_frees_message = True # once the other bot's keyboard is gone, the bot may set one + await replace(app) + live = chan.msgs[MID].reply_markup + assert live is not None and live.rows[0].buttons[0].type.url == LINK + assert "Telegram dropped the buttons with that edit, so the bot put them back" in said(app)[-1] + await app.db.close() + + asyncio.run(run()) + + +def test_buttons_that_stay_are_reported_as_kept(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path) + chan.user_edit_keeps_markup = True + await replace(app) + assert chan.msgs[MID].reply_markup is not None + assert "The buttons are still on the post." in said(app)[-1] + await app.db.close() + + asyncio.run(run()) + + +def test_the_userbot_is_not_asked_when_the_bot_can_do_it(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path, foreign=False) + await replace(app) + assert user.requests == [] and not user.connected # nobody else was bothered + assert chan._dm.sent == [] and waiting(app) == [] + assert app.tg.edits[-1][1] == MID and "Replaced the media" in said(app)[-1] + assert "userbot" not in said(app)[-1] + await app.db.close() + + asyncio.run(run()) + + +# -------------------------------------------------------------------------- when nobody can do it +def test_without_a_userbot_the_owner_is_pointed_to_it_and_nothing_changes(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path, userbot=False) + await replace(app) + text = said(app)[-1] + assert "Telegram refused (MessageIdInvalidError)" in text and "see /userbot" in text and "Nothing was changed" in text + assert chan.msgs[MID].message == "old caption" and chan.msgs[MID].media.photo.id == 10 + assert (await the_post(app)).text == "old caption" + await app.db.close() + + asyncio.run(run()) + + +def test_a_userbot_that_cannot_get_the_right_is_explained_and_nothing_changes(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path, rights=dict(FULL, add_admins=False)) + await replace(app) + text = said(app)[-1] + assert "Telegram refused (MessageIdInvalidError)" in text and "The userbot could not do it either" in text + assert "may not edit other people's posts" in text and "Add new admins" in text and "Nothing was changed" in text + assert chan.msgs[MID].message == "old caption" and (await the_post(app)).text == "old caption" + assert not app.ctx.userbot.lock.locked() + await app.db.close() + + asyncio.run(run()) + + +def test_a_userbot_that_telegram_refuses_too_is_reported(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path) + chan.fail["user:EditMessageRequest"] = rpc("MessageIdInvalidError") + await replace(app) + text = said(app)[-1] + assert "The userbot could not do it either" in text and "Telegram refused the userbot as well" in text + assert chan.admins == {} and (await the_post(app)).text == "old caption" + await app.db.close() + + asyncio.run(run()) + + +def test_a_connected_but_broken_userbot_session_is_named(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path) + user.authorized = False # the session was revoked + await replace(app) + text = said(app)[-1] + assert "not logged in any more" in text and "Nothing was changed" in text + await app.db.close() + + asyncio.run(run()) + + +def test_only_text_media_and_caption_edits_go_to_the_userbot(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path) + await replace(app) # adopts the post + post = await the_post(app) + ch = await app.db.get_channel(CID) + user.requests.clear() + chan.msgs[MID].via_other_bot = True + with pytest.raises(UserError) as exc: # buttons can only be set by a bot + await apply_edit_reported(app.ctx, post, ch, buttons=[[{"t": "X", "u": "https://x.com"}]]) + assert "Nothing was changed" in str(exc.value) and user.requests == [] + chan.fail["EditMessageRequest"] = rpc("EntityBoundsInvalidError") # the text itself is what Telegram dislikes + with pytest.raises(UserError) as exc: + await apply_edit_reported(app.ctx, post, ch, text="fine", entities=[{"k": "bold", "o": 0, "l": 99}]) + assert "EntityBoundsInvalidError" in str(exc.value) and user.requests == [] + await app.db.close() + + asyncio.run(run()) + + +# ------------------------------------------------------------------------ the edits in My posts +def test_a_caption_typed_in_markdown_is_edited_by_the_userbot_when_the_bot_is_refused(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path) + post = await app.db.create_post( + channel_id=CID, message_id=MID, status="sent", source="adopted", text="old caption", entities=[], + buttons=BUTTONS, media_kind="photo", media_file_id=pack_file_id(replacement()), + ) + await app.press(f"et:{post.id}") + assert "HTML / Markdown" in app.out.last_text + await app.text("**new** caption") + m = chan.msgs[MID] + assert m.message == "new caption" and [(type(e).__name__, e.offset, e.length) for e in m.entities] == [("MessageEntityBold", 0, 3)] + assert m.media.photo.id == 10 # only the caption changed, the photo stays + assert user.uploads == [] and chan._dm.sent == [] # no file moved, the chat was not used + note = norm(app.out.last_text) + assert "Formatting read from Markdown" in note and "the userbot made the edit" in note + saved = await app.db.get_post(post.id) + assert saved.text == "new caption" and saved.entities == [{"k": "bold", "o": 0, "l": 3}] + await app.db.close() + + asyncio.run(run()) + + +def test_new_media_sent_to_the_post_panel_reaches_the_userbot_through_its_chat(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path) + post = await app.db.create_post( + channel_id=CID, message_id=MID, status="sent", source="adopted", text="old caption", entities=[], + buttons=BUTTONS, media_kind="photo", media_file_id=pack_file_id(make_msg(2, "", media=photo_media(10))), + ) + await app.press(f"em:{post.id}") + await app.text("", message=replacement(caption="")) + m = chan.msgs[MID] + assert m.message == "old caption" and m.media.photo.id == 20 and user.uploads == [] + assert len(waiting(app)) == 1 and "Telegram refused the bot, so the userbot is making the edit" in waiting(app)[0] + assert "the userbot made the edit" in norm(app.out.last_text) + assert (await app.db.get_post(post.id)).media_file_id == media_info(m)[1] + await app.db.close() + + asyncio.run(run()) + + +# ------------------------------------------------------------------------------- the thumbnail stays +def test_a_video_keeps_its_thumbnail_when_it_goes_through_the_chat(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path) + await replace(app, message=video_replacement()) + m = chan.msgs[MID] + assert m.media.document.id == 31 and m.media.document.thumbs # the same file: its thumbnail comes with it + assert user.uploads == [] and (await the_post(app)).media_kind == "video" + await app.db.close() + + asyncio.run(run()) + + +def test_a_video_keeps_its_thumbnail_when_it_has_to_be_uploaded_again(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path) + chan._dm.error = rpc("UserIsBlockedError") # the chat does not work: the slow way + chan._media_data[("thumb", 31)] = b"THE THUMBNAIL" + await replace(app, message=video_replacement()) + doc = chan.msgs[MID].media.document + assert doc.id != 31 and doc.thumbs # a new upload, but not a bare file icon + assert chan._media_data[("thumb", doc.id)] == b"THE THUMBNAIL" + assert [u[2] for u in user.uploads] == [len(b"bytes of doc 31"), len(b"THE THUMBNAIL")] # the file, then its picture + await app.db.close() + + asyncio.run(run()) + + +def test_a_file_without_a_thumbnail_is_uploaded_without_one(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path) + chan._dm.error = rpc("UserIsBlockedError") + await replace(app, message=video_replacement(thumb=False)) + assert chan.msgs[MID].media.document.thumbs is None and len(user.uploads) == 1 + await app.db.close() + + asyncio.run(run()) + + +# ----------------------------------------------------------------------------- when the chat does not work +def test_when_the_userbot_never_started_the_bot_the_file_is_downloaded_and_uploaded_again(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path) + chan._dm.error = rpc("UserIsBlockedError") + await replace(app) + m = chan.msgs[MID] + assert m.message == "new caption" and m.media.photo.id not in (10, 20) # a new upload + assert chan._media_data[("photo", m.media.photo.id)] == b"NEW PHOTO" # the bot downloaded it, the userbot uploaded it + assert len(user.uploads) == 1 and user.uploads[0][2] == len(b"NEW PHOTO") and chan._dm.sent == [] + # the owner is told, twice while waiting, why it is the slow way and what fixes that + first, second = waiting(app) + assert "Telegram refused the bot, so the userbot is making the edit" in first + assert "downloaded and uploaded again" in second and "a big file takes a while" in second + assert "has not started the bot" in second and "/start" in second + last = said(app)[-1] + assert "Replaced the media" in last and "the file was downloaded and uploaded again, because the userbot account has not started the bot" in last + post = await the_post(app) + assert post.media_file_id == media_info(m)[1] and post.text == "new caption" + assert chan.admins == {} and not app.ctx.userbot.lock.locked() + await app.db.close() + + asyncio.run(run()) + + +def test_a_refusal_about_the_userbots_copy_of_the_file_falls_back_to_the_upload(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path) + chan._dm.reference_error = rpc("FileReferenceExpiredError") # Telegram will not take the userbot's copy + await replace(app) + m = chan.msgs[MID] + assert m.message == "new caption" and m.media.photo.id not in (10, 20) and len(user.uploads) == 1 + assert len(user_edits(user)) == 2 # the edit with the copy was refused, the one with the upload was not + assert chan._dm.msgs == [] and len(chan._dm.deleted) == 1 # the helper message was cleaned up all the same + second = waiting(app)[1] + assert "Telegram would not take the userbot's copy of the file (FileReferenceExpiredError)" in second + assert "Telegram would not take the userbot's copy of the file" in said(app)[-1] + await app.db.close() + + asyncio.run(run()) + + +def test_a_refusal_that_is_not_about_the_file_is_not_answered_with_a_long_upload(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path) + chan.fail["user:EditMessageRequest"] = rpc("MessageIdInvalidError") # the post itself can't be edited + await replace(app) + text = said(app)[-1] + assert "The userbot could not do it either" in text and "Telegram refused the userbot as well (MessageIdInvalidError)" in text + assert user.uploads == [] and len(user_edits(user)) == 1 # trying again with an upload would fail the same way + assert len(waiting(app)) == 1 and "Nothing was changed" in text + assert chan._dm.msgs == [] and len(chan._dm.deleted) == 1 and chan.admins == {} + assert chan.msgs[MID].message == "old caption" and (await the_post(app)).text == "old caption" + await app.db.close() + + asyncio.run(run()) + + +def test_when_the_upload_fails_as_well_the_owner_hears_why_and_nothing_changes(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path) + chan._dm.error = rpc("UserIsBlockedError") + chan.fail["user:EditMessageRequest"] = rpc("MediaInvalidError") + await replace(app) + text = said(app)[-1] + assert "The userbot could not do it either" in text and "MediaInvalidError" in text and "Nothing was changed" in text + assert chan.msgs[MID].media.photo.id == 10 and (await the_post(app)).text == "old caption" + assert chan.admins == {} and not app.ctx.userbot.lock.locked() + await app.db.close() + + asyncio.run(run()) + + +@pytest.mark.parametrize("edit_error", [None, "MessageIdInvalidError", "FileReferenceExpiredError", "MediaInvalidError"]) +@pytest.mark.parametrize("copy_error", [None, "FileReferenceExpiredError"]) +@pytest.mark.parametrize("send_error", [None, "UserIsBlockedError", "ChatWriteForbiddenError"]) +@pytest.mark.parametrize("reading", ["fine", "late", "unreadable"]) +def test_whatever_goes_wrong_the_channel_is_left_clean_and_the_owner_is_told( + tmp_path, monkeypatch, edit_error, copy_error, send_error, reading +): + """Every combination of: the chat refusing the bot, the chat being slow or unreadable, Telegram refusing the userbot's + copy, Telegram refusing every edit. Whatever happens: no helper message, admin right or invite link is left behind, the + userbot's lock is free, and the post and My posts are either both changed or both untouched - and the owner is told.""" + monkeypatch.setattr(userbot_module, "_DM_WAIT", 0) + monkeypatch.setattr(userbot_module, "_DM_POLLS", 3) + + async def run(): + app, chan, user = await make_app(tmp_path) + if edit_error: + chan.fail["user:EditMessageRequest"] = rpc(edit_error) + if copy_error: + chan._dm.reference_error = rpc(copy_error) + if send_error: + chan._dm.error = rpc(send_error) + if reading == "late": + chan._dm.late = 99 + elif reading == "unreadable": + chan._dm.read_error = rpc("PeerIdInvalidError") + await replace(app) + last = said(app)[-1] + assert chan.admins == {} and all(i["revoked"] for i in chan.invites.values()) and not app.ctx.userbot.lock.locked() + assert chan._dm.msgs == [] # no helper message is left in the userbot's chat + post, live = await the_post(app), chan.msgs[MID] + if "Replaced the media" in last: # it worked: the channel and My posts agree + assert live.message == "new caption" and live.media.photo.id != 10 and post.text == "new caption" + assert post.media_file_id == media_info(live)[1] + assert user.uploads or live.media.photo.id == 20 # a copy by reference, or an upload + else: # it did not: nothing was changed anywhere, and the owner is told why + assert "Nothing was changed" in last and "The userbot could not do it either" in last + assert live.message == "old caption" and live.media.photo.id == 10 and post.text == "old caption" + await app.db.close() + + asyncio.run(run()) + + +# --------------------------------------------------------------------------------------------- /userbot +def test_the_userbot_status_says_it_has_to_start_the_bot(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path) + await app.text("/userbot") + text = said(app)[-1] + assert "connected as @helper_acct" in text and "made admin only while it deletes or edits" in text + assert "must have started this bot" in text and "/start" in text + (tmp_path / "off").mkdir() + off, _, _ = await make_app(tmp_path / "off", userbot=False) + await off.text("/userbot") + text = said(off)[-1] + assert "not set up" in text and "send /start to this bot from that account" in text + await app.db.close() + await off.db.close() + + asyncio.run(run()) + + +# ------------------------------------------------------------- Telegram's own formatting, HTML, Markdown +def sent_caption(app): + kw = app.tg.edits[-1][2] + return kw["text"], [(type(e).__name__, e.offset, e.length) for e in kw["formatting_entities"]] + + +def test_replace_keeps_the_formatting_made_in_telegram(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path, foreign=False) + ents = [types.MessageEntityItalic(0, 3), types.MessageEntityTextUrl(4, 7, "https://x.com"), types.MessageEntityBlockquote(12, 3, True)] + await replace(app, caption="new **cap** now", entities=ents) # Telegram formatting wins: the ** stays as typed + assert sent_caption(app) == ("new **cap** now", [("MessageEntityItalic", 0, 3), ("MessageEntityTextUrl", 4, 7), ("MessageEntityBlockquote", 12, 3)]) + assert "Formatting read from" not in said(app)[-1] + post = await the_post(app) + assert [e["k"] for e in post.entities] == ["italic", "url", "quote"] and post.entities[2]["c"] is True + await app.db.close() + + asyncio.run(run()) + + +def test_replace_reads_markdown_typed_without_the_editor(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path, foreign=False) + await replace(app, caption="**Attack on Titan** - [watch](https://t.me/x)\n> quoted") + text, ents = sent_caption(app) + assert text == "Attack on Titan - watch\nquoted" + assert ents == [("MessageEntityBold", 0, 15), ("MessageEntityTextUrl", 18, 5), ("MessageEntityBlockquote", 24, 6)] + assert "Formatting read from Markdown" in said(app)[-1] + await app.db.close() + + asyncio.run(run()) + + +def test_replace_reads_html_typed_without_the_editor(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path, foreign=False) + await replace(app, caption='Episode 12 here & secret') + text, ents = sent_caption(app) + assert text == "Episode 12 here & secret" + assert ents == [("MessageEntityBold", 0, 10), ("MessageEntityTextUrl", 11, 4), ("MessageEntitySpoiler", 18, 6)] + assert "Formatting read from HTML" in said(app)[-1] + await app.db.close() + + asyncio.run(run()) + + +def test_markup_input_can_be_switched_off(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path, foreign=False, markup_input=False) + await replace(app, caption="**kept** as typed") + assert sent_caption(app) == ("**kept** as typed", []) + assert "Formatting read from" not in said(app)[-1] + await app.db.close() + + asyncio.run(run()) + + +def test_a_caption_that_is_too_long_is_refused_before_anything_happens(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path) + await replace(app, caption="x" * 1025) + assert "at most 1024 characters" in said(app)[-1] + assert app.tg.edits == [] and user.requests == [] and chan.msgs[MID].message == "old caption" + await app.db.close() + + asyncio.run(run()) + + +def test_the_length_limit_counts_the_text_after_the_markup_is_read(tmp_path): + async def run(): + app, chan, user = await make_app(tmp_path, foreign=False) + await replace(app, caption="**" + "x" * 1020 + "**") # 1024 characters of text; the marks don't count + assert len(sent_caption(app)[0]) == 1020 + await app.db.close() + + asyncio.run(run()) diff --git a/tests/test_repost.py b/tests/test_repost.py new file mode 100644 index 0000000000000000000000000000000000000000..1909a2a5ec2626e3a6c54973b824a0de36fb9cf7 --- /dev/null +++ b/tests/test_repost.py @@ -0,0 +1,344 @@ +"""The repost engine against a simulated channel: what is copied how, buttons verified, deletes with a userbot.""" +import asyncio + +from telethon import functions, types + +from app.repost_engine import RepostOptions, delete_copies, plan_repost, run_repost +from app.tgutil import button_url, is_callback_button, utf16_len + +from .dbutil import db_url_for, fresh_db +from .fakes import ( + FakeChannelClient, + cb_btn, + make_msg, + markup, + photo_media, + quote, + rpc, + service_msg, + url_btn, + video_media, +) + +OLD, NEW = "oldbot", "goku" +Q_TEXT = "Click the button below 👇" +CAP = "Caption 😀 with link" +TYPED = "see https://t.me/oldbot?start=Q done" + + +def build(): + """A little channel: pure posts, button posts, hyperlinks, an album, a typed link, a service message.""" + typed_bold = types.MessageEntityBold(TYPED.index("done"), 4) + return { + 1: make_msg(1, "Welcome", [types.MessageEntityBold(0, 7)]), + 2: make_msg( + 2, + Q_TEXT, + [quote(0, utf16_len(Q_TEXT), True)], + markup( + [url_btn("Download Episode 1", f"https://t.me/{OLD}?start=AAA")], + [url_btn("Other", "https://example.com/x"), cb_btn("👍 3", b"r1")], + ), + ), + 3: make_msg( + 3, CAP, [types.MessageEntityBold(0, 7), types.MessageEntityTextUrl(16, 4, "https://t.me/OldBot?start=ZZZ")], + media=photo_media(31), + ), + 4: make_msg(4, "", media=photo_media(41), grouped_id=50), + 5: make_msg(5, "album caption", [types.MessageEntityItalic(0, 5)], media=photo_media(42), grouped_id=50), + 6: service_msg(6), + 8: make_msg(8, "Movie", markup=markup([url_btn("Get", f"https://t.me/{OLD}?start=VVV")]), media=video_media(81)), + 9: make_msg(9, TYPED, [typed_bold]), + 10: make_msg(10, "Bye", [types.MessageEntityItalic(0, 3)]), + } + + +async def setup(tmp_path, chan=None, **mig_kw): + db = await fresh_db(db_url_for(tmp_path)) + await db.save_channel(1, 5, "Test", "testch", 99) + ch = await db.get_channel(1) + chan = chan or FakeChannelClient(build()) + kw = dict(old=OLD, new=NEW, include_typed=True, include_posts=False, first_id=1, last_id=max(chan.msgs), partial=False, user_id=99) + kw.update(mig_kw) + await db.create_migration("m1", 1, **kw) + return db, ch, chan, await db.get_migration("m1") + + +def edit_requests(chan): + return [r for r in chan.requests if isinstance(r, functions.messages.EditMessageRequest)] + + +def forwarded_ids(chan): + return [list(r.id) for r in chan.requests if isinstance(r, functions.messages.ForwardMessagesRequest)] + + +def test_plan_counts(tmp_path): + async def run(): + db, ch, chan, _ = await setup(tmp_path) + plan = await plan_repost(chan, ch, RepostOptions(OLD, NEW)) + assert (plan.first, plan.last, plan.error) == (1, 10, None) + assert (plan.units, plan.messages, plan.albums, plan.service) == (7, 8, 1, 1) + assert (plan.text, plan.media) == (4, 4) + assert plan.link_posts == 4 and (plan.n_buttons, plan.n_links, plan.n_typed) == (2, 1, 1) + assert plan.dropped_posts == 1 # post 2 carries somebody else's 👍 button + await db.close() + + asyncio.run(run()) + + +def test_pure_posts_are_forwarded_and_button_posts_are_created_with_their_buttons(tmp_path): + async def run(): + db, ch, chan, mig = await setup(tmp_path) + res = await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + assert (res.copied_units, res.copied_messages, res.failed, res.aborted) == (7, 8, [], None) + assert (res.forwarded, res.rebuilt, res.repaired) == (3, 4, 0) + # only posts that need no change are copied by Telegram ... + assert forwarded_ids(chan) == [[1], [4, 5], [10]] + # ... and nothing was ever edited afterwards: buttons are part of the request that creates the post + assert edit_requests(chan) == [] + + new = {i: m for i, m in chan.msgs.items() if i > 10} + assert list(new) == list(range(11, 19)) # same order as the originals + # 11 = Welcome (forwarded, untouched) + assert new[11].message == "Welcome" and isinstance(new[11].entities[0], types.MessageEntityBold) + # 12 = the button post: final text, expandable quote kept, link button swapped, foreign button dropped + m = new[12] + assert m.message == Q_TEXT + assert isinstance(m.entities[0], types.MessageEntityBlockquote) and m.entities[0].collapsed + rows = m.reply_markup.rows + assert len(rows) == 2 and len(rows[0].buttons) == 1 and len(rows[1].buttons) == 1 + assert button_url(rows[0].buttons[0]) == f"https://t.me/{NEW}?start=AAA" + assert rows[0].buttons[0].text == "Download Episode 1" + assert button_url(rows[1].buttons[0]) == "https://example.com/x" + assert not any(is_callback_button(b) for r in rows for b in r.buttons) + # 13 = photo with a hyperlink to the old name: media re-sent by reference, link swapped, bold kept + m = new[13] + assert m.message == CAP and m.media.photo.id == 31 + ents = {type(e).__name__: e for e in m.entities} + assert ents["MessageEntityTextUrl"].url == f"https://t.me/{NEW}?start=ZZZ" and ents["MessageEntityTextUrl"].offset == 16 + assert ents["MessageEntityBold"].length == 7 + # 14, 15 = the album, forwarded as one unit with a new shared group id + assert new[14].grouped_id and new[14].grouped_id == new[15].grouped_id != 50 + assert new[15].message == "album caption" + # 16 = video with a button; 17 = typed link swapped and the bold span moved with the text + assert new[16].media.document.id == 81 and button_url(new[16].reply_markup.rows[0].buttons[0]) == f"https://t.me/{NEW}?start=VVV" + assert new[17].message == TYPED.replace(OLD, NEW) + b = new[17].entities[0] + assert new[17].message.encode("utf-16-le")[b.offset * 2 : (b.offset + b.length) * 2].decode("utf-16-le") == "done" + assert new[18].message == "Bye" + + # everything is registered in My posts exactly as it looks in the channel + done = await db.migration_done_old_ids("m1") + assert done == {1, 2, 3, 4, 5, 8, 9, 10} + p12 = await db.find_by_message(1, 12) + assert p12.source == "bot" and p12.status == "sent" and p12.text == Q_TEXT + assert p12.buttons == [ + [{"t": "Download Episode 1", "u": f"https://t.me/{NEW}?start=AAA"}], + [{"t": "Other", "u": "https://example.com/x"}], + ] + p13 = await db.find_by_message(1, 13) + assert p13.media_kind == "photo" and p13.media_file_id.startswith("tl:") + assert (await db.migration_counts("m1"))["copied"] == 8 + # the originals are untouched + assert all(i in chan.msgs for i in (1, 2, 3, 4, 5, 8, 9, 10)) + await db.close() + + asyncio.run(run()) + + +def test_channel_that_forbids_forwarding_gets_everything_rebuilt(tmp_path): + async def run(): + chan = FakeChannelClient(build()) + chan.restrict_forwards = True + db, ch, chan, mig = await setup(tmp_path, chan) + res = await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + assert (res.copied_units, res.failed, res.forwarded, res.rebuilt) == (7, [], 0, 7) + assert len(forwarded_ids(chan)) == 1 # tried once, then remembered that it is not allowed + new = {i: m for i, m in chan.msgs.items() if i > 10} + assert [new[i].message for i in sorted(new)] == [ + "Welcome", Q_TEXT, CAP, "", "album caption", "Movie", TYPED.replace(OLD, NEW), "Bye", + ] + a, b = new[14], new[15] + assert a.grouped_id == b.grouped_id and a.media.photo.id == 41 and b.media.photo.id == 42 + assert isinstance(b.entities[0], types.MessageEntityItalic) + await db.close() + + asyncio.run(run()) + + +def test_a_keyboard_that_is_not_shown_is_noticed_and_repaired(tmp_path): + async def run(): + chan = FakeChannelClient(build()) + chan.hide_keyboard_on_create = 1 # Telegram "forgets" the keyboard of the next button post + db, ch, chan, mig = await setup(tmp_path, chan) + res = await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + assert res.failed == [] and res.copied_units == 7 and res.repaired == 1 + live = chan.msgs[12].reply_markup + assert live is not None and button_url(live.rows[0].buttons[0]) == f"https://t.me/{NEW}?start=AAA" + # Telegram said "not modified" to the plain edit, so the two-step edit was needed (a stand-in, then the real one) + assert len(chan.edits) == 2 + assert button_url(chan.edits[0].reply_markup.rows[0].buttons[0]) == "https://t.me/telegram" + assert chan.edits[1].reply_markup is not None + await db.close() + + asyncio.run(run()) + + +def test_a_copy_that_never_shows_its_buttons_is_removed_and_the_original_kept(tmp_path): + async def run(): + chan = FakeChannelClient(build()) + chan.drop_all_markup = True + db, ch, chan, mig = await setup(tmp_path, chan) + res = await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + assert res.failed == [(2, "ButtonsNotShown"), (8, "ButtonsNotShown")] and res.aborted is None + assert res.copied_units == 5 + # no copy of the failed posts is left, and they are not registered + assert sorted(i for i in chan.msgs if i > 10 and chan.msgs[i].message in (Q_TEXT, "Movie")) == [] + done = await db.migration_done_old_ids("m1") + assert 2 not in done and 8 not in done and {1, 3, 4, 5, 9, 10} <= done + assert 2 in chan.msgs and 8 in chan.msgs and chan.msgs[2].reply_markup is not None + await db.close() + + asyncio.run(run()) + + +def test_stop_then_continue_copies_nothing_twice(tmp_path): + async def run(): + db, ch, chan, mig = await setup(tmp_path) + seen = [] + + async def progress(r): + seen.append(r.copied_units) + + res = await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0, progress=progress, should_stop=lambda: len(seen) >= 3) + assert res.stopped and res.copied_units == 3 + res2 = await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + assert not res2.stopped and res2.skipped_done == 3 and res2.copied_units == 4 + texts = [m.message for i, m in sorted(chan.msgs.items()) if i > 10] + assert texts.count("Welcome") == 1 and texts.count("Bye") == 1 and len(texts) == 8 + await db.close() + + asyncio.run(run()) + + +def test_a_fatal_telegram_error_stops_the_run(tmp_path): + async def run(): + chan = FakeChannelClient(build()) + chan.fail["SendMessageRequest"] = rpc("ChatWriteForbiddenError") + db, ch, chan, mig = await setup(tmp_path, chan) + res = await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + assert res.aborted == "ChatWriteForbiddenError" and res.copied_units == 1 # only the forwarded first post + await db.close() + + asyncio.run(run()) + + +# ------------------------------------------------------------------------------------------ deleting +async def copied(tmp_path, chan=None): + db, ch, chan, mig = await setup(tmp_path, chan) + await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + return db, ch, chan, await db.get_migration("m1") + + +def test_delete_old_posts_with_the_bot_alone(tmp_path): + async def run(): + db, ch, chan, mig = await copied(tmp_path) + res = await delete_copies(chan, db, ch, mig, "old", delay=0) + assert (res.deleted, res.remaining, res.error, res.by_userbot, res.blocked) == (8, 0, None, 0, False) + assert sorted(chan.msgs) == [6] + list(range(11, 19)) + assert await db.find_by_message(1, 2) is None # nothing left of the old posts in the database + assert await db.find_by_message(1, 12) is not None # the copies stay + await db.close() + + asyncio.run(run()) + + +def test_old_posts_the_bot_cannot_delete_go_to_the_userbot(tmp_path): + async def run(): + db, ch, chan, mig = await copied(tmp_path) + chan.undeletable = {1, 2, 3, 4, 5} # "older than 48 hours" for the bot + calls = [] + + async def userbot(ids): + calls.append(list(ids)) + for i in ids: + chan.msgs.pop(i, None) + + res = await delete_copies(chan, db, ch, mig, "old", delay=0, fallback=userbot) + assert calls == [[1, 2, 3, 4, 5]] + assert (res.deleted, res.by_userbot, res.remaining, res.error, res.tried_userbot) == (8, 5, 0, None, True) + assert sorted(chan.msgs) == [6] + list(range(11, 19)) + await db.close() + + asyncio.run(run()) + + +def test_a_failing_userbot_is_reported_and_what_the_bot_could_delete_still_counts(tmp_path): + async def run(): + db, ch, chan, mig = await copied(tmp_path) + chan.undeletable = {1, 2, 3, 4, 5} + calls = [] + + async def userbot(ids): + calls.append(ids) + raise RuntimeError("the userbot is banned here") + + res = await delete_copies(chan, db, ch, mig, "old", delay=0, fallback=userbot) + assert res.deleted == 3 and res.remaining == 5 and res.by_userbot == 0 + assert res.fallback_error == "the userbot is banned here" and res.blocked and res.error is None + assert len(calls) == 1 + await db.close() + + asyncio.run(run()) + + +def many_messages(n): + return {i: make_msg(i, f"post {i}") for i in range(1, n + 1)} + + +def test_an_undeletable_batch_does_not_stop_the_newer_ones(tmp_path): + async def run(): + chan = FakeChannelClient(many_messages(250)) + db, ch, chan, mig = await setup(tmp_path, chan, old=None, new=None) + rows = [{"old_id": i, "new_id": 1000 + i, "post": {"text": "x", "entities": [], "buttons": [], "media_kind": None, "media_file_id": None, "link_preview": False}} for i in range(1, 251)] + await db.record_repost("m1", 1, rows, 99) + chan.undeletable = set(range(1, 101)) + res = await delete_copies(chan, db, ch, mig, "old", delay=0) + assert len(chan.delete_requests) == 3 # all three batches were tried + assert (res.deleted, res.remaining, res.blocked, res.error) == (150, 100, True, None) + await db.close() + + asyncio.run(run()) + + +def test_missing_delete_right_stops_after_the_first_batch(tmp_path): + async def run(): + chan = FakeChannelClient(many_messages(250)) + db, ch, chan, mig = await setup(tmp_path, chan, old=None, new=None) + rows = [{"old_id": i, "new_id": 1000 + i, "post": {"text": "x", "entities": [], "buttons": [], "media_kind": None, "media_file_id": None, "link_preview": False}} for i in range(1, 251)] + await db.record_repost("m1", 1, rows, 99) + chan.delete_error = rpc("ChatAdminRequiredError") + res = await delete_copies(chan, db, ch, mig, "old", delay=0) + assert res.error == "ChatAdminRequiredError" and res.deleted == 0 and len(chan.delete_requests) == 1 + + # with a userbot that can do it, the bot's missing right is no problem + async def userbot(ids): + for i in ids: + chan.msgs.pop(i, None) + + res = await delete_copies(chan, db, ch, mig, "old", delay=0, fallback=userbot) + assert (res.deleted, res.by_userbot, res.remaining, res.error) == (250, 250, 0, None) + await db.close() + + asyncio.run(run()) + + +def test_undo_removes_only_the_copies(tmp_path): + async def run(): + db, ch, chan, mig = await copied(tmp_path) + res = await delete_copies(chan, db, ch, mig, "new", delay=0) + assert res.deleted == 8 and res.remaining == 0 + assert sorted(chan.msgs) == [1, 2, 3, 4, 5, 6, 8, 9, 10] + await db.close() + + asyncio.run(run()) diff --git a/tests/test_repost_flow.py b/tests/test_repost_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..83ac3a5240e171d909f6534975c618fbe50f77c8 --- /dev/null +++ b/tests/test_repost_flow.py @@ -0,0 +1,613 @@ +"""/repost as the owner experiences it: pick the channel with buttons, check the plan, copy, then delete the old +posts (by the bot, or by the userbot when the bot is not allowed to).""" +import asyncio +from types import SimpleNamespace + +from app.tgutil import button_url +from app.userbot import Userbot + +from .fakes import FakeUserClient, make_msg +from .harness import App, norm +from .test_repost import NEW, OLD, build + +OLD_IDS = {1, 2, 3, 4, 5, 8, 9, 10} # the posts of build() that /repost copies (6 is a service message) + + +def fill(tg, msgs): + tg.msgs = dict(msgs) + tg._top = max(msgs, default=0) + for m in msgs.values(): + tg._remember_media(m) + + +async def make_app(tmp_path, msgs=None, **cfg): + cfg.setdefault("edit_delay", 0.0) + app = App(tmp_path, **cfg) + await app.start() + await app.db.save_channel(1, 5, "Test", "testch", 1) + fill(app.tg, build() if msgs is None else msgs) + return app + + +def buttons_text(app): + return " | ".join(t for row in app.out.last_buttons() for t in row) + + +async def pick(app, args=f"@{OLD} @{NEW}"): + await app.text(f"/repost {args}".strip()) + await app.press(app.out.callback_data("Test")) + + +async def copy_all(app): + await pick(app) + await app.press(app.out.callback_data("Start copying")) + + +def migration_id(app): + return app.out.callback_data("Undo").split(":")[1] + + +# ---------------------------------------------------------------------------------------- choosing +def test_usage_does_not_mention_the_channel_option_any_more(tmp_path): + async def run(): + app = await make_app(tmp_path) + await app.text("/repost") + text = norm(app.out.last_text) + assert "Usage" in text and "--channel" not in text and "buttons" in text + await app.db.close() + + asyncio.run(run()) + + +def test_the_old_channel_option_is_explained_not_obeyed(tmp_path): + async def run(): + app = await make_app(tmp_path) + await app.text(f"/repost @{OLD} @{NEW} --channel @testch") + assert "no longer takes --channel" in norm(app.out.last_text) + assert app.tg.requests == [] # nothing was read or posted + await app.db.close() + + asyncio.run(run()) + + +def test_connected_channels_are_offered_as_a_numbered_list(tmp_path): + async def run(): + app = await make_app(tmp_path) + await app.db.save_channel(2, 6, "Second channel", None, 1) + await app.text(f"/repost @{OLD} @{NEW}") + text = norm(app.out.last_text) + assert "Which channel" in text and f"@{OLD}" in text and f"@{NEW}" in text + assert "1. Second channel" in text and "2. Test" in text # the names are in the message, A to Z + assert app.out.last_buttons() == [["1", "2"], ["✖️ Cancel"]] # the buttons only carry the numbers + first, second = app.out.callback_exact("1"), app.out.callback_exact("2") + assert first.startswith("rpch:") and first.endswith(":2") # number 1 is "Second channel", channel 2 + assert second.startswith("rpch:") and second.endswith(":1") + assert app.tg.requests == [] # choosing is free: nothing is read before a button is pressed + await app.db.close() + + asyncio.run(run()) + + +def test_without_usernames_the_posts_are_copied_without_changing_links(tmp_path): + async def run(): + app = await make_app(tmp_path) + await app.text("/repost") + assert "Usage" in norm(app.out.last_text) + await app.text("/repost --last 4") + assert "copy without changing any link" in norm(app.out.last_text) and "newest 4" in norm(app.out.last_text) + await app.press(app.out.callback_data("Test")) + assert "Repost plan" in norm(app.out.last_text) and "Trial run" in norm(app.out.last_text) + await app.db.close() + + asyncio.run(run()) + + +def test_no_registered_channel_is_explained(tmp_path): + async def run(): + app = App(tmp_path) + await app.start() + await app.text(f"/repost @{OLD} @{NEW}") + assert "No channels registered" in norm(app.out.last_text) + await app.db.close() + + asyncio.run(run()) + + +def test_bad_arguments(tmp_path): + async def run(): + app = await make_app(tmp_path) + for bad, part in [ + (f"@{OLD}", "both usernames"), + (f"@{OLD} @{OLD}", "are the same"), + ("@a-b @c", "Usernames look like"), + ("--last x", "--last needs a number"), + ("--wat", "Unknown option"), + ]: + await app.text(f"/repost {bad}") + assert part in norm(app.out.last_text), (bad, norm(app.out.last_text)) + await app.db.close() + + asyncio.run(run()) + + +def test_the_list_can_be_cancelled_and_then_no_longer_works(tmp_path): + async def run(): + app = await make_app(tmp_path) + await app.text(f"/repost @{OLD} @{NEW}") + pick_data = app.out.callback_data("Test") + await app.press(app.out.callback_data("Cancel")) + assert "Cancelled" in norm(app.out.last_text) + await app.press(pick_data) + assert "expired" in norm(app.out.last_text) + assert app.tg.requests == [] + await app.db.close() + + asyncio.run(run()) + + +def test_a_forged_or_old_button_is_refused(tmp_path): + async def run(): + app = await make_app(tmp_path) + await app.press("rpch:deadbeef:1") + assert "expired" in norm(app.out.last_text) + await app.press("rpa:deadbeef") + assert "expired" in norm(app.out.last_text) + await app.press("rpdy:nosuch") + assert "don't know that repost" in norm(app.out.last_text) + await app.db.close() + + asyncio.run(run()) + + +def test_only_the_owner_can_use_it(tmp_path): + async def run(): + app = await make_app(tmp_path, admins=frozenset({7})) + app.uid = 7 # an allowed helper account, but not an owner + await app.text(f"/repost @{OLD} @{NEW}") + assert "private" in norm(app.out.last_text) + # a list made by the owner can't be used by somebody else, even by pressing the same button + app.uid = 1 + await app.text(f"/repost @{OLD} @{NEW}") + data = app.out.callback_data("Test") + app.uid = 7 + await app.press(data) + assert "Only the bot owner" in norm(app.out.last_text) + await app.press("rpdy:whatever") + assert "Only the bot owner" in norm(app.out.last_text) + assert app.tg.requests == [] + await app.db.close() + + asyncio.run(run()) + + +def test_the_bot_needs_the_post_right(tmp_path): + async def run(): + app = await make_app(tmp_path) + app.tg.rights = dict(admin=True, post=False, edit=True, delete=True, invite=False, add_admins=False) + await pick(app) + assert "Post messages" in norm(app.out.last_text) + await app.db.close() + + asyncio.run(run()) + + +def test_another_long_job_blocks_a_new_plan(tmp_path): + async def run(): + app = await make_app(tmp_path) + await app.text(f"/repost @{OLD} @{NEW}") + data = app.out.callback_data("Test") + await app.ctx.lock.acquire() + await app.press(data) + assert "still running" in norm(app.out.last_text) + app.ctx.lock.release() + await app.press(data) # the list is still valid afterwards + assert "Repost plan" in norm(app.out.last_text) + await app.db.close() + + asyncio.run(run()) + + +# ------------------------------------------------------------------------------------------ plan +def test_the_plan_describes_what_will_happen(tmp_path): + async def run(): + app = await make_app(tmp_path) + await pick(app) + text = norm(app.out.last_text) + assert "Repost plan - Test" in text + assert "7 posts to copy (8 messages, 1 album(s))" in text + assert f"@{OLD} → @{NEW} in 4 post(s): 2 button link(s), 1 hyperlink(s), 1 typed link(s)" in text + assert "1 service message(s)" in text + assert "1 post(s) carry other bots' buttons" in text + assert "read back" in text and "Nothing is deleted in this step" in text + assert app.out.last_buttons() == [["▶️ Start copying", "✖️ Cancel"]] + # planning only reads: nothing was copied, posted or deleted + assert app.tg.requests and not any( + type(r).__name__ in ("ForwardMessagesRequest", "SendMessageRequest", "SendMediaRequest", "DeleteMessagesRequest") + for r in app.tg.requests + ) + assert sorted(app.tg.msgs) == sorted(build()) # reading changed nothing + await app.db.close() + + asyncio.run(run()) + + +def test_plan_of_an_empty_channel(tmp_path): + async def run(): + app = await make_app(tmp_path, msgs={}) + await pick(app) + assert "⚠️" in norm(app.out.last_text) and "Start copying" not in buttons_text(app) + await app.db.close() + + asyncio.run(run()) + + +# ---------------------------------------------------------------------------------- copy and result +def test_copy_everything_and_look_at_the_result(tmp_path): + async def run(): + app = await make_app(tmp_path) + await copy_all(app) + text = norm(app.out.last_text) + assert "Test: all posts copied in order" in text and f"@{OLD} → @{NEW}" in text + assert "8 messages are now at the end of the channel" in text + assert "3 post(s) were copied by Telegram, 4 were posted again with their buttons" in text + assert "Delete the old posts" in buttons_text(app) and "Undo" in buttons_text(app) + # the channel: the originals are untouched and the 8 copies follow in order + assert OLD_IDS <= set(app.tg.msgs) + new = [app.tg.msgs[i] for i in sorted(app.tg.msgs) if i > 10] + assert [m.message for m in new][0] == "Welcome" and [m.message for m in new][-1] == "Bye" + with_buttons = [m for m in new if m.reply_markup is not None] + assert len(with_buttons) == 2 + assert button_url(with_buttons[0].reply_markup.rows[0].buttons[0]) == f"https://t.me/{NEW}?start=AAA" + mig = await app.db.get_migration(migration_id(app)) + assert mig.status == "copied" and not mig.partial + # every copy is in My posts + assert (await app.db.migration_counts(mig.id))["copied"] == 8 + await app.db.close() + + asyncio.run(run()) + + +def test_a_second_press_on_start_does_not_copy_twice(tmp_path): + async def run(): + app = await make_app(tmp_path) + await pick(app) + start = app.out.callback_data("Start copying") + await app.press(start) + n = len(app.tg.msgs) + await app.press(start) + assert "expired" in norm(app.out.last_text) + assert len(app.tg.msgs) == n + await app.db.close() + + asyncio.run(run()) + + +def test_an_unfinished_repost_is_offered_again_and_blocks_a_second_one(tmp_path): + async def run(): + app = await make_app(tmp_path) + await pick(app) + await app.press(app.out.callback_data("Start copying")) + mid = migration_id(app) + # the copy is finished but the old posts are not decided yet: /repost shows where things stand + await app.db.set_migration_status(mid, "stopped") + await app.text("/repost") + text = norm(app.out.last_text) + assert "Unfinished repost" in text and "stopped" in text and "Continue" in buttons_text(app) + await app.text(f"/repost @{OLD} @{NEW}") + await app.press(app.out.callback_data("Test")) + assert "unfinished repost for this channel" in norm(app.out.last_text) + await app.db.close() + + asyncio.run(run()) + + +def test_continue_after_a_stop_finishes_the_job_without_copying_twice(tmp_path): + async def run(): + from app.repost_engine import run_repost + + app = await make_app(tmp_path) + ch = await app.db.get_channel(1) + await app.db.create_migration( + "mig1", 1, old=OLD, new=NEW, include_typed=True, include_posts=False, first_id=1, last_id=10, partial=False, user_id=1 + ) + mig = await app.db.get_migration("mig1") + seen = [] + + async def progress(r): + seen.append(r.copied_units) + + res = await run_repost(app.tg, app.db, ch, mig, 1, delay=0, settle_pause=0, progress=progress, should_stop=lambda: len(seen) >= 3) + assert res.stopped and res.copied_units == 3 + await app.db.set_migration_status("mig1", "stopped") + await app.text("/repost") + assert "Continue" in buttons_text(app) + await app.press(app.out.callback_data("Continue")) + assert "all posts copied in order" in norm(app.out.last_text) + texts = [m.message for i, m in sorted(app.tg.msgs.items()) if i > 10] + assert len(texts) == 8 and texts.count("Welcome") == 1 + await app.db.close() + + asyncio.run(run()) + + +def test_stop_button_without_a_running_job(tmp_path): + async def run(): + app = await make_app(tmp_path) + await app.press("rps:nothing") + assert "Nothing is running" in norm(app.out.last_text) + await app.db.close() + + asyncio.run(run()) + + +def test_a_failed_copy_is_reported_and_can_be_retried(tmp_path): + async def run(): + app = await make_app(tmp_path) + app.tg.drop_all_markup = True # Telegram never shows the keyboards + await copy_all(app) + text = norm(app.out.last_text) + assert "not everything was copied" in text + assert "2 post(s) failed" in text and "ButtonsNotShown" in text + assert "Try the rest again" in buttons_text(app) and "Delete the old posts" not in buttons_text(app) + # the failed posts left no copy behind + assert not [m for i, m in app.tg.msgs.items() if i > 10 and m.message in ("Movie",)] + # once Telegram behaves, "try the rest again" completes the job + app.tg.drop_all_markup = False + await app.press(app.out.callback_data("Try the rest again")) + assert "all posts copied in order" in norm(app.out.last_text) + await app.db.close() + + asyncio.run(run()) + + +# ----------------------------------------------------------------------------- deleting old posts +def test_delete_old_posts_with_the_bot_alone(tmp_path): + async def run(): + app = await make_app(tmp_path) + await copy_all(app) + mid = migration_id(app) + await app.press(app.out.callback_data("Delete the old posts")) + text = norm(app.out.last_text) + assert "Delete 8 old message(s)" in text and "can't be undone" in text + await app.press(app.out.callback_data("Yes, delete 8")) + text = norm(app.out.last_text) + assert "Done. 8 old message(s) deleted" in text and "by the userbot" not in text + assert sorted(app.tg.msgs) == [6] + list(range(11, 19)) + assert (await app.db.get_migration(mid)).status == "old_deleted" + assert await app.db.open_migration() is None + # the copies are the channel now: still registered in My posts, the originals are not + assert await app.db.find_by_message(1, 12) is not None and await app.db.find_by_message(1, 2) is None + await app.db.close() + + asyncio.run(run()) + + +def test_old_posts_the_bot_cannot_delete_are_explained_when_there_is_no_userbot(tmp_path): + async def run(): + app = await make_app(tmp_path) + await copy_all(app) + app.tg.undeletable = {1, 2, 3, 4, 5} # "older than 48 hours" for the bot + await app.press(app.out.callback_data("Delete the old posts")) + await app.press(app.out.callback_data("Yes, delete")) + text = norm(app.out.last_text) + assert "Deleted 3, 5 old message(s) are still there" in text + assert "userbot" in text and "/userbot" in text + assert "Try again" in buttons_text(app) and "Close this repost" in buttons_text(app) + assert sorted(i for i in app.tg.msgs if i <= 10) == [1, 2, 3, 4, 5, 6] + await app.db.close() + + asyncio.run(run()) + + +def userbot_setup(app, *, bot_rights=None, username="helper_acct"): + """A real Userbot object wired to a simulated second account, plus the channel rights of the bot.""" + app.tg.rights = bot_rights or dict(admin=True, post=True, edit=True, delete=True, invite=True, add_admins=True) + app.tg.username = None # a private channel: the only way in is an invite link + holder = {} + + def factory(cfg): + holder["client"] = FakeUserClient(app.tg, username=username) + return holder["client"] + + cfg = SimpleNamespace(userbot_session="SESSION", userbot_keep_admin=False, api_id=1, api_hash="x") + ub = Userbot(app.tg, cfg, client_factory=factory) + app.ctx.userbot = ub + return ub, holder + + +def test_the_userbot_joins_promotes_deletes_and_then_steps_back(tmp_path): + async def run(): + app = await make_app(tmp_path) + await copy_all(app) + ub, holder = userbot_setup(app) + app.tg.undeletable = {1, 2, 3, 4, 5} + await app.press(app.out.callback_data("Delete the old posts")) + await app.press(app.out.callback_data("Yes, delete")) + text = norm(app.out.last_text) + assert "Done. 8 old message(s) deleted (5 of them by the userbot)" in text + assert "made a one-time invite link" in text and "the userbot joined the channel" in text + assert "made the userbot an admin with only “Delete messages”" in text + assert "took the admin right away from the userbot again" in text + assert sorted(app.tg.msgs) == [6] + list(range(11, 19)) + # the userbot only did what the bot could not + assert holder["client"].deleted == [[1, 2, 3, 4, 5]] + # nothing is left behind: no admin right, and the temporary link is revoked + assert app.tg.admins == {} + assert all(v["revoked"] for v in app.tg.invites.values()) and len(app.tg.invites) == 1 + # the user's account stays a member (it was never asked to leave) + assert 777 in app.tg.members + await app.db.close() + + asyncio.run(run()) + + +def test_deleting_the_old_posts_never_asks_whether_the_userbot_may_help(tmp_path): + """The one question is about deleting the old posts. Who deletes them is not asked: the bot tries first and the userbot + takes over by itself wherever Telegram refuses the bot - one press of "Yes, delete", one answer.""" + async def run(): + app = await make_app(tmp_path) + await copy_all(app) + userbot_setup(app) + app.tg.undeletable = {1, 2, 3, 4, 5} # the bot is refused for these + await app.press(app.out.callback_data("Delete the old posts")) + ask = norm(app.out.last_text) + assert "Delete 8 old message(s)" in ask and "can't be undone" in ask + assert "userbot" not in ask.lower() and "if you set one up" not in ask # nothing about the helper account to agree to + assert app.out.last_buttons() == [["🗑 Yes, delete 8", "↩️ Back"]] + shown = len(app.out.log) + await app.press(app.out.callback_data("Yes, delete 8")) + after = [norm(row[1]) for row in app.out.log[shown:]] # everything the owner was shown after that one press + assert after and "Done. 8 old message(s) deleted (5 of them by the userbot)" in after[-1] + # nothing on the way asks for a go-ahead: no "may I", no yes/no about the userbot + assert not any(w in t.lower() for t in after for w in ("may i", "permission", "allow", "shall i", "use the userbot?")) + assert app.out.last_buttons() == [["🔗 Update links again"]] + assert sorted(app.tg.msgs) == [6] + list(range(11, 19)) + await app.db.close() + + asyncio.run(run()) + + +def test_the_userbot_is_not_touched_when_the_bot_can_delete_everything(tmp_path): + async def run(): + app = await make_app(tmp_path) + await copy_all(app) + ub, holder = userbot_setup(app) + await app.press(app.out.callback_data("Delete the old posts")) + await app.press(app.out.callback_data("Yes, delete")) + assert "Done. 8 old message(s) deleted" in norm(app.out.last_text) + assert "by the userbot" not in norm(app.out.last_text) + # the helper account is only logged in; it joined nothing and did nothing + assert holder["client"].requests == [] and holder["client"].deleted == [] + assert app.tg.invites == {} and app.tg.members == set() and app.tg.admins == {} + await app.db.close() + + asyncio.run(run()) + + +def test_without_the_add_admins_right_the_owner_is_told_what_to_do(tmp_path): + async def run(): + app = await make_app(tmp_path) + await copy_all(app) + userbot_setup(app, bot_rights=dict(admin=True, post=True, edit=True, delete=True, invite=True, add_admins=False)) + app.tg.undeletable = {1, 2, 3, 4, 5} + await app.press(app.out.callback_data("Delete the old posts")) + await app.press(app.out.callback_data("Yes, delete")) + text = norm(app.out.last_text) + assert "Deleted 3, 5 old message(s) are still there" in text + assert "Add new admins" in text + assert "Try again" in buttons_text(app) + assert app.tg.admins == {} + assert all(v["revoked"] for v in app.tg.invites.values()) # the link made for the userbot does not stay open + await app.db.close() + + asyncio.run(run()) + + +def test_try_again_after_fixing_the_rights_finishes_the_job(tmp_path): + async def run(): + app = await make_app(tmp_path) + await copy_all(app) + userbot_setup(app, bot_rights=dict(admin=True, post=True, edit=True, delete=True, invite=True, add_admins=False)) + app.tg.undeletable = {1, 2, 3, 4, 5} + await app.press(app.out.callback_data("Delete the old posts")) + await app.press(app.out.callback_data("Yes, delete")) + assert "Try again" in buttons_text(app) + app.tg.rights = dict(admin=True, post=True, edit=True, delete=True, invite=True, add_admins=True) # the owner fixed it + await app.press(app.out.callback_data("Try again")) + text = norm(app.out.last_text) + assert "Done. 5 old message(s) deleted (5 of them by the userbot)" in text + assert sorted(app.tg.msgs) == [6] + list(range(11, 19)) + await app.db.close() + + asyncio.run(run()) + + +def test_close_this_repost_after_deleting_by_hand(tmp_path): + async def run(): + app = await make_app(tmp_path) + await copy_all(app) + mid = migration_id(app) + app.tg.undeletable = {1, 2, 3, 4, 5} + await app.press(app.out.callback_data("Delete the old posts")) + await app.press(app.out.callback_data("Yes, delete")) + await app.press(app.out.callback_data("Close this repost")) + assert "Closed" in norm(app.out.last_text) + assert (await app.db.get_migration(mid)).status == "closed" + assert await app.db.open_migration() is None + await app.db.close() + + asyncio.run(run()) + + +# ----------------------------------------------------------------------------------------- undo +def test_undo_removes_the_copies_and_keeps_the_originals(tmp_path): + async def run(): + app = await make_app(tmp_path) + await copy_all(app) + await app.press(app.out.callback_data("Undo")) + assert "Remove the 8 copied message(s)" in norm(app.out.last_text) + await app.press(app.out.callback_data("Yes, remove the copies")) + assert "8 copied message(s) removed" in norm(app.out.last_text) + assert sorted(app.tg.msgs) == sorted(build()) + await app.db.close() + + asyncio.run(run()) + + +def test_undo_is_not_offered_once_originals_are_gone(tmp_path): + async def run(): + app = await make_app(tmp_path) + await copy_all(app) + mid = migration_id(app) + await app.press(app.out.callback_data("Delete the old posts")) + await app.press(app.out.callback_data("Yes, delete")) + await app.press(f"rpu:{mid}") + assert "Undo is not possible" in norm(app.out.last_text) or "already deleted" in norm(app.out.last_text) + await app.press(f"rpuy:{mid}") + assert "Undo is not possible" in norm(app.out.last_text) + assert [i for i in app.tg.msgs if i > 10] == list(range(11, 19)) # the copies are safe + await app.db.close() + + asyncio.run(run()) + + + +def test_trial_run_can_be_removed_or_kept(tmp_path): + async def run(): + app = await make_app(tmp_path) + await app.text(f"/repost @{OLD} @{NEW} --last 3") + await app.press(app.out.callback_data("Test")) + assert "Trial run" in norm(app.out.last_text) + await app.press(app.out.callback_data("Start copying")) + text = norm(app.out.last_text) + assert "trial finished" in text and "Delete the old posts" not in buttons_text(app) + mid = migration_id(app) + close = app.out.callback_data("Close, keep the copies") + # a trial never offers to delete the old posts, even by a hand-made button press + await app.press(f"rpd:{mid}") + assert "complete, successful copy" in norm(app.out.last_text) + await app.press(f"rpdy:{mid}") + assert "complete, successful copy" in norm(app.out.last_text) + assert OLD_IDS <= set(app.tg.msgs) # nothing was deleted + await app.press(close) + assert "Closed" in norm(app.out.last_text) + assert await app.db.open_migration() is None + await app.db.close() + + asyncio.run(run()) + + +def test_messages_posted_during_the_plan_are_not_part_of_it(tmp_path): + async def run(): + msgs = {i: make_msg(i, f"post {i}") for i in range(1, 6)} + app = await make_app(tmp_path, msgs=msgs) + await pick(app) + start = app.out.callback_data("Start copying") + app.tg.msgs[6] = make_msg(6, "posted while the plan was open") # a new post appears + app.tg._top = 6 + await app.press(start) + copies = [m.message for i, m in sorted(app.tg.msgs.items()) if i > 6] + assert copies == [f"post {i}" for i in range(1, 6)] # exactly what the plan showed + await app.db.close() + + asyncio.run(run()) diff --git a/tests/test_repost_links.py b/tests/test_repost_links.py new file mode 100644 index 0000000000000000000000000000000000000000..8c3e3f4ac9f177bec540c141778c8bad79c6fec1 --- /dev/null +++ b/tests/test_repost_links.py @@ -0,0 +1,332 @@ +"""/repost keeps what a plain copy would lose: answers (replies), pins, and links to other posts of the channel.""" +import asyncio + +from telethon import functions, types + +from app.repost_engine import RepostOptions, plan_repost, relink_copies, run_repost +from app.tgutil import button_url + +from .dbutil import db_url_for, fresh_db +from .fakes import FakeChannelClient, make_msg, markup, photo_media, service_msg, url_btn +from .test_repost import edit_requests, forwarded_ids, setup + +CH = "testch" # the channel's username in the database (see setup()) + + +def build_linked(): + """Posts that point at each other, answer each other and are pinned.""" + return { + 1: make_msg(1, "Intro"), + 2: make_msg(2, "Next: part five", [types.MessageEntityTextUrl(6, 9, f"https://t.me/{CH}/5")]), # forward reference + 3: make_msg( + 3, + f"Index: https://t.me/{CH}/1 and https://t.me/c/1/2 and https://t.me/other_chan/2 end", + [types.MessageEntityBold(len("Index: https://t.me/testch/1 and https://t.me/c/1/2 and https://t.me/other_chan/2 "), 3)], + markup([url_btn("Go to 4", f"https://t.me/{CH}/4?single")]), # forward reference in a button + ), + 4: make_msg(4, "Fourth", reply_to=3), + 5: make_msg(5, "Fifth", [types.MessageEntityTextUrl(0, 5, f"https://t.me/{CH}/1?single")], pinned=True, reply_to=4), + 6: service_msg(6), + 7: make_msg(7, "", media=photo_media(71), grouped_id=70, reply_to=5), + 8: make_msg(8, "album caption", media=photo_media(72), grouped_id=70), + 9: make_msg(9, f"Ghost https://t.me/{CH}/999", []), # a post that never existed: left as it is + 10: make_msg(10, "Last", pinned=True), + } + + +def run(coro): + return asyncio.run(coro) + + +async def linked_setup(tmp_path, chan=None, **kw): + chan = chan or FakeChannelClient(build_linked()) + kw.setdefault("old", None) + kw.setdefault("new", None) + return await setup(tmp_path, chan, **kw) + + +def new_posts(chan, above=10): + return {i: m for i, m in chan.msgs.items() if i > above and not isinstance(m, types.MessageService)} + + +def reply_of(m): + return m.reply_to.reply_to_msg_id if m.reply_to else None + + +def test_the_plan_tells_what_will_be_kept(tmp_path): + async def go(): + db, ch, chan, _ = await linked_setup(tmp_path) + plan = await plan_repost(chan, ch, RepostOptions()) + assert plan.error is None and plan.units == 8 + assert plan.pinned == 2 and plan.replies == 3 + assert (plan.post_link_posts, plan.post_links) == (4, 6) # posts 2, 3 (three links), 5 and 9 + await db.close() + + run(go()) + + +def test_replies_pins_and_links_follow_the_copies(tmp_path): + async def go(): + db, ch, chan, mig = await linked_setup(tmp_path) + res = await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + assert (res.copied_units, res.copied_messages, res.failed, res.aborted) == (8, 9, [], None) + new = new_posts(chan) + assert sorted(new) == list(range(11, 11 + 9 + 0)) or sorted(new) == [11, 12, 13, 14, 15, 16, 17, 18, 19] + + # answers: the copy of 4 answers the copy of 3, 5 answers 4, the album answers 5 + assert reply_of(new[11]) is None and reply_of(new[12]) is None and reply_of(new[13]) is None + assert (reply_of(new[14]), reply_of(new[15]), reply_of(new[16]), reply_of(new[17])) == (13, 14, 15, 15) + assert (res.replies, res.reply_lost, res.reply_dropped) == (3, 0, 0) + + # links typed in the text and hyperlinks: backward references were right from the start ... + assert new[13].message == f"Index: https://t.me/{CH}/11 and https://t.me/c/1/12 and https://t.me/other_chan/2 end" + bold = new[13].entities[0] + assert new[13].message.encode("utf-16-le")[bold.offset * 2 : (bold.offset + bold.length) * 2].decode("utf-16-le") == "end" + link5 = [e for e in new[15].entities if isinstance(e, types.MessageEntityTextUrl)][0] + assert link5.url == f"https://t.me/{CH}/11?single" and new[15].message == "Fifth" + # ... forward references were fixed afterwards (post 2 -> 5 is now 15, the button 4 is now 14) + link2 = [e for e in new[12].entities if isinstance(e, types.MessageEntityTextUrl)][0] + assert link2.url == f"https://t.me/{CH}/15" and (link2.offset, link2.length) == (6, 9) + assert button_url(new[13].reply_markup.rows[0].buttons[0]) == f"https://t.me/{CH}/14?single" + assert new[13].reply_markup.rows[0].buttons[0].text == "Go to 4" + assert new[18].message == f"Ghost https://t.me/{CH}/999" # no copy of 999: untouched + fin = res.final + assert (fin.checked, fin.relinked, fin.links, fin.failed) == (9, 2, 2, []) + assert len(edit_requests(chan)) == 2 # only the two posts with a forward reference are edited + + # pins: the copies of the pinned posts, oldest first; the originals stay pinned; no notice is left behind + assert (fin.pin_wanted, fin.pinned, fin.pin_error) == (2, 2, None) + assert chan.pinned_order == [15, 19] + assert new[15].pinned and new[19].pinned and not new[11].pinned + assert chan.msgs[5].pinned and chan.msgs[10].pinned + assert [m.id for m in chan.msgs.values() if isinstance(m, types.MessageService)] == [6] + + # My posts shows exactly what the channel shows + p12, p13 = await db.find_by_message(1, 12), await db.find_by_message(1, 13) + assert p12.entities[0]["u"] == f"https://t.me/{CH}/15" + assert p13.buttons == [[{"t": "Go to 4", "u": f"https://t.me/{CH}/14?single"}]] + assert p13.text == new[13].message + await db.close() + + run(go()) + + +def test_what_needs_no_change_is_still_copied_by_telegram_itself(tmp_path): + async def go(): + db, ch, chan, mig = await linked_setup(tmp_path) + await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + # intro, the forward reference (fixed afterwards), the ghost link and the last post: no reply, no buttons + assert forwarded_ids(chan) == [[1], [2], [9], [10]] + reqs = [r for r in chan.requests if isinstance(r, functions.messages.SendMessageRequest)] + assert [r.reply_to.reply_to_msg_id for r in reqs if r.reply_to] == [13, 14] + await db.close() + + run(go()) + + +def test_running_it_again_changes_nothing(tmp_path): + async def go(): + db, ch, chan, mig = await linked_setup(tmp_path) + await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + edits, requests = len(edit_requests(chan)), len(chan.requests) + again = await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + assert (again.copied_units, again.skipped_done) == (0, 8) + assert (again.final.relinked, again.final.pin_wanted, again.final.pinned) == (0, 0, 0) + assert len(edit_requests(chan)) == edits + assert not any(isinstance(r, functions.messages.UpdatePinnedMessageRequest) for r in chan.requests[requests:]) + await db.close() + + run(go()) + + +def test_a_channel_that_forbids_forwarding_gets_the_same_result(tmp_path): + async def go(): + chan = FakeChannelClient(build_linked()) + chan.restrict_forwards = True + db, ch, chan, mig = await linked_setup(tmp_path, chan) + res = await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + assert (res.failed, res.aborted, res.forwarded, res.rebuilt) == ([], None, 0, 8) + new = new_posts(chan) + assert (reply_of(new[14]), reply_of(new[15]), reply_of(new[16])) == (13, 14, 15) + assert chan.pinned_order == [15, 19] + assert res.final.relinked == 2 + await db.close() + + run(go()) + + +def test_a_post_waits_for_the_post_it_answers(tmp_path): + """The parent's copy fails (Telegram never shows its buttons): the child is not copied as a loose post.""" + + async def go(): + chan = FakeChannelClient( + { + 1: make_msg(1, "Parent", markup=markup([url_btn("Get", "https://t.me/goku?start=P")])), + 2: make_msg(2, "Child", reply_to=1), + 3: make_msg(3, "Other"), + } + ) + chan.drop_all_markup = True + db, ch, chan, mig = await linked_setup(tmp_path, chan) + res = await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + assert [n for _, n in res.failed] == ["ButtonsNotShown", "ReplyParentMissing"] + assert res.copied_units == 1 and res.final.relinked == 0 # only post 3 was copied + assert [m.message for m in new_posts(chan, 3).values()] == ["Other"] + chan.drop_all_markup = False # Telegram behaves again: "Try the rest again" + res2 = await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + assert (res2.copied_units, res2.failed) == (2, []) + new = new_posts(chan, 3) + parent, child = [m for m in new.values() if m.message == "Parent"][0], [m for m in new.values() if m.message == "Child"][0] + assert reply_of(child) == parent.id + await db.close() + + run(go()) + + +def test_a_reply_to_a_post_outside_a_trial_run_is_copied_without_the_reply(tmp_path): + async def go(): + chan = FakeChannelClient({1: make_msg(1, "Parent"), 2: make_msg(2, "Child", reply_to=1), 3: make_msg(3, "Gone parent", reply_to=99)}) + db, ch, chan, mig = await linked_setup(tmp_path, chan, first_id=2, partial=True) + res = await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + assert (res.copied_units, res.failed, res.replies, res.reply_dropped) == (2, [], 0, 2) + assert all(reply_of(m) is None for m in new_posts(chan, 3).values()) + await db.close() + + run(go()) + + +def test_media_that_cannot_be_rebuilt_is_copied_without_its_reply(tmp_path): + async def go(): + chan = FakeChannelClient({1: make_msg(1, "Parent"), 2: make_msg(2, "Odd", media=types.MessageMediaUnsupported(), reply_to=1)}) + db, ch, chan, mig = await linked_setup(tmp_path, chan) + res = await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + assert (res.copied_units, res.failed, res.reply_lost) == (2, [], 1) + assert forwarded_ids(chan) == [[1], [2]] + await db.close() + + run(go()) + + +def test_pinning_needs_a_right_the_bot_may_lack(tmp_path): + async def go(): + chan = FakeChannelClient(build_linked()) + chan.rights = dict(admin=True, post=True, edit=False, delete=True, invite=False, add_admins=False) + db, ch, chan, mig = await linked_setup(tmp_path, chan) + res = await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + assert (res.failed, res.aborted, res.copied_units) == ([], None, 8) # the copies are fine + assert (res.final.pin_wanted, res.final.pinned, res.final.pin_error) == (2, 0, "ChatAdminRequiredError") + assert chan.pinned_order == [] + await db.close() + + run(go()) + + +def test_links_in_copies_made_earlier_can_be_fixed_afterwards(tmp_path): + """A finished repost whose originals are gone: the copies still point at the old ids (the links in the copies are pointed at the new ids afterwards).""" + + async def go(): + db = await fresh_db(db_url_for(tmp_path)) + await db.save_channel(1, 5, "Test", CH, 99) + ch = await db.get_channel(1) + text = f"Part 1 https://t.me/{CH}/3 and https://t.me/{CH}/4 and https://t.me/{CH}/50" + chan = FakeChannelClient( + { + 11: make_msg(11, "one", out=True), + 12: make_msg(12, text, out=True, markup=markup([url_btn("Two", f"https://t.me/{CH}/1")])), + 13: make_msg(13, "three", out=True), + 14: make_msg(14, "four", out=True), + } + ) + ids = {1: 11, 2: 12, 3: 13, 4: 14} + await db.create_post(channel_id=1, message_id=12, status="sent", source="bot", text=text, entities=[], buttons=[[{"t": "Two", "u": f"https://t.me/{CH}/1"}]]) + dry = await relink_copies(chan, db, ch, ids, [11, 12, 13, 14], dry_run=True) + assert (dry.checked, dry.relinked, dry.links) == (4, 1, 3) and chan.edits == [] + res = await relink_copies(chan, db, ch, ids, [11, 12, 13, 14], delay=0, settle_pause=0) + assert (res.relinked, res.links, res.failed) == (1, 3, []) + assert chan.msgs[12].message == f"Part 1 https://t.me/{CH}/13 and https://t.me/{CH}/14 and https://t.me/{CH}/50" + assert button_url(chan.msgs[12].reply_markup.rows[0].buttons[0]) == f"https://t.me/{CH}/11" + saved = await db.find_by_message(1, 12) + assert saved.text == chan.msgs[12].message and saved.buttons[0][0]["u"].endswith("/11") + # nothing left to do the second time + again = await relink_copies(chan, db, ch, ids, [11, 12, 13, 14], delay=0, settle_pause=0) + assert (again.relinked, again.links) == (0, 0) + # a copy that was deleted in the meantime is reported, not an error + del chan.msgs[14] + gone = await relink_copies(chan, db, ch, ids, [11, 12, 13, 14], delay=0, settle_pause=0) + assert gone.missing == 1 + await db.close() + + run(go()) + + +def test_the_copies_of_every_repost_are_listed_oldest_first_and_undone_ones_left_out(tmp_path): + async def go(): + db, ch, chan, mig = await linked_setup(tmp_path) + await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + pairs = await db.migration_pairs(channel_id=1) + assert pairs == [(1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (7, 16), (8, 17), (9, 18), (10, 19)] + assert await db.migration_pairs(mid="m1") == pairs and await db.migration_pairs(mid="nope") == [] + await db.mark_migration_deleted("m1", 1, "new", [18, 19]) + assert await db.migration_pairs(channel_id=1) == pairs[:-2] + assert len(await db.migration_pairs(channel_id=1, alive_only=False)) == 9 + await db.close() + + run(go()) + + +# ------------------------------------------------------------------------------ as the owner sees it +def test_the_plan_and_the_result_message_mention_replies_links_and_pins(tmp_path): + from .harness import norm + from .test_repost_flow import make_app, pick + + async def go(): + app = await make_app(tmp_path, build_linked()) + await pick(app) + plan = norm(app.out.last_text) + assert "6 link(s) in 4 post(s) point at other posts of this channel" in plan + assert "3 post(s) answer another post" in plan and "2 pinned post(s)" in plan + assert "pinned state" not in plan # it is kept now + await app.press(app.out.callback_data("Start copying")) + done = norm(app.out.last_text) + assert "all posts copied in order" in done + assert "3 post(s) answer the copy of the post they answered" in done + assert "2 link(s) in 2 post(s) now point at the new copies" in done + assert "2 pinned post(s) are pinned again" in done + assert app.tg.pinned_order == [15, 19] + await app.db.close() + + asyncio.run(go()) + + +def test_a_missing_pin_right_is_explained_in_the_result(tmp_path): + from .harness import norm + from .test_repost_flow import make_app, pick + + async def go(): + app = await make_app(tmp_path, build_linked()) + app.tg.rights = dict(admin=True, post=True, edit=False, delete=True, invite=False, add_admins=False) + await pick(app) + await app.press(app.out.callback_data("Start copying")) + done = norm(app.out.last_text) + assert "2 copy/copies could not be pinned (ChatAdminRequiredError)" in done and "Edit messages of others" in done + assert "all posts copied in order" in done # the copy itself is complete + await app.db.close() + + asyncio.run(go()) + + +async def finished_repost(app, deleted_originals=True): + """A repost that is over: the copies (ids 11-13) still point at the old ids 1-3, the originals are gone.""" + text = f"Part one: https://t.me/{CH}/3 and https://t.me/{CH}/2" + app.tg.msgs = { + 11: make_msg(11, "one", out=True), + 12: make_msg(12, text, out=True, markup=markup([url_btn("Back", f"https://t.me/{CH}/1")])), + 13: make_msg(13, "three", out=True), + } + app.tg._top = 13 + await app.db.create_migration("m9", 1, old=None, new=None, include_typed=True, include_posts=False, first_id=1, last_id=3, partial=False, user_id=1) + rows = [{"old_id": o, "new_id": n, "post": dict(text="", entities=[], buttons=[], media_kind=None, media_file_id=None, link_preview=False)} for o, n in ((1, 11), (2, 12), (3, 13))] + await app.db.record_repost("m9", 1, rows, 1) + if deleted_originals: + await app.db.mark_migration_deleted("m9", 1, "old", [1, 2, 3]) + return text diff --git a/tests/test_restricted.py b/tests/test_restricted.py new file mode 100644 index 0000000000000000000000000000000000000000..cef46070bbf333b95fd9682f5efcaeef9813098a --- /dev/null +++ b/tests/test_restricted.py @@ -0,0 +1,393 @@ +"""What TELEGRAM does to a channel (a copyright strike ...) is not an admin's edit: My posts stay exactly as saved.""" +from telethon import types + +from app.restrictions import PLACEHOLDER_NOTE, is_placeholder_text, message_restriction, restriction_of +from app.sync_engine import MASS_NOTE, diff_post, split_mass_text, sync_channel, sync_ids + +from .fakes import markup, url_btn +from .harness import norm +from .test_sync import foreign, looked, old_msg, opts, run, world +from .test_syncer import dms, make_app, three as three_posts + +NOTICE = "This message couldn't be displayed on your device due to copyright infringement." +CHANNEL_NOTICE = "This channel is unavailable due to copyright infringement." # what Telegram says of a struck channel + + +def strike(m, text=NOTICE): + """Telegram holds a message back: its own restriction mark on it.""" + m.restriction_reason = [types.RestrictionReason(platform="all", reason="copyright", text=text)] + return m + + +def seven(): + return {i: old_msg(i, f"post number {i}", markup=markup([url_btn("Watch", f"https://t.me/a/{i}")])) for i in range(1, 8)} + + +# ================================================================================================ recognising it +def test_the_notice_telegram_shows_instead_of_a_post_is_recognised(): + for text in ( + NOTICE, + "This message couldn’t be displayed on your device due to copyright infringement", + " This message couldn't be displayed\non your device due to copyright infringement. ", + "This channel can't be displayed because it violated Telegram's Terms of Service.", + "This post isn't available in your country due to copyright.", + ): + assert is_placeholder_text(text), text + for text in ( + "", + None, + "Episode 12 is out now", + "This video is not available in HD", # says "not available" but nothing about a restriction + "Watch: this message couldn't be displayed on your device", # not the notice itself + "This message couldn't be displayed on your device due to copyright infringement. " + "x" * 300, # a long post + ): + assert not is_placeholder_text(text), text + + +def test_telegrams_own_marks_are_read_from_messages_and_channels(): + plain = old_msg(1, "hello") + assert restriction_of(plain) is None and message_restriction(plain) is None + held = strike(old_msg(2, "hello"), "Removed after a copyright complaint") + assert restriction_of(held) == "Removed after a copyright complaint" + assert message_restriction(held) == "Removed after a copyright complaint" + two = old_msg(3, "x") + two.restriction_reason = [ + types.RestrictionReason("ios", "sensitive", "Sensitive content"), + types.RestrictionReason("android", "sensitive", "Sensitive content"), # the same words twice: said once + types.RestrictionReason("all", "copyright", ""), # no words: its code is used + ] + assert restriction_of(two) == "Sensitive content; copyright" + nameless = old_msg(4, "x") + nameless.restriction_reason = [types.RestrictionReason("all", "terms", "")] + assert restriction_of(nameless) == "terms" + chan = types.Channel(id=1, title="t", photo=types.ChatPhotoEmpty(), date=None, restricted=True) + assert restriction_of(chan) == "restricted by Telegram" + assert restriction_of(types.Channel(id=1, title="t", photo=types.ChatPhotoEmpty(), date=None)) is None + + +def test_a_text_the_saved_post_already_has_is_the_owners_own_wording(): + m = old_msg(1, NOTICE) + assert message_restriction(m) == PLACEHOLDER_NOTE # an unknown message: it is the notice + assert message_restriction(m, "post number 1") == PLACEHOLDER_NOTE # the saved post said something else + assert message_restriction(m, NOTICE) is None # the saved post says exactly that: nothing changed + + +def test_many_posts_that_suddenly_show_one_text_are_held_back_but_few_are_not(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, {i: old_msg(i, f"post number {i}") for i in range(1, 8)}) + rows = {p.message_id: p for p in await db.sent_posts(1)} + + def edits_to(text, ids): + return [(rows[i], diff_post(rows[i], old_msg(i, text))) for i in ids] + + keep, held = split_mass_text(edits_to("Gone.", range(1, 6))) + assert keep == [] and len(held) == 5 + keep, held = split_mass_text(edits_to("Gone.", range(1, 5))) # four are below the line + assert len(keep) == 4 and held == [] + keep, held = split_mass_text(edits_to("", range(1, 8))) # all texts removed: a person can do that + assert len(keep) == 7 and held == [] + keep, held = split_mass_text(edits_to("Gone.", range(1, 6)) + edits_to("Other", [6, 7])) + assert [p.message_id for p, _ in keep] == [6, 7] and len(held) == 5 + await db.close() + + run(go()) + + +def test_edits_that_all_have_the_same_text_but_the_same_saved_text_are_a_real_edit(tmp_path): + async def go(): + msgs = {i: old_msg(i, "Join us") for i in range(1, 8)} # seven posts that said exactly the same + chan, db, ch = await world(tmp_path, msgs) + for m in msgs.values(): + m.message = "Join us now" + rep = await sync_channel(chan, db, ch, opts()) + assert len(rep.edited) == 7 and rep.restricted == [] + await db.close() + + run(go()) + + +# =============================================================================================== the whole channel +def test_a_channel_telegram_restricted_is_left_alone(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path, seven()) + before = await db.get_sync(1) + chan.restriction = NOTICE + del chan.msgs[2] + chan.msgs[1].message = "edited by an admin" + new = foreign(chan, "a new post") + chan._pts += 2 + rep = await sync_channel(chan, db, ch, opts()) + assert rep.restricted_channel == NOTICE and rep.error is None + assert (rep.deleted, rep.edited, rep.adopted, rep.restricted) == ([], [], [], []) + assert sorted(p.message_id for p in await db.sent_posts(1)) == list(range(1, 8)) # nothing removed + assert (await db.find_by_message(1, 1)).text == "post number 1" # nothing edited + assert await db.find_by_message(1, new.id) is None # nothing added + after = await db.get_sync(1) + assert (after.last_top, after.last_pts) == (before.last_top, before.last_pts) # the mark did not move + + chan.restriction = None # the strike is lifted: the next look is the normal one again + rep = await sync_channel(chan, db, ch, opts()) + assert rep.restricted_channel is None + assert (rep.deleted, rep.edited, rep.adopted) == ([2], [1], [new.id]) + await db.close() + + run(go()) + + +def test_the_first_look_at_a_restricted_channel_changes_nothing_either(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, seven()) + chan.restriction = NOTICE + for m in chan.msgs.values(): + m.message = NOTICE + rep = await sync_channel(chan, db, ch, opts()) + assert rep.restricted_channel == NOTICE and rep.first_look is False + assert await db.get_sync(1) is None + assert [p.text for p in await db.sent_posts(1)] == [f"post number {i}" for i in range(1, 8)] + await db.close() + + run(go()) + + +# ============================================================================================ a copyright strike +def test_every_post_turning_into_the_notice_changes_nothing_in_my_posts(tmp_path): + """The case that was asked about: Telegram swaps the text of EVERY post for its notice.""" + + async def go(): + chan, db, ch = await looked(tmp_path, seven()) + for m in chan.msgs.values(): + m.message, m.entities, m.reply_markup = NOTICE, None, None # what the strike leaves in the channel + chan._pts += 7 + rep = await sync_channel(chan, db, ch, opts()) + assert rep.edited == [] and rep.deleted == [] and rep.buttons_missing == [] + assert sorted(rep.restricted) == list(range(1, 8)) and rep.restricted_why == PLACEHOLDER_NOTE + for i, p in enumerate(await db.sent_posts(1), 1): + assert p.text == f"post number {i}" and p.buttons == [[{"t": "Watch", "u": f"https://t.me/a/{i}"}]] + await db.close() + + run(go()) + + +def test_posts_carrying_telegrams_restriction_mark_are_left_as_saved(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path, seven()) + for i in (2, 3): + strike(chan.msgs[i]) + chan.msgs[i].message = "(something else)" + chan.msgs[4].message = "a real edit by an admin" + chan._pts += 3 + rep = await sync_channel(chan, db, ch, opts()) + assert sorted(rep.restricted) == [2, 3] and rep.restricted_why == NOTICE + assert rep.edited == [4] # everything else is looked at as usual + assert (await db.find_by_message(1, 2)).text == "post number 2" + assert (await db.find_by_message(1, 4)).text == "a real edit by an admin" + await db.close() + + run(go()) + + +def test_a_post_that_is_really_gone_is_still_removed_while_others_are_held_back(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path, seven()) + strike(chan.msgs[2]) + chan.msgs[2].message = NOTICE + del chan.msgs[6] + chan._pts += 2 + rep = await sync_channel(chan, db, ch, opts()) + assert rep.deleted == [6] and rep.restricted == [2] + assert (await db.find_by_message(1, 2)).text == "post number 2" + await db.close() + + run(go()) + + +def test_a_notice_does_not_stop_a_normal_edit_of_another_post(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path, seven()) + chan.msgs[1].message = NOTICE + chan.msgs[5].message = "the admin fixed a typo" + rep = await sync_channel(chan, db, ch, opts()) + assert rep.restricted == [1] and rep.edited == [5] + await db.close() + + run(go()) + + +def test_five_posts_that_all_show_the_same_unknown_text_are_held_back(tmp_path): + """The notice in another language: it is not in any list, but nobody edits five posts into one text.""" + + async def go(): + chan, db, ch = await looked(tmp_path, seven()) + for i in range(1, 6): + chan.msgs[i].message = "Este mensaje no se puede mostrar en tu dispositivo." + rep = await sync_channel(chan, db, ch, opts()) + assert sorted(rep.restricted) == [1, 2, 3, 4, 5] and rep.edited == [] and rep.restricted_why == MASS_NOTE + assert (await db.find_by_message(1, 1)).text == "post number 1" + await db.close() + + run(go()) + + +def test_four_posts_with_the_same_new_text_are_ordinary_edits(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path, seven()) + for i in range(1, 5): + chan.msgs[i].message = "Moved to the new channel." + rep = await sync_channel(chan, db, ch, opts()) + assert sorted(rep.edited) == [1, 2, 3, 4] and rep.restricted == [] + await db.close() + + run(go()) + + +# ================================================================================================= new posts +def test_new_posts_that_telegram_holds_back_are_not_added(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path, three_posts_dict()) + a = foreign(chan, "a normal new post") + b = strike(foreign(chan, "hidden by Telegram")) + c = foreign(chan, NOTICE) + rep = await sync_channel(chan, db, ch, opts()) + assert rep.adopted == [a.id] and sorted(rep.restricted) == [b.id, c.id] + assert await db.find_by_message(1, b.id) is None and await db.find_by_message(1, c.id) is None + again = await sync_channel(chan, db, ch, opts()) # looked at once, not over and over + assert again.restricted == [] and again.adopted == [] + await db.close() + + run(go()) + + +def three_posts_dict(): + return {m.id: m for m in three_posts()} + + +# =============================================================================================== the live look +def test_the_live_look_leaves_a_restricted_post_alone(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path, seven()) + strike(chan.msgs[3]) + chan.msgs[3].message = NOTICE + chan.msgs[4].message = "a real edit" + rep = await sync_ids(chan, db, ch, [3, 4], opts()) + assert rep.restricted == [3] and rep.edited == [4] + assert (await db.find_by_message(1, 3)).text == "post number 3" + await db.close() + + run(go()) + + +def test_the_live_look_holds_back_a_burst_of_identical_texts(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path, seven()) + for i in range(1, 6): + chan.msgs[i].message = "Blocked." + rep = await sync_ids(chan, db, ch, [1, 2, 3, 4, 5], opts()) + assert sorted(rep.restricted) == [1, 2, 3, 4, 5] and rep.edited == [] + await db.close() + + run(go()) + + +def test_the_live_look_does_not_add_a_restricted_new_post(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path, seven()) + m = foreign(chan, NOTICE) + rep = await sync_ids(chan, db, ch, [m.id], opts(), adopt_ids=[m.id]) + assert rep.adopted == [] and rep.restricted == [m.id] + await db.close() + + run(go()) + + +# ============================================================================== what "everything looks deleted" means +def test_posts_really_deleted_by_an_admin_all_go_even_when_that_is_everything(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path, seven()) + chan.msgs.clear() + chan._pts += 7 # seven deletions are seven events + rep = await sync_channel(chan, db, ch, opts()) + assert sorted(rep.deleted) == list(range(1, 8)) and rep.anomaly is None + assert await db.sent_posts(1) == [] + await db.close() + + run(go()) + + +def test_posts_that_merely_vanish_from_view_are_not_removed_without_the_events(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path, seven()) + chan.msgs.clear() # nothing happened in the channel: the bot just sees nothing + rep = await sync_channel(chan, db, ch, opts()) + assert rep.deleted == [] and rep.anomaly and "All 7" in rep.anomaly + chan._pts += 3 # three events are not enough to explain seven missing posts + rep = await sync_channel(chan, db, ch, opts()) + assert rep.deleted == [] and rep.anomaly + assert len(await db.sent_posts(1)) == 7 + await db.close() + + run(go()) + + +# ================================================================================================= the owners +def test_sync_tells_what_it_left_alone_in_a_restricted_channel(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three_posts()) + await app.text("/sync") # the first look + app.tg.restriction = NOTICE + app.tg.msgs[2].message = NOTICE + await app.text("/sync") + text = norm(app.out.last_text) + assert "Telegram has restricted this channel" in text and "copyright infringement" in text + assert "stay exactly as they are" in text and "Everything matches" not in text + assert (await app.db.find_by_message(1, 2)).text == "second" + await app.db.close() + + run(go()) + + +def test_sync_tells_which_posts_it_held_back(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three_posts()) + await app.text("/sync") + strike(app.tg.msgs[2]) + app.tg.msgs[2].message = "(hidden)" + await app.text("/sync") + text = norm(app.out.last_text) + assert "1 post(s) are held back by Telegram" in text and "left exactly as saved" in text and "message 2" in text + assert "Everything matches" not in text + await app.db.close() + + run(go()) + + +def test_the_owners_are_told_about_a_restriction_once_not_every_check(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three_posts()) + sy = app.ctx.syncer + app.tg.restriction = NOTICE + await sy.run_all() + await sy.run_all() + await sy.run_all() + told = [t for t in dms(app) if "restricted" in t] + assert len(told) == 1 and "Anime Channel" in told[0] and "stay exactly as they are" in told[0] + sy._told.clear() # a week later + await sy.run_all() + assert len([t for t in dms(app) if "restricted" in t]) == 2 + await app.db.close() + + run(go()) + + +def test_the_owners_are_told_about_held_back_posts_too(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three_posts()) + sy = app.ctx.syncer + await sy.run_all() + strike(app.tg.msgs[3]) + await sy.run_all() + await sy.run_all() + told = [t for t in dms(app) if "holds back" in t] + assert len(told) == 1 and "1 post(s)" in told[0] + await app.db.close() + + run(go()) diff --git a/tests/test_restricted_source.py b/tests/test_restricted_source.py new file mode 100644 index 0000000000000000000000000000000000000000..5163ff4427abac960288021f8ede13527a4481d9 --- /dev/null +++ b/tests/test_restricted_source.py @@ -0,0 +1,418 @@ +"""A source channel that TELEGRAM restricts (a copyright strike: "This channel is unavailable due to copyright +infringement"): /shift copies it from what My posts saved - every post that has a saved copy, whatever Telegram hands out +of it now - and never copies Telegram's notice. Every copy is read back, so the report can say when Telegram itself hides +the NEW posts (a blocked file, a restricted destination) instead of the bot being blamed for copying a notice.""" +import asyncio + +from telethon import functions + +from app.repost_engine import CHECK_FIRST, RepostOptions, plan_repost, saved_lookup +from app.restrictions import message_restriction +from app.shift_engine import run_shift +from app.tgutil import button_url + +from .fakes import make_msg, rpc +from .harness import norm +from .test_held_back import ( + buttons, + held_app, + held_setup, + held_version, + forwarded_ids, + originals, + shown, + unreadable, +) +from .test_restricted import CHANNEL_NOTICE, NOTICE +from .test_shift import SRC + + +def run(coro): + return asyncio.run(coro) + + +COPIES = {11: "Welcome", 12: "Episode 2 is out", 13: "Caption with link", 14: "Fifth", 15: "Sixth"} # as My posts has them + + +def differ(src, ids): + """What Telegram hands out of these posts now is not what My posts saved (so the source of a copy can be told).""" + for i in ids: + old = src.msgs[i] + src.msgs[i] = make_msg(i, f"LIVE {i}", reply_to=old.reply_to.reply_to_msg_id if old.reply_to else None) + + +async def struck(tmp_path, *, no_row=(), live_differs=True, **kw): + """The source is restricted as a whole; its posts are handed out intact (and, by default, differently from what My + posts saved) and carry no mark of their own - the case that went wrong.""" + src, dst, db, dst_row, shift = await held_setup(tmp_path, held=kw.pop("held", ()), no_row=no_row, **kw) + src.restriction = CHANNEL_NOTICE + if live_differs: + differ(src, [i for i in (1, 2, 3, 5, 6) if i in src.msgs and not message_restriction(src.msgs[i])]) + return src, dst, db, dst_row, shift + + +# ======================================================================================== the copy loop +def test_a_struck_channel_is_copied_from_my_posts_even_when_telegram_still_hands_the_posts_out(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await struck(tmp_path) + dst.fail["ForwardMessagesRequest"] = rpc("MessageIdInvalidError") # what the real run met: nothing can be forwarded + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert (res.failed, res.aborted, res.held_back) == ([], None, []) + assert res.from_saved == 5 and res.copied_units == 5 and res.live_restricted == 0 and res.held_why == CHANNEL_NOTICE + assert shown(dst) == COPIES # My posts' texts - not "LIVE n" + assert forwarded_ids(dst) == [] # Telegram is not even asked to copy anything out of the struck channel + # text, formatting, buttons, media and links come from My posts + assert [(e.offset, e.length) for e in dst.msgs[12].entities] == [(0, 9)] + btn = dst.msgs[12].reply_markup.rows[0].buttons[0] + assert (btn.text, button_url(btn)) == ("Download", "https://t.me/goku?start=AAA") + assert dst.msgs[13].media.photo.id == 31 + assert dst.msgs[13].entities[0].url == "https://t.me/dstch/14" # the link to post 5 follows its copy + assert dst.msgs[14].reply_to.reply_to_msg_id == 12 # an answer answers the copy + # My posts knows the copies as they are, and the source was only read + assert (await db.find_by_message(2, 12)).text == "Episode 2 is out" + assert not [r for r in src.requests if type(r).__name__.startswith(("Edit", "Delete", "Send", "Forward"))] + await db.close() + + run(go()) + + +def test_a_struck_channel_is_copied_from_my_posts_when_telegram_hands_out_only_the_notice(tmp_path): + """The same channel when the apps show the notice: the posts carry Telegram's mark, or only its words as the text.""" + + async def go(): + for flagged in (True, False): + src, dst, db, dst_row, shift = await struck(tmp_path / str(flagged), held=(1, 2, 3, 5, 6), flagged=flagged) + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert (res.failed, res.aborted, res.held_back) == ([], None, []) + assert res.from_saved == 5 and shown(dst) == COPIES + assert not any(NOTICE in (m.message or "") for m in dst.msgs.values()) + await db.close() + + run(go()) + + +def test_a_post_of_a_struck_channel_without_a_saved_copy_is_copied_as_telegram_hands_it_out(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await struck(tmp_path, no_row=(3, 5)) + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert (res.failed, res.aborted, res.held_back) == ([], None, []) + assert res.from_saved == 3 and res.live_restricted == 2 # 1 2 6 from My posts; 3 and 5 as they are now + assert shown(dst) == {11: "Welcome", 12: "Episode 2 is out", 13: "LIVE 3", 14: "LIVE 5", 15: "Sixth"} + assert forwarded_ids(dst) == [] # not even those: a restricted post is never copied by Telegram itself + await db.close() + + run(go()) + + +def test_a_post_of_a_struck_channel_with_only_the_notice_and_no_saved_copy_is_skipped(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await struck(tmp_path, held=(3,), no_row=(3,), flagged=False) + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert res.held_back == [3] and res.from_saved == 4 and res.failed == [] + assert shown(dst) == {11: "Welcome", 12: "Episode 2 is out", 13: "Fifth", 14: "Sixth"} + assert not any(NOTICE in (m.message or "") for m in dst.msgs.values()) + await db.close() + + run(go()) + + +def test_a_saved_copy_that_is_telegrams_notice_is_never_posted(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await struck(tmp_path, no_row=(2, 3)) + for mid in (2, 3): # what an older version saved when it synced the struck channel + await db.create_post( + channel_id=1, message_id=mid, status="sent", source="adopted", created_by=1, link_preview=False, + text=NOTICE, entities=[], buttons=[], media_kind=None, media_file_id=None, + ) + src.msgs[3] = held_version(originals()[3], flagged=False) # post 3: the notice from Telegram as well + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + # post 2: the saved copy is useless but Telegram hands the post out; post 3: nothing but notices + assert res.held_back == [3] and res.live_restricted == 1 and res.from_saved == 3 and res.failed == [] + assert shown(dst) == {11: "Welcome", 12: "LIVE 2", 13: "Fifth", 14: "Sixth"} + assert not any(NOTICE in (m.message or "") for m in dst.msgs.values()) + await db.close() + + run(go()) + + +def test_a_source_that_cannot_be_read_never_gets_a_saved_notice_posted(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await held_setup(tmp_path, held=(), no_row=(2,)) + await db.create_post( + channel_id=1, message_id=2, status="sent", source="adopted", created_by=1, link_preview=False, + text=NOTICE, entities=[], buttons=[], media_kind=None, media_file_id=None, + ) + unreadable(src) + await db.set_mark("s1", "fromdb") + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert res.copied_units == 4 and res.failed == [] + assert shown(dst) == {11: "Welcome", 12: "Caption with link", 13: "Fifth", 14: "Sixth"} + await db.close() + + run(go()) + + +def test_a_channel_nothing_restricts_is_copied_as_before(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await held_setup(tmp_path, held=()) + differ(src, (1, 2, 3, 5, 6)) + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert res.from_saved == 0 and res.live_restricted == 0 and res.held_why is None and res.held_back == [] + assert shown(dst) == {11: "LIVE 1", 12: "LIVE 2", 13: "LIVE 3", 14: "LIVE 5", 15: "LIVE 6"} # what the channel says + await db.close() + + run(go()) + + +def test_lifting_the_strike_makes_the_next_run_an_ordinary_one(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await struck(tmp_path, last=3) + stopper = {"n": 0} + + async def prog(r): + stopper["n"] = r.copied_units + + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0, progress=prog, should_stop=lambda: stopper["n"] >= 1) + assert res.stopped and shown(dst) == {11: "Welcome"} # post 1, from My posts + src.restriction = None # the strike is lifted: the channel says what it says now + again = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert again.held_why is None and again.from_saved == 0 + assert shown(dst) == {11: "Welcome", 12: "LIVE 2", 13: "LIVE 3"} + await db.close() + + run(go()) + + +# ================================================================================================ the plan +def test_the_plan_counts_a_struck_channel_as_copied_from_my_posts(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await struck(tmp_path, no_row=(5,)) + lookup = saved_lookup(db, 1) + plan = await plan_repost(src, SRC, RepostOptions(), saved=lookup, use_saved=True) + assert plan.channel_restricted == CHANNEL_NOTICE and plan.held_why == CHANNEL_NOTICE + # 1 2 3 6 have a saved copy; 5 has none but Telegram still hands it out + assert (plan.units, plan.held_saved, plan.live_restricted, plan.held_skipped, plan.service) == (5, 4, 1, 0, 1) + assert plan.media == 1 # post 3 is counted from its saved copy, not from what Telegram hands out now + # /repost copies the posts of the channel itself, post by post: a struck channel changes nothing about that + plain = await plan_repost(src, SRC, RepostOptions(), saved=lookup) + assert (plain.units, plain.held_saved, plain.live_restricted, plain.held_skipped) == (5, 0, 0, 0) + assert plain.channel_restricted == CHANNEL_NOTICE + await db.close() + + run(go()) + + +# ========================================================================================= the read-back +def test_every_copy_of_a_struck_channel_is_read_back_and_what_telegram_hides_is_counted(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await struck(tmp_path) + dst.restrict_new = lambda m: CHANNEL_NOTICE if m.media is not None else None # the file of post 3 is blocked + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert res.copied_units == 5 and res.failed == [] and res.held_back == [] + assert res.checked == 5 # every copy of a restricted source + assert res.hidden == [(3, True)] and res.hidden_why == CHANNEL_NOTICE and res.dst_restricted is None + # the bot posted the saved text; the notice is Telegram's mark on the new post + assert dst.msgs[13].message == "Caption with link" and message_restriction(dst.msgs[13]) == CHANNEL_NOTICE + assert not any(NOTICE in (m.message or "") for m in dst.msgs.values()) + await db.close() + + run(go()) + + +def test_a_destination_that_is_restricted_itself_is_named(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await struck(tmp_path) + dst.restriction = CHANNEL_NOTICE + dst.restrict_new = lambda m: CHANNEL_NOTICE + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert [i for i, _ in res.hidden] == [1, 2, 3] and res.dst_restricted == CHANNEL_NOTICE # it stopped after 3 + assert res.hidden_stop + await db.close() + + run(go()) + + +def test_a_normal_channel_is_only_sampled_when_the_copies_are_read_back(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await held_setup(tmp_path, held=()) + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert res.copied_units == 5 and res.checked == CHECK_FIRST and res.hidden == [] and res.dst_restricted is None + assert not [r for r in dst.requests if isinstance(r, functions.channels.GetFullChannelRequest)] # nothing to ask + await db.close() + + run(go()) + + +def test_a_read_back_that_fails_does_not_fail_the_copy(tmp_path): + async def go(): + for error in (rpc("ChannelPrivateError"), ConnectionError("the network dropped")): # Telegram's refusal, or not + src, dst, db, dst_row, shift = await struck(tmp_path / type(error).__name__, last=1) # post 1: no buttons to read back + dst.fail["GetMessagesRequest"] = error + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert res.copied_units == 1 and res.failed == [] and res.checked == 0 and res.hidden == [] + assert shown(dst) == {11: "Welcome"} + await db.close() + + run(go()) + + +def test_a_source_that_cannot_be_asked_about_its_restriction_is_copied_as_an_unrestricted_one(tmp_path): + async def go(): + for error in (rpc("ChannelPrivateError"), ConnectionError("the network dropped")): + src, dst, db, dst_row, shift = await held_setup(tmp_path / type(error).__name__, held=()) + src.fail["GetFullChannelRequest"] = error + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert res.copied_units == 5 and res.failed == [] and res.held_why is None and res.from_saved == 0 + await db.close() + + run(go()) + + +# ================================================================================================ the owner's view +def test_the_plan_and_the_result_for_a_struck_channel_read_as_they_should(tmp_path): + async def go(): + app, dst = await held_app(tmp_path, held=()) + app.tg.restriction = CHANNEL_NOTICE + dst.fail["ForwardMessagesRequest"] = rpc("MessageIdInvalidError") + await app.text("/shift @srcch @dstch") + plan = norm(app.out.last_text) + assert "Telegram restricts Anime Source itself" in plan + assert "5 post(s) of Anime Source are restricted by Telegram" in plan and "copied from what My posts saved" in plan + assert "5 posts" in plan and "The new posts are read back" in plan + + await app.press(app.out.callback_data("Start copying")) + done = norm(app.out.last_text) + assert "5 post(s) are restricted by Telegram" in done and "copied from what My posts saved of them" in done + assert "5 message(s) copied" in done and "hides" not in done + assert [m.message for i, m in sorted(dst.msgs.items()) if i > 10] == list(COPIES.values()) + await app.db.close() + + run(go()) + + +def test_the_report_says_when_telegram_itself_hides_the_new_posts(tmp_path): + async def go(): + app, dst = await held_app(tmp_path, held=()) + app.tg.restriction = CHANNEL_NOTICE + dst.restrict_new = lambda m: CHANNEL_NOTICE if m.media is not None else None + await app.text("/shift @srcch @dstch") + await app.press(app.out.callback_data("Start copying")) + done = norm(app.out.last_text) + assert "Telegram itself hides 1 of the 5 new post(s) I read back" in done + assert "carry its restriction mark" in done and "never posts one" in done + assert "1 post(s) of these carry a file" in done and "--no-media" in done + assert "The saved posts in My posts are intact" in done + assert "5 message(s) copied" in done # the copies exist: Undo removes them + assert any("Undo" in t for row in app.out.last_buttons() for t in row) + await app.db.close() + + run(go()) + + +def test_the_report_names_a_restricted_destination(tmp_path): + async def go(): + app, dst = await held_app(tmp_path, held=()) + app.tg.restriction = CHANNEL_NOTICE + dst.restriction = CHANNEL_NOTICE + dst.restrict_new = lambda m: CHANNEL_NOTICE + await app.text("/shift @srcch @dstch") + await app.press(app.out.callback_data("Start copying")) + done = norm(app.out.last_text) + assert "Telegram itself hides 3 of the 3 new post(s) I read back" in done + assert "Telegram restricts the destination channel itself" in done + await app.db.close() + + run(go()) + + +def test_a_repost_plan_for_a_struck_channel_points_at_shift(tmp_path): + from .test_repost_flow import make_app + + async def go(): + app = await make_app(tmp_path, msgs={1: make_msg(1, "First post"), 2: make_msg(2, "Second post")}) + app.tg.restriction = CHANNEL_NOTICE + await app.text("/repost --no-typed") + await app.press(app.out.callback_data("Test")) + plan = norm(app.out.last_text) + assert "Telegram restricts Test itself" in plan and "use /shift" in plan + assert "2 posts" in plan and "no saved copy" not in plan # /repost does not look at My posts + await app.db.close() + + run(go()) + + +# ====================================================================== stopping when Telegram hides the copies +def test_a_shift_stops_by_itself_when_telegram_hides_every_new_copy(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await struck(tmp_path) + dst.restrict_new = lambda m: CHANNEL_NOTICE # every new post is hidden + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert res.stopped and res.hidden_stop and res.copied_units == 3 # not 5: it did not go on + assert [i for i, _ in res.hidden] == [1, 2, 3] and res.checked == 3 + assert shown(dst) == {11: "Welcome", 12: "Episode 2 is out", 13: "Caption with link"} + assert res.phase == "copy" and res.final is None # the finishing touches wait for the rest + await db.close() + + run(go()) + + +def test_the_owner_can_go_on_anyway_and_it_does_not_stop_again(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await struck(tmp_path) + dst.restrict_new = lambda m: CHANNEL_NOTICE + first = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert first.hidden_stop and first.copied_units == 3 + await db.set_mark("s1", "hiddenok") # what pressing Continue anyway rests on + again = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert not again.stopped and not again.hidden_stop and again.copied_units == 2 and again.skipped_done == 3 + assert shown(dst) == COPIES + await db.close() + + run(go()) + + +def test_a_shift_does_not_stop_when_only_some_copies_are_hidden(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await struck(tmp_path) + dst.restrict_new = lambda m: CHANNEL_NOTICE if m.media is not None else None # only the photo + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert not res.stopped and res.copied_units == 5 and res.hidden == [(3, True)] + await db.close() + + run(go()) + + +def test_a_shift_with_fewer_copies_than_the_threshold_is_not_stopped(tmp_path): + async def go(): + src, dst, db, dst_row, shift = await struck(tmp_path, last=2) + dst.restrict_new = lambda m: CHANNEL_NOTICE + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert not res.stopped and res.copied_units == 2 and len(res.hidden) == 2 # reported, nothing left to stop + await db.close() + + run(go()) + + +def test_the_stopped_shift_explains_itself_and_continue_anyway_goes_on(tmp_path): + async def go(): + app, dst = await held_app(tmp_path, held=()) + app.tg.restriction = CHANNEL_NOTICE + dst.restrict_new = lambda m: CHANNEL_NOTICE + await app.text("/shift @srcch @dstch") + await app.press(app.out.callback_data("Start copying")) + done = norm(app.out.last_text) + assert "stopped" in done and "3 message(s) copied so far" in done + assert "I stopped after 3 post(s)" in done and "Telegram hides every new copy I read back" in done + assert "Telegram itself hides 3 of the 3 new post(s) I read back" in done + assert any("Continue" in t for t in buttons(app)) and any("Undo" in t for t in buttons(app)) + sid = app.out.callback_data("Undo").split(":")[1] + assert await app.db.marks_of(sid) == {"hiddenok"} + assert len([i for i in dst.msgs if i > 10]) == 3 # three posts, not the whole channel + + await app.press(app.out.callback_data("Continue")) + done = norm(app.out.last_text) + assert "5 message(s) copied" in done and "I stopped" not in done # it went on, as the owner chose + assert len([i for i in dst.msgs if i > 10]) == 5 + await app.db.close() + + run(go()) diff --git a/tests/test_rich.py b/tests/test_rich.py new file mode 100644 index 0000000000000000000000000000000000000000..bd5d2205dcb5f248cbdd6e678ba2471e07aec242 --- /dev/null +++ b/tests/test_rich.py @@ -0,0 +1,483 @@ +"""Rich messages (headings, lists, tables,
, math, maps, pictures, buttons ...): what is recognised, how a rich message is +kept in a post, what is sent to Telegram for it and how one that is sent to the bot is read.""" +import asyncio +from types import SimpleNamespace + +import pytest +from telethon import errors, functions, types + +from app.richmsg import ( + RICH_HELP, + RICH_HELP_HTML, + MAX_SOURCE, + Rich, + RichError, + blank_references, + check, + detect, + entry, + fingerprint, + input_users, + is_rich, + is_rich_message, + mention_ids, + plain_of, + plain_of_message, + read_typed, + real_entities, + received, + rich_from_received, + rich_of, + send_rich, + sent_message, + to_input, + with_rich, +) +from app.tgutil import de_entities, edit_raw + +from .fakes import photo_media, rpc, video_media + +T = types.TextPlain + + +def blocks(word="Hello"): + return [types.PageBlockHeading1(T("Title")), types.PageBlockParagraph(types.TextBold(T(word)))] + + +def rich_msg(bl=None, *, photos=None, documents=None, rtl=None, part=None): + """A rich message as Telegram hands it to the bot.""" + return types.RichMessage(blocks=bl or blocks(), photos=photos or [], documents=documents or [], rtl=rtl, part=part) + + +def same(a, b): + """The same TL objects (they have no usable ==).""" + return [bytes(x) for x in a] == [bytes(x) for x in b] + + +# ============================================================================================ what is a rich message +HTML_RICH = [ + "

Title

", + "

Small

", + "

one

two

", + "
  • a
  • b
", + "
  1. a
", + "
a
", + "
Moretext
", + "", + "E = mc^2", + "", + "
", + "
fine print
", + "", + "
c
", + "", + "Open", + "text with marked words", + "H2O and x2", + " done", + "soon", + "go", + "back to the top", + "note", +] +MARKDOWN_RICH = [ + "# Title", + "text\n\n### Sub heading", + "###### Smallest", + "- [ ] todo", + "1. [x] done", + "| a | b |\n|---|---|\n| 1 | 2 |", + "a | b\n:-:|--:\n1 | 2", + "$$E = mc^2$$", + "a note[^1]\n\n[^1]: the note", + "some ==marked== text", + "![](https://x.org/a.jpg)", + "![](https://x.org/a.mp4 \"caption\")", + "see ![22:45 tomorrow](tg://time?unix=1647531900&format=wDT)", +] +NOT_RICH = [ + "Episode 12 is out", + "#anime #naruto", + "#1 hit", # a hashtag with no space after the # is not a heading + "Price: $5 and $6", + "a == b", + "1 == 1 and 2 == 2", + "I <3 this", + "- one\n- two", + "* a\n* b", + "---", + "1) first\n2) second", + "**bold** and __under__ and ~~strike~~ and ||spoiler|| and `code`", + "bold it u s x c s", + "
quote
and
block
", + "
<h1> stays text
", + "`

` is a tag", + "```\n# not a heading\n```", + "~~~\n| a | b |\n|---|---|\n~~~", + "a | b | c", + "5 > 3 and 2 < 4", + "@channel_name look at https://example.com/a#section", + "[watch](https://t.me/x) and ![smile](tg://emoji?id=1)", + "", + " ", +] + + +@pytest.mark.parametrize("text", HTML_RICH) +def test_html_with_rich_blocks_is_a_rich_message(text): + assert detect(text) == "html" + assert read_typed(text) == Rich("html", text) + + +@pytest.mark.parametrize("text", MARKDOWN_RICH) +def test_markdown_with_rich_blocks_is_a_rich_message(text): + assert detect(text) == "markdown" + assert read_typed(text) == Rich("markdown", text) + + +@pytest.mark.parametrize("text", NOT_RICH) +def test_ordinary_text_is_not_turned_into_a_rich_message(text): + assert detect(text) is None + assert read_typed(text) is None + + +def test_html_wins_when_the_text_starts_with_a_tag_and_markdown_otherwise(): + assert detect("

Title

\n\n- [ ] not a task here") == "html" + assert detect("# Title\n\nsome marked html inside") == "markdown" + assert detect("intro\n

Sub

") == "html" + + +def test_the_rich_marker_makes_any_text_a_rich_message(): + assert read_typed("\nhello **x**") == Rich("markdown", "hello **x**") + assert read_typed("\nx and y") == Rich("html", "x and y") + r = read_typed("\nhello #tag @name") + assert (r.fmt, r.source, r.rtl, r.noautolink) == ("markdown", "hello #tag @name", True, True) + r = read_typed(" \r\nمرحبا") # spaces, any case and a Windows line end are fine + assert (r.source, r.rtl, r.noautolink) == ("مرحبا", True, False) + assert read_typed("\n# Title") == Rich("markdown", "# Title", noautolink=True) + # the marker is a line of its own, at the start + assert read_typed(" hello") is None + assert read_typed("hello \nx") is None + assert read_typed("hello\n\nx") is None + assert read_typed("") is None and read_typed("\n \n") is None + + +def test_what_is_typed_is_handed_over_exactly(): + src = "# Title \n\n indented\n\n| a | b |\n|---|---|\n| 1 | 2 |" + assert read_typed("\n" + src + "\n\n").source == src.strip() + assert read_typed(src).source == src + assert read_typed("\n" + src).source == src + + +def test_code_is_not_markup(): + assert detect("```python\n# comment\nprint('

')\n```") is None + assert detect("use `# Heading` for a heading and

in HTML") is None + assert detect("```\n- [ ] x\n```\n# Real heading") == "markdown" + + +# ================================================================================================= keeping a rich message +def test_a_rich_message_is_one_entry_among_the_entities_of_a_post(): + r = Rich("html", "

x

", rtl=True, noautolink=True, fp="abc") + e = entry(r) + assert e == {"k": "rich", "f": "html", "s": "

x

", "r": 1, "n": 1, "p": "abc"} + assert entry(Rich("markdown", "# x")) == {"k": "rich", "f": "markdown", "s": "# x"} + post = SimpleNamespace(entities=[{"k": "bold", "o": 0, "l": 1}, e]) + assert rich_of(post) == r and is_rich(post) + assert real_entities(post.entities) == [{"k": "bold", "o": 0, "l": 1}] + assert real_entities(None) == [] + for bad in ({"k": "rich", "f": "pdf", "s": "x"}, {"k": "rich", "f": "html", "s": ""}, {"k": "bold", "o": 0, "l": 1}, "x"): + assert rich_of(SimpleNamespace(entities=[bad])) is None + assert rich_of(SimpleNamespace(entities=None)) is None and rich_of(SimpleNamespace()) is None + assert not is_rich(SimpleNamespace(entities=[])) + + +def test_the_entry_is_not_formatting(): + assert de_entities([entry(Rich("markdown", "# x"))]) == [] + assert de_entities([entry(Rich("html", "x")), {"k": "bold", "o": 0, "l": 2}]) == [types.MessageEntityBold(0, 2)] + + +# ============================================================================================ what is sent to Telegram +def test_typed_text_goes_to_telegram_as_html_or_markdown_for_it_to_read(): + i = to_input(Rich("html", "

x

", rtl=True)) + assert isinstance(i, types.InputRichMessageHTML) and i.html == "

x

" and i.rtl is True and i.noautolink is None + i = to_input(Rich("markdown", "# x", noautolink=True)) + assert isinstance(i, types.InputRichMessageMarkdown) and i.markdown == "# x" and i.noautolink is True and i.rtl is None + bytes(to_input(Rich("markdown", "# x"))) # serialises + + +def test_a_rich_message_that_was_received_is_sent_again_block_for_block(): + rm = rich_msg(photos=[photo_media(5).photo], documents=[video_media(81).document], rtl=True) + r = rich_from_received(rm) + assert (r.fmt, r.rtl, r.fp) == ("blocks", True, fingerprint(rm)) + inp = to_input(r) + assert isinstance(inp, types.InputRichMessage) and inp.rtl is True + assert same(inp.blocks, rm.blocks) + assert [(p.id, p.access_hash, p.file_reference) for p in inp.photos] == [(5, 35, b"ref5")] + assert [(d.id, d.access_hash, d.file_reference) for d in inp.documents] == [(81, 81 * 7, b"fr81")] + bytes(inp) + plain = to_input(rich_from_received(rich_msg())) + assert plain.photos is None and plain.documents is None and plain.users is None and not plain.rtl + + +def test_file_references_can_be_left_out(): + inp = to_input(rich_from_received(rich_msg(photos=[photo_media(5).photo], documents=[video_media(81).document]))) + blank = blank_references(inp) + assert blank.photos[0].file_reference == b"" and (blank.photos[0].id, blank.photos[0].access_hash) == (5, 35) + assert blank.documents[0].file_reference == b"" and blank.documents[0].id == 81 + assert inp.photos[0].file_reference == b"ref5" # the original is untouched + html = types.InputRichMessageHTML(html="x") + assert blank_references(html) is html + + +def test_a_stale_file_reference_is_retried_without_it(): + async def run(): + r = rich_from_received(rich_msg(photos=[photo_media(5).photo])) + seen = [] + + async def call(inp): + seen.append(inp) + if len(seen) == 1: + raise rpc("FileReferenceExpiredError") + return "ok" + + assert await with_rich(r, call) == "ok" + assert seen[0].photos[0].file_reference == b"ref5" and seen[1].photos[0].file_reference == b"" + + async def always(inp): + raise rpc("FileReferenceExpiredError") + + with pytest.raises(errors.RPCError): + await with_rich(r, always) # the second try failed as well: that error is shown + with pytest.raises(errors.RPCError): + await with_rich(Rich("html", "

x

"), always) # typed text has no references to blame + + async def other(inp): + raise rpc("MessageEmptyError") + + with pytest.raises(errors.MessageEmptyError): + await with_rich(r, other) + + asyncio.run(run()) + + +def test_send_rich_makes_one_raw_request_and_finds_the_message_it_created(): + async def run(): + sent = [] + + async def client(req): + sent.append(req) + return types.Updates( + updates=[types.UpdateNewChannelMessage(message=types.Message(id=41, peer_id=types.PeerChannel(1), date=None, message=""), pts=1, pts_count=1)], + users=[], chats=[], date=None, seq=0, + ) + + markup = types.ReplyInlineMarkup([]) + m = await send_rich(client, types.InputPeerChannel(1, 5), Rich("markdown", "# x"), markup=markup, silent=True) + assert m.id == 41 + (req,) = sent + assert isinstance(req, functions.messages.SendMessageRequest) + assert req.message == "" and req.reply_markup is markup and req.silent is True + assert isinstance(req.rich_message, types.InputRichMessageMarkdown) and req.rich_message.markdown == "# x" + bytes(req) + + asyncio.run(run()) + + +def test_the_message_a_send_created_is_found_in_every_answer_telegram_gives(): + short = types.UpdateShortSentMessage(id=7, pts=1, pts_count=1, date=None, out=True) + assert sent_message(short).id == 7 + new = types.UpdateNewMessage(message=types.Message(id=8, peer_id=types.PeerUser(1), date=None, message=""), pts=1, pts_count=1) + assert sent_message(types.Updates(updates=[new], users=[], chats=[], date=None, seq=0)).id == 8 + with pytest.raises(RuntimeError): + sent_message(types.Updates(updates=[], users=[], chats=[], date=None, seq=0)) + + +def test_edit_raw_makes_the_message_that_rich_message(): + async def run(): + sent = [] + + async def client(req): + sent.append(req) + + inp = types.InputRichMessageMarkdown(markdown="# x") + peer = types.InputPeerChannel(1, 5) + await edit_raw(client, peer, 9, rich_message=inp, markup=None, text="ignored", entities=[types.MessageEntityBold(0, 1)], preview=True) + (req,) = sent + assert req.rich_message is inp and req.message is None and not req.entities and not req.no_webpage and req.reply_markup is None + bytes(req) + sent.clear() + await edit_raw(client, peer, 9, text="plain", entities=[], markup=None) + assert sent[0].rich_message is None and sent[0].message == "plain" + + asyncio.run(run()) + + +def test_a_rich_message_longer_than_telegram_allows_is_refused(): + check(Rich("html", "x" * MAX_SOURCE)) + check(Rich("blocks", "x" * (MAX_SOURCE * 2))) # received blocks are Telegram's own: nothing to count here + with pytest.raises(RichError) as exc: + check(Rich("markdown", "x" * (MAX_SOURCE + 1))) + assert "32768" in str(exc.value) + + +# ===================================================================================== a rich message sent to the bot +def test_the_fingerprint_follows_what_the_message_shows(): + a, b = rich_msg(blocks("x")), rich_msg(blocks("x"), photos=[photo_media(5).photo]) + assert fingerprint(a) == fingerprint(b) # the pictures' file references change from fetch to fetch + assert fingerprint(a) != fingerprint(rich_msg(blocks("y"))) + assert fingerprint(a) != fingerprint(rich_msg(blocks("x"), rtl=True)) + assert len(fingerprint(a)) == 20 + + +def test_is_rich_message(): + assert is_rich_message(SimpleNamespace(rich_message=rich_msg())) + assert not is_rich_message(SimpleNamespace(rich_message=None)) and not is_rich_message(SimpleNamespace()) + + +def test_people_mentioned_by_link_are_found_and_looked_up(): + async def run(): + bl = [types.PageBlockParagraph(types.TextConcat([T("hi "), types.TextMentionName(T("Bob"), 42), types.TextMentionName(T("Bob"), 42), types.TextMentionName(T("Al"), 43)]))] + assert mention_ids(bl) == [42, 43] + assert mention_ids(blocks()) == [] and mention_ids(None) == [] + + class Client: + async def get_input_entity(self, uid): + if uid == 42: + return types.InputPeerUser(42, 777) + raise ValueError("unknown") + + users = await input_users(Client(), [42, 43]) + assert [(u.user_id, u.access_hash) for u in users] == [(42, 777)] # the one that can't be found is left out + r = rich_from_received(rich_msg(bl), users) + assert [u.user_id for u in to_input(r).users] == [42] + + asyncio.run(run()) + + +class Event: + """The message event of a rich message that arrived (what `received` reads).""" + + def __init__(self, rm, mid=77): + self.message = SimpleNamespace(rich_message=rm, id=mid) + + async def get_input_chat(self): + return types.InputPeerUser(1, 0) + + +class Client: + def __init__(self, answer=None, error=None): + self.answer, self.error, self.requests = answer, error, [] + + async def __call__(self, req): + self.requests.append(req) + if self.error: + raise self.error + return self.answer + + async def get_input_entity(self, uid): + raise ValueError(uid) + + +def test_a_whole_rich_message_is_read_as_it_arrived(): + async def run(): + rm = rich_msg(photos=[photo_media(5).photo]) + client = Client() + r = await received(client, Event(rm)) + assert client.requests == [] # nothing more to ask + assert (r.fmt, r.fp) == ("blocks", fingerprint(rm)) and plain_of(r) == "Title\nHello" + assert await received(client, Event(None)) is None # an ordinary message + + asyncio.run(run()) + + +def test_a_rich_message_that_arrives_in_parts_is_fetched_whole(): + async def run(): + part = rich_msg([types.PageBlockParagraph(T("first"))], part=True) + client = Client(answer=rich_msg(blocks("whole"))) + r = await received(client, Event(part, mid=9)) + (req,) = client.requests + assert isinstance(req, functions.messages.GetRichMessageRequest) and req.id == 9 + assert plain_of(r) == "Title\nwhole" + + asyncio.run(run()) + + +def test_a_rich_message_that_cannot_be_had_whole_is_refused_in_plain_words(): + async def run(): + part = rich_msg([types.PageBlockParagraph(T("first"))], part=True) + for client in ( + Client(answer=rich_msg(blocks(), part=True)), # still only a part + Client(error=rpc("MessageIdInvalidError")), # Telegram refuses to say more + Client(answer=None), # nothing came back + ): + with pytest.raises(RichError) as exc: + await received(client, Event(part)) + assert "part of that rich message" in str(exc.value) + with pytest.raises(RichError) as exc: + await received(Client(), Event(types.RichMessage(blocks=[], photos=[], documents=[]))) + assert "no content" in str(exc.value) + + asyncio.run(run()) + + +# ==================================================================================== the plain text of a rich message +def test_the_plain_text_of_typed_html(): + html = ( + "

Schedule

Every Monday

  • one
  • two
" + "
DayShow
MonNaruto
" + "
Morehidden text
quoteme
" + "E = mc^2" + ) + assert plain_of(Rich("html", html)) == ( + "Schedule\nEvery Monday\n• one\n• ☑ two\nDay | Show\nMon | Naruto\nMore\nhidden text\nquote\nme\nE = mc^2" + ) + assert plain_of(Rich("html", "line one
line two

after a gap & more")) == "line one\nline two\n\nafter a gap & more" + assert plain_of(Rich("html", "ab")) == "ab" + + +def test_the_plain_text_of_typed_markdown(): + md = ( + "# Title\n\nSome **bold**, *it* and ==mark== [link](https://t.me/x)\n\n- [x] done\n- [ ] todo\n- item\n\n" + "| a | b |\n|:--|--:|\n| 1 | 2 |\n\n> quoted\n\n```python\nprint(1)\n```\n\n$$E = mc^2$$\n\n" + "note[^1]\n\n[^1]: the note\n\n![](https://x.org/a.jpg \"a caption\")\n\n---\n\nend" + ) + assert plain_of(Rich("markdown", md)) == ( + "Title\n\nSome bold, it and mark link\n\n☑ done\n☐ todo\n• item\n\na | b\n1 | 2\n\nquoted\n\nprint(1)\n\n" + "$$E = mc^2$$\n\nnote\n\n1: the note\n\na caption\n\nend" + ) + + +def test_the_plain_text_of_a_rich_message_made_in_telegram(): + bl = [ + types.PageBlockHeading1(T("Title")), + types.PageBlockParagraph(types.TextConcat([T("Every "), types.TextBold(T("Monday"))])), + types.PageBlockList([types.PageListItemText(T("one")), types.PageListItemText(T("two"), checkbox=True, checked=True)]), + types.PageBlockTable( + T("sched"), + [ + types.PageTableRow([types.PageTableCell(text=T("Day"), header=True), types.PageTableCell(text=T("Show"), header=True)]), + types.PageTableRow([types.PageTableCell(text=T("Mon")), types.PageTableCell(text=T("Naruto"))]), + ], + ), + types.PageBlockMath("E = mc^2"), + types.PageBlockDetails([types.PageBlockParagraph(T("hidden"))], T("More")), + ] + want = "Title\nEvery Monday\n• one\n☑ two\nsched\nDay | Show\nMon | Naruto\nE = mc^2\nMore\nhidden" + rm = rich_msg(bl) + assert plain_of(rich_from_received(rm)) == want + assert plain_of_message(SimpleNamespace(rich_message=rm)) == want + assert plain_of_message(SimpleNamespace(rich_message=None)) == "" + assert plain_of(Rich("blocks", "not base64 of anything")) == "" + + +# ============================================================================================================== the help +def test_the_help_pages_fit_in_a_message_and_cover_the_blocks(): + for page in (RICH_HELP, RICH_HELP_HTML): + assert len(page) < 4096 + help_all = RICH_HELP + RICH_HELP_HTML + for word in ( + "<rich>", "# Heading", "- [ ] task", "```python", "$$E = mc^2$$", "[^1]", "tg://time", "tg://emoji", "==marked==", + "<details", "<table", "<tg-math-block>", "<tg-map", "<tg-collage>", "<tg-slideshow>", + "<tg-button-row", "<aside>", "<figure>", "<tg-reference", "<tg-time", "<sub>", "https", + ): + assert word in help_all, word diff --git a/tests/test_rich_flows.py b/tests/test_rich_flows.py new file mode 100644 index 0000000000000000000000000000000000000000..b607425888f3f9a398a3aff950a022323824ad7f --- /dev/null +++ b/tests/test_rich_flows.py @@ -0,0 +1,759 @@ +"""Rich messages through the bot: /new, the edits in My posts, the preview, /broadcast, the userbot, /swap, the sync and /repost.""" +import asyncio +from types import SimpleNamespace + +from telethon import functions, types + +from app.replace_engine import ScanOptions, apply_channel, scan_channel, undo_batch +from app.repost_engine import RepostOptions, final_state, run_repost, stand_in +from app.richmsg import Rich, entry, fingerprint, rich_of +from app.suggest import build_suggestion +from app.sync_engine import diff_post, live_fields, message_supported, sync_channel +from app.tgutil import button_url, pack_file_id + +from .fakes import FakeChannelClient, make_msg, markup, photo_media, rpc, url_btn, video_media +from .harness import App, norm +from .test_broadcast import broadcast, make_app as broadcast_app +from .test_engine import setup as engine_setup +from .test_flows import make_app +from .test_markup_flows import msg, new_post +from .test_replace_userbot import BUTTONS, CID, MID, make_app as userbot_app, replacement, user_edits +from .test_repost import NEW, OLD, edit_requests, forwarded_ids, setup as repost_setup +from .test_rich import blocks, rich_msg, same +from .test_sync import old_msg, opts, world + +HEADING = "# Release notes\n\n- [x] fixed\n- [ ] todo\n\n| a | b |\n|---|---|\n| 1 | 2 |" +TABLE = '

Schedule

DayShow
MonNaruto
' + + +def native(rm=None, mid=77): + """A rich message sent to the bot (or forwarded to it).""" + return SimpleNamespace( + raw_text="", entities=[], media=None, grouped_id=None, forward=None, rich_message=rm or rich_msg(), id=mid + ) + + +def raw_edits(app): + """The messages.editMessage requests the bot sent, each once.""" + out = [] + for e in app.tg.edits: + r = e[2] if isinstance(e, tuple) and e[0] == "raw" else e + if isinstance(r, functions.messages.EditMessageRequest) and not any(r is o for o in out): + out.append(r) + return out + + +def rich_sends(app): + return [e for e in app.tg.sent if e[0] == "rich"] + + +def md_post(source): + return dict(text="x", entities=[entry(Rich("markdown", source))]) + + +# ============================================================================================== typed text: /new +def test_markdown_with_a_heading_is_published_as_a_rich_message(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, prompt = await new_post(app, HEADING) + assert "Rich message read from Markdown" in prompt and "/rich" in prompt and "buttons" in prompt.lower() + post = await app.db.get_post(pid) + assert post.status == "sent" and post.entities == [{"k": "rich", "f": "markdown", "s": HEADING}] + assert post.text.startswith("Release notes\n") and "☑ fixed" in post.text and "☐ todo" in post.text + kind, peer, inp, kw = app.tg.sent[-1] + assert kind == "rich" and isinstance(peer, types.InputPeerChannel) and peer.channel_id == 1 + assert isinstance(inp, types.InputRichMessageMarkdown) and inp.markdown == HEADING and not inp.rtl + assert kw["reply_markup"] is None + live = app.tg.msgs[post.message_id] # Telegram made a rich message of it + assert live.rich_message is not None and live.message == "" + assert [e for e in app.tg.sent if e[0] in ("text", "file")] == [] # nothing went out as an ordinary message + await app.db.close() + + asyncio.run(run()) + + +def test_html_with_a_table_is_published_as_a_rich_message(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, prompt = await new_post(app, TABLE) + assert "Rich message read from HTML" in prompt + post = await app.db.get_post(pid) + assert post.entities == [{"k": "rich", "f": "html", "s": TABLE}] + assert post.text == "Schedule\nDay | Show\nMon | Naruto" + kind, peer, inp, kw = app.tg.sent[-1] + assert kind == "rich" and isinstance(inp, types.InputRichMessageHTML) and inp.html == TABLE + await app.db.close() + + asyncio.run(run()) + + +def test_the_rich_marker_turns_any_text_into_a_rich_message_with_its_options(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, prompt = await new_post(app, "\nhello **x** #tag @name") + assert "Rich message read from Markdown" in prompt + post = await app.db.get_post(pid) + assert post.text == "hello x #tag @name" + assert post.entities == [{"k": "rich", "f": "markdown", "s": "hello **x** #tag @name", "r": 1, "n": 1}] + kind, peer, inp, kw = app.tg.sent[-1] + assert isinstance(inp, types.InputRichMessageMarkdown) and inp.markdown == "hello **x** #tag @name" + assert inp.rtl is True and inp.noautolink is True + await app.db.close() + + asyncio.run(run()) + + +def test_text_that_only_looks_a_little_like_markup_stays_an_ordinary_post(tmp_path): + async def run(): + app = await make_app(tmp_path) + for text in ("#anime #naruto new episode", "Price: $5 and $6 - a == b - I <3 it\n- one\n- two\n---", "**bold** [x](https://t.me/x)"): + pid, prompt = await new_post(app, text) + assert "Rich message" not in prompt + assert rich_of(await app.db.get_post(pid)) is None + assert app.tg.sent[-1][0] == "text" + await app.db.close() + + asyncio.run(run()) + + +def test_markup_input_off_keeps_typed_blocks_literal(tmp_path): + async def run(): + app = App(tmp_path, markup_input=False) + await app.start() + await app.db.save_channel(1, 5, "Anime Channel", "animech", 1) + pid, prompt = await new_post(app, HEADING) + assert "Rich message" not in prompt + kind, peer, text, kw = app.tg.sent[-1] + assert kind == "text" and text == HEADING and kw["formatting_entities"] == [] + # a rich message made in Telegram is not typed text: it is still kept + pid, prompt = await new_post(app, "", message=native()) + assert "Rich message kept as it is" in prompt and app.tg.sent[-1][0] == "rich" + await app.db.close() + + asyncio.run(run()) + + +def test_a_typed_rich_message_that_is_too_long_is_refused(tmp_path): + async def run(): + app = await make_app(tmp_path) + await app.text("/new") + await app.text("# Title\n" + "x" * 33000, message=msg("# Title\n" + "x" * 33000)) + assert "32768" in norm(app.out.last_text) + assert (await app.db.list_posts(1, None, 0, 10))[1] == 0 # nothing was saved + await app.db.close() + + asyncio.run(run()) + + +# =================================================================================== a rich message sent to the bot +def test_a_rich_message_sent_to_the_bot_is_published_block_for_block(tmp_path): + async def run(): + app = await make_app(tmp_path) + rm = rich_msg(photos=[photo_media(5).photo], documents=[video_media(81).document], rtl=True) + pid, prompt = await new_post(app, "", message=native(rm)) + assert "Rich message kept as it is" in prompt + post = await app.db.get_post(pid) + (e,) = post.entities + assert (e["k"], e["f"], e["r"], e["p"]) == ("rich", "blocks", 1, fingerprint(rm)) and post.text == "Title\nHello" + kind, peer, inp, kw = app.tg.sent[-1] + assert kind == "rich" and isinstance(inp, types.InputRichMessage) and inp.rtl + assert same(inp.blocks, rm.blocks) + assert [(p.id, p.access_hash, p.file_reference) for p in inp.photos] == [(5, 35, b"ref5")] + assert [d.id for d in inp.documents] == [81] + live = app.tg.msgs[post.message_id].rich_message + assert same(live.blocks, rm.blocks) and [p.id for p in live.photos] == [5] + await app.db.close() + + asyncio.run(run()) + + +def test_a_rich_message_that_arrives_in_parts_is_asked_for_whole(tmp_path): + async def run(): + app = await make_app(tmp_path) + part = rich_msg([types.PageBlockParagraph(types.TextPlain("first"))], part=True) + app.tg.full_rich = {77: rich_msg(blocks("whole"))} + pid, prompt = await new_post(app, "", message=native(part)) + assert "Rich message kept as it is" in prompt + assert (await app.db.get_post(pid)).text == "Title\nwhole" + assert any(isinstance(r, functions.messages.GetRichMessageRequest) and r.id == 77 for r in app.tg.requests) + await app.db.close() + + asyncio.run(run()) + + +def test_a_rich_message_that_cannot_be_had_whole_makes_no_post(tmp_path): + async def run(): + app = await make_app(tmp_path) + part = rich_msg([types.PageBlockParagraph(types.TextPlain("first"))], part=True) + app.tg.full_rich = {77: rich_msg(blocks(), part=True)} + await app.text("/new") + await app.text("", message=native(part)) + assert "part of that rich message" in norm(app.out.last_text) + assert (await app.db.list_posts(1, None, 0, 10))[1] == 0 + assert app.ctx.state[app.uid]["mode"] == "new_content" # still waiting for the message + await app.text("hello", message=msg("hello")) # and a better one is taken + assert (await app.db.list_posts(1, None, 0, 10))[1] == 1 + await app.db.close() + + asyncio.run(run()) + + +# ================================================================================ buttons, preview, publishing +def test_the_link_buttons_of_a_post_go_with_its_rich_message(tmp_path): + async def run(): + app = await make_app(tmp_path) + await app.text("/new") + await app.text(HEADING, message=msg(HEADING)) + await app.text("Download - https://t.me/x?start=a | Other - https://example.com", message=msg("x")) + pid = int(app.out.callback_data("Publish").split(":")[1]) + await app.press(f"pb:{pid}") + await app.press(f"pby:{pid}") + kind, peer, inp, kw = app.tg.sent[-1] + rows = kw["reply_markup"].rows + assert kind == "rich" and [b.text for b in rows[0].buttons] == ["Download", "Other"] + assert [button_url(b) for b in rows[0].buttons] == ["https://t.me/x?start=a", "https://example.com"] + assert app.tg.msgs[(await app.db.get_post(pid)).message_id].reply_markup is not None + await app.db.close() + + asyncio.run(run()) + + +def test_the_preview_of_a_rich_draft_goes_to_the_owner_and_not_to_the_channel(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await new_post(app, HEADING, publish=False) + await app.press(f"pv:{pid}") + kind, peer, inp, kw = app.tg.sent[-1] + assert kind == "rich" and isinstance(peer, types.InputPeerUser) and inp.markdown == HEADING + assert app.tg.msgs == {} and (await app.db.get_post(pid)).status == "draft" + await app.db.close() + + asyncio.run(run()) + + +def test_telegram_not_being_able_to_make_the_message_is_explained_in_the_preview_and_when_publishing(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await new_post(app, "\n", publish=False) + app.tg.fail["SendMessageRequest"] = rpc("MessageEmptyError") + await app.press(f"pv:{pid}") + assert "see /rich for the syntax" in norm(app.out.last_text) + await app.press(f"pb:{pid}") + await app.press(f"pby:{pid}") + assert "NOT published" in norm(app.out.last_text) + assert (await app.db.get_post(pid)).status == "draft" and app.tg.msgs == {} + await app.db.close() + + asyncio.run(run()) + + +def test_the_panel_of_a_rich_post_has_no_media_or_link_preview(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await new_post(app, HEADING, publish=False) + await app.press(f"po:{pid}") + text = norm(app.out.last_text) + assert "Type: 🧩 rich message (typed as Markdown)" in text and "Release notes" in text + labels = [b for row in app.out.last_buttons() for b in row] + assert "✏️ Text" in labels and "👁 Preview" in labels and "➕ Button" in labels + assert not any("Media" in b or "Link preview" in b for b in labels if b) + native_pid, _ = await new_post(app, "", message=native(), publish=False) + assert "made in Telegram" in norm((await _panel(app, native_pid))) + await app.db.close() + + asyncio.run(run()) + + +async def _panel(app, pid): + await app.press(f"po:{pid}") + return app.out.last_text + + +# ====================================================================================== editing in My posts +def test_the_text_of_a_published_rich_post_is_changed_with_a_new_rich_message(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await new_post(app, "# One\n\ntext") + before = app.tg.msgs[(await app.db.get_post(pid)).message_id].rich_message + await app.press(f"et:{pid}") + assert "/rich" in norm(app.out.last_text) + new = "# Two\n\n- [ ] a" + await app.text(new, message=msg(new)) + (req,) = raw_edits(app) + assert isinstance(req.rich_message, types.InputRichMessageMarkdown) and req.rich_message.markdown == new + assert req.message is None and not req.entities + post = await app.db.get_post(pid) + assert post.entities == [{"k": "rich", "f": "markdown", "s": new}] and post.text == "Two\n\n☐ a" + assert bytes(app.tg.msgs[post.message_id].rich_message) != bytes(before) # the channel shows the new one + assert "Rich message read from Markdown" in norm(app.out.last_text) + await app.db.close() + + asyncio.run(run()) + + +def test_a_native_rich_message_can_replace_the_text_of_a_post(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await new_post(app, "plain words") + await app.press(f"et:{pid}") + await app.text("", message=native(rich_msg(blocks("brand new")))) + (req,) = raw_edits(app) + assert isinstance(req.rich_message, types.InputRichMessage) and req.message is None + post = await app.db.get_post(pid) + assert rich_of(post).fmt == "blocks" and post.text == "Title\nbrand new" + assert "Rich message kept as it is" in norm(app.out.last_text) + await app.db.close() + + asyncio.run(run()) + + +def test_a_plain_post_becomes_a_rich_one_and_a_rich_one_a_plain_one_again(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await new_post(app, "hello") + await app.press(f"et:{pid}") + await app.text(HEADING, message=msg(HEADING)) + assert isinstance(raw_edits(app)[-1].rich_message, types.InputRichMessageMarkdown) + assert rich_of(await app.db.get_post(pid)) is not None + await app.press(f"et:{pid}") + await app.text("plain again", message=msg("plain again")) + last = raw_edits(app)[-1] + assert last.message == "plain again" and last.rich_message is None + post = await app.db.get_post(pid) + assert rich_of(post) is None and post.text == "plain again" and post.entities == [] + await app.db.close() + + asyncio.run(run()) + + +def test_a_draft_can_be_changed_into_a_rich_message_before_it_is_published(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await new_post(app, "first", publish=False) + await app.press(f"et:{pid}") + await app.text(TABLE, message=msg(TABLE)) + post = await app.db.get_post(pid) + assert post.status == "draft" and rich_of(post).fmt == "html" and raw_edits(app) == [] + await app.press(f"pb:{pid}") + await app.press(f"pby:{pid}") + assert app.tg.sent[-1][0] == "rich" and app.tg.sent[-1][2].html == TABLE + await app.db.close() + + asyncio.run(run()) + + +def test_the_buttons_of_a_published_rich_post_are_changed_without_losing_the_message(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await new_post(app, HEADING) + await app.press(f"ba:{pid}") + await app.text("Watch", message=msg("Watch")) + await app.text("https://example.com/w", message=msg("https://example.com/w")) + req = raw_edits(app)[-1] + assert isinstance(req.rich_message, types.InputRichMessageMarkdown) and req.rich_message.markdown == HEADING + assert [button_url(b) for b in req.reply_markup.rows[0].buttons] == ["https://example.com/w"] + post = await app.db.get_post(pid) + assert rich_of(post) is not None and post.buttons == [[{"t": "Watch", "u": "https://example.com/w"}]] + await app.db.close() + + asyncio.run(run()) + + +def test_a_rich_post_has_no_media_slot(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await new_post(app, HEADING) + await app.press(f"em:{pid}") + assert "has no media slot" in norm(app.out.last_text) + assert app.ctx.state.get(app.uid) is None or app.ctx.state[app.uid]["mode"] != "edit_media" + await app.db.close() + + asyncio.run(run()) + + +def test_a_caption_is_never_a_rich_message(tmp_path): + async def run(): + app = await make_app(tmp_path) + post = await app.db.create_post( + channel_id=1, message_id=7, status="sent", source="bot", text="old", entities=[], buttons=[], + media_kind="photo", media_file_id=pack_file_id(make_msg(1, "", media=photo_media(3))), + ) + await app.press(f"et:{post.id}") + assert "Rich messages" not in norm(app.out.last_text) + await app.text("", message=native()) # a rich message as a caption + assert "caption can't be a rich message" in norm(app.out.last_text) + await app.text("# Heading\n\n- [ ] task", message=msg("# Heading\n\n- [ ] task")) # typed blocks stay words + saved_post = await app.db.get_post(post.id) + assert rich_of(saved_post) is None and saved_post.text.startswith("# Heading") and saved_post.media_kind == "photo" + assert all(r.rich_message is None for r in raw_edits(app)) + await app.db.close() + + asyncio.run(run()) + + +def test_a_rich_message_can_not_be_made_a_media_post_by_the_media_edit(tmp_path): + async def run(): + app = await make_app(tmp_path) + await app.text("/new") + await app.text("", message=SimpleNamespace(raw_text="", entities=[], media=photo_media(5), grouped_id=None, forward=None, rich_message=rich_msg())) + post = (await app.db.list_posts(1, None, 0, 10))[0][0] + assert post.media_kind == "photo" and rich_of(post) is None # a photo wins: the message is not a rich post + await app.db.close() + + asyncio.run(run()) + + +# =================================================================================================== /broadcast +def test_a_broadcast_can_be_a_rich_message(tmp_path): + async def run(): + app = await broadcast_app(tmp_path) + await app.text("/broadcast 1h") + assert "/rich" in norm(app.out.last_text) + text = "# Maintenance\n\n- tonight 22:00\n- [ ] backups" + await app.text(text, message=msg(text)) + assert "Rich message read from Markdown" in norm(app.out.last_text) + await app.press(app.out.callback_data("No buttons")) + assert rich_sends(app)[-1][1].__class__ is types.InputPeerUser # the preview was made as a rich message too + await app.press(app.out.callback_data("Send to all channels")) + for cid in (1, 2): + chan = app.tg.registry[cid] + (live,) = [m for m in chan.msgs.values() if m.rich_message is not None] + assert isinstance(live.rich_input, types.InputRichMessageMarkdown) and live.rich_input.markdown == text + (p,) = await app.db.sent_posts(cid) + assert p.message_id == live.id and p.entities == [{"k": "rich", "f": "markdown", "s": text}] + assert p.text.startswith("Maintenance") + assert len(await app.db.pending_deletes()) == 2 # it is still deleted when its time is up + await app.db.close() + + asyncio.run(run()) + + +def test_a_broadcast_with_a_native_rich_message_and_buttons(tmp_path): + async def run(): + app = await broadcast_app(tmp_path) + await broadcast(app, "/broadcast 1h", "", buttons="Open - https://t.me/x", message=native()) + for cid in (1, 2): + (live,) = [m for m in app.tg.registry[cid].msgs.values() if m.rich_message is not None] + assert same(live.rich_message.blocks, blocks()) + assert [button_url(b) for b in live.reply_markup.rows[0].buttons] == ["https://t.me/x"] + await app.db.close() + + asyncio.run(run()) + + +# ======================================================================================================== /replace +def test_replace_leaves_a_rich_post_alone(tmp_path): + async def run(): + app, chan, user = await userbot_app(tmp_path) + live = chan.msgs[MID] + live.media, live.message, live.rich_message = None, "", rich_msg() # the channel's post is a rich message + await app.text(f"/replace https://t.me/c/{CID}/{MID}", reply=replacement()) + assert "is a rich message" in norm(app.out.last_text) + assert user_edits(user) == [] and not any(isinstance(r, functions.messages.EditMessageRequest) for r in chan.requests) + assert chan.msgs[MID].rich_message is not None + await app.db.close() + + asyncio.run(run()) + + +# ================================================================================================ the userbot +def test_a_rich_edit_that_telegram_refuses_the_bot_is_made_by_the_userbot(tmp_path): + async def run(): + app, chan, user = await userbot_app(tmp_path) # the post belongs to another bot: the bot may not edit it + live = chan.msgs[MID] + live.media, live.message, live.rich_message = None, "", chan._rich(types.InputRichMessageMarkdown(markdown="# old")) + post = await app.db.create_post( + channel_id=CID, message_id=MID, status="sent", source="adopted", text="old", + entities=[entry(Rich("markdown", "# old"))], buttons=BUTTONS, + ) + await app.press(f"et:{post.id}") + new = "# New\n\n- [x] a" + await app.text(new, message=msg(new)) + (req,) = user_edits(user) + assert isinstance(req.rich_message, types.InputRichMessageMarkdown) and req.rich_message.markdown == new + assert req.message is None and req.reply_markup is None # a user account sends no keyboard + assert isinstance(chan.msgs[MID].rich_message, types.RichMessage) and chan.msgs[MID].rich_input.markdown == new + assert "the userbot made the edit" in norm(app.out.last_text) and "Rich message read from Markdown" in norm(app.out.last_text) + saved_post = await app.db.get_post(post.id) + assert saved_post.entities == [{"k": "rich", "f": "markdown", "s": new}] and saved_post.buttons == BUTTONS + await app.db.close() + + asyncio.run(run()) + + +def test_the_userbot_editor_can_set_a_rich_message(): + from .test_userbot import channel + from .test_userbot_edit import ready_editor + + async def go(): + bot = channel() + ub, made, e = await ready_editor(bot) + await e.edit(5, text="", entities=[], rich=Rich("html", "

New

")) + await e.close() + req = bot.user_edits[-1] + assert isinstance(req.rich_message, types.InputRichMessageHTML) and req.rich_message.html == "

New

" + assert req.message is None and bot.msgs[5].rich_message is not None and bot.msgs[5].message == "" + + asyncio.run(go()) + + +# ============================================================================================ /swap and /handleswap +OLD_LINK = "https://t.me/bharath?start=AAA" + + +def live_rich_post(i=1, *, out=True): + m = make_msg(i, "", markup=markup([url_btn("Get", OLD_LINK)]), out=out) + m.rich_message = rich_msg( + [types.PageBlockParagraph(types.TextUrl(types.TextPlain("t.me/bharath"), "https://t.me/bharath?start=ZZZ", 0))] + ) + return m + + +def test_swap_changes_only_the_buttons_of_a_rich_post_and_undo_puts_them_back(tmp_path): + async def run(): + live = live_rich_post() + db, ch, client = await engine_setup(tmp_path, {1: live}) + typed = Rich("markdown", "# Title\n\n@bharath t.me/bharath") + await db.create_post( + channel_id=1, message_id=1, status="sent", source="bot", text="Title", entities=[entry(typed)], + buttons=[[{"t": "Get", "u": OLD_LINK}]], + ) + o = ScanOptions("bharath", "goku") + scan = await scan_channel(client, ch, o, can_edit_others=True) + assert set(scan.infos) == {1} + await db.create_batch("b1", "bharath", "goku", 99) + res = await apply_channel(client, db, scan, o, "b1", 99, edit_delay=0) + assert (res.edited, res.failed) == (1, []) + req = client.edits[-1] + assert req.message is None and req.rich_message is None # only the keyboard was sent + assert button_url(live.reply_markup.rows[0].buttons[0]) == "https://t.me/goku?start=AAA" + assert live.message == "" and live.rich_message is not None + p = await db.find_by_message(1, 1) + assert rich_of(p) == typed and p.text == "Title" and p.buttons == [[{"t": "Get", "u": "https://t.me/goku?start=AAA"}]] + + ures = await undo_batch(client, db, "b1", edit_delay=0) + assert ures.restored == 1 and not ures.failed + assert client.edits[-1].message is None and client.edits[-1].rich_message is None + assert button_url(live.reply_markup.rows[0].buttons[0]) == OLD_LINK + p = await db.find_by_message(1, 1) + assert rich_of(p) == typed and p.text == "Title" and p.buttons == [[{"t": "Get", "u": OLD_LINK}]] + await db.close() + + asyncio.run(run()) + + +def test_a_rich_post_nobody_saved_is_adopted_by_a_swap_as_its_blocks(tmp_path): + async def run(): + live = live_rich_post() + db, ch, client = await engine_setup(tmp_path, {1: live}) + o = ScanOptions("bharath", "goku") + scan = await scan_channel(client, ch, o, can_edit_others=True) + await db.create_batch("b1", "bharath", "goku", 99) + await apply_channel(client, db, scan, o, "b1", 99, edit_delay=0) + p = await db.find_by_message(1, 1) + r = rich_of(p) + assert p.source == "adopted" and r.fmt == "blocks" and r.fp == fingerprint(live.rich_message) + assert p.text == "t.me/bharath" and p.buttons == [[{"t": "Get", "u": "https://t.me/goku?start=AAA"}]] + await db.close() + + asyncio.run(run()) + + +def test_swaps_leave_the_text_of_a_rich_post_alone(tmp_path): + async def run(): + for mode in ("links", "handles"): + live = make_msg(1, "") + live.rich_message = rich_msg([types.PageBlockParagraph(types.TextPlain("@bharath https://t.me/bharath?start=A"))]) + db, ch, client = await engine_setup(tmp_path, {1: live}) + scan = await scan_channel(client, ch, ScanOptions("bharath", "goku", mode=mode), can_edit_others=True) + assert scan.infos == {} # no button to change: nothing to do + await db.close() + + asyncio.run(run()) + + +def test_a_handleswap_renames_the_buttons_of_a_rich_post_only(tmp_path): + async def run(): + live = make_msg(1, "", markup=markup([url_btn("Join @bharath", "https://example.com")]), out=True) + live.rich_message = rich_msg() + db, ch, client = await engine_setup(tmp_path, {1: live}) + o = ScanOptions("bharath", "goku", mode="handles") + scan = await scan_channel(client, ch, o, can_edit_others=True) + await db.create_batch("b1", "bharath", "goku", 99) + await apply_channel(client, db, scan, o, "b1", 99, edit_delay=0) + assert live.reply_markup.rows[0].buttons[0].text == "Join @goku" and client.edits[-1].message is None + assert live.rich_message is not None + await db.close() + + asyncio.run(run()) + + +# ===================================================================================================== the sync +class SavedLike: + """Anything with the Post fields.""" + + def __init__(self, m, **kw): + for k, v in live_fields(m).items(): + setattr(self, k, v) + self.link_preview = False + for k, v in kw.items(): + setattr(self, k, v) + + +def rich_live(i, word="Hello", **kw): + m = old_msg(i, "", **kw) + m.rich_message = rich_msg(blocks(word)) + return m + + +def test_a_saved_rich_post_that_is_unchanged_shows_no_difference(): + m = rich_live(1) + p = SavedLike(m) + d = diff_post(p, m) + assert d.fields == {} and not d.quiet and not d.buttons_missing + assert message_supported(m) and not message_supported(old_msg(2, "")) + + +def test_a_rich_post_edited_in_the_channel_is_taken_over_as_its_new_blocks(): + m = rich_live(1, "Hello") + p = SavedLike(m) + edited = rich_live(1, "Changed") + d = diff_post(p, edited) + assert set(d.fields) == {"text", "entities"} and d.fields["text"] == "Title\nChanged" + (e,) = d.fields["entities"] + assert e["f"] == "blocks" and e["p"] == fingerprint(edited.rich_message) and not d.quiet + + +def test_the_bots_own_typed_rich_post_is_only_noted_the_first_time_the_sync_sees_it(): + m = rich_live(1) + typed = Rich("markdown", HEADING) + p = SavedLike(m, text="Release notes", entities=[entry(typed)]) + d = diff_post(p, m) + assert d.quiet and set(d.fields) == {"entities"} + (e,) = d.fields["entities"] + assert (e["f"], e["s"], e["p"]) == ("markdown", HEADING, fingerprint(m.rich_message)) # its source is kept, the fingerprint added + again = SavedLike(m, text="Release notes", entities=d.fields["entities"]) + assert diff_post(again, m).fields == {} + changed = rich_live(1, "Edited by an admin") + assert set(diff_post(again, changed).fields) == {"text", "entities"} + + +def test_a_rich_post_that_became_an_ordinary_one_or_the_other_way_round_is_followed(): + rich = rich_live(1) + plain = old_msg(1, "now just words") + d = diff_post(SavedLike(rich), plain) + assert d.fields == {"text": "now just words", "entities": []} + d = diff_post(SavedLike(plain), rich) + assert d.fields["text"] == "Title\nHello" and d.fields["entities"][0]["f"] == "blocks" + empty = old_msg(1, "") # Telegram shows nothing this time: that is not an edit + assert diff_post(SavedLike(rich), empty).fields == {} + + +def test_the_sync_saves_a_rich_post_it_finds_and_leaves_it_alone_afterwards(tmp_path): + async def run(): + chan, db, ch = await world(tmp_path, {1: old_msg(1, "plain"), 2: rich_live(2)}, save=False) + rep = await sync_channel(chan, db, ch, opts()) + p = await db.find_by_message(1, 2) + assert p is not None and rich_of(p).fmt == "blocks" and p.text == "Title\nHello" and p.source == "adopted" + again = await sync_channel(chan, db, ch, opts()) + assert again.edited == [] and again.adopted == [] and rep.error is None + chan.msgs[2].rich_message = rich_msg(blocks("Later")) # somebody edits it in the channel + third = await sync_channel(chan, db, ch, opts()) + assert third.edited == [2] and (await db.find_by_message(1, 2)).text == "Title\nLater" + await db.close() + + asyncio.run(run()) + + +# ===================================================================================================== /repost +def rich_channel(): + welcome = make_msg(1, "Welcome") + same_post = make_msg(2, "") + same_post.rich_message = rich_msg(blocks("one")) + with_button = make_msg(3, "", markup=markup([url_btn("Get", f"https://t.me/{OLD}?start=AAA"), url_btn("Other", "https://example.com/x")])) + with_button.rich_message = rich_msg(blocks("two"), photos=[photo_media(5).photo]) + return {1: welcome, 2: same_post, 3: with_button} + + +def test_a_repost_copies_rich_posts_and_rebuilds_the_one_with_buttons(tmp_path): + async def run(): + db, ch, chan, mig = await repost_setup(tmp_path, FakeChannelClient(rich_channel()), include_typed=True) + res = await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + assert (res.copied_units, res.failed, res.aborted) == (3, [], None) + assert forwarded_ids(chan) == [[1], [2]] and edit_requests(chan) == [] + new = {i: m for i, m in chan.msgs.items() if i > 3} + assert list(new) == [4, 5, 6] + assert new[4].message == "Welcome" + assert same(new[5].rich_message.blocks, blocks("one")) # a copy by Telegram: still the same rich message + m = new[6] # the post with buttons is created again, with the link swapped + assert isinstance(m.rich_input, types.InputRichMessage) and same(m.rich_input.blocks, blocks("two")) + assert [(p.id, p.file_reference) for p in m.rich_input.photos] == [(5, b"ref5")] + rows = m.reply_markup.rows + assert [button_url(b) for b in rows[0].buttons] == [f"https://t.me/{NEW}?start=AAA", "https://example.com/x"] + saved_row = await db.find_by_message(1, 6) + assert saved_row.text == "Title\ntwo" and rich_of(saved_row).fmt == "blocks" + assert saved_row.buttons[0][0]["u"] == f"https://t.me/{NEW}?start=AAA" + assert rich_of(await db.find_by_message(1, 5)) is not None + await db.close() + + asyncio.run(run()) + + +def test_a_channel_that_forbids_forwarding_gets_its_rich_posts_rebuilt(tmp_path): + async def run(): + chan = FakeChannelClient(rich_channel()) + chan.restrict_forwards = True + db, ch, chan, mig = await repost_setup(tmp_path, chan) + res = await run_repost(chan, db, ch, mig, 99, delay=0, settle_pause=0) + assert (res.copied_units, res.failed) == (3, []) and forwarded_ids(chan) == [[1]] # only the first, refused, try + new = {i: m for i, m in chan.msgs.items() if i > 3} + assert same(new[5].rich_input.blocks, blocks("one")) and same(new[6].rich_input.blocks, blocks("two")) + assert new[5].reply_markup is None and new[6].reply_markup is not None + await db.close() + + asyncio.run(run()) + + +def test_a_post_held_back_by_telegram_is_rebuilt_from_its_saved_rich_message(): + row = SimpleNamespace( + text="Release notes", entities=[entry(Rich("markdown", HEADING))], buttons=[], media_file_id=None, link_preview=False + ) + live = make_msg(7, "This message couldn't be displayed on your device due to copyright infringement.") + final = final_state(stand_in(live, row), RepostOptions(OLD, NEW)) + assert final.rich == Rich("markdown", HEADING) and final.text == "" and final.entities == [] + assert final_state(make_msg(8, "plain"), RepostOptions(OLD, NEW)).rich is None + + +# ============================================================================================== everything else +def test_a_rich_post_is_kept_by_an_export_and_an_import(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await new_post(app, HEADING) + data = await app.db.export_all() + (p,) = [x for x in data["posts"] if x["id"] == pid] + assert p["entities"] == [{"k": "rich", "f": "markdown", "s": HEADING}] + await app.db.close() + + asyncio.run(run()) + + +def test_the_next_post_suggestion_leaves_rich_posts_out(): + post = SimpleNamespace( + text="x", entities=[entry(Rich("markdown", HEADING))], buttons=[[{"t": "Download Episodes 1 to 20", "u": "https://t.me/x?start=a"}]], + ) + assert build_suggestion(post) is None + + +def test_the_rich_command_and_the_help_pages(tmp_path): + async def run(): + app = await make_app(tmp_path) + await app.text("/rich") + said = [norm(t) for kind, t, _ in app.out.log if kind == "say"] + assert len(said) == 2 and "Rich messages" in said[0] and " self.limit: + raise block_invalid() + return types.UpdateShortSentMessage(id=next(self.ids), pts=0, pts_count=0, date=None, out=True) + if isinstance(req, functions.messages.DeleteMessagesRequest): + self.deleted += list(req.id) + return None + raise NotImplementedError(type(req)) + + +# ================================================================================================= what is converted +def test_a_stored_map_is_turned_into_an_input_map_wherever_it_is(): + cap = types.PageCaption(T("c"), types.TextEmpty()) + detail = types.PageBlockDetails([types.PageBlockParagraph(T("x")), a_map()], T("More")) + collage = types.PageBlockCollage([a_map()], cap) + original = [bytes(b) for b in (detail, collage)] + out = inputify([detail, collage, types.PageBlockParagraph(T("p"))]) + assert [type(b).__name__ for b in out] == ["PageBlockDetails", "PageBlockCollage", "PageBlockParagraph"] + inner = out[0].blocks[1] + assert isinstance(inner, types.InputPageBlockMap) and isinstance(out[1].items[0], types.InputPageBlockMap) + assert (inner.geo.lat, inner.geo.long, inner.geo.accuracy_radius) == (41.9, 12.5, 7) + assert (inner.zoom, inner.w, inner.h, bytes(inner.caption)) == (14, 600, 300, bytes(a_map().caption)) + assert isinstance(inner.geo, types.InputGeoPoint) + assert [bytes(b) for b in (detail, collage)] == original # what was handed to us is left as it was + assert isinstance(detail.blocks[1], types.PageBlockMap) + bytes(types.InputRichMessage(blocks=out)) # and it can be sent + + +def test_blocks_without_a_map_come_back_the_same(): + bl = blocks() + [types.PageBlockDetails(blocks("x"), T("t")), types.PageBlockDivider()] + assert same(inputify(bl), bl) + + +def test_a_received_message_with_a_map_is_sent_with_an_input_map_and_keeps_its_fingerprint(): + rm = rich_msg([types.PageBlockHeading1(T("Trip")), a_map(), types.PageBlockParagraph(T("end"))]) + r = rich_from_received(rm) + sent = to_input(r) + assert [type(b).__name__ for b in sent.blocks] == ["PageBlockHeading1", "InputPageBlockMap", "PageBlockParagraph"] + assert [type(b).__name__ for b in input_of(rm).blocks] == [type(b).__name__ for b in sent.blocks] + assert r.fp == fingerprint(rm) + assert fingerprint(rich_msg([types.PageBlockHeading1(T("Trip")), a_map(access_hash=12345), types.PageBlockParagraph(T("end"))])) == r.fp + + +def test_blocks_saved_in_telegrams_own_form_by_an_older_version_are_converted_when_sent(): + old = types.InputRichMessage(blocks=[a_map(), types.PageBlockParagraph(T("end"))]) + sent = to_input(Rich("blocks", _b64(old), False, False, None)) + assert [type(b).__name__ for b in sent.blocks] == ["InputPageBlockMap", "PageBlockParagraph"] + assert isinstance(old.blocks[0], types.PageBlockMap) # the saved copy itself is not touched + + +def test_a_thinking_block_goes_out_as_an_expandable_section(): + thought = types.PageBlockThinking(types.TextBold(T("let me see"))) + nested = types.PageBlockDetails([thought], T("Outer")) + out = inputify([thought, nested]) + for sec in (out[0], out[1].blocks[0]): + assert isinstance(sec, types.PageBlockDetails) and bytes(sec.title) == bytes(T("Thinking")) + (para,) = sec.blocks + assert isinstance(para, types.PageBlockParagraph) and bytes(para.text) == bytes(types.TextBold(T("let me see"))) + assert isinstance(nested.blocks[0], types.PageBlockThinking) # what was handed to us is left as it was + # what the sync compares is the same whichever of the two forms Telegram shows + assert fingerprint(rich_msg([thought])) == fingerprint(rich_msg([out[0]])) + + +def test_a_mention_of_somebody_the_message_has_no_access_data_for_stays_the_plain_name(): + mention = types.PageBlockParagraph(types.TextConcat([T("hi "), types.TextMentionName(T("Mia"), 5)])) + rm = rich_msg([mention]) + plain = to_input(rich_from_received(rm, [])) + assert plain.blocks[0].text.texts[1].__class__ is types.TextPlain and plain.blocks[0].text.texts[1].text == "Mia" + known = to_input(rich_from_received(rm, [types.InputUser(5, 77)])) + assert isinstance(known.blocks[0].text.texts[1], types.TextMentionName) and known.blocks[0].text.texts[1].user_id == 5 + assert [u.user_id for u in known.users] == [5] + + +# ==================================================================================== how the owner is told which blocks +def test_blocks_have_names_and_are_listed_from_one(): + r = rich_from_received(rich_msg([types.PageBlockHeading2(T("a")), a_map(), types.PageBlockTable(T(""), [])])) + assert [block_name(b) for b in to_input(r).blocks] == ["heading", "map", "table"] + assert block_name(types.PageBlockUnsupported()) == "a block this version does not know" + assert block_name(types.InputPageBlockMap(types.InputGeoPointEmpty(), 1, 1, 1, types.PageCaption(T(""), T(""))))== "map" + assert block_labels(r, [2, 1, 1, 9]) == "2 (map), 3 (table)" + assert block_count(r) == 3 and block_count(Rich("markdown", "# x")) == 0 + + +def test_block_numbers_fit_in_a_button(): + for idx in ([], [0], [1, 3], [0, 59], list(range(60))): + word = pack_blocks(idx) + assert unpack_blocks(word) == sorted(idx) and len(f"rx:123456789:abcdef:{word}") <= 64 + assert pack_blocks([]) == "0" + + +def test_leaving_blocks_out_keeps_the_rest_and_forgets_the_fingerprint(): + rm = rich_msg(with_bad(4, bad=(2,)), photos=[], documents=[], rtl=True) + r = rich_from_received(rm) + kept = without_blocks(r, [2]) + inp = to_input(kept) + assert [type(b).__name__ for b in inp.blocks] == ["PageBlockParagraph"] * 3 and inp.rtl is True + assert kept.fp is None and kept.fmt == "blocks" and kept.rtl is True + assert digest(kept) != digest(r) and block_count(r) == 4 and block_count(kept) == 3 + + +def test_explain_rpc_knows_the_code_that_telegram_gave_for_a_rich_message(): + text = explain_rpc(block_invalid()) + assert text.startswith("Telegram refused (BadRequestError).") and "would not take one of the blocks" in text + assert "(RICH_MESSAGE_BLOCK_INVALID)" in text + assert "admin rights" in explain_rpc(rpc("ChatAdminRequiredError")) # the others are as they were + other = errors.BadRequestError(None, "SOMETHING_ELSE", 400) + assert "SOMETHING_ELSE" in explain_rpc(other) and not is_block_invalid(other) and is_block_invalid(block_invalid()) + + +# ================================================================================================ finding the blocks +def refusing_the_unsupported(gate): + """`gate`, but a message with a block of the unsupported kind is refused (like a block Telegram can't take back).""" + + async def call(req): + if isinstance(req, functions.messages.SendMessageRequest) and any( + isinstance(b, types.PageBlockUnsupported) for b in req.rich_message.blocks + ): + gate.sent.append(req) + raise block_invalid() + return await gate(req) + + return call + + +def test_the_refused_blocks_are_found_and_the_test_messages_are_deleted(): + async def run(): + gate = Gate(limit=10) + r = rich_from_received(rich_msg(with_bad(8, bad=(2, 5)))) + assert await refused_blocks(refusing_the_unsupported(gate), PEER, r, pause=0) == [2, 5] + assert all(q.silent for q in gate.sent) and len(gate.sent) <= 14 # (the whole message is known to be refused: not asked again) + refused = [q for q in gate.sent if any(isinstance(b, types.PageBlockUnsupported) for b in q.rich_message.blocks)] + taken = len(gate.sent) - len(refused) + assert taken > 0 and gate.deleted == list(range(500, 500 + taken)) # every test message that was made is deleted again + + asyncio.run(run()) + + +def test_nothing_is_found_when_every_part_is_taken_or_it_cannot_be_looked_into(): + async def run(): + r = rich_from_received(rich_msg(with_bad(4, bad=()))) + assert await refused_blocks(Gate(limit=2), PEER, r, pause=0) is None # too long together, fine in parts + assert await refused_blocks(Gate(limit=2), PEER, Rich("markdown", "# x"), pause=0) is None # Telegram reads that itself + assert await refused_blocks(Gate(limit=9), PEER, rich_from_received(rich_msg(with_bad(61, bad=()))), pause=0) is None + broken = Gate(limit=0, error=rpc("ChatWriteForbiddenError")) # not a refused block: something else is wrong + assert await refused_blocks(broken, PEER, rich_from_received(rich_msg(with_bad(3, bad=(1,)))), pause=0) is None + + asyncio.run(run()) + + +def test_a_test_message_that_cannot_be_deleted_does_not_stop_the_search(): + async def run(): + gate = Gate(limit=10) + inner = refusing_the_unsupported(gate) + + async def call(req): + if isinstance(req, functions.messages.DeleteMessagesRequest): + raise rpc("MessageIdInvalidError") + return await inner(req) + + r = rich_from_received(rich_msg(with_bad(4, bad=(0, 2)))) + assert await refused_blocks(call, PEER, r, pause=0) == [0, 2] + + asyncio.run(run()) + + +# ================================================================================ a forwarded rich message in the bot +MAPPED = [types.PageBlockHeading1(T("Trip")), a_map(), types.PageBlockParagraph(T("end"))] + + +def test_a_forwarded_message_with_a_map_is_previewed_and_published(tmp_path): + async def run(): + app = await make_app(tmp_path) + rm = rich_msg(MAPPED) + pid, prompt = await new_post(app, "", message=native(rm), publish=False) + assert "Rich message kept as it is" in prompt + await app.press(f"pv:{pid}") + kind, peer, inp, kw = rich_sends(app)[-1] + assert isinstance(peer, types.InputPeerUser) + assert [type(b).__name__ for b in inp.blocks] == ["PageBlockHeading1", "InputPageBlockMap", "PageBlockParagraph"] + assert "refused" not in norm(app.out.last_text or "") + await app.press(f"pb:{pid}") + await app.press(f"pby:{pid}") + post = await app.db.get_post(pid) + assert post.status == "sent" + live = app.tg.msgs[post.message_id].rich_message + assert [type(b).__name__ for b in live.blocks][1] == "InputPageBlockMap" + assert rich_of(post).fp == fingerprint(rm) # the sync still knows it + await app.db.close() + + asyncio.run(run()) + + +def test_a_forwarded_message_with_a_thinking_block_is_previewed_and_published(tmp_path): + async def run(): + app = await make_app(tmp_path) + rm = rich_msg([types.PageBlockThinking(T("pondering")), a_map(), types.PageBlockParagraph(T("answer"))]) + pid, _ = await new_post(app, "", message=native(rm), publish=False) + await app.press(f"pv:{pid}") + assert "refused" not in norm(app.out.last_text or "") + assert [type(b).__name__ for b in rich_sends(app)[-1][2].blocks] == [ + "PageBlockDetails", "InputPageBlockMap", "PageBlockParagraph" + ] + await app.press(f"pb:{pid}") + await app.press(f"pby:{pid}") + post = await app.db.get_post(pid) + live = app.tg.msgs[post.message_id].rich_message + assert post.status == "sent" and bytes(live.blocks[0].title) == bytes(T("Thinking")) + assert rich_of(post).fp == fingerprint(live) # the sync sees what is in the channel as the saved post + await app.db.close() + + asyncio.run(run()) + + +def forwarded_with_bad_blocks(app): + return new_post(app, "", message=native(rich_msg(with_bad(5, bad=(1, 3)))), publish=False) + + +def test_the_preview_says_which_blocks_telegram_refuses_and_a_draft_can_go_on_without_them(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await forwarded_with_bad_blocks(app) + await app.press(f"pv:{pid}") + text = norm(app.out.last_text) + assert "Telegram refused (BadRequestError)" in text and "would not take one of the blocks" in text + assert "It won't take these blocks (of 5): 2 (a block this version does not know), 4 (a block this version does not know). The others are fine." in text + assert "see /rich for the syntax" not in text # that is for typed messages + assert app.out.last_buttons() == [["✂️ Leave those out"], ["↩️ Back"]] + probes = [e for e in rich_sends(app) if isinstance(e[1], types.InputPeerUser)] + assert all(e[3]["silent"] for e in probes[1:]) and sorted(app.tg.dm_rich_ids) == sorted( + i for ids in app.tg.delete_requests for i in ids + ) # nothing of the check stays in the chat + + await app.press(app.out.callback_data("Leave those out")) + assert "Left out: 2 (a block this version does not know), 4 (a block this version does not know)." in norm(app.out.last_text) + post = await app.db.get_post(pid) + kept = to_input(rich_of(post)) + assert [b.text.text for b in kept.blocks] == ["block 0", "block 2", "block 4"] + assert post.text == plain_of(rich_of(post)) == "block 0\nblock 2\nblock 4" and post.status == "draft" + assert len(post.entities) == 1 and post.entities[0]["k"] == "rich" and "p" not in post.entities[0] + + before = len(rich_sends(app)) + await app.press(f"pv:{pid}") # now Telegram takes it + assert len(rich_sends(app)) == before + 1 and len(rich_sends(app)[-1][2].blocks) == 3 + await app.press(f"pb:{pid}") + await app.press(f"pby:{pid}") + post = await app.db.get_post(pid) + assert post.status == "sent" and len(app.tg.msgs[post.message_id].rich_message.blocks) == 3 + await app.db.close() + + asyncio.run(run()) + + +def test_publishing_a_message_telegram_refuses_names_the_blocks_and_publishes_nothing(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await forwarded_with_bad_blocks(app) + await app.press(f"pb:{pid}") + await app.press(f"pby:{pid}") + text = norm(app.out.last_text) + assert "It won't take these blocks (of 5): 2 (" in text and "The post was NOT published." in text + assert "Leave those out" in str(app.out.last_buttons()) + assert (await app.db.get_post(pid)).status == "draft" and app.tg.msgs == {} + await app.press(app.out.callback_data("Leave those out")) + await app.press(f"pb:{pid}") + await app.press(f"pby:{pid}") + assert (await app.db.get_post(pid)).status == "sent" and len(app.tg.msgs) == 1 + await app.db.close() + + asyncio.run(run()) + + +def test_the_leave_out_button_is_only_for_the_draft_that_was_checked(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await forwarded_with_bad_blocks(app) + await app.press(f"pv:{pid}") + data = app.out.callback_data("Leave those out") + # the post is changed meanwhile: the old button must not cut blocks out of the new message + await app.press(f"et:{pid}") + await app.text("", message=native(rich_msg(with_bad(6, bad=(0,))))) + changed = (await app.db.get_post(pid)).entities + await app.press(data) + assert "not the one that was checked any more" in norm(app.out.last_text) + assert (await app.db.get_post(pid)).entities == changed + # a post that is published is not edited this way + await app.press(f"pv:{pid}") + data = app.out.callback_data("Leave those out") + await app.db.update_post(pid, status="sent") + await app.press(data) + assert "not the one that was checked any more" in norm(app.out.last_text) + assert (await app.db.get_post(pid)).entities == changed + await app.db.close() + + asyncio.run(run()) + + +def test_when_every_block_is_refused_nothing_is_offered_to_leave_out(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await new_post(app, "", message=native(rich_msg(with_bad(3, bad=(0, 1, 2)))), publish=False) + await app.press(f"pv:{pid}") + text = norm(app.out.last_text) + assert "It won't take any block of that message as it is" in text and "/rich" in text + assert "Leave those out" not in text and "(of 3)" not in text + await app.db.close() + + asyncio.run(run()) + + +def test_a_refusal_that_is_not_about_a_block_is_not_looked_into(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await forwarded_with_bad_blocks(app) + app.tg.fail["SendMessageRequest"] = rpc("ChatWriteForbiddenError") + await app.press(f"pv:{pid}") + text = norm(app.out.last_text) + assert "ChatWriteForbiddenError" in text and "Telegram could not make that rich message." in text + assert "see /rich for the syntax" not in text and "blocks (of" not in text + assert len(rich_sends(app)) == 1 # no test messages were sent + await app.db.close() + + asyncio.run(run()) + + +def test_a_typed_rich_message_that_is_refused_still_points_to_the_syntax(tmp_path): + async def run(): + app = await make_app(tmp_path) + pid, _ = await new_post(app, "\n", publish=False) + app.tg.fail["SendMessageRequest"] = block_invalid() + await app.press(f"pv:{pid}") + text = norm(app.out.last_text) + assert "would not take one of the blocks" in text and "see /rich for the syntax" in text + assert len(rich_sends(app)) == 1 # (Telegram reads the typed text itself: there are no blocks to try) + await app.db.close() + + asyncio.run(run()) + + +def test_a_broadcast_of_a_message_telegram_refuses_says_why(tmp_path): + async def run(): + app = await broadcast_app(tmp_path) + await app.text("/broadcast 1h") + await app.text("", message=native(rich_msg(with_bad(3, bad=(1,))))) + await app.press(app.out.callback_data("No buttons")) + text = norm(app.out.last_text) + assert "would not take one of the blocks" in text and "can't be sent like this" in text + assert "It won't take these blocks (of 3): 2 (a block this version does not know)." in text + assert all(not chan.msgs for chan in app.tg.registry.values()) + await app.db.close() + + asyncio.run(run()) diff --git a/tests/test_richtext.py b/tests/test_richtext.py new file mode 100644 index 0000000000000000000000000000000000000000..7e71bfdc9404c929efde83008d79770078473c02 --- /dev/null +++ b/tests/test_richtext.py @@ -0,0 +1,534 @@ +"""HTML and Markdown typed as text become Telegram formatting (app/richtext.py) - and everything else stays as typed.""" +import html +import random +import re +import time +from types import SimpleNamespace + +import pytest +from telethon import types +from telethon.extensions import html as telethon_html + +from app import richtext +from app.common import UserError +from app.handlers.panel import extract_content, markup_note +from app.richtext import CHEAT_SHEET, clean_url, convert, from_html, from_markdown, looks_like_html, message_text +from app.tgutil import de_entities, ser_entities, utf16_len + +from .harness import App, norm + + +def piece(text, e): + """The text an entity covers, found the way Telegram counts: in UTF-16 units.""" + raw = text.encode("utf-16-le") + return raw[e["o"] * 2 : (e["o"] + e["l"]) * 2].decode("utf-16-le") + + +def read(src): + """(text, [(kind, covered text)] outer first, how it was read)""" + text, ents, how = convert(src) + ents = sorted(ents, key=lambda e: (e["o"], -e["l"], e["k"])) + return text, [(e["k"], piece(text, e)) for e in ents], how + + +def entity(src, kind, **extra): + """The one entity of `kind` in `src`, as stored.""" + text, ents, _ = convert(src) + (found,) = [e for e in ents if e["k"] == kind] + for key, value in extra.items(): + assert found[key] == value, (found, key) + return found + + +def msg(text, entities=None): + return SimpleNamespace(raw_text=text, entities=entities or [], media=None, grouped_id=None, forward=None) + + +# --------------------------------------------------------------------------------------------- Markdown marks +@pytest.mark.parametrize( + "src, text, found", + [ + ("**bold**", "bold", [("bold", "bold")]), + ("*it*", "it", [("italic", "it")]), + ("_it_", "it", [("italic", "it")]), + ("__under__", "under", [("underline", "under")]), + ("~~gone~~", "gone", [("strike", "gone")]), + ("||secret||", "secret", [("spoiler", "secret")]), + ("`code`", "code", [("code", "code")]), + ("**bold** *it* _it2_ __under__ ~~gone~~ ||secret|| `code`", "bold it it2 under gone secret code", + [("bold", "bold"), ("italic", "it"), ("italic", "it2"), ("underline", "under"), ("strike", "gone"), ("spoiler", "secret"), ("code", "code")]), + ("***both***", "both", [("bold", "both"), ("italic", "both")]), + ("**bold *and italic* inside**", "bold and italic inside", [("bold", "bold and italic inside"), ("italic", "and italic")]), + ("~~**both**~~", "both", [("bold", "both"), ("strike", "both")]), + ("||**sp bold**||", "sp bold", [("bold", "sp bold"), ("spoiler", "sp bold")]), + ("||a|b||", "a|b", [("spoiler", "a|b")]), + ("**a** and **b**", "a and b", [("bold", "a"), ("bold", "b")]), + ("**bold**text", "boldtext", [("bold", "bold")]), # ** works inside a word, like in Telegram's own Markdown + ("(_paren_)", "(paren)", [("italic", "paren")]), + ("- item *x*", "- item x", [("italic", "x")]), + (" **lead space** ", " lead space ", [("bold", "lead space")]), + ("`**not bold**`", "**not bold**", [("code", "**not bold**")]), # nothing is read inside code + ("`` a`b ``", " a`b ", [("code", " a`b ")]), # a longer fence lets a ` be part of the code + ("line1\nline2\n\nline4 **b**", "line1\nline2\n\nline4 b", [("bold", "b")]), + ("नमस्ते *दुनिया*", "नमस्ते दुनिया", [("italic", "दुनिया")]), + ], +) +def test_markdown_marks_become_formatting(src, text, found): + assert read(src) == (text, found, "markdown") + + +@pytest.mark.parametrize( + "src", + [ + "plain text", + "5 * 3 = 15", + "price: $5 * 2 and $6 * 3", + "2 ** 3 ** 4", + "snake_case_names and a*b*c", + "a_b_c_d", + "foo_bar_ baz", + "__a__b", + "x ~y~ z", + "|||x|||", + "Sub | Dub | Hindi", + "<3 [Group] Title", + r"C:\Users\me\file_name.txt", + "* list item\n* another", + ">> Download <<", + "[x](nonsense)", + "[x](javascript:alert(1))", + "[ ](https://x.com)", + "`unclosed", + "```python\nunclosed fence", + "``````", + "https://example.com/a_b_c", + "just a lone tag", + "never closed", + "1 < 2 > 0", + ], +) +def test_text_without_formatting_is_left_exactly_as_typed(src): + assert convert(src) == (src, [], None) + + +def test_marks_that_pair_with_nothing_stay_in_the_text(): + assert read("**bold* x") == ("*bold x", [("italic", "bold")], "markdown") # one * closes the first, one is left over + assert read("a *b") == ("a *b", [], None) + assert read("**a** and **b") == ("a and **b", [("bold", "a")], "markdown") + + +def test_a_mark_needs_to_touch_the_text_it_formats(): + assert convert("** not bold **") == ("** not bold **", [], None) + assert convert("* not italic *") == ("* not italic *", [], None) + assert read("**bold** and ** not **") == ("bold and ** not **", [("bold", "bold")], "markdown") + + +# -------------------------------------------------------------------------------------------------- escapes +def test_a_backslash_keeps_the_next_mark_as_typed(): + assert read("\\*not italic\\*") == ("*not italic*", [], "markdown") + assert read("\\# not heading \\[x\\] \\`t\\`") == ("# not heading [x] `t`", [], "markdown") + assert read("**a \\*b\\* c**") == ("a *b* c", [("bold", "a *b* c")], "markdown") + assert read("\\\\**x**") == ("\\x", [("bold", "x")], "markdown") # an escaped backslash does not escape the mark + assert read("\\_\\_x\\_\\_") == ("__x__", [], "markdown") + + +def test_a_backslash_before_anything_else_is_just_a_backslash(): + assert read("x\\—y *a*") == ("x\\—y a", [("italic", "a")], "markdown") + assert read("path\\to *x*") == ("path\\to x", [("italic", "x")], "markdown") + + +# ---------------------------------------------------------------------------------------------------- links +@pytest.mark.parametrize( + "src, label, url", + [ + ("[text](https://t.me/name)", "text", "https://t.me/name"), + ("[x](t.me/name)", "x", "https://t.me/name"), # a link without https:// gets it + ("[x](example.com/path?q=1)", "x", "https://example.com/path?q=1"), + ("[x](tg://resolve?domain=x)", "x", "tg://resolve?domain=x"), + ("[w](https://en.wikipedia.org/wiki/Foo_(bar))", "w", "https://en.wikipedia.org/wiki/Foo_(bar)"), + ("[a\\]b](https://x.com)", "a]b", "https://x.com"), + ("[**bold link**](https://x.com)", "bold link", "https://x.com"), + ], +) +def test_markdown_links(src, label, url): + text, found, how = read(src) + assert (text, how) == (label, "markdown") and ("url", label) in found + assert entity(src, "url", u=url)["l"] == utf16_len(label) + + +def test_two_links_in_one_line_and_a_link_next_to_text(): + text, found, _ = read("[a](https://x.com) and [b](https://y.com)") + assert (text, found) == ("a and b", [("url", "a"), ("url", "b")]) + assert [e["u"] for e in convert("[a](https://x.com) and [b](https://y.com)")[1]] == ["https://x.com", "https://y.com"] + assert read("see [here](https://x.com)!") == ("see here!", [("url", "here")], "markdown") + + +def test_a_link_typed_as_it_is_is_not_cut_up_by_marks_inside_it(): + assert convert("https://example.com/a_b_c and https://t.me/x_y_z?start=1") == ( + "https://example.com/a_b_c and https://t.me/x_y_z?start=1", [], None) + text, found, _ = read("**https://example.com/a_b**") + assert text == "https://example.com/a_b" and found == [("bold", "https://example.com/a_b")] + assert read("_see https://example.com/x_y now_") == ("see https://example.com/x_y now", [("italic", "see https://example.com/x_y now")], "markdown") + + +@pytest.mark.parametrize("raw", ["https://t.me/x", "t.me/x", "tg://resolve?domain=x", "ton://transfer/abc", "example.com/a?b=c#d", " https://x.com "]) +def test_clean_url_accepts_links(raw): + url = clean_url(raw) + assert url is not None and url.startswith(("https://", "http://", "tg://", "ton://")) + + +@pytest.mark.parametrize("raw", [None, "", "x", "nonsense", "javascript:alert(1)", "https://", "tg://", "a b", "https://x.com/a b", "https://x.com/" + "a" * 2001, "file:///etc/passwd"]) +def test_clean_url_refuses_what_is_no_link(raw): + assert clean_url(raw) is None + + +# --------------------------------------------------------------------------------------------------- quotes +def test_a_line_that_starts_with_a_greater_than_sign_is_quoted(): + assert read("> quote\nplain") == ("quote\nplain", [("quote", "quote")], "markdown") + assert entity("> quote\nplain", "quote", c=False) + assert read(">no space") == ("no space", [("quote", "no space")], "markdown") + + +def test_following_lines_make_one_quote_and_a_gap_ends_it(): + assert read("> a\n> b\n\nplain\n> c") == ("a\nb\n\nplain\nc", [("quote", "a\nb"), ("quote", "c")], "markdown") + assert read("intro\n> a\n> b\noutro") == ("intro\na\nb\noutro", [("quote", "a\nb")], "markdown") + + +def test_a_quote_may_hold_other_formatting(): + assert read("> **bold** inside") == ("bold inside", [("quote", "bold inside"), ("bold", "bold")], "markdown") + + +def test_an_expandable_quote_starts_with_and_ends_with_the_marks(): + assert read("**> exp\n> more||\nafter") == ("exp\nmore\nafter", [("quote", "exp\nmore")], "markdown") + assert entity("**> exp\n> more||\nafter", "quote", c=True) + assert entity("**> only one line||", "quote", c=True) + + +def test_two_greater_than_signs_are_decoration_not_a_quote(): + assert convert(">> Download <<") == (">> Download <<", [], None) + assert read(">> Download <<\n**x**") == (">> Download <<\nx", [("bold", "x")], "markdown") + + +def test_text_before_a_quote_keeps_its_offsets(): + text, ents, _ = convert("🙂 head\n> quoted *it*\ntail") + assert text == "🙂 head\nquoted it\ntail" + assert [(e["k"], piece(text, e)) for e in sorted(ents, key=lambda e: (e["o"], -e["l"]))] == [("quote", "quoted it"), ("italic", "it")] + + +# -------------------------------------------------------------------------------------------- code blocks +def test_fenced_code_with_and_without_a_language(): + assert read("```python\nprint(1)\n```") == ("print(1)", [("pre", "print(1)")], "markdown") + assert entity("```python\nprint(1)\n```", "pre", g="python") + assert entity("```\nx = 1\n```", "pre", g="") + assert entity("```code```", "pre", g="") + assert entity("```c++\nint x;\n```", "pre", g="c++") + + +def test_text_around_a_code_block_is_read_and_the_code_inside_is_not(): + text, found, how = read("intro **a**\n```py\n**x**\nb\n```\noutro *c*") + assert how == "markdown" and text == "intro a\n**x**\nb\noutro c" + assert found == [("bold", "a"), ("pre", "**x**\nb"), ("italic", "c")] + + +def test_an_unclosed_fence_is_text(): + assert convert("```python\nx") == ("```python\nx", [], None) + + +# ------------------------------------------------------------------------------------------------ emoji +def test_a_custom_emoji_is_written_like_an_image_link(): + text, found, how = read("![🙂](tg://emoji?id=5368324170671202286)") + assert (text, found, how) == ("🙂", [("emoji", "🙂")], "markdown") + assert entity("![🙂](tg://emoji?id=5368324170671202286)", "emoji", d=5368324170671202286)["l"] == 2 # two UTF-16 units + + +def test_offsets_count_utf16_units_not_characters(): + text, ents, _ = convert("🙂🙂 **bold** ![🙂](tg://emoji?id=1) _it_") + assert text == "🙂🙂 bold 🙂 it" + by_kind = {e["k"]: e for e in ents} + assert (by_kind["bold"]["o"], by_kind["bold"]["l"]) == (5, 4) # 2 emoji x 2 units + a space + assert (by_kind["emoji"]["o"], by_kind["emoji"]["l"]) == (10, 2) + assert (by_kind["italic"]["o"], by_kind["italic"]["l"]) == (13, 2) + assert all(piece(text, e) for e in ents) + + +# -------------------------------------------------------------------------------------------------- HTML +def test_html_tags_become_formatting(): + src = ('bold it un st sp c
block
' + 'link
q
') + assert read(src) == ( + "bold it un st sp c block link q", + [("bold", "bold"), ("italic", "it"), ("underline", "un"), ("strike", "st"), ("spoiler", "sp"), ("code", "c"), + ("pre", "block"), ("url", "link"), ("quote", "q")], + "html", + ) + assert entity(src, "url", u="https://t.me/x") and entity(src, "quote", c=False) and entity(src, "pre", g="") + + +@pytest.mark.parametrize( + "src, kind", + [ + ("x", "bold"), ("x", "italic"), ("x", "underline"), ("x", "strike"), + ("x", "strike"), ('x', "spoiler"), ("x", "bold"), + ], +) +def test_the_other_spellings_of_the_tags(src, kind): + assert read(src) == ("x", [(kind, "x")], "html") + + +def test_html_entities_and_line_breaks(): + assert read("a & b <c> "d" 'e' x") == ("a & b \"d\" 'e' x", [("bold", "x")], "html") + assert read("a
b
cd") == ("a\nb\ncd", [("bold", "d")], "html") + assert read("bold\nit\n") == ("bold\nit\n", [("bold", "bold"), ("italic", "it")], "html") + + +def test_nested_tags(): + assert read("a b c") == ("a b c", [("bold", "a b c"), ("italic", "b")], "html") + assert read("x") == ("x", [("bold", "x"), ("italic", "x")], "html") + assert read('x') == ("x", [("bold", "x"), ("url", "x")], "html") + + +def test_pre_with_a_language_and_blockquote_expandable_and_custom_emoji(): + assert entity('
x = 1
', "pre", g="python") + assert read('
x = 1
') == ("x = 1", [("pre", "x = 1")], "html") + assert entity("
no lang
", "pre", g="") + assert entity("
long
", "quote", c=True) + assert entity("
a\nb
", "quote", c=False)["l"] == 3 + assert entity('🙂', "emoji", d=123)["l"] == 2 + assert read('🙂y') == ("🙂y", [("bold", "y")], "html") # no usable id: plain emoji + + +def test_code_is_shown_as_typed_even_with_tags_in_it(): + assert read("<b>") == ("", [("code", "")], "html") + assert read("
x
") == ("x", [("pre", "x")], "html") + assert read("ab") == ("ab", [("code", "a"), ("code", "b")], "html") + + +def test_tags_the_bot_does_not_know_stay_as_typed(): + assert read("x
y
") == ("x
y
", [("bold", "x")], "html") + assert read('xy') == ('xy', [("bold", "y")], "html") + assert read("1 < 2 and x") == ("1 < 2 and x", [("bold", "x")], "html") + + +def test_a_tag_of_the_same_kind_inside_another_adds_nothing(): + assert read("a b c") == ("a b c", [("bold", "a b c")], "html") + assert read("a b") == ("a b", [("bold", "a b")], "html") + assert read("
a
b
") == ("ab", [("quote", "ab")], "html") + nested_links = 'a b' + assert read(nested_links) == ("a b", [("url", "a b")], "html") and entity(nested_links, "url", u="https://x.com") + # other kinds still nest, and two separate ones stay two + assert read("a b c") == ("a b c", [("bold", "a b"), ("italic", "b"), ("bold", "c")], "html") + + +def test_unclosed_and_stray_tags_do_no_harm(): + assert read("unclosed x") == ("unclosed x", [("italic", "unclosed x"), ("bold", "x")], "html") # ends with the text + assert read("x stray") == ("x
stray", [("bold", "x")], "html") + assert read("xy") == ("xy", [("italic", "y")], "html") # an empty tag formats nothing + + +def test_unsafe_or_missing_links_lose_the_link_but_keep_the_text(): + assert read('xy') == ("xy", [("bold", "y")], "html") + assert read("no hrefy") == ("no hrefy", [("bold", "y")], "html") + assert entity('y', "url", u="https://t.me/x") + + +@pytest.mark.parametrize( + "src, yes", + [ + ("x", True), ("x", True), ('y', True), ("
q
", True), + ("a and b", True), ("s", True), ("
x
", True), + ("x", False), ("x ", False), ("a < b > c", False), ("<3", False), ("
x
", False), ("**x**", False), ("", False), + ], +) +def test_html_is_recognised_by_a_tag_with_its_closing_tag(src, yes): + assert looks_like_html(src) is yes + + +def test_html_wins_over_markdown_in_the_same_text(): + assert read("x **y**") == ("x **y**", [("bold", "x")], "html") + + +# ------------------------------------------------------------------------------------------- the choice +def test_text_with_nothing_to_read_comes_back_untouched(): + for src in ("", "hello", " spaced ", "line\n\nbreak", "100% sure #tag @name /command"): + assert convert(src) == (src, [], None) + + +def test_a_reader_that_fails_leaves_the_text_as_typed(monkeypatch): + def boom(*a, **k): + raise RuntimeError("bug") + + monkeypatch.setattr(richtext, "from_markdown", boom) + assert convert("**x**") == ("**x**", [], None) + monkeypatch.setattr(richtext, "from_html", boom) + assert convert("x") == ("x", [], None) + + +# ----------------------------------------------------------------- what the bot does with a message +def test_telegram_formatting_wins_over_anything_typed(): + ents = [types.MessageEntityItalic(0, 5), types.MessageEntityTextUrl(6, 4, "https://x.com"), types.MessageEntityBlockquote(11, 3, True)] + text, stored, how = message_text(msg("**x** y z", ents)) + assert text == "**x** y z" and how is None + assert stored == [{"k": "italic", "o": 0, "l": 5}, {"k": "url", "o": 6, "l": 4, "u": "https://x.com"}, {"k": "quote", "o": 11, "l": 3, "c": True}] + + +def test_links_and_mentions_telegram_finds_by_itself_are_not_formatting(): + src = "see https://x.com and @name and **bold**" + auto = [types.MessageEntityUrl(4, 13), types.MessageEntityMention(22, 5)] + text, stored, how = message_text(msg(src, auto)) + assert how == "markdown" and text == "see https://x.com and @name and bold" + assert [(e["k"], piece(text, e)) for e in stored] == [("bold", "bold")] + + +def test_typed_formatting_can_be_switched_off(): + assert message_text(msg("**x** y"), enabled=False) == ("**x** y", [], None) + assert message_text(msg("**x**"), enabled=True)[2] == "markdown" + + +def test_empty_messages(): + assert message_text(msg("")) == ("", [], None) + assert message_text(SimpleNamespace(raw_text=None, entities=None)) == ("", [], None) + + +def test_extract_content_says_how_the_text_was_read(): + c = extract_content(msg("**Hi** there")) + assert (c["text"], c["entities"], c.how) == ("Hi there", [{"k": "bold", "o": 0, "l": 2}], "markdown") + assert c["media_kind"] is None and c["media_file_id"] is None + assert extract_content(msg("Hi")).how == "html" + assert extract_content(msg("plain")).how is None + assert extract_content(msg("**Hi**"), markup=False)["text"] == "**Hi**" + native = extract_content(msg("**Hi**", [types.MessageEntityBold(0, 6)])) + assert native["text"] == "**Hi**" and native.how is None and native["entities"] == [{"k": "bold", "o": 0, "l": 6}] + + +def test_the_note_names_the_format_that_was_read(): + assert markup_note(None) == "" and markup_note(None, "\n") == "" + assert markup_note("markdown").startswith("🎨 Formatting read from Markdown") and markup_note("markdown").endswith("\n\n") + assert markup_note("html", "\n").startswith("🎨 Formatting read from HTML") and markup_note("html", "\n").endswith("/formatting.\n") + + +def test_the_length_limit_counts_the_text_the_formatting_leaves(): + assert len(extract_content(msg("**" + "x" * 4094 + "**"))["text"]) == 4094 # the marks do not count + with pytest.raises(UserError): + extract_content(msg("x" * 4097)) + with pytest.raises(UserError): + extract_content(msg("")) # nothing is left once the empty tag is read + + +# --------------------------------------------------------------------------- any input, always usable +KINDS = {"bold", "italic", "underline", "strike", "spoiler", "code", "pre", "url", "quote", "emoji"} +TOKENS = [ + "*", "**", "***", "_", "__", "~~", "~", "||", "|", "`", "``", "```", "```py\n", "[", "]", "(", ")", "](", "[a](https://x.com)", + "[a](t.me/x)", "![🙂](tg://emoji?id=5)", "!", "\\", "\\*", ">", ">>", "**>", "\n", "\n\n", " ", "a", "bc", "dé", "🙂", "नमस्ते", + "https://x.com/a_b_c", "http://", "tg://x", "<", "", "", "", "", "", "", "", "", "", "", + "
", "
", "
", "
", "
", "
", "
", + "", "", "", "", "", "", "", + "", "", "
", "
", "&", "<", ">", "&", "😀", "", "", "", +] + + +def is_subsequence(small, big): + it = iter(big) + return all(ch in it for ch in small) + + +def check_entities(text, ents): + n = utf16_len(text) + last = (-1, 0) + for e in ents: + assert e["k"] in KINDS, e + assert e["l"] > 0 and e["o"] >= 0 and e["o"] + e["l"] <= n, (text, e) + assert (e["o"], -e["l"]) >= last, "outer entities first" + last = (e["o"], -e["l"]) + if e["k"] == "url": + assert e["u"].startswith(("http://", "https://", "tg://", "ton://")), e + for i, a in enumerate(ents): # entities are nested or apart, never partly over each other; none sits in one of its own kind + for b in ents[i + 1:]: + a_end, b_end = a["o"] + a["l"], b["o"] + b["l"] + nested = (a["o"] <= b["o"] and b_end <= a_end) or (b["o"] <= a["o"] and a_end <= b_end) + assert not (b["o"] < a_end and a["o"] < b_end) or nested, (text, a, b) + if a["k"] == b["k"] and a["k"] in richtext._NO_NEST: + assert not nested, (text, a, b) + assert len(de_entities(ents)) == len(ents) # Telethon can build every one of them + + +def test_whatever_is_typed_the_readers_never_fail_and_never_point_outside_the_text(): + rng = random.Random(20261029) + for _ in range(4000): + src = "".join(rng.choice(TOKENS) for _ in range(rng.randint(1, 40))) + text, ents = from_markdown(src) # called directly: convert() would hide a crash + check_entities(text, ents) + assert is_subsequence(text, src), (src, text) # the Markdown reader only takes marks away, it invents nothing + text, ents = from_html(src) + check_entities(text, ents) + text, ents, how = convert(src) + check_entities(text, ents) + assert how in (None, "html", "markdown") + if how is None: + assert (text, ents) == (src, []) + + +@pytest.mark.parametrize( + "src", + ["[" * 4000, "*" * 4000, "_" * 4000, "`" * 4000, "**a " * 1000, "[a](" * 1000, "a*" * 2000, "![" * 2000, "\\" * 4000, "(" * 4000, + "> " * 2000, "||a " * 1300, "~~a " * 1300, "http://" * 500, "[a](https://x.com" * 200, "" * 1300 + "" * 1300, + '' * 300 + "" * 300, "<" * 4000, "&" * 4000, "*a_" * 1300 + "_a*" * 1300, "[[[a]]](" * 500], + ids=lambda s: f"{s[:8]!r}x{len(s)}", +) +def test_a_hostile_message_is_read_quickly(src): + started = time.monotonic() + text, ents, _ = convert(src) + assert time.monotonic() - started < 3.0 + check_entities(text, ents) + + +# ---------------------------------------------------------------------------------------- the cheat sheet +def test_the_cheat_sheet_is_valid_telegram_html_and_fits_one_message(): + text, ents = telethon_html.parse(CHEAT_SHEET) + assert 0 < len(text) < 4096 and len(ents) <= 100 + assert all(0 <= e.offset and e.offset + e.length <= utf16_len(text) for e in ents) + assert "Markdown" in text and "HTML" in text and "/formatting" not in text + + +@pytest.mark.parametrize( + "snippet, kind", + [ + ("**bold**", "bold"), ("*italic*", "italic"), ("_italic_", "italic"), ("__underline__", "underline"), ("~~strike~~", "strike"), + ("||spoiler||", "spoiler"), ("`code`", "code"), ("```code block```", "pre"), ("[text](https://t.me/name)", "url"), ("> quote", "quote"), + ("bold", "bold"), ("italic", "italic"), ("underline", "underline"), ("strike", "strike"), + ("spoiler", "spoiler"), ("code", "code"), ("
block
", "pre"), + ('link', "url"), ("
quote
", "quote"), + ], +) +def test_every_example_in_the_cheat_sheet_does_what_it_says(snippet, kind): + shown = {html.unescape(s) for s in re.findall(r"(.*?)", CHEAT_SHEET, re.S)} + assert snippet in shown, "the example is not in the cheat sheet any more" + assert kind in {k for k, _ in read(snippet)[1]} + + +def test_the_example_post_in_the_cheat_sheet_reads_as_it_promises(): + example = html.unescape(re.search(r"
(.*?)
", CHEAT_SHEET, re.S).group(1)) + text, found, how = read(example) + assert how == "markdown" + assert found == [("bold", "Attack on Titan"), ("underline", "Hindi"), ("spoiler", "spoiler"), ("url", "Watch here")] + assert entity(example, "url", u="https://t.me/yourchannel") + + +def test_the_formatting_command_sends_the_cheat_sheet_and_the_help_lists_it(tmp_path): + async def go(): + app = App(tmp_path) + await app.start() + await app.text("/formatting") + assert app.out.last_text == CHEAT_SHEET + await app.text("/help") + assert "/formatting" in norm(app.out.last_text) + await app.db.close() + + import asyncio + + asyncio.run(go()) + + +def test_stored_entities_survive_the_round_trip_through_telethon(): + text, stored, _ = convert("**a** [b](https://x.com) > not a quote here\n> q\n```py\nx\n```") + again = ser_entities(de_entities(stored)) + assert again == stored diff --git a/tests/test_shift.py b/tests/test_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..ef4d772140c3a5103676842799e441131328be5f --- /dev/null +++ b/tests/test_shift.py @@ -0,0 +1,526 @@ +"""/shift: posts of one channel copied into another - range, buttons, replies, links between the posts, undo.""" +import asyncio +from types import SimpleNamespace + +import pytest +from telethon import functions, types + +from app.channelref import classify_ref, resolve_channel +from app.common import UserError +from app.handlers.shift import parse_shift_args +from app.repost_engine import RepostOptions, plan_repost +from app.shift_engine import delete_shift_copies, run_shift +from app.tgutil import button_url + +from .dbutil import db_url_for, fresh_db +from .fakes import FakeChannelClient, cb_btn, make_msg, markup, photo_media, service_msg, url_btn +from .harness import App, norm +from .test_repost_flow import fill + +SRC = SimpleNamespace(id=1, access_hash=5, title="Anime Source", username="srcch") + + +def source_posts(): + return { + 1: make_msg(1, "Welcome", [types.MessageEntityBold(0, 7)]), + 2: make_msg( + 2, "Click below", + markup=markup([url_btn("Download", "https://t.me/goku?start=AAA")], [cb_btn("👍 3", b"r")]), + ), + 3: make_msg(3, "Caption with link", [types.MessageEntityTextUrl(13, 4, "https://t.me/srcch/5")], media=photo_media(31)), + 4: service_msg(4), + 5: make_msg(5, "Fifth", reply_to=2, pinned=True), + 6: make_msg(6, "", media=photo_media(61), grouped_id=60), + 7: make_msg(7, "album caption", media=photo_media(62), grouped_id=60), + 8: make_msg(8, "See https://t.me/srcch/1 and https://t.me/c/1/2 and https://t.me/elsewhere/9"), + } + + +def old_posts(): + """Posts the destination already has, so that the copies get ids that differ from the originals'.""" + return {i: make_msg(i, f"existing {i}", out=True) for i in range(1, 11)} + + +def two_channels(src_msgs=None, dst_msgs=None): + src = FakeChannelClient(source_posts() if src_msgs is None else src_msgs, username="srcch", title="Anime Source") + dst = src.add_channel(FakeChannelClient(old_posts() if dst_msgs is None else dst_msgs, username="dstch", cid=2, title="Anime Backup")) + return src, dst + + +async def engine_setup(tmp_path, src, first=1, last=8): + db = await fresh_db(db_url_for(tmp_path)) + await db.save_channel(2, 6, "Anime Backup", "dstch", 1) + dst_row = await db.get_channel(2) + await db.create_shift("s1", src=SRC, dst_channel_id=2, first_id=first, last_id=last, user_id=1) + return db, dst_row, await db.get_shift("s1") + + +def reply_of(m): + return m.reply_to.reply_to_msg_id if m.reply_to else None + + +def run(coro): + return asyncio.run(coro) + + +# ------------------------------------------------------------------------------------- the command line +def test_arguments_are_read_as_source_destination_and_an_optional_range(): + def read(raw): + *four, flags = parse_shift_args(raw) + assert (flags.links, flags.profile) == (False, False) # no extras unless they are asked for + return tuple(four) + + assert read("@a @b") == ("@a", "@b", None, None) + assert read("@a @b 15 20") == ("@a", "@b", 15, 20) + assert read("@a @b 20 15") == ("@a", "@b", 15, 20) # either order + assert read("@a @b 15") == ("@a", "@b", 15, 15) # one id = just that post + assert read("https://t.me/+AbCdEfGhIj -1001234567890") == ("https://t.me/+AbCdEfGhIj", "-1001234567890", None, None) + for bad in ("", "@a", "@a @b x", "@a @b 0", "@a @b 1 2 3", "@a @b -5", "-c", "-c -all", "@a -c", "@a @b -c x"): + with pytest.raises(ValueError): + parse_shift_args(bad) + + +def test_the_two_extras_can_be_given_separately_together_in_any_order_or_not_at_all(): + def read(raw): + src, dst, first, last, flags = parse_shift_args(raw) + assert (src, dst) == ("@old", "@new") + return (first, last), (flags.links, flags.profile) + + assert read("@old @new") == ((None, None), (False, False)) + assert read("@old @new -c") == ((None, None), (True, False)) + assert read("@old @new -all") == ((None, None), (False, True)) + assert read("@old @new -c -all") == ((None, None), (True, True)) + assert read("@old @new -all -c") == ((None, None), (True, True)) + assert read("@old @new - all") == ((None, None), (False, True)) # typed with a space + assert read("@old @new - c - all") == ((None, None), (True, True)) + assert read("@old @new -ALL -C") == ((None, None), (True, True)) # case does not matter + assert read("@old @new --all --c") == ((None, None), (True, True)) # a double dash is understood too + assert read("@old @new 15 20 -c") == ((15, 20), (True, False)) # with a range + assert read("-c @old @new -all 15 20") == ((15, 20), (True, True)) # in front, or between the other words + assert read("@old -c @new 15 -all 20") == ((15, 20), (True, True)) + assert read("@old @new -c -c") == ((None, None), (True, False)) # twice is the same as once + + +def test_a_channel_id_is_not_mistaken_for_an_option_and_unknown_options_are_refused(): + src, dst, first, last, flags = parse_shift_args("-1001234567890 -1009876543210 -c") + assert (src, dst, flags.links) == ("-1001234567890", "-1009876543210", True) + for bad in ("@a @b -x", "@a @b --everything", "@a @b -call"): + with pytest.raises(ValueError, match="Unknown option"): + parse_shift_args(bad) + + +def test_every_kind_of_channel_reference_is_told_apart(): + assert classify_ref("@srcch") == ("username", "srcch") + assert classify_ref("https://t.me/srcch") == ("username", "srcch") + assert classify_ref("https://t.me/srcch/15") == ("username", "srcch") + assert classify_ref("-1001234567890") == ("id", 1234567890) + assert classify_ref("https://t.me/c/1234567890/5") == ("id", 1234567890) + assert classify_ref("https://t.me/+AbCdEfGhIjKl") == ("invite", "AbCdEfGhIjKl") + assert classify_ref("t.me/joinchat/AbCdEfGhIjKl") == ("invite", "AbCdEfGhIjKl") + assert classify_ref("tg://join?invite=AbCdEfGhIjKl") == ("invite", "AbCdEfGhIjKl") + assert classify_ref("???") == (None, None) + + +def test_channels_are_found_by_name_id_or_invite_link(tmp_path): + async def go(): + app = App(tmp_path) + await app.start() + src, dst = two_channels() + app.tg.registry = src.registry + app.tg.registry[1] = app.tg + app.tg.username, app.tg.title = "srcch", "Anime Source" + app.tg.add_channel(dst) + await app.db.save_channel(1, 5, "Anime Source", "srcch", 1) # registered + # registered: found in the database, whatever the spelling + for text in ("@srcch", "SRCCH", "https://t.me/srcch/12", "1"): + ref = await resolve_channel(app.ctx, text) + assert (ref.id, ref.title, ref.registered) == (1, "Anime Source", True), text + # not registered: asked from Telegram by name, by id (a channel the bot has met) or by invite link + ref = await resolve_channel(app.ctx, "@dstch") + assert (ref.id, ref.title, ref.username, ref.registered) == (2, "Anime Backup", "dstch", False) + assert (await resolve_channel(app.ctx, "2")).id == 2 + dst.invite_hash = "AbCdEfGhIjKl" + assert (await resolve_channel(app.ctx, "https://t.me/+AbCdEfGhIjKl")).id == 2 + # things that cannot be used say why + for text, part in ( + ("???", "not a channel I understand"), + ("@nosuchchannel", "couldn't find a channel"), + ("99", "don't know a channel with the id 99"), + ("https://t.me/+ZzZzZzZzZz", "invite link doesn't work"), + ): + with pytest.raises(UserError, match=part): + await resolve_channel(app.ctx, text) + await app.db.close() + + run(go()) + + +def test_a_group_or_a_user_is_not_a_channel(tmp_path): + async def go(): + app = App(tmp_path) + await app.start() + group = FakeChannelClient({}, username="agroup", cid=3) + group._channel_obj = lambda: types.Channel(id=3, title="G", photo=types.ChatPhotoEmpty(), date=None, access_hash=1, username="agroup", megagroup=True) + app.tg.add_channel(group) + with pytest.raises(UserError, match="group, not a channel"): + await resolve_channel(app.ctx, "@agroup") + await app.db.close() + + run(go()) + + +# ------------------------------------------------------------------------------------------ the engine +def test_posts_arrive_in_the_other_channel_with_everything_they_had(tmp_path): + async def go(): + src, dst = two_channels() + db, dst_row, shift = await engine_setup(tmp_path, src) + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert (res.copied_units, res.copied_messages, res.failed, res.aborted) == (6, 7, [], None) + new = {i: m for i, m in dst.msgs.items() if i > 10} + assert list(new) == [11, 12, 13, 14, 15, 16, 17] # same order as the originals + + assert new[11].message == "Welcome" and isinstance(new[11].entities[0], types.MessageEntityBold) + # the button post: link button kept, the other bot's 👍 button is not copied (it would be dead) + rows = new[12].reply_markup.rows + assert len(rows) == 1 and button_url(rows[0].buttons[0]) == "https://t.me/goku?start=AAA" and rows[0].buttons[0].text == "Download" + assert new[13].media.photo.id == 31 + # a reply answers the COPY of the post it answered; a pin is not copied + assert reply_of(new[14]) == 12 and not new[14].pinned + assert new[15].grouped_id and new[15].grouped_id == new[16].grouped_id and new[16].message == "album caption" + # links to other source posts follow the content: backward ones at once, forward ones afterwards + assert new[17].message == "See https://t.me/dstch/11 and https://t.me/dstch/12 and https://t.me/elsewhere/9" + link = [e for e in new[13].entities if isinstance(e, types.MessageEntityTextUrl)][0] + assert link.url == "https://t.me/dstch/14" and (link.offset, link.length) == (13, 4) + assert (res.final.relinked, res.final.links) == (1, 1) + + # the source was only read + assert sorted(src.msgs) == [1, 2, 3, 4, 5, 6, 7, 8] and src.msgs[5].pinned + assert src.delete_requests == [] and src.edits == [] + assert not any(isinstance(r, (functions.messages.SendMessageRequest, functions.messages.SendMediaRequest)) for r in src.requests) + + # recorded for My posts: only the destination has posts, exactly as they look there + assert await db.shift_pairs("s1") == [(1, 11), (2, 12), (3, 13), (5, 14), (6, 15), (7, 16), (8, 17)] + assert await db.sent_posts(1) == [] + mine = {p.message_id: p for p in await db.sent_posts(2)} + assert sorted(mine) == [11, 12, 13, 14, 15, 16, 17] and mine[12].source == "bot" + assert mine[12].buttons == [[{"t": "Download", "u": "https://t.me/goku?start=AAA"}]] + assert mine[13].entities[0]["u"] == "https://t.me/dstch/14" + assert mine[17].text == new[17].message and mine[13].media_kind == "photo" + await db.close() + + run(go()) + + +def test_only_the_posts_in_the_range_are_copied(tmp_path): + async def go(): + src, dst = two_channels() + db, dst_row, shift = await engine_setup(tmp_path, src, first=2, last=3) + plan = await plan_repost(src, SRC, RepostOptions(), first_id=2, last_id=3) + assert (plan.first, plan.last, plan.units, plan.partial) == (2, 3, 2, True) + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert (res.copied_units, res.failed) == (2, []) + assert [m.message for i, m in sorted(dst.msgs.items()) if i > 10] == ["Click below", "Caption with link"] + await db.close() + + run(go()) + + +def test_a_reply_to_a_post_outside_the_range_is_copied_without_the_reply(tmp_path): + async def go(): + src, dst = two_channels() + db, dst_row, shift = await engine_setup(tmp_path, src, first=5, last=5) + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert (res.copied_units, res.replies, res.reply_dropped) == (1, 0, 1) + assert reply_of(dst.msgs[11]) is None + await db.close() + + run(go()) + + +def test_a_source_that_forbids_saving_is_rebuilt_from_its_parts(tmp_path): + async def go(): + src, dst = two_channels() + src.restrict_forwards = True + db, dst_row, shift = await engine_setup(tmp_path, src) + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert (res.failed, res.forwarded, res.rebuilt) == ([], 0, 6) + new = {i: m for i, m in dst.msgs.items() if i > 10} + assert new[15].grouped_id == new[16].grouped_id and new[13].media.photo.id == 31 + assert reply_of(new[14]) == 12 + await db.close() + + run(go()) + + +def test_a_stopped_shift_continues_without_copying_anything_twice(tmp_path): + async def go(): + src, dst = two_channels() + db, dst_row, shift = await engine_setup(tmp_path, src) + calls = [] + + async def prog(res): + calls.append(res.copied_units) + + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0, progress=prog, should_stop=lambda: len(calls) >= 2) + assert res.stopped and res.copied_units == 2 and res.final is None + again = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert (again.copied_units, again.skipped_done, again.failed) == (4, 2, []) + assert sorted(i for i in dst.msgs if i > 10) == [11, 12, 13, 14, 15, 16, 17] # no duplicates + # the reply of the 3rd copy found the copy made in the first run + assert reply_of(dst.msgs[14]) == 12 + await db.close() + + run(go()) + + +def test_undo_removes_only_the_copies(tmp_path): + async def go(): + src, dst = two_channels() + db, dst_row, shift = await engine_setup(tmp_path, src) + await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + res = await delete_shift_copies(src, db, dst_row, shift, delay=0) + assert (res.deleted, res.remaining, res.error) == (7, 0, None) + assert sorted(dst.msgs) == list(range(1, 11)) and sorted(src.msgs) == [1, 2, 3, 4, 5, 6, 7, 8] + assert await db.sent_posts(2) == [] and await db.shift_pairs("s1") == [] + assert (await db.shift_counts("s1"))["new_left"] == 0 + await db.close() + + run(go()) + + +def test_a_post_that_was_shifted_before_is_known(tmp_path): + async def go(): + src, dst = two_channels() + db, dst_row, shift = await engine_setup(tmp_path, src) + await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert await db.shifted_ids(1, 2, 1, 5) == {1, 2, 3, 5} + assert await db.shifted_ids(1, 3, 1, 5) == set() and await db.shifted_ids(2, 1, 1, 5) == set() + await db.mark_shift_deleted("s1", 2, [11]) + assert await db.shifted_ids(1, 2, 1, 5) == {2, 3, 5} + await db.close() + + run(go()) + + +# ---------------------------------------------------------------------------- as the owner experiences it +async def shift_app(tmp_path, **cfg): + cfg.setdefault("edit_delay", 0.0) + app = App(tmp_path, **cfg) + await app.start() + app.tg.username, app.tg.title = "srcch", "Anime Source" + fill(app.tg, source_posts()) + dst = app.tg.add_channel(FakeChannelClient(old_posts(), username="dstch", cid=2, title="Anime Backup")) + await app.db.save_channel(1, 5, "Anime Source", "srcch", 1) + await app.db.save_channel(2, 6, "Anime Backup", "dstch", 1) + return app, dst + + +def test_usage_and_bad_commands_are_explained(tmp_path): + async def go(): + app, _ = await shift_app(tmp_path) + await app.text("/shift") + text = norm(app.out.last_text) + assert "Usage: /shift [from_id] [to_id]" in text and "15 20" in text + for args, part in ( + ("@srcch", "Give the source and the destination"), + ("@srcch @dstch x", "“x” is not a message id"), + ("@srcch @srcch", "same channel"), + ("@srcch @nosuch", "couldn't find a channel"), + ): + await app.text(f"/shift {args}") + assert part in norm(app.out.last_text), (args, norm(app.out.last_text)) + assert not any(isinstance(r, functions.messages.SendMessageRequest) for r in app.tg.requests) + await app.db.close() + + run(go()) + + +def test_the_plan_is_shown_before_anything_is_copied(tmp_path): + async def go(): + app, dst = await shift_app(tmp_path) + await app.text("/shift @srcch @dstch 2 5") + text = norm(app.out.last_text) + assert "Shift plan" in text and "From Anime Source → Anime Backup" in text + assert "Post ids 2-5" in text and "3 posts to copy" in text # 2, 3 and 5 (4 is a service message) + assert "1 service message(s)" in text and "1 post(s) answer another post" in text + assert "1 link(s) in 1 post(s) point at other posts of Anime Source" in text + assert "Nothing is changed in Anime Source" in text + assert dst.requests == [] or not any(isinstance(r, functions.messages.SendMessageRequest) for r in dst.requests) + assert sorted(dst.msgs) == list(range(1, 11)) + await app.db.close() + + run(go()) + + +def test_cancel_and_an_old_button(tmp_path): + async def go(): + app, dst = await shift_app(tmp_path) + await app.text("/shift @srcch @dstch") + start = app.out.callback_data("Start copying") + await app.press(app.out.callback_data("Cancel")) + assert "Cancelled" in norm(app.out.last_text) + await app.press(start) + assert "expired" in norm(app.out.last_text) + assert sorted(dst.msgs) == list(range(1, 11)) + await app.db.close() + + run(go()) + + +def test_the_whole_flow_copy_then_undo(tmp_path): + async def go(): + app, dst = await shift_app(tmp_path) + await app.text("/shift @srcch @dstch") + await app.press(app.out.callback_data("Start copying")) + done = norm(app.out.last_text) + assert "Anime Source → Anime Backup: 7 message(s) copied" in done and "registered in My posts" in done + assert "The source was not changed" in done and "1 link(s) in 1 post(s) now point at the new copies" in done + assert sorted(i for i in dst.msgs if i > 10) == [11, 12, 13, 14, 15, 16, 17] + assert len(await app.db.sent_posts(2)) == 7 + + await app.press(app.out.callback_data("Undo")) + assert "Remove the 7 copied message(s) from Anime Backup" in norm(app.out.last_text) + await app.press(app.out.callback_data("Yes, remove")) + assert "7 copied message(s) removed from Anime Backup" in norm(app.out.last_text) + assert sorted(dst.msgs) == list(range(1, 11)) and await app.db.sent_posts(2) == [] + sh = await app.db.open_shift() + assert sh is None # nothing is left open + await app.db.close() + + run(go()) + + +def test_without_arguments_a_finished_shift_can_still_be_undone(tmp_path): + """The result message of a finished shift may be far up the chat: /shift alone offers its Undo again.""" + async def go(): + app, dst = await shift_app(tmp_path) + before = len(app.out.log) + await app.text("/shift") # nothing was shifted yet: only the usage + assert len(app.out.log) - before == 1 and "Usage: /shift" in norm(app.out.last_text) + + await app.text("/shift @srcch @dstch") + await app.press(app.out.callback_data("Start copying")) + assert "7 message(s) copied" in norm(app.out.last_text) + + await app.text("/shift") + assert "Usage: /shift" in norm(app.out.log[-2][1]) # the usage first, the finished shift right under it + text = norm(app.out.last_text) + assert "Latest finished shift - you can still undo it" in text and "7 message(s) copied" in text + await app.press(app.out.callback_data("Undo")) + await app.press(app.out.callback_data("Yes, remove")) + assert "7 copied message(s) removed from Anime Backup" in norm(app.out.last_text) + assert sorted(dst.msgs) == list(range(1, 11)) + + before = len(app.out.log) + await app.text("/shift") # undone: nothing is left to offer + assert len(app.out.log) - before == 1 and "Latest finished shift" not in norm(app.out.last_text) + await app.db.close() + + run(go()) + + +def test_only_a_finished_shift_that_still_has_copies_is_offered(tmp_path): + async def go(): + app, dst = await shift_app(tmp_path) + await app.text("/shift @srcch @dstch") + await app.press(app.out.callback_data("Start copying")) + first = await app.db.last_finished_shift() + assert first is not None + # every copy of it was deleted some other way: nothing to undo, so nothing is offered + await app.db.mark_shift_deleted(first.id, 2, await app.db.shift_pending_new(first.id)) + assert await app.db.last_finished_shift() is None + before = len(app.out.log) + await app.text("/shift") + assert len(app.out.log) - before == 1 and "Latest finished shift" not in norm(app.out.last_text) + + # a newer shift is the one offered + await app.text("/shift @srcch @dstch") + await app.press(app.out.callback_data("Start copying")) + second = await app.db.last_finished_shift() + assert second is not None and second.id != first.id + await app.text("/shift") + assert "Latest finished shift" in norm(app.out.last_text) + assert app.out.callback_data("Undo") == f"sfu:{second.id}" + await app.db.close() + + run(go()) + + +def test_a_destination_the_bot_does_not_know_yet_becomes_one_of_its_channels(tmp_path): + async def go(): + app, dst = await shift_app(tmp_path) + await app.db.set_channel_active(2, False) + await app.text("/shift @srcch @dstch 1 1") + await app.press(app.out.callback_data("Start copying")) + assert "1 message(s) copied" in norm(app.out.last_text) + assert [c.id for c in await app.db.list_channels()] == [2, 1] or {c.id for c in await app.db.list_channels()} == {1, 2} + await app.db.close() + + run(go()) + + +def test_the_bot_must_be_allowed_to_post_in_the_destination(tmp_path): + async def go(): + app, dst = await shift_app(tmp_path) + dst.rights = dict(admin=True, post=False, edit=True, delete=True, invite=False, add_admins=False) + await app.text("/shift @srcch @dstch") + assert "needs the “Post messages” admin right in Anime Backup" in norm(app.out.last_text) + await app.db.close() + + run(go()) + + +def test_an_unreadable_source_is_explained(tmp_path): + async def go(): + app, dst = await shift_app(tmp_path) + app.tg.fail["GetMessagesRequest"] = __import__("telethon").errors.ChannelPrivateError(request=None) + await app.text("/shift @srcch @dstch") + text = norm(app.out.last_text) + assert "I can't read Anime Source" in text and "member of the source channel" in text + await app.db.close() + + run(go()) + + +def test_an_unfinished_shift_must_be_dealt_with_first(tmp_path): + async def go(): + app, dst = await shift_app(tmp_path) + await app.db.create_shift("old1", src=SRC, dst_channel_id=2, first_id=1, last_id=8, user_id=1) + await app.db.set_shift_status("old1", "stopped") + await app.text("/shift @srcch @dstch") + text = norm(app.out.last_text) + assert "unfinished shift between these two channels" in text and "stopped" in text + assert "Continue" in " ".join(t for row in app.out.last_buttons() for t in row) + await app.text("/shift") # without arguments it shows the same unfinished shift + assert "Unfinished shift" in norm(app.out.last_text) + # Continue copies what is left; the shift is over afterwards + await app.press(app.out.callback_data("Continue")) + assert "7 message(s) copied" in norm(app.out.last_text) + assert await app.db.open_shift() is None + await app.db.close() + + run(go()) + + +def test_copying_the_same_posts_twice_is_pointed_out(tmp_path): + async def go(): + app, dst = await shift_app(tmp_path) + await app.text("/shift @srcch @dstch 1 2") + await app.press(app.out.callback_data("Start copying")) + await app.text("/shift @srcch @dstch 1 3") + assert "2 of these posts were already shifted into Anime Backup before" in norm(app.out.last_text) + await app.db.close() + + run(go()) + + +def test_shift_is_for_the_owner_only(tmp_path): + async def go(): + app, dst = await shift_app(tmp_path, admins=frozenset({7})) + app.uid = 7 + await app.text("/shift @srcch @dstch") + assert "Shift plan" not in norm(app.out.last_text or "") + assert sorted(dst.msgs) == list(range(1, 11)) + await app.db.close() + + run(go()) diff --git a/tests/test_shift_extras.py b/tests/test_shift_extras.py new file mode 100644 index 0000000000000000000000000000000000000000..64078e2fd5fb4c1982ebf86c1b80e713dd2b2bec --- /dev/null +++ b/tests/test_shift_extras.py @@ -0,0 +1,551 @@ +"""/shift -c (links to the source's posts follow the copies, in every connected channel) and -all (the destination takes +over the source's name, description and photo).""" +import asyncio + +from telethon import functions, types + +from app.crosslinks import relink_after_shift, restore_after_shift_undo +from app.profile_copy import copy_profile, profile_lines +from app.shift_engine import delete_shift_copies, run_shift, shift_profile, source_of +from app.sync_engine import SyncOptions, live_fields, sync_channel +from app.tgutil import button_url + +from .dbutil import db_url_for, fresh_db +from .fakes import FakeChannelClient, make_msg, markup, rpc, url_btn +from .harness import norm +from .test_shift import SRC, shift_app, two_channels + + +def run(coro): + return asyncio.run(coro) + + +T1 = "Watch https://t.me/srcch/3 here" + + +def other_posts(): + """A third connected channel with every kind of link to the source's posts.""" + return { + 1: make_msg(1, T1, [types.MessageEntityBold(T1.index("here"), 4)], out=True), + 2: make_msg(2, "Fifth", [types.MessageEntityTextUrl(0, 5, "https://t.me/srcch/5?single")], out=True), + 3: make_msg( + 3, "Pick", + markup=markup([url_btn("Second", "https://t.me/srcch/2"), url_btn("Site", "https://example.com/x")]), out=True, + ), + 4: make_msg(4, "Private https://t.me/c/1/8 form", out=True), + 5: make_msg(5, "Never shifted https://t.me/srcch/99", out=True), # no copy of 99: stays + 6: make_msg(6, "Already there https://t.me/dstch/3", out=True), # a link to the destination: stays + 7: make_msg(7, "By a friend https://t.me/srcch/1", out=False), + 8: make_msg(8, "No link", out=True), + } + + +async def extras_setup(tmp_path, *marks, first=1, last=8): + """source (id 1, registered), destination (id 2) and another channel (id 3), a shift s1 with the given marks.""" + src, dst = two_channels() + other = src.add_channel(FakeChannelClient(other_posts(), username="otherch", cid=3, title="Other")) + dst.msgs[5] = make_msg(5, "Old post: https://t.me/srcch/1", out=True) # the destination had a link already + db = await fresh_db(db_url_for(tmp_path)) + await db.save_channel(1, 5, "Anime Source", "srcch", 1) + await db.save_channel(2, 6, "Anime Backup", "dstch", 1) + await db.save_channel(3, 7, "Other", "otherch", 1) + for m in other.msgs.values(): + if m.out: + await db.create_post( + channel_id=3, message_id=m.id, status="sent", source="bot", created_by=1, link_preview=False, **live_fields(m) + ) + await db.create_shift("s1", src=SRC, dst_channel_id=2, first_id=first, last_id=last, user_id=1) + for mark in marks: + await db.set_mark("s1", mark) + return src, dst, other, db, await db.get_channel(2), await db.get_shift("s1") + + +def edited(chan): + return [r.id for r in chan.requests if isinstance(r, functions.messages.EditMessageRequest)] + + +# ===================================================================================================== -c +def test_links_to_the_source_follow_the_copies_in_every_connected_channel(tmp_path): + async def go(): + src, dst, other, db, dst_row, shift = await extras_setup(tmp_path, "relink") + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert (res.copied_units, res.failed, res.aborted, res.cross_error) == (6, [], None, None) + # copies: 1->11 2->12 3->13 5->14 6->15 7->16 8->17 + assert res.phase == "links" and res.cross is not None and res.cross.clean + + # a typed link, with the bold word after it moved along (the link got one character longer) + assert other.msgs[1].message == "Watch https://t.me/dstch/13 here" + bold = other.msgs[1].entities[0] + assert other.msgs[1].message[bold.offset : bold.offset + bold.length] == "here" + # a hyperlink behind text keeps its text and its ?single + link = other.msgs[2].entities[0] + assert link.url == "https://t.me/dstch/14?single" and (link.offset, link.length) == (0, 5) + # a button changes, the other button stays + row = other.msgs[3].reply_markup.rows[0].buttons + assert button_url(row[0]) == "https://t.me/dstch/12" and row[0].text == "Second" + assert button_url(row[1]) == "https://example.com/x" + # the private form of the link, and a post made by somebody else (the bot may edit those here) + assert other.msgs[4].message == "Private https://t.me/dstch/17 form" + assert other.msgs[7].message == "By a friend https://t.me/dstch/11" + # nothing else was touched: no copy / a link to the destination / no link + assert other.msgs[5].message == "Never shifted https://t.me/srcch/99" + assert other.msgs[6].message == "Already there https://t.me/dstch/3" and other.msgs[8].message == "No link" + assert edited(other) == [1, 2, 3, 4, 7] + # the destination's own older post was fixed too + assert dst.msgs[5].message == "Old post: https://t.me/dstch/11" + # the source is only read - although the bot knows it as one of its channels and its posts link to each other + assert edited(src) == [] and src.delete_requests == [] + assert src.msgs[8].message == "See https://t.me/srcch/1 and https://t.me/c/1/2 and https://t.me/elsewhere/9" + # My posts follows what the channel shows + row1 = await db.find_by_message(3, 1) + assert row1.text == other.msgs[1].message + assert await db.has_mark("s1", "links") + assert sorted(c.channel.id for c in res.cross.changed_channels) == [2, 3] + await db.close() + + run(go()) + + +async def older_posts_setup(tmp_path, *, edit_right=True): + """Like extras_setup, but the third channel's posts are all older ones made by somebody else before the bot was added: + the sync has read them into My posts ("adopted"), nothing is registered as made by the bot.""" + src, dst = two_channels() + posts = other_posts() + for m in posts.values(): + m.out = False + other = src.add_channel(FakeChannelClient(posts, username="otherch", cid=3, title="Other")) + if not edit_right: + other.rights = dict(admin=True, post=True, edit=False, delete=True, invite=False, add_admins=False) + dst.msgs[5] = make_msg(5, "Old post: https://t.me/srcch/1", out=True) + db = await fresh_db(db_url_for(tmp_path)) + await db.save_channel(1, 5, "Anime Source", "srcch", 1) + await db.save_channel(2, 6, "Anime Backup", "dstch", 1) + await db.save_channel(3, 7, "Other", "otherch", 1) + rep = await sync_channel(src, db, await db.get_channel(3), SyncOptions(pause=0, grace=0)) # reads the older posts in + assert rep.imported == 8 and {p.source for p in await db.sent_posts(3)} == {"adopted"} + await db.create_shift("s1", src=SRC, dst_channel_id=2, first_id=1, last_id=8, user_id=1) + await db.set_mark("s1", "relink") + return src, dst, other, db, await db.get_channel(2), await db.get_shift("s1") + + +def test_links_in_the_older_posts_the_sync_read_into_my_posts_follow_the_copies_too(tmp_path): + async def go(): + src, dst, other, db, dst_row, shift = await older_posts_setup(tmp_path) + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert (res.copied_units, res.failed, res.aborted, res.cross_error) == (6, [], None, None) + assert res.cross is not None and res.cross.clean + # the links in posts that were in the channel before the bot was added: every kind is changed + assert other.msgs[1].message == "Watch https://t.me/dstch/13 here" + assert other.msgs[2].entities[0].url == "https://t.me/dstch/14?single" + assert button_url(other.msgs[3].reply_markup.rows[0].buttons[0]) == "https://t.me/dstch/12" + assert button_url(other.msgs[3].reply_markup.rows[0].buttons[1]) == "https://example.com/x" + assert other.msgs[4].message == "Private https://t.me/dstch/17 form" + assert other.msgs[7].message == "By a friend https://t.me/dstch/11" + assert other.msgs[5].message == "Never shifted https://t.me/srcch/99" and other.msgs[8].message == "No link" + assert edited(other) == [1, 2, 3, 4, 7] + # My posts follows: the saved copies are the posts of others, now with the new links + for mid in (1, 2, 3, 4, 7): + row = await db.find_by_message(3, mid) + assert row.source == "adopted" and row.created_by == 0 + assert row.text == other.msgs[mid].message + assert (await db.find_by_message(3, 3)).buttons[0][0]["u"] == "https://t.me/dstch/12" + assert (await db.find_by_message(3, 2)).entities[0]["u"] == "https://t.me/dstch/14?single" + assert (await db.find_by_message(3, 5)).text == "Never shifted https://t.me/srcch/99" + # nothing is left for the sync to "find": the saved copies and the channel agree + rep = await sync_channel(src, db, await db.get_channel(3), SyncOptions(pause=0, grace=0)) + assert rep.edited == [] and rep.deleted == [] and rep.adopted == [] + await db.close() + + run(go()) + + +def test_older_posts_of_others_need_the_edit_right_and_the_report_counts_the_ones_left(tmp_path): + async def go(): + src, dst, other, db, dst_row, shift = await older_posts_setup(tmp_path, edit_right=False) + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert res.cross is not None and res.cross.not_allowed == 5 and not res.cross.clean + assert edited(other) == [] # Telegram would refuse: nothing is tried, nothing is changed + assert other.msgs[1].message == "Watch https://t.me/srcch/3 here" + assert (await db.find_by_message(3, 1)).text == "Watch https://t.me/srcch/3 here" + assert dst.msgs[5].message == "Old post: https://t.me/dstch/11" # a post of the bot itself is still fixed + await db.close() + + run(go()) + + +def test_without_the_c_option_only_the_copies_themselves_are_fixed(tmp_path): + async def go(): + src, dst, other, db, dst_row, shift = await extras_setup(tmp_path) + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert res.cross is None and res.profile is None + assert edited(other) == [] and other.msgs[1].message == T1 + assert dst.msgs[5].message == "Old post: https://t.me/srcch/1" # an older post of the destination stays + assert not await db.has_mark("s1", "links") + await db.close() + + run(go()) + + +def test_only_the_posts_that_were_shifted_have_their_links_changed(tmp_path): + async def go(): + src, dst, other, db, dst_row, shift = await extras_setup(tmp_path, "relink", first=1, last=2) + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + # only the posts 1 and 2 were shifted (copies 11 and 12): two posts of the other channel and the old post of the + # destination link to them + assert res.copied_units == 2 and res.cross.relinked == 3 + assert other.msgs[7].message == "By a friend https://t.me/dstch/11" + assert button_url(other.msgs[3].reply_markup.rows[0].buttons[0]) == "https://t.me/dstch/12" + assert dst.msgs[5].message == "Old post: https://t.me/dstch/11" + assert edited(other) == [3, 7] + # the links to posts that were not shifted stay as they are + assert other.msgs[1].message == T1 + assert other.msgs[2].entities[0].url == "https://t.me/srcch/5?single" + assert other.msgs[4].message == "Private https://t.me/c/1/8 form" + await db.close() + + run(go()) + + +def test_the_links_can_be_updated_again_and_nothing_changes_twice(tmp_path): + async def go(): + src, dst, other, db, dst_row, shift = await extras_setup(tmp_path, "relink") + await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + n = len(edited(other)) + again = await relink_after_shift(src, db, shift, source_of(shift), dst_row, delay=0, settle_pause=0, pause=0) + assert again.relinked == 0 and again.clean and len(edited(other)) == n + late = other._new("Late: https://t.me/srcch/6", None, None) + late.out = False + again = await relink_after_shift(src, db, shift, source_of(shift), dst_row, delay=0, settle_pause=0, pause=0) + assert again.relinked == 1 and other.msgs[late.id].message == "Late: https://t.me/dstch/15" + await db.close() + + run(go()) + + +def test_undo_points_the_links_back_at_the_source(tmp_path): + async def go(): + src, dst, other, db, dst_row, shift = await extras_setup(tmp_path, "relink") + before = {i: (m.message, [e.to_dict() for e in (m.entities or [])]) for i, m in other.msgs.items()} + await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + back = await restore_after_shift_undo(src, db, shift, source_of(shift), dst_row, delay=0, settle_pause=0, pause=0) + assert back.relinked == 6 and back.clean # the five posts of the other channel and the old post of the destination + for i, (text, ents) in before.items(): + if i == 4: # the private form t.me/c/1/8 comes back as the public form of the same post (the source has a name) + assert other.msgs[i].message == "Private https://t.me/srcch/8 form" + continue + assert other.msgs[i].message == text and [e.to_dict() for e in (other.msgs[i].entities or [])] == ents, i + assert button_url(other.msgs[3].reply_markup.rows[0].buttons[0]) == "https://t.me/srcch/2" + assert dst.msgs[5].message == "Old post: https://t.me/srcch/1" + res = await delete_shift_copies(src, db, dst_row, shift, delay=0) + assert res.remaining == 0 and res.deleted == 7 + await db.close() + + run(go()) + + +def test_an_undo_without_c_reads_nothing(tmp_path): + async def go(): + src, dst, other, db, dst_row, shift = await extras_setup(tmp_path) + await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + mark = len(other.requests) + back = await restore_after_shift_undo(src, db, shift, source_of(shift), dst_row, delay=0, settle_pause=0, pause=0) + assert back.channels == [] and len(other.requests) == mark + await db.close() + + run(go()) + + +# ================================================================================================== -all +def prepare_profiles(src, dst): + src.about, dst.about = "Source about", "old about" + src.set_photo(b"SRC-PHOTO") + dst.set_photo(b"OLD-PHOTO") + + +def notices(chan): + return [m for m in chan.msgs.values() if isinstance(m, types.MessageService)] + + +def test_the_destination_takes_over_name_description_and_photo(tmp_path): + async def go(): + src, dst, other, db, dst_row, shift = await extras_setup(tmp_path, "profile") + prepare_profiles(src, dst) + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert res.profile is not None and res.profile.ok and res.profile_error is None + assert res.profile.outcome == {"name": ("done", "Anime Source"), "description": ("done", ""), "photo": ("done", "")} + assert (dst.title, dst.about, dst.photo_bytes()) == ("Anime Source", "Source about", b"SRC-PHOTO") + # the source was only read + assert (src.title, src.about, src.photo_bytes()) == ("Anime Source", "Source about", b"SRC-PHOTO") + assert not [r for r in src.requests if type(r).__name__.startswith("Edit")] + # the "name changed" / "photo changed" notices Telegram adds are deleted again + assert notices(dst) == [] + # the bot's own list knows the new name + assert (await db.get_channel(2)).title == "Anime Source" + assert await db.has_mark("s1", "profile_done") + # the posts were copied as usual, and -c was not asked for + assert res.copied_units == 6 and res.cross is None + await db.close() + + run(go()) + + +def test_it_is_done_once_not_again_when_a_stopped_shift_continues(tmp_path): + async def go(): + src, dst, other, db, dst_row, shift = await extras_setup(tmp_path, "profile") + prepare_profiles(src, dst) + calls = [] + + async def prog(res): + calls.append(res.copied_units) + + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0, progress=prog, should_stop=lambda: len(calls) >= 2) + assert res.stopped and res.profile is None and dst.title == "Anime Backup" # not before everything is copied + again = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert again.profile is not None and again.profile.ok and dst.title == "Anime Source" + titles = [r for r in dst.requests if isinstance(r, functions.channels.EditTitleRequest)] + third = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) # nothing left to do + assert third.profile is None + assert [r for r in dst.requests if isinstance(r, functions.channels.EditTitleRequest)] == titles + await db.close() + + run(go()) + + +def test_a_part_the_source_does_not_have_is_left_as_the_destination_has_it(tmp_path): + async def go(): + src, dst, other, db, dst_row, shift = await extras_setup(tmp_path, "profile") + dst.title = "Anime Source" # the same name already + dst.about = "my own description" + dst.set_photo(b"MY-OWN-PHOTO") # the source has neither a description nor a photo + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert res.profile.outcome == {"name": ("same", ""), "description": ("none", ""), "photo": ("none", "")} + assert (dst.title, dst.about, dst.photo_bytes()) == ("Anime Source", "my own description", b"MY-OWN-PHOTO") + lines = "\n".join(profile_lines(res.profile)) + assert "the source has none - left as it is" in lines and "already the same" in lines + await db.close() + + run(go()) + + +def test_a_missing_admin_right_is_named_and_the_parts_can_be_tried_again(tmp_path): + async def go(): + src, dst, other, db, dst_row, shift = await extras_setup(tmp_path, "profile") + prepare_profiles(src, dst) + dst.rights = dict(admin=True, post=True, edit=True, delete=True, invite=False, add_admins=False, change_info=False) + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert res.copied_units == 6 and res.failed == [] # the posts are there + assert not res.profile.ok and [p for p, _ in res.profile.failed] == ["name", "description", "photo"] + text = "\n".join(profile_lines(res.profile)) + assert "Change channel info" in text and "Not copied" in text + assert dst.title == "Anime Backup" and dst.about == "old about" and dst.photo_bytes() == b"OLD-PHOTO" + assert not await db.has_mark("s1", "profile_done") + # the right is given: the same run again (the "copy again" button) does it + dst.rights["change_info"] = True + holder = type(res)() + await shift_profile(src, db, shift, dst_row, 1, holder) + assert holder.profile.ok and (dst.title, dst.about, dst.photo_bytes()) == ("Anime Source", "Source about", b"SRC-PHOTO") + assert await db.has_mark("s1", "profile_done") + await db.close() + + run(go()) + + +def test_one_part_failing_does_not_stop_the_others(tmp_path): + async def go(): + src, dst, other, db, dst_row, shift = await extras_setup(tmp_path, "profile") + prepare_profiles(src, dst) + dst.fail["EditPhotoRequest"] = rpc("PhotoCropSizeSmallError") + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert res.profile.outcome["name"][0] == "done" and res.profile.outcome["description"][0] == "done" + assert res.profile.outcome["photo"] == ("failed", "PhotoCropSizeSmallError") + assert (dst.title, dst.about, dst.photo_bytes()) == ("Anime Source", "Source about", b"OLD-PHOTO") + assert not await db.has_mark("s1", "profile_done") # so the button to try again is offered + assert (await db.get_channel(2)).title == "Anime Source" # what was changed is known to the bot + await db.close() + + run(go()) + + +def test_an_unreadable_source_fails_every_part_and_changes_nothing(tmp_path): + async def go(): + src, dst, other, db, dst_row, shift = await extras_setup(tmp_path, "profile") + prepare_profiles(src, dst) + src.fail["GetFullChannelRequest"] = rpc("ChannelPrivateError") + res = await copy_profile(src, source_of(shift), dst_row) + assert [p for p, _ in res.failed] == ["name", "description", "photo"] and "can't be read" in res.failed[0][1] + assert (dst.title, dst.about, dst.photo_bytes()) == ("Anime Backup", "old about", b"OLD-PHOTO") + await db.close() + + run(go()) + + +def test_both_extras_together(tmp_path): + async def go(): + src, dst, other, db, dst_row, shift = await extras_setup(tmp_path, "relink", "profile") + prepare_profiles(src, dst) + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert res.profile.ok and res.cross.relinked == 6 and res.cross_error is None and res.profile_error is None + assert other.msgs[1].message == "Watch https://t.me/dstch/13 here" and dst.title == "Anime Source" + await db.close() + + run(go()) + + +# ========================================================================================= the owner's view +async def extras_app(tmp_path): + app, dst = await shift_app(tmp_path) + other = app.tg.add_channel(FakeChannelClient(other_posts(), username="otherch", cid=3, title="Other")) + await app.db.save_channel(3, 7, "Other", "otherch", 1) + dst.msgs[5] = make_msg(5, "Old post: https://t.me/srcch/1", out=True) + app.tg.about, dst.about = "Source about", "old about" + app.tg.set_photo(b"SRC-PHOTO") + dst.set_photo(b"OLD-PHOTO") + return app, dst, other + + +def labels(app): + return [t for row in app.out.last_buttons() for t in row] + + +def test_the_plan_names_the_extras_that_were_asked_for(tmp_path): + async def go(): + app, dst, other = await extras_app(tmp_path) + await app.text("/shift @srcch @dstch") + plain = norm(app.out.last_text) + assert "-c" not in plain and "-all" not in plain + + await app.text("/shift @srcch @dstch -c") + text = norm(app.out.last_text) + assert "-c: afterwards every link to a post of Anime Source" in text and "in your 2 other connected channel(s)" in text + assert "Anime Source itself is not changed" in text and "-all" not in text + + await app.text("/shift @srcch @dstch - all") # typed with a space + text = norm(app.out.last_text) + assert "-all: afterwards Anime Backup gets the name, description and profile photo of Anime Source" in text + assert "undo does not bring them back" in text and "-c:" not in text and "Change channel info" not in text + + await app.text("/shift @srcch @dstch 2 5 -all -c") + text = norm(app.out.last_text) + assert "Post ids 2-5" in text and "-c: afterwards" in text and "-all: afterwards" in text + assert dst.title == "Anime Backup" and edited(other) == [] # a plan changes nothing + await app.db.close() + + run(go()) + + +def test_the_plan_warns_when_the_info_right_is_missing(tmp_path): + async def go(): + app, dst, other = await extras_app(tmp_path) + dst.rights = dict(admin=True, post=True, edit=True, delete=True, invite=False, add_admins=False, change_info=False) + await app.text("/shift @srcch @dstch -all") + assert "does not have the “Change channel info” admin right in Anime Backup yet" in norm(app.out.last_text) + await app.db.close() + + run(go()) + + +def test_an_unknown_option_is_explained(tmp_path): + async def go(): + app, dst, other = await extras_app(tmp_path) + await app.text("/shift @srcch @dstch -x") + assert "Unknown option -x" in norm(app.out.last_text) and "-c, -all and --no-media" in norm(app.out.last_text) + assert dst.title == "Anime Backup" + await app.db.close() + + run(go()) + + +def test_the_whole_flow_with_both_extras_then_undo(tmp_path): + async def go(): + app, dst, other = await extras_app(tmp_path) + await app.text("/shift @srcch @dstch -c -all") + await app.press(app.out.callback_data("Start copying")) + done = norm(app.out.last_text) + assert "7 message(s) copied" in done + assert "link(s) in 6 post(s) of 2 channel(s) now point at the new copies" in done + assert "Other: 5 link(s) in 5 post(s)" in done + assert "name copied, description copied, profile photo copied" in done + assert (dst.title, dst.about, dst.photo_bytes()) == ("Anime Source", "Source about", b"SRC-PHOTO") + assert other.msgs[1].message == "Watch https://t.me/dstch/13 here" + shown = labels(app) + assert any("Update links again" in t for t in shown) and any("Undo" in t for t in shown) + assert not any("again" in t and "photo" in t for t in shown) # the profile was copied: no button for it + + # "update links again": nothing new, so nothing to change + await app.press(app.out.callback_data("Update links again")) + assert "no link there needed changing" in norm(app.out.last_text) + + # undo: the links go back to the source's posts first, then the copies are removed + await app.press(app.out.callback_data("Undo")) + await app.press(app.out.callback_data("Yes, remove")) + text = norm(app.out.last_text) + assert "7 copied message(s) removed from" in text and "6 post(s) of 2 channel(s) point back at the original posts" in text + assert other.msgs[1].message == T1 and other.msgs[7].message == "By a friend https://t.me/srcch/1" + assert dst.msgs[5].message == "Old post: https://t.me/srcch/1" + assert dst.title == "Anime Source" # the name is not taken back (the plan said so) + await app.db.close() + + run(go()) + + +def test_a_failed_profile_gets_its_own_button(tmp_path): + async def go(): + app, dst, other = await extras_app(tmp_path) + dst.rights = dict(admin=True, post=True, edit=True, delete=True, invite=False, add_admins=False, change_info=False) + await app.text("/shift @srcch @dstch -all") + await app.press(app.out.callback_data("Start copying")) + text = norm(app.out.last_text) + assert "7 message(s) copied" in text and "Not copied" in text and "Change channel info" in text + assert any("Copy name, description, photo again" in t for t in labels(app)) + dst.rights["change_info"] = True + await app.press(app.out.callback_data("Copy name, description, photo again")) + text = norm(app.out.last_text) + assert "name copied, description copied, profile photo copied" in text + assert (dst.title, dst.about, dst.photo_bytes()) == ("Anime Source", "Source about", b"SRC-PHOTO") + assert not any("photo again" in t for t in labels(app)) # done now + await app.db.close() + + run(go()) + + +def test_the_extra_buttons_only_exist_for_the_extras_that_were_asked_for(tmp_path): + async def go(): + app, dst, other = await extras_app(tmp_path) + await app.text("/shift @srcch @dstch") + await app.press(app.out.callback_data("Start copying")) + shown = " | ".join(labels(app)) + assert "Update links again" not in shown and "photo again" not in shown and "Undo" in shown + assert edited(other) == [] + await app.db.close() + + run(go()) + + +def test_the_extras_that_were_asked_for_are_remembered_with_the_shift(tmp_path): + async def go(): + app, dst, other = await extras_app(tmp_path) + await app.text("/shift @srcch @dstch -c") + await app.press(app.out.callback_data("Start copying")) + sid = app.out.callback_data("Undo").split(":")[1] + assert await app.db.marks_of(sid) == {"relink", "links"} + await app.db.close() + + run(go()) + + +def test_a_stopped_shift_that_is_continued_still_updates_the_links(tmp_path): + async def go(): + src, dst, other, db, dst_row, shift = await extras_setup(tmp_path, "relink") + calls = [] + + async def prog(res): + calls.append(res.copied_units) + + res = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0, progress=prog, should_stop=lambda: len(calls) >= 2) + assert res.stopped and res.cross is None and edited(other) == [] # the links wait until everything is copied + again = await run_shift(src, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert not again.stopped and again.cross is not None and again.cross.relinked == 6 + assert other.msgs[1].message == "Watch https://t.me/dstch/13 here" + await db.close() + + run(go()) diff --git a/tests/test_startup.py b/tests/test_startup.py new file mode 100644 index 0000000000000000000000000000000000000000..a839d0fdd11bba0ac34f71e4a38e271c76df8609 --- /dev/null +++ b/tests/test_startup.py @@ -0,0 +1,163 @@ +"""bot.main(): start-up order, the command menu, the error log chat, the optional userbot, and what happens on a crash.""" +import asyncio +import logging +from types import SimpleNamespace + +import pytest +from telethon import functions, types + +import bot +from app.config import Config +from app.errorlog import TelegramLogHandler + +from .harness import FakeTG + +CHAT = -1002525172451 +TOKEN = "123456:ABCdefGHIjklMNOpqrSTUvwxYZ" + + +class StartupTG(FakeTG): + """The bot's connection with the few extra methods main() uses.""" + + def __init__(self, *, start_error=None, log_chat_known=True): + super().__init__() + self.start_error = start_error + self.connected = True + self.authorized = True + self.calls = [] + self.menu = None + if log_chat_known: + self.known_users[CHAT] = SimpleNamespace(id=2525172451, access_hash=7) + + async def start(self, bot_token=None): + self.calls.append(("start", bot_token)) + if self.start_error: + raise self.start_error + + async def get_me(self): + return SimpleNamespace(username="personalbuttonbot", id=42) + + async def run_until_disconnected(self): + self.calls.append(("run", None)) + + def is_connected(self): + return self.connected + + async def connect(self): + self.connected = True + self.calls.append(("connect", None)) + + async def is_user_authorized(self): + return self.authorized + + async def sign_in(self, bot_token=None): + self.authorized = True + self.calls.append(("sign_in", bot_token)) + + async def __call__(self, req): + if isinstance(req, functions.bots.SetBotCommandsRequest): + self.menu = [(c.command, c.description) for c in req.commands] + return True + return await super().__call__(req) + + async def get_input_entity(self, peer): + if isinstance(peer, int) and peer in self.known_users: + return types.InputPeerChannel(2525172451, 7) + return await super().get_input_entity(peer) + + +def make_cfg(tmp_path, **kw): + base = dict( + api_id=1, api_hash="hashhashhash", bot_token=TOKEN, owners=frozenset({1}), admins=frozenset(), + database_url=f"sqlite+aiosqlite:///{tmp_path}/main.db", db_pool="null", session_path=str(tmp_path / "s"), + session_string="", edit_delay=0.3, replace_typed_links=True, port=0, log_level="INFO", error_log_chat_id=CHAT, + ) + base.update(kw) + return Config(**base) + + +@pytest.fixture +def run_main(monkeypatch): + """Runs bot.main() with the given config and connection; always removes the log handler main() installs.""" + + def go(cfg, tg): + monkeypatch.setattr(bot, "load_config", lambda: cfg) + monkeypatch.setattr(bot, "build_client", lambda c: tg) + root = logging.getLogger() + before = list(root.handlers) + try: + asyncio.run(bot.main()) + finally: + for h in list(root.handlers): + if h not in before and isinstance(h, TelegramLogHandler): + root.removeHandler(h) + + return go + + +def test_normal_start_up(tmp_path, run_main): + tg = StartupTG() + run_main(make_cfg(tmp_path), tg) + assert tg.calls == [("start", TOKEN), ("run", None)] + assert tg.menu == [(c, d) for c, d in bot.COMMANDS] + names = [c for c, _ in tg.menu] + assert "repost" in names and "userbot" in names and "testerror" not in names + assert "testedit" not in names and "selftest" not in names + assert tg.handlers # every module registered its handlers + assert tg.sent == [] # nothing needed reporting + + +def test_a_log_chat_the_bot_is_not_in_does_not_stop_it(tmp_path, run_main, caplog): + tg = StartupTG(log_chat_known=False) + with caplog.at_level(logging.INFO): + run_main(make_cfg(tmp_path), tg) + assert ("run", None) in tg.calls + assert any("errors cannot be sent to chat" in r.getMessage() and "add the bot to that chat" in r.getMessage() for r in caplog.records) + + +def test_log_chat_can_be_switched_off(tmp_path, run_main, caplog): + tg = StartupTG(log_chat_known=False) + with caplog.at_level(logging.INFO): + run_main(make_cfg(tmp_path, error_log_chat_id=None), tg) + assert ("run", None) in tg.calls and any("error log chat: off" in r.getMessage() for r in caplog.records) + + +def test_a_broken_userbot_session_does_not_stop_the_bot(tmp_path, run_main, caplog): + tg = StartupTG() + with caplog.at_level(logging.INFO): + run_main(make_cfg(tmp_path, userbot_session="this is not a session"), tg) + assert ("run", None) in tg.calls + assert any("the userbot is not available" in r.getMessage() for r in caplog.records) + + +def test_the_health_endpoint_is_started_when_a_port_is_set(tmp_path, run_main, caplog): + import socket + + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + tg = StartupTG() + with caplog.at_level(logging.INFO): + run_main(make_cfg(tmp_path, port=port), tg) + assert any(f"health endpoint listening on :{port}" in r.getMessage() for r in caplog.records) + + +def test_a_crash_is_reported_to_the_log_chat_and_still_raised(tmp_path, run_main): + tg = StartupTG(start_error=RuntimeError("login failed for 123456:ABCdefGHIjklMNOpqrSTUvwxYZ")) + tg.connected = False # the connection is gone when the crash happens + tg.authorized = False + with pytest.raises(RuntimeError, match="login failed"): + run_main(make_cfg(tmp_path), tg) + (kind, peer, text, kw), = tg.sent + assert text.startswith("The bot stopped because of an unhandled exception:\n\nTraceback (most recent call last):") + assert "RuntimeError: login failed for ***" in text and TOKEN not in text # the token is never sent + ent, = kw["formatting_entities"] + assert isinstance(ent, types.MessageEntityPre) and ent.language == "python" + assert ("connect", None) in tg.calls and ("sign_in", TOKEN) in tg.calls # it reconnected just to say this + + +def test_a_crash_without_a_log_chat_is_just_raised(tmp_path, run_main): + tg = StartupTG(start_error=RuntimeError("boom")) + with pytest.raises(RuntimeError, match="boom"): + run_main(make_cfg(tmp_path, error_log_chat_id=None), tg) + assert tg.sent == [] diff --git a/tests/test_sync.py b/tests/test_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..015f5b058d8ef1a8b30a3cb665bc64d141ef19c4 --- /dev/null +++ b/tests/test_sync.py @@ -0,0 +1,650 @@ +"""The sync engine: My posts follows what channel admins do outside the bot (deleted, edited and new posts, service messages).""" +import asyncio +import datetime + +from telethon import errors, types + +from app.db import as_utc, utcnow +from app.servicemsg import remove +from app.sync_engine import ( + SyncOptions, + diff_post, + find_top, + live_fields, + message_supported, + sync_channel, + sync_ids, +) +from app.tgutil import media_info + +from .dbutil import db_url_for, fresh_db +from .fakes import FakeChannelClient, make_msg, markup, photo_media, service_msg, url_btn, video_media + +OLD = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=1) +FAST = dict(pause=0) + + +def old_msg(i, text="", **kw): + m = make_msg(i, text, **kw) + m.date = OLD + return m + + +def foreign(chan, text="", *, age=86400, **kw): + """A post somebody else made in the channel (not out).""" + m = chan._new(text, kw.pop("entities", None), kw.pop("markup", None), kw.pop("media", None)) + m.out = False + m.date = utcnow() - datetime.timedelta(seconds=age) + return m + + +async def saved(db, m, **extra): + """The bot's saved copy of live message `m`, exactly as the bot would have saved it a day ago.""" + fields = dict( + channel_id=1, message_id=m.id, status="sent", source="bot", created_by=99, link_preview=False, + created_at=OLD, updated_at=OLD, sent_at=OLD, **live_fields(m), + ) + fields.update(extra) + return await db.create_post(**fields) + + +async def world(tmp_path, msgs, *, save=True): + chan = FakeChannelClient(msgs, username="chan") + db = await fresh_db(db_url_for(tmp_path)) + await db.save_channel(1, 5, "Chan", "chan", 99) + ch = await db.get_channel(1) + if save: + for m in msgs.values(): + await saved(db, m) + return chan, db, ch + + +def run(coro): + return asyncio.run(coro) + + +def opts(**kw): + return SyncOptions(**{**FAST, "grace": 0, **kw}) + + +def three(): + return { + 1: old_msg(1, "first"), + 2: old_msg(2, "second", markup=markup([url_btn("Watch", "https://t.me/a/1")])), + 3: old_msg(3, "third"), + } + + +# ============================================================================================ comparing one post +def test_a_post_that_is_as_saved_has_no_difference(): + m = old_msg(1, "hello", markup=markup([url_btn("Go", "https://x.org")])) + p = SaveLike(m) + d = diff_post(p, m) + assert d.fields == {} and not d.buttons_missing and not d.quiet + + +class SaveLike: + """Anything with the Post fields.""" + + def __init__(self, m, **kw): + for k, v in live_fields(m).items(): + setattr(self, k, v) + self.link_preview = False + for k, v in kw.items(): + setattr(self, k, v) + + +def test_text_formatting_and_buttons_that_changed_are_found(): + m = old_msg(1, "hello world", entities=[types.MessageEntityBold(0, 5)], markup=markup([url_btn("Go", "https://x.org")])) + p = SaveLike(m, text="hello", entities=[], buttons=[[{"t": "Go", "u": "https://old.org"}]]) + d = diff_post(p, m) + assert d.fields["text"] == "hello world" + assert d.fields["entities"] == [{"k": "bold", "o": 0, "l": 5}] + assert d.fields["buttons"] == [[{"t": "Go", "u": "https://x.org"}]] + assert not d.quiet and not d.buttons_missing + + +def test_a_keyboard_that_is_not_shown_never_wipes_the_saved_buttons(): + m = old_msg(1, "hello") # the channel shows no keyboard + p = SaveLike(m, buttons=[[{"t": "Go", "u": "https://x.org"}]]) + d = diff_post(p, m) + assert d.buttons_missing and "buttons" not in d.fields + + +def test_only_spaces_around_the_text_is_a_quiet_correction(): + m = old_msg(1, "hello") + d = diff_post(SaveLike(m, text="hello \n"), m) + assert d.fields == {"text": "hello"} and d.quiet + + +def test_media_is_compared_by_its_id_not_by_its_file_reference(): + m = old_msg(1, "pic", media=photo_media(11)) + p = SaveLike(m) + other_fetch = old_msg(1, "pic", media=photo_media(11)) + other_fetch.media.photo.file_reference = b"a-fresh-reference" + assert diff_post(p, other_fetch).fields == {} # same photo, new file reference: nothing changed + replaced = old_msg(1, "pic", media=photo_media(12)) + d = diff_post(p, replaced) + assert d.fields["media_kind"] == "photo" and d.fields["media_file_id"] == media_info(replaced)[1] + + +def test_media_that_seems_to_have_vanished_is_not_forgotten(): + with_media = old_msg(1, "pic", media=photo_media(11)) + p = SaveLike(with_media) + stripped = old_msg(1, "pic") # Telegram showed it without the photo this time + assert diff_post(p, stripped).fields == {} + + +def test_what_the_bot_can_hold(): + assert message_supported(old_msg(1, "text")) + assert message_supported(old_msg(1, "", media=photo_media())) + assert message_supported(old_msg(1, "", media=video_media())) + assert not message_supported(old_msg(1, "")) # a poll, a sticker ... + assert not message_supported(old_msg(1, " \n ")) + + +# ================================================================================================= the first look +def test_the_first_look_notes_where_the_channel_stands_and_reads_in_the_older_posts(tmp_path): + async def go(): + msgs = three() + chan, db, ch = await world(tmp_path, msgs, save=False) # nothing saved: the channel has history only + for i in (4, 5): + chan.msgs[i] = old_msg(i, f"older post {i}") + chan._top = chan._pts = 5 + rep = await sync_channel(chan, db, ch, opts()) + assert rep.first_look and rep.error is None + assert rep.adopted == [] and rep.deleted == [] and rep.edited == [] # these are not "new posts" ... + assert rep.imported == 5 and rep.history_done # ... they are the posts from before the bot was added + posts, total = await db.list_posts(1, None, 0, 50) + assert total == 5 and {p.source for p in posts} == {"adopted"} and {p.status for p in posts} == {"sent"} + state = await db.get_sync(1) + assert (state.last_top, state.last_pts, state.deferred) == (5, 5, 0) + hist = await db.get_history(1) + assert (hist.top, hist.next_id, hist.imported, hist.done) == (5, 6, 5, True) + again = await sync_channel(chan, db, ch, opts()) # nothing is read twice + assert again.imported == 0 and again.history_top == 0 and again.changed is False + await db.close() + + run(go()) + + +def test_a_channel_without_any_message_is_fine(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, {}, save=False) + rep = await sync_channel(chan, db, ch, opts()) + assert rep.first_look and rep.error is None and rep.adopted == [] + again = await sync_channel(chan, db, ch, opts()) + assert again.error is None and again.changed is False + await db.close() + + run(go()) + + +def test_the_first_look_finds_the_newest_message_below_a_long_run_of_deleted_ids(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, {1: old_msg(1, "a"), 2: old_msg(2, "b")}, save=False) + chan._top, chan._pts = 2, 1000 # a thousand edits and deletes since + top = await find_top(chan, types.InputPeerChannel(1, 5), 1000, 0, pause=0) + assert top == 2 + # the newest saved post is a floor: looking stops there + assert await find_top(chan, types.InputPeerChannel(1, 5), 1000, 2, pause=0) == 2 + await db.close() + + run(go()) + + +# ============================================================================================= saved posts vs channel +def test_a_post_deleted_in_the_channel_leaves_my_posts(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, three()) + await sync_channel(chan, db, ch, opts()) # the first look + del chan.msgs[2] + chan._pts += 1 + rep = await sync_channel(chan, db, ch, opts()) + assert rep.deleted == [2] and rep.checked == 3 + assert sorted(p.message_id for p in await db.sent_posts(1)) == [1, 3] + await db.close() + + run(go()) + + +def test_a_post_edited_in_the_channel_is_updated_here(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, three()) + m2 = chan.msgs[2] + m2.message = "second, edited by an admin" + m2.entities = [types.MessageEntityItalic(0, 6)] + m2.reply_markup = markup([url_btn("Watch now", "https://t.me/new/9")]) + rep = await sync_channel(chan, db, ch, opts()) + assert rep.edited == [2] and rep.deleted == [] and rep.adopted == [] + p = await db.find_by_message(1, 2) + assert p.text == "second, edited by an admin" + assert p.entities == [{"k": "italic", "o": 0, "l": 6}] + assert p.buttons == [[{"t": "Watch now", "u": "https://t.me/new/9"}]] + again = await sync_channel(chan, db, ch, opts()) + assert again.edited == [] and again.changed is False # nothing left to record + await db.close() + + run(go()) + + +def test_a_missing_keyboard_is_reported_and_the_saved_buttons_stay(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, three()) + chan.msgs[2].reply_markup = None # the channel shows no keyboard any more + rep = await sync_channel(chan, db, ch, opts()) + assert rep.buttons_missing == [2] and rep.edited == [] + assert (await db.find_by_message(1, 2)).buttons == [[{"t": "Watch", "u": "https://t.me/a/1"}]] + await db.close() + + run(go()) + + +def test_posts_the_bot_touched_a_moment_ago_are_left_for_later(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, three()) + await db.update_post((await db.find_by_message(1, 1)).id, text="just edited through the bot") # updated_at = now + chan.msgs[1].message = "an admin's text" + rep = await sync_channel(chan, db, ch, opts(grace=120)) + assert rep.young == [1] and rep.edited == [] and rep.checked == 2 + assert (await db.find_by_message(1, 1)).text == "just edited through the bot" + await db.close() + + run(go()) + + +def test_if_every_saved_post_looks_deleted_nothing_is_removed(tmp_path): + async def go(): + msgs = {i: old_msg(i, f"post {i}") for i in range(1, 8)} + chan, db, ch = await world(tmp_path, msgs) + chan.msgs.clear() # e.g. the bot lost access and Telegram shows nothing + rep = await sync_channel(chan, db, ch, opts()) + assert rep.deleted == [] and rep.anomaly and "All 7" in rep.anomaly + assert len(await db.sent_posts(1)) == 7 + await db.close() + + run(go()) + + +def test_one_or_two_posts_can_be_deleted_even_when_that_is_all_there_is(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, {1: old_msg(1, "a"), 2: old_msg(2, "b")}) + chan.msgs.clear() + rep = await sync_channel(chan, db, ch, opts()) + assert sorted(rep.deleted) == [1, 2] and rep.anomaly is None + await db.close() + + run(go()) + + +def test_a_change_made_through_the_bot_while_the_channel_was_read_wins(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, three()) + chan.msgs[3].message = "an admin's text" + pid = (await db.find_by_message(1, 3)).id + real_get = chan.get_messages + + async def get_while_the_owner_edits(peer, ids=None): + res = await real_get(peer, ids=ids) + await db.update_post(pid, text="the owner's newer text") # happens between reading and saving + return res + + chan.get_messages = get_while_the_owner_edits + rep = await sync_channel(chan, db, ch, opts()) + assert rep.edited == [] and rep.changed_meanwhile == 1 + assert (await db.find_by_message(1, 3)).text == "the owner's newer text" + await db.close() + + run(go()) + + +# ================================================================================================= new posts +async def looked(tmp_path, msgs=None): + chan, db, ch = await world(tmp_path, msgs or three()) + first = await sync_channel(chan, db, ch, opts()) # the first look sets the mark + assert first.first_look + return chan, db, ch + + +def test_a_new_post_made_outside_the_bot_is_added(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path) + m = foreign(chan, "posted from the Telegram app", entities=[types.MessageEntityBold(0, 6)], + markup=markup([url_btn("Open", "https://example.org/x")])) + rep = await sync_channel(chan, db, ch, opts()) + assert rep.adopted == [m.id] and rep.first_look is False + p = await db.find_by_message(1, m.id) + assert (p.source, p.status, p.created_by) == ("adopted", "sent", 0) + assert p.text == "posted from the Telegram app" + assert p.entities == [{"k": "bold", "o": 0, "l": 6}] + assert p.buttons == [[{"t": "Open", "u": "https://example.org/x"}]] + assert p.media_kind is None and p.link_preview is False + assert as_utc(p.sent_at) == as_utc(m.date) + state = await db.get_sync(1) + assert state.last_top == m.id + again = await sync_channel(chan, db, ch, opts()) + assert again.adopted == [] # not saved twice + assert len(await db.sent_posts(1)) == 4 + await db.close() + + run(go()) + + +def test_new_media_posts_keep_their_media(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path) + m = foreign(chan, "caption", media=photo_media(31)) + await sync_channel(chan, db, ch, opts()) + p = await db.find_by_message(1, m.id) + assert p.media_kind == "photo" and p.media_file_id.startswith("tl:") and p.text == "caption" + await db.close() + + run(go()) + + +def test_the_bots_own_posts_that_are_saved_are_not_picked_up_again(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path) + m = chan._new("made with the bot", None, None) # out=True, like the bot's own post + m.date = utcnow() - datetime.timedelta(minutes=10) + mine = await db.create_post(channel_id=1, message_id=m.id, status="sent", source="bot", created_by=99, + sent_at=OLD, created_at=OLD, updated_at=OLD, **live_fields(m)) + rep = await sync_channel(chan, db, ch, opts()) + assert rep.adopted == [] and rep.deleted == [] + assert (await db.find_by_message(1, m.id)).id == mine.id and mine.source == "bot" + await db.close() + + run(go()) + + +def test_a_message_that_appeared_a_moment_ago_waits_for_the_next_look(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path) + m = foreign(chan, "brand new", age=1) + rep = await sync_channel(chan, db, ch, opts(grace=120)) + assert rep.adopted == [] and rep.young_new == [m.id] + state = await db.get_sync(1) + assert state.last_top == 3 and state.deferred == 1 # the mark stays below it + m.date = utcnow() - datetime.timedelta(minutes=10) # time passes + rep = await sync_channel(chan, db, ch, opts(grace=120)) + assert rep.adopted == [m.id] and rep.young_new == [] + state = await db.get_sync(1) + assert state.last_top == m.id and state.deferred == 0 + await db.close() + + run(go()) + + +def test_a_quiet_channel_costs_no_reading_at_all(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path) + before = len(chan.requests) + reads = [] + real_get = chan.get_messages + + async def counting(peer, ids=None): + reads.append(list(ids)) + return await real_get(peer, ids=ids) + + chan.get_messages = counting + rep = await sync_channel(chan, db, ch, opts()) + assert rep.adopted == [] and rep.scanned_to == 3 # only the saved posts were compared (ids 1-3) + assert reads == [[1, 2, 3]] # nothing was read beyond them: not a single event since the last look + assert len(chan.requests) - before == 1 # just the channel counter + await db.close() + + run(go()) + + +def test_messages_of_a_kind_the_bot_cannot_hold_are_left_alone(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path) + foreign(chan, "") # a poll or a sticker: no text, no supported media + rep = await sync_channel(chan, db, ch, opts()) + assert rep.adopted == [] and rep.unsupported == 1 + await db.close() + + run(go()) + + +def test_a_post_the_owner_made_the_bot_forget_is_not_brought_back(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path) + m = foreign(chan, "a post that cannot be deleted") + rep = await sync_channel(chan, db, ch, opts(ignore={(1, m.id)})) + assert rep.adopted == [] + await db.close() + + run(go()) + + +def test_a_dead_tail_longer_than_the_quick_look_needs_a_deep_look(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, three()) + chan._top, chan._pts = 3, 900 # lots of events happened: the counter is far above the newest message + first = await sync_channel(chan, db, ch, opts()) + assert (await db.get_sync(1)).last_top == 3 and first.first_look + chan._top = 600 # 597 ids went to messages that were deleted, then a new post appears + chan._pts = 901 + m = foreign(chan, "after a very long run of deleted ids") + assert m.id == 601 + quick = await sync_channel(chan, db, ch, opts()) + assert quick.adopted == [] # the quick look reads 300 ids beyond the likely end and stops + deep = await sync_channel(chan, db, ch, opts(deep=True)) + assert deep.adopted == [601] + assert (await db.get_sync(1)).last_top == 601 + await db.close() + + run(go()) + + +def test_the_automatic_looks_go_deep_once_a_day(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, three()) + chan._top, chan._pts = 3, 900 + await sync_channel(chan, db, ch, opts()) + chan._top, chan._pts = 600, 901 + m = foreign(chan, "hidden behind a long dead tail") + assert (await sync_channel(chan, db, ch, opts())).adopted == [] + # a day later the same automatic look reads every possible id + old = utcnow() - datetime.timedelta(hours=25) + state = await db.get_sync(1) + await db.save_sync(1, last_top=state.last_top, last_pts=state.last_pts, deep=False) + async with db.Session() as s: + row = await s.get(type(state), 1) + row.last_deep = old + await s.commit() + assert (await sync_channel(chan, db, ch, opts())).adopted == [m.id] + await db.close() + + run(go()) + + +# ======================================================================================== service messages +def test_service_messages_that_appeared_are_deleted_by_the_look(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path) + chan.msgs[4] = service_msg(4) + chan.msgs[5] = types.MessageService(id=5, peer_id=types.PeerChannel(1), date=OLD, action=types.MessageActionChatEditTitle("New")) + chan._top, chan._pts = 5, 5 + rep = await sync_channel(chan, db, ch, opts()) + assert rep.services_deleted == 2 and rep.services_failed == 0 + assert 4 not in chan.msgs and 5 not in chan.msgs and sorted(chan.msgs) == [1, 2, 3] + assert rep.adopted == [] + await db.close() + + run(go()) + + +def test_service_messages_stay_when_the_switch_is_off(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path) + chan.msgs[4] = service_msg(4) + chan._top, chan._pts = 4, 4 + rep = await sync_channel(chan, db, ch, opts(delete_services=False)) + assert rep.services_deleted == 0 and 4 in chan.msgs + await db.close() + + run(go()) + + +def test_a_service_message_the_bot_may_not_delete_is_counted(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path) + chan.msgs[4] = service_msg(4) + chan._top, chan._pts = 4, 4 + chan.undeletable.add(4) + rep = await sync_channel(chan, db, ch, opts()) + assert (rep.services_deleted, rep.services_failed) == (0, 1) and rep.services_error + await db.close() + + run(go()) + + +# ============================================================================================= errors and busy +def test_a_channel_the_bot_cannot_read_is_reported_not_raised(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, three()) + chan.fail["GetFullChannelRequest"] = errors.ChannelPrivateError(request=None) + rep = await sync_channel(chan, db, ch, opts()) + assert rep.error and "ChannelPrivateError" in rep.error + assert len(await db.sent_posts(1)) == 3 + chan.fail.clear() + chan.fail["GetMessagesRequest"] = errors.ChannelPrivateError(request=None) + rep = await sync_channel(chan, db, ch, opts()) + assert rep.error and len(await db.sent_posts(1)) == 3 + await db.close() + + run(go()) + + +def test_a_long_job_that_starts_cuts_the_look_short(tmp_path): + async def go(): + chan, db, ch = await looked(tmp_path) + m = foreign(chan, "new while a repost runs") + del chan.msgs[2] + chan._pts += 1 + rep = await sync_channel(chan, db, ch, opts(), busy=lambda: True) + assert rep.busy and rep.deleted == [] and rep.adopted == [] + assert len(await db.sent_posts(1)) == 3 + rep = await sync_channel(chan, db, ch, opts()) # the job is over + assert rep.deleted == [2] and rep.adopted == [m.id] + await db.close() + + run(go()) + + +# =================================================================================== looking at given ids only +def test_sync_ids_handles_edits_deletes_new_posts_and_notices(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, three()) + chan.msgs[1].message = "edited" + del chan.msgs[3] + new = foreign(chan, "added") + chan.msgs[9] = service_msg(9) + chan._top = 9 + ids = [1, 3, new.id, 9, 2] + rep = await sync_ids(chan, db, ch, ids, opts(), adopt_ids={new.id, 9}) + assert rep.edited == [1] and rep.deleted == [3] and rep.adopted == [new.id] + assert rep.services_deleted == 1 and 9 not in chan.msgs + assert (await db.find_by_message(1, 2)).text == "second" + await db.close() + + run(go()) + + +def test_an_edit_of_a_post_the_bot_never_saved_is_history_and_ignored(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, three()) + old = old_msg(7, "an old post, edited today") + chan.msgs[7] = old + chan._top = 7 + rep = await sync_ids(chan, db, ch, [7], opts(), adopt_ids=set()) + assert rep.adopted == [] and await db.find_by_message(1, 7) is None + await db.close() + + run(go()) + + +def test_sync_ids_reports_what_is_too_fresh(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, three()) + new = foreign(chan, "right now", age=0) + await db.update_post((await db.find_by_message(1, 1)).id, text="saved a second ago") + chan.msgs[1].message = "different" + rep = await sync_ids(chan, db, ch, [1, new.id], opts(grace=60), adopt_ids={new.id}) + assert rep.young == [1] and rep.young_new == [new.id] and rep.adopted == [] and rep.edited == [] + await db.close() + + run(go()) + + +# ================================================================================================ the database +def test_adopting_a_message_twice_saves_it_once(tmp_path): + async def go(): + db = await fresh_db(db_url_for(tmp_path)) + await db.save_channel(1, 5, "Chan", "chan", 99) + p, created = await db.adopt_message(1, 50, {"text": "x"}, sent_at=OLD) + assert created and p.source == "adopted" + again, created = await db.adopt_message(1, 50, {"text": "y"}) + assert again is None and created is False + assert (await db.find_by_message(1, 50)).text == "x" + await db.close() + + run(go()) + + +def test_a_reposted_copy_takes_the_place_of_a_post_the_sync_saved_first(tmp_path): + async def go(): + db = await fresh_db(db_url_for(tmp_path)) + await db.save_channel(1, 5, "Chan", "chan", 99) + await db.adopt_message(1, 50, {"text": "picked up by the sync"}) + await db.create_migration("m1", 1, old=None, new=None, include_typed=False, include_posts=False, first_id=1, last_id=9, partial=False, user_id=99) + await db.record_repost("m1", 1, [{"old_id": 1, "new_id": 50, "post": {"text": "the copy"}}], 99) + p = await db.find_by_message(1, 50) + assert p.text == "the copy" and p.source == "bot" + await db.close() + + run(go()) + + +def test_publishing_takes_the_place_of_a_post_the_sync_saved_first(tmp_path): + async def go(): + db = await fresh_db(db_url_for(tmp_path)) + await db.save_channel(1, 5, "Chan", "chan", 99) + await db.adopt_message(1, 60, {"text": "picked up first"}) + draft = await db.create_post(channel_id=1, status="draft", text="my draft", created_by=99) + assert await db.release_slot(1, 60, keep_pid=draft.id) == 1 + sent = await db.update_post(draft.id, status="sent", message_id=60) + assert sent.message_id == 60 and (await db.find_by_message(1, 60)).text == "my draft" + await db.close() + + run(go()) + + +def test_the_sync_update_only_applies_to_an_unchanged_post(tmp_path): + async def go(): + db = await fresh_db(db_url_for(tmp_path)) + await db.save_channel(1, 5, "Chan", "chan", 99) + post = await db.create_post(channel_id=1, message_id=5, status="sent", text="v1", created_by=99) + seen = (await db.get_post(post.id)).updated_at + assert await db.sync_update_post(post.id, seen, {"text": "v2"}) is True + assert await db.sync_update_post(post.id, seen, {"text": "v3"}) is False # it changed since `seen` + assert (await db.get_post(post.id)).text == "v2" + await db.close() + + run(go()) + + +def test_servicemsg_remove_reports_refusals_instead_of_raising(tmp_path): + async def go(): + chan = FakeChannelClient({1: service_msg(1), 2: service_msg(2)}) + peer = types.InputPeerChannel(1, 5) + ok = await remove(chan, peer, [1, 2]) + assert (ok.deleted, ok.failed, ok.error) == (2, 0, None) + chan.msgs[3] = service_msg(3) + chan.fail["DeleteMessagesRequest"] = errors.ChatAdminRequiredError(request=None) + bad = await remove(chan, peer, [3]) + assert bad.failed == 1 and bad.error_name == "ChatAdminRequiredError" + + run(go()) diff --git a/tests/test_sync_old_posts.py b/tests/test_sync_old_posts.py new file mode 100644 index 0000000000000000000000000000000000000000..17122fd758328ce12ab545be95120f56a6373444 --- /dev/null +++ b/tests/test_sync_old_posts.py @@ -0,0 +1,283 @@ +"""The sync and the posts it reads into My posts from before the bot was added. + +* a saved post that was deleted in the channel leaves My posts - also at the first look, when there is no earlier look to + compare with: the bot only holds back when it can't read ANY message of the channel; +* what Telegram itself does to a channel (a copyright strike) is never taken for an edit or a deletion; +* the older posts are followed like every other saved post: what admins change in them outside the bot (edited, deleted) + reaches My posts, in the timed check and in the live watch. +""" +from telethon import types + +from app.sync_engine import sees_live_messages, sync_channel +from app.tgutil import media_info + +from .fakes import FakeChannelClient, markup, photo_media, url_btn +from .test_restricted import CHANNEL_NOTICE, NOTICE, seven, strike +from .test_sync import old_msg, opts, run, world +from .test_syncer import delete_update, edit_update, make_app + +PEER = types.InputPeerChannel(1, 5) + + +# ================================================================================ deleted posts at the first look +def test_saved_posts_deleted_in_the_channel_leave_my_posts_at_the_first_look(tmp_path): + """The real case: seven saved posts, all of them deleted in the channel while the bot was not looking, and older posts + that the very same look reads in. The bot reads those, so it is not blind: the seven are really gone.""" + async def go(): + chan, db, ch = await world(tmp_path, seven()) # seven saved posts ... + chan.msgs.clear() # ... all deleted in the channel + for i in range(8, 18): + chan.msgs[i] = old_msg(i, f"older post {i}") + chan._top = chan._pts = 17 + rep = await sync_channel(chan, db, ch, opts()) + assert rep.first_look and rep.anomaly is None and rep.error is None + assert sorted(rep.deleted) == list(range(1, 8)) and rep.checked == 7 + assert rep.imported == 10 and rep.history_done + assert [p.message_id for p in await db.sent_posts(1)] == list(range(8, 18)) # the seven are gone, the older ones are in + await db.close() + + run(go()) + + +def test_the_same_without_reading_the_older_posts(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, seven()) + chan.msgs.clear() + chan.msgs[8] = old_msg(8, "a post nobody saved") + chan._top = chan._pts = 8 + rep = await sync_channel(chan, db, ch, opts(history=False)) + assert sorted(rep.deleted) == list(range(1, 8)) and rep.anomaly is None and rep.imported == 0 + assert await db.sent_posts(1) == [] + await db.close() + + run(go()) + + +def test_the_bot_looks_downwards_from_the_event_counter_for_a_message_it_can_read(tmp_path): + async def go(): + chan = FakeChannelClient({1: old_msg(1, "a"), 2: old_msg(2, "b")}, username="chan") + chan._pts = 1000 # a thousand events since: the messages are far below the counter + assert await sees_live_messages(chan, PEER, 1000, pause=0) + assert not await sees_live_messages(chan, PEER, 1000, pause=0, tries=3) # 300 ids are not enough to get down to them + assert not await sees_live_messages(chan, PEER, None) and not await sees_live_messages(chan, PEER, 0) + empty = FakeChannelClient({}, username="chan") + assert not await sees_live_messages(empty, PEER, 50, pause=0) + # a service message is something the bot can read, too + only_notice = FakeChannelClient({3: types.MessageService(id=3, peer_id=types.PeerChannel(1), date=None, action=types.MessageActionPinMessage())}, username="chan") + assert await sees_live_messages(only_notice, PEER, 3, pause=0) + + run(go()) + + +def test_when_the_counter_is_far_above_the_messages_the_deleted_posts_still_leave(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, seven()) + chan.msgs.clear() + chan.msgs[8] = old_msg(8, "still there") + chan._top, chan._pts = 8, 1000 # many edits and deletions since + rep = await sync_channel(chan, db, ch, opts(history=False)) + assert sorted(rep.deleted) == list(range(1, 8)) and rep.anomaly is None + await db.close() + + run(go()) + + +def test_when_nothing_at_all_can_be_read_nothing_is_removed_and_the_report_says_why(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, seven()) + chan.msgs.clear() # the bot sees nothing: it may have lost access + rep = await sync_channel(chan, db, ch, opts()) + assert rep.deleted == [] and len(await db.sent_posts(1)) == 7 + assert rep.anomaly and "All 7 saved posts look deleted" in rep.anomaly + assert "can't read any other message of the channel" in rep.anomaly and "none was removed" in rep.anomaly + await db.close() + + run(go()) + + +def test_a_long_job_that_starts_while_the_bot_is_unsure_cuts_the_look_short(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, seven()) + chan.msgs.clear() + calls = [0] + + def busy(): + calls[0] += 1 + return calls[0] > 1 # free while the posts are read, busy by the time the bot has to decide + + rep = await sync_channel(chan, db, ch, opts(), busy=busy) + assert rep.busy and rep.deleted == [] and rep.anomaly is None and len(await db.sent_posts(1)) == 7 + await db.close() + + run(go()) + + +# ============================================================================================ what Telegram does +def test_a_struck_channel_is_left_alone_even_when_every_saved_post_would_look_deleted(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, seven()) + chan.restriction = CHANNEL_NOTICE # the whole channel is struck + chan.msgs.clear() # ... and Telegram shows nothing of it + rep = await sync_channel(chan, db, ch, opts()) + assert rep.restricted_channel == CHANNEL_NOTICE + assert rep.deleted == [] and rep.edited == [] and rep.adopted == [] and rep.imported == 0 and not rep.checked + posts = await db.sent_posts(1) + assert len(posts) == 7 and [p.text for p in posts] == [f"post number {i}" for i in range(1, 8)] + await db.close() + + run(go()) + + +def test_posts_held_back_by_telegram_are_neither_edited_nor_removed_even_when_every_post_is_held_back(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, seven()) + before = {p.message_id: (p.text, p.buttons, p.entities) for p in await db.sent_posts(1)} + for m in chan.msgs.values(): # Telegram's own mark and its notice instead of the text and the buttons + strike(m) + m.message, m.reply_markup = NOTICE, None + rep = await sync_channel(chan, db, ch, opts()) + assert sorted(rep.restricted) == list(range(1, 8)) + assert rep.edited == [] and rep.deleted == [] and rep.anomaly is None and rep.buttons_missing == [] + assert {p.message_id: (p.text, p.buttons, p.entities) for p in await db.sent_posts(1)} == before + await db.close() + + run(go()) + + +def test_a_notice_without_any_mark_is_not_taken_for_an_edit_either(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, seven()) + for m in chan.msgs.values(): + m.message = NOTICE # some places hand out the notice as the text + rep = await sync_channel(chan, db, ch, opts()) + assert sorted(rep.restricted) == list(range(1, 8)) and rep.edited == [] and rep.deleted == [] + assert [p.text for p in await db.sent_posts(1)] == [f"post number {i}" for i in range(1, 8)] + await db.close() + + run(go()) + + +def test_held_back_posts_stay_while_the_posts_that_are_really_gone_leave(tmp_path): + async def go(): + chan, db, ch = await world(tmp_path, seven()) + for i in (1, 2, 3): + strike(chan.msgs[i]) + chan.msgs[i].message = NOTICE + for i in (4, 5, 6, 7): + del chan.msgs[i] + chan._pts += 4 + rep = await sync_channel(chan, db, ch, opts()) + assert sorted(rep.deleted) == [4, 5, 6, 7] and sorted(rep.restricted) == [1, 2, 3] and rep.edited == [] + posts = await db.sent_posts(1) + assert [p.message_id for p in posts] == [1, 2, 3] and [p.text for p in posts] == [f"post number {i}" for i in (1, 2, 3)] + await db.close() + + run(go()) + + +# ================================================================== the older posts are followed like any other post +def older(n=8): + return { + i: old_msg( + i, f"older post {i}", markup=markup([url_btn("Watch", f"https://t.me/old/{i}")]), + media=photo_media(10 + i) if i == 4 else None, + ) + for i in range(1, n + 1) + } + + +async def imported(tmp_path, n=8): + """A channel whose posts all come from before the bot was added: the first look reads them into My posts.""" + chan, db, ch = await world(tmp_path, older(n), save=False) + rep = await sync_channel(chan, db, ch, opts()) + assert rep.first_look and rep.imported == n and rep.history_done + assert {p.source for p in await db.sent_posts(1)} == {"adopted"} + return chan, db, ch + + +def test_what_admins_do_to_the_older_posts_outside_the_bot_reaches_my_posts(tmp_path): + async def go(): + chan, db, ch = await imported(tmp_path) + chan.msgs[2].message = "older post 2, corrected by an admin" + chan.msgs[2].entities = [types.MessageEntityBold(0, 5)] + chan.msgs[3].reply_markup = markup([url_btn("New link", "https://t.me/new/3"), url_btn("Site", "https://example.org")]) + chan.msgs[4].media = photo_media(99) # the picture was replaced + del chan.msgs[5] + chan._pts += 4 + rep = await sync_channel(chan, db, ch, opts()) + assert sorted(rep.edited) == [2, 3, 4] and rep.deleted == [5] and rep.checked == 8 and rep.anomaly is None + rows = {p.message_id: p for p in await db.sent_posts(1)} + assert sorted(rows) == [1, 2, 3, 4, 6, 7, 8] + assert rows[2].text == "older post 2, corrected by an admin" and rows[2].entities == [{"k": "bold", "o": 0, "l": 5}] + assert rows[3].buttons == [[{"t": "New link", "u": "https://t.me/new/3"}, {"t": "Site", "u": "https://example.org"}]] + assert rows[4].media_file_id == media_info(chan.msgs[4])[1] + assert {p.source for p in rows.values()} == {"adopted"} # still the posts of others, now up to date + again = await sync_channel(chan, db, ch, opts()) + assert again.changed is False and again.edited == [] and again.deleted == [] + await db.close() + + run(go()) + + +def test_every_older_post_is_compared_on_each_look_not_only_the_newest(tmp_path): + async def go(): + chan, db, ch = await imported(tmp_path, n=250) # three requests' worth of posts + chan.msgs[1].message = "the oldest post, edited" + chan.msgs[250].message = "the newest post, edited" + del chan.msgs[120] + chan._pts += 3 + rep = await sync_channel(chan, db, ch, opts()) + assert rep.checked == 250 and sorted(rep.edited) == [1, 250] and rep.deleted == [120] + assert (await db.find_by_message(1, 1)).text == "the oldest post, edited" + assert await db.find_by_message(1, 120) is None + await db.close() + + run(go()) + + +def test_the_live_watch_follows_an_admin_who_edits_or_deletes_an_older_post(tmp_path): + async def go(): + app = await make_app(tmp_path) # nothing saved by the bot + sy = app.ctx.syncer + for i, m in older(6).items(): + app.tg.msgs[i] = m + app.tg._top = app.tg._pts = 6 + await app.text("/sync") # the first look reads the older posts into My posts + assert len(await app.db.sent_posts(1)) == 6 + # an admin edits one of them and deletes another, from the Telegram app + m = app.tg.msgs[2] + m.message, m.entities = "older post 2, with a correction", [types.MessageEntityItalic(0, 5)] + await app.raw(edit_update(m)) + del app.tg.msgs[5] + await app.raw(delete_update(1, [5])) + await sy.flush_events() + p = await app.db.find_by_message(1, 2) + assert p.text == "older post 2, with a correction" and p.entities == [{"k": "italic", "o": 0, "l": 5}] and p.source == "adopted" + assert sy.last_reports[1].edited == [2] + assert await app.db.find_by_message(1, 5) is None + assert sorted(x.message_id for x in await app.db.sent_posts(1)) == [1, 2, 3, 4, 6] + await app.db.close() + + run(go()) + + +def test_the_timed_check_follows_the_older_posts_too(tmp_path): + async def go(): + app = await make_app(tmp_path) + sy = app.ctx.syncer + plain = sy.options + sy.options = lambda **kw: plain(grace=0, **kw) # in real life the next check is minutes later: nothing is too fresh + for i, m in older(6).items(): + app.tg.msgs[i] = m + app.tg._top = app.tg._pts = 6 + await sy.run_all() # the timed check: the first look reads the older posts + assert len(await app.db.sent_posts(1)) == 6 + app.tg.msgs[3].message = "older post 3, edited while the bot was off" + del app.tg.msgs[1] + app.tg._pts += 2 + await sy.run_all() # ... and the next one compares them + assert (await app.db.find_by_message(1, 3)).text == "older post 3, edited while the bot was off" + assert await app.db.find_by_message(1, 1) is None + await app.db.close() + + run(go()) diff --git a/tests/test_syncer.py b/tests/test_syncer.py new file mode 100644 index 0000000000000000000000000000000000000000..a692315a5146a51241ffc89e598a684e57b7c63d --- /dev/null +++ b/tests/test_syncer.py @@ -0,0 +1,597 @@ +"""The live side of the sync (what Telegram's updates say), the timed check, service-message deletion and /sync.""" +import asyncio +import datetime + +from telethon import errors, types + +from app.db import utcnow +from app.syncer import Syncer + +from .fakes import FakeChannelClient, markup, photo_media, url_btn +from .harness import App, norm +from .test_sync import OLD, foreign, old_msg, saved + +NOW = datetime.datetime.now(datetime.timezone.utc) + + +def run(coro): + return asyncio.run(coro) + + +# ------------------------------------------------------------------------------------------------ set-up +async def make_app(tmp_path, *, posts=(), **cfg): + """Channel 1 "Anime Channel" (the app's own fake) with `posts` saved the way the bot saved them a day ago.""" + app = App(tmp_path, edit_delay=0, **cfg) + await app.start() + app.tg.username, app.tg.title = "animech", "Anime Channel" + await app.db.save_channel(1, 5, "Anime Channel", "animech", 1) + for m in posts: + app.tg.msgs[m.id] = m + app.tg._top = app.tg._pts = max(app.tg._top, m.id) + await saved(app.db, m) + sy = app.ctx.syncer + sy.debounce, sy.max_debounce, sy.lock_wait, sy.rt_grace, sy.pause, sy.start_delay = 0.01, 0.2, 0.02, 0, 0, 0.01 + return app + + +def three(): + return [ + old_msg(1, "first"), + old_msg(2, "second", markup=markup([url_btn("Watch", "https://t.me/a/1")])), + old_msg(3, "third"), + ] + + +def new_update(m): + return types.UpdateNewChannelMessage(message=m, pts=m.id, pts_count=1) + + +def edit_update(m): + return types.UpdateEditChannelMessage(message=m, pts=m.id, pts_count=1) + + +def delete_update(cid, ids): + return types.UpdateDeleteChannelMessages(channel_id=cid, messages=list(ids), pts=0, pts_count=len(ids)) + + +def notice(i, action=None, cid=1): + return types.MessageService( + id=i, peer_id=types.PeerChannel(cid), date=NOW, action=action or types.MessageActionPinMessage() + ) + + +def dms(app): + """Texts the bot sent to people (not to channels).""" + return [e[2] for e in app.tg.sent if not isinstance(e[1], types.InputPeerChannel)] + + +# ============================================================================================ service messages +def test_every_kind_of_notice_is_deleted_the_moment_it_appears(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + actions = [ + types.MessageActionChatEditTitle("A new name"), + types.MessageActionChatEditPhoto(photo=types.PhotoEmpty(0)), + types.MessageActionChatDeletePhoto(), + types.MessageActionPinMessage(), + types.MessageActionGroupCall(call=types.InputGroupCall(1, 2)), + types.MessageActionHistoryClear(), + ] + for n, action in enumerate(actions, start=10): + app.tg.msgs[n] = notice(n, action) + await app.raw(new_update(app.tg.msgs[n])) + assert [i for i in app.tg.msgs if i >= 10] == [] + assert sorted(app.tg.msgs) == [1, 2, 3] # posts are never touched + assert len(await app.db.sent_posts(1)) == 3 + await app.db.close() + + run(go()) + + +def test_notices_stay_when_the_switch_is_off(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three(), delete_service_messages=False) + app.tg.msgs[10] = notice(10) + await app.raw(new_update(app.tg.msgs[10])) + assert 10 in app.tg.msgs + await app.db.close() + + run(go()) + + +def test_notices_in_channels_that_are_not_connected_are_left_alone(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + other = app.tg.add_channel(FakeChannelClient({5: notice(5, cid=2)}, username="other", cid=2, title="Other")) + before = len(app.tg.requests) + len(other.requests) + await app.raw(new_update(other.msgs[5])) + assert 5 in other.msgs and len(app.tg.requests) + len(other.requests) == before # not even a request + # a channel that was removed from the bot counts as not connected too + await app.db.set_channel_active(1, False) + app.ctx.syncer.forget_cache() + app.tg.msgs[10] = notice(10) + await app.raw(new_update(app.tg.msgs[10])) + assert 10 in app.tg.msgs + await app.db.close() + + run(go()) + + +def test_the_owner_is_told_once_when_the_bot_may_not_delete(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + app.tg.fail["DeleteMessagesRequest"] = errors.ChatAdminRequiredError(request=None) + for i in (10, 11, 12): + app.tg.msgs[i] = notice(i) + await app.raw(new_update(app.tg.msgs[i])) + texts = [norm(t) for t in dms(app)] + assert len(texts) == 1 and "Anime Channel" in texts[0] and "Delete messages" in texts[0] + assert "DELETE_SERVICE_MESSAGES" in texts[0] + assert {10, 11, 12} <= set(app.tg.msgs) + # a day later the same problem is worth saying again + app.ctx.syncer.tell_every = 0 + await app.raw(new_update(app.tg.msgs[10])) + assert len(dms(app)) == 2 + await app.db.close() + + run(go()) + + +def test_other_refusals_are_only_logged(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + app.tg.fail["DeleteMessagesRequest"] = errors.MessageDeleteForbiddenError(request=None) + app.tg.msgs[10] = notice(10) + await app.raw(new_update(app.tg.msgs[10])) + assert dms(app) == [] and 10 in app.tg.msgs + await app.db.close() + + run(go()) + + +def test_notices_are_deleted_even_when_the_automatic_sync_is_switched_off(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three(), sync_interval_minutes=0) + app.tg.msgs[10] = notice(10) + await app.raw(new_update(app.tg.msgs[10])) + assert 10 not in app.tg.msgs + await app.db.close() + + run(go()) + + +def test_notices_are_deleted_while_a_long_job_runs(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + async with app.ctx.lock: + app.tg.msgs[10] = notice(10) + await app.raw(new_update(app.tg.msgs[10])) + assert 10 not in app.tg.msgs + await app.db.close() + + run(go()) + + +# ============================================================================================== live changes +def test_a_new_post_by_someone_else_is_added_a_moment_later(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + sy = app.ctx.syncer + m = foreign(app.tg, "from the Telegram app", markup=markup([url_btn("Open", "https://example.org")])) + await app.raw(new_update(m)) + assert await app.db.find_by_message(1, m.id) is None # not yet: the wait lets the bot finish its own business + await sy.flush_events() + p = await app.db.find_by_message(1, m.id) + assert p.source == "adopted" and p.text == "from the Telegram app" and p.buttons == [[{"t": "Open", "u": "https://example.org"}]] + await app.db.close() + + run(go()) + + +def test_the_bots_own_posts_are_not_looked_at(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + sy = app.ctx.syncer + mine = app.tg._new("sent by the bot", None, None) # out=True + await app.raw(new_update(mine)) + assert not sy._pending() + await app.db.close() + + run(go()) + + +def test_nothing_is_queued_while_a_long_job_runs_or_when_the_sync_is_off(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + sy = app.ctx.syncer + m = foreign(app.tg, "x") + async with app.ctx.lock: + await app.raw(new_update(m)) + await app.raw(edit_update(app.tg.msgs[1])) + assert not sy._pending() + off = await make_app(tmp_path / "off", posts=three(), sync_interval_minutes=0) + m2 = foreign(off.tg, "y") + await off.raw(new_update(m2)) + await off.raw(edit_update(off.tg.msgs[1])) + await off.raw(delete_update(1, [2])) + assert not off.ctx.syncer._pending() and len(await off.db.sent_posts(1)) == 3 + await app.db.close() + await off.db.close() + + (tmp_path / "off").mkdir() + run(go()) + + +def test_an_edit_made_by_an_admin_is_recorded(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + sy = app.ctx.syncer + m = app.tg.msgs[3] + m.message, m.entities = "third, with a correction", [types.MessageEntityBold(0, 5)] + await app.raw(edit_update(m)) + await sy.flush_events() + p = await app.db.find_by_message(1, 3) + assert p.text == "third, with a correction" and p.entities == [{"k": "bold", "o": 0, "l": 5}] + assert sy.last_reports[1].edited == [3] + await app.db.close() + + run(go()) + + +def test_the_echo_of_an_edit_made_through_the_bot_changes_nothing(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + sy = app.ctx.syncer + sy.rt_grace = 60 # the bot saved the post a moment ago + pid = (await app.db.find_by_message(1, 1)).id + await app.db.update_post(pid, text="the owner's new text") # updated_at = now + app.tg.msgs[1].message = "the owner's new text" + await app.raw(edit_update(app.tg.msgs[1])) + sy.max_tries = 1 + await sy.flush_events() + assert (await app.db.find_by_message(1, 1)).text == "the owner's new text" + assert sy.last_reports[1].edited == [] + await app.db.close() + + run(go()) + + +def test_a_post_deleted_by_an_admin_leaves_my_posts_at_once(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + sy = app.ctx.syncer + m = foreign(app.tg, "will be deleted before the wait is over") + await app.raw(new_update(m)) + await app.raw(edit_update(app.tg.msgs[2])) + del app.tg.msgs[2] + await app.raw(delete_update(1, [2, m.id])) + assert await app.db.find_by_message(1, 2) is None # no flush needed + assert sy._news == {1: set()} and sy._edits == {1: set()} # and nothing is left to look at for them + await sy.flush_events() + assert await app.db.find_by_message(1, m.id) is None + assert sorted(p.message_id for p in await app.db.sent_posts(1)) == [1, 3] + await app.db.close() + + run(go()) + + +def test_deleted_posts_of_other_channels_are_ignored(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + await app.raw(delete_update(77, [1, 2, 3])) + assert len(await app.db.sent_posts(1)) == 3 + await app.db.close() + + run(go()) + + +def test_a_message_that_is_still_too_fresh_is_looked_at_again(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + sy = app.ctx.syncer + sy.rt_grace, sy.max_tries = 0.15, 500 + m = foreign(app.tg, "just posted", age=0) + await app.raw(new_update(m)) + await asyncio.wait_for(sy.flush_events(), 5) + p = await app.db.find_by_message(1, m.id) + assert p is not None and p.source == "adopted" + assert not sy._pending() and sy._tries == {} + await app.db.close() + + run(go()) + + +def test_a_message_that_never_gets_old_enough_is_given_up(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + sy = app.ctx.syncer + sy.rt_grace, sy.max_tries = 3600, 2 + m = foreign(app.tg, "from the future", age=0) + await app.raw(new_update(m)) + await asyncio.wait_for(sy.flush_events(), 5) + assert await app.db.find_by_message(1, m.id) is None and not sy._pending() and sy._tries == {} + await app.db.close() + + run(go()) + + +def test_the_queue_waits_for_a_long_job_to_finish(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + sy = app.ctx.syncer + m = foreign(app.tg, "posted before the long job started") + await app.raw(new_update(m)) + async with app.ctx.lock: + task = asyncio.create_task(sy.flush_events()) + await asyncio.sleep(0.15) + assert not task.done() and await app.db.find_by_message(1, m.id) is None + await asyncio.wait_for(task, 5) + assert (await app.db.find_by_message(1, m.id)).source == "adopted" + await app.db.close() + + run(go()) + + +def test_a_burst_of_changes_becomes_one_look_at_the_whole_channel(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + sy = app.ctx.syncer + sy.max_ids = 2 + for i in (1, 2, 3): + app.tg.msgs[i].message = f"edited {i}" + await app.raw(edit_update(app.tg.msgs[i])) + await sy.flush_events() + rep = sy.last_reports[1] + assert rep.checked == 3 and sorted(rep.edited) == [1, 2, 3] # compared as a whole, not id by id + await app.db.close() + + run(go()) + + +# ===================================================================================================== the timer +def test_the_timed_check_looks_at_every_channel_and_gives_way_to_long_jobs(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + sy = app.ctx.syncer + app.tg.msgs[2].message = "edited meanwhile" + async with app.ctx.lock: + assert await sy.run_all() == [] # a long job is running: nothing is read + assert (await app.db.find_by_message(1, 2)).text == "second" + reports = await sy.run_all() + assert [r.channel.id for r in reports] == [1] and reports[0].edited == [2] + assert sy.last_reports[1] is reports[0] + await app.db.close() + + run(go()) + + +def test_one_channel_that_fails_does_not_stop_the_others(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + broken = app.tg.add_channel(FakeChannelClient({1: old_msg(1, "x")}, username="broken", cid=2, title="Broken")) + await app.db.save_channel(2, 6, "Broken", "broken", 1) + await app.db.create_post(channel_id=2, message_id=1, status="sent", source="bot", created_by=1, text="x", + created_at=OLD, updated_at=OLD, sent_at=OLD) + broken.fail["GetMessagesRequest"] = RuntimeError("the network dropped") + app.tg.msgs[3].message = "edited" + reports = await app.ctx.syncer.run_all() + by_id = {r.channel.id: r for r in reports} + assert by_id[1].edited == [3] and by_id[1].error is None + assert by_id[2].error and "RuntimeError" in by_id[2].error + await app.db.close() + + run(go()) + + +def test_the_timer_starts_and_stops_with_the_bot(tmp_path): + async def go(): + off = await make_app(tmp_path / "off", posts=three(), sync_interval_minutes=0) + off.ctx.syncer.start() + assert off.ctx.syncer._tasks == [] and off.ctx.syncer.enabled is False + + app = await make_app(tmp_path, posts=three()) + sy = app.ctx.syncer + app.tg.msgs[1].message = "edited" + sy.start() + assert len(sy._tasks) == 2 + for _ in range(100): + if 1 in sy.last_reports: + break + await asyncio.sleep(0.05) + assert sy.last_reports[1].edited == [1] + await sy.stop() + assert sy._tasks == [] + await app.db.close() + await off.db.close() + + (tmp_path / "off").mkdir() + run(go()) + + +def test_the_syncer_is_part_of_the_context_the_bot_builds(tmp_path): + async def go(): + app = await make_app(tmp_path) + assert isinstance(app.ctx.syncer, Syncer) + await app.db.close() + + run(go()) + + +# ============================================================================================ the /sync command +def test_sync_is_for_the_owner_only(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + app.uid = 555 + await app.text("/sync") + assert "private" in norm(app.out.last_text).lower() or "owner" in norm(app.out.last_text).lower() + assert app.ctx.syncer.last_reports == {} + await app.db.close() + + run(go()) + + +def test_sync_needs_a_channel_and_understands_only_its_options(tmp_path): + async def go(): + bare = App(tmp_path, edit_delay=0) + await bare.start() + await bare.text("/sync") + assert "No channels registered" in norm(bare.out.last_text) + await bare.db.close() + + app = await make_app(tmp_path / "b", posts=three()) + await app.text("/sync --bogus") + assert "I don't know “--bogus”" in norm(app.out.last_text) and "Usage: /sync" in norm(app.out.last_text) + await app.text("/sync --channel @nowhere") + assert "isn't registered" in norm(app.out.last_text) + await app.db.close() + + (tmp_path / "b").mkdir() + run(go()) + + +def test_sync_reports_what_it_found_in_every_channel(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + await app.text("/sync") # the first look + first = norm(app.out.last_text) + assert "Sync finished" in first and "Anime Channel" in first and "First look" in first + assert "3 saved post(s) compared" in first + + app.tg.msgs[2].message = "second, edited" + del app.tg.msgs[3] + app.tg._pts += 2 + new = foreign(app.tg, "from the app") + app.tg.msgs[new.id + 1] = notice(new.id + 1) + app.tg._top = new.id + 1 + app.tg._pts += 1 + app.tg.msgs[2].reply_markup = None # and the channel shows no keyboard for post 2 + await app.text("/sync") + text = norm(app.out.last_text) + assert "1 deleted in the channel" in text and "message 3" in text + assert "1 edited in the channel" in text and "message 2" in text + assert "1 new post(s) made outside the bot" in text and f"message {new.id}" in text + assert "1 service message(s) deleted" in text + assert "show no buttons in the channel (message 2)" in text and "Check buttons" in text + assert not app.ctx.lock.locked() + await app.text("/sync") + assert "Everything matches." in norm(app.out.last_text) or "show no buttons" in norm(app.out.last_text) + await app.db.close() + + run(go()) + + +def test_sync_looks_at_one_channel_only_when_asked(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + app.tg.add_channel(FakeChannelClient({}, username="movies", cid=2, title="Movies")) + await app.db.save_channel(2, 6, "Movies", "movies", 1) + await app.text("/sync --channel @movies") + text = norm(app.out.last_text) + assert "Movies" in text and "Anime Channel" not in text + assert set(app.ctx.syncer.last_reports) == {2} + await app.db.close() + + run(go()) + + +def test_sync_holds_the_long_job_lock_and_refuses_a_second_run(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + gate = asyncio.Event() + real_get = app.tg.get_messages + seen = [] + + async def slow(peer, ids=None): + seen.append(app.ctx.lock.locked()) + await gate.wait() + return await real_get(peer, ids=ids) + + app.tg.get_messages = slow + first = asyncio.create_task(app.text("/sync")) + await asyncio.sleep(0.1) + await app.text("/sync") + assert "still running" in norm(app.out.last_text) + gate.set() + await asyncio.wait_for(first, 5) + assert seen and all(seen) and not app.ctx.lock.locked() + await app.db.close() + + run(go()) + + +def test_sync_reports_a_channel_it_cannot_read(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + app.tg.fail["GetFullChannelRequest"] = errors.ChannelPrivateError(request=None) + await app.text("/sync") + text = norm(app.out.last_text) + assert "Anime Channel" in text and "ChannelPrivateError" in text + assert len(await app.db.sent_posts(1)) == 3 + await app.db.close() + + run(go()) + + +# ================================================================================== the rest of the bot +def test_forgetting_a_post_in_the_bot_keeps_the_sync_from_bringing_it_back(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + p = await app.db.find_by_message(1, 2) + await app.press(f"dly:{p.id}:b") + assert await app.db.find_by_message(1, 2) is None and (1, 2) in app.ctx.sync_ignore + assert 2 in app.tg.msgs # still in the channel + await app.text("/sync") # the first look + del app.tg.msgs[2] + assert (1, 2) in app.ctx.sync_ignore + await app.db.close() + + run(go()) + + +def test_a_post_the_sync_saved_first_does_not_stop_the_bot_from_publishing(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + draft = await app.db.create_post(channel_id=1, status="draft", text="my new post", created_by=1) + sent = app.tg._new("my new post", None, None) # what Telegram will answer the publish with + await app.db.adopt_message(1, sent.id, {"text": "picked up by the sync a moment earlier"}) + + async def send_message(peer, message="", **kw): + return sent + + app.tg.send_message = send_message + await app.press(f"pby:{draft.id}") + p = await app.db.find_by_message(1, sent.id) + assert p.id == draft.id and p.source == "bot" and p.text == "my new post" + await app.db.close() + + run(go()) + + +def test_the_panel_says_where_an_adopted_post_came_from(tmp_path): + from app.ui import panel_text + + async def go(): + app = await make_app(tmp_path, posts=three()) + p, _ = await app.db.adopt_message(1, 40, {"text": "made in the app"}) + ch = await app.db.get_channel(1) + assert "not made with this bot" in panel_text(p, ch) + await app.db.close() + + run(go()) + + +def test_photos_of_new_posts_survive_the_trip_to_my_posts(tmp_path): + async def go(): + app = await make_app(tmp_path, posts=three()) + m = foreign(app.tg, "a captioned photo", media=photo_media(41)) + await app.raw(new_update(m)) + await app.ctx.syncer.flush_events() + p = await app.db.find_by_message(1, m.id) + assert p.media_kind == "photo" and p.media_file_id.startswith("tl:") + await app.db.close() + + run(go()) + + +def test_utcnow_is_what_the_fresh_checks_compare_with(): + assert (utcnow() - NOW).total_seconds() < 3600 # sanity for the helpers above diff --git a/tests/test_units.py b/tests/test_units.py new file mode 100644 index 0000000000000000000000000000000000000000..3e65664fa8db8a37d59ac29ff760e2b026eb1f73 --- /dev/null +++ b/tests/test_units.py @@ -0,0 +1,272 @@ +import asyncio +import datetime +from types import SimpleNamespace + +import pytest +from telethon import TelegramClient, types +from telethon.sessions import MemorySession + +from app import buttons as B +from app.common import UserError +from app.db import normalize_db_url +from app.channelref import parse_channel_ref +from app.handlers.panel import extract_content +from app.handlers.replace import parse_post_link, parse_replace_args +from app.linkswap import apply_span_replacements, classify_url, normalize_username, swap_url +from app.suggest import advance_plain, build_suggestion +from app.tgutil import ( + build_markup, + button_url, + classify_media, + de_entities, + is_callback_button, + media_from_ref, + pack_file_id, + ser_entities, + ser_markup, + utf16_len, +) + +from .fakes import FakeChannelClient, cb_btn, make_msg, markup, photo_media, url_btn +from .harness import App + +NOW = datetime.datetime.now(datetime.timezone.utc) + + +def photo_msg(caption="cap", entities=None): + photo = types.Photo(1, 2, b"ref", NOW, [types.PhotoSize("x", 100, 100, 999)], 2) + return make_msg(5, caption, entities, media=types.MessageMediaPhoto(photo=photo)) + + +def video_msg(gif=False): + attrs = [types.DocumentAttributeVideo(3.0, 100, 100)] + if gif: + attrs.append(types.DocumentAttributeAnimated()) + doc = types.Document(9, 8, b"ref", NOW, "video/mp4", 1000, 2, attrs) + return make_msg(6, "v", media=types.MessageMediaDocument(document=doc)) + + +# ------------------------------------------------------------------ entities / markup +def test_entity_roundtrip_keeps_formatting_and_unknown_types(): + ents = [ + types.MessageEntityBold(0, 3), + types.MessageEntityTextUrl(4, 2, "https://t.me/x?start=1"), + types.MessageEntityPre(7, 3, "python"), + types.MessageEntitySpoiler(11, 2), + types.MessageEntityUrl(14, 5), # auto entity: not stored + types.MessageEntityFormattedDate(20, 4, NOW), # unknown to us: kept byte-for-byte + ] + data = ser_entities(ents) + assert [d["k"] for d in data] == ["bold", "url", "pre", "spoiler", "raw"] + back = de_entities(data) + assert [type(e).__name__ for e in back] == [ + "MessageEntityBold", "MessageEntityTextUrl", "MessageEntityPre", "MessageEntitySpoiler", "MessageEntityFormattedDate" + ] + assert back[1].url == "https://t.me/x?start=1" and back[2].language == "python" + + +def test_markup_roundtrip_keeps_other_bots_buttons_and_colours(): + style = types.KeyboardButtonStyle(bg_success=True) + coloured = types.KeyboardButton(text="Go", type=types.InlineButtonTypeUrl("https://t.me/x"), style=style) + mk = markup([coloured, cb_btn("👍 3", b"react:1")], [url_btn("Two", "https://t.me/y")]) + rows = ser_markup(mk) + assert rows[0][0]["u"] == "https://t.me/x" and "s" in rows[0][0] + assert rows[0][1]["raw"] and rows[1][0]["u"] == "https://t.me/y" + rebuilt = build_markup(rows) + b0, b1 = rebuilt.rows[0].buttons + assert button_url(b0) == "https://t.me/x" and b0.style.bg_success + assert is_callback_button(b1) and b1.type.data == b"react:1" + + +def test_utf16_len_counts_emoji_as_two(): + assert utf16_len("a😀") == 3 + + +def test_apply_span_replacements_shifts_entities(): + ents = [types.MessageEntityBold(14, 3), types.MessageEntityItalic(0, 4), types.MessageEntityCode(5, 13)] + text, out = apply_span_replacements("open t.me/abc now", ents, [(10, 13, "longer")]) + assert text == "open t.me/longer now" + assert (out[0].offset, out[0].length) == (17, 3) # after the change: moved by +3 + assert (out[1].offset, out[1].length) == (0, 4) # before it: untouched + assert (out[2].offset, out[2].length) == (5, 16) # spanning it: grows + + +# -------------------------------------------------------------------- media handling +def test_extract_content_photo_video_gif_and_text(): + c = extract_content(photo_msg("hello", [types.MessageEntityBold(0, 5)])) + assert c["media_kind"] == "photo" and c["text"] == "hello" and c["entities"][0]["k"] == "bold" + assert c["media_file_id"] + assert classify_media(video_msg()) == "video" and classify_media(video_msg(gif=True)) == "animation" + t = extract_content(make_msg(1, "plain")) + assert t["media_kind"] is None and t["media_file_id"] is None + with pytest.raises(UserError): + extract_content(make_msg(1, " ")) + with pytest.raises(UserError): + extract_content(photo_msg("x" * 1025)) + with pytest.raises(UserError): # a poll can't be used in a post + extract_content(make_msg(1, "q", media=types.MessageMediaPoll(types.Poll(1, [], types.TextWithEntities("q", []), None), types.PollResults()))) + + +def test_link_preview_photo_is_not_mistaken_for_a_photo_post(): + page = types.WebPage(id=1, url="https://x.com", display_url="x.com", hash=0, photo=types.Photo(1, 2, b"r", NOW, [], 2)) + m = make_msg(2, "look https://x.com", media=types.MessageMediaWebPage(webpage=page)) + assert classify_media(m) is None + assert extract_content(m)["media_kind"] is None + + +def test_bot_file_id_can_be_reused_when_sending(): + m = photo_msg() + fid = pack_file_id(m) + assert fid.startswith("tl:") + + async def go(blank): + client = TelegramClient(MemorySession(), 1, "h") + # what send_file / edit_message do with the media object + _, media, _ = await client._file_to_media(media_from_ref(fid, blank_reference=blank)) + return media + + assert isinstance(asyncio.run(go(False)), types.InputMediaPhoto) + blank = asyncio.run(go(True)) + assert blank.id.file_reference == b"" and blank.id.id == 1 and blank.id.access_hash == 2 + doc_ref = pack_file_id(video_msg()) + assert media_from_ref(doc_ref).document.id == 9 + + +# --------------------------------------------------------------------------- parsing +def test_button_parsing_and_limits(): + assert B.parse_buttons_text("A - t.me/x | B - https://y.com/?a=1\nC — https://z.com") == [ + [{"t": "A", "u": "https://t.me/x"}, {"t": "B", "u": "https://y.com/?a=1"}], + [{"t": "C", "u": "https://z.com"}], + ] + for bad in ("no link here", "- https://x.com", "A - htp://x"): + with pytest.raises(ValueError): + B.parse_buttons_text(bad) + with pytest.raises(ValueError): + B.parse_buttons_text(" | ".join(f"b{i} - https://x.com/{i}" for i in range(9))) + + +def test_move_button_edges(): + rows = [[{"t": "a", "u": "u"}, {"t": "b", "u": "u"}], [{"t": "c", "u": "u"}]] + assert B.move_button(rows, 0, 0, "l")[0] == rows and B.move_button(rows, 0, 0, "u")[0] == rows + r, nr, nc = B.move_button(rows, 1, 0, "u") # keeps its column when it can + assert [[b["t"] for b in x] for x in r] == [["c", "a", "b"]] and (nr, nc) == (0, 0) + r, nr, nc = B.move_button(rows, 0, 1, "d") + assert [[b["t"] for b in x] for x in r] == [["a"], ["c", "b"]] and (nr, nc) == (1, 1) + r, nr, nc = B.move_button([[{"t": "a"}, {"t": "b"}]], 0, 1, "d") # last row with company -> new row + assert [[b["t"] for b in x] for x in r] == [["a"], ["b"]] and (nr, nc) == (1, 0) + assert B.delete_button([[{"t": "a"}]], 0, 0) == [] + + +def test_replace_args_and_refs(): + old, new, f = parse_replace_args("@Bharath goku --last 50 --posts --channel @ch") + assert (old, new, f["last"], f["posts"], f["channel"]) == ("Bharath", "goku", 50, True, "@ch") + for bad in ("@a", "@a @a", "@a @b --wat", "@a @b --last x", "@a b!d"): + with pytest.raises(ValueError): + parse_replace_args(bad) + assert normalize_username("https://t.me/foo_bar/") == "foo_bar" and normalize_username("@x y") is None + assert parse_channel_ref("@animech") == "animech" and parse_channel_ref("https://t.me/c/123456/7") == 123456 + assert parse_channel_ref("-1001234567890") == 1234567890 and parse_channel_ref("???") is None + assert parse_post_link("https://t.me/c/1723201445/9084") == (1723201445, 9084) + assert parse_post_link("https://t.me/animech/9084") == ("animech", 9084) + + +def test_replace_adopts_a_linked_private_post_then_updates_its_media(tmp_path): + async def run(): + app = App(tmp_path) + await app.start() + channel_id, message_id = 1723201445, 9084 + old = make_msg(message_id, "old caption", media=photo_media(10)) + app.tg.add_channel(FakeChannelClient({message_id: old}, cid=channel_id, title="Database Channel")) + await app.db.save_channel(channel_id, 5, "Database Channel", None, 1) + replacement = make_msg(1, "new caption", media=photo_media(20)) + + await app.text(f"/replace https://t.me/c/{channel_id}/{message_id}", reply=replacement) + + saved = await app.db.find_by_message(channel_id, message_id) + assert saved is not None and saved.source == "adopted" + assert saved.text == "new caption" and saved.media_file_id == pack_file_id(replacement) + assert app.tg.edits[-1][1] == message_id + assert "Replaced the media" in app.out.last_text + await app.db.close() + + asyncio.run(run()) + + +def test_url_helpers(): + assert classify_url("https://T.me/Bharath?start=x", "bharath") == "link" + assert classify_url("https://t.me/bharath/12", "bharath") == "post" + assert classify_url("https://t.me/bharath_bot", "bharath") is None + assert classify_url("https://example.com/bharath", "bharath") is None + assert swap_url("http://telegram.me/Bharath?start=A_b-C", "bharath", "goku") == "http://telegram.me/goku?start=A_b-C" + + +def test_db_url_normalisation(): + url, args = normalize_db_url("postgres://u:p@ep-x-pooler.eu.neon.tech/db?sslmode=require&channel_binding=require") + assert url.startswith("postgresql+asyncpg://") and "sslmode" not in url and "channel_binding" not in url + assert args == {"ssl": True, "statement_cache_size": 0} and "prepared_statement_cache_size=0" in url + assert normalize_db_url("sqlite:///data/x.db")[0] == "sqlite+aiosqlite:///data/x.db" + + +# ------------------------------------------------------------------------ suggestions +def test_suggestion_details(): + post = SimpleNamespace( + id=1, text="Episodes 01 to 20 are here 👇", entities=[{"k": "bold", "o": 0, "l": 8}], + buttons=[[{"t": "Download Episodes 01 to 20", "u": "https://x"}, {"t": "Join", "u": "https://j"}], + [{"t": "👍 2", "raw": "AAAA"}]], + media_kind="photo", media_file_id="FID", + ) + s = build_suggestion(post) + assert s.text == "Episodes 21 to 40 are here 👇" and s.entities[0]["l"] == 8 + assert s.buttons == [[{"t": "Download Episodes 21 to 40", "u": None}, {"t": "Join", "u": "https://j"}]] + assert s.pending == [(0, 0)] and s.media_file_id == "FID" # reactions from another bot are dropped + assert advance_plain("no numbers") is None + assert build_suggestion(SimpleNamespace(id=2, text="", entities=[], buttons=[[{"t": "Join", "u": "u"}]], media_kind=None, media_file_id=None)) is None + + +# ------------------------------------------------------- channel registration handler +def test_add_channel_by_forward_and_rights(tmp_path): + async def run(): + app = App(tmp_path) + await app.start() + ch = types.Channel(id=77, title="Fwd Channel", photo=types.ChatPhotoEmpty(), date=NOW, broadcast=True, + access_hash=1234, username="fwdch") + msg = SimpleNamespace(raw_text="", entities=[], media=None, grouped_id=None, forward=SimpleNamespace(chat=ch)) + await app.text("/addchannel") + await app.text("", message=msg) + assert "Added" in app.out.last_text + saved = await app.db.get_channel(77) + assert (saved.access_hash, saved.username, saved.active) == (1234, "fwdch", True) + + # a "min" channel without access details is refused with an explanation + mini = types.Channel(id=78, title="Min", photo=types.ChatPhotoEmpty(), date=NOW, broadcast=True, min=True) + await app.text("/addchannel") + await app.text("", message=SimpleNamespace(raw_text="", entities=[], media=None, grouped_id=None, forward=SimpleNamespace(chat=mini))) + assert "access details" in app.out.last_text + assert await app.db.get_channel(78) is None + await app.db.close() + + asyncio.run(run()) + + +def test_media_post_publish_uses_send_file_and_caption_edit(tmp_path): + async def run(): + app = App(tmp_path) + await app.start() + await app.db.save_channel(1, 5, "C", None, 1) + p = await app.db.create_post(channel_id=1, status="draft", source="bot", text="cap", entities=[], media_kind="photo", + media_file_id=pack_file_id(photo_msg()), buttons=[[{"t": "Go", "u": "https://x.com"}]], created_by=1) + await app.press(f"pby:{p.id}") + kind, peer, file, kw = app.tg.sent[-1] + assert kind == "file" and isinstance(file, types.MessageMediaPhoto) and kw["caption"] == "cap" + # editing the caption of the live media post goes through messages.editMessage + await app.press(f"et:{p.id}") + await app.text("new caption") + req = app.tg.edits[-1][2] + assert req.message == "new caption" and len(req.reply_markup.rows[0].buttons) == 1 + # replacing the media uses Telegram's file-edit path + await app.press(f"em:{p.id}") + await app.text("nope") + assert "Send a photo" in app.out.last_text + await app.db.close() + + asyncio.run(run()) diff --git a/tests/test_userbot.py b/tests/test_userbot.py new file mode 100644 index 0000000000000000000000000000000000000000..ac79cb279e6e76f589ce93aab6cd8c8d19366a1d --- /dev/null +++ b/tests/test_userbot.py @@ -0,0 +1,459 @@ +"""The userbot: logging in, joining a channel by invite link, getting the "Delete messages" right, deleting, cleaning up.""" +import asyncio +from types import SimpleNamespace + +import pytest +from telethon import functions, types + +from app.userbot import Userbot, UserbotError, delete_problem_text, parse_invite_hash + +from .fakes import FakeChannelClient, FakeUserClient, make_msg, rpc + +FULL = dict(admin=True, post=True, edit=True, delete=True, invite=True, add_admins=True) + + +def run(coro): + return asyncio.run(coro) + + +def channel(n=30, **kw): + bot = FakeChannelClient({i: make_msg(i, f"post {i}") for i in range(1, n + 1)}, username=kw.pop("username", None)) + bot.rights = dict(kw.pop("rights", FULL)) + return bot + + +def ch_row(bot): + return SimpleNamespace(id=1, access_hash=5, title="Test", username=bot.username) + + +def make_userbot(bot, *, keep_admin=False, session="SESSION", user=None, **user_kw): + made = {} + + def factory(cfg): + made["client"] = user or FakeUserClient(bot, **user_kw) + return made["client"] + + cfg = SimpleNamespace(userbot_session=session, userbot_keep_admin=keep_admin, api_id=1, api_hash="x") + return Userbot(bot, cfg, client_factory=factory), made + + +# ------------------------------------------------------------------------------------------ helpers +def test_parse_invite_hash(): + assert parse_invite_hash("https://t.me/+AbCdEfGh0001") == "AbCdEfGh0001" + assert parse_invite_hash("t.me/+AbCdEfGh0001") == "AbCdEfGh0001" + assert parse_invite_hash("https://t.me/joinchat/AbCdEfGh-_01") == "AbCdEfGh-_01" + assert parse_invite_hash("tg://join?invite=AbCdEfGh0001") == "AbCdEfGh0001" + assert parse_invite_hash("https://telegram.me/+AbCdEfGh0001?x=1") == "AbCdEfGh0001" + assert parse_invite_hash("https://t.me/somechannel") is None + assert parse_invite_hash("") is None and parse_invite_hash(None) is None + + +# --------------------------------------------------------------------------------------- logging in +def test_not_set_up(): + async def go(): + bot = channel() + ub, made = make_userbot(bot, session="") + assert not ub.enabled and not ub.ready + assert await ub.connect() is False and "USERBOT_SESSION is not set" in ub.last_error + assert "not set up" in ub.describe() + assert await ub.fallback_for(ch_row(bot)) == (None, None) + assert made == {} # nothing was even created + + run(go()) + + +def test_connect_ok_and_describe(): + async def go(): + bot = channel() + ub, made = make_userbot(bot, username="helper_acct") + assert await ub.connect() is True and ub.ready and made["client"].connected + assert ub.describe() == "connected as @helper_acct (id 777)" + assert await ub.connect() is True # a second call does nothing + fb, deleter = await ub.fallback_for(ch_row(bot)) + assert fb == deleter.delete and bot.requests == [] # nothing happens in the channel until it is needed + await ub.close() + assert not ub.ready and not made["client"].connected + + run(go()) + + +def test_connect_without_a_username_describes_the_name(): + async def go(): + bot = channel() + ub, _ = make_userbot(bot, username=None, first_name="Helper") + await ub.connect() + assert ub.describe() == "connected as Helper (id 777)" + + run(go()) + + +def test_a_revoked_session_is_reported(): + async def go(): + bot = channel() + ub, made = make_userbot(bot, authorized=False) + assert await ub.connect() is False and not ub.ready + assert "not logged in any more" in ub.last_error and "make_userbot_session.py" in ub.last_error + assert not made["client"].connected # it hangs up again + assert "not connected" in ub.describe() and "not logged in" in ub.describe() + assert await ub.fallback_for(ch_row(bot)) == (None, None) + + run(go()) + + +def test_a_bot_session_is_refused(): + async def go(): + bot = channel() + ub, _ = make_userbot(bot, user=FakeUserClient(bot, bot=True)) + assert await ub.connect() is False and "belongs to a bot" in ub.last_error + + run(go()) + + +def test_a_connection_error_is_not_fatal(): + async def go(): + bot = channel() + + class Broken(FakeUserClient): + async def connect(self): + raise ConnectionError("no route to host") + + ub, _ = make_userbot(bot, user=Broken(bot)) + assert await ub.connect() is False and "ConnectionError: no route to host" in ub.last_error + + run(go()) + + +# ------------------------------------------------------------------------------------------ deleting +async def ready_deleter(bot, **kw): + ub, made = make_userbot(bot, **kw) + assert await ub.connect() + return ub, made, ub.deleter(ch_row(bot)) + + +def test_private_channel_one_time_link_then_admin_then_clean_up(): + async def go(): + bot = channel() + ub, made, d = await ready_deleter(bot) + await d.delete([1, 2, 3]) + user = made["client"] + assert sorted(bot.msgs)[:3] == [4, 5, 6] and user.deleted == [[1, 2, 3]] + # the link was made by the bot with a limit of one use and an expiry, and the userbot joined with it + (h, inv), = bot.invites.items() + assert inv["limit"] == 1 and inv["title"] == "Cleanup helper" and inv["expire"] is not None + assert inv["uses"] == 1 and 777 in bot.members + # promoted with exactly one right + rights = bot.admins[777] + assert rights.delete_messages and not any( + v for k, v in rights.to_dict().items() if k not in ("_", "delete_messages") + ) + assert d.notes == [ + "made a one-time invite link for the userbot", + "the userbot joined the channel", + "made the userbot an admin with only “Delete messages”", + ] + await d.close() + assert bot.admins == {} and inv["revoked"] is True + assert d.notes[-1] == "took the admin right away from the userbot again" + assert not ub.lock.locked() + + run(go()) + + +def test_the_second_delete_reuses_the_prepared_channel(): + async def go(): + bot = channel() + ub, made, d = await ready_deleter(bot) + await d.delete([1, 2]) + n = len(made["client"].requests) + await d.delete([3, 4]) + # only the delete request was added: no second join, no second promotion + assert [type(r).__name__ for r in made["client"].requests[n:]] == ["DeleteMessagesRequest"] + assert len(bot.invites) == 1 + await d.close() + + run(go()) + + +def test_more_than_100_ids_are_sent_in_chunks_of_100(): + async def go(): + bot = channel(250) + ub, made, d = await ready_deleter(bot) + await d.delete(list(range(1, 251))) + await d.close() + assert [len(x) for x in made["client"].deleted] == [100, 100, 50] and bot.msgs == {} + + run(go()) + + +def test_channels_own_invite_link_is_used_and_never_revoked(): + async def go(): + bot = channel(rights=dict(FULL, invite=False)) # the bot may not make links itself + bot.primary_invite = "https://t.me/+PrimaryLink01" + bot.invites["PrimaryLink01"] = dict(limit=0, uses=0, revoked=False, title=None, expire=None) + ub, made, d = await ready_deleter(bot) + await d.delete([1]) + await d.close() + assert "used the channel's own invite link" in d.notes + assert bot.invites["PrimaryLink01"]["revoked"] is False # it is not ours to revoke + assert 1 not in bot.msgs + + run(go()) + + +def test_public_channel_is_joined_by_its_name_when_there_is_no_link(): + async def go(): + bot = channel(username="testch", rights=dict(FULL, invite=False)) + ub, made, d = await ready_deleter(bot) + await d.delete([1, 2]) + await d.close() + assert "the userbot joined the channel by its public name" in d.notes + assert any(isinstance(r, functions.channels.JoinChannelRequest) for r in made["client"].requests) + assert 1 not in bot.msgs and 2 not in bot.msgs + + run(go()) + + +def test_private_channel_without_any_link_explains_what_to_do(): + async def go(): + bot = channel(rights=dict(FULL, invite=False)) + ub, made, d = await ready_deleter(bot) + with pytest.raises(UserbotError) as e: + await d.delete([1]) + assert "Invite users via link" in str(e.value) and "add the userbot to the channel yourself" in str(e.value) + await d.close() + assert not ub.lock.locked() + + run(go()) + + +def test_an_expired_link_falls_back_to_the_public_name(): + async def go(): + bot = channel(username="testch") + ub, made, d = await ready_deleter(bot) + bot.fail["ExportChatInviteRequest"] = rpc("ChatAdminRequiredError") + bot.primary_invite = "https://t.me/+GoneGone0001" # not in bot.invites: Telegram says the hash is invalid + await d.delete([1]) + await d.close() + assert "the userbot joined the channel by its public name" in d.notes + + run(go()) + + +def test_a_channel_that_wants_to_approve_new_members(): + async def go(): + bot = channel() + bot.require_approval = True + ub, made, d = await ready_deleter(bot) + with pytest.raises(UserbotError) as e: + await d.delete([1]) + assert "approve" in str(e.value) + await d.close() + assert all(v["revoked"] for v in bot.invites.values()) # the link made for it does not stay around + + run(go()) + + +@pytest.mark.parametrize( + "error,text", + [ + ("ChannelsTooMuchError", "too many channels"), + ("UserChannelsTooMuchError", "too many channels"), + ("UserBannedInChannelError", "banned in this channel"), + ], +) +def test_join_problems_are_explained(error, text): + async def go(): + bot = channel() + bot.fail["user:ImportChatInviteRequest"] = rpc(error) + ub, made, d = await ready_deleter(bot) + with pytest.raises(UserbotError) as e: + await d.delete([1]) + assert text in str(e.value) + await d.close() + + run(go()) + + +def test_userbot_already_in_the_channel_as_a_plain_member(): + async def go(): + bot = channel() + ub, made, d = await ready_deleter(bot) + made["client"]._join() # a member from an earlier clean-up + await d.delete([1]) + await d.close() + assert not any(isinstance(r, functions.messages.ImportChatInviteRequest) for r in made["client"].requests) + assert "the userbot joined the channel" not in d.notes and bot.invites == {} + assert 1 not in bot.msgs + + run(go()) + + +def test_userbot_that_may_already_delete_is_left_alone(): + async def go(): + bot = channel(rights=dict(FULL, invite=False, add_admins=False)) + ub, made, d = await ready_deleter(bot) + made["client"]._join() + bot.admins[777] = types.ChatAdminRights(delete_messages=True) # the owner made it an admin by hand + await d.delete([1, 2]) + await d.close() + assert bot.admins[777].delete_messages # still an admin: we did not make it one, so we do not take it away + assert d.notes == [] and bot.msgs.get(1) is None + + run(go()) + + +def test_userbot_may_not_delete_and_the_bot_cannot_promote_it(): + async def go(): + bot = channel(rights=dict(FULL, add_admins=False)) + ub, made, d = await ready_deleter(bot) + with pytest.raises(UserbotError) as e: + await d.delete([1]) + assert "Add new admins" in str(e.value) + await d.close() + assert bot.admins == {} and 1 in bot.msgs + + run(go()) + + +def test_promotion_refused_by_telegram(): + async def go(): + bot = channel() + bot.fail["EditAdminRequest"] = rpc("RightForbiddenError") + ub, made, d = await ready_deleter(bot) + with pytest.raises(UserbotError) as e: + await d.delete([1]) + assert "RightForbiddenError" in str(e.value) and "may not give that right" in str(e.value) + await d.close() + assert bot.admins == {} + + run(go()) + + +def test_the_bot_cannot_find_the_account_to_promote(): + async def go(): + bot = channel() + bot.participants_visible = False + ub, made, d = await ready_deleter(bot) + with pytest.raises(UserbotError) as e: + await d.delete([1]) + assert "cannot find that account" in str(e.value) + await d.close() + + run(go()) + + +def test_the_bot_knows_the_account_already(): + async def go(): + bot = channel() + ub, made, d = await ready_deleter(bot) + bot.known_users[777] = made["client"].me # the bot has met this user before + bot.participants_visible = False + await d.delete([1]) + await d.close() + assert 1 not in bot.msgs and bot.admins == {} + + run(go()) + + +def test_keep_admin_keeps_the_right(): + async def go(): + bot = channel() + ub, made, d = await ready_deleter(bot, keep_admin=True) + await d.delete([1]) + await d.close() + assert bot.admins[777].delete_messages # USERBOT_KEEP_ADMIN=true + assert not any("took the admin right away" in n for n in d.notes) + assert next(iter(bot.invites.values()))["revoked"] is True # the link is revoked either way + + run(go()) + + +def test_failing_demotion_is_reported_not_fatal(): + async def go(): + bot = channel() + ub, made, d = await ready_deleter(bot) + await d.delete([1]) + bot.fail["EditAdminRequest"] = rpc("ChatAdminRequiredError") + await d.close() + assert d.notes[-1] == "could not take the admin right away from the userbot - please do it by hand" + assert not ub.lock.locked() + + run(go()) + + +def test_not_connected_userbot_cannot_delete(): + async def go(): + bot = channel() + ub, made = make_userbot(bot, authorized=False) + await ub.connect() + d = ub.deleter(ch_row(bot)) + with pytest.raises(UserbotError) as e: + await d.delete([1]) + assert "not connected" in str(e.value) + + run(go()) + + +def test_clean_ups_of_two_channels_do_not_overlap(): + async def go(): + bot = channel() + ub, made = make_userbot(bot) + await ub.connect() + first, second = ub.deleter(ch_row(bot)), ub.deleter(ch_row(bot)) + await first.delete([1]) + order = [] + + async def other(): + await second.delete([2]) # waits until the first clean-up is closed + order.append("second") + await second.close() + + t = asyncio.create_task(other()) + await asyncio.sleep(0.1) + assert order == [] and ub.lock.locked() + order.append("first closes") + await first.close() + await asyncio.wait_for(t, 5) + assert order == ["first closes", "second"] and not ub.lock.locked() + + run(go()) + + +def test_a_failed_prepare_can_be_retried_without_a_deadlock(): + async def go(): + bot = channel(rights=dict(FULL, invite=False)) + ub, made, d = await ready_deleter(bot) + with pytest.raises(UserbotError): + await d.delete([1]) # no way into the channel + bot.rights = dict(FULL) # the owner fixed the rights + await asyncio.wait_for(d.delete([1]), 5) # the same deleter tries again; it must not wait for its own lock + await d.close() + assert 1 not in bot.msgs and not ub.lock.locked() + + run(go()) + + +def test_close_without_anything_done_is_harmless(): + async def go(): + bot = channel() + ub, made, d = await ready_deleter(bot) + await d.close() + await d.close() + assert bot.requests == [] and not ub.lock.locked() + + run(go()) + + +# -------------------------------------------------------------------------------- words for the owner +def test_delete_problem_text(): + off = SimpleNamespace(enabled=False) + ready = SimpleNamespace(enabled=True, ready=True, last_error=None) + down = SimpleNamespace(enabled=True, ready=False, last_error="the session was revoked") + assert "see /userbot" in delete_problem_text(None) + assert "see /userbot" in delete_problem_text(off) + assert "the session was revoked" in delete_problem_text(down) + assert "tried as well" in delete_problem_text(ready, tried=True) + assert "The userbot could not help: boom" in delete_problem_text(ready, fallback_error="boom", tried=True) + t = delete_problem_text(ready, bot_error="ChatAdminRequiredError", tried=True) + assert t.startswith("Telegram refused the bot (ChatAdminRequiredError).") + assert "age limit" in delete_problem_text(ready) # nothing else to say: a generic hint diff --git a/tests/test_userbot_dm.py b/tests/test_userbot_dm.py new file mode 100644 index 0000000000000000000000000000000000000000..1f74faa6d4f3aa952e602033db4a99c7c1e81610 --- /dev/null +++ b/tests/test_userbot_dm.py @@ -0,0 +1,417 @@ +"""A new photo / file reaches the userbot through its own chat with the bot: no download, no upload, the thumbnail stays. + +The bot sends the media to the userbot account (Telegram reuses the file it already has), the userbot finds it there and +edits the post with ITS copy. When that chat does not work, the file is downloaded and uploaded again - with its thumbnail.""" +import os + +import pytest +from telethon import TelegramClient, errors, types +from telethon.sessions import MemorySession + +import app.userbot as userbot_module +from app.tgutil import MediaFile, fetch_media, fetch_thumb, media_ref +from app.userbot import UserbotError, UserbotRefused + +from .fakes import NOW, make_msg, photo_media, rpc, video_media +from .test_userbot import FULL, channel, run +from .test_userbot_edit import ready_editor + + +@pytest.fixture(autouse=True) +def quick_polling(monkeypatch): + monkeypatch.setattr(userbot_module, "_DM_WAIT", 0) # the tests that wait for a message must not wait for real + monkeypatch.setattr(userbot_module, "_DM_POLLS", 4) + + +def ref_of(media): + """The stored reference of a photo / file the owner sent to the bot.""" + return media_ref(make_msg(1, "", media=media)) + + +# ------------------------------------------------------------------------------------------- the quick way +def test_a_file_goes_through_the_userbots_chat_and_the_post_shows_that_same_file(): + async def go(): + bot = channel() + bot.msgs[5].media = photo_media(10) + new = video_media(31, thumb=True) + ub, made, e = await ready_editor(bot) + got = await e.media_by_reference(ref_of(new)) + assert isinstance(got, types.InputMediaDocument) and got.id.id == 31 and e.dm_problem is None + # what the userbot presents is ITS copy: the same file, but with the access data of its own account + assert (got.id.access_hash, got.id.file_reference) == bot._dm.known[("doc", 31)] + assert (got.id.access_hash, got.id.file_reference) != (new.document.access_hash, new.document.file_reference) + await e.edit(5, text="cap", entities=[], media=got) + doc = bot.msgs[5].media.document + assert doc.id == 31 and doc.thumbs # the very same file, so it keeps its thumbnail + assert made["client"].uploads == [] and bot.user_edits[-1].media is got and bot.user_edits[-1].message == "cap" + await e.close() + + run(go()) + + +def test_a_photo_goes_through_the_chat_too(): + async def go(): + bot = channel() + ub, made, e = await ready_editor(bot) + got = await e.media_by_reference(ref_of(photo_media(20))) + assert isinstance(got, types.InputMediaPhoto) and got.id.id == 20 + await e.edit(5, text="", entities=[], media=got) + assert bot.msgs[5].media.photo.id == 20 and made["client"].uploads == [] + await e.close() + + run(go()) + + +def test_the_helper_message_is_sent_quietly_and_deleted_at_the_end(): + async def go(): + bot = channel() + ub, made, e = await ready_editor(bot) + await e.edit(5, text="x", entities=[], media=await e.media_by_reference(ref_of(photo_media(20)))) + (bot_id, kw), = bot._dm.sent + assert kw == {"silent": True} # the account's phone does not ring for it + assert len(bot._dm.msgs) == 1 # still there while the job runs ... + await e.close() + assert bot._dm.deleted == [bot_id] and bot._dm.msgs == [] # ... and gone afterwards + assert bot.admins == {} and not ub.lock.locked() + + run(go()) + + +def test_the_userbot_finds_its_file_among_the_other_messages_of_the_chat(): + async def go(): + bot = channel() + bot._dm.msgs += [make_msg(901, "hello", media=None), make_msg(902, "", media=photo_media(98)), make_msg(903, "", media=video_media(97))] + ub, made, e = await ready_editor(bot) + got = await e.media_by_reference(ref_of(video_media(31))) + assert got.id.id == 31 # picked by the id of the file, not by position + await e.close() + assert [m.id for m in bot._dm.msgs] == [901, 902, 903] # the others were not touched + + run(go()) + + +def test_a_file_that_reaches_the_userbot_late_is_waited_for(): + async def go(): + bot = channel() + bot._dm.late = 2 # the first two reads find nothing yet + ub, made, e = await ready_editor(bot) + got = await e.media_by_reference(ref_of(photo_media(20))) + assert got is not None and got.id.id == 20 and e.dm_problem is None + await e.close() + + run(go()) + + +# ------------------------------------------------------------------------------- when the chat does not work +def test_a_file_that_never_arrives_is_reported_and_the_helper_message_is_still_cleaned_up(): + async def go(): + bot = channel() + bot._dm.late = 99 + ub, made, e = await ready_editor(bot) + assert await e.media_by_reference(ref_of(photo_media(20))) is None + assert e.dm_problem == "the file did not show up in the userbot's chat with the bot" + await e.close() + assert len(bot._dm.deleted) == 1 and bot._dm.msgs == [] + + run(go()) + + +@pytest.mark.parametrize("name", ["UserIsBlockedError", "PeerIdInvalidError", "InputUserDeactivatedError"]) +def test_an_account_that_never_started_the_bot_is_told_what_to_do(name): + async def go(): + bot = channel() + bot._dm.error = rpc(name) + ub, made, e = await ready_editor(bot) + assert await e.media_by_reference(ref_of(photo_media(20))) is None + assert "has not started the bot" in e.dm_problem and "/start" in e.dm_problem + await e.close() + assert bot._dm.deleted == [] and bot._dm.sent == [] # nothing was sent, so nothing is cleaned up + + run(go()) + + +def test_any_other_refusal_of_the_send_is_named(): + async def go(): + bot = channel() + bot._dm.error = rpc("ChatWriteForbiddenError") + ub, made, e = await ready_editor(bot) + assert await e.media_by_reference(ref_of(photo_media(20))) is None + assert e.dm_problem == "Telegram would not let the bot send the file to the userbot (ChatWriteForbiddenError)" + await e.close() + + run(go()) + + +def test_a_chat_the_userbot_cannot_read_is_named(): + async def go(): + bot = channel() + bot._dm.read_error = rpc("PeerIdInvalidError") + ub, made, e = await ready_editor(bot) + assert await e.media_by_reference(ref_of(photo_media(20))) is None + assert e.dm_problem == "the userbot could not read its chat with the bot (PeerIdInvalidError)" + await e.close() + assert bot._dm.msgs == [] # the helper message is deleted all the same + + run(go()) + + +def test_a_bot_without_a_username_cannot_be_found_and_nothing_is_sent(): + async def go(): + bot = channel() + bot._dm.bot_user.username = None + ub, made, e = await ready_editor(bot) + assert await e.media_by_reference(ref_of(photo_media(20))) is None + assert "no username" in e.dm_problem + await e.close() + assert bot._dm.sent == [] + + run(go()) + + +def test_a_bot_the_userbot_cannot_resolve_is_named_and_nothing_is_sent(): + async def go(): + bot = channel() + ub, made, e = await ready_editor(bot) + + async def nothing(peer): + raise ValueError("Cannot find any entity") + + made["client"].get_input_entity = nothing + assert await e.media_by_reference(ref_of(photo_media(20))) is None + assert e.dm_problem == "the userbot could not find the bot by its username" + await e.close() + assert bot._dm.sent == [] + + run(go()) + + +def test_a_userbot_account_the_bot_cannot_find_gets_nothing(): + async def go(): + bot = channel() + bot.participants_visible = False # the bot can't list the members, and has never met the account + ub, made, e = await ready_editor(bot) + made["client"]._join() + bot.admins[777] = types.ChatAdminRights(edit_messages=True) # it may edit already: no promotion, no lookup needed so far + assert await e.media_by_reference(ref_of(photo_media(20))) is None + assert e.dm_problem == "the bot cannot find the userbot account" + await e.close() + assert bot._dm.sent == [] + + run(go()) + + +def test_the_channel_comes_first_nothing_is_sent_when_the_userbot_cannot_get_in(): + async def go(): + bot = channel(rights=dict(FULL, invite=False)) # no invite link: the userbot can't join + ub, made, e = await ready_editor(bot) + with pytest.raises(UserbotError) as exc: + await e.media_by_reference(ref_of(photo_media(20))) + assert "“Edit messages of others”" in str(exc.value) + await e.close() + assert bot._dm.sent == [] + + run(go()) + + +# ------------------------------------------------------------------------------- when Telegram refuses the edit +def test_a_refused_edit_is_named_and_the_helper_message_is_still_deleted(): + async def go(): + bot = channel() + bot.fail["user:EditMessageRequest"] = rpc("MessageIdInvalidError") + ub, made, e = await ready_editor(bot) + got = await e.media_by_reference(ref_of(photo_media(20))) + with pytest.raises(UserbotRefused) as exc: + await e.edit(5, text="x", entities=[], media=got) + assert exc.value.name == "MessageIdInvalidError" and not exc.value.about_media + assert "Telegram refused the userbot as well (MessageIdInvalidError)" in str(exc.value) + await e.close() + assert bot._dm.msgs == [] and bot.admins == {} and not ub.lock.locked() + + run(go()) + + +@pytest.mark.parametrize( + "name,about_media", + [ + ("FileReferenceExpiredError", True), ("FileReferenceInvalidError", True), ("MediaEmptyError", True), + ("MediaInvalidError", True), ("DocumentInvalidError", True), ("PhotoInvalidError", True), + ("MessageIdInvalidError", False), ("ChatAdminRequiredError", False), ("MessageAuthorRequiredError", False), + ], +) +def test_a_refusal_about_the_file_is_told_apart_from_the_others(name, about_media): + assert UserbotRefused("x", name).about_media is about_media + + +def test_the_userbots_edit_with_somebody_elses_access_data_is_refused_by_the_simulation(): + """Guards the simulation itself: the bot's own reference must NOT work for the userbot (that is why the chat exists).""" + + async def go(): + bot = channel() + new = photo_media(20) + ub, made, e = await ready_editor(bot) + await e.media_by_reference(ref_of(new)) # the userbot now holds its own copy ... + bots_own = types.InputMediaPhoto(id=types.InputPhoto(20, new.photo.access_hash, new.photo.file_reference)) + with pytest.raises(UserbotRefused) as exc: # ... but not the bot's + await e.edit(5, text="x", entities=[], media=bots_own) + assert exc.value.name == "FileReferenceExpiredError" and exc.value.about_media + unknown = types.InputMediaPhoto(id=types.InputPhoto(77, 1, b"x")) + with pytest.raises(UserbotRefused) as exc: + await e.edit(5, text="x", entities=[], media=unknown) + assert exc.value.name == "MediaEmptyError" + await e.close() + + run(go()) + + +# ----------------------------------------------------------------------------------- the slow way keeps the thumbnail +def test_an_uploaded_file_takes_its_thumbnail_along(tmp_path): + async def go(): + bot = channel() + video, thumb = tmp_path / "Episode 12.mkv", tmp_path / "photo_1.jpg" + video.write_bytes(b"VIDEO BYTES") + thumb.write_bytes(b"THE THUMBNAIL") + attrs = [types.DocumentAttributeFilename("Episode 12.mkv"), types.DocumentAttributeVideo(5.0, 320, 240)] + ub, made, e = await ready_editor(bot) + await e.edit(5, text="", entities=[], media=MediaFile(str(video), "video", "Episode 12.mkv", "video/x-matroska", attrs, str(thumb))) + await e.close() + sent = bot.user_edits[-1].media + assert isinstance(sent, types.InputMediaUploadedDocument) and sent.thumb is not None + assert made["client"].uploads == [(str(video), "Episode 12.mkv", 11), (str(thumb), None, 13)] + doc = bot.msgs[5].media.document + assert doc.thumbs and bot._media_data[("thumb", doc.id)] == b"THE THUMBNAIL" + + run(go()) + + +def test_a_thumbnail_that_cannot_be_uploaded_does_not_stop_the_edit(tmp_path): + async def go(): + bot = channel() + video = tmp_path / "x.mkv" + video.write_bytes(b"V") + ub, made, e = await ready_editor(bot) + await e.edit(5, text="", entities=[], media=MediaFile(str(video), "video", "x.mkv", thumb_path=str(tmp_path / "gone.jpg"))) + await e.close() + assert bot.user_edits[-1].media.thumb is None and bot.msgs[5].media.document.thumbs is None # it went without + + run(go()) + + +def test_a_file_without_a_thumbnail_is_uploaded_without_one(tmp_path): + async def go(): + bot = channel() + video = tmp_path / "x.mkv" + video.write_bytes(b"V") + ub, made, e = await ready_editor(bot) + await e.edit(5, text="", entities=[], media=MediaFile(str(video), "document", "x.mkv")) + await e.close() + assert bot.user_edits[-1].media.thumb is None and len(made["client"].uploads) == 1 + + run(go()) + + +# ---------------------------------------------------------------------------------------- downloading the thumbnail +def patch_download(monkeypatch, wanted_sizes): + """Telethon's real download_media runs; only the transfer of the bytes is replaced (it records what was asked for).""" + + async def fake_download(self, input_location, file, **kw): + wanted_sizes.append(getattr(input_location, "thumb_size", None)) + with open(file, "wb") as f: + f.write(b"THUMB" if getattr(input_location, "thumb_size", "") else b"THE BYTES") + return file + + monkeypatch.setattr(TelegramClient, "_download_file", fake_download) + + +def doc_ref(thumbs, attrs=None): + attrs = attrs or [types.DocumentAttributeFilename("Episode 12.mkv"), types.DocumentAttributeVideo(5.0, 320, 240)] + doc = types.Document(21, 7, b"fr", NOW, "video/x-matroska", 1000, 2, attrs, thumbs=thumbs) + return ref_of(types.MessageMediaDocument(document=doc)) + + +def test_the_largest_thumbnail_is_downloaded_with_the_file(tmp_path, monkeypatch): + asked = [] + patch_download(monkeypatch, asked) + ref = doc_ref([types.PhotoStrippedSize("i", b"\x01\x28\x28"), types.PhotoSize("s", 100, 56, 900), types.PhotoSize("m", 320, 180, 4000)]) + + async def go(): + client = TelegramClient(MemorySession(), 1, "h") + got = await fetch_media(client, ref, "video", str(tmp_path)) + assert open(got.path, "rb").read() == b"THE BYTES" and got.name == "Episode 12.mkv" + assert got.thumb_path and got.thumb_path.endswith(".jpg") and os.path.dirname(got.thumb_path) != os.path.dirname(got.path) + assert open(got.thumb_path, "rb").read() == b"THUMB" + assert asked == ["", "m"] # the file itself, then the biggest picture of the file + + run(go()) + + +def test_a_file_without_a_thumbnail_has_none(tmp_path, monkeypatch): + asked = [] + patch_download(monkeypatch, asked) + + async def go(): + client = TelegramClient(MemorySession(), 1, "h") + got = await fetch_media(client, doc_ref(None), "video", str(tmp_path)) + assert got.thumb_path is None and os.path.isfile(got.path) and asked == [""] + + run(go()) + + +def test_a_file_that_only_has_the_tiny_inline_thumbnail_still_gets_one(tmp_path, monkeypatch): + asked = [] + patch_download(monkeypatch, asked) + stripped = types.PhotoStrippedSize("i", b"\x01\x28\x28\xa2\x8a\x28\x03") + + async def go(): + client = TelegramClient(MemorySession(), 1, "h") + got = await fetch_media(client, doc_ref([stripped]), "video", str(tmp_path)) + assert got.thumb_path and os.path.getsize(got.thumb_path) > 0 # Telethon turns the inline bytes into a JPEG itself + assert asked == [""] # no download needed: the picture was inside the message + + run(go()) + + +def test_a_thumbnail_that_cannot_be_downloaded_is_left_out_and_the_file_is_kept(tmp_path, monkeypatch): + async def fake_download(self, input_location, file, **kw): + if getattr(input_location, "thumb_size", ""): + raise errors.FileReferenceExpiredError(request=None) + with open(file, "wb") as f: + f.write(b"THE BYTES") + return file + + monkeypatch.setattr(TelegramClient, "_download_file", fake_download) + ref = doc_ref([types.PhotoSize("m", 320, 180, 4000)]) + + async def go(): + client = TelegramClient(MemorySession(), 1, "h") + got = await fetch_media(client, ref, "video", str(tmp_path)) + assert got.thumb_path is None and open(got.path, "rb").read() == b"THE BYTES" + + run(go()) + + +def test_a_photo_is_fetched_without_a_thumbnail_step(tmp_path, monkeypatch): + asked = [] + patch_download(monkeypatch, asked) + + async def go(): + client = TelegramClient(MemorySession(), 1, "h") + got = await fetch_media(client, ref_of(photo_media(11)), "photo", str(tmp_path)) + assert got.thumb_path is None and len(asked) == 1 # the photo itself, nothing else + + run(go()) + + +def test_a_client_that_cannot_give_thumbnails_is_not_a_problem(tmp_path): + class Plain: # a download_media that knows nothing of thumbnails + async def download_media(self, media, file=None): + path = str(file) + "x.bin" + with open(path, "wb") as f: + f.write(b"B") + return path + + async def go(): + got = await fetch_media(Plain(), doc_ref([types.PhotoSize("m", 320, 180, 4000)]), "document", str(tmp_path)) + assert got.thumb_path is None and os.path.isfile(got.path) + assert await fetch_thumb(Plain(), doc_ref(None), str(tmp_path)) is None + + run(go()) diff --git a/tests/test_userbot_edit.py b/tests/test_userbot_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..e4cf4626afba80542b8d6ced5f9a5d65408387c7 --- /dev/null +++ b/tests/test_userbot_edit.py @@ -0,0 +1,310 @@ +"""The userbot as an editor: it edits what Telegram won't let the bot edit (text, caption, a new photo or file).""" +import asyncio +import os + +import pytest +from telethon import TelegramClient, types +from telethon.sessions import MemorySession + +from app.tgutil import MediaFile, fetch_media, media_ref +from app.userbot import UserbotError, edit_problem_text + +from .fakes import NOW, make_msg, markup, photo_media, rpc, url_btn +from .test_userbot import FULL, channel, ch_row, make_userbot, run + + +async def ready_editor(bot, **kw): + ub, made = make_userbot(bot, **kw) + assert await ub.connect() + return ub, made, ub.editor(ch_row(bot)) + + +def only_right(rights, name): + return getattr(rights, name) and not any(v for k, v in rights.to_dict().items() if k not in ("_", name)) + + +# ------------------------------------------------------------------------------------------ text +def test_a_text_edit_joins_gets_only_the_edit_right_and_gives_it_back(): + async def go(): + bot = channel() + bot.msgs[5].reply_markup = markup([url_btn("Go", "https://t.me/x")]) + ub, made, e = await ready_editor(bot) + await e.edit(5, text="new text", entities=[types.MessageEntityBold(0, 3)]) + m = bot.msgs[5] + assert m.message == "new text" and [type(x).__name__ for x in m.entities] == ["MessageEntityBold"] + assert m.reply_markup is None # a user account sends no keyboard, so Telegram drops it + assert only_right(bot.admins[777], "edit_messages") + assert e.notes == [ + "made a one-time invite link for the userbot", + "the userbot joined the channel", + "made the userbot an admin with only “Edit messages of others”", + ] + await e.close() + assert bot.admins == {} and not ub.lock.locked() + assert e.notes[-1] == "took the admin right away from the userbot again" + req = made["client"].requests[-1] + assert type(req).__name__ == "EditMessageRequest" and req.media is None and req.reply_markup is None + + run(go()) + + +def test_the_link_preview_choice_is_sent_for_text_posts_only(): + async def go(): + bot = channel() + ub, made, e = await ready_editor(bot) + await e.edit(5, text="a https://x.com", entities=[], preview=False) + await e.edit(6, text="b", entities=[]) + await e.close() + first, second = bot.user_edits + assert first.no_webpage is True and not second.no_webpage + + run(go()) + + +# ----------------------------------------------------------------------------------------- media +def test_a_new_photo_is_uploaded_and_replaces_the_old_one(tmp_path): + async def go(): + bot = channel() + bot.msgs[5].media = photo_media(10) + path = tmp_path / "new.jpg" + path.write_bytes(b"NEW PHOTO") + ub, made, e = await ready_editor(bot) + await e.edit(5, text="cap", entities=[], media=MediaFile(str(path), "photo", "new.jpg")) + await e.close() + m = bot.msgs[5] + assert isinstance(m.media, types.MessageMediaPhoto) and m.media.photo.id != 10 + assert bot._media_data[("photo", m.media.photo.id)] == b"NEW PHOTO" and m.message == "cap" + assert made["client"].uploads == [(str(path), "new.jpg", 9)] + req = bot.user_edits[-1] + assert isinstance(req.media, types.InputMediaUploadedPhoto) and req.message == "cap" + + run(go()) + + +@pytest.mark.parametrize("kind,forced", [("video", None), ("animation", None), ("audio", None), ("document", True)]) +def test_a_file_keeps_its_name_type_and_attributes(tmp_path, kind, forced): + async def go(): + bot = channel() + path = tmp_path / "Episode 12.mkv" + path.write_bytes(b"VIDEO BYTES") + attrs = [types.DocumentAttributeFilename("Episode 12.mkv"), types.DocumentAttributeVideo(5.0, 320, 240)] + ub, made, e = await ready_editor(bot) + await e.edit(5, text="", entities=[], media=MediaFile(str(path), kind, "Episode 12.mkv", "video/x-matroska", attrs)) + await e.close() + req = bot.user_edits[-1] + assert isinstance(req.media, types.InputMediaUploadedDocument) + assert req.media.mime_type == "video/x-matroska" and req.media.attributes == attrs and req.media.force_file == forced + doc = bot.msgs[5].media.document + assert doc.mime_type == "video/x-matroska" and doc.attributes == attrs and doc.size == 11 + + run(go()) + + +def test_a_file_without_a_known_type_is_uploaded_as_a_plain_file(tmp_path): + async def go(): + bot = channel() + path = tmp_path / "x.bin" + path.write_bytes(b"1") + ub, made, e = await ready_editor(bot) + await e.edit(5, text="", entities=[], media=MediaFile(str(path), "document", "x.bin")) + await e.close() + assert bot.user_edits[-1].media.mime_type == "application/octet-stream" + + run(go()) + + +# ------------------------------------------------------------------------------------------ rights +def test_rights_the_userbot_already_has_are_kept_and_given_back(): + async def go(): + bot = channel() + ub, made, e = await ready_editor(bot) + made["client"]._join() + bot.admins[777] = types.ChatAdminRights(delete_messages=True) # e.g. left over from USERBOT_KEEP_ADMIN + await e.edit(5, text="x", entities=[]) + assert bot.admins[777].delete_messages and bot.admins[777].edit_messages + assert "gave the userbot the “Edit messages of others” right on top of the ones it had" in e.notes + await e.close() + assert bot.admins[777].delete_messages and not bot.admins[777].edit_messages + assert e.notes[-1] == "put the userbot's admin rights back as they were" + + run(go()) + + +def test_a_userbot_that_may_already_edit_is_left_alone(): + async def go(): + bot = channel() + ub, made, e = await ready_editor(bot) + made["client"]._join() + bot.admins[777] = types.ChatAdminRights(edit_messages=True) + await e.edit(5, text="x", entities=[]) + await e.close() + assert e.notes == [] and bot.admins[777].edit_messages + assert not [r for r in bot.requests if type(r).__name__ == "EditAdminRequest"] + + run(go()) + + +def test_keep_admin_keeps_the_edit_right(): + async def go(): + bot = channel() + ub, made, e = await ready_editor(bot, keep_admin=True) + await e.edit(5, text="x", entities=[]) + await e.close() + assert only_right(bot.admins[777], "edit_messages") + assert not any("took the admin right away" in n for n in e.notes) + + run(go()) + + +def test_without_the_add_admins_right_the_owner_is_told_what_to_do(): + async def go(): + bot = channel(rights=dict(FULL, add_admins=False)) + ub, made, e = await ready_editor(bot) + made["client"]._join() + with pytest.raises(UserbotError) as exc: + await e.edit(5, text="x", entities=[]) + text = str(exc.value) + assert "edit other people's posts" in text and "Add new admins" in text and "“Edit messages of others”" in text + await e.close() + assert not ub.lock.locked() + + run(go()) + + +def test_an_invite_problem_names_the_right_to_give(): + async def go(): + bot = channel(rights=dict(FULL, invite=False)) # no link can be made and the channel has none + ub, made, e = await ready_editor(bot) + with pytest.raises(UserbotError) as exc: + await e.edit(5, text="x", entities=[]) + assert "“Edit messages of others”" in str(exc.value) and "Delete messages" not in str(exc.value) + await e.close() + + run(go()) + + +# ---------------------------------------------------------------------------------------- failures +def test_a_refused_edit_is_reported_with_the_name_and_cleans_up(): + async def go(): + bot = channel() + bot.fail["user:EditMessageRequest"] = rpc("MessageIdInvalidError") + ub, made, e = await ready_editor(bot) + with pytest.raises(UserbotError) as exc: + await e.edit(5, text="x", entities=[]) + assert "Telegram refused the userbot as well (MessageIdInvalidError)" in str(exc.value) + await e.close() + assert bot.admins == {} and not ub.lock.locked() + + run(go()) + + +def test_a_missing_right_in_telegrams_eyes_is_explained(): + async def go(): + bot = channel() + bot.fail["user:EditMessageRequest"] = rpc("MessageAuthorRequiredError") + ub, made, e = await ready_editor(bot) + with pytest.raises(UserbotError) as exc: + await e.edit(5, text="x", entities=[]) + assert "MessageAuthorRequiredError" in str(exc.value) and "Edit messages of others" in str(exc.value) + await e.close() + + run(go()) + + +def test_nothing_to_change_is_not_an_error(): + async def go(): + bot = channel() + bot.msgs[5].message = "same" + ub, made, e = await ready_editor(bot) + await e.edit(5, text="same", entities=[]) + await e.close() + assert bot.msgs[5].message == "same" and bot.user_edits == [] + + run(go()) + + +def test_an_editor_without_a_connected_userbot_says_so(): + async def go(): + bot = channel() + ub, made = make_userbot(bot, session="") + assert await ub.editor_for(ch_row(bot)) is None + with pytest.raises(UserbotError, match="not connected"): + await ub.editor(ch_row(bot)).edit(5, text="x", entities=[]) + + run(go()) + + +def test_editor_for_connects_the_userbot_when_needed(): + async def go(): + bot = channel() + ub, made = make_userbot(bot) + assert not ub.ready + e = await ub.editor_for(ch_row(bot)) + assert e is not None and ub.ready + await e.close() + + run(go()) + + +def test_an_edit_and_a_clean_up_do_not_overlap(): + async def go(): + bot = channel() + ub, made = make_userbot(bot) + assert await ub.connect() + e, d = ub.editor(ch_row(bot)), ub.deleter(ch_row(bot)) + await e.edit(5, text="x", entities=[]) + task = asyncio.ensure_future(d.delete([1])) + await asyncio.sleep(0.05) + assert not task.done() and 1 in bot.msgs # it waits until the editor lets go + await e.close() + await asyncio.wait_for(task, 5) + await d.close() + assert 1 not in bot.msgs and bot.admins == {} + + run(go()) + + +def test_edit_problem_text(): + ready = type("U", (), {"enabled": True, "ready": True, "last_error": None})() + off = type("U", (), {"enabled": False, "ready": False, "last_error": None})() + down = type("U", (), {"enabled": True, "ready": False, "last_error": "the session was revoked"})() + assert "see /userbot" in edit_problem_text(None) and "see /userbot" in edit_problem_text(off) + assert "the session was revoked" in edit_problem_text(down) + assert edit_problem_text(ready, fallback_error="boom") == "The userbot could not do it either: boom" + assert edit_problem_text(ready) == "" + + +# ------------------------------------------------------------------------------ the bot's download +def test_fetch_media_names_a_file_like_the_original_and_keeps_its_attributes(tmp_path, monkeypatch): + async def fake_download(self, input_location, file, **kw): + with open(file, "wb") as f: + f.write(b"THE BYTES") + return file + + monkeypatch.setattr(TelegramClient, "_download_file", fake_download) + attrs = [types.DocumentAttributeFilename("Episode 12.mkv"), types.DocumentAttributeVideo(5.0, 320, 240)] + doc = types.Document(21, 7, b"fr", NOW, "video/x-matroska", 1000, 2, attrs) + ref = media_ref(make_msg(1, "", media=types.MessageMediaDocument(document=doc))) + + async def go(): + client = TelegramClient(MemorySession(), 1, "h") + got = await fetch_media(client, ref, "video", str(tmp_path)) + assert os.path.basename(got.path) == "Episode 12.mkv" and got.name == "Episode 12.mkv" + assert open(got.path, "rb").read() == b"THE BYTES" + assert got.kind == "video" and got.mime_type == "video/x-matroska" + assert [bytes(a) for a in got.attributes] == [bytes(a) for a in attrs] # (stored and read back: same on the wire) + photo = media_ref(make_msg(2, "", media=photo_media(11))) + pic = await fetch_media(client, photo, "photo", str(tmp_path)) + assert pic.path.endswith(".jpg") and pic.mime_type is None and pic.attributes == [] + + asyncio.run(go()) + + +def test_fetch_media_says_so_when_telegram_gives_nothing(tmp_path): + class Silent: + async def download_media(self, media, file=None): + return None + + ref = media_ref(make_msg(2, "", media=photo_media(11))) + with pytest.raises(ValueError): + asyncio.run(fetch_media(Silent(), ref, "photo", str(tmp_path))) diff --git a/tests/test_wire.py b/tests/test_wire.py new file mode 100644 index 0000000000000000000000000000000000000000..9974970b0c2b076a7fb9e77d01d065ecb0f75ddb --- /dev/null +++ b/tests/test_wire.py @@ -0,0 +1,166 @@ +"""Check that every Telegram call the bot makes builds a valid, serialisable MTProto request. + +Telethon's network layer is replaced by a function that captures the request (after Telethon has +resolved it) and serialises it, so wrong argument types or shapes fail here instead of in production. +""" +import asyncio +import datetime + +import pytest +from telethon import TelegramClient, functions, types, utils +from telethon.sessions import MemorySession + +from app.common import push_edit, send_post +from app.tgutil import ( + build_markup, + de_entities, + edit_raw, + media_from_ref, + media_ref, + peer_of, + ser_entities, +) +from app.ui import button_keyboard, panel_keyboard + +from .fakes import make_msg + +NOW = datetime.datetime.now(datetime.timezone.utc) +CH = type("Ch", (), {"id": 1234, "access_hash": 5678})() + + +class Captured(Exception): + def __init__(self, req): + self.req = req + + +@pytest.fixture() +def client(monkeypatch): + async def fake_call(self, request, ordered=False, flood_sleep_threshold=None): + reqs = list(request) if isinstance(request, (list, tuple)) else [request] + for r in reqs: + if hasattr(r, "resolve"): + await r.resolve(self, utils) + assert isinstance(bytes(r), bytes) # must serialise + raise Captured(reqs[0]) + + monkeypatch.setattr(TelegramClient, "__call__", fake_call) + return TelegramClient(MemorySession(), 1, "h") + + +def capture(coro): + async def go(): + try: + await coro + except Captured as c: + return c.req + raise AssertionError("no request was made") + + return asyncio.run(go()) + + +def post(**kw): + base = dict( + id=1, message_id=50, text="Hello 😀", entities=[{"k": "bold", "o": 0, "l": 5}, {"k": "url", "o": 6, "l": 2, "u": "https://x.com"}], + media_kind=None, media_file_id=None, link_preview=False, + buttons=[[{"t": "Go", "u": "https://t.me/bot?start=a"}, {"t": "Two", "u": "https://t.me/bot?start=b"}]], + ) + base.update(kw) + return type("P", (), base)() + + +def photo_ref(): + photo = types.Photo(11, 22, b"ref", NOW, [types.PhotoSize("x", 100, 100, 999)], 2) + return media_ref(make_msg(1, "", media=types.MessageMediaPhoto(photo=photo))) + + +def test_send_text_post(client): + req = capture(send_post(client, peer_of(CH), post())) + assert isinstance(req, functions.messages.SendMessageRequest) + assert req.message == "Hello 😀" and req.no_webpage is True + assert [type(e).__name__ for e in req.entities] == ["MessageEntityBold", "MessageEntityTextUrl"] + assert req.reply_markup.rows[0].buttons[1].text == "Two" + assert isinstance(req.peer, types.InputPeerChannel) + + +def test_send_media_post_with_and_without_file_reference(client): + ref = photo_ref() + req = capture(send_post(client, peer_of(CH), post(media_kind="photo", media_file_id=ref))) + assert isinstance(req, functions.messages.SendMediaRequest) + assert isinstance(req.media, types.InputMediaPhoto) and req.media.id.id == 11 and req.media.id.file_reference == b"ref" + assert req.message == "Hello 😀" and req.reply_markup is not None + + async def blank(): + c = client + _, media, _ = await c._file_to_media(media_from_ref(ref, blank_reference=True)) + return media + + assert asyncio.run(blank()).id.file_reference == b"" + + +def test_raw_edits(client): + p = post() + req = capture(push_edit(client, CH, p)) + assert isinstance(req, functions.messages.EditMessageRequest) + assert req.id == 50 and req.message == "Hello 😀" and req.no_webpage is True and req.reply_markup is not None + # no buttons -> no reply_markup (Telegram then removes the keyboard) + req = capture(push_edit(client, CH, post(buttons=[]))) + assert req.reply_markup is None and req.message == "Hello 😀" + # markup-only edit leaves the text alone + req = capture(edit_raw(client, peer_of(CH), 9, markup=build_markup([[{"t": "A", "u": "https://a.com"}]]))) + assert req.message is None and req.entities is None and req.reply_markup.rows[0].buttons[0].text == "A" + + +def test_media_replacement_edit(client): + ref = photo_ref() + req = capture(push_edit(client, CH, post(media_kind="photo", media_file_id=ref), replace_media=True)) + assert isinstance(req, functions.messages.EditMessageRequest) + assert isinstance(req.media, types.InputMediaPhoto) and req.message == "Hello 😀" + assert req.reply_markup is not None + + +def test_reads_deletes_and_rights_requests(client): + peer = peer_of(CH) + req = capture(client.get_messages(peer, ids=[1, 2, 3])) + assert isinstance(req, functions.channels.GetMessagesRequest) + assert isinstance(req.channel, types.InputChannel) and [i.id for i in req.id] == [1, 2, 3] + req = capture(client.delete_messages(peer, [7])) + assert isinstance(req, functions.channels.DeleteMessagesRequest) and req.id == [7] + req = capture(client(functions.channels.GetFullChannelRequest(peer))) + assert isinstance(req.channel, types.InputChannel) + req = capture(client(functions.channels.GetParticipantRequest(channel=peer, participant=types.InputPeerSelf()))) + assert isinstance(req.participant, types.InputPeerSelf) + + +def test_entities_with_every_stored_kind_serialise(): + ents = [ + types.MessageEntityBold(0, 1), types.MessageEntityItalic(1, 1), types.MessageEntityUnderline(2, 1), + types.MessageEntityStrike(3, 1), types.MessageEntitySpoiler(4, 1), types.MessageEntityCode(5, 1), + types.MessageEntityPre(6, 1, "py"), types.MessageEntityTextUrl(7, 1, "https://x.com"), + types.MessageEntityBlockquote(8, 1, True), types.MessageEntityCustomEmoji(9, 2, 123456789), + ] + back = de_entities(ser_entities(ents)) + assert [type(e) for e in back] == [type(e) for e in ents] + assert back[8].collapsed is True + for e in back: + bytes(e) + + +def test_ui_keyboards_serialise(client): + p = post() + p.status, p.channel_id, p.source = "draft", 1, "bot" + p.buttons = [[{"t": "A", "u": "https://a.com"}, {"t": "⚠️ no link", "u": None}], [{"t": "👍", "raw": ""}]] + for kb in (panel_keyboard(p), button_keyboard(p, 0, 0), button_keyboard(p, 1, 0)): + mk = client.build_reply_markup(kb) + assert isinstance(bytes(mk), bytes) + for label_row in panel_keyboard(p): + for b in label_row: + assert len(b.type.data) <= 64 # Telegram's limit for callback data + + +def test_button_callback_data_fits_for_large_ids(): + p = post(id=2_000_000_000) + p.status, p.channel_id, p.source = "sent", -1, "bot" + p.buttons = [[{"t": "x", "u": "https://a.com"}] * 8] * 12 + for row in panel_keyboard(p): + for b in row: + assert len(b.type.data) <= 64 diff --git a/tests/test_wire2.py b/tests/test_wire2.py new file mode 100644 index 0000000000000000000000000000000000000000..543500a2cfeeae2a7b8915b728a111344bdbbf87 --- /dev/null +++ b/tests/test_wire2.py @@ -0,0 +1,199 @@ +"""The repost / delete / buttons / userbot flows through a REAL Telethon client object. + +Telethon resolves and serialises every request exactly as it does before sending it to Telegram; only the network at +the very end is replaced by the simulated channel. A request that would not build or serialise in production fails here. +""" +import asyncio +import datetime + +import pytest +from telethon import TelegramClient, functions, types, utils +from telethon.sessions import MemorySession + +from app.buttons_sync import ensure_markup, fix_buttons, scan_buttons +from app.repost_engine import RepostOptions, delete_copies, plan_repost, run_repost +from app.tgutil import build_markup, button_url, get_rights, peer_of +from app.userbot import Userbot + +from .dbutil import db_url_for, fresh_db +from .fakes import FakeChannelClient, FakeUserClient, make_msg, markup, url_btn +from .test_repost import NEW, OLD, build + + +@pytest.fixture() +def wired(monkeypatch): + chan = FakeChannelClient(build()) + chan.rights = dict(admin=True, post=True, edit=True, delete=True, invite=True, add_admins=True) + seen = [] + + async def fake_call(self, request, ordered=False, flood_sleep_threshold=None): + assert not isinstance(request, (list, tuple)) + await request.resolve(self, utils) # what Telethon does just before sending + seen.append(type(request).__name__) + return await chan(request) # serialises again and answers like Telegram + + monkeypatch.setattr(TelegramClient, "__call__", fake_call) + return TelegramClient(MemorySession(), 1, "h"), chan, seen + + +async def setup(tmp_path, client): + db = await fresh_db(db_url_for(tmp_path)) + await db.save_channel(1, 5, "Test", "testch", 99) + ch = await db.get_channel(1) + plan = await plan_repost(client, ch, RepostOptions(OLD, NEW)) + assert plan.error is None + await db.create_migration( + "m1", 1, old=OLD, new=NEW, include_typed=True, include_posts=False, first_id=plan.first, last_id=plan.last, partial=False, user_id=99 + ) + return db, ch, await db.get_migration("m1") + + +def test_repost_then_delete_through_a_real_client(wired, tmp_path): + client, chan, seen = wired + + async def go(): + db, ch, mig = await setup(tmp_path, client) + res = await run_repost(client, db, ch, mig, 99, delay=0, settle_pause=0) + assert (res.copied_units, res.copied_messages, res.failed, res.aborted) == (7, 8, [], None) + assert (res.forwarded, res.rebuilt) == (3, 4) + new = [chan.msgs[i] for i in sorted(chan.msgs) if i > 10] + assert len(new) == 8 and new[0].message == "Welcome" + assert button_url(new[1].reply_markup.rows[0].buttons[0]) == f"https://t.me/{NEW}?start=AAA" + out = await delete_copies(client, db, ch, mig, "old", delay=0) + assert (out.deleted, out.remaining, out.error) == (8, 0, None) + assert sorted(chan.msgs) == [6] + list(range(11, 19)) + await db.close() + + asyncio.run(go()) + assert {"GetFullChannelRequest", "GetMessagesRequest", "ForwardMessagesRequest", "SendMessageRequest", "SendMediaRequest", "DeleteMessagesRequest"} <= set(seen) + + +def test_a_channel_that_forbids_forwarding_rebuilds_albums_through_a_real_client(wired, tmp_path): + client, chan, seen = wired + chan.restrict_forwards = True + + async def go(): + db, ch, mig = await setup(tmp_path, client) + res = await run_repost(client, db, ch, mig, 99, delay=0, settle_pause=0) + assert (res.copied_units, res.failed, res.forwarded, res.rebuilt) == (7, [], 0, 7) + new = {i: m for i, m in chan.msgs.items() if i > 10} + assert new[14].grouped_id == new[15].grouped_id and new[14].media.photo.id == 41 + await db.close() + + asyncio.run(go()) + assert "SendMultiMediaRequest" in seen + + +def test_the_repair_edits_go_through_a_real_client(wired, tmp_path): + client, chan, seen = wired + chan.hide_keyboard_on_create = 1 + + async def go(): + db, ch, mig = await setup(tmp_path, client) + res = await run_repost(client, db, ch, mig, 99, delay=0, settle_pause=0) + assert res.failed == [] and res.repaired == 1 + await db.close() + + asyncio.run(go()) + # the plain edit (Telegram answers "not modified"), then the stand-in keyboard, then the real one + assert seen.count("EditMessageRequest") == 3 and len(chan.edits) == 2 + + +def test_checking_and_fixing_buttons_through_a_real_client(wired, tmp_path): + client, chan, seen = wired + A, B = "https://t.me/goku?start=A", "https://t.me/goku?start=B" + chan.msgs = { + 1: make_msg(1, "fine", markup=markup([url_btn("Get", A)]), out=True), + 2: make_msg(2, "lost its buttons", out=True), + 3: make_msg(3, "wrong link", markup=markup([url_btn("Get", B)]), out=True), + } + chan._top = 3 + + async def go(): + db = await fresh_db(db_url_for(tmp_path)) + await db.save_channel(1, 5, "Test", "testch", 99) + ch = await db.get_channel(1) + posts = [ + await db.create_post(channel_id=1, message_id=i, status="sent", source="bot", text=f"p{i}", entities=[], buttons=[[{"t": "Get", "u": A}]]) + for i in (1, 2, 3) + ] + scan = await scan_buttons(client, ch, posts) + assert (scan.total, scan.fine, [p.message_id for p, _, _ in scan.bad], scan.gone) == (3, 1, [2, 3], []) + res = await fix_buttons(client, ch, scan.bad, delay=0, pause=0) + assert (res.fixed, res.failed) == (2, []) + assert [button_url(chan.msgs[i].reply_markup.rows[0].buttons[0]) for i in (1, 2, 3)] == [A, A, A] + assert await ensure_markup(client, peer_of(ch), 2, build_markup([[{"t": "Get", "u": A}]]), pause=0) == "fine" + await db.close() + + asyncio.run(go()) + assert "EditMessageRequest" in seen + + +def test_the_bots_own_rights_are_read_through_a_real_client(wired): + client, chan, seen = wired + + async def go(): + ch = type("Ch", (), {"id": 1, "access_hash": 5})() + r = await get_rights(client, ch) + assert (r.admin, r.post, r.delete, r.invite, r.add_admins) == (True, True, True, True, True) + chan.rights = dict(admin=True, post=True, edit=False, delete=False, invite=False, add_admins=False) + r = await get_rights(client, ch) + assert (r.post, r.delete, r.invite, r.add_admins) == (True, False, False, False) + + asyncio.run(go()) + assert seen == ["GetParticipantRequest", "GetParticipantRequest"] + + +def test_userbot_clean_up_with_a_real_bot_client(wired, tmp_path): + """Bot side (invite link, promotion, demotion, revoking) runs through the real client; the helper account is simulated.""" + client, chan, seen = wired + chan.undeletable = {1, 2, 3, 4, 5} + + class Cfg: + userbot_session, userbot_keep_admin, api_id, api_hash = "S", False, 1, "h" + + async def go(): + db, ch, mig = await setup(tmp_path, client) + await run_repost(client, db, ch, mig, 99, delay=0, settle_pause=0) + ub = Userbot(client, Cfg(), client_factory=lambda cfg: FakeUserClient(chan)) + fallback, deleter = await ub.fallback_for(ch) + try: + out = await delete_copies(client, db, ch, mig, "old", delay=0, fallback=fallback) + finally: + await deleter.close() + assert (out.deleted, out.by_userbot, out.remaining, out.error, out.fallback_error) == (8, 5, 0, None, None) + assert chan.admins == {} and all(v["revoked"] for v in chan.invites.values()) + await db.close() + + asyncio.run(go()) + for name in ("ExportChatInviteRequest", "EditAdminRequest", "GetParticipantsRequest", "EditExportedChatInviteRequest"): + assert name in seen, (name, seen) + assert seen.count("EditAdminRequest") == 2 # promote, then demote + + +def test_invite_and_admin_requests_build_with_the_values_the_userbot_code_uses(wired): + client, chan, seen = wired + peer = types.InputPeerChannel(1, 5) + expires = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) + + async def go(): + inv = await client(functions.messages.ExportChatInviteRequest(peer=peer, expire_date=expires, usage_limit=1, title="Cleanup helper")) + assert inv.link.startswith("https://t.me/+") and inv.usage_limit == 1 + await client(functions.messages.EditExportedChatInviteRequest(peer=peer, link=inv.link, revoked=True)) + chan.users[777] = types.User(id=777, access_hash=555, first_name="H") + await client( + functions.channels.EditAdminRequest( + channel=peer, user_id=types.InputUser(777, 555), admin_rights=types.ChatAdminRights(delete_messages=True), rank="" + ) + ) + assert chan.admins[777].delete_messages + await client( + functions.channels.EditAdminRequest(channel=peer, user_id=types.InputUser(777, 555), admin_rights=types.ChatAdminRights(), rank="") + ) + assert chan.admins == {} + res = await client( + functions.channels.GetParticipantsRequest(channel=peer, filter=types.ChannelParticipantsSearch("h"), offset=0, limit=200, hash=0) + ) + assert res.users == [] + + asyncio.run(go()) diff --git a/tests/test_wire3.py b/tests/test_wire3.py new file mode 100644 index 0000000000000000000000000000000000000000..fa8c296412800ddd521002fe05905d38424d3647 --- /dev/null +++ b/tests/test_wire3.py @@ -0,0 +1,333 @@ +"""Replies, pins, the copy between two channels and the sync with the channels, through a REAL Telethon client object. + +Telethon resolves and serialises every request exactly as it does before sending it to Telegram; only the network at +the very end is replaced by the simulated channels. A request that would not build or serialise in production fails here. +""" +import asyncio + +import pytest +from telethon import TelegramClient, functions, types, utils +from telethon.sessions import MemorySession + +from app.db import utcnow +from app.repost_engine import run_repost +from app.servicemsg import remove +from app.shift_engine import delete_shift_copies, run_shift +from app.sync_engine import SyncOptions, sync_channel, sync_ids +from app.tgutil import peer_of + +from .dbutil import db_url_for, fresh_db +from .fakes import FakeChannelClient, markup, rpc, service_msg, url_btn +from .test_repost_links import CH, build_linked, new_posts, reply_of +from .test_shift import SRC, old_posts, source_posts +from .test_sync import foreign, old_msg, saved + + +class Wire: + """A real client whose requests are answered by `root` (a simulated channel; the other channels sit next to it).""" + + def __init__(self): + self.client = TelegramClient(MemorySession(), 1, "h") + self.root = None + self.seen = [] + + +@pytest.fixture() +def wire(monkeypatch): + w = Wire() + + async def fake_call(self, request, ordered=False, flood_sleep_threshold=None): + assert not isinstance(request, (list, tuple)) + await request.resolve(self, utils) # what Telethon does just before sending + w.seen.append(request) + return await w.root(request) # serialises again and answers like Telegram + + monkeypatch.setattr(TelegramClient, "__call__", fake_call) + return w + + +def two_wired(w, *, restrict=False): + """channel 1 "srcch" with the source posts, channel 2 "dstch" with ten old posts.""" + src = FakeChannelClient(source_posts(), username="srcch", title="Anime Source") + src.restrict_forwards = restrict + dst = src.add_channel(FakeChannelClient(old_posts(), username="dstch", cid=2, title="Anime Backup")) + w.root = src + return src, dst + + +def names(seen): + return [type(r).__name__ for r in seen] + + +def test_replies_and_pins_of_a_repost_go_through_a_real_client(wire, tmp_path): + client, seen = wire.client, wire.seen + chan = wire.root = FakeChannelClient(build_linked(), username=CH) + + async def go(): + db = await fresh_db(db_url_for(tmp_path)) + await db.save_channel(1, 5, "Test", CH, 99) + ch = await db.get_channel(1) + await db.create_migration("m1", 1, old=None, new=None, include_typed=False, include_posts=False, first_id=1, last_id=10, partial=False, user_id=99) + mig = await db.get_migration("m1") + res = await run_repost(client, db, ch, mig, 99, delay=0, settle_pause=0) + assert (res.copied_units, res.failed, res.aborted) == (8, [], None) + new = new_posts(chan) + assert (reply_of(new[14]), reply_of(new[15]), reply_of(new[16]), reply_of(new[17])) == (13, 14, 15, 15) + assert (res.final.pin_wanted, res.final.pinned, res.final.pin_error) == (2, 2, None) + assert chan.pinned_order == [15, 19] and new[15].pinned and new[19].pinned + assert not [m for m in chan.msgs.values() if isinstance(m, types.MessageService) and m.id > 10] # pin notices deleted + await db.close() + + asyncio.run(go()) + got = names(seen) + for name in ("SendMessageRequest", "SendMultiMediaRequest", "UpdatePinnedMessageRequest", "DeleteMessagesRequest", "EditMessageRequest"): + assert name in got, (name, got) + # an answer is made with the new-style reply header, never with the old reply_to_msg_id field + replies = [r.reply_to for r in seen if isinstance(r, (functions.messages.SendMessageRequest, functions.messages.SendMultiMediaRequest)) and r.reply_to] + assert replies and all(isinstance(r, types.InputReplyToMessage) for r in replies) + pins = [r for r in seen if isinstance(r, functions.messages.UpdatePinnedMessageRequest)] + assert [(p.id, p.silent, bool(p.unpin)) for p in pins] == [(15, True, False), (19, True, False)] + + +def test_a_shift_between_two_channels_through_a_real_client(wire, tmp_path): + client, seen = wire.client, wire.seen + src, dst = two_wired(wire) + + async def go(): + db = await fresh_db(db_url_for(tmp_path)) + await db.save_channel(2, 6, "Anime Backup", "dstch", 1) + dst_row = await db.get_channel(2) + await db.create_shift("s1", src=SRC, dst_channel_id=2, first_id=1, last_id=8, user_id=1) + shift = await db.get_shift("s1") + res = await run_shift(client, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert (res.copied_units, res.copied_messages, res.failed, res.aborted) == (6, 7, [], None) + new = {i: m for i, m in dst.msgs.items() if i > 10} + assert sorted(new) == [11, 12, 13, 14, 15, 16, 17] + assert reply_of(new[14]) == 12 and not new[14].pinned + assert new[17].message == "See https://t.me/dstch/11 and https://t.me/dstch/12 and https://t.me/elsewhere/9" + assert sorted(src.msgs) == [1, 2, 3, 4, 5, 6, 7, 8] and src.msgs[5].pinned # the source is only read + assert await db.shift_pairs("s1") == [(1, 11), (2, 12), (3, 13), (5, 14), (6, 15), (7, 16), (8, 17)] + + undo = await delete_shift_copies(client, db, dst_row, shift, delay=0) + assert (undo.deleted, undo.remaining, undo.error) == (7, 0, None) + assert sorted(dst.msgs) == list(range(1, 11)) + assert sorted(src.msgs) == [1, 2, 3, 4, 5, 6, 7, 8] + await db.close() + + asyncio.run(go()) + # posts are carried over by Telegram itself when it is allowed to (here: from channel 1 to channel 2) + forwards = [r for r in seen if isinstance(r, functions.messages.ForwardMessagesRequest)] + assert forwards and all(isinstance(r.from_peer, types.InputPeerChannel) and r.from_peer.channel_id == 1 for r in forwards) + assert all(isinstance(r.to_peer, types.InputPeerChannel) and r.to_peer.channel_id == 2 for r in forwards) + assert all(r.drop_author for r in forwards) + sent = [r for r in seen if isinstance(r, functions.messages.SendMessageRequest) and r.reply_to] + assert sent and sent[0].peer.channel_id == 2 and sent[0].reply_to.reply_to_msg_id == 12 + # the source channel was never written to + for r in seen: + if isinstance(r, (functions.messages.SendMessageRequest, functions.messages.SendMediaRequest, functions.messages.SendMultiMediaRequest, functions.messages.EditMessageRequest)): + assert r.peer.channel_id == 2 + if isinstance(r, functions.channels.DeleteMessagesRequest): + assert r.channel.channel_id == 2 + + +def test_a_shift_from_a_channel_that_forbids_forwarding_through_a_real_client(wire, tmp_path): + client, seen = wire.client, wire.seen + src, dst = two_wired(wire, restrict=True) + + async def go(): + db = await fresh_db(db_url_for(tmp_path)) + await db.save_channel(2, 6, "Anime Backup", "dstch", 1) + dst_row = await db.get_channel(2) + await db.create_shift("s1", src=SRC, dst_channel_id=2, first_id=1, last_id=8, user_id=1) + shift = await db.get_shift("s1") + res = await run_shift(client, db, shift, dst_row, 99, delay=0, settle_pause=0) + assert (res.copied_units, res.failed, res.forwarded, res.rebuilt) == (6, [], 0, 6) + new = {i: m for i, m in dst.msgs.items() if i > 10} + assert new[12].reply_markup is not None and new[15].grouped_id == new[16].grouped_id + await db.close() + + asyncio.run(go()) + assert "SendMultiMediaRequest" in names(seen) and "SendMediaRequest" in names(seen) + + +# ===================================================================================== the sync with the channels +def notice(chan, action): + """A service message as Telegram adds one: it takes the next message id and moves the event counter.""" + chan._top += 1 + chan._pts += 1 + note = types.MessageService(id=chan._top, peer_id=types.PeerChannel(chan.cid), date=utcnow(), action=action) + chan.msgs[note.id] = note + return note + + +def synced_channel(wire): + """Posts 1, 2, 3 and 5 made through the bot a day ago; 4 is an old "pinned a message" notice.""" + msgs = { + 1: old_msg(1, "first"), + 2: old_msg(2, "second", markup=markup([url_btn("Watch", "https://t.me/a/1")])), + 3: old_msg(3, "third"), + 4: service_msg(4), + 5: old_msg(5, "fifth"), + } + chan = wire.root = FakeChannelClient(msgs, username="chan") + return msgs, chan + + +async def saved_world(tmp_path, msgs): + db = await fresh_db(db_url_for(tmp_path)) + await db.save_channel(1, 5, "Chan", "chan", 99) + ch = await db.get_channel(1) + for m in msgs.values(): + if not isinstance(m, types.MessageService): + await saved(db, m) + return db, ch + + +def test_the_sync_compares_a_channel_and_deletes_new_notices_through_a_real_client(wire, tmp_path): + client, seen = wire.client, wire.seen + msgs, chan = synced_channel(wire) + + async def go(): + db, ch = await saved_world(tmp_path, msgs) + opts = SyncOptions(pause=0, grace=0) + + first = await sync_channel(client, db, ch, opts) # the first look only notes where the channel stands + assert (first.error, first.first_look, first.checked, first.changed) == (None, True, 4, False) + assert sorted(chan.msgs) == [1, 2, 3, 4, 5] + + # what admins do outside the bot: delete a post, edit one, write a new one - Telegram adds notices meanwhile + del chan.msgs[3] + chan._pts += 1 + chan.msgs[1].message = "first, edited" + chan._pts += 1 + foreign(chan, "written by another admin") # id 6 + notice(chan, types.MessageActionChatEditTitle("A new name")) # id 7 + notice(chan, types.MessageActionPinMessage()) # id 8 + + rep = await sync_channel(client, db, ch, opts) + assert rep.error is None and rep.anomaly is None + assert (rep.deleted, rep.edited, rep.adopted, rep.services_deleted, rep.services_failed) == ([3], [1], [6], 2, 0) + assert sorted(chan.msgs) == [1, 2, 4, 5, 6] # the two new notices are gone, the old one is left alone + + assert await db.find_by_message(1, 3) is None + assert (await db.find_by_message(1, 1)).text == "first, edited" + took = await db.find_by_message(1, 6) + assert (took.source, took.text, took.created_by, took.status) == ("adopted", "written by another admin", 0, "sent") + + again = await sync_channel(client, db, ch, opts) # nothing left to do + assert not again.changed and again.error is None + await db.close() + + asyncio.run(go()) + got = names(seen) + for name in ("GetFullChannelRequest", "GetMessagesRequest", "DeleteMessagesRequest"): + assert name in got, (name, got) + # the channel counter and every read name the channel the way Telegram wants it + fulls = [r for r in seen if isinstance(r, functions.channels.GetFullChannelRequest)] + assert fulls and all(isinstance(r.channel, types.InputChannel) and r.channel.channel_id == 1 for r in fulls) + reads = [r for r in seen if isinstance(r, functions.channels.GetMessagesRequest)] + assert reads and all(isinstance(r.channel, types.InputChannel) for r in reads) + # only the two new notices were deleted, in one request, and nothing was written to the channel + deletes = [r for r in seen if isinstance(r, functions.channels.DeleteMessagesRequest)] + assert [i for r in deletes for i in r.id] == [7, 8] + assert all(isinstance(r.channel, types.InputChannel) and r.channel.channel_id == 1 for r in deletes) + writes = ( + functions.messages.SendMessageRequest, functions.messages.SendMediaRequest, functions.messages.SendMultiMediaRequest, + functions.messages.EditMessageRequest, functions.messages.ForwardMessagesRequest, functions.messages.UpdatePinnedMessageRequest, + ) + assert not [r for r in seen if isinstance(r, writes)] + + +def test_the_live_look_at_a_few_messages_through_a_real_client(wire, tmp_path): + client, seen = wire.client, wire.seen + msgs, chan = synced_channel(wire) + + async def go(): + db, ch = await saved_world(tmp_path, msgs) + opts = SyncOptions(pause=0, grace=0) + await sync_channel(client, db, ch, opts) + + chan.msgs[2].message = "second, edited" + chan._pts += 1 + foreign(chan, "a new post") # 6 + note = notice(chan, types.MessageActionChatEditTitle("Another name")) # 7 + del chan.msgs[5] + chan._pts += 1 + + rep = await sync_ids(client, db, ch, [2, 5, 6, note.id], opts, adopt_ids=[6]) + assert rep.error is None + assert (rep.edited, rep.deleted, rep.adopted, rep.services_deleted) == ([2], [5], [6], 1) + assert sorted(chan.msgs) == [1, 2, 3, 4, 6] + assert (await db.find_by_message(1, 2)).text == "second, edited" + assert (await db.find_by_message(1, 2)).buttons == [[{"t": "Watch", "u": "https://t.me/a/1"}]] # the saved buttons stay + assert await db.find_by_message(1, 5) is None + await db.close() + + asyncio.run(go()) + assert [i for r in seen if isinstance(r, functions.channels.DeleteMessagesRequest) for i in r.id] == [7] + + +def test_deleting_a_notice_and_the_refusals_through_a_real_client(wire, tmp_path): + client = wire.client + msgs, chan = synced_channel(wire) + + async def go(): + db, ch = await saved_world(tmp_path, msgs) + peer = peer_of(ch) + + out = await remove(client, peer, [4]) + assert (out.deleted, out.failed, out.error) == (1, 0, None) and 4 not in chan.msgs + + chan.fail["DeleteMessagesRequest"] = rpc("ChatAdminRequiredError") + note = notice(chan, types.MessageActionPinMessage()) + out = await remove(client, peer, [note.id]) + assert (out.deleted, out.failed, out.error_name) == (0, 1, "ChatAdminRequiredError") and note.id in chan.msgs + chan.fail.clear() + + chan.fail["GetFullChannelRequest"] = rpc("ChannelPrivateError") # the bot lost its place in the channel + rep = await sync_channel(client, db, ch, SyncOptions(pause=0, grace=0)) + assert rep.error and not rep.changed and rep.checked == 0 + assert [p.message_id for p in await db.sent_posts(1)] == [1, 2, 3, 5] # nothing was touched + await db.close() + + asyncio.run(go()) + + +def test_a_restricted_channel_and_restricted_posts_through_a_real_client(wire, tmp_path): + """The channel object and the messages come back as real Telethon types, with Telegram's restriction marks.""" + client, seen = wire.client, wire.seen + msgs, chan = synced_channel(wire) + + async def go(): + db, ch = await saved_world(tmp_path, msgs) + opts = SyncOptions(pause=0, grace=0) + await sync_channel(client, db, ch, opts) # the first look + + notice_text = "This message couldn't be displayed on your device due to copyright infringement." + chan.restriction = notice_text # a copyright strike: the channel itself is restricted + for m in chan.msgs.values(): + if not isinstance(m, types.MessageService): + m.message = notice_text + chan._pts += 4 + del chan.msgs[3] + rep = await sync_channel(client, db, ch, opts) + assert rep.restricted_channel == notice_text and not rep.changed and rep.checked == 0 + assert [p.text for p in await db.sent_posts(1)] == ["first", "second", "third", "fifth"] # My posts untouched + + chan.restriction = None # only the posts carry the mark now (as real messages with restriction_reason) + for i in (1, 2): + chan.msgs[i].restriction_reason = [types.RestrictionReason("all", "copyright", notice_text)] + rep = await sync_channel(client, db, ch, opts) + assert sorted(rep.restricted) == [1, 2, 5] and rep.restricted_why in (notice_text, "Telegram shows a notice instead of the post") + assert rep.deleted == [3] and rep.edited == [] # post 3 really is gone, the others were left alone + assert [p.text for p in await db.sent_posts(1)] == ["first", "second", "fifth"] + await db.close() + + asyncio.run(go()) + writes = ( + functions.messages.SendMessageRequest, functions.messages.SendMediaRequest, functions.messages.EditMessageRequest, + functions.messages.ForwardMessagesRequest, functions.channels.DeleteMessagesRequest, + ) + assert not [r for r in seen if isinstance(r, writes)] + fulls = [r for r in seen if isinstance(r, functions.channels.GetFullChannelRequest)] + assert len(fulls) == 3 and all(isinstance(r.channel, types.InputChannel) for r in fulls)