-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
83 lines (68 loc) · 2.71 KB
/
index.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
const express = require('express');
const path = require('path');
const http = require('http');
const socketio = require('socket.io');
const Filter = require('bad-words');
const { generateMessage, generateLocationMessage } = require('./src/utils/messages');
const { addUser, removeUser, getUser, getUsersInRoom } = require('./src/utils/users');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
const port = process.env.PORT || 3000;
const publicDirectoryPath = path.join(__dirname, './public');
app.use(express.static(publicDirectoryPath));
//socket.emit => event to specific client
//io.emit => event to every connected client
//socket.broadcast.emit => event to every connected client except current client
//io.to.emit => event to every connected client in same room
//socket.broadcast.io.emit => event every connected client except current client in same room
io.on('connection', (socket) => {
console.log('New WebSocket connection');
socket.on('join', (options, callback) => {
const {error, user} = addUser({ id: socket.id, ...options});
if(error) {
return callback(error);
}
socket.join(user.room);
socket.emit('message', generateMessage('Admin', 'Welcome!'));
socket.broadcast.to(user.room).emit('message', generateMessage('Admin', `${user.username} has joined!`));
io.to(user.room).emit('roomData', {
room: user.room,
users: getUsersInRoom(user.room)
});
callback();
});
socket.on('sendMessage', (message, callback) => {
const filter = new Filter();
if(filter.isProfane(message)) {
return callback('Profanity is not allowed!')
}
const user = getUser(socket.id);
if(user) {
io.to(user.room).emit('message', generateMessage(user.username, message));
}
callback();
});
socket.on('sendLocation', (locationObj, callback) => {
const {latitude, longitude} = locationObj;
const user = getUser(socket.id);
if(user) {
io.to(user.room).emit('locationMessage', generateLocationMessage(user.username, `https://google.com/maps?q=${latitude},${longitude}`));
}
callback();
});
socket.on('disconnect', () => {
const user = removeUser(socket.id);
if(user) {
io.to(user.room).emit('message', generateMessage('Admin', `${user.username} has left!`));
io.to(user.room).emit('roomData', {
room: user.room,
users: getUsersInRoom(user.room)
});
}
});
});
server.listen(port, () => {
console.log(`Server is up on PORT : ${port}`);
});
module.exports = server;