chats.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. from fastapi import Depends, Request, HTTPException, status
  2. from datetime import datetime, timedelta
  3. from typing import List, Union, Optional
  4. from utils.utils import get_current_user, get_admin_user
  5. from fastapi import APIRouter
  6. from pydantic import BaseModel
  7. import json
  8. import logging
  9. from apps.web.models.users import Users
  10. from apps.web.models.chats import (
  11. ChatModel,
  12. ChatResponse,
  13. ChatTitleForm,
  14. ChatForm,
  15. ChatTitleIdResponse,
  16. Chats,
  17. )
  18. from apps.web.models.tags import (
  19. TagModel,
  20. ChatIdTagModel,
  21. ChatIdTagForm,
  22. ChatTagsResponse,
  23. Tags,
  24. )
  25. from constants import ERROR_MESSAGES
  26. from config import SRC_LOG_LEVELS, ENABLE_ADMIN_EXPORT
  27. log = logging.getLogger(__name__)
  28. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  29. router = APIRouter()
  30. ############################
  31. # GetChatList
  32. ############################
  33. @router.get("/", response_model=List[ChatTitleIdResponse])
  34. @router.get("/list", response_model=List[ChatTitleIdResponse])
  35. async def get_session_user_chat_list(
  36. user=Depends(get_current_user), skip: int = 0, limit: int = 50
  37. ):
  38. return Chats.get_chat_list_by_user_id(user.id, skip, limit)
  39. ############################
  40. # DeleteAllChats
  41. ############################
  42. @router.delete("/", response_model=bool)
  43. async def delete_all_user_chats(request: Request, user=Depends(get_current_user)):
  44. if (
  45. user.role == "user"
  46. and not request.app.state.USER_PERMISSIONS["chat"]["deletion"]
  47. ):
  48. raise HTTPException(
  49. status_code=status.HTTP_401_UNAUTHORIZED,
  50. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  51. )
  52. result = Chats.delete_chats_by_user_id(user.id)
  53. return result
  54. ############################
  55. # GetUserChatList
  56. ############################
  57. @router.get("/list/user/{user_id}", response_model=List[ChatTitleIdResponse])
  58. async def get_user_chat_list_by_user_id(
  59. user_id: str, user=Depends(get_admin_user), skip: int = 0, limit: int = 50
  60. ):
  61. return Chats.get_chat_list_by_user_id(user_id, skip, limit)
  62. ############################
  63. # GetArchivedChats
  64. ############################
  65. @router.get("/archived", response_model=List[ChatTitleIdResponse])
  66. async def get_archived_session_user_chat_list(
  67. user=Depends(get_current_user), skip: int = 0, limit: int = 50
  68. ):
  69. return Chats.get_archived_chat_list_by_user_id(user.id, skip, limit)
  70. ############################
  71. # GetChats
  72. ############################
  73. @router.get("/all", response_model=List[ChatResponse])
  74. async def get_user_chats(user=Depends(get_current_user)):
  75. return [
  76. ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  77. for chat in Chats.get_chats_by_user_id(user.id)
  78. ]
  79. ############################
  80. # GetAllChatsInDB
  81. ############################
  82. @router.get("/all/db", response_model=List[ChatResponse])
  83. async def get_all_user_chats_in_db(user=Depends(get_admin_user)):
  84. if not ENABLE_ADMIN_EXPORT:
  85. raise HTTPException(
  86. status_code=status.HTTP_401_UNAUTHORIZED,
  87. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  88. )
  89. return [
  90. ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  91. for chat in Chats.get_chats()
  92. ]
  93. ############################
  94. # CreateNewChat
  95. ############################
  96. @router.post("/new", response_model=Optional[ChatResponse])
  97. async def create_new_chat(form_data: ChatForm, user=Depends(get_current_user)):
  98. try:
  99. chat = Chats.insert_new_chat(user.id, form_data)
  100. return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  101. except Exception as e:
  102. log.exception(e)
  103. raise HTTPException(
  104. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  105. )
  106. ############################
  107. # GetChatById
  108. ############################
  109. @router.get("/{id}", response_model=Optional[ChatResponse])
  110. async def get_chat_by_id(id: str, user=Depends(get_current_user)):
  111. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  112. if chat:
  113. return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  114. else:
  115. raise HTTPException(
  116. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  117. )
  118. ############################
  119. # UpdateChatById
  120. ############################
  121. @router.post("/{id}", response_model=Optional[ChatResponse])
  122. async def update_chat_by_id(
  123. id: str, form_data: ChatForm, user=Depends(get_current_user)
  124. ):
  125. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  126. if chat:
  127. updated_chat = {**json.loads(chat.chat), **form_data.chat}
  128. chat = Chats.update_chat_by_id(id, updated_chat)
  129. return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  130. else:
  131. raise HTTPException(
  132. status_code=status.HTTP_401_UNAUTHORIZED,
  133. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  134. )
  135. ############################
  136. # DeleteChatById
  137. ############################
  138. @router.delete("/{id}", response_model=bool)
  139. async def delete_chat_by_id(request: Request, id: str, user=Depends(get_current_user)):
  140. if user.role == "admin":
  141. result = Chats.delete_chat_by_id(id)
  142. return result
  143. else:
  144. if not request.app.state.USER_PERMISSIONS["chat"]["deletion"]:
  145. raise HTTPException(
  146. status_code=status.HTTP_401_UNAUTHORIZED,
  147. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  148. )
  149. result = Chats.delete_chat_by_id_and_user_id(id, user.id)
  150. return result
  151. ############################
  152. # ArchiveChat
  153. ############################
  154. @router.get("/{id}/archive", response_model=Optional[ChatResponse])
  155. async def archive_chat_by_id(id: str, user=Depends(get_current_user)):
  156. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  157. if chat:
  158. chat = Chats.toggle_chat_archive_by_id(id)
  159. return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  160. else:
  161. raise HTTPException(
  162. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  163. )
  164. ############################
  165. # ShareChatById
  166. ############################
  167. @router.post("/{id}/share", response_model=Optional[ChatResponse])
  168. async def share_chat_by_id(id: str, user=Depends(get_current_user)):
  169. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  170. if chat:
  171. if chat.share_id:
  172. shared_chat = Chats.update_shared_chat_by_chat_id(chat.id)
  173. return ChatResponse(
  174. **{**shared_chat.model_dump(), "chat": json.loads(shared_chat.chat)}
  175. )
  176. shared_chat = Chats.insert_shared_chat_by_chat_id(chat.id)
  177. if not shared_chat:
  178. raise HTTPException(
  179. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  180. detail=ERROR_MESSAGES.DEFAULT(),
  181. )
  182. return ChatResponse(
  183. **{**shared_chat.model_dump(), "chat": json.loads(shared_chat.chat)}
  184. )
  185. else:
  186. raise HTTPException(
  187. status_code=status.HTTP_401_UNAUTHORIZED,
  188. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  189. )
  190. ############################
  191. # DeletedSharedChatById
  192. ############################
  193. @router.delete("/{id}/share", response_model=Optional[bool])
  194. async def delete_shared_chat_by_id(id: str, user=Depends(get_current_user)):
  195. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  196. if chat:
  197. if not chat.share_id:
  198. return False
  199. result = Chats.delete_shared_chat_by_chat_id(id)
  200. update_result = Chats.update_chat_share_id_by_id(id, None)
  201. return result and update_result != None
  202. else:
  203. raise HTTPException(
  204. status_code=status.HTTP_401_UNAUTHORIZED,
  205. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  206. )
  207. ############################
  208. # GetSharedChatById
  209. ############################
  210. @router.get("/share/{share_id}", response_model=Optional[ChatResponse])
  211. async def get_shared_chat_by_id(share_id: str, user=Depends(get_current_user)):
  212. if user.role == "pending":
  213. raise HTTPException(
  214. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  215. )
  216. if user.role == "user":
  217. chat = Chats.get_chat_by_share_id(share_id)
  218. elif user.role == "admin":
  219. chat = Chats.get_chat_by_id(share_id)
  220. if chat:
  221. return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  222. else:
  223. raise HTTPException(
  224. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  225. )
  226. ############################
  227. # GetAllTags
  228. ############################
  229. @router.get("/tags/all", response_model=List[TagModel])
  230. async def get_all_tags(user=Depends(get_current_user)):
  231. try:
  232. tags = Tags.get_tags_by_user_id(user.id)
  233. return tags
  234. except Exception as e:
  235. log.exception(e)
  236. raise HTTPException(
  237. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  238. )
  239. ############################
  240. # GetChatsByTags
  241. ############################
  242. class TagNameForm(BaseModel):
  243. name: str
  244. @router.post("/tags", response_model=List[ChatTitleIdResponse])
  245. async def get_user_chat_list_by_tag_name(
  246. form_data: TagNameForm,
  247. user=Depends(get_current_user),
  248. skip: int = 0,
  249. limit: int = 50,
  250. ):
  251. chat_ids = [
  252. chat_id_tag.chat_id
  253. for chat_id_tag in Tags.get_chat_ids_by_tag_name_and_user_id(
  254. form_data.name, user.id
  255. )
  256. ]
  257. chats = Chats.get_chat_list_by_chat_ids(chat_ids, skip, limit)
  258. if len(chats) == 0:
  259. Tags.delete_tag_by_tag_name_and_user_id(form_data.name, user.id)
  260. return chats
  261. ############################
  262. # GetChatTagsById
  263. ############################
  264. @router.get("/{id}/tags", response_model=List[TagModel])
  265. async def get_chat_tags_by_id(id: str, user=Depends(get_current_user)):
  266. tags = Tags.get_tags_by_chat_id_and_user_id(id, user.id)
  267. if tags != None:
  268. return tags
  269. else:
  270. raise HTTPException(
  271. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  272. )
  273. ############################
  274. # AddChatTagById
  275. ############################
  276. @router.post("/{id}/tags", response_model=Optional[ChatIdTagModel])
  277. async def add_chat_tag_by_id(
  278. id: str, form_data: ChatIdTagForm, user=Depends(get_current_user)
  279. ):
  280. tags = Tags.get_tags_by_chat_id_and_user_id(id, user.id)
  281. if form_data.tag_name not in tags:
  282. tag = Tags.add_tag_to_chat(user.id, form_data)
  283. if tag:
  284. return tag
  285. else:
  286. raise HTTPException(
  287. status_code=status.HTTP_401_UNAUTHORIZED,
  288. detail=ERROR_MESSAGES.NOT_FOUND,
  289. )
  290. else:
  291. raise HTTPException(
  292. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  293. )
  294. ############################
  295. # DeleteChatTagById
  296. ############################
  297. @router.delete("/{id}/tags", response_model=Optional[bool])
  298. async def delete_chat_tag_by_id(
  299. id: str, form_data: ChatIdTagForm, user=Depends(get_current_user)
  300. ):
  301. result = Tags.delete_tag_by_tag_name_and_chat_id_and_user_id(
  302. form_data.tag_name, id, user.id
  303. )
  304. if result:
  305. return result
  306. else:
  307. raise HTTPException(
  308. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  309. )
  310. ############################
  311. # DeleteAllChatTagsById
  312. ############################
  313. @router.delete("/{id}/tags/all", response_model=Optional[bool])
  314. async def delete_all_chat_tags_by_id(id: str, user=Depends(get_current_user)):
  315. result = Tags.delete_tags_by_chat_id_and_user_id(id, user.id)
  316. if result:
  317. return result
  318. else:
  319. raise HTTPException(
  320. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  321. )