Просмотр исходного кода

Implement a socket to emit when the last user leaves the Editor

Shun Miyazawa 1 год назад
Родитель
Сommit
af39515fd4
1 измененных файлов с 18 добавлено и 0 удалено
  1. 18 0
      apps/app/src/server/service/socket-io.js

+ 18 - 0
apps/app/src/server/service/socket-io.js

@@ -1,4 +1,5 @@
 import { GlobalSocketEventName } from '@growi/core/dist/interfaces';
 import { GlobalSocketEventName } from '@growi/core/dist/interfaces';
+import mongoose from 'mongoose';
 import { Server } from 'socket.io';
 import { Server } from 'socket.io';
 
 
 import { SocketEventName } from '~/interfaces/websocket';
 import { SocketEventName } from '~/interfaces/websocket';
@@ -169,14 +170,31 @@ class SocketIoService {
 
 
   setupYjsConnection() {
   setupYjsConnection() {
     const yjsConnectionManager = getYjsConnectionManager();
     const yjsConnectionManager = getYjsConnectionManager();
+    const Page = mongoose.model('Page');
     this.io.on('connection', (socket) => {
     this.io.on('connection', (socket) => {
 
 
       yjsConnectionManager.ysocketioInstance.on('awareness-update', async(update) => {
       yjsConnectionManager.ysocketioInstance.on('awareness-update', async(update) => {
         const pageId = extractPageIdFromYdocId(update.name);
         const pageId = extractPageIdFromYdocId(update.name);
         const awarenessStateSize = update.awareness.states.size;
         const awarenessStateSize = update.awareness.states.size;
+
         this.io
         this.io
           .in(getRoomNameWithId(RoomPrefix.PAGE, pageId))
           .in(getRoomNameWithId(RoomPrefix.PAGE, pageId))
           .emit(SocketEventName.YjsAwarenessStateUpdated, awarenessStateSize);
           .emit(SocketEventName.YjsAwarenessStateUpdated, awarenessStateSize);
+
+        // Executed when the last user leaves the Editor
+        if (awarenessStateSize === 0) {
+          const page = await Page.findOne({ _id: pageId });
+          if (page != null) {
+            const populatedPage = await page.populateDataToShowRevision();
+            const revisionBody = populatedPage.revision.body;
+            const currentYdoc = yjsConnectionManager.getCurrentYdoc(pageId);
+            const yjsDraft = currentYdoc?.getText('codemirror').toString();
+            const hasRevisionBodyDiff = revisionBody != null && yjsDraft != null && yjsDraft !== revisionBody;
+            this.io
+              .in(getRoomNameWithId(RoomPrefix.PAGE, pageId))
+              .emit(SocketEventName.YjsHasRevisionBodyDiffUpdated, hasRevisionBodyDiff);
+          }
+        }
       });
       });
 
 
       socket.on(GlobalSocketEventName.YDocSync, async({ pageId, initialValue }) => {
       socket.on(GlobalSocketEventName.YDocSync, async({ pageId, initialValue }) => {