model.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. from dataclasses import dataclass
  2. import datetime
  3. from passlib.apps import custom_app_context as pwd
  4. import peewee
  5. import playhouse.shortcuts
  6. import typing
  7. import lc.config as c
  8. import lc.error as e
  9. import lc.request as r
  10. class Model(peewee.Model):
  11. class Meta:
  12. database = c.DB
  13. def to_dict(self) -> dict:
  14. return playhouse.shortcuts.model_to_dict(self)
  15. @dataclass
  16. class Pagination:
  17. current: int
  18. last: int
  19. def previous(self) -> dict:
  20. if self.current > 1:
  21. return {"page": self.current - 1}
  22. return None
  23. def next(self) -> dict:
  24. if self.current < self.last:
  25. return {"page": self.current + 1}
  26. return None
  27. @classmethod
  28. def from_total(cls, current, total) -> "Pagination":
  29. return cls(
  30. current=current,
  31. last=((total-1)//c.PER_PAGE)+1,
  32. )
  33. # TODO: figure out authorization for users (oauth? passwd?)
  34. class User(Model):
  35. """
  36. A user! you know tf this is about
  37. """
  38. name = peewee.TextField(unique=True)
  39. passhash = peewee.TextField()
  40. is_admin = peewee.BooleanField(default=False)
  41. @staticmethod
  42. def from_request(user: r.User) -> "User":
  43. passhash = pwd.hash(user.password)
  44. try:
  45. return User.create(name=user.name, passhash=passhash,)
  46. except peewee.IntegrityError:
  47. raise e.UserExists(name=user.name)
  48. def authenticate(self, password: str) -> bool:
  49. return pwd.verify(password, self.passhash)
  50. def set_as_admin(self):
  51. self.is_admin = True
  52. self.save()
  53. @staticmethod
  54. def login(user: r.User) -> typing.Tuple["User", str]:
  55. u = User.by_slug(user.name)
  56. if not u.authenticate(user.password):
  57. raise e.BadPassword(name=user.name)
  58. return u, c.SERIALIZER.dumps(user.to_dict())
  59. @staticmethod
  60. def by_slug(slug: str) -> "User":
  61. u = User.get_or_none(name=slug)
  62. if u is None:
  63. raise e.NoSuchUser(name=slug)
  64. return u
  65. def base_url(self) -> str:
  66. return f"/u/{self.name}"
  67. def get_links(self, page: int) -> typing.Tuple[typing.List["Link"], Pagination]:
  68. links = Link.select().where(Link.user == self).order_by(-Link.created).paginate(page, c.PER_PAGE)
  69. pagination = Pagination.from_total(page, Link.select().count())
  70. return links, pagination
  71. def get_link(self, link_id: int) -> "Link":
  72. return Link.get((Link.user == self) & (Link.id == link_id))
  73. def get_tag(self, tag_name: str) -> "Tag":
  74. return Tag.get((Tag.user == self) & (Tag.name == tag_name))
  75. def to_dict(self) -> dict:
  76. return {"id": self.id, "name": self.name}
  77. class Link(Model):
  78. """
  79. A link as stored in the database
  80. """
  81. url = peewee.TextField()
  82. name = peewee.TextField()
  83. description = peewee.TextField()
  84. # TODO: do we need to track modified time?
  85. created = peewee.DateTimeField()
  86. # is the field entirely private?
  87. private = peewee.BooleanField()
  88. # owned by
  89. user = peewee.ForeignKeyField(User, backref="links")
  90. def link_url(self) -> str:
  91. return f"/u/{self.user.name}/l/{self.id}"
  92. @staticmethod
  93. def from_request(user: User, link: r.Link) -> "Link":
  94. l = Link.create(
  95. url=link.url,
  96. name=link.name,
  97. description=link.description,
  98. private=link.private,
  99. created=link.created or datetime.datetime.now(),
  100. user=user,
  101. )
  102. for tag_name in link.tags:
  103. t = Tag.get_or_create_tag(user, tag_name)
  104. HasTag.create(
  105. link=l, tag=t,
  106. )
  107. return l
  108. class Tag(Model):
  109. """
  110. A tag. This just indicates that a user has used this tag at some point.
  111. """
  112. name = peewee.TextField()
  113. parent = peewee.ForeignKeyField("self", null=True, backref="children")
  114. user = peewee.ForeignKeyField(User, backref="tags")
  115. def url(self) -> str:
  116. return f"/u/{self.user.name}/t/{self.name}"
  117. def get_links(self, page: int) -> typing.Tuple[typing.List[Link], Pagination]:
  118. links = [
  119. ht.link
  120. for ht in HasTag.select()
  121. .join(Link)
  122. .where((HasTag.tag == self))
  123. .order_by(-Link.created)
  124. .paginate(page, c.PER_PAGE)
  125. ]
  126. pagination = Pagination.from_total(
  127. page,
  128. HasTag.select().where((HasTag.tag == self)).count(),
  129. )
  130. return links, pagination
  131. @staticmethod
  132. def get_or_create_tag(user: User, tag_name: str):
  133. if (t := Tag.get_or_none(name=tag_name, user=user)) :
  134. return t
  135. parent = None
  136. if "/" in tag_name:
  137. parent_name = tag_name[: tag_name.rindex("/")]
  138. parent = Tag.get_or_create_tag(user, parent_name)
  139. return Tag.create(name=tag_name, parent=parent, user=user)
  140. class HasTag(Model):
  141. """
  142. Establishes that a link is tagged with a given tag.
  143. """
  144. link = peewee.ForeignKeyField(Link, backref="tags")
  145. tag = peewee.ForeignKeyField(Tag, backref="models")
  146. class UserInvite(Model):
  147. token: str
  148. MODELS = [
  149. User,
  150. Link,
  151. Tag,
  152. HasTag,
  153. ]
  154. def create_tables():
  155. c.DB.create_tables(MODELS, safe=True)