File size: 3,069 Bytes
2844900
 
 
 
 
 
 
 
 
 
 
b370a90
2844900
 
06ae3cf
2844900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1f38c6
 
 
 
 
2844900
 
8f6f721
 
b2243c4
 
8f6f721
e1f38c6
8f6f721
06ae3cf
8f6f721
b2243c4
8f6f721
 
06ae3cf
b2243c4
8f6f721
ad67da4
8f6f721
06ae3cf
8f6f721
2844900
 
b370a90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6062efa
 
 
 
 
 
 
b370a90
 
 
 
 
 
 
 
2844900
745d853
2844900
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const express = require('express');
const fetch = require('node-fetch');
const querystring = require('querystring');
const app = express();
const port = 7860;

const clientId = process.env.SPOTIFY_CLIENT_ID;
const clientSecret = process.env.SPOTIFY_CLIENT_SECRET;
const redirectUri = process.env.SPOTIFY_REDIRECT_URI;

app.use(express.static('public'));
app.use(express.json());

app.get('/login', (req, res) => {
  const scope = 'streaming user-read-private user-read-email user-read-currently-playing user-modify-playback-state playlist-read-private user-library-read user-library-modify user-follow-read';
  res.redirect('https://accounts.spotify.com/authorize?' +
    querystring.stringify({
      response_type: 'code',
      client_id: clientId,
      scope: scope,
      redirect_uri: redirectUri,
    }));
});

app.get('/callback', async (req, res) => {
  const code = req.query.code || null;
  const authOptions = {
    method: 'POST',
    headers: {
      'Authorization': 'Basic ' + (Buffer.from(clientId + ':' + clientSecret).toString('base64')),
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: querystring.stringify({
      code: code,
      redirect_uri: redirectUri,
      grant_type: 'authorization_code'
    })
  };

  try {
    const response = await fetch('https://accounts.spotify.com/api/token', authOptions);
    const data = await response.json();

    if (!response.ok) {
        console.error("Error from Spotify:", data);
        res.status(response.status).send(`Error from Spotify: ${data.error_description || data.error}`);
        return;
    }

    const token = data.access_token;
    res.redirect('/#' + querystring.stringify({ access_token: token }));
    return;

  } catch (error) {
    console.error("Network or other error during token exchange:", error);
    res.status(500).send("An internal server error occurred.");
    return;
  }
});

// Endpoint to get recommendations
app.post('/recommendations', async (req, res) => {
  const { access_token, seed_tracks, seed_artists, seed_genres } = req.body;
  
  try {
    const params = new URLSearchParams();
    if (seed_tracks) params.append('seed_tracks', seed_tracks);
    if (seed_artists) params.append('seed_artists', seed_artists);
    if (seed_genres) params.append('seed_genres', seed_genres);
    params.append('limit', '20');

    const response = await fetch(`https://api.spotify.com/v1/recommendations?${params}`, {
      headers: {
        'Authorization': `Bearer ${access_token}`
      }
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('Spotify API error:', response.status, errorText);
      res.status(response.status).json({ error: 'Failed to get recommendations' });
      return;
    }

    const data = await response.json();
    res.json(data);
  } catch (error) {
    console.error('Error getting recommendations:', error);
    res.status(500).json({ error: 'Failed to get recommendations' });
  }
});

app.listen(port, () => {
  console.log(`App listening at port ${port}`);
});