Просмотр исходного кода

Move more command handling stuff to mautrix-python

Tulir Asokan 4 лет назад
Родитель
Сommit
184bdf10cc

+ 2 - 2
mautrix_signal/commands/__init__.py

@@ -1,2 +1,2 @@
-from .handler import (CommandProcessor, command_handler, CommandEvent, CommandHandler, SECTION_AUTH, SECTION_CONNECTION)
-from . import auth, conn
+from .auth import SECTION_AUTH
+from .conn import SECTION_CONNECTION

+ 4 - 1
mautrix_signal/commands/auth.py

@@ -20,9 +20,10 @@ from mausignald.types import Account
 from mautrix.client import Client
 from mautrix.bridge import custom_puppet as cpu
 from mautrix.types import MediaMessageEventContent, MessageType, ImageInfo
+from mautrix.bridge.commands import HelpSection, command_handler
 
-from . import command_handler, CommandEvent, SECTION_AUTH
 from .. import puppet as pu
+from .typehint import CommandEvent
 
 try:
     import qrcode
@@ -30,6 +31,8 @@ try:
 except ImportError:
     qrcode = None
 
+SECTION_AUTH = HelpSection("Authentication", 10, "")
+
 
 @command_handler(needs_auth=False, management_only=True, help_section=SECTION_AUTH,
                  help_text="Link the bridge as a secondary device", help_args="[device name]")

+ 4 - 2
mautrix_signal/commands/conn.py

@@ -13,7 +13,10 @@
 #
 # You should have received a copy of the GNU Affero General Public License
 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
