matrix.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2022 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 __future__ import annotations
  17. from typing import TYPE_CHECKING
  18. import sys
  19. from mautrix.bridge import BaseMatrixHandler
  20. from mautrix.types import (
  21. Event,
  22. EventID,
  23. EventType,
  24. PresenceEvent,
  25. ReactionEvent,
  26. ReactionEventContent,
  27. ReceiptEvent,
  28. RedactionEvent,
  29. RelationType,
  30. RoomID,
  31. SingleReceiptEventContent,
  32. TypingEvent,
  33. UserID,
  34. )
  35. from mautrix.util.message_send_checkpoint import MessageSendCheckpointStatus
  36. from . import portal as po, user as u
  37. from .db import Message as DBMessage
  38. if TYPE_CHECKING:
  39. from .__main__ import InstagramBridge
  40. class MatrixHandler(BaseMatrixHandler):
  41. def __init__(self, bridge: "InstagramBridge") -> None:
  42. prefix, suffix = bridge.config["bridge.username_template"].format(userid=":").split(":")
  43. homeserver = bridge.config["homeserver.domain"]
  44. self.user_id_prefix = f"@{prefix}"
  45. self.user_id_suffix = f"{suffix}:{homeserver}"
  46. super().__init__(bridge=bridge)
  47. async def check_versions(self) -> None:
  48. await super().check_versions()
  49. if self.config["bridge.backfill.msc2716"] and not (
  50. support := self.versions.supports("org.matrix.msc2716")
  51. ):
  52. self.log.fatal(
  53. "Backfilling is enabled in bridge config, but "
  54. + (
  55. "MSC2716 batch sending is not enabled on homeserver"
  56. if support is False
  57. else "homeserver does not support MSC2716 batch sending"
  58. )
  59. )
  60. sys.exit(18)
  61. async def send_welcome_message(self, room_id: RoomID, inviter: u.User) -> None:
  62. await super().send_welcome_message(room_id, inviter)
  63. if not inviter.notice_room:
  64. inviter.notice_room = room_id
  65. await inviter.update()
  66. await self.az.intent.send_notice(
  67. room_id, "This room has been marked as your Instagram bridge notice room."
  68. )
  69. async def handle_leave(self, room_id: RoomID, user_id: UserID, event_id: EventID) -> None:
  70. portal = await po.Portal.get_by_mxid(room_id)
  71. if not portal:
  72. return
  73. user = await u.User.get_by_mxid(user_id, create=False)
  74. if not user:
  75. return
  76. await portal.handle_matrix_leave(user)
  77. @staticmethod
  78. async def handle_redaction(
  79. room_id: RoomID, user_id: UserID, event_id: EventID, redaction_event_id: EventID
  80. ) -> None:
  81. user = await u.User.get_by_mxid(user_id)
  82. if not user:
  83. return
  84. portal = await po.Portal.get_by_mxid(room_id)
  85. if not portal:
  86. user.send_remote_checkpoint(
  87. MessageSendCheckpointStatus.PERM_FAILURE,
  88. event_id,
  89. room_id,
  90. EventType.ROOM_REDACTION,
  91. error=Exception("Ignoring redaction event in non-portal room"),
  92. )
  93. return
  94. await portal.handle_matrix_redaction(user, event_id, redaction_event_id)
  95. @classmethod
  96. async def handle_reaction(
  97. cls,
  98. room_id: RoomID,
  99. user_id: UserID,
  100. event_id: EventID,
  101. content: ReactionEventContent,
  102. timestamp: int,
  103. ) -> None:
  104. if content.relates_to.rel_type != RelationType.ANNOTATION:
  105. cls.log.debug(
  106. f"Ignoring m.reaction event in {room_id} from {user_id} with unexpected "
  107. f"relation type {content.relates_to.rel_type}"
  108. )
  109. return
  110. user = await u.User.get_by_mxid(user_id)
  111. if not user:
  112. return
  113. portal = await po.Portal.get_by_mxid(room_id)
  114. if not portal:
  115. return
  116. await portal.handle_matrix_reaction(
  117. user, event_id, content.relates_to.event_id, content.relates_to.key, timestamp
  118. )
  119. async def handle_read_receipt(
  120. self,
  121. user: u.User,
  122. portal: po.Portal,
  123. event_id: EventID,
  124. data: SingleReceiptEventContent,
  125. ) -> None:
  126. message = await DBMessage.get_by_mxid(event_id, portal.mxid)
  127. if not message or message.is_internal:
  128. # Message might actually be reaction - mark all as read
  129. message = await DBMessage.get_last(portal.mxid)
  130. if not message:
  131. return
  132. user.log.debug(f"Marking {message.item_id} in {portal.thread_id} as read")
  133. await user.mqtt.mark_seen(portal.thread_id, message.item_id)
  134. @staticmethod
  135. async def handle_typing(room_id: RoomID, typing: list[UserID]) -> None:
  136. portal = await po.Portal.get_by_mxid(room_id)
  137. if not portal:
  138. return
  139. await portal.handle_matrix_typing(set(typing))
  140. async def handle_event(self, evt: Event) -> None:
  141. if evt.type == EventType.ROOM_REDACTION:
  142. evt: RedactionEvent
  143. await self.handle_redaction(evt.room_id, evt.sender, evt.redacts, evt.event_id)
  144. elif evt.type == EventType.REACTION:
  145. evt: ReactionEvent
  146. await self.handle_reaction(
  147. evt.room_id, evt.sender, evt.event_id, evt.content, evt.timestamp
  148. )
  149. async def handle_ephemeral_event(
  150. self, evt: ReceiptEvent | PresenceEvent | TypingEvent
  151. ) -> None:
  152. if evt.type == EventType.TYPING:
  153. await self.handle_typing(evt.room_id, evt.content.user_ids)
  154. else:
  155. await super().handle_ephemeral_event(evt)