model.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. from dataclasses import dataclass
  2. import datetime
  3. import json
  4. from passlib.apps import custom_app_context as pwd
  5. import peewee
  6. import playhouse.shortcuts
  7. from typing import Iterator, List, Optional, Tuple
  8. import lc.config as c
  9. import lc.error as e
  10. import lc.request as r
  11. import lc.view as v
  12. class Model(peewee.Model):
  13. class Meta:
  14. database = c.db
  15. def to_dict(self) -> dict:
  16. return playhouse.shortcuts.model_to_dict(self)
  17. class User(Model):
  18. """
  19. A user! you know tf this is about
  20. """
  21. name = peewee.TextField(unique=True)
  22. passhash = peewee.TextField()
  23. is_admin = peewee.BooleanField(default=False)
  24. @staticmethod
  25. def from_request(user: r.User) -> "User":
  26. passhash = pwd.hash(user.password)
  27. try:
  28. return User.create(name=user.name, passhash=passhash,)
  29. except peewee.IntegrityError:
  30. raise e.UserExists(name=user.name)
  31. @staticmethod
  32. def from_invite(user: r.User, token: str) -> "User":
  33. invite = UserInvite.by_code(token)
  34. if invite.claimed_by is not None or invite.claimed_at is not None:
  35. raise e.AlreadyUsedInvite(invite=token)
  36. u = User.from_request(user)
  37. invite.claimed_at = datetime.datetime.now()
  38. invite.claimed_by = u
  39. invite.save()
  40. return u
  41. def authenticate(self, password: str) -> bool:
  42. return pwd.verify(password, self.passhash)
  43. def set_as_admin(self):
  44. self.is_admin = True
  45. self.save()
  46. @staticmethod
  47. def login(user: r.User) -> Tuple["User", str]:
  48. u = User.by_slug(user.name)
  49. if not u.authenticate(user.password):
  50. raise e.BadPassword(name=user.name)
  51. return u, user.to_token()
  52. @staticmethod
  53. def by_slug(slug: str) -> "User":
  54. u = User.get_or_none(name=slug)
  55. if u is None:
  56. raise e.NoSuchUser(name=slug)
  57. return u
  58. def base_url(self) -> str:
  59. return f"/u/{self.name}"
  60. def get_links(
  61. self, as_user: Optional["User"], page: int
  62. ) -> Tuple[List[v.Link], v.Pagination]:
  63. links = (
  64. Link.select()
  65. .where((Link.user == self) & ((self == as_user) | (Link.private == False)))
  66. .order_by(-Link.created)
  67. .paginate(page, c.per_page)
  68. )
  69. link_views = [l.to_view(as_user) for l in links]
  70. pagination = v.Pagination.from_total(page, Link.select().count())
  71. return link_views, pagination
  72. def get_link(self, link_id: int) -> "Link":
  73. try:
  74. return Link.get((Link.user == self) & (Link.id == link_id))
  75. except Link.DoesNotExist:
  76. raise e.NoSuchLink(link_id)
  77. def get_tag(self, tag_name: str) -> "Tag":
  78. return Tag.get((Tag.user == self) & (Tag.name == tag_name))
  79. def to_dict(self) -> dict:
  80. return {"id": self.id, "name": self.name}
  81. def get_config(self) -> v.Config:
  82. admin_pane = None
  83. if self.is_admin:
  84. user_invites = [
  85. v.UserInvite(
  86. claimed=ui.claimed_by is not None,
  87. claimant=ui.claimed_by and ui.claimed_by.name,
  88. token=ui.token,
  89. )
  90. for ui in UserInvite.select().where(UserInvite.created_by == self)
  91. ]
  92. admin_pane = v.AdminPane(invites=user_invites)
  93. return v.Config(username=self.name, admin_pane=admin_pane,)
  94. def import_pinboard_data(self, stream):
  95. try:
  96. links = json.load(stream)
  97. except json.decoder.JSONDecodeError as exn:
  98. raise e.BadFileUpload("could not parse file as JSON")
  99. if not isinstance(links, list):
  100. raise e.BadFileUpload(f"expected a list")
  101. # create and (for this session) cache the tags
  102. tags = {}
  103. for l in links:
  104. if "tags" not in l:
  105. raise e.BadFileUpload("missing key {exn.args[0]}")
  106. for t in l["tags"].split():
  107. if t in tags:
  108. continue
  109. tags[t] = Tag.get_or_create_tag(self, t)
  110. with c.db.atomic():
  111. for l in links:
  112. try:
  113. time = datetime.datetime.strptime(l["time"], "%Y-%m-%dT%H:%M:%SZ")
  114. ln = Link.create(
  115. url=l["href"],
  116. name=l["description"],
  117. description=l["extended"],
  118. private=l["shared"] == "no",
  119. created=time,
  120. user=self,
  121. )
  122. except KeyError as exn:
  123. raise e.BadFileUpload(f"missing key {exn.args[0]}")
  124. for t in l["tags"].split():
  125. HasTag.get_or_create(link=ln, tag=tags[t])
  126. def get_tags(self) -> List[v.Tag]:
  127. return sorted(
  128. (t.to_view() for t in self.tags), # type: ignore
  129. key=lambda t: t.name,
  130. )
  131. def get_related_tags(self, tag: "Tag") -> List[v.Tag]:
  132. # SELECT * from has_tag t1, has_tag t2, link l WHERE t1.link_id == l.id AND t2.link_id == l.id AND t1.id != t2.id AND t1 = self
  133. SelfTag = HasTag.alias()
  134. query = (
  135. HasTag.select(HasTag.tag)
  136. .join(Link, on=(HasTag.link == Link.id))
  137. .join(SelfTag, on=(SelfTag.link == Link.id))
  138. .where((SelfTag.tag == tag) & (SelfTag.id != HasTag.id))
  139. .group_by(HasTag.tag)
  140. )
  141. return sorted((t.tag.to_view() for t in query), key=lambda t: t.name,)
  142. class Link(Model):
  143. """
  144. A link as stored in the database
  145. """
  146. url = peewee.TextField()
  147. name = peewee.TextField()
  148. description = peewee.TextField()
  149. # TODO: do we need to track modified time?
  150. created = peewee.DateTimeField()
  151. # is the field entirely private?
  152. private = peewee.BooleanField()
  153. # owned by
  154. user = peewee.ForeignKeyField(User, backref="links")
  155. def link_url(self) -> str:
  156. return f"/u/{self.user.name}/l/{self.id}"
  157. @staticmethod
  158. def by_id(id: int) -> Optional["Link"]:
  159. return Link.get_or_none(id=id)
  160. @staticmethod
  161. def from_request(user: User, link: r.Link) -> "Link":
  162. l = Link.create(
  163. url=link.url,
  164. name=link.name,
  165. description=link.description,
  166. private=link.private,
  167. created=link.created or datetime.datetime.now(),
  168. user=user,
  169. )
  170. for tag_name in link.tags:
  171. tag = Tag.get_or_create_tag(user, tag_name)
  172. HasTag.get_or_create(link=l, tag=tag)
  173. return l
  174. def update_from_request(self, user: User, link: r.Link):
  175. with c.db.atomic():
  176. req_tags = set(link.tags)
  177. for hastag in self.tags: # type: ignore
  178. name = hastag.tag.name
  179. if name not in req_tags:
  180. hastag.delete_instance()
  181. else:
  182. req_tags.remove(name)
  183. for tag_name in req_tags:
  184. t = Tag.get_or_create_tag(user, tag_name)
  185. HasTag.get_or_create(link=self, tag=t)
  186. self.url = link.url
  187. self.name = link.name
  188. self.description = link.description
  189. self.private = link.private
  190. self.save()
  191. def to_view(self, as_user: Optional[User]) -> v.Link:
  192. return v.Link(
  193. id=self.id,
  194. url=self.url,
  195. name=self.name,
  196. description=self.description,
  197. private=self.private,
  198. tags=self.get_tags_view(),
  199. created=self.created,
  200. is_mine=self.user.id == as_user.id if as_user else False,
  201. link_url=self.link_url(),
  202. )
  203. def get_tags_view(self) -> List[v.Tag]:
  204. return [
  205. v.Tag(url=f"/u/{self.user.name}/t/{ht.tag.name}", name=ht.tag.name)
  206. for ht in HasTag().select(Tag.name).join(Tag).where(HasTag.link == self)
  207. ]
  208. class Tag(Model):
  209. """
  210. A tag. This just indicates that a user has used this tag at some point.
  211. """
  212. name = peewee.TextField()
  213. parent = peewee.ForeignKeyField("self", null=True, backref="children")
  214. user = peewee.ForeignKeyField(User, backref="tags")
  215. def url(self) -> str:
  216. return f"/u/{self.user.name}/t/{self.name}"
  217. def get_links(
  218. self, as_user: Optional[User], page: int
  219. ) -> Tuple[List[Link], v.Pagination]:
  220. links = [
  221. ht.link.to_view(as_user)
  222. for ht in HasTag.select()
  223. .join(Link)
  224. .where(
  225. (HasTag.tag == self)
  226. & ((HasTag.link.user == as_user) | (HasTag.link.private == False))
  227. )
  228. .order_by(-Link.created)
  229. .paginate(page, c.per_page)
  230. ]
  231. pagination = v.Pagination.from_total(
  232. page, HasTag.select().where((HasTag.tag == self)).count(),
  233. )
  234. return links, pagination
  235. def get_family(self) -> Iterator["Tag"]:
  236. yield self
  237. p = self
  238. while (p := p.parent) :
  239. yield p
  240. BAD_TAG_CHARS = set("{}[]\\()#?")
  241. @staticmethod
  242. def is_valid_tag_name(tag_name: str) -> bool:
  243. return all((c not in Tag.BAD_TAG_CHARS for c in tag_name))
  244. @staticmethod
  245. def get_or_create_tag(user: User, tag_name: str) -> "Tag":
  246. if (t := Tag.get_or_none(name=tag_name, user=user)) :
  247. return t
  248. if not Tag.is_valid_tag_name(tag_name):
  249. raise e.BadTagName(tag_name)
  250. parent = None
  251. if "/" in tag_name:
  252. parent_name = tag_name[: tag_name.rindex("/")]
  253. parent = Tag.get_or_create_tag(user, parent_name)
  254. return Tag.create(name=tag_name, parent=parent, user=user)
  255. def to_view(self) -> v.Tag:
  256. return v.Tag(url=self.url(), name=self.name)
  257. class HasTag(Model):
  258. """
  259. Establishes that a link is tagged with a given tag.
  260. """
  261. link = peewee.ForeignKeyField(Link, backref="tags")
  262. tag = peewee.ForeignKeyField(Tag, backref="models")
  263. @staticmethod
  264. def get_or_create(link: Link, tag: Tag):
  265. res = HasTag.get_or_none(link=link, tag=tag)
  266. if res is None:
  267. res = HasTag.create(link=link, tag=tag)
  268. if tag.parent:
  269. HasTag.get_or_create(link, tag.parent)
  270. return res
  271. class UserInvite(Model):
  272. token = peewee.TextField(unique=True)
  273. created_by = peewee.ForeignKeyField(User, backref="invites")
  274. created_at = peewee.DateTimeField()
  275. claimed_by = peewee.ForeignKeyField(User, null=True)
  276. claimed_at = peewee.DateTimeField(null=True)
  277. @staticmethod
  278. def by_code(token: str) -> "UserInvite":
  279. if (u := UserInvite.get_or_none(token=token)) :
  280. return u
  281. raise e.NoSuchInvite(invite=token)
  282. @staticmethod
  283. def manufacture(creator: User) -> "UserInvite":
  284. now = datetime.datetime.now()
  285. token = c.serializer.dumps(
  286. {"created_at": now.timestamp(), "created_by": creator.name,}
  287. )
  288. return UserInvite.create(
  289. token=token,
  290. created_by=creator,
  291. created_at=now,
  292. claimed_by=None,
  293. claimed_at=None,
  294. )
  295. MODELS = [
  296. User,
  297. Link,
  298. Tag,
  299. HasTag,
  300. UserInvite,
  301. ]
  302. def create_tables():
  303. c.db.create_tables(MODELS, safe=True)