-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
71 lines (58 loc) · 1.78 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
require('dotenv').config();
const express = require("express");
const axios = require("axios");
const fs = require("fs");
const app = express();
app.use(express.json());
app.use(express.static(__dirname + "/assets"));
const index = fs.readFileSync("./pages/index.html");
app.get("/", async (req, res) => {
return res.status(200).send(index.toString("utf-8"));
});
const chat = fs.readFileSync("./pages/chat-only.html");
app.get("/chat-only", async (req, res) => {
return res.status(200).send(chat.toString("utf-8"));
});
const alerts = fs.readFileSync("./pages/alerts-only.html");
app.get("/alerts-only", async (req, res) => {
return res.status(200).send(alerts.toString("utf-8"));
});
const evtClients = {};
app.get("/events", async (req, res) => {
console.log("New connection request received");
let clientId = req.query.client_id;
evtClients[clientId] = res;
res.socket.on("end", (_) => {
delete evtClients[clientId];
res.end();
});
res.setHeader("Content-Type", "text/event-stream");
res.write(`event: connect\n`);
res.write(`data: Connection established.\n\n`);
});
async function getToken() {
var query =
`client_id=${process.env.CLIENT_ID}` +
`&client_secret=${process.env.CLIENT_SECRET}` +
`&grant_type=client_credentials`;
try {
var req = await axios.post(`https://id.twitch.tv/oauth2/token?${query}`);
var data = req.data;
} catch (e) {
console.log(e.config, e.message);
}
return data.access_token;
}
async function setup() {
const TOKEN = await getToken();
var files = fs.readdirSync(__dirname + "/handlers");
for (var f of files) {
var fn = `${__dirname}/handlers/${f}`;
var handler = require(fn);
await handler(app, evtClients, TOKEN);
}
}
setup();
const PORT = process.env.PORT ?? 8080;
app.listen(PORT);
console.log(`App listening on port ${PORT}`);