Portal.tsx 7.3 KB

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