chats.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. # GetChatTagsById
  143. ############################
  144. @router.get("/{id}/tags", response_model=List[TagModel])
  145. async def get_chat_tags_by_id(id: str, user=Depends(get_current_user)):
  146. tags = Tags.get_tags_by_chat_id_and_user_id(id, user.id)
  147. if tags != None:
  148. return tags
  149. else:
  150. raise HTTPException(
  151. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  152. )
  153. ############################
  154. # AddChatTagById
  155. ############################
  156. @router.post("/{id}/tags", response_model=Optional[ChatIdTagModel])
  157. async def add_chat_tag_by_id(
  158. id: str, form_data: ChatIdTagForm, user=Depends(get_current_user)
  159. ):
  160. tags = Tags.get_tags_by_chat_id_and_user_id(id, user.id)
  161. if form_data.tag_name not in tags:
  162. tag = Tags.add_tag_to_chat(user.id, form_data)
  163. if tag:
  164. return tag
  165. else:
  166. raise HTTPException(
  167. status_code=status.HTTP_401_UNAUTHORIZED,
  168. detail=ERROR_MESSAGES.NOT_FOUND,
  169. )
  170. else:
  171. raise HTTPException(
  172. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  173. )
  174. ############################
  175. # DeleteChatTagById
  176. ############################
  177. @router.delete("/{id}/tags", response_model=Optional[bool])
  178. async def delete_chat_tag_by_id(
  179. id: str, form_data: ChatIdTagForm, user=Depends(get_current_user)
  180. ):
  181. result = Tags.delete_tag_by_tag_name_and_chat_id_and_user_id(
  182. form_data.tag_name, id, user.id
  183. )
  184. if result:
  185. return result
  186. else:
  187. raise HTTPException(
  188. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  189. )
  190. ############################
  191. # DeleteAllChatTagsById
  192. ############################
  193. @router.delete("/{id}/tags/all", response_model=Optional[bool])
  194. async def delete_all_chat_tags_by_id(id: str, user=Depends(get_current_user)):
  195. result = Tags.delete_tags_by_chat_id_and_user_id(id, user.id)
  196. if result:
  197. return result
  198. else:
  199. raise HTTPException(
  200. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  201. )
  202. ############################
  203. # DeleteAllChats
  204. ############################
  205. @router.delete("/", response_model=bool)
  206. async def delete_all_user_chats(request: Request, user=Depends(get_current_user)):
  207. if (
  208. user.role == "user"
  209. and not request.app.state.USER_PERMISSIONS["chat"]["deletion"]
  210. ):
  211. raise HTTPException(
  212. status_code=status.HTTP_401_UNAUTHORIZED,
  213. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  214. )
  215. result = Chats.delete_chats_by_user_id(user.id)
  216. return result