channels.py 4.4 KB

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