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,196 +1,199 @@
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) {
function generateRandomString(length) { let result = "";
let result = ""; const characters =
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; const charactersLength = characters.length;
const charactersLength = characters.length; let counter = 0;
let counter = 0; while (counter < length) {
while (counter < length) { result += characters.charAt(Math.floor(Math.random() * charactersLength));
result += characters.charAt(Math.floor(Math.random() * charactersLength)); counter += 1;
counter += 1; }
} return result;
return result; }
} async function refreshToken(refresh_token) {
async function refreshToken(refresh_token) { try {
try { // var refresh_token = req.query.refresh_token;
// var refresh_token = req.query.refresh_token; const authOptions = {
const authOptions = { url: "https://accounts.spotify.com/api/token",
url: "https://accounts.spotify.com/api/token", headers: {
headers: { "content-type": "application/x-www-form-urlencoded",
"content-type": "application/x-www-form-urlencoded", Authorization:
Authorization: "Basic " +
"Basic " + new Buffer.from(client_id + ":" + client_secret).toString("base64"),
new Buffer.from(client_id + ":" + client_secret).toString("base64"), },
}, form: {
form: { grant_type: "refresh_token",
grant_type: "refresh_token", refresh_token: refresh_token,
refresh_token: refresh_token, },
}, json: true,
json: true, };
}; const formdm = new URLSearchParams();
const formdm = new URLSearchParams();
formdm.append("grant_type", "refresh_token");
formdm.append("grant_type", "refresh_token"); formdm.append("refresh_token", refresh_token);
formdm.append("refresh_token", refresh_token);
fetch(authOptions.url, {
fetch(authOptions.url, { body: formdm,
body: formdm, headers: authOptions.headers,
headers: authOptions.headers, method: "POST",
method: "POST", })
}) .then(async (r) => {
.then(async (r) => { const text = await r.text();
const text = await r.text(); // console.log(text);
// console.log(text); return JSON.parse(text);
return JSON.parse(text); })
}) .then((auth) => {
.then((auth) => { if (!auth.refresh_token) auth.refresh_token = refresh_token;
if (!auth.refresh_token) auth.refresh_token = refresh_token; // console.log(auth);
// console.log(auth); authStuff = auth;
authStuff = auth; token = auth.access_token;
token = auth.access_token; saveCredentials(auth);
saveCredentials(auth); if (auth.expires_in) {
if (auth.expires_in) { setTimeout(() => {
setTimeout(() => { refreshToken(auth.refresh_token);
refreshToken(auth.refresh_token); }, auth.expires_in * 1000);
}, auth.expires_in * 1000); }
} });
}); } catch (e) {
} catch (e) { console.error(`Welp it broke`);
console.error(`Welp it broke`); // try again asap because we NEED THAT TOKEN
// try again asap because we NEED THAT TOKEN refreshToken(refresh_token);
refreshToken(refresh_token); }
} }
} function saveCredentials(creds) {
function saveCredentials(creds) { require("fs").writeFileSync(
require('fs').writeFileSync('data/credentials.json', JSON.stringify(creds, null, 2)); "data/credentials.json",
} JSON.stringify(creds, null, 2),
function getCredentials() { );
try { }
return JSON.parse(require('fs').readFileSync('data/credentials.json', 'utf8')); function getCredentials() {
} catch (e) { try {
return null; return JSON.parse(
} require("fs").readFileSync("data/credentials.json", "utf8"),
);
} } catch (e) {
function spotifyRoutes(app) { return null;
app.get('/spotify/callback', async (req,res) => { }
const code = req.query.code || null; }
const state = req.query.state || null; function spotifyRoutes(app) {
app.get("/spotify/callback", async (req, res) => {
if (state === null) { const code = req.query.code || null;
res.redirect( const state = req.query.state || null;
"/#" +
querystring.stringify({ if (state === null) {
error: "state_mismatch", res.redirect(
}), "/#" +
); querystring.stringify({
} else { error: "state_mismatch",
const authOptions = { }),
url: "https://accounts.spotify.com/api/token", );
form: { } else {
code: code, const authOptions = {
redirect_uri: redirect_uri, url: "https://accounts.spotify.com/api/token",
grant_type: "authorization_code", form: {
}, code: code,
headers: { redirect_uri: redirect_uri,
"content-type": "application/x-www-form-urlencoded", grant_type: "authorization_code",
Authorization: },
"Basic " + headers: {
new Buffer.from(client_id + ":" + client_secret).toString("base64"), "content-type": "application/x-www-form-urlencoded",
}, Authorization:
json: true, "Basic " +
}; new Buffer.from(client_id + ":" + client_secret).toString("base64"),
const formdm = new URLSearchParams(); },
// Object.entries(authOptions.form).forEach(([key, value]) => { json: true,
// formdm.append(key, value); };
// }) const formdm = new URLSearchParams();
formdm.append("code", code); // Object.entries(authOptions.form).forEach(([key, value]) => {
formdm.append("redirect_uri", redirect_uri); // formdm.append(key, value);
formdm.append("grant_type", "authorization_code"); // })
formdm.append("code", code);
fetch(authOptions.url, { formdm.append("redirect_uri", redirect_uri);
body: formdm, formdm.append("grant_type", "authorization_code");
headers: authOptions.headers,
method: "POST", fetch(authOptions.url, {
}) body: formdm,
.then((r) => r.json()) headers: authOptions.headers,
.then((auth) => { method: "POST",
// console.log(auth); })
authStuff = auth; .then((r) => r.json())
saveCredentials(auth) .then((auth) => {
token = auth.access_token; // console.log(auth);
if (auth.expires_in) { authStuff = auth;
setTimeout(() => { saveCredentials(auth);
refreshToken(auth.refresh_token); token = auth.access_token;
}, auth.expires_in * 1000); if (auth.expires_in) {
} setTimeout(() => {
res.status(200).end("Successfully logged in!"); refreshToken(auth.refresh_token);
}) }, auth.expires_in * 1000);
} }
}) res.status(200).end("Successfully logged in!");
} });
function addSongToPlaylist(url) { }
fetchWebApi('v1/playlists/3gRv97fvllFFLVdCH6XzsE/tracks', 'POST', { });
uris: [url], }
position: 0, function addSongToPlaylist(url) {
}) fetchWebApi("v1/playlists/3gRv97fvllFFLVdCH6XzsE/tracks", "POST", {
} uris: [url],
module.exports = { position: 0,
getLoginUrl, });
refreshToken, }
saveCredentials, module.exports = {
getCredentials, getLoginUrl,
spotifyRoutes, refreshToken,
addSongToPlaylist saveCredentials,
getCredentials,
// getToken spotifyRoutes,
} addSongToPlaylist,
// getToken
};