matrix.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. # mautrix-signal - A Matrix-Signal puppeting bridge
  2. # Copyright (C) 2020 Tulir Asokan
  3. #
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. from typing import List, Union, TYPE_CHECKING
  17. from mautrix.bridge import BaseMatrixHandler
  18. from mautrix.types import (Event, ReactionEvent, MessageEvent, StateEvent, EncryptedEvent, RoomID,
  19. EventID, UserID, ReactionEventContent, RelationType, EventType,
  20. ReceiptEvent, TypingEvent, PresenceEvent, RedactionEvent)
  21. from .db import Message as DBMessage
  22. from . import commands as com, puppet as pu, portal as po, user as u
  23. if TYPE_CHECKING:
  24. from .__main__ import SignalBridge
  25. class MatrixHandler(BaseMatrixHandler):
  26. commands: 'com.CommandProcessor'
  27. def __init__(self, bridge: 'SignalBridge') -> None:
  28. prefix, suffix = bridge.config["bridge.username_template"].format(userid=":").split(":")
  29. homeserver = bridge.config["homeserver.domain"]
  30. self.user_id_prefix = f"@{prefix}"
  31. self.user_id_suffix = f"{suffix}:{homeserver}"
  32. super().__init__(command_processor=com.CommandProcessor(bridge), bridge=bridge)
  33. def filter_matrix_event(self, evt: Event) -> bool:
  34. if not isinstance(evt, (ReactionEvent, MessageEvent, StateEvent, EncryptedEvent,
  35. RedactionEvent)):
  36. return True
  37. return (evt.sender == self.az.bot_mxid
  38. or pu.Puppet.get_id_from_mxid(evt.sender) is not None)
  39. async def send_welcome_message(self, room_id: RoomID, inviter: 'u.User') -> None:
  40. await super().send_welcome_message(room_id, inviter)
  41. if not inviter.notice_room:
  42. inviter.notice_room = room_id
  43. await inviter.update()
  44. await self.az.intent.send_notice(room_id, "This room has been marked as your "
  45. "Signal bridge notice room.")
  46. async def handle_leave(self, room_id: RoomID, user_id: UserID, event_id: EventID) -> None:
  47. portal = await po.Portal.get_by_mxid(room_id)
  48. if not portal:
  49. return
  50. user = await u.User.get_by_mxid(user_id, create=False)
  51. if not user:
  52. return
  53. await portal.handle_matrix_leave(user)
  54. @staticmethod
  55. async def allow_bridging_message(user: 'u.User', portal: 'po.Portal') -> bool:
  56. return user.is_whitelisted and bool(user.username)
  57. # @staticmethod
  58. # async def handle_redaction(room_id: RoomID, user_id: UserID, event_id: EventID,
  59. # redaction_event_id: EventID) -> None:
  60. # user = await u.User.get_by_mxid(user_id)
  61. # if not user:
  62. # return
  63. #
  64. # portal = await po.Portal.get_by_mxid(room_id)
  65. # if not portal:
  66. # return
  67. #
  68. # await portal.handle_matrix_redaction(user, event_id, redaction_event_id)
  69. @classmethod
  70. async def handle_reaction(cls, room_id: RoomID, user_id: UserID, event_id: EventID,
  71. content: ReactionEventContent) -> None:
  72. if content.relates_to.rel_type != RelationType.ANNOTATION:
  73. cls.log.debug(f"Ignoring m.reaction event in {room_id} from {user_id} with unexpected "
  74. f"relation type {content.relates_to.rel_type}")
  75. return
  76. user = await u.User.get_by_mxid(user_id)
  77. if not user:
  78. return
  79. portal = await po.Portal.get_by_mxid(room_id)
  80. if not portal:
  81. return
  82. await portal.handle_matrix_reaction(user, event_id, content.relates_to.event_id,
  83. content.relates_to.key)
  84. @staticmethod
  85. async def handle_receipt(evt: ReceiptEvent) -> None:
  86. # These events come from custom puppet syncing, so there's always only one user.
  87. event_id, receipts = evt.content.popitem()
  88. receipt_type, users = receipts.popitem()
  89. user_id, data = users.popitem()
  90. user = await u.User.get_by_mxid(user_id, create=False)
  91. if not user or not user.client:
  92. return
  93. portal = await po.Portal.get_by_mxid(evt.room_id)
  94. if not portal:
  95. return
  96. message = await DBMessage.get_by_mxid(event_id, portal.mxid)
  97. if not message:
  98. return
  99. # user.log.debug(f"Marking messages in {portal.twid} read up to {message.twid}")
  100. # await user.client.conversation(portal.twid).mark_read(message.twid)
  101. @staticmethod
  102. async def handle_typing(room_id: RoomID, typing: List[UserID]) -> None:
  103. # TODO implement
  104. pass
  105. async def handle_event(self, evt: Event) -> None:
  106. if evt.type == EventType.ROOM_REDACTION:
  107. evt: RedactionEvent
  108. # await self.handle_redaction(evt.room_id, evt.sender, evt.redacts, evt.event_id)
  109. elif evt.type == EventType.REACTION:
  110. evt: ReactionEvent
  111. await self.handle_reaction(evt.room_id, evt.sender, evt.event_id, evt.content)
  112. async def handle_ephemeral_event(self, evt: Union[ReceiptEvent, PresenceEvent, TypingEvent]
  113. ) -> None:
  114. if evt.type == EventType.TYPING:
  115. await self.handle_typing(evt.room_id, evt.content.user_ids)
  116. elif evt.type == EventType.RECEIPT:
  117. await self.handle_receipt(evt)