chats.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. from pydantic import BaseModel
  2. from typing import List, Union, Optional
  3. from peewee import *
  4. from playhouse.shortcuts import model_to_dict
  5. import json
  6. import uuid
  7. import time
  8. from apps.web.internal.db import DB
  9. ####################
  10. # Chat DB Schema
  11. ####################
  12. class Chat(Model):
  13. id = CharField(unique=True)
  14. user_id: CharField()
  15. title = CharField()
  16. chat = TextField() # Save Chat JSON as Text
  17. timestamp = DateField()
  18. class Meta:
  19. database = DB
  20. class ChatModel(BaseModel):
  21. id: str
  22. user_id: str
  23. title: str
  24. chat: dict
  25. timestamp: int # timestamp in epoch
  26. ####################
  27. # Forms
  28. ####################
  29. class ChatForm(BaseModel):
  30. chat: dict
  31. class ChatUpdateForm(ChatForm):
  32. id: str
  33. class ChatTitleIdResponse(BaseModel):
  34. id: str
  35. title: str
  36. class ChatTable:
  37. def __init__(self, db):
  38. self.db = db
  39. db.create_tables([Chat])
  40. def insert_new_chat(self, user_id: str, form_data: ChatForm) -> Optional[ChatModel]:
  41. id = str(uuid.uuid4())
  42. chat = ChatModel(
  43. **{
  44. "id": id,
  45. "user_id": user_id,
  46. "title": form_data.chat["title"],
  47. "chat": json.dump(form_data.chat),
  48. "timestamp": int(time.time()),
  49. }
  50. )
  51. result = Chat.create(**chat.model_dump())
  52. return chat if result else None
  53. def update_chat_by_id(self, id: str, chat: dict) -> Optional[ChatModel]:
  54. try:
  55. query = Chat.update(chat=json.dump(chat)).where(Chat.id == id)
  56. query.execute()
  57. chat = Chat.get(Chat.id == id)
  58. return ChatModel(**model_to_dict(chat))
  59. except:
  60. return None
  61. def get_chat_lists_by_user_id(
  62. self, user_id: str, skip: int = 0, limit: int = 50
  63. ) -> List[ChatModel]:
  64. return [
  65. ChatModel(**model_to_dict(chat))
  66. for chat in Chat.select(Chat.id, Chat.title)
  67. .where(Chat.user_id == user_id)
  68. .limit(limit)
  69. .offset(skip)
  70. ]
  71. def get_chat_by_id_and_user_id(self, id: str, user_id: str) -> Optional[ChatModel]:
  72. try:
  73. chat = Chat.get(Chat.id == id, Chat.user_id == user_id)
  74. return ChatModel(**model_to_dict(chat))
  75. except:
  76. return None
  77. def get_chats(self, skip: int = 0, limit: int = 50) -> List[ChatModel]:
  78. return [
  79. ChatModel(**model_to_dict(chat))
  80. for chat in Chat.select().limit(limit).offset(skip)
  81. ]
  82. Chats = ChatTable(DB)