-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
145 lines (132 loc) · 3.84 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
const express = require('express')
const cookieParser = require('cookie-parser')
const dotenv = require('dotenv')
const jwt = require('jsonwebtoken')
const cors = require('cors')
const morgan = require('morgan')
const Message = require('./models/Message')
const ws = require('ws')
const fs = require('fs')
const register = require('./routes/register.routes')
const login = require('./routes/login.routes')
const people = require('./routes/people.routes')
const logout = require('./routes/login.routes')
const profile = require('./routes/profile.routes')
const message = require('./routes/messages.routes')
const { connectDB } = require('./db/db')
//config
dotenv.config()
const port = process.env.PORT
const jwtSecret = process.env.JWT_SECRET
const front_url = process.env.CLIENT_URL
const app = express()
app.use(morgan('dev'))
app.use('/uploads', express.static(__dirname + '/uploads'))
app.use(express.json())
app.use(cookieParser())
app.use(cors({
methods: 'GET, HEAD, PUT, PATCH, POST, DELETE',
credentials: true,
origin:front_url,
}))
//routes
app.use(message)
app.use(profile)
app.use(register)
app.use(people)
app.use(logout)
app.use(login)
//conect data base
connectDB()
// listen port express
const server = app.listen(port, () => {
console.log(`Server is running in ${port}!`)
})
// web Socket
const wss = new ws.WebSocketServer({ server })
wss.on('connection', (connection, req) => {
function notifyAboutOnlinePeople() {
;[...wss.clients].forEach(client => {
client.send(
JSON.stringify({
online: [...wss.clients].map(c => ({
userId: c.userId,
username: c.username,
})),
})
)
})
}
connection.isAlive = true
connection.timer = setInterval(() => {
connection.ping()
connection.deathTimer = setTimeout(() => {
connection.isAlive = false
clearInterval(connection.timer)
connection.terminate()
notifyAboutOnlinePeople()
console.log('dead')
}, 1000)
}, 5000)
connection.on('pong', () => {
clearTimeout(connection.deathTimer)
})
// read username and id form the cookie for this connection
const cookies = req.headers.cookie
if (cookies) {
const tokenCookieString = cookies
.split(';')
.find(str => str.startsWith('token='))
if (tokenCookieString) {
const token = tokenCookieString.split('=')[1]
if (token) {
jwt.verify(token, jwtSecret, {}, (err, userData) => {
if (err) throw err
const { userId, username } = userData
connection.userId = userId
connection.username = username
})
}
}
}
connection.on('message', async message => {
const messageData = JSON.parse(message.toString())
const { recipient, text, file } = messageData
let filename = null
if (file) {
console.log('size', file.data.length)
const parts = file.name.split('.')
const ext = parts[parts.length - 1]
filename = Date.now() + '.' + ext
const path = __dirname + '/uploads/' + filename
const bufferData = new Buffer(file.data.split(',')[1], 'base64')
fs.writeFile(path, bufferData, () => {
console.log('file saved:' + path)
})
}
if (recipient && (text || file)) {
const messageDoc = await Message.create({
sender: connection.userId,
recipient,
text,
file: file ? filename : null,
})
console.log('created message')
;[...wss.clients]
.filter(c => c.userId === recipient)
.forEach(c =>
c.send(
JSON.stringify({
text,
sender: connection.userId,
recipient,
file: file ? filename : null,
_id: messageDoc._id,
})
)
)
}
})
// notify everyone about online people (when someone connects)
notifyAboutOnlinePeople()
})