-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
executable file
·216 lines (181 loc) · 6.05 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
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
"use strict";
const express = require("express");
const app = express();
const cmd = require("node-cmd");
const crypto = require("crypto");
const bodyParser = require("body-parser");
const fs = require("fs");
const dotenv = require("dotenv").config();
const debug = process.env.DEBUG || "true";
let options;
if (!debug) {
options = {
key: fs.readFileSync(process.env.KEY_PATH),
cert: fs.readFileSync(process.env.CERT_PATH)
};
}
const https = require("https").createServer(options, app);
// default -- pingInterval: 1000 * 25, pingTimeout: 1000 * 60
// low latency -- pingInterval: 1000 * 5, pingTimeout: 1000 * 10
let io, http;
const ping_interval = 1000 * 5;
const ping_timeout = 1000 * 10;
const port_http = process.env.PORT_HTTP || 8080;
const port_https = process.env.PORT_HTTPS || 443;
const port_ws = process.env.PORT_WS || 4321;
const WebSocket = require("ws");
const ws = new WebSocket.Server({ port: port_ws, pingInterval: ping_interval, pingTimeout: ping_timeout }, function() {
console.log("\nNode.js listening on websocket port " + port_ws);
});
if (!debug) {
http = require("http");
http.createServer(function(req, res) {
res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url });
res.end();
}).listen(port_http);
io = require("socket.io")(https, {
pingInterval: ping_interval,
pingTimeout: ping_timeout
});
} else {
http = require("http").Server(app);
io = require("socket.io")(http, {
pingInterval: ping_interval,
pingTimeout: ping_timeout
});
}
// ~ ~ ~ ~
app.use(express.static("public"));
// https://opensourcelibs.com/lib/glitchub
app.use(bodyParser.json());
const onWebhook = (req, res) => {
let hmac = crypto.createHmac("sha1", process.env.SECRET);
let sig = `sha1=${hmac.update(JSON.stringify(req.body)).digest("hex")}`;
if (req.headers["x-github-event"] === "push" && sig === req.headers["x-hub-signature"]) {
cmd.run("chmod +x ./redeploy.sh");
cmd.run("./redeploy.sh");
cmd.run("refresh");
}
return res.sendStatus(200);
}
app.post("/redeploy", onWebhook);
app.get("/", function(req, res) {
res.sendFile(__dirname + "/public/index.html");
});
// ~ ~ ~ ~
if (!debug) {
https.listen(port_https, function() {
console.log("\nNode.js listening on https port " + port_https);
});
} else {
http.listen(port_http, function() {
console.log("\nNode.js listening on http port " + port_http);
});
}
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
const strokeLifetime = 10000;
class Frame {
constructor() {
this.strokes = [];
}
}
class Layer {
constructor() {
this.frames = [];
}
getFrame(index) {
if (!this.frames[index]) {
//console.log("Client asked for frame " + index +", but it's missing.");
for (let i=0; i<index+1; i++) {
if (!this.frames[i]) {
let frame = new Frame();
this.frames.push(frame);
//console.log("* Created frame " + i + ".");
}
}
}
//console.log("Retrieving frame " + index + " of " + this.frames.length + ".");
return this.frames[index];
}
addStroke(data) {
try {
let index = data["index"];
if (!isNaN(index)) {
this.getFrame(index);
this.frames[index].strokes.push(data);
console.log("<<< Received a stroke with color (" + data["color"] + ") and " + data["points"].length + " points.");
}
} catch (e) {
console.log("Error adding stroke" + e.data);
}
}
}
let layer = new Layer();
setInterval(function() {
/*
let time = new Date().getTime();
for (let i=0; i<layer.frames.length; i++) {
for (let j=0; j<layer.frames[i].strokes.length; j++) {
if (time > layer.frames[i].strokes[j]["timestamp"] + strokeLifetime) {
layer.frames[i].strokes.splice(j, 1);
console.log("X Removing frame " + i + ", stroke " + j + ".");
}
}
}
*/
for (let i=0; i<layer.frames.length; i++) {
layer.frames[i].strokes.shift();
console.log("X Removing oldest stroke from frame " + i + ".");
}
}, strokeLifetime);
// ~ ~ ~ ~
let lastIndex = 0; // for ws
io.on("connection", function(socket) {
console.log("A socket.io user connected.");
//~
socket.on("disconnect", function(event) {
console.log("A socket.io user disconnected.");
});
//~
socket.on("clientStrokeToServer", function(data) {
//console.log(data);
try { // json coming from Unity needs to be parsed...
let newData = JSON.parse(data);
layer.addStroke(newData);
} catch (e) { // ...but json coming from JS client does not need to be
layer.addStroke(data);
}
});
//~
socket.on("clientRequestFrame", function(data) {
//console.log(data["num"]);
let index = data["num"];
if (index != NaN) {
lastIndex = index; // for ws
let frame = layer.getFrame(index);
if (frame && frame.strokes.length > 0) {
io.emit("newFrameFromServer", frame.strokes);
console.log("> > > Sending a new frame " + frame.strokes[0]["index"] + " with " + frame.strokes.length + " strokes.");
}
}
});
});
ws.on("connection", function(socket) {
console.log("A ws user connected.");
//~
socket.onclose = function(event) {
console.log("A ws user disconnected.");
};
//~
socket.onmessage = function(event) {
//console.log(data["num"]);
let index = lastIndex; //data["num"];
if (index != NaN) {
let frame = layer.getFrame(index);
if (frame && frame.strokes.length > 0) {
socket.send(JSON.stringify(frame.strokes));
console.log("> WS > Sending a new frame " + frame.strokes[0]["index"] + " with " + frame.strokes.length + " strokes.");
}
}
};
});