chats.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. import json
  2. import logging
  3. from typing import Optional
  4. from open_webui.socket.main import get_event_emitter
  5. from open_webui.models.chats import (
  6. ChatForm,
  7. ChatImportForm,
  8. ChatResponse,
  9. Chats,
  10. ChatTitleIdResponse,
  11. )
  12. from open_webui.models.tags import TagModel, Tags
  13. from open_webui.models.folders import Folders
  14. from open_webui.config import ENABLE_ADMIN_CHAT_ACCESS, ENABLE_ADMIN_EXPORT
  15. from open_webui.constants import ERROR_MESSAGES
  16. from open_webui.env import SRC_LOG_LEVELS
  17. from fastapi import APIRouter, Depends, HTTPException, Request, status
  18. from pydantic import BaseModel
  19. from open_webui.utils.auth import get_admin_user, get_verified_user
  20. from open_webui.utils.access_control import has_permission
  21. log = logging.getLogger(__name__)
  22. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  23. router = APIRouter()
  24. ############################
  25. # GetChatList
  26. ############################
  27. @router.get("/", response_model=list[ChatTitleIdResponse])
  28. @router.get("/list", response_model=list[ChatTitleIdResponse])
  29. async def get_session_user_chat_list(
  30. user=Depends(get_verified_user), page: Optional[int] = None
  31. ):
  32. if page is not None:
  33. limit = 60
  34. skip = (page - 1) * limit
  35. return Chats.get_chat_title_id_list_by_user_id(user.id, skip=skip, limit=limit)
  36. else:
  37. return Chats.get_chat_title_id_list_by_user_id(user.id)
  38. ############################
  39. # DeleteAllChats
  40. ############################
  41. @router.delete("/", response_model=bool)
  42. async def delete_all_user_chats(request: Request, user=Depends(get_verified_user)):
  43. if user.role == "user" and not has_permission(
  44. user.id, "chat.delete", request.app.state.config.USER_PERMISSIONS
  45. ):
  46. raise HTTPException(
  47. status_code=status.HTTP_401_UNAUTHORIZED,
  48. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  49. )
  50. result = Chats.delete_chats_by_user_id(user.id)
  51. return result
  52. ############################
  53. # GetUserChatList
  54. ############################
  55. @router.get("/list/user/{user_id}", response_model=list[ChatTitleIdResponse])
  56. async def get_user_chat_list_by_user_id(
  57. user_id: str,
  58. page: Optional[int] = None,
  59. query: Optional[str] = None,
  60. order_by: Optional[str] = None,
  61. direction: Optional[str] = None,
  62. user=Depends(get_admin_user),
  63. ):
  64. if not ENABLE_ADMIN_CHAT_ACCESS:
  65. raise HTTPException(
  66. status_code=status.HTTP_401_UNAUTHORIZED,
  67. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  68. )
  69. if page is None:
  70. page = 1
  71. limit = 60
  72. skip = (page - 1) * limit
  73. filter = {}
  74. if query:
  75. filter["query"] = query
  76. if order_by:
  77. filter["order_by"] = order_by
  78. if direction:
  79. filter["direction"] = direction
  80. return Chats.get_chat_list_by_user_id(
  81. user_id, include_archived=True, filter=filter, skip=skip, limit=limit
  82. )
  83. ############################
  84. # CreateNewChat
  85. ############################
  86. @router.post("/new", response_model=Optional[ChatResponse])
  87. async def create_new_chat(form_data: ChatForm, user=Depends(get_verified_user)):
  88. try:
  89. chat = Chats.insert_new_chat(user.id, form_data)
  90. return ChatResponse(**chat.model_dump())
  91. except Exception as e:
  92. log.exception(e)
  93. raise HTTPException(
  94. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  95. )
  96. ############################
  97. # ImportChat
  98. ############################
  99. @router.post("/import", response_model=Optional[ChatResponse])
  100. async def import_chat(form_data: ChatImportForm, user=Depends(get_verified_user)):
  101. try:
  102. chat = Chats.import_chat(user.id, form_data)
  103. if chat:
  104. tags = chat.meta.get("tags", [])
  105. for tag_id in tags:
  106. tag_id = tag_id.replace(" ", "_").lower()
  107. tag_name = " ".join([word.capitalize() for word in tag_id.split("_")])
  108. if (
  109. tag_id != "none"
  110. and Tags.get_tag_by_name_and_user_id(tag_name, user.id) is None
  111. ):
  112. Tags.insert_new_tag(tag_name, user.id)
  113. return ChatResponse(**chat.model_dump())
  114. except Exception as e:
  115. log.exception(e)
  116. raise HTTPException(
  117. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  118. )
  119. ############################
  120. # GetChats
  121. ############################
  122. @router.get("/search", response_model=list[ChatTitleIdResponse])
  123. async def search_user_chats(
  124. text: str, page: Optional[int] = None, user=Depends(get_verified_user)
  125. ):
  126. if page is None:
  127. page = 1
  128. limit = 60
  129. skip = (page - 1) * limit
  130. chat_list = [
  131. ChatTitleIdResponse(**chat.model_dump())
  132. for chat in Chats.get_chats_by_user_id_and_search_text(
  133. user.id, text, skip=skip, limit=limit
  134. )
  135. ]
  136. # Delete tag if no chat is found
  137. words = text.strip().split(" ")
  138. if page == 1 and len(words) == 1 and words[0].startswith("tag:"):
  139. tag_id = words[0].replace("tag:", "")
  140. if len(chat_list) == 0:
  141. if Tags.get_tag_by_name_and_user_id(tag_id, user.id):
  142. log.debug(f"deleting tag: {tag_id}")
  143. Tags.delete_tag_by_name_and_user_id(tag_id, user.id)
  144. return chat_list
  145. ############################
  146. # GetChatsByFolderId
  147. ############################
  148. @router.get("/folder/{folder_id}", response_model=list[ChatResponse])
  149. async def get_chats_by_folder_id(folder_id: str, user=Depends(get_verified_user)):
  150. folder_ids = [folder_id]
  151. children_folders = Folders.get_children_folders_by_id_and_user_id(
  152. folder_id, user.id
  153. )
  154. if children_folders:
  155. folder_ids.extend([folder.id for folder in children_folders])
  156. return [
  157. ChatResponse(**chat.model_dump())
  158. for chat in Chats.get_chats_by_folder_ids_and_user_id(folder_ids, user.id)
  159. ]
  160. ############################
  161. # GetPinnedChats
  162. ############################
  163. @router.get("/pinned", response_model=list[ChatTitleIdResponse])
  164. async def get_user_pinned_chats(user=Depends(get_verified_user)):
  165. return [
  166. ChatTitleIdResponse(**chat.model_dump())
  167. for chat in Chats.get_pinned_chats_by_user_id(user.id)
  168. ]
  169. ############################
  170. # GetChats
  171. ############################
  172. @router.get("/all", response_model=list[ChatResponse])
  173. async def get_user_chats(user=Depends(get_verified_user)):
  174. return [
  175. ChatResponse(**chat.model_dump())
  176. for chat in Chats.get_chats_by_user_id(user.id)
  177. ]
  178. ############################
  179. # GetArchivedChats
  180. ############################
  181. @router.get("/all/archived", response_model=list[ChatResponse])
  182. async def get_user_archived_chats(user=Depends(get_verified_user)):
  183. return [
  184. ChatResponse(**chat.model_dump())
  185. for chat in Chats.get_archived_chats_by_user_id(user.id)
  186. ]
  187. ############################
  188. # GetAllTags
  189. ############################
  190. @router.get("/all/tags", response_model=list[TagModel])
  191. async def get_all_user_tags(user=Depends(get_verified_user)):
  192. try:
  193. tags = Tags.get_tags_by_user_id(user.id)
  194. return tags
  195. except Exception as e:
  196. log.exception(e)
  197. raise HTTPException(
  198. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  199. )
  200. ############################
  201. # GetAllChatsInDB
  202. ############################
  203. @router.get("/all/db", response_model=list[ChatResponse])
  204. async def get_all_user_chats_in_db(user=Depends(get_admin_user)):
  205. if not ENABLE_ADMIN_EXPORT:
  206. raise HTTPException(
  207. status_code=status.HTTP_401_UNAUTHORIZED,
  208. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  209. )
  210. return [ChatResponse(**chat.model_dump()) for chat in Chats.get_chats()]
  211. ############################
  212. # GetArchivedChats
  213. ############################
  214. @router.get("/archived", response_model=list[ChatTitleIdResponse])
  215. async def get_archived_session_user_chat_list(
  216. page: Optional[int] = None,
  217. query: Optional[str] = None,
  218. order_by: Optional[str] = None,
  219. direction: Optional[str] = None,
  220. user=Depends(get_verified_user),
  221. ):
  222. if page is None:
  223. page = 1
  224. limit = 60
  225. skip = (page - 1) * limit
  226. filter = {}
  227. if query:
  228. filter["query"] = query
  229. if order_by:
  230. filter["order_by"] = order_by
  231. if direction:
  232. filter["direction"] = direction
  233. chat_list = [
  234. ChatTitleIdResponse(**chat.model_dump())
  235. for chat in Chats.get_archived_chat_list_by_user_id(
  236. user.id,
  237. filter=filter,
  238. skip=skip,
  239. limit=limit,
  240. )
  241. ]
  242. return chat_list
  243. ############################
  244. # ArchiveAllChats
  245. ############################
  246. @router.post("/archive/all", response_model=bool)
  247. async def archive_all_chats(user=Depends(get_verified_user)):
  248. return Chats.archive_all_chats_by_user_id(user.id)
  249. ############################
  250. # GetSharedChatById
  251. ############################
  252. @router.get("/share/{share_id}", response_model=Optional[ChatResponse])
  253. async def get_shared_chat_by_id(share_id: str, user=Depends(get_verified_user)):
  254. if user.role == "pending":
  255. raise HTTPException(
  256. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  257. )
  258. if user.role == "user" or (user.role == "admin" and not ENABLE_ADMIN_CHAT_ACCESS):
  259. chat = Chats.get_chat_by_share_id(share_id)
  260. elif user.role == "admin" and ENABLE_ADMIN_CHAT_ACCESS:
  261. chat = Chats.get_chat_by_id(share_id)
  262. if chat:
  263. return ChatResponse(**chat.model_dump())
  264. else:
  265. raise HTTPException(
  266. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  267. )
  268. ############################
  269. # GetChatsByTags
  270. ############################
  271. class TagForm(BaseModel):
  272. name: str
  273. class TagFilterForm(TagForm):
  274. skip: Optional[int] = 0
  275. limit: Optional[int] = 50
  276. @router.post("/tags", response_model=list[ChatTitleIdResponse])
  277. async def get_user_chat_list_by_tag_name(
  278. form_data: TagFilterForm, user=Depends(get_verified_user)
  279. ):
  280. chats = Chats.get_chat_list_by_user_id_and_tag_name(
  281. user.id, form_data.name, form_data.skip, form_data.limit
  282. )
  283. if len(chats) == 0:
  284. Tags.delete_tag_by_name_and_user_id(form_data.name, user.id)
  285. return chats
  286. ############################
  287. # GetChatById
  288. ############################
  289. @router.get("/{id}", response_model=Optional[ChatResponse])
  290. async def get_chat_by_id(id: str, user=Depends(get_verified_user)):
  291. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  292. if chat:
  293. return ChatResponse(**chat.model_dump())
  294. else:
  295. raise HTTPException(
  296. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  297. )
  298. ############################
  299. # UpdateChatById
  300. ############################
  301. @router.post("/{id}", response_model=Optional[ChatResponse])
  302. async def update_chat_by_id(
  303. id: str, form_data: ChatForm, user=Depends(get_verified_user)
  304. ):
  305. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  306. if chat:
  307. updated_chat = {**chat.chat, **form_data.chat}
  308. chat = Chats.update_chat_by_id(id, updated_chat)
  309. return ChatResponse(**chat.model_dump())
  310. else:
  311. raise HTTPException(
  312. status_code=status.HTTP_401_UNAUTHORIZED,
  313. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  314. )
  315. ############################
  316. # UpdateChatMessageById
  317. ############################
  318. class MessageForm(BaseModel):
  319. content: str
  320. @router.post("/{id}/messages/{message_id}", response_model=Optional[ChatResponse])
  321. async def update_chat_message_by_id(
  322. id: str, message_id: str, form_data: MessageForm, user=Depends(get_verified_user)
  323. ):
  324. chat = Chats.get_chat_by_id(id)
  325. if not chat:
  326. raise HTTPException(
  327. status_code=status.HTTP_401_UNAUTHORIZED,
  328. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  329. )
  330. if chat.user_id != user.id and user.role != "admin":
  331. raise HTTPException(
  332. status_code=status.HTTP_401_UNAUTHORIZED,
  333. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  334. )
  335. chat = Chats.upsert_message_to_chat_by_id_and_message_id(
  336. id,
  337. message_id,
  338. {
  339. "content": form_data.content,
  340. },
  341. )
  342. event_emitter = get_event_emitter(
  343. {
  344. "user_id": user.id,
  345. "chat_id": id,
  346. "message_id": message_id,
  347. },
  348. False,
  349. )
  350. if event_emitter:
  351. await event_emitter(
  352. {
  353. "type": "chat:message",
  354. "data": {
  355. "chat_id": id,
  356. "message_id": message_id,
  357. "content": form_data.content,
  358. },
  359. }
  360. )
  361. return ChatResponse(**chat.model_dump())
  362. ############################
  363. # SendChatMessageEventById
  364. ############################
  365. class EventForm(BaseModel):
  366. type: str
  367. data: dict
  368. @router.post("/{id}/messages/{message_id}/event", response_model=Optional[bool])
  369. async def send_chat_message_event_by_id(
  370. id: str, message_id: str, form_data: EventForm, user=Depends(get_verified_user)
  371. ):
  372. chat = Chats.get_chat_by_id(id)
  373. if not chat:
  374. raise HTTPException(
  375. status_code=status.HTTP_401_UNAUTHORIZED,
  376. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  377. )
  378. if chat.user_id != user.id and user.role != "admin":
  379. raise HTTPException(
  380. status_code=status.HTTP_401_UNAUTHORIZED,
  381. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  382. )
  383. event_emitter = get_event_emitter(
  384. {
  385. "user_id": user.id,
  386. "chat_id": id,
  387. "message_id": message_id,
  388. }
  389. )
  390. try:
  391. if event_emitter:
  392. await event_emitter(form_data.model_dump())
  393. else:
  394. return False
  395. return True
  396. except:
  397. return False
  398. ############################
  399. # DeleteChatById
  400. ############################
  401. @router.delete("/{id}", response_model=bool)
  402. async def delete_chat_by_id(request: Request, id: str, user=Depends(get_verified_user)):
  403. if user.role == "admin":
  404. chat = Chats.get_chat_by_id(id)
  405. for tag in chat.meta.get("tags", []):
  406. if Chats.count_chats_by_tag_name_and_user_id(tag, user.id) == 1:
  407. Tags.delete_tag_by_name_and_user_id(tag, user.id)
  408. result = Chats.delete_chat_by_id(id)
  409. return result
  410. else:
  411. if not has_permission(
  412. user.id, "chat.delete", request.app.state.config.USER_PERMISSIONS
  413. ):
  414. raise HTTPException(
  415. status_code=status.HTTP_401_UNAUTHORIZED,
  416. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  417. )
  418. chat = Chats.get_chat_by_id(id)
  419. for tag in chat.meta.get("tags", []):
  420. if Chats.count_chats_by_tag_name_and_user_id(tag, user.id) == 1:
  421. Tags.delete_tag_by_name_and_user_id(tag, user.id)
  422. result = Chats.delete_chat_by_id_and_user_id(id, user.id)
  423. return result
  424. ############################
  425. # GetPinnedStatusById
  426. ############################
  427. @router.get("/{id}/pinned", response_model=Optional[bool])
  428. async def get_pinned_status_by_id(id: str, user=Depends(get_verified_user)):
  429. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  430. if chat:
  431. return chat.pinned
  432. else:
  433. raise HTTPException(
  434. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  435. )
  436. ############################
  437. # PinChatById
  438. ############################
  439. @router.post("/{id}/pin", response_model=Optional[ChatResponse])
  440. async def pin_chat_by_id(id: str, user=Depends(get_verified_user)):
  441. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  442. if chat:
  443. chat = Chats.toggle_chat_pinned_by_id(id)
  444. return chat
  445. else:
  446. raise HTTPException(
  447. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  448. )
  449. ############################
  450. # CloneChat
  451. ############################
  452. class CloneForm(BaseModel):
  453. title: Optional[str] = None
  454. @router.post("/{id}/clone", response_model=Optional[ChatResponse])
  455. async def clone_chat_by_id(
  456. form_data: CloneForm, id: str, user=Depends(get_verified_user)
  457. ):
  458. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  459. if chat:
  460. updated_chat = {
  461. **chat.chat,
  462. "originalChatId": chat.id,
  463. "branchPointMessageId": chat.chat["history"]["currentId"],
  464. "title": form_data.title if form_data.title else f"Clone of {chat.title}",
  465. }
  466. chat = Chats.insert_new_chat(user.id, ChatForm(**{"chat": updated_chat}))
  467. return ChatResponse(**chat.model_dump())
  468. else:
  469. raise HTTPException(
  470. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  471. )
  472. ############################
  473. # CloneSharedChatById
  474. ############################
  475. @router.post("/{id}/clone/shared", response_model=Optional[ChatResponse])
  476. async def clone_shared_chat_by_id(id: str, user=Depends(get_verified_user)):
  477. if user.role == "admin":
  478. chat = Chats.get_chat_by_id(id)
  479. else:
  480. chat = Chats.get_chat_by_share_id(id)
  481. if chat:
  482. updated_chat = {
  483. **chat.chat,
  484. "originalChatId": chat.id,
  485. "branchPointMessageId": chat.chat["history"]["currentId"],
  486. "title": f"Clone of {chat.title}",
  487. }
  488. chat = Chats.insert_new_chat(user.id, ChatForm(**{"chat": updated_chat}))
  489. return ChatResponse(**chat.model_dump())
  490. else:
  491. raise HTTPException(
  492. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  493. )
  494. ############################
  495. # ArchiveChat
  496. ############################
  497. @router.post("/{id}/archive", response_model=Optional[ChatResponse])
  498. async def archive_chat_by_id(id: str, user=Depends(get_verified_user)):
  499. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  500. if chat:
  501. chat = Chats.toggle_chat_archive_by_id(id)
  502. # Delete tags if chat is archived
  503. if chat.archived:
  504. for tag_id in chat.meta.get("tags", []):
  505. if Chats.count_chats_by_tag_name_and_user_id(tag_id, user.id) == 0:
  506. log.debug(f"deleting tag: {tag_id}")
  507. Tags.delete_tag_by_name_and_user_id(tag_id, user.id)
  508. else:
  509. for tag_id in chat.meta.get("tags", []):
  510. tag = Tags.get_tag_by_name_and_user_id(tag_id, user.id)
  511. if tag is None:
  512. log.debug(f"inserting tag: {tag_id}")
  513. tag = Tags.insert_new_tag(tag_id, user.id)
  514. return ChatResponse(**chat.model_dump())
  515. else:
  516. raise HTTPException(
  517. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  518. )
  519. ############################
  520. # ShareChatById
  521. ############################
  522. @router.post("/{id}/share", response_model=Optional[ChatResponse])
  523. async def share_chat_by_id(request: Request, id: str, user=Depends(get_verified_user)):
  524. if not has_permission(
  525. user.id, "chat.share", request.app.state.config.USER_PERMISSIONS
  526. ):
  527. raise HTTPException(
  528. status_code=status.HTTP_401_UNAUTHORIZED,
  529. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  530. )
  531. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  532. if chat:
  533. if chat.share_id:
  534. shared_chat = Chats.update_shared_chat_by_chat_id(chat.id)
  535. return ChatResponse(**shared_chat.model_dump())
  536. shared_chat = Chats.insert_shared_chat_by_chat_id(chat.id)
  537. if not shared_chat:
  538. raise HTTPException(
  539. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  540. detail=ERROR_MESSAGES.DEFAULT(),
  541. )
  542. return ChatResponse(**shared_chat.model_dump())
  543. else:
  544. raise HTTPException(
  545. status_code=status.HTTP_401_UNAUTHORIZED,
  546. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  547. )
  548. ############################
  549. # DeletedSharedChatById
  550. ############################
  551. @router.delete("/{id}/share", response_model=Optional[bool])
  552. async def delete_shared_chat_by_id(id: str, user=Depends(get_verified_user)):
  553. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  554. if chat:
  555. if not chat.share_id:
  556. return False
  557. result = Chats.delete_shared_chat_by_chat_id(id)
  558. update_result = Chats.update_chat_share_id_by_id(id, None)
  559. return result and update_result != None
  560. else:
  561. raise HTTPException(
  562. status_code=status.HTTP_401_UNAUTHORIZED,
  563. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  564. )
  565. ############################
  566. # UpdateChatFolderIdById
  567. ############################
  568. class ChatFolderIdForm(BaseModel):
  569. folder_id: Optional[str] = None
  570. @router.post("/{id}/folder", response_model=Optional[ChatResponse])
  571. async def update_chat_folder_id_by_id(
  572. id: str, form_data: ChatFolderIdForm, user=Depends(get_verified_user)
  573. ):
  574. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  575. if chat:
  576. chat = Chats.update_chat_folder_id_by_id_and_user_id(
  577. id, user.id, form_data.folder_id
  578. )
  579. return ChatResponse(**chat.model_dump())
  580. else:
  581. raise HTTPException(
  582. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  583. )
  584. ############################
  585. # GetChatTagsById
  586. ############################
  587. @router.get("/{id}/tags", response_model=list[TagModel])
  588. async def get_chat_tags_by_id(id: str, user=Depends(get_verified_user)):
  589. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  590. if chat:
  591. tags = chat.meta.get("tags", [])
  592. return Tags.get_tags_by_ids_and_user_id(tags, user.id)
  593. else:
  594. raise HTTPException(
  595. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  596. )
  597. ############################
  598. # AddChatTagById
  599. ############################
  600. @router.post("/{id}/tags", response_model=list[TagModel])
  601. async def add_tag_by_id_and_tag_name(
  602. id: str, form_data: TagForm, user=Depends(get_verified_user)
  603. ):
  604. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  605. if chat:
  606. tags = chat.meta.get("tags", [])
  607. tag_id = form_data.name.replace(" ", "_").lower()
  608. if tag_id == "none":
  609. raise HTTPException(
  610. status_code=status.HTTP_400_BAD_REQUEST,
  611. detail=ERROR_MESSAGES.DEFAULT("Tag name cannot be 'None'"),
  612. )
  613. if tag_id not in tags:
  614. Chats.add_chat_tag_by_id_and_user_id_and_tag_name(
  615. id, user.id, form_data.name
  616. )
  617. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  618. tags = chat.meta.get("tags", [])
  619. return Tags.get_tags_by_ids_and_user_id(tags, user.id)
  620. else:
  621. raise HTTPException(
  622. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  623. )
  624. ############################
  625. # DeleteChatTagById
  626. ############################
  627. @router.delete("/{id}/tags", response_model=list[TagModel])
  628. async def delete_tag_by_id_and_tag_name(
  629. id: str, form_data: TagForm, user=Depends(get_verified_user)
  630. ):
  631. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  632. if chat:
  633. Chats.delete_tag_by_id_and_user_id_and_tag_name(id, user.id, form_data.name)
  634. if Chats.count_chats_by_tag_name_and_user_id(form_data.name, user.id) == 0:
  635. Tags.delete_tag_by_name_and_user_id(form_data.name, user.id)
  636. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  637. tags = chat.meta.get("tags", [])
  638. return Tags.get_tags_by_ids_and_user_id(tags, user.id)
  639. else:
  640. raise HTTPException(
  641. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  642. )
  643. ############################
  644. # DeleteAllTagsById
  645. ############################
  646. @router.delete("/{id}/tags/all", response_model=Optional[bool])
  647. async def delete_all_tags_by_id(id: str, user=Depends(get_verified_user)):
  648. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  649. if chat:
  650. Chats.delete_all_tags_by_id_and_user_id(id, user.id)
  651. for tag in chat.meta.get("tags", []):
  652. if Chats.count_chats_by_tag_name_and_user_id(tag, user.id) == 0:
  653. Tags.delete_tag_by_name_and_user_id(tag, user.id)
  654. return True
  655. else:
  656. raise HTTPException(
  657. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  658. )