-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
executable file
·248 lines (230 loc) · 8.58 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
/**
* ---------------------------------------------
* -------- IMPORTING REQUIRED FILES -----------
* ---------------------------------------------
*/
const http = require("http");
const express = require("express");
const socketio = require("socket.io");
const redisAdapter = require("socket.io-redis");
const chamber = require("./model/chamber_schema");
const user = require('./model/users_schema')
const cors = require("cors");
const router = require("./router");
const mongoose = require("mongoose");
const jwt = require("jsonwebtoken");
const path=require('path')
const dotenv = require("dotenv");
dotenv.config();
/**
* ---------------------------------------------
* --------------- PORT SETUP -----------------
* ---------------------------------------------
*/
const PORT = process.env.PORT || 5000;
/**
* ---------------------------------------------
* --------------- REDIS SETUP -----------------
* ---------------------------------------------
*/
var client = require("./redis/redis_connect");
client.on("error", function (error) {
console.error("error");
});
/**
* ---------------------------------------------
* ----------- SETTINGUP MIDDLEWARES -----------
* ---------------------------------------------
*/
const app = express();
app.use(express.json());
const server = http.createServer(app);
const io = socketio(server).adapter(
redisAdapter({host:process.env.redishost, port:process.env.redisport,auth_pass:process.env.redispass})
);
app.use(cors({origin:"https://discussjunction.herokuapp.com"}));
app.use("/api", router);
/**
* ---------------------------------------------
* ----------- SOCKETIO MANAGEMENT-- -----------
* ---------------------------------------------
*/
io.use(function (socket, next) {
if (socket.handshake.query && socket.handshake.query.token) {
jwt.verify(socket.handshake.query.token, process.env.jwt_secret, function (
err,
decoded
) {
if (err) {
console.log("error");
return next(new Error("Authentication error"));
} else {
client.set(socket.id,decoded.DJID)
next();
}
});
} else {
next(new Error("Authentication error"));
}
}).on("connect", function (socket) {
console.log("connected with socket id: " + socket.id);
socket.emit('confirmconnect', {"success":"connected"});
/**
* ---------------------------------------------
* JOIN A CHAMBER
* ---------------------------------------------
*/
socket.on("joinroom", (message /* chamber_id,name,user_Id */, callback) => {
client.SADD(message.user_id,message.chamber_id,async function(err,reply){
console.log(reply)
if(reply===1){
chamber.findByIdAndUpdate({ _id: message.chamber_id },{ $inc: { active_user_count: 1 } },{useFindAndModify:false}).then((doc) => {
if(doc){
console.log("incremented active users")
socket.join(message.chamber_id, (err) => {
if (err) {
callback({ error: err });
}
});
socket.emit('confirmjoiningroom', {"success":message.chamber_id,"name":doc.chamber_name,"photo":doc.photo_url,"count":doc.active_user_count});
user.findByIdAndUpdate({_id:message.user_id},{$push:{joined_chambers:{chamber_id:message.chamber_id,date:Date.now()}}},{useFindAndModify:false}).then(doc=>console.log('added to user history'))
}
}).catch((err) => {console.log("error" + err);
socket.emit('errorjoiningroom', {"error":message.chamber_id,"message":"Error joining the room"});
}
);
}if(reply===0){
socket.emit('errorjoiningroom', {"error":message.chamber_id,"message":"you have already joined the room"});
}
})
});
/**
* ---------------------------------------------
* SEND MY DETAILS TO CHAMBER
* ---------------------------------------------
*/
socket.on('sendme',(message,callback)=>{
socket.to(message.chamber_id).emit("userjoined", {
"chamber_id": message.chamber_id,
"socketid": socket.id,
"name": message.name,
"user_id":message.user_id,
"message": `${message.name} has joined the chamber`,
});
})
/**
* ---------------------------------------------
* SEND ONLINE USERS TO CHAMBER
* ---------------------------------------------
*/
socket.on('listofusers',(message,callback)=>{
socket.to(message.chamber_id).emit("listofonlineusers", {
"chamber_id": message.chamber_id,
"list":message.list
})
})
/**
* ---------------------------------------------
* SEND MESSAGE TO CHAMBER
* ---------------------------------------------
*/
socket.on('sendmessage',(message/* roomid,name,message */,callback)=>{
socket.to(message.chamber_id).emit('receivemessage',{"chamber_id": message.chamber_id,"socketid": socket.id,"name": `${message.name}`,"message":message.message,"userid":message.user_id});
socket.emit('messagereceipt',{"chamber_id": message.chamber_id,"msgid":message.msgid});
})
/**
* ---------------------------------------------
* SEND KEYPRESS TO CHAMBER
* ---------------------------------------------
*/
socket.on('keypress',(message/* roomid,name,message */,callback)=>{
socket.to(message.chamber_id).emit('keypressreceive',{"chamber_id": message.chamber_id,"socketid": socket.id,"name": `${message.name}`,"message":`${message.name} is typing`});
})
/**
* ---------------------------------------------
* LEAVE FROM CHAMBER
* ---------------------------------------------
*/
socket.on('leavechamber',(message,callback)=>{
client.srem(message.user_id,message.chamber_id)
socket.leave(message.chamber_id, () => {
io.to(message.chamber_id).emit("left",{"socketid":socket.id,"chamber_id":message.chamber_id});
socket.emit("leftaroom",{"chamber_id":message.chamber_id})
});
chamber.findByIdAndUpdate({ _id: message.chamber_id },{ $inc: { active_user_count: -1 } },{useFindAndModify:false}).then(doc=>console.log("reduced"))
})
/**
* ---------------------------------------------
* REMOVE FROM MONGO AND ROOMS
* ---------------------------------------------
*/
socket.on("disconnecting", () => {
var tasks = [];
client.get(socket.id,(err,reply)=>{
client.del(reply,(err,reply)=>{if(err){console.log("delusererror: "+err)}if(reply){console.log("deluserreply:"+reply)}})
client.del(socket.id,(err,reply)=>{if(err){console.log("socketerror: "+err)}if(reply){console.log("socketreply:"+reply)}})
})
socket.adapter.clientRooms(socket.id, (err, rooms) => {
if (err) {
console.log("error getting details");
}
console.log(rooms); // an array containing every room a given id has joined.
let makeevents = new Promise((resolve, reject) => {
for (i = 1; i < rooms.length; i++) {
io.to(rooms[i]).emit("left",{"socketid":socket.id,"chamber_id":rooms[i]})
tasks.push({
updateOne: {
filter: { "_id": { $eq: rooms[i] } },
update: { "$inc": { "active_user_count": -1 } },
},
});
if (i === rooms.length) {
resolve(success);
}
}
});
if(rooms.length>1){makeevents.then(chamber.bulkWrite(tasks).then((result) => console.log('removed from all rooms')));}
});
});
/**
* ---------------------------------------------
* get room data A SOCKET not yet used
* ---------------------------------------------
*/
// socket.on('getusers',(message,callback)=>{
// io.in('5f34f5c7f2fa0e1e9c26ab80').clients((err, clients) => {
// console.log(clients); // an array containing socket ids in 'room3'
// socket.to(message.chamber_id).emit('receivemessage',{"chamber_id": message.chamber_id,"socketid": socket.id,"name": `admin`,"message":clients});
// });
// })
/**
* ---------------------------------------------
* DISCONNET A SOCKET
* ---------------------------------------------
*/
socket.on("disconnect", () => {
console.log(
"disconnected socket id: " + socket.id
);
socket.disconnect(0);
});
});
if (process.env.NODE_ENV === "production") {
app.use(express.static(__dirname + "/public"));
app.get("*", (req, res) =>
res.sendFile(path.join(__dirname, "/public/index.html"))
);
}
/**
* ---------------------------------------------
* ------------- SETTINGUP SERVERS -------------
* ---------------------------------------------
*/
server.listen(process.env.PORT || 5000, () =>
console.log("server is started at port " + PORT)
);
mongoose.connect(
process.env.data_connection_string,
{ useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true},
() => console.log("connected to database")
);