chats.py 12 KB

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