-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
133 lines (79 loc) · 2.38 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
const express = require('express');
const bodyParser=require("body-parser");
const http=require("http");
const formatMessage=require("./utils/messages");
const {userJoin,getCurrentUser,userLeave,getRoomUsers}=require("./utils/users");
const app=express();
app.use(bodyParser.urlencoded({extended:true}));
app.set("view engine","ejs");
const socketio=require("socket.io");
const server = http.createServer(app);
const io=socketio(server);
app.use(express.static("public"));
const botName="Bot";
let roomsCollection=[];
io.on("connection",socket=>{
socket.on("joinRoom",({username,room})=>{
console.log(username);
const user=userJoin(socket.id,username,room);
console.log(user);
socket.join(user.room);
socket.emit("message",formatMessage(botName,"Welcome to chatter"));
socket.broadcast.to(user.room).emit("message",formatMessage(botName, `A ${user.username} has joined the chat!`));//broadcas to all except client
io.to(user.room).emit("roomUsers",{
room:user.room,
users: getRoomUsers(user.room)
});
});
socket.on("chatMessage",(msg)=>{
const user=getCurrentUser(socket.id);
io.to(user.room).emit("message",formatMessage(user.username,msg));
});
socket.on("disconnect",()=>{
const user=userLeave(socket.id);
if(user){
io.to(user.room).emit('message', formatMessage(botName, `${user.username} has left the chat`));
io.to(user.room).emit("roomUsers",{
room:user.room,
users: getRoomUsers(user.room)
});
}
});
})
app.get("/",function(req,res){
res.render("index",{pass:1});
})
// app.get("/chat",function(req,res){
//
//
// })
app.post("/enter",function(req,res){
const name=req.body.name;
const rName=req.body.room_name;
const rPK=req.body.room_no;
for(i=0;i<roomsCollection.length;i++){
if(roomsCollection[i].rname==rName){
if(roomsCollection[i].passkey==rPK){
res.render("chat",{rn:rName,name:name});
}
}
}
res.render("index",{pass:0});
})
app.post("/rooms",function(req,res){
const name=req.body.name;
const rName=req.body.room_name;
const rPK=req.body.room_no;
var temp={
name:name,
rname:rName,
passkey:rPK
}
roomsCollection.push(temp);
// console.log(temp);
res.render("chat",{rn:rName,name:name});
// res.redirect("/chat");
})
server.listen(process.env.PORT || 3000,function(){
console.log("Running on 3000")
});