chats.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. from apps.web.models.users import Users
  9. from apps.web.models.chats import (
  10. ChatModel,
  11. ChatResponse,
  12. ChatTitleForm,
  13. ChatForm,
  14. ChatTitleIdResponse,
  15. Chats,
  16. )
  17. from apps.web.models.tags import (
  18. TagModel,
  19. ChatIdTagModel,
  20. ChatIdTagForm,
  21. ChatTagsResponse,
  22. Tags,
  23. )
  24. from constants import ERROR_MESSAGES
  25. router = APIRouter()
  26. ############################
  27. # GetChats
  28. ############################
  29. @router.get("/", response_model=List[ChatTitleIdResponse])
  30. async def get_user_chats(
  31. user=Depends(get_current_user), skip: int = 0, limit: int = 50
  32. ):
  33. return Chats.get_chat_lists_by_user_id(user.id, skip, limit)
  34. ############################
  35. # GetAllChats
  36. ############################
  37. @router.get("/all", response_model=List[ChatResponse])
  38. async def get_all_user_chats(user=Depends(get_current_user)):
  39. return [
  40. ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  41. for chat in Chats.get_all_chats_by_user_id(user.id)
  42. ]
  43. ############################
  44. # GetAllChatsInDB
  45. ############################
  46. @router.get("/all/db", response_model=List[ChatResponse])
  47. async def get_all_user_chats_in_db(user=Depends(get_admin_user)):
  48. return [
  49. ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  50. for chat in Chats.get_all_chats()
  51. ]
  52. ############################
  53. # CreateNewChat
  54. ############################
  55. @router.post("/new", response_model=Optional[ChatResponse])
  56. async def create_new_chat(form_data: ChatForm, user=Depends(get_current_user)):
  57. try:
  58. chat = Chats.insert_new_chat(user.id, form_data)
  59. return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  60. except Exception as e:
  61. print(e)
  62. raise HTTPException(
  63. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  64. )
  65. ############################
  66. # GetAllTags
  67. ############################
  68. @router.get("/tags/all", response_model=List[TagModel])
  69. async def get_all_tags(user=Depends(get_current_user)):
  70. try:
  71. tags = Tags.get_tags_by_user_id(user.id)
  72. return tags
  73. except Exception as e:
  74. print(e)
  75. raise HTTPException(
  76. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  77. )
  78. ############################
  79. # GetChatsByTags
  80. ############################
  81. @router.get("/tags/tag/{tag_name}", response_model=List[ChatTitleIdResponse])
  82. async def get_user_chats_by_tag_name(
  83. tag_name: str, user=Depends(get_current_user), skip: int = 0, limit: int = 50
  84. ):
  85. chat_ids = [
  86. chat_id_tag.chat_id
  87. for chat_id_tag in Tags.get_chat_ids_by_tag_name_and_user_id(tag_name, user.id)
  88. ]
  89. chats = Chats.get_chat_lists_by_chat_ids(chat_ids, skip, limit)
  90. if len(chats) == 0:
  91. Tags.delete_tag_by_tag_name_and_user_id(tag_name, user.id)
  92. return chats
  93. ############################
  94. # GetChatById
  95. ############################
  96. @router.get("/{id}", response_model=Optional[ChatResponse])
  97. async def get_chat_by_id(id: str, user=Depends(get_current_user)):
  98. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  99. if chat:
  100. return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  101. else:
  102. raise HTTPException(
  103. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  104. )
  105. ############################
  106. # UpdateChatById
  107. ############################
  108. @router.post("/{id}", response_model=Optional[ChatResponse])
  109. async def update_chat_by_id(
  110. id: str, form_data: ChatForm, user=Depends(get_current_user)
  111. ):
  112. chat = Chats.get_chat_by_id_and_user_id(id, user.id)
  113. if chat:
  114. updated_chat = {**json.loads(chat.chat), **form_data.chat}
  115. chat = Chats.update_chat_by_id(id, updated_chat)
  116. return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
  117. else:
  118. raise HTTPException(
  119. status_code=status.HTTP_401_UNAUTHORIZED,
  120. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  121. )
  122. ############################
  123. # DeleteChatById
  124. ############################
  125. @router.delete("/{id}", response_model=bool)
  126. async def delete_chat_by_id(request: Request, id: str, user=Depends(get_current_user)):
  127. if (
  128. user.role == "user"
  129. and not request.app.state.USER_PERMISSIONS["chat"]["deletion"]
  130. ):
  131. raise HTTPException(
  132. status_code=status.HTTP_401_UNAUTHORIZED,
  133. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  134. )
  135. result = Chats.delete_chat_by_id_and_user_id(id, user.id)
  136. return result
  137. ############################
  138. # GetChatTagsById
  139. ############################
  140. @router.get("/{id}/tags", response_model=List[TagModel])
  141. async def get_chat_tags_by_id(id: str, user=Depends(get_current_user)):
  142. tags = Tags.get_tags_by_chat_id_and_user_id(id, user.id)
  143. if tags != None:
  144. return tags
  145. else:
  146. raise HTTPException(
  147. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  148. )
  149. ############################
  150. # AddChatTagById
  151. ############################
  152. @router.post("/{id}/tags", response_model=Optional[ChatIdTagModel])
  153. async def add_chat_tag_by_id(
  154. id: str, form_data: ChatIdTagForm, user=Depends(get_current_user)
  155. ):
  156. tags = Tags.get_tags_by_chat_id_and_user_id(id, user.id)
  157. if form_data.tag_name not in tags:
  158. tag = Tags.add_tag_to_chat(user.id, form_data)
  159. if tag:
  160. return tag
  161. else:
  162. raise HTTPException(
  163. status_code=status.HTTP_401_UNAUTHORIZED,
  164. detail=ERROR_MESSAGES.NOT_FOUND,
  165. )
  166. else:
  167. raise HTTPException(
  168. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
  169. )
  170. ############################
  171. # DeleteChatTagById
  172. ############################
  173. @router.delete("/{id}/tags", response_model=Optional[bool])
  174. async def delete_chat_tag_by_id(
  175. id: str, form_data: ChatIdTagForm, user=Depends(get_current_user)
  176. ):
  177. result = Tags.delete_tag_by_tag_name_and_chat_id_and_user_id(
  178. form_data.tag_name, id, user.id
  179. )
  180. if result:
  181. return result
  182. else:
  183. raise HTTPException(
  184. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  185. )
  186. ############################
  187. # DeleteAllChatTagsById
  188. ############################
  189. @router.delete("/{id}/tags/all", response_model=Optional[bool])
  190. async def delete_all_chat_tags_by_id(id: str, user=Depends(get_current_user)):
  191. result = Tags.delete_tags_by_chat_id_and_user_id(id, user.id)
  192. if result:
  193. return result
  194. else:
  195. raise HTTPException(
  196. status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
  197. )
  198. ############################
  199. # DeleteAllChats
  200. ############################
  201. @router.delete("/", response_model=bool)
  202. async def delete_all_user_chats(user=Depends(get_current_user)):
  203. result = Chats.delete_chats_by_user_id(user.id)
  204. return result