lucks232

Untitled

Jun 24th, 2023
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. server side:
  2. --------------------------------------------------------------------------------------------------------------------
  3. const path = require('path');
  4. const express = require('express');
  5. const request = require('request');
  6. const querystring = require('querystring');
  7. const app = express();
  8.  
  9. const client_id = 'censored';
  10. const client_secret = 'censored';
  11. const redirect_uri = 'http://localhost:3000/callback';
  12.  
  13. // Agrega la siguiente línea de código para servir tus archivos HTML, CSS y JavaScript
  14. app.use(express.static(path.join(__dirname, 'public')));
  15.  
  16. app.get('/callback', function(req, res) {
  17.   const code = req.query.code || null;
  18.   const authOptions = {
  19.     url: 'https://accounts.spotify.com/api/token',
  20.     form: {
  21.       code: code,
  22.       redirect_uri: redirect_uri,
  23.       grant_type: 'authorization_code'
  24.     },
  25.     headers: {
  26.       'Authorization': 'Basic ' + (new Buffer.from(client_id + ':' + client_secret).toString('base64'))
  27.     },
  28.     json: true
  29.   };
  30.  
  31.   request.post(authOptions, function(error, response, body) {
  32.     if (!error && response.statusCode === 200) {
  33.       const access_token = body.access_token,
  34.             refresh_token = body.refresh_token;
  35.  
  36.       // redirecciona a la página principal con los tokens en la URL
  37.       res.redirect(`/index.html?access_token=${access_token}&refresh_token=${refresh_token}`);
  38.     } else {
  39.       res.redirect('/#' +
  40.         querystring.stringify({
  41.           error: 'invalid_token'
  42.         }));
  43.     }
  44.   });
  45. });
  46.  
  47. app.get('/refresh_token', function(req, res) {
  48.   const refresh_token = req.query.refresh_token;
  49.   const authOptions = {
  50.     url: 'https://accounts.spotify.com/api/token',
  51.     headers: { 'Authorization': 'Basic ' + (new Buffer.from(client_id + ':' + client_secret).toString('base64')) },
  52.     form: {
  53.       grant_type: 'refresh_token',
  54.       refresh_token: refresh_token
  55.     },
  56.     json: true
  57.   };
  58.  
  59.   request.post(authOptions, function(error, response, body) {
  60.     if (!error && response.statusCode === 200) {
  61.       const access_token = body.access_token;
  62.       res.send({
  63.         'access_token': access_token
  64.       });
  65.     }
  66.   });
  67. });
  68.  
  69. app.listen(3000, () => console.log('App listening on port 3000!'));
  70. --------------------------------------------------------------------------------------------------------------------
  71.  
  72. user side:
  73. --------------------------------------------------------------------------------------------------------------------
  74. const client_id = "censored";
  75. const redirect_uri = "http://localhost:3000/callback";
  76. const scopes = "user-read-playback-state";
  77. const authUrl = `https://accounts.spotify.com/authorize?client_id=${client_id}&response_type=code&redirect_uri=${encodeURIComponent(redirect_uri)}&scope=${encodeURIComponent(scopes)}`;
  78.  
  79. document.getElementById("login").addEventListener("click", () => {
  80.   window.location = authUrl;
  81. });
  82.  
  83. const refreshUrl = "http://localhost:3000/refresh_token";
  84.  
  85. function getAccessTokenFromUrl() {
  86.   let accessToken = null;
  87.   const queryString = window.location.search;
  88.   const urlParams = new URLSearchParams(queryString);
  89.   accessToken = urlParams.get('access_token');
  90.   return accessToken;
  91. }
  92.  
  93. function getRefreshTokenFromUrl() {
  94.   let refreshToken = null;
  95.   const queryString = window.location.search;
  96.   const urlParams = new URLSearchParams(queryString);
  97.   refreshToken = urlParams.get('refresh_token');
  98.   return refreshToken;
  99. }
  100.  
  101. let access_token = getAccessTokenFromUrl();
  102. let refresh_token = getRefreshTokenFromUrl();
  103.  
  104. async function refreshAccessToken() {
  105.   const response = await fetch(`${refreshUrl}?refresh_token=${refresh_token}`);
  106.   const data = await response.json();
  107.   access_token = data.access_token;
  108. }
  109.  
  110. async function isTokenValid(accessToken) {
  111.   const response = await fetch("https://api.spotify.com/v1/me", {
  112.     headers: {
  113.       "Authorization": `Bearer ${accessToken}`
  114.     }
  115.   });
  116.   return response.status === 200;
  117. }
  118.  
  119. async function updatePlayer(accessToken) {
  120.   if (!accessToken) return;
  121.  
  122.   const response = await fetch("https://api.spotify.com/v1/me/player", {
  123.     headers: {
  124.       "Authorization": `Bearer ${accessToken}`
  125.     }
  126.   });
  127.  
  128.   if (response.status === 200) {
  129.     const data = await response.json();
  130.     const { item, progress_ms, is_playing } = data;
  131.     const { name, album, artists } = item;
  132.     const artistNames = artists.map(artist => artist.name).join(", ");
  133.     const imageUrl = album.images[0].url;
  134.  
  135.     document.querySelector(".song-image img").src = imageUrl;
  136.     document.querySelector(".footer").textContent = `${name} - ${artistNames}`;
  137.  
  138.     if (is_playing) {
  139.       const progress = (progress_ms / item.duration_ms) * 100;
  140.       document.querySelector(".progress-bar").style.width = `${progress}%`;
  141.     }
  142.   }
  143. }
  144.  
  145. setInterval(async () => {
  146.   if (!(await isTokenValid(access_token))) {
  147.     await refreshAccessToken();
  148.   }
  149.   updatePlayer(access_token);
  150. }, 1000);
  151. --------------------------------------------------------------------------------------------------------------------
Add Comment
Please, Sign In to add comment