-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
256 lines (218 loc) · 8.31 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
/**
* ? Importing the packages/libraries
*/
const express = require("express");
const cookieParser = require("cookie-parser");
require("dotenv").config();
/**
* ? express setup
*/
const app = express();
app.use(express.json());
app.use(express.static(__dirname));
app.use(cookieParser());
/**
* ? socket.io setup
*/
const http = require("http").Server(app);
const io = require("socket.io")(http);
http.listen("3000", () => {
console.log("Listening to 3000");
})
/**
* ? Tests if the password has a lowercase, an uppercase, a number and if the password is 8 characters or longer
*/
app.post("/ValidatePassword", async (req, res) => {
const password = await req.body.password;
if (!password) return res.send({ isValid: false });
const cond1 = password.length >= 8; // check if the password is 8 characters or longer
// Check if the chatacter has a lowercase, an uppercase and a number in the password
const cond2 = (/[a-z]/).test(password) && (/[A-Z]/).test(password) && (/[0-9]/).test(password);
return res.send({ isValid: cond1 && cond2, charLen8: cond1, mixOfDiff: cond2 }); // return true if both the conditions are true
})
app.get(`/@me/:channel_id`, async (req, res) => {
res.sendFile(__dirname + "/@me/");
})
app.get(`/gif`, async (req, res) => {
const query = req.query.q;
const pos = req.query.pos;
const limit = req.query.limit;
await fetch(`https://tenor.googleapis.com/v2/search?q=${query}&limit=${limit}&pos=${pos}&key=${process.env.TENORAPIKEY}&client_key=ChatterBox`).then(async response => {
if (response.ok) return response.json();
}).then(response => {
const results = response.results;
const next = response.next;
const resToSend = [];
results.forEach(result => {
resToSend.push(result.media_formats.gif.url);
})
res.send({ results: resToSend, next: next });
})
})
/**
* ? socket.io events
*/
let activeUsers = new Map();
let usersTyping = new Map();
setInterval(() => {
usersTyping.clear();
}, 5000);
const url = "http://localhost:3000";
io.on("connection", socket => {
socket.on("SET_UNAME", async data => {
try {
socket.data.username = data.user.username;
socket.data.channelId = data.channel ? data.channel._id : data.user.username;
} catch (error) {
console.log(error);
}
})
socket.on("JOIN_CHANNEL", async data => {
try {
const channel = data.channel;
const username = data.user.username;
const avatarURL = data.user.avatarURL;
const colorPrefered = data.user.color;
const user = {
username: username,
avatarURL: avatarURL,
color: colorPrefered,
};
const aUsersInChnl = (activeUsers.has(channel._id) && activeUsers.get(channel._id).length > 0) ? activeUsers.get(channel._id) : [];
aUsersInChnl.push(user);
socket.join(`${url}/@me/${channel._id}`);
const onlineRes = await fetch(`http://localhost:3001/api/make_online?key=${process.env.logoutKey}&uname=${socket.data.username}`)
io.to(`${url}/@me/${username}`).emit("GET_USERS", channel);
io.emit("UPDATE_GLOBAL_USERS", { user: username, mode: "online" });
activeUsers.set(channel._id, aUsersInChnl);
if (socket.data.username !== undefined) await fetch(`http://localhost:3001/api/make_online?key=${process.env.logoutKey}&uname=${socket.data.username}`);
} catch (error) {
console.log(error);
}
})
socket.on("LEAVE_CHANNEL", data => {
try {
const channel = data.channel;
const user = data.user;
socket.leave(`${url}/@me/${channel._id}`);
const aUsersInChnl = activeUsers.get(channel._id);
const updatedUsers = [];
aUsersInChnl.forEach(u => {
const u2push = {
username: u.username,
avatarURL: u.avatarURL,
color: u.color,
};
if (u.username !== user.username) {
updatedUsers.push(u2push);
}
})
io.emit("UPDATE_GLOBAL_USERS", { user: user.username, mode: "offline" });
activeUsers.set(channel._id, updatedUsers);
} catch (error) {
console.log(error);
}
})
socket.on("UUL", data => {
io.to(`${url}/@me/${data.channel._id}`).emit("UPDATE_USERS_LIST", data.members);
})
socket.on("LOGIN", async data => {
try {
const username = data.username;
const pfp = data.avatarURL;
const colorPrefered = data.color;
socket.join(`${url}/@me/${username}`);
const user = {
username: username,
pfp: pfp,
color: colorPrefered
};
io.emit("UPDATE_GLOBAL_USERS", { user: username, mode: "online" });
if (socket.data.username !== undefined) await fetch(`http://localhost:3001/api/make_online?key=${process.env.logoutKey}&uname=${socket.data.username}`);
} catch (error) {
console.log(error);
}
})
socket.on("MESSAGES", data => {
try {
const channelId = data.channel._id;
const channelURL = `${url}/@me/${channelId}`;
const message = {
_id: data._id,
user: data.user,
content: data.content,
channel: data.channel,
components: data.components ? data.components : [],
timestamp: Date.now(),
edited: false
}
if (data.repliedTo)
message.repliedTo = data.repliedTo;
io.to(channelURL).emit("MESSAGES", message);
} catch (error) {
console.log(error);
}
})
socket.on("DEL_MSG", data => {
try {
const channelURL = `${url}/@me/${data.channel._id}`;
io.to(channelURL).emit("DEL_MSG", data.id);
} catch (e) {
console.log(e);
}
})
socket.on("EDIT_MSG", data => {
try {
const channelURL = `${url}/@me/${data.cid}`;
io.to(channelURL).emit("EDIT_MSG", { id: data.mid, content: data.content });
} catch (e) {
console.log(e);
}
})
socket.on("TYPING", data => {
try {
const username = data.username;
const channelId = data.channelId;
if (usersTyping.has(channelId)) {
const channelTypingUsers = usersTyping.get(channelId);
if (!channelTypingUsers.includes(username)) {
channelTypingUsers.push(username);
usersTyping.set(channelId, Array.from(new Set(channelTypingUsers).values()));
}
}
else {
const channelTypUsers = [];
channelTypUsers.push(username);
usersTyping.set(channelId, Array.from(new Set(channelTypUsers).values()));
}
io.to(`${url}/@me/${channelId}`).emit("TYPING", usersTyping.get(channelId));
} catch (error) {
console.log(error);
}
})
socket.on("USER_INVITE", (username, user) => {
try {
io.to(`${url}/@me/${username}`).emit("USER_INVITE", `${user.username} added you to a channel`);
} catch (error) {
console.log(error);
}
})
socket.on("disconnect", async data => {
try {
const username = socket.data.username;
[...activeUsers.keys()].forEach(key => {
const u2push = [];
[...activeUsers.get(key)].forEach(user => {
if (user.username !== username) u2push.push(user);
});
activeUsers.set(key, u2push);
})
io.emit("UPDATE_GLOBAL_USERS", { user: username, mode: "offline" });
const logoutRes = await fetch(`http://localhost:3001/api/make_offline?key=${process.env.logoutKey}&uname=${socket.data.username}`);
if (logoutRes.ok) return;
else console.log("something went wrong!");
} catch (error) {
console.log(error);
}
})
})