-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.js
258 lines (213 loc) · 7.22 KB
/
main.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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
var express = require('express');
var app = express();
//Load ejs
var ejs = require('ejs');
app.set('view engine', 'ejs');
app.set('views', __dirname + '/Views');
app.use(express.static(__dirname));
//Load the Spotify Node API
var SpotifyWebApi = require('spotify-web-api-node');
var spotifyApi = new SpotifyWebApi({
clientId: '###',
clientSecret: '###',
redirectUri: 'http://localhost:8080/callback'
});
var scopes = ['playlist-read-private', 'playlist-read-collaborative', 'user-modify-playback-state',
'user-read-currently-playing', 'user-read-private', 'user-library-read', 'user-read-playback-state'];
//Sets random values for state
const validChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var state = "";
var random;
for (i = 0; i < 15; i++) {
random = Math.floor(Math.random() * (validChars.length - 1));
state += validChars.charAt(random);
}
var authorizeURL = spotifyApi.createAuthorizeURL(scopes, state);
//Homepage
app.get('/', function(req, res){
res.render('index', {authurl: authorizeURL});
});
var tokenExpirationEpoch;
//Redirect URI
app.get('/callback', function(req, res){
var code = req.query.code;
spotifyApi.authorizationCodeGrant(code).then(
function(data) {
//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']);
//Save the amount of seconds until the access token expired
tokenExpirationEpoch =
new Date().getTime() / 1000 + data.body['expires_in'];
console.log(
'Retrieved token. It expires in ' +
Math.floor(tokenExpirationEpoch - new Date().getTime() / 1000) +
' seconds!'
);
res.redirect('/game');
},
function(err) {
console.log('Something went wrong!', err);
}
);
});
//Refreshes the Acces Token
var numberOfTimesUpdated = 0;
setInterval(function() {
//Stop printing and refresh.
if (++numberOfTimesUpdated > 5) {
clearInterval(this);
//Refresh token and print the new time to expiration.
spotifyApi.refreshAccessToken().then(
function(data) {
tokenExpirationEpoch =
new Date().getTime() / 1000 + data.body['expires_in'];
console.log(
'Refreshed token. It now expires in ' +
Math.floor(tokenExpirationEpoch - new Date().getTime() / 1000) +
' seconds!'
);
},
function(err) {
console.log('Could not refresh the token!', err.message);
}
);
}}, 1000);
//Game Page
app.get('/game', function(req, res){
spotifyApi.getMe()
.then(function(data) {
//console.log(data.body);
res.render('game', {
name: data.body['display_name']
});
}, function(err) {
console.log('Something went wrong!', err);
});
});
//Loads User Devices and Sends to Page
app.get('/get_user_devices', function(req, res){
spotifyApi.getMyDevices()
.then(function(data){
//Checks if there are no devices active
if (Object(data.body.devices).length == 0) {
console.log("ERROR: No devices found!");
}
console.log("Device data sent");
res.send(data.body.devices);
}, function(err){
console.log("Something went wrong", err);
}).catch(error => {console.log(error)});
});
//Loads User Playlists and Sends to Page
app.get('/get_user_playlists', function(req, res){
spotifyApi.getUserPlaylists()
.then(function(data){
console.log("User Playlists Sent");
res.send(data.body.items);
}, function(err){
console.log('Something went wrong!', err);
}).catch(error => {console.log(error)});
});
var playlist_id;
var track_data;
var track_start;
//Loads Playlists Tracks and Sends to Page
app.get('/get_playlist_tracks/:playlist_id', function(req, res){
playlist_id = req.params.playlist_id;
spotifyApi.getPlaylistTracks(playlist_id, { fields: 'items' })
.then(function(data){
console.log("Track Data Sent");
res.send(data.body.items);
}, function(err){
console.log('Something went wrong!', err);
}).catch(error => {console.log(error)});
});
//Play Selected Playlist on Selected Device and Sends Track to Page
app.get('/play_playlist/:device_id/:playlist_uri', function(req, res){
spotifyApi.play({ device_id: req.params.device_id, context_uri: req.params.playlist_uri })
.then(function(data){
//Sets the playback to shuffle
spotifyApi.setShuffle({state: 'true'})
.then(function(data){
console.log("Shuffle Set");
//Skips to next song since it will always begin on first song in playlist
spotifyApi.skipToNext()
.then(function(data){
//Delays to Give Device Time to Change Song
setTimeout(function(data){
console.log("Skipped song");
//Gets name of current track and returns it to the game
spotifyApi.getMyCurrentPlayingTrack()
.then(function(data){
//Skips to a random point in the song so it's easier to identify
track_data = data.body.item;
if (track_data.duration_ms >= 45000) {
track_start = Math.floor(Math.random() * (track_data.duration_ms - 40000) + 15000);
} else {
track_start = 15000;
}
spotifyApi.seek(track_start)
.then(function(data){
res.send(track_data);
}, function(error){
console.log(error);
}).catch(error => {console.log(error)});
}, function(error){
console.log(error);
}).catch(error => {console.log(error)});
}, 600);
}, function(error){
console.log(error);
}).catch(error => {console.log(error)});
}, function(err){
console.log(err)
}).catch(error => {console.log(error)});
}, function(err){
console.log(err);
}).catch(error => {console.log(error)});
});
//Play next song in game and Sends Track to Page
app.get('/play_next', function(req, res){
spotifyApi.skipToNext()
.then(function(data){
//Delays to Give Device Time to Change Song
setTimeout(function(data){
console.log("Skipped song");
//Gets name of current track and returns it to the game
spotifyApi.getMyCurrentPlayingTrack()
.then(function(data){
//Skips a bit into the song so easier to identify
track_data = data.body.item;
if (track_data.duration_ms >= 45000) {
track_start = Math.floor(Math.random() * (track_data.duration_ms - 40000) + 15000);
} else {
track_start = 15000;
}
spotifyApi.seek(track_start).then(function(data){
res.send(track_data);
}, function(error){
console.log(error);
}).catch(error => {console.log(error)});
}, function(error){
console.log(error);
}).catch(error => {console.log(error)});
}, 200);
}, function(error){
console.log(error);
}).catch(error => {console.log(error)});
});
//Pauses Music
app.get('/pause', function(req, res){
spotifyApi.pause()
.then(function(data){}, function(error){console.log(error)})
.catch(error => {console.log(error)});
});
//Plays Music
app.get('/play', function(req, res){
spotifyApi.play()
.then(function(data){}, function(error){console.log(error)})
.catch(error => {console.log(error)});
});
const PORT = process.env.PORT || 8080;
app.listen(PORT || 8080, () => console.log("Currently listening on " + PORT));