message.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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, ClassVar
  18. from attr import dataclass
  19. import attr
  20. from mautrix.types import EventID, RoomID
  21. from mautrix.util.async_db import Database, Scheme
  22. fake_db = Database.create("") if TYPE_CHECKING else None
  23. @dataclass
  24. class Message:
  25. db: ClassVar[Database] = fake_db
  26. mxid: EventID
  27. mx_room: RoomID
  28. item_id: str
  29. client_context: str | None
  30. receiver: int
  31. sender: int
  32. ig_timestamp: int | None
  33. _columns = "mxid, mx_room, item_id, client_context, receiver, sender, ig_timestamp"
  34. _insert_query = f"INSERT INTO message ({_columns}) VALUES ($1, $2, $3, $4, $5, $6, $7)"
  35. @property
  36. def ig_timestamp_ms(self) -> int:
  37. return (self.ig_timestamp // 1000) if self.ig_timestamp else 0
  38. async def insert(self) -> None:
  39. await self.db.execute(
  40. self._insert_query,
  41. self.mxid,
  42. self.mx_room,
  43. self.item_id,
  44. self.client_context,
  45. self.receiver,
  46. self.sender,
  47. self.ig_timestamp,
  48. )
  49. @classmethod
  50. async def bulk_insert(cls, messages: list[Message]) -> None:
  51. columns = cls._columns.split(", ")
  52. records = [attr.astuple(message) for message in messages]
  53. async with cls.db.acquire() as conn, conn.transaction():
  54. if cls.db.scheme == Scheme.POSTGRES:
  55. await conn.copy_records_to_table("message", records=records, columns=columns)
  56. else:
  57. await conn.executemany(cls._insert_query, records)
  58. async def delete(self) -> None:
  59. q = "DELETE FROM message WHERE item_id=$1 AND receiver=$2"
  60. await self.db.execute(q, self.item_id, self.receiver)
  61. @classmethod
  62. async def delete_all(cls, room_id: RoomID) -> None:
  63. await cls.db.execute("DELETE FROM message WHERE mx_room=$1", room_id)
  64. @classmethod
  65. async def get_by_mxid(cls, mxid: EventID, mx_room: RoomID) -> Message | None:
  66. q = f"SELECT {cls._columns} FROM message WHERE mxid=$1 AND mx_room=$2"
  67. row = await cls.db.fetchrow(q, mxid, mx_room)
  68. if not row:
  69. return None
  70. return cls(**row)
  71. @classmethod
  72. async def get_last(cls, mx_room: RoomID) -> Message | None:
  73. q = f"""
  74. SELECT {cls._columns} FROM message
  75. WHERE mx_room=$1 AND ig_timestamp IS NOT NULL AND item_id NOT LIKE 'fi.mau.instagram.%'
  76. ORDER BY ig_timestamp DESC LIMIT 1
  77. """
  78. row = await cls.db.fetchrow(q, mx_room)
  79. if not row:
  80. return None
  81. return cls(**row)
  82. @classmethod
  83. async def get_closest(cls, mx_room: RoomID, before_ts: int) -> Message | None:
  84. q = f"""
  85. SELECT {cls._columns} FROM message
  86. WHERE mx_room=$1 AND ig_timestamp<=$2 AND item_id NOT LIKE 'fi.mau.instagram.%'
  87. ORDER BY ig_timestamp DESC LIMIT 1
  88. """
  89. row = await cls.db.fetchrow(q, mx_room, before_ts)
  90. if not row:
  91. return None
  92. return cls(**row)
  93. @classmethod
  94. async def get_by_item_id(cls, item_id: str, receiver: int) -> Message | None:
  95. q = f"SELECT {cls._columns} FROM message WHERE item_id=$1 AND receiver=$2"
  96. row = await cls.db.fetchrow(q, item_id, receiver)
  97. if not row:
  98. return None
  99. return cls(**row)
  100. @property
  101. def is_internal(self) -> bool:
  102. return self.item_id.startswith("fi.mau.instagram.")