-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathserver.js
202 lines (187 loc) · 6.66 KB
/
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
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
128
129
130
131
132
133
134
135
136
137
138
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
#!./node_modules/.bin/babel-node
import 'core-js/stable';
import 'regenerator-runtime/runtime';
/* eslint-disable no-console */
import Y from 'yjs';
import yWebsocketsServer from 'y-websockets-server';
import yMemory from 'y-memory';
import express from 'express';
import socketIo from 'socket.io';
import http from 'http';
import bodyParser from 'body-parser';
import clone from 'lodash/clone';
import crypto from 'crypto';
Y.extend(yWebsocketsServer, yMemory);
const isProduction = process.env.NODE_ENV === 'production';
const serverMode = process.env.SERVER_MODE;
const port = Number.parseInt(process.env.PORT || '8080', 10);
const app = express();
const server = http.createServer(app);
const io = socketIo.listen(server);
const bodyParserText = bodyParser.text();
const yInstances = {};
const metadata = {};
function getInstanceOfY(room) {
if (yInstances[room] == null) {
yInstances[room] = Y({
db: {
name: 'memory',
dir: 'y-leveldb-databases',
namespace: room,
},
connector: {
name: 'websockets-server',
// TODO: Will be solved in future https://github.com/y-js/y-websockets-server/commit/2c8588904a334631cb6f15d8434bb97064b59583#diff-e6a5b42b2f7a26c840607370aed5301a
room: encodeURIComponent(room),
io,
debug: !isProduction,
},
share: {},
});
metadata[room] = {
created: new Date(),
modified: new Date(),
active: 0,
};
}
return yInstances[room];
}
function removeInstanceOfY(room) {
delete yInstances[room];
delete metadata[room];
}
function getSha1Hash(plaintext) {
const sha1 = crypto.createHash('sha1');
sha1.update(plaintext);
return sha1.digest('hex');
}
app.get('/pages', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(Object.keys(metadata).map((k) => {
const m = metadata[k];
return {
page: k,
created: m.created,
modified: m.modified,
active: m.active,
};
})));
});
app.post('/deletePage', bodyParserText, async (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Content-Type', 'application/json');
const room = req.body;
const yPromise = yInstances[room];
if (!yPromise) {
res.end(JSON.stringify({ status: 'FAILURE', msg: 'No y instance' }));
return;
}
try {
const y = await yPromise;
const roomMetadata = metadata[room];
if (!roomMetadata) {
res.end(JSON.stringify({ status: 'FAILURE', msg: 'No metadata' }));
return;
}
if (roomMetadata.active > 0) {
res.end(JSON.stringify({ status: 'FAILURE', msg: 'There are still users on this page' }));
return;
}
try {
await y.destroy();
removeInstanceOfY(room);
res.end(JSON.stringify({ status: 'SUCCESS', msg: `Delete ${room}` }));
} catch (ex) {
console.error(ex);
res.end(JSON.stringify({ status: 'FAILURE', msg: 'Y instance destroy error' }));
}
} catch (ex) {
console.error(ex);
res.end(JSON.stringify({ status: 'FAILURE', msg: ex }));
}
});
io.on('connection', (socket) => {
const rooms = [];
socket.on('joinRoom', async (escapedRoom) => {
// TODO: Will be solved in future https://github.com/y-js/y-websockets-server/commit/2c8588904a334631cb6f15d8434bb97064b59583#diff-e6a5b42b2f7a26c840607370aed5301a
const room = decodeURIComponent(escapedRoom);
console.log('User', socket.id, 'joins room:', room);
socket.join(escapedRoom);
const y = await getInstanceOfY(room);
if (rooms.indexOf(room) === -1) {
y.connector.userJoined(socket.id, 'slave');
rooms.push(room);
metadata[room].active += 1;
io.in(escapedRoom).emit('activeUser', metadata[room].active);
}
});
socket.on('yjsEvent', async (msg) => {
if (msg.room != null) {
// TODO: Will be solved in future https://github.com/y-js/y-websockets-server/commit/2c8588904a334631cb6f15d8434bb97064b59583#diff-e6a5b42b2f7a26c840607370aed5301a
const room = decodeURIComponent(msg.room);
const y = await getInstanceOfY(room);
y.connector.receiveMessage(socket.id, msg);
if (msg.type === 'update') {
metadata[room].modified = new Date();
}
}
});
socket.on('disconnect', async () => {
await Promise.all(rooms.map(async (room) => {
const y = await getInstanceOfY(room);
y.connector.userLeft(socket.id);
metadata[room].active -= 1;
// TODO: Will be solved in future https://github.com/y-js/y-websockets-server/commit/2c8588904a334631cb6f15d8434bb97064b59583#diff-e6a5b42b2f7a26c840607370aed5301a
const escapedRoom = encodeURIComponent(room);
io.in(escapedRoom).emit('activeUser', metadata[room].active);
io.in(escapedRoom).emit('clientCursor', { type: 'delete', id: getSha1Hash(socket.id) });
}));
rooms.splice(0, rooms.length);
});
socket.on('leaveRoom', async (escapedRoom) => {
// TODO: Will be solved in future https://github.com/y-js/y-websockets-server/commit/2c8588904a334631cb6f15d8434bb97064b59583#diff-e6a5b42b2f7a26c840607370aed5301a
const room = decodeURIComponent(escapedRoom);
const y = await getInstanceOfY(room);
const i = rooms.indexOf(room);
if (i >= 0) {
y.connector.userLeft(socket.id);
rooms.splice(i, 1);
metadata[room].active -= 1;
io.in(room).emit('activeUser', metadata[room].active);
io.in(room).emit('clientCursor', { type: 'delete', id: getSha1Hash(socket.id) });
}
});
socket.on('clientCursor', (msg) => {
if (msg.room != null) {
const msgCloned = clone(msg);
msgCloned.id = getSha1Hash(socket.id);
// TODO: Will be solved in future https://github.com/y-js/y-websockets-server/commit/2c8588904a334631cb6f15d8434bb97064b59583#diff-e6a5b42b2f7a26c840607370aed5301a
socket.to(encodeURIComponent(msg.room)).emit('clientCursor', msgCloned);
}
});
});
switch (serverMode) {
case 'storybook':
break;
case 'landingpage':
app.use(express.static('.'));
break;
default:
if (isProduction) {
app.use(express.static('build'));
} else {
/* eslint-disable global-require, import/no-extraneous-dependencies */
const webpackConfig = require('./webpack.config.babel.js').default;
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
/* eslint-enable global-require */
const compiler = webpack(webpackConfig);
app.use(webpackDevMiddleware(compiler));
app.use(webpackHotMiddleware(compiler));
}
}
server.listen(port, () => {
console.log(`Running y-websockets-server on port ${port}`);
});