model.py 12 KB

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