-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
171 lines (156 loc) · 4.88 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
// express
const express = require('express');
// db
const {mongoose} = require('./db');
// view template
const hbs = require('hbs');
// socket.io
const socketIO = require('socket.io');
const http = require('http');
const path = require('path');
const bodyParser = require('body-parser');
// sessions
const session = require("express-session")({
secret: "vladchatapp-secret",
resave: true,
saveUninitialized: true
});
// sharing sessions with socket
const sharedsession = require("express-socket.io-session");
// file system
const fs = require('fs');
// file uploading
const dl = require('delivery');
// logger
const winston = require('winston');
winston.configure({
transports: [
new (winston.transports.File)({ filename: 'logs/logfile.log' })
]
});
// moment
const moment = require('moment');
// Message model
const {Message} = require('./models/Message');
// APP init
const app = express();
// register hbs-partials
hbs.registerPartials(__dirname + '/views/partials');
app.set('view engine', 'hbs');
// register static files
const publicPath = path.join(__dirname, '/public');
app.use(express.static(publicPath));
app.use(session);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(require('./controllers'));
// start server
const server = http.createServer(app);
// socket init
const io = socketIO(server);
// share sessions
io.use(sharedsession(session, {
autoSave:true
}));
// all connected users
var connectedUsers = {};
// filepath
const uploadFilePath = __dirname + '/uploads/';
/**
* IO connection
*/
io.on('connection', (socket) => {
// get user from session
const currentUser = socket.handshake.session.loggedUser || {};
// get user ID
const currId = currentUser._id;
// get current user room ID
const roomId = socket.handshake.session.roomId;
/**
* JOIN event. Update all connected users list
*/
socket.on('join', () => {
// joining
socket.join(roomId);
// add users to the list
if (!(roomId in connectedUsers)) {
connectedUsers[roomId] = {};
}
connectedUsers[roomId][currId] = currentUser.username;
// emit event updateUserList
io.to(roomId).emit('updateUserList', connectedUsers[roomId]);
});
/**
* DISCONNECT event. Update all connected users list
*/
socket.on('disconnect', function() {
if ((roomId in connectedUsers) && (currId in connectedUsers[roomId])) {
delete connectedUsers[roomId][currId];
// emit event updateUserList
io.to(roomId).emit('updateUserList', connectedUsers[roomId]);
}
});
/**
* CREATE NEW MESSAGE event
*/
socket.on('createMessage', (newMessage) => {
// get message
const messageObj = {
text: newMessage.text,
user: currentUser._id,
room: roomId,
createdAt: newMessage.createdAt,
fileLink: newMessage.fileLink
};
const message = new Message(messageObj);
// save it
message.save(function(err) {
if (err) {
winston.log('error', err);
socket.emit('newMessageError', {'text' : "This message couldn't be saved. Please, try one more time :("});
} else {
// emit newMessage event
messageObj.user = currentUser.username;
io.to(roomId).emit('newMessage', messageObj);
}
});
});
/**
* SEND FILE event
*/
const delivery = dl.listen(socket);
delivery.on('receive.success',function(file) {
// file-link
const fileLink = Date.now() + file.name;
fs.writeFile(uploadFilePath + fileLink, file.buffer, function(err) {
if (err) {
winston.log('error', err);
socket.emit('newMessageError', {'text' : "This file couldn't be saved. Please, try one more time :("});
} else {
const fileMessage = {
text: file.name,
user: currentUser._id,
room: roomId,
createdAt: moment().format('MM/DDD/YY, hh:mm a'),
fileLink
};
const message = new Message(fileMessage);
// save it
message.save(function(err) {
if (err) {
winston.log('error', err);
socket.emit('newMessageError', {'text' : "This message couldn't be saved. Please, try one more time :("});
} else {
// emit newMessage event
fileMessage.user = currentUser.username;
io.to(roomId).emit('newMessage', fileMessage);
}
});
}
});
});
});
server.listen(3010, () => {
console.log('Server is up on port 3010...');
});