-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
72 lines (57 loc) · 2.23 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
const express = require('express')
const http = require('http')
const app = express()
const path = require('path')
const socketio = require('socket.io')
const Filter = require('bad-words')
const filter = new Filter()
const { generateMessage, generateLocationMessage } = require('./utils/message')
const { addUser, removeUser, getUser, getUsersInRoom } = require('./utils/users')
const port = process.env.PORT || 3000
const server = http.createServer(app)
const io = socketio(server)
const public = path.join(__dirname, 'public')
app.use(express.static(public))
io.on('connection', (socket) => {
console.log('New connection : ' + socket.id)
socket.on('join', ({ username, room }, callback) => {
const { user, error } = addUser({ id: socket.id, username, room })
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('sendLocation', (location, callback) => {
const user = getUser(socket.id)
io.to(user.room).emit('locationMessage', generateLocationMessage(user.username, `https://google.com/maps?q=${location.lat},${location.lon}`))
callback()
})
socket.on('sendMessage', (message, callback) => {
if (filter.isProfane(message)) {
return callback('Profanity not allowd!')
}
const user = getUser(socket.id)
io.to(user.room).emit('message', generateMessage(user.username, message))
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 listening on port ${port}...`)
})