chats.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. created_at = DateTimeField()
  18. updated_at = DateTimeField()
  19. share_id = CharField(null=True, unique=True)
  20. archived = BooleanField(default=False)
  21. class Meta:
  22. database = DB
  23. class ChatModel(BaseModel):
  24. id: str
  25. user_id: str
  26. title: str
  27. chat: str
  28. created_at: int # timestamp in epoch
  29. updated_at: int # timestamp in epoch
  30. share_id: Optional[str] = None
  31. archived: bool = False
  32. ####################
  33. # Forms
  34. ####################
  35. class ChatForm(BaseModel):
  36. chat: dict
  37. class ChatTitleForm(BaseModel):
  38. title: str
  39. class ChatResponse(BaseModel):
  40. id: str
  41. user_id: str
  42. title: str
  43. chat: dict
  44. updated_at: int # timestamp in epoch
  45. created_at: int # timestamp in epoch
  46. share_id: Optional[str] = None # id of the chat to be shared
  47. class ChatTitleIdResponse(BaseModel):
  48. id: str
  49. title: str
  50. updated_at: int
  51. created_at: int
  52. class ChatTable:
  53. def __init__(self, db):
  54. self.db = db
  55. db.create_tables([Chat])
  56. def insert_new_chat(self, user_id: str, form_data: ChatForm) -> Optional[ChatModel]:
  57. id = str(uuid.uuid4())
  58. chat = ChatModel(
  59. **{
  60. "id": id,
  61. "user_id": user_id,
  62. "title": (
  63. form_data.chat["title"] if "title" in form_data.chat else "New Chat"
  64. ),
  65. "chat": json.dumps(form_data.chat),
  66. "created_at": int(time.time()),
  67. "updated_at": int(time.time()),
  68. }
  69. )
  70. result = Chat.create(**chat.model_dump())
  71. return chat if result else None
  72. def update_chat_by_id(self, id: str, chat: dict) -> Optional[ChatModel]:
  73. try:
  74. query = Chat.update(
  75. chat=json.dumps(chat),
  76. title=chat["title"] if "title" in chat else "New Chat",
  77. updated_at=int(time.time()),
  78. ).where(Chat.id == id)
  79. query.execute()
  80. chat = Chat.get(Chat.id == id)
  81. return ChatModel(**model_to_dict(chat))
  82. except:
  83. return None
  84. def insert_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
  85. # Get the existing chat to share
  86. chat = Chat.get(Chat.id == chat_id)
  87. # Check if the chat is already shared
  88. if chat.share_id:
  89. return self.get_chat_by_id_and_user_id(chat.share_id, "shared")
  90. # Create a new chat with the same data, but with a new ID
  91. shared_chat = ChatModel(
  92. **{
  93. "id": str(uuid.uuid4()),
  94. "user_id": f"shared-{chat_id}",
  95. "title": chat.title,
  96. "chat": chat.chat,
  97. "created_at": chat.created_at,
  98. "updated_at": int(time.time()),
  99. }
  100. )
  101. shared_result = Chat.create(**shared_chat.model_dump())
  102. # Update the original chat with the share_id
  103. result = (
  104. Chat.update(share_id=shared_chat.id).where(Chat.id == chat_id).execute()
  105. )
  106. return shared_chat if (shared_result and result) else None
  107. def update_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
  108. try:
  109. print("update_shared_chat_by_id")
  110. chat = Chat.get(Chat.id == chat_id)
  111. print(chat)
  112. query = Chat.update(
  113. title=chat.title,
  114. chat=chat.chat,
  115. ).where(Chat.id == chat.share_id)
  116. query.execute()
  117. chat = Chat.get(Chat.id == chat.share_id)
  118. return ChatModel(**model_to_dict(chat))
  119. except:
  120. return None
  121. def delete_shared_chat_by_chat_id(self, chat_id: str) -> bool:
  122. try:
  123. query = Chat.delete().where(Chat.user_id == f"shared-{chat_id}")
  124. query.execute() # Remove the rows, return number of rows removed.
  125. return True
  126. except:
  127. return False
  128. def update_chat_share_id_by_id(
  129. self, id: str, share_id: Optional[str]
  130. ) -> Optional[ChatModel]:
  131. try:
  132. query = Chat.update(
  133. share_id=share_id,
  134. ).where(Chat.id == id)
  135. query.execute()
  136. chat = Chat.get(Chat.id == id)
  137. return ChatModel(**model_to_dict(chat))
  138. except:
  139. return None
  140. def toggle_chat_archive_by_id(self, id: str) -> Optional[ChatModel]:
  141. try:
  142. chat = self.get_chat_by_id(id)
  143. query = Chat.update(
  144. archived=(not chat.archived),
  145. ).where(Chat.id == id)
  146. query.execute()
  147. chat = Chat.get(Chat.id == id)
  148. return ChatModel(**model_to_dict(chat))
  149. except:
  150. return None
  151. def get_archived_chat_lists_by_user_id(
  152. self, user_id: str, skip: int = 0, limit: int = 50
  153. ) -> List[ChatModel]:
  154. return [
  155. ChatModel(**model_to_dict(chat))
  156. for chat in Chat.select()
  157. .where(Chat.archived == True)
  158. .where(Chat.user_id == user_id)
  159. .order_by(Chat.updated_at.desc())
  160. # .limit(limit)
  161. # .offset(skip)
  162. ]
  163. def get_chat_lists_by_user_id(
  164. self, user_id: str, skip: int = 0, limit: int = 50
  165. ) -> List[ChatModel]:
  166. return [
  167. ChatModel(**model_to_dict(chat))
  168. for chat in Chat.select()
  169. .where(Chat.archived == False)
  170. .where(Chat.user_id == user_id)
  171. .order_by(Chat.updated_at.desc())
  172. # .limit(limit)
  173. # .offset(skip)
  174. ]
  175. def get_chat_lists_by_chat_ids(
  176. self, chat_ids: List[str], skip: int = 0, limit: int = 50
  177. ) -> List[ChatModel]:
  178. return [
  179. ChatModel(**model_to_dict(chat))
  180. for chat in Chat.select()
  181. .where(Chat.archived == False)
  182. .where(Chat.id.in_(chat_ids))
  183. .order_by(Chat.updated_at.desc())
  184. ]
  185. def get_all_chats(self) -> List[ChatModel]:
  186. return [
  187. ChatModel(**model_to_dict(chat))
  188. for chat in Chat.select().order_by(Chat.updated_at.desc())
  189. ]
  190. def get_all_chats_by_user_id(self, user_id: str) -> List[ChatModel]:
  191. return [
  192. ChatModel(**model_to_dict(chat))
  193. for chat in Chat.select()
  194. .where(Chat.user_id == user_id)
  195. .order_by(Chat.updated_at.desc())
  196. ]
  197. def get_chat_by_id(self, id: str) -> Optional[ChatModel]:
  198. try:
  199. chat = Chat.get(Chat.id == id)
  200. return ChatModel(**model_to_dict(chat))
  201. except:
  202. return None
  203. def get_chat_by_share_id(self, id: str) -> Optional[ChatModel]:
  204. try:
  205. chat = Chat.get(Chat.share_id == id)
  206. if chat:
  207. chat = Chat.get(Chat.id == id)
  208. return ChatModel(**model_to_dict(chat))
  209. else:
  210. return None
  211. except:
  212. return None
  213. def get_chat_by_id_and_user_id(self, id: str, user_id: str) -> Optional[ChatModel]:
  214. try:
  215. chat = Chat.get(Chat.id == id, Chat.user_id == user_id)
  216. return ChatModel(**model_to_dict(chat))
  217. except:
  218. return None
  219. def get_chats(self, skip: int = 0, limit: int = 50) -> List[ChatModel]:
  220. return [
  221. ChatModel(**model_to_dict(chat))
  222. for chat in Chat.select().limit(limit).offset(skip)
  223. ]
  224. def delete_chat_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  225. try:
  226. query = Chat.delete().where((Chat.id == id) & (Chat.user_id == user_id))
  227. query.execute() # Remove the rows, return number of rows removed.
  228. return True and self.delete_shared_chat_by_chat_id(id)
  229. except:
  230. return False
  231. def delete_chats_by_user_id(self, user_id: str) -> bool:
  232. try:
  233. self.delete_shared_chats_by_user_id(user_id)
  234. query = Chat.delete().where(Chat.user_id == user_id)
  235. query.execute() # Remove the rows, return number of rows removed.
  236. return True
  237. except:
  238. return False
  239. def delete_shared_chats_by_user_id(self, user_id: str) -> bool:
  240. try:
  241. shared_chat_ids = [
  242. f"shared-{chat.id}"
  243. for chat in Chat.select().where(Chat.user_id == user_id)
  244. ]
  245. query = Chat.delete().where(Chat.user_id << shared_chat_ids)
  246. query.execute() # Remove the rows, return number of rows removed.
  247. return True
  248. except:
  249. return False
  250. Chats = ChatTable(DB)