channels.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. "user": UserNameResponse(**user.model_dump()).model_dump(),
  165. "channel": channel.model_dump(),
  166. },
  167. to=f"channel:{channel.id}",
  168. )
  169. return MessageModel(**message.model_dump())
  170. except Exception as e:
  171. log.exception(e)
  172. raise HTTPException(
  173. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  174. )
  175. ############################
  176. # UpdateMessageById
  177. ############################
  178. @router.post(
  179. "/{id}/messages/{message_id}/update", response_model=Optional[MessageModel]
  180. )
  181. async def update_message_by_id(
  182. id: str, message_id: str, form_data: MessageForm, user=Depends(get_verified_user)
  183. ):
  184. channel = Channels.get_channel_by_id(id)
  185. if not channel:
  186. raise HTTPException(
  187. status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND
  188. )
  189. if user.role != "admin" and not has_access(
  190. user.id, type="read", access_control=channel.access_control
  191. ):
  192. raise HTTPException(
  193. status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT()
  194. )
  195. message = Messages.get_message_by_id(message_id)
  196. if not message:
  197. raise HTTPException(
  198. status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND
  199. )
  200. if message.channel_id != id:
  201. raise HTTPException(
  202. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  203. )
  204. try:
  205. message = Messages.update_message_by_id(message_id, form_data)
  206. if message:
  207. await sio.emit(
  208. "channel-events",
  209. {
  210. "channel_id": channel.id,
  211. "message_id": message.id,
  212. "data": {
  213. "type": "message:update",
  214. "data": {
  215. **message.model_dump(),
  216. "user": UserNameResponse(**user.model_dump()).model_dump(),
  217. },
  218. },
  219. "user": UserNameResponse(**user.model_dump()).model_dump(),
  220. "channel": channel.model_dump(),
  221. },
  222. to=f"channel:{channel.id}",
  223. )
  224. return MessageModel(**message.model_dump())
  225. except Exception as e:
  226. log.exception(e)
  227. raise HTTPException(
  228. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  229. )
  230. ############################
  231. # DeleteMessageById
  232. ############################
  233. @router.delete("/{id}/messages/{message_id}/delete", response_model=bool)
  234. async def delete_message_by_id(
  235. id: str, message_id: str, user=Depends(get_verified_user)
  236. ):
  237. channel = Channels.get_channel_by_id(id)
  238. if not channel:
  239. raise HTTPException(
  240. status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND
  241. )
  242. if user.role != "admin" and not has_access(
  243. user.id, type="read", access_control=channel.access_control
  244. ):
  245. raise HTTPException(
  246. status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT()
  247. )
  248. message = Messages.get_message_by_id(message_id)
  249. if not message:
  250. raise HTTPException(
  251. status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND
  252. )
  253. if message.channel_id != id:
  254. raise HTTPException(
  255. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  256. )
  257. try:
  258. Messages.delete_message_by_id(message_id)
  259. await sio.emit(
  260. "channel-events",
  261. {
  262. "channel_id": channel.id,
  263. "message_id": message.id,
  264. "data": {
  265. "type": "message:delete",
  266. "data": {
  267. **message.model_dump(),
  268. "user": UserNameResponse(**user.model_dump()).model_dump(),
  269. },
  270. },
  271. "user": UserNameResponse(**user.model_dump()).model_dump(),
  272. "channel": channel.model_dump(),
  273. },
  274. to=f"channel:{channel.id}",
  275. )
  276. return True
  277. except Exception as e:
  278. log.exception(e)
  279. raise HTTPException(
  280. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  281. )