-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
88 lines (73 loc) · 2.64 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
const express = require("express");
const app = express();
const path = require('path');
const mongoose = require('mongoose');
// const fs = require('fs');
// const https = require('https');
const pug = require('pug');
// For SSL
// var options = {
// key: fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem'),
// cert: fs.readFileSync('/etc/letsencrypt/live/example.com/cert.pem'),
// ca: fs.readFileSync('/etc/letsencrypt/live/example.com/chain.pem')
// };
//Creating socket.io server
// const server = https.createServer(options).listen(8000);
const io = require('socket.io')(8000);
// mongoose.connect('mongodb://localhost/', { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connect('mongodb://localhost/ichat', { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
const nameSchema = new mongoose.Schema({
name: String
});
app.listen(5001,()=>{
console.log("Server is running on port 5001");
});
const namemodel = mongoose.model('username', nameSchema);
app.use(express.static(__dirname + '/static'));
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, "views"));
app.get("/", (req, res) => {
namemodel.find({}, (err, username) => {
if (err) return console.error(err);
let jsonobj = JSON.stringify(username);
res.status(200).render("main.pug", { "mongodoc": jsonobj });
});
});
const users = {};
// Handling events with Socket.io
io.on('connection', (socket) => {
socket.on('new-user-joined', username => {
let nameobj = {
name: username
};
const name = new namemodel(nameobj);
name.save().then(() => {
users[socket.id] = username;
namemodel.find({}, (err, namedocument) => {
if (err) return console.error(err);
socket.broadcast.emit("user-joined", namedocument);
});
}).catch((err) => {
console.error(err);
});
});
socket.on("send", message => {
socket.broadcast.emit("receive", { message: message, name: users[socket.id] });
});
socket.on("disconnect", () => {
namemodel.deleteOne({ name: users[socket.id] }).then(() => {
namemodel.find({}, (err, newdocument) => {
if (err) return console.error(err);
let newlist = {
'name': users[socket.id],
'onlinelist': newdocument
};
socket.broadcast.emit("user-left", newlist);
delete users[socket.id];
});
}).catch((err) => {
console.error(err);
});
});
});