-from . import command_handler, CommandEvent, SECTION_CONNECTION
+from mautrix.bridge.commands import HelpSection, command_handler
+from .typehint import CommandEvent
+
+SECTION_CONNECTION = HelpSection("Connection management", 15, "")
 
 
 @command_handler(needs_auth=False, management_only=True, help_section=SECTION_CONNECTION,
@@ -23,7 +26,6 @@ async def set_notice_room(evt: CommandEvent) -> None:
     await evt.sender.update()
     await evt.reply("This room has been marked as your bridge notice room")
 
-
 # @command_handler(needs_auth=False, management_only=True, help_section=SECTION_CONNECTION,
 #                  help_text="Check if you're logged into Twitter")
 # async def ping(evt: CommandEvent) -> None:

+ 0 - 98
mautrix_signal/commands/handler.py

@@ -1,98 +0,0 @@
-# mautrix-signal - A Matrix-Signal puppeting bridge
-# Copyright (C) 2020 Tulir Asokan
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU Affero General Public License for more details.
-#
-# You should have received a copy of the GNU Affero General Public License
-# along with this program.  If not, see <https://www.gnu.org/licenses/>.
-from typing import Awaitable, Callable, List, Optional, NamedTuple, TYPE_CHECKING
-
-from mautrix.types import RoomID, EventID, MessageEventContent
-from mautrix.bridge.commands import (HelpSection, CommandEvent as BaseCommandEvent,
-                                     CommandHandler as BaseCommandHandler,
-                                     CommandProcessor as BaseCommandProcessor,
-                                     CommandHandlerFunc, command_handler as base_command_handler)
-
-from .. import user as u
-
-if TYPE_CHECKING:
-    from ..__main__ import SignalBridge
-
-HelpCacheKey = NamedTuple('HelpCacheKey', is_management=bool, is_portal=bool, is_admin=bool,
-                          is_logged_in=bool)
-SECTION_AUTH = HelpSection("Authentication", 10, "")
-SECTION_CONNECTION = HelpSection("Connection management", 15, "")
-
-
-class CommandEvent(BaseCommandEvent):
-    sender: u.User
-    bridge: 'SignalBridge'
-
-    def __init__(self, processor: 'CommandProcessor', room_id: RoomID, event_id: EventID,
-                 sender: u.User, command: str, args: List[str], content: MessageEventContent,
-                 is_management: bool, is_portal: bool) -> None:
-        super().__init__(processor, room_id, event_id, sender, command, args, content,
-                         is_management, is_portal)
-        self.bridge = processor.bridge
-        self.config = processor.config
-
-    @property
-    def print_error_traceback(self) -> bool:
-        return self.sender.is_admin
-
-    async def get_help_key(self) -> HelpCacheKey:
-        return HelpCacheKey(self.is_management, self.is_portal, self.sender.is_admin,
-                            await self.sender.is_logged_in())
-
-
-class CommandHandler(BaseCommandHandler):
-    name: str
-
-    management_only: bool
-    needs_auth: bool
-    needs_admin: bool
-
-    def __init__(self, handler: Callable[[CommandEvent], Awaitable[EventID]],
-                 management_only: bool, name: str, help_text: str, help_args: str,
-                 help_section: HelpSection, needs_auth: bool, needs_admin: bool) -> None:
-        super().__init__(handler, management_only, name, help_text, help_args, help_section,
-                         needs_auth=needs_auth, needs_admin=needs_admin)
-
-    async def get_permission_error(self, evt: CommandEvent) -> Optional[str]:
-        if self.management_only and not evt.is_management:
-            return (f"`{evt.command}` is a restricted command: "
-                    "you may only run it in management rooms.")
-        elif self.needs_admin and not evt.sender.is_admin:
-            return "This command requires administrator privileges."
-        elif self.needs_auth and not await evt.sender.is_logged_in():
-            return "This command requires you to be logged in."
-        return None
-
-    def has_permission(self, key: HelpCacheKey) -> bool:
-        return ((not self.management_only or key.is_management) and
-                (not self.needs_admin or key.is_admin) and
-                (not self.needs_auth or key.is_logged_in))
-
-
-def command_handler(_func: Optional[CommandHandlerFunc] = None, *, needs_auth: bool = True,
-                    needs_admin: bool = False, management_only: bool = False,
-                    name: Optional[str] = None, help_text: str = "", help_args: str = "",
-                    help_section: HelpSection = None) -> Callable[[CommandHandlerFunc],
-                                                                  CommandHandler]:
-    return base_command_handler(_func, _handler_class=CommandHandler, name=name,
-                                help_text=help_text, help_args=help_args,
-                                help_section=help_section, management_only=management_only,
-                                needs_auth=needs_auth, needs_admin=needs_admin)
-
-
-class CommandProcessor(BaseCommandProcessor):
-    def __init__(self, bridge: 'SignalBridge') -> None:
-        super().__init__(bridge=bridge, event_class=CommandEvent)

+ 12 - 0
mautrix_signal/commands/typehint.py

@@ -0,0 +1,12 @@
+from typing import TYPE_CHECKING
+
+from mautrix.bridge.commands import CommandEvent as BaseCommandEvent
+
+if TYPE_CHECKING:
+    from ..__main__ import SignalBridge
+    from ..user import User
+
+
+class CommandEvent(BaseCommandEvent):
+    bridge: 'SignalBridge'
+    sender: 'User'

+ 3 - 20
mautrix_signal/matrix.py

@@ -23,14 +23,13 @@ from mautrix.types import (Event, ReactionEvent, MessageEvent, StateEvent, Encry
                            ReceiptEvent, TypingEvent, PresenceEvent, RedactionEvent)
 
 from .db import Message as DBMessage
-from . import commands as com, puppet as pu, portal as po, user as u, signal as s
+from . import puppet as pu, portal as po, user as u, signal as s
 
 if TYPE_CHECKING:
     from .__main__ import SignalBridge
 
 
 class MatrixHandler(BaseMatrixHandler):
-    commands: 'com.CommandProcessor'
     signal: 's.SignalHandler'
 
     def __init__(self, bridge: 'SignalBridge') -> None:
@@ -40,7 +39,7 @@ class MatrixHandler(BaseMatrixHandler):
         self.user_id_suffix = f"{suffix}:{homeserver}"
         self.signal = bridge.signal
 
-        super().__init__(command_processor=com.CommandProcessor(bridge), bridge=bridge)
+        super().__init__(bridge=bridge)
 
     def filter_matrix_event(self, evt: Event) -> bool:
         if not isinstance(evt, (ReactionEvent, MessageEvent, StateEvent, EncryptedEvent,
@@ -68,19 +67,6 @@ class MatrixHandler(BaseMatrixHandler):
 
         await portal.handle_matrix_leave(user)
 
-    # @staticmethod
-    # async def handle_redaction(room_id: RoomID, user_id: UserID, event_id: EventID,
-    #                            redaction_event_id: EventID) -> None:
-    #     user = await u.User.get_by_mxid(user_id)
-    #     if not user:
-    #         return
-    #
-    #     portal = await po.Portal.get_by_mxid(room_id)
-    #     if not portal:
-    #         return
-    #
-    #     await portal.handle_matrix_redaction(user, event_id, redaction_event_id)
-
     @classmethod
     async def handle_reaction(cls, room_id: RoomID, user_id: UserID, event_id: EventID,
                               content: ReactionEventContent) -> None:
@@ -134,10 +120,7 @@ class MatrixHandler(BaseMatrixHandler):
         #     # TODO
 
     async def handle_event(self, evt: Event) -> None:
-        if evt.type == EventType.ROOM_REDACTION:
-            evt: RedactionEvent
-            # await self.handle_redaction(evt.room_id, evt.sender, evt.redacts, evt.event_id)
-        elif evt.type == EventType.REACTION:
+        if evt.type == EventType.REACTION:
             evt: ReactionEvent
             await self.handle_reaction(evt.room_id, evt.sender, evt.event_id, evt.content)
 

+ 1 - 1
requirements.txt

@@ -4,5 +4,5 @@ commonmark>=0.8,<0.10
 aiohttp>=3,<4
 yarl>=1,<2
 attrs>=19.1
-mautrix>=0.7.11,<0.8
+mautrix==0.8.0b1
 asyncpg>=0.20,<0.22