-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
74 lines (60 loc) · 1.6 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
const express = require("express");
const bodyParser = require("body-parser");
const WebSocket = require("express-ws");
const cors = require("cors");
const { dispatchMetaInformation } = require("./src/http");
const { writeToBucket } = require("./src/s3");
const PORT = process.env.PORT || 3031;
const MUSIC_API_PASSWORD = process.env.MUSIC_API_PASSWORD;
let currentSong = "";
let sendToSocket = () => {};
const app = express();
const expressWs = WebSocket(app);
const wss = expressWs.getWss("/");
app.use(cors());
app.use(
bodyParser.json({
type: ["application/json", "text/plain"] // for getting past Heroku CORS block
})
);
app.post("/newsong", (req, res) => {
// TODO: password should not be in body
const { song, password } = req.body;
if (!song || typeof song !== "string") {
return res.sendStatus(400); // 400 Bad Request
}
if (password !== MUSIC_API_PASSWORD) {
return res.sendStatus(403); // 403 Forbidden
}
console.log(`Received new song: ${song}`);
currentSong = song;
sendToSocket(song);
res.sendStatus(200);
});
sendToSocket = song => {
if (song !== "") {
dispatchMetaInformation(song);
writeToBucket(song);
wss.clients.forEach(client => {
client.send(song);
});
}
};
app.ws("/", client => {
client.on("message", message => {
if (message !== "PONG") {
console.log("received: %s", message);
}
});
if (currentSong !== "") {
client.send(currentSong);
}
});
setInterval(() => {
wss.clients.forEach(client => {
client.send("PING");
});
}, 1000);
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});