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
if TYPE_CHECKING:
from .types import TelegramId
from .types import TelegramID
from .context import Context
from .config import Config
from .bot import Bot
@@ -68,7 +68,7 @@ class AbstractUser(ABC):
self.whitelisted = False # type: bool
self.relaybot_whitelisted = False # type: bool
self.client = None # type: MautrixTelegramClient
self.tgid = None # type: TelegramId
self.tgid = None # type: TelegramID
self.mxid = None # type: str
self.is_relaybot = 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.errors import ChannelInvalidError, ChannelPrivateError
from .types import MatrixUserId
from .types import MatrixUserID
from .abstract_user import AbstractUser
from .db import BotChat
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.")
async def handle_command_invite(self, portal: po.Portal, reply: ReplyFunc,
mxid_input: MatrixUserId) -> Message:
mxid_input: MatrixUserID) -> Message:
if len(mxid_input) == 0:
return await reply("Usage: `/invite <mxid>`")
elif not portal.mxid:
@@ -180,7 +180,7 @@ class Bot(AbstractUser):
"Create one with /portal first.")
if not self.mxid_regex.match(mxid_input):
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:
return await reply("That user is not whitelisted to use the bridge.")
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 ..types import MatrixRoomId, MatrixUserId
from ..types import MatrixRoomID, MatrixUserID
from . import command_handler, CommandEvent, SECTION_ADMIN
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"]]:
management_rooms = [] # type: List[ManagementRoom]
unidentified_rooms = [] # type: List[MatrixRoomId]
unidentified_rooms = [] # type: List[MatrixRoomID]
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],
unidentified_rooms: List[MatrixRoomId], portals: List["po.Portal"],
unidentified_rooms: List[MatrixRoomID], portals: List["po.Portal"],
empty_portals: List["po.Portal"]) -> None:
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":
rooms_to_clean += empty_portals
rooms_to_clean += unidentified_rooms
@@ -159,7 +159,7 @@ async def set_rooms_to_clean(evt, management_rooms: List[ManagementRoom],
"`$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":
await evt.reply(f"Cleaning {len(rooms_to_clean)} rooms. "
"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):
await room.cleanup_and_delete()
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")
cleaned += 1
evt.sender.command_status = None
+3 -3
View File
@@ -21,7 +21,7 @@ import logging
from telethon.errors import FloodWaitError
from ..types import MatrixRoomId
from ..types import MatrixRoomID
from ..util import format_duration
from .. import user as u, context as c
@@ -38,7 +38,7 @@ SECTION_ADMIN = HelpSection("Administration", 50, "")
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:
self.az = processor.az
self.log = processor.log
@@ -154,7 +154,7 @@ class CommandProcessor:
self.public_website = context.public_website
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]:
evt = CommandEvent(self, room, sender, command, args, is_management, is_portal)
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 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 (command_handler, CommandEvent,
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,
action: Optional[str] = None
) -> 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)
if not portal:
@@ -168,7 +168,7 @@ async def bridge(evt: CommandEvent) -> Dict:
if len(evt.args) == 0:
return await evt.reply("**Usage:** "
"`$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"
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
tgid_str = evt.args[0]
if tgid_str.startswith("-100"):
tgid = TelegramId(int(tgid_str[4:]))
tgid = TelegramID(int(tgid_str[4:]))
peer_type = "channel"
elif tgid_str.startswith("-"):
tgid = TelegramId(-int(tgid_str))
tgid = TelegramID(-int(tgid_str))
peer_type = "chat"
else:
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.intent_api import IntentAPI
from ..types import TelegramId
from ..types import TelegramID
from .. import user as u, puppet as pu, portal as po
from ..db import Message as DBMessage
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
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)
if user:
mxid = user.mxid
+28 -28
View File
@@ -21,7 +21,7 @@ import re
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
if TYPE_CHECKING:
@@ -38,7 +38,7 @@ class MatrixHandler:
def __init__(self, context: 'Context') -> None:
self.az, self.db, self.config, _, self.tgbot = context.core
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)
@@ -58,7 +58,7 @@ class MatrixHandler:
except asyncio.TimeoutError:
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:
intent = puppet.default_mxid_intent
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 "
"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
while tries < 5:
try:
@@ -136,8 +136,8 @@ class MatrixHandler:
"<code>bridge.permissions</code> section in your config file.")
await self.az.intent.leave_room(room_id)
async def handle_invite(self, room_id: MatrixRoomId, user_id: MatrixUserId,
inviter_mxid: MatrixUserId) -> None:
async def handle_invite(self, room_id: MatrixRoomID, user_id: MatrixUserID,
inviter_mxid: MatrixUserID) -> None:
self.log.debug(f"{inviter_mxid} invited {user_id} to {room_id}")
inviter = u.User.get_by_mxid(inviter_mxid)
if inviter is None:
@@ -164,8 +164,8 @@ class MatrixHandler:
# The rest can probably be ignored
async def handle_join(self, room_id: MatrixRoomId, user_id: MatrixUserId,
event_id: MatrixEventId) -> None:
async def handle_join(self, room_id: MatrixRoomID, user_id: MatrixUserID,
event_id: MatrixEventID) -> None:
user = await u.User.get_by_mxid(user_id).ensure_started()
portal = po.Portal.get_by_mxid(room_id)
@@ -186,8 +186,8 @@ class MatrixHandler:
if await user.is_logged_in() or portal.has_bot:
await portal.join_matrix(user, event_id)
async def handle_part(self, room_id: MatrixRoomId, user_id: MatrixUserId,
sender_mxid: MatrixUserId, event_id: MatrixEventId) -> None:
async def handle_part(self, room_id: MatrixRoomID, user_id: MatrixUserID,
sender_mxid: MatrixUserID, event_id: MatrixEventID) -> None:
self.log.debug(f"{user_id} left {room_id}")
sender = u.User.get_by_mxid(sender_mxid, create=False)
@@ -219,8 +219,8 @@ class MatrixHandler:
text = text[len(prefix) + 1:]
return is_command, text
async def handle_message(self, room: MatrixRoomId, sender_id: MatrixUserId, message: Dict,
event_id: MatrixEventId) -> None:
async def handle_message(self, room: MatrixRoomID, sender_id: MatrixUserID, message: Dict,
event_id: MatrixEventID) -> None:
is_command, text = self.is_command(message)
sender = await u.User.get_by_mxid(sender_id).ensure_started()
if not sender.relaybot_whitelisted:
@@ -255,8 +255,8 @@ class MatrixHandler:
is_portal=portal is not None)
@staticmethod
async def handle_redaction(room_id: MatrixRoomId, sender_mxid: MatrixUserId,
event_id: MatrixEventId) -> None:
async def handle_redaction(room_id: MatrixRoomID, sender_mxid: MatrixUserID,
event_id: MatrixEventID) -> None:
sender = await u.User.get_by_mxid(sender_mxid).ensure_started()
if not sender.relaybot_whitelisted:
return
@@ -268,7 +268,7 @@ class MatrixHandler:
await portal.handle_matrix_deletion(sender, event_id)
@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:
portal = po.Portal.get_by_mxid(room_id)
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"])
@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:
portal = po.Portal.get_by_mxid(room_id)
sender = await u.User.get_by_mxid(sender_mxid).ensure_started()
@@ -291,7 +291,7 @@ class MatrixHandler:
await handler(sender, content[content_key])
@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:
portal = po.Portal.get_by_mxid(room_id)
sender = await u.User.get_by_mxid(sender_mxid).ensure_started()
@@ -305,8 +305,8 @@ class MatrixHandler:
await portal.handle_matrix_pin(sender, None)
@staticmethod
async def handle_name_change(room_id: MatrixRoomId, user_id: MatrixUserId, displayname: str,
prev_displayname: str, event_id: MatrixEventId) -> None:
async def handle_name_change(room_id: MatrixRoomID, user_id: MatrixUserID, displayname: str,
prev_displayname: str, event_id: MatrixEventID) -> None:
portal = po.Portal.get_by_mxid(room_id)
if not portal or not portal.has_bot:
return
@@ -316,14 +316,14 @@ class MatrixHandler:
await portal.name_change_matrix(user, displayname, prev_displayname, event_id)
@staticmethod
def parse_read_receipts(content: Dict) -> Dict[MatrixUserId, MatrixEventId]:
def parse_read_receipts(content: Dict) -> Dict[MatrixUserID, MatrixEventID]:
return {user_id: event_id
for event_id, receipts in content.items()
for user_id in receipts.get("m.read", {})}
@staticmethod
async def handle_read_receipts(room_id: MatrixRoomId,
receipts: Dict[MatrixUserId, MatrixEventId]) -> None:
async def handle_read_receipts(room_id: MatrixRoomID,
receipts: Dict[MatrixUserID, MatrixEventID]) -> None:
portal = po.Portal.get_by_mxid(room_id)
if not portal:
return
@@ -335,13 +335,13 @@ class MatrixHandler:
await portal.mark_read(user, event_id)
@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()
if not await user.is_logged_in():
return
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)
if not portal:
return
@@ -378,12 +378,12 @@ class MatrixHandler:
return
self.log.debug("Received event: %s", evt)
evt_type = evt.get("type", "m.unknown") # type: str
room_id = evt.get("room_id", None) # type: Optional[MatrixRoomId]
event_id = evt.get("event_id", None) # type: Optional[MatrixEventId]
sender = evt.get("sender", None) # type: Optional[MatrixUserId]
room_id = evt.get("room_id", None) # type: Optional[MatrixRoomID]
event_id = evt.get("event_id", None) # type: Optional[MatrixEventID]
sender = evt.get("sender", None) # type: Optional[MatrixUserID]
content = evt.get("content", {}) # type: Dict
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
membership = content.get("membership", "") # 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)
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 .db import Portal as DBPortal, Message as DBMessage, TelegramFile as DBTelegramFile
from . import puppet as p, user as u, formatter, util
@@ -105,13 +105,13 @@ class Portal:
by_mxid = {} # type: Dict[str, Portal]
by_tgid = {} # type: Dict[Tuple[int, int], Portal]
def __init__(self, tgid: TelegramId, peer_type: str, tg_receiver: Optional[int] = None,
mxid: Optional[MatrixRoomId] = None, username: Optional[str] = None,
def __init__(self, tgid: TelegramID, peer_type: str, tg_receiver: Optional[int] = None,
mxid: Optional[MatrixRoomID] = None, username: Optional[str] = None,
megagroup: Optional[bool] = False, title: Optional[str] = None,
about: Optional[str] = None, photo_id: Optional[str] = None,
db_instance: DBPortal = None) -> None:
self.mxid = mxid # type: Optional[MatrixRoomId]
self.tgid = tgid # type: TelegramId
self.mxid = mxid # type: Optional[MatrixRoomID]
self.tgid = tgid # type: TelegramID
self.tg_receiver = tg_receiver or tgid # type: int
self.peer_type = peer_type # type: str
self.username = username # type: str
@@ -304,7 +304,7 @@ class Portal:
return await self._create_matrix_room(user, entity, invites)
async def _create_matrix_room(self, user: 'AbstractUser', entity: TypeChat, invites: InviteList
) -> Optional[MatrixRoomId]:
) -> Optional[MatrixRoomID]:
direct = self.peer_type == "user"
if self.mxid:
@@ -439,7 +439,7 @@ class Portal:
and config["bridge.max_initial_member_sync"] == -1
and (self.megagroup or self.peer_type != "channel"))
if trust_member_list:
joined_mxids = cast(List[MatrixUserId],
joined_mxids = cast(List[MatrixUserID],
await self.main_intent.get_room_members(self.mxid))
for user_mxid in joined_mxids:
if user_mxid == self.az.bot_mxid:
@@ -460,7 +460,7 @@ class Portal:
"You had left this Telegram chat.")
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:
puppet = p.Puppet.get(user_id)
if source:
@@ -473,7 +473,7 @@ class Portal:
user.register_portal(self)
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)
user = u.User.get_by_tgid(user_id)
kick_message = (f"Kicked by {sender.displayname}"
@@ -733,7 +733,7 @@ class Portal:
return user.client(SetTypingRequest(
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:
return
space = self.tgid if self.peer_type == "channel" else user.tgid
@@ -748,7 +748,7 @@ class Portal:
else:
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:
if await user.needs_relaybot(self):
async with self.require_send_lock(self.bot.tgid):
@@ -971,7 +971,7 @@ class Portal:
except ChatNotModifiedError:
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
space = self.tgid if self.peer_type == "channel" else real_deleter.tgid
message = DBMessage.query.filter(DBMessage.mxid == event_id,
@@ -981,7 +981,7 @@ class Portal:
return
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:
if self.peer_type == "chat":
await sender.client(EditChatAdminRequest(
@@ -999,7 +999,7 @@ class Portal:
user_id=user_id, admin_rights=rights))
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:
# TODO handle all power level changes and bridge exact admin rights to supergroups/channels
for user, level in new_users.items():
@@ -1531,7 +1531,7 @@ class Portal:
else:
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)
user = u.User.get_by_tgid(user_id)
@@ -1664,7 +1664,7 @@ class Portal:
mxid=self.mxid, username=self.username, megagroup=self.megagroup,
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)
if existing:
self.db.delete(existing)
@@ -1711,7 +1711,7 @@ class Portal:
# region Class instance lookup
@classmethod
def get_by_mxid(cls, mxid: MatrixRoomId) -> Optional['Portal']:
def get_by_mxid(cls, mxid: MatrixRoomID) -> Optional['Portal']:
try:
return cls.by_mxid[mxid]
except KeyError:
@@ -1746,7 +1746,7 @@ class Portal:
return None
@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']:
tg_receiver = tg_receiver or tgid
tgid_full = (tgid, tg_receiver)
@@ -1770,7 +1770,7 @@ class Portal:
@classmethod
def get_by_entity(cls, entity: Union[TypeChat, TypePeer, TypeUser, TypeUserFull,
TypeInputPeer],
receiver_id: Optional[TelegramId] = None, create: bool = True
receiver_id: Optional[TelegramID] = None, create: bool = True
) -> Optional['Portal']:
entity_type = type(entity)
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 mautrix_appservice import AppService, IntentAPI, IntentError, MatrixRequestError
from .types import MatrixUserId, TelegramId
from .types import MatrixUserID, TelegramID
from .db import Puppet as DBPuppet
from . import util
@@ -52,28 +52,28 @@ class Puppet:
mxid_regex = None # type: Pattern
username_template = 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]
def __init__(self,
id: TelegramId,
id: TelegramID,
access_token: Optional[str] = None,
custom_mxid: Optional[MatrixUserId] = None,
custom_mxid: Optional[MatrixUserID] = None,
username: Optional[str] = None,
displayname: Optional[str] = None,
displayname_source: Optional[TelegramId] = None,
displayname_source: Optional[TelegramID] = None,
photo_id: Optional[str] = None,
is_bot: bool = False,
is_registered: bool = False,
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.custom_mxid = custom_mxid # type: Optional[MatrixUserId]
self.default_mxid = self.get_mxid_from_id(self.id) # type: MatrixUserId
self.custom_mxid = custom_mxid # type: Optional[MatrixUserID]
self.default_mxid = self.get_mxid_from_id(self.id) # type: MatrixUserID
self.username = username # 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.is_bot = is_bot # type: bool
self.is_registered = is_registered # type: bool
@@ -91,7 +91,7 @@ class Puppet:
return self.custom_mxid or self.default_mxid
@property
def tgid(self) -> TelegramId:
def tgid(self) -> TelegramID:
return self.id
@property
@@ -109,7 +109,7 @@ class Puppet:
return (self.az.intent.user(self.custom_mxid, self.access_token)
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
self.custom_mxid = mxid
self.access_token = access_token
@@ -355,10 +355,10 @@ class Puppet:
if displayname != self.displayname:
await self.default_mxid_intent.set_display_name(displayname)
self.displayname = displayname
self.displayname_source = TelegramId(source.tgid)
self.displayname_source = TelegramID(source.tgid)
return True
elif source.is_relaybot or self.displayname_source is None:
self.displayname_source = TelegramId(source.tgid)
self.displayname_source = TelegramID(source.tgid)
return True
else:
return False
@@ -378,7 +378,7 @@ class Puppet:
# region Getters
@classmethod
def get(cls, tgid: TelegramId, create: bool = True) -> Optional['Puppet']:
def get(cls, tgid: TelegramID, create: bool = True) -> Optional['Puppet']:
try:
return cls.cache[tgid]
except KeyError:
@@ -397,7 +397,7 @@ class Puppet:
return None
@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)
if tgid:
return cls.get(tgid, create)
@@ -405,7 +405,7 @@ class Puppet:
return None
@classmethod
def get_by_custom_mxid(cls, mxid: MatrixUserId) -> Optional['Puppet']:
def get_by_custom_mxid(cls, mxid: MatrixUserID) -> Optional['Puppet']:
if not mxid:
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()]
@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)
if match:
return TelegramId(int(match.group(1)))
return TelegramID(int(match.group(1)))
return None
@classmethod
def get_mxid_from_id(cls, tgid: TelegramId) -> MatrixUserId:
return MatrixUserId(f"@{cls.username_template.format(userid=tgid)}:{cls.hs_domain}")
def get_mxid_from_id(cls, tgid: TelegramID) -> MatrixUserID:
return MatrixUserID(f"@{cls.username_template.format(userid=tgid)}:{cls.hs_domain}")
@classmethod
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 .types import MatrixUserId, MatrixRoomId
from .types import MatrixUserID, MatrixRoomID
from . import puppet as pu
from .db import RoomState, UserProfile
@@ -33,12 +33,12 @@ class SQLStateStore(StateStore):
self.room_state_cache = {} # type: Dict[str, RoomState]
@staticmethod
def is_registered(user: MatrixUserId) -> bool:
def is_registered(user: MatrixUserID) -> bool:
puppet = pu.Puppet.get_by_mxid(user)
return puppet.is_registered if puppet else False
@staticmethod
def registered(user: MatrixUserId) -> None:
def registered(user: MatrixUserID) -> None:
puppet = pu.Puppet.get_by_mxid(user)
if puppet:
puppet.is_registered = True
@@ -51,7 +51,7 @@ class SQLStateStore(StateStore):
elif event_type == "m.room.member":
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:
key = (room_id, user_id)
try:
@@ -69,22 +69,22 @@ class SQLStateStore(StateStore):
self.profile_cache[key] = 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()
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.membership = member.get("membership", profile.membership or "leave")
profile.displayname = member.get("displayname", profile.displayname)
profile.avatar_url = member.get("avatar_url", profile.avatar_url)
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, {
"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:
return self.room_state_cache[room_id]
except KeyError:
@@ -98,13 +98,13 @@ class SQLStateStore(StateStore):
self.room_state_cache[room_id] = 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
def get_power_levels(self, room: MatrixRoomId) -> Dict:
def get_power_levels(self, room: MatrixRoomID) -> Dict:
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)
power_levels = room_state.power_levels
if not power_levels:
@@ -116,7 +116,7 @@ class SQLStateStore(StateStore):
room_state.power_levels = power_levels
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.power_levels = content
self.db.commit()
+4 -4
View File
@@ -1,10 +1,10 @@
from typing import Dict, NewType
# MatrixId = NewType('MatrixId', str)
MatrixUserId = NewType('MatrixUserId', str)
MatrixRoomId = NewType('MatrixRoomId', str)
MatrixEventId = NewType('MatrixEventId', str)
MatrixUserID = NewType('MatrixUserID', str)
MatrixRoomID = NewType('MatrixRoomID', str)
MatrixEventID = NewType('MatrixEventID', str)
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 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 .abstract_user import AbstractUser
from . import portal as po, puppet as pu
@@ -47,13 +47,13 @@ class User(AbstractUser):
by_mxid = {} # type: Dict[str, 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,
saved_contacts: int = 0, is_bot: bool = False, db_portals: List[DBPortal] = [],
db_instance: Optional[DBUser] = None) -> None:
super().__init__()
self.mxid = mxid # type: MatrixUserId
self.tgid = tgid # type: TelegramId
self.mxid = mxid # type: MatrixUserID
self.tgid = tgid # type: TelegramID
self.is_bot = is_bot # type: bool
self.username = username # type: str
self.contacts = [] # type: List[pu.Puppet]
@@ -332,7 +332,7 @@ class User(AbstractUser):
# region Class instance lookup
@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:
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 mautrix_appservice import AppService, MatrixRequestError, IntentError
from ...types import MatrixUserId
from ...types import MatrixUserID, TelegramID
from ...user import User
from ...portal import Portal
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"]
if chat_id.startswith("-100"):
tgid = int(chat_id[4:])
tgid = TelegramID(int(chat_id[4:]))
peer_type = "channel"
elif chat_id.startswith("-"):
tgid = -int(chat_id)
tgid = TelegramID(-int(chat_id))
peer_type = "chat"
else:
return self.get_error_response(400, "tgid_invalid", "Invalid Telegram chat ID.")
@@ -154,14 +154,14 @@ class ProvisioningAPI(AuthAPI):
"Matrix room.")
is_logged_in = user is not None and await user.is_logged_in()
user = user if is_logged_in else self.context.bot
if not user:
acting_user = user if is_logged_in else self.context.bot
if not acting_user:
return self.get_login_response(status=403, errcode="not_logged_in",
error="You are not logged in and there is no relay bot.")
entity = None # type: Optional[TypeChat]
try:
entity = await user.client.get_entity(portal.peer)
entity = await acting_user.client.get_entity(portal.peer)
except Exception:
self.log.exception("Failed to get_entity(%s) for manual bridging.", portal.peer)
@@ -412,7 +412,7 @@ class ProvisioningAPI(AuthAPI):
except json.JSONDecodeError:
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
) -> Tuple[Optional[User], Optional[web.Response]]:
if not mxid: