-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
517 lines (400 loc) · 15.5 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
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
const express = require('express');
const app = express();
const path = require('path');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const passport = require('passport');
const localstrategy = require('passport-local');
const flash = require('connect-flash');
const User = require('./models/users');
const Patient = require('./models/patients');
const Specialty = require('./models/specialties');
const Appointment = require('./models/appointments');
const apperror = require('./apperror');
const catchAsync = require('./catchAsync');
const http = require("http")
const formatMessage = require("./utils/messages");
const { userJoin, getCurrentUser, userLeave, getRoomUsers } = require("./utils/users");
const socketio = require("socket.io");
const bot = 'Health-E Bot';
const server = http.createServer(app);
const io = socketio(server);
app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, 'views'));
app.use(bodyParser.urlencoded({ extended: true }))
app.use(methodOverride('_method'));
app.use('/public', express.static('public'));
app.use(express.static(path.join(__dirname, 'public')));
mongoose.connect('mongodb+srv://healthe:[email protected]/healthe?retryWrites=true&w=majority');
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log('Database connected');
})
const session = require('express-session');
const { isLoggedIn } = require('./middleware');
const doctors = require('./models/doctors');
const sessionOptions = {
secret: 'thisisnotagoodsecret', resave: false, saveUninitialized: true,
cookie: {
expires: Date.now() + 500000000,
maxAge: 500000000, httpOnly: true
}
}
app.use(flash());
app.use(session(sessionOptions));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new localstrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use((req, res, next) => {
res.locals.currentUser = req.user;
res.locals.success = req.flash('success');
res.locals.error = req.flash('error');
next();
})
app.get('/', (req, res) => {
res.render('home');
})
app.get('/users/register', (req, res) => {
res.render('users/create')
})
app.get('/users/login', (req, res) => {
res.render('users/login')
})
app.get('/myprofile', isLoggedIn, catchAsync(async (req, res) => {
if (req.user.usertype == 0) {
const profiledetails = await Patient.findOne({ 'user': `${req.user._id}` });
res.render('users/showpatientinfo', { profiledetails });
}
if (req.user.usertype == 1) {
const profiledetails = await doctors.findOne({ 'user': `${req.user._id}` }).populate('specialty');
res.render('users/showdoctorinfo', { profiledetails });
}
}))
app.get('/newprofile', catchAsync(async (req, res) => {
if (req.user.usertype == 0) {
res.render('users/patientprofile');
}
else {
const specialties = await Specialty.find();
res.render('users/doctorprofile', { specialties });
}
}))
app.post('/patientprofile', catchAsync(async (req, res) => {
const newpat = await new Patient(req.body);
newpat.user = req.user._id;
newpat.save();
res.redirect('/specialties');
}))
app.post('/doctorprofile', isLoggedIn, catchAsync(async (req, res) => {
const newdoc = await new doctors(req.body);
newdoc.user = req.user._id;
console.log(req.body.selectspecialty);
const specialty = await Specialty.findOne({ 'name': req.body.selectspecialty })
newdoc.specialty = specialty;
await newdoc.save();
specialty.doctors.push(newdoc);
await specialty.save();
res.redirect('/specialties');
}))
app.get('/myprofile/:patientid/update', isLoggedIn, catchAsync(async (req, res) => {
if (req.user.usertype == 0) {
const requiredpatient = await Patient.findById(req.params.patientid);
res.render('users/updatepatientinfo', { requiredpatient });
}
else {
const requiredpatient = await doctors.findById(req.params.patientid).populate('specialty');
res.render('users/updatedoctorinfo', { requiredpatient });
}
}))
app.put('/myprofile/:patientid', isLoggedIn, catchAsync(async (req, res) => {
if (req.user.usertype == 0) {
await Patient.findByIdAndUpdate(req.params.patientid, req.body, { runValidators: true });
}
else {
await doctors.findByIdAndUpdate(req.params.patientid, req.body, { runValidators: true });
}
res.redirect('/myprofile');
}))
app.get('/specialties', catchAsync(async (req, res) => {
const specialties = await Specialty.find();
res.render('appointments/specialties', { specialties });
}))
app.get('/specialties/:specialtyid', catchAsync(async (req, res) => {
const specialty = await Specialty.findById(req.params.specialtyid).populate('doctors');
if (req.isAuthenticated() && req.user.usertype == 1) {
const curdoc = await doctors.findOne({ 'user': `${req.user._id}` });
res.render('appointments/show', { specialty, curdoc });
}
else
res.render('appointments/show', { specialty });
}))
app.post('/register', catchAsync(async (req, res) => {
try {
const { email, username, password, usertype } = req.body;
const user = new User({ email, username, usertype });
const registereduser = await User.register(user, password);
req.login(registereduser, err => {
if (err) return next(err);
req.flash('success', 'Welcome to Health-E!');
res.redirect('/newprofile');
})
}
catch (err) {
req.flash('error', err.message);
res.redirect('/users/register');
}
}))
app.post('/login', passport.authenticate('local', { failureFlash: true, failureRedirect: '/users/login' }), catchAsync(async (req, res) => {
try {
if (req.user.usertype == 1)
req.flash('success', 'Welcome Back, Doctor!');
else req.flash('success', 'Welcome Back, Patient!');
const redirectUrl = req.session.returnTo || '/specialties';
delete req.session.returnTo;
res.redirect(redirectUrl);
}
catch (err) {
req.flash('error', 'Invalid Credentials');
}
}))
app.get('/book/:doctorid', isLoggedIn, catchAsync(async (req, res) => {
const curdoc = await doctors.findById(req.params.doctorid);
let today = new Date();
let dd = String(today.getDate()).padStart(2, '0');
let mm = String(today.getMonth() + 1).padStart(2, '0');
let yyyy = today.getFullYear();
let stdate = yyyy + '-' + mm + '-' + dd;
Date.prototype.addDays = function (days) {
let date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
let date = new Date();
today = date.addDays(10);
dd = String(today.getDate()).padStart(2, '0');
mm = String(today.getMonth() + 1).padStart(2, '0');
yyyy = today.getFullYear();
let endate = yyyy + '-' + mm + '-' + dd;
res.render('appointments/book', { curdoc, stdate, endate });
}))
app.post('/appointment/:doctorid', isLoggedIn, catchAsync(async (req, res) => {
const newappt = await new Appointment(req.body);
const curdoc = await doctors.findById(req.params.doctorid);
const curpar = await Patient.findOne({ 'user': `${req.user._id}` });
newappt.patient = curpar;
newappt.doctor = curdoc;
newappt.fee = curdoc.fee;
await newappt.save();
console.log(curpar);
curdoc.myappointments.push(newappt);
curpar.myappointments.push(newappt);
await curdoc.save();
await curpar.save();
res.redirect('/myappointments');
}))
app.get('/myappointments', isLoggedIn, catchAsync(async (req, res) => {
if (req.user.usertype == 0) {
const curpar = await Patient.findOne({ 'user': `${req.user._id}` }).populate({
path: 'myappointments',
populate: {
path: 'doctor'
}
});;
res.render('appointments/myappointments', { curpar });
}
else {
const curdoc = await doctors.findOne({ 'user': `${req.user._id}` }).populate({
path: 'myappointments',
populate: {
path: 'patient'
}
});
res.render('appointments/myappointments', { curdoc });
}
}))
app.get('/getforupdateappointment/:appointmentid', isLoggedIn, catchAsync(async (req, res) => {
const curap = await Appointment.findById(req.params.appointmentid).populate('doctor');
let today = new Date();
let dd = String(today.getDate()).padStart(2, '0');
let mm = String(today.getMonth() + 1).padStart(2, '0');
let yyyy = today.getFullYear();
let stdate = yyyy + '-' + mm + '-' + dd;
Date.prototype.addDays = function (days) {
let date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
let date = new Date();
today = date.addDays(10);
dd = String(today.getDate()).padStart(2, '0');
mm = String(today.getMonth() + 1).padStart(2, '0');
yyyy = today.getFullYear();
let endate = yyyy + '-' + mm + '-' + dd;
today = curap.date;
console.log(today);
dd = String(today.getDate()).padStart(2, '0');
mm = String(today.getMonth() + 1).padStart(2, '0');
yyyy = today.getFullYear();
let apdate = yyyy + '-' + mm + '-' + dd;
console.log(apdate);
res.render('appointments/update', { curap, apdate, stdate, endate });
}))
app.put('/updateappointment/:appointmentid', isLoggedIn, catchAsync(async (req, res) => {
await Appointment.findByIdAndUpdate(req.params.appointmentid, req.body, { runValidators: true });
res.redirect('/myappointments');
}))
app.delete('/deleteappointment/:appointmentid', isLoggedIn, catchAsync(async (req, res) => {
const curappt = await Appointment.findById(req.params.appointmentid);
await doctors.findByIdAndUpdate(curappt.doctor, { $pull: { myappointments: req.params.appointmentid } });
await Patient.findByIdAndUpdate(curappt.patient, { $pull: { myappointments: req.params.appointmentid } });
await Appointment.findByIdAndDelete(req.params.appointmentid);
res.redirect('/myappointments');
}))
app.get('/mychats', isLoggedIn, catchAsync(async (req, res) => {
const curuser = await User.findById(req.user._id).populate({
path: 'mychats',
populate: {
path: 'userids'
}
});
const chats = [];
const curusername = curuser.username;
for (ch of curuser.mychats) {
const obj = {
chat: ch.room_name,
others: []
};
for (x of ch.userids) {
if (curusername.localeCompare(x.username) == 0)
continue;
if (x.usertype == 1) {
const curdoc = await doctors.findOne({ 'user': `${x._id}` });
obj.others.push(curdoc.fullname);
} else {
const curpar = await Patient.findOne({ 'user': `${x._id}` });
obj.others.push(curpar.fullname);
}
}
chats.push(obj);
}
chats.reverse();
res.render('chats/list', { chats });
}))
app.get('/logout', isLoggedIn, catchAsync(async (req, res) => {
req.logout();
res.redirect('/users/login');
}))
//socket.on is definition of the function 'example'
//while socket.emit is kind of calling the socket.on function
const roomsSchema = {
room_name: String,
chat_history: [],
userids: []
}
const Room = new mongoose.model("Room", roomsSchema);
// we are using http to help express work with socket io
//run when client connects
//io will listen for a event/connection
io.on("connection", function (socket) {
socket.on('joinRoom', function ({ username, room }) {
const user = userJoin(socket.id, username, room);
socket.join(user.room);
//it is only sent to the guy joining
console.log("hello");
Room.find({}, function (err, result) {
var x = -1;
// console.log("I am looking for room:"+user.room);
for (var i = 0; i < result.length; i++) {
if (result[i].room_name == user.room) {
x = i;
}
}
if (x == -1) {
const room1 = new Room({
room_name: user.room,
chat_history: [],
userids: []
});
room1.save();
async function add() {
console.log(room1);
const curuser = await User.findById(username);
curuser.mychats.push(room1);
await curuser.save();
let len = username.length;
let docid = room1.room_name.substring(len);
const curdoc = await doctors.findById(docid);
const docuser = await User.findById(curdoc.user);
docuser.mychats.push(room1);
await docuser.save();
room1.userids.push(curuser);
room1.userids.push(docuser);
await room1.save();
}
add();
// console.log("creating a new room");
socket.emit("message", formatMessage(bot, "Welcome to chat app"));
} else {
for (var i = 0; i < result[x].chat_history.length; i++) {
socket.emit("message", result[x].chat_history[i]);
}
socket.emit("message", formatMessage(bot, "Welcome to chat app"));
}
});
//broadcast when a user connections
//it is sent to all except the guy joining
socket.broadcast.to(user.room).emit("message", formatMessage(bot, `${username} has joined the chat`));
//Send users and room info from
//server to clients
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
});
//jesse hi client side se kuch bhi chat waale form se content
//server pe aata hai toh hum usse baaki members ko bhi dikhana
//chahenge, so ab hum server se firse client ko content bhej denge
//listen for chatMessage
socket.on("chatMessage", function (msg) {
const user = getCurrentUser(socket.id);
const msg1 = formatMessage(user.username, msg);
io.to(user.room).emit("message", msg1);
Room.find({}, function (err, res) {
for (var i = 0; i < res.length; i++) {
if (res[i].room_name == user.room) {
res[i].chat_history.push(msg1);
res[i].save();
}
}
})
});
//runs when a client disconnects
//it is sent to all
socket.on("disconnect", function () {
const user = userLeave(socket.id);
// console.log(user);
io.to(user.room).emit("message", formatMessage(bot, `${user.username} has left the chat`));
//Send users and room info from
//server to clients
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
});
});
app.all('*', (req, res, next) => {
next(new apperror('page not found', 404));
})
app.use((err, req, res, next) => {
const { status1 = 500, } = err;
if (!err.message)
err.message = 'something went wrong';
res.status(status1).render('error', { err })
})
server.listen(3000, () => {
console.log('serving on port 3000');
})