-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.mjs
100 lines (81 loc) · 2.3 KB
/
index.mjs
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
#!/usr/bin/env node
import { serializeError } from "serialize-error";
import http from "http";
import fs from "fs";
import bodyParser from "body-parser";
import EventEmitter from "events";
import express from "express";
import sockjs from "sockjs";
const [port = "9999"] = process.argv.slice(2);
const hasDisallowWsFlag = process.argv.includes("--disallowWs");
const app = express();
app.use((req, res, next) => {
if (req.url === "/listen") {
return;
}
next();
});
app.use(bodyParser.json());
app.options("*", (req, res) => {
res.setHeader(
`Access-Control-Allow-Origin`,
req.headers.origin || req.hostname || "*",
);
res.setHeader(
"Access-Control-Allow-Headers",
req.headers["access-control-request-headers"] || "*",
);
res.setHeader(`Access-Control-Allow-Methods`, `GET,POST,PUT,PATCH,DELETE`);
res.setHeader("Access-Control-Allow-Credentials", true);
res.sendStatus(200);
});
process.on("uncaughtException", (error) => {
console.error(error);
fs.writeFileSync("./error.txt", JSON.stringify(serializeError(error), null, 2));
process.exit(-1);
});
process.on("unhandledRejection", (error) => {
throw error;
});
const sockjsServer = sockjs.createServer();
const emitter = new EventEmitter();
{
const clients = [];
sockjsServer.on('connection', (conn) => {
clients.push(conn);
conn.on('close', () => {
const index = clients.indexOf(conn);
if (index !== -1) {
clients.splice(index, 1);
}
});
});
emitter.on('event', (data) => {
const chunk = JSON.stringify(data);
clients.forEach((client) => {
client.write(chunk);
});
});
}
app.post("/emit", (req, res) => {
const userId = req.header("x-appwrite-webhook-user-id");
const projectId = req.header("x-appwrite-webhook-project-id");
const events = req.header("x-appwrite-webhook-events");
const timestamp = Date.now();
const payload = req.body;
emitter.emit("event", {
userId,
projectId,
events,
timestamp,
payload,
});
res.status(200).send("ok");
});
const server = http
.createServer(app)
.listen(port, "0.0.0.0")
.addListener("listening", () => {
console.log(`Restream started: PORT=${port}`);
});
sockjsServer.installHandlers(server, { prefix: '/listen', websocket: !hasDisallowWsFlag });