This repository has been archived by the owner on Jan 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
191 lines (149 loc) · 4.63 KB
/
app.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
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
const express = require('express');
const socketio = require('socket.io');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const debug = require('debug')('Sentiment:server');
const helmet = require('helmet');
const app = express();
const srv = require('http').Server(app);
const io = socketio(srv);
const User = require('./src/user');
app.use(bodyParser.json());
app.use(helmet());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static('static/client_resources'));
app.get('/', (req, res) => {
res.sendFile(path.join( __dirname + '/static/index.html'));
});
app.get('/:room', (req, res) => {
res.sendFile(path.join( __dirname + '/static/chatroom.html'));
});
/**
* SocketIO calls.
*/
io.on('connection', (socket)=>{
const user = new User(socket.id);
socket.on('get-sys-info', () => {
console.log('System info requested.');
let currentRooms = {};
Object.keys(io.nsps['/'].adapter.rooms).forEach(k => {
const users = io.nsps['/'].adapter.rooms[k].length
if (users >= 2) {
console.log(`${users} users in ${k} room.`);
let x = io.nsps['/'].adapter.rooms[k].fn;
k = x ? x : k;
currentRooms[k] = users;
}
});
socket.emit('sys-info', currentRooms);
});
socket.on('get-page-info',(pageurl)=>{
const { roomid, fancyname } = parseUrl(pageurl);
io.to(socket.id).emit('room-setup', {}, fancyname, roomid);
user.setRoom(roomid, fancyname);
if (!io.nsps['/'].adapter.rooms[roomid]) {
socket.emit('message', 'You are first!');
socket.join(roomid);
io.nsps['/'].adapter.rooms[roomid].fn = fancyname;
} else {
socket.emit('message', `${io.nsps['/'].adapter.rooms[roomid].length} other users present in ${roomid}`);
socket.join(roomid);
}
console.log(`User ${socket.id} joined room ${user.getRoom()}`);
console.log('\nRooms:');
let currentRooms = {};
Object.keys(io.nsps['/'].adapter.rooms).forEach(k => {
const users = io.nsps['/'].adapter.rooms[k].length
if (users >= 2) {
console.log(`${users} users in ${k} room.`);
currentRooms[k] = users;
}
});
rooms = currentRooms;
console.log('\n');
});
socket.on('message-from-user', (x) => {
if (!x.message || !x.username || !x.room )
return 1;
socket.to(user.socket).emit('message', 'Client recieved message '+x.message);
console.log('Circulating message to' + x.room);
io.to(user.getRoom()).emit('message-to-room', {
'username': x.username.substr(0,20),
'message': x.message.substr(0, 240)
});
});
socket.on('disconnect', () => {
console.log(`User ${user.socket} left room ${user.getRoom()}`);
});
});
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
/**
* Listen on provided port, on all network interfaces.
*/
srv.listen(port);
srv.on('error', onError);
srv.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP srv "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP srv "listening" event.
*/
function onListening() {
var addr = srv.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
function parseUrl(url){
url = decodeURI(url.substr(1));
const roomid = url.replace(/[^0-9a-z]/gi, '').toLowerCase();
return { 'roomid': roomid, 'fancyname': url };
}
module.exports = app;