message.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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 Optional, ClassVar, Union, List, TYPE_CHECKING
  17. from uuid import UUID
  18. from attr import dataclass
  19. import asyncpg
  20. from mausignald.types import Address, GroupID
  21. from mautrix.types import RoomID, EventID
  22. from mautrix.util.async_db import Database
  23. from ..util import id_to_str
  24. fake_db = Database.create("") if TYPE_CHECKING else None
  25. @dataclass
  26. class Message:
  27. db: ClassVar[Database] = fake_db
  28. mxid: EventID
  29. mx_room: RoomID
  30. sender: Address
  31. timestamp: int
  32. signal_chat_id: Union[GroupID, Address]
  33. signal_receiver: str
  34. async def insert(self) -> None:
  35. q = """
  36. INSERT INTO message (mxid, mx_room, sender, timestamp, signal_chat_id, signal_receiver)
  37. VALUES ($1, $2, $3, $4, $5, $6)
  38. """
  39. await self.db.execute(
  40. q,
  41. self.mxid,
  42. self.mx_room,
  43. self.sender.best_identifier,
  44. self.timestamp,
  45. id_to_str(self.signal_chat_id),
  46. self.signal_receiver,
  47. )
  48. async def delete(self) -> None:
  49. q = """
  50. DELETE FROM message
  51. WHERE sender=$1 AND timestamp=$2 AND signal_chat_id=$3 AND signal_receiver=$4
  52. """
  53. await self.db.execute(
  54. q,
  55. self.sender.best_identifier,
  56. self.timestamp,
  57. id_to_str(self.signal_chat_id),
  58. self.signal_receiver,
  59. )
  60. @classmethod
  61. async def delete_all(cls, room_id: RoomID) -> None:
  62. await cls.db.execute("DELETE FROM message WHERE mx_room=$1", room_id)
  63. @classmethod
  64. def _from_row(cls, row: asyncpg.Record) -> "Message":
  65. data = {**row}
  66. chat_id = data.pop("signal_chat_id")
  67. if data["signal_receiver"]:
  68. chat_id = Address.parse(chat_id)
  69. sender = Address.parse(data.pop("sender"))
  70. return cls(signal_chat_id=chat_id, sender=sender, **data)
  71. @classmethod
  72. async def get_by_mxid(cls, mxid: EventID, mx_room: RoomID) -> Optional["Message"]:
  73. q = """
  74. SELECT mxid, mx_room, sender, timestamp, signal_chat_id, signal_receiver
  75. FROM message WHERE mxid=$1 AND mx_room=$2
  76. """
  77. row = await cls.db.fetchrow(q, mxid, mx_room)
  78. if not row:
  79. return None
  80. return cls._from_row(row)
  81. @classmethod
  82. async def get_by_signal_id(
  83. cls,
  84. sender: Address,
  85. timestamp: int,
  86. signal_chat_id: Union[GroupID, Address],
  87. signal_receiver: str = "",
  88. ) -> Optional["Message"]:
  89. q = """
  90. SELECT mxid, mx_room, sender, timestamp, signal_chat_id, signal_receiver
  91. FROM message
  92. WHERE sender=$1 AND timestamp=$2 AND signal_chat_id=$3 AND signal_receiver=$4
  93. """
  94. row = await cls.db.fetchrow(
  95. q, sender.best_identifier, timestamp, id_to_str(signal_chat_id), signal_receiver
  96. )
  97. if not row:
  98. return None
  99. return cls._from_row(row)
  100. @classmethod
  101. async def find_by_timestamps(cls, timestamps: List[int]) -> List["Message"]:
  102. if cls.db.scheme == "postgres":
  103. q = """
  104. SELECT mxid, mx_room, sender, timestamp, signal_chat_id, signal_receiver
  105. FROM message
  106. WHERE timestamp=ANY($1)
  107. """
  108. rows = await cls.db.fetch(q, timestamps)
  109. else:
  110. placeholders = ", ".join("?" for _ in range(len(timestamps)))
  111. q = f"""
  112. SELECT mxid, mx_room, sender, timestamp, signal_chat_id, signal_receiver
  113. FROM message
  114. WHERE timestamp IN ({placeholders})
  115. """
  116. rows = await cls.db.fetch(q, *timestamps)
  117. return [cls._from_row(row) for row in rows]
  118. @classmethod
  119. async def find_by_sender_timestamp(
  120. cls, sender: Address, timestamp: int
  121. ) -> Optional["Message"]:
  122. q = """
  123. SELECT mxid, mx_room, sender, timestamp, signal_chat_id, signal_receiver
  124. FROM message
  125. WHERE sender=$1 AND timestamp=$2
  126. """
  127. row = await cls.db.fetchrow(q, sender.best_identifier, timestamp)
  128. if not row:
  129. return None
  130. return cls._from_row(row)