model.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. from typing import List, Optional, Tuple
  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) -> Optional[dict]:
  20. if self.current > 1:
  21. return {"page": self.current - 1}
  22. return None
  23. def next(self) -> Optional[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(current=current, last=((total - 1) // c.per_page) + 1,)
  30. # TODO: figure out authorization for users (oauth? passwd?)
  31. class User(Model):
  32. """
  33. A user! you know tf this is about
  34. """
  35. name = peewee.TextField(unique=True)
  36. passhash = peewee.TextField()
  37. is_admin = peewee.BooleanField(default=False)
  38. @staticmethod
  39. def from_request(user: r.User) -> "User":
  40. passhash = pwd.hash(user.password)
  41. try:
  42. return User.create(name=user.name, passhash=passhash,)
  43. except peewee.IntegrityError:
  44. raise e.UserExists(name=user.name)
  45. @staticmethod
  46. def from_invite(user: r.User, token: str) -> "User":
  47. invite = UserInvite.by_code(token)
  48. if invite.claimed_by is not None or invite.claimed_at is not None:
  49. raise e.AlreadyUsedInvite(invite=token)
  50. u = User.from_request(user)
  51. invite.claimed_at = datetime.datetime.now()
  52. invite.claimed_by = u
  53. invite.save()
  54. return u
  55. def authenticate(self, password: str) -> bool:
  56. return pwd.verify(password, self.passhash)
  57. def set_as_admin(self):
  58. self.is_admin = True
  59. self.save()
  60. @staticmethod
  61. def login(user: r.User) -> Tuple["User", str]:
  62. u = User.by_slug(user.name)
  63. if not u.authenticate(user.password):
  64. raise e.BadPassword(name=user.name)
  65. return u, user.to_token()
  66. @staticmethod
  67. def by_slug(slug: str) -> "User":
  68. u = User.get_or_none(name=slug)
  69. if u is None:
  70. raise e.NoSuchUser(name=slug)
  71. return u
  72. def base_url(self) -> str:
  73. return f"/u/{self.name}"
  74. def get_links(self, page: int) -> Tuple[List["Link"], Pagination]:
  75. links = (
  76. Link.select()
  77. .where(Link.user == self)
  78. .order_by(-Link.created)
  79. .paginate(page, c.per_page)
  80. )
  81. pagination = Pagination.from_total(page, Link.select().count())
  82. return links, pagination
  83. def get_link(self, link_id: int) -> "Link":
  84. return Link.get((Link.user == self) & (Link.id == link_id))
  85. def get_tag(self, tag_name: str) -> "Tag":
  86. return Tag.get((Tag.user == self) & (Tag.name == tag_name))
  87. def to_dict(self) -> dict:
  88. return {"id": self.id, "name": self.name}
  89. def get_config(self) -> dict:
  90. admin_pane = None
  91. if self.is_admin:
  92. user_invites = [
  93. {
  94. "claimed": ui.claimed_by is not None,
  95. "claimant": ui.claimed_by and ui.claimed_by.name,
  96. "token": ui.token,
  97. }
  98. for ui in UserInvite.select().where(UserInvite.created_by == self)
  99. ]
  100. admin_pane = {"invites": user_invites}
  101. return {
  102. "username": self.name,
  103. "admin_pane": admin_pane,
  104. }
  105. class Link(Model):
  106. """
  107. A link as stored in the database
  108. """
  109. url = peewee.TextField()
  110. name = peewee.TextField()
  111. description = peewee.TextField()
  112. # TODO: do we need to track modified time?
  113. created = peewee.DateTimeField()
  114. # is the field entirely private?
  115. private = peewee.BooleanField()
  116. # owned by
  117. user = peewee.ForeignKeyField(User, backref="links")
  118. def link_url(self) -> str:
  119. return f"/u/{self.user.name}/l/{self.id}"
  120. @staticmethod
  121. def from_request(user: User, link: r.Link) -> "Link":
  122. l = Link.create(
  123. url=link.url,
  124. name=link.name,
  125. description=link.description,
  126. private=link.private,
  127. created=link.created or datetime.datetime.now(),
  128. user=user,
  129. )
  130. for tag_name in link.tags:
  131. t = Tag.get_or_create_tag(user, tag_name)
  132. HasTag.create(
  133. link=l, tag=t,
  134. )
  135. return l
  136. class Tag(Model):
  137. """
  138. A tag. This just indicates that a user has used this tag at some point.
  139. """
  140. name = peewee.TextField()
  141. parent = peewee.ForeignKeyField("self", null=True, backref="children")
  142. user = peewee.ForeignKeyField(User, backref="tags")
  143. def url(self) -> str:
  144. return f"/u/{self.user.name}/t/{self.name}"
  145. def get_links(self, page: int) -> Tuple[List[Link], Pagination]:
  146. links = [
  147. ht.link
  148. for ht in HasTag.select()
  149. .join(Link)
  150. .where((HasTag.tag == self))
  151. .order_by(-Link.created)
  152. .paginate(page, c.per_page)
  153. ]
  154. pagination = Pagination.from_total(
  155. page, HasTag.select().where((HasTag.tag == self)).count(),
  156. )
  157. return links, pagination
  158. @staticmethod
  159. def get_or_create_tag(user: User, tag_name: str):
  160. if (t := Tag.get_or_none(name=tag_name, user=user)) :
  161. return t
  162. parent = None
  163. if "/" in tag_name:
  164. parent_name = tag_name[: tag_name.rindex("/")]
  165. parent = Tag.get_or_create_tag(user, parent_name)
  166. return Tag.create(name=tag_name, parent=parent, user=user)
  167. class HasTag(Model):
  168. """
  169. Establishes that a link is tagged with a given tag.
  170. """
  171. link = peewee.ForeignKeyField(Link, backref="tags")
  172. tag = peewee.ForeignKeyField(Tag, backref="models")
  173. class UserInvite(Model):
  174. token = peewee.TextField(unique=True)
  175. created_by = peewee.ForeignKeyField(User, backref="invites")
  176. created_at = peewee.DateTimeField()
  177. claimed_by = peewee.ForeignKeyField(User, null=True)
  178. claimed_at = peewee.DateTimeField(null=True)
  179. @staticmethod
  180. def by_code(token: str) -> "UserInvite":
  181. if (u := UserInvite.get_or_none(token=token)) :
  182. return u
  183. raise e.NoSuchInvite(invite=token)
  184. @staticmethod
  185. def manufacture(creator: User) -> "UserInvite":
  186. now = datetime.datetime.now()
  187. token = c.serializer.dumps(
  188. {"created_at": now.timestamp(), "created_by": creator.name,}
  189. )
  190. return UserInvite.create(
  191. token=token,
  192. created_by=creator,
  193. created_at=now,
  194. claimed_by=None,
  195. claimed_at=None,
  196. )
  197. MODELS = [
  198. User,
  199. Link,
  200. Tag,
  201. HasTag,
  202. UserInvite,
  203. ]
  204. def create_tables():
  205. c.db.create_tables(MODELS, safe=True)