-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
71 lines (68 loc) · 2.56 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
const express = require('express')
const app = express()
const SERVER_PORT = process.env.PORT || 1111
const http= require('http')
const server = http.createServer(app)
const socket = require('socket.io')
const io = socket(server)
const { generateMessage, generateLocationMessage } = require('./utils/messages')
const { addUser, removeUser, getUser, getUsersInRoom } = require('./utils/users')
app.use(express.urlencoded({extended: true}))
app.use('/', express.static(__dirname + '/public'))
io.on('connection', (socket) => {
socket.on('join', (data, callback) => {
const { error, user } = addUser({ id: socket.id, username : data.username, room : data.room})
if(error) {
return callback(error)
}
socket.join(user.room)
socket.emit('message', generateMessage('Welcome!', 'Admin'))
socket.broadcast.to(user.room).emit('message', generateMessage(`${user.username} has joined`, 'Admin'))
io.to(user.room).emit('roomData', {
room: user.room,
users: getUsersInRoom(user.room)
})
callback()
})
socket.on('isTyping', (data) => {
const user = getUser(socket.id)
data.username = user.username
socket.broadcast.to(user.room).emit('isTyping', data)
})
socket.on('sendMessage', (data, callback) => {
const user = getUser(socket.id)
data.username = user.username
io.to(user.room).emit('message', data)
callback()
})
socket.on('sendImage', (data, callback) => {
const user = getUser(socket.id)
data.username = user.username
io.to(user.room).emit('imageMessage', data)
callback()
})
socket.on('sendLiveImage', (data, callback) => {
const user = getUser(socket.id)
data.username = user.username
io.to(user.room).emit('liveImageMessage', data)
callback()
})
socket.on('sendLocation', (data, callback) => {
const user = getUser(socket.id)
io.to(user.room).emit('locationMessage', generateLocationMessage(`https://google.com/maps/?q=${data.latitude},${data.longitude}`, user.username))
callback()
})
socket.on('disconnect', () => {
const user = removeUser(socket.id)
if(user) {
io.to(user.room).emit('message', generateMessage(`${user.username} has left`, 'Admin'))
io.to(user.room).emit('roomData', {
room: user.room,
users: getUsersInRoom(user.room)
})
}
})
})
server.listen(SERVER_PORT, () => {
console.log('server started')
})