Skip to content

Commit

Permalink
Remove utils file
Browse files Browse the repository at this point in the history
This gets rid of awkward lazy imports as well.
  • Loading branch information
Lonami committed Oct 29, 2023
1 parent 8fe8949 commit d80c6b3
Show file tree
Hide file tree
Showing 15 changed files with 167 additions and 151 deletions.
3 changes: 1 addition & 2 deletions client/src/telethon/_impl/client/client/chats.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
from typing import TYPE_CHECKING, Optional

from ...tl import abcs, functions, types
from ..types import AsyncList, ChatLike, File, Participant, RecentAction
from ..utils import build_chat_map
from ..types import AsyncList, ChatLike, File, Participant, RecentAction, build_chat_map
from .messages import SearchList

if TYPE_CHECKING:
Expand Down
3 changes: 1 addition & 2 deletions client/src/telethon/_impl/client/client/dialogs.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
from typing import TYPE_CHECKING, Optional

from ...tl import functions, types
from ..types import AsyncList, ChatLike, Dialog, Draft
from ..utils import build_chat_map, build_msg_map
from ..types import AsyncList, ChatLike, Dialog, Draft, build_chat_map, build_msg_map
from .messages import parse_message

if TYPE_CHECKING:
Expand Down
4 changes: 2 additions & 2 deletions client/src/telethon/_impl/client/client/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
Message,
OutFileLike,
OutWrapper,
expand_stripped_size,
generate_random_id,
)
from ..types.file import expand_stripped_size
from ..utils import generate_random_id
from .messages import parse_message

if TYPE_CHECKING:
Expand Down
12 changes: 10 additions & 2 deletions client/src/telethon/_impl/client/client/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,16 @@
from ...session import PackedChat
from ...tl import abcs, functions, types
from ..parsers import parse_html_message, parse_markdown_message
from ..types import AsyncList, Chat, ChatLike, Message, buttons
from ..utils import build_chat_map, generate_random_id, peer_id
from ..types import (
AsyncList,
Chat,
ChatLike,
Message,
build_chat_map,
buttons,
generate_random_id,
peer_id,
)

if TYPE_CHECKING:
from .client import Client
Expand Down
2 changes: 1 addition & 1 deletion client/src/telethon/_impl/client/client/updates.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from ...tl import abcs
from ..events import Event as EventBase
from ..events.filters import Filter
from ..utils import build_chat_map
from ..types import build_chat_map

if TYPE_CHECKING:
from .client import Client
Expand Down
12 changes: 10 additions & 2 deletions client/src/telethon/_impl/client/client/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,16 @@
from ...mtproto import RpcError
from ...session import PackedChat, PackedType
from ...tl import abcs, functions, types
from ..types import AsyncList, Channel, Chat, ChatLike, Group, User
from ..utils import build_chat_map, peer_id
from ..types import (
AsyncList,
Channel,
Chat,
ChatLike,
Group,
User,
build_chat_map,
peer_id,
)

if TYPE_CHECKING:
from .client import Client
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from ..event import Event

if TYPE_CHECKING:
from ...client import Client
from ...client.client import Client


class Text:
Expand Down
22 changes: 19 additions & 3 deletions client/src/telethon/_impl/client/types/__init__.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
from .async_list import AsyncList
from .callback_answer import CallbackAnswer
from .chat import Channel, Chat, ChatLike, Group, User
from .chat import (
Channel,
Chat,
ChatLike,
Group,
User,
build_chat_map,
expand_peer,
peer_id,
)
from .dialog import Dialog
from .draft import Draft
from .file import File, InFileLike, OutFileLike, OutWrapper
from .file import File, InFileLike, OutFileLike, OutWrapper, expand_stripped_size
from .inline_result import InlineResult
from .login_token import LoginToken
from .message import Message
from .message import Message, adapt_date, build_msg_map, generate_random_id
from .meta import NoPublicConstructor
from .participant import Participant
from .password_token import PasswordToken
Expand All @@ -20,15 +29,22 @@
"ChatLike",
"Group",
"User",
"build_chat_map",
"expand_peer",
"peer_id",
"Dialog",
"Draft",
"File",
"InFileLike",
"OutFileLike",
"OutWrapper",
"expand_stripped_size",
"InlineResult",
"LoginToken",
"Message",
"adapt_date",
"build_msg_map",
"generate_random_id",
"NoPublicConstructor",
"Participant",
"PasswordToken",
Expand Down
85 changes: 83 additions & 2 deletions client/src/telethon/_impl/client/types/chat/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,92 @@
from typing import Union
import itertools
import sys
from collections import defaultdict
from typing import DefaultDict, Dict, List, Optional, Union

from ....session import PackedChat
from ....tl import abcs, types
from .channel import Channel
from .chat import Chat
from .group import Group
from .user import User

ChatLike = Union[Chat, PackedChat, int, str]

__all__ = ["Chat", "ChatLike", "Channel", "Group", "User"]

def build_chat_map(users: List[abcs.User], chats: List[abcs.Chat]) -> Dict[int, Chat]:
users_iter = (User._from_raw(u) for u in users)
chats_iter = (
Channel._from_raw(c)
if isinstance(c, (types.Channel, types.ChannelForbidden)) and c.broadcast
else Group._from_raw(c)
for c in chats
)

