-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
200 lines (171 loc) · 5.98 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
192
193
194
195
196
197
198
199
200
const express = require('express');
const http = require("http");
const app = express();
const request = require('request');
const server =http.createServer(app);
const io = require("socket.io").listen(server);
const mongoose = require('mongoose');
var createError = require('http-errors');
const morgan = require('morgan');
var path = require('path');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const expressValidator = require('express-validator');
const cors = require('cors');
const passport = require('passport');
var methodOverride = require("method-override");
const flash = require('connect-flash');
const dotenv = require('dotenv');
dotenv.config();
require('./config/passport');
const PORT = process.env.PORT;
mongoose.set('useNewUrlParser', true);
mongoose.set('useUnifiedTopology', true);
mongoose.connect(process.env.MONGODB_URI)
.then(() => console.log('db connected'));
mongoose.connection.on('error', err => {
console.log(`DB Error: ${err.message}`);
});
const postRoutes = require('./routes/post');
const authRoutes = require('./routes/auth');
const userRoutes = require('./routes/user');
const chatRoutes = require('./routes/chat');
const lostRoutes = require('./routes/lost');
const paymentRoutes = require('./routes/payment');
const priceRoutes = require('./routes/price');
const adminRoutes = require('./routes/admin');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(morgan('dev'));
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(expressValidator());
app.use(cors());
app.use("/images",express.static(path.join(__dirname, 'images')));
app.use(express.static(path.join(__dirname, 'assets')));
const Socket = require('./models/socket');
const Chat = require('./models/chat');
io.on('connection', async (socket) => {
console.log('CLIENT CONNECTED')
socket.on('userInfo',(user) => {
console.log(user);
Socket.findOne({email: user.email}, function(err,res) {
if(!res){
let newSocket = new Socket({
socketId: socket.id,
user: user,
email: user.email
})
newSocket.save((err,result) => {
if(err){
console.log(err)
} else {
console.log("ADDED TO DB ", socket.id)
}
})
} else {
Socket.findOneAndUpdate({email: user.email} ,{$set: {"socketId": socket.id}}, (err,result) => {
if(err){
console.log(err)
}else{
console.log("UPDATED");
}
})
}
})
});
socket.on('sendMessage', (message, sender, receiver, callback) => {
const senderId = sender._id;
const receiverId = receiver._id;
Socket.findOne({email: receiver.email})
.exec(async function(err,res) {
if(res!=null){
console.log("SENT")
const newChat = new Chat({
message,
receiver,
sender
});
await newChat.save((err,result) => {
if(err){
console.log(err)
} else {
console.log("--------------------------------");
console.log("CHAT SAVED");
console.log("--------------------------------");
}
})
// const allChats = await Chat.find({ $or: [{ 'receiver._id': receiverId, 'sender._id': senderId },{ 'sender._id': receiverId, 'receiver._id': senderId }] })
console.log("emitting online")
io.to(res.socketId).emit('message', newChat);
socket.emit('message', newChat);
} else {
const newChat = new Chat({
message,
receiver,
sender
});
await newChat.save((err,result) => {
if(err){
console.log(err)
} else {
console.log("--------------------------------");
console.log("OFFLINE CHAT SAVED");
console.log("--------------------------------");
}
})
console.log("emitting offline")
//console.log(newChat);
socket.emit('message', newChat);
}
})
callback();
});
socket.on('disconnect', () => {
Socket.findOne({socketId: socket.id})
.remove((err, result) => {
if(err){
console.log(err)
} else {
console.log("DELETED");
}
})
console.log("DISCONNECTED")
});
});
app.use(session({
secret: 'supersecret',
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
cookie: { maxAge: 180 * 60 * 1000 }/* 180 minutes */
}));
app.use(flash());
app.use(methodOverride("_method"));
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next){
res.locals.currentUser = req.user;
res.locals.session = req.session;
next();
});
app.use(authRoutes);
app.use(postRoutes);
app.use(chatRoutes);
app.use(userRoutes);
app.use(lostRoutes);
app.use(paymentRoutes);
app.use(priceRoutes);
app.use(adminRoutes);
app.use(function(err,req,res,next){
if(err.name === 'UnauthorizedError'){
res.status(401).json({ error: "Unauthorized !" });
}
});
server.listen(PORT, () => {
console.log(`Server started at port ${PORT}`)
})