-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
94 lines (77 loc) · 2.46 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
84
85
86
87
88
89
90
91
92
93
94
const express = require('express')
var app = express()
const http = require('http').createServer(app);
const io = require('socket.io')(http)
const path = require('path')
io.origins(['http://localhost:3000', 'http://127.0.0.1:3000', 'http://127.0.0.1:4200', 'http://localhost:4200', 'https://colaborative-text-editor-serve.herokuapp.com'])
const port = process.env.PORT || 3000
const useHTTPS = process.env.HTTPS || false
if (useHTTPS) {
app.use(function(req, res, next) {
if (req.headers["x-forwarded-proto"] === "https")
return next();
res.redirect("https://" + req.headers.host + req.url);
});
}
app.use(express.static('public'))
app.get('/', (req, res) => res.sendFile(path.resolve('public/index.html')))
let clients = []
let content = ""
let typing = {
username: null,
id: null
}
let timer
function updateUsersList() {
clients.forEach(c => c.client.emit('updateUsersList', { users: clients.map(c => c.data.username) }))
}
function onType(client, data) {
if (typing.id === client.id || typing.id === null) {
content = data
clients.forEach(c => {
if (c.client.id !== client.id)
return
typing.username = c.data.username
typing.id = c.client.id
})
clients.forEach(c => {
if (c.client.id === client.id)
return c.client.emit('typing', typing.username)
c.client.emit('update', content)
c.client.emit('typing', typing.username)
})
clearTimeout(timer)
timer = setTimeout(() => {
typing.id = null
typing.username = null
clients.forEach(c => c.client.emit('typing', null))
}, 600)
}
}
function identify(client, username) {
console.log(`Novo cliente conectado : ${username}`)
clients.push({
data: {
username: username
},
client: client
})
updateUsersList()
client.on('type', data => onType(client, data))
client.on('disconnect', () => disconnect(client))
client.emit('update', content)
}
function disconnect(client) {
clients.forEach((c, idx) => {
if (c.client.id === client.id)
clients.splice(idx, 1)
})
updateUsersList()
}
function connect(client) {
client.on('identify', username => identify(client, username))
}
io.on('connect', (client) => connect(client))
http.listen(port, function() {
console.log(`Servidor inicializado na porta ${port}`)
})