-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
461 lines (386 loc) · 14.6 KB
/
server.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
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
// ---------------------------------------------
// Hey! Welcome to the backend code of Syncify!
// Unless you're an advanced user, you probably shouldn't mess with anything below.
// If you do though, consider forking the repo and contributing!
// ---------------------------------------------
import express from "express";
import path from "path";
import { fileURLToPath } from "url";
import dotenv from "dotenv";
import { existsSync, writeFileSync, readFileSync, writeFile, unlink } from "fs";
import utils from "./src/utils/utils.js";
import spotifyapi from "./src/utils/spotifyapi.js";
import { URLSearchParams } from "url";
const red = "\x1b[31m";
const green = "\x1b[32m";
const yellow = "\x1b[33m";
const reset = "\x1b[0m";
// Load config
if (!existsSync("./config.env")) {
unlink("tokens.json", (err) => {
// Delete tokens.json as they're likely not usable anymore.
if (err) {
console.error(`${red}Failed to delete tokens.json: `, err, reset);
return;
}
});
try {
const defaultConfig = [
"# Populate this file with your API credentials and preferences",
"CLIENT_ID=your-client-id-here",
"CLIENT_SECRET=your-client-secret-here",
"PORT=8888",
"THEME=Default",
"VERBOSITY=2",
].join("\n");
// Create a config file if one does not exist
writeFileSync("./config.env", defaultConfig, { encoding: "utf8" });
console.warn(
`${yellow}Config.env was not found, and one has been created. Please populate the file with your configuration, then restart Syncify.`,
reset
);
} catch (err) {
console.error(
`${red}Config.env was not found, and one could not be created.\n`,
err,
`\n${yellow}Tip:${reset} Please ensure Syncify is in a location with write permissions.`
);
}
process.exit(1);
} else {
try {
// Load environment variables from config.env
dotenv.config({ path: "./config.env" });
// Validate to ensure config.env has a proper config
const validConf = utils.ValidateConfig(process.env);
if (validConf != "") {
console.error(
`${red}Error starting Syncify: Config.env could not be validated. `,
validConf,
reset
);
process.exit(1);
}
} catch (ex) {
console.error(
`${red}Error starting Syncify: Config.env could not be loaded. The file may be corrupted.`,
"\nIn case you'd like to attempt to repair your config file, Syncify has left the file untouched.",
"\nIf you cannot repair the file, please delete it and reobtain your API credentials at https://developer.spotify.com/dashboard.",
"\n----\nTechnical mumbo jumbo:\n",
ex.message,
reset
);
process.exit(1);
}
}
const app = express();
const port = process.env.PORT || 8888;
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const verbosity = process.env.VERBOSITY;
// Var for if polling has started for the currently playing song
var intervalStarted = false;
// Var for if the current song has been set manually via the setsong API endpoint
var manualSong = false;
// Var for if the play status has been set manually via the setplaystatus API endpoint
var manualPlayStatus = false;
// Var that houses the info for the currently playing song
var currentSong = {
playing: false,
stopped: true,
song: "",
artists: [{ name: "" }],
firstArtist: "",
coverArtUrl: "",
};
if (!existsSync("./dist")) {
console.error(
`${red}Failed to start Syncify. The build files have not been created. Please open Build.bat or run "npm run build" before starting Syncify.`,
reset
);
process.exit(1);
}
var lastSong = currentSong;
// Spotify API vars
const REDIRECT_URI = `http://localhost:${port}/callback`;
const SCOPE = "user-read-currently-playing";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
async function StartInterval() {
if (!intervalStarted) {
setInterval(() => {
spotifyapi
.GetCurrentlyPlaying(path.resolve(__dirname, "./tokens.json"))
.then((data) => {
// If a manual song or manual play status is set and there is not a new Spotify song
if ((manualSong == true || manualPlayStatus == true) && data.song == lastSong.song && data.artists[0].name == lastSong.artists[0].name) {
// Set the playing status if it doesn't match the last song's playing status
// i.e. Replace the playing status after the manual play status has been set at least once
if (data.playing != lastSong.playing) {
manualPlayStatus = false;
currentSong.playing = data.playing;
}
return;
}
currentSong = data;
if (currentSong.song != lastSong.song && currentSong.artists[0].name != lastSong.artists[0].name) { // If the current song does not match the last song...
lastSong = currentSong;
manualSong = false;
manualPlayStatus = false;
if (!currentSong.stopped && verbosity >= 3) {
console.log(
`${green}New song:${reset} ${currentSong.artists[0].name} - ${currentSong.song}`
);
}
// If the song wasn't changed, but the last song doesn't match the playing status of the current
} else if (lastSong.playing != currentSong.playing) {
// This is purely for the setplaystatus endpoint.
lastSong.playing = currentSong.playing;
}
});
}, 1000);
intervalStarted = true;
}
}
// Serve static files from the Vite build output directory
app.use(express.static(path.join(__dirname, "dist")));
// Login to na Spotify
app.get("/login", (req, res) => {
const params = new URLSearchParams({
response_type: "code",
client_id: CLIENT_ID,
scope: SCOPE,
redirect_uri: REDIRECT_URI,
}).toString();
res.redirect("https://accounts.spotify.com/authorize?" + params);
});
// Callback for Spotify login
app.get("/callback", async (req, res) => {
const code = req.query.code || null;
try {
const tokenData = await spotifyapi.GetTokens(code);
const jsonString = JSON.stringify(tokenData, null, 2); // Adding indentation for readability
writeFile("tokens.json", jsonString, (err) => {
if (err) {
console.error(`${red}Error writing tokens.json: `, err, reset);
} else {
if (verbosity >= 3) console.log(`${green}tokens.json successfully saved.`, reset);
}
});
// Start polling for currently playing song
StartInterval();
if (verbosity >= 3) console.log(`${green}Successfully authenticated with Spotify!`, reset);
res.send("Successfully authenticated! You can close this window.");
} catch (error) {
if (verbosity >= 1)
console.error(`${red}Error getting access token:`, error.response.data, reset);
res.send(
"Error getting access token. Check Syncify console for more info."
);
}
});
// API endpoint to get configuration
app.get("/api/config", (req, res) => {
const config = {
CLIENT_ID: process.env.CLIENT_ID,
CLIENT_SECRET: process.env.CLIENT_SECRET,
PORT: process.env.PORT || 8888,
THEME: process.env.THEME || "default",
VERBOSITY: process.env.VERBOSITY,
};
res.json(config);
});
// API endpoint to get the current playing song
app.get("/api/getsong", (req, res) => {
res.setHeader("Connection", "close");
res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
res.setHeader("Content-Type", "application/json");
try {
res.json(currentSong);
} catch (error) {
console.error(`${red}Server error:`, error, reset);
res.status(500).json({ error: "Internal server error" });
}
});
// For POST requests
app.use(express.json());
// API endpoint to set the currently playing song
app.post('/api/setsong', (req, res) => {
try {
const data = req.body;
if (verbosity >= 3) console.log("Set song received:", data);
// Check if request is valid
if (!data?.hasOwnProperty("playing")) {
if (verbosity >= 3) console.log("Set song was denied: No playing status");
res.status(422).json({
message: "Syncify: Set song denied",
details: "No playing status",
});
return;
} else if (!data?.hasOwnProperty("stopped")) {
if (verbosity >= 3) console.log("Set song was denied: No stopped status");
res.status(422).json({
message: "Syncify: Set song denied",
details: "No stopped status",
});
return;
} else if (!data?.hasOwnProperty("song")) {
if (verbosity >= 3) console.log("Set song was denied: No song title");
res.status(422).json({
message: "Syncify: Set song denied",
details: "No song title",
});
return;
} else if (!data?.hasOwnProperty("artists")) {
if (verbosity >= 3) console.log("Set song was denied: No artists array");
res.status(422).json({
message: "Syncify: Set song denied",
details: "No artists array",
});
return;
} else if (!data?.hasOwnProperty("firstArtist")) {
if (verbosity >= 3) console.log("Set song was denied: No first artist");
res.status(422).json({
message: "Syncify: Set song denied",
details: "No first artist",
});
return;
} else if (!data?.hasOwnProperty("coverArtUrl")) {
if (verbosity >= 3) console.log("Set song was denied: No cover art URL");
res.status(422).json({
message: "Syncify: Set song denied",
details: "No cover art URL",
});
return;
}
if (data?.hasOwnProperty("artists")) {
data.artists.forEach((artist) => {
if (!artist?.hasOwnProperty("name")) {
if (verbosity >= 3) console.log("Set song was denied: No artists name for one or more artists");
res.status(422).json({
message: "Syncify: Set song denied",
details: "No artist name for one or more artists",
});
return;
}
});
}
manualSong = true;
currentSong = data;
if (verbosity >= 3) {
console.log(
`${green}New song (manual):${reset} ${currentSong.artists[0].name} - ${currentSong.song} ${data.stopped ? "(stopped)" : data.playing ? "" : "(paused)"}`
);
}
res.status(200).json({
message: 'Syncify: Set song received successfully',
receivedData: data
});
} catch (error) {
if (verbosity >= 1) console.log(`${red}ERROR:${reset} Syncify received a set song command but failed to handle it.`);
if (verbosity >= 3) console.log(error.message);
res.status(400).json({
error: 'Syncify: Failed to process set song request',
details: 'Internal server error'
});
}
});
// API endpoint to modify the currently playing song's playing status
app.post("/api/setplaystatus", (req, res) => {
try {
const data = req.body;
if (verbosity >= 3) console.log("Set play status received:", data);
// Check if request is valid
if (!data?.hasOwnProperty("playing")) {
if (verbosity >= 3) console.log("Set play status was denied: No playing status");
res.status(422).json({
message: "Syncify: Set song denied",
details: "No playing status",
});
return;
} else if (!data?.hasOwnProperty("stopped")) {
if (verbosity >= 3) console.log("Set play status was denied: No stopped status");
res.status(422).json({
message: "Syncify: Set song denied",
details: "No stopped status",
});
return;
}
manualPlayStatus = true;
currentSong.playing = data.playing;
currentSong.stopped = data.stopped;
if (verbosity >= 3) {
console.log(
`${green}New manual play status: Playing: ${data.playing} Stopped: ${data.stopped}`
);
}
res.status(200).json({
message: "Syncify: Set play status received successfully",
receivedData: data,
});
} catch (error) {
if (verbosity >= 1)
console.log(
`${red}ERROR:${reset} Syncify received a set play status command but failed to handle it.`
);
if (verbosity >= 3) console.log(error.message);
res.status(400).json({
error: "Syncify: Failed to process set play status request",
details: "Internal server error",
});
}
});
// catch-all request for queries that don't match one above
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "dist", "index.html"));
});
async function LoadToken() {
try {
const data = JSON.parse(readFileSync("./tokens.json"));
await spotifyapi.EnsureValidToken(
data,
path.resolve(__dirname, "./tokens.json")
);
// Start polling for currently playing song
StartInterval();
} catch (err) {
if (verbosity >= 1) console.error(`${red}Failed to read from tokens.json: `, err, reset);
process.exit();
}
}
app.listen(port, async () => {
// Load environment variables for the Spotify API script
await spotifyapi.SetConfig(port, CLIENT_ID, CLIENT_SECRET, verbosity);
try {
const updates = utils.CheckGitRepoUpdates(__dirname);
if (updates.hasUpdates && verbosity >= 2) {
console.log(`${yellow}Syncify Update available! Your repository is ${updates.commitsBehinds} commit(s) behind.`, reset);
console.log('Latest change:', yellow, updates.latestCommitMessage, reset);
console.log('Open update.bat or run "git pull" to update.');
} else if (verbosity >= 2) {
console.log(`${green}Syncify is up-to-date!`, reset);
}
} catch (error) {
if (verbosity >= 1)console.error('Failed to check for updates:', error.message);
}
if (verbosity >= 3) console.log(
`\n----------\n${yellow}WARN:${reset} You are currently running Syncify with a verbosity level of ${verbosity}.\n` +
"For content creators, it is recommended to keep your verbosity level (set in config.env) lower than 3, as levels of 3 or higher may output sensitive information to the console.\n" +
"This functionality is intentional for debugging purposes.\n" +
`${yellow}If you are streaming, ${red}PLEASE SET YOUR VERBOSITY TO LESS THAN 3!` +
reset +
"\n----------\n"
);
if (verbosity >= 1) console.log(`${green}Server running at http://localhost:${port}`, reset);
// Simple message for those with a verbosity level of 0.
if (verbosity == 0) console.log(`${green}Syncify is running.`, reset);
if (verbosity >= 3) console.log(`Theme to serve is ${yellow}${process.env.THEME}${reset}. If another theme is being served, remember to open build.bat or run "npm run build" in the root folder.`);
if (!existsSync("tokens.json")) {
console.log(
`${yellow}Please visit http://localhost:${port}/login to authenticate with Spotify`,
reset
);
} else {
LoadToken();
}
});