user.py 2.6 KB

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