chats.py 9.8 KB

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