enhancement(lint): Fix lint errors for hackclub-spotify-bot/src/spotify.js

Co-authored-by: NeonGamerBot-QK <saahilattud@gmail.com>
Signed-off-by: zeon-neon[bot] <136533918+zeon-neon[bot]@users.noreply.github.com>
This commit is contained in:
zeon-neon[bot] 2024-10-12 22:01:22 +00:00 committed by GitHub
parent 7499857a57
commit 0bf03719c2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,128 +1,131 @@
let token = null; let token = null;
let authStuff = null; let authStuff = null;
const client_id = process.env.SPOTIFY_CLIENT_ID; const client_id = process.env.SPOTIFY_CLIENT_ID;
const client_secret = process.env.SPOTIFY_CLIENT_SECRET; const client_secret = process.env.SPOTIFY_CLIENT_SECRET;
const redirect_uri = process.env.SPOTIFY_REDIRECT_URI; const redirect_uri = process.env.SPOTIFY_REDIRECT_URI;
async function fetchWebApi(endpoint, method, body) { async function fetchWebApi(endpoint, method, body) {
const res = await fetch(`https://api.spotify.com/${endpoint}`, { const res = await fetch(`https://api.spotify.com/${endpoint}`, {
headers: { headers: {
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
}, },
method, method,
body: JSON.stringify(body), body: JSON.stringify(body),
}); });
const text = await res.text(); const text = await res.text();
// console.debug(text) // console.debug(text)
// abs nothing is wrong // abs nothing is wrong
return JSON.parse(text.trim()); return JSON.parse(text.trim());
} }
function getLoginUrl() { function getLoginUrl() {
const state = generateRandomString(16); const state = generateRandomString(16);
const scope = [ const scope = [
// "ugc-image-upload", // "ugc-image-upload",
// "user-read-playback-state", // "user-read-playback-state",
// "user-modify-playback-state", // "user-modify-playback-state",
// "user-read-currently-playing", // "user-read-currently-playing",
// "app-remote-control", // "app-remote-control",
// "streaming", // "streaming",
"playlist-read-private", "playlist-read-private",
"playlist-read-collaborative", "playlist-read-collaborative",
"playlist-modify-private", "playlist-modify-private",
"playlist-modify-public", "playlist-modify-public",
// "user-follow-modify", // "user-follow-modify",
// "user-follow-read", // "user-follow-read",
// "user-read-playback-position", // "user-read-playback-position",
// "user-top-read", // "user-top-read",
// "user-read-recently-played", // "user-read-recently-played",
"user-library-modify", "user-library-modify",
// "user-library-read", // "user-library-read",
// "user-read-email", // "user-read-email",
"user-read-private", "user-read-private",
].join(" "); ].join(" ");
return ( return (
"https://accounts.spotify.com/authorize?" + "https://accounts.spotify.com/authorize?" +
`response_type=code&grant_type=client_credentials&client_id=${client_id}&scope=${scope}&redirect_uri=${redirect_uri}&state=${state}` `response_type=code&grant_type=client_credentials&client_id=${client_id}&scope=${scope}&redirect_uri=${redirect_uri}&state=${state}`
); );
}
function generateRandomString(length) {
let result = "";
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const charactersLength = characters.length;
let counter = 0;
while (counter < length) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
counter += 1;
} }
return result;
}
async function refreshToken(refresh_token) {
try {
// var refresh_token = req.query.refresh_token;
const authOptions = {
url: "https://accounts.spotify.com/api/token",
headers: {
"content-type": "application/x-www-form-urlencoded",
Authorization:
"Basic " +
new Buffer.from(client_id + ":" + client_secret).toString("base64"),
},
form: {
grant_type: "refresh_token",
refresh_token: refresh_token,
},
json: true,
};
const formdm = new URLSearchParams();
function generateRandomString(length) { formdm.append("grant_type", "refresh_token");
let result = ""; formdm.append("refresh_token", refresh_token);
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const charactersLength = characters.length;
let counter = 0;
while (counter < length) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
counter += 1;
}
return result;
}
async function refreshToken(refresh_token) {
try {
// var refresh_token = req.query.refresh_token;
const authOptions = {
url: "https://accounts.spotify.com/api/token",
headers: {
"content-type": "application/x-www-form-urlencoded",
Authorization:
"Basic " +
new Buffer.from(client_id + ":" + client_secret).toString("base64"),
},
form: {
grant_type: "refresh_token",
refresh_token: refresh_token,
},
json: true,
};
const formdm = new URLSearchParams();
formdm.append("grant_type", "refresh_token"); fetch(authOptions.url, {
formdm.append("refresh_token", refresh_token); body: formdm,
headers: authOptions.headers,
fetch(authOptions.url, { method: "POST",
body: formdm, })
headers: authOptions.headers, .then(async (r) => {
method: "POST", const text = await r.text();
// console.log(text);
return JSON.parse(text);
}) })
.then(async (r) => { .then((auth) => {
const text = await r.text(); if (!auth.refresh_token) auth.refresh_token = refresh_token;
// console.log(text); // console.log(auth);
return JSON.parse(text); authStuff = auth;
}) token = auth.access_token;
.then((auth) => { saveCredentials(auth);
if (!auth.refresh_token) auth.refresh_token = refresh_token; if (auth.expires_in) {
// console.log(auth); setTimeout(() => {
authStuff = auth; refreshToken(auth.refresh_token);
token = auth.access_token; }, auth.expires_in * 1000);
saveCredentials(auth); }
if (auth.expires_in) { });
setTimeout(() => { } catch (e) {
refreshToken(auth.refresh_token); console.error(`Welp it broke`);
}, auth.expires_in * 1000); // try again asap because we NEED THAT TOKEN
} refreshToken(refresh_token);
});
} catch (e) {
console.error(`Welp it broke`);
// try again asap because we NEED THAT TOKEN
refreshToken(refresh_token);
}
} }
}
function saveCredentials(creds) { function saveCredentials(creds) {
require('fs').writeFileSync('data/credentials.json', JSON.stringify(creds, null, 2)); require("fs").writeFileSync(
"data/credentials.json",
JSON.stringify(creds, null, 2),
);
} }
function getCredentials() { function getCredentials() {
try { try {
return JSON.parse(require('fs').readFileSync('data/credentials.json', 'utf8')); return JSON.parse(
} catch (e) { require("fs").readFileSync("data/credentials.json", "utf8"),
return null; );
} } catch (e) {
return null;
}
} }
function spotifyRoutes(app) { function spotifyRoutes(app) {
app.get('/spotify/callback', async (req,res) => { app.get("/spotify/callback", async (req, res) => {
const code = req.query.code || null; const code = req.query.code || null;
const state = req.query.state || null; const state = req.query.state || null;
@ -166,7 +169,7 @@ function spotifyRoutes(app) {
.then((auth) => { .then((auth) => {
// console.log(auth); // console.log(auth);
authStuff = auth; authStuff = auth;
saveCredentials(auth) saveCredentials(auth);
token = auth.access_token; token = auth.access_token;
if (auth.expires_in) { if (auth.expires_in) {
setTimeout(() => { setTimeout(() => {
@ -174,23 +177,23 @@ function spotifyRoutes(app) {
}, auth.expires_in * 1000); }, auth.expires_in * 1000);
} }
res.status(200).end("Successfully logged in!"); res.status(200).end("Successfully logged in!");
}) });
} }
}) });
} }
function addSongToPlaylist(url) { function addSongToPlaylist(url) {
fetchWebApi('v1/playlists/3gRv97fvllFFLVdCH6XzsE/tracks', 'POST', { fetchWebApi("v1/playlists/3gRv97fvllFFLVdCH6XzsE/tracks", "POST", {
uris: [url], uris: [url],
position: 0, position: 0,
}) });
} }
module.exports = { module.exports = {
getLoginUrl, getLoginUrl,
refreshToken, refreshToken,
saveCredentials, saveCredentials,
getCredentials, getCredentials,
spotifyRoutes, spotifyRoutes,
addSongToPlaylist addSongToPlaylist,
// getToken // getToken
} };