main.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. import asyncio
  2. import random
  3. import socketio
  4. import logging
  5. import sys
  6. import time
  7. from typing import Dict, Set
  8. from redis import asyncio as aioredis
  9. import pycrdt as Y
  10. from open_webui.models.users import Users, UserNameResponse
  11. from open_webui.models.channels import Channels
  12. from open_webui.models.chats import Chats
  13. from open_webui.models.notes import Notes, NoteUpdateForm
  14. from open_webui.utils.redis import (
  15. get_sentinels_from_env,
  16. get_sentinel_url_from_env,
  17. )
  18. from open_webui.env import (
  19. ENABLE_WEBSOCKET_SUPPORT,
  20. WEBSOCKET_MANAGER,
  21. WEBSOCKET_REDIS_URL,
  22. WEBSOCKET_REDIS_CLUSTER,
  23. WEBSOCKET_REDIS_LOCK_TIMEOUT,
  24. WEBSOCKET_SENTINEL_PORT,
  25. WEBSOCKET_SENTINEL_HOSTS,
  26. REDIS_KEY_PREFIX,
  27. )
  28. from open_webui.utils.auth import decode_token
  29. from open_webui.socket.utils import RedisDict, RedisLock, YdocManager
  30. from open_webui.tasks import create_task, stop_item_tasks
  31. from open_webui.utils.redis import get_redis_connection
  32. from open_webui.utils.access_control import has_access, get_users_with_access
  33. from open_webui.env import (
  34. GLOBAL_LOG_LEVEL,
  35. SRC_LOG_LEVELS,
  36. )
  37. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  38. log = logging.getLogger(__name__)
  39. log.setLevel(SRC_LOG_LEVELS["SOCKET"])
  40. REDIS = None
  41. if WEBSOCKET_MANAGER == "redis":
  42. if WEBSOCKET_SENTINEL_HOSTS:
  43. mgr = socketio.AsyncRedisManager(
  44. get_sentinel_url_from_env(
  45. WEBSOCKET_REDIS_URL, WEBSOCKET_SENTINEL_HOSTS, WEBSOCKET_SENTINEL_PORT
  46. )
  47. )
  48. else:
  49. mgr = socketio.AsyncRedisManager(WEBSOCKET_REDIS_URL)
  50. sio = socketio.AsyncServer(
  51. cors_allowed_origins=[],
  52. async_mode="asgi",
  53. transports=(["websocket"] if ENABLE_WEBSOCKET_SUPPORT else ["polling"]),
  54. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT,
  55. always_connect=True,
  56. client_manager=mgr,
  57. )
  58. else:
  59. sio = socketio.AsyncServer(
  60. cors_allowed_origins=[],
  61. async_mode="asgi",
  62. transports=(["websocket"] if ENABLE_WEBSOCKET_SUPPORT else ["polling"]),
  63. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT,
  64. always_connect=True,
  65. )
  66. # Timeout duration in seconds
  67. TIMEOUT_DURATION = 3
  68. # Dictionary to maintain the user pool
  69. if WEBSOCKET_MANAGER == "redis":
  70. log.debug("Using Redis to manage websockets.")
  71. REDIS = get_redis_connection(
  72. redis_url=WEBSOCKET_REDIS_URL,
  73. redis_sentinels=get_sentinels_from_env(
  74. WEBSOCKET_SENTINEL_HOSTS, WEBSOCKET_SENTINEL_PORT
  75. ),
  76. redis_cluster=WEBSOCKET_REDIS_CLUSTER,
  77. async_mode=True,
  78. )
  79. redis_sentinels = get_sentinels_from_env(
  80. WEBSOCKET_SENTINEL_HOSTS, WEBSOCKET_SENTINEL_PORT
  81. )
  82. SESSION_POOL = RedisDict(
  83. f"{REDIS_KEY_PREFIX}:session_pool",
  84. redis_url=WEBSOCKET_REDIS_URL,
  85. redis_sentinels=redis_sentinels,
  86. redis_cluster=WEBSOCKET_REDIS_CLUSTER,
  87. )
  88. USER_POOL = RedisDict(
  89. f"{REDIS_KEY_PREFIX}:user_pool",
  90. redis_url=WEBSOCKET_REDIS_URL,
  91. redis_sentinels=redis_sentinels,
  92. redis_cluster=WEBSOCKET_REDIS_CLUSTER,
  93. )
  94. USAGE_POOL = RedisDict(
  95. f"{REDIS_KEY_PREFIX}:usage_pool",
  96. redis_url=WEBSOCKET_REDIS_URL,
  97. redis_sentinels=redis_sentinels,
  98. redis_cluster=WEBSOCKET_REDIS_CLUSTER,
  99. )
  100. clean_up_lock = RedisLock(
  101. redis_url=WEBSOCKET_REDIS_URL,
  102. lock_name=f"{REDIS_KEY_PREFIX}:usage_cleanup_lock",
  103. timeout_secs=WEBSOCKET_REDIS_LOCK_TIMEOUT,
  104. redis_sentinels=redis_sentinels,
  105. redis_cluster=WEBSOCKET_REDIS_CLUSTER,
  106. )
  107. aquire_func = clean_up_lock.aquire_lock
  108. renew_func = clean_up_lock.renew_lock
  109. release_func = clean_up_lock.release_lock
  110. else:
  111. SESSION_POOL = {}
  112. USER_POOL = {}
  113. USAGE_POOL = {}
  114. aquire_func = release_func = renew_func = lambda: True
  115. YDOC_MANAGER = YdocManager(
  116. redis=REDIS,
  117. redis_key_prefix=f"{REDIS_KEY_PREFIX}:ydoc:documents",
  118. )
  119. async def periodic_usage_pool_cleanup():
  120. max_retries = 2
  121. retry_delay = random.uniform(
  122. WEBSOCKET_REDIS_LOCK_TIMEOUT / 2, WEBSOCKET_REDIS_LOCK_TIMEOUT
  123. )
  124. for attempt in range(max_retries + 1):
  125. if aquire_func():
  126. break
  127. else:
  128. if attempt < max_retries:
  129. log.debug(
  130. f"Cleanup lock already exists. Retry {attempt + 1} after {retry_delay}s..."
  131. )
  132. await asyncio.sleep(retry_delay)
  133. else:
  134. log.warning(
  135. "Failed to acquire cleanup lock after retries. Skipping cleanup."
  136. )
  137. return
  138. log.debug("Running periodic_cleanup")
  139. try:
  140. while True:
  141. if not renew_func():
  142. log.error(f"Unable to renew cleanup lock. Exiting usage pool cleanup.")
  143. raise Exception("Unable to renew usage pool cleanup lock.")
  144. now = int(time.time())
  145. send_usage = False
  146. for model_id, connections in list(USAGE_POOL.items()):
  147. # Creating a list of sids to remove if they have timed out
  148. expired_sids = [
  149. sid
  150. for sid, details in connections.items()
  151. if now - details["updated_at"] > TIMEOUT_DURATION
  152. ]
  153. for sid in expired_sids:
  154. del connections[sid]
  155. if not connections:
  156. log.debug(f"Cleaning up model {model_id} from usage pool")
  157. del USAGE_POOL[model_id]
  158. else:
  159. USAGE_POOL[model_id] = connections
  160. send_usage = True
  161. await asyncio.sleep(TIMEOUT_DURATION)
  162. finally:
  163. release_func()
  164. app = socketio.ASGIApp(
  165. sio,
  166. socketio_path="/ws/socket.io",
  167. )
  168. def get_models_in_use():
  169. # List models that are currently in use
  170. models_in_use = list(USAGE_POOL.keys())
  171. return models_in_use
  172. def get_active_user_ids():
  173. """Get the list of active user IDs."""
  174. return list(USER_POOL.keys())
  175. def get_user_active_status(user_id):
  176. """Check if a user is currently active."""
  177. return user_id in USER_POOL
  178. def get_user_id_from_session_pool(sid):
  179. user = SESSION_POOL.get(sid)
  180. if user:
  181. return user["id"]
  182. return None
  183. def get_session_ids_from_room(room):
  184. """Get all session IDs from a specific room."""
  185. active_session_ids = sio.manager.get_participants(
  186. namespace="/",
  187. room=room,
  188. )
  189. return [session_id[0] for session_id in active_session_ids]
  190. def get_user_ids_from_room(room):
  191. active_session_ids = get_session_ids_from_room(room)
  192. active_user_ids = list(
  193. set([SESSION_POOL.get(session_id)["id"] for session_id in active_session_ids])
  194. )
  195. return active_user_ids
  196. def get_active_status_by_user_id(user_id):
  197. if user_id in USER_POOL:
  198. return True
  199. return False
  200. @sio.on("usage")
  201. async def usage(sid, data):
  202. if sid in SESSION_POOL:
  203. model_id = data["model"]
  204. # Record the timestamp for the last update
  205. current_time = int(time.time())
  206. # Store the new usage data and task
  207. USAGE_POOL[model_id] = {
  208. **(USAGE_POOL[model_id] if model_id in USAGE_POOL else {}),
  209. sid: {"updated_at": current_time},
  210. }
  211. @sio.event
  212. async def connect(sid, environ, auth):
  213. user = None
  214. if auth and "token" in auth:
  215. data = decode_token(auth["token"])
  216. if data is not None and "id" in data:
  217. user = Users.get_user_by_id(data["id"])
  218. if user:
  219. SESSION_POOL[sid] = user.model_dump(
  220. exclude=["date_of_birth", "bio", "gender"]
  221. )
  222. if user.id in USER_POOL:
  223. USER_POOL[user.id] = USER_POOL[user.id] + [sid]
  224. else:
  225. USER_POOL[user.id] = [sid]
  226. @sio.on("user-join")
  227. async def user_join(sid, data):
  228. auth = data["auth"] if "auth" in data else None
  229. if not auth or "token" not in auth:
  230. return
  231. data = decode_token(auth["token"])
  232. if data is None or "id" not in data:
  233. return
  234. user = Users.get_user_by_id(data["id"])
  235. if not user:
  236. return
  237. SESSION_POOL[sid] = user.model_dump(exclude=["date_of_birth", "bio", "gender"])
  238. if user.id in USER_POOL:
  239. USER_POOL[user.id] = USER_POOL[user.id] + [sid]
  240. else:
  241. USER_POOL[user.id] = [sid]
  242. # Join all the channels
  243. channels = Channels.get_channels_by_user_id(user.id)
  244. log.debug(f"{channels=}")
  245. for channel in channels:
  246. await sio.enter_room(sid, f"channel:{channel.id}")
  247. return {"id": user.id, "name": user.name}
  248. @sio.on("join-channels")
  249. async def join_channel(sid, data):
  250. auth = data["auth"] if "auth" in data else None
  251. if not auth or "token" not in auth:
  252. return
  253. data = decode_token(auth["token"])
  254. if data is None or "id" not in data:
  255. return
  256. user = Users.get_user_by_id(data["id"])
  257. if not user:
  258. return
  259. # Join all the channels
  260. channels = Channels.get_channels_by_user_id(user.id)
  261. log.debug(f"{channels=}")
  262. for channel in channels:
  263. await sio.enter_room(sid, f"channel:{channel.id}")
  264. @sio.on("join-note")
  265. async def join_note(sid, data):
  266. auth = data["auth"] if "auth" in data else None
  267. if not auth or "token" not in auth:
  268. return
  269. token_data = decode_token(auth["token"])
  270. if token_data is None or "id" not in token_data:
  271. return
  272. user = Users.get_user_by_id(token_data["id"])
  273. if not user:
  274. return
  275. note = Notes.get_note_by_id(data["note_id"])
  276. if not note:
  277. log.error(f"Note {data['note_id']} not found for user {user.id}")
  278. return
  279. if (
  280. user.role != "admin"
  281. and user.id != note.user_id
  282. and not has_access(user.id, type="read", access_control=note.access_control)
  283. ):
  284. log.error(f"User {user.id} does not have access to note {data['note_id']}")
  285. return
  286. log.debug(f"Joining note {note.id} for user {user.id}")
  287. await sio.enter_room(sid, f"note:{note.id}")
  288. @sio.on("channel-events")
  289. async def channel_events(sid, data):
  290. room = f"channel:{data['channel_id']}"
  291. participants = sio.manager.get_participants(
  292. namespace="/",
  293. room=room,
  294. )
  295. sids = [sid for sid, _ in participants]
  296. if sid not in sids:
  297. return
  298. event_data = data["data"]
  299. event_type = event_data["type"]
  300. if event_type == "typing":
  301. await sio.emit(
  302. "channel-events",
  303. {
  304. "channel_id": data["channel_id"],
  305. "message_id": data.get("message_id", None),
  306. "data": event_data,
  307. "user": UserNameResponse(**SESSION_POOL[sid]).model_dump(),
  308. },
  309. room=room,
  310. )
  311. @sio.on("ydoc:document:join")
  312. async def ydoc_document_join(sid, data):
  313. """Handle user joining a document"""
  314. user = SESSION_POOL.get(sid)
  315. try:
  316. document_id = data["document_id"]
  317. if document_id.startswith("note:"):
  318. note_id = document_id.split(":")[1]
  319. note = Notes.get_note_by_id(note_id)
  320. if not note:
  321. log.error(f"Note {note_id} not found")
  322. return
  323. if (
  324. user.get("role") != "admin"
  325. and user.get("id") != note.user_id
  326. and not has_access(
  327. user.get("id"), type="read", access_control=note.access_control
  328. )
  329. ):
  330. log.error(
  331. f"User {user.get('id')} does not have access to note {note_id}"
  332. )
  333. return
  334. user_id = data.get("user_id", sid)
  335. user_name = data.get("user_name", "Anonymous")
  336. user_color = data.get("user_color", "#000000")
  337. log.info(f"User {user_id} joining document {document_id}")
  338. await YDOC_MANAGER.add_user(document_id=document_id, user_id=sid)
  339. # Join Socket.IO room
  340. await sio.enter_room(sid, f"doc_{document_id}")
  341. active_session_ids = get_session_ids_from_room(f"doc_{document_id}")
  342. # Get the Yjs document state
  343. ydoc = Y.Doc()
  344. updates = await YDOC_MANAGER.get_updates(document_id)
  345. for update in updates:
  346. ydoc.apply_update(bytes(update))
  347. # Encode the entire document state as an update
  348. state_update = ydoc.get_update()
  349. await sio.emit(
  350. "ydoc:document:state",
  351. {
  352. "document_id": document_id,
  353. "state": list(state_update), # Convert bytes to list for JSON
  354. "sessions": active_session_ids,
  355. },
  356. room=sid,
  357. )
  358. # Notify other users about the new user
  359. await sio.emit(
  360. "ydoc:user:joined",
  361. {
  362. "document_id": document_id,
  363. "user_id": user_id,
  364. "user_name": user_name,
  365. "user_color": user_color,
  366. },
  367. room=f"doc_{document_id}",
  368. skip_sid=sid,
  369. )
  370. log.info(f"User {user_id} successfully joined document {document_id}")
  371. except Exception as e:
  372. log.error(f"Error in yjs_document_join: {e}")
  373. await sio.emit("error", {"message": "Failed to join document"}, room=sid)
  374. async def document_save_handler(document_id, data, user):
  375. if document_id.startswith("note:"):
  376. note_id = document_id.split(":")[1]
  377. note = Notes.get_note_by_id(note_id)
  378. if not note:
  379. log.error(f"Note {note_id} not found")
  380. return
  381. if (
  382. user.get("role") != "admin"
  383. and user.get("id") != note.user_id
  384. and not has_access(
  385. user.get("id"), type="read", access_control=note.access_control
  386. )
  387. ):
  388. log.error(f"User {user.get('id')} does not have access to note {note_id}")
  389. return
  390. Notes.update_note_by_id(note_id, NoteUpdateForm(data=data))
  391. @sio.on("ydoc:document:state")
  392. async def yjs_document_state(sid, data):
  393. """Send the current state of the Yjs document to the user"""
  394. try:
  395. document_id = data["document_id"]
  396. room = f"doc_{document_id}"
  397. active_session_ids = get_session_ids_from_room(room)
  398. if sid not in active_session_ids:
  399. log.warning(f"Session {sid} not in room {room}. Cannot send state.")
  400. return
  401. if not await YDOC_MANAGER.document_exists(document_id):
  402. log.warning(f"Document {document_id} not found")
  403. return
  404. # Get the Yjs document state
  405. ydoc = Y.Doc()
  406. updates = await YDOC_MANAGER.get_updates(document_id)
  407. for update in updates:
  408. ydoc.apply_update(bytes(update))
  409. # Encode the entire document state as an update
  410. state_update = ydoc.get_update()
  411. await sio.emit(
  412. "ydoc:document:state",
  413. {
  414. "document_id": document_id,
  415. "state": list(state_update), # Convert bytes to list for JSON
  416. "sessions": active_session_ids,
  417. },
  418. room=sid,
  419. )
  420. except Exception as e:
  421. log.error(f"Error in yjs_document_state: {e}")
  422. @sio.on("ydoc:document:update")
  423. async def yjs_document_update(sid, data):
  424. """Handle Yjs document updates"""
  425. try:
  426. document_id = data["document_id"]
  427. try:
  428. await stop_item_tasks(REDIS, document_id)
  429. except:
  430. pass
  431. user_id = data.get("user_id", sid)
  432. update = data["update"] # List of bytes from frontend
  433. await YDOC_MANAGER.append_to_updates(
  434. document_id=document_id,
  435. update=update, # Convert list of bytes to bytes
  436. )
  437. # Broadcast update to all other users in the document
  438. await sio.emit(
  439. "ydoc:document:update",
  440. {
  441. "document_id": document_id,
  442. "user_id": user_id,
  443. "update": update,
  444. "socket_id": sid, # Add socket_id to match frontend filtering
  445. },
  446. room=f"doc_{document_id}",
  447. skip_sid=sid,
  448. )
  449. async def debounced_save():
  450. await asyncio.sleep(0.5)
  451. await document_save_handler(
  452. document_id, data.get("data", {}), SESSION_POOL.get(sid)
  453. )
  454. if data.get("data"):
  455. await create_task(REDIS, debounced_save(), document_id)
  456. except Exception as e:
  457. log.error(f"Error in yjs_document_update: {e}")
  458. @sio.on("ydoc:document:leave")
  459. async def yjs_document_leave(sid, data):
  460. """Handle user leaving a document"""
  461. try:
  462. document_id = data["document_id"]
  463. user_id = data.get("user_id", sid)
  464. log.info(f"User {user_id} leaving document {document_id}")
  465. # Remove user from the document
  466. await YDOC_MANAGER.remove_user(document_id=document_id, user_id=sid)
  467. # Leave Socket.IO room
  468. await sio.leave_room(sid, f"doc_{document_id}")
  469. # Notify other users
  470. await sio.emit(
  471. "ydoc:user:left",
  472. {"document_id": document_id, "user_id": user_id},
  473. room=f"doc_{document_id}",
  474. )
  475. if (
  476. await YDOC_MANAGER.document_exists(document_id)
  477. and len(await YDOC_MANAGER.get_users(document_id)) == 0
  478. ):
  479. log.info(f"Cleaning up document {document_id} as no users are left")
  480. await YDOC_MANAGER.clear_document(document_id)
  481. except Exception as e:
  482. log.error(f"Error in yjs_document_leave: {e}")
  483. @sio.on("ydoc:awareness:update")
  484. async def yjs_awareness_update(sid, data):
  485. """Handle awareness updates (cursors, selections, etc.)"""
  486. try:
  487. document_id = data["document_id"]
  488. user_id = data.get("user_id", sid)
  489. update = data["update"]
  490. # Broadcast awareness update to all other users in the document
  491. await sio.emit(
  492. "ydoc:awareness:update",
  493. {"document_id": document_id, "user_id": user_id, "update": update},
  494. room=f"doc_{document_id}",
  495. skip_sid=sid,
  496. )
  497. except Exception as e:
  498. log.error(f"Error in yjs_awareness_update: {e}")
  499. @sio.event
  500. async def disconnect(sid):
  501. if sid in SESSION_POOL:
  502. user = SESSION_POOL[sid]
  503. del SESSION_POOL[sid]
  504. user_id = user["id"]
  505. USER_POOL[user_id] = [_sid for _sid in USER_POOL[user_id] if _sid != sid]
  506. if len(USER_POOL[user_id]) == 0:
  507. del USER_POOL[user_id]
  508. await YDOC_MANAGER.remove_user_from_all_documents(sid)
  509. else:
  510. pass
  511. # print(f"Unknown session ID {sid} disconnected")
  512. def get_event_emitter(request_info, update_db=True):
  513. async def __event_emitter__(event_data):
  514. user_id = request_info["user_id"]
  515. session_ids = list(
  516. set(
  517. USER_POOL.get(user_id, [])
  518. + (
  519. [request_info.get("session_id")]
  520. if request_info.get("session_id")
  521. else []
  522. )
  523. )
  524. )
  525. chat_id = request_info.get("chat_id", None)
  526. message_id = request_info.get("message_id", None)
  527. emit_tasks = [
  528. sio.emit(
  529. "chat-events",
  530. {
  531. "chat_id": chat_id,
  532. "message_id": message_id,
  533. "data": event_data,
  534. },
  535. to=session_id,
  536. )
  537. for session_id in session_ids
  538. ]
  539. await asyncio.gather(*emit_tasks)
  540. if (
  541. update_db
  542. and message_id
  543. and not request_info.get("chat_id", "").startswith("local:")
  544. ):
  545. if "type" in event_data and event_data["type"] == "status":
  546. Chats.add_message_status_to_chat_by_id_and_message_id(
  547. request_info["chat_id"],
  548. request_info["message_id"],
  549. event_data.get("data", {}),
  550. )
  551. if "type" in event_data and event_data["type"] == "message":
  552. message = Chats.get_message_by_id_and_message_id(
  553. request_info["chat_id"],
  554. request_info["message_id"],
  555. )
  556. if message:
  557. content = message.get("content", "")
  558. content += event_data.get("data", {}).get("content", "")
  559. Chats.upsert_message_to_chat_by_id_and_message_id(
  560. request_info["chat_id"],
  561. request_info["message_id"],
  562. {
  563. "content": content,
  564. },
  565. )
  566. if "type" in event_data and event_data["type"] == "replace":
  567. content = event_data.get("data", {}).get("content", "")
  568. Chats.upsert_message_to_chat_by_id_and_message_id(
  569. request_info["chat_id"],
  570. request_info["message_id"],
  571. {
  572. "content": content,
  573. },
  574. )
  575. if "type" in event_data and event_data["type"] == "embeds":
  576. message = Chats.get_message_by_id_and_message_id(
  577. request_info["chat_id"],
  578. request_info["message_id"],
  579. )
  580. embeds = event_data.get("data", {}).get("embeds", [])
  581. embeds.extend(message.get("embeds", []))
  582. Chats.upsert_message_to_chat_by_id_and_message_id(
  583. request_info["chat_id"],
  584. request_info["message_id"],
  585. {
  586. "embeds": embeds,
  587. },
  588. )
  589. if "type" in event_data and event_data["type"] == "files":
  590. message = Chats.get_message_by_id_and_message_id(
  591. request_info["chat_id"],
  592. request_info["message_id"],
  593. )
  594. files = event_data.get("data", {}).get("files", [])
  595. files.extend(message.get("files", []))
  596. Chats.upsert_message_to_chat_by_id_and_message_id(
  597. request_info["chat_id"],
  598. request_info["message_id"],
  599. {
  600. "files": files,
  601. },
  602. )
  603. if event_data.get("type") in ["source", "citation"]:
  604. data = event_data.get("data", {})
  605. if data.get("type") == None:
  606. message = Chats.get_message_by_id_and_message_id(
  607. request_info["chat_id"],
  608. request_info["message_id"],
  609. )
  610. sources = message.get("sources", [])
  611. sources.append(data)
  612. Chats.upsert_message_to_chat_by_id_and_message_id(
  613. request_info["chat_id"],
  614. request_info["message_id"],
  615. {
  616. "sources": sources,
  617. },
  618. )
  619. return __event_emitter__
  620. def get_event_call(request_info):
  621. async def __event_caller__(event_data):
  622. response = await sio.call(
  623. "chat-events",
  624. {
  625. "chat_id": request_info.get("chat_id", None),
  626. "message_id": request_info.get("message_id", None),
  627. "data": event_data,
  628. },
  629. to=request_info["session_id"],
  630. )
  631. return response
  632. return __event_caller__
  633. get_event_caller = get_event_call