chats.py 11 KB

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