You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
2.2 KiB

  1. # maunium-stickerpicker - A fast and simple Matrix sticker picker widget.
  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 List, Dict, Any
  17. from attr import dataclass
  18. from mautrix.types import UserID
  19. from .base import Base
  20. from .sticker import Sticker
  21. @dataclass(kw_only=True)
  22. class Pack(Base):
  23. id: str
  24. owner: UserID
  25. title: str
  26. meta: Dict[str, Any]
  27. async def delete(self) -> None:
  28. await self.db.execute("DELETE FROM pack WHERE id=$1", self.id)
  29. async def insert(self) -> None:
  30. await self.db.execute("INSERT INTO pack (id, owner, title, meta) VALUES ($1, $2, $3, $4)",
  31. self.id, self.owner, self.title, self.meta)
  32. async def get_stickers(self) -> List[Sticker]:
  33. res = await self.db.fetch('SELECT id, url, body, meta, "order" '
  34. 'FROM sticker WHERE pack_id=$1 ORDER BY "order"', self.id)
  35. return [Sticker(**row, pack_id=self.id) for row in res]
  36. async def set_stickers(self, stickers: List[Sticker]) -> None:
  37. data = ((sticker.id, self.id, sticker.url, sticker.body, sticker.meta, order)
  38. for order, sticker in enumerate(stickers))
  39. columns = ["id", "pack_id", "url", "body", "meta", "order"]
  40. async with self.db.acquire() as conn, conn.transaction():
  41. await conn.execute("DELETE FROM sticker WHERE pack_id=$1", self.id)
  42. await conn.copy_records_to_table("sticker", records=data, columns=columns)
  43. def to_dict(self) -> Dict[str, Any]:
  44. return {
  45. **self.meta,
  46. "title": self.title,
  47. "id": self.id,
  48. }