-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
103 lines (74 loc) · 2.51 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
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const morgan = require('morgan');
const path = require('path');
const { render } = require('ejs');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const bodyParser = require('body-parser');
const passport = require('passport');
var http = require('http');
var socketIO = require('socket.io');
const formatMessage = require('./utils/moment.js');
dotenv.config({ path: './config/config.env' });
require('./config/passport')(passport);
const db = require('./config/key.js').MongoURI;
mongoose.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
.then(() => { console.log("Connectd to MongoDB") })
.catch(err => console.log(err));
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'public')));
app.use(morgan('dev'));
app.set('view engine', 'ejs');
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: true,
store: new MongoStore({mongooseConnection : mongoose.connection})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "public")));
app.use('/', require('./routes/mainRouter.js'));
var server = http.Server(app);
server.listen(PORT);
var io = socketIO(server);
let users = {};
io.use(async (socket,next) => {
const userID = socket.handshake.query.userid;
const name = socket.handshake.query.name;
if(!userID){
return next(new Error("invalid username"));
}
users[userID] = socket.id;
socket.userID = userID;
socket.name = name;
next();
})
io.on('connection' , (socket) => {
socket.emit('message' , { message : `Welcome to chat ${socket.name}` , time: formatMessage().time});
socket.on('private message' , ({content , to}) => {
var toID = users[to];
var time = formatMessage().time;
socket.to(toID).emit("private message" , {
content,
from : socket.id,
time : time
});
});
socket.on('typing', function (data) {
socket.broadcast.emit('typing', data);
});
socket.on('disconnect' , ()=>{
io.emit('message' , {message : `${socket.name} has left the chat` , time : formatMessage().time});
});
})