This repository has been archived by the owner on Oct 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
90 lines (78 loc) · 2.49 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
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
let app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// CORS
app.use((req, res, next) => {
res.set('Access-Control-Allow-Origin', '*');
next();
});
let connections = {};
app.get('/subscribe', (req, res) => {
if (!req.get("X-User-Claim")) {
res.sendStatus(401);
return;
}
try {
const user_claim = JSON.parse(req.get("X-User-Claim"));
if (!connections[user_claim.userid]) {
connections[user_claim.userid] = {};
}
console.log(`Someone subscribed to ${user_claim.userid}, ${user_claim.clientid}`);
connections[user_claim.userid][user_claim.clientid] = res;
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache'
});
// So the connection doesn't timeout and die
let timeoutID = 0;
const refresh = () => {
res.write(':\n\n');
timeoutID = setTimeout(refresh, 25000);
};
refresh();
res.on('close', () => {
connections[user_claim.userid][user_claim.clientid] = null;
clearTimeout(timeoutID);
});
} catch(e) {
res.sendStatus(401)
}
});
app.get('/user/:user/devices', (req, res) => {
if (!connections[req.params.user]) {
res.status(200).json([]);
} else {
res.status(200).json(Object.keys(connections[req.params.user]));
}
});
app.post('/user/:user/device/:device', (req, res) => {
if(!connections[req.params.user]){
res.sendStatus(404);
} else if (!connections[req.params.user][req.params.device]){
res.sendStatus(404);
} else if (!req.body.data) {
res.sendStatus(400);
} else {
try {
const user_claim = JSON.parse(req.get("X-User-Claim"));
if(!(user_claim.userid && user_claim.clientid)) {
res.sendStatus(401);
} else {
console.log('Posting:');
req.body.id = `${user_claim.userid}:${user_claim.clientid}`
console.log(`id: ${req.body.id}\nevent: ${req.body.event}\ndata: ${encodeURI(req.body.data)}\n\n`);
console.log(`To ${req.params.user}, ${req.params.device}`);
connections[req.params.user][req.params.device].write(`id: ${req.body.id}\nevent: ${req.body.event}\ndata: ${encodeURI(req.body.data)}\n\n`);
res.sendStatus(200);
}
} catch(e) {
res.sendStatus(401);
}
}
});
app.listen(process.env.PORT, (err) => {
err ? console.error(err) : console.log(`Listening on port ${process.env.PORT}`);
});