result: Dict[int, Chat] = {c.id: c for c in itertools.chain(users_iter, chats_iter)}

if len(result) != len(users) + len(chats):
# The fabled ID collision between different chat types.
counter: DefaultDict[int, List[Union[abcs.User, abcs.Chat]]] = defaultdict(list)
for user in users:
if (id := getattr(user, "id", None)) is not None:
counter[id].append(user)
for chat in chats:
if (id := getattr(chat, "id", None)) is not None:
counter[id].append(chat)

for k, v in counter.items():
if len(v) > 1:
for x in v:
print(x, file=sys.stderr)

raise RuntimeError(
f"chat identifier collision: {k}; please report this"
)

return result


def peer_id(peer: abcs.Peer) -> int:
if isinstance(peer, types.PeerUser):
return peer.user_id
elif isinstance(peer, types.PeerChat):
return peer.chat_id
elif isinstance(peer, types.PeerChannel):
return peer.channel_id
else:
raise RuntimeError("unexpected case")


def expand_peer(peer: abcs.Peer, *, broadcast: Optional[bool]) -> Chat:
if isinstance(peer, types.PeerUser):
return User._from_raw(types.UserEmpty(id=peer.user_id))
elif isinstance(peer, types.PeerChat):
return Group._from_raw(types.ChatEmpty(id=peer.chat_id))
elif isinstance(peer, types.PeerChannel):
if broadcast is None:
broadcast = True # assume broadcast by default (Channel type is more accurate than Group)

channel = types.ChannelForbidden(
broadcast=broadcast,
megagroup=not broadcast,
id=peer.channel_id,
access_hash=0,
title="",
until_date=None,
)

return Channel._from_raw(channel) if broadcast else Group._from_raw(channel)
else:
raise RuntimeError("unexpected case")


__all__ = [
"Chat",
"ChatLike",
"Channel",
"Group",
"User",
"build_chat_map",
"peer_id",
"expand_peer",
]
6 changes: 2 additions & 4 deletions client/src/telethon/_impl/client/types/dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
from typing import TYPE_CHECKING, Dict, Optional, Self, Union

from ...tl import abcs, types
from .chat import Chat
from .chat import Chat, peer_id
from .draft import Draft
from .message import Message
from .meta import NoPublicConstructor

if TYPE_CHECKING:
from ..client import Client
from ..client.client import Client


class Dialog(metaclass=NoPublicConstructor):
Expand Down Expand Up @@ -51,8 +51,6 @@ def chat(self) -> Chat:
"""
The chat where messages are sent in this dialog.
"""
from ..utils import peer_id

return self._chat_map[peer_id(self._raw.peer)]

@property
Expand Down
12 changes: 3 additions & 9 deletions client/src/telethon/_impl/client/types/draft.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
from ...session import PackedChat
from ...tl import abcs, functions, types
from ..parsers import generate_html_message, generate_markdown_message
from .chat import Chat
from .message import Message
from .chat import Chat, expand_peer, peer_id
from .message import Message, generate_random_id
from .meta import NoPublicConstructor

if TYPE_CHECKING:
from ..client import Client
from ..client.client import Client


class Draft(metaclass=NoPublicConstructor):
Expand Down Expand Up @@ -60,8 +60,6 @@ def chat(self) -> Chat:
This is also the chat where the message will be sent to by :meth:`send`.
"""
from ..utils import expand_peer, peer_id

return self._chat_map.get(peer_id(self._peer)) or expand_peer(
self._peer, broadcast=None
)
Expand Down Expand Up @@ -161,8 +159,6 @@ async def edit(
)

async def _packed_chat(self) -> PackedChat:
from ..utils import peer_id

packed = None
if chat := self._chat_map.get(peer_id(self._peer)):
packed = chat.pack()
Expand All @@ -184,8 +180,6 @@ async def send(self) -> Message:
await draft.send(clear=False)
"""
from ..utils import generate_random_id

packed = await self._packed_chat()
peer = packed._to_input_peer()

Expand Down
2 changes: 1 addition & 1 deletion client/src/telethon/_impl/client/types/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from .meta import NoPublicConstructor

if TYPE_CHECKING:
from ..client import Client
from ..client.client import Client

math_round = round

Expand Down
6 changes: 2 additions & 4 deletions client/src/telethon/_impl/client/types/inline_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@

from ...tl import abcs, functions, types
from .chat import ChatLike
from .message import Message
from .message import Message, generate_random_id
from .meta import NoPublicConstructor

if TYPE_CHECKING:
from ..client import Client
from ..client.client import Client


class InlineResult(metaclass=NoPublicConstructor):
Expand Down Expand Up @@ -62,8 +62,6 @@ async def send(
:return: The sent message.
"""
from ..utils import generate_random_id

if chat is None and isinstance(self._default_peer, types.InputPeerEmpty):
raise ValueError("no target chat was specified")

Expand Down

0 comments on commit d80c6b3

Please sign in to comment.