-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket-server.js
101 lines (94 loc) · 2.83 KB
/
socket-server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
"use strict";
var socketIO = require("socket.io");
var ot = require("ot");
var roomList = {};
module.exports = function (server) {
var html = "HTML";
var css = "CSS";
var js = "JS";
var io = socketIO(server);
io.on("connection", function (socket) {
socket.on("joinRoom", function (data) {
// check if socket-room exists
if (!roomList[data.room]) {
// check the type of connection if it is from html editor
if(data.editor === 'html') {
console.log('html');
// create an exclusive socketServer fot the editor that is connected
var socketIOServer = new ot.EditorSocketIOServer(
// the document which editor is using
html,
// editor operations
[],
// document id
data.room,
// what happens when user writes in document
function (socket, cb) {
var self = this;
// find the project by its document id and update it's data
Project.findByIdAndUpdate(
data.docId,
// update html part of project
{ html: self.document },
// check if there's any error
function (err) {
if (err) return cb(false);
cb(true);
}
);
}
);
}
if(data.editor === 'css') {
console.log('css');
var socketIOServer = new ot.EditorSocketIOServer(
css,
[],
data.room,
function (socket, cb) {
var self = this;
Project.findByIdAndUpdate(
data.docId,
{ css: self.document },
function (err) {
if (err) return cb(false);
cb(true);
}
);
}
);
}
if(data.editor === 'js') {
console.log('js');
var socketIOServer = new ot.EditorSocketIOServer(
js,
[],
data.room,
function (socket, cb) {
var self = this;
Project.findByIdAndUpdate(
data.docId,
{ js: self.document },
function (err) {
if (err) return cb(false);
cb(true);
}
);
}
);
}
roomList[data.room] = socketIOServer;
}
roomList[data.room].addClient(socket);
roomList[data.room].setName(socket, data.username);
socket.room = data.room;
socket.join(data.room);
});
socket.on("chatMessage", function (data) {
io.to(socket.room).emit("chatMessage", data);
});
socket.on("disconnect", function () {
socket.leave(socket.room);
});
});
};