slidgram 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- slidgram/__init__.py +7 -0
- slidgram/__main__.py +9 -0
- slidgram/avatar.py +51 -0
- slidgram/command.py +35 -0
- slidgram/config.py +50 -0
- slidgram/contact.py +98 -0
- slidgram/errors.py +72 -0
- slidgram/gateway.py +174 -0
- slidgram/group.py +478 -0
- slidgram/reactions.py +77 -0
- slidgram/session.py +585 -0
- slidgram/telegram.py +297 -0
- slidgram/text_entities.py +191 -0
- slidgram/tg_msg.py +278 -0
- slidgram-0.2.0.dist-info/LICENSE +661 -0
- slidgram-0.2.0.dist-info/METADATA +79 -0
- slidgram-0.2.0.dist-info/RECORD +19 -0
- slidgram-0.2.0.dist-info/WHEEL +4 -0
- slidgram-0.2.0.dist-info/entry_points.txt +3 -0
slidgram/__init__.py
ADDED
slidgram/__main__.py
ADDED
slidgram/avatar.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import TYPE_CHECKING
|
|
3
|
+
|
|
4
|
+
from pyrogram.types import ChatPhoto, Photo
|
|
5
|
+
from slidge.core.mixins import AvatarMixin
|
|
6
|
+
|
|
7
|
+
from . import config
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from .session import Session
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class SetAvatarMixin(AvatarMixin):
|
|
14
|
+
session: "Session"
|
|
15
|
+
log: logging.Logger
|
|
16
|
+
|
|
17
|
+
async def update_chat_photo(self, photo: ChatPhoto | Photo | None) -> None:
|
|
18
|
+
if photo is None:
|
|
19
|
+
await self.set_avatar(None)
|
|
20
|
+
return
|
|
21
|
+
|
|
22
|
+
if isinstance(photo, ChatPhoto):
|
|
23
|
+
if config.BIG_AVATARS:
|
|
24
|
+
file_id = photo.big_file_id
|
|
25
|
+
unique_id = photo.big_photo_unique_id
|
|
26
|
+
else:
|
|
27
|
+
file_id = photo.small_file_id
|
|
28
|
+
unique_id = photo.small_photo_unique_id
|
|
29
|
+
else:
|
|
30
|
+
file_id = photo.file_id
|
|
31
|
+
unique_id = photo.file_unique_id
|
|
32
|
+
|
|
33
|
+
if self.avatar_id == unique_id:
|
|
34
|
+
self.log.debug("Cached avatar is OK")
|
|
35
|
+
return
|
|
36
|
+
|
|
37
|
+
self.log.debug("Cached avatar is not OK: %r vs %r", self.avatar_id, unique_id)
|
|
38
|
+
self.session.create_task(self.__download(file_id, unique_id))
|
|
39
|
+
|
|
40
|
+
async def __download(self, file_id: str, unique_id: str) -> None:
|
|
41
|
+
try:
|
|
42
|
+
path = await self.session.tg.download_avatar(file_id)
|
|
43
|
+
except Exception as e:
|
|
44
|
+
self.log.error("Could not download avatar: %r", e)
|
|
45
|
+
return
|
|
46
|
+
|
|
47
|
+
if path is None:
|
|
48
|
+
self.log.error("Empty avatar download path? %r", path)
|
|
49
|
+
return
|
|
50
|
+
|
|
51
|
+
await self.set_avatar(path, unique_id, delete=True)
|
slidgram/command.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from typing import TYPE_CHECKING
|
|
2
|
+
|
|
3
|
+
from slidge import FormField
|
|
4
|
+
from slidge.command import Command, CommandAccess, Form
|
|
5
|
+
from slidge.command.categories import GROUPS
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from .session import Session
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class JoinPublicChat(Command):
|
|
12
|
+
NAME = "🚪 Join a telegram chat"
|
|
13
|
+
HELP = "Join a public channel, private group or supergroup"
|
|
14
|
+
NODE = CHAT_COMMAND = "join-chat"
|
|
15
|
+
ACCESS = CommandAccess.USER_LOGGED
|
|
16
|
+
INSTRUCTIONS = "Use a tg:// URI or a or a https://tg.me URL to join a group"
|
|
17
|
+
CATEGORY = GROUPS
|
|
18
|
+
|
|
19
|
+
async def run(self, _session, _ifrom, *_args):
|
|
20
|
+
return Form(
|
|
21
|
+
title=self.NAME,
|
|
22
|
+
instructions=self.INSTRUCTIONS,
|
|
23
|
+
fields=[FormField("query", label="Username, tg:// or t.me URL")],
|
|
24
|
+
handler=self.finish, # type:ignore
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
@staticmethod
|
|
28
|
+
async def finish(form_values: dict, session: "Session", _ifrom):
|
|
29
|
+
chat_name: str = form_values["query"]
|
|
30
|
+
if chat_name.startswith("http://"):
|
|
31
|
+
chat_name = "https://" + chat_name[7:]
|
|
32
|
+
|
|
33
|
+
chat = await session.tg.join_chat(chat_name)
|
|
34
|
+
muc = await session.bookmarks.by_legacy_id(chat.id)
|
|
35
|
+
return f"You can now join '{chat.title}' at xmpp:{muc.jid}?join"
|
slidgram/config.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
_api_txt = "\nIf you dont set it, users will have to enter their own on registration."
|
|
4
|
+
|
|
5
|
+
API_ID: Optional[int] = None
|
|
6
|
+
API_ID__DOC = "Telegram app api_id, obtained at https://my.telegram.org/apps" + _api_txt
|
|
7
|
+
|
|
8
|
+
API_HASH: Optional[str] = None
|
|
9
|
+
API_HASH__DOC = (
|
|
10
|
+
"Telegram app api_hash, obtained at https://my.telegram.org/apps" + _api_txt
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
REGISTRATION_AUTH_CODE_TIMEOUT: int = 60
|
|
14
|
+
REGISTRATION_AUTH_CODE_TIMEOUT__DOC = (
|
|
15
|
+
"On registration, users will be prompted for a 2FA code they receive "
|
|
16
|
+
"on other telegram clients."
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
GROUP_HISTORY_MAXIMUM_MESSAGES = 50
|
|
20
|
+
GROUP_HISTORY_MAXIMUM_MESSAGES__DOC = (
|
|
21
|
+
"The number of messages to fetch from a group history. "
|
|
22
|
+
"These messages and their attachments will be fetched on slidge startup."
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
ATTACHMENT_MAX_SIZE: int = 10 * 1024**2
|
|
26
|
+
ATTACHMENT_MAX_SIZE__DOC = (
|
|
27
|
+
"Maximum file size (in bytes) to download from telegram automatically/"
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
BIG_AVATARS = False
|
|
31
|
+
BIG_AVATARS__DOC = (
|
|
32
|
+
"Fetch contact avatars in high-resolution (640x640) instead of the "
|
|
33
|
+
"default 160x160. NB: slidge core main config AVATAR_SIZE still applies."
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
CONVERT_STICKERS = True
|
|
37
|
+
CONVERT_STICKERS__DOC = (
|
|
38
|
+
"Convert incoming animated stickers to webm videos. "
|
|
39
|
+
"Requires lottie_to_webm.sh in $PATH, cf <https://github.com/ed-asriyan/lottie-converter>, "
|
|
40
|
+
"along with FFMPEG."
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
CONVERT_STICKERS_EXECUTABLE = "lottie_to_webm.sh"
|
|
44
|
+
CONVERT_STICKERS_EXECUTABLE__DOC = "Path to the TGS/webm converter executable."
|
|
45
|
+
|
|
46
|
+
CONVERT_STICKERS_SIZE = 128
|
|
47
|
+
CONVERT_STICKERS_SIZE__DOC = "Width and height video stickers."
|
|
48
|
+
|
|
49
|
+
CONVERT_STICKERS_FPS = 60
|
|
50
|
+
CONVERT_STICKERS_FPS__DOC = "Framerate of the video stickers"
|
slidgram/contact.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from datetime import datetime, timedelta
|
|
3
|
+
from typing import TYPE_CHECKING
|
|
4
|
+
|
|
5
|
+
from pyrogram.enums import UserStatus
|
|
6
|
+
from pyrogram.types import Message, User
|
|
7
|
+
from slidge.contact import LegacyContact, LegacyRoster
|
|
8
|
+
from slixmpp.exceptions import XMPPError
|
|
9
|
+
|
|
10
|
+
from .avatar import SetAvatarMixin
|
|
11
|
+
from .errors import tg_to_xmpp_errors, tg_to_xmpp_errors_it
|
|
12
|
+
from .reactions import ReactionsMixin
|
|
13
|
+
from .tg_msg import TelegramMessageSenderMixin
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from .gateway import Gateway
|
|
17
|
+
from .session import Session
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Roster(LegacyRoster[int, "Contact"]):
|
|
21
|
+
session: "Session"
|
|
22
|
+
|
|
23
|
+
async def jid_username_to_legacy_id(self, jid_username: str) -> int:
|
|
24
|
+
try:
|
|
25
|
+
return int(jid_username)
|
|
26
|
+
except ValueError:
|
|
27
|
+
raise XMPPError("bad-request", f"Not an integer: {jid_username}")
|
|
28
|
+
|
|
29
|
+
@tg_to_xmpp_errors_it
|
|
30
|
+
async def fill(self):
|
|
31
|
+
assert self.session.tg.me is not None
|
|
32
|
+
for user in await self.session.tg.get_contacts():
|
|
33
|
+
if user.id == self.session.tg.me.id:
|
|
34
|
+
continue
|
|
35
|
+
yield await self.by_legacy_id(user.id)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Contact(
|
|
39
|
+
ReactionsMixin, TelegramMessageSenderMixin, SetAvatarMixin, LegacyContact[int]
|
|
40
|
+
):
|
|
41
|
+
xmpp: "Gateway"
|
|
42
|
+
session: "Session"
|
|
43
|
+
legacy_id: int
|
|
44
|
+
|
|
45
|
+
async def get_tg_user(self) -> User:
|
|
46
|
+
return await self.session.tg.get_user(self.legacy_id)
|
|
47
|
+
|
|
48
|
+
@tg_to_xmpp_errors
|
|
49
|
+
async def update_info(self):
|
|
50
|
+
user = await self.get_tg_user()
|
|
51
|
+
|
|
52
|
+
self.name = user.full_name
|
|
53
|
+
self.is_friend = user.is_contact
|
|
54
|
+
|
|
55
|
+
await self.update_chat_photo(user.photo)
|
|
56
|
+
|
|
57
|
+
self.update_tg_status(user)
|
|
58
|
+
|
|
59
|
+
if user.is_bot:
|
|
60
|
+
self.client_type = "bot"
|
|
61
|
+
else:
|
|
62
|
+
self.client_type = "phone"
|
|
63
|
+
|
|
64
|
+
self.set_vcard(
|
|
65
|
+
given=user.first_name,
|
|
66
|
+
surname=user.last_name,
|
|
67
|
+
full_name=user.full_name,
|
|
68
|
+
phone=user.phone_number,
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
if user.is_contact:
|
|
72
|
+
self.session.create_task(self.add_to_roster())
|
|
73
|
+
|
|
74
|
+
def update_tg_status(self, user: User):
|
|
75
|
+
if user.status is None:
|
|
76
|
+
self.offline()
|
|
77
|
+
return
|
|
78
|
+
|
|
79
|
+
if user.status == UserStatus.ONLINE:
|
|
80
|
+
self.online(last_seen=user.last_online_date)
|
|
81
|
+
elif user.status == UserStatus.RECENTLY:
|
|
82
|
+
self.away(last_seen=user.last_online_date)
|
|
83
|
+
elif user.last_online_date is not None:
|
|
84
|
+
now = datetime.now()
|
|
85
|
+
if now - user.last_online_date < timedelta(hours=1):
|
|
86
|
+
self.away(last_seen=user.last_online_date)
|
|
87
|
+
else:
|
|
88
|
+
self.extended_away(last_seen=user.last_online_date)
|
|
89
|
+
else:
|
|
90
|
+
self.offline()
|
|
91
|
+
|
|
92
|
+
async def send_tg_msg(
|
|
93
|
+
self, message: Message, carbon=False, correction=False, archive_only=False
|
|
94
|
+
) -> None:
|
|
95
|
+
await super().send_tg_msg(message, carbon=carbon, correction=correction)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
log = logging.getLogger(__name__)
|
slidgram/errors.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import functools
|
|
2
|
+
from typing import Any, Callable, ParamSpec, TypeVar
|
|
3
|
+
|
|
4
|
+
from pyrogram.errors import (
|
|
5
|
+
BadRequest,
|
|
6
|
+
Forbidden,
|
|
7
|
+
ReactionInvalid,
|
|
8
|
+
RPCError,
|
|
9
|
+
Unauthorized,
|
|
10
|
+
)
|
|
11
|
+
from slixmpp.exceptions import XMPPError
|
|
12
|
+
from slixmpp.types import ErrorConditions
|
|
13
|
+
|
|
14
|
+
from .telegram import InvalidUserException
|
|
15
|
+
|
|
16
|
+
P = ParamSpec("P")
|
|
17
|
+
R = TypeVar("R")
|
|
18
|
+
WrappedMethod = Callable[P, R]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
_ERROR_MAP: dict[Any, ErrorConditions] = {
|
|
22
|
+
ReactionInvalid: "not-acceptable",
|
|
23
|
+
Forbidden: "forbidden",
|
|
24
|
+
BadRequest: "bad-request",
|
|
25
|
+
Unauthorized: "not-authorized",
|
|
26
|
+
InvalidUserException: "item-not-found",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def tg_to_xmpp_errors(func: WrappedMethod) -> WrappedMethod:
|
|
31
|
+
@functools.wraps(func)
|
|
32
|
+
async def wrapped(*a, **ka):
|
|
33
|
+
try:
|
|
34
|
+
return await func(*a, **ka)
|
|
35
|
+
except (RPCError, InvalidUserException) as e:
|
|
36
|
+
_raise(e, func)
|
|
37
|
+
|
|
38
|
+
return wrapped
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def tg_to_xmpp_errors_it(func: WrappedMethod) -> WrappedMethod:
|
|
42
|
+
@functools.wraps(func)
|
|
43
|
+
async def wrapped(*a, **ka):
|
|
44
|
+
try:
|
|
45
|
+
async for x in func(*a, **ka):
|
|
46
|
+
yield x
|
|
47
|
+
except (RPCError, InvalidUserException) as e:
|
|
48
|
+
_raise(e, func)
|
|
49
|
+
|
|
50
|
+
return wrapped
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def catch_peer_id_invalid(func: WrappedMethod) -> WrappedMethod:
|
|
54
|
+
@functools.wraps(func)
|
|
55
|
+
async def wrapped(self, *a, **ka):
|
|
56
|
+
try:
|
|
57
|
+
return await func(self, *a, **ka)
|
|
58
|
+
except XMPPError as e:
|
|
59
|
+
self.log.error(
|
|
60
|
+
"%r in %s called with %s and %s", e.text, func.__name__, a, ka
|
|
61
|
+
)
|
|
62
|
+
except InvalidUserException as e:
|
|
63
|
+
self.log.error("Couldn't find user", e.args[0], func.__name__, a, ka)
|
|
64
|
+
|
|
65
|
+
return wrapped
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _raise(e: RPCError | InvalidUserException, func: WrappedMethod):
|
|
69
|
+
condition = _ERROR_MAP.get(type(e), "internal-server-error")
|
|
70
|
+
raise XMPPError(
|
|
71
|
+
condition, getattr(e, "MESSAGE", str(e.args)) + f" in '{func.__name__}'"
|
|
72
|
+
)
|
slidgram/gateway.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import shutil
|
|
3
|
+
import typing
|
|
4
|
+
|
|
5
|
+
import sqlalchemy as sa
|
|
6
|
+
from pyrogram import Client
|
|
7
|
+
from pyrogram.errors import SessionPasswordNeeded
|
|
8
|
+
from pyrogram.types import User as TGUser
|
|
9
|
+
from slidge import BaseGateway, global_config
|
|
10
|
+
from slidge.command.register import (
|
|
11
|
+
FormField,
|
|
12
|
+
GatewayUser,
|
|
13
|
+
RegistrationType,
|
|
14
|
+
TwoFactorNotRequired,
|
|
15
|
+
)
|
|
16
|
+
from slidge.util.util import is_valid_phone_number
|
|
17
|
+
from slixmpp import JID
|
|
18
|
+
from slixmpp.exceptions import XMPPError
|
|
19
|
+
|
|
20
|
+
from . import config, reactions
|
|
21
|
+
|
|
22
|
+
if typing.TYPE_CHECKING:
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
REGISTRATION_INSTRUCTIONS = (
|
|
26
|
+
"You need to create a telegram account in an official telegram client.\n\nThen you"
|
|
27
|
+
" can enter your phone number here, and you will receive a confirmation code in the"
|
|
28
|
+
" official telegram client. You can uninstall the telegram client after this if you"
|
|
29
|
+
" want."
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Gateway(BaseGateway):
|
|
34
|
+
REGISTRATION_INSTRUCTIONS = REGISTRATION_INSTRUCTIONS
|
|
35
|
+
REGISTRATION_FIELDS = [
|
|
36
|
+
FormField(var="phone", label="Phone number", required=True),
|
|
37
|
+
FormField(
|
|
38
|
+
var="password",
|
|
39
|
+
label="Password (only required if you set up one in Telegram)",
|
|
40
|
+
required=False,
|
|
41
|
+
private=True,
|
|
42
|
+
),
|
|
43
|
+
]
|
|
44
|
+
REGISTRATION_TYPE = RegistrationType.TWO_FACTOR_CODE
|
|
45
|
+
ROSTER_GROUP = "Telegram"
|
|
46
|
+
COMPONENT_NAME = "Telegram (slidge)"
|
|
47
|
+
COMPONENT_TYPE = "telegram"
|
|
48
|
+
COMPONENT_AVATAR = "https://web.telegram.org/img/logo_share.png"
|
|
49
|
+
|
|
50
|
+
SEARCH_FIELDS = [
|
|
51
|
+
FormField(var="phone", label="Phone number", required=True),
|
|
52
|
+
FormField(
|
|
53
|
+
var="first",
|
|
54
|
+
label="A first name for this contact (you can use whatever you want).",
|
|
55
|
+
required=True,
|
|
56
|
+
),
|
|
57
|
+
FormField(
|
|
58
|
+
var="last",
|
|
59
|
+
label="A last name for this contact (you can use whatever you want).",
|
|
60
|
+
),
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
GROUPS = True
|
|
64
|
+
|
|
65
|
+
LEGACY_MSG_ID_TYPE = LEGACY_CONTACT_ID_TYPE = LEGACY_ROOM_ID_TYPE = int
|
|
66
|
+
|
|
67
|
+
def __init__(self):
|
|
68
|
+
super().__init__()
|
|
69
|
+
if not config.API_ID:
|
|
70
|
+
self.REGISTRATION_FIELDS.extend(
|
|
71
|
+
[
|
|
72
|
+
FormField(
|
|
73
|
+
var="info",
|
|
74
|
+
type="fixed",
|
|
75
|
+
label="Get API id and hash on https://my.telegram.org/apps",
|
|
76
|
+
),
|
|
77
|
+
FormField(var="api_id", label="API ID", required=True),
|
|
78
|
+
FormField(var="api_hash", label="API Hash", required=True),
|
|
79
|
+
]
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
if not logging.getLogger().isEnabledFor(logging.DEBUG):
|
|
83
|
+
logging.getLogger("pyrogram.connection.connection").setLevel(
|
|
84
|
+
logging.WARNING
|
|
85
|
+
)
|
|
86
|
+
logging.getLogger("pyrogram.session.session").setLevel(logging.WARNING)
|
|
87
|
+
logging.getLogger("pyrogram.session.auth").setLevel(logging.WARNING)
|
|
88
|
+
|
|
89
|
+
reactions_db_path = global_config.HOME_DIR / "reacters.sqlite"
|
|
90
|
+
reactions.engine = sa.create_engine(f"sqlite:///{reactions_db_path}")
|
|
91
|
+
if not reactions_db_path.exists():
|
|
92
|
+
reactions.Base.metadata.create_all(reactions.engine)
|
|
93
|
+
|
|
94
|
+
if config.CONVERT_STICKERS:
|
|
95
|
+
self.stickers_dir = global_config.HOME_DIR / "stickers"
|
|
96
|
+
self.stickers_dir.mkdir(exist_ok=True)
|
|
97
|
+
|
|
98
|
+
async def validate(self, user_jid: JID, registration_form: dict[str, str | None]):
|
|
99
|
+
phone = registration_form["phone"]
|
|
100
|
+
assert isinstance(phone, str)
|
|
101
|
+
if not is_valid_phone_number(phone):
|
|
102
|
+
raise ValueError("Not a valid phone number")
|
|
103
|
+
for u in self.store.users.get_all():
|
|
104
|
+
if u.legacy_module_data.get("phone") == phone:
|
|
105
|
+
raise XMPPError(
|
|
106
|
+
"not-allowed",
|
|
107
|
+
text="Someone is already using this phone number on this server.",
|
|
108
|
+
)
|
|
109
|
+
tg_client = Client(
|
|
110
|
+
str(user_jid.bare),
|
|
111
|
+
phone_number=phone,
|
|
112
|
+
api_id=registration_form.get("api_id") or config.API_ID,
|
|
113
|
+
api_hash=registration_form.get("api_hash") or config.API_HASH,
|
|
114
|
+
workdir=global_config.HOME_DIR,
|
|
115
|
+
)
|
|
116
|
+
if await tg_client.connect():
|
|
117
|
+
await tg_client.disconnect()
|
|
118
|
+
raise TwoFactorNotRequired
|
|
119
|
+
|
|
120
|
+
sent_code = await tg_client.send_code(phone)
|
|
121
|
+
log.debug("The confirmation code for has been sent via %s", sent_code)
|
|
122
|
+
|
|
123
|
+
_clients[str(user_jid.bare)] = tg_client
|
|
124
|
+
|
|
125
|
+
return registration_form | {
|
|
126
|
+
"sent_code_hash": sent_code.phone_code_hash,
|
|
127
|
+
"api_id": registration_form.get("api_id") or config.API_ID,
|
|
128
|
+
"api_hash": registration_form.get("api_hash") or config.API_HASH,
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async def validate_two_factor_code(self, user: GatewayUser, code: str):
|
|
132
|
+
phone = user.legacy_module_data["phone"]
|
|
133
|
+
code_hash = user.legacy_module_data["sent_code_hash"]
|
|
134
|
+
|
|
135
|
+
assert isinstance(phone, str)
|
|
136
|
+
assert isinstance(code_hash, str)
|
|
137
|
+
|
|
138
|
+
tg_client = _clients[str(user.jid)]
|
|
139
|
+
tg_client.phone_code = code
|
|
140
|
+
|
|
141
|
+
try:
|
|
142
|
+
tg_user = await tg_client.sign_in(phone, code_hash, code)
|
|
143
|
+
except SessionPasswordNeeded as e:
|
|
144
|
+
log.debug("Password needed:", exc_info=e)
|
|
145
|
+
password = user.legacy_module_data["password"]
|
|
146
|
+
assert isinstance(password, str)
|
|
147
|
+
tg_user = await tg_client.check_password(password)
|
|
148
|
+
tg_client.password = password
|
|
149
|
+
|
|
150
|
+
await tg_client.disconnect()
|
|
151
|
+
del _clients[str(user.jid)]
|
|
152
|
+
|
|
153
|
+
if not isinstance(tg_user, TGUser):
|
|
154
|
+
log.error("Not a TG User: %s", tg_user)
|
|
155
|
+
raise XMPPError(
|
|
156
|
+
"not-authorized",
|
|
157
|
+
text=(
|
|
158
|
+
"Something went wrong when trying to authenticate you on the "
|
|
159
|
+
"telegram network. Please retry and/or contact your slidge admin."
|
|
160
|
+
),
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
async def unregister(self, user: GatewayUser):
|
|
164
|
+
session = self.session_cls.from_user(user)
|
|
165
|
+
session.logged = False
|
|
166
|
+
workdir = session.tg.settings.files_directory.absolute()
|
|
167
|
+
await session.tg.api.log_out()
|
|
168
|
+
shutil.rmtree(workdir)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
_clients: dict[str, Client] = {}
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
log = logging.getLogger(__name__)
|