forked from strnadchristopher/arizona
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spotify.js
295 lines (286 loc) · 8.2 KB
/
spotify.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
const { app, BrowserWindow, Menu, Tray, screen, net, nativeImage } = require('electron')
//SPOTIFY STUFF HERE
const fs = require('fs')
const request = require('request')
var authWindow;
var accessCode;
var aToken, rToken;
var spotifyAuthSuccess = false;
var artist, trackName, album, albumArtURL, cTime, duration, isPlaying;
var dirPath = __dirname;
exports.aToken = function(){
return aToken;
}
exports.rToken = function(){
return rToken;
}
exports.authorized = function(){
return spotifyAuthSuccess;
}
exports.artist = function(){
return artist;
}
exports.trackName = function(){
return trackName;
}
exports.album = function(){
return album;
}
exports.albumArtURL = function(){
return album;
}
exports.cTime = function(){
return cTime;
}
exports.duration = function(){
return duration;
}
exports.isPlaying = function(){
return isPlaying;
}
//Beginning of Spotify Auth Process, Opens a window to get approval
exports.authorize = function(callback){
authWindow = new BrowserWindow({
width: 500,
height: 500,
transparent: true,
frame: true,
x:0,
y:0,
alwaysOnTop:true,
resizable:false,
webPreferences: {
nodeIntegration: true
}
})
authWindow.on('close', function(event){
event.preventDefault();
authWindow.hide()
})
//Open spotify auth link, get access code
var url = "https://accounts.spotify.com/en/authorize?response_type=code&client_id=eb0929c190354d7ea0b7e8a065ad68ed&scope=user-modify-playback-state%20user-read-currently-playing%20user-read-playback-state%20user-top-read&redirect_uri=https%3A%2F%2Fstrnadchristopher.github.io%2FarizonaPage%2F";
authWindow.loadURL(url)
var newURL = authWindow.webContents.getURL();
if(!newURL.includes("spotify") && newURL != ""){}else{
var i = setInterval(function(){
if(!authWindow.isVisible()){
clearInterval(i)
}else{
newURL = authWindow.webContents.getURL();
if(!newURL.includes("spotify") && newURL != ""){ //If auth is done
console.log("finished");
if(newURL.split("?")[1] != void(0)){
clearInterval(i)
accessCode = newURL.split("?")[1].substring(5)
fs.writeFile(dirPath + '/spotifyAuth.txt', accessCode, function(err){
if (err) return console.log(err);
authWindow.close()
getTokens(callback)
});
}
}else{
authWindow.show();
}
}
},5000)
}
}
//Get The Initial set of tokens, access and refreshToken
function getTokens(callback){
console.log("Getting inital access token and refresh token");
fs.readFile(dirPath + "/spotifyAuth.txt", "utf8", function(err, data) {
//console.log("Spotify auth found: " + data);
accessCode = data;
request.post('https://accounts.spotify.com/api/token', {
form: {
"grant_type": "authorization_code",
"code": accessCode,
"redirect_uri": "https://strnadchristopher.github.io/arizonaPage/"
},
headers: {'Authorization': "Basic ZWIwOTI5YzE5MDM1NGQ3ZWEwYjdlOGEwNjVhZDY4ZWQ6OWQ4NTRhMzY3OThhNGNlODljOTRiNmFlOWFlYjdmOTA="
},
json: true
}, (error, res, body) => {
if (error) {
console.log("Failed to get inital tokens.")
return false;
console.error(error)
}
aToken = body["access_token"]
rToken = body["refresh_token"]
spotifyAuthSuccess = true;
console.log("Authorization successful");
callback()
})
});
}
//Refresh the token if it's expired
function refreshToken(){
console.log("Getting refresh token")
request.post('https://accounts.spotify.com/api/token', {
form: {
"grant_type": "refresh_token",
"code": rToken,
"redirect_uri": "https://strnadchristopher.github.io/arizonaPage/"
},
headers: {'Authorization': "Basic ZWIwOTI5YzE5MDM1NGQ3ZWEwYjdlOGEwNjVhZDY4ZWQ6OWQ4NTRhMzY3OThhNGNlODljOTRiNmFlOWFlYjdmOTA="
},
json: true
}, (error, res, body) => {
if (error) {
console.log("Failed to refresh token");
console.error(error)
spotifyAuth();
return
}
aToken = body["access_token"]
rToken = body["refresh_token"]
spotifyAuthSuccess = true;
console.log("Authorization successful")
})
}
//Various spotify control functions
exports.pause = function(){
console.log("Pausing Track");
request.put('https://api.spotify.com/v1/me/player/pause', {
headers: {'Authorization': "Bearer " + aToken},
json: true
}, (error, res, body) => {
if (error) {
console.error(error)
return
}
console.log(`statusCode: ${res.statusCode}`)
isPlaying = false;
})
}
exports.resume = function(){
request.put('https://api.spotify.com/v1/me/player/play', {
headers: {'Authorization': "Bearer " + aToken},
json: true
}, (error, res, body) => {
if (error) {
console.error(error)
return
}
console.log(`statusCode: ${res.statusCode}`)
isPlaying = true;
})
}
exports.skip = function(callback){
console.log("Playing next song")
request.post('https://api.spotify.com/v1/me/player/next', {
headers: {'Authorization': "Bearer " + aToken},
json: true
}, (error, res, body) => {
if (error) {
console.error(error)
return
}
console.log(`statusCode: ${res.statusCode}`)
callback()
})
}
exports.previous = function(callback){
console.log("Playing previous song");
request.post('https://api.spotify.com/v1/me/player/previous', {
headers: {'Authorization': "Bearer " + aToken},
json: true
}, (error, res, body) => {
if (error) {
console.error(error)
return
}
console.log(`statusCode: ${res.statusCode}`)
callback()
})
}
exports.play = function(songName){
var foundTrack; //Search for the artist
request.get('https://api.spotify.com/v1/search/?q='+encodeURI(songName)+'&type=track', {
headers: {'Authorization': "Bearer " + aToken},
json: true
}, (error, res, body) => {
if (error) {
console.error(error)
return
}
console.log(`statusCode: ${res.statusCode}`)
console.log(body);
//console.log(body)
if(body["tracks"]["items"].length > 0){
foundTrack = body["tracks"]["items"]["0"]["uri"] //Play the first song
request.post('https://api.spotify.com/v1/me/player/queue?uri='+foundTrack, {
headers: {'Authorization': "Bearer " + aToken},
json: true
}, (error, res, body) => {
if (error) {
console.error(error)
return
}
console.log(body);
console.log(`statusCode: ${res.statusCode}`)
//console.log(body);
return skipTrack();
})
}else{
return false;
}
})
}
exports.toggleMusic = function(){ //Check playback state then change it
if(spotifyAuthSuccess){
request.get('https://api.spotify.com/v1/me/player', {
headers: {'Authorization': "Bearer " + aToken},
json: true
}, (error, res, body) => {
if (error) {
console.error(error)
return
}
console.log(`statusCode: ${res.statusCode}`)
if(body != void(0)){
console.log(body["is_playing"])
isPlaying = body["is_playing"];
setTimeout(function(){
if(isPlaying){
exports.pause();
}else{
exports.resume();
}
}, 500)
}else{
return false;
}
})
}
}
exports.getTrackInfo = async function(callback){
request.get('https://api.spotify.com/v1/me/player/currently-playing', {
headers: {'Authorization': "Bearer " + aToken},
json: true
}, (error, res, body) => {
if (error) {
console.log("Failed to get track info")
//console.error(error)
refreshToken();
return false;
}
console.log(`statusCode: ${res.statusCode}`)
if(body != void(0)){
if(body["item"] != void(0)){
artist = body["item"]["artists"][0]["name"];
trackName = body["item"]["name"]
album = body["item"]["album"]["name"]
albumArtURL = body["item"]["album"]["images"][0]["url"]
cTime = body["progess_ms"];
duration = body["item"]["duration_ms"];
isPlaying = body["is_playing"];
callback(artist + ";" + trackName + ";" + album + ";" + albumArtURL);
shouldUpdateTrack = false;
}
}else{
return false;
}
})
}