-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathserver.js
114 lines (91 loc) · 2.54 KB
/
server.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
const express = require("express");
const http = require("http");
const enforce = require("express-sslify");
const app = express();
const server = http.createServer(app);
const socket = require("socket.io");
const io = socket(server);
const path = require("path");
const { AwakeHeroku } = require("awake-heroku");
const _ = require("lodash");
AwakeHeroku.add({
url: "https://smishy.herokuapp.com",
});
app.use(enforce.HTTPS({ trustProtoHeader: true }));
app.use(express.static("./client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
let users = [];
let queue = [];
io.on("connection", (socket) => {
let isBusy = false;
if (!_.includes(users, socket.id)) {
users.push(socket.id);
}
socket.emit("yourID", socket.id);
io.sockets.emit("allUsers", users);
socket.on("disconnect", () => {
_.pull(users, socket.id);
const userInQueue = _.find(queue, u => u.id === socket.id);
if (userInQueue) {
_.remove(queue, {id: userInQueue.id});
isBusy = false;
}
});
socket.on("leaveQueue", () => {
const userInQueue = _.find(queue, u => u.id === socket.id);
if (userInQueue && isBusy) {
isBusy = false;
_.remove(queue, {id: userInQueue.id});
}
});
socket.on("sendMessage", (data) => {
socket.emit("messageSent", {
message: data.message,
});
io.to(data.peerId).emit("receiveMessage", {
message: data.message,
});
});
socket.on("findPartner", (data) => {
viablePartner = _.find(queue, u => {
return u.id !== socket.id && u.onlyChat === data.onlyChat
});
if (!viablePartner && !isBusy) {
isBusy = true;
const userInQueue = _.find(queue, u => u.id === socket.id);
if (!userInQueue) {
queue.push({ id: socket.id, onlyChat: data.onlyChat });
}
} else if (!isBusy) {
isBusy = true;
_.remove(queue, {id: viablePartner.id});
io.to(viablePartner.id).emit("peer", {
peerId: socket.id,
initiator: true,
});
socket.emit("peer", {
peerId: viablePartner.id,
initiator: false,
});
}
});
socket.on("signal", (data) => {
if (!data.peerId) {
return;
}
isBusy = false;
io.to(data.peerId).emit("signal", {
signal: data.signal,
peerId: socket.id,
});
});
// socket.on("close", (data) => {
// io.to(data.peerId).emit("close");
// });
});
const port = process.env.PORT || 8000;
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});