|
| 1 | +import sys |
| 2 | +import time |
| 3 | +import web |
| 4 | +import json |
| 5 | +from queue import Queue |
| 6 | +from bridge.context import * |
| 7 | +from bridge.reply import Reply, ReplyType |
| 8 | +from channel.chat_channel import ChatChannel, check_prefix |
| 9 | +from channel.chat_message import ChatMessage |
| 10 | +from common.log import logger |
| 11 | +from common.singleton import singleton |
| 12 | +from config import conf |
| 13 | +import os |
| 14 | + |
| 15 | + |
| 16 | +class WebMessage(ChatMessage): |
| 17 | + def __init__( |
| 18 | + self, |
| 19 | + msg_id, |
| 20 | + content, |
| 21 | + ctype=ContextType.TEXT, |
| 22 | + from_user_id="User", |
| 23 | + to_user_id="Chatgpt", |
| 24 | + other_user_id="Chatgpt", |
| 25 | + ): |
| 26 | + self.msg_id = msg_id |
| 27 | + self.ctype = ctype |
| 28 | + self.content = content |
| 29 | + self.from_user_id = from_user_id |
| 30 | + self.to_user_id = to_user_id |
| 31 | + self.other_user_id = other_user_id |
| 32 | + |
| 33 | + |
| 34 | +@singleton |
| 35 | +class WebChannel(ChatChannel): |
| 36 | + NOT_SUPPORT_REPLYTYPE = [ReplyType.VOICE] |
| 37 | + _instance = None |
| 38 | + |
| 39 | + # def __new__(cls): |
| 40 | + # if cls._instance is None: |
| 41 | + # cls._instance = super(WebChannel, cls).__new__(cls) |
| 42 | + # return cls._instance |
| 43 | + |
| 44 | + def __init__(self): |
| 45 | + super().__init__() |
| 46 | + self.message_queues = {} # 为每个用户存储一个消息队列 |
| 47 | + self.msg_id_counter = 0 # 添加消息ID计数器 |
| 48 | + |
| 49 | + def _generate_msg_id(self): |
| 50 | + """生成唯一的消息ID""" |
| 51 | + self.msg_id_counter += 1 |
| 52 | + return str(int(time.time())) + str(self.msg_id_counter) |
| 53 | + |
| 54 | + def send(self, reply: Reply, context: Context): |
| 55 | + try: |
| 56 | + if reply.type == ReplyType.IMAGE: |
| 57 | + from PIL import Image |
| 58 | + |
| 59 | + image_storage = reply.content |
| 60 | + image_storage.seek(0) |
| 61 | + img = Image.open(image_storage) |
| 62 | + print("<IMAGE>") |
| 63 | + img.show() |
| 64 | + elif reply.type == ReplyType.IMAGE_URL: |
| 65 | + import io |
| 66 | + |
| 67 | + import requests |
| 68 | + from PIL import Image |
| 69 | + |
| 70 | + img_url = reply.content |
| 71 | + pic_res = requests.get(img_url, stream=True) |
| 72 | + image_storage = io.BytesIO() |
| 73 | + for block in pic_res.iter_content(1024): |
| 74 | + image_storage.write(block) |
| 75 | + image_storage.seek(0) |
| 76 | + img = Image.open(image_storage) |
| 77 | + print(img_url) |
| 78 | + img.show() |
| 79 | + else: |
| 80 | + print(reply.content) |
| 81 | + |
| 82 | + # 获取用户ID,如果没有则使用默认值 |
| 83 | + # user_id = getattr(context.get("session", None), "session_id", "default_user") |
| 84 | + user_id = context["receiver"] |
| 85 | + # 确保用户有对应的消息队列 |
| 86 | + if user_id not in self.message_queues: |
| 87 | + self.message_queues[user_id] = Queue() |
| 88 | + |
| 89 | + # 将消息放入对应用户的队列 |
| 90 | + message_data = { |
| 91 | + "type": str(reply.type), |
| 92 | + "content": reply.content, |
| 93 | + "timestamp": time.time() |
| 94 | + } |
| 95 | + self.message_queues[user_id].put(message_data) |
| 96 | + logger.debug(f"Message queued for user {user_id}") |
| 97 | + |
| 98 | + except Exception as e: |
| 99 | + logger.error(f"Error in send method: {e}") |
| 100 | + raise |
| 101 | + |
| 102 | + def sse_handler(self, user_id): |
| 103 | + """ |
| 104 | + Handle Server-Sent Events (SSE) for real-time communication. |
| 105 | + """ |
| 106 | + web.header('Content-Type', 'text/event-stream') |
| 107 | + web.header('Cache-Control', 'no-cache') |
| 108 | + web.header('Connection', 'keep-alive') |
| 109 | + |
| 110 | + # 确保用户有消息队列 |
| 111 | + if user_id not in self.message_queues: |
| 112 | + self.message_queues[user_id] = Queue() |
| 113 | + |
| 114 | + try: |
| 115 | + while True: |
| 116 | + try: |
| 117 | + # 发送心跳 |
| 118 | + yield f": heartbeat\n\n" |
| 119 | + |
| 120 | + # 非阻塞方式获取消息 |
| 121 | + if not self.message_queues[user_id].empty(): |
| 122 | + message = self.message_queues[user_id].get_nowait() |
| 123 | + yield f"data: {json.dumps(message)}\n\n" |
| 124 | + time.sleep(0.5) |
| 125 | + except Exception as e: |
| 126 | + logger.error(f"SSE Error: {e}") |
| 127 | + break |
| 128 | + finally: |
| 129 | + # 清理资源 |
| 130 | + if user_id in self.message_queues: |
| 131 | + # 只有当队列为空时才删除 |
| 132 | + if self.message_queues[user_id].empty(): |
| 133 | + del self.message_queues[user_id] |
| 134 | + |
| 135 | + def post_message(self): |
| 136 | + """ |
| 137 | + Handle incoming messages from users via POST request. |
| 138 | + """ |
| 139 | + try: |
| 140 | + data = web.data() # 获取原始POST数据 |
| 141 | + json_data = json.loads(data) |
| 142 | + user_id = json_data.get('user_id', 'default_user') |
| 143 | + prompt = json_data.get('message', '') |
| 144 | + except json.JSONDecodeError: |
| 145 | + return json.dumps({"status": "error", "message": "Invalid JSON"}) |
| 146 | + except Exception as e: |
| 147 | + return json.dumps({"status": "error", "message": str(e)}) |
| 148 | + |
| 149 | + if not prompt: |
| 150 | + return json.dumps({"status": "error", "message": "No message provided"}) |
| 151 | + |
| 152 | + try: |
| 153 | + msg_id = self._generate_msg_id() |
| 154 | + context = self._compose_context(ContextType.TEXT, prompt, msg=WebMessage(msg_id, |
| 155 | + prompt, |
| 156 | + from_user_id=user_id, |
| 157 | + other_user_id = user_id |
| 158 | + )) |
| 159 | + context["isgroup"] = False |
| 160 | + # context["session"] = web.storage(session_id=user_id) |
| 161 | + |
| 162 | + if not context: |
| 163 | + return json.dumps({"status": "error", "message": "Failed to process message"}) |
| 164 | + |
| 165 | + self.produce(context) |
| 166 | + return json.dumps({"status": "success", "message": "Message received"}) |
| 167 | + |
| 168 | + except Exception as e: |
| 169 | + logger.error(f"Error processing message: {e}") |
| 170 | + return json.dumps({"status": "error", "message": "Internal server error"}) |
| 171 | + |
| 172 | + def chat_page(self): |
| 173 | + """Serve the chat HTML page.""" |
| 174 | + file_path = os.path.join(os.path.dirname(__file__), 'chat.html') # 使用绝对路径 |
| 175 | + with open(file_path, 'r', encoding='utf-8') as f: |
| 176 | + return f.read() |
| 177 | + |
| 178 | + def startup(self): |
| 179 | + logger.setLevel("WARN") |
| 180 | + print("\nWeb Channel is running. Send POST requests to /message to send messages.") |
| 181 | + |
| 182 | + urls = ( |
| 183 | + '/sse/(.+)', 'SSEHandler', # 修改路由以接收用户ID |
| 184 | + '/message', 'MessageHandler', |
| 185 | + '/chat', 'ChatHandler', |
| 186 | + ) |
| 187 | + port = conf().get("web_port", 9899) |
| 188 | + app = web.application(urls, globals(), autoreload=False) |
| 189 | + web.httpserver.runsimple(app.wsgifunc(), ("0.0.0.0", port)) |
| 190 | + |
| 191 | + |
| 192 | +class SSEHandler: |
| 193 | + def GET(self, user_id): |
| 194 | + return WebChannel().sse_handler(user_id) |
| 195 | + |
| 196 | + |
| 197 | +class MessageHandler: |
| 198 | + def POST(self): |
| 199 | + return WebChannel().post_message() |
| 200 | + |
| 201 | + |
| 202 | +class ChatHandler: |
| 203 | + def GET(self): |
| 204 | + return WebChannel().chat_page() |
0 commit comments