chats.py 11 KB

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