Portal.tsx 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import {
  2. isSyncableElement,
  3. SocketUpdateData,
  4. SocketUpdateDataSource,
  5. SyncableExcalidrawElement,
  6. } from "../data";
  7. import { TCollabClass } from "./Collab";
  8. import { OrderedExcalidrawElement } from "../../packages/excalidraw/element/types";
  9. import { WS_EVENTS, FILE_UPLOAD_TIMEOUT, WS_SUBTYPES } from "../app_constants";
  10. import {
  11. OnUserFollowedPayload,
  12. SocketId,
  13. UserIdleState,
  14. } from "../../packages/excalidraw/types";
  15. import { trackEvent } from "../../packages/excalidraw/analytics";
  16. import throttle from "lodash.throttle";
  17. import { newElementWith } from "../../packages/excalidraw/element/mutateElement";
  18. import { encryptData } from "../../packages/excalidraw/data/encryption";
  19. import type { Socket } from "socket.io-client";
  20. class Portal {
  21. collab: TCollabClass;
  22. socket: Socket | null = null;
  23. socketInitialized: boolean = false; // we don't want the socket to emit any updates until it is fully initialized
  24. roomId: string | null = null;
  25. roomKey: string | null = null;
  26. broadcastedElementVersions: Map<string, number> = new Map();
  27. constructor(collab: TCollabClass) {
  28. this.collab = collab;
  29. }
  30. open(socket: Socket, id: string, key: string) {
  31. this.socket = socket;
  32. this.roomId = id;
  33. this.roomKey = key;
  34. // Initialize socket listeners
  35. this.socket.on("init-room", () => {
  36. if (this.socket) {
  37. this.socket.emit("join-room", this.roomId);
  38. trackEvent("share", "room joined");
  39. }
  40. });
  41. this.socket.on("new-user", async (_socketId: string) => {
  42. this.broadcastScene(
  43. WS_SUBTYPES.INIT,
  44. this.collab.getSceneElementsIncludingDeleted(),
  45. /* syncAll */ true,
  46. );
  47. });
  48. this.socket.on("room-user-change", (clients: SocketId[]) => {
  49. this.collab.setCollaborators(clients);
  50. });
  51. return socket;
  52. }
  53. close() {
  54. if (!this.socket) {
  55. return;
  56. }
  57. this.queueFileUpload.flush();
  58. this.socket.close();
  59. this.socket = null;
  60. this.roomId = null;
  61. this.roomKey = null;
  62. this.socketInitialized = false;
  63. this.broadcastedElementVersions = new Map();
  64. }
  65. isOpen() {
  66. return !!(
  67. this.socketInitialized &&
  68. this.socket &&
  69. this.roomId &&
  70. this.roomKey
  71. );
  72. }
  73. async _broadcastSocketData(
  74. data: SocketUpdateData,
  75. volatile: boolean = false,
  76. roomId?: string,
  77. ) {
  78. if (this.isOpen()) {
  79. const json = JSON.stringify(data);
  80. const encoded = new TextEncoder().encode(json);
  81. const { encryptedBuffer, iv } = await encryptData(this.roomKey!, encoded);
  82. this.socket?.emit(
  83. volatile ? WS_EVENTS.SERVER_VOLATILE : WS_EVENTS.SERVER,
  84. roomId ?? this.roomId,
  85. encryptedBuffer,
  86. iv,
  87. );
  88. }
  89. }
  90. queueFileUpload = throttle(async () => {
  91. try {
  92. await this.collab.fileManager.saveFiles({
  93. elements: this.collab.excalidrawAPI.getSceneElementsIncludingDeleted(),
  94. files: this.collab.excalidrawAPI.getFiles(),
  95. });
  96. } catch (error: any) {
  97. if (error.name !== "AbortError") {
  98. this.collab.excalidrawAPI.updateScene({
  99. appState: {
  100. errorMessage: error.message,
  101. },
  102. });
  103. }
  104. }
  105. this.collab.excalidrawAPI.updateScene({
  106. elements: this.collab.excalidrawAPI
  107. .getSceneElementsIncludingDeleted()
  108. .map((element) => {
  109. if (this.collab.fileManager.shouldUpdateImageElementStatus(element)) {
  110. // this will signal collaborators to pull image data from server
  111. // (using mutation instead of newElementWith otherwise it'd break
  112. // in-progress dragging)
  113. return newElementWith(element, { status: "saved" });
  114. }
  115. return element;
  116. }),
  117. });
  118. }, FILE_UPLOAD_TIMEOUT);
  119. broadcastScene = async (
  120. updateType: WS_SUBTYPES.INIT | WS_SUBTYPES.UPDATE,
  121. elements: readonly OrderedExcalidrawElement[],
  122. syncAll: boolean,
  123. ) => {
  124. if (updateType === WS_SUBTYPES.INIT && !syncAll) {
  125. throw new Error("syncAll must be true when sending SCENE.INIT");
  126. }
  127. // sync out only the elements we think we need to to save bandwidth.
  128. // periodically we'll resync the whole thing to make sure no one diverges
  129. // due to a dropped message (server goes down etc).
  130. const syncableElements = elements.reduce((acc, element) => {
  131. if (
  132. (syncAll ||
  133. !this.broadcastedElementVersions.has(element.id) ||
  134. element.version > this.broadcastedElementVersions.get(element.id)!) &&
  135. isSyncableElement(element)
  136. ) {
  137. acc.push(element);
  138. }
  139. return acc;
  140. }, [] as SyncableExcalidrawElement[]);
  141. const data: SocketUpdateDataSource[typeof updateType] = {
  142. type: updateType,
  143. payload: {
  144. elements: syncableElements,
  145. },
  146. };
  147. for (const syncableElement of syncableElements) {
  148. this.broadcastedElementVersions.set(
  149. syncableElement.id,
  150. syncableElement.version,
  151. );
  152. }
  153. this.queueFileUpload();
  154. await this._broadcastSocketData(data as SocketUpdateData);
  155. };
  156. broadcastIdleChange = (userState: UserIdleState) => {
  157. if (this.socket?.id) {
  158. const data: SocketUpdateDataSource["IDLE_STATUS"] = {
  159. type: WS_SUBTYPES.IDLE_STATUS,
  160. payload: {
  161. socketId: this.socket.id as SocketId,
  162. userState,
  163. username: this.collab.state.username,
  164. },
  165. };
  166. return this._broadcastSocketData(
  167. data as SocketUpdateData,
  168. true, // volatile
  169. );
  170. }
  171. };
  172. broadcastMouseLocation = (payload: {
  173. pointer: SocketUpdateDataSource["MOUSE_LOCATION"]["payload"]["pointer"];
  174. button: SocketUpdateDataSource["MOUSE_LOCATION"]["payload"]["button"];
  175. }) => {
  176. if (this.socket?.id) {
  177. const data: SocketUpdateDataSource["MOUSE_LOCATION"] = {
  178. type: WS_SUBTYPES.MOUSE_LOCATION,
  179. payload: {
  180. socketId: this.socket.id as SocketId,
  181. pointer: payload.pointer,
  182. button: payload.button || "up",
  183. selectedElementIds:
  184. this.collab.excalidrawAPI.getAppState().selectedElementIds,
  185. username: this.collab.state.username,
  186. },
  187. };
  188. return this._broadcastSocketData(
  189. data as SocketUpdateData,
  190. true, // volatile
  191. );
  192. }
  193. };
  194. broadcastVisibleSceneBounds = (
  195. payload: {
  196. sceneBounds: SocketUpdateDataSource["USER_VISIBLE_SCENE_BOUNDS"]["payload"]["sceneBounds"];
  197. },
  198. roomId: string,
  199. ) => {
  200. if (this.socket?.id) {
  201. const data: SocketUpdateDataSource["USER_VISIBLE_SCENE_BOUNDS"] = {
  202. type: WS_SUBTYPES.USER_VISIBLE_SCENE_BOUNDS,
  203. payload: {
  204. socketId: this.socket.id as SocketId,
  205. username: this.collab.state.username,
  206. sceneBounds: payload.sceneBounds,
  207. },
  208. };
  209. return this._broadcastSocketData(
  210. data as SocketUpdateData,
  211. true, // volatile
  212. roomId,
  213. );
  214. }
  215. };
  216. broadcastUserFollowed = (payload: OnUserFollowedPayload) => {
  217. if (this.socket?.id) {
  218. this.socket.emit(WS_EVENTS.USER_FOLLOW_CHANGE, payload);
  219. }
  220. };
  221. }
  222. export default Portal;