This repository was archived by the owner on May 17, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
215 lines (183 loc) · 6.25 KB
/
app.js
File metadata and controls
215 lines (183 loc) · 6.25 KB
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
const axios = require('axios');
const express = require('express');
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');
require('dotenv').config();
const app = express();
// Middleware
app.use(express.static('public'));
app.use(express.json());
app.use(cookieParser());
// View Engine
app.set('view engine', 'ejs');
const server = app.listen(3000);
mongoose.connect(process.env.ATLAS_URI)
.then((result) => server)
.catch((err) => console.log(err));
const routes = require('./routes/routes');
const User = require('./models/user'); // User model
app.use(routes)
// WebSocket Server
const updateStatus = require('./middleware/updateStatus');
const io = require('socket.io')(server);
const connections = {};
io.on('connection', async (socket) => {
if (socket.handshake.headers.cookie) {
const token = socket.handshake.headers.cookie.split("=")[1];
const user = await verifyToken(token);
if (user) {
connections[user.id] = socket.id;
};
socket.on('getUsername', async () => {
const full_user = await User.findOne({_id: user.id});
socket.emit('username', full_user.username);
});
updateStatus.set_status(token, "online");
socket.emit('current-status', "online");
let conversations = await updateConversations(socket, token);
if (!conversations.message) {
const chatIds = conversations.map(conversation => conversation.chatId);
const messages = await getMessages(chatIds);
socket.emit('receive-messages', messages);
};
socket.on('getPrivateKey', async () => {
try {
const privateKey = await getPrivateKey(token);
if (privateKey) {
socket.emit('privateKey', privateKey);
}
} catch (error) {
console.log(error);
}
});
socket.on('getPublicKey', async (username) => {
try {
const publicKey = await getPublicKey(token, username);
if (publicKey) {
socket.emit('publicKey', publicKey);
}
} catch(error) {
console.log(error);
}
});
socket.on('message', async (data) => {
try {
data.token = token;
const new_message = await sendMessage(data);
const messages = await getMessages([data.chatId]);
if (messages) {
for(const id of new_message) {
if (connections[id]) {
io.to(connections[id]).emit('receive-messages', messages);
}
}
} else {
console.log("Messages could not be retrieved.");
}
} catch(error) {
console.log(error);
}
});
socket.on('get-messages', async (chatId) => {
const messages = await getMessages(chatId);
socket.emit('receive-messages', messages);
});
socket.on('disconnect', () => {
updateStatus.set_status(token, "offline");
socket.emit('current-status', "offline");
const userId = Object.keys(connections).find(key => connections[key] === socket.id);
if (userId) {
delete connections[userId];
}
});
}
});
async function getPublicKey(token, username) {
const response = await axios.get(`http://localhost:3000/chat/public-key/${token}/${username}`);
return response.data;
};
async function getPrivateKey(token) {
const response = await axios.get(`http://localhost:3000/chat/private-key/${token}`);
return response.data.privateKey;
};
async function updateConversations(socket, token) {
try {
let conversations = await getConversations(token);
socket.emit('chatData', conversations);
setInterval(async () => {
const newConversations = await getConversations(token);
if (newConversations && JSON.stringify(conversations) !== JSON.stringify(newConversations)) {
socket.emit('chatData', newConversations);
conversations = newConversations;
return conversations;
}
}, 500);
return conversations;
} catch (error) {
console.error(error);
}
};
async function getConversations(token) {
try {
const response = await axios.get('http://localhost:3000/chat', {
headers: {
'jwt': token
}
});
return response.data;
} catch (error) {
console.error(error);
throw error;
}
};
async function sendMessage(data) {
try {
const response = await axios.post('http://localhost:3000/create-message', {
data: data
});
if (response.status === 200) {
return response.data;
} else {
return null;
}
} catch(error) {
console.log(error);
}
};
async function getMessages(chatId) {
try {
const response = await axios.post(`http://localhost:3000/messages/`, {
chatId
});
if (response.status === 200) {
return response.data;
} else {
return null;
}
} catch(error) {
console.log(error);
}
};
async function closeSocketIoConnections() {
io.close();
};
async function handleServerShutdown() {
console.log('Server is shutting down');
closeSocketIoConnections();
server.close(() => {
console.log('Server has been gracefully shut down');
process.exit(0);
});
};
async function verifyToken (token) {
try {
const user = jwt.verify(token, process.env.JWT_SIGNATURE);
return user;
} catch (error) {
console.log(error);
return null;
}
};
process.on('SIGINT', handleServerShutdown);
process.on('SIGTERM', handleServerShutdown);