-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
252 lines (229 loc) · 7.92 KB
/
app.js
File metadata and controls
252 lines (229 loc) · 7.92 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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
//Import, initialize modules and variables
const express = require('express'),
http = require('http'),
app = express(),
path = require('path');
cookieParser = require('cookie-parser');
logger = require('morgan');
server = http.createServer(app);
io = require('socket.io')(server);
router = express.Router();
User = require("./utils/database");
jwt = require('jsonwebtoken');
secret = process.env.JWTSECRET || 'testing secret string is super secret, please change.';
let usersRouter = require('./routes/users');
let loginRouter = require('./routes/login');
// add middleware to express server
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
extended: false
}));
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(cookieParser());
app.use('/users', usersRouter);
app.use('/login', loginRouter);
app.use(express.static('public'));//Route to html application
// Block other event listeners until JWT has been verifed.
io.use(function(socket, next){
console.log("io.use() being called");
console.log(socket.handshake);
if (socket.handshake && (socket.handshake.query.xAccessToken || socket.handshake.query.authorization)){
let token = socket.handshake.query.xAccessToken || socket.handshake.query.authorization;
if (token.startsWith('Bearer ')) {
// Slice out 'Bearer '
token = token.slice(7, token.length);
}
jwt.verify(token, secret, function(err, decoded) {
if(err)
return next(new Error('Authentication error'));
socket.decoded = decoded;
next();
});
} else {
next(new Error('Authentication error'));
}
/**
* Connect a prospective socket to the server
* Param: socket
*/
}).on('connection', (socket) =>{
let addedUser = false;
socket.emit('doLogin');
socket.on('login', (username, uuid) => {
if (addedUser) return;
socket.username = username;
socket.uuid = uuid;
addedUser = true;
User.setSocketID({username, uuid}, socket.id);
console.log('\\********************************/');
console.log(`Username#uuid: ${socket.username}#${socket.uuid}`);
console.log('The current userid is: ' + socket.id);
console.log('Headers are:');
console.dir(socket.handshake.headers);
console.log('/********************************\\');
});
/**
* Send messages to room
* Param: msgObj, roomNo
*/
socket.on("sendMessage", ({msgObj, roomNo}) =>
{
messageOutRoom(msgObj, roomNo);
});
/**
* Send messages privately (no room, just one-time messages)
* Param: msgObj, username, uuid
*/
socket.on('privateMessage', ({msgObj, username, uuid}) =>
{
messageOutPrivate(msgObj, username, uuid, socket);
});
/**
* Close all rooms socket is associated with
* Param: socket
*/
socket.on('closeRooms', function(socket)
{
closeOutAllRooms(socket);
});
/**
* Close the room specified
* Param: socket, room
*/
socket.on('closeThisRoom',({socket, room}) =>
{
closeOutRoom(socket, room);
});
/**
* Socket leaves all rooms it is associated with
* Param: socket
*/
socket.on('leaveRooms', function(socket)//
{
leaveAllRooms(socket);
});
/**
* Send messages privately (no room, just one-time messages)
* Param: socket, room
*/
socket.on('leaveThisRoom',({socket, room}) =>//WORK TO BE DONE, ROOM MUST BE PASSED AS ARGUMENT FROM CLIENT
{
leaveRoom(socket, room);
});
/**
* Joins socket to room when client decides to
* Param: socket, room
*/
socket.on('joinHere', ({socket, room})=>{
socket.join(room);
});
/**
* Disconnect socket, close all associated rooms
* Param: socket
*/
socket.on('disconnectWithRooms', function (socket)
{
closeOutAllRooms(socket);
socket.close();
});
/**
* Disconnect the socket from all connections and the server
* Param: socket
*/
socket.on('disconnect', function (socket)
{
socket.disconnect(true);
console.log("remaining sockets");
});
/**
* Send an invitation to the user/socket.id whose username/uuid is passed via the client, forces join
* Param: socket, username, uuid, roomVal
*/
socket.on("inviteMe", ({socket, username, uuid, roomVal}) =>//Send an invitation to the user/socket.id whose username/uuid is passed via the client, forces join
{
console.log(socket, username, uuid, roomVal);
inviteUser(socket, username, uuid, roomVal);
});
/**
* Checks if user is typing and broadcasts message to all users in room with that socket
* Param: socket
*/
socket.on('isTyping', function ()
{
setTimeout(function(socket)
{
let room = Object.keys(io.sockets.adapter.sids[socket.id]);
userIsTyping(socket, room);
}, 3000);
});
});
function randomRoom(socket)//Create a random room string
{
console.log('Room '+ socket.id + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15));
return ('Room '+ socket.id + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15));//Creates one of 36^22 random rooms for temporary usage
}
function messageOutRoom(msgObj, roomNo)//Send a message to a room
{
console.log("listened for public message: " + msgObj);
io.sockets.in(roomNo).emit("newMessage", msgObj); //
// was getting error here
//socket.to(Object.keys(io.sockets.adapter.sids[socket.id])[roomNo]).broadcast.emit("newMessage", msgObj);// send a message to every user in the specified room
}
function messageOutPrivate(msgObj, username, uuid, socket)//Send a message privately, direct to socket.id
{
User.userInfo(username, uuid).then((user) => {
console.log("listened for private message: " + msgObj + " from ", socket.id + " to " + user[0].socketid);
io.to(user[0].socketid).emit('privateMessage', msgObj, socket.username);
}).catch(err => {
console.error(err);
})
}
function inviteUser(socket, username, uuid, roomVal){
User.userInfo(username,uuid).then((user)=>{
let talkChannel;
if(roomVal != null)// checks if there is a room setup
talkChannel = roomVal;// talkChannel
else
talkChannel = randomRoom(socket.id);
io.to(socket.id).emit('join', talkChannel);// emit join event to client with talkChannel(room)
io.to(user[0].socketid).emit('join', talkChannel);// emit join event to desired user and destination room
}).catch(err => {
console.log(err);
})
}
function userIsTyping(socket, room)//send message that user is typing
{
io.to(room).emit('notify', socket.username + 'is typing');//Take a look at this, make sure username is getting fetched properly (my execution is probably wrong here)
}
function closeOutAllRooms(socket)//Close all rooms socket is connected to
{
let i = 0;
while ((Object.keys(io.sockets.adapter.sids[socket.id])[i]) !== 'undefined')
{
io.to(Object.keys(io.sockets.adapter.sids[socket.id])[i]).clear();
i++;
}
}
function closeOutRoom(socket, room)//Close out a specific room the socket is connected to
{
socket.close(room);
}
function leaveAllRooms(socket)//Leave, but dont close all rooms
{
let i = 0;
while ((Object.keys(io.sockets.adapter.sids[socket.id])[i]) !== 'undefined')
{
io.to(Object.keys(io.sockets.adapter.sids[socket.id])[i]).leave();
i++;
}
}
function leaveRoom(socket, room)//Leave, but dont close a specific room
{
socket.leave(room);
}
module.exports = {app, server};