Change case of new types

This commit is contained in:
Kai A. Hiller
2018-08-09 14:11:41 +02:00
parent 0f8009b1e9
commit e751d140f2
13 changed files with 118 additions and 118 deletions
+2 -2
View File
@@ -38,7 +38,7 @@ from .db import Message as DBMessage
from .tgclient import MautrixTelegramClient from .tgclient import MautrixTelegramClient
if TYPE_CHECKING: if TYPE_CHECKING:
from .types import TelegramId from .types import TelegramID
from .context import Context from .context import Context
from .config import Config from .config import Config
from .bot import Bot from .bot import Bot
@@ -68,7 +68,7 @@ class AbstractUser(ABC):
self.whitelisted = False # type: bool self.whitelisted = False # type: bool
self.relaybot_whitelisted = False # type: bool self.relaybot_whitelisted = False # type: bool
self.client = None # type: MautrixTelegramClient self.client = None # type: MautrixTelegramClient
self.tgid = None # type: TelegramId self.tgid = None # type: TelegramID
self.mxid = None # type: str self.mxid = None # type: str
self.is_relaybot = False # type: bool self.is_relaybot = False # type: bool
self.is_bot = False # type: bool self.is_bot = False # type: bool
+3 -3
View File
@@ -27,7 +27,7 @@ from telethon.tl.functions.messages import GetChatsRequest, GetFullChatRequest
from telethon.tl.functions.channels import GetChannelsRequest, GetParticipantRequest from telethon.tl.functions.channels import GetChannelsRequest, GetParticipantRequest
from telethon.errors import ChannelInvalidError, ChannelPrivateError from telethon.errors import ChannelInvalidError, ChannelPrivateError
from .types import MatrixUserId from .types import MatrixUserID
from .abstract_user import AbstractUser from .abstract_user import AbstractUser
from .db import BotChat from .db import BotChat
from . import puppet as pu, portal as po, user as u from . import puppet as pu, portal as po, user as u
@@ -172,7 +172,7 @@ class Bot(AbstractUser):
"Portal is not public. Use `/invite <mxid>` to get an invite.") "Portal is not public. Use `/invite <mxid>` to get an invite.")
async def handle_command_invite(self, portal: po.Portal, reply: ReplyFunc, async def handle_command_invite(self, portal: po.Portal, reply: ReplyFunc,
mxid_input: MatrixUserId) -> Message: mxid_input: MatrixUserID) -> Message:
if len(mxid_input) == 0: if len(mxid_input) == 0:
return await reply("Usage: `/invite <mxid>`") return await reply("Usage: `/invite <mxid>`")
elif not portal.mxid: elif not portal.mxid:
@@ -180,7 +180,7 @@ class Bot(AbstractUser):
"Create one with /portal first.") "Create one with /portal first.")
if not self.mxid_regex.match(mxid_input): if not self.mxid_regex.match(mxid_input):
return await reply("That doesn't look like a Matrix ID.") return await reply("That doesn't look like a Matrix ID.")
user = await u.User.get_by_mxid(MatrixUserId(mxid_input)).ensure_started() user = await u.User.get_by_mxid(MatrixUserID(mxid_input)).ensure_started()
if not user.relaybot_whitelisted: if not user.relaybot_whitelisted:
return await reply("That user is not whitelisted to use the bridge.") return await reply("That user is not whitelisted to use the bridge.")
elif await user.is_logged_in(): elif await user.is_logged_in():
+8 -8
View File
@@ -18,17 +18,17 @@ from typing import Dict, List, NewType, Optional, Tuple, Union
from mautrix_appservice import MatrixRequestError, IntentAPI from mautrix_appservice import MatrixRequestError, IntentAPI
from ..types import MatrixRoomId, MatrixUserId from ..types import MatrixRoomID, MatrixUserID
from . import command_handler, CommandEvent, SECTION_ADMIN from . import command_handler, CommandEvent, SECTION_ADMIN
from .. import puppet as pu, portal as po from .. import puppet as pu, portal as po
ManagementRoom = NewType('ManagementRoom', Tuple[MatrixRoomId, MatrixUserId]) ManagementRoom = NewType('ManagementRoom', Tuple[MatrixRoomID, MatrixUserID])
async def _find_rooms(intent: IntentAPI) -> Tuple[List[ManagementRoom], List[MatrixRoomId], async def _find_rooms(intent: IntentAPI) -> Tuple[List[ManagementRoom], List[MatrixRoomID],
List["po.Portal"], List["po.Portal"]]: List["po.Portal"], List["po.Portal"]]:
management_rooms = [] # type: List[ManagementRoom] management_rooms = [] # type: List[ManagementRoom]
unidentified_rooms = [] # type: List[MatrixRoomId] unidentified_rooms = [] # type: List[MatrixRoomID]
portals = [] # type: List[po.Portal] portals = [] # type: List[po.Portal]
empty_portals = [] # type: List[po.Portal] empty_portals = [] # type: List[po.Portal]
@@ -107,10 +107,10 @@ async def clean_rooms(evt: CommandEvent) -> Optional[Dict]:
async def set_rooms_to_clean(evt, management_rooms: List[ManagementRoom], async def set_rooms_to_clean(evt, management_rooms: List[ManagementRoom],
unidentified_rooms: List[MatrixRoomId], portals: List["po.Portal"], unidentified_rooms: List[MatrixRoomID], portals: List["po.Portal"],
empty_portals: List["po.Portal"]) -> None: empty_portals: List["po.Portal"]) -> None:
command = evt.args[0] command = evt.args[0]
rooms_to_clean = [] # type: List[Union[po.Portal, MatrixRoomId]] rooms_to_clean = [] # type: List[Union[po.Portal, MatrixRoomID]]
if command == "clean-recommended": if command == "clean-recommended":
rooms_to_clean += empty_portals rooms_to_clean += empty_portals
rooms_to_clean += unidentified_rooms rooms_to_clean += unidentified_rooms
@@ -159,7 +159,7 @@ async def set_rooms_to_clean(evt, management_rooms: List[ManagementRoom],
"`$cmdprefix+sp confirm-clean`.") "`$cmdprefix+sp confirm-clean`.")
async def execute_room_cleanup(evt, rooms_to_clean: List[Union[po.Portal, MatrixRoomId]]) -> None: async def execute_room_cleanup(evt, rooms_to_clean: List[Union[po.Portal, MatrixRoomID]]) -> None:
if len(evt.args) > 0 and evt.args[0] == "confirm-clean": if len(evt.args) > 0 and evt.args[0] == "confirm-clean":
await evt.reply(f"Cleaning {len(rooms_to_clean)} rooms. " await evt.reply(f"Cleaning {len(rooms_to_clean)} rooms. "
"This might take a while.") "This might take a while.")
@@ -168,7 +168,7 @@ async def execute_room_cleanup(evt, rooms_to_clean: List[Union[po.Portal, Matrix
if isinstance(room, po.Portal): if isinstance(room, po.Portal):
await room.cleanup_and_delete() await room.cleanup_and_delete()
cleaned += 1 cleaned += 1
elif isinstance(room, str): # str is aliased by MatrixRoomId elif isinstance(room, str): # str is aliased by MatrixRoomID
await po.Portal.cleanup_room(evt.az.intent, room, message="Room deleted") await po.Portal.cleanup_room(evt.az.intent, room, message="Room deleted")
cleaned += 1 cleaned += 1
evt.sender.command_status = None evt.sender.command_status = None
+3 -3
View File
@@ -21,7 +21,7 @@ import logging
from telethon.errors import FloodWaitError from telethon.errors import FloodWaitError
from ..types import MatrixRoomId from ..types import MatrixRoomID
from ..util import format_duration from ..util import format_duration
from .. import user as u, context as c from .. import user as u, context as c
@@ -38,7 +38,7 @@ SECTION_ADMIN = HelpSection("Administration", 50, "")
class CommandEvent: class CommandEvent:
def __init__(self, processor: 'CommandProcessor', room: MatrixRoomId, sender: u.User, def __init__(self, processor: 'CommandProcessor', room: MatrixRoomID, sender: u.User,
command: str, args: List[str], is_management: bool, is_portal: bool) -> None: command: str, args: List[str], is_management: bool, is_portal: bool) -> None:
self.az = processor.az self.az = processor.az
self.log = processor.log self.log = processor.log
@@ -154,7 +154,7 @@ class CommandProcessor:
self.public_website = context.public_website self.public_website = context.public_website
self.command_prefix = self.config["bridge.command_prefix"] self.command_prefix = self.config["bridge.command_prefix"]
async def handle(self, room: MatrixRoomId, sender: u.User, command: str, args: List[str], async def handle(self, room: MatrixRoomID, sender: u.User, command: str, args: List[str],
is_management: bool, is_portal: bool) -> Optional[Dict]: is_management: bool, is_portal: bool) -> Optional[Dict]:
evt = CommandEvent(self, room, sender, command, args, is_management, is_portal) evt = CommandEvent(self, room, sender, command, args, is_management, is_portal)
orig_command = command orig_command = command
+5 -5
View File
@@ -22,7 +22,7 @@ from telethon.errors import (ChatAdminRequiredError, UsernameInvalidError,
from telethon.tl.types import ChatForbidden, ChannelForbidden from telethon.tl.types import ChatForbidden, ChannelForbidden
from mautrix_appservice import MatrixRequestError, IntentAPI from mautrix_appservice import MatrixRequestError, IntentAPI
from ..types import MatrixRoomId, TelegramId from ..types import MatrixRoomID, TelegramID
from .. import portal as po, user as u from .. import portal as po, user as u
from . import (command_handler, CommandEvent, from . import (command_handler, CommandEvent,
SECTION_ADMIN, SECTION_CREATING_PORTALS, SECTION_PORTAL_MANAGEMENT) SECTION_ADMIN, SECTION_CREATING_PORTALS, SECTION_PORTAL_MANAGEMENT)
@@ -86,7 +86,7 @@ async def user_has_power_level(room: str, intent, sender: u.User, event: str, de
async def _get_portal_and_check_permission(evt: CommandEvent, permission: str, async def _get_portal_and_check_permission(evt: CommandEvent, permission: str,
action: Optional[str] = None action: Optional[str] = None
) -> Tuple[Union[Dict, po.Portal], bool]: ) -> Tuple[Union[Dict, po.Portal], bool]:
room_id = MatrixRoomId(evt.args[0]) if len(evt.args) > 0 else evt.room_id room_id = MatrixRoomID(evt.args[0]) if len(evt.args) > 0 else evt.room_id
portal = po.Portal.get_by_mxid(room_id) portal = po.Portal.get_by_mxid(room_id)
if not portal: if not portal:
@@ -168,7 +168,7 @@ async def bridge(evt: CommandEvent) -> Dict:
if len(evt.args) == 0: if len(evt.args) == 0:
return await evt.reply("**Usage:** " return await evt.reply("**Usage:** "
"`$cmdprefix+sp bridge <Telegram chat ID> [Matrix room ID]`") "`$cmdprefix+sp bridge <Telegram chat ID> [Matrix room ID]`")
room_id = MatrixRoomId(evt.args[1]) if len(evt.args) > 1 else evt.room_id room_id = MatrixRoomID(evt.args[1]) if len(evt.args) > 1 else evt.room_id
that_this = "This" if room_id == evt.room_id else "That" that_this = "This" if room_id == evt.room_id else "That"
portal = po.Portal.get_by_mxid(room_id) portal = po.Portal.get_by_mxid(room_id)
@@ -181,10 +181,10 @@ async def bridge(evt: CommandEvent) -> Dict:
# The /id bot command provides the prefixed ID, so we assume # The /id bot command provides the prefixed ID, so we assume
tgid_str = evt.args[0] tgid_str = evt.args[0]
if tgid_str.startswith("-100"): if tgid_str.startswith("-100"):
tgid = TelegramId(int(tgid_str[4:])) tgid = TelegramID(int(tgid_str[4:]))
peer_type = "channel" peer_type = "channel"
elif tgid_str.startswith("-"): elif tgid_str.startswith("-"):
tgid = TelegramId(-int(tgid_str)) tgid = TelegramID(-int(tgid_str))
peer_type = "chat" peer_type = "chat"
else: else:
return await evt.reply("That doesn't seem like a prefixed Telegram chat ID.\n\n" return await evt.reply("That doesn't seem like a prefixed Telegram chat ID.\n\n"
+2 -2
View File
@@ -28,7 +28,7 @@ from telethon.tl.types import (MessageEntityMention, MessageEntityMentionName,
from mautrix_appservice import MatrixRequestError from mautrix_appservice import MatrixRequestError
from mautrix_appservice.intent_api import IntentAPI from mautrix_appservice.intent_api import IntentAPI
from ..types import TelegramId from ..types import TelegramID
from .. import user as u, puppet as pu, portal as po from .. import user as u, puppet as pu, portal as po
from ..db import Message as DBMessage from ..db import Message as DBMessage
from .util import (add_surrogates, remove_surrogates, trim_reply_fallback_html, from .util import (add_surrogates, remove_surrogates, trim_reply_fallback_html,
@@ -292,7 +292,7 @@ def _parse_mention(html: List[str], entity_text: str) -> bool:
return False return False
def _parse_name_mention(html: List[str], entity_text: str, user_id: TelegramId) -> bool: def _parse_name_mention(html: List[str], entity_text: str, user_id: TelegramID) -> bool:
user = u.User.get_by_tgid(user_id) user = u.User.get_by_tgid(user_id)
if user: if user:
mxid = user.mxid mxid = user.mxid
+28 -28
View File
@@ -21,7 +21,7 @@ import re
from mautrix_appservice import MatrixRequestError, IntentError from mautrix_appservice import MatrixRequestError, IntentError
from .types import MatrixEvent, MatrixEventId, MatrixRoomId, MatrixUserId from .types import MatrixEvent, MatrixEventID, MatrixRoomID, MatrixUserID
from . import user as u, portal as po, puppet as pu, commands as com from . import user as u, portal as po, puppet as pu, commands as com
if TYPE_CHECKING: if TYPE_CHECKING:
@@ -38,7 +38,7 @@ class MatrixHandler:
def __init__(self, context: 'Context') -> None: def __init__(self, context: 'Context') -> None:
self.az, self.db, self.config, _, self.tgbot = context.core self.az, self.db, self.config, _, self.tgbot = context.core
self.commands = com.CommandProcessor(context) # type: com.CommandProcessor self.commands = com.CommandProcessor(context) # type: com.CommandProcessor
self.previously_typing = [] # type: List[MatrixUserId] self.previously_typing = [] # type: List[MatrixUserID]
self.az.matrix_event_handler(self.handle_event) self.az.matrix_event_handler(self.handle_event)
@@ -58,7 +58,7 @@ class MatrixHandler:
except asyncio.TimeoutError: except asyncio.TimeoutError:
self.log.exception("TimeoutError when trying to set avatar") self.log.exception("TimeoutError when trying to set avatar")
async def handle_puppet_invite(self, room_id: MatrixRoomId, puppet: pu.Puppet, inviter: u.User async def handle_puppet_invite(self, room_id: MatrixRoomID, puppet: pu.Puppet, inviter: u.User
) -> None: ) -> None:
intent = puppet.default_mxid_intent intent = puppet.default_mxid_intent
self.log.debug(f"{inviter} invited puppet for {puppet.tgid} to {room_id}") self.log.debug(f"{inviter} invited puppet for {puppet.tgid} to {room_id}")
@@ -111,7 +111,7 @@ class MatrixHandler:
await intent.send_notice(room_id, "This puppet will remain inactive until a " await intent.send_notice(room_id, "This puppet will remain inactive until a "
"Telegram chat is created for this room.") "Telegram chat is created for this room.")
async def accept_bot_invite(self, room_id: MatrixRoomId, inviter: u.User) -> None: async def accept_bot_invite(self, room_id: MatrixRoomID, inviter: u.User) -> None:
tries = 0 tries = 0
while tries < 5: while tries < 5:
try: try:
@@ -136,8 +136,8 @@ class MatrixHandler:
"<code>bridge.permissions</code> section in your config file.") "<code>bridge.permissions</code> section in your config file.")
await self.az.intent.leave_room(room_id) await self.az.intent.leave_room(room_id)
async def handle_invite(self, room_id: MatrixRoomId, user_id: MatrixUserId, async def handle_invite(self, room_id: MatrixRoomID, user_id: MatrixUserID,
inviter_mxid: MatrixUserId) -> None: inviter_mxid: MatrixUserID) -> None:
self.log.debug(f"{inviter_mxid} invited {user_id} to {room_id}") self.log.debug(f"{inviter_mxid} invited {user_id} to {room_id}")
inviter = u.User.get_by_mxid(inviter_mxid) inviter = u.User.get_by_mxid(inviter_mxid)
if inviter is None: if inviter is None:
@@ -164,8 +164,8 @@ class MatrixHandler:
# The rest can probably be ignored # The rest can probably be ignored
async def handle_join(self, room_id: MatrixRoomId, user_id: MatrixUserId, async def handle_join(self, room_id: MatrixRoomID, user_id: MatrixUserID,
event_id: MatrixEventId) -> None: event_id: MatrixEventID) -> None:
user = await u.User.get_by_mxid(user_id).ensure_started() user = await u.User.get_by_mxid(user_id).ensure_started()
portal = po.Portal.get_by_mxid(room_id) portal = po.Portal.get_by_mxid(room_id)
@@ -186,8 +186,8 @@ class MatrixHandler:
if await user.is_logged_in() or portal.has_bot: if await user.is_logged_in() or portal.has_bot:
await portal.join_matrix(user, event_id) await portal.join_matrix(user, event_id)
async def handle_part(self, room_id: MatrixRoomId, user_id: MatrixUserId, async def handle_part(self, room_id: MatrixRoomID, user_id: MatrixUserID,
sender_mxid: MatrixUserId, event_id: MatrixEventId) -> None: sender_mxid: MatrixUserID, event_id: MatrixEventID) -> None:
self.log.debug(f"{user_id} left {room_id}") self.log.debug(f"{user_id} left {room_id}")
sender = u.User.get_by_mxid(sender_mxid, create=False) sender = u.User.get_by_mxid(sender_mxid, create=False)
@@ -219,8 +219,8 @@ class MatrixHandler:
text = text[len(prefix) + 1:] text = text[len(prefix) + 1:]
return is_command, text return is_command, text
async def handle_message(self, room: MatrixRoomId, sender_id: MatrixUserId, message: Dict, async def handle_message(self, room: MatrixRoomID, sender_id: MatrixUserID, message: Dict,
event_id: MatrixEventId) -> None: event_id: MatrixEventID) -> None:
is_command, text = self.is_command(message) is_command, text = self.is_command(message)
sender = await u.User.get_by_mxid(sender_id).ensure_started() sender = await u.User.get_by_mxid(sender_id).ensure_started()
if not sender.relaybot_whitelisted: if not sender.relaybot_whitelisted:
@@ -255,8 +255,8 @@ class MatrixHandler:
is_portal=portal is not None) is_portal=portal is not None)
@staticmethod @staticmethod
async def handle_redaction(room_id: MatrixRoomId, sender_mxid: MatrixUserId, async def handle_redaction(room_id: MatrixRoomID, sender_mxid: MatrixUserID,
event_id: MatrixEventId) -> None: event_id: MatrixEventID) -> None:
sender = await u.User.get_by_mxid(sender_mxid).ensure_started() sender = await u.User.get_by_mxid(sender_mxid).ensure_started()
if not sender.relaybot_whitelisted: if not sender.relaybot_whitelisted:
return return
@@ -268,7 +268,7 @@ class MatrixHandler:
await portal.handle_matrix_deletion(sender, event_id) await portal.handle_matrix_deletion(sender, event_id)
@staticmethod @staticmethod
async def handle_power_levels(room_id: MatrixRoomId, sender_mxid: MatrixUserId, async def handle_power_levels(room_id: MatrixRoomID, sender_mxid: MatrixUserID,
new: Dict, old: Dict) -> None: new: Dict, old: Dict) -> None:
portal = po.Portal.get_by_mxid(room_id) portal = po.Portal.get_by_mxid(room_id)
sender = await u.User.get_by_mxid(sender_mxid).ensure_started() sender = await u.User.get_by_mxid(sender_mxid).ensure_started()
@@ -276,7 +276,7 @@ class MatrixHandler:
await portal.handle_matrix_power_levels(sender, new["users"], old["users"]) await portal.handle_matrix_power_levels(sender, new["users"], old["users"])
@staticmethod @staticmethod
async def handle_room_meta(evt_type: str, room_id: MatrixRoomId, sender_mxid: MatrixUserId, async def handle_room_meta(evt_type: str, room_id: MatrixRoomID, sender_mxid: MatrixUserID,
content: dict) -> None: content: dict) -> None:
portal = po.Portal.get_by_mxid(room_id) portal = po.Portal.get_by_mxid(room_id)
sender = await u.User.get_by_mxid(sender_mxid).ensure_started() sender = await u.User.get_by_mxid(sender_mxid).ensure_started()
@@ -291,7 +291,7 @@ class MatrixHandler:
await handler(sender, content[content_key]) await handler(sender, content[content_key])
@staticmethod @staticmethod
async def handle_room_pin(room_id: MatrixRoomId, sender_mxid: MatrixUserId, async def handle_room_pin(room_id: MatrixRoomID, sender_mxid: MatrixUserID,
new_events: Set[str], old_events: Set[str]) -> None: new_events: Set[str], old_events: Set[str]) -> None:
portal = po.Portal.get_by_mxid(room_id) portal = po.Portal.get_by_mxid(room_id)
sender = await u.User.get_by_mxid(sender_mxid).ensure_started() sender = await u.User.get_by_mxid(sender_mxid).ensure_started()
@@ -305,8 +305,8 @@ class MatrixHandler:
await portal.handle_matrix_pin(sender, None) await portal.handle_matrix_pin(sender, None)
@staticmethod @staticmethod
async def handle_name_change(room_id: MatrixRoomId, user_id: MatrixUserId, displayname: str, async def handle_name_change(room_id: MatrixRoomID, user_id: MatrixUserID, displayname: str,
prev_displayname: str, event_id: MatrixEventId) -> None: prev_displayname: str, event_id: MatrixEventID) -> None:
portal = po.Portal.get_by_mxid(room_id) portal = po.Portal.get_by_mxid(room_id)
if not portal or not portal.has_bot: if not portal or not portal.has_bot:
return return
@@ -316,14 +316,14 @@ class MatrixHandler:
await portal.name_change_matrix(user, displayname, prev_displayname, event_id) await portal.name_change_matrix(user, displayname, prev_displayname, event_id)
@staticmethod @staticmethod
def parse_read_receipts(content: Dict) -> Dict[MatrixUserId, MatrixEventId]: def parse_read_receipts(content: Dict) -> Dict[MatrixUserID, MatrixEventID]:
return {user_id: event_id return {user_id: event_id
for event_id, receipts in content.items() for event_id, receipts in content.items()
for user_id in receipts.get("m.read", {})} for user_id in receipts.get("m.read", {})}
@staticmethod @staticmethod
async def handle_read_receipts(room_id: MatrixRoomId, async def handle_read_receipts(room_id: MatrixRoomID,
receipts: Dict[MatrixUserId, MatrixEventId]) -> None: receipts: Dict[MatrixUserID, MatrixEventID]) -> None:
portal = po.Portal.get_by_mxid(room_id) portal = po.Portal.get_by_mxid(room_id)
if not portal: if not portal:
return return
@@ -335,13 +335,13 @@ class MatrixHandler:
await portal.mark_read(user, event_id) await portal.mark_read(user, event_id)
@staticmethod @staticmethod
async def handle_presence(user_id: MatrixUserId, presence: str) -> None: async def handle_presence(user_id: MatrixUserID, presence: str) -> None:
user = await u.User.get_by_mxid(user_id).ensure_started() user = await u.User.get_by_mxid(user_id).ensure_started()
if not await user.is_logged_in(): if not await user.is_logged_in():
return return
user.set_presence(presence == "online") user.set_presence(presence == "online")
async def handle_typing(self, room_id: MatrixRoomId, now_typing: List[MatrixUserId]) -> None: async def handle_typing(self, room_id: MatrixRoomID, now_typing: List[MatrixUserID]) -> None:
portal = po.Portal.get_by_mxid(room_id) portal = po.Portal.get_by_mxid(room_id)
if not portal: if not portal:
return return
@@ -378,12 +378,12 @@ class MatrixHandler:
return return
self.log.debug("Received event: %s", evt) self.log.debug("Received event: %s", evt)
evt_type = evt.get("type", "m.unknown") # type: str evt_type = evt.get("type", "m.unknown") # type: str
room_id = evt.get("room_id", None) # type: Optional[MatrixRoomId] room_id = evt.get("room_id", None) # type: Optional[MatrixRoomID]
event_id = evt.get("event_id", None) # type: Optional[MatrixEventId] event_id = evt.get("event_id", None) # type: Optional[MatrixEventID]
sender = evt.get("sender", None) # type: Optional[MatrixUserId] sender = evt.get("sender", None) # type: Optional[MatrixUserID]
content = evt.get("content", {}) # type: Dict content = evt.get("content", {}) # type: Dict
if evt_type == "m.room.member": if evt_type == "m.room.member":
state_key = evt["state_key"] # type: MatrixUserId state_key = evt["state_key"] # type: MatrixUserID
prev_content = evt.get("unsigned", {}).get("prev_content", {}) # type: Dict prev_content = evt.get("unsigned", {}).get("prev_content", {}) # type: Dict
membership = content.get("membership", "") # type: str membership = content.get("membership", "") # type: str
prev_membership = prev_content.get("membership", "leave") # type: str prev_membership = prev_content.get("membership", "leave") # type: str
+19 -19
View File
@@ -62,7 +62,7 @@ from telethon.tl.types import (
UserFull) UserFull)
from mautrix_appservice import MatrixRequestError, IntentError, AppService, IntentAPI from mautrix_appservice import MatrixRequestError, IntentError, AppService, IntentAPI
from .types import MatrixEventId, MatrixRoomId, MatrixUserId, TelegramId from .types import MatrixEventID, MatrixRoomID, MatrixUserID, TelegramID
from .context import Context from .context import Context
from .db import Portal as DBPortal, Message as DBMessage, TelegramFile as DBTelegramFile from .db import Portal as DBPortal, Message as DBMessage, TelegramFile as DBTelegramFile
from . import puppet as p, user as u, formatter, util from . import puppet as p, user as u, formatter, util
@@ -105,13 +105,13 @@ class Portal:
by_mxid = {} # type: Dict[str, Portal] by_mxid = {} # type: Dict[str, Portal]
by_tgid = {} # type: Dict[Tuple[int, int], Portal] by_tgid = {} # type: Dict[Tuple[int, int], Portal]
def __init__(self, tgid: TelegramId, peer_type: str, tg_receiver: Optional[int] = None, def __init__(self, tgid: TelegramID, peer_type: str, tg_receiver: Optional[int] = None,
mxid: Optional[MatrixRoomId] = None, username: Optional[str] = None, mxid: Optional[MatrixRoomID] = None, username: Optional[str] = None,
megagroup: Optional[bool] = False, title: Optional[str] = None, megagroup: Optional[bool] = False, title: Optional[str] = None,
about: Optional[str] = None, photo_id: Optional[str] = None, about: Optional[str] = None, photo_id: Optional[str] = None,
db_instance: DBPortal = None) -> None: db_instance: DBPortal = None) -> None:
self.mxid = mxid # type: Optional[MatrixRoomId] self.mxid = mxid # type: Optional[MatrixRoomID]
self.tgid = tgid # type: TelegramId self.tgid = tgid # type: TelegramID
self.tg_receiver = tg_receiver or tgid # type: int self.tg_receiver = tg_receiver or tgid # type: int
self.peer_type = peer_type # type: str self.peer_type = peer_type # type: str
self.username = username # type: str self.username = username # type: str
@@ -304,7 +304,7 @@ class Portal:
return await self._create_matrix_room(user, entity, invites) return await self._create_matrix_room(user, entity, invites)
async def _create_matrix_room(self, user: 'AbstractUser', entity: TypeChat, invites: InviteList async def _create_matrix_room(self, user: 'AbstractUser', entity: TypeChat, invites: InviteList
) -> Optional[MatrixRoomId]: ) -> Optional[MatrixRoomID]:
direct = self.peer_type == "user" direct = self.peer_type == "user"
if self.mxid: if self.mxid:
@@ -439,7 +439,7 @@ class Portal:
and config["bridge.max_initial_member_sync"] == -1 and config["bridge.max_initial_member_sync"] == -1
and (self.megagroup or self.peer_type != "channel")) and (self.megagroup or self.peer_type != "channel"))
if trust_member_list: if trust_member_list:
joined_mxids = cast(List[MatrixUserId], joined_mxids = cast(List[MatrixUserID],
await self.main_intent.get_room_members(self.mxid)) await self.main_intent.get_room_members(self.mxid))
for user_mxid in joined_mxids: for user_mxid in joined_mxids:
if user_mxid == self.az.bot_mxid: if user_mxid == self.az.bot_mxid:
@@ -460,7 +460,7 @@ class Portal:
"You had left this Telegram chat.") "You had left this Telegram chat.")
continue continue
async def add_telegram_user(self, user_id: TelegramId, source: Optional['AbstractUser'] = None async def add_telegram_user(self, user_id: TelegramID, source: Optional['AbstractUser'] = None
) -> None: ) -> None:
puppet = p.Puppet.get(user_id) puppet = p.Puppet.get(user_id)
if source: if source:
@@ -473,7 +473,7 @@ class Portal:
user.register_portal(self) user.register_portal(self)
await self.invite_to_matrix(user.mxid) await self.invite_to_matrix(user.mxid)
async def delete_telegram_user(self, user_id: TelegramId, sender: p.Puppet) -> None: async def delete_telegram_user(self, user_id: TelegramID, sender: p.Puppet) -> None:
puppet = p.Puppet.get(user_id) puppet = p.Puppet.get(user_id)
user = u.User.get_by_tgid(user_id) user = u.User.get_by_tgid(user_id)
kick_message = (f"Kicked by {sender.displayname}" kick_message = (f"Kicked by {sender.displayname}"
@@ -733,7 +733,7 @@ class Portal:
return user.client(SetTypingRequest( return user.client(SetTypingRequest(
self.peer, action() if typing else SendMessageCancelAction())) self.peer, action() if typing else SendMessageCancelAction()))
async def mark_read(self, user: 'u.User', event_id: MatrixEventId) -> None: async def mark_read(self, user: 'u.User', event_id: MatrixEventID) -> None:
if user.is_bot: if user.is_bot:
return return
space = self.tgid if self.peer_type == "channel" else user.tgid space = self.tgid if self.peer_type == "channel" else user.tgid
@@ -748,7 +748,7 @@ class Portal:
else: else:
await user.client(ReadMessageHistoryRequest(peer=self.peer, max_id=message.tgid)) await user.client(ReadMessageHistoryRequest(peer=self.peer, max_id=message.tgid))
async def leave_matrix(self, user: 'u.User', source: 'u.User', event_id: MatrixEventId async def leave_matrix(self, user: 'u.User', source: 'u.User', event_id: MatrixEventID
) -> None: ) -> None:
if await user.needs_relaybot(self): if await user.needs_relaybot(self):
async with self.require_send_lock(self.bot.tgid): async with self.require_send_lock(self.bot.tgid):
@@ -971,7 +971,7 @@ class Portal:
except ChatNotModifiedError: except ChatNotModifiedError:
pass pass
async def handle_matrix_deletion(self, deleter: 'u.User', event_id: MatrixEventId) -> None: async def handle_matrix_deletion(self, deleter: 'u.User', event_id: MatrixEventID) -> None:
real_deleter = deleter if not await deleter.needs_relaybot(self) else self.bot real_deleter = deleter if not await deleter.needs_relaybot(self) else self.bot
space = self.tgid if self.peer_type == "channel" else real_deleter.tgid space = self.tgid if self.peer_type == "channel" else real_deleter.tgid
message = DBMessage.query.filter(DBMessage.mxid == event_id, message = DBMessage.query.filter(DBMessage.mxid == event_id,
@@ -981,7 +981,7 @@ class Portal:
return return
await real_deleter.client.delete_messages(self.peer, [message.tgid]) await real_deleter.client.delete_messages(self.peer, [message.tgid])
async def _update_telegram_power_level(self, sender: 'u.User', user_id: TelegramId, async def _update_telegram_power_level(self, sender: 'u.User', user_id: TelegramID,
level: int) -> None: level: int) -> None:
if self.peer_type == "chat": if self.peer_type == "chat":
await sender.client(EditChatAdminRequest( await sender.client(EditChatAdminRequest(
@@ -999,7 +999,7 @@ class Portal:
user_id=user_id, admin_rights=rights)) user_id=user_id, admin_rights=rights))
async def handle_matrix_power_levels(self, sender: 'u.User', async def handle_matrix_power_levels(self, sender: 'u.User',
new_users: Dict[MatrixUserId, int], new_users: Dict[MatrixUserID, int],
old_users: Dict[str, int]) -> None: old_users: Dict[str, int]) -> None:
# TODO handle all power level changes and bridge exact admin rights to supergroups/channels # TODO handle all power level changes and bridge exact admin rights to supergroups/channels
for user, level in new_users.items(): for user, level in new_users.items():
@@ -1531,7 +1531,7 @@ class Portal:
else: else:
self.log.debug("Unhandled Telegram action in %s: %s", self.title, action) self.log.debug("Unhandled Telegram action in %s: %s", self.title, action)
async def set_telegram_admin(self, user_id: TelegramId) -> None: async def set_telegram_admin(self, user_id: TelegramID) -> None:
puppet = p.Puppet.get(user_id) puppet = p.Puppet.get(user_id)
user = u.User.get_by_tgid(user_id) user = u.User.get_by_tgid(user_id)
@@ -1664,7 +1664,7 @@ class Portal:
mxid=self.mxid, username=self.username, megagroup=self.megagroup, mxid=self.mxid, username=self.username, megagroup=self.megagroup,
title=self.title, about=self.about, photo_id=self.photo_id) title=self.title, about=self.about, photo_id=self.photo_id)
def migrate_and_save(self, new_id: TelegramId) -> None: def migrate_and_save(self, new_id: TelegramID) -> None:
existing = DBPortal.query.get(self.tgid_full) existing = DBPortal.query.get(self.tgid_full)
if existing: if existing:
self.db.delete(existing) self.db.delete(existing)
@@ -1711,7 +1711,7 @@ class Portal:
# region Class instance lookup # region Class instance lookup
@classmethod @classmethod
def get_by_mxid(cls, mxid: MatrixRoomId) -> Optional['Portal']: def get_by_mxid(cls, mxid: MatrixRoomID) -> Optional['Portal']:
try: try:
return cls.by_mxid[mxid] return cls.by_mxid[mxid]
except KeyError: except KeyError:
@@ -1746,7 +1746,7 @@ class Portal:
return None return None
@classmethod @classmethod
def get_by_tgid(cls, tgid: TelegramId, tg_receiver: Optional[TelegramId] = None, def get_by_tgid(cls, tgid: TelegramID, tg_receiver: Optional[TelegramID] = None,
peer_type: str = None) -> Optional['Portal']: peer_type: str = None) -> Optional['Portal']:
tg_receiver = tg_receiver or tgid tg_receiver = tg_receiver or tgid
tgid_full = (tgid, tg_receiver) tgid_full = (tgid, tg_receiver)
@@ -1770,7 +1770,7 @@ class Portal:
@classmethod @classmethod
def get_by_entity(cls, entity: Union[TypeChat, TypePeer, TypeUser, TypeUserFull, def get_by_entity(cls, entity: Union[TypeChat, TypePeer, TypeUser, TypeUserFull,
TypeInputPeer], TypeInputPeer],
receiver_id: Optional[TelegramId] = None, create: bool = True receiver_id: Optional[TelegramID] = None, create: bool = True
) -> Optional['Portal']: ) -> Optional['Portal']:
entity_type = type(entity) entity_type = type(entity)
if entity_type in {Chat, ChatFull}: if entity_type in {Chat, ChatFull}:
+20 -20
View File
@@ -26,7 +26,7 @@ from sqlalchemy import orm
from telethon.tl.types import UserProfilePhoto, User, FileLocation from telethon.tl.types import UserProfilePhoto, User, FileLocation
from mautrix_appservice import AppService, IntentAPI, IntentError, MatrixRequestError from mautrix_appservice import AppService, IntentAPI, IntentError, MatrixRequestError
from .types import MatrixUserId, TelegramId from .types import MatrixUserID, TelegramID
from .db import Puppet as DBPuppet from .db import Puppet as DBPuppet
from . import util from . import util
@@ -52,28 +52,28 @@ class Puppet:
mxid_regex = None # type: Pattern mxid_regex = None # type: Pattern
username_template = None # type: str username_template = None # type: str
hs_domain = None # type: str hs_domain = None # type: str
cache = {} # type: Dict[TelegramId, Puppet] cache = {} # type: Dict[TelegramID, Puppet]
by_custom_mxid = {} # type: Dict[str, Puppet] by_custom_mxid = {} # type: Dict[str, Puppet]
def __init__(self, def __init__(self,
id: TelegramId, id: TelegramID,
access_token: Optional[str] = None, access_token: Optional[str] = None,
custom_mxid: Optional[MatrixUserId] = None, custom_mxid: Optional[MatrixUserID] = None,
username: Optional[str] = None, username: Optional[str] = None,
displayname: Optional[str] = None, displayname: Optional[str] = None,
displayname_source: Optional[TelegramId] = None, displayname_source: Optional[TelegramID] = None,
photo_id: Optional[str] = None, photo_id: Optional[str] = None,
is_bot: bool = False, is_bot: bool = False,
is_registered: bool = False, is_registered: bool = False,
db_instance: Optional[DBPuppet] = None) -> None: db_instance: Optional[DBPuppet] = None) -> None:
self.id = id # type: TelegramId self.id = id # type: TelegramID
self.access_token = access_token # type: Optional[str] self.access_token = access_token # type: Optional[str]
self.custom_mxid = custom_mxid # type: Optional[MatrixUserId] self.custom_mxid = custom_mxid # type: Optional[MatrixUserID]
self.default_mxid = self.get_mxid_from_id(self.id) # type: MatrixUserId self.default_mxid = self.get_mxid_from_id(self.id) # type: MatrixUserID
self.username = username # type: Optional[str] self.username = username # type: Optional[str]
self.displayname = displayname # type: Optional[str] self.displayname = displayname # type: Optional[str]
self.displayname_source = displayname_source # type: Optional[TelegramId] self.displayname_source = displayname_source # type: Optional[TelegramID]
self.photo_id = photo_id # type: Optional[str] self.photo_id = photo_id # type: Optional[str]
self.is_bot = is_bot # type: bool self.is_bot = is_bot # type: bool
self.is_registered = is_registered # type: bool self.is_registered = is_registered # type: bool
@@ -91,7 +91,7 @@ class Puppet:
return self.custom_mxid or self.default_mxid return self.custom_mxid or self.default_mxid
@property @property
def tgid(self) -> TelegramId: def tgid(self) -> TelegramID:
return self.id return self.id
@property @property
@@ -109,7 +109,7 @@ class Puppet:
return (self.az.intent.user(self.custom_mxid, self.access_token) return (self.az.intent.user(self.custom_mxid, self.access_token)
if self.is_real_user else self.default_mxid_intent) if self.is_real_user else self.default_mxid_intent)
async def switch_mxid(self, access_token: str, mxid: MatrixUserId) -> PuppetError: async def switch_mxid(self, access_token: str, mxid: MatrixUserID) -> PuppetError:
prev_mxid = self.custom_mxid prev_mxid = self.custom_mxid
self.custom_mxid = mxid self.custom_mxid = mxid
self.access_token = access_token self.access_token = access_token
@@ -355,10 +355,10 @@ class Puppet:
if displayname != self.displayname: if displayname != self.displayname:
await self.default_mxid_intent.set_display_name(displayname) await self.default_mxid_intent.set_display_name(displayname)
self.displayname = displayname self.displayname = displayname
self.displayname_source = TelegramId(source.tgid) self.displayname_source = TelegramID(source.tgid)
return True return True
elif source.is_relaybot or self.displayname_source is None: elif source.is_relaybot or self.displayname_source is None:
self.displayname_source = TelegramId(source.tgid) self.displayname_source = TelegramID(source.tgid)
return True return True
else: else:
return False return False
@@ -378,7 +378,7 @@ class Puppet:
# region Getters # region Getters
@classmethod @classmethod
def get(cls, tgid: TelegramId, create: bool = True) -> Optional['Puppet']: def get(cls, tgid: TelegramID, create: bool = True) -> Optional['Puppet']:
try: try:
return cls.cache[tgid] return cls.cache[tgid]
except KeyError: except KeyError:
@@ -397,7 +397,7 @@ class Puppet:
return None return None
@classmethod @classmethod
def get_by_mxid(cls, mxid: MatrixUserId, create: bool = True) -> Optional['Puppet']: def get_by_mxid(cls, mxid: MatrixUserID, create: bool = True) -> Optional['Puppet']:
tgid = cls.get_id_from_mxid(mxid) tgid = cls.get_id_from_mxid(mxid)
if tgid: if tgid:
return cls.get(tgid, create) return cls.get(tgid, create)
@@ -405,7 +405,7 @@ class Puppet:
return None return None
@classmethod @classmethod
def get_by_custom_mxid(cls, mxid: MatrixUserId) -> Optional['Puppet']: def get_by_custom_mxid(cls, mxid: MatrixUserID) -> Optional['Puppet']:
if not mxid: if not mxid:
raise ValueError("Matrix ID can't be empty") raise ValueError("Matrix ID can't be empty")
@@ -429,15 +429,15 @@ class Puppet:
for puppet in DBPuppet.query.filter(DBPuppet.custom_mxid is not None).all()] for puppet in DBPuppet.query.filter(DBPuppet.custom_mxid is not None).all()]
@classmethod @classmethod
def get_id_from_mxid(cls, mxid: MatrixUserId) -> Optional[TelegramId]: def get_id_from_mxid(cls, mxid: MatrixUserID) -> Optional[TelegramID]:
match = cls.mxid_regex.match(mxid) match = cls.mxid_regex.match(mxid)
if match: if match:
return TelegramId(int(match.group(1))) return TelegramID(int(match.group(1)))
return None return None
@classmethod @classmethod
def get_mxid_from_id(cls, tgid: TelegramId) -> MatrixUserId: def get_mxid_from_id(cls, tgid: TelegramID) -> MatrixUserID:
return MatrixUserId(f"@{cls.username_template.format(userid=tgid)}:{cls.hs_domain}") return MatrixUserID(f"@{cls.username_template.format(userid=tgid)}:{cls.hs_domain}")
@classmethod @classmethod
def find_by_username(cls, username: str) -> Optional['Puppet']: def find_by_username(cls, username: str) -> Optional['Puppet']:
+12 -12
View File
@@ -20,7 +20,7 @@ from sqlalchemy import orm
from mautrix_appservice import StateStore from mautrix_appservice import StateStore
from .types import MatrixUserId, MatrixRoomId from .types import MatrixUserID, MatrixRoomID
from . import puppet as pu from . import puppet as pu
from .db import RoomState, UserProfile from .db import RoomState, UserProfile
@@ -33,12 +33,12 @@ class SQLStateStore(StateStore):
self.room_state_cache = {} # type: Dict[str, RoomState] self.room_state_cache = {} # type: Dict[str, RoomState]
@staticmethod @staticmethod
def is_registered(user: MatrixUserId) -> bool: def is_registered(user: MatrixUserID) -> bool:
puppet = pu.Puppet.get_by_mxid(user) puppet = pu.Puppet.get_by_mxid(user)
return puppet.is_registered if puppet else False return puppet.is_registered if puppet else False
@staticmethod @staticmethod
def registered(user: MatrixUserId) -> None: def registered(user: MatrixUserID) -> None:
puppet = pu.Puppet.get_by_mxid(user) puppet = pu.Puppet.get_by_mxid(user)
if puppet: if puppet:
puppet.is_registered = True puppet.is_registered = True
@@ -51,7 +51,7 @@ class SQLStateStore(StateStore):
elif event_type == "m.room.member": elif event_type == "m.room.member":
self.set_member(event["room_id"], event["state_key"], event["content"]) self.set_member(event["room_id"], event["state_key"], event["content"])
def _get_user_profile(self, room_id: MatrixRoomId, user_id: MatrixUserId, create: bool = True def _get_user_profile(self, room_id: MatrixRoomID, user_id: MatrixUserID, create: bool = True
) -> UserProfile: ) -> UserProfile:
key = (room_id, user_id) key = (room_id, user_id)
try: try:
@@ -69,22 +69,22 @@ class SQLStateStore(StateStore):
self.profile_cache[key] = profile self.profile_cache[key] = profile
return profile return profile
def get_member(self, room: MatrixRoomId, user: MatrixUserId) -> Dict: def get_member(self, room: MatrixRoomID, user: MatrixUserID) -> Dict:
return self._get_user_profile(room, user).dict() return self._get_user_profile(room, user).dict()
def set_member(self, room: MatrixRoomId, user: MatrixUserId, member: Dict) -> None: def set_member(self, room: MatrixRoomID, user: MatrixUserID, member: Dict) -> None:
profile = self._get_user_profile(room, user) profile = self._get_user_profile(room, user)
profile.membership = member.get("membership", profile.membership or "leave") profile.membership = member.get("membership", profile.membership or "leave")
profile.displayname = member.get("displayname", profile.displayname) profile.displayname = member.get("displayname", profile.displayname)
profile.avatar_url = member.get("avatar_url", profile.avatar_url) profile.avatar_url = member.get("avatar_url", profile.avatar_url)
self.db.commit() self.db.commit()
def set_membership(self, room: MatrixRoomId, user: MatrixUserId, membership: str) -> None: def set_membership(self, room: MatrixRoomID, user: MatrixUserID, membership: str) -> None:
self.set_member(room, user, { self.set_member(room, user, {
"membership": membership, "membership": membership,
}) })
def _get_room_state(self, room_id: MatrixRoomId, create: bool = True) -> RoomState: def _get_room_state(self, room_id: MatrixRoomID, create: bool = True) -> RoomState:
try: try:
return self.room_state_cache[room_id] return self.room_state_cache[room_id]
except KeyError: except KeyError:
@@ -98,13 +98,13 @@ class SQLStateStore(StateStore):
self.room_state_cache[room_id] = room self.room_state_cache[room_id] = room
return room return room
def has_power_levels(self, room: MatrixRoomId) -> bool: def has_power_levels(self, room: MatrixRoomID) -> bool:
return self._get_room_state(room).has_power_levels return self._get_room_state(room).has_power_levels
def get_power_levels(self, room: MatrixRoomId) -> Dict: def get_power_levels(self, room: MatrixRoomID) -> Dict:
return self._get_room_state(room).power_levels return self._get_room_state(room).power_levels
def set_power_level(self, room: MatrixRoomId, user: MatrixUserId, level: int) -> None: def set_power_level(self, room: MatrixRoomID, user: MatrixUserID, level: int) -> None:
room_state = self._get_room_state(room) room_state = self._get_room_state(room)
power_levels = room_state.power_levels power_levels = room_state.power_levels
if not power_levels: if not power_levels:
@@ -116,7 +116,7 @@ class SQLStateStore(StateStore):
room_state.power_levels = power_levels room_state.power_levels = power_levels
self.db.commit() self.db.commit()
def set_power_levels(self, room: MatrixRoomId, content: Dict) -> None: def set_power_levels(self, room: MatrixRoomID, content: Dict) -> None:
state = self._get_room_state(room) state = self._get_room_state(room)
state.power_levels = content state.power_levels = content
self.db.commit() self.db.commit()
+4 -4
View File
@@ -1,10 +1,10 @@
from typing import Dict, NewType from typing import Dict, NewType
# MatrixId = NewType('MatrixId', str) # MatrixId = NewType('MatrixId', str)
MatrixUserId = NewType('MatrixUserId', str) MatrixUserID = NewType('MatrixUserID', str)
MatrixRoomId = NewType('MatrixRoomId', str) MatrixRoomID = NewType('MatrixRoomID', str)
MatrixEventId = NewType('MatrixEventId', str) MatrixEventID = NewType('MatrixEventID', str)
MatrixEvent = NewType('MatrixEvent', Dict) MatrixEvent = NewType('MatrixEvent', Dict)
TelegramId = NewType('TelegramId', int) TelegramID = NewType('TelegramID', int)
+5 -5
View File
@@ -28,7 +28,7 @@ from telethon.tl.functions.contacts import GetContactsRequest, SearchRequest
from telethon.tl.functions.account import UpdateStatusRequest from telethon.tl.functions.account import UpdateStatusRequest
from mautrix_appservice import MatrixRequestError from mautrix_appservice import MatrixRequestError
from .types import MatrixUserId, TelegramId from .types import MatrixUserID, TelegramID
from .db import User as DBUser, Contact as DBContact, Portal as DBPortal from .db import User as DBUser, Contact as DBContact, Portal as DBPortal
from .abstract_user import AbstractUser from .abstract_user import AbstractUser
from . import portal as po, puppet as pu from . import portal as po, puppet as pu
@@ -47,13 +47,13 @@ class User(AbstractUser):
by_mxid = {} # type: Dict[str, User] by_mxid = {} # type: Dict[str, User]
by_tgid = {} # type: Dict[int, User] by_tgid = {} # type: Dict[int, User]
def __init__(self, mxid: MatrixUserId, tgid: Optional[TelegramId] = None, def __init__(self, mxid: MatrixUserID, tgid: Optional[TelegramID] = None,
username: Optional[str] = None, db_contacts: Optional[List[DBContact]] = None, username: Optional[str] = None, db_contacts: Optional[List[DBContact]] = None,
saved_contacts: int = 0, is_bot: bool = False, db_portals: List[DBPortal] = [], saved_contacts: int = 0, is_bot: bool = False, db_portals: List[DBPortal] = [],
db_instance: Optional[DBUser] = None) -> None: db_instance: Optional[DBUser] = None) -> None:
super().__init__() super().__init__()
self.mxid = mxid # type: MatrixUserId self.mxid = mxid # type: MatrixUserID
self.tgid = tgid # type: TelegramId self.tgid = tgid # type: TelegramID
self.is_bot = is_bot # type: bool self.is_bot = is_bot # type: bool
self.username = username # type: str self.username = username # type: str
self.contacts = [] # type: List[pu.Puppet] self.contacts = [] # type: List[pu.Puppet]
@@ -332,7 +332,7 @@ class User(AbstractUser):
# region Class instance lookup # region Class instance lookup
@classmethod @classmethod
def get_by_mxid(cls, mxid: MatrixUserId, create: bool = True) -> Optional['User']: def get_by_mxid(cls, mxid: MatrixUserID, create: bool = True) -> Optional['User']:
if not mxid: if not mxid:
raise ValueError("Matrix ID can't be empty") raise ValueError("Matrix ID can't be empty")
@@ -24,7 +24,7 @@ from telethon.utils import get_peer_id, resolve_id
from telethon.tl.types import ChatForbidden, ChannelForbidden, TypeChat from telethon.tl.types import ChatForbidden, ChannelForbidden, TypeChat
from mautrix_appservice import AppService, MatrixRequestError, IntentError from mautrix_appservice import AppService, MatrixRequestError, IntentError
from ...types import MatrixUserId from ...types import MatrixUserID, TelegramID
from ...user import User from ...user import User
from ...portal import Portal from ...portal import Portal
from ...commands.portal import user_has_power_level, get_initial_state from ...commands.portal import user_has_power_level, get_initial_state
@@ -119,10 +119,10 @@ class ProvisioningAPI(AuthAPI):
chat_id = request.match_info["chat_id"] chat_id = request.match_info["chat_id"]
if chat_id.startswith("-100"): if chat_id.startswith("-100"):
tgid = int(chat_id[4:]) tgid = TelegramID(int(chat_id[4:]))
peer_type = "channel" peer_type = "channel"
elif chat_id.startswith("-"): elif chat_id.startswith("-"):
tgid = -int(chat_id) tgid = TelegramID(-int(chat_id))
peer_type = "chat" peer_type = "chat"
else: else:
return self.get_error_response(400, "tgid_invalid", "Invalid Telegram chat ID.") return self.get_error_response(400, "tgid_invalid", "Invalid Telegram chat ID.")
@@ -154,14 +154,14 @@ class ProvisioningAPI(AuthAPI):
"Matrix room.") "Matrix room.")
is_logged_in = user is not None and await user.is_logged_in() is_logged_in = user is not None and await user.is_logged_in()
user = user if is_logged_in else self.context.bot acting_user = user if is_logged_in else self.context.bot
if not user: if not acting_user:
return self.get_login_response(status=403, errcode="not_logged_in", return self.get_login_response(status=403, errcode="not_logged_in",
error="You are not logged in and there is no relay bot.") error="You are not logged in and there is no relay bot.")
entity = None # type: Optional[TypeChat] entity = None # type: Optional[TypeChat]
try: try:
entity = await user.client.get_entity(portal.peer) entity = await acting_user.client.get_entity(portal.peer)
except Exception: except Exception:
self.log.exception("Failed to get_entity(%s) for manual bridging.", portal.peer) self.log.exception("Failed to get_entity(%s) for manual bridging.", portal.peer)
@@ -412,7 +412,7 @@ class ProvisioningAPI(AuthAPI):
except json.JSONDecodeError: except json.JSONDecodeError:
return None return None
async def get_user(self, mxid: MatrixUserId, expect_logged_in: Optional[bool] = False, async def get_user(self, mxid: MatrixUserID, expect_logged_in: Optional[bool] = False,
require_puppeting: bool = True, require_user: bool = True require_puppeting: bool = True, require_user: bool = True
) -> Tuple[Optional[User], Optional[web.Response]]: ) -> Tuple[Optional[User], Optional[web.Response]]:
if not mxid: if not mxid: