67 lines
2.1 KiB
JavaScript
67 lines
2.1 KiB
JavaScript
require("dotenv").config();
|
|
const express = require("express");
|
|
const app = express();
|
|
const port = process.env.SERVER_PORT || 3000;
|
|
const sqlite3 = require("sqlite3").verbose();
|
|
const db = new sqlite3.Database("database.db");
|
|
db.on("open", () => {
|
|
db.run("CREATE TABLE IF NOT EXISTS playlists (id TEXT PRIMARY KEY, name TEXT, artist TEXT, image TEXT);");
|
|
db.run(`CREATE TABLE IF NOT EXISTS songs (
|
|
id INTEGER PRIMARY KEY,
|
|
assetid TEXT,
|
|
title TEXT,
|
|
artist TEXT,
|
|
image TEXT,
|
|
playlistId TEXT,
|
|
FOREIGN KEY(playlistId) REFERENCES playlists(id),
|
|
UNIQUE (assetid, playlistId) -- This ensures each assetid can only appear once per playlistId
|
|
);`);
|
|
const og = require("./bigone.json");
|
|
//db.run("INSERT INTO playlists VALUES (?, ?, ?, ?);", ["theone", og.metadata.title, og.metadata.artist, og.metadata.image]);
|
|
og.songs.forEach(song => {
|
|
//db.run("INSERT INTO songs (assetid, title, artist, image, playlistId) VALUES (?, ?, ?, ?, ?);", [song.assetid, song.title, song.artist, song.image, "theone"]);
|
|
})
|
|
});
|
|
|
|
function shuffle(array) {
|
|
let currentIndex = array.length;
|
|
|
|
// While there remain elements to shuffle...
|
|
while (currentIndex != 0) {
|
|
|
|
// Pick a remaining element...
|
|
let randomIndex = Math.floor(Math.random() * currentIndex);
|
|
currentIndex--;
|
|
|
|
// And swap it with the current element.
|
|
[array[currentIndex], array[randomIndex]] = [
|
|
array[randomIndex], array[currentIndex]];
|
|
}
|
|
}
|
|
app.get('/playlists/:playlistId', (req, res) => {
|
|
db.all("SELECT * FROM playlists WHERE id = ?;", [req.params.playlistId], (err, playlists) => {
|
|
if (err) {
|
|
res.status(500).send(err);
|
|
return;
|
|
}
|
|
if (playlists.length === 0) {
|
|
res.status(404).send("Playlist not found");
|
|
return;
|
|
}
|
|
db.all("SELECT * FROM songs WHERE playlistId = ?;", [req.params.playlistId], (err, songs) => {
|
|
if (err) {
|
|
res.status(500).send(err);
|
|
return;
|
|
}
|
|
if(req.query.shuffle) shuffle(songs);
|
|
res.json({
|
|
songs: songs,
|
|
metadata: playlists[0]
|
|
});
|
|
});
|
|
});
|
|
});
|
|
|
|
app.listen(port, () => {
|
|
console.log(`Server listening at http://localhost:${port}`);
|
|
}); |