channels.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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 not has_access(user.id, type="read", access_control=channel.access_control):
  51. raise HTTPException(
  52. status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT()
  53. )
  54. return ChannelModel(**channel.model_dump())
  55. ############################
  56. # GetChannelMessages
  57. ############################
  58. class MessageUserModel(MessageModel):
  59. user: UserNameResponse
  60. @router.get("/{id}/messages", response_model=list[MessageUserModel])
  61. async def get_channel_messages(id: str, page: int = 1, user=Depends(get_verified_user)):
  62. channel = Channels.get_channel_by_id(id)
  63. if not channel:
  64. raise HTTPException(
  65. status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND
  66. )
  67. if not has_access(user.id, type="read", access_control=channel.access_control):
  68. raise HTTPException(
  69. status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT()
  70. )
  71. limit = 50
  72. skip = (page - 1) * limit
  73. message_list = Messages.get_messages_by_channel_id(id, skip, limit)
  74. users = {}
  75. messages = []
  76. for message in message_list:
  77. if message.user_id not in users:
  78. user = Users.get_user_by_id(message.user_id)
  79. users[message.user_id] = user
  80. messages.append(
  81. MessageUserModel(
  82. **{
  83. **message.model_dump(),
  84. "user": UserNameResponse(**users[message.user_id].model_dump()),
  85. }
  86. )
  87. )
  88. return messages
  89. ############################
  90. # PostNewMessage
  91. ############################
  92. @router.post("/{id}/messages/post", response_model=Optional[MessageModel])
  93. async def post_new_message(
  94. id: str, form_data: MessageForm, user=Depends(get_verified_user)
  95. ):
  96. channel = Channels.get_channel_by_id(id)
  97. if not channel:
  98. raise HTTPException(
  99. status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND
  100. )
  101. if not has_access(user.id, type="read", access_control=channel.access_control):
  102. raise HTTPException(
  103. status_code=status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.DEFAULT()
  104. )
  105. try:
  106. message = Messages.insert_new_message(form_data, channel.id, user.id)
  107. if message:
  108. await sio.emit(
  109. "channel-events",
  110. {
  111. "channel_id": channel.id,
  112. "message_id": message.id,
  113. "data": {
  114. "type": "message",
  115. "data": {
  116. **message.model_dump(),
  117. "user": UserNameResponse(**user.model_dump()).model_dump(),
  118. },
  119. },
  120. },
  121. to=f"channel:{channel.id}",
  122. )
  123. return MessageModel(**message.model_dump())
  124. except Exception as e:
  125. log.exception(e)
  126. raise HTTPException(
  127. status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
  128. )