chats.py 8.9 KB

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