channels.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. import json
  2. import logging
  3. from typing import Optional
  4. from fastapi import APIRouter, Depends, HTTPException, Request, status
  5. from pydantic import BaseModel
  6. from open_webui.socket.main import sio
  7. from open_webui.models.users import Users, UserNameResponse
  8. from open_webui.models.channels import Channels, ChannelModel, ChannelForm
  9. from open_webui.models.messages import Messages, MessageModel, MessageForm
  10. from open_webui.config import ENABLE_ADMIN_CHAT_ACCESS, ENABLE_ADMIN_EXPORT
  11. from open_webui.constants import ERROR_MESSAGES
  12. from open_webui.env import SRC_LOG_LEVELS
  13. from open_webui.utils.auth import get_admin_user, get_verified_user
  14. from open_webui.utils.access_control import has_access
  15. log = logging.getLogger(__name__)
  16. log.setLevel(SRC_LOG_LEVELS["MODELS"])
  17. router = APIRouter()
  18. ############################
  19. # GetChatList
  20. ############################
  21. @router.get("/", response_model=list[ChannelModel])
  22. async def get_channels(user=Depends(get_verified_user)):
  23. if user.role == "admin":
  24. return Channels.get_channels()
  25. else:
  26. return Channels.get_channels_by_user_id(user.id)
  27. ############################
  28. # CreateNewChannel
  29. ############################
  30. @router.post("/create", response_model=Optional[ChannelModel])
  31. async def create_new_channel(form_data: ChannelForm, user=Depends(get_admin_user)):
  32. try:
  33. channel = Channels.insert_new_channel(form_data, user.id)
  34. return ChannelModel(**channel.model_dump())
  35. except Exception as e:
  36. log.exception(e)
  37. raise HTTPException(
  38. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  39. )
  40. ############################
  41. # GetChannelById
  42. ############################
  43. @router.get("/{id}", response_model=Optional[ChannelModel])
  44. async def get_channel_by_id(id: str, user=Depends(get_verified_user)):
  45. channel = Channels.get_channel_by_id(id)
  46. if not channel:
  47. raise HTTPException(
  48. status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND
  49. )
  50. if user.role != "admin" and not has_access(
  51. user.id, type="read", access_control=channel.access_control
  52. ):
  53. raise HTTPException(
  54. status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT()
  55. )
  56. return ChannelModel(**channel.model_dump())
  57. ############################
  58. # UpdateChannelById
  59. ############################
  60. @router.post("/{id}/update", response_model=Optional[ChannelModel])
  61. async def update_channel_by_id(
  62. id: str, form_data: ChannelForm, user=Depends(get_admin_user)
  63. ):
  64. channel = Channels.get_channel_by_id(id)
  65. if not channel:
  66. raise HTTPException(
  67. status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND
  68. )
  69. try:
  70. channel = Channels.update_channel_by_id(id, form_data)
  71. return ChannelModel(**channel.model_dump())
  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. # DeleteChannelById
  79. ############################
  80. @router.delete("/{id}/delete", response_model=bool)
  81. async def delete_channel_by_id(id: str, user=Depends(get_admin_user)):
  82. channel = Channels.get_channel_by_id(id)
  83. if not channel:
  84. raise HTTPException(
  85. status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND
  86. )
  87. try:
  88. Channels.delete_channel_by_id(id)
  89. return True
  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. # GetChannelMessages
  97. ############################
  98. class MessageUserModel(MessageModel):
  99. user: UserNameResponse
  100. @router.get("/{id}/messages", response_model=list[MessageUserModel])
  101. async def get_channel_messages(
  102. id: str, skip: int = 0, limit: int = 50, user=Depends(get_verified_user)
  103. ):
  104. channel = Channels.get_channel_by_id(id)
  105. if not channel:
  106. raise HTTPException(
  107. status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND
  108. )
  109. if user.role != "admin" and not has_access(
  110. user.id, type="read", access_control=channel.access_control
  111. ):
  112. raise HTTPException(
  113. status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT()
  114. )
  115. message_list = Messages.get_messages_by_channel_id(id, skip, limit)
  116. users = {}
  117. messages = []
  118. for message in message_list:
  119. if message.user_id not in users:
  120. user = Users.get_user_by_id(message.user_id)
  121. users[message.user_id] = user
  122. messages.append(
  123. MessageUserModel(
  124. **{
  125. **message.model_dump(),
  126. "user": UserNameResponse(**users[message.user_id].model_dump()),
  127. }
  128. )
  129. )
  130. return messages
  131. ############################
  132. # PostNewMessage
  133. ############################
  134. @router.post("/{id}/messages/post", response_model=Optional[MessageModel])
  135. async def post_new_message(
  136. id: str, form_data: MessageForm, user=Depends(get_verified_user)
  137. ):
  138. channel = Channels.get_channel_by_id(id)
  139. if not channel:
  140. raise HTTPException(
  141. status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND
  142. )
  143. if user.role != "admin" and not has_access(
  144. user.id, type="read", access_control=channel.access_control
  145. ):
  146. raise HTTPException(
  147. status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT()
  148. )
  149. try:
  150. message = Messages.insert_new_message(form_data, channel.id, user.id)
  151. if message:
  152. await sio.emit(
  153. "channel-events",
  154. {
  155. "channel_id": channel.id,
  156. "message_id": message.id,
  157. "data": {
  158. "type": "message",
  159. "data": {
  160. **message.model_dump(),
  161. "user": UserNameResponse(**user.model_dump()).model_dump(),
  162. },
  163. },
  164. },
  165. to=f"channel:{channel.id}",
  166. )
  167. return MessageModel(**message.model_dump())
  168. except Exception as e:
  169. log.exception(e)
  170. raise HTTPException(
  171. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  172. )
  173. ############################
  174. # UpdateMessageById
  175. ############################
  176. @router.post(
  177. "/{id}/messages/{message_id}/update", response_model=Optional[MessageModel]
  178. )
  179. async def update_message_by_id(
  180. id: str, message_id: str, form_data: MessageForm, user=Depends(get_verified_user)
  181. ):
  182. channel = Channels.get_channel_by_id(id)
  183. if not channel:
  184. raise HTTPException(
  185. status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND
  186. )
  187. if user.role != "admin" and not has_access(
  188. user.id, type="read", access_control=channel.access_control
  189. ):
  190. raise HTTPException(
  191. status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT()
  192. )
  193. message = Messages.get_message_by_id(message_id)
  194. if not message:
  195. raise HTTPException(
  196. status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND
  197. )
  198. if message.channel_id != id:
  199. raise HTTPException(
  200. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  201. )
  202. try:
  203. message = Messages.update_message_by_id(message_id, form_data)
  204. if message:
  205. await sio.emit(
  206. "channel-events",
  207. {
  208. "channel_id": channel.id,
  209. "message_id": message.id,
  210. "data": {
  211. "type": "message:update",
  212. "data": {
  213. **message.model_dump(),
  214. "user": UserNameResponse(**user.model_dump()).model_dump(),
  215. },
  216. },
  217. },
  218. to=f"channel:{channel.id}",
  219. )
  220. return MessageModel(**message.model_dump())
  221. except Exception as e:
  222. log.exception(e)
  223. raise HTTPException(
  224. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  225. )
  226. ############################
  227. # DeleteMessageById
  228. ############################
  229. @router.delete("/{id}/messages/{message_id}/delete", response_model=bool)
  230. async def delete_message_by_id(
  231. id: str, message_id: str, user=Depends(get_verified_user)
  232. ):
  233. channel = Channels.get_channel_by_id(id)
  234. if not channel:
  235. raise HTTPException(
  236. status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND
  237. )
  238. if user.role != "admin" and not has_access(
  239. user.id, type="read", access_control=channel.access_control
  240. ):
  241. raise HTTPException(
  242. status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT()
  243. )
  244. message = Messages.get_message_by_id(message_id)
  245. if not message:
  246. raise HTTPException(
  247. status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND
  248. )
  249. if message.channel_id != id:
  250. raise HTTPException(
  251. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  252. )
  253. try:
  254. Messages.delete_message_by_id(message_id)
  255. await sio.emit(
  256. "channel-events",
  257. {
  258. "channel_id": channel.id,
  259. "message_id": message.id,
  260. "data": {
  261. "type": "message:delete",
  262. "data": {
  263. **message.model_dump(),
  264. "user": UserNameResponse(**user.model_dump()).model_dump(),
  265. },
  266. },
  267. },
  268. to=f"channel:{channel.id}",
  269. )
  270. return True
  271. except Exception as e:
  272. log.exception(e)
  273. raise HTTPException(
  274. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  275. )