spotifylookup/bits/spotify.js

94 lines
2.7 KiB
JavaScript
Raw Normal View History

2022-01-04 18:19:03 +00:00
const SpotifyWebApi = require('spotify-web-api-node');
const ReadLine = require('readline');
const fs = require('fs').promises;
const path = require('path');
// Create the authorization URL
const rl = ReadLine.createInterface({
input: process.stdin,
output: process.stdout,
});
const root = path.join(__dirname, '..');
/*
{
"clientId": "",
"clientSecret": "",
"redirectUri": "https://lunasqu.ee/callback"
}
*/
const spotifyApi = new SpotifyWebApi(require(path.join(root, 'credentials.json')));
function ask(msg) {
return new Promise((resolve) => rl.question(msg, resolve));
}
async function setupSpotify() {
let credentials = {
token: null,
expires: null,
refresh: null,
};
try {
credentials = JSON.parse(await fs.readFile(path.join(root, '.token.json')));
} catch (e) {}
if (!credentials.token) {
const authorizeURL = spotifyApi.createAuthorizeURL(['playlist-modify-private'], 'FPEPFERHR234234trGEWErjrjsdw3666sf06');
console.log('Authorize the application');
console.log(authorizeURL);
const code = await ask('Enter code []> ');
if (!code) {
process.exit(1);
}
const data = await spotifyApi.authorizationCodeGrant(code);
console.log('The access token has been received.');
// Set the access token on the API object to use it in later calls
spotifyApi.setAccessToken(data.body['access_token']);
spotifyApi.setRefreshToken(data.body['refresh_token']);
credentials.token = data.body['access_token'];
credentials.expires = Math.floor(Date.now() / 1000) + data.body['expires_in'];
credentials.refresh = data.body['refresh_token'];
await fs.writeFile(path.join(root, '.token.json'), JSON.stringify(credentials, undefined, 2));
} else {
console.log('The access token is present');
spotifyApi.setAccessToken(credentials.token);
spotifyApi.setRefreshToken(credentials.refresh);
}
if ((credentials.expires * 1000) < Date.now()) {
console.log('Refreshing access token');
try {
const refresh = await spotifyApi.refreshAccessToken();
credentials.token = refresh.body['access_token'];
credentials.expires = Math.floor(Date.now() / 1000) + refresh.body['expires_in'];
spotifyApi.setAccessToken(credentials.token);
spotifyApi.setRefreshToken(credentials.refresh);
} catch (e) {
console.error(e);
console.log('need to reauthorize');
credentials.token = null;
}
await fs.writeFile(path.join(root, '.token.json'), JSON.stringify(credentials, undefined, 2));
if (!credentials.token) {
return setupSpotify();
}
}
console.log('the token is good until', new Date(credentials.expires * 1000).toString());
rl.close();
return spotifyApi;
}
module.exports = {
setupSpotify,
spotifyApi,
};