chats.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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_list_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_list_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_list_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_chat_by_id(self, id: str) -> Optional[ChatModel]:
  187. try:
  188. chat = Chat.get(Chat.id == id)
  189. return ChatModel(**model_to_dict(chat))
  190. except:
  191. return None
  192. def get_chat_by_share_id(self, id: str) -> Optional[ChatModel]:
  193. try:
  194. chat = Chat.get(Chat.share_id == id)
  195. if chat:
  196. chat = Chat.get(Chat.id == id)
  197. return ChatModel(**model_to_dict(chat))
  198. else:
  199. return None
  200. except:
  201. return None
  202. def get_chat_by_id_and_user_id(self, id: str, user_id: str) -> Optional[ChatModel]:
  203. try:
  204. chat = Chat.get(Chat.id == id, Chat.user_id == user_id)
  205. return ChatModel(**model_to_dict(chat))
  206. except:
  207. return None
  208. def get_chats(self, skip: int = 0, limit: int = 50) -> List[ChatModel]:
  209. return [
  210. ChatModel(**model_to_dict(chat))
  211. for chat in Chat.select().order_by(Chat.updated_at.desc())
  212. # .limit(limit).offset(skip)
  213. ]
  214. def get_chats_by_user_id(self, user_id: str) -> List[ChatModel]:
  215. return [
  216. ChatModel(**model_to_dict(chat))
  217. for chat in Chat.select()
  218. .where(Chat.user_id == user_id)
  219. .order_by(Chat.updated_at.desc())
  220. # .limit(limit).offset(skip)
  221. ]
  222. def delete_chat_by_id(self, id: str) -> bool:
  223. try:
  224. query = Chat.delete().where((Chat.id == id))
  225. query.execute() # Remove the rows, return number of rows removed.
  226. return True and self.delete_shared_chat_by_chat_id(id)
  227. except:
  228. return False
  229. def delete_chat_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  230. try:
  231. query = Chat.delete().where((Chat.id == id) & (Chat.user_id == user_id))
  232. query.execute() # Remove the rows, return number of rows removed.
  233. return True and self.delete_shared_chat_by_chat_id(id)
  234. except:
  235. return False
  236. def delete_chats_by_user_id(self, user_id: str) -> bool:
  237. try:
  238. self.delete_shared_chats_by_user_id(user_id)
  239. query = Chat.delete().where(Chat.user_id == user_id)
  240. query.execute() # Remove the rows, return number of rows removed.
  241. return True
  242. except:
  243. return False
  244. def delete_shared_chats_by_user_id(self, user_id: str) -> bool:
  245. try:
  246. shared_chat_ids = [
  247. f"shared-{chat.id}"
  248. for chat in Chat.select().where(Chat.user_id == user_id)
  249. ]
  250. query = Chat.delete().where(Chat.user_id << shared_chat_ids)
  251. query.execute() # Remove the rows, return number of rows removed.
  252. return True
  253. except:
  254. return False
  255. Chats = ChatTable(DB)