message.py 2.5 KB

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