chats.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. import json
  2. import time
  3. import uuid
  4. from typing import Optional
  5. from open_webui.apps.webui.internal.db import Base, get_db
  6. from open_webui.apps.webui.models.tags import TagModel, Tag, Tags
  7. from pydantic import BaseModel, ConfigDict
  8. from sqlalchemy import BigInteger, Boolean, Column, String, Text, JSON
  9. from sqlalchemy import or_, func, select, and_, text
  10. from sqlalchemy.sql import exists
  11. ####################
  12. # Chat DB Schema
  13. ####################
  14. class Chat(Base):
  15. __tablename__ = "chat"
  16. id = Column(String, primary_key=True)
  17. user_id = Column(String)
  18. title = Column(Text)
  19. chat = Column(JSON)
  20. created_at = Column(BigInteger)
  21. updated_at = Column(BigInteger)
  22. share_id = Column(Text, unique=True, nullable=True)
  23. archived = Column(Boolean, default=False)
  24. pinned = Column(Boolean, default=False, nullable=True)
  25. meta = Column(JSON, server_default="{}")
  26. folder_id = Column(Text, nullable=True)
  27. class ChatModel(BaseModel):
  28. model_config = ConfigDict(from_attributes=True)
  29. id: str
  30. user_id: str
  31. title: str
  32. chat: dict
  33. created_at: int # timestamp in epoch
  34. updated_at: int # timestamp in epoch
  35. share_id: Optional[str] = None
  36. archived: bool = False
  37. pinned: Optional[bool] = False
  38. meta: dict = {}
  39. folder_id: Optional[str] = None
  40. ####################
  41. # Forms
  42. ####################
  43. class ChatForm(BaseModel):
  44. chat: dict
  45. class ChatImportForm(ChatForm):
  46. pinned: Optional[bool] = False
  47. folder_id: Optional[str] = None
  48. class ChatTitleMessagesForm(BaseModel):
  49. title: str
  50. messages: list[dict]
  51. class ChatTitleForm(BaseModel):
  52. title: str
  53. class ChatResponse(BaseModel):
  54. id: str
  55. user_id: str
  56. title: str
  57. chat: dict
  58. updated_at: int # timestamp in epoch
  59. created_at: int # timestamp in epoch
  60. share_id: Optional[str] = None # id of the chat to be shared
  61. archived: bool
  62. pinned: Optional[bool] = False
  63. meta: dict = {}
  64. folder_id: Optional[str] = None
  65. class ChatTitleIdResponse(BaseModel):
  66. id: str
  67. title: str
  68. updated_at: int
  69. created_at: int
  70. class ChatTable:
  71. def insert_new_chat(self, user_id: str, form_data: ChatForm) -> Optional[ChatModel]:
  72. with get_db() as db:
  73. id = str(uuid.uuid4())
  74. chat = ChatModel(
  75. **{
  76. "id": id,
  77. "user_id": user_id,
  78. "title": (
  79. form_data.chat["title"]
  80. if "title" in form_data.chat
  81. else "New Chat"
  82. ),
  83. "chat": form_data.chat,
  84. "created_at": int(time.time()),
  85. "updated_at": int(time.time()),
  86. }
  87. )
  88. result = Chat(**chat.model_dump())
  89. db.add(result)
  90. db.commit()
  91. db.refresh(result)
  92. return ChatModel.model_validate(result) if result else None
  93. def import_chat(
  94. self, user_id: str, form_data: ChatImportForm
  95. ) -> Optional[ChatModel]:
  96. with get_db() as db:
  97. id = str(uuid.uuid4())
  98. chat = ChatModel(
  99. **{
  100. "id": id,
  101. "user_id": user_id,
  102. "title": (
  103. form_data.chat["title"]
  104. if "title" in form_data.chat
  105. else "New Chat"
  106. ),
  107. "chat": form_data.chat,
  108. "pinned": form_data.pinned,
  109. "folder_id": form_data.folder_id,
  110. "created_at": int(time.time()),
  111. "updated_at": int(time.time()),
  112. }
  113. )
  114. result = Chat(**chat.model_dump())
  115. db.add(result)
  116. db.commit()
  117. db.refresh(result)
  118. return ChatModel.model_validate(result) if result else None
  119. def update_chat_by_id(self, id: str, chat: dict) -> Optional[ChatModel]:
  120. try:
  121. with get_db() as db:
  122. chat_item = db.get(Chat, id)
  123. chat_item.chat = chat
  124. chat_item.title = chat["title"] if "title" in chat else "New Chat"
  125. chat_item.updated_at = int(time.time())
  126. db.commit()
  127. db.refresh(chat_item)
  128. return ChatModel.model_validate(chat_item)
  129. except Exception:
  130. return None
  131. def insert_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
  132. with get_db() as db:
  133. # Get the existing chat to share
  134. chat = db.get(Chat, chat_id)
  135. # Check if the chat is already shared
  136. if chat.share_id:
  137. return self.get_chat_by_id_and_user_id(chat.share_id, "shared")
  138. # Create a new chat with the same data, but with a new ID
  139. shared_chat = ChatModel(
  140. **{
  141. "id": str(uuid.uuid4()),
  142. "user_id": f"shared-{chat_id}",
  143. "title": chat.title,
  144. "chat": chat.chat,
  145. "created_at": chat.created_at,
  146. "updated_at": int(time.time()),
  147. }
  148. )
  149. shared_result = Chat(**shared_chat.model_dump())
  150. db.add(shared_result)
  151. db.commit()
  152. db.refresh(shared_result)
  153. # Update the original chat with the share_id
  154. result = (
  155. db.query(Chat)
  156. .filter_by(id=chat_id)
  157. .update({"share_id": shared_chat.id})
  158. )
  159. db.commit()
  160. return shared_chat if (shared_result and result) else None
  161. def update_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
  162. try:
  163. with get_db() as db:
  164. print("update_shared_chat_by_id")
  165. chat = db.get(Chat, chat_id)
  166. print(chat)
  167. chat.title = chat.title
  168. chat.chat = chat.chat
  169. db.commit()
  170. db.refresh(chat)
  171. return self.get_chat_by_id(chat.share_id)
  172. except Exception:
  173. return None
  174. def delete_shared_chat_by_chat_id(self, chat_id: str) -> bool:
  175. try:
  176. with get_db() as db:
  177. db.query(Chat).filter_by(user_id=f"shared-{chat_id}").delete()
  178. db.commit()
  179. return True
  180. except Exception:
  181. return False
  182. def update_chat_share_id_by_id(
  183. self, id: str, share_id: Optional[str]
  184. ) -> Optional[ChatModel]:
  185. try:
  186. with get_db() as db:
  187. chat = db.get(Chat, id)
  188. chat.share_id = share_id
  189. db.commit()
  190. db.refresh(chat)
  191. return ChatModel.model_validate(chat)
  192. except Exception:
  193. return None
  194. def toggle_chat_pinned_by_id(self, id: str) -> Optional[ChatModel]:
  195. try:
  196. with get_db() as db:
  197. chat = db.get(Chat, id)
  198. chat.pinned = not chat.pinned
  199. chat.updated_at = int(time.time())
  200. db.commit()
  201. db.refresh(chat)
  202. return ChatModel.model_validate(chat)
  203. except Exception:
  204. return None
  205. def toggle_chat_archive_by_id(self, id: str) -> Optional[ChatModel]:
  206. try:
  207. with get_db() as db:
  208. chat = db.get(Chat, id)
  209. chat.archived = not chat.archived
  210. chat.updated_at = int(time.time())
  211. db.commit()
  212. db.refresh(chat)
  213. return ChatModel.model_validate(chat)
  214. except Exception:
  215. return None
  216. def archive_all_chats_by_user_id(self, user_id: str) -> bool:
  217. try:
  218. with get_db() as db:
  219. db.query(Chat).filter_by(user_id=user_id).update({"archived": True})
  220. db.commit()
  221. return True
  222. except Exception:
  223. return False
  224. def get_archived_chat_list_by_user_id(
  225. self, user_id: str, skip: int = 0, limit: int = 50
  226. ) -> list[ChatModel]:
  227. with get_db() as db:
  228. all_chats = (
  229. db.query(Chat)
  230. .filter_by(user_id=user_id, archived=True)
  231. .order_by(Chat.updated_at.desc())
  232. # .limit(limit).offset(skip)
  233. .all()
  234. )
  235. return [ChatModel.model_validate(chat) for chat in all_chats]
  236. def get_chat_list_by_user_id(
  237. self,
  238. user_id: str,
  239. include_archived: bool = False,
  240. skip: int = 0,
  241. limit: int = 50,
  242. ) -> list[ChatModel]:
  243. with get_db() as db:
  244. query = db.query(Chat).filter_by(user_id=user_id).filter_by(folder_id=None)
  245. if not include_archived:
  246. query = query.filter_by(archived=False)
  247. query = query.order_by(Chat.updated_at.desc())
  248. if skip:
  249. query = query.offset(skip)
  250. if limit:
  251. query = query.limit(limit)
  252. all_chats = query.all()
  253. return [ChatModel.model_validate(chat) for chat in all_chats]
  254. def get_chat_title_id_list_by_user_id(
  255. self,
  256. user_id: str,
  257. include_archived: bool = False,
  258. skip: Optional[int] = None,
  259. limit: Optional[int] = None,
  260. ) -> list[ChatTitleIdResponse]:
  261. with get_db() as db:
  262. query = db.query(Chat).filter_by(user_id=user_id).filter_by(folder_id=None)
  263. query = query.filter(or_(Chat.pinned == False, Chat.pinned == None))
  264. if not include_archived:
  265. query = query.filter_by(archived=False)
  266. query = query.order_by(Chat.updated_at.desc()).with_entities(
  267. Chat.id, Chat.title, Chat.updated_at, Chat.created_at
  268. )
  269. if skip:
  270. query = query.offset(skip)
  271. if limit:
  272. query = query.limit(limit)
  273. all_chats = query.all()
  274. # result has to be destrctured from sqlalchemy `row` and mapped to a dict since the `ChatModel`is not the returned dataclass.
  275. return [
  276. ChatTitleIdResponse.model_validate(
  277. {
  278. "id": chat[0],
  279. "title": chat[1],
  280. "updated_at": chat[2],
  281. "created_at": chat[3],
  282. }
  283. )
  284. for chat in all_chats
  285. ]
  286. def get_chat_list_by_chat_ids(
  287. self, chat_ids: list[str], skip: int = 0, limit: int = 50
  288. ) -> list[ChatModel]:
  289. with get_db() as db:
  290. all_chats = (
  291. db.query(Chat)
  292. .filter(Chat.id.in_(chat_ids))
  293. .filter_by(archived=False)
  294. .order_by(Chat.updated_at.desc())
  295. .all()
  296. )
  297. return [ChatModel.model_validate(chat) for chat in all_chats]
  298. def get_chat_by_id(self, id: str) -> Optional[ChatModel]:
  299. try:
  300. with get_db() as db:
  301. chat = db.get(Chat, id)
  302. return ChatModel.model_validate(chat)
  303. except Exception:
  304. return None
  305. def get_chat_by_share_id(self, id: str) -> Optional[ChatModel]:
  306. try:
  307. with get_db() as db:
  308. chat = db.query(Chat).filter_by(share_id=id).first()
  309. if chat:
  310. return self.get_chat_by_id(id)
  311. else:
  312. return None
  313. except Exception:
  314. return None
  315. def get_chat_by_id_and_user_id(self, id: str, user_id: str) -> Optional[ChatModel]:
  316. try:
  317. with get_db() as db:
  318. chat = db.query(Chat).filter_by(id=id, user_id=user_id).first()
  319. return ChatModel.model_validate(chat)
  320. except Exception:
  321. return None
  322. def get_chats(self, skip: int = 0, limit: int = 50) -> list[ChatModel]:
  323. with get_db() as db:
  324. all_chats = (
  325. db.query(Chat)
  326. # .limit(limit).offset(skip)
  327. .order_by(Chat.updated_at.desc())
  328. )
  329. return [ChatModel.model_validate(chat) for chat in all_chats]
  330. def get_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  331. with get_db() as db:
  332. all_chats = (
  333. db.query(Chat)
  334. .filter_by(user_id=user_id)
  335. .order_by(Chat.updated_at.desc())
  336. )
  337. return [ChatModel.model_validate(chat) for chat in all_chats]
  338. def get_pinned_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  339. with get_db() as db:
  340. all_chats = (
  341. db.query(Chat)
  342. .filter_by(user_id=user_id, pinned=True, archived=False)
  343. .order_by(Chat.updated_at.desc())
  344. )
  345. return [ChatModel.model_validate(chat) for chat in all_chats]
  346. def get_archived_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  347. with get_db() as db:
  348. all_chats = (
  349. db.query(Chat)
  350. .filter_by(user_id=user_id, archived=True)
  351. .order_by(Chat.updated_at.desc())
  352. )
  353. return [ChatModel.model_validate(chat) for chat in all_chats]
  354. def get_chats_by_user_id_and_search_text(
  355. self,
  356. user_id: str,
  357. search_text: str,
  358. include_archived: bool = False,
  359. skip: int = 0,
  360. limit: int = 60,
  361. ) -> list[ChatModel]:
  362. """
  363. Filters chats based on a search query using Python, allowing pagination using skip and limit.
  364. """
  365. search_text = search_text.lower().strip()
  366. if not search_text:
  367. return self.get_chat_list_by_user_id(user_id, include_archived, skip, limit)
  368. search_text_words = search_text.split(" ")
  369. # search_text might contain 'tag:tag_name' format so we need to extract the tag_name, split the search_text and remove the tags
  370. tag_ids = [
  371. word.replace("tag:", "").replace(" ", "_").lower()
  372. for word in search_text_words
  373. if word.startswith("tag:")
  374. ]
  375. search_text_words = [
  376. word for word in search_text_words if not word.startswith("tag:")
  377. ]
  378. search_text = " ".join(search_text_words)
  379. with get_db() as db:
  380. query = db.query(Chat).filter(Chat.user_id == user_id)
  381. if not include_archived:
  382. query = query.filter(Chat.archived == False)
  383. query = query.order_by(Chat.updated_at.desc())
  384. # Check if the database dialect is either 'sqlite' or 'postgresql'
  385. dialect_name = db.bind.dialect.name
  386. if dialect_name == "sqlite":
  387. # SQLite case: using JSON1 extension for JSON searching
  388. query = query.filter(
  389. (
  390. Chat.title.ilike(
  391. f"%{search_text}%"
  392. ) # Case-insensitive search in title
  393. | text(
  394. """
  395. EXISTS (
  396. SELECT 1
  397. FROM json_each(Chat.chat, '$.messages') AS message
  398. WHERE LOWER(message.value->>'content') LIKE '%' || :search_text || '%'
  399. )
  400. """
  401. )
  402. ).params(search_text=search_text)
  403. )
  404. # Check if there are any tags to filter, it should have all the tags
  405. if tag_ids:
  406. query = query.filter(
  407. and_(
  408. *[
  409. text(
  410. f"""
  411. EXISTS (
  412. SELECT 1
  413. FROM json_each(Chat.meta, '$.tags') AS tag
  414. WHERE tag.value = :tag_id_{tag_idx}
  415. )
  416. """
  417. ).params(**{f"tag_id_{tag_idx}": tag_id})
  418. for tag_idx, tag_id in enumerate(tag_ids)
  419. ]
  420. )
  421. )
  422. elif dialect_name == "postgresql":
  423. # PostgreSQL relies on proper JSON query for search
  424. query = query.filter(
  425. (
  426. Chat.title.ilike(
  427. f"%{search_text}%"
  428. ) # Case-insensitive search in title
  429. | text(
  430. """
  431. EXISTS (
  432. SELECT 1
  433. FROM json_array_elements(Chat.chat->'messages') AS message
  434. WHERE LOWER(message->>'content') LIKE '%' || :search_text || '%'
  435. )
  436. """
  437. )
  438. ).params(search_text=search_text)
  439. )
  440. # Check if there are any tags to filter, it should have all the tags
  441. if tag_ids:
  442. query = query.filter(
  443. and_(
  444. *[
  445. text(
  446. f"""
  447. EXISTS (
  448. SELECT 1
  449. FROM json_array_elements_text(Chat.meta->'tags') AS tag
  450. WHERE tag = :tag_id_{tag_idx}
  451. )
  452. """
  453. ).params(**{f"tag_id_{tag_idx}": tag_id})
  454. for tag_idx, tag_id in enumerate(tag_ids)
  455. ]
  456. )
  457. )
  458. else:
  459. raise NotImplementedError(
  460. f"Unsupported dialect: {db.bind.dialect.name}"
  461. )
  462. # Perform pagination at the SQL level
  463. all_chats = query.offset(skip).limit(limit).all()
  464. print(len(all_chats))
  465. # Validate and return chats
  466. return [ChatModel.model_validate(chat) for chat in all_chats]
  467. def get_chats_by_folder_id_and_user_id(
  468. self, folder_id: str, user_id: str
  469. ) -> list[ChatModel]:
  470. with get_db() as db:
  471. query = db.query(Chat).filter_by(folder_id=folder_id, user_id=user_id)
  472. query = query.filter(or_(Chat.pinned == False, Chat.pinned == None))
  473. query = query.filter_by(archived=False)
  474. query = query.order_by(Chat.updated_at.desc())
  475. all_chats = query.all()
  476. return [ChatModel.model_validate(chat) for chat in all_chats]
  477. def update_chat_folder_id_by_id_and_user_id(
  478. self, id: str, user_id: str, folder_id: str
  479. ) -> Optional[ChatModel]:
  480. try:
  481. with get_db() as db:
  482. chat = db.get(Chat, id)
  483. chat.folder_id = folder_id
  484. chat.updated_at = int(time.time())
  485. chat.pinned = False
  486. db.commit()
  487. db.refresh(chat)
  488. return ChatModel.model_validate(chat)
  489. except Exception:
  490. return None
  491. def get_chat_tags_by_id_and_user_id(self, id: str, user_id: str) -> list[TagModel]:
  492. with get_db() as db:
  493. chat = db.get(Chat, id)
  494. tags = chat.meta.get("tags", [])
  495. return [Tags.get_tag_by_name_and_user_id(tag, user_id) for tag in tags]
  496. def get_chat_list_by_user_id_and_tag_name(
  497. self, user_id: str, tag_name: str, skip: int = 0, limit: int = 50
  498. ) -> list[ChatModel]:
  499. with get_db() as db:
  500. query = db.query(Chat).filter_by(user_id=user_id)
  501. tag_id = tag_name.replace(" ", "_").lower()
  502. print(db.bind.dialect.name)
  503. if db.bind.dialect.name == "sqlite":
  504. # SQLite JSON1 querying for tags within the meta JSON field
  505. query = query.filter(
  506. text(
  507. f"EXISTS (SELECT 1 FROM json_each(Chat.meta, '$.tags') WHERE json_each.value = :tag_id)"
  508. )
  509. ).params(tag_id=tag_id)
  510. elif db.bind.dialect.name == "postgresql":
  511. # PostgreSQL JSON query for tags within the meta JSON field (for `json` type)
  512. query = query.filter(
  513. text(
  514. "EXISTS (SELECT 1 FROM json_array_elements_text(Chat.meta->'tags') elem WHERE elem = :tag_id)"
  515. )
  516. ).params(tag_id=tag_id)
  517. else:
  518. raise NotImplementedError(
  519. f"Unsupported dialect: {db.bind.dialect.name}"
  520. )
  521. all_chats = query.all()
  522. print("all_chats", all_chats)
  523. return [ChatModel.model_validate(chat) for chat in all_chats]
  524. def add_chat_tag_by_id_and_user_id_and_tag_name(
  525. self, id: str, user_id: str, tag_name: str
  526. ) -> Optional[ChatModel]:
  527. tag = Tags.get_tag_by_name_and_user_id(tag_name, user_id)
  528. if tag is None:
  529. tag = Tags.insert_new_tag(tag_name, user_id)
  530. try:
  531. with get_db() as db:
  532. chat = db.get(Chat, id)
  533. tag_id = tag.id
  534. if tag_id not in chat.meta.get("tags", []):
  535. chat.meta = {
  536. **chat.meta,
  537. "tags": list(set(chat.meta.get("tags", []) + [tag_id])),
  538. }
  539. db.commit()
  540. db.refresh(chat)
  541. return ChatModel.model_validate(chat)
  542. except Exception:
  543. return None
  544. def count_chats_by_tag_name_and_user_id(self, tag_name: str, user_id: str) -> int:
  545. with get_db() as db: # Assuming `get_db()` returns a session object
  546. query = db.query(Chat).filter_by(user_id=user_id, archived=False)
  547. # Normalize the tag_name for consistency
  548. tag_id = tag_name.replace(" ", "_").lower()
  549. if db.bind.dialect.name == "sqlite":
  550. # SQLite JSON1 support for querying the tags inside the `meta` JSON field
  551. query = query.filter(
  552. text(
  553. f"EXISTS (SELECT 1 FROM json_each(Chat.meta, '$.tags') WHERE json_each.value = :tag_id)"
  554. )
  555. ).params(tag_id=tag_id)
  556. elif db.bind.dialect.name == "postgresql":
  557. # PostgreSQL JSONB support for querying the tags inside the `meta` JSON field
  558. query = query.filter(
  559. text(
  560. "EXISTS (SELECT 1 FROM json_array_elements_text(Chat.meta->'tags') elem WHERE elem = :tag_id)"
  561. )
  562. ).params(tag_id=tag_id)
  563. else:
  564. raise NotImplementedError(
  565. f"Unsupported dialect: {db.bind.dialect.name}"
  566. )
  567. # Get the count of matching records
  568. count = query.count()
  569. # Debugging output for inspection
  570. print(f"Count of chats for tag '{tag_name}':", count)
  571. return count
  572. def delete_tag_by_id_and_user_id_and_tag_name(
  573. self, id: str, user_id: str, tag_name: str
  574. ) -> bool:
  575. try:
  576. with get_db() as db:
  577. chat = db.get(Chat, id)
  578. tags = chat.meta.get("tags", [])
  579. tag_id = tag_name.replace(" ", "_").lower()
  580. tags = [tag for tag in tags if tag != tag_id]
  581. chat.meta = {
  582. **chat.meta,
  583. "tags": list(set(tags)),
  584. }
  585. db.commit()
  586. return True
  587. except Exception:
  588. return False
  589. def delete_all_tags_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  590. try:
  591. with get_db() as db:
  592. chat = db.get(Chat, id)
  593. chat.meta = {
  594. **chat.meta,
  595. "tags": [],
  596. }
  597. db.commit()
  598. return True
  599. except Exception:
  600. return False
  601. def delete_chat_by_id(self, id: str) -> bool:
  602. try:
  603. with get_db() as db:
  604. db.query(Chat).filter_by(id=id).delete()
  605. db.commit()
  606. return True and self.delete_shared_chat_by_chat_id(id)
  607. except Exception:
  608. return False
  609. def delete_chat_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  610. try:
  611. with get_db() as db:
  612. db.query(Chat).filter_by(id=id, user_id=user_id).delete()
  613. db.commit()
  614. return True and self.delete_shared_chat_by_chat_id(id)
  615. except Exception:
  616. return False
  617. def delete_chats_by_user_id(self, user_id: str) -> bool:
  618. try:
  619. with get_db() as db:
  620. self.delete_shared_chats_by_user_id(user_id)
  621. db.query(Chat).filter_by(user_id=user_id).delete()
  622. db.commit()
  623. return True
  624. except Exception:
  625. return False
  626. def delete_chats_by_user_id_and_folder_id(
  627. self, user_id: str, folder_id: str
  628. ) -> bool:
  629. try:
  630. with get_db() as db:
  631. db.query(Chat).filter_by(user_id=user_id, folder_id=folder_id).delete()
  632. db.commit()
  633. return True
  634. except Exception:
  635. return False
  636. def delete_shared_chats_by_user_id(self, user_id: str) -> bool:
  637. try:
  638. with get_db() as db:
  639. chats_by_user = db.query(Chat).filter_by(user_id=user_id).all()
  640. shared_chat_ids = [f"shared-{chat.id}" for chat in chats_by_user]
  641. db.query(Chat).filter(Chat.user_id.in_(shared_chat_ids)).delete()
  642. db.commit()
  643. return True
  644. except Exception:
  645. return False
  646. Chats = ChatTable()