-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
executable file
·92 lines (78 loc) · 2.22 KB
/
app.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
const koa = require('koa');
const serve = require('koa-static');
const uuid = require('node-uuid');
const app = koa();
const server = require('http').createServer(app.callback());
/** io */
const io = require('socket.io')(server, { path: '/code' });
io.on('connection', function () { /* … */ });
/** io */
app.use(serve(__dirname + '/dist'));
server.listen(process.env.PORT || 5000);
io.on('connection', (socket) => {
let isInitialized = () => { //fixme change to bool value?
return socket.roomUuid;
}
const leaveRoom = () => {
socket.roomUuid && socket.leave(socket.roomUuid);
socket.roomUuid = null;
}
socket.on('create room', () => {
leaveRoom();
//fixme username?
socket.roomUuid = uuid.v4();
socket.join(socket.roomUuid);
socket.emit('create room', socket.roomUuid);
});
socket.on('join room', (roomUuid) => {
//fixme username?
//fixme what if room was not created?
if (!roomUuid) {
return;
}
leaveRoom();
socket.roomUuid = roomUuid;
socket.join(socket.roomUuid);
})
socket.on('code change', (code) => {
if (!isInitialized()) {
return;
}
socket.broadcast.to(socket.roomUuid).emit('code change', {
username: socket.username,
code: code
});
});
socket.on('add user', (username) => {
if (addedUser) return;
socket.username = username;
socket.emit('login', {
//FIXME
});
// echo globally (all clients) that a person has connected
socket.broadcast.to(socket.roomUuid).emit('user joined', {
username: socket.username
});
});
// when the client emits 'typing', we broadcast it to others
socket.on('typing', () => {
socket.broadcast.to(socket.roomUuid).emit('typing', {
username: socket.username
});
});
// when the client emits 'stop typing', we broadcast it to others
socket.on('stop typing', () => {
socket.broadcast.to(socket.roomUuid).emit('stop typing', {
username: socket.username
});
});
// when the user disconnects perform this
socket.on('disconnect', () => {
if (false) { //TODO FIXME
// echo globally that this client has left
socket.broadcast.emit('user left', {
username: socket.username
});
}
});
});