message.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. async def insert(self) -> None:
  29. q = "INSERT INTO message (mxid, mx_room, item_id, receiver) VALUES ($1, $2, $3, $4)"
  30. await self.db.execute(q, self.mxid, self.mx_room, self.item_id, self.receiver)
  31. async def delete(self) -> None:
  32. q = "DELETE FROM message WHERE item_id=$1 AND receiver=$2"
  33. await self.db.execute(q, self.item_id, self.receiver)
  34. @classmethod
  35. async def delete_all(cls, room_id: RoomID) -> None:
  36. await cls.db.execute("DELETE FROM message WHERE mx_room=$1", room_id)
  37. @classmethod
  38. async def get_by_mxid(cls, mxid: EventID, mx_room: RoomID) -> Optional['Message']:
  39. row = await cls.db.fetchrow("SELECT mxid, mx_room, item_id, receiver "
  40. "FROM message WHERE mxid=$1 AND mx_room=$2", mxid, mx_room)
  41. if not row:
  42. return None
  43. return cls(**row)
  44. @classmethod
  45. async def get_by_item_id(cls, item_id: str, receiver: int = 0) -> Optional['Message']:
  46. row = await cls.db.fetchrow("SELECT mxid, mx_room, item_id, receiver "
  47. "FROM message WHERE item_id=$1 AND receiver=$2",
  48. item_id, receiver)
  49. if not row:
  50. return None
  51. return cls(**row)