mirror of
https://github.com/20kaushik02/spotify-manager.git
synced 2026-01-25 06:04:05 +00:00
back
small improvements, bug fixes, ocd formatting,
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
const { authInstance } = require("../api/axios");
|
||||
|
||||
const typedefs = require("../typedefs");
|
||||
const { scopes, stateKey, accountsAPIURL, sessionName } = require('../constants');
|
||||
const { scopes, stateKey, accountsAPIURL, sessionName } = require("../constants");
|
||||
|
||||
const generateRandString = require('../utils/generateRandString');
|
||||
const generateRandString = require("../utils/generateRandString");
|
||||
const { getUserProfile } = require("../api/spotify");
|
||||
const logger = require('../utils/logger')(module);
|
||||
const logger = require("../utils/logger")(module);
|
||||
|
||||
/**
|
||||
* Stateful redirect to Spotify login with credentials
|
||||
@@ -17,11 +17,11 @@ const login = (_req, res) => {
|
||||
const state = generateRandString(16);
|
||||
res.cookie(stateKey, state);
|
||||
|
||||
const scope = Object.values(scopes).join(' ');
|
||||
const scope = Object.values(scopes).join(" ");
|
||||
res.redirect(
|
||||
`${accountsAPIURL}/authorize?` +
|
||||
new URLSearchParams({
|
||||
response_type: 'code',
|
||||
response_type: "code",
|
||||
client_id: process.env.CLIENT_ID,
|
||||
scope: scope,
|
||||
redirect_uri: process.env.REDIRECT_URI,
|
||||
@@ -31,7 +31,7 @@ const login = (_req, res) => {
|
||||
return;
|
||||
} catch (error) {
|
||||
res.sendStatus(500);
|
||||
logger.error('login', { error });
|
||||
logger.error("login", { error });
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -48,12 +48,12 @@ const callback = async (req, res) => {
|
||||
|
||||
// check state
|
||||
if (state === null || state !== storedState) {
|
||||
res.redirect(409, '/');
|
||||
logger.error('state mismatch');
|
||||
res.redirect(409, "/");
|
||||
logger.error("state mismatch");
|
||||
return;
|
||||
} else if (error) {
|
||||
res.status(401).send("Auth callback error");
|
||||
logger.error('callback error', { error });
|
||||
logger.error("callback error", { error });
|
||||
return;
|
||||
} else {
|
||||
// get auth tokens
|
||||
@@ -62,21 +62,21 @@ const callback = async (req, res) => {
|
||||
const authForm = {
|
||||
code: code,
|
||||
redirect_uri: process.env.REDIRECT_URI,
|
||||
grant_type: 'authorization_code'
|
||||
grant_type: "authorization_code"
|
||||
}
|
||||
|
||||
const authPayload = (new URLSearchParams(authForm)).toString();
|
||||
|
||||
const tokenResponse = await authInstance.post('/api/token', authPayload);
|
||||
const tokenResponse = await authInstance.post("/api/token", authPayload);
|
||||
|
||||
if (tokenResponse.status === 200) {
|
||||
logger.debug('Tokens obtained.');
|
||||
logger.debug("Tokens obtained.");
|
||||
req.session.accessToken = tokenResponse.data.access_token;
|
||||
req.session.refreshToken = tokenResponse.data.refresh_token;
|
||||
req.session.cookie.maxAge = 7 * 24 * 60 * 60 * 1000 // 1 week
|
||||
} else {
|
||||
logger.error('login failed', { statusCode: tokenResponse.status });
|
||||
res.status(tokenResponse.status).send('Error: Login failed');
|
||||
logger.error("login failed", { statusCode: tokenResponse.status });
|
||||
res.status(tokenResponse.status).send("Error: Login failed");
|
||||
}
|
||||
|
||||
const userData = await getUserProfile(req, res);
|
||||
@@ -94,7 +94,7 @@ const callback = async (req, res) => {
|
||||
}
|
||||
} catch (error) {
|
||||
res.sendStatus(500);
|
||||
logger.error('callback', { error });
|
||||
logger.error("callback", { error });
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -108,28 +108,28 @@ const refresh = async (req, res) => {
|
||||
try {
|
||||
const authForm = {
|
||||
refresh_token: req.session.refreshToken,
|
||||
grant_type: 'refresh_token',
|
||||
grant_type: "refresh_token",
|
||||
}
|
||||
|
||||
const authPayload = (new URLSearchParams(authForm)).toString();
|
||||
|
||||
const response = await authInstance.post('/api/token', authPayload);
|
||||
const response = await authInstance.post("/api/token", authPayload);
|
||||
|
||||
if (response.status === 200) {
|
||||
req.session.accessToken = response.data.access_token;
|
||||
req.session.refreshToken = response.data.refresh_token ?? req.session.refreshToken; // refresh token rotation
|
||||
|
||||
res.sendStatus(200);
|
||||
logger.info(`Access token refreshed${(response.data.refresh_token !== null) ? ' and refresh token updated' : ''}.`);
|
||||
logger.info(`Access token refreshed${(response.data.refresh_token !== null) ? " and refresh token updated" : ""}.`);
|
||||
return;
|
||||
} else {
|
||||
res.status(response.status).send('Error: Refresh token flow failed.');
|
||||
logger.error('refresh failed', { statusCode: response.status });
|
||||
res.status(response.status).send("Error: Refresh token flow failed.");
|
||||
logger.error("refresh failed", { statusCode: response.status });
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
res.sendStatus(500);
|
||||
logger.error('refresh', { error });
|
||||
logger.error("refresh", { error });
|
||||
return;
|
||||
}
|
||||
};
|
||||
@@ -155,7 +155,7 @@ const logout = async (req, res) => {
|
||||
})
|
||||
} catch (error) {
|
||||
res.sendStatus(500);
|
||||
logger.error('logout', { error });
|
||||
logger.error("logout", { error });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
const typedefs = require("../typedefs");
|
||||
const logger = require("../utils/logger")(module);
|
||||
|
||||
const { getUserPlaylistsFirstPage, getUserPlaylistsNextPage, getPlaylistDetailsFirstPage, getPlaylistDetailsNextPage, removeItemsFromPlaylist } = require("../api/spotify");
|
||||
const { getUserPlaylistsFirstPage, getUserPlaylistsNextPage, getPlaylistDetailsFirstPage, getPlaylistDetailsNextPage, addItemsToPlaylist, removeItemsFromPlaylist, checkPlaylistEditable } = require("../api/spotify");
|
||||
const { parseSpotifyLink } = require("../utils/spotifyURITransformer");
|
||||
const myGraph = require("../utils/graph");
|
||||
|
||||
@@ -115,12 +115,12 @@ const updateUser = async (req, res) => {
|
||||
}
|
||||
}
|
||||
|
||||
res.status(200).send({ removedLinks });
|
||||
res.status(200).send({ removedLinks: removedLinks > 0 });
|
||||
logger.info("Updated user data", { delLinks: removedLinks, delPls: cleanedUser, addPls: updatedUser.length });
|
||||
return;
|
||||
} catch (error) {
|
||||
res.sendStatus(500);
|
||||
logger.error('updateUser', { error });
|
||||
logger.error("updateUser", { error });
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -158,7 +158,7 @@ const fetchUser = async (req, res) => {
|
||||
return;
|
||||
} catch (error) {
|
||||
res.sendStatus(500);
|
||||
logger.error('fetchUser', { error });
|
||||
logger.error("fetchUser", { error });
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -248,7 +248,7 @@ const createLink = async (req, res) => {
|
||||
return;
|
||||
} catch (error) {
|
||||
res.sendStatus(500);
|
||||
logger.error('createLink', { error });
|
||||
logger.error("createLink", { error });
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -314,12 +314,11 @@ const removeLink = async (req, res) => {
|
||||
return;
|
||||
} catch (error) {
|
||||
res.sendStatus(500);
|
||||
logger.error('removeLink', { error });
|
||||
logger.error("removeLink", { error });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add tracks to the link-head playlist,
|
||||
* that are present in the link-tail playlist but not in the link-head playlist,
|
||||
@@ -376,20 +375,8 @@ const populateSingleLink = async (req, res) => {
|
||||
return;
|
||||
}
|
||||
|
||||
let checkFields = ["collaborative", "owner(id)"];
|
||||
const checkFromData = await getPlaylistDetailsFirstPage(req, res, checkFields.join(), fromPl.id);
|
||||
if (res.headersSent) return;
|
||||
|
||||
// editable = collaborative || user is owner
|
||||
if (checkFromData.collaborative !== true &&
|
||||
checkFromData.owner.id !== uID) {
|
||||
res.status(403).send({
|
||||
message: "You cannot edit this playlist, you must be owner/playlist must be collaborative",
|
||||
playlistID: fromPl.id
|
||||
});
|
||||
logger.warn("user cannot edit target playlist", { playlistID: fromPl.id });
|
||||
if (!await checkPlaylistEditable(req, res, fromPl.id, uID))
|
||||
return;
|
||||
}
|
||||
|
||||
let initialFields = ["tracks(next,items(is_local,track(uri)))"];
|
||||
let mainFields = ["next", "items(is_local,track(uri))"];
|
||||
@@ -413,7 +400,7 @@ const populateSingleLink = async (req, res) => {
|
||||
|
||||
|
||||
// keep getting batches of 50 till exhausted
|
||||
while (fromPlaylist.next) {
|
||||
for (let i = 1; "next" in fromPlaylist; i++) {
|
||||
const nextData = await getPlaylistDetailsNextPage(req, res, fromPlaylist.next);
|
||||
if (res.headersSent) return;
|
||||
|
||||
@@ -449,9 +436,10 @@ const populateSingleLink = async (req, res) => {
|
||||
});
|
||||
|
||||
// keep getting batches of 50 till exhausted
|
||||
while (toPlaylist.next) {
|
||||
for (let i = 1; "next" in toPlaylist; i++) {
|
||||
const nextData = await getPlaylistDetailsNextPage(req, res, toPlaylist.next);
|
||||
if (res.headersSent) return;
|
||||
|
||||
toPlaylist.tracks.push(
|
||||
...nextData.items.map((playlist_item) => {
|
||||
return {
|
||||
@@ -476,22 +464,22 @@ const populateSingleLink = async (req, res) => {
|
||||
const localNum = toPlaylist.tracks.filter(track => track.is_local).length;
|
||||
|
||||
// append to end in batches of 100
|
||||
while (toTrackURIs.length) {
|
||||
while (toTrackURIs.length > 0) {
|
||||
const nextBatch = toTrackURIs.splice(0, 100);
|
||||
const addData = await addItemsToPlaylist(req, res, nextBatch, fromPl.id);
|
||||
if (res.headersSent) return;
|
||||
}
|
||||
|
||||
res.status(201).send({
|
||||
message: 'Added tracks.',
|
||||
message: `Added ${toAddNum} tracks, could not add ${localNum} local files.`,
|
||||
added: toAddNum,
|
||||
local: localNum,
|
||||
});
|
||||
logger.info(`Backfilled ${result.added} tracks, could not add ${result.local} local files.`);
|
||||
logger.info(`Backfilled ${toAddNum} tracks, could not add ${localNum} local files.`);
|
||||
return;
|
||||
} catch (error) {
|
||||
res.sendStatus(500);
|
||||
logger.error('populateSingleLink', { error });
|
||||
logger.error("populateSingleLink", { error });
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -548,21 +536,8 @@ const pruneSingleLink = async (req, res) => {
|
||||
return
|
||||
}
|
||||
|
||||
let checkFields = ["collaborative", "owner(id)"];
|
||||
|
||||
const checkToData = await getPlaylistDetailsFirstPage(req, res, checkFields.join(), toPl.id);
|
||||
if (res.headersSent) return;
|
||||
|
||||
// editable = collaborative || user is owner
|
||||
if (checkToData.collaborative !== true &&
|
||||
checkToData.owner.id !== uID) {
|
||||
res.status(403).send({
|
||||
message: "You cannot edit this playlist, you must be owner/playlist must be collaborative",
|
||||
playlistID: toPl.id
|
||||
});
|
||||
logger.error("user cannot edit target playlist");
|
||||
if (!await checkPlaylistEditable(req, res, toPl.id, uID))
|
||||
return;
|
||||
}
|
||||
|
||||
let initialFields = ["snapshot_id", "tracks(next,items(is_local,track(uri)))"];
|
||||
let mainFields = ["next", "items(is_local,track(uri))"];
|
||||
@@ -586,7 +561,7 @@ const pruneSingleLink = async (req, res) => {
|
||||
});
|
||||
|
||||
// keep getting batches of 50 till exhausted
|
||||
while (fromPlaylist.next) {
|
||||
for (let i = 1; "next" in fromPlaylist; i++) {
|
||||
const nextData = await getPlaylistDetailsNextPage(req, res, fromPlaylist.next);
|
||||
if (res.headersSent) return;
|
||||
|
||||
@@ -623,7 +598,7 @@ const pruneSingleLink = async (req, res) => {
|
||||
});
|
||||
|
||||
// keep getting batches of 50 till exhausted
|
||||
while (toPlaylist.next) {
|
||||
for (let i = 1; "next" in toPlaylist; i++) {
|
||||
const nextData = await getPlaylistDetailsNextPage(req, res, toPlaylist.next);
|
||||
if (res.headersSent) return;
|
||||
|
||||
@@ -651,7 +626,7 @@ const pruneSingleLink = async (req, res) => {
|
||||
let indexes = indexedToTrackURIs.filter(track => !fromTrackURIs.includes(track.uri)); // only those missing from the 'from' playlist
|
||||
indexes = indexes.map(track => track.position); // get track positions
|
||||
|
||||
const logNum = indexes.length;
|
||||
const toDelNum = indexes.length;
|
||||
|
||||
// remove in batches of 100 (from reverse, to preserve positions while modifying)
|
||||
let currentSnapshot = toPlaylist.snapshot_id;
|
||||
@@ -662,12 +637,12 @@ const pruneSingleLink = async (req, res) => {
|
||||
currentSnapshot = delResponse.snapshot_id;
|
||||
}
|
||||
|
||||
res.status(200).send({ message: `Removed ${logNum} tracks.` });
|
||||
logger.info(`Pruned ${logNum} tracks`);
|
||||
res.status(200).send({ message: `Removed ${toDelNum} tracks.` });
|
||||
logger.info(`Pruned ${toDelNum} tracks`);
|
||||
return;
|
||||
} catch (error) {
|
||||
res.sendStatus(500);
|
||||
logger.error('pruneSingleLink', { error });
|
||||
logger.error("pruneSingleLink", { error });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,11 +51,11 @@ const fetchUserPlaylists = async (req, res) => {
|
||||
delete userPlaylists.next;
|
||||
|
||||
res.status(200).send(userPlaylists);
|
||||
logger.debug("Fetched user's playlists", { num: userPlaylists.total });
|
||||
logger.info("Fetched user playlists", { num: userPlaylists.total });
|
||||
return;
|
||||
} catch (error) {
|
||||
res.sendStatus(500);
|
||||
logger.error('fetchUserPlaylists', { error });
|
||||
logger.error("fetchUserPlaylists", { error });
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -148,7 +148,7 @@ const fetchPlaylistDetails = async (req, res) => {
|
||||
return;
|
||||
} catch (error) {
|
||||
res.sendStatus(500);
|
||||
logger.error('getPlaylistDetails', { error });
|
||||
logger.error("getPlaylistDetails", { error });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user