user.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # mautrix-signal - A Matrix-Signal puppeting bridge
  2. # Copyright (C) 2021 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 TYPE_CHECKING, ClassVar, List, Optional
  17. from uuid import UUID
  18. from attr import dataclass
  19. from mautrix.types import RoomID, UserID
  20. from mautrix.util.async_db import Database
  21. fake_db = Database.create("") if TYPE_CHECKING else None
  22. @dataclass
  23. class User:
  24. db: ClassVar[Database] = fake_db
  25. mxid: UserID
  26. username: Optional[str]
  27. uuid: Optional[UUID]
  28. notice_room: Optional[RoomID]
  29. async def insert(self) -> None:
  30. q = 'INSERT INTO "user" (mxid, username, uuid, notice_room) ' "VALUES ($1, $2, $3, $4)"
  31. await self.db.execute(q, self.mxid, self.username, self.uuid, self.notice_room)
  32. async def update(self) -> None:
  33. q = 'UPDATE "user" SET username=$1, uuid=$2, notice_room=$3 WHERE mxid=$4'
  34. await self.db.execute(q, self.username, self.uuid, self.notice_room, self.mxid)
  35. @classmethod
  36. async def get_by_mxid(cls, mxid: UserID) -> Optional["User"]:
  37. q = 'SELECT mxid, username, uuid, notice_room FROM "user" WHERE mxid=$1'
  38. row = await cls.db.fetchrow(q, mxid)
  39. if not row:
  40. return None
  41. return cls(**row)
  42. @classmethod
  43. async def get_by_username(cls, username: str) -> Optional["User"]:
  44. q = 'SELECT mxid, username, uuid, notice_room FROM "user" WHERE username=$1'
  45. row = await cls.db.fetchrow(q, username)
  46. if not row:
  47. return None
  48. return cls(**row)
  49. @classmethod
  50. async def get_by_uuid(cls, uuid: UUID) -> Optional["User"]:
  51. q = 'SELECT mxid, username, uuid, notice_room FROM "user" WHERE uuid=$1'
  52. row = await cls.db.fetchrow(q, uuid)
  53. if not row:
  54. return None
  55. return cls(**row)
  56. @classmethod
  57. async def all_logged_in(cls) -> List["User"]:
  58. q = 'SELECT mxid, username, uuid, notice_room FROM "user" WHERE username IS NOT NULL'
  59. rows = await cls.db.fetch(q)
  60. return [cls(**row) for row in rows]