websockets.js 10.4 KB
Newer Older
mntmn's avatar
mntmn committed
1
2
3
'use strict';
require('../models/schema');

4
5
const config = require('config');

mntmn's avatar
mntmn committed
6
7
const WebSocketServer = require('ws').Server;

8
const RedisConnection = require('ioredis');
mntmn's avatar
mntmn committed
9
10
11
12
13
const async = require('async');
const _ = require("underscore");
const mongoose = require("mongoose");
const crypto = require('crypto');

14
const redisMock = require("./redis.js");
mntmn's avatar
mntmn committed
15

mntmn's avatar
mntmn committed
16
module.exports = {
mntmn's avatar
mntmn committed
17
  startWebsockets: function(server) {
mntmn's avatar
mntmn committed
18
    this.setupSubscription();
mntmn's avatar
mntmn committed
19
    
20
21
22
23
24
25
    if (!this.current_websockets) {
      if (config.get("redis_mock")) {
        this.state = redisMock.getConnection();
      } else {
        this.state = new RedisConnection(6379, process.env.REDIS_PORT_6379_TCP_ADDR || config.get("redis_host"));
      }
mntmn's avatar
mntmn committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
      this.current_websockets = [];
    }

    const wss = new WebSocketServer({ server:server,  path: "/socket" });
    wss.on('connection', function(ws) {

      this.state.incr("socket_id", function(err, socketCounter) {
        const socketId = "socket_"  + socketCounter + "_" + crypto.randomBytes(64).toString('hex').substring(0,8);
        const serverScope = this;

        ws.on('message', function(msgString){
          const socket = this;

          const msg = JSON.parse(msgString);

          if(msg.action == "auth"){

            const token = msg.auth_token;
            const editorName = msg.editor_name;
            const editorAuth = msg.editor_auth;
            const spaceId = msg.space_id;

            Space.findOne({"_id": spaceId}).populate('creator').exec((err, space) => {
              if (space) {
                const upgradeSocket = function() {
                  if (token) {
                    User.findBySessionToken(token, function(err, user) {
                      if (err) {
                        console.error(err, user);
                      } else {
                        if (user) {
                          serverScope.addUserInSpace(user._id, space, ws, function(err){
                            serverScope.addLocalUser(user._id, ws);
                            console.log("[websockets] user " + user.email + " online in space " +  space._id);
                          });
                        }
                      }
                    });
                  } else {
                    const anonymousUserId = space._id + "-" + editorName;

                    if(space.access_mode == "private" && space.edit_hash != editorAuth){
                      console.error("closing websocket: unauthed.");
                      ws.send(JSON.stringify({error: "auth_failed"}));
                      // ws.close();
                      return;
                    }

                    serverScope.addUserInSpace(anonymousUserId, space, ws, function(err){
                      serverScope.addLocalUser(anonymousUserId, ws);
                      console.log("[websockets] anonymous user " + anonymousUserId + " online in space " +  space._id);
                    });
                  }
                };

                if (!ws.id) {
                  ws['id'] = socketId;
                  try {
                    ws.send(JSON.stringify({"action": "init", "channel_id": socketId}));
                  } catch (e) {
                    console.log("ws.send error: "+e);
                  }
                }

                if (ws.space_id) {
                  serverScope.removeUserInSpace(ws.space_id, ws, function(err) {
                    upgradeSocket();
                  });
                } else {
                  upgradeSocket();
                }
              } else {
                ws.send(JSON.stringify({error: "space not found"}));
                ws.close();
                return;
              }
            });

          } else if (msg.action == "cursor" || msg.action == "viewport" || msg.action=="media") {
            msg.space_id = socket.space_id;
            msg.from_socket_id = socket.id;
            serverScope.state.publish('cursors', JSON.stringify(msg));
          }
        });

        ws.on('close', function(evt) {
          console.log("websocket closed: ", ws.id, ws.space_id);
          const spaceId = ws.space_id;
          serverScope.removeUserInSpace(spaceId, ws, function(err) {
            this.removeLocalUser(ws, function(err) {
            }.bind(this));
          }.bind(this));
        }.bind(this));

        ws.on('error', function(ws, err) {
          console.error(err, res);
        }.bind(this));
      }.bind(this));
    }.bind(this));
  },

  setupSubscription: function() {
128
129
130
131
132
133
134
135
136
137
138
    if (config.get("redis_mock")) {
      this.cursorSubscriber = redisMock.getConnection().subscribe(['cursors', 'users', 'updates'], function (err, count) {
        console.log("[redis-mock] websockets subscribed to " + count + " topics." );
      });
    } else {
      this.cursorSubscriber = new RedisConnection(6379, process.env.REDIS_PORT_6379_TCP_ADDR || config.get("redis_host"));
      this.cursorSubscriber.subscribe(['cursors', 'users', 'updates'], function (err, count) {
        console.log("[redis] websockets subscribed to " + count + " topics." );
      });
    }
    
mntmn's avatar
mntmn committed
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
    this.cursorSubscriber.on('message', function (channel, rawMessage) {
      const msg = JSON.parse(rawMessage);
      const spaceId = msg.space_id;

      const websockets = this.current_websockets;

      if(channel === "updates") {
        for(let i=0;i<websockets.length;i++) {
          const ws = websockets[i];
          if(ws.readyState === 1) {
            ws.send(JSON.stringify(msg));
          }
        }
      } else if(channel === "users") {
        const usersList = msg.users;

        if (usersList) {
          for(let i=0;i<usersList.length;i++) {
            const activeUser = usersList[i];
            let user_id;

            if (activeUser._id) {
              user_id = activeUser._id;
            } else {
              user_id = spaceId + "-" + (activeUser.nickname||"anonymous");
            }

            for (let a=0; a < websockets.length; a++) {
              const ws = websockets[a];
              if(ws.readyState === 1){
                if(ws.space_id == spaceId) {
                  ws.send(JSON.stringify({"action": "status_update", space_id: spaceId, users: usersList}));
                } else {
                  //console.log("space id not matching", spaceId, ws.space_id);
                }

              } else {
                // FIXME SHOULD CLEANUP SOCKET HERE
                console.error("socket in wrong state", ws.readyState);
                if(ws.readyState == 3) {
                  this.removeLocalUser(ws, (err) => {
                    console.log("old websocket removed");
                  });
                }
              }
            }
          }
        } else {
          console.error("userlist undefined for websocket");
        }
      } else if(channel === "cursors") {
        const socketId = msg.from_socket_id;
        for (let i=0;i<websockets.length;i++) {
          const ws = websockets[i];
          if (ws.readyState === 1) {
            if (ws.space_id && spaceId) {
              if ((ws.space_id == spaceId) && (ws.id !== socketId)) {
                ws.send(JSON.stringify(msg));
              }
            } else {
              console.log("space id not set, ignoring");
            }
          }
        }
      }
    }.bind(this));
  },

  addLocalUser: function(username, ws) {
    if (ws.added) {
      return;
    }
    ws.added = true;
    this.current_websockets.push(ws);
  },
  
  removeLocalUser: function(ws, cb) {
    const idx = this.current_websockets.indexOf(ws);
    if(idx > -1) {
      this.removed_items = this.current_websockets.splice(idx, 1);
      console.log("removed local socket, current online on this process: ", this.current_websockets.length);
    } else {
      console.log("websocket not found to remove");
    }

mntmn's avatar
mntmn committed
224
    this.state.del(ws.id+"", function(err, res) {
mntmn's avatar
mntmn committed
225
226
227
228
229
230
231
232
233
234
235
236
237
238
      if (err) console.error(err, res);
      else {
        this.removeUserInSpace(ws.space_id, ws, (err) => {
          console.log("removed user from space list");
          this.distributeUsers(ws.space_id);
        })
        if(cb)
          cb(err);
      }
    }.bind(this));
  },
  
  addUserInSpace: function(username, space, ws, cb) {
    console.log("[websockets] user "+username+" in "+space.access_mode +" space " +  space._id + " with socket "  +  ws.id);
mntmn's avatar
mntmn committed
239
240
    
    this.state.set(ws.id+"", username+"", function(err, res) {
mntmn's avatar
mntmn committed
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
      if(err) console.error(err, res);
      else {
        this.state.sadd("space_" + space._id, ws.id, function(err, res) {
          if(err) cb(err);
          else {
            ws['space_id'] = space._id.toString();

            this.distributeUsers(ws.space_id);
            if(cb)
              cb();
          }
        }.bind(this));
      }
    }.bind(this));
  },
  removeUserInSpace: function(spaceId, ws, cb) {
mntmn's avatar
mntmn committed
257
    this.state.srem("space_" + spaceId, ws.id+"", function(err, res) {
mntmn's avatar
mntmn committed
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
      if (err) cb(err);
      else {
        console.log("[websockets] socket "+  ws.id + " went offline in space " + spaceId);
        this.distributeUsers(spaceId);
        ws['space_id'] = null;

        if (cb)
          cb();
      }
    }.bind(this));
  },

  distributeUsers: function(spaceId) {
    if(!spaceId)
      return;

    this.state.smembers("space_" + spaceId, function(err, list) {
      async.map(list, function(item, callback) {
        this.state.get(item, function(err, userId) {
          console.log(item, "->", userId);
          callback(null, userId);
        });
      }.bind(this), function(err, userIds) {
        const uniqueUserIds = _.unique(userIds);
        const validUserIds = _.filter(uniqueUserIds, function(uId) {
          return mongoose.Types.ObjectId.isValid(uId);
        });

        const nonValidUserIds = _.filter(uniqueUserIds, function(uId) {
          return (uId !== null && !mongoose.Types.ObjectId.isValid(uId));
        });

        const anonymousUsers = _.map(nonValidUserIds, function(nonValidId) {
          const realNickname = nonValidId.slice(nonValidId.indexOf("-")+1);
          return {nickname: realNickname, email: null, avatar_thumbnail_uri: null };
        });

        User.find({"_id" : { "$in" : validUserIds }}, { "nickname" : 1 ,  "email" : 1, "avatar_thumbnail_uri": 1 }, function(err, users) {
          if (err)
            console.error(err);
          else {
            const allUsers = users.concat(anonymousUsers);
            const strUsers = JSON.stringify({users: allUsers, space_id: spaceId});
            this.state.publish("users", strUsers);
          }
        }.bind(this));
      }.bind(this));
    }.bind(this));
  }
};