main.py 23 KB

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