model.py 11 KB

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