model.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import datetime
  2. import peewee
  3. import lc.config
  4. import lc.requests as r
  5. class Model(peewee.Model):
  6. class Meta:
  7. database = lc.config.DB
  8. # TODO: figure out authorization for users (oauth? passwd?)
  9. class User(Model):
  10. """
  11. A user! you know tf this is about
  12. """
  13. name = peewee.TextField()
  14. class Link(Model):
  15. """
  16. A link as stored in the database
  17. """
  18. url = peewee.TextField()
  19. name = peewee.TextField()
  20. description = peewee.TextField()
  21. # TODO: do we need to track modified time?
  22. created = peewee.DateTimeField()
  23. # is the field entirely private?
  24. private = peewee.BooleanField()
  25. # owned by
  26. user = peewee.ForeignKeyField(User, backref="all_links")
  27. @staticmethod
  28. def from_request(user: User, link: r.Link) -> "Link":
  29. l = Link.create(
  30. url=link.url,
  31. name=link.name,
  32. description=link.description,
  33. private=link.private,
  34. created=datetime.datetime.now(),
  35. user=user,
  36. )
  37. for tag_name in link.tags:
  38. t = Tag.find_tag(tag_name)
  39. HasTag.create(
  40. link=l, tag=t,
  41. )
  42. return l
  43. class Tag(Model):
  44. """
  45. A tag. This just indicates that a user has used this tag at some point.
  46. """
  47. name = peewee.TextField()
  48. parent = peewee.ForeignKeyField("self", null=True, backref="children")
  49. user = peewee.ForeignKeyField(User, backref="tags")
  50. @staticmethod
  51. def find_tag(user: User, tag_name: str):
  52. if (t := Tag.get_or_none(name=tag_name, user=user)) :
  53. return t
  54. parent = None
  55. if "/" in tag_name:
  56. parent_name = tag_name[: tag_name.rindex("/")]
  57. parent = Tag.find_tag(user, parent_name)
  58. return Tag.create(name=tag_name, parent=parent, user=user,)
  59. class HasTag(Model):
  60. """
  61. Establishes that a link is tagged with a given tag.
  62. """
  63. link = peewee.ForeignKeyField(Link, backref="tags")
  64. tag = peewee.ForeignKeyField(Tag, backref="models")
  65. MODELS = [
  66. User,
  67. Link,
  68. Tag,
  69. HasTag,
  70. ]
  71. def create_tables():
  72. lc.config.DB.create_tables(MODELS, safe=True)