-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
150 lines (134 loc) · 4.66 KB
/
server.js
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
const SpotifyWebApi = require("spotify-web-api-node");
const polka = require('polka');
const port = process.env.PORT || 3000;
var scopes = ['user-read-currently-playing'],
redirectUri = 'http://localhost',
state = 'now-playing';
// 1. Get Client ID and Client Secret by creating Spotify API App
// https://developer.spotify.com/dashboard/applications
// I'll put it on ENV, but you can just change it in code.
const spotifyApi = new SpotifyWebApi({
redirectUri: redirectUri,
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
});
// 2. Uncoment this section, get the link and and grant permission,
// then take a look at the URL bar.
// console.log(spotifyApi.createAuthorizeURL(scopes, state));
// 3. Use the code that's returned as a query parameter to the redirect URI.
// It's one-time code! You need to refresh it in case of something went wrong
// by link from step 2
// Retrieve an access token and a refresh token with this part
// var code = '';
// spotifyApi.authorizationCodeGrant(code).then(
// function(data) {
// console.log('The token expires in ' + data.body['expires_in']);
// console.log('The access token is ' + data.body['access_token']);
// console.log('The refresh token is ' + data.body['refresh_token']);
// // 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']);
// process.env.accessToken = data.body['access_token'];
// process.env.refreshToken = data.body['refresh_token'];
// },
// function(err) {
// console.log('Something went wrong!', err);
// }
// );
spotifyApi.setAccessToken(process.env.accessToken)
spotifyApi.setRefreshToken(process.env.refreshToken)
let currentSong = {
name: null,
artists: null,
image: null,
url: null,
duration: null,
progress: null,
update: null,
}
const getText = (name, artists, url) => `<a href="${url}">${artists} — ${name}</a>`
const getMyCurrentPlaybackState = async () => {
try {
let data = await spotifyApi.getMyCurrentPlayingTrack({})
if (data.statusCode === 200) {
let body = data.body
let artists = body.item.artists.map(artist => artist.name).join(", ")
currentSong = {
name: body.item.name,
artists: artists,
url: body.item.external_urls.spotify,
paused: false,
ok: true
}
return currentSong
}
else if (data.statusCode === 204) {
currentSong = {
paused: true,
ok: true
}
return currentSong
}
else {
return {
ok: false,
message: "Status code is not 200",
data: data
}
}
}
catch (err) {
if (err.statusCode === 401) {
try {
let data = await spotifyApi.refreshAccessToken()
spotifyApi.setAccessToken(data.body['access_token']);
spotifyApi.setRefreshToken(data.body['refresh_token']);
process.env.accessToken = data.body['access_token'];
process.env.refreshToken = data.body['refresh_token'];
console.log("The access token has been refreshed!");
return await getMyCurrentPlaybackState()
}
catch (err) {
return {
ok: false,
message: "Could not refresh access token",
data: err
}
}
}
//TODO: check 502 error and return "Spotify's problems"
else {
return {
ok: false,
message: "Something went wrong",
data: err
}
}
}
}
const showNowPlaying = async () => {
var playbackState = await getMyCurrentPlaybackState();
if (playbackState.ok) {
if (playbackState.paused) {
return 'paused'
}
return getText(playbackState.name, playbackState.artists, playbackState.url)
}
else {
console.log(playbackState.message)
console.log(playbackState.data)
return '⚠️ Error, try again later'
}
}
polka()
.get('/', async (req, res) => {
res.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
});
res.end(await showNowPlaying());
})
.listen(port, err => {
if (err) throw err;
console.log(`> Running`);
});