Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- server side:
- --------------------------------------------------------------------------------------------------------------------
- const path = require('path');
- const express = require('express');
- const request = require('request');
- const querystring = require('querystring');
- const app = express();
- const client_id = 'censored';
- const client_secret = 'censored';
- const redirect_uri = 'http://localhost:3000/callback';
- // Agrega la siguiente línea de código para servir tus archivos HTML, CSS y JavaScript
- app.use(express.static(path.join(__dirname, 'public')));
- app.get('/callback', function(req, res) {
- const code = req.query.code || null;
- const authOptions = {
- url: 'https://accounts.spotify.com/api/token',
- form: {
- code: code,
- redirect_uri: redirect_uri,
- grant_type: 'authorization_code'
- },
- headers: {
- 'Authorization': 'Basic ' + (new Buffer.from(client_id + ':' + client_secret).toString('base64'))
- },
- json: true
- };
- request.post(authOptions, function(error, response, body) {
- if (!error && response.statusCode === 200) {
- const access_token = body.access_token,
- refresh_token = body.refresh_token;
- // redirecciona a la página principal con los tokens en la URL
- res.redirect(`/index.html?access_token=${access_token}&refresh_token=${refresh_token}`);
- } else {
- res.redirect('/#' +
- querystring.stringify({
- error: 'invalid_token'
- }));
- }
- });
- });
- app.get('/refresh_token', function(req, res) {
- const refresh_token = req.query.refresh_token;
- const authOptions = {
- url: 'https://accounts.spotify.com/api/token',
- headers: { 'Authorization': 'Basic ' + (new Buffer.from(client_id + ':' + client_secret).toString('base64')) },
- form: {
- grant_type: 'refresh_token',
- refresh_token: refresh_token
- },
- json: true
- };
- request.post(authOptions, function(error, response, body) {
- if (!error && response.statusCode === 200) {
- const access_token = body.access_token;
- res.send({
- 'access_token': access_token
- });
- }
- });
- });
- app.listen(3000, () => console.log('App listening on port 3000!'));
- --------------------------------------------------------------------------------------------------------------------
- user side:
- --------------------------------------------------------------------------------------------------------------------
- const client_id = "censored";
- const redirect_uri = "http://localhost:3000/callback";
- const scopes = "user-read-playback-state";
- const authUrl = `https://accounts.spotify.com/authorize?client_id=${client_id}&response_type=code&redirect_uri=${encodeURIComponent(redirect_uri)}&scope=${encodeURIComponent(scopes)}`;
- document.getElementById("login").addEventListener("click", () => {
- window.location = authUrl;
- });
- const refreshUrl = "http://localhost:3000/refresh_token";
- function getAccessTokenFromUrl() {
- let accessToken = null;
- const queryString = window.location.search;
- const urlParams = new URLSearchParams(queryString);
- accessToken = urlParams.get('access_token');
- return accessToken;
- }
- function getRefreshTokenFromUrl() {
- let refreshToken = null;
- const queryString = window.location.search;
- const urlParams = new URLSearchParams(queryString);
- refreshToken = urlParams.get('refresh_token');
- return refreshToken;
- }
- let access_token = getAccessTokenFromUrl();
- let refresh_token = getRefreshTokenFromUrl();
- async function refreshAccessToken() {
- const response = await fetch(`${refreshUrl}?refresh_token=${refresh_token}`);
- const data = await response.json();
- access_token = data.access_token;
- }
- async function isTokenValid(accessToken) {
- const response = await fetch("https://api.spotify.com/v1/me", {
- headers: {
- "Authorization": `Bearer ${accessToken}`
- }
- });
- return response.status === 200;
- }
- async function updatePlayer(accessToken) {
- if (!accessToken) return;
- const response = await fetch("https://api.spotify.com/v1/me/player", {
- headers: {
- "Authorization": `Bearer ${accessToken}`
- }
- });
- if (response.status === 200) {
- const data = await response.json();
- const { item, progress_ms, is_playing } = data;
- const { name, album, artists } = item;
- const artistNames = artists.map(artist => artist.name).join(", ");
- const imageUrl = album.images[0].url;
- document.querySelector(".song-image img").src = imageUrl;
- document.querySelector(".footer").textContent = `${name} - ${artistNames}`;
- if (is_playing) {
- const progress = (progress_ms / item.duration_ms) * 100;
- document.querySelector(".progress-bar").style.width = `${progress}%`;
- }
- }
- }
- setInterval(async () => {
- if (!(await isTokenValid(access_token))) {
- await refreshAccessToken();
- }
- updatePlayer(access_token);
- }, 1000);
- --------------------------------------------------------------------------------------------------------------------
Add Comment
Please, Sign In to add comment