From 7c3a3d1fa72051282cb290111a644ce20b80dada Mon Sep 17 00:00:00 2001 From: bingus_violet Date: Sat, 8 Jun 2024 19:14:16 -0500 Subject: [PATCH] SpotifyDownloader --- .gitignore | 3 ++- defaults/config.json | 5 +++++ index.js | 25 ++++++++++++++++++++++++- 3 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 defaults/config.json diff --git a/.gitignore b/.gitignore index 48cd5ad..9fe195d 100644 --- a/.gitignore +++ b/.gitignore @@ -131,4 +131,5 @@ dist .pnp.* cache -/cache.json \ No newline at end of file +/cache.json +/config.json \ No newline at end of file diff --git a/defaults/config.json b/defaults/config.json new file mode 100644 index 0000000..005c091 --- /dev/null +++ b/defaults/config.json @@ -0,0 +1,5 @@ +{ + "Spotify": { + "client_secret": "" + } +} \ No newline at end of file diff --git a/index.js b/index.js index b6fcc5e..c3b3c34 100644 --- a/index.js +++ b/index.js @@ -6,12 +6,14 @@ WebSocket = require('ws') const PORT = process.env.PORT || 8080 const cachePath = path.join(__dirname, "cache"), -cacheFile = path.join(__dirname, "cache.json") +cacheFile = path.join(__dirname, "cache.json"), +configFile = path.join(__dirname, "config.json") if (!fs.existsSync(cachePath)) { fs.mkdirSync(cachePath) } if (!fs.existsSync(cacheFile) || !JSON.parse(fs.readFileSync(cacheFile)).songs) { fs.writeFileSync(cacheFile, fs.readFileSync(path.join(__dirname, "defaults/cache.json"))) } +if (!fs.existsSync(configFile)) { fs.writeFileSync(configFile, fs.readFileSync(path.join(__dirname, "defaults/config.json")))} var cacheDirs = ["songs", "imgs"] for (var i = 0; i < cacheDirs.length; i++) { @@ -20,6 +22,14 @@ for (var i = 0; i < cacheDirs.length; i++) { } } +var conf = JSON.parse(fs.readFileSync(path.join(__dirname, "config.json"))) + +const Spotify = require("spotifydl-core").default +const spotifydl = new Spotify({ + clientId: "5420a0e8fae24101ac6ad57278bde694", + clientSecret: conf.Spotify.client_secret +}) + const songCache = path.join(cachePath, "songs"), imgCache = path.join(cachePath, "imgs") @@ -27,6 +37,8 @@ var app = express() const imgWaitMax = 2 +app.use("/songs", express.static(songCache)) + app.get("/cached/*", (req, res) => { var imgURL = req.originalUrl imgURL = imgURL.substring(imgURL.indexOf("/", 2) + 1) @@ -130,6 +142,17 @@ function socketeer() { } else if (data.op == 0) { var lanyardData = data.d + var spotify = lanyardData.spotify + + if (conf.Spotify.client_secret && spotify) { + var trackURL = "https://open.spotify.com/track/" + spotify.track_id + + var songPath = path.join(cachePath, "/songs/", spotify.track_id + ".mp3") + if (!fs.existsSync(songPath)) { + await spotifydl.downloadTrack(trackURL, songPath) + } + } + for (let index = 0; index < lanyardData.activities.length; index++) { const activity = lanyardData.activities[index];