Portal.tsx 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import {
  2. isSyncableElement,
  3. SocketUpdateData,
  4. SocketUpdateDataSource,
  5. } from "../data";
  6. import { TCollabClass } from "./Collab";
  7. import { ExcalidrawElement } from "../../packages/excalidraw/element/types";
  8. import {
  9. WS_EVENTS,
  10. FILE_UPLOAD_TIMEOUT,
  11. WS_SCENE_EVENT_TYPES,
  12. } from "../app_constants";
  13. import { UserIdleState } from "../../packages/excalidraw/types";
  14. import { trackEvent } from "../../packages/excalidraw/analytics";
  15. import throttle from "lodash.throttle";
  16. import { newElementWith } from "../../packages/excalidraw/element/mutateElement";
  17. import { BroadcastedExcalidrawElement } from "./reconciliation";
  18. import { encryptData } from "../../packages/excalidraw/data/encryption";
  19. import { PRECEDING_ELEMENT_KEY } from "../../packages/excalidraw/constants";
  20. class Portal {
  21. collab: TCollabClass;
  22. socket: SocketIOClient.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: SocketIOClient.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_SCENE_EVENT_TYPES.INIT,
  44. this.collab.getSceneElementsIncludingDeleted(),
  45. /* syncAll */ true,
  46. );
  47. });
  48. this.socket.on("room-user-change", (clients: string[]) => {
  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. ) {
  77. if (this.isOpen()) {
  78. const json = JSON.stringify(data);
  79. const encoded = new TextEncoder().encode(json);
  80. const { encryptedBuffer, iv } = await encryptData(this.roomKey!, encoded);
  81. this.socket?.emit(
  82. volatile ? WS_EVENTS.SERVER_VOLATILE : WS_EVENTS.SERVER,
  83. this.roomId,
  84. encryptedBuffer,
  85. iv,
  86. );
  87. }
  88. }
  89. queueFileUpload = throttle(async () => {
  90. try {
  91. await this.collab.fileManager.saveFiles({
  92. elements: this.collab.excalidrawAPI.getSceneElementsIncludingDeleted(),
  93. files: this.collab.excalidrawAPI.getFiles(),
  94. });
  95. } catch (error: any) {
  96. if (error.name !== "AbortError") {
  97. this.collab.excalidrawAPI.updateScene({
  98. appState: {
  99. errorMessage: error.message,
  100. },
  101. });
  102. }
  103. }
  104. this.collab.excalidrawAPI.updateScene({
  105. elements: this.collab.excalidrawAPI
  106. .getSceneElementsIncludingDeleted()
  107. .map((element) => {
  108. if (this.collab.fileManager.shouldUpdateImageElementStatus(element)) {
  109. // this will signal collaborators to pull image data from server
  110. // (using mutation instead of newElementWith otherwise it'd break
  111. // in-progress dragging)
  112. return newElementWith(element, { status: "saved" });
  113. }
  114. return element;
  115. }),
  116. });
  117. }, FILE_UPLOAD_TIMEOUT);
  118. broadcastScene = async (
  119. updateType: WS_SCENE_EVENT_TYPES.INIT | WS_SCENE_EVENT_TYPES.UPDATE,
  120. allElements: readonly ExcalidrawElement[],
  121. syncAll: boolean,
  122. ) => {
  123. if (updateType === WS_SCENE_EVENT_TYPES.INIT && !syncAll) {
  124. throw new Error("syncAll must be true when sending SCENE.INIT");
  125. }
  126. // sync out only the elements we think we need to to save bandwidth.
  127. // periodically we'll resync the whole thing to make sure no one diverges
  128. // due to a dropped message (server goes down etc).
  129. const syncableElements = allElements.reduce(
  130. (acc, element: BroadcastedExcalidrawElement, idx, elements) => {
  131. if (
  132. (syncAll ||
  133. !this.broadcastedElementVersions.has(element.id) ||
  134. element.version >
  135. this.broadcastedElementVersions.get(element.id)!) &&
  136. isSyncableElement(element)
  137. ) {
  138. acc.push({
  139. ...element,
  140. // z-index info for the reconciler
  141. [PRECEDING_ELEMENT_KEY]: idx === 0 ? "^" : elements[idx - 1]?.id,
  142. });
  143. }
  144. return acc;
  145. },
  146. [] as BroadcastedExcalidrawElement[],
  147. );
  148. const data: SocketUpdateDataSource[typeof updateType] = {
  149. type: updateType,
  150. payload: {
  151. elements: syncableElements,
  152. },
  153. };
  154. for (const syncableElement of syncableElements) {
  155. this.broadcastedElementVersions.set(
  156. syncableElement.id,
  157. syncableElement.version,
  158. );
  159. }
  160. this.queueFileUpload();
  161. await this._broadcastSocketData(data as SocketUpdateData);
  162. };
  163. broadcastIdleChange = (userState: UserIdleState) => {
  164. if (this.socket?.id) {
  165. const data: SocketUpdateDataSource["IDLE_STATUS"] = {
  166. type: "IDLE_STATUS",
  167. payload: {
  168. socketId: this.socket.id,
  169. userState,
  170. username: this.collab.state.username,
  171. },
  172. };
  173. return this._broadcastSocketData(
  174. data as SocketUpdateData,
  175. true, // volatile
  176. );
  177. }
  178. };
  179. broadcastMouseLocation = (payload: {
  180. pointer: SocketUpdateDataSource["MOUSE_LOCATION"]["payload"]["pointer"];
  181. button: SocketUpdateDataSource["MOUSE_LOCATION"]["payload"]["button"];
  182. }) => {
  183. if (this.socket?.id) {
  184. const data: SocketUpdateDataSource["MOUSE_LOCATION"] = {
  185. type: "MOUSE_LOCATION",
  186. payload: {
  187. socketId: this.socket.id,
  188. pointer: payload.pointer,
  189. button: payload.button || "up",
  190. selectedElementIds:
  191. this.collab.excalidrawAPI.getAppState().selectedElementIds,
  192. username: this.collab.state.username,
  193. },
  194. };
  195. return this._broadcastSocketData(
  196. data as SocketUpdateData,
  197. true, // volatile
  198. );
  199. }
  200. };
  201. }
  202. export default Portal;