From 1b211e6fcdded1b39f4d4bae0cfc56af461c1824 Mon Sep 17 00:00:00 2001 From: Pouri <94605698+erfnzdeh@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:19:20 +0330 Subject: [PATCH 1/4] message delete: refuse ids that are not in the named chat In private chats and basic groups messages.deleteMessages takes bare ids and Telethon drops the peer, so a wrong id or a range in a DM deleted messages in other chats, for both sides. Fetch the ids back through the peer first: a typed id that is not a message of the chat is refused and nothing is deleted, ids that only came from a range are skipped and listed in skipped. call log delete checks every chat before deleting anything. Channels and supergroups are unchanged. --- docs/reference/message.md | 2 +- tests/fake_telethon.py | 19 ++++++++-- tests/test_ops_call.py | 16 +++++++++ tests/test_ops_message.py | 76 +++++++++++++++++++++++++++++++++++++++ tlgr/models/message.py | 3 ++ tlgr/ops/_common.py | 61 +++++++++++++++++++++++++++++-- tlgr/ops/call.py | 14 +++++++- tlgr/ops/message.py | 38 +++++++++++++++++--- 8 files changed, 218 insertions(+), 11 deletions(-) diff --git a/docs/reference/message.md b/docs/reference/message.md index aecd022..d714c86 100644 --- a/docs/reference/message.md +++ b/docs/reference/message.md @@ -89,7 +89,7 @@ Composing a rich body needs layer 229 and is refused with NOT_SUPPORTED. Delete messages for me or for everyone. -In a channel or supergroup a delete is always for everyone — `channels.deleteMessages` has no revoke flag — so --for-me is only meaningful in private chats and basic groups. +In a channel or supergroup a delete is always for everyone (`channels.deleteMessages` has no revoke flag), so --for-me is only meaningful in private chats and basic groups. There, Telegram deletes by bare id across the whole account, so each id is first checked to be a message of CHAT: a typed id that is not is refused and nothing is deleted; ids from a range that are not are skipped and listed in `skipped`. ``` tlgr message delete [MSG_ID]... [OPTIONS] diff --git a/tests/fake_telethon.py b/tests/fake_telethon.py index 8e8d8c6..c5d8631 100644 --- a/tests/fake_telethon.py +++ b/tests/fake_telethon.py @@ -1294,6 +1294,9 @@ def add_call_log_entry( action=action, ) self.call_log.append(message) + # A call is a service message in the DM too, which is what lets + # `call log delete` check the id belongs to that chat. + self.history(chat_id).append(message) return message # -- the administration world ------------------------------------------ @@ -4846,9 +4849,19 @@ async def edit_message(self, entity: Any, message: Any, text: str = "", **kwargs async def delete_messages(self, entity: Any, message_ids: Any, revoke: bool = True) -> Any: chat_id = self._chat_id(entity) wanted = {int(i) for i in ([message_ids] if isinstance(message_ids, int) else message_ids)} - history = self.world.history(chat_id) - removed = [m for m in history if m.id in wanted] - self.world.messages[chat_id] = [m for m in history if m.id not in wanted] + # Like Telegram: a channel numbers its own messages and + # `channels.deleteMessages` honours it, but for any other peer + # Telethon sends `messages.deleteMessages(id=[...])` with no peer, and + # the ids are account-wide: whatever chat holds them loses them. + if chat_id <= -1000000000000: + scope = [chat_id] + else: + scope = [c for c in self.world.messages if c > -1000000000000] + removed = [] + for chat in scope: + history = self.world.history(chat) + removed.extend(m for m in history if m.id in wanted) + self.world.messages[chat] = [m for m in history if m.id not in wanted] self.world.calls.append( ("delete_messages", {"chat_id": chat_id, "ids": sorted(wanted), "revoke": revoke}) ) diff --git a/tests/test_ops_call.py b/tests/test_ops_call.py index 4b79262..2acab3c 100644 --- a/tests/test_ops_call.py +++ b/tests/test_ops_call.py @@ -418,6 +418,22 @@ async def test_deleting_rows_takes_chat_and_id(self, live_daemon, client, in_thr assert deleted == {"deleted": 1, "revoked": True} assert log.called("delete_messages")[0]["ids"] == [501] + async def test_a_row_naming_another_chats_message_is_refused( + self, live_daemon, client, in_thread, log + ): + """`messages.deleteMessages` takes bare ids: 777 would go wherever it lives.""" + from fake_telethon import make_user + + log.add_user(make_user(4343, username="bobby")) + log.add_message(4343, "not a call", message_id=777) + error = await failure( + client, in_thread, "call.log.delete", {"id": [f"{ALICE}:501", f"{ALICE}:777"]} + ) + assert error.exit_code == EXIT_NOT_FOUND + assert "777" in error.message + assert log.find(4343, 777) is not None + assert not log.called("delete_messages") + async def test_a_row_without_a_chat_is_a_usage_error(self, live_daemon, client, in_thread, log): error = await failure(client, in_thread, "call.log.delete", {"id": ["501"]}) assert error.exit_code == EXIT_USAGE diff --git a/tests/test_ops_message.py b/tests/test_ops_message.py index 418b62d..4d89ada 100644 --- a/tests/test_ops_message.py +++ b/tests/test_ops_message.py @@ -26,6 +26,8 @@ ) ALICE = 4242 +BOB = 4343 +BASIC = 320 CHANNEL = 5150 CHANNEL_ID = -1000000000000 - CHANNEL @@ -348,6 +350,80 @@ async def test_delete_removes_the_messages(self, live_daemon, client, in_thread, assert deleted["ids"] == [102, 103] assert history.find(ALICE, 102) is None + async def test_delete_refuses_an_id_from_another_private_chat( + self, live_daemon, client, in_thread, history + ): + """DMs share one id counter: 201 "in @alice" would delete Bob's message.""" + from fake_telethon import make_user + + history.add_user(make_user(BOB, username="bobby")) + history.add_message(BOB, "bob's message", message_id=201) + with pytest.raises(Exception) as caught: + await result( + client, in_thread, "message.delete", {"chat": "@alice", "msg_id": ["102", "201"]} + ) + error = classify(caught.value) + assert error.exit_code == EXIT_NOT_FOUND + assert "201" in error.message and "102" not in error.message + assert history.find(BOB, 201) is not None + assert history.find(ALICE, 102) is not None + assert not history.called("delete_messages") + + async def test_delete_in_a_basic_group_checks_ids_too( + self, live_daemon, client, in_thread, history + ): + from datetime import datetime, timezone + + from telethon.tl import types + + history.chats[BASIC] = types.Chat( + id=BASIC, + title="Old crew", + photo=types.ChatPhotoEmpty(), + participants_count=3, + date=datetime.now(timezone.utc), + version=1, + ) + history.add_message(-BASIC, "group message", message_id=301) + with pytest.raises(Exception) as caught: + await result( + client, in_thread, "message.delete", {"chat": str(-BASIC), "msg_id": ["104"]} + ) + assert classify(caught.value).exit_code == EXIT_NOT_FOUND + assert history.find(ALICE, 104) is not None + deleted = await result( + client, in_thread, "message.delete", {"chat": str(-BASIC), "msg_id": ["301"]} + ) + assert deleted["ids"] == [301] + assert history.find(-BASIC, 301) is None + + async def test_a_range_skips_ids_that_belong_to_other_chats( + self, live_daemon, client, in_thread, history + ): + from fake_telethon import make_user + + # 104 is Bob's: the account-wide counter interleaves the two DMs. + history.add_user(make_user(BOB, username="bobby")) + history.messages[ALICE] = [m for m in history.history(ALICE) if m.id != 104] + history.add_message(BOB, "bob's message", message_id=104) + envelope = await call( + client, in_thread, "message.delete", {"chat": "@alice", "msg_id": ["102-105"]} + ) + assert envelope["result"]["ids"] == [102, 103, 105] + assert envelope["result"]["skipped"] == [104] + assert any("skipped" in w for w in envelope["meta"]["warnings"]) + assert history.find(BOB, 104) is not None + assert history.find(ALICE, 103) is None + + async def test_a_channel_delete_is_not_checked(self, live_daemon, client, in_thread, history): + """Channels number their own messages; the peer is honoured there.""" + history.add_message(CHANNEL_ID, "post", message_id=7) + await result( + client, in_thread, "message.delete", {"chat": str(CHANNEL_ID), "msg_id": ["7", "8"]} + ) + assert history.find(CHANNEL_ID, 7) is None + assert history.called("delete_messages")[0]["ids"] == [7, 8] + async def test_delete_needs_ids_or_a_sender(self, live_daemon, client, in_thread, history): with pytest.raises(Exception) as caught: await result(client, in_thread, "message.delete", {"chat": "@alice"}) diff --git a/tlgr/models/message.py b/tlgr/models/message.py index 07077fc..13de54b 100644 --- a/tlgr/models/message.py +++ b/tlgr/models/message.py @@ -253,6 +253,9 @@ class DeleteResult(Model): #: reported as affected across every round trip. affected: int | None = None scheduled: bool = False + #: Ids from a range that are not messages of this chat (in a private chat + #: or basic group they belong to other chats), so they were not deleted. + skipped: list[int] = [] class EditResult(Model): diff --git a/tlgr/ops/_common.py b/tlgr/ops/_common.py index eb5ade8..0f49cea 100644 --- a/tlgr/ops/_common.py +++ b/tlgr/ops/_common.py @@ -14,7 +14,7 @@ from typing import Any -from tlgr.core.errors import UsageError +from tlgr.core.errors import NotFoundError, UsageError from tlgr.core.pagination import PageKind, decode_cursor from tlgr.ops._spec import OpContext @@ -23,8 +23,11 @@ "already", "client", "ids", + "ids_outside_chat", "input_channel", "is_not_modified", + "is_range", + "not_in_chat", "only", "random_id", "window", @@ -65,7 +68,7 @@ def ids(values: tuple[int, ...] | tuple[str, ...] | list[str] | None) -> list[in out: list[int] = [] for value in values or (): text = str(value) - if "-" in text[1:]: + if is_range(text): head, _, tail = text.partition("-") try: start, end = int(head), int(tail) @@ -82,6 +85,60 @@ def ids(values: tuple[int, ...] | tuple[str, ...] | list[str] | None) -> list[in return out +def is_range(value: object) -> bool: + """`100-120` rather than `100` or `-5`: the shape `ids` expands.""" + return "-" in str(value)[1:] + + +async def ids_outside_chat(ctx: OpContext, peer: Any, wanted: list[int]) -> list[int]: + """The ids in *wanted* that are not messages of *peer*, in order. + + Private chats and basic groups share one message-id counter per account, + and `messages.deleteMessages` takes bare ids with no peer at all: Telethon + drops the peer it was given. Deleting `[105]` "in @alice" therefore deletes + message 105 wherever it lives, in some other chat, for both sides. So the + ids are fetched back through the peer first (`get_messages` with a peer + returns None for an id from another chat), and only the ones that come + back may be deleted. Channels and supergroups number their own messages + and `channels.deleteMessages` honours the channel, so they are not checked. + + A deleted message also comes back None: from here "already gone" and + "belongs to someone else" look the same, and both mean "do not send it". + """ + from telethon.tl import types + + if not wanted or isinstance( + peer, (types.InputPeerChannel, types.InputPeerChannelFromMessage, types.InputChannel) + ): + return [] + handle = client(ctx) + present: set[int] = set() + for start in range(0, len(wanted), 100): + if start: + limiter = getattr(ctx, "limiter", None) + if limiter is not None: + await limiter.acquire("bulk") + found = await handle.get_messages(peer, ids=wanted[start : start + 100]) + if found is not None and not isinstance(found, list): + found = [found] + present.update(int(m.id) for m in found or [] if m is not None) + return [i for i in wanted if i not in present] + + +def not_in_chat(chat: str, refused: list[int]) -> NotFoundError: + """The refusal for ids `ids_outside_chat` found, raised before any delete.""" + listed = ", ".join(str(i) for i in refused[:20]) + if len(refused) > 20: + listed += f" and {len(refused) - 20} more" + error = NotFoundError( + f"message id(s) {listed} are not in {chat}: deleted already, or they belong to " + "another chat. In private chats and basic groups Telegram deletes by bare id " + "across the whole account, so nothing was deleted." + ) + error.hint = f"Check the ids with: tlgr message list {chat}" + return error + + def is_not_modified(exc: BaseException) -> bool: """MESSAGE_NOT_MODIFIED is success: the world already looks like that. diff --git a/tlgr/ops/call.py b/tlgr/ops/call.py index e4f540a..8b5702f 100644 --- a/tlgr/ops/call.py +++ b/tlgr/ops/call.py @@ -51,6 +51,7 @@ from tlgr.models.page import Page from tlgr.models.peer import Peer, PeerRef from tlgr.ops import _calls, _send +from tlgr.ops._common import ids_outside_chat, not_in_chat from tlgr.ops._params import arg, choice, opt from tlgr.ops._serialize import entity_to_peer from tlgr.ops._spec import OpContext, OperationSpec @@ -1585,9 +1586,20 @@ async def log_delete(ctx: OpContext, req: LogDeleteReq) -> CallLogDeleted: raise UsageError(f"{token!r} is not CHAT:MSG_ID", field="id") grouped.setdefault(chat, []).append(int(tail)) - deleted = 0 + # Every chat is checked before anything is deleted: a row naming a + # message of another private chat would otherwise delete that message + # (`messages.deleteMessages` takes bare ids), and a refusal half way + # through would leave the earlier chats already changed. + resolved: list[tuple[Any, list[int]]] = [] for chat, ids in grouped.items(): peer = await _send.resolve(ctx, parse_peer_ref(chat)) + outside = await ids_outside_chat(ctx, peer, ids) + if outside: + raise not_in_chat(chat, outside) + resolved.append((peer, ids)) + + deleted = 0 + for peer, ids in resolved: await client.delete_messages(peer, ids, revoke=req.revoke) deleted += len(ids) ctx.emit("call_log_deleted", {"count": deleted}) diff --git a/tlgr/ops/message.py b/tlgr/ops/message.py index 4c37b00..b3922c3 100644 --- a/tlgr/ops/message.py +++ b/tlgr/ops/message.py @@ -70,8 +70,11 @@ from tlgr.ops._common import already as _already from tlgr.ops._common import client as _client from tlgr.ops._common import ids as _ids +from tlgr.ops._common import ids_outside_chat as _ids_outside_chat from tlgr.ops._common import input_channel as _input_channel from tlgr.ops._common import is_not_modified as _is_not_modified +from tlgr.ops._common import is_range as _is_range +from tlgr.ops._common import not_in_chat as _not_in_chat from tlgr.ops._common import only as _only from tlgr.ops._common import random_id as _random_id from tlgr.ops._common import window as _window @@ -1633,11 +1636,34 @@ async def delete(ctx: OpContext, req: DeleteReq) -> DeleteResult: await client(fn.DeleteScheduledMessagesRequest(peer=peer, id=ids)) return DeleteResult(chat_id=chat_id, deleted=len(ids), ids=ids, scheduled=True) + skipped: list[int] = [] + outside = await _ids_outside_chat(ctx, peer, ids) + if outside: + # An id the caller typed by hand is refused outright: it may be a + # message in another chat. Ids that only came from a range are + # skipped instead, because in a private chat a range interleaves with + # every other private chat's messages and most of it is foreign. + typed = set(_ids(tuple(v for v in req.msg_id if not _is_range(v)))) + refused = [i for i in outside if i in typed] + if refused: + raise _not_in_chat(req.chat.raw, refused) + skipped = sorted(set(outside)) + ids = [i for i in ids if i not in set(skipped)] + ctx.warn(f"skipped {len(skipped)} id(s) in the range that are not messages of this chat") + if not ids: + return DeleteResult(chat_id=chat_id, deleted=0, skipped=skipped) + revoke = not req.for_me and req.for_everyone result = await client.delete_messages(peer, ids, revoke=revoke) affected = sum(int(getattr(item, "pts_count", 0) or 0) for item in (result or [])) ctx.emit("message_delete", {"chat_id": chat_id, "ids": ids}) - return DeleteResult(chat_id=chat_id, deleted=affected or len(ids), ids=ids, affected=affected) + return DeleteResult( + chat_id=chat_id, + deleted=affected or len(ids), + ids=ids, + affected=affected, + skipped=skipped, + ) SPEC_DELETE = OperationSpec( @@ -1647,9 +1673,13 @@ async def delete(ctx: OpContext, req: DeleteReq) -> DeleteResult: impl=delete, summary="Delete messages for me or for everyone", description=( - "In a channel or supergroup a delete is always for everyone — " - "`channels.deleteMessages` has no revoke flag — so --for-me is only " - "meaningful in private chats and basic groups." + "In a channel or supergroup a delete is always for everyone " + "(`channels.deleteMessages` has no revoke flag), so --for-me is only " + "meaningful in private chats and basic groups. There, Telegram deletes " + "by bare id across the whole account, so each id is first checked to be " + "a message of CHAT: a typed id that is not is refused and nothing is " + "deleted; ids from a range that are not are skipped and listed in " + "`skipped`." ), aliases=("msg.delete", "message.rm"), legacy_paths=("message delete", "msg delete"), From ea9525ae91de4264b6464b55042bf918ab300f33 Mon Sep 17 00:00:00 2001 From: Pouri <94605698+erfnzdeh@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:23:34 +0330 Subject: [PATCH 2/4] Refuse typed phone numbers that are not E.164 instead of guessing a country e164() prefixed + to any digits, so an Iranian 9123456789 typed without its trunk 0 became +91 (India) and a US 2125551234 became +212 (Morocco), and the lookup or import reached a stranger. Add a strict parse_e164 for user input (leading +, country code not starting with 0, 7 to 15 digits, separators, direction marks and Persian digits tolerated) and use it in resolve phone, contact add/remove --phone and +phone peer refs. vCard and CSV import and sync skip rows they cannot read and list them in rejected; sync --delete-missing --apply refuses when a row was rejected. e164() stays for phones the server returns. --- docs/reference/contact.md | 4 +- docs/reference/resolve.md | 2 +- tests/test_models.py | 47 ++++++++++++ tests/test_ops_contacts.py | 108 +++++++++++++++++++++++++++ tlgr/models/contact.py | 17 +++++ tlgr/models/peer.py | 72 +++++++++++++++++- tlgr/ops/contact.py | 147 +++++++++++++++++++++++++++++-------- tlgr/ops/resolve.py | 8 +- 8 files changed, 365 insertions(+), 40 deletions(-) diff --git a/docs/reference/contact.md b/docs/reference/contact.md index 8d252f3..694c591 100644 --- a/docs/reference/contact.md +++ b/docs/reference/contact.md @@ -215,7 +215,7 @@ Full: `contacts-users.close-friends-set`, `stories.close-friends-set` Bulk-import a phonebook from vCard or CSV. -Heavily flood-limited, so imports are chunked (`--batch-size`, 200 by default) and paced by the session limiter. `popular_invites` says how many other people already imported that number. +Heavily flood-limited, so imports are chunked (`--batch-size`, 200 by default) and paced by the session limiter. `popular_invites` says how many other people already imported that number. Numbers must be international (+ and country code): a row that is not is skipped and listed in `rejected`, never guessed at. ``` tlgr contact import [OPTIONS] @@ -560,7 +560,7 @@ Full: `contacts-users.contacts-statuses`, `dialogs.presence-watch` Two-way sync of a local phonebook file with the server contact list. -Prints the diff and changes nothing unless `--apply` is given, because `contacts.deleteByPhones` is irreversible server-side. +Prints the diff and changes nothing unless `--apply` is given, because `contacts.deleteByPhones` is irreversible server-side. Rows whose number is not international (+ and country code) are listed in `rejected`; with --delete-missing they make --apply refuse, since a skipped row may be a contact the diff would delete. ``` tlgr contact sync [OPTIONS] diff --git a/docs/reference/resolve.md b/docs/reference/resolve.md index be0c8e9..11ec61b 100644 --- a/docs/reference/resolve.md +++ b/docs/reference/resolve.md @@ -114,7 +114,7 @@ Full: `contacts-users.peer-id-conversion`, `dialogs.resolve-peer` Resolve a phone number to a user without adding a contact. -PHONE_NOT_OCCUPIED exits 13, never 5: no account and a privacy refusal are indistinguishable from here. The server asks for at most one lookup every three seconds, so --offline formats and validates against help.getCountriesList without an RPC. +PHONE_NOT_OCCUPIED exits 13, never 5: no account and a privacy refusal are indistinguishable from here. The server asks for at most one lookup every three seconds, so --offline formats and validates against help.getCountriesList without an RPC. The number must be international (+ and country code); a local form such as 0912... is refused rather than given a guessed country code. ``` tlgr resolve phone [OPTIONS] diff --git a/tests/test_models.py b/tests/test_models.py index 0d637cd..06f3b47 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -170,6 +170,53 @@ def test_user_ref_rejects_a_channel_id(self): def test_user_ref_accepts_a_user(self): assert parse_user_ref("+989120000000").kind == "phone" + def test_a_phone_ref_with_a_zero_country_code_is_refused(self): + with pytest.raises(ValueError, match="never starts with 0"): + parse_peer_ref("+0912 345 6789") + + +class TestParseE164: + """Typed phones: international form only, never a guessed country code.""" + + @pytest.mark.parametrize( + ("text", "value"), + [ + ("+98 912 345 6789", "+989123456789"), + ("+1 (212) 555-1234", "+12125551234"), + ("+44.20.7946.0018", "+442079460018"), + (" +7 916 123-45-67 ", "+79161234567"), + ("+۹۸ ۹۱۲ ۳۴۵ ۶۷۸۹", "+989123456789"), + ("‎+98 912 345 6789‏", "+989123456789"), + ("+683 4002", "+6834002"), + ], + ) + def test_accepts_international_numbers(self, text, value): + from tlgr.models.peer import parse_e164 + + assert parse_e164(text) == value + + @pytest.mark.parametrize( + ("text", "why"), + [ + # The issue's two misdirections: +91 India and +212 Morocco. + ("9123456789", "no country code"), + ("2125551234", "no country code"), + ("8 999 000-11-22", "no country code"), + ("0912 345 6789", "local number"), + ("0098 912 345 6789", r"\+98 ?912"), + ("+0912 345 6789", "never starts with 0"), + ("+12345", "7 to 15"), + ("+1234567890123456", "7 to 15"), + ("+98 912 abc", "not a phone number"), + ("", "required"), + ], + ) + def test_refuses_local_and_malformed_forms(self, text, why): + from tlgr.models.peer import PhoneNumberError, parse_e164 + + with pytest.raises(PhoneNumberError, match=why): + parse_e164(text) + def test_peer_ref_is_a_wire_shape(self): ref = parse_peer_ref("@alice") assert json.loads(encode(ref)) == {"raw": "@alice", "kind": "username", "value": "alice"} diff --git a/tests/test_ops_contacts.py b/tests/test_ops_contacts.py index f810a26..c640cf2 100644 --- a/tests/test_ops_contacts.py +++ b/tests/test_ops_contacts.py @@ -265,6 +265,19 @@ async def test_no_target_at_all_is_a_usage_error(self, live_daemon, client, in_t await result(client, in_thread, "contact.add", {"first_name": "Nobody"}) assert classify(caught.value).exit_code == EXIT_USAGE + async def test_a_phone_without_a_country_code_is_refused_not_guessed( + self, live_daemon, client, in_thread, book + ): + """`2125551234` must not become +212 (Morocco) and import a stranger.""" + with pytest.raises(Exception) as caught: + await result( + client, in_thread, "contact.add", {"phone": "2125551234", "first_name": "Al"} + ) + error = classify(caught.value) + assert error.exit_code == EXIT_USAGE + assert "country code" in error.message + assert not book.called("ImportContactsRequest") + class TestContactRename: async def test_it_writes_only_our_view_of_the_name(self, live_daemon, client, in_thread, book): @@ -317,6 +330,21 @@ async def test_removing_by_phone_reaches_numbers_with_no_account( assert answer["phones"] == ["+15550003333"] assert book.saved_contacts == [] + async def test_a_local_phone_is_refused_before_anything_is_deleted( + self, live_daemon, client, in_thread, book + ): + with pytest.raises(Exception) as caught: + await result( + client, + in_thread, + "contact.remove", + {"user": ["@alice"], "phone": ["0912 345 6789"]}, + ) + assert classify(caught.value).exit_code == EXIT_USAGE + assert not book.called("DeleteByPhonesRequest") + assert not book.called("DeleteContactsRequest") + assert ALICE in book.contacts + async def test_nothing_to_remove_is_a_usage_error(self, live_daemon, client, in_thread, book): with pytest.raises(Exception) as caught: await result(client, in_thread, "contact.remove", {}) @@ -704,6 +732,75 @@ async def test_import_batches(self, live_daemon, client, in_thread, book, tmp_pa ) assert answer["batches"] == 3 + async def test_a_local_number_is_reported_and_the_rest_imported( + self, live_daemon, client, in_thread, book, tmp_path + ): + """`9123456789` (an Iranian mobile without its 0) is not +91 India.""" + path = tmp_path / "mixed.csv" + path.write_text("phone,first,last\n+15550009999,Carol,\n9123456789,Reza,Ahmadi\n") + envelope = await call(client, in_thread, "contact.import", {"file": str(path)}) + answer = envelope["result"] + assert answer["parsed"] == 1 + assert [row["phone"] for row in answer["imported"]] == ["+15550009999"] + assert answer["rejected"] == [ + { + "line": 3, + "value": "9123456789", + "name": "Reza Ahmadi", + "reason": answer["rejected"][0]["reason"], + } + ] + assert "country code" in answer["rejected"][0]["reason"] + assert any("line 3" in w for w in envelope["meta"]["warnings"]) + sent = [c.phone for r in book.called("ImportContactsRequest") for c in r.contacts] + assert sent == ["+15550009999"] + + async def test_a_vcard_with_only_a_local_number_is_rejected( + self, live_daemon, client, in_thread, book, tmp_path + ): + path = tmp_path / "local.vcf" + path.write_text( + "BEGIN:VCARD\nVERSION:3.0\nN:Ahmadi;Reza;;;\nTEL;TYPE=CELL:0912 345 6789\n" + "END:VCARD\nBEGIN:VCARD\nVERSION:4.0\nFN:Carol Cooper\n" + "TEL;VALUE=uri;TYPE=cell:tel:+1-555-000-9999\nEND:VCARD\n" + ) + answer = await result(client, in_thread, "contact.import", {"file": str(path)}) + assert [row["phone"] for row in answer["imported"]] == ["+15550009999"] + assert [(r["line"], r["name"]) for r in answer["rejected"]] == [(4, "Reza Ahmadi")] + + async def test_a_file_of_only_local_numbers_is_a_usage_error( + self, live_daemon, client, in_thread, book, tmp_path + ): + path = tmp_path / "local.csv" + path.write_text("09123456789,Reza\n") + with pytest.raises(Exception) as caught: + await result(client, in_thread, "contact.import", {"file": str(path)}) + error = classify(caught.value) + assert error.exit_code == EXIT_USAGE + assert "line 1" in error.message + assert not book.called("ImportContactsRequest") + + async def test_sync_refuses_to_delete_when_a_row_was_rejected( + self, live_daemon, client, in_thread, book, tmp_path + ): + """A skipped `0...` row may be exactly a contact --delete-missing would delete.""" + path = tmp_path / "sync.csv" + path.write_text("+15550009999,Carol\n15550001111,Alice\n") + preview = await result( + client, in_thread, "contact.sync", {"file": str(path), "delete_missing": True} + ) + assert [r["value"] for r in preview["rejected"]] == ["15550001111"] + with pytest.raises(Exception) as caught: + await result( + client, + in_thread, + "contact.sync", + {"file": str(path), "delete_missing": True, "apply": True}, + ) + assert classify(caught.value).exit_code == EXIT_USAGE + assert not book.called("DeleteByPhonesRequest") + assert ALICE in book.contacts + async def test_an_empty_file_is_a_usage_error( self, live_daemon, client, in_thread, book, tmp_path ): @@ -1261,6 +1358,17 @@ async def test_a_phone_resolves_without_adding_a_contact( assert answer["peer"]["id"] == CAROL assert CAROL not in book.contacts + async def test_a_phone_without_a_plus_is_refused_before_any_lookup( + self, live_daemon, client, in_thread, book + ): + """`9123456789` typed for Iran must not be looked up as +91 (India).""" + with pytest.raises(Exception) as caught: + await result(client, in_thread, "resolve.phone", {"phone": "912 345 6789"}) + error = classify(caught.value) + assert error.exit_code == EXIT_USAGE + assert "country code" in error.message + assert not book.called("ResolvePhoneRequest") + async def test_an_unoccupied_phone_is_indeterminate_never_not_found( self, live_daemon, client, in_thread, book ): diff --git a/tlgr/models/contact.py b/tlgr/models/contact.py index c42d0cd..f1a530b 100644 --- a/tlgr/models/contact.py +++ b/tlgr/models/contact.py @@ -50,6 +50,7 @@ "PhoneShared", "PhotoResult", "ProfilePhoto", + "RejectedPhone", "SavedPhoneContact", "SignUp", "SuggestedBirthday", @@ -180,6 +181,20 @@ class ImportedPhone(ContactModel): retry: bool = False +class RejectedPhone(ContactModel): + """A phonebook row that was not imported because its number is not E.164. + + A number without a `+` and a country code is refused rather than guessed + at: prefixing `+` to local digits picks a country by accident and imports + a stranger. The row is reported so it can be fixed and imported again. + """ + + line: int = 0 + value: str = "" + name: str = "" + reason: str = "" + + class ContactImport(ContactModel): """`contact import`, reporting the retry list rather than swallowing it. @@ -194,6 +209,7 @@ class ContactImport(ContactModel): batches: int = 0 flood_waits: int = 0 dry_run: bool = False + rejected: list[RejectedPhone] = [] class ContactSync(ContactModel): @@ -204,6 +220,7 @@ class ContactSync(ContactModel): applied: bool = False imported: int = 0 deleted: int = 0 + rejected: list[RejectedPhone] = [] class SavedPhoneContact(ContactModel): diff --git a/tlgr/models/peer.py b/tlgr/models/peer.py index 5cdd6f7..6022ce4 100644 --- a/tlgr/models/peer.py +++ b/tlgr/models/peer.py @@ -20,10 +20,12 @@ "PeerKind", "PeerRef", "PeerRefKind", + "PhoneNumberError", "Photo", "Rights", "User", "UserRef", + "parse_e164", "parse_message_link", "parse_peer_ref", "parse_user_ref", @@ -38,6 +40,14 @@ _USERNAME_RE = re.compile(r"^[a-zA-Z0-9_]{4,32}$") _PHONE_RE = re.compile(r"^\+?[0-9][0-9 \-()]{4,24}$") +# What a typed or pasted number may carry besides digits: spaces, dots, +# brackets, ASCII and Unicode dashes, and the invisible direction marks +# (LRM, RLM, ZWNJ, isolates) that numbers copied out of right-to-left text pick up. +_PHONE_SEPARATORS = re.compile(r"[\s.()\-‐-―−​-‏⁦-⁩]") +_DIGITS = str.maketrans( + "۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩", + "01234567890123456789", +) _INT_RE = re.compile(r"^-?\d+$") @@ -305,6 +315,63 @@ def _mark_channel(raw_id: int) -> int: return _CHANNEL_MARK - abs(raw_id) if raw_id > 0 else raw_id +class PhoneNumberError(PeerRefError): + """A typed phone number that is not in international (E.164) form.""" + + +def parse_e164(text: str) -> str: + """A phone number a person typed, as `+`, or an error. + + Strict on purpose. A number with no `+` has no country code, and adding + one by prefixing `+` to the digits picks a country by accident: an + Iranian `912 345 6789` typed without its trunk 0 becomes +91 (India), a + US `212 555 1234` becomes +212 (Morocco), and the lookup or import then + reaches a stranger. So only the international form is accepted: a + leading `+`, a country code that does not start with 0, 7 to 15 digits + in all. Spaces, dots, dashes and brackets are ignored, and Persian or + Arabic-Indic digits count as digits. Local forms (`0912...`, `00 98...`, + `8 999...`) are refused with a message saying how to write them. + + Phones the *server* returns come without a `+` and are always + international; they do not go through here. + """ + raw = (text or "").strip() + if not raw: + raise PhoneNumberError("a phone number is required") + cleaned = _PHONE_SEPARATORS.sub("", raw.translate(_DIGITS)) + plus = cleaned.startswith("+") + digits = cleaned[1:] if plus else cleaned + if not digits.isascii() or not digits.isdigit(): + raise PhoneNumberError(f"{raw!r} is not a phone number") + if not plus: + if digits.startswith("00") and len(digits) > 2: + raise PhoneNumberError( + f"{raw!r} starts with the 00 international prefix; write it with a " + f"leading + instead, for example +{digits[2:]}" + ) + if digits.startswith("0"): + raise PhoneNumberError( + f"{raw!r} is a local number; drop the leading 0 and add the country " + "code with a leading +, for example +98 912 345 6789 for Iran" + ) + raise PhoneNumberError( + f"{raw!r} has no country code; write it in international form with a " + "leading + and the country code, for example +98 912 345 6789 or " + "+1 212 555 1234 (local forms such as 8 999 ... are not guessed at)" + ) + if digits.startswith("0"): + raise PhoneNumberError( + f"{raw!r}: a country code never starts with 0; if this is a local " + "number, drop the 0 and put the country code after the +" + ) + if not 7 <= len(digits) <= 15: + raise PhoneNumberError( + f"{raw!r} has {len(digits)} digits; an international number has 7 to 15, " + "country code included" + ) + return "+" + digits + + def parse_peer_ref(text: str) -> PeerRef: """Classify a chat/user reference. Syntax only — nothing is resolved here. @@ -339,10 +406,7 @@ def parse_peer_ref(text: str) -> PeerRef: return PeerRef(raw=raw, kind="id", value=value) if raw.startswith("+") and _PHONE_RE.match(raw): - digits = re.sub(r"[^0-9]", "", raw) - if not digits: - raise PeerRefError(f"{raw!r} is not a valid phone number") - return PeerRef(raw=raw, kind="phone", value="+" + digits) + return PeerRef(raw=raw, kind="phone", value=parse_e164(raw)) if _USERNAME_RE.match(raw): # A bare username is accepted because half the world types it that way. diff --git a/tlgr/ops/contact.py b/tlgr/ops/contact.py index 893f166..0f70d7d 100644 --- a/tlgr/ops/contact.py +++ b/tlgr/ops/contact.py @@ -51,6 +51,7 @@ FoundPeer, ImportedPhone, PhoneShared, + RejectedPhone, SavedPhoneContact, SignUp, TopPeer, @@ -58,7 +59,7 @@ UserStatus, ) from tlgr.models.page import Page -from tlgr.models.peer import Peer, PeerRef +from tlgr.models.peer import Peer, PeerRef, PhoneNumberError, parse_e164 from tlgr.ops import _send from tlgr.ops._params import arg, choice, opt from tlgr.ops._serialize import entity_to_peer, peer_id_of @@ -131,12 +132,26 @@ def mark_already(ctx: OpContext) -> None: def e164(phone: str) -> str: - """`(555) 000-1111` → `+15550001111`. Format only; nothing is looked up.""" + """A phone the *server* returned (`15550001111`) as `+15550001111`. + + Lenient on purpose: Telegram hands back international numbers without the + `+`, so prefixing one is correct here. It is wrong for anything a person + typed, where the digits may be a local number; that goes through + `typed_phone`. Format only; nothing is looked up. + """ cleaned = _PHONE_CHARS.sub("", (phone or "").strip()) digits = cleaned.lstrip("+") return f"+{digits}" if digits else "" +def typed_phone(text: str, field: str = "phone") -> str: + """A phone number from the caller, strictly E.164, or a USAGE error.""" + try: + return parse_e164(text) + except PhoneNumberError as exc: + raise UsageError(str(exc), field=field) from exc + + async def input_user( ctx: OpContext, ref: PeerRef | str, @@ -374,31 +389,42 @@ def _read_file(source: str, field: str) -> str: raise UsageError(f"{source}: {exc.strerror or exc}", field=field) from exc -def parse_phonebook(text: str) -> list[ImportedPhone]: - """vCard, CSV or one-number-per-line, into the same list. +def parse_phonebook(text: str) -> tuple[list[ImportedPhone], list[RejectedPhone]]: + """vCard, CSV or one-number-per-line, into `(entries, rejected rows)`. - Deliberately forgiving about the input and strict about the output: every - entry ends up with an E.164 number and a first name, because - `importContacts` rejects an empty name with `CONTACT_NAME_EMPTY` and a - whole batch fails for one bad row. + Forgiving about the layout and strict about the numbers: every entry ends + up with an E.164 number and a first name, because `importContacts` + rejects an empty name with `CONTACT_NAME_EMPTY` and a whole batch fails + for one bad row. A number without a `+` and country code is not guessed + at (see `parse_e164`); its row comes back in the second list instead, so + one local number does not abort the rest of the file. """ body = text.strip() if not body: - return [] + return [], [] if "BEGIN:VCARD" in body.upper(): return _parse_vcard(body) return _parse_csv(body) -def _parse_vcard(text: str) -> list[ImportedPhone]: +def _tel_value(value: str) -> str: + """The number in a vCard TEL value; vCard 4 spells it `tel:+1-555-...`.""" + value = value.strip() + return value[4:] if value.lower().startswith("tel:") else value + + +def _parse_vcard(text: str) -> tuple[list[ImportedPhone], list[RejectedPhone]]: out: list[ImportedPhone] = [] + rejected: list[RejectedPhone] = [] first = last = "" phone = "" - for raw_line in text.splitlines(): + refused: RejectedPhone | None = None + for number, raw_line in enumerate(text.splitlines(), start=1): line = raw_line.strip() upper = line.upper() if upper.startswith("BEGIN:VCARD"): first = last = phone = "" + refused = None elif upper.startswith("N:"): parts = line.split(":", 1)[1].split(";") last = parts[0].strip() if parts else "" @@ -408,25 +434,49 @@ def _parse_vcard(text: str) -> list[ImportedPhone]: first = words[0] if words else "" last = words[1] if len(words) > 1 else last elif upper.startswith("TEL") and ":" in line: - phone = e164(line.split(":", 1)[1]) - elif upper.startswith("END:VCARD") and phone: - out.append(ImportedPhone(phone=phone, first_name=first or phone, last_name=last)) - return out - - -def _parse_csv(text: str) -> list[ImportedPhone]: + value = _tel_value(line.split(":", 1)[1]) + try: + phone = parse_e164(value) + except PhoneNumberError as exc: + refused = RejectedPhone(line=number, value=value, reason=str(exc)) + elif upper.startswith("END:VCARD"): + if phone: + out.append(ImportedPhone(phone=phone, first_name=first or phone, last_name=last)) + elif refused is not None: + # Reported only when the card has no usable number at all: a + # card with an international mobile and a local landline + # imports the mobile, as it did before. + refused.name = " ".join(part for part in (first, last) if part) + rejected.append(refused) + return out, rejected + + +def _parse_csv(text: str) -> tuple[list[ImportedPhone], list[RejectedPhone]]: import csv import io out: list[ImportedPhone] = [] - for row in csv.reader(io.StringIO(text)): + rejected: list[RejectedPhone] = [] + reader = csv.reader(io.StringIO(text)) + for row in reader: cells = [cell.strip() for cell in row if cell.strip()] if not cells: continue - phone = e164(cells[0]) - if not phone or not phone.lstrip("+").isdigit(): + if not any(char.isdigit() for char in cells[0]): # A header row, or a comment. Skipping beats importing "phone". continue + try: + phone = parse_e164(cells[0]) + except PhoneNumberError as exc: + rejected.append( + RejectedPhone( + line=reader.line_num, + value=cells[0], + name=" ".join(cells[1:3]), + reason=str(exc), + ) + ) + continue out.append( ImportedPhone( phone=phone, @@ -434,7 +484,7 @@ def _parse_csv(text: str) -> list[ImportedPhone]: last_name=cells[2] if len(cells) > 2 else "", ) ) - return out + return out, rejected def render_export(contacts: list[Contact], fmt: str) -> str: @@ -773,7 +823,7 @@ async def add(ctx: OpContext, req: AddReq) -> ContactAdded: first, last = _split_name(req.name) first = req.first_name if req.first_name is not None else first last = req.last_name if req.last_name is not None else last - phone = e164(req.phone or "") + phone = typed_phone(req.phone) if req.phone else "" if req.from_message: card_phone, card_first, card_last, user_id = await _card_from_message(ctx, req.from_message) @@ -939,6 +989,10 @@ async def remove(ctx: OpContext, req: RemoveReq) -> ContactRemoved: if not req.user and not req.phone: raise UsageError("give at least one user or --phone", field="user") + # Every number is checked before anything is deleted: deleteByPhones is + # irreversible, and a guessed country code deletes somebody else's entry. + phones = [typed_phone(p) for p in req.phone if p.strip()] + user_ids: list[int] = [] if req.user: targets = [await input_user(ctx, ref) for ref in req.user] @@ -947,7 +1001,6 @@ async def remove(ctx: OpContext, req: RemoveReq) -> ContactRemoved: int(u.id) for u in (getattr(result, "users", None) or []) if hasattr(u, "id") ] or [int(getattr(t, "user_id", 0) or 0) for t in targets] - phones = [e164(p) for p in req.phone if e164(p)] if phones: await client_of(ctx)(fn.DeleteByPhonesRequest(phones=phones)) @@ -2153,9 +2206,12 @@ async def contact_import(ctx: OpContext, req: ImportReq) -> ContactImport: from telethon.tl import types from telethon.tl.functions import contacts as fn - entries = parse_phonebook(_read_file(req.file, "file")) + entries, rejected = parse_phonebook(_read_file(req.file, "file")) if not entries: - raise UsageError(f"{req.file} has no usable phone numbers in it", field="file") + detail = f"; {_rejected_summary(rejected)}" if rejected else "" + raise UsageError(f"{req.file} has no usable phone numbers in it{detail}", field="file") + if rejected: + ctx.warn(_rejected_summary(rejected)) imported: list[ImportedPhone] = [] retry: list[ImportedPhone] = [] @@ -2226,6 +2282,17 @@ async def contact_import(ctx: OpContext, req: ImportReq) -> ContactImport: popular_invites=popular, batches=batches, flood_waits=int(getattr(ctx, "flood_wait_slept", 0) or 0), + rejected=rejected, + ) + + +def _rejected_summary(rejected: list[RejectedPhone]) -> str: + """One line naming the rows that were left out, for a warning or an error.""" + shown = ", ".join(f"line {row.line} ({row.value})" for row in rejected[:5]) + more = f" and {len(rejected) - 5} more" if len(rejected) > 5 else "" + return ( + f"{len(rejected)} row(s) skipped because the number is not in international " + f"form (+ and country code): {shown}{more}; see `rejected` for the reasons" ) @@ -2238,7 +2305,9 @@ async def contact_import(ctx: OpContext, req: ImportReq) -> ContactImport: description=( "Heavily flood-limited, so imports are chunked (`--batch-size`, 200 " "by default) and paced by the session limiter. `popular_invites` " - "says how many other people already imported that number." + "says how many other people already imported that number. Numbers " + "must be international (+ and country code): a row that is not is " + "skipped and listed in `rejected`, never guessed at." ), mutating=True, rate_class="bulk", @@ -2270,7 +2339,7 @@ async def sync(ctx: OpContext, req: SyncReq) -> ContactSync: from telethon.tl import types from telethon.tl.functions import contacts as fn - entries = parse_phonebook(_read_file(req.file, "file")) + entries, rejected = parse_phonebook(_read_file(req.file, "file")) _, users, _ = await load_contacts(ctx) server = {e164(getattr(u, "phone", "") or ""): u for u in users if getattr(u, "phone", None)} local = {entry.phone: entry for entry in entries} @@ -2278,8 +2347,22 @@ async def sync(ctx: OpContext, req: SyncReq) -> ContactSync: to_import = [entry for phone, entry in local.items() if phone not in server] to_delete = [phone for phone in server if phone not in local] if req.delete_missing else [] + if rejected: + ctx.warn(_rejected_summary(rejected)) if not req.apply: - return ContactSync(to_import=to_import, to_delete=to_delete, applied=False) + return ContactSync( + to_import=to_import, to_delete=to_delete, applied=False, rejected=rejected + ) + if rejected and to_delete: + # A row we could not read may be one of the numbers in to_delete + # (`0912...` in the file, `+98912...` on the server), and + # deleteByPhones cannot be undone. Importing alone would be safe, but + # half-applying a sync the caller asked for whole is not. + raise UsageError( + f"refusing --delete-missing: {_rejected_summary(rejected)}. A skipped row " + "may be one of the contacts it would delete. Fix those rows and run again.", + field="file", + ) imported = 0 if to_import: @@ -2306,6 +2389,7 @@ async def sync(ctx: OpContext, req: SyncReq) -> ContactSync: applied=True, imported=imported, deleted=len(to_delete), + rejected=rejected, ) @@ -2317,7 +2401,10 @@ async def sync(ctx: OpContext, req: SyncReq) -> ContactSync: summary="Two-way sync of a local phonebook file with the server contact list", description=( "Prints the diff and changes nothing unless `--apply` is given, " - "because `contacts.deleteByPhones` is irreversible server-side." + "because `contacts.deleteByPhones` is irreversible server-side. Rows " + "whose number is not international (+ and country code) are listed " + "in `rejected`; with --delete-missing they make --apply refuse, since " + "a skipped row may be a contact the diff would delete." ), mutating=True, destructive=True, diff --git a/tlgr/ops/resolve.py b/tlgr/ops/resolve.py index 1d1c012..0305a10 100644 --- a/tlgr/ops/resolve.py +++ b/tlgr/ops/resolve.py @@ -47,7 +47,7 @@ from tlgr.ops._params import arg, choice, opt from tlgr.ops._serialize import entity_to_peer from tlgr.ops._spec import OpContext, OperationSpec -from tlgr.ops.contact import client_of, e164 +from tlgr.ops.contact import client_of, typed_phone __all__ = [name for name in dir() if name.startswith("SPEC_")] @@ -328,7 +328,7 @@ async def phone(ctx: OpContext, req: PhoneReq) -> ResolvedPhone: """ from telethon.tl.functions import contacts as fn - number = e164(req.phone) + number = typed_phone(req.phone) if (req.phone or "").strip() else "" table: list[dict[str, Any]] = [] if req.countries and not number: table = await _country_table(ctx, req.lang) @@ -389,7 +389,9 @@ async def phone(ctx: OpContext, req: PhoneReq) -> ResolvedPhone: "PHONE_NOT_OCCUPIED exits 13, never 5: no account and a privacy " "refusal are indistinguishable from here. The server asks for at " "most one lookup every three seconds, so --offline formats and " - "validates against help.getCountriesList without an RPC." + "validates against help.getCountriesList without an RPC. The number " + "must be international (+ and country code); a local form such as " + "0912... is refused rather than given a guessed country code." ), rate_class="resolve", min_interval_s=3.0, From 11fd2bb3bb65b0e5ff28413c9ebbcdb27ce685ec Mon Sep 17 00:00:00 2001 From: Pouri <94605698+erfnzdeh@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:26:13 +0330 Subject: [PATCH 3/4] Send and read formatted_date entities with their date tl_entities built MessageEntityFormattedDate without its required date, the constructor raised TypeError and the entity was dropped silently, and the read side dropped the date and flags too. MessageEntity gains date, date_unix and the six display flags; tl_entities passes them (a date chip without a date is now a USAGE error, not a silent drop), received entities keep them, and every place that copies an entity uses structs.replace so new fields are not lost when text is split or shifted. --- tests/test_ops_message.py | 85 +++++++++++++++++++++++++++++++++++++++ tests/test_text.py | 16 ++++++++ tlgr/core/text.py | 34 +++++++++++----- tlgr/models/message.py | 14 +++++++ tlgr/ops/_send.py | 48 ++++++++++++++++++---- tlgr/ops/_serialize.py | 18 +-------- tlgr/ops/message.py | 13 ++---- 7 files changed, 185 insertions(+), 43 deletions(-) diff --git a/tests/test_ops_message.py b/tests/test_ops_message.py index 4d89ada..4296068 100644 --- a/tests/test_ops_message.py +++ b/tests/test_ops_message.py @@ -82,6 +82,91 @@ async def test_markdown_is_parsed_into_entities_with_utf16_offsets( bold = [e for e in request.entities if type(e).__name__ == "MessageEntityBold"] assert bold and bold[0].offset == 3, "the emoji must count as two units" + async def test_a_formatted_date_entity_is_sent_with_its_date( + self, live_daemon, client, in_thread, peers + ): + """The constructor needs `date`; without it the entity was silently dropped.""" + import json + from datetime import datetime, timezone + + entities = [ + { + "type": "formatted_date", + "offset": 8, + "length": 11, + "date": "2026-09-13T17:00:00Z", + "short_date": True, + "short_time": True, + } + ] + sent = await result( + client, + in_thread, + "message.send", + {"chat": "@alice", "text": "meet on 13/09 17:00", "entities": json.dumps(entities)}, + ) + request = peers.called("SendMessageRequest")[0] + [chip] = request.entities + assert type(chip).__name__ == "MessageEntityFormattedDate" + assert chip.date == datetime(2026, 9, 13, 17, 0, tzinfo=timezone.utc) + assert (chip.short_date, chip.short_time, chip.long_date) == (True, True, None) + assert bytes(chip), "the entity must serialise as a real TL object" + assert sent["entities"] == [ + { + "type": "formatted_date", + "offset": 8, + "length": 11, + "date": "2026-09-13T17:00:00Z", + "date_unix": 1789318800, + "short_time": True, + "short_date": True, + } + ] + + async def test_a_formatted_date_entity_without_a_date_is_a_usage_error( + self, live_daemon, client, in_thread, peers + ): + import json + + entities = [{"type": "formatted_date", "offset": 0, "length": 5}] + with pytest.raises(Exception) as caught: + await result( + client, + in_thread, + "message.send", + {"chat": "@alice", "text": "13/09", "entities": json.dumps(entities)}, + ) + assert classify(caught.value).exit_code == EXIT_USAGE + assert not peers.called("SendMessageRequest") + + async def test_a_received_date_chip_keeps_its_date(self, live_daemon, client, in_thread, peers): + from datetime import datetime, timezone + + from telethon.tl import types + + message = peers.add_message(ALICE, "see you Monday", message_id=900) + message.entities = [ + types.MessageEntityFormattedDate( + offset=8, + length=6, + date=datetime(2026, 9, 14, 9, 30, tzinfo=timezone.utc), + day_of_week=True, + relative=False, + ) + ] + got = await result(client, in_thread, "message.get", {"chat": "@alice", "msg_id": 900}) + row = got[0] if isinstance(got, list) else got + assert row["entities"] == [ + { + "type": "formatted_date", + "offset": 8, + "length": 6, + "date": "2026-09-14T09:30:00Z", + "date_unix": 1789378200, + "day_of_week": True, + } + ] + async def test_the_default_parse_mode_is_none(self, live_daemon, client, in_thread, peers): """COR-21: v1 silently ate underscores and asterisks.""" sent = await result( diff --git a/tests/test_text.py b/tests/test_text.py index 54d3e34..c6556bb 100644 --- a/tests/test_text.py +++ b/tests/test_text.py @@ -104,3 +104,19 @@ def test_rejects_a_bare_object(self): def test_rejects_a_malformed_entity(self): with pytest.raises(UsageError, match="entities"): entities_from_json('[{"type":"bold","offset":"zero","length":4}]') + + def test_a_date_chip_survives_json_and_splits(self): + """Every copy of an entity must carry the date, not only the old fields.""" + from tlgr.ops._send import split_text + + chip = MessageEntity( + type="formatted_date", + offset=4, + length=5, + date_unix=1789318800, + short_date=True, + ) + assert entities_from_json(entities_to_json([chip])) == [chip] + parts = split_text("a" * 10 + " 13/09 17:00", [chip], limit=8) + carried = [e for _, ents in parts for e in ents if e.type == "formatted_date"] + assert carried and all(e.date_unix == 1789318800 and e.short_date for e in carried) diff --git a/tlgr/core/text.py b/tlgr/core/text.py index 8eb9848..b1d706d 100644 --- a/tlgr/core/text.py +++ b/tlgr/core/text.py @@ -17,22 +17,28 @@ from __future__ import annotations import json +from datetime import datetime from typing import Any from tlgr.core.errors import UsageError from tlgr.models.message import MessageEntity __all__ = [ + "DATE_FLAGS", "PARSE_MODES", "default_parse_mode", "entities_from_json", "entities_to_json", + "entity_from_tl", "parse_text", "utf16_len", ] PARSE_MODES = ("md", "html", "none") +#: The display flags of `messageEntityFormattedDate`, in TL order. +DATE_FLAGS = ("relative", "short_time", "long_time", "short_date", "long_date", "day_of_week") + #: Private-use sentinels: the parsers pass them through untouched, so a #: spoiler's boundaries survive markdown/HTML parsing and can be converted to #: real offsets afterwards. They are stripped from user input first. @@ -119,16 +125,13 @@ def shift(offset: int) -> int: total = cumulative return offset - total + import msgspec + moved = [ - MessageEntity( - type=entity.type, + msgspec.structs.replace( + entity, offset=shift(entity.offset), length=shift(entity.offset + entity.length) - shift(entity.offset), - url=entity.url, - user_id=entity.user_id, - language=entity.language, - document_id=entity.document_id, - collapsed=entity.collapsed, ) for entity in entities ] @@ -152,7 +155,17 @@ def _tl_entity_type(obj: Any) -> str: return "".join(result) -def _from_tl(obj: Any) -> MessageEntity: +def entity_from_tl(obj: Any) -> MessageEntity: + """A Telethon `MessageEntity*` as the model, every field it carries kept. + + `formatted_date` is the one with a payload beyond offsets: its date and + display flags are what make it a date chip, and dropping them turns a + received chip into plain text that cannot be sent back. + """ + from tlgr.core.timefmt import fmt_dt, to_unix + + date = getattr(obj, "date", None) + flags = {name: (getattr(obj, name, None) or None) for name in DATE_FLAGS} return MessageEntity( type=_tl_entity_type(obj), offset=int(getattr(obj, "offset", 0)), @@ -162,6 +175,9 @@ def _from_tl(obj: Any) -> MessageEntity: language=getattr(obj, "language", None), document_id=getattr(obj, "document_id", None), collapsed=getattr(obj, "collapsed", None), + date=fmt_dt(date) if isinstance(date, datetime) else None, + date_unix=to_unix(date) if isinstance(date, datetime) else None, + **flags, ) @@ -184,7 +200,7 @@ def parse_text(text: str, mode: str = "none") -> tuple[str, list[MessageEntity]] parser = tl_markdown if mode == "md" else tl_html parsed, raw_entities = parser.parse(marked) - entities = [_from_tl(entity) for entity in raw_entities or []] + entities = [entity_from_tl(entity) for entity in raw_entities or []] return _extract_spoilers(parsed, entities) diff --git a/tlgr/models/message.py b/tlgr/models/message.py index 13de54b..aaf559a 100644 --- a/tlgr/models/message.py +++ b/tlgr/models/message.py @@ -139,6 +139,20 @@ class MessageEntity(Model): language: str | None = None document_id: int | None = None collapsed: bool | None = None + #: `formatted_date` only: the moment the run shows in each reader's own + #: locale and zone. On input `date` takes RFC-3339, a unix timestamp or + #: anything `--schedule` takes; `date_unix` is accepted too. + date: str | None = None + date_unix: int | None = None + #: `formatted_date` display flags, as in `messageEntityFormattedDate`: + #: `relative` shows the time relative to now, the others pick which parts + #: of the date and time a client renders. + relative: bool | None = None + short_time: bool | None = None + long_time: bool | None = None + short_date: bool | None = None + long_date: bool | None = None + day_of_week: bool | None = None class Button(Model): diff --git a/tlgr/ops/_send.py b/tlgr/ops/_send.py index 825ed03..e9a9861 100644 --- a/tlgr/ops/_send.py +++ b/tlgr/ops/_send.py @@ -22,7 +22,13 @@ from typing import Annotated, Any from tlgr.core.errors import NotSupportedError, UsageError -from tlgr.core.text import default_parse_mode, entities_from_json, parse_text, utf16_len +from tlgr.core.text import ( + DATE_FLAGS, + default_parse_mode, + entities_from_json, + parse_text, + utf16_len, +) from tlgr.core.timefmt import parse_dt from tlgr.models.base import Request from tlgr.models.message import Message, MessageEntity @@ -212,6 +218,8 @@ def tl_entities(entities: list[MessageEntity]) -> list[Any] | None: kwargs["collapsed"] = entity.collapsed if entity.user_id is not None and name == "MessageEntityMentionName": kwargs["user_id"] = entity.user_id + if name == "MessageEntityFormattedDate": + kwargs.update(_date_kwargs(entity)) try: out.append(klass(**kwargs)) except TypeError: @@ -219,6 +227,33 @@ def tl_entities(entities: list[MessageEntity]) -> list[Any] | None: return out or None +def _date_kwargs(entity: MessageEntity) -> dict[str, Any]: + """The date and flags of a `formatted_date` run, or a USAGE error. + + `date` is a required field of the constructor, so an entity without one + is not something to drop quietly like an unknown type: the caller named a + date chip and would get plain text instead. + """ + if entity.date_unix is not None: + when = datetime.fromtimestamp(int(entity.date_unix), tz=timezone.utc) + elif entity.date: + parsed = parse_dt(entity.date) + if parsed is None: # pragma: no cover - a non-empty string parses or raises + raise UsageError("a formatted_date entity needs a date", field="entities") + when = parsed + else: + raise UsageError( + "a formatted_date entity needs a date (RFC-3339 or a unix timestamp) in " + "`date` or `date_unix`", + field="entities", + ) + out: dict[str, Any] = {"date": when} + for flag in DATE_FLAGS: + if getattr(entity, flag): + out[flag] = True + return out + + def split_text( text: str, entities: list[MessageEntity], limit: int = MAX_TEXT_UTF16 ) -> list[tuple[str, list[MessageEntity]]]: @@ -231,6 +266,8 @@ def split_text( if utf16_len(text) <= limit: return [(text, entities)] + import msgspec + parts: list[tuple[str, list[MessageEntity]]] = [] start = 0 # in UTF-16 units remaining = text @@ -253,15 +290,10 @@ def split_text( width = utf16_len(chunk) end = start + width sliced = [ - MessageEntity( - type=e.type, + msgspec.structs.replace( + e, offset=max(0, e.offset - start), length=min(e.offset + e.length, end) - max(e.offset, start), - url=e.url, - user_id=e.user_id, - language=e.language, - document_id=e.document_id, - collapsed=e.collapsed, ) for e in entities if e.offset < end and e.offset + e.length > start diff --git a/tlgr/ops/_serialize.py b/tlgr/ops/_serialize.py index da6cc14..c5f824a 100644 --- a/tlgr/ops/_serialize.py +++ b/tlgr/ops/_serialize.py @@ -12,6 +12,7 @@ import base64 from typing import Any +from tlgr.core.text import entity_from_tl from tlgr.core.timefmt import fmt_dt, to_unix from tlgr.models.dialog import ActionBar, ChatTheme, ChatWallpaper, NotifySettings from tlgr.models.message import ( @@ -341,22 +342,7 @@ def reactions_summary(message: Any) -> ReactionSummary | None: def message_entities(message: Any) -> list[MessageEntity]: """Formatting runs, with their UTF-16 offsets untouched.""" - out: list[MessageEntity] = [] - for entity in getattr(message, "entities", None) or []: - user_id = getattr(entity, "user_id", None) - out.append( - MessageEntity( - type=tl_snake(type(entity).__name__, "MessageEntity"), - offset=int(getattr(entity, "offset", 0)), - length=int(getattr(entity, "length", 0)), - url=getattr(entity, "url", None), - user_id=getattr(user_id, "user_id", user_id), - language=getattr(entity, "language", None), - document_id=getattr(entity, "document_id", None), - collapsed=getattr(entity, "collapsed", None), - ) - ) - return out + return [entity_from_tl(entity) for entity in getattr(message, "entities", None) or []] def service_action(action: Any) -> ServiceAction | None: diff --git a/tlgr/ops/message.py b/tlgr/ops/message.py index b3922c3..acb9616 100644 --- a/tlgr/ops/message.py +++ b/tlgr/ops/message.py @@ -2448,6 +2448,8 @@ async def entity_list(ctx: OpContext, req: EntityListReq) -> EntityReport: def _recount(text: str, entity: MessageEntity, units: str) -> MessageEntity: """Re-express a UTF-16 offset in code points or bytes.""" + import msgspec + raw = text.encode("utf-16-le") prefix = raw[: entity.offset * 2].decode("utf-16-le", "ignore") body = raw[entity.offset * 2 : (entity.offset + entity.length) * 2].decode( @@ -2457,16 +2459,7 @@ def _recount(text: str, entity: MessageEntity, units: str) -> MessageEntity: offset, length = len(prefix), len(body) else: offset, length = len(prefix.encode()), len(body.encode()) - return MessageEntity( - type=entity.type, - offset=offset, - length=length, - url=entity.url, - user_id=entity.user_id, - language=entity.language, - document_id=entity.document_id, - collapsed=entity.collapsed, - ) + return msgspec.structs.replace(entity, offset=offset, length=length) SPEC_ENTITY_LIST = OperationSpec( From bde7e2834b76d637f940565ef933f8e80425e00f Mon Sep 17 00:00:00 2001 From: Pouri <94605698+erfnzdeh@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:28:16 +0330 Subject: [PATCH 4/4] chat member remove: never lift an existing ban, refuse self, report a failed unban A kick is ban then unban, and the unban cleared any ban already in place, so kicking a banned user let them back in. In a channel or supergroup the member is now looked up first: an already banned user stays banned and a non-member is left alone (already: true). Naming this account is refused before anyone is removed. The ban and unban run under asyncio.shield, and a failed unban raises an error under the cause's code saying the user is now banned, with the unban command. --- docs/reference/chat.md | 2 +- tests/test_ops_chat_admin.py | 81 ++++++++++++++++++++ tlgr/ops/chat_member.py | 143 +++++++++++++++++++++++++++-------- 3 files changed, 195 insertions(+), 31 deletions(-) diff --git a/docs/reference/chat.md b/docs/reference/chat.md index bcb1194..3ced41e 100644 --- a/docs/reference/chat.md +++ b/docs/reference/chat.md @@ -1617,7 +1617,7 @@ Partial: `groups-channels-admin.admin-list` Remove (kick) a member; they can rejoin. -A kick is `editBanned(view_messages)` followed by an empty mask, so the person may come back. Use `chat member ban` to keep them out. `--purge` drains `messages.affectedHistory` until the server stops handing back an offset. +A kick is `editBanned(view_messages)` followed by an empty mask, so the person may come back. Use `chat member ban` to keep them out. In a channel or supergroup the member is looked up first: someone already banned stays banned and someone not in the chat is left alone (`already: true`). Naming this account is refused (use `chat leave`), and if the unban step fails the error says they are now banned. `--purge` drains `messages.affectedHistory` until the server stops handing back an offset. ``` tlgr chat member remove [USER]... [OPTIONS] diff --git a/tests/test_ops_chat_admin.py b/tests/test_ops_chat_admin.py index c735cbf..1527904 100644 --- a/tests/test_ops_chat_admin.py +++ b/tests/test_ops_chat_admin.py @@ -31,6 +31,7 @@ EXIT_INDETERMINATE, EXIT_NOT_FOUND, EXIT_PERMISSION, + EXIT_RATE_LIMITED, EXIT_USAGE, classify, ) @@ -246,6 +247,86 @@ async def test_a_kick_bans_then_unbans_so_they_may_return( assert sent[1].banned_rights.view_messages is False assert admin_world.banned.get(GROUP_ID, {}) == {} + async def test_kicking_an_already_banned_user_does_not_unban_them( + self, live_daemon, client, in_thread, admin_world + ): + """The kick's second editBanned would otherwise lift the ban.""" + await result( + client, in_thread, "chat.member.ban", {"chat": str(GROUP_ID), "user": [str(BOB)]} + ) + bans = len(admin_world.called("EditBannedRequest")) + out = await result( + client, in_thread, "chat.member.remove", {"chat": str(GROUP_ID), "user": [str(BOB)]} + ) + assert out == [ + {"chat_id": GROUP_ID, "user_id": BOB, "removed": False, "banned": True, "already": True} + ] + assert len(admin_world.called("EditBannedRequest")) == bans + assert admin_world.banned[GROUP_ID][BOB].view_messages is True + + async def test_kicking_a_non_member_changes_nothing( + self, live_daemon, client, in_thread, admin_world + ): + out = await result( + client, in_thread, "chat.member.remove", {"chat": str(GROUP_ID), "user": [str(CAROL)]} + ) + assert out[0]["already"] is True and out[0]["removed"] is False + assert not admin_world.called("EditBannedRequest") + + async def test_kicking_yourself_is_refused_before_anyone_is_removed( + self, live_daemon, client, in_thread, admin_world + ): + with pytest.raises(Exception) as caught: + await call( + client, + in_thread, + "chat.member.remove", + {"chat": str(GROUP_ID), "user": [str(BOB), "me"]}, + ) + error = classify(caught.value) + assert error.exit_code == EXIT_USAGE + assert "chat leave" in error.message + assert not admin_world.called("EditBannedRequest") + assert BOB in admin_world.members[GROUP_ID] + + async def test_kicking_yourself_by_username_is_refused_too( + self, live_daemon, client, in_thread, admin_world + ): + admin_world.me.username = "myself" + admin_world.add_user(admin_world.me) + code = await fails( + client, in_thread, "chat.member.remove", {"chat": str(GROUP_ID), "user": ["@myself"]} + ) + assert code == EXIT_USAGE + assert not admin_world.called("EditBannedRequest") + + async def test_a_failed_unban_says_the_user_is_now_banned( + self, live_daemon, client, in_thread, admin_world + ): + from telethon.errors import FloodWaitError + from telethon.tl import types + + def ban_then_flood(request): + if request.banned_rights.view_messages: + admin_world.banned.setdefault(GROUP_ID, {})[BOB] = request.banned_rights + return types.Updates(updates=[], users=[], chats=[], date=None, seq=0) + raise FloodWaitError(request, capture=30) + + admin_world.raw["EditBannedRequest"] = ban_then_flood + with pytest.raises(Exception) as caught: + await call( + client, + in_thread, + "chat.member.remove", + {"chat": str(GROUP_ID), "user": [str(BOB)]}, + flood_wait_max=0, + ) + error = classify(caught.value) + assert error.exit_code == EXIT_RATE_LIMITED + assert "BANNED" in error.message + assert f"chat member unban {GROUP_ID} {BOB}" in (error.hint or "") + assert error.wait_seconds == 30 + async def test_a_ban_leaves_the_mask_in_place( self, live_daemon, client, in_thread, admin_world ): diff --git a/tlgr/ops/chat_member.py b/tlgr/ops/chat_member.py index bb85550..b6b3fe8 100644 --- a/tlgr/ops/chat_member.py +++ b/tlgr/ops/chat_member.py @@ -24,7 +24,7 @@ import asyncio from typing import Annotated, Any -from tlgr.core.errors import EXIT_EMPTY, NotFoundError, UsageError +from tlgr.core.errors import EXIT_EMPTY, NotFoundError, TlgrError, UsageError, rule_for from tlgr.core.pagination import PageKind, build_page from tlgr.core.timefmt import fmt_dt, to_unix from tlgr.models.admin import ( @@ -576,8 +576,14 @@ async def remove_member(ctx: OpContext, req: MemberRemoveReq) -> list[MemberResu Telegram has no kick method. `editBanned(view_messages=True)` followed by an empty mask is what every client calls a kick, and the second call is the whole difference from `chat member ban`. + + That second call also lifts any ban already in place, so in a channel the + member is looked up first: someone already banned is left banned, and + someone not in the chat is left alone (`already: true` for both). The + ban and unban run shielded from cancellation, and if the unban fails the + error says the user is now banned and how to undo it. """ - from telethon.tl.functions import channels as chan_fn + from telethon.tl import types from telethon.tl.functions import messages as msg_fn if not req.user: @@ -585,26 +591,33 @@ async def remove_member(ctx: OpContext, req: MemberRemoveReq) -> list[MemberResu peer = await _send.resolve(ctx, req.chat) chat_id = _send.peer_id_of(peer) handle = _admin.client(ctx) + self_id = getattr(handle, "_self_id", None) + users = [(ref, await _send.resolve(ctx, ref)) for ref in req.user] + for ref, user in users: + # Checked for every user before anyone is removed, so a list that + # names this account by mistake changes nothing. + if isinstance(user, types.InputPeerSelf) or ( + self_id is not None and abs(_send.peer_id_of(user)) == int(self_id) + ): + raise UsageError( + f"{ref.raw} is this account; to leave the chat run: tlgr chat leave {req.chat.raw}", + field="user", + ) + out: list[MemberResult] = [] - for ref in req.user: - user = await _send.resolve(ctx, ref) + for ref, user in users: + row = MemberResult(chat_id=chat_id, user_id=abs(_send.peer_id_of(user)), removed=True) if _admin.is_channel(peer): - channel = _admin.input_channel(peer) - await handle( - chan_fn.EditBannedRequest( - channel=channel, - participant=user, - banned_rights=_rights.build_banned_rights([]), - ) - ) - await asyncio.sleep(0) - await handle( - chan_fn.EditBannedRequest( - channel=channel, - participant=user, - banned_rights=_rights.build_banned_rights(_rights.all_allowed()), - ) - ) + state = await _channel_presence(ctx, peer, user) + if state == "present": + try: + await asyncio.shield(_kick(handle, _admin.input_channel(peer), user)) + except _BanLeftInPlace as exc: + raise _ban_left_error(req, ref, out, exc.__cause__) from exc.__cause__ + else: + row.removed = False + row.already = True + row.banned = True if state == "banned" else None else: await handle( msg_fn.DeleteChatUserRequest( @@ -614,22 +627,87 @@ async def remove_member(ctx: OpContext, req: MemberRemoveReq) -> list[MemberResu purged = await _purge_all(ctx, peer, user) if req.purge else None if req.messages: purged = (purged or 0) + await _purge(ctx, peer, user, req.messages) - reported = ( + row.purged_messages = purged + row.reported = ( await _report_spam(ctx, peer, user, req.messages) if (req.report and _admin.is_channel(peer)) else None ) - out.append( - MemberResult( - chat_id=chat_id, - user_id=abs(_send.peer_id_of(user)), - removed=True, - purged_messages=purged, - reported=reported, + out.append(row) + ctx.emit( + "chat_members_removed", + {"chat_id": chat_id, "users": [r.user_id for r in out if r.removed]}, + ) + return out + + +async def _channel_presence(ctx: OpContext, peer: Any, user: Any) -> str: + """`present`, `banned` or `absent`: whether a kick has anything to do. + + A restricted member who is still in the chat is `present`: the kick + removes them, and their restriction goes with the ban that is lifted. + """ + try: + found = await _member_of(ctx, peer, user) + except NotFoundError: + return "absent" + participant = getattr(found, "participant", None) + kind = type(participant).__name__ + if kind == "ChannelParticipantLeft": + return "absent" + if kind == "ChannelParticipantBanned" and getattr(participant, "left", False): + rights = getattr(participant, "banned_rights", None) + return "banned" if getattr(rights, "view_messages", False) else "absent" + return "present" + + +class _BanLeftInPlace(Exception): + """The kick's ban went through and the unban after it did not.""" + + +async def _kick(handle: Any, channel: Any, user: Any) -> None: + """Ban then unban. Run under `asyncio.shield` so a cancel cannot split it.""" + from telethon.tl.functions import channels as chan_fn + + await handle( + chan_fn.EditBannedRequest( + channel=channel, participant=user, banned_rights=_rights.build_banned_rights([]) + ) + ) + await asyncio.sleep(0) + try: + await handle( + chan_fn.EditBannedRequest( + channel=channel, + participant=user, + banned_rights=_rights.build_banned_rights(_rights.all_allowed()), ) ) - ctx.emit("chat_members_removed", {"chat_id": chat_id, "users": [r.user_id for r in out]}) - return out + except Exception as exc: + raise _BanLeftInPlace() from exc + + +def _ban_left_error( + req: MemberRemoveReq, ref: PeerRef, done: list[MemberResult], cause: BaseException | None +) -> TlgrError: + """The failed unban, under the cause's own code, saying the user is banned.""" + rule = rule_for(cause) if cause is not None else None + wait = getattr(cause, "seconds", None) + removed = [str(r.user_id) for r in done if r.removed] + before = f" Removed before this one: {', '.join(removed)}." if removed else "" + error = TlgrError( + f"{ref.raw} was removed, but lifting the ban afterwards failed ({cause}), so they " + f"are now BANNED from {req.chat.raw} and cannot rejoin.{before}", + code=rule.code if rule else None, + ) + if rule is not None: + error.exit_code = rule.exit_code + error.http = rule.http + after = f" after {wait}s" if isinstance(wait, int) and wait else "" + error.hint = f"Run: tlgr chat member unban {req.chat.raw} {ref.raw}{after}" + if isinstance(wait, int): + error.wait_seconds = wait # type: ignore[attr-defined] + return error SPEC_MEMBER_REMOVE = OperationSpec( @@ -641,6 +719,11 @@ async def remove_member(ctx: OpContext, req: MemberRemoveReq) -> list[MemberResu description=( "A kick is `editBanned(view_messages)` followed by an empty mask, so " "the person may come back. Use `chat member ban` to keep them out. " + "In a channel or supergroup the member is looked up first: someone " + "already banned stays banned and someone not in the chat is left " + "alone (`already: true`). Naming this account is refused (use `chat " + "leave`), and if the unban step fails the error says they are now " + "banned. " "`--purge` drains `messages.affectedHistory` until the server stops " "handing back an offset." ),