-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
202 lines (156 loc) · 6.64 KB
/
server.js
File metadata and controls
202 lines (156 loc) · 6.64 KB
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
// Base Requirements
import dotenv from "dotenv";
import fs from "fs";
import {getBaseURL, handleErrors} from "./utils.js";
// Server Requirements
import {SpotifyAPI} from "./spotifyAPI.js";
import express from "express";
import rateLimit from "express-rate-limit";
const limiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 50, // limit each IP to 50 requests per windowMs
message: "Too many requests from this IP, please try again later."
});
import cors from "cors";
// Websocket stuff
import http from "http";
import {WebSocketServer} from "ws";
// Widgets
import {listeningWidget} from "./widgets/listeningWidget.js";
// Plugins
import {PaintCanvas} from "./plugins/paintCanvas.js";
import {SOTD} from "./plugins/sotd.js";
dotenv.config();
// Constants
const BASE_URL = getBaseURL();
const app = express();
app.use(express.json());
app.use(limiter);
app.use(cors());
app.use((req, res, next) => {
console.log(`[${req.method}] [${new Date().toLocaleString("it")}] ${req.url}`)
next();
})
const server = http.createServer(app);
const wss = new WebSocketServer({server});
server.listen(process.env.PORT || 3000, () => console.log(`Server started on ${BASE_URL}\nAlternatively on http://localhost:${process.env.PORT || 3000}`));
const spotify = new SpotifyAPI();
// Main app Loop
setInterval(async () => {
if (!spotify.refreshToken) return console.log("There is no refresh token");
const newData = await spotify.getData();
if (newData?.status == 401) return console.log(`3. Error in refresh token: ${newData?.status}`, newData.response);
if (
(spotify?.data?.song_link != newData?.song_link) ||
(spotify?.data?.playing != newData?.playing) ||
(Math.abs(newData?.progress - spotify?.data?.progress) >= 15000)
) {
wss.clients.forEach(client => {
client.send(JSON.stringify({
data: newData,
type: "listening-status",
clients: wss.clients.size
}));
});
}
spotify.data = newData;
}, 5000);
let recentMessages = [];
let onCooldown = [];
wss.on("connection", ws => {
const data = {...spotify.data};
ws.send(JSON.stringify({data, clients: wss.clients.size, recentMessages, type: "init"}));
ws.on("message", (message) => {
console.log(`Received message from client: ${message}`);
try {
const received = JSON.parse(message);
if (onCooldown.includes(ws)) return;
onCooldown.push(ws);
setTimeout(() => onCooldown.splice(onCooldown.indexOf(ws), 1), 2500);
if (received.type == "chat") {
recentMessages.push({username: received.username, message: received.message});
setTimeout(() => recentMessages.shift(), 1000 * 60 * 60);
Array.from(wss.clients).forEach(client => {
client.send(JSON.stringify({
type: "chat",
clients: wss.clients.size,
data: {
...received.message
}
}));
});
}
} catch (err) {
console.error(err);
}
});
});
// app.get("/", (req, res) => handleErrors(res, 200, `You shouldn't be here... Please go to https://reloia.github.io/ or the api endpoint : ${BASE_URL}/api`));
app.get("/", (req, res) => res.send(fs.readFileSync("./static/index.html").toString()));
app.get("/privacy", (req, res) => res.send(fs.readFileSync("./static/privacy.html").toString()));
app.get("/terms", (req, res) => res.send(fs.readFileSync("./static/terms.html").toString()));
app.get("/api", async (_, res) => {
if (!spotify.accessToken) return handleErrors(res, 401, "Not logged in to Spotify or the Refresh Token has expired");
res.send(spotify.data);
});
app.get("/api/last", async (_, res) => {
if (!spotify.accessToken) return handleErrors(res, 401, "Not logged in to Spotify or the Refresh Token has expired");
res.send(await spotify.getLastSong())
});
app.get("/song-info", async (req, res) => {
if (!spotify.accessToken) return handleErrors(res, 401, "Not logged in to Spotify or the Refresh Token has expired");
if (!req.query.id) return handleErrors(res, 400, "Missing ID parameter");
if (req.headers.authorization !== process.env.SECRET) return handleErrors(res, 401, "Wrong code");
const song = await spotify.getSongData(req.query.id);
res.send(song);
});
app.get("/log-in", (req, res) => {
if (spotify.refreshToken) return handleErrors(res, 403, "Already logged in.");
res.redirect("https://accounts.spotify.com/authorize?" + (new URLSearchParams({
response_type: "code",
client_id: process.env.CLIENT_ID,
scope: "user-read-private user-read-email user-read-playback-state user-read-currently-playing user-read-recently-played user-top-read user-read-playback-position",
redirect_uri: `${BASE_URL}/callback`,
state: (`${Math.random().toString(36)}00000000000000000`).slice(2, 12 + 2),
})).toString());
});
app.get("/callback", async (req, res) => {
const code = req.query.code;
if (code) {
const resp = await fetch("https://accounts.spotify.com/api/token", {
method: "POST",
body: new URLSearchParams({
code,
redirect_uri: `${BASE_URL}/callback`,
grant_type: "authorization_code"
}),
headers: {Authorization: `Basic ${(Buffer.from(`${process.env.CLIENT_ID}:${process.env.CLIENT_SECRET}`)).toString("base64")}`,}
})
console.log(resp.status);
const text = await resp.text();
// const data = await resp.json();
const data = JSON.parse(text);
if (data.error) return handleErrors(res, 400, "The server has given the error: " + data.error_description);
spotify.accessToken = data.access_token;
spotify.refreshToken = data.refresh_token;
}
res.send('<a href="/">Goto home</a>');
});
// SOTD Stuff
const sotd = new SOTD(spotify);
app.get("/sotd", sotd.get);
app.post("/sotd/clear", sotd.clear);
app.post("/sotd/remove", sotd.remove);
app.post("/sotd/remove/date", sotd.removeFromDate);
app.post("/sotd/remove/url", sotd.removeFromUrl);
app.post("/sotd/url", sotd.url);
app.post("/sotd", sotd.post);
// PaintCanvas canvas
const paintCanvas = new PaintCanvas(wss);
app.get("/paintcanvas/status", paintCanvas.sendStatus);
/**
* PaintCanvas a pixel in the canvas with the specified color using the index calculated in the frontend.
*/
app.post("/paintcanvas", paintCanvas.post);
// Widgets
app.get('/widgets/listening', (req, res) => listeningWidget(req, res, spotify));