message.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # mautrix-instagram - A Matrix-Instagram 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, TYPE_CHECKING
  17. from attr import dataclass
  18. from mautrix.types import RoomID, EventID
  19. from mautrix.util.async_db import Database
  20. fake_db = Database("") if TYPE_CHECKING else None
  21. @dataclass
  22. class Message:
  23. db: ClassVar[Database] = fake_db
  24. mxid: EventID
  25. mx_room: RoomID
  26. item_id: str
  27. receiver: int
  28. sender: int
  29. async def insert(self) -> None:
  30. q = ("INSERT INTO message (mxid, mx_room, item_id, receiver, sender) "
  31. "VALUES ($1, $2, $3, $4, $5)")
  32. await self.db.execute(q, self.mxid, self.mx_room, self.item_id, self.receiver, self.sender)
  33. async def delete(self) -> None:
  34. q = "DELETE FROM message WHERE item_id=$1 AND receiver=$2"
  35. await self.db.execute(q, self.item_id, self.receiver)
  36. @classmethod
  37. async def delete_all(cls, room_id: RoomID) -> None:
  38. await cls.db.execute("DELETE FROM message WHERE mx_room=$1", room_id)
  39. @classmethod
  40. async def get_by_mxid(cls, mxid: EventID, mx_room: RoomID) -> Optional['Message']:
  41. row = await cls.db.fetchrow("SELECT mxid, mx_room, item_id, receiver, sender "
  42. "FROM message WHERE mxid=$1 AND mx_room=$2", mxid, mx_room)
  43. if not row:
  44. return None
  45. return cls(**row)
  46. @classmethod
  47. async def get_by_item_id(cls, item_id: str, receiver: int) -> Optional['Message']:
  48. row = await cls.db.fetchrow("SELECT mxid, mx_room, item_id, receiver, sender "
  49. "FROM message WHERE item_id=$1 AND receiver=$2",
  50. item_id, receiver)
  51. if not row:
  52. return None
  53. return cls(**row)
  54. @property
  55. def is_internal(self) -> bool:
  56. return self.item_id.startswith("fi.mau.instagram.")