-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
175 lines (152 loc) · 5.54 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
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
const express = require('express');
const app = (exports = express());
const port = process.env.PORT || 8080;
const server = require('http').Server(app);
const db = require('./db');
const io = require('socket.io')(server, {
origins:
'localhost:8080 192.168.0.123:8080 social-reaction.herokuapp.com:*',
});
const { SESSION_SECRET: sessionSecret } = process.env.SESSION_SECRET
? process.env
: require('./secrets.json');
const cookieSession = require('cookie-session');
const cookieSessionMiddleware = cookieSession({
secret: sessionSecret,
maxAge: 1000 * 60 * 60 * 24 * 14, // ~ 1.2 billion milliseconds = 14 days
});
const csurf = require('csurf');
const bodyParser = require('body-parser');
const {
logRoute,
makeCookiesSafe,
logErrors,
clientErrorHandler,
errorHandler,
} = require('./utils/middleware');
const compression = require('compression');
const auth = require('./routes/auth');
const profile = require('./routes/profile');
const people = require('./routes/people');
app.use(express.static('./public'));
app.use(bodyParser.json());
app.use(cookieSessionMiddleware);
io.use(function (socket, next) {
cookieSessionMiddleware(socket.request, socket.request.res, next);
});
app.use(csurf());
app.use((req, res, next) => {
res.cookie('_ctkn', req.csrfToken());
next();
});
app.use(compression());
app.use(logRoute);
app.use(makeCookiesSafe);
if (process.env.NODE_ENV != 'production') {
app.use(
'/bundle.js',
require('http-proxy-middleware')({
target: 'http://localhost:8081/',
})
);
} else {
app.use('/bundle.js', (req, res) => res.sendFile(`${__dirname}/bundle.js`));
}
// if NOT LOGGED IN: serve index.html (stay where you are), else: redirect to /
app.get('/welcome', (req, res) => {
!req.session.id
? res.sendFile(__dirname + '/index.html')
: res.redirect('/');
});
app.use('/auth', auth);
app.use('/profile', profile);
app.use('/people', people);
app.post('/bounce', (req, res) => res.sendStatus(200));
// if LOGGED IN: serve index.html, else: redirect to /welcome
app.get('*', (req, res) => {
req.session.id
? res.sendFile(__dirname + '/index.html')
: res.redirect('/welcome');
});
app.use(logErrors);
app.use(clientErrorHandler);
app.use(errorHandler);
server.listen(port, function () {
console.log(`I'm listening on port: ${port}`);
});
let onlineUsers = {};
let onlineUsersIds = [];
io.on('connection', function (socket) {
console.log(`socket with the id ${socket.id} is now connected`);
if (!socket.request.session.id) return socket.disconnect(true);
const id = socket.request.session.id;
if (Object.values(onlineUsers).filter((n) => n === id).length === 0) {
db.getUserById(id).then((user) => {
console.log('userJoined :', user);
io.sockets.sockets[socket.id].broadcast.emit('userJoined', user);
});
}
onlineUsers[socket.id] = id;
onlineUsersIds = [...new Set(Object.values(onlineUsers))];
// console.log('onlineUsersIds :', onlineUsersIds);
db.getOnlineUsersByIds(onlineUsersIds).then((users) => {
// console.log('getOnlineUsersByIds :', users);
io.sockets.sockets[socket.id].emit('onlineUsers', users);
});
console.log('onlineUsers', onlineUsers);
db.getLatestMessages(10).then((data) => {
data = data.map((item) => ({
id: item.msg_id,
msg: item.msg,
created_at: item.created_at,
sender: {
id: item.sender_id,
first: item.first,
last: item.last,
img_url: item.img_url,
bio: item.bio,
},
}));
io.sockets.sockets[socket.id].emit('latestMessages', data.reverse());
});
socket.on('newPublicMessage', (msg) => {
// console.log('This is a message:', msg, 'user:', id);
Promise.all([db.addPublicMessage(id, msg), db.getUserById(id)]).then(
([{ msg_id, created_at }, { first, last, img_url, bio }]) =>
io.sockets.emit('publicMessage', {
id: msg_id,
msg: msg,
created_at: created_at,
sender: {
id: id,
first: first,
last: last,
img_url: img_url,
bio: bio,
},
})
);
});
// socket.on('thanks', function (data) {
// console.log(data);
// });
// socket.emit('welcome', {
// message: 'Welome. It is nice to see you',
// });
socket.on('disconnect', function () {
// runs when a user disconnects - ie logs off or closes browser/tab
delete onlineUsers[socket.id]; // remove user from onlineUsers who just left
if (Object.values(onlineUsers).filter((n) => n === id).length === 0) {
onlineUsersIds = [...new Set(Object.values(onlineUsers))];
db.getOnlineUsersByIds(onlineUsersIds).then((users) => {
console.log('leftUsers :', users);
io.sockets.emit('userLeft', users);
});
}
console.log('userLeft', id);
// before we emit userLeft, we need to confirm that the user is really gone
// ie if the user had 7 tabs open and they closed only 1, don't fire userLeft because the user hasn't actually left! only fire userLeft when the user closed all 7 tabs!
// emit userLeft here
console.log(`socket with the id ${socket.id} is now disconnected`);
});